docs(code-reviews): review Secrets, LocalDb, GalaxyRepository, Overview; re-review changed libs (scadaproj#15)

First reviews of Secrets, LocalDb, GalaxyRepository and Overview, and
2026-11-09 re-reviews of Auth, Health, Theme, Telemetry, Audit and
Configuration, all at 91fb2b4. 49 new open findings, each with a P1/P2/P3
priority and a failure scenario: 1 P1, 13 P2, 35 P3. README regenerated;
REVIEW-PROCESS, template and regen script now cover all ten libraries and
the Priority field.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 14:33:14 -05:00
parent 91fb2b48dd
commit 477245f5db
14 changed files with 2602 additions and 52 deletions
+222 -5
View File
@@ -7,14 +7,48 @@
| Component spec | `components/auth/spec/SPEC.md` |
| Shared contract | `components/auth/shared-contract/ZB.MOM.WW.Auth.md` |
| Status | Reviewed |
| Last reviewed | 2026-06-01 |
| Reviewer | Claude (automated baseline) |
| Commit reviewed | `5f75cd4` |
| Open findings | 0 |
| Last reviewed | 2026-11-09 (re-review; baseline 2026-06-01 at `5f75cd4`) |
| Reviewer | Claude (2026-11-09 re-review, scadaproj#15; baseline: Claude automated) |
| Commit reviewed | `91fb2b4` |
| Open findings | 4 |
## Summary
The security-critical core of this library is sound: API-key secrets are 32-byte CSPRNG values,
**2026-11-09 re-review (`91fb2b4`, scadaproj#15).** Re-reviewed at `91fb2b4` (on-disk version `0.4.3`; the feed carries `0.4.1`), covering everything added
since the `5f75cd4` baseline: LDAP `FallbackServers` failover with a sticky preferred endpoint (0.2.0), the AD
continuation-referral skip (0.2.1), the new `ZB.MOM.WW.Auth.ApiKeys.SqlServer` package (stores, migrator that
copes with concurrent boots, SQLite importer, `AddZbApiKeyAuthSqlServer`) (0.3.0), opt-in LDAP user bind
(`BindMode=User` / `UserBindTemplate` / `AcceptDomainQualifiedNames`) (0.4.0), and the canonical username plus
empty-password refusal (0.4.1). Auth-001..006 remain correctly resolved, and the new code holds up on its main
security points:
- **One connection per attempt.** Every endpoint attempt gets a fresh `ILdapConnection`, disposed by `using` on
every path, including failover.
- **Failover is system-side only.** A `BadCredentials`/49 answer is final and is never replayed against another
DC.
- **Empty passwords are refused before any network call in both modes**, which closes the unauthenticated-bind
hole.
- **Filter values are still RFC 4515-escaped.**
- **The SQL Server store is parameterised throughout.** The schema name passes a strict ASCII allow-list
re-checked at the public DDL entry point.
- **Concurrent first-boot migration converges.** The retry on 1205/2714/1913/2627 with jitter works: the live
suite passes 92/92 against a throwaway SQL Server 2022, and the DBA script plus a row-only login migrate cleanly.
- **The SQL Server DI extension has container-building tests.**
The main new issue is in user-bind mode. The account that binds and the entry whose groups and username are
returned are found independently: the first from `UserBindTemplate`, the second from a `UserNameAttribute`
search. Nothing checks that they are the same object, so a UPN template, which the validator's own error text
offers first, can sign one user in with another user's groups (Auth-007). The remaining findings are Low:
- **Silent truncation in the SQL Server store.** The store sets explicit `SqlParameter` sizes and uses
case-insensitive key ids, so it does not match SQLite's semantics (Auth-008).
- **Username from a multi-valued attribute.** The canonical username takes the first value of a possibly
multi-valued attribute (Auth-009).
- **Store faults escape the verifier.** `ApiKeyVerifier` still lets store exceptions out, which matters more now
that the store can be a network database (Auth-010).
Offline suite: 331 passed / 76 skipped (live-gated). With `AUTH_SQLSERVER_CONNSTR` set, the SqlServer suite
runs 92/92.
**2026-06-01 baseline (`5f75cd4`).** The security-critical core of this library is sound: API-key secrets are 32-byte CSPRNG values,
hashing is HMAC-SHA256 keyed by an external pepper, verification uses
`CryptographicOperations.FixedTimeEquals`, the SQLite stores use parameterized SQL throughout,
LDAP filter values are RFC 4515-escaped before being interpolated into the search filter, group-DN
@@ -31,6 +65,23 @@ hashing algorithm and the AspNetCore surface. The library is **not yet adopted**
## Checklist coverage
2026-11-09 re-review at `91fb2b4`:
| # | Category | Examined | Notes |
|---|----------|----------|-------|
| 1 | Correctness & logic bugs | ☑ | Failover walk, sticky index, referral skip, `LdapUserName` normaliser and the expiry check are correct. See Auth-008 (silent truncation / case-insensitive key ids diverge from SQLite) and Auth-009 (canonical username = first value of a multi-valued attribute) |
| 2 | Public API surface & compatibility | ☑ | `IApiKeyStoreMigrator` seam is clean and the old `SqliteAuthStoreMigrator` ctor is kept. Two changes are 0.x source/binary breaks with no other effect: the new `IApiKeyAdminStore` members and the optional parameter on `ApiKeyRecord`. No issues found |
| 3 | Concurrency & thread safety | ☑ | The sticky `_preferredIndex` uses `Volatile`, so its race is benign. The SQL Server migrator's retry with jitter converged under the live 8-way test. Stores open one connection per operation. No issues found |
| 4 | Error handling & resilience | ☑ | `LdapAuthService` stays fail-closed on every stage and `MarkUsedAsync` is best-effort (Auth-002 holds). See Auth-010: store lookup faults (e.g. `SqlException` on a shared-DB outage) still escape `ApiKeyVerifier`, despite its "only cancellation" contract |
| 5 | Security & secret handling | ☑ | Empty passwords are refused in both modes, BadCredentials is never failed over, filter escaping is intact, SQL is parameterised and the schema identifier is allow-listed. See Auth-007 (user-bind mode reads a different entry from the one that bound). DN templates are not escaped, but README documents this |
| 6 | Performance & resource management | ☑ | `ILdapConnection` is disposed via `using` inside the per-attempt try (every path, incl. failover). SQL connections, commands and readers use `await using`, and `OpenConnectionAsync` disposes on a failed open. No issues found |
| 7 | Spec & shared-contract adherence | ☑ | SQL Server rows mirror SQLite column-for-column, apart from Auth-008. The `IApiKeyVerifier` "only cancellation" contract is violated (Auth-010) |
| 8 | Packaging, dependencies & project layout | ☑ | New SqlServer package is cleanly split and depends only on Abstractions-level `Microsoft.Extensions.*`. The Pkcs/SQLitePCLRaw transitive pins are present. No issues found |
| 9 | Testing coverage | ☑ | Strong: failover, user-bind, referral, normaliser, validator, live SQL Server suites, plus DI tests that build containers for `AddZbApiKeyAuthSqlServer`, `AddZbApiKeyAuth` and `AddZbLdapAuth`. Gaps: no test ties the bound identity to the returned entry (Auth-007), no over-length or case-variant key-id test (Auth-008), no multi-valued username attribute test (Auth-009), no store-throws verifier test (Auth-010) |
| 10 | Documentation & XML docs | ☑ | Thorough. `UserBindTemplate` docs warn about UPN mismatch, but the validator message offers the UPN form first (Auth-007). `ApiKeyVerifier` remark overstates its exception contract (Auth-010) |
<details><summary>2026-06-01 baseline checklist (<code>5f75cd4</code>)</summary>
| # | Category | Examined | Notes |
|---|----------|----------|-------|
| 1 | Correctness & logic bugs | ☑ | Core logic correct; see Auth-003 (JSON parse can throw on hot path), Auth-005 (KeyPrefix value inconsistency) |
@@ -44,6 +95,8 @@ hashing algorithm and the AspNetCore surface. The library is **not yet adopted**
| 9 | Testing coverage | ☑ | Broad and contract-level; gaps: no test for corrupt-`scopes` deserialization (Auth-003) or `MarkUsedAsync`-throws (Auth-002); `ValidateOnStart` behavior untested (Auth-001) |
| 10 | Documentation & XML docs | ☑ | XML docs thorough and accurate; README is stale — see Auth-004 |
</details>
## Findings
### Auth-001 — LDAP options validator is registered but never runs at startup
@@ -252,3 +305,167 @@ beyond the OS default, and document the default validation behavior.
**Resolution**
Resolved in `544a6dd`, 2026-06-01 — added an optional `LdapOptions.ServerCertificateValidationCallback` (BCL `RemoteCertificateValidationCallback`, no new dependency) threaded through the `ILdapConnection.Connect` seam; `NovellLdapConnection` now builds `LdapConnectionOptions.ConfigureRemoteCertificateValidationCallback(...)` (a supplied callback wins; otherwise the previously-dead `allowInsecure` gates a dev-only accept-any path; otherwise OS-trust-store default), and the default validation behaviour is documented in XML/README (tests: `LdapAuthServiceTests.Connect_ReceivesConfiguredCertValidationCallback`, `..._Connect_ReceivesAllowInsecureFlag_FromOptions`, `..._Connect_NoCertCallbackConfigured_PassesNull`).
<!-- 2026-11-09 re-review (scadaproj#15) findings below. -->
### Auth-007 — User-bind mode never checks that the entry whose groups it returns is the account that bound
| | |
|--|--|
| Severity | Medium |
| Priority | P2 |
| Category | Security & secret handling |
| Status | Open |
| Location | `ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Ldap/LdapAuthService.cs:329` |
**Description**
`CompleteAsUser` authenticates by binding as `UserBindTemplate.Replace("{0}", username)` (line 329–332). It then
runs a separate search, `(<UserNameAttribute>=<username>)` (line 345 → `SearchUser`, line 361), and returns the
groups and username of whatever single entry that search finds (line 349 → `SucceedFromEntry`). Two different
directory lookups resolve the bind name and the search filter. Nothing checks that the entry found is the account
the directory just authenticated. There is no comparison of DNs, no RFC 4532 "Who am I?", and no search keyed on
the bind identity. The XML doc and README describe the UPN mismatch as guidance only ("a mismatch can … bind a
different account than the one whose groups are read"). The validator's failure message
(`LdapOptionsValidator.cs:77`) offers `"{0}@example.com"` as its first example template. A DN-form template is also
spliced in unescaped (documented), which is another way for the bind identity and the search key to diverge.
**Failure scenario**
`BindMode=User` with `UserBindTemplate="{0}@corp.com"` and `UserNameAttribute=sAMAccountName` on AD, a combination
the validator message suggests. Mallory's account has explicit UPN `jsmith@corp.com` and `sAMAccountName=jsmith2`,
which is common after a rename or when two people share a name. A separate admin account has `sAMAccountName=jsmith`.
Mallory signs in as `jsmith` with her own password:
1. AD resolves the UPN bind to Mallory's account and accepts it.
2. The search `(sAMAccountName=jsmith)` returns the admin's entry.
3. `LdapAuthResult.Success("jsmith", "Admin Smith", ["UG_Admins"])` is returned.
That is privilege escalation with valid credentials of a different user. I reproduced this through the
`FakeLdapConnection` seam: the bind went to `jsmith@corp.test` and the result carried the other entry's groups.
**Recommendation**
After the bind, identify the entry by the bound identity, not the typed name:
- **UPN templates:** search on `userPrincipalName=<bindName>`.
- **Any template:** use the RFC 4532 Who-am-I extended operation (AD returns `u:DOMAIN\sam`) and check it against
the found entry's `sAMAccountName`.
- **DN templates:** require the found entry's DN to equal the bind DN, and DN-escape `{0}` (RFC 4514).
Fail with `GroupLookupFailed` on a mismatch. At minimum, reorder the validator example to lead with
`EXAMPLE\{0}`. Add a test where the bind name and the searched entry differ.
### Auth-008 — SQL Server store silently truncates over-length values and matches key ids case-insensitively, diverging from SQLite
| | |
|--|--|
| Severity | Low |
| Priority | P3 |
| Category | Correctness & logic bugs |
| Status | Open |
| Location | `ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys.SqlServer/SqlServerApiKeyAdminStore.cs:45` (also `:46`, `:48`; `SqlServerApiKeyStore.cs:56,77`; `SqlServerApiKeyAuditStore.cs:30-32`; `SqliteApiKeyStoreImporter.cs:258-261,292-294`; columns in `SqlServerAuthSchema.cs:79-96`) |
**Description**
Every string parameter is added with an explicit size: `NVarChar, 64` for `key_id`, `event_type` and
`remote_address`, `16` for `key_prefix`, and `256` for `display_name`. `SqlParameter` truncates an input longer
than `Size` without raising an error, so over-length values are cut down rather than rejected. The columns also use
the database's default collation, which is case-insensitive on a stock SQL Server. The SQLite store this one claims
to port "one-for-one" has `TEXT` columns, no length limits and BINARY (case-sensitive) comparison. `CreateKeyAsync`
validates only that `keyId` is non-blank and has no `_`.
I verified this live against a SQL Server 2022 container:
- A 70-char `keyId` with a 20-char prefix and a 300-char display name was created without error, and the row was
stored as 64/16/256 characters.
- `FindByKeyIdAsync` with the full 70-char id, and with a different 70-char id sharing the first 64 characters,
both found the row.
- `FindByKeyIdAsync("LINE1")` found the row stored as `line1`.
- Creating `Line1` beside `line1` failed with a PK violation.
- An 80-char audit `event_type`/`remote_address` was stored as 64 characters.
**Failure scenario**
1. **Over-length key id.** An admin mints a key with a long, descriptive key id (more than 64 characters) on a host
using `AddZbApiKeyAuthSqlServer`. Creation succeeds and the returned token embeds the full id. Verification
succeeds only because the lookup parameter is truncated the same way. The authenticated `ApiKeyIdentity.KeyId`
is the 64-character stored value, not the id the admin assigned. Any host ACL or audit correlation keyed on the
assigned id never matches.
2. **Case-variant ids in the importer.** Two SQLite keys `Line1` and `line1` (legal on SQLite) migrate through
`SqliteApiKeyStoreImporter`. The second is counted as "skipped" because the `IF NOT EXISTS` check matches
case-insensitively. After cut-over its token resolves to the other key's row, fails `SecretMismatch`, and that
client is locked out with no error at import time.
**Recommendation**
- Pass `-1`/no explicit size, or validate lengths up front and throw `ArgumentException`, in both `CreateKeyAsync`
and the importer.
- Declare `key_id` with a binary or case-sensitive collation (e.g. `COLLATE Latin1_General_100_BIN2`) to match
SQLite. Alternatively, document and enforce a case-folded, `[A-Za-z0-9-]{1,64}` key-id alphabet in
`ApiKeyAdminCommands`.
- Make the importer report key-id collisions instead of counting them as plain skips.
### Auth-009 — Canonical username is the first value of a possibly multi-valued attribute, not the value the user matched
| | |
|--|--|
| Severity | Low |
| Priority | P3 |
| Category | Correctness & logic bugs |
| Status | Open |
| Location | `ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Ldap/LdapAuthService.cs:437` |
**Description**
0.4.1's `ExtractUserName` returns `values[0]` of `UserNameAttribute` whenever that value is non-blank (lines
437–441). The default `UserNameAttribute` is `cn` (`LdapContracts.cs:30`), which is multi-valued in standard LDAP
schemas: OpenLDAP and 389-DS entries routinely carry both `cn: John Smith` and `cn: jsmith`. The search matched on
one of those values, but the code returns whichever value the server lists first, which need not be the one the
user typed. This is the same person and the same entry, so there is no privilege effect. However, the identity
string handed to the host changes with the 0.4.1 upgrade and depends on server attribute ordering.
**Failure scenario**
A host on the default `UserNameAttribute=cn` runs against an OpenLDAP directory where users have two `cn` values.
Before 0.4.1 `jsmith` signed in as `jsmith`. After the upgrade the result's `Username` is `John Smith`. Per-user
records, audit trails and any username-keyed role overrides in the host split into two identities, and a username
containing a space can break downstream consumers that treat it as an account name. I reproduced this through the
fake connection: typed `jsmith` returned `Username == "John Smith"`.
**Recommendation**
Prefer the attribute value that equals the typed (normalised) name under `OrdinalIgnoreCase`, which still
canonicalises case. Fall back to `values[0]` only when no value matches. Add a multi-valued-attribute test.
### Auth-010 — `ApiKeyVerifier` lets store exceptions escape despite its "only exception path is cancellation" contract
| | |
|--|--|
| Severity | Low |
| Priority | P3 |
| Category | Error handling & resilience |
| Status | Open |
| Location | `ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/ApiKeyVerifier.cs:47` (contract stated at `:13`) |
**Description**
The type remark (line 13) promises "The only exception path is cancellation". Auth-002 fixed `MarkUsedAsync` to
honour that promise, but the lookup `await store.FindByKeyIdAsync(...)` at line 47 is unguarded. Its failures
propagate unchanged. With the new `SqlServerApiKeyStore` the store is a network database shared by a cluster, so
lookup failures are an expected operating condition, not a rare local-disk fault. A misconfigured
`SqlServerApiKeyOptions` also escapes: it is validated lazily in the `AuthSqlServerConnectionFactory` constructor.
With `RunMigrationsOnStartup=false` that throws `InvalidOperationException` out of the first verifier resolution or
call.
**Failure scenario**
The shared SQL Server is briefly unreachable during a failover, or the central pair loses its route to it. Every
inbound API request's `VerifyAsync` throws `Microsoft.Data.SqlClient.SqlException`; I verified this against a closed
port. Consumers wrote their middleware and interceptors against the documented contract and map
`Succeeded == false` to 401, so they do not catch this. The request surfaces as an unhandled 500, or a gRPC
`Unknown`, instead of a clean auth failure or 503, and the failure goes unaudited.
**Recommendation**
Wrap the lookup and map non-cancellation exceptions to a structured failure, for example a new
`ApiKeyFailure.StoreUnavailable`. Otherwise, correct the remark to say store exceptions propagate. Add a test
where the store throws. Optionally add `SqlServerApiKeyOptions` startup validation
(`AddOptions().Validate(...).ValidateOnStart()`), mirroring Auth-001.