Skip to content

Documentation

Enterprise Identity & Audit-Logging Inventory

Verified inventory of SAML, OIDC, SCIM, WebAuthn and audit-logging behaviour in the source on `next` (post-PR #566). Every row carries path:line; unimplemented capabilities are recorded as 'not found' with the search that proves it.

11/11/2026
27 min read Edit on GitHub

Status: current audit of next. The baseline snapshot was efa57c55e on the (now deleted) fix/enterprise-readiness-20261110 branch; PR #566 is merged and every row below was re-verified against the current tree, so a reference that moved cites the symbol. Per-finding status is listed below — entries marked fixed are no longer current defects and must not be read as open risks. Rows without a reachable call site keep their not found result and the search behind it. Re-verified 2026-11-11 on the current tree: the status and evidence of every row this pass touched were checked against the code again; references that moved cite the symbol.

Finding Status Evidence
SCIM active:false did not deprovision (wrote isActive; auth enforces blocked) Fixed — PATCH, PUT and POST now set isActive and blocked; non-boolean values are rejected with 400 parseScimActive() (src/utils/scim-utils.ts:167), applyScimPatchOps (:180, :199-205), PUT (handlers/scim.ts:229-233), POST (:164-190); tests/unit/api/scim-deprovisioning.test.ts, tests/unit/api/scim-put-endpoint.test.ts
IdP-driven logout deleted SSO metadata only; the session stayed valid Fixed — all three OIDC paths now call terminateSessionAndMetadata() terminateSessionAndMetadata() (src/databases/auth/sso-session.ts:487); tests/unit/auth/sso-logout-revocation.test.ts
IdP-driven logout could only find sessions created on the same worker (ssoSessionMetadata is a process-local map) Fixed — every logout lookup now resolves through a distributed index + directory Directory sso:directory:<sessionId> and buckets sso:index:{sid,sub,nameid}:<value> written by setSsoSessionMetadata() (sso-session.ts:535, helpers :215-297), read by collectIndexedSsoSessions() (:299), used by front-channel (:1247), back-channel (:1316) and findSamlSessions() (:601). resetSsoSessions() (:655) exists so tests can model a second node. Cross-node tests: tests/unit/auth/sso-distributed-logout.test.ts (8: two users, two sessions per user, two tenants sharing a provider id, SAML NameID, index pruning, cache-down fallback).
Legacy /login/oauth callback does not verify state (login CSRF) — and the OIDC login start accepted any redirect_uri Partially fixed in PR #566 (commit 5dafc3a5d): redirect_uri is same-origin only handleOidcLoginStart in handlers/auth.ts; tests/unit/auth/oidc-login-redirect.test.ts (3 of 4 cases fail on the old handler). The legacy /login/oauth state check is still open.
Audit chain verifier read a hash nothing wrote; buffered writes lost rows on crash/outage Fixed — writer and verifier share one canonical payload; fork guard + tail checkpoint, with limits canonicalAuditPayload() / computeChainHash() (src/services/audit-chain.ts:224, :246); auditChainService.append() (:299); chainScope = tenantId ?? "__global__" (chainHashScope, :55); unique (chainScope, previousHash) index (system-schema-spec.ts:1350-1367); re-chain after a rejected fork (audit-service.ts:38, :352-400); checkpoint (audit-chain.ts:432-483, verified :628-660). Tests: tests/unit/services/audit-chain-writer.test.ts, tests/integration/databases/audit-chain-integrity.test.ts, audit-chain-fork-guard.test.ts. Limits: the DB checkpoint is written after the batch and audit rows are not in the business transaction. An independent anchor is now written outside the database (AUDIT_ANCHOR_PATH → audit-anchor-<scope>.json, atomic temp→rename) and compared by verifyChain().anchor, so deleting the tail and the DB checkpoint row no longer verifies; anchor write failures are counted (getAnchorStatus()) and logged as ANCHOR_WRITE_FAILED. A failed checkpoint write is no longer silent: it is counted per tenant, logged at error level (CHECKPOINT_WRITE_FAILED), reported by getCheckpointStatus() (src/services/audit-chain.ts) and returned by the admin verification as checkpointPersistence (tests/unit/services/audit-chain-checkpoint-health.test.ts); it is still not retried, and the file fallback is not the verified ledger.
OIDC redirect_uri unvalidated at login; no at_hash; SAML signature checks are library-side and mocked in tests Partially fixed — redirect_uri same-origin; SAML IdP-initiated + SLO shipped; OIDC logout now scoped redirect_uri same-origin http(s) only; SAML_ALLOW_IDP_INITIATED (saml-auth.ts:120), handleSAMLACS (:585), handleSAMLLogoutRequest (:773), SLO route (handlers/auth.ts:1667); OIDC sid/sub stored at login (handlers/auth.ts:900-913) and matched on logout (sso-session.ts:1247 front, :1316 back); tests/unit/auth/saml-slo.test.ts, sso-logout-scoping.test.ts. Still open: at_hash validation, a signed LogoutResponse requires SAML_SP_PRIVATE_KEY, and SAML logout session lookup is distributed (local map + shared index).

This page records what the source does, not what a settings screen or a prose doc promises. It was built by reading the tree on next. Every statement below is a source citation, and every “not found” is paired with the exact search that returned nothing.

Status vocabulary:

Status Meaning
Implemented + tested Code path exists and a named test exercises the behaviour described.
Implemented, no test Code path exists; no test asserts it.
Partial Code exists but a named part of the contract (validation, revocation, persistence) is absent.
Not found No code path exists. The search that proves it is given.
Important

The repository has an HTTP-mutation log and a separate database audit service. They are not the same thing and neither is transactional. Read §3 before relying on either for compliance evidence.


1. Identity protocols

1.1 Protocol capability table

Capability Status Implementation (file:line) Validation enforced Existing tests Gap
SAML 2.0 SP (SP-initiated) Implemented + tested (state/InResponseTo), signature delegated and untested Route dispatch src/routes/api/[...path]/handlers/auth.ts:1652-1745 (handleSAMLRoutes; case "acs" :1661, login :1697, config :1733); engine src/databases/auth/saml-auth.ts (handleSAMLACS :585, processSAMLResponse :468, getSAMLConfig :130); library @node-saml/node-saml saml-auth.ts:12 (^5.2.0, package.json:210) CSRF state bound to a 5-min HttpOnly cookie; InResponseTo compared to a one-time cookie (assertInResponseTo); response processed by validatePostResponseAsync (saml-auth.ts:491) with idpCert (buildSAMLOptions :177), wantAssertionsSigned: true (:153, :178) and signatureAlgorithm: "sha256" (:179); audience falls back to the SP issuer in node-saml; assertion NotOnOrAfter enforced by the library tests/unit/api/saml.test.ts:81-259 (config gate, state mismatch 403, missing request-id cookie 403, InResponseTo mismatch 403); tests/unit/auth/sso/saml.test.ts:125-259 (metadata parse, XXE/DOCTYPE reject, tenant binding, InResponseTo); tests/unit/auth/sso/saml-sso-federation.test.ts:30-48 No test performs real XML-DSig verification: the library is mocked at tests/unit/api/saml.test.ts:13 and tests/unit/auth/sso/saml.test.ts:59. A broken signature path, an expired assertion, or a wrong audience would not fail CI.
SAML IdP-initiated Implemented + tested (opt-in) isIdpInitiatedLoginAllowed() src/databases/auth/saml-auth.ts:120; handleSAMLACS :585: an unsolicited response is accepted only when SAML_ALLOW_IDP_INITIATED (or its samlAllowIdpInitiated alias) is on; a response carrying InResponseTo is never treated as unsolicited (:468-483) Default is off (fail closed); enabling it is an explicit operator decision. CSRF flow cookies still win when present (:617-627). tests/unit/auth/saml-slo.test.ts:115-215 (accept when on, alias, reject when off, reject InResponseTo, reject foreign flow cookie) Opt-in only; an unsolicited assertion is not bound to a browser that started a login, so it is not enabled by default.
SAML Single Logout (SLO) Implemented + tested (IdP-initiated request + SP-initiated response) handleSAMLLogoutRequest() src/databases/auth/saml-auth.ts:773; handleSAMLSLOEvent() :981 (GET Redirect + POST binding); route case "slo" src/routes/api/[...path]/handlers/auth.ts:1667-1669 node-saml validates the LogoutRequest signature/issuer/NotBefore before anything is destroyed; sessions are located by NameID (+ SessionIndex when present) and removed via terminateSessionAndMetadata() (:829-833); a request matching no session still succeeds (idempotent). tests/unit/auth/saml-slo.test.ts:217-430 (bad signature destroys nothing, session + metadata deleted, missing/foreign SessionIndex, no match, SP-initiated request, both bindings) findSamlSessions() (sso-session.ts:601) resolves candidates through collectIndexedSsoSessions() (:299) — the local map plus the shared sso:index:nameid:<NameID> bucket — so a logout handled by another node still finds the session (tests/unit/auth/sso-distributed-logout.test.ts). A signed LogoutResponse requires SAML_SP_PRIVATE_KEY.
OpenID Connect (authorization code + PKCE) Implemented + tested Start handlers/auth.ts:626-674; callback :679-911; engine src/databases/auth/sso-session.ts:850-951; JWT verify :737-845 state cookie compare handlers/auth.ts:704-706; nonce compare :731-737; PKCE S256 :640-642,664 + sso-session.ts:105-112; exact iss sso-session.ts:756-758; asymmetric-alg allowlist :761-764; exp :768-773; nbf :774-781; iat :782-789; aud contains clientId :795-802; azp :803-805; strict kid select :820-828; JWKS mandatory (fail closed) :811-816; signature :836-839; discovery/JWKS fetch egress-guarded :551,611,914 tests/unit/auth/sso/oidc-jwt-verification.test.ts:141-345 (RS256, ES256, PS256, expired, aud, azp, HS256 reject, missing kid, wrong key, nbf, iat); tests/unit/auth/sso/oidc-pkce-jit.test.ts:19-172; tests/unit/auth/sso-session.test.ts:328-416; tests/integration/auth/oidc-live.test.ts:154-340 (live server: PKCE mismatch, wrong redirect URI, tampered signature) at_hash / c_hash are not checked: grep -rn 'at_hash\|c_hash' src/ → 0 hits. Not required for the code flow, but it means an id_token is never bound to the access token.
OIDC redirect_uri validation at login Implemented (same-origin) handleOidcLoginStart handlers/auth.ts:640-655: the requested URI must be a valid http(s) URL with the same origin as the request, and it is then stored in the authorize request and the state cookie A foreign origin or non-http(s) scheme is rejected with 400 (:644-655). This is not a per-client registered-URI allowlist: the post-logout allowlist (sso-session.ts, allowedRedirectUris) is not consulted here. tests/unit/auth/oidc-login-redirect.test.ts (3 of 4 cases fail on the old handler) OIDC Core 3.1.2.3 asks the RP to require a pre-registered redirect URI; same-origin is a meaningful narrowing (no open redirect to a foreign host) but not that check. The code exchange reuses the cookie value, so PKCE still protects the code.
OIDC RP-initiated logout Implemented + tested handlers/auth.ts:540-620; sso-session.ts:450-527 Redirect allowlist sso-session.ts:389-416; local session terminated handlers/auth.ts:578-580 tests/unit/auth/sso-session.test.ts:363-416 —
OIDC back-channel logout Implemented + tested (session-terminating, scoped) handleBackChannelLogout() src/databases/auth/sso-session.ts:1316; route src/routes/api/[...path]/handlers/auth.ts:192-193; sid/sub recorded at login :900-913 iss; event claim; iat ≤ 300 s; nonce forbidden; aud; JWKS signature. The token’s sid narrows the match, falling back to sub only when no sid is present; a token that names no local session terminates nothing (:1199-1226). tests/unit/auth/sso-logout-scoping.test.ts:154-229 (sub-only, sid preferred, no match); tests/integration/auth/oidc-live.test.ts:292-340 The session store walked is in-process, so a logout delivered to another node does not terminate sessions created here. Session validation now reads the distributed user/tenant/global markers (handle-authentication.ts:305-321, :586-592), but a single-session logout publishes none of them, so a peer’s warm LRU entry survives until it re-validates.
OIDC front-channel logout Implemented + tested (session-terminating, scoped) handleFrontChannelLogout() src/databases/auth/sso-session.ts:1247; route src/routes/api/[...path]/handlers/auth.ts:190-191; oidcSid recorded at login :900-911 Matches the OP sid against the session’s stored oidcSid; an unmatched (or absent) sid terminates nothing, and the response is still 200 so the OP iframe completes (:1061-1068). tests/unit/auth/sso-logout-scoping.test.ts:123-154 (matching sid only; unmatched terminates nothing) The endpoint is unauthenticated (the message is unsigned by spec) and walks the in-process session map, so a logout on another node can miss sessions here.
SCIM 2.0 (/api/scim/v2) Implemented + tested (CRUD + deprovisioning) Dispatcher src/routes/api/[...path]/handlers/scim.ts:34-79; map +server.ts:70,108; Users scim.ts:124-277; Groups :220-277; Bulk :288-432 Bearer token looked up hashed (src/databases/core/relational-auth.ts:1635-1652 — expiry and consumed filtered in the query), type === "scim", not blocked, not expired src/utils/scim-utils.ts:273-282; tenant taken from the token scim.ts:50; admin-session fallback scim-utils.ts:294-300. active:false sets both isActive and blocked on PATCH/PUT/POST; non-boolean values are rejected 400 (parseScimActive, scim-utils.ts:167). tests/unit/api/scim.test.ts:113-287; scim-deprovisioning.test.ts; scim-put-endpoint.test.ts; tests/unit/services/scim.test.ts:25-249 active:false now cuts access because blocked is what authentication reads (handle-authentication.ts), but SCIM still deletes no session row, so an already-issued session survives its expiry window. No audit record is written. externalId is stored but never used for lookup, so an IdP rename can create a second user (dedupe is by email only).
WebAuthn / passkeys Implemented + tested src/databases/auth/webauthn/webauthn-service.ts:213-302; login src/routes/login/auth.remote.ts:1025-1165 Challenge equality + type webauthn-service.ts:174-187; origin :188-190; RP-ID hash :98-101,265-267; assertion signature :274-282; user-present flag :288; sign-counter replay :290-292; challenge single-use + 300 s TTL :20-46 tests/unit/auth/webauthn/webauthn-ceremony.test.ts:73-88 (foreign origin, no-UP flag, happy path); webauthn-attestation.test.ts; webauthn-cbor.test.ts User verification is not required (userVerification: "preferred" :119,148; only the UP bit is asserted :288), so a bare touch satisfies a passkey login. Attestation is not verified (attestation: "none" :117; credentialDeviceType hard-coded "multi-device" :243). The login path emits no audit record, is not rate-limited, and creates a session without tenantId (auth.remote.ts:1144-1147).
Legacy Google / GitHub OAuth (/login/oauth) Implemented, state unverified src/routes/login/oauth/+page.server.ts:390-620; state signing src/databases/auth/google-auth.ts:72-112; redirect URI google-auth.ts:22-31 Google branch exchanges the code server-side +page.server.ts:538-566; GitHub branch :480-525 tests/unit/auth/google-auth.test.ts:54-96 tests the signer as a helper; tests/e2e/routes/login/oauth.spec.ts:44-151 covers the mock happy path The callback never calls verifyOAuthState: it reads state and decodeURIComponents it into the registration token (+page.server.ts:410-418). The verifier exists (google-auth.ts:83-112, constant-time at :107) and is used on the other callback (src/routes/login/+page.server.ts:357-361), but getOAuthRedirectUri() points the OAuth client at /login/oauth (google-auth.ts:26-30, consumed at +page.server.ts:539). email_verified is never inspected: grep -rn 'email_verified\|verified_email' src/ → 0 hits. Account is selected by email alone (+page.server.ts:196), with no tenant argument.
LDAP / Active Directory bind Not found — — — grep -rn -i 'ldap' src/ --include=*.ts --include=*.svelte --include=*.mdx → 12 hits across four files, all LDAP-injection scanners (src/services/security/threat-scan.ts:592-637, src/services/security/auth-guard.ts:83-84, src/services/security/response-service.ts:462-463, src/services/security/types.ts:37). No bind, no directory client, no ldapjs/ldapts dependency in package.json.

1.2 Account linking and identity collision

Capability Status Implementation (file:line) Validation enforced Existing tests Gap
SAML identity binding Partial Lookup by email + tenant src/databases/auth/saml-auth.ts:441-446; JIT create :448-461 Tenant scoping on the lookup and the insert :440,456 tests/unit/auth/sso/saml.test.ts:210-223 (tenant binding) The stable subject (NameID, samlId) is never persisted or matched. samlId exists in the model (src/databases/auth/types.ts:66) and getUserBySamlId exists (auth-service.ts:237-243), but the JIT insert at saml-auth.ts:449-457 sets no samlId and the lookup at :441 uses email. Renaming a user in the IdP orphans the local account; an IdP that asserts admin@… logs into the existing local admin. No domain allowlist, no SAML_JIT_PROVISIONING role mapping (role is hard-coded "user" :454, unlike OIDC handlers/auth.ts:750).
OIDC identity binding Partial Lookup by email + tenant handlers/auth.ts:752; JIT :760-787; SSO metadata sso-session.ts:328-347 Tenant scoping :752; role mapping resolveJitRole :750, sso-session.ts:114-137 tests/unit/auth/sso/oidc-pkce-jit.test.ts:46-134 (role mapping only) Account linking still uses email only: the id token’s sub is now persisted as oidcSubject on the session metadata (handlers/auth.ts:900-913) but is used for logout scoping, not for lookup. Linking is therefore still email-based, so a subject change in the IdP re-links by whatever email it now asserts.
Legacy OAuth linking Partial +page.server.ts:196 (auth.checkUser({ email }), no tenant), :204-241 (existing user → login) None beyond the TLS-verified userinfo response e2e mock only tests/e2e/routes/login/oauth.spec.ts:81-151 First registered user becomes admin (+page.server.ts:245-270); the same email arriving from GitHub (:518-525) or Google is linked without an email_verified check.
Collision handling on create Partial SCIM scim.ts:159-160 (409 on duplicate email); OIDC handlers/auth.ts:784-786 (500 on unique-constraint failure) Email uniqueness only tests/unit/api/scim.test.ts:140-172 No cross-provider collision policy: two IdPs asserting one email both authenticate into the same row, and externalId/sub are not consulted.

1.3 Session termination and revocation

Capability Status Implementation (file:line) Validation enforced Existing tests Gap
Local logout Implemented + tested handlers/auth.ts:512-528; src/services/sdk/namespaces/auth-namespace.ts:634-647 Row deleted via the DB auth adapter auth-namespace.ts:646; SSO metadata removed :640-641; cookie cleared with matching attributes handlers/auth.ts:524, src/utils/security/session-cookie.ts tests/unit/routes/cookie-logout.test.ts:9-36 Logout terminates one session. invalidateAllUserSessions is not called on this path: grep -rn 'invalidateAllUserSessions' src/ → 15 hits, none in handleLogout. Other devices stay signed in by design.
Global revocation primitive Implemented + tested src/databases/auth/auth-service.ts:1191-1227 (publish revocation epoch, drop L0/L1/L2) Epoch + distributed marker :1198-1201; DB sweep :1224. Read path: warm LRU handle-authentication.ts:305-321 (call :586-592); store session-manager.ts:53-64 tests/unit/auth/revocation-epoch.test.ts; revocation-read-path.test.ts (8); revocation-distributed.test.ts (6) publishUserRevocation() is wired to password change (src/utils/server/user-attribute-update.server.ts:188-198 → auth-service.ts:1198), OIDC role sync (handlers/auth.ts:827) and SDK attribute updates (auth-namespace.ts:416). The hook’s session:<tenant>:<id> snapshot branch now runs the shared gate (handle-authentication.ts:709-726, gate :715) and the warm-LRU path calls it at :613, so a user/tenant/global marker is honoured on every session read. Remaining limits: publishGlobalRevocation()/publishTenantRevocation() still have no production caller (nothing in src/ triggers a tenant lockout or “log out everywhere” yet); the session store’s get/getSessionData branches check tenant/global but not the distributed user marker; the memo admits up to 5 s of staleness (revocation-publish.server.ts:34).
Deprovisioning: block / delete user Implemented, no direct test auth-namespace.ts:848-917 (batchAction delete/block/unblock) Cache purges per affected user :884-913; enforcement is per-request in src/hooks/handle-authentication.ts:704-707, :763-766 No test calls cms.auth.batchAction; grep -rn 'batchAction' tests → 6 textual hits (mock stubs/comments) Relational deleteUsers removes session + token rows in one transaction (src/databases/core/relational-auth.ts:795-830); Mongo deleteUsers deletes the user docs only (src/databases/mongodb/auth-user.ts:391-414), leaving session rows. block/unblock purge caches only (:884-913) and depend on the DB blocked check on the next request. publishUserRevocation is not called by batchAction. No audit record (grep -n -i audit auth-namespace.ts → role paths :713, :753, :770, :808 only).
Deprovisioning: SCIM Implemented, still no session kill scim.ts:164-190 (POST), :229-233 (PUT), scim-utils.ts:199-205 (PATCH) isActive: false and blocked: true, which authentication enforces; non-boolean rejected 400 tests/unit/api/scim-deprovisioning.test.ts; scim-put-endpoint.test.ts No session revocation and no audit: an already-issued session survives until expiry even though the account is now blocked.
Deprovisioning: IdP-initiated Implemented (distributed) SAML SLO saml-auth.ts:773; OIDC front sso-session.ts:1247; back :1316 All three call terminateSessionAndMetadata(), which deletes the session row; candidates come from the local map plus the distributed index (collectIndexedSsoSessions, :299) tests/unit/auth/saml-slo.test.ts; sso-logout-scoping.test.ts; sso-logout-revocation.test.ts; sso-distributed-logout.test.ts Cross-node lookup is solved; two limits remain. A single-session logout publishes no revocation marker, so a peer’s warm session cache entry is only dropped when it re-validates. And the index is a cache write: when the cache is unavailable the lookup silently degrades to the local map (logged at debug, never thrown).

2. Where the identity code is NOT wired to audit

The audit subsystem is reachable only by explicit calls. These four modules contain zero audit references (case-insensitive grep -n -i 'audit' on each file returned no lines):

Module Consequence
src/routes/api/[...path]/handlers/auth.ts API login, logout, OIDC login/logout, SAML SSO, 2FA, role updates are unaudited.
src/routes/api/[...path]/handlers/scim.ts Every SCIM provision/deprovision/deprovision-failure is unaudited.
src/databases/auth/saml-auth.ts SSO authentication, JIT provisioning and IdP reconfiguration are unaudited.
src/databases/auth/sso-session.ts Provider configuration changes, RP-initiated, front- and back-channel logout are unaudited.

The only identity audit call sites in the tree are:

  • form login — src/routes/login/auth.remote.ts:648-659 (fire-and-forget, .catch() swallows the failure)
  • role matrix write — src/services/sdk/namespaces/auth-namespace.ts:808-816
  • individual role create/update — auth-namespace.ts:770-784
  • GDPR erasure — src/services/security/gdpr-service.ts:241-248

src/routes/login/auth.remote.ts:1081-1165 (passkey login) contains no audit call either.


3. Audit logging

3.1 What exists (two independent pipelines)

Capability Status Implementation (file:line) Validation enforced Existing tests Gap
HTTP mutation log (pipeline 1) Implemented + tested, not persisted src/hooks/handle-audit-logging.ts:153-189; queue :44-45; drain :64-110 Fields: timestamp, method, path, status, userId, tenantId, ip, durationMs, success, error :31-42,137-150; actor = locals.user._id ?? "anonymous" :131 tests/unit/hooks/audit-logging.test.ts:38-199 (success entry, failure entry, test-bypass, env-disable, non-API/read pass-through, thrown-status capture) Successful mutations are only emitted at debug level (:80-83); production runs at error, so successes are discarded. Nothing is written to a database — the sink is logger (:80-86); only a leaf hash feeds the in-memory rollingMerkleAccumulator (:88-94, rolling-merkle.ts, never persisted). The ring buffer drops the oldest record past 2048 entries (:44,104-107). No target object, no before/after, no actor email.
Audit records (pipeline 2) Implemented + tested src/services/security/audit-service.ts — buffer (:185), log() (:671), _flushOnce() (:329), insertBatch() (:476) Full field set on AuditLogEntry; chainScope set from chainHashScope() (:710); secret redaction (redactSensitiveDetails, :54, applied :708) tests/unit/services/audit-service-redaction.test.ts:22-96; tests/unit/services/audit-log-microbatch.test.ts:16-85; tests/unit/security/audit-chain-verification.test.ts:18-149; tests/unit/security/audit-ledger-integrity.test.ts:13-109; tests/unit/auth/roles/rbac-audit-trail.test.ts:11-17 Atomicity: none. insertBatch() calls a standalone crud.insertMany (:476-495) with no transaction, although the adapter exposes one. Durability by default is a 5 s flush / 15 ms micro-batch (:202-203) and the default flag is chainSync: false (src/utils/security/audit-flags.ts:44).
Durability on DB outage Partial _flushOnce catch audit-service.ts:405-428; file sink :572-575 Buffer restored and capped at maxTotalBuffer = 200 (:201, :421-426) tests/unit/services/audit-log-microbatch.test.ts:85 (500 concurrent writes, no drop — with a healthy mock DB) On a failed write the batch is appended to logs/audit.log and re-buffered; once the restore exceeds 200 entries the excess is dropped with only a logger.warn (recordDroppedEntries, :236, :421-426). Neither sink fsyncs.
Durability on crash Partial log() returns after enqueue unless chainSync (audit-service.ts:745-760) — none A SIGKILL/OOM between push (:745) and the flush loses every buffered entry — up to maxBufferSize = 50 on the healthy path (:200, :770) and maxTotalBuffer = 200 when flushes are failing. AUDIT_CHAIN_SYNC=true closes this window but is off by default (audit-flags.ts:44).
Tamper-evidence (writes) Implemented + tested (with limits) AuditChainService.append() (src/services/audit-chain.ts:299): reads the tenant head under a per-tenant in-process lock, hashes with computeChainHash() (:246) over canonicalAuditPayload() (:224), writes chainScope = tenantId ?? "__global__" (:55). audit-service.ts:721-731 persists chainHash (+ hash alias). One SHA-256 per entry; previousHash comes from the DB head (cached per tenant), not process genesis. tests/unit/services/audit-chain-writer.test.ts; tests/integration/databases/audit-chain-integrity.test.ts; audit-chain-fork-guard.test.ts withTenantLock serialises writers inside one process. Multi-process forks are rejected by the unique (chainScope, previousHash) index (system-schema-spec.ts:1350-1367; Mongo partial index in mongodb/adapter-core.ts), and the flush re-chains onto the winning head (3 tries). Pre-existing unchained rows stay unverifiable.
Tamper-evidence (verification) Implemented + tested src/services/audit-chain.ts:502-680 (verifyChain); exposed via src/routes/(app)/audit-history.remote.ts Writer and verifier call the same canonicalAuditPayload()/computeChainHash() — no parallel field list. verifyChain also checks the tail checkpoint (:628-660) and accepts second-precision timestamps for legacy rows, counted as legacySecondPrecisionEntries (:118, :621). tests/integration/databases/audit-chain-integrity.test.ts (7 tests, 4 adapters); tests/unit/services/audit-chain-writer.test.ts Truncation is signalled by the checkpoint head hash (counts are per-writer lower bounds) when the head is no longer in the chain. Limitation: the DB checkpoint itself is not an independent anchor — but the out-of-DB anchor (AUDIT_ANCHOR_PATH) is compared on every verification (#, above), so deleting the tail and the DB checkpoint row is now detected as long as the anchor file survives. A checkpoint that could not be written is reported as checkpointPersistence (unhealthy, with the last error) instead of the row silently ageing; it is not retried. Pinned by tests/unit/services/audit-chain-checkpoint-health.test.ts.
Field mapping to schema Partial Service still writes actorIp and a hash alias (audit-service.ts:700-731); schema declares ipAddress (system-schema-spec.ts:1277), chainHash (:1298) and chainScope (:1305); sessionId, userAgent, correlationId, errorDetails are schema columns the service does not set — none No shared mapping layer exists between AuditLogEntry and the table: actorIp and hash have no declared column of the same name, so whether the IP survives a relational insert depends on adapter behaviour rather than a schema contract. The chain fields (previousHash, chainHash, chainScope) are written and projected correctly.
Immutability vs. a normal admin Partial — no guard No append-only enforcement found for auditLogs; the only collection-level protection is the plugin sandbox src/plugins/sandbox.ts:52-60,93 — none Two internal paths delete audit rows: GDPR erasure gdpr-service.ts:202-207 (deleteMany("audit_logs", { actorId: userId })) and tenant deletion src/services/core/tenant-service.ts:119-126. No DB trigger protects the table — the only triggers in the schema are on content_nodes (system-schema-spec.ts:1730-1737). Search for an immutability guard: grep -rn 'immutable\|appendOnly\|protectedCollections' src/ --include=*.ts → hits are HTTP cache headers, widget definitions and comments only.
Audit suppression switch Implemented, no test audit-flags.ts:52-84 (DISABLE_AUDIT_LOGS, AUDIT_CHAIN_SYNC resolved from env or DB settings, 5 s TTL) — tests/unit/hooks/audit-logging.test.ts:113 covers the env path only Whoever can write those system-settings keys can silence both pipelines at runtime without a deploy, and the resolution module performs no permission check of its own (audit-flags.ts:69-83).
Read access to audit records Partial handlers/dashboard.ts:591-600 (case "audit"), :548-589 (case "logs"); src/routes/(app)/audit-history.remote.ts:9-46 Dashboard gate is dashboard:read or system:dashboard (+server.ts:346-367) tests/unit/api/dashboard-license-gate.test.ts (license only) Not admin-only: every seeded editor role carries system:dashboard (+server.ts:346-350). audit-history.remote.ts:23 uses getAuthenticatedUser, not an admin guard, and returns rows for any targetId in the tenant (:27-31).
Event coverage Partial Enum audit-service.ts:55-84 — — Emitted: USER_LOGIN (form path only), ROLE_MUTATED, ROLE_DELETED, USER_ROLE_CHANGED, DATA_DELETION, DATA_EXPORT, UNAUTHORIZED_ACCESS (1 hit each). Never emitted: USER_LOGOUT, USER_CREATED, USER_DELETED, USER_UPDATED, PASSWORD_CHANGE, USER_LOGIN_FAILED, PRIVILEGE_ESCALATION, API_KEY_CREATED — grep -rn "AuditEventType.<NAME>" src/ outside audit-service.ts returns 0 for each of those eight.
Per-row data audit Implemented, off by default audit-service.ts:281-347 (registerHook) — none Guarded by AUDIT_INSERT_HOOK !== "true" (:317-321), so by default a content insert writes no audit row; the only coverage is the non-persistent HTTP log (§3.1 row 1).

Documented limitations of the chained ledger (visible on purpose — do not read the chain as a complete evidence store):

  • The checkpoint shares the audit database. systemPreferences is tenant-scoped KV in the same database as audit_logs. An actor who deletes the tail and the checkpoint row leaves a shorter chain that still verifies; evasion needs a store outside the CMS database (see the roadmap’s external-anchoring candidate).
  • The checkpoint is written after the batch, not with it. A checkpoint failure only warns (AuditChainService.commitCheckpoint, audit-chain.ts:462-483); the entries are already durable, so this under-counts rather than losing data, and verification treats extra entries as a normal append.
  • Audit rows are not committed in the business transaction. The audit insert is a standalone crud.insertMany (audit-service.ts:476-495), sequenced after the mutation; a crash between the two can leave a business change without its audit row.
  • The file fallback is not the verified ledger. When the audit table is unavailable the batch is appended to logs/audit.log (audit-service.ts:569-575) and counted as dropped from the chain; those entries can never be verified or linked.

3.2 The outbox is not an outbox

src/services/outbox/outbox-service.ts:18-24 states it directly: “This is NOT a transactional outbox — there is no atomic same-transaction write… a crash between the content commit and the queue flush can drop the delivery intent.” Enqueue is a synchronous in-memory push with a 25 ms debounce (:27-28,506-521). Audit records do not use it at all; they use the separate buffer in audit-service.ts.

Net answer to “is the audit write atomic with the business change?” No. Three independent writes exist — the business row, the buffered audit row (audit-service.ts:233-238), the buffered outbox event (outbox-service.ts:213) — sequenced after the fact, each with its own failure mode.


4. The five highest-value tests for data safety

Each was written as a failing-then-passing case. T1, T2 and T4 have since shipped — their “expected” behaviour is now the implementation and is pinned by the named tests. T3 and T5 remain open.

T1 — Deprovisioning must kill the session, not just the metadata

  • Precondition: OIDC provider configured with a JWKS; user u1 with one active session sess-1 (setSsoSessionMetadata("sess-1", {provider: "p1"}, "tenant-a")); db.auth.validateSession("sess-1") returns u1.
  • Action: handleBackChannelLogout(validLogoutToken) then re-validate sess-1; repeat the same sequence with handleFrontChannelLogout(issuer, sid) for the front-channel endpoint.
  • Expected behaviour (now implemented): terminateSessionAndMetadata() deletes the session row through the adapter, invalidates the in-process session cache and drops the SSO metadata, so validateSession("sess-1") returns null and the next API call is 401. Pinned by tests/unit/auth/sso-logout-revocation.test.ts and tests/unit/auth/sso-logout-scoping.test.ts.
  • Residual gap: the lookup is distributed (local map + the shared sso:index/sso:directory written at login, sso-session.ts:215-297, read by collectIndexedSsoSessions() :299), so a logout delivered to another worker still finds the session — pinned by tests/unit/auth/sso-distributed-logout.test.ts (including two tenants that share a provider id). What remains: the logout publishes no revocation marker, so a peer’s warm session cache entry is only dropped when it re-validates; and with the shared cache down the index read degrades to the local map instead of failing the logout.

T2 — active: false from SCIM must lock the account

  • Precondition: SCIM bearer token for tenant-a; user u2 created through SCIM; one live session and a valid session cookie.
  • Action: PATCH /api/scim/v2/Users/u2 with {Operations:[{op:"replace", path:"active", value:false}]}, then call an authenticated write endpoint with the existing cookie.
  • Expected behaviour (now implemented): applyScimPatchOps writes isActive: false and blocked: true (src/utils/scim-utils.ts:199-205), which is what the per-request gate reads (handle-authentication.ts), so the next write is rejected; non-boolean active values are rejected with 400 (parseScimActive, :167). Pinned by tests/unit/api/scim-deprovisioning.test.ts.
  • Residual gap: the session row is not deleted, so an already-issued session survives until expiry (the block is enforced on the next re-validation, not by revocation).

T3 — Audit records must survive a mid-request crash

  • Precondition: AUDIT_CHAIN_SYNC unset (default false, audit-flags.ts:44); DB adapter with a settable failNextInsert; audit table empty.
  • Action: call auditService.log(...) for a privileged action (e.g. USER_ROLE_CHANGED), do not await a flush, and simulate process death (vi.resetModules() after clearing the module registry, or spawn a child that process.exit(1)s immediately after log() resolves); then boot a fresh service and query the table.
  • Expected failure mode (today): log() resolves as soon as the entry is in the in-memory array (audit-service.ts:421), so the record is absent after the restart while the API reported success. The test must assert either the row exists, or that log() rejected — never “success, no row”.
  • Companion assertion in the same test: with the DB insert failing, after 201 queued entries the oldest are dropped silently (:263-267) — assert an explicit, observable drop counter rather than a logger.warn.

T4 — The verifier must fail only when the chain is actually broken

  • Precondition: write three entries through auditService.log with AUDIT_CHAIN_SYNC=true; no tampering.
  • Action: call auditChainService.verifyChain(tenantId) — the exact call the UI makes (audit-history.remote.ts:54).
  • Expected behaviour (now implemented): a clean chain verifies. Writer and verifier share canonicalAuditPayload()/computeChainHash(), so the hash the service writes is the one the verifier recomputes. Deleting a middle row is detected by the linkage check, and deleting the tail is detected by the per-tenant checkpoint (head hash no longer present). Pinned by tests/integration/databases/audit-chain-integrity.test.ts (7 tests, all four adapters).
  • Remaining limit: the checkpoint lives in the same database (systemPreferences), so an actor who deletes the tail and the checkpoint row evades truncation detection.

T5 — Auditing must not be switchable off by the actor it records

  • Precondition: admin session; DISABLE_AUDIT_LOGS absent; one existing audit row.
  • Action: as an admin, write the value true to the DISABLE_AUDIT_LOGS system setting, perform a privileged mutation (role change + user delete), then read the audit table.
  • Expected failure mode (today): audit-flags.ts:69-83 reads the key 5 s later and both pipelines short-circuit (handle-audit-logging.ts:129,166, audit-service.ts:221-224,380,388), so the mutation leaves no record and no marker that logging was off during that window. Also assert the second half: GDPR erasure must not remove the trail of the erased subject’s privileged actions — gdpr-service.ts:202-207 deletes every audit_logs row whose actorId is the erased user (i.e. exactly those actions), and the DATA_DELETION record written afterwards (:241-248) survives only because it is logged with id: "system".

5. Method and negative results

Tree: next (baseline snapshot efa57c55e).

Commands that produced the “not found” rows, verbatim:

grep -rn 'SingleLogout\|LogoutRequest\|logoutRequest' src/ tests/     # 34 hits in src/ (SAML SLO shipped); no longer a "not found" row
grep -rn -i 'ldap' src/ --include=*.ts --include=*.svelte --include=*.mdx # 12 hits in 4 files, all injection scanners
grep -rn 'verifyOAuthState' src/                                        # google-auth.ts:83 (def) + login/+page.server.ts:357 (1 caller)
grep -rn 'email_verified\|verified_email' src/                          # 0 hits
grep -rn 'at_hash\|c_hash' src/                                         # 0 hits
grep -n -i 'audit' 'src/routes/api/[...path]/handlers/auth.ts'          # 0 hits
grep -n -i 'audit' 'src/routes/api/[...path]/handlers/scim.ts'          # 0 hits
grep -n -i 'audit' src/databases/auth/saml-auth.ts                      # 0 hits
grep -n -i 'audit' src/databases/auth/sso-session.ts                    # 0 hits
grep -rn 'createLog\|auditChainService\.' src/                          # 1 hit: verifyChain caller only
grep -rn 'CREATE TRIGGER' src/databases/                                # content_nodes only

Paths in this repository are not under src/lib/server or src/routes/api/auth/: the auth engine is src/databases/auth/*, the HTTP surface is the single dispatcher src/routes/api/[...path]/handlers/*, and the request pipeline is src/hooks/*. A search in the conventional SvelteKit layout returns nothing and must not be read as a missing feature.

6. Related reading

  • docs/reference/security/authentication-system.mdx — narrative description of the same components (this page is the evidence layer under it).
  • docs/reference/architecture/transactional-outbox.mdx — the delivery queue, including its own non-transactional caveat.
  • docs/reference/security/secrets-inventory.mdx — where the IdP client secrets and certificates live.
securityidentitysamloidcscimaudit
Was this page helpful?