diff --git a/AgileConfig.sln b/AgileConfig.sln index eefa9081..baf13336 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.6.33801.468 @@ -60,6 +60,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Applicat EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.ApplicationTests", "test\AgileConfig.Server.ApplicationTests\AgileConfig.Server.ApplicationTests.csproj", "{0AF33559-2F97-4F77-B8E4-859B6A341BA8}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.MongodbTests", "test\AgileConfig.Server.Data.MongodbTests\AgileConfig.Server.Data.MongodbTests.csproj", "{CE8930D4-1D11-4DD1-8A43-45AEA1072113}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -154,6 +156,10 @@ Global {0AF33559-2F97-4F77-B8E4-859B6A341BA8}.Debug|Any CPU.Build.0 = Debug|Any CPU {0AF33559-2F97-4F77-B8E4-859B6A341BA8}.Release|Any CPU.ActiveCfg = Release|Any CPU {0AF33559-2F97-4F77-B8E4-859B6A341BA8}.Release|Any CPU.Build.0 = Release|Any CPU + {CE8930D4-1D11-4DD1-8A43-45AEA1072113}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CE8930D4-1D11-4DD1-8A43-45AEA1072113}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CE8930D4-1D11-4DD1-8A43-45AEA1072113}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CE8930D4-1D11-4DD1-8A43-45AEA1072113}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -181,6 +187,7 @@ Global {899F5AAE-2C6F-4F0A-9358-6F5C7D0412DC} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {CA724F53-FA58-44CC-B0E7-5FD05CF5E63E} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {0AF33559-2F97-4F77-B8E4-859B6A341BA8} = {F277EC27-8C0E-4490-9645-F5F3244F9246} + {CE8930D4-1D11-4DD1-8A43-45AEA1072113} = {F277EC27-8C0E-4490-9645-F5F3244F9246} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7F10DB58-5B6F-4EAC-994F-14E8046B306F} diff --git a/README.md b/README.md index c7fa663e..ad3666b6 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,40 @@ sudo docker run \ After the docker instance has successfully started you can visit http://localhost:5000 . +#### Connect to MongoDB with a private CA (self-signed certificate) + +When the MongoDB server certificate is signed by a private CA (for example a self-hosted replica set), +pass that CA to AgileConfig. Otherwise the driver fails with +`The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot`. + +Two equivalent ways: + +```shell +# 1) connection string option, the same form mongosh and the other official drivers accept +-e db__conn="mongodb://user:pwd@mdb1.example.com:27017/db?replicaSet=rs0&authSource=admin&tls=true&tlsCAFile=/certs/ca.crt" \ +-v /host/path/ca.crt:/certs/ca.crt:ro \ + +# 2) dedicated setting, keeps the connection string portable across environments +-e db__tls__caFile=/certs/ca.crt \ +-v /host/path/ca.crt:/certs/ca.crt:ro \ +``` + +| Setting | Environment variable | Description | +|---|---|---| +| `db:tls:caFile` | `db__tls__caFile` | Path of the CA file (PEM or DER). A relative path resolves against the application directory. Mount the file into the container first. | +| `db:tls:ca` | `db__tls__ca` | Inline CA content: PEM (write line breaks as `\n`) or Base64 encoded DER. Useful when the certificate is injected as a secret instead of a file. | +| `db:tls:allowInvalidHostnames` | `db__tls__allowInvalidHostnames` | Skip the host name check only; chain validation still applies. | +| `db:tls:allowInvalidCertificates` | `db__tls__allowInvalidCertificates` | Skip certificate validation completely. Debug only. | +| `db:tls:checkCertificateRevocation` | `db__tls__checkCertificateRevocation` | Check CRL / OCSP while building the chain from `caFile` / `ca`. | + +> - When none of them is set, the behavior is identical to previous versions (the OS trust store is used). +> - The boolean options default to `false` and never enable TLS on their own. When custom TLS settings are effective (for example a CA is configured), TLS is enabled automatically unless the connection string explicitly says `tls=false` (or `ssl=false`), which always wins. +> - Rebuilt certificate chains keep the serverAuth (`1.3.6.1.5.5.7.3.1`) usage constraint, so a certificate that only allows clientAuth is still rejected. +> - Per environment override: `db:env:{TEST|STAGING|PROD}:tls:*`; a missing key falls back to `db:tls:*`. +> - `tlsCAFile`, `tlsAllowInvalidCertificates` and `tlsAllowInvalidHostnames` (including the legacy `ssl` prefix) are recognized by AgileConfig and stripped from the connection string before it reaches the .NET driver, which does not support them natively. All other options are passed through. +> - Client certificates (mTLS, `tlsCertificateKeyFile`) are not supported yet; a clear error is returned. +> - The private CA is additional trust: certificates already trusted by the OS still work. + ## use client install client lib from nuget: ``` diff --git a/README_CN.md b/README_CN.md index 1152acbb..bbf70a4b 100644 --- a/README_CN.md +++ b/README_CN.md @@ -104,7 +104,7 @@ AgileConfig的节点都是无状态的,所以可以横向部署多个节点来 有同学说你这样没什么卵用,数据库还是单点的,一旦数据库崩了,同样GG。但是数据库有数据库的高可用技术,比如mysql的binlog等等。至于数据库的高可用还是让数据库自己搞定吧。从架构上看携程的apollo数据库也是单点的。 ## 部署服务端 ## 初始化数据库 -用户只需要手工建一个空库,所有的表在第一次启动的时候都会自动生成。目前支持sqlserver,mysql,sqlite, PostgreSql,Oracle 五种数据库。 +用户只需要手工建一个空库,所有的表在第一次启动的时候都会自动生成。目前支持sqlserver,mysql,sqlite, PostgreSql,Oracle,MongoDB 六种数据库。 provider对照: sqlserver = SqlServer mysql = MySql @@ -128,7 +128,7 @@ sudo docker run \ ``` 通过docker建立一个agile_config实例,其中有3个环境变量需要配置: 1. adminConsole 配置程序是否为管理控制台。如果为true则启用控制台功能,访问该实例会出现管理界面。 -2. db__provider 配置程序的数据库类型。目前程序支持:sqlserver,mysql,sqlite, PostgreSql,Oracle 五种数据库。 +2. db__provider 配置程序的数据库类型。目前程序支持:sqlserver,mysql,sqlite, PostgreSql,Oracle,MongoDB 六种数据库。 3. db__conn 配置数据库连接串 > 💥注意:如果通过IIS或者别的方式部署,请自行从主页上的[releases](https://github.com/dotnetcore/AgileConfig/releases)页面下载最新的部署包。如果自己使用源码编译,请先编译react-ui-antd项目把dist内的产物复制到apisite项目的wwwroot/ui目录下。调试的时候需要复制到bin目录下。 @@ -184,6 +184,62 @@ services: networks: net0: ``` +### 连接启用 TLS 的 MongoDB(私有 CA / 自签证书) +MongoDB 使用私有 CA 签发服务端证书时(例如自建的三节点副本集),必须把这份 CA 交给 AgileConfig,否则会报 +`The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot`。 + +支持两种写法,任选其一。 + +**方式一:连接串参数**(与 `mongosh` 等官方客户端写法一致) + +```shell +-e db__conn="mongodb://user:pwd@mdb1.example.com:27017/db?replicaSet=rs0&authSource=admin&tls=true&tlsCAFile=/certs/ca.crt" \ +-v /host/path/ca.crt:/certs/ca.crt:ro \ +``` + +**方式二:独立配置项**(推荐,连接串可以在不同环境间复用) + +```shell +-e db__tls__caFile=/certs/ca.crt \ +-v /host/path/ca.crt:/certs/ca.crt:ro \ +``` + +完整示例: + +```shell +sudo docker run \ + --restart=always \ + --name agile_config \ + -e TZ=Asia/Shanghai \ + -e adminConsole=true \ + -e db__provider=mongodb \ + -e db__conn="mongodb://root:password@mdb1.example.com:27017,mdb2.example.com:27017,mdb3.example.com:27017/AgileConfig?replicaSet=rs0&authSource=admin&tls=true" \ + -e db__tls__caFile=/certs/ca.crt \ + -v /host/path/ca.crt:/certs/ca.crt:ro \ + -p 2371:5000 \ + -d kklldog/agile_config:latest +``` + +配置项说明: + +| 配置项 | 环境变量 | 说明 | +|---|---|---| +| `db:tls:caFile` | `db__tls__caFile` | CA 证书文件路径,支持 PEM / DER。相对路径基于程序目录解析。容器内必须先挂载该文件 | +| `db:tls:ca` | `db__tls__ca` | 直接内联 CA 内容。可为 PEM(换行写成 `\n`),也可为 Base64 编码的 DER,适合证书以 Secret 注入、无法挂载文件的场景 | +| `db:tls:allowInvalidHostnames` | `db__tls__allowInvalidHostnames` | 只跳过主机名校验,证书链校验仍然生效 | +| `db:tls:allowInvalidCertificates` | `db__tls__allowInvalidCertificates` | 完全跳过证书校验,仅用于排查问题,生产环境不要开启 | +| `db:tls:checkCertificateRevocation` | `db__tls__checkCertificateRevocation` | 使用 `caFile` / `ca` 建立证书链时是否检查 CRL / OCSP | + +> 💥注意: +> - 未配置以上任何一项时,程序行为与旧版本完全一致(使用操作系统的默认信任库),不需要修改已有部署。 +> - 三个布尔项默认就是 `false`,不会单独触发 TLS;只有自定义 TLS 配置真正生效时(例如配置了 CA),才会在连接串未显式写 `tls=false` 的情况下自动启用 TLS。连接串里显式的 `tls=false`(或 `ssl=false`)始终优先。 +> - 重建证书链时会保留服务端用途约束(serverAuth `1.3.6.1.5.5.7.3.1`),仅包含 clientAuth 用途的证书仍会被拒绝。 +> - 每个环境可以单独覆盖:`db:env:{TEST|STAGING|PROD}:tls:*`,未配置的项自动回退到全局 `db:tls:*`。 +> - 连接串里的 `tlsCAFile`、`tlsAllowInvalidCertificates`、`tlsAllowInvalidHostnames`(含 `ssl` 前缀的旧写法)会被 AgileConfig 识别并从连接串中剥离后再交给 .NET 驱动——.NET 驱动本身不支持这些参数,其余参数原样透传。 +> - 客户端证书(mTLS,`tlsCertificateKeyFile`)暂不支持,配置该参数会得到明确的错误提示。 +> - `ca.crt` 只包含公钥,可以安全分发。容器内**只挂载 `ca.crt`**,不要挂载 CA 私钥或服务端私钥。 +> - 私有 CA 是**追加信任**:操作系统已信任的公共证书依然可以连接,同一份配置可以在公网托管 MongoDB 与自建集群之间切换。 + ### 初始化管理员密码 第一次运行程序需要初始化超级管理员密码,超管用户名固定为 admin ![](https://static.xbaby.xyz/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20220821020958.png) diff --git a/README_EN.md b/README_EN.md index d1921170..216334b7 100644 --- a/README_EN.md +++ b/README_EN.md @@ -96,6 +96,40 @@ sudo docker run \ After the docker instance has successfully started you can visit http://localhost:5000 . +#### Connect to MongoDB with a private CA (self-signed certificate) + +When the MongoDB server certificate is signed by a private CA (for example a self-hosted replica set), +pass that CA to AgileConfig. Otherwise the driver fails with +`The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot`. + +Two equivalent ways: + +```shell +# 1) connection string option, the same form mongosh and the other official drivers accept +-e db__conn="mongodb://user:pwd@mdb1.example.com:27017/db?replicaSet=rs0&authSource=admin&tls=true&tlsCAFile=/certs/ca.crt" \ +-v /host/path/ca.crt:/certs/ca.crt:ro \ + +# 2) dedicated setting, keeps the connection string portable across environments +-e db__tls__caFile=/certs/ca.crt \ +-v /host/path/ca.crt:/certs/ca.crt:ro \ +``` + +| Setting | Environment variable | Description | +|---|---|---| +| `db:tls:caFile` | `db__tls__caFile` | Path of the CA file (PEM or DER). A relative path resolves against the application directory. Mount the file into the container first. | +| `db:tls:ca` | `db__tls__ca` | Inline CA content: PEM (write line breaks as `\n`) or Base64 encoded DER. Useful when the certificate is injected as a secret instead of a file. | +| `db:tls:allowInvalidHostnames` | `db__tls__allowInvalidHostnames` | Skip the host name check only; chain validation still applies. | +| `db:tls:allowInvalidCertificates` | `db__tls__allowInvalidCertificates` | Skip certificate validation completely. Debug only. | +| `db:tls:checkCertificateRevocation` | `db__tls__checkCertificateRevocation` | Check CRL / OCSP while building the chain from `caFile` / `ca`. | + +> - When none of them is set, the behavior is identical to previous versions (the OS trust store is used). +> - The boolean options default to `false` and never enable TLS on their own. When custom TLS settings are effective (for example a CA is configured), TLS is enabled automatically unless the connection string explicitly says `tls=false` (or `ssl=false`), which always wins. +> - Rebuilt certificate chains keep the serverAuth (`1.3.6.1.5.5.7.3.1`) usage constraint, so a certificate that only allows clientAuth is still rejected. +> - Per environment override: `db:env:{TEST|STAGING|PROD}:tls:*`; a missing key falls back to `db:tls:*`. +> - `tlsCAFile`, `tlsAllowInvalidCertificates` and `tlsAllowInvalidHostnames` (including the legacy `ssl` prefix) are recognized by AgileConfig and stripped from the connection string before it reaches the .NET driver, which does not support them natively. All other options are passed through. +> - Client certificates (mTLS, `tlsCertificateKeyFile`) are not supported yet; a clear error is returned. +> - The private CA is additional trust: certificates already trusted by the OS still work. + ## use client install client lib from nuget: ``` diff --git a/src/AgileConfig.Server.Apisite/appsettings.json b/src/AgileConfig.Server.Apisite/appsettings.json index 20b11cdd..15c0d29d 100644 --- a/src/AgileConfig.Server.Apisite/appsettings.json +++ b/src/AgileConfig.Server.Apisite/appsettings.json @@ -35,6 +35,20 @@ "db": { "provider": "", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb "conn": "", + // MongoDB only. Validates a server certificate that is signed by a private / self-signed CA. + // The defaults below do not enable TLS and do not change the driver behavior; the OS trust + // store is used unless a CA or an option that needs the custom validator is configured. + // Environment variables: db__tls__caFile, db__tls__ca, db__tls__allowInvalidHostnames, ... + // Per environment override: db:env:{env}:tls:* + "tls": { + "caFile": "", // Path of the CA file (PEM or DER). Relative paths resolve against the app directory. + // In Docker mount it first: -v /host/ca.crt:/certs/ca.crt:ro and set db__tls__caFile=/certs/ca.crt + "ca": "", // Inline CA content: PEM (use \n for line breaks), or Base64 encoded DER. + // Useful when the certificate cannot be mounted as a file (e.g. injected as a secret). + "allowInvalidCertificates": false, // false is the default and never enables TLS by itself. Debug only. + "allowInvalidHostnames": false, // false is the default and never enables TLS by itself. + "checkCertificateRevocation": false // false is the default and never enables TLS by itself. + }, "env": { "TEST": { "provider": "", //sqlite,mysql,sqlserver,npgsql,oracle diff --git a/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj b/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj index 047cc477..4fe053e2 100644 --- a/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj +++ b/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -6,7 +6,7 @@ - + diff --git a/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj b/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj index 40a84ab8..73b6b6a3 100644 --- a/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj +++ b/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -10,7 +10,11 @@ - + + + + + diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs index 7508ab3d..d3b9bea5 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs @@ -7,48 +7,121 @@ public abstract class MongodbAccess { private static readonly Lazy> LazyMongoClients = new(); - private readonly string _connectionString; + private readonly string _cacheKey; - internal MongodbAccess(string? connectionString) + internal MongodbAccess(string? connectionString, MongodbTlsOptions tlsOptions = null) { if (string.IsNullOrEmpty(connectionString)) { if (!LazyMongoClients.Value.IsEmpty) { - _connectionString = LazyMongoClients.Value.First().Key; + _cacheKey = LazyMongoClients.Value.First().Key; return; } throw new Exception("MongoDB connection string is not configured."); } - _connectionString = connectionString; - if (LazyMongoClients is not { IsValueCreated: true } || !LazyMongoClients.Value.ContainsKey(connectionString)) + // "tlsCAFile" and friends are accepted by most MongoDB drivers but not by the .NET one. + // They are extracted here and translated into the certificate validation callback below. + var normalized = MongodbConnectionString.Normalize(connectionString); + var effectiveTlsOptions = MongodbTlsOptions.Merge(tlsOptions, normalized.TlsOptions); + _cacheKey = BuildCacheKey(normalized.ConnectionString, effectiveTlsOptions); + + if (!LazyMongoClients.Value.ContainsKey(_cacheKey)) { - var url = MongoUrl.Create(connectionString); + var url = MongoUrl.Create(normalized.ConnectionString); // Use "AgileConfig" as the default database name when it is not specified in the connection string. const string defaultDataBaseName = "AgileConfig"; var databaseName = string.IsNullOrEmpty(url.DatabaseName) ? defaultDataBaseName : url.DatabaseName; - LazyMongoClients.Value.TryAdd(connectionString, new Db(databaseName, new MongoClient(url))); + LazyMongoClients.Value.TryAdd(_cacheKey, + new Db(databaseName, CreateClient(url, normalized.ConnectionString, effectiveTlsOptions))); } } /// /// Get the MongoDB client instance. /// - internal IMongoClient Client => LazyMongoClients.Value[_connectionString].Client ?? + internal IMongoClient Client => LazyMongoClients.Value[_cacheKey].Client ?? throw new Exception("IMongoClient value is null"); /// /// Get the MongoDB database instance. /// - public IMongoDatabase Database => Client.GetDatabase(LazyMongoClients.Value[_connectionString].DatabaseName); + public IMongoDatabase Database => Client.GetDatabase(LazyMongoClients.Value[_cacheKey].DatabaseName); + + private static string BuildCacheKey(string connectionString, MongodbTlsOptions tlsOptions) + { + return tlsOptions is null || tlsOptions.IsEmpty + ? connectionString + : $"{connectionString}|tls:{tlsOptions.CacheKey}"; + } + + private static IMongoClient CreateClient(MongoUrl url, string connectionString, MongodbTlsOptions tlsOptions) + { + if (tlsOptions is null || tlsOptions.IsEmpty) return new MongoClient(url); + + return new MongoClient(CreateClientSettings(url, connectionString, tlsOptions)); + } + + /// + /// Builds the driver settings for the custom TLS branch. Exposed for unit tests. + /// + internal static MongoClientSettings CreateClientSettings(MongoUrl url, string connectionString, + MongodbTlsOptions tlsOptions) + { + var settings = MongoClientSettings.FromUrl(url); + + if (tlsOptions is null || tlsOptions.IsEmpty) return settings; + + if (!settings.UseTls) + { + // An explicit "tls=false" is an operator decision and must not be overridden. Without it, + // a configured CA means an encrypted connection is expected even when the connection + // string forgot to append "tls=true". + if (IsTlsExplicitlyDisabled(connectionString)) return settings; + + settings.UseTls = true; + } + + var sslSettings = (settings.SslSettings ?? new SslSettings()).Clone(); + sslSettings.ServerCertificateValidationCallback = MongodbServerCertificateValidator.Create(tlsOptions); + settings.SslSettings = sslSettings; + + return settings; + } + + private static bool IsTlsExplicitlyDisabled(string connectionString) + { + if (string.IsNullOrEmpty(connectionString)) return false; + + var queryIndex = connectionString.IndexOf('?'); + if (queryIndex < 0) return false; + + bool? tlsEnabled = null; + foreach (var pair in connectionString[(queryIndex + 1)..].Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var separatorIndex = pair.IndexOf('='); + var key = (separatorIndex < 0 ? pair : pair[..separatorIndex]).Trim(); + if (!key.Equals("tls", StringComparison.OrdinalIgnoreCase) && + !key.Equals("ssl", StringComparison.OrdinalIgnoreCase)) + continue; + + var value = separatorIndex < 0 + ? string.Empty + : Uri.UnescapeDataString(pair[(separatorIndex + 1)..].Replace("+", "%20")).Trim(); + if (bool.TryParse(value, out var parsed)) tlsEnabled = parsed; + } + + return tlsEnabled == false; + } private readonly record struct Db(string DatabaseName, IMongoClient Client); } -public sealed class MongodbAccess(string? connectionString) : MongodbAccess(connectionString) +public sealed class MongodbAccess(string? connectionString, MongodbTlsOptions tlsOptions = null) + : MongodbAccess(connectionString, tlsOptions) where T : new() { /// @@ -67,4 +140,4 @@ public sealed class MongodbAccess(string? connectionString) : MongodbAccess(c /// public IQueryable MongoQueryable => Database.GetCollection(CollectionName).AsQueryable( new AggregateOptions { AllowDiskUse = true }); -} \ No newline at end of file +} diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbConnectionString.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbConnectionString.cs new file mode 100644 index 00000000..409885e1 --- /dev/null +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbConnectionString.cs @@ -0,0 +1,105 @@ +namespace AgileConfig.Server.Data.Mongodb; + +/// +/// Normalizes a MongoDB connection string before it is handed to the .NET driver. +/// +/// The .NET driver rejects the tlsCAFile / tlsAllowInvalidCertificates / +/// tlsAllowInvalidHostnames options that the MongoDB shell and most other official drivers +/// accept. AgileConfig understands those options itself: they are removed from the connection +/// string and translated into a instead, so the same connection +/// string can be reused across drivers. +/// +/// +internal static class MongodbConnectionString +{ + private const string TlsCaFileKey = "tlscafile"; + private const string SslCaFileKey = "sslcafile"; + private const string TlsAllowInvalidCertificatesKey = "tlsallowinvalidcertificates"; + private const string SslAllowInvalidCertificatesKey = "sslallowinvalidcertificates"; + private const string TlsAllowInvalidHostnamesKey = "tlsallowinvalidhostnames"; + private const string SslAllowInvalidHostnamesKey = "sslallowinvalidhostnames"; + private const string TlsCertificateKeyFileKey = "tlscertificatekeyfile"; + private const string SslCertificateKeyFileKey = "sslcertificatekeyfile"; + + /// + /// Removes the TLS options the .NET driver does not understand and returns them separately. + /// + /// The connection string to pass to the driver, plus the extracted TLS options (or null). + public static NormalizedConnectionString Normalize(string connectionString) + { + if (string.IsNullOrEmpty(connectionString)) + return new NormalizedConnectionString(connectionString, null); + + var queryIndex = connectionString.IndexOf('?'); + if (queryIndex < 0) return new NormalizedConnectionString(connectionString, null); + + var prefix = connectionString[..queryIndex]; + var query = connectionString[(queryIndex + 1)..]; + + var kept = new List(); + string caFile = null; + bool? allowInvalidCertificates = null; + bool? allowInvalidHostnames = null; + var optionsFound = false; + + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var separatorIndex = pair.IndexOf('='); + var key = (separatorIndex < 0 ? pair : pair[..separatorIndex]).Trim().ToLowerInvariant(); + var value = separatorIndex < 0 ? "" : pair[(separatorIndex + 1)..]; + + switch (key) + { + case TlsCaFileKey: + case SslCaFileKey: + caFile = Decode(value); + optionsFound = true; + break; + case TlsAllowInvalidCertificatesKey: + case SslAllowInvalidCertificatesKey: + allowInvalidCertificates = ParseBool(key, value); + optionsFound = true; + break; + case TlsAllowInvalidHostnamesKey: + case SslAllowInvalidHostnamesKey: + allowInvalidHostnames = ParseBool(key, value); + optionsFound = true; + break; + case TlsCertificateKeyFileKey: + case SslCertificateKeyFileKey: + throw new NotSupportedException( + $"The MongoDB connection string option '{key}' (client certificate / mTLS) is not supported by AgileConfig yet. " + + "Remove it and use a server certificate issued by a CA that can be configured with 'db:tls:caFile' instead."); + default: + kept.Add(pair); + break; + } + } + + if (!optionsFound) return new NormalizedConnectionString(connectionString, null); + + var normalized = kept.Count == 0 ? prefix : $"{prefix}?{string.Join('&', kept)}"; + var tlsOptions = MongodbTlsOptions.Create(caFile, null, allowInvalidCertificates, allowInvalidHostnames); + + return new NormalizedConnectionString(normalized, tlsOptions); + } + + private static string Decode(string value) + { + return Uri.UnescapeDataString(value.Replace("+", "%20")); + } + + private static bool ParseBool(string key, string value) + { + var decoded = Decode(value).Trim(); + if (bool.TryParse(decoded, out var parsed)) return parsed; + + throw new InvalidOperationException( + $"The MongoDB connection string option '{key}' must be 'true' or 'false', but its value is '{value}'."); + } +} + +/// +/// Result of . +/// +internal readonly record struct NormalizedConnectionString(string ConnectionString, MongodbTlsOptions TlsOptions); diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs index addd951e..f59f651e 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs @@ -15,16 +15,16 @@ public class MongodbRepository : IRepository private MongodbUow? _mongodbUow; - public MongodbRepository(string? connectionString) + public MongodbRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) { - _access = new MongodbAccess(connectionString); + _access = new MongodbAccess(connectionString, tlsOptions); } [ActivatorUtilitiesConstructor] public MongodbRepository(IConfiguration configuration) { var connectionString = configuration["db:conn"]; - _access = new MongodbAccess(connectionString); + _access = new MongodbAccess(connectionString, MongodbTlsOptions.FromConfiguration(configuration)); } public IUow Uow diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbServerCertificateValidator.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbServerCertificateValidator.cs new file mode 100644 index 00000000..fc9c4863 --- /dev/null +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbServerCertificateValidator.cs @@ -0,0 +1,176 @@ +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; + +namespace AgileConfig.Server.Data.Mongodb; + +/// +/// Validates the certificate presented by a MongoDB server. +/// +/// When or is configured the +/// chain is rebuilt against that private trust store, which is what makes a self signed / internal CA +/// work with the .NET driver. Certificates that the operating system already trusts are still accepted, +/// so a connection string can be switched between a private cluster and a public one without changes. +/// +/// +internal sealed class MongodbServerCertificateValidator +{ + private const string ServerAuthenticationOid = "1.3.6.1.5.5.7.3.1"; + private static readonly string[] PemMarkers = ["-----BEGIN CERTIFICATE-----", "-----BEGIN TRUSTED CERTIFICATE-----"]; + + private readonly MongodbTlsOptions _options; + private readonly Lazy _trustedRoots; + + private MongodbServerCertificateValidator(MongodbTlsOptions options) + { + _options = options; + _trustedRoots = new Lazy(() => LoadTrustedRoots(options)); + } + + private X509Certificate2Collection TrustedRoots => _trustedRoots.Value; + + /// + /// Creates the callback assigned to SslSettings.ServerCertificateValidationCallback. + /// + public static RemoteCertificateValidationCallback Create(MongodbTlsOptions options) + { + var validator = new MongodbServerCertificateValidator(options); + return validator.Validate; + } + + private bool Validate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + // The platform trust store already accepted the certificate; nothing else to check. + if (sslPolicyErrors == SslPolicyErrors.None) return true; + + if (_options.AllowInvalidCertificates) return true; + + if (certificate is null) return false; + + if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) return false; + + if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) + { + var roots = TrustedRoots; + if (roots.Count == 0) return false; + if (!BuildChainWithPrivateTrustStore(certificate, chain, roots)) return false; + } + + return _options.AllowInvalidHostnames || + (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == 0; + } + + private bool BuildChainWithPrivateTrustStore(X509Certificate certificate, X509Chain driverChain, + X509Certificate2Collection roots) + { + var leaf = certificate as X509Certificate2; + var ownsLeaf = false; + if (leaf is null) + { + leaf = X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()); + ownsLeaf = true; + } + + try + { + using var chainToValidate = new X509Chain(); + var policy = chainToValidate.ChainPolicy; + policy.TrustMode = X509ChainTrustMode.CustomRootTrust; + policy.CustomTrustStore.AddRange(roots); + policy.RevocationMode = _options.CheckCertificateRevocation + ? X509RevocationMode.Online + : X509RevocationMode.NoCheck; + policy.RevocationFlag = X509RevocationFlag.ExcludeRoot; + policy.VerificationFlags = X509VerificationFlags.NoFlag; + + // Rebuilding the chain must not relax the platform's purpose check: a certificate issued + // for clientAuth only has to stay rejected for a TLS server endpoint. X509Chain does not + // inherit this from the driver chain, so the serverAuth EKU is applied explicitly. + policy.ApplicationPolicy.Add(new Oid(ServerAuthenticationOid, "Server Authentication")); + + // The driver already collected the intermediates sent by the server; feed them to our chain. + if (driverChain is not null) + foreach (var element in driverChain.ChainElements) + policy.ExtraStore.Add(element.Certificate); + + return chainToValidate.Build(leaf); + } + finally + { + if (ownsLeaf) leaf.Dispose(); + } + } + + private static X509Certificate2Collection LoadTrustedRoots(MongodbTlsOptions options) + { + if (!string.IsNullOrEmpty(options.Ca)) return Parse(options.Ca, "db:tls:ca"); + + if (string.IsNullOrEmpty(options.CaFile)) return []; + + var path = options.CaFile; + if (!Path.IsPathRooted(path)) path = Path.Combine(AppContext.BaseDirectory, path); + + if (!File.Exists(path)) + throw new FileNotFoundException( + $"The MongoDB CA file configured by 'db:tls:caFile' was not found. " + + $"Resolved path: '{path}'. When AgileConfig runs in a container, make sure the certificate is " + + "mounted into the container, for example: -v /host/path/ca.crt:/certs/ca.crt:ro", + path); + + var content = File.ReadAllBytes(path); + if (LooksLikePem(content)) return Parse(Encoding.UTF8.GetString(content), path); + + // DER encoded certificate file. + var collection = new X509Certificate2Collection(); + collection.Add(X509CertificateLoader.LoadCertificate(content)); + return collection; + } + + private static X509Certificate2Collection Parse(string content, string source) + { + // Environment variables can not contain real line breaks, so "\n" is accepted as an escape. + var text = content.Replace("\\r\\n", "\n").Replace("\\n", "\n").Trim(); + var collection = new X509Certificate2Collection(); + + if (PemMarkers.Any(marker => text.Contains(marker, StringComparison.Ordinal))) + { + try + { + collection.ImportFromPem(text); + } + catch (CryptographicException ex) + { + throw new InvalidOperationException( + $"Failed to read the MongoDB CA certificate(s) from '{source}'. The content looks like PEM " + + "but could not be parsed.", ex); + } + + if (collection.Count == 0) + throw new InvalidOperationException( + $"No certificate was found in the MongoDB CA configured by '{source}'."); + + return collection; + } + + // A single line Base64 encoded DER certificate, the easiest form for an environment variable. + try + { + collection.Add(X509CertificateLoader.LoadCertificate(Convert.FromBase64String(text))); + } + catch (FormatException ex) + { + throw new InvalidOperationException( + $"Failed to read the MongoDB CA certificate(s) from '{source}'. Provide PEM text " + + "(-----BEGIN CERTIFICATE-----) or a Base64 encoded DER certificate.", ex); + } + + return collection; + } + + private static bool LooksLikePem(byte[] content) + { + var text = Encoding.UTF8.GetString(content); + return PemMarkers.Any(marker => text.Contains(marker, StringComparison.Ordinal)); + } +} diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbTlsOptions.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbTlsOptions.cs new file mode 100644 index 00000000..1c1ebec4 --- /dev/null +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbTlsOptions.cs @@ -0,0 +1,202 @@ +using System.Text; +using Microsoft.Extensions.Configuration; + +namespace AgileConfig.Server.Data.Mongodb; + +/// +/// TLS settings used when the MongoDB server presents a certificate that is not signed by a +/// publicly trusted CA (for example a private CA deployed together with a replica set). +/// +/// Everything is optional. When no setting is provided the MongoDB driver keeps its default +/// behavior, which means the current deployments are not affected at all. +/// +/// +/// Both db:tls:* and the per environment db:env:{env}:tls:* configuration keys are +/// supported, as well as the tlsCAFile family of connection string options that other +/// MongoDB drivers accept but the .NET driver does not. +/// +/// +public sealed class MongodbTlsOptions +{ + /// + /// Configuration section (relative to db: or db:env:{env}:) that holds the settings. + /// + public const string ConfigSection = "tls"; + + private readonly Raw _raw; + + private MongodbTlsOptions(Raw raw) + { + _raw = raw; + } + + /// + /// Path of a PEM or DER file that contains one or more trusted root (CA) certificates. + /// A relative path is resolved against the application base directory. + /// + public string CaFile => _raw.CaFile; + + /// + /// Inline trusted root (CA) certificate(s). Accepts PEM text, a PEM text whose line breaks were + /// escaped as \n (handy for environment variables), or Base64 encoded DER. + /// + public string Ca => _raw.Ca; + + /// + /// Skip the certificate chain validation completely. Meant for local debugging only. + /// + public bool AllowInvalidCertificates => _raw.AllowInvalidCertificates ?? false; + + /// + /// Skip the host name check while keeping certificate chain validation. + /// + public bool AllowInvalidHostnames => _raw.AllowInvalidHostnames ?? false; + + /// + /// Check certificate revocation for chains built from / . + /// + public bool CheckCertificateRevocation => _raw.CheckCertificateRevocation ?? false; + + /// + /// True when the instance carries no effective setting, i.e. when it can not change the + /// behavior of the MongoDB driver. An explicit false is the default value of every + /// boolean option and does not require the custom TLS branch on its own. + /// + public bool IsEmpty => _raw.IsEmpty; + + /// + /// Reads the TLS settings from configuration. + /// + /// The application configuration. + /// Optional environment name; db:env:{env}:tls:* overrides db:tls:* per key. + /// + /// The settings, or null when no effective setting is configured. Configuration keys that + /// merely repeat a default value (for example allowInvalidHostnames=false in + /// appsettings.json) do not count as an effective setting. + /// + public static MongodbTlsOptions FromConfiguration(IConfiguration configuration, string env = null) + { + if (configuration is null) return null; + + var raw = Read(configuration, $"db:{ConfigSection}"); + if (!string.IsNullOrWhiteSpace(env)) raw = raw.Override(Read(configuration, $"db:env:{env}:{ConfigSection}")); + + return raw.IsEmpty ? null : new MongodbTlsOptions(raw); + } + + /// + /// Merges two settings instances. Values present in win, values that + /// are missing there fall back to . + /// + public static MongodbTlsOptions Merge(MongodbTlsOptions baseline, MongodbTlsOptions overrides) + { + if (baseline is null) return overrides; + if (overrides is null) return baseline; + + var raw = baseline._raw.Override(overrides._raw); + return raw.IsEmpty ? null : new MongodbTlsOptions(raw); + } + + /// + /// Creates an instance from explicit values. Used by tests and by the connection string parser. + /// + /// An explicit false is kept so that it can override a true value coming from a + /// lower precedence source, but the resulting instance is still because + /// it does not enable any custom TLS behavior. + /// + /// + public static MongodbTlsOptions Create( + string caFile = null, + string ca = null, + bool? allowInvalidCertificates = null, + bool? allowInvalidHostnames = null, + bool? checkCertificateRevocation = null) + { + var raw = new Raw(Trim(caFile), Trim(ca), allowInvalidCertificates, allowInvalidHostnames, + checkCertificateRevocation); + return raw.HasAnyValue ? new MongodbTlsOptions(raw) : null; + } + + /// + /// Key used to cache one MongoDB client per connection string + TLS configuration combination. + /// + internal string CacheKey + { + get + { + var caHash = string.IsNullOrEmpty(_raw.Ca) + ? "" + : Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(_raw.Ca))); + return string.Join('|', _raw.CaFile ?? "", caHash, + AllowInvalidCertificates, AllowInvalidHostnames, CheckCertificateRevocation); + } + } + + private static Raw Read(IConfiguration configuration, string section) + { + var caFile = Trim(configuration[$"{section}:caFile"]); + var ca = Trim(configuration[$"{section}:ca"]); + var allowInvalidCertificates = ReadBool(configuration[$"{section}:allowInvalidCertificates"]); + var allowInvalidHostnames = ReadBool(configuration[$"{section}:allowInvalidHostnames"]); + var checkCertificateRevocation = ReadBool(configuration[$"{section}:checkCertificateRevocation"]); + + return new Raw(caFile, ca, allowInvalidCertificates, allowInvalidHostnames, checkCertificateRevocation); + } + + private static string Trim(string value) + { + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } + + private static bool? ReadBool(string value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + + var trimmed = value.Trim(); + if (bool.TryParse(trimmed, out var parsed)) return parsed; + // Common environment variable spellings. + if (trimmed is "1" or "yes" or "on") return true; + if (trimmed is "0" or "no" or "off") return false; + + throw new InvalidOperationException( + $"MongoDB TLS configuration value '{value}' is not a valid boolean. Use true or false."); + } + + /// + /// All explicitly provided values. Keeping them nullable lets an environment specific setting + /// override a single key of the global setting without resetting the others. + /// + private readonly record struct Raw( + string CaFile, + string Ca, + bool? AllowInvalidCertificates, + bool? AllowInvalidHostnames, + bool? CheckCertificateRevocation) + { + /// + /// True when at least one key was provided, even if its value is the default (for example + /// an explicit false). Such a value still has to take part in precedence handling. + /// + public bool HasAnyValue => CaFile is not null || Ca is not null || + AllowInvalidCertificates is not null || AllowInvalidHostnames is not null || + CheckCertificateRevocation is not null; + + /// + /// True when no setting can change the driver behavior: there is no CA to trust and no + /// option is enabled. Explicit false values are deliberately ignored here. + /// + public bool IsEmpty => string.IsNullOrWhiteSpace(CaFile) && string.IsNullOrWhiteSpace(Ca) && + AllowInvalidCertificates is not true && AllowInvalidHostnames is not true && + CheckCertificateRevocation is not true; + + public Raw Override(Raw overrides) + { + return new Raw( + overrides.CaFile ?? CaFile, + overrides.Ca ?? Ca, + overrides.AllowInvalidCertificates ?? AllowInvalidCertificates, + overrides.AllowInvalidHostnames ?? AllowInvalidHostnames, + overrides.CheckCertificateRevocation ?? CheckCertificateRevocation); + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/AppInheritancedRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/AppInheritancedRepository.cs index a28de534..029df936 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/AppInheritancedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/AppInheritancedRepository.cs @@ -2,7 +2,7 @@ public class AppInheritancedRepository : MongodbRepository, IAppInheritancedRepository { - public AppInheritancedRepository(string? connectionString) : base(connectionString) + public AppInheritancedRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/AppRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/AppRepository.cs index 7245f5da..cc5cecc4 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/AppRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/AppRepository.cs @@ -2,7 +2,7 @@ public class AppRepository : MongodbRepository, IAppRepository { - public AppRepository(string? connectionString) : base(connectionString) + public AppRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigPublishedRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigPublishedRepository.cs index 319ea636..85fb7abb 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigPublishedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigPublishedRepository.cs @@ -2,7 +2,8 @@ public class ConfigPublishedRepository : MongodbRepository, IConfigPublishedRepository { - public ConfigPublishedRepository(string? connectionString) : base(connectionString) + public ConfigPublishedRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) + : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigRepository.cs index 10dc2382..33f78ce3 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigRepository.cs @@ -2,7 +2,8 @@ public class ConfigRepository : MongodbRepository, IConfigRepository { - public ConfigRepository(string? connectionString) : base(connectionString) + public ConfigRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) + : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/FunctionRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/FunctionRepository.cs index 49d3ec64..6b1fe807 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/FunctionRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/FunctionRepository.cs @@ -2,7 +2,7 @@ namespace AgileConfig.Server.Data.Repository.Mongodb; public class FunctionRepository : MongodbRepository, IFunctionRepository { - public FunctionRepository(string? connectionString) : base(connectionString) + public FunctionRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryServiceRegister.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryServiceRegister.cs index 709ce0de..0e57fde8 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryServiceRegister.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryServiceRegister.cs @@ -26,29 +26,21 @@ public T GetServiceByEnv(IServiceProvider sp, string env) where T : class var dbConfigInfoFactory = sp.GetRequiredService(); if (typeof(T) == typeof(IUow)) return new MongodbUow() as T; + + var envDbConfig = dbConfigInfoFactory.GetConfigInfo(env); + var tlsOptions = MongodbTlsOptions.FromConfiguration(sp.GetService(), env); + if (typeof(T) == typeof(IConfigPublishedRepository)) - { - var envDbConfig = dbConfigInfoFactory.GetConfigInfo(env); - return new ConfigPublishedRepository(envDbConfig.ConnectionString) as T; - } + return new ConfigPublishedRepository(envDbConfig.ConnectionString, tlsOptions) as T; if (typeof(T) == typeof(IConfigRepository)) - { - var envDbConfig = dbConfigInfoFactory.GetConfigInfo(env); - return new ConfigRepository(envDbConfig.ConnectionString) as T; - } + return new ConfigRepository(envDbConfig.ConnectionString, tlsOptions) as T; if (typeof(T) == typeof(IPublishDetailRepository)) - { - var envDbConfig = dbConfigInfoFactory.GetConfigInfo(env); - return new PublishDetailRepository(envDbConfig.ConnectionString) as T; - } + return new PublishDetailRepository(envDbConfig.ConnectionString, tlsOptions) as T; if (typeof(T) == typeof(IPublishTimelineRepository)) - { - var envDbConfig = dbConfigInfoFactory.GetConfigInfo(env); - return new PublishTimelineRepository(envDbConfig.ConnectionString) as T; - } + return new PublishTimelineRepository(envDbConfig.ConnectionString, tlsOptions) as T; return default; } @@ -63,4 +55,4 @@ public bool IsSuit4Provider(string provider) return false; } -} \ No newline at end of file +} diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/PublishDetailRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/PublishDetailRepository.cs index 0bf3f62c..84f123ff 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/PublishDetailRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/PublishDetailRepository.cs @@ -2,7 +2,8 @@ public class PublishDetailRepository : MongodbRepository, IPublishDetailRepository { - public PublishDetailRepository(string? connectionString) : base(connectionString) + public PublishDetailRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) + : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/PublishTimelineRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/PublishTimelineRepository.cs index 8e0544ad..ba941c84 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/PublishTimelineRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/PublishTimelineRepository.cs @@ -2,7 +2,8 @@ public class PublishTimelineRepository : MongodbRepository, IPublishTimelineRepository { - public PublishTimelineRepository(string? connectionString) : base(connectionString) + public PublishTimelineRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) + : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/RoleDefinitionRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/RoleDefinitionRepository.cs index 99957385..5895aa71 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/RoleDefinitionRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/RoleDefinitionRepository.cs @@ -2,7 +2,7 @@ public class RoleDefinitionRepository : MongodbRepository, IRoleDefinitionRepository { - public RoleDefinitionRepository(string? connectionString) : base(connectionString) + public RoleDefinitionRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/RoleFunctionRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/RoleFunctionRepository.cs index 9aacc6a2..4555c3e6 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/RoleFunctionRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/RoleFunctionRepository.cs @@ -2,7 +2,7 @@ namespace AgileConfig.Server.Data.Repository.Mongodb; public class RoleFunctionRepository : MongodbRepository, IRoleFunctionRepository { - public RoleFunctionRepository(string? connectionString) : base(connectionString) + public RoleFunctionRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/ServerNodeRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/ServerNodeRepository.cs index da19f131..47f0aebc 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/ServerNodeRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/ServerNodeRepository.cs @@ -2,7 +2,7 @@ public class ServerNodeRepository : MongodbRepository, IServerNodeRepository { - public ServerNodeRepository(string? connectionString) : base(connectionString) + public ServerNodeRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/ServiceInfoRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/ServiceInfoRepository.cs index 514f5bb9..b3d76ece 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/ServiceInfoRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/ServiceInfoRepository.cs @@ -2,7 +2,7 @@ public class ServiceInfoRepository : MongodbRepository, IServiceInfoRepository { - public ServiceInfoRepository(string? connectionString) : base(connectionString) + public ServiceInfoRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/SettingRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/SettingRepository.cs index 079a980f..ab4c3aad 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/SettingRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/SettingRepository.cs @@ -2,7 +2,7 @@ public class SettingRepository : MongodbRepository, ISettingRepository { - public SettingRepository(string? connectionString) : base(connectionString) + public SettingRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs index c7140203..f99ea7b4 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs @@ -10,19 +10,22 @@ public class SysInitRepository : ISysInitRepository private readonly string _connectionString = ""; + private readonly MongodbTlsOptions? _tlsOptions; + public SysInitRepository(IConfiguration configuration) { _configuration = configuration; _connectionString = _configuration["db:conn"] ?? ""; + _tlsOptions = MongodbTlsOptions.FromConfiguration(configuration); } - private MongodbAccess _settingAccess => new(_connectionString); - private MongodbAccess _userAccess => new(_connectionString); - private MongodbAccess _userRoleAccess => new(_connectionString); - private MongodbAccess _roleAccess => new(_connectionString); - private MongodbAccess _appAccess => new(_connectionString); - private MongodbAccess _functionAccess => new(_connectionString); - private MongodbAccess _roleFunctionAccess => new(_connectionString); + private MongodbAccess _settingAccess => new(_connectionString, _tlsOptions); + private MongodbAccess _userAccess => new(_connectionString, _tlsOptions); + private MongodbAccess _userRoleAccess => new(_connectionString, _tlsOptions); + private MongodbAccess _roleAccess => new(_connectionString, _tlsOptions); + private MongodbAccess _appAccess => new(_connectionString, _tlsOptions); + private MongodbAccess _functionAccess => new(_connectionString, _tlsOptions); + private MongodbAccess _roleFunctionAccess => new(_connectionString, _tlsOptions); public string? GetDefaultEnvironmentFromDb() { diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs index 453f6108..c6eb35ab 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs @@ -2,7 +2,7 @@ public class SysLogRepository : MongodbRepository, ISysLogRepository { - public SysLogRepository(string? connectionString) : base(connectionString) + public SysLogRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/UserAppAuthRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/UserAppAuthRepository.cs index 783415f8..ba944ecf 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/UserAppAuthRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/UserAppAuthRepository.cs @@ -2,7 +2,7 @@ public class UserAppAuthRepository : MongodbRepository, IUserAppAuthRepository { - public UserAppAuthRepository(string? connectionString) : base(connectionString) + public UserAppAuthRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/UserRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/UserRepository.cs index 72a105d8..b60e85cb 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/UserRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/UserRepository.cs @@ -2,7 +2,7 @@ public class UserRepository : MongodbRepository, IUserRepository { - public UserRepository(string? connectionString) : base(connectionString) + public UserRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/UserRoleRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/UserRoleRepository.cs index 744c097c..ef2455b5 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/UserRoleRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/UserRoleRepository.cs @@ -2,7 +2,7 @@ public class UserRoleRepository : MongodbRepository, IUserRoleRepository { - public UserRoleRepository(string? connectionString) : base(connectionString) + public UserRoleRepository(string? connectionString, MongodbTlsOptions tlsOptions = null) : base(connectionString, tlsOptions) { } diff --git a/test/AgileConfig.Server.Data.MongodbTests/AgileConfig.Server.Data.MongodbTests.csproj b/test/AgileConfig.Server.Data.MongodbTests/AgileConfig.Server.Data.MongodbTests.csproj new file mode 100644 index 00000000..7537298a --- /dev/null +++ b/test/AgileConfig.Server.Data.MongodbTests/AgileConfig.Server.Data.MongodbTests.csproj @@ -0,0 +1,28 @@ + + + + net10.0 + enable + disable + + false + true + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + diff --git a/test/AgileConfig.Server.Data.MongodbTests/MongodbAccessTests.cs b/test/AgileConfig.Server.Data.MongodbTests/MongodbAccessTests.cs new file mode 100644 index 00000000..2b98e83c --- /dev/null +++ b/test/AgileConfig.Server.Data.MongodbTests/MongodbAccessTests.cs @@ -0,0 +1,99 @@ +using AgileConfig.Server.Data.Mongodb; +using MongoDB.Driver; + +namespace AgileConfig.Server.Data.MongodbTests; + +[TestClass] +public class MongodbAccessTests +{ + private const string PlainConnectionString = "mongodb://localhost:27017/AgileConfig"; + + private static MongoClientSettings BuildSettings(string connectionString, MongodbTlsOptions tlsOptions) + { + var normalized = MongodbConnectionString.Normalize(connectionString); + var effectiveTlsOptions = MongodbTlsOptions.Merge(tlsOptions, normalized.TlsOptions); + + return MongodbAccess.CreateClientSettings(MongoUrl.Create(normalized.ConnectionString), + normalized.ConnectionString, effectiveTlsOptions); + } + + [TestMethod] + public void DefaultAppSettings_KeepTlsOff_ForAPlainConnectionString() + { + var tlsOptions = MongodbTlsOptions.FromConfiguration(TestConfiguration.LoadDefaultAppSettings()); + Assert.IsNull(tlsOptions); + + var settings = BuildSettings(PlainConnectionString, tlsOptions); + + Assert.IsFalse(settings.UseTls); + Assert.IsNull(settings.SslSettings?.ServerCertificateValidationCallback); + } + + [TestMethod] + public void DefaultAppSettings_DoNotOverrideExplicitTlsFalse() + { + var tlsOptions = MongodbTlsOptions.FromConfiguration(TestConfiguration.LoadDefaultAppSettings()); + + var settings = BuildSettings($"{PlainConnectionString}?tls=false", tlsOptions); + + Assert.IsFalse(settings.UseTls); + Assert.IsNull(settings.SslSettings?.ServerCertificateValidationCallback); + } + + [TestMethod] + public void ExplicitTlsFalse_IsRespected_EvenWhenACaIsConfigured() + { + var tlsOptions = MongodbTlsOptions.Create(ca: "not-used-while-tls-is-disabled"); + + var settings = BuildSettings($"{PlainConnectionString}?tls=false", tlsOptions); + + Assert.IsFalse(settings.UseTls); + Assert.IsNull(settings.SslSettings?.ServerCertificateValidationCallback); + } + + [TestMethod] + public void ExplicitLegacySslFalse_IsRespected_EvenWhenACaIsConfigured() + { + var tlsOptions = MongodbTlsOptions.Create(ca: "not-used-while-tls-is-disabled"); + + var settings = BuildSettings($"{PlainConnectionString}?ssl=false", tlsOptions); + + Assert.IsFalse(settings.UseTls); + } + + [TestMethod] + public void ConfiguredCa_TurnsTlsOn_WhenTheConnectionStringDoesNotMentionIt() + { + var tlsOptions = MongodbTlsOptions.Create(ca: "not-loaded-until-the-callback-runs"); + + var settings = BuildSettings(PlainConnectionString, tlsOptions); + + Assert.IsTrue(settings.UseTls); + Assert.IsNotNull(settings.SslSettings?.ServerCertificateValidationCallback); + } + + [TestMethod] + public void ExplicitTlsTrue_KeepsTlsOn_AndInstallsTheCustomValidator() + { + var tlsOptions = MongodbTlsOptions.Create(ca: "not-loaded-until-the-callback-runs"); + + var settings = BuildSettings($"{PlainConnectionString}?tls=true", tlsOptions); + + Assert.IsTrue(settings.UseTls); + Assert.IsNotNull(settings.SslSettings?.ServerCertificateValidationCallback); + } + + [TestMethod] + public void DefaultOnlyFalseOptions_DoNotInstallTheCustomValidator() + { + // An explicit false can arrive from an environment override even when FromConfiguration + // already collapsed the default configuration to null. + var tlsOptions = MongodbTlsOptions.Create(allowInvalidHostnames: false, checkCertificateRevocation: false); + Assert.IsTrue(tlsOptions.IsEmpty); + + var settings = BuildSettings(PlainConnectionString, tlsOptions); + + Assert.IsFalse(settings.UseTls); + Assert.IsNull(settings.SslSettings?.ServerCertificateValidationCallback); + } +} diff --git a/test/AgileConfig.Server.Data.MongodbTests/MongodbConnectionStringTests.cs b/test/AgileConfig.Server.Data.MongodbTests/MongodbConnectionStringTests.cs new file mode 100644 index 00000000..08a9eee2 --- /dev/null +++ b/test/AgileConfig.Server.Data.MongodbTests/MongodbConnectionStringTests.cs @@ -0,0 +1,118 @@ +using AgileConfig.Server.Data.Mongodb; + +namespace AgileConfig.Server.Data.MongodbTests; + +[TestClass] +public class MongodbConnectionStringTests +{ + [TestMethod] + public void Normalize_ExtractsTlsCaFile() + { + var normalized = MongodbConnectionString.Normalize( + "mongodb://u:p@h1:27017,h2:27017/db?replicaSet=rs0&authSource=admin&tls=true&tlsCAFile=%2Fcerts%2Fca.crt"); + + Assert.AreEqual("mongodb://u:p@h1:27017,h2:27017/db?replicaSet=rs0&authSource=admin&tls=true", + normalized.ConnectionString); + Assert.IsNotNull(normalized.TlsOptions); + Assert.AreEqual("/certs/ca.crt", normalized.TlsOptions.CaFile); + } + + [TestMethod] + public void Normalize_AcceptsTheLegacySslPrefix() + { + var normalized = MongodbConnectionString.Normalize( + "mongodb://localhost:27017/db?ssl=true&sslCAFile=/tmp/ca.crt&sslAllowInvalidHostnames=true"); + + Assert.AreEqual("mongodb://localhost:27017/db?ssl=true", normalized.ConnectionString); + Assert.IsNotNull(normalized.TlsOptions); + Assert.AreEqual("/tmp/ca.crt", normalized.TlsOptions.CaFile); + Assert.IsTrue(normalized.TlsOptions.AllowInvalidHostnames); + } + + [TestMethod] + public void Normalize_ExtractsAllowInvalidCertificates() + { + var normalized = MongodbConnectionString.Normalize( + "mongodb://localhost:27017/db?tls=true&tlsAllowInvalidCertificates=true"); + + Assert.AreEqual("mongodb://localhost:27017/db?tls=true", normalized.ConnectionString); + Assert.IsNotNull(normalized.TlsOptions); + Assert.IsTrue(normalized.TlsOptions.AllowInvalidCertificates); + } + + [TestMethod] + public void Normalize_KeepsOptionsTheDriverUnderstands() + { + var normalized = MongodbConnectionString.Normalize( + "mongodb://localhost:27017/db?tls=true&tlsInsecure=true&tlsDisableCertificateRevocationCheck=true"); + + Assert.AreEqual( + "mongodb://localhost:27017/db?tls=true&tlsInsecure=true&tlsDisableCertificateRevocationCheck=true", + normalized.ConnectionString); + Assert.IsNull(normalized.TlsOptions); + } + + [TestMethod] + public void Normalize_ReturnsOriginalString_WhenThereIsNoQuery() + { + var normalized = MongodbConnectionString.Normalize("mongodb://localhost:27017/db"); + + Assert.AreEqual("mongodb://localhost:27017/db", normalized.ConnectionString); + Assert.IsNull(normalized.TlsOptions); + } + + [TestMethod] + public void Normalize_ReturnsOriginalString_WhenNoTlsOptionIsPresent() + { + const string connectionString = "mongodb://localhost:27017/db?replicaSet=rs0"; + var normalized = MongodbConnectionString.Normalize(connectionString); + + Assert.AreEqual(connectionString, normalized.ConnectionString); + Assert.IsNull(normalized.TlsOptions); + } + + [TestMethod] + public void Normalize_RemovesTheQuestionMark_WhenEveryOptionIsExtracted() + { + var normalized = MongodbConnectionString.Normalize( + "mongodb://localhost:27017/db?tlsCAFile=/tmp/ca.crt"); + + Assert.AreEqual("mongodb://localhost:27017/db", normalized.ConnectionString); + Assert.IsNotNull(normalized.TlsOptions); + } + + [TestMethod] + public void Normalize_IsCaseInsensitive() + { + var normalized = MongodbConnectionString.Normalize( + "mongodb://localhost:27017/db?TLS=true&TLSCAFILE=/tmp/ca.crt"); + + Assert.AreEqual("mongodb://localhost:27017/db?TLS=true", normalized.ConnectionString); + Assert.AreEqual("/tmp/ca.crt", normalized.TlsOptions.CaFile); + } + + [TestMethod] + public void Normalize_Throws_ForClientCertificateOption() + { + var exception = Assert.Throws(() => + MongodbConnectionString.Normalize( + "mongodb://localhost:27017/db?tls=true&tlsCertificateKeyFile=/tmp/client.pem")); + + StringAssert.Contains(exception.Message, "mTLS"); + } + + [TestMethod] + public void Normalize_Throws_ForInvalidBooleanValue() + { + Assert.Throws(() => + MongodbConnectionString.Normalize( + "mongodb://localhost:27017/db?tls=true&tlsAllowInvalidHostnames=maybe")); + } + + [TestMethod] + public void Normalize_HandlesNullAndEmptyInput() + { + Assert.IsNull(MongodbConnectionString.Normalize(null).ConnectionString); + Assert.AreEqual(string.Empty, MongodbConnectionString.Normalize(string.Empty).ConnectionString); + } +} diff --git a/test/AgileConfig.Server.Data.MongodbTests/MongodbServerCertificateValidatorTests.cs b/test/AgileConfig.Server.Data.MongodbTests/MongodbServerCertificateValidatorTests.cs new file mode 100644 index 00000000..a538b3b3 --- /dev/null +++ b/test/AgileConfig.Server.Data.MongodbTests/MongodbServerCertificateValidatorTests.cs @@ -0,0 +1,229 @@ +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using AgileConfig.Server.Data.Mongodb; + +namespace AgileConfig.Server.Data.MongodbTests; + +[TestClass] +public class MongodbServerCertificateValidatorTests +{ + private const string NodeHostName = "mdb1.dpangzi.com"; + private const string ServerAuthenticationOid = "1.3.6.1.5.5.7.3.1"; + private const string ClientAuthenticationOid = "1.3.6.1.5.5.7.3.2"; + + private static (X509Certificate2 Ca, X509Certificate2 Leaf) CreateCaAndLeaf(string dnsName, + params string[] enhancedKeyUsages) + { + // No explicit EKU means a normal TLS server certificate. + if (enhancedKeyUsages.Length == 0) enhancedKeyUsages = [ServerAuthenticationOid]; + + using var caKey = RSA.Create(2048); + var caRequest = new CertificateRequest("CN=AgileConfig Test Root CA", caKey, + HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + caRequest.CertificateExtensions.Add( + new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); + caRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(caRequest.PublicKey, false)); + var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); + + using var leafKey = RSA.Create(2048); + var leafRequest = new CertificateRequest($"CN={dnsName}", leafKey, HashAlgorithmName.SHA256, + RSASignaturePadding.Pkcs1); + leafRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); + leafRequest.CertificateExtensions.Add( + new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, false)); + var usages = new OidCollection(); + foreach (var oid in enhancedKeyUsages) usages.Add(new Oid(oid)); + leafRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(usages, false)); + var subjectAlternativeName = new SubjectAlternativeNameBuilder(); + subjectAlternativeName.AddDnsName(dnsName); + leafRequest.CertificateExtensions.Add(subjectAlternativeName.Build()); + + var serialNumber = new byte[8]; + RandomNumberGenerator.Fill(serialNumber); + var leaf = leafRequest.Create(ca, DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddMonths(6), + serialNumber); + + return (ca, leaf); + } + + [TestMethod] + public void Accepts_CertificateSignedByTheConfiguredCa() + { + var (ca, leaf) = CreateCaAndLeaf(NodeHostName); + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(ca: ca.ExportCertificatePem())); + + Assert.IsTrue(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [TestMethod] + public void Rejects_ServerCertificateThatOnlyAllowsClientAuthentication() + { + // Same private CA, matching host name, but the EKU only permits clientAuth. The platform + // would report NotValidForUsage for a TLS server, so the rebuilt chain must do the same. + var (ca, leaf) = CreateCaAndLeaf(NodeHostName, ClientAuthenticationOid); + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(ca: ca.ExportCertificatePem())); + + Assert.IsFalse(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [TestMethod] + public void Accepts_ServerCertificateThatAlsoAllowsClientAuthentication() + { + var (ca, leaf) = CreateCaAndLeaf(NodeHostName, ServerAuthenticationOid, ClientAuthenticationOid); + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(ca: ca.ExportCertificatePem())); + + Assert.IsTrue(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [TestMethod] + public void Rejects_CertificateSignedByAnotherCa() + { + var (_, leaf) = CreateCaAndLeaf(NodeHostName); + var (otherCa, _) = CreateCaAndLeaf(NodeHostName); + var callback = + MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(ca: otherCa.ExportCertificatePem())); + + Assert.IsFalse(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [TestMethod] + public void Rejects_HostNameMismatch() + { + var (ca, leaf) = CreateCaAndLeaf(NodeHostName); + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(ca: ca.ExportCertificatePem())); + + var errors = SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch; + + Assert.IsFalse(callback(null, leaf, null, errors)); + } + + [TestMethod] + public void Accepts_HostNameMismatch_WhenAllowInvalidHostnamesIsEnabled() + { + var (ca, leaf) = CreateCaAndLeaf(NodeHostName); + var callback = MongodbServerCertificateValidator.Create( + MongodbTlsOptions.Create(ca: ca.ExportCertificatePem(), allowInvalidHostnames: true)); + + var errors = SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch; + + Assert.IsTrue(callback(null, leaf, null, errors)); + } + + [TestMethod] + public void Accepts_Anything_WhenThePlatformAlreadyTrustsTheCertificate() + { + var (_, leaf) = CreateCaAndLeaf(NodeHostName); + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(caFile: "/does/not/matter")); + + Assert.IsTrue(callback(null, leaf, null, SslPolicyErrors.None)); + } + + [TestMethod] + public void Accepts_Anything_WhenAllowInvalidCertificatesIsEnabled() + { + var (_, leaf) = CreateCaAndLeaf(NodeHostName); + var callback = MongodbServerCertificateValidator.Create( + MongodbTlsOptions.Create(allowInvalidCertificates: true)); + + Assert.IsTrue(callback(null, leaf, null, + SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch)); + } + + [TestMethod] + public void Rejects_ChainErrors_WhenNoCaIsConfigured() + { + var (_, leaf) = CreateCaAndLeaf(NodeHostName); + var callback = MongodbServerCertificateValidator.Create( + MongodbTlsOptions.Create(allowInvalidHostnames: true)); + + Assert.IsFalse(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [TestMethod] + public void Rejects_WhenNoCertificateWasPresented() + { + var (ca, _) = CreateCaAndLeaf(NodeHostName); + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(ca: ca.ExportCertificatePem())); + + Assert.IsFalse(callback(null, null, null, SslPolicyErrors.RemoteCertificateNotAvailable)); + } + + [TestMethod] + public void Accepts_InlinePem_WithEscapedNewLines() + { + var (ca, leaf) = CreateCaAndLeaf(NodeHostName); + var escaped = ca.ExportCertificatePem().Replace("\n", "\\n"); + + // This is the form that fits into a docker environment variable. + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(ca: escaped)); + + Assert.IsTrue(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [TestMethod] + public void Accepts_CaFile_OnDisk() + { + var (ca, leaf) = CreateCaAndLeaf(NodeHostName); + var path = Path.Combine(Path.GetTempPath(), $"agileconfig-ca-{Guid.NewGuid():N}.crt"); + + try + { + File.WriteAllText(path, ca.ExportCertificatePem()); + + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(caFile: path)); + + Assert.IsTrue(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } + finally + { + File.Delete(path); + } + } + + [TestMethod] + public void Accepts_CaFile_WithRelativePath() + { + var (ca, leaf) = CreateCaAndLeaf(NodeHostName); + var fileName = $"agileconfig-ca-{Guid.NewGuid():N}.crt"; + var path = Path.Combine(AppContext.BaseDirectory, fileName); + + try + { + File.WriteAllText(path, ca.ExportCertificatePem()); + + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(caFile: fileName)); + + Assert.IsTrue(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } + finally + { + File.Delete(path); + } + } + + [TestMethod] + public void Throws_WithMountHint_WhenCaFileDoesNotExist() + { + var (_, leaf) = CreateCaAndLeaf(NodeHostName); + var callback = MongodbServerCertificateValidator.Create( + MongodbTlsOptions.Create(caFile: "/certs/missing-ca.crt")); + + var exception = Assert.Throws(() => + callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + + StringAssert.Contains(exception.Message, "mounted"); + } + + [TestMethod] + public void Accepts_Base64EncodedDerCa() + { + var (ca, leaf) = CreateCaAndLeaf(NodeHostName); + var base64 = Convert.ToBase64String(ca.Export(X509ContentType.Cert)); + + var callback = MongodbServerCertificateValidator.Create(MongodbTlsOptions.Create(ca: base64)); + + Assert.IsTrue(callback(null, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors)); + } +} diff --git a/test/AgileConfig.Server.Data.MongodbTests/MongodbTlsOptionsTests.cs b/test/AgileConfig.Server.Data.MongodbTests/MongodbTlsOptionsTests.cs new file mode 100644 index 00000000..45725015 --- /dev/null +++ b/test/AgileConfig.Server.Data.MongodbTests/MongodbTlsOptionsTests.cs @@ -0,0 +1,222 @@ +using AgileConfig.Server.Data.Mongodb; +using Microsoft.Extensions.Configuration; + +namespace AgileConfig.Server.Data.MongodbTests; + +[TestClass] +public class MongodbTlsOptionsTests +{ + private static IConfiguration BuildConfiguration(Dictionary values) + { + return new ConfigurationBuilder().AddInMemoryCollection(values).Build(); + } + + [TestMethod] + public void FromConfiguration_ReturnsNull_WhenNothingIsConfigured() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:provider"] = "mongodb", + ["db:conn"] = "mongodb://localhost:27017" + }); + + Assert.IsNull(MongodbTlsOptions.FromConfiguration(configuration)); + Assert.IsNull(MongodbTlsOptions.FromConfiguration(configuration, "TEST")); + } + + [TestMethod] + public void FromConfiguration_ReturnsNull_WhenConfigurationIsNull() + { + Assert.IsNull(MongodbTlsOptions.FromConfiguration(null)); + } + + [TestMethod] + public void FromConfiguration_DefaultAppSettings_DoesNotRequireCustomTls() + { + var configuration = TestConfiguration.LoadDefaultAppSettings(); + + // The shipped appsettings.json documents the keys with their default values (false / empty). + // Those defaults must not be mistaken for "TLS was configured". + Assert.IsNull(MongodbTlsOptions.FromConfiguration(configuration)); + Assert.IsNull(MongodbTlsOptions.FromConfiguration(configuration, "TEST")); + Assert.IsNull(MongodbTlsOptions.FromConfiguration(configuration, "PROD")); + } + + [TestMethod] + public void FromConfiguration_ExplicitFalseValues_AreTreatedAsDefault() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:tls:caFile"] = "", + ["db:tls:ca"] = "", + ["db:tls:allowInvalidCertificates"] = "false", + ["db:tls:allowInvalidHostnames"] = "false", + ["db:tls:checkCertificateRevocation"] = "false" + }); + + Assert.IsNull(MongodbTlsOptions.FromConfiguration(configuration)); + } + + [TestMethod] + public void FromConfiguration_EnvironmentFalse_DisablesGlobalTrue() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:tls:allowInvalidHostnames"] = "true", + ["db:env:TEST:tls:allowInvalidHostnames"] = "false" + }); + + Assert.IsNull(MongodbTlsOptions.FromConfiguration(configuration, "TEST")); + } + + [TestMethod] + public void FromConfiguration_ReadsGlobalSettings() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:tls:caFile"] = "/certs/ca.crt", + ["db:tls:allowInvalidHostnames"] = "true", + ["db:tls:checkCertificateRevocation"] = "false" + }); + + var options = MongodbTlsOptions.FromConfiguration(configuration); + + Assert.IsNotNull(options); + Assert.AreEqual("/certs/ca.crt", options.CaFile); + Assert.IsNull(options.Ca); + Assert.IsTrue(options.AllowInvalidHostnames); + Assert.IsFalse(options.AllowInvalidCertificates); + Assert.IsFalse(options.CheckCertificateRevocation); + } + + [TestMethod] + public void FromConfiguration_ReadsInlineCa() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:tls:ca"] = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----" + }); + + var options = MongodbTlsOptions.FromConfiguration(configuration); + + Assert.IsNotNull(options); + StringAssert.Contains(options.Ca, "BEGIN CERTIFICATE"); + } + + [TestMethod] + public void FromConfiguration_EnvironmentSpecificSettingOverridesOnlyThatKey() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:tls:caFile"] = "/certs/ca.crt", + ["db:tls:allowInvalidHostnames"] = "false", + ["db:env:TEST:tls:allowInvalidHostnames"] = "true" + }); + + var options = MongodbTlsOptions.FromConfiguration(configuration, "TEST"); + + Assert.IsNotNull(options); + Assert.AreEqual("/certs/ca.crt", options.CaFile); + Assert.IsTrue(options.AllowInvalidHostnames); + } + + [TestMethod] + public void FromConfiguration_EnvironmentWithoutOwnSection_KeepsGlobalSettings() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:tls:caFile"] = "/certs/ca.crt" + }); + + var options = MongodbTlsOptions.FromConfiguration(configuration, "PROD"); + + Assert.IsNotNull(options); + Assert.AreEqual("/certs/ca.crt", options.CaFile); + } + + [TestMethod] + public void FromConfiguration_SupportsYesNoAndOneZero() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:tls:allowInvalidCertificates"] = "yes", + ["db:tls:allowInvalidHostnames"] = "0" + }); + + var options = MongodbTlsOptions.FromConfiguration(configuration); + + Assert.IsNotNull(options); + Assert.IsTrue(options.AllowInvalidCertificates); + Assert.IsFalse(options.AllowInvalidHostnames); + } + + [TestMethod] + public void FromConfiguration_Throws_ForInvalidBoolean() + { + var configuration = BuildConfiguration(new Dictionary + { + ["db:tls:allowInvalidHostnames"] = "maybe" + }); + + Assert.Throws(() => MongodbTlsOptions.FromConfiguration(configuration)); + } + + [TestMethod] + public void Merge_OverridesOnlyProvidedValues() + { + var baseline = MongodbTlsOptions.Create(caFile: "/certs/ca.crt", allowInvalidHostnames: false); + var overrides = MongodbTlsOptions.Create(allowInvalidHostnames: true); + + var merged = MongodbTlsOptions.Merge(baseline, overrides); + + Assert.IsNotNull(merged); + Assert.AreEqual("/certs/ca.crt", merged.CaFile); + Assert.IsTrue(merged.AllowInvalidHostnames); + } + + [TestMethod] + public void Merge_ReturnsTheOtherSide_WhenOneSideIsNull() + { + var baseline = MongodbTlsOptions.Create(caFile: "/certs/ca.crt"); + + Assert.AreSame(baseline, MongodbTlsOptions.Merge(baseline, null)); + Assert.AreSame(baseline, MongodbTlsOptions.Merge(null, baseline)); + Assert.IsNull(MongodbTlsOptions.Merge(null, null)); + } + + [TestMethod] + public void Merge_ExplicitFalseOverridesBaselineTrue() + { + var baseline = MongodbTlsOptions.Create(allowInvalidHostnames: true); + var overrides = MongodbTlsOptions.Create(allowInvalidHostnames: false); + + Assert.IsNull(MongodbTlsOptions.Merge(baseline, overrides)); + } + + [TestMethod] + public void Create_ExplicitFalse_IsKeptForPrecedenceButIsEmpty() + { + var options = MongodbTlsOptions.Create(allowInvalidHostnames: false); + + Assert.IsNotNull(options); + Assert.IsTrue(options.IsEmpty); + } + + [TestMethod] + public void Create_ReturnsNull_WhenEverythingIsEmpty() + { + Assert.IsNull(MongodbTlsOptions.Create()); + Assert.IsNull(MongodbTlsOptions.Create("", " ")); + } + + [TestMethod] + public void CacheKey_IsStable_ForEquivalentSettings() + { + var first = MongodbTlsOptions.Create(caFile: "/certs/ca.crt", allowInvalidHostnames: true); + var second = MongodbTlsOptions.Create(caFile: "/certs/ca.crt", allowInvalidHostnames: true); + var different = MongodbTlsOptions.Create(caFile: "/certs/other.crt", allowInvalidHostnames: true); + + Assert.AreEqual(first.CacheKey, second.CacheKey); + Assert.AreNotEqual(first.CacheKey, different.CacheKey); + } +} diff --git a/test/AgileConfig.Server.Data.MongodbTests/TestConfiguration.cs b/test/AgileConfig.Server.Data.MongodbTests/TestConfiguration.cs new file mode 100644 index 00000000..5d59462f --- /dev/null +++ b/test/AgileConfig.Server.Data.MongodbTests/TestConfiguration.cs @@ -0,0 +1,33 @@ +using Microsoft.Extensions.Configuration; + +namespace AgileConfig.Server.Data.MongodbTests; + +internal static class TestConfiguration +{ + private const string DefaultAppSettingsRelativePath = "src/AgileConfig.Server.Apisite/appsettings.json"; + + /// + /// Loads the real appsettings.json shipped with the API site, including its commented defaults, + /// so tests can prove that the default configuration does not change the driver behavior. + /// + public static IConfiguration LoadDefaultAppSettings() + { + return new ConfigurationBuilder() + .AddJsonFile(FindRepositoryFile(DefaultAppSettingsRelativePath), optional: false, reloadOnChange: false) + .Build(); + } + + private static string FindRepositoryFile(string relativePath) + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null) + { + var candidate = Path.Combine(directory.FullName, relativePath); + if (File.Exists(candidate)) return candidate; + directory = directory.Parent; + } + + Assert.Fail($"Could not locate '{relativePath}' from '{AppContext.BaseDirectory}'."); + return null; + } +}