Fix all baseline code-review findings across the six shared libraries
Resolves the 35 findings from the 2026-06-01 baseline (commit 26ba1c7),
test-first for every behavioral change. +51 tests (331 -> 382 passing, 0 failed).
- Telemetry-001 (HIGH): RedactionEnricher now honours property removal, so a
redactor that drops a key actually scrubs the secret from the event.
- Auth: LDAP validator ValidateOnStart; API-key verify no longer fails on a
best-effort MarkUsed write or a corrupt scopes column (fail-closed); LDAP cert
validation hook; KeyPrefix persistence aligned; README algorithm corrected.
- Health: Akka checks return Degraded (not throw) when the cluster isn't up yet;
GrpcDependencyHealthCheck catch-all; null 'description' rendered; composite
endpoint builder; XML docs shipped.
- Audit: CompositeAuditWriter no longer re-throws OperationCanceledException;
TruncatingAuditRedactor over-redact scrubs Target + safe negative max; options
record; XML docs shipped.
- Configuration: TryAddEnumerable idempotent registration; consistent port
quoting; strict invariant port parsing; XML docs + README packaged.
- Theme: mobile toggle is now CSS-only (no Bootstrap JS); token/CSS hygiene;
XML docs on the public parameter surface.
Shared-contract/spec docs updated where the code was the source of truth
(observability service.instance.id, MapZbMetrics, redactor reach). All changes
additive/back-compatible at v0.1.0. code-reviews bookkeeping follows separately.
This commit is contained in:
@@ -10,8 +10,8 @@ Authentication and authorisation libraries for the **ZB.MOM.WW SCADA family** (O
|
||||
|---|---|---|
|
||||
| `ZB.MOM.WW.Auth.Abstractions` | Auth contracts, canonical role constants, and shared types (`LdapOptions`, `LdapAuthResult`, `ILdapAuthService`, `IApiKeyStore`). No runtime dependencies beyond the BCL. | — |
|
||||
| `ZB.MOM.WW.Auth.Ldap` | LDAP authentication service: bind-then-search-then-bind against GLAuth or Active Directory; RFC 4514-aware group extraction; fail-closed. | `Abstractions`, `Novell.Directory.Ldap.NETStandard` |
|
||||
| `ZB.MOM.WW.Auth.ApiKeys` | SQLite-backed API-key store with pepper-based PBKDF2 hashing, rotation, and audit log. Includes a `MigrationHostedService` that runs schema migrations on startup. | `Abstractions`, `Microsoft.Data.Sqlite` |
|
||||
| `ZB.MOM.WW.Auth.AspNetCore` | ASP.NET Core DI helpers (`AddZbAuth`), cookie defaults, claim-type constants, and `LdapOptionsValidator` registration. Wires together Ldap + ApiKeys + cookie middleware. | `Abstractions`, `Ldap`, `ApiKeys`, `Microsoft.AspNetCore.App` |
|
||||
| `ZB.MOM.WW.Auth.ApiKeys` | SQLite-backed API-key store with **pepper-keyed HMAC-SHA256** secret hashing, rotation, and audit log. DI wiring is `AddZbApiKeyAuth`; an opt-in `MigrationHostedService` runs schema migrations on startup. | `Abstractions`, `Microsoft.Data.Sqlite` |
|
||||
| `ZB.MOM.WW.Auth.AspNetCore` | ASP.NET Core wiring for the **LDAP** provider only: `AddZbLdapAuth` (binds + start-time-validates `LdapOptions`, registers `ILdapAuthService`), plus `ZbCookieDefaults.Apply` (hardened cookie helper the consumer calls itself) and `ZbClaimTypes` constants. It does **not** wire API keys or cookie middleware — API-key DI is `AddZbApiKeyAuth` in the `ApiKeys` package. | `Abstractions`, `Ldap`, `Microsoft.AspNetCore.App` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Net.Security;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
public enum LdapTransport { Ldaps, StartTls, None }
|
||||
@@ -16,6 +18,16 @@ public sealed record LdapOptions
|
||||
public string DisplayNameAttribute { get; init; } = "cn";
|
||||
public string GroupAttribute { get; init; } = "memberOf";
|
||||
public int ConnectionTimeoutMs { get; init; } = 10_000;
|
||||
|
||||
/// <summary>
|
||||
/// Optional hook to harden (or, in dev, relax) TLS server-certificate validation for the
|
||||
/// <see cref="LdapTransport.Ldaps"/> / <see cref="LdapTransport.StartTls"/> transports. When
|
||||
/// <see langword="null"/> (the default) the LDAP client validates the server certificate against
|
||||
/// the OS trust store — it does <em>not</em> blind-accept. Supply a callback to pin a CA, validate
|
||||
/// the SAN against <see cref="Server"/>, or otherwise tighten validation. This is a code-only seam
|
||||
/// (not bound from configuration) and takes precedence over <see cref="AllowInsecure"/>.
|
||||
/// </summary>
|
||||
public RemoteCertificateValidationCallback? ServerCertificateValidationCallback { get; init; }
|
||||
}
|
||||
|
||||
public enum LdapAuthFailure { BadCredentials, UserNotFound, AmbiguousUser, GroupLookupFailed, ServiceAccountBindFailed, Disabled }
|
||||
|
||||
@@ -101,7 +101,10 @@ public sealed class ApiKeyAdminCommands
|
||||
|
||||
var record = new ApiKeyRecord(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: $"{_options.TokenPrefix}_{keyId}",
|
||||
// KeyPrefix is the bare token prefix (e.g. "mxgw"), NOT prefix_keyId — the key id is
|
||||
// already its own column. Embedding it here produced a self-referential value that
|
||||
// confused admin tooling and disagreed with the read/test paths (see Auth-005).
|
||||
KeyPrefix: _options.TokenPrefix,
|
||||
SecretHash: secretHash,
|
||||
DisplayName: displayName,
|
||||
Scopes: scopes,
|
||||
|
||||
@@ -62,8 +62,24 @@ public sealed class ApiKeyVerifier(
|
||||
return Fail(ApiKeyFailure.SecretMismatch);
|
||||
}
|
||||
|
||||
// 6. Record successful use, then return the identity (no secret/hash/pepper included).
|
||||
await store.MarkUsedAsync(record.KeyId, _timeProvider.GetUtcNow(), ct).ConfigureAwait(false);
|
||||
// 6. The authentication decision is already made (line 60). Recording last-used is
|
||||
// best-effort bookkeeping: a transient storage hiccup (SQLITE_BUSY past the busy-timeout,
|
||||
// disk full, DB locked by a migration) must NOT turn an otherwise-valid credential into a
|
||||
// failed auth. Swallow any non-cancellation failure so the only exception path remains
|
||||
// cancellation, as the class contract promises. Cancellation is honoured (re-thrown).
|
||||
try
|
||||
{
|
||||
await store.MarkUsedAsync(record.KeyId, _timeProvider.GetUtcNow(), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort: the last-used write failed, but the credential is valid. Fail open on the
|
||||
// bookkeeping (not the auth decision) rather than denying a legitimate caller.
|
||||
}
|
||||
|
||||
return new ApiKeyVerification(
|
||||
Succeeded: true,
|
||||
|
||||
@@ -20,7 +20,12 @@ public static class ScopeSerializer
|
||||
|
||||
/// <summary>Deserializes scopes from a JSON array string.</summary>
|
||||
/// <param name="value">The JSON string to deserialize; may be null or empty.</param>
|
||||
/// <returns>An ordinal-compared set of scopes; empty when the input is null/blank.</returns>
|
||||
/// <returns>
|
||||
/// An ordinal-compared set of scopes; empty when the input is null/blank. A malformed or
|
||||
/// non-array column (operator tampering, a partial write, a format change, or a buggy writer)
|
||||
/// fails closed to an EMPTY set rather than throwing, so a single poisoned row degrades to a
|
||||
/// zero-scope identity on the auth path instead of an unhandled <see cref="JsonException"/>.
|
||||
/// </returns>
|
||||
public static IReadOnlySet<string> Deserialize(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
@@ -28,7 +33,18 @@ public static class ScopeSerializer
|
||||
return new HashSet<string>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
string[]? scopes = JsonSerializer.Deserialize<string[]>(value);
|
||||
string[]? scopes;
|
||||
try
|
||||
{
|
||||
scopes = JsonSerializer.Deserialize<string[]>(value);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Fail closed: a corrupt scopes column yields no scopes rather than an exception on the
|
||||
// verification hot path. The verifier's "only exception path is cancellation" contract
|
||||
// is preserved, and a key with an unreadable scope set is left with zero authority.
|
||||
return new HashSet<string>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
return new HashSet<string>(scopes ?? [], StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
@@ -37,7 +37,14 @@ public static class ServiceCollectionExtensions
|
||||
ArgumentNullException.ThrowIfNull(config);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(sectionPath);
|
||||
|
||||
services.Configure<LdapOptions>(config.GetSection(sectionPath));
|
||||
// Bind via the options builder and opt into start-time validation. An IValidateOptions<T>
|
||||
// otherwise only runs when the options are first materialized (IOptions<T>.Value) — which
|
||||
// here is the first login (ILdapAuthService factory below), not boot. ValidateOnStart hooks
|
||||
// the host's start-time options validation so a misconfigured directory (e.g. insecure
|
||||
// transport without AllowInsecure) fails fast at startup rather than on first login.
|
||||
services.AddOptions<LdapOptions>()
|
||||
.Bind(config.GetSection(sectionPath))
|
||||
.ValidateOnStart();
|
||||
|
||||
// Fail fast at startup on a misconfigured directory rather than on first login.
|
||||
services.AddSingleton<IValidateOptions<LdapOptions>, LdapOptionsValidator>();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
using System.Net.Security;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
/// <summary>
|
||||
@@ -15,8 +16,29 @@ internal sealed record LdapSearchEntry(
|
||||
/// </summary>
|
||||
internal interface ILdapConnection : IDisposable
|
||||
{
|
||||
/// <summary>Opens (and optionally upgrades to TLS) a connection to the given host.</summary>
|
||||
void Connect(string host, int port, LdapTransport transport, bool allowInsecure, int timeoutMs);
|
||||
/// <summary>
|
||||
/// Opens (and optionally upgrades to TLS) a connection to the given host.
|
||||
/// </summary>
|
||||
/// <param name="host">The LDAP server hostname or IP.</param>
|
||||
/// <param name="port">The LDAP server port.</param>
|
||||
/// <param name="transport">The transport security mode.</param>
|
||||
/// <param name="allowInsecure">
|
||||
/// When <see langword="true"/> AND no <paramref name="serverCertificateValidationCallback"/> is
|
||||
/// supplied, TLS server-certificate validation is bypassed (dev/test only). Ignored when a
|
||||
/// validation callback is supplied (the callback wins) or for plaintext transport.
|
||||
/// </param>
|
||||
/// <param name="timeoutMs">The connection/operation timeout in milliseconds.</param>
|
||||
/// <param name="serverCertificateValidationCallback">
|
||||
/// Optional TLS server-certificate validation callback. When <see langword="null"/>, the OS trust
|
||||
/// store is used (the client does not blind-accept).
|
||||
/// </param>
|
||||
void Connect(
|
||||
string host,
|
||||
int port,
|
||||
LdapTransport transport,
|
||||
bool allowInsecure,
|
||||
int timeoutMs,
|
||||
RemoteCertificateValidationCallback? serverCertificateValidationCallback);
|
||||
|
||||
/// <summary>Binds with the supplied DN and password. Throws <c>LdapException</c> on bad credentials.</summary>
|
||||
void Bind(string dn, string password);
|
||||
|
||||
@@ -2,19 +2,67 @@ namespace ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
using Novell.Directory.Ldap;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
// Disambiguate: Novell also declares a RemoteCertificateValidationCallback delegate; the seam and
|
||||
// LdapConnectionOptions.ConfigureRemoteCertificateValidationCallback both use the BCL one.
|
||||
using RemoteCertificateValidationCallback = System.Net.Security.RemoteCertificateValidationCallback;
|
||||
|
||||
/// <summary>
|
||||
/// Production <see cref="ILdapConnection"/> backed by <c>Novell.Directory.Ldap.LdapConnection</c>.
|
||||
/// Mirrors the connection/search idioms from ZB.MOM.WW.ScadaBridge.Security.LdapAuthService.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// TLS server-certificate validation: by default the underlying
|
||||
/// <c>Novell.Directory.Ldap.NETStandard</c> client validates the server certificate against the OS
|
||||
/// trust store (it does NOT blind-accept). A caller-supplied
|
||||
/// <c>RemoteCertificateValidationCallback</c> overrides that default (CA pinning / SAN checks); when
|
||||
/// none is supplied and <c>allowInsecure</c> is set, validation is bypassed for dev/test only.
|
||||
/// </remarks>
|
||||
internal sealed class NovellLdapConnection : ILdapConnection
|
||||
{
|
||||
private readonly LdapConnection _conn = new();
|
||||
private readonly LdapConnection _conn;
|
||||
private bool _disposed;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Connect(string host, int port, LdapTransport transport, bool allowInsecure, int timeoutMs)
|
||||
/// <summary>
|
||||
/// Builds the connection, wiring a TLS server-certificate validation policy: a supplied
|
||||
/// <paramref name="serverCertificateValidationCallback"/> wins; otherwise <paramref name="allowInsecure"/>
|
||||
/// bypasses validation (dev/test only); otherwise the OS-trust-store default applies.
|
||||
/// </summary>
|
||||
public NovellLdapConnection(
|
||||
bool allowInsecure = false,
|
||||
RemoteCertificateValidationCallback? serverCertificateValidationCallback = null)
|
||||
{
|
||||
if (serverCertificateValidationCallback is not null)
|
||||
{
|
||||
var options = new LdapConnectionOptions()
|
||||
.ConfigureRemoteCertificateValidationCallback(serverCertificateValidationCallback);
|
||||
_conn = new LdapConnection(options);
|
||||
}
|
||||
else if (allowInsecure)
|
||||
{
|
||||
// Dev/test only: accept any server certificate. Reachable solely when an operator has set
|
||||
// AllowInsecure (rejected for plaintext-without-AllowInsecure by LdapOptionsValidator).
|
||||
var options = new LdapConnectionOptions()
|
||||
.ConfigureRemoteCertificateValidationCallback((_, _, _, _) => true);
|
||||
_conn = new LdapConnection(options);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Default: validate against the OS trust store (no blind-accept).
|
||||
_conn = new LdapConnection();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Connect(
|
||||
string host,
|
||||
int port,
|
||||
LdapTransport transport,
|
||||
bool allowInsecure,
|
||||
int timeoutMs,
|
||||
RemoteCertificateValidationCallback? serverCertificateValidationCallback)
|
||||
{
|
||||
// The TLS-validation policy (allowInsecure / callback) is wired at construction time on the
|
||||
// LdapConnectionOptions; the per-call arguments here are accepted for seam symmetry.
|
||||
ApplyTimeout(timeoutMs);
|
||||
|
||||
// LDAPS: TLS is negotiated at the TCP-connection level.
|
||||
@@ -98,8 +146,16 @@ internal sealed class NovellLdapConnection : ILdapConnection
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Factory that produces fresh <see cref="NovellLdapConnection"/> instances.</summary>
|
||||
internal sealed class NovellLdapConnectionFactory : ILdapConnectionFactory
|
||||
/// <summary>
|
||||
/// Factory that produces fresh <see cref="NovellLdapConnection"/> instances, carrying the TLS
|
||||
/// server-certificate validation policy (a supplied callback, or an <c>allowInsecure</c> bypass) so
|
||||
/// it is wired onto each connection at construction time.
|
||||
/// </summary>
|
||||
internal sealed class NovellLdapConnectionFactory(
|
||||
bool allowInsecure = false,
|
||||
RemoteCertificateValidationCallback? serverCertificateValidationCallback = null)
|
||||
: ILdapConnectionFactory
|
||||
{
|
||||
public ILdapConnection Create() => new NovellLdapConnection();
|
||||
public ILdapConnection Create() =>
|
||||
new NovellLdapConnection(allowInsecure, serverCertificateValidationCallback);
|
||||
}
|
||||
|
||||
@@ -26,10 +26,14 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
|
||||
/// <summary>
|
||||
/// Production constructor: binds against a live directory via the real
|
||||
/// Novell-backed connection factory.
|
||||
/// Novell-backed connection factory. The TLS server-certificate validation policy
|
||||
/// (<see cref="LdapOptions.ServerCertificateValidationCallback"/> or the
|
||||
/// <see cref="LdapOptions.AllowInsecure"/> bypass) is carried into the factory so each
|
||||
/// connection is built with it.
|
||||
/// </summary>
|
||||
public LdapAuthService(LdapOptions options)
|
||||
: this(options, new NovellLdapConnectionFactory())
|
||||
: this(options, new NovellLdapConnectionFactory(
|
||||
options.AllowInsecure, options.ServerCertificateValidationCallback))
|
||||
{
|
||||
}
|
||||
|
||||
@@ -92,7 +96,13 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
// Abstractions change could add DirectoryUnavailable to disambiguate.
|
||||
try
|
||||
{
|
||||
conn.Connect(_options.Server, _options.Port, _options.Transport, _options.AllowInsecure, _options.ConnectionTimeoutMs);
|
||||
conn.Connect(
|
||||
_options.Server,
|
||||
_options.Port,
|
||||
_options.Transport,
|
||||
_options.AllowInsecure,
|
||||
_options.ConnectionTimeoutMs,
|
||||
_options.ServerCertificateValidationCallback);
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
|
||||
@@ -87,6 +87,33 @@ public sealed class ApiKeyAdminCommandsTests : IAsyncLifetime
|
||||
Assert.Single(recent, e => e.EventType == "create-key");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateKey_PersistsBareTokenPrefix_NotPrefixUnderscoreKeyId()
|
||||
{
|
||||
// Auth-005: KeyPrefix is the bare token prefix ("mxgw"), NOT "mxgw_key-1". The key id is
|
||||
// already its own column; embedding it produced a self-referential value that disagreed with
|
||||
// the read/test paths and confused admin tooling.
|
||||
ApiKeyAdminCommands commands = BuildCommands();
|
||||
await commands.InitDbAsync(null, CancellationToken.None);
|
||||
|
||||
await commands.CreateKeyAsync(
|
||||
"key-1",
|
||||
"Service A",
|
||||
new HashSet<string>(["read"], StringComparer.Ordinal),
|
||||
constraintsJson: null,
|
||||
remoteAddress: null,
|
||||
CancellationToken.None);
|
||||
|
||||
ApiKeyRecord? found = await _read.FindByKeyIdAsync("key-1", CancellationToken.None);
|
||||
Assert.NotNull(found);
|
||||
Assert.Equal("mxgw", found!.KeyPrefix);
|
||||
|
||||
// The same bare prefix is surfaced by the admin list projection.
|
||||
IReadOnlyList<ApiKeyListItem> listed = await commands.ListKeysAsync(CancellationToken.None);
|
||||
ApiKeyListItem item = Assert.Single(listed, k => k.KeyId == "key-1");
|
||||
Assert.Equal("mxgw", item.KeyPrefix);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateKey_PepperUnavailable_ReturnsNoTokenAndAppendsNoAudit()
|
||||
{
|
||||
|
||||
@@ -212,6 +212,51 @@ public class ApiKeyVerifierTests
|
||||
Assert.DoesNotContain(Convert.ToBase64String(hash), identityText, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
// --- Auth-002: a failed best-effort MarkUsedAsync must NOT fail a valid key ---
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAsync_ValidKey_MarkUsedThrows_StillSucceeds()
|
||||
{
|
||||
// MarkUsedAsync is best-effort "last used" bookkeeping. A transient storage failure
|
||||
// (SQLITE_BUSY, disk full, locked DB) must not turn an otherwise-valid credential into a
|
||||
// failed auth: the decision is already made before the usage write. The verifier's contract
|
||||
// is "the only exception path is cancellation", so a non-cancellation MarkUsedAsync failure
|
||||
// is swallowed and the result is still Succeeded == true.
|
||||
byte[] hash = ApiKeySecretHasher.Hash(Secret, Pepper);
|
||||
var store = new FakeApiKeyStore
|
||||
{
|
||||
Record = BuildRecord(hash),
|
||||
MarkUsedException = new InvalidOperationException("SQLITE_BUSY"),
|
||||
};
|
||||
var verifier = BuildVerifier(store, new FakePepperProvider(Pepper));
|
||||
|
||||
ApiKeyVerification result =
|
||||
await verifier.VerifyAsync(Header(KeyId, Secret), CancellationToken.None);
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Null(result.Failure);
|
||||
Assert.NotNull(result.Identity);
|
||||
Assert.Equal(KeyId, result.Identity!.KeyId);
|
||||
Assert.True(store.MarkUsedCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAsync_MarkUsedThrowsOperationCanceled_Propagates()
|
||||
{
|
||||
// The ONLY exception path is cancellation: an OperationCanceledException from the usage
|
||||
// write (e.g. the request was cancelled mid-write) is honoured and re-thrown, not swallowed.
|
||||
byte[] hash = ApiKeySecretHasher.Hash(Secret, Pepper);
|
||||
var store = new FakeApiKeyStore
|
||||
{
|
||||
Record = BuildRecord(hash),
|
||||
MarkUsedException = new OperationCanceledException(),
|
||||
};
|
||||
var verifier = BuildVerifier(store, new FakePepperProvider(Pepper));
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
() => verifier.VerifyAsync(Header(KeyId, Secret), CancellationToken.None));
|
||||
}
|
||||
|
||||
// --- Cancellation ---
|
||||
|
||||
[Fact]
|
||||
@@ -253,6 +298,9 @@ public class ApiKeyVerifierTests
|
||||
public string? MarkUsedKeyId { get; private set; }
|
||||
public DateTimeOffset? MarkUsedWhenUtc { get; private set; }
|
||||
|
||||
/// <summary>When set, <see cref="MarkUsedAsync"/> throws this exception (after recording the call).</summary>
|
||||
public Exception? MarkUsedException { get; set; }
|
||||
|
||||
public Task<ApiKeyRecord?> FindByKeyIdAsync(string keyId, CancellationToken ct)
|
||||
{
|
||||
FindByKeyIdCalled = true;
|
||||
@@ -267,6 +315,11 @@ public class ApiKeyVerifierTests
|
||||
MarkUsedCalled = true;
|
||||
MarkUsedKeyId = keyId;
|
||||
MarkUsedWhenUtc = whenUtc;
|
||||
if (MarkUsedException is not null)
|
||||
{
|
||||
return Task.FromException(MarkUsedException);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +164,36 @@ public sealed class SqliteApiKeyStoreTests : IAsyncLifetime
|
||||
Assert.Empty(ScopeSerializer.Deserialize(""));
|
||||
}
|
||||
|
||||
// --- Auth-003: corrupt scopes JSON must fail closed (empty set), never throw JsonException ---
|
||||
|
||||
[Theory]
|
||||
[InlineData("not json at all")]
|
||||
[InlineData("{")]
|
||||
[InlineData("{\"a\":1}")] // valid JSON, but an object, not a string[]
|
||||
[InlineData("42")] // valid JSON, but a number
|
||||
[InlineData("[\"read\",")] // truncated/partial write
|
||||
public void ScopeSerializer_DeserializeMalformed_ReturnsEmptySet_DoesNotThrow(string value)
|
||||
{
|
||||
// A poisoned scopes column (tampering, partial write, format change, buggy writer) must
|
||||
// degrade to a zero-scope set rather than throwing on the verification hot path.
|
||||
IReadOnlySet<string> scopes = ScopeSerializer.Deserialize(value);
|
||||
Assert.Empty(scopes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindByKeyId_CorruptScopesColumn_ReturnsRecordWithEmptyScopes_DoesNotThrow()
|
||||
{
|
||||
// Insert a row whose scopes column holds malformed (non-array) JSON, then read it through
|
||||
// the store. The store must NOT propagate a JsonException out of FindByKeyIdAsync (which the
|
||||
// verifier relies on for its "only exception path is cancellation" contract).
|
||||
await InsertWithRawScopesAsync("key-corrupt", scopesJson: "{ this is not valid json");
|
||||
|
||||
ApiKeyRecord? found = await _store.FindByKeyIdAsync("key-corrupt", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(found);
|
||||
Assert.Empty(found!.Scopes);
|
||||
}
|
||||
|
||||
private static ApiKeyRecord SampleRecord(string keyId) => new(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: "mxgw_ab12",
|
||||
@@ -213,6 +243,33 @@ public sealed class SqliteApiKeyStoreTests : IAsyncLifetime
|
||||
await command.ExecuteNonQueryAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
private async Task InsertWithRawScopesAsync(string keyId, string scopesJson)
|
||||
{
|
||||
// Writes the scopes column verbatim (NOT via ScopeSerializer.Serialize) so a malformed
|
||||
// value can be persisted to simulate tampering / a partial or buggy write.
|
||||
await using SqliteConnection connection =
|
||||
await _factory.OpenConnectionAsync(CancellationToken.None);
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
INSERT INTO api_keys (
|
||||
key_id, key_prefix, secret_hash, display_name, scopes,
|
||||
constraints, created_utc, last_used_utc, revoked_utc)
|
||||
VALUES (
|
||||
$key_id, $key_prefix, $secret_hash, $display_name, $scopes,
|
||||
$constraints, $created_utc, $last_used_utc, $revoked_utc);
|
||||
""";
|
||||
command.Parameters.AddWithValue("$key_id", keyId);
|
||||
command.Parameters.AddWithValue("$key_prefix", "mxgw");
|
||||
command.Parameters.Add("$secret_hash", SqliteType.Blob).Value = new byte[] { 1, 2, 3 };
|
||||
command.Parameters.AddWithValue("$display_name", "Corrupt Key");
|
||||
command.Parameters.AddWithValue("$scopes", scopesJson);
|
||||
command.Parameters.AddWithValue("$constraints", DBNull.Value);
|
||||
command.Parameters.AddWithValue("$created_utc", DateTimeOffset.UnixEpoch.ToString("O"));
|
||||
command.Parameters.AddWithValue("$last_used_utc", DBNull.Value);
|
||||
command.Parameters.AddWithValue("$revoked_utc", DBNull.Value);
|
||||
await command.ExecuteNonQueryAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
public Task DisposeAsync()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
|
||||
+49
@@ -1,5 +1,6 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
using ZB.MOM.WW.Auth.AspNetCore;
|
||||
@@ -85,4 +86,52 @@ public class ServiceCollectionExtensionsTests
|
||||
|
||||
Assert.Contains(validators, v => v is LdapOptionsValidator);
|
||||
}
|
||||
|
||||
// --- Auth-001: ValidateOnStart must run options validation at host startup, not first login ---
|
||||
|
||||
private static IConfiguration BuildInsecureConfiguration() =>
|
||||
new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
[$"{LdapSection}:Server"] = LdapServer,
|
||||
[$"{LdapSection}:SearchBase"] = "dc=example,dc=com",
|
||||
[$"{LdapSection}:ServiceAccountDn"] = "cn=svc,dc=example,dc=com",
|
||||
// Plaintext transport without AllowInsecure: the validator must reject this.
|
||||
[$"{LdapSection}:Transport"] = nameof(LdapTransport.None),
|
||||
[$"{LdapSection}:AllowInsecure"] = "false",
|
||||
})
|
||||
.Build();
|
||||
|
||||
[Fact]
|
||||
public async Task AddZbLdapAuth_StartingHost_FailsForInsecureConfig()
|
||||
{
|
||||
// The misconfiguration must surface at host start, not deferred until the first login
|
||||
// (i.e. the first ILdapAuthService resolution). ValidateOnStart wires the host's
|
||||
// start-time options validation, so StartAsync must throw OptionsValidationException.
|
||||
IConfiguration config = BuildInsecureConfiguration();
|
||||
|
||||
using IHost host = new HostBuilder()
|
||||
.ConfigureServices(services => services.AddZbLdapAuth(config, LdapSection))
|
||||
.Build();
|
||||
|
||||
OptionsValidationException ex =
|
||||
await Assert.ThrowsAsync<OptionsValidationException>(() => host.StartAsync());
|
||||
|
||||
Assert.Contains(nameof(LdapOptions.Transport), string.Join(" ", ex.Failures));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddZbLdapAuth_StartingHost_SucceedsForSecureConfig()
|
||||
{
|
||||
// A valid (secure) config must start cleanly — proving ValidateOnStart does not reject
|
||||
// well-formed options.
|
||||
IConfiguration config = BuildConfiguration();
|
||||
|
||||
using IHost host = new HostBuilder()
|
||||
.ConfigureServices(services => services.AddZbLdapAuth(config, LdapSection))
|
||||
.Build();
|
||||
|
||||
await host.StartAsync();
|
||||
await host.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Net.Security;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
using ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
@@ -19,6 +20,10 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
// ---- observation -----
|
||||
|
||||
public (string Host, int Port, LdapTransport Transport, bool AllowInsecure, int TimeoutMs)? ConnectArgs { get; private set; }
|
||||
|
||||
/// <summary>The server-certificate validation callback passed to the most recent <see cref="Connect"/> call.</summary>
|
||||
public RemoteCertificateValidationCallback? ConnectCertCallback { get; private set; }
|
||||
|
||||
public List<string> BoundDns { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -107,9 +112,16 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
|
||||
// ---- ILdapConnection -----
|
||||
|
||||
public void Connect(string host, int port, LdapTransport transport, bool allowInsecure, int timeoutMs)
|
||||
public void Connect(
|
||||
string host,
|
||||
int port,
|
||||
LdapTransport transport,
|
||||
bool allowInsecure,
|
||||
int timeoutMs,
|
||||
RemoteCertificateValidationCallback? serverCertificateValidationCallback = null)
|
||||
{
|
||||
ConnectArgs = (host, port, transport, allowInsecure, timeoutMs);
|
||||
ConnectCertCallback = serverCertificateValidationCallback;
|
||||
if (_throwOnConnect)
|
||||
throw new Novell.Directory.Ldap.LdapException(
|
||||
"Directory unreachable", Novell.Directory.Ldap.LdapException.ConnectError, host);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Net.Security;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
using ZB.MOM.WW.Auth.Ldap;
|
||||
|
||||
@@ -80,6 +81,56 @@ public class LdapAuthServiceTests
|
||||
Assert.Equal(LdapAuthFailure.Disabled, (await svc.AuthenticateAsync("a", "b", default)).Failure);
|
||||
}
|
||||
|
||||
// --- Auth-006: TLS validation seam — allowInsecure is honoured and a cert-validation
|
||||
// callback is threaded into the connection rather than being silently ignored. ---
|
||||
|
||||
[Fact]
|
||||
public async Task Connect_ReceivesAllowInsecureFlag_FromOptions()
|
||||
{
|
||||
// The allowInsecure flag must reach the connection (it used to be an unused parameter).
|
||||
var fake = new FakeLdapConnection().WithUserEntry(
|
||||
"cn=alice,dc=x", memberOf: new[] { "cn=Engineers,ou=g,dc=x" });
|
||||
var svc = new LdapAuthService(
|
||||
Opts() with { AllowInsecure = true }, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
await svc.AuthenticateAsync("alice", "pw", default);
|
||||
|
||||
Assert.NotNull(fake.ConnectArgs);
|
||||
Assert.True(fake.ConnectArgs!.Value.AllowInsecure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Connect_ReceivesConfiguredCertValidationCallback()
|
||||
{
|
||||
// A consumer-supplied RemoteCertificateValidationCallback must be passed through to the
|
||||
// connection so production callers can pin a CA / validate the SAN — the seam no longer
|
||||
// discards it.
|
||||
RemoteCertificateValidationCallback callback = (_, _, _, _) => true;
|
||||
var fake = new FakeLdapConnection().WithUserEntry(
|
||||
"cn=alice,dc=x", memberOf: new[] { "cn=Engineers,ou=g,dc=x" });
|
||||
var svc = new LdapAuthService(
|
||||
Opts() with { ServerCertificateValidationCallback = callback },
|
||||
new FakeLdapConnectionFactory(fake));
|
||||
|
||||
await svc.AuthenticateAsync("alice", "pw", default);
|
||||
|
||||
Assert.Same(callback, fake.ConnectCertCallback);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Connect_NoCertCallbackConfigured_PassesNull()
|
||||
{
|
||||
// Default: no callback configured -> null reaches the connection, which means the
|
||||
// production adapter falls back to OS-trust-store validation (documented behaviour).
|
||||
var fake = new FakeLdapConnection().WithUserEntry(
|
||||
"cn=alice,dc=x", memberOf: new[] { "cn=Engineers,ou=g,dc=x" });
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
await svc.AuthenticateAsync("alice", "pw", default);
|
||||
|
||||
Assert.Null(fake.ConnectCertCallback);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PreservesEscapedCommaInGroupName_OnRfc4514Dn()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user