-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathBuilder.cs
More file actions
3211 lines (2933 loc) · 152 KB
/
Copy pathBuilder.cs
File metadata and controls
3211 lines (2933 loc) · 152 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.Frozen;
using System.IO.Compression;
using System.Text.Json.Nodes;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Npgsql;
using NpgsqlRest;
using NpgsqlRestClient.Fido2;
using Serilog;
using Serilog.Extensions.Logging;
using Serilog.Sinks.OpenTelemetry;
namespace NpgsqlRestClient;
public class Builder
{
private readonly Config _config;
public Builder(Config config)
{
_config = config;
}
public WebApplicationBuilder Instance { get; private set; } = default!;
public bool LoggingEnabled { get; private set; } = false;
public Microsoft.Extensions.Logging.ILogger? Logger { get; private set; } = null;
public Microsoft.Extensions.Logging.ILogger? ClientLogger { get; private set; } = null;
public bool UseHttpsRedirection { get; private set; } = false;
public bool UseHsts { get; private set; } = false;
public BearerTokenConfig? BearerTokenConfig { get; private set; } = null;
public JwtTokenConfig? JwtTokenConfig { get; private set; } = null;
/// <summary>BearerToken-type entries registered under <c>Auth:Schemes</c>. Each carries its own scheme name and (optionally) refresh path.</summary>
public List<BearerTokenConfig> AdditionalBearerTokenConfigs { get; } = [];
/// <summary>Jwt-type entries registered under <c>Auth:Schemes</c>. Each carries its own scheme name, secret, validation options and (optionally) refresh path.</summary>
public List<JwtTokenConfig> AdditionalJwtTokenConfigs { get; } = [];
/// <summary>
/// Every registered cookie scheme in registration order — main scheme first (when CookieAuth is on),
/// then each Cookie-type entry under <c>Auth:Schemes</c>. Each tuple pairs the scheme name with the
/// HTTP cookie name actually written to the request. Consumed by the cookie-aware
/// <c>ForwardDefaultSelector</c> on the policy scheme so that requests bearing a named-scheme cookie
/// authenticate under that scheme (not just the default).
/// </summary>
public List<(string SchemeName, string CookieName)> CookieSchemesInOrder { get; } = [];
public string? ConnectionString { get; private set; } = null;
public string? ConnectionName { get; private set; } = null;
public ExternalAuthConfig? ExternalAuthConfig { get; private set; } = null;
public PasskeyConfig? PasskeyConfig { get; private set; } = null;
public bool SslEnabled { get; private set; } = false;
public void BuildInstance()
{
var staticFilesCfg = _config.Cfg.GetSection("StaticFiles");
string? webRootPath = staticFilesCfg is not null && _config.GetConfigBool("Enabled", staticFilesCfg) is true ? _config.GetConfigStr("RootPath", staticFilesCfg) ?? "wwwroot" : null;
var options = new WebApplicationOptions()
{
ApplicationName = _config.GetConfigStr("ApplicationName") ?? Path.GetFileName(Environment.CurrentDirectory),
WebRootPath = webRootPath,
EnvironmentName = _config.GetConfigStr("EnvironmentName") ?? "Production",
};
Instance = WebApplication.CreateEmptyBuilder(options);
Instance.WebHost.UseKestrelCore();
var kestrelConfig = _config.Cfg.GetSection("Kestrel");
if (kestrelConfig is not null && kestrelConfig.Exists())
{
var transformedKestrelConfig = _config.TransformSection(kestrelConfig);
Instance.WebHost.ConfigureKestrel((context, options) =>
{
options.Configure(transformedKestrelConfig);
options.DisableStringReuse = _config.GetConfigBool("DisableStringReuse", kestrelConfig, options.DisableStringReuse);
options.AllowAlternateSchemes = _config.GetConfigBool("AllowAlternateSchemes", kestrelConfig, options.AllowAlternateSchemes);
options.AllowSynchronousIO = _config.GetConfigBool("AllowSynchronousIO", kestrelConfig, options.AllowSynchronousIO);
options.AllowResponseHeaderCompression = _config.GetConfigBool("AllowResponseHeaderCompression", kestrelConfig, options.AllowResponseHeaderCompression);
options.AddServerHeader = _config.GetConfigBool("AddServerHeader", kestrelConfig, options.AddServerHeader);
options.AllowHostHeaderOverride = _config.GetConfigBool("AllowSynchronousIO", kestrelConfig, options.AllowHostHeaderOverride);
var limitsSection = transformedKestrelConfig.GetSection("Limits");
if (limitsSection.Exists())
{
limitsSection.Bind(options.Limits);
}
});
}
var urls = _config.GetConfigStr("Urls");
if (urls is not null)
{
Instance.WebHost.UseUrls(urls.Split(';'));
}
else
{
Instance.WebHost.UseUrls("http://localhost:8080");
}
var ssqlCfg = _config.Cfg.GetSection("Ssl");
if (_config.Exists(ssqlCfg) is true)
{
if (_config.GetConfigBool("Enabled", ssqlCfg) is true)
{
SslEnabled = true;
Instance.WebHost.UseKestrelHttpsConfiguration();
UseHttpsRedirection = _config.GetConfigBool("UseHttpsRedirection", ssqlCfg, true);
UseHsts = _config.GetConfigBool("UseHsts", ssqlCfg, true);
}
}
else
{
UseHttpsRedirection = false;
UseHsts = false;
}
}
public WebApplication Build() => Instance.Build();
public void BuildLogger(RetryStrategy? cmdRetryStrategy)
{
var logCfg = _config.Cfg.GetSection("Log");
Logger = null;
var logToConsole = _config.GetConfigBool("ToConsole", logCfg, true);
var logToFile = _config.GetConfigBool("ToFile", logCfg);
var filePath = _config.GetConfigStr("FilePath", logCfg) ?? "logs/log.txt";
var logToPostgres = _config.GetConfigBool("ToPostgres", logCfg);
var postgresCommand = _config.GetConfigStr("PostgresCommand", logCfg);
var logToOpenTelemetry = _config.GetConfigBool("ToOpenTelemetry", logCfg);
if (
logToConsole is true ||
(logToFile is true) ||
(logToPostgres is true && postgresCommand is not null) ||
(logToOpenTelemetry is true))
{
LoggingEnabled = true;
var loggerConfig = new LoggerConfiguration().MinimumLevel.Verbose();
bool npgsqlRestAdded = false;
bool npgsqlRestClientAdded = false;
bool systemAdded = false;
bool microsoftAdded = false;
var appName = _config.GetConfigStr("ApplicationName", _config.Cfg);
var envName = _config.GetConfigStr("EnvironmentName", _config.Cfg) ?? "Production";
string clientLoggerName = string.IsNullOrEmpty(appName) ? "NpgsqlRestClient" : appName;
foreach (var level in logCfg?.GetSection("MinimalLevels")?.GetChildren() ?? [])
{
var key = level.Key;
var value = _config.GetEnum<Serilog.Events.LogEventLevel?>(level.Value);
if (value is not null && key is not null)
{
if (string.Equals(key, "NpgsqlRest", StringComparison.OrdinalIgnoreCase))
{
loggerConfig.MinimumLevel.Override("NpgsqlRest", value.Value);
npgsqlRestAdded = true;
}
else if (string.Equals(key, "NpgsqlRestClient", StringComparison.OrdinalIgnoreCase))
{
loggerConfig.MinimumLevel.Override(clientLoggerName, value.Value);
npgsqlRestClientAdded = true;
}
else if (string.Equals(key, "System", StringComparison.OrdinalIgnoreCase))
{
loggerConfig.MinimumLevel.Override(key, value.Value);
systemAdded = true;
}
else if (string.Equals(key, "Microsoft", StringComparison.OrdinalIgnoreCase))
{
loggerConfig.MinimumLevel.Override(key, value.Value);
microsoftAdded = true;
}
else
{
loggerConfig.MinimumLevel.Override(key, value.Value);
}
}
}
if (npgsqlRestAdded is false)
{
loggerConfig.MinimumLevel.Override("NpgsqlRest", Serilog.Events.LogEventLevel.Information);
}
if (npgsqlRestClientAdded is false)
{
loggerConfig.MinimumLevel.Override(clientLoggerName, Serilog.Events.LogEventLevel.Information);
}
if (systemAdded is false)
{
loggerConfig.MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Warning);
}
if (microsoftAdded is false)
{
loggerConfig.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning);
}
string outputTemplate = _config.GetConfigStr("OutputTemplate", logCfg) ??
"[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj} [{SourceContext}]{NewLine}{Exception}";
List<string> logDebug = new(4);
if (logToConsole is true)
{
var minLevel = _config.GetConfigEnum<Serilog.Events.LogEventLevel?>("ConsoleMinimumLevel", logCfg) ?? Serilog.Events.LogEventLevel.Verbose;
loggerConfig = loggerConfig.WriteTo.Console(
restrictedToMinimumLevel: minLevel,
outputTemplate: outputTemplate,
theme: Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme.Code);
logDebug.Add(string.Concat("Console (minimum level: ", minLevel.ToString(), ")"));
}
if (logToFile is true)
{
var minLevel = _config.GetConfigEnum<Serilog.Events.LogEventLevel?>("FileMinimumLevel", logCfg) ?? Serilog.Events.LogEventLevel.Verbose;
loggerConfig = loggerConfig.WriteTo.File(
restrictedToMinimumLevel: minLevel,
path: filePath ?? "logs/log.txt",
rollingInterval: RollingInterval.Day,
fileSizeLimitBytes: _config.GetConfigInt("FileSizeLimitBytes", logCfg) ?? 30000000,
retainedFileCountLimit: _config.GetConfigInt("RetainedFileCountLimit", logCfg) ?? 30,
rollOnFileSizeLimit: _config.GetConfigBool("RollOnFileSizeLimit", logCfg, defaultVal: true),
outputTemplate: outputTemplate);
logDebug.Add(string.Concat("Rolling File (minimum level: ", minLevel.ToString(), ")"));
}
if (logToPostgres is true && postgresCommand is not null)
{
var minLevel = _config.GetConfigEnum<Serilog.Events.LogEventLevel?>("PostgresMinimumLevel", logCfg) ?? Serilog.Events.LogEventLevel.Verbose;
loggerConfig = loggerConfig.WriteTo.Postgres(
postgresCommand,
restrictedToMinimumLevel: minLevel,
connectionString: ConnectionString,
cmdRetryStrategy);
logDebug.Add(string.Concat("PostgreSQL Database (minimum level: ", minLevel.ToString(), ", command: ", postgresCommand, ")"));
}
if (logToOpenTelemetry)
{
var minLevel = _config.GetConfigEnum<Serilog.Events.LogEventLevel?>("OTLPMinimumLevel", logCfg) ?? Serilog.Events.LogEventLevel.Verbose;
var endpoint = _config.GetConfigStr("OTLPEndpoint", logCfg) ?? "http://localhost:4317";
var protocol = _config.GetConfigEnum<OtlpProtocol?>("OTLPProtocol", logCfg) ?? OtlpProtocol.Grpc;
loggerConfig = loggerConfig.WriteTo.OpenTelemetry(options =>
{
options.Endpoint = endpoint;
options.Protocol = protocol;
var formatDict = new Dictionary<string, string>
{
["application"] = appName ?? "NpgsqlRest",
["environment"] = envName
};
if (logCfg is not null)
{
options.ResourceAttributes =
(_config.GetConfigDict(logCfg.GetSection("OTLResourceAttributes")) ??
new Dictionary<string, string>())
.ToDictionary(kv => kv.Key,
kv => (object)Formatter.FormatString(kv.Value.AsSpan(), formatDict).ToString());
var headers = _config.GetConfigDict(logCfg.GetSection("OTLPHeaders"));
if (headers is not null && headers.Count > 0)
{
options.Headers = headers;
}
}
options.LevelSwitch = new Serilog.Core.LoggingLevelSwitch(minLevel);
});
logDebug.Add(string.Concat("OpenTelemetry (minimum level: ", minLevel.ToString(), ", endpoint: ", endpoint, ", protocol: ", protocol.ToString(), ")"));
}
var serilog = loggerConfig.CreateLogger();
var serilogFactory = new SerilogLoggerFactory(serilog);
// Core library logger - always uses "NpgsqlRest" name
Logger = serilogFactory.CreateLogger("NpgsqlRest");
// Client application logger - uses ApplicationName or "NpgsqlRestClient"
ClientLogger = serilogFactory.CreateLogger(clientLoggerName);
Instance.Host.UseSerilog(serilog);
var providerString = _config.Cfg.Providers.Select(p =>
{
var str = p.ToString();
if (p is Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider j)
{
if(File.Exists(j.Source.Path) is false)
{
str = str?.Replace("(Optional)", "(Missing)");
}
}
return str;
}).Aggregate((a, b) => string.Concat(a, ", ", b));
ClientLogger?.LogDebug("----> Starting with configuration(s): {providerString}", providerString);
if (logDebug.Count > 0)
{
ClientLogger?.LogDebug("----> Logging enabled: {logDebug}", string.Join(", ", logDebug));
}
}
}
public ErrorHandlingOptions BuildErrorHandlingOptions()
{
var errConfig = _config.Cfg.GetSection("ErrorHandlingOptions");
var defaults = new ErrorHandlingOptions();
if (errConfig.Exists() is false)
{
// Always register ProblemDetails for AOT compatibility
// Apply default behavior: remove traceId (matches default when config exists)
Instance.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = ctx =>
{
ctx.ProblemDetails.Extensions.Remove("traceId");
};
});
var defaultTimeoutLog = defaults.TimeoutErrorMapping?.ToString() ?? "disabled";
var defaultPoliciesLog = defaults.ErrorCodePolicies.Count > 0
? string.Join("; ", defaults.ErrorCodePolicies.Select(p =>
$"{p.Key}: [{string.Join(", ", p.Value.Select(m => $"{m.Key}->{m.Value.StatusCode}"))}]"))
: "none";
ClientLogger?.LogDebug("Using default error handling options: DefaultErrorCodePolicy={DefaultErrorCodePolicy}, TimeoutErrorMapping=[{TimeoutErrorMapping}], ErrorCodePolicies=[{ErrorCodePolicies}]",
defaults.DefaultErrorCodePolicy ?? "Default",
defaultTimeoutLog,
defaultPoliciesLog);
return defaults;
}
var removeTypeUrl = _config.GetConfigBool("RemoveTypeUrl", errConfig);
var removeTraceId = _config.GetConfigBool("RemoveTraceId", errConfig, true);
// Always register ProblemDetails for AOT compatibility
Instance.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = ctx =>
{
// Remove the type field completely
if (removeTypeUrl is true)
{
ctx.ProblemDetails.Type = null;
}
// Remove the traceId extension
if (removeTraceId is true)
{
ctx.ProblemDetails.Extensions.Remove("traceId");
}
};
});
var result = new ErrorHandlingOptions
{
DefaultErrorCodePolicy = _config.GetConfigStr("DefaultErrorCodePolicy", errConfig) ?? defaults.DefaultErrorCodePolicy
};
var timeoutErrorMapping = errConfig.GetSection("TimeoutErrorMapping");
if (timeoutErrorMapping.Exists())
{
var statusCode = _config.GetConfigInt("StatusCode", timeoutErrorMapping);
if (statusCode is not null)
{
result.TimeoutErrorMapping = new()
{
StatusCode = statusCode.Value,
Title = _config.GetConfigStr("Title", timeoutErrorMapping),
Details = _config.GetConfigStr("Details", timeoutErrorMapping),
Type = _config.GetConfigStr("Type", timeoutErrorMapping),
};
}
}
else
{
result.TimeoutErrorMapping = defaults.TimeoutErrorMapping;
}
result.ErrorCodePolicies = new Dictionary<string, Dictionary<string, ErrorCodeMappingOptions>>();
var policiesCfg = errConfig.GetSection("ErrorCodePolicies");
foreach (var policySection in policiesCfg.GetChildren())
{
var policy = _config.GetConfigStr("Name", policySection);
if (string.IsNullOrEmpty(policy))
{
continue;
}
var mappingCfg = policySection.GetSection("ErrorCodes");
var mappingDict = new Dictionary<string, ErrorCodeMappingOptions>();
foreach (var mappingSection in mappingCfg.GetChildren())
{
var errorCode = mappingSection.Key;
if (string.IsNullOrEmpty(errorCode))
{
continue;
}
var statusCode = _config.GetConfigInt("StatusCode", mappingSection);
if (statusCode is null)
{
continue;
}
mappingDict.TryAdd(errorCode, new()
{
StatusCode = statusCode.Value,
Title = _config.GetConfigStr("Title", mappingSection),
Details = _config.GetConfigStr("Details", mappingSection),
Type = _config.GetConfigStr("Type", mappingSection),
});
}
if (mappingDict.Count > 0)
{
result.ErrorCodePolicies[policy] = mappingDict;
}
}
if (result.ErrorCodePolicies.Count == 0)
{
result.ErrorCodePolicies = defaults.ErrorCodePolicies;
}
// Log error handling options
var timeoutLog = result.TimeoutErrorMapping is not null
? result.TimeoutErrorMapping.ToString()
: "disabled";
var policiesLog = result.ErrorCodePolicies.Count > 0
? string.Join("; ", result.ErrorCodePolicies.Select(p =>
$"{p.Key}: [{string.Join(", ", p.Value.Select(m => $"{m.Key}->{m.Value.StatusCode}"))}]"))
: "none";
ClientLogger?.LogDebug("Using error handling options: DefaultErrorCodePolicy={DefaultErrorCodePolicy}, RemoveTypeUrl={RemoveTypeUrl}, RemoveTraceId={RemoveTraceId}, TimeoutErrorMapping=[{TimeoutErrorMapping}], ErrorCodePolicies=[{ErrorCodePolicies}]",
result.DefaultErrorCodePolicy ?? "Default",
removeTypeUrl,
removeTraceId,
timeoutLog,
policiesLog);
return result;
}
public enum DataProtectionStorage
{
Default,
FileSystem,
Database
}
public enum KeyEncryptionMethod
{
None,
Certificate,
Dpapi // Windows only
}
public string? BuildDataProtection(RetryStrategy? cmdRetryStrategy)
{
var dataProtectionCfg = _config.Cfg.GetSection("DataProtection");
if (_config.Exists(dataProtectionCfg) is false || _config.GetConfigBool("Enabled", dataProtectionCfg) is false)
{
return null;
}
var dataProtectionBuilder = Instance.Services.AddDataProtection();
var encryptionAlgorithm = _config.GetConfigEnum<EncryptionAlgorithm?>("EncryptionAlgorithm", dataProtectionCfg);
var validationAlgorithm = _config.GetConfigEnum<ValidationAlgorithm?>("ValidationAlgorithm", dataProtectionCfg);
if (encryptionAlgorithm is not null || validationAlgorithm is not null)
{
dataProtectionBuilder.UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration
{
EncryptionAlgorithm = encryptionAlgorithm ?? EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = validationAlgorithm ?? ValidationAlgorithm.HMACSHA256
});
}
DirectoryInfo? dirInfo = null;
var storage = _config.GetConfigEnum<DataProtectionStorage?>("Storage", dataProtectionCfg) ?? DataProtectionStorage.Default;
if (storage == DataProtectionStorage.FileSystem)
{
var path = _config.GetConfigStr("FileSystemPath", dataProtectionCfg);
if (string.IsNullOrEmpty(path) is true)
{
throw new ArgumentException("FileSystemPath value in DataProtection can't be null or empty when using FileSystem Storage");
}
dirInfo = new DirectoryInfo(path);
dataProtectionBuilder.PersistKeysToFileSystem(dirInfo);
}
else if (storage == DataProtectionStorage.Database)
{
var getAllElementsCommand = _config.GetConfigStr("GetAllElementsCommand", dataProtectionCfg) ?? "select get_data_protection_keys()";
var storeElementCommand = _config.GetConfigStr("StoreElementCommand", dataProtectionCfg) ?? "call store_data_protection_keys($1,$2)";
Instance.Services.Configure<KeyManagementOptions>(options =>
{
options.XmlRepository = new DbDataProtection(
ConnectionString,
getAllElementsCommand,
storeElementCommand,
cmdRetryStrategy,
Logger);
});
}
var keyEncryption = _config.GetConfigEnum<KeyEncryptionMethod?>("KeyEncryption", dataProtectionCfg) ?? KeyEncryptionMethod.None;
if (keyEncryption == KeyEncryptionMethod.Certificate)
{
var certPath = _config.GetConfigStr("CertificatePath", dataProtectionCfg);
if (string.IsNullOrEmpty(certPath))
{
throw new ArgumentException("CertificatePath value in DataProtection can't be null or empty when using Certificate KeyEncryption");
}
var certPassword = _config.GetConfigStr("CertificatePassword", dataProtectionCfg);
if (string.IsNullOrEmpty(certPassword))
{
dataProtectionBuilder.ProtectKeysWithCertificate(System.Security.Cryptography.X509Certificates.X509CertificateLoader.LoadPkcs12FromFile(certPath, null));
}
else
{
dataProtectionBuilder.ProtectKeysWithCertificate(System.Security.Cryptography.X509Certificates.X509CertificateLoader.LoadPkcs12FromFile(certPath, certPassword));
}
ClientLogger?.LogDebug("Data Protection keys encrypted with certificate from {certPath}", certPath);
}
else if (keyEncryption == KeyEncryptionMethod.Dpapi)
{
if (OperatingSystem.IsWindows() is false)
{
throw new PlatformNotSupportedException("DPAPI key encryption is only supported on Windows");
}
var protectToLocalMachine = _config.GetConfigBool("DpapiLocalMachine", dataProtectionCfg);
#pragma warning disable CA1416 // Validate platform compatibility - already checked above
dataProtectionBuilder.ProtectKeysWithDpapi(protectToLocalMachine);
#pragma warning restore CA1416
ClientLogger?.LogDebug("Data Protection keys encrypted with DPAPI (LocalMachine: {protectToLocalMachine})", protectToLocalMachine);
}
var expiresInDays = _config.GetConfigInt("DefaultKeyLifetimeDays", dataProtectionCfg) ?? 90;
dataProtectionBuilder.SetDefaultKeyLifetime(TimeSpan.FromDays(expiresInDays));
var customAppName = _config.GetConfigStr("CustomApplicationName", dataProtectionCfg);
if (string.IsNullOrEmpty(customAppName) is true)
{
customAppName = Instance.Environment.ApplicationName;
}
dataProtectionBuilder.SetApplicationName(customAppName);
if (storage == DataProtectionStorage.Default)
{
ClientLogger?.LogDebug("Using Data Protection for application {customAppName} with default provider. Expiration in {expiresInDays} days.",
customAppName,
expiresInDays);
}
else
{
ClientLogger?.LogDebug($"Using Data Protection for application {{customAppName}} in{(dirInfo is null ? " " : " directory ")}{{dirInfo}}. Expiration in {{expiresInDays}} days.",
customAppName,
dirInfo?.FullName ?? "database",
expiresInDays);
}
return customAppName;
}
public void BuildAuthentication()
{
var authCfg = _config.Cfg.GetSection("Auth");
bool cookieAuth = false;
bool bearerTokenAuth = false;
bool jwtAuth = false;
if (_config.Exists(authCfg) is true)
{
cookieAuth = _config.GetConfigBool("CookieAuth", authCfg);
bearerTokenAuth = _config.GetConfigBool("BearerTokenAuth", authCfg);
jwtAuth = _config.GetConfigBool("JwtAuth", authCfg);
}
if (cookieAuth is false && bearerTokenAuth is false && jwtAuth is false)
{
return;
}
var cookieScheme = _config.GetConfigStr("CookieAuthScheme", authCfg) ?? CookieAuthenticationDefaults.AuthenticationScheme;
var tokenScheme = _config.GetConfigStr("BearerTokenAuthScheme", authCfg) ?? BearerTokenDefaults.AuthenticationScheme;
var jwtScheme = _config.GetConfigStr("JwtAuthScheme", authCfg) ?? JwtBearerDefaults.AuthenticationScheme;
// Build default scheme name based on enabled auth methods
var enabledSchemes = new List<string>();
if (cookieAuth) enabledSchemes.Add(cookieScheme);
if (bearerTokenAuth) enabledSchemes.Add(tokenScheme);
if (jwtAuth) enabledSchemes.Add(jwtScheme);
// Pre-scan Auth:Schemes for enabled Cookie-type entries so we can decide upfront whether a
// policy scheme is needed (and, if so, whether the existing composite name collides with a
// single main scheme's own name). Full registration runs later in RegisterAuthSchemes.
var namedCookieSchemeCount = CountEnabledNamedCookieSchemes(authCfg);
var totalCookieSchemes = (cookieAuth ? 1 : 0) + namedCookieSchemeCount;
// Policy scheme triggers:
// - Existing case: more than one of {cookies, bearer, jwt} is enabled.
// - New case: cookies enabled plus one or more named cookie schemes — so requests bearing a
// named-scheme cookie can still authenticate against ASP.NET's default scheme.
var needsPolicyScheme = enabledSchemes.Count > 1 || totalCookieSchemes > 1;
// defaultScheme is what ASP.NET treats as the DefaultAuthenticateScheme. When we register a
// policy scheme, this MUST be the policy scheme's name. The composite "_and_"-joined name is
// distinct from any individual scheme. But when only one main scheme is enabled, we can't
// reuse its name for the policy scheme (collides with the existing AddCookie/AddJwtBearer/...
// registration), so a synthetic name is used instead.
const string SyntheticPolicySchemeName = "NpgsqlRest_PolicyScheme";
string defaultScheme;
string? policySchemeName;
if (enabledSchemes.Count > 1)
{
defaultScheme = string.Join("_and_", enabledSchemes);
policySchemeName = defaultScheme;
}
else if (needsPolicyScheme)
{
defaultScheme = SyntheticPolicySchemeName;
policySchemeName = SyntheticPolicySchemeName;
}
else
{
defaultScheme = enabledSchemes[0];
policySchemeName = null;
}
// Fail fast if any of the four legacy integer time fields is still present in the user's config
// (CookieValidDays / BearerTokenExpireHours / JwtExpireMinutes / JwtRefreshExpireDays). They were
// removed in 3.13.0 in favor of the interval-notation fields.
DetectLegacyAuthTimeFields(authCfg);
var auth = Instance.Services.AddAuthentication(defaultScheme);
if (cookieAuth is true)
{
var cookieValid = ResolveAuthTimeSpan("CookieValid", TimeSpan.FromDays(14), authCfg);
var mainCookieNameRaw = _config.GetConfigStr("CookieName", authCfg);
var mainSameSite = ResolveSameSiteMode("CookieSameSite", authCfg);
var mainSecure = ResolveCookieSecurePolicy("CookieSecure", authCfg);
WarnIfSameSiteNoneWithoutSecure(authCfg.Path, mainSameSite, mainSecure);
auth.AddCookie(cookieScheme, options =>
{
options.ExpireTimeSpan = cookieValid;
if (string.IsNullOrEmpty(mainCookieNameRaw) is false)
{
options.Cookie.Name = mainCookieNameRaw;
}
options.Cookie.Path = _config.GetConfigStr("CookiePath", authCfg);
options.Cookie.Domain = _config.GetConfigStr("CookieDomain", authCfg);
options.Cookie.MaxAge = _config.GetConfigBool("CookieMultiSessions", authCfg, true) is true ? cookieValid : null;
options.Cookie.HttpOnly = _config.GetConfigBool("CookieHttpOnly", authCfg, true) is true;
if (mainSameSite is not null) options.Cookie.SameSite = mainSameSite.Value;
if (mainSecure is not null) options.Cookie.SecurePolicy = mainSecure.Value;
});
// Track the resolved cookie name for the policy-scheme selector. When CookieName is unset,
// ASP.NET defaults Cookie.Name to ".AspNetCore.<schemeName>".
CookieSchemesInOrder.Add((cookieScheme,
string.IsNullOrEmpty(mainCookieNameRaw) ? $".AspNetCore.{cookieScheme}" : mainCookieNameRaw));
ClientLogger?.LogDebug(
"Using Cookie Authentication with scheme {cookieScheme}. Cookie expires in {cookieValid}. SameSite={SameSite}, Secure={Secure}.",
cookieScheme, cookieValid,
mainSameSite?.ToString() ?? "<default>",
mainSecure?.ToString() ?? "<default>");
}
if (bearerTokenAuth is true)
{
var bearerExpire = ResolveAuthTimeSpan("BearerTokenExpire", TimeSpan.FromHours(1), authCfg);
BearerTokenConfig = new()
{
Scheme = tokenScheme,
RefreshPath = _config.GetConfigStr("BearerTokenRefreshPath", authCfg)
};
auth.AddBearerToken(tokenScheme, options =>
{
options.BearerTokenExpiration = bearerExpire;
options.RefreshTokenExpiration = bearerExpire;
options.Validate();
});
ClientLogger?.LogDebug(
"Using Bearer Token Authentication with scheme {tokenScheme}. Token expires in {bearerExpire}. Refresh path is {RefreshPath}",
tokenScheme,
bearerExpire,
BearerTokenConfig.RefreshPath);
}
if (jwtAuth is true)
{
var jwtSecret = _config.GetConfigStr("JwtSecret", authCfg);
if (string.IsNullOrEmpty(jwtSecret))
{
throw new InvalidOperationException("JwtSecret must be configured when JwtAuth is enabled. The secret must be at least 32 characters for HS256.");
}
if (jwtSecret.Length < 32)
{
throw new InvalidOperationException("JwtSecret must be at least 32 characters long for HS256 algorithm.");
}
var jwtExpire = ResolveAuthTimeSpan("JwtExpire", TimeSpan.FromMinutes(60), authCfg);
var jwtRefreshExpire = ResolveAuthTimeSpan("JwtRefreshExpire", TimeSpan.FromDays(7), authCfg);
var clockSkew = Parser.ParsePostgresInterval(_config.GetConfigStr("JwtClockSkew", authCfg)) ?? TimeSpan.FromMinutes(5);
JwtTokenConfig = new()
{
Scheme = jwtScheme,
Secret = jwtSecret,
Issuer = _config.GetConfigStr("JwtIssuer", authCfg),
Audience = _config.GetConfigStr("JwtAudience", authCfg),
Expire = jwtExpire,
RefreshExpire = jwtRefreshExpire,
ValidateIssuer = _config.GetConfigBool("JwtValidateIssuer", authCfg),
ValidateAudience = _config.GetConfigBool("JwtValidateAudience", authCfg),
ValidateLifetime = _config.GetConfigBool("JwtValidateLifetime", authCfg, true),
ValidateIssuerSigningKey = _config.GetConfigBool("JwtValidateIssuerSigningKey", authCfg, true),
ClockSkew = clockSkew,
RefreshPath = _config.GetConfigStr("JwtRefreshPath", authCfg)
};
auth.AddJwtBearer(jwtScheme, options =>
{
options.TokenValidationParameters = JwtTokenConfig.GetTokenValidationParameters();
options.SaveToken = true;
});
ClientLogger?.LogDebug(
"Using JWT Authentication with scheme {jwtScheme}. Access token expires in {jwtExpire}. Refresh token expires in {jwtRefreshExpire}. Refresh path is {RefreshPath}",
jwtScheme,
jwtExpire,
jwtRefreshExpire,
JwtTokenConfig.RefreshPath);
}
// Register additional authentication schemes from Auth:Schemes. Each enabled entry registers a
// fully-fledged ASP.NET Core authentication scheme (Cookie, BearerToken, or Jwt) so a login
// function can return that scheme's name in its `scheme` column to sign in under those options.
RegisterAuthSchemes(auth, authCfg, cookieScheme, tokenScheme, jwtScheme);
// Register the policy scheme whenever we have:
// - more than one of {cookies, bearer, jwt} enabled (legacy case), OR
// - more than one cookie scheme (main + named, or multiple named) — the named-schemes case.
// For the cookie-only case the synthetic policy name is used (see SyntheticPolicySchemeName
// above) to avoid colliding with the main cookie scheme's own AddCookie registration.
if (needsPolicyScheme)
{
// Capture the cookie-scheme list by reference: it gets filled out below by
// RegisterAuthSchemes → RegisterCookieSchemeFromConfig before any request is dispatched.
var cookieSchemes = CookieSchemesInOrder;
auth.AddPolicyScheme(policySchemeName!, policySchemeName!, options =>
{
// runs on each request
options.ForwardDefaultSelector = context =>
{
string? authorization = context.Request.Headers[HeaderNames.Authorization];
if (string.IsNullOrEmpty(authorization) is false && authorization.StartsWith("Bearer "))
{
// For Bearer tokens, we need to determine if it's JWT or Microsoft Bearer Token
// JWT tokens are in format: xxxxx.yyyyy.zzzzz (three Base64 parts separated by dots)
var token = authorization["Bearer ".Length..].Trim();
if (jwtAuth && IsJwtToken(token))
{
return jwtScheme;
}
if (bearerTokenAuth)
{
return tokenScheme;
}
}
// Cookie-aware dispatch: walk registered cookie schemes in order and return the
// first one whose configured cookie name is present in the request. This lets
// named-scheme cookies authenticate against their own scheme (so any endpoint that
// consults context.User — passkey endpoints, @authorize, plain IsAuthenticated
// checks — accepts them just like the main cookie).
foreach (var (schemeName, cookieName) in cookieSchemes)
{
if (context.Request.Cookies.ContainsKey(cookieName))
{
return schemeName;
}
}
// Default to cookie auth if enabled
if (cookieAuth)
{
return cookieScheme;
}
// Fallback to first enabled scheme
return enabledSchemes[0];
};
});
}
if (cookieAuth || bearerTokenAuth || jwtAuth)
{
ExternalAuthConfig = new ExternalAuthConfig();
ExternalAuthConfig.Build(authCfg, _config, this);
}
}
/// <summary>
/// Resolves a <see cref="Microsoft.AspNetCore.Http.SameSiteMode"/> from a string config value. Accepts the four ASP.NET enum
/// names case-insensitively (<c>Unspecified</c>, <c>None</c>, <c>Lax</c>, <c>Strict</c>). Returns
/// null when the key is unset/empty so the caller can preserve ASP.NET's per-handler default.
/// Throws on unknown values — silently falling back hides typos in security-relevant config.
/// </summary>
private Microsoft.AspNetCore.Http.SameSiteMode? ResolveSameSiteMode(string key, IConfigurationSection section)
{
var raw = _config.GetConfigStr(key, section);
if (string.IsNullOrWhiteSpace(raw))
{
return null;
}
if (Enum.TryParse<Microsoft.AspNetCore.Http.SameSiteMode>(raw, ignoreCase: true, out var parsed)
&& Enum.IsDefined(parsed))
{
return parsed;
}
throw new InvalidOperationException(
$"Invalid value '{raw}' for {section.Path}:{key}. Expected one of: Unspecified, None, Lax, Strict.");
}
/// <summary>
/// Resolves a <see cref="CookieSecurePolicy"/> from a string config value. Accepts the three
/// ASP.NET enum names case-insensitively (<c>SameAsRequest</c>, <c>Always</c>, <c>None</c>).
/// Returns null when unset so ASP.NET's default (<c>SameAsRequest</c>) applies. Throws on unknown
/// values.
/// </summary>
private CookieSecurePolicy? ResolveCookieSecurePolicy(string key, IConfigurationSection section)
{
var raw = _config.GetConfigStr(key, section);
if (string.IsNullOrWhiteSpace(raw))
{
return null;
}
if (Enum.TryParse<CookieSecurePolicy>(raw, ignoreCase: true, out var parsed)
&& Enum.IsDefined(parsed))
{
return parsed;
}
throw new InvalidOperationException(
$"Invalid value '{raw}' for {section.Path}:{key}. Expected one of: SameAsRequest, Always, None.");
}
/// <summary>
/// Logs a warning at startup when a cookie scheme is configured with <c>SameSite=None</c> but
/// without forcing <c>Secure=Always</c>. Browsers silently drop <c>SameSite=None</c> cookies that
/// lack the <c>Secure</c> attribute, which produces a hard-to-diagnose "logs in, but no cookie
/// arrives on the next request" symptom — especially under local HTTP testing.
/// </summary>
private void WarnIfSameSiteNoneWithoutSecure(string sectionPath, Microsoft.AspNetCore.Http.SameSiteMode? sameSite, CookieSecurePolicy? secure)
{
if (sameSite == Microsoft.AspNetCore.Http.SameSiteMode.None && secure != CookieSecurePolicy.Always)
{
ClientLogger?.LogWarning(
"{Path}:CookieSameSite=None requires CookieSecure=Always — browsers drop SameSite=None cookies " +
"without the Secure attribute. Set {Path}:CookieSecure to \"Always\".",
sectionPath, sectionPath);
}
}
/// <summary>
/// Pre-scan helper: counts enabled Cookie-type entries under <c>Auth:Schemes</c> without registering
/// them. Used by <see cref="BuildAuthentication"/> to decide upfront whether a policy scheme is
/// needed (and what default scheme name to pass to <c>AddAuthentication</c>) before
/// <see cref="RegisterAuthSchemes"/> runs the real registration. Validation and full processing
/// happen later in <see cref="RegisterCookieSchemeFromConfig"/>; this method is intentionally lax —
/// it skips entries whose <c>Type</c> isn't <c>Cookies</c> and trusts <see cref="RegisterAuthSchemes"/>
/// to throw on shape errors.
/// </summary>
private int CountEnabledNamedCookieSchemes(IConfigurationSection authCfg)
{
var schemesCfg = authCfg.GetSection("Schemes");
if (!schemesCfg.Exists())
{
return 0;
}
var count = 0;
foreach (var sch in schemesCfg.GetChildren())
{
if (string.IsNullOrWhiteSpace(sch.Key))
{
continue;
}
if (_config.GetConfigBool("Enabled", sch, true) is false)
{
continue;
}
var typeStr = _config.GetConfigStr("Type", sch);
if (string.Equals(typeStr, "Cookies", StringComparison.OrdinalIgnoreCase))
{
count++;
}
}
return count;
}
/// <summary>
/// Resolves an auth-related <see cref="TimeSpan"/> from a Postgres-interval string at the given key.
/// Returns <paramref name="defaultValue"/> when the field is null/empty/missing. Throws on
/// syntactically invalid interval values (fail-fast at startup).
///
/// Reads from the section provided in <paramref name="authCfg"/> — this is reused for both the root
/// <c>Auth</c> section and individual <c>Auth:Schemes:<name></c> sections.
/// </summary>
public TimeSpan ResolveAuthTimeSpan(string key, TimeSpan defaultValue, IConfigurationSection authCfg)
{
var raw = _config.GetConfigStr(key, authCfg);
if (string.IsNullOrWhiteSpace(raw))
{
return defaultValue;
}
return Parser.ParsePostgresInterval(raw)
?? throw new InvalidOperationException(
$"Invalid interval value for {authCfg.Path}:{key}: '{raw}'. Expected Postgres interval syntax (e.g. '14 days', '1 hour', '60 minutes').");
}
/// <summary>
/// Throws if any of the four removed legacy auth time fields appears in the user's config. We
/// hard-cut these in 3.13.0 (interval notation is the only supported form). Failing fast — rather
/// than silently ignoring legacy fields — prevents the surprising case where an upgraded user's
/// "this should be 30 days" expiration silently flips to the new field's default of 14 days.
/// </summary>
private void DetectLegacyAuthTimeFields(IConfigurationSection authCfg)
{
DetectLegacyAuthTimeField(authCfg, "CookieValidDays", "CookieValid", "e.g. \"14 days\"");
DetectLegacyAuthTimeField(authCfg, "BearerTokenExpireHours", "BearerTokenExpire", "e.g. \"1 hour\"");
DetectLegacyAuthTimeField(authCfg, "JwtExpireMinutes", "JwtExpire", "e.g. \"60 minutes\"");
DetectLegacyAuthTimeField(authCfg, "JwtRefreshExpireDays", "JwtRefreshExpire", "e.g. \"7 days\"");
}
private void DetectLegacyAuthTimeField(IConfigurationSection authCfg, string legacyKey, string newKey, string example)
{
// Distinguish "key explicitly set" from "key absent" by checking the section directly. Calling
// GetConfigStr/GetConfigInt would return null in both cases.
var section = authCfg.GetSection(legacyKey);
if (section.Value is null && !section.GetChildren().Any())
{
return;
}
throw new InvalidOperationException(
$"Auth:{legacyKey} has been removed in 3.13.0. Use Auth:{newKey} with Postgres interval syntax instead ({example}). " +
$"See changelog/v3.13.0.md for migration details.");
}
/// <summary>
/// Registers additional authentication schemes declared under <c>Auth:Schemes</c>. Each enabled
/// entry becomes a fully-fledged ASP.NET Core authentication scheme of type Cookies, BearerToken,
/// or Jwt — login functions returning the scheme's name in the <c>scheme</c> column sign in under
/// those options.
///
/// All scheme types inherit any unset field from the root <c>Auth</c> section so blocks stay small.
/// Validation (fail-fast at startup):
/// <list type="bullet">
/// <item>Scheme name must not collide with the main scheme names (CookieAuthScheme,
/// BearerTokenAuthScheme, JwtAuthScheme).</item>
/// <item><c>Type</c> must be one of Cookies / BearerToken / Jwt (case-insensitive).</item>
/// <item>Explicit <c>CookieName</c> values must be unique across all cookie schemes.</item>
/// <item>Refresh paths must be unique across all schemes that define one.</item>
/// <item>Jwt schemes inherit <c>JwtSecret</c> from root if unset; secret must be ≥32 chars.</item>
/// </list>
///
/// BearerToken/Jwt scheme configs are appended to <see cref="AdditionalBearerTokenConfigs"/> /
/// <see cref="AdditionalJwtTokenConfigs"/> so <see cref="App"/> can wire per-scheme refresh
/// middlewares and the <see cref="JwtLoginHandler"/> can resolve the right config when a login
/// function returns one of these scheme names.
/// </summary>
public void RegisterAuthSchemes(
Microsoft.AspNetCore.Authentication.AuthenticationBuilder auth,
IConfigurationSection authCfg,
string cookieScheme,
string tokenScheme,
string jwtScheme)
{
var schemesCfg = authCfg.GetSection("Schemes");
if (!schemesCfg.Exists())
{
return;
}
// Track CookieName values across the main cookie scheme + Cookie-type schemes that set one
// explicitly. Schemes that don't set CookieName use ASP.NET's per-scheme `.AspNetCore.<name>`
// default which auto-differs and is excluded from collision tracking.
var explicitCookieNames = new HashSet<string>(StringComparer.Ordinal);
var mainCookieName = _config.GetConfigStr("CookieName", authCfg);
if (!string.IsNullOrEmpty(mainCookieName))
{