# Phase 146 implementation evidence

This ledger maps checked Phase 146 requirements to current, executable evidence.
It is intentionally incremental: unchecked sections in `phase-146.md` remain
open until equivalent implementation and verification exist.

## 146.1 Directory and account store

| Requirement          | Implementation evidence                                                                                                                                                                                                                              | Verification evidence                                                                                                                                                                         |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 146.1.1.1–146.1.1.10 | `libs/neith/idp-core/src/types.ts`, `schema.ts`, and `directory.ts` define all directory resources, enforce tenant-scoped hierarchy/references, SPIFFE syntax, custom schemas, uniqueness, and bounded seat assignment.                              | `idp-core.spec.ts` exercises every resource kind, hierarchy, cross-tenant rejection, custom/immutable attributes, and seat exhaustion/release.                                                |
| 146.1.2.1            | `postgres.ts` performs encrypted record and audit writes in one PostgreSQL transaction with row locking and optimistic concurrency. `migrations/0001_directory.sql` defines the partitioned primary schema and logical-publication operator command. | The PostgreSQL adapter test proves transaction boundaries, encrypted persistence, audit insertion, and round-trip read. The migration contract test asserts publication and schema artifacts. |
| 146.1.2.2–146.1.2.4  | `crypto.ts` provides tenant/context-bound AES-256-GCM envelope encryption. `storage.ts` and `postgres.ts` implement tombstones and per-record revision history.                                                                                      | Ciphertext context rejection, soft-delete/restore, and revision-order tests.                                                                                                                  |
| 146.1.2.5–146.1.2.6  | `TenantPlacement` and `TenantRouter` model primary/replica regions, active-active eligibility, residency, and physical shard; invalid active-active or out-of-residency routing fails closed.                                                        | Placement validation and allowed/denied region tests.                                                                                                                                         |
| 146.1.2.7            | Retained key versions decrypt historical data; rotation plus `reencryptTenant` migrates live ciphertext and records a re-encryption revision.                                                                                                        | Old-key decrypt, new-key selection, and tenant re-encryption tests.                                                                                                                           |
| 146.1.2.8            | The idempotent initial migration uses stable relational envelopes, hash partitions, and separately documented concurrent-index/operator steps so rolling payload/schema evolution does not require decrypting or rewriting directory rows.           | Migration artifact assertions plus package strict typecheck.                                                                                                                                  |
| 146.1.2.9            | `createBackup`, `verifyBackup`, and `restoreBackup` provide checksummed hot/cold snapshots including placement and tombstone state.                                                                                                                  | Both backup tiers are checksummed and a restore drill verifies the recovered identity.                                                                                                        |
| 146.1.2.10           | Tenant placement selects a physical shard; PostgreSQL records are hash-partitioned on `tenant_id` into eight independently movable partitions.                                                                                                       | Tenant isolation/shard tests and eight-partition migration assertion.                                                                                                                         |

### Verified commands

- `pnpm nx run neith-idp-core:lint`
- `pnpm nx run neith-idp-core:typecheck`
- `pnpm exec vitest run --config libs/neith/idp-core/vitest.config.ts libs/neith/idp-core/src/idp-core.spec.ts --reporter=verbose`
- `pnpm exec prettier --check 'libs/neith/idp-core/**/*.{ts,json}'`

## 146.2.1 Authentication credentials

| Requirement                       | Implementation evidence                                                                                                                                                                          | Verification evidence                                                                                                        |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| 146.2.1.1–146.2.1.2               | `idp-authn/password.ts` uses parameterized Argon2id and supports both offline SHA-1 corpora and HIBP five-character range queries with padded responses.                                         | Argon2id hash/verify and offline/remote breach tests prove that neither password nor full digest is sent remotely.           |
| 146.2.1.3, 146.2.1.9              | `attestation.ts` registers discoverable, backed-up platform or roaming WebAuthn credentials and verifies RP hash, client data, UP/UV flags, signatures, and monotonic counters.                  | Ed25519 assertion round trip plus counter-replay rejection.                                                                  |
| 146.2.1.4                         | `otp.ts` implements base32, RFC 4226 HOTP, RFC 6238 TOTP with drift and replay control, and PNG enrollment QR generation.                                                                        | All ten RFC 4226 vectors, TOTP replay rejection, and QR/URI assertions.                                                      |
| 146.2.1.5–146.2.1.8, 146.2.1.14   | `challenge.ts` provides expiring single-use token storage, email links, one-time recovery codes, number-matching push, and fraud/rate/attempt-limited SMS and voice delivery.                    | Single-consumption, push mismatch, risk denial, delivery, recovery, magic-link, and bootstrap tests.                         |
| 146.2.1.10–146.2.1.11, 146.2.1.15 | `SignedFactorVerifier` verifies signed hardware, biometric, and trusted smart-card factors. `MutualTlsAuthenticator` validates certificate lifetime, issuer signature/trust, and SAN identities. | Deterministic CAC/PIV-style client certificate and biometric signature tests, including extracted SPIFFE and DNS identities. |
| 146.2.1.12–146.2.1.13             | `risk.ts` scores new device, posture, IP reputation, breach, velocity, privilege, and haversine geo-velocity signals; adaptive policy filters enrolled factors and enforces phishing resistance. | Impossible-travel/high-risk step-up, privileged factor filtering, low-risk allow, and critical-risk deny tests.              |

### Verified commands

- `pnpm nx run neith-idp-authn:lint`
- `pnpm nx run neith-idp-authn:typecheck`
- `pnpm exec vitest run --config libs/neith/idp-authn/vitest.config.ts libs/neith/idp-authn/src/idp-authn.spec.ts --reporter=verbose`

## 146.2.2.1–146.2.2.6 Modern protocol endpoints

| Requirement         | Implementation evidence                                                                                                                                                                                  | Verification evidence                                                                                        |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| 146.2.2.1–146.2.2.2 | `idp-authn/oauth.ts` publishes OIDC discovery, validates dynamic redirect registration, issues signed ID/access tokens, and implements single-use authorization codes with mandatory RFC 7636 S256 PKCE. | Discovery/unsafe-registration/PKCE rejection tests plus signed access and nonce-bound ID-token verification. |
| 146.2.2.3           | Device grants issue opaque device/user codes, enforce expiry and increasing poll intervals, and remain pending until explicit user approval.                                                             | Pending, slow-down, approval, and successful token tests.                                                    |
| 146.2.2.4           | Token exchange delegates subject-token trust validation, restricts requested scopes to both subject and client grants, and supports audience/confirmation binding.                                       | Audience JWT verification, successful downscope, and elevation rejection.                                    |
| 146.2.2.5           | Opaque refresh tokens rotate on every use and share a family; reuse atomically revokes every descendant.                                                                                                 | Rotation followed by old-token reuse and descendant-family rejection.                                        |
| 146.2.2.6           | `DpopProofVerifier` checks embedded public JWK, signature, age, method, URI, access-token hash, and one-time JTI. Access/refresh tokens carry JWK or RFC 8705 certificate confirmation.                  | Valid DPoP proof/replay tests and mTLS DER-thumbprint `cnf` assertion in a verified access token.            |

### Verified commands

- `pnpm nx run neith-idp-authn:lint`
- `pnpm nx run neith-idp-authn:typecheck`
- `pnpm exec vitest run --config libs/neith/idp-authn/vitest.config.ts libs/neith/idp-authn/src/oauth.spec.ts libs/neith/idp-authn/src/idp-authn.spec.ts --reporter=verbose`

## 146.2.2.7–146.2.2.8 SAML 2.0

`idp-authn/saml.ts` implements an IdP and SP with HTTP-Redirect AuthnRequests,
HTTP-POST responses, SP and IdP initiation, RSA-SHA256 XML signatures, SHA-256
reference digests, persistent NameID, conditions, audience, bearer-subject
confirmation, authentication context, multivalued attributes, and one-time
assertions. Registered ACS/destination allowlists, request signing,
request/response correlation, clock skew, issuer/audience/recipient validation,
and assertion replay defense fail closed.

Verification uses real RSA keys for a complete signed SP-initiated round trip,
an IdP-initiated round trip, multivalued attributes, request/relay-state
tampering, assertion tampering, and replay rejection:

- `pnpm nx run neith-idp-authn:lint`
- `pnpm nx run neith-idp-authn:typecheck`
- `pnpm exec vitest run --config libs/neith/idp-authn/vitest.config.ts libs/neith/idp-authn/src/saml.spec.ts --reporter=verbose`

## 146.2.2.9–146.2.2.15 Enterprise, network, and social protocols

| Requirement | Implementation evidence                                                                                                                                                                                                                                                         | Verification evidence                                                                                                          |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| 146.2.2.9   | `enterprise.ts` emits WS-Federation passive forms and WS-Trust 1.4 RSTR responses containing the configured signed SAML security token, with exact realm/reply allowlisting.                                                                                                    | Passive/active response and open-redirect rejection tests.                                                                     |
| 146.2.2.10  | CAS server issues random, hashed, five-minute, service-bound, single-use tickets and CAS 3 XML with multivalued attributes.                                                                                                                                                     | Successful validation, two-value attribute, and reuse failure tests.                                                           |
| 146.2.2.11  | SPNEGO adapter decodes `Negotiate`, requires RFC 5929 TLS-server-end-point channel binding, delegates native GSS context acceptance, requires a completed principal, and rejects NTLM fallback by default.                                                                      | Kerberos principal/token/channel-binding propagation and NTLM downgrade tests.                                                 |
| 146.2.2.12  | LDAP directory core requires StartTLS/LDAPS for simple bind, normalizes DNs, enforces base/one/sub scopes and size limits, parses equality/presence/AND/OR/NOT filters, and carries AD attributes such as `sAMAccountName`, `userPrincipalName`, `objectClass`, and `memberOf`. | Cleartext-bind denial, LDAPS bind, AD-schema filter, one-level scope, and requested-attribute projection tests.                |
| 146.2.2.13  | RADIUS Access-Request decoder validates framing/attributes, implements RFC 2865 chained-MD5 PAP decryption, rejects unknown clients, and emits Access-Accept/Reject packets with the correct response authenticator.                                                            | Wire packet/password round trip and independently recomputed response authenticator.                                           |
| 146.2.2.14  | `social.ts` brokers Apple, Google, and Microsoft authorization code flows with one-time state/nonce, S256 PKCE, exact HTTPS callback configuration, and injected provider token/JWKS validation.                                                                                | Google flow proves PKCE/state/nonce/exchange and verified external identity; provider support is closed to the declared union. |
| 146.2.2.15  | Conditional passkey service produces resident/discoverable auto-fill requests with `mediation: conditional`, no credential allowlist, required UV, and a CTAP2 authenticator transport boundary.                                                                                | Conditional request shape and CTAP2 assertion delegation test.                                                                 |

### Verified commands

- `pnpm nx run neith-idp-authn:lint`
- `pnpm nx run neith-idp-authn:typecheck`
- `pnpm exec vitest run --config libs/neith/idp-authn/vitest.config.ts libs/neith/idp-authn/src/enterprise.spec.ts libs/neith/idp-authn/src/saml.spec.ts libs/neith/idp-authn/src/oauth.spec.ts libs/neith/idp-authn/src/idp-authn.spec.ts --reporter=dot`

## 146.3 Authorization policy model and decision runtime

| Requirement          | Implementation evidence                                                                                                                                                                                                                                                                       | Verification evidence                                                                                                                                                                   |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 146.3.1.1–146.3.1.3  | `idp-authz/model.ts` maintains tenant-local permission catalogs, hierarchical roles with cycle rejection, subject/group assignments, temporal bounds, and ancestry-aware resource scopes.                                                                                                     | Tests prove inherited group access on a descendant resource, expired-access denial, and cross-tenant rejection.                                                                         |
| 146.3.1.4–146.3.1.7  | `runtime.ts` dispatches CEL, Cedar, and Rego evaluator adapters with versioned compilation caching, merges PIP subject/resource/context data, propagates user/group/role attributes, evaluates device/geo/time/risk rules, and resolves Zanzibar-style relationship tuples with cycle safety. | Adapter/PIP propagation, deny precedence, conditional access, and direct/group relationship tests.                                                                                      |
| 146.3.1.8–146.3.1.10 | Assignment validity windows provide just-in-time access; break-glass roles require bounded assignment plus MFA and justification at use time; conflicting role assignment is rejected by tenant SoD rules.                                                                                    | Expired, break-glass precondition/audit-obligation, and editor/approver conflict tests.                                                                                                 |
| 146.3.2.1–146.3.2.3  | `PolicyDecisionPoint` returns reasoned, versioned decisions; `PolicyInformationPoint` is the dynamic-attribute boundary; `PolicyEnforcementPoint` exposes allow-or-throw enforcement with the full decision attached.                                                                         | Nine authorization tests include a 2,000-decision warm-path benchmark averaging below one millisecond.                                                                                  |
| 146.3.2.4            | `IdentityPolicyAdministrationPanel` adds a tenant/version-oriented PAP workbench to the Oshun policy workspace, with policy inventory and editing, decision simulation and trace, coverage gaps, and immutable rollback controls.                                                             | Component tests cover edit/version, explicit/default deny simulation, and rollback. Playwright covers the complete operator flow, axe accessibility fixture, and compact mobile layout. |
| 146.3.2.5–146.3.2.10 | `PolicyAnalysis` supplies who-can-do-what simulation and catalog coverage gaps. Tenant configuration supports explicit default effects, immutable version history, rollback, and declarative policy assertions.                                                                               | Simulation, orphan-permission detection, default deny, rollback, policy test DSL, and tenant isolation tests.                                                                           |

### Verified commands

- `pnpm nx run neith-idp-authz:typecheck`
- `pnpm nx run neith-idp-authz:lint`
- `pnpm nx run neith-idp-authz:test -- --reporter=verbose`
- `pnpm exec vitest run --config vitest.config.ts src/__tests__/IdentityPolicyAdministrationPanel.test.tsx --reporter=verbose`
  (from `apps/oshun/admin`)
- `pnpm nx run @oshun/admin:typecheck --skip-nx-cache`
- `pnpm nx run @oshun/admin:lint --skip-nx-cache`
- `pnpm exec playwright test e2e/identity-policy-administration-flows.spec.ts --project=chromium --workers=1`
  (2 passed, including automatic axe scans)

## 146.4 External identity federation

| Requirement      | Implementation evidence                                                                                                                                                                                                                                                                                           | Verification evidence                                                                                                                |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| 146.4.1–146.4.2  | `idp-federation/broker.ts` declares all eight social and seven enterprise templates and enforces the correct OIDC, OAuth 2.0, or SAML protocol per built-in provider.                                                                                                                                             | Catalog coverage asserts every named provider and distinguishes OIDC providers from OAuth 2.0 user-info providers.                   |
| 146.4.3–146.4.4  | `FederationProtocolGateway` binds generic SAML responses to issuer, audience, request ID, and age; binds OIDC tokens to issuer, audience, JWKS URI, nonce, and age; and binds OAuth 2.0 user-info to configured HTTPS endpoints and one-time state validation through injected cryptographic/verifier boundaries. | Exact verifier-input tests cover OIDC, SAML, OAuth 2.0, state mismatch, and locally authoritative provider identity.                 |
| 146.4.5–146.4.7  | `FederationBroker` JIT-provisions one stable tenant/provider/subject account after assertion-age and verified-email checks. `AttributeMapper` safely resolves nested scalar claims with declared transforms and required fields. Exact normalized email-domain routes select the home realm.                      | JIT stability, mapping success/fail-closed behavior, exact realm selection, and tenant isolation tests.                              |
| 146.4.8–146.4.10 | Explicit relying-tenant trust enables identity-hub brokering. Single-use, tenant/email-bound invitations create expiring B2B guests. External members carry hard expiry and re-verification deadlines.                                                                                                            | Untrusted-hub denial, trusted hub login, invitation mismatch/reuse denial, guest projection, re-verification, and hard-expiry tests. |

### Verified commands

- `pnpm nx run neith-idp-federation:typecheck --skip-nx-cache`
- `pnpm nx run neith-idp-federation:lint --skip-nx-cache`
- `pnpm nx run neith-idp-federation:test --skip-nx-cache -- --reporter=verbose`
  (9 passed)
