Access: sign-in, tokens and RBAC

Everything except DNS goes through the HTTP API on :8080: the dashboard is a single-page app served from / that talks only to /api/v1, and the CLI uses the same API with a bearer token. This page shows how a request becomes a principal and how the principal is authorized.

Code: internal/api (routes, middleware, authorization), internal/auth/* (authenticators, sessions, OIDC, tokens, users, the admin socket, Kubernetes tokens), internal/rbac (permissions.yaml, the engine, SubjectAccessReview), internal/cluster/internalapi (node-to-node).

Two parts of this page need a license key (see licensing). OIDC sign-in lives in ee/oidc: without a key the providers stay configured but are switched off. Roles beyond the built-in administrator live in ee/rbac: without a key the authorization step (see "Authorization" below) ends after the built-in administrator, API token scopes and the peer-node grant, so role bindings and Kubernetes SubjectAccessReview grant nothing. The first-boot administrator, the bootstrap token and the admin socket keep full access.

CLI operation transport

internal/apiclient retains authentication snapshots, cookie/CSRF handling, pagination, structured errors and SSE. Its documented routes call the matching internal/apiclient/openapi operation method through a generated dispatch table. make client-go regenerates that table from OpenAPI and the generated Go AST; unsupported or missing operation coverage fails generation.

The adapter preserves raw request bodies and original contexts. Its final guard checks method, origin and escaped path segments before supplying the original query, headers and body policy. An encoded slash cannot become a route separator. Unknown method/path pairs retain the raw compatibility path; matched parameter, build or transport failures never cause fallback or an adapter retry. Single-use auth retains disabled redirects and cleared replay headers/GetBody. SSE removes only the per-call HTTP timeout while retaining cancellation and its existing explicit subscription policy. Custom HTTP clients and low-level generated request editors remain trusted extension points; the public CLI exposes no request editor.

Shared Kubernetes password lockouts (D304)

Kubernetes replicas reserve password-attempt capacity in one private kudurru-login-lockouts Secret in the release namespace. Admission retains the actual driver's cluster-identity guard and performs one original UID/version update or absent-state create. A conflict, lost reply, malformed state or API outage returns 503 before a session can be issued; there is no local fallback or mutation retry. The existing namespace Secret permissions suffice.

sequenceDiagram
    participant A as Replica A or B
    participant K as Kubernetes API
    participant P as Password verifier
    A->>K: Reserve IP prefix and username with original CAS
    K-->>A: Confirm reservation
    A->>P: Verify once
    P-->>A: Result
    A->>K: Complete exact reservation with original CAS
    K-->>A: Confirm result
    A-->>A: Continue existing session checks or return refusal

The unchanged policy is five IP failures within five minutes for a five-minute lockout, and ten username failures within fifteen minutes for a fifteen-minute lockout. IPv6 clients share a /64. In-flight attempts reserve capacity before hashing, preventing simultaneous requests across replicas from multiplying available guesses. Abandoned reservations become failures at their original expiry. A successful password removes its own IP reservation and clears earlier completed username failures; another in-flight attempt or later failure survives. The durable sequence distinguishes operations even at identical wall times.

Reservations retain their original context and expire within thirty seconds. State is bounded by 4,096 combined keys and 512 KiB; whichever bound is reached first refuses new admission. Only expired entries are reclaimed. Keys are HMACs under a random salt stored with the document; raw usernames/IPs are absent, but access to the Secret still exposes sensitive operational metadata. Keep replica clocks synchronized: a sample earlier than the last durable observation refuses rather than resetting counters. Encryption-key rotation does not reset this separate salt. Privileged deletion of the Secret resets its history.

This mount covers Kubernetes local-password login. It does not replace OIDC start/callback limits, create shared TOTP replay authority, or make unrelated identity/session writes a cross-object transaction. Static independent stores do not gain shared authority from configured peer names.

SQLite password admission (D305)

The complete SQLite runtime stages password counters in the original login command, under its original HTTP lease, elected writer and dependency pins. It uses the same IP-prefix/username policies and document bounds as Kubernetes. The optional runtime/password-admission/v1/state row belongs to complete replication images; safe object exports omit it. Legacy absence initializes on the first admitted attempt. Privileged removal explicitly resets this history.

sequenceDiagram
    participant H as Original HTTP proof request
    participant C as Original SQLite command
    participant P as Password and factor verifier
    H->>C: Admit original lease and writer
    C->>C: Reserve bounded shared counters
    C->>P: Verify once
    alt Pre-mutation credential refusal
        P-->>C: Exact command-bound refusal
        C->>C: Stage failed counters only
    else Successful proof
        P-->>C: Authenticated current account
        C->>C: Stage result, factor use and requested auth change
    end
    C->>C: Final original context, clock and authority checks
    C-->>H: Commit all effects or roll back all effects
    H->>H: Refuse or seal exact published enrollment

Only a package-issued credential refusal from before authentication-state mutation can commit failed counters. Arbitrary errors, later enrollment errors, clock rollback, expired contexts and poisoned commands roll back counters and authentication effects together. The command is bounded by the earlier original deadline or thirty seconds. Malformed state refuses without repair; followers retain the exact document through install/restart but cannot mutate it locally.

This mount covers local login, including its supplied TOTP proof. D307 also shares these counters across authenticated TOTP setup, confirmation and disable. Current cookie/account and CSRF checks precede the same original command. Invalid challenge/candidate proofs may count only before factor state changes; all later errors roll back counters and factor effects together. Successful setup or an already-disabled factor can advance operational counters while leaving all factor/object state unchanged. Administrator recovery keeps its existing current users/write authorization. The one-second factor throttle remains an additional local control; distributed failure caps do not claim distributed pacing.

D308 applies the same counters to self-service password changes. After current cookie/API-token and exact-account checks, it verifies the current password and factor once, before changing the password. Invalid proofs change counters only; all later errors roll back every effect. Cookie callers receive an enrollment from that same verified decision after the password change; token callers receive no cookie. The prepared new hash is opaque, one-use and bound to the original 30-second-or-earlier context through response publication. New-password hashing still occurs outside locks before shared admission.

SQLite browser starts, callbacks and CLI preparation use the shared request budgets below. Kubernetes browser starts and callbacks share the D310 Secret budget. An enrolled follower forwards local password login and the caller's own password change to its primary (D363, D368), so the password counters above are charged there (local sign-in on an enrolled follower). OIDC starts, callbacks and CLI preparation are not forwarded: their request budget is charged under the local elected writer, which a follower does not have, so a follower refuses them.

Shared SQLite browser request budgets (D309)

An outer request gate charges a separate replicated operational document before any cookie/JWT interpretation and before the first complete authentication lease. It retains the original request deadline (at most thirty seconds) and exact elected writer through the handler. Only a confirmed charge reaches the normal adapter; missing state authority, conflicts and uncertain completion refuse without retry or local fallback. No prior authentication snapshot is replaced.

sequenceDiagram
    participant R as Original HTTP request
    participant Q as Shared request budget
    participant A as Complete authentication adapter
    participant P as Original provider and command
    R->>Q: Charge IP-prefix lane under original writer/deadline
    Q-->>R: Confirm commit or refuse
    R->>A: First complete lease capture after confirmed charge
    A->>A: Wait up to 5 s for the publication of the charge
    A->>P: Existing original credential/provider flow
    P-->>R: Verified response or original-source refusal

The charge advances the installed revision, so no publication served before it is eligible for the request: its capture always waits for the publication of its own commit. That capture waits up to servinghttp.OwnCommitWait (five seconds) instead of the two-second capture wait of other requests (servinghttp.WithOwnCommit, D426); with only two seconds, a node whose preparation outlasted them refused every provider sign-in, and every resend, with 503 generation_pending.

Starts and CLI preparations each allow five requests per prefix; callbacks allow ten. An idle gap longer than one minute resets that lane; reaching its threshold starts a one-minute lock. The versioned document stores salted address hashes and source time, with 512KiB/4096-key bounds and no live-key eviction. Complete replicas preserve it; safe object exports omit it. Legacy absence initializes; privileged deletion explicitly resets this operational state. Malformed history refuses rather than resetting. Cancellation after a confirmed charge retains that charge, without entering authentication or issuing a refund.

A charge is a canonical commit: it can supersede another request during provider I/O. That request must fail without recapturing its source or replaying the exchange. The local attempt latch and concurrency bounds remain additional controls, not a distributed guarantee of one exchange. Logout routes are outside these login request lanes. The D306 completion predicate remains response-only.

Shared Kubernetes browser request budgets (D310)

The Kubernetes root mounts the same bounded request policies before provider selection. Both start and callback requests, including unknown providers, charge kudurru-browser-admission in the release namespace. This private Secret is separate from password lockouts and stores salted address keys without raw IPs. Only a confirmed original-version write permits provider dispatch. Conflicts, malformed history, unavailable reads and lost write replies refuse without retry or local fallback. A successful charge remains spent after later cancellation.

The original context expires within thirty seconds and stays with the provider handler. The API validates the private Secret type, UID, resource version and shape; foreign owners are not adopted. Confirmed absence initializes history; privileged deletion explicitly resets it. The D309 policy and document bounds apply. This budget does not provide a cross-object session transaction or shared TOTP replay prevention. Public CLI preparation uses the complete SQLite path.

Commands superseded before dispatch (D399)

Every HTTP request captures one complete publication before it authenticates, and a command is held to it (D199): the command's first check, and the same check again in its transaction before its body runs, require that publication, or a later publication of the same cut, to still be the current one in the request's elected writer incarnation (servinghttp.CheckWriter, D208; the same-cut rule is below). The node's own work commits on its own schedule (zone status and lifecycle writes, admission, the anchor updater, signed UPDATEs), and each such commit retires the publication of every request that is in flight.

Most commands keep that refusal: they carry something derived from their first capture into their transaction, and a newer publication must not silently repair it. A small set of commands carries nothing of the kind, and only those opt in (servinghttp.WithRecapture). When such a command is refused before its transaction body began it has dispatched nothing, so it captures the current publication again and is dispatched once on it (recaptureCommand in the root, servinghttp.Recapture):

flowchart TD
  CAP["request captures publication P1,<br/>authenticates on P1"] --> CHK{"command check:<br/>P1 still current?"}
  CHK -- "yes" --> BODY["transaction body runs<br/>(dispatched once)"]
  CHK -- "no: another commit<br/>published P2" --> MARK{"command marked<br/>WithRecapture, single item?"}
  MARK -- "no" --> NOW["503 unavailable at once,<br/>nothing applied (D199, D208)"]
  MARK -- "yes" --> WAIT{"within 5 s and the<br/>request deadline?"}
  WAIT -- "no" --> R503["503 unavailable,<br/>Retry-After: 1, nothing applied"]
  WAIT -- "yes" --> NEW["capture P2"]
  NEW --> SAME{"no earlier command of the request dispatched,<br/>P2's authority = P1's but its revision,<br/>same auth dependencies, controls and settings,<br/>same credential, principal, session and roles on P2?"}
  SAME -- "no" --> R503
  SAME -- "yes" --> CHK
  BODY --> FINAL["any refusal from here on is final:<br/>never repeated"]

Captured again (marked):

  • a local password sign-in (POST /auth/login): it proves its password in the transaction; the only thing it read from its first capture is the settings (local sign-in enabled), which a recapture requires unchanged;
  • a sign-out (POST /auth/logout): it verifies its credential again in the transaction and revokes only its own session;
  • a whole-object write without If-Match (PUT or POST of one object under /objects, api.RecapturableCommand) of a DNSZone, DNSRecordSet, BlockList, ClientGroup, Policy or Integration: the request is the whole document, and the command reads, authorizes and admits the stored object in its own transaction (for an Integration that includes its secrets authorization and license check);
  • a record upsert (POST /zones/{zone}/records): the request is one endpoint, and the command reads the zone and the record set, merges the endpoint and authorizes the result in its own transaction (TestServingCommandRecaptureZoneRecordSupersededBeforeDispatch). A record delete and a zone import are not marked.

Never captured again (unmarked), each with the test that states it:

  • a write with If-Match, an object delete, and a source entries edit, which is bound to the incarnation its request saw (TestServingSourceCommandRetainsOriginalRequest);
  • every item of a multi-item request (POST /apply, batch deletes), the first one too: the request's chain (D378) is bound to its first capture (TestServingItemsFirstItemKeepsTheOriginalSource);
  • domain-list commands, which run a reviewed plan prepared for the captured publication (TestServingDomainCommandRetainsOriginalLeaseAndPlan);
  • cache invalidation, bound to the captured keyring and invalidation generation (TestServingCacheCommandRefusesOriginalAuthorityLoss);
  • node-local settings (TestServingNodeCommandActualRefusesStaleAuthorityAndFinalExpiry);
  • import adoption and migration steps, bound to the reviewed selection and their own cut (TestServingAdoptionActualHTTPOriginalWriterProofAndLease; a later migration step recaptures only its cut, as before);
  • cluster settings and control changes, which merge into the captured settings (TestRunServeSQLiteControlSettingsRestart);
  • cluster activation, join-token and promotion, bound to a reviewed source; OIDC callbacks and browser sign-out, bound to captured provider evidence; TSIG keys, factors, tokens, users, role bindings, IAM writers, blocking, notify and the integration operations (check, preview, sync, actions, release and delete cleanup, whose first no-op holds the integration host's lease barrier and runtime lock; a whole-object write of an Integration is marked, above).

Rules of the recapture itself:

  • The wait is bounded by five seconds (the same bound as a later import step's wait for its cut) or the request's deadline, whichever ends first. When it ends the answer is the same effect-free 503 unavailable, now with Retry-After: 1 on the object routes. Only a refusal returned before any transaction body of the request began carries that header there; a refusal from inside a body, at commit or after it does not, and neither does the refusal of a later command of a request one of whose commands already dispatched (D405). The authentication routes answer every 503 with Retry-After (auth.WriteError), so there the header says nothing about what ran.
  • Only a request none of whose commands has dispatched yet captures again (servinghttp.MarkDispatched): after its own first commit a request is held to its publication exactly as before.
  • The new publication must carry the original authority, advanced only in its installed revision: a fence, a term or incarnation change, a mode change, a conflict or divergence refuses. Its auth view must have the same dependency identity (license, permissions, role bindings, session and factor keys, providers, auth controls such as the cookie policy) and the same cluster settings object. The original raw credential must verify on the new publication's auth view as the same principal, with the same session (ID, CSRF secret, issue and absolute expiry; the idle expiry may advance) and the same effective roles. A sign-in carries no prior credential and proves its password in the transaction, as before.
  • The transaction then repeats its own authorization and every source check against the new capture. A refusal from inside the transaction body, a refusal at commit and an uncertain outcome are never repeated.
  • The request keeps every lease it held until it ends.
  • This covers a request that was read. A request that arrives while the node has not published its newest commit is still refused at capture, before it is read, with 503 generation_pending (the middleware's two-second capture wait; five seconds for a provider sign-in, which waits for its own admission charge, D426). D405 shortened that window: a Wake no longer cancels the preparation in progress, and a zone content commit deletes the chunks no head references. A preparation that outlasts the capture wait (one to three seconds under the race detector on a loaded machine) still refuses requests at capture; that limit stays open.
  • A command does not wake the publisher after its own commit advanced the generation (D407, servinghttp.CommittedPast): that commit already makes the publisher prepare a candidate read after it. With D405's coalescing, a Wake that arrived after that preparation had read its candidate made the publisher publish the same revision a second time, and that second publication refused as superseded every command captured on the first one, marked or not (the next command of the same client, typically). A command that committed nothing new, an item of a multi-item request and the other wakes (dependency watchers, cluster activation and promotion, node-local settings, TSIG keys, blocking, edge blocks) are unchanged.
  • A later publication of the same cut does not refuse a command at all, marked or not (Publisher.CheckWriterCut in servinghttp.CheckWriter): when the publication that replaced the request's has the same installed generation (term, revision and digest) and the same dependency identity, and the lease's own dependency cursors are current, the command keeps its lease and is dispatched as if nothing had been published. Such a publication is the same source prepared again after a Wake that arrived during its first preparation (D405); other Wakes than a command's own (provider coordinator, dependency watchers) still cause it. Background acknowledgments keep the exact publication rule (CheckWriterLease).
  • A follower's early admission and its forwarded commands stay bound to the follower's captured publication. The primary's entry for forwarded commands is bound to the member request's authority, not to a publication, so the primary's own commits do not refuse it.
  • A signed RFC 2136 UPDATE is not recaptured: its publication is the DNS transport's capture, whose keyring verified the signature and whose output signs the answer. Its pre-dispatch refusal stays an effect-free SERVFAIL (Handler.resolve), and the withheld acknowledgment (D313) is unchanged.

Browser response completion (D306)

Browser start, callback and local logout retain their original complete HTTP lease and elected writer through command admission. Provider capture/exchange still require the original source to be current. A pending-row or session commit retires that source revision, so response acknowledgment uses a private completion check issued only after the actual command succeeds. It retains the same request lifetime, writer episode, term/incarnation and all captured dependency installations. Cancellation, writer loss, key/license/provider or managed-anchor replacement still refuse; matching bytes cannot replace an installation identity.

flowchart LR
    A[Original source and provider] --> B[Original admitted command]
    B --> C[Actual pending or session commit]
    C --> D[Retained writer and dependency check]
    D --> E[Exact committed row in complete publication]
    E --> F[Original cookie policy and expiry]
    F --> G[Seal response]

This completion check cannot authorize authentication, provider I/O or another mutation. The fresh publication is only an acknowledgment of the exact pending row/enrollment; no provider or writer is reacquired. Its own memory-only source check must still pass immediately before response emission. A later canonical change refuses rather than recapturing or resealing. Browser logout confirms local revocation before creating an optional remote continuation. A failed command or uncertain completion issues no completion check and is never retried.

Coherent authentication owner foundation

The complete SQLite runtime exposes dedicated reviewed RoleBinding commands (D294; operator guide). Creation requires absence; replacement and deletion require exact UID/resourceVersion and API ownership. Each command retains its original raw proof, view and writer while checking current authority, target identity and final time/cancellation. The object, grant floors and audit commit in the same security transaction. Dedicated CLI mutation transport disables redirects and body replay. Legacy/Kubernetes mutations explicitly refuse; ordinary IAM aliases remain unavailable.

SQLite mounts a required RoleBinding source capability before the first file or inline load. Each loader pass retains its immutable accepted input, exact original target UID/revision/manager and original startup or elector writer. Create, change, delete and unchanged reconciliation all cross the same concrete security transaction; the revocation clock is sampled after acquiring its writer lock. Final source, writer, cancellation and clock checks apply even to no-ops. Removing and regranting a file-managed binding cannot revive the original frozen cookie or token. Installed inline/environment maps are detached once; watched configuration files are captured on each pass. Broken sources retain their objects. The input pin protects accepted loader passes, not concurrent native filesystem writes. Kubernetes has no such transaction; it persists the revocation times of removed binding grants separately, in the kudurru-grant-floors Secret (Authorization, D364).

internal/servingauth prepares an immutable auth view from one complete SQLite replication image. Its input includes public ServiceAccount, RoleBinding and IdentityProvider configuration, private LocalUser, APIToken and PrincipalState objects, the Kudurru singleton, and versioned security state. Public IAM objects remain outside DNS snapshot readiness. Explicit empty manifest entries are valid; missing kinds, a safe export, or missing security history cannot create a view.

The required auth/v1/root row inventories every auth-owned security row and records a monotonic epoch. Sessions bind the exact account UID and issuance epoch to durable enrollment, expiry, grants, a CSRF verifier and revocation state. Account/provider floors also bind UIDs; normalized grant revocations survive deletion and regrant. Cookies issued at or before a retained floor are rejected. D413 compacts historical floors into a durable revocation checkpoint after materializing their effect on stored credentials, as described under IAM writers. The new version 2 cookie requires its matching enrollment, so activating this owner will require users of legacy sealed cookies to sign in again.

Startup initialization and security commands account for every owner's rows in the shared security section. They check the combined count and byte limits before staging a new auth manifest, including other rows staged after the command loaded auth state. Exceeding those limits rolls back the complete command; another owner’s capacity cannot silently make the next authentication image unreadable. Current transaction reads first use scalar SQL row and byte counts, including staged data, before allocating section payloads. Malformed historical data cannot bypass those limits merely because it predates owner validation.

internal/auth/providerregistry owns a separate oidc-provider/v1/root manifest in the same replicated section. Configured providers receive independent durable UIDs and creation times; spec edits retain them, removal retains a tombstone, and recreation gets a new UID. Both config and object providers have exact accepted credential/trust/entitlement receipts. Replacing or withdrawing a receipt raises the old incarnation's auth floor in the same SQLite command, before staging the registry plan. No-op receipt admission still checks the actual staged source.

Authority acceptance supplies the complete active inventory across both origins. Omitted receipts become inactive history; unavailable unchanged providers retain their accepted receipt. A newly configured provider retires a shadowed object's accepted authority. History has an explicit finite cap and is never silently evicted to recover capacity.

Management entitlement loss and regain is a security transition even if the license or provider credentials return with identical bytes. The root owner must withdraw and later reactivate accepted authority with revocation floors, or assign a new captured entitlement identity and admit its changed receipt. Replaying an unchanged active receipt is deliberately a no-op and cannot record that transition. Denied entitlement performs no provider credential or network acquisition; current authentication reads the durable floors in its own command.

providerentitlement supplies the shared receipt format and pure selection helpers. One activation binds the actual cluster, verified management-policy profile and a random primary-admitted nonce across the complete provider inventory. The profile includes effective license identity, plan, nodes, features and original grace deadline; signed issue/not-before times and signing-key identity are not profile fields. License cuts still enforce current verification and eligibility. A pending nonce grants nothing, and a local license installation ID cannot serve as shared authority. Startup, writer turnover and observed license replacement must withdraw old authority with floors before admitting a new activation, even when the profile is unchanged. Historical restarted or tainted followers wait for a new primary activation. The helper has signed-license and actual replica acceptance. The provider host now owns the local continuity state and exact license/static/auth-key exclusion. A restarted or tainted follower uses its first validated current installed image only to establish a baseline; a later different primary activation is required. If observation is delayed past a new activation, recovery can conservatively require one additional primary reset.

SQLite startup initializes both owner roots together through an explicit fenced command. Followers receive them only in a complete image. The replica feature provider-registry-v1 requires receiver support, and composed image validation rejects missing or incomplete inventories before installation, serving capture or promotion. The complete builder derives config-provider precedence from that same registry image; local resource omission cannot reveal a shadowed object.

internal/auth/providerresources acquires discovery and JWKS in bounded background jobs. Each immutable resource binds the actual credential fingerprint, explicit trust roots, endpoint and algorithm policy, management entitlement, and the exact accepted source receipt. Config and stored-object credential capabilities remain separate. Changed desired authority installs an unavailable resource before any network call; a privately verified acquisition candidate still needs durable receipt admission. Old jobs and held leases cannot revive across A → B → A.

Current commands hold the resource pin through writer waits, final validation and commit, including no-op responses. Their provider dependencies come from the actual staged registry and IdentityProvider objects. Authority changes use publication exclusion, exclusive resource replacement, then SQLite in that order. They stage revocation floors before receipts and replace the desired resource cut before releasing exclusion. A failed replacement retires the memory cut and requires fresh canonical capture. Complete publication uses the same resource exclusion through its pointer swap. No network or credential resolution occurs under these guards or during authentication.

Explicit TLS/origin policy, bounded document parsing and absolute resource freshness apply to discovery and JWKS refresh. Transient failures can retain only an unchanged resource until its original deadline; security mismatches retire it. Unknown token keys never initiate discovery. These resource and transaction adapters are tested with real TLS, SQLite and the publisher. SQLite startup mounts the coordinator, captured local HTTP routes and browser OIDC. Browser exchange uses an explicit credential-bound handle from the same published resource lease; it does not perform discovery or select a newer provider during a request.

Host-only auth.providerResources settings now declare explicit network origins, local exceptions, asymmetric JWT algorithms, system trust and extra CA files. They require restart and cannot be changed through replicated settings or public IdentityProvider objects. The root trust loader captures actual CA bytes before locks, deduplicates and sorts them, and enforces 2 MiB/256-certificate limits. Linux uses the first existing standard CA bundle; macOS uses /etc/ssl/cert.pem and BSD uses its documented file locations. It does not query the macOS keychain or read SSL_CERT_FILE/SSL_CERT_DIR. Other platforms need explicit CA files with system trust disabled. Missing, malformed or oversized requested trust is an error, without partial or implicit system-pool fallback. These inputs and the loader feed the root static preparation adapter, which detaches permissions, bindings, sealing/TOTP keys and per-provider credential capabilities before locks. An explicitly configured file belongs only to that config provider; it does not grant a stored provider filesystem access. A separate auth-key installation owner pins the loaded keys through complete transactions and excludes replacement.

providerhost.PinHostCurrent supplies a predicate for the original pinned local generation, license, static resources and deadline. It is memory/clock-only and ends at callback exit. Root still retains the original elected writer and its concrete transaction checks separately. Host captures distinguish independent local installations even when their serials or configuration bytes are equal; their local identities never replace the shared entitlement activation. A bounded four-entry memo preserves concurrently prepared old/new resource projections. Host reset, follower observation, real JWT/current commands and reference lifetimes have actual SQLite/complete-publisher acceptance and are mounted in SQLite startup with the original elected writer lifecycle.

flowchart LR
    I["One complete image"] --> C["Sealed auth cut"]
    D["Pinned key and management policy"] --> V["Immutable auth view"]
    C --> V
    V --> R["Leased HTTP read"]
    P["Raw credential proof"] --> T["Current command transaction"]
    T --> A["Reverify current account and permissions"]
    A --> W["Mutation or dedup response"]

Local passwords, local/service-account tokens and enrolled cookies verify without store reads from the view. Command authentication instead rereads the current identities and security rows through an actual sqlite.CommandTx, including staged changes and dedup replay. A previously authenticated principal cannot authorize that write. Current local groups and private administrator state remain authoritative; token scopes narrow administrator permissions too.

internal/servinghttp captures the complete publisher lease before checking a cookie, API token or OIDC JWT and keeps it until the bounded handler finishes. JWTs use only the captured offline verifier and bounded claim policy; unknown issuers, expired signatures and oversized proofs cannot trigger discovery or a cookie fallback. Ordinary raw HTTP proofs survive only for the lease lifetime. A bounded migration program can retain its original untrusted proof for its original ten-minute job deadline and elected writer episode; each later step captures its own initial lease and reverifies that proof against current transaction-local authority. No previously successful step grants permission to another step. CSRF uses the same captured enrollment. Authorization rechecks the original proof against that view; a caller-supplied principal cannot replace it. Pending publication returns 503, and a rejected bearer never falls back to a cookie. Mutations must pass the retained raw proof to the current command verifier separately. The HTTP writer check uses that original request lease and the carried writer target at entry and final commit. A newer publication cannot repair an old request. This memory-only check is safe inside the actual transaction hook; it does not replace current credential verification or dependency exclusion.

The root current-command adapter retains the original elected episode and holds publication, provider, host/license/auth-key, TSIG, catalog and manager exclusion through the whole SQLite command. Only the coordinator's host wrapper expands these lower pins; the publication source and primary guard keep their existing base host pins. Current raw authentication runs before mutations or a dedup result. ReauthorizeCurrentWithClock retains private validity from that same successful verification and checks it again at final admission, including no-ops. Token expiry, enrolled cookie absolute/idle expiry and verified JWT time bounds reject at equality; a clock moving before authentication time also rejects. This final check performs no store read, parsing, crypto or policy evaluation. Password/TOTP consumption remains once in the transaction, and enrolled external cookies keep their own durable deadlines rather than inheriting the source JWT's expiry.

These owners are tested across held old/new views, store closure, restart, actual replica installation and promotion. The HTTP bridge also tests held reads during revocation, current-command denial and cleanup on cancellation/panic. SQLite serve.go now mounts the captured HTTP adapter for authentication, authorization, local login, password changes, token CRUD, IAM reads and own-session inventory and revocation. The API and adapter share the same cookie and cross-origin policy. Login verifies the current password/TOTP once, stages durable enrollment, checks its original deadlines at final commit, and seals only from a published view containing that enrollment. Password changes raise revocation floors and can revoke tokens atomically with replacement enrollment. Session responses expose only the identifier, timestamps and current/revoked flags for the exact account UID. The Access page lists those browser sessions and revokes an explicitly selected identifier. Revoking another session preserves the caller. Revoking the current session clears local authentication and cached answers after 204, without a second logout request; it does not claim to clear the HttpOnly cookie. Late responses and cancellation cleanup check the original session lifetime before touching state, including after awaiting query cancellation. A stale postcommit inventory remains pending until a fresh read shows the revocation; mutations are never retried automatically.

The password-change floor uses the same successful current-authentication time sample. A transient later clock rollback cannot put the floor before an old session and silently preserve it; replacement issuance and final original-proof checks still use the actual clock.

When own-password change requests token revocation, it matches both supported local provider spellings by exact account identity. It deletes system-issued tokens without Force; a foreign-manager failure rolls back the password change and all staged revocations.

Generic public object writes and canonical settings writes reauthorize the original raw proof within the admitted command, including unchanged writes.

POST /iam/users creates ordinary API-managed local accounts. The bounded request accepts only a canonical name, display name and initial password. Hash preparation happens before command pins; current cluster users.write authorization, CreateOnly, password status and the final staged UID/version projection share one transaction. New accounts have no groups or authenticator and must change their password. The own-password route preserves explicitly supported API/system ownership; it cannot adopt file/controller-managed users.

POST /iam/users/{name}/password is an administrator reset of an API-managed, non-built-in account. It requires the exact UID and opaque resourceVersion from authorized inventory. The transaction preserves the authenticator, replay record and disabled state, sets must-change, raises the account floor and revokes every exact-owned local personal token, including the legacy empty-provider spelling. Account floors alone do not revoke those tokens. An incompatible token manager aborts the entire reset; no Force or partial success is used. Self-reset keeps the original successful proof's final time checks and clears its cookie after commit, without reauthorizing against its own newly raised floor. No replacement credential is issued. A stale version requires a fresh read and deliberate request; commands are not retried automatically. Kubernetes explicitly returns 503 for these writes. Profile and group changes, disable and delete are the D396 writers below.

SQLite OIDC start/callback routes use the captured browser adapter described below; an unavailable capability returns 503 without a legacy Stack fallback. Startup bootstrap and local admin-socket integration still use the legacy Stack, with its provider discovery disabled on SQLite. Completing current admission for those administrative paths remains open. SQLite also mounts the factor management routes described below. Kubernetes retains the legacy Stack and its separate verified migration journal gate; its factor management routes return 503 until equivalent current commands are available.

SQLite startup initializes the explicit empty security manifest under its writer fence and validates owner rows on later writes/replica installation. Existing history is preserved; an absent root beside other auth rows is an error. Startup explicitly upgrades complete version 1, 2, 3 or 4 manifests to version 5, preserving every session, replay row and revocation floor and advancing the security epoch once. Version 3 introduced external identities and sessions; version 4 adds the mandatory pending browser-attempt inventory, and version 5 adds the required revocationCheckpoint time (initially zero). Migration preserves the full history before later admitted compaction, even at row capacity. If the new field would exceed an old database's byte budget, that same startup command materializes eligible revocations into the checkpoint before staging the new manifest; failure rolls back the complete migration. Replication requires both auth-browser-attempts-v1 and auth-revocation-checkpoint-v1; receivers without these capabilities reject the image independently of its payload digest. Coordinated upgrades must account for that compatibility boundary. Version 1 or empty-state initialization rejects legacy account seeds without replay authority, including disabled accounts; the version 2 upgrade preserves supported active factors. Startup never silently adopts or clears a seed. Other security owners' rows remain intact. internal/auth/security supplies transaction-bound object changes and monotonic revocation floors, session enrollment/revocation, and expiry collection. Current local-password issuance resolves the actual account, grants and canonical login policy/TTL before staging enrollment in that same command. Cookie sealing requires a committed view containing the enrollment. These command APIs are tested; the production HTTP stack still needs to adopt them for every relevant writer.

internal/auth/totp implements the fixed SHA-1, six-digit, 30-second RFC 6238 profile with a one-step window. A purpose-separated sealed seed binds the exact LocalUser UID, seed version and random seed identity. Replay rows retain the greatest consumed step, including step zero, across encryption-key and seed rotation. Auth roots from version 2 require an explicit inventory of these rows; ordinary decoding never substitutes an empty replay history.

Current password authentication verifies both factors and stages replay consumption inside the actual command transaction. Session issuance then loads that staged state and enrolls the session in the same transaction. A later failure rolls both changes back; concurrent use of one code can enroll only one session. Immutable auth views cannot consume a code or accept a factor password login.

The current command layer also supports factor setup, confirmation, removal and administrator recovery. Setup verifies the current local password and existing factor, then returns a five-minute purpose-separated challenge and provisioning secret through an explicit disclosure API. The challenge binds the exact account UID/resource version, prior seed version, keyring and dependency identity. Confirmation rechecks current proof, verifies a code from the new seed, and commits the seed, replay consumption and session revocation together. Rotation preserves the old replay floor; removal and recovery retain the disabled replay row. Recovery separately requires current users/write permission and the exact target UID. Concurrent confirmation can enroll once; failed callbacks consume nothing. Clock-aware commands retain the same verified credential or decoded challenge bounds through final commit, including no-ops. Their final checks read only memory, context and actual time; they never consume a second code.

SQLite exposes own status at GET /auth/totp and setup, confirmation and removal at POST /auth/totp/{setup,confirm,disable}. These routes require a current local enrolled cookie; mutations also verify the current password and existing factor. Administrator recovery uses POST /iam/users/{name}/totp/recover with the exact UID returned by authorized IAM reads. It reauthorizes the original raw proof for cluster users.write inside the complete current command. Requests are bounded and reject duplicate or unknown fields, and factor attempts share login's rate limiter. Setup discloses its secret only after successful commit and a final deadline check, with private response headers. Confirmation and removal clear the cookie after commit and require a fresh login; self-target recovery does too. The consumed confirmation code cannot be reused for login.

Dashboard login and password change accept an optional six-digit authenticator code, preserve leading zeros and clear it after submission. They do not retry factor-bearing mutations. The Access page provides a three-step enrollment and replacement wizard with a manual key, plus removal and administrator recovery dialogs. Local enrollment requires a local cookie session; recovery also permits external cookie administrators with cluster users.write. Recovery binds the selected account name and UID and checks a fresh inventory before submission. An account replacement requires explicit reselection.

Passwords, codes and setup secrets remain in the mounted component, outside query and mutation caches. Closing a pending dialog aborts the request and reports an unknown outcome; it never retries the mutation. Successful confirmation, removal and self-recovery clear the session, CSRF value and cached answers without a second logout. Canceled session reads cannot restore old CSRF state after cleanup. No external QR service receives provisioning material.

flowchart LR
    Proof["Password + TOTP code"] --> Current["Current UID-bound account and seed"]
    Current --> Replay["Verify and stage increasing replay step"]
    Replay --> Enroll["Load staged security state and enroll session"]
    Enroll --> Commit["One fenced commit"]
    Commit --> Published["Committed auth view seals cookie"]

Offline provider verification and claim policy

internal/auth/oidccore verifies signed ID tokens against an explicitly captured issuer, asymmetric algorithm allowlist and public JWKS. It performs no discovery, refresh, store read or enrollment. An opaque verified token carries detached claims and typed issuance/expiry times. Policy evaluation checks time again, so holding a verified token does not extend its lifetime. Browser evaluation also requires the verifier's nonce and optional at_hash check.

The compiler consumes the public IdentityProvider scalar and expression fields. CEL exposes only claims, with bounded source, AST, comprehension depth and per-expression/aggregate execution cost. Validation rules return booleans; username/display/email mappings return strings; group mappings return string lists. Missing claims, type errors and exhausted budgets deny authentication. Prefixes, verified-email requirements and exact allowed email domains still apply after mapping. Identity remains the provider/issuer/subject tuple.

flowchart LR
    Keys["Captured issuer + public JWKS"] --> Verify["Offline signature and time checks"]
    Proof["Raw ID token + optional browser proof"] --> Verify
    Verify --> Facts["Opaque verified facts"]
    Spec["Captured public provider spec"] --> Compile["Bounded scalar/CEL compiler"]
    Compile --> Evaluate["Current-time audience and claim policy"]
    Facts --> Evaluate
    Evaluate --> Identity["External identity; no granted rights"]

servingauth binds each selected provider's ID, actual UID, origin, spec and compiled policy to exactly one immutable verifier resource or explicit unavailable resource. Config providers retain precedence even when unavailable; no fallback to an object or live discovery can bypass that decision. Unknown or mismatched resources reject preparation. Unavailable providers deny external proofs while local authentication remains available. Management licensing remains explicit.

External identities have independently generated durable UIDs. External cookie version 3 requires an exact enrolled session, CSRF, expiry and revocation state. Purpose-separated encrypted evidence binds the original verified claims to the provider incarnation, identity UID and session. Enrolled sessions may outlive the original ID token, but current claim policy and durable authority are reevaluated. Request evidence retains strict JWT expiry and exact resource identity. Session and personal-token grants intersect frozen grants with current subject authority; scopes and persistent floors still apply. Missing identity rows with retained floors cannot silently reprovision a new UID.

security.IssueExternal resolves raw proof against the current command, creates or reuses the independent identity UID, and atomically commits profile, group snapshot, revocation floors and session enrollment. Initial groups come from the verified proof; later group updates obey syncGroups. Username changes and group removal raise the account floor. Issuance samples the real clock again, rechecks original proof expiry, and must be strictly later than any new floor. Equality rejects the command; timestamps are never adjusted to bypass revocation. Cookie sealing requires a complete committed view containing the new enrollment.

External issuance rechecks the private verified proof at final command admission, after all staged enrollment and other callback work. Expiry or a clock regression rolls back the entire enrollment. The outer resource pin still excludes provider rotation through the actual commit; a time check alone is not that exclusion.

These owners and commands are tested with real signed JWTs, concurrent concrete transactions, rollback, restart, replica installation and promotion. SQLite browser login now composes bounded discovery/exchange, durable pending-attempt consumption and external enrollment. SQLite CLI sign-in verifies the raw ID token against the same captured provider (browser and device flows). The legacy Kubernetes OIDC adapter has not adopted this owner and rejects expression policies.

Principals

KindComes fromTypical caller
Userlocal password login, or OIDC sign-ina person in the dashboard
ServiceAccounta kdr_ API token owned by a kudurru ServiceAccountautomation, the bootstrap token
KubernetesServiceAccounta projected ServiceAccount token (audience kudurru)a Job or controller in the cluster
LocalRoota peer on the unix admin socket (uid 0, the server's uid, or a configured gid)kudurru admin inside the container
Nodethe internal node tokenanother kudurru node, an edge supervisor

The request path

flowchart LR
    R(["HTTP request"]) --> M1["recover, request ID,<br/>real IP (trusted proxies),<br/>security headers, access log"]
    M1 --> M2["cross-origin protection<br/>(Sec-Fetch-Site / Origin)"]
    M2 --> AUTHN["authenticate<br/>(/api/v1 only)"]
    AUTHN --> ROUTE["route: each operation declares<br/>resource + verb (+ zone scope)"]
    ROUTE --> AUTHZ["authorize"]
    AUTHZ --> H["handler"]
    H --> AUD["audit: mutations, denials,<br/>runtime actions"]

Authentication: first claim wins

flowchart TD
    R(["request to /api/v1"]) --> B{"Authorization:<br/>Bearer kdr_…?"}
    B -- "yes" --> TOK["API token: look up the id, compare<br/>sha256 in constant time, check expiry<br/>and account UID"]
    B -- "no" --> J{"Bearer JWT?"}
    J -- "yes" --> ISS{"route by iss"}
    ISS -- "a configured OIDC issuer" --> OIDC["verify ID token (JWKS),<br/>aud, azp, claim mapping"]
    ISS -- "the cluster's issuer" --> K8S["ServiceAccount token:<br/>JWKS offline, else TokenReview<br/>JWT lifetime ≤ 10 min; cache ≤ 2 min"]
    J -- "no" --> CK{"session cookie?"}
    CK -- "yes" --> SES["open the sealed cookie: expiry,<br/>idle timeout, sessionsValidAfter;<br/>unsafe method needs X-Kudurru-CSRF"]
    CK -- "no" --> UX{"unix socket peer?"}
    UX -- "yes" --> ROOT["LocalRoot"]
    UX -- "no" --> NT{"internal node token?"}
    NT -- "yes" --> NODE["Node (viewer + auditor)"]
    NT -- "no" --> ANON["anonymous"]
    TOK --> P(["principal"])
    OIDC --> P
    K8S --> P
    SES --> UID["local account UID must match;<br/>load current groups and account state"]
    UID --> P
    ROOT --> P
    NODE --> P

A credential that is present but wrong is rejected at once (401); it never falls through to the next authenticator, and an unknown bearer value is never anonymous.

Kubernetes ServiceAccount credential bounds

The Kubernetes-store identity stack accepts projected ServiceAccount JWTs for audience: kudurru. Both offline JWKS verification and the TokenReview fallback require canonical whole-second iat and exp, nonfuture issuance, a valid optional nbf, and 0 < exp - iat <= 10 minutes. Original expiry is exclusive: verification, cache lookup and later request authorization reject at equality. Opaque legacy ServiceAccount tokens, missing issuance/expiry, malformed dates, one-hour projections and extended-lifetime tokens are rejected. These bounds apply to incoming kudurru credentials, not the server's own Kubernetes client.

Offline verification does not detect deletion immediately. A deleted pod or ServiceAccount can retain offline authority until the original JWT expires, within at most ten minutes of issuance. Kubernetes must stop issuing/renewing the credential after deletion. TokenReview can observe deletion sooner; a successful review is cached for at most two minutes and never beyond the original JWT expiry. Every acquisition also checks time after it finishes. Clock rollback before verification or issuance fails closed. Neither cache renewal nor a newer credential changes an already held proof's expiry.

During an API outage, an already known JWKS can verify a correctly signed token within those original bounds. Missing keys or an unavailable/rejecting TokenReview deny authentication. Discovery, JWKS and review requests have a maximum ten-second transport timeout; shorter caller/client limits remain in force. Review responses must match the projected subject, ServiceAccount UID and requested audience. Errors and logs omit remote review error text and raw proof. This policy bounds offline revocation without introducing periodic TokenReview or network fallback into captured reads/current commands.

The verifier retains private, nonserializable request time evidence. Principal lookup and the stack/REST authorization gates recheck it, including after a slow SAR and before reusing an allowing per-object decision. This time evidence cannot authorize a current mutation. Kubernetes tokens remain mounted only in the Kubernetes identity stack; SQLite's captured provider path does not accept them. Its original raw-proof/publication/writer exclusions and final credential/license checks are unchanged. See the projected token configuration.

Signing in

First start

When there is no LocalUser, the server creates admin (built-in admin) with the password from KUDURRU_ADMIN_PASSWORD[_FILE] or auth.bootstrap.adminPasswordFile; otherwise it generates one, prints it once, and requires a change at the first sign-in (every permission route answers 403 password_change_required until then). KUDURRU_BOOTSTRAP_TOKEN[_FILE] creates an admin API token for automation.

Local passwords are Argon2id (19 MiB, t=2, p=1). Failed sign-ins lock an address for 5 minutes after 5 failures, and an account for 15 minutes after 10.

Local sign-in on an enrolled follower (D363)

An enrolled SQLite follower cannot commit a session or a failed-attempt counter itself, so POST /auth/login on a follower runs on its primary. The follower prepares the session identifier and CSRF secret, keeps the secret, and sends one version-1 auth.login member command over member mutual TLS: the normalized username, the password, the factor code, the client key, the session identifier, the CSRF hash and a random nonce. The command carries no prior credential and no preconditions.

sequenceDiagram
    actor B as browser or CLI
    participant F as follower API
    participant P as primary member executor
    B->>F: POST /auth/login (username, password, factor code)
    F->>F: Capture source (30 s bound), prepare session ID and CSRF secret
    F->>P: auth.login (member mTLS): credentials, session ID, CSRF hash, nonce
    P->>P: Shared counters, password, factor and login policy in one command
    alt refused or locked out
        P-->>F: Retained refusal (counters committed)
        F-->>B: The primary's status, key and Retry-After
    else admitted
        P->>P: Enroll exactly that session and record last login
        P-->>F: Committed, session ID
        F->>F: Pull, then wait until the published view contains the session
        F-->>B: Set-Cookie sealed with the follower's CSRF secret
    end

The primary runs the same admission as its own login route (IssueForwardedLocalWithAdmission): shared lockout counters, password, factor and local-login policy, then enrollment of exactly the forwarded session identifier and CSRF hash. A credential refusal or lockout is a retained result whose counters commit on the primary. The dedup record keeps only a fingerprint whose input includes the nonce, which is stored nowhere, so it cannot be used to test passwords offline.

The sign-in holds the follower's scheduled pull while it runs, as the object, settings, sign-out, password and token commands do (D375, D424), so a pull cannot install a newer commit of the primary between the request's arrival and its forward and refuse it. The hold ends once the primary has answered, before the explicit pull, so that the scheduled pull can still install a committed session if that pull fails. The follower answers only after its own pull has installed the session and a published authentication view contains it; the cookie then works on every member. If the primary cannot be reached, the login is not attempted and the follower answers 503 unavailable. If the exchange is lost after sending, it answers 503 completion_unknown and never repeats the command. Static twins and standalone nodes sign in locally. See the member-command executor for the transport.

OIDC in the browser

kudurru is a confidential client: the browser receives a sealed session cookie, not provider tokens. On SQLite, background discovery prepares the exact accepted provider capability before a request starts. Start commits a random pending attempt bound to provider UID, spec/resource identity, redirect, client and the preauth payload hash, then seals from a published view containing that row.

sequenceDiagram
    autonumber
    actor B as browser
    participant K as kudurru API
    participant I as identity provider
    B->>K: GET /api/v1/auth/oidc/{idp}/start?next=/zones
    K->>K: capture provider#59; generate state, nonce and PKCE verifier
    K->>K: current command commits pending attempt
    K->>K: published view seals exact pending row
    K-->>B: 302 to IdP + sealed pre-auth cookie (10 min, single use)
    B->>I: authorize (code, S256 challenge, nonce)
    I-->>B: 302 /callback?code&state
    B->>K: GET /api/v1/auth/oidc/{idp}/callback
    K->>K: original view checks pre-auth cookie, state and pending row
    K->>I: bounded code exchange outside owner/transaction guards
    I-->>K: ID token
    K->>K: verify signature, aud, azp, nonce, at_hash
    K->>K: claims → username (prefix) and groups (prefix)
    K->>K: current command consumes pending row and enrolls session atomically
    K->>K: published view seals exact enrollment
    K-->>B: Set-Cookie session + 302 next
    B->>K: GET /api/v1/auth/me → principal, permissions, CSRF token

The pending inventory allows at most 256 attempts, each valid for ten minutes. Missing, consumed or expired rows deny callbacks, including after restart, promotion or garbage collection. Callback consumes the exact row in the same command as external enrollment; failure rolls both changes back. The exchange supports S256 and client_secret_basic, enforces the original resource and credential identity before and after I/O, and performs no automatic retries or redirect following. No refresh token is retained. Provider receipt profile provider-metadata/v2-browser requires fresh authority admission; identical-byte withdrawal/reactivation cannot revive a preauth cookie across its provider floor.

Browser logout

On the complete SQLite runtime, POST /auth/logout/browser retains the original credential, CSRF and final writer checks and durably revokes the exact local session before clearing cookies. Its response may contain a same-origin continuation path. The dashboard clears cached session state and CSRF before navigating. Existing POST /auth/logout remains local and returns 204 for CLI cleanup and old callers; legacy Kubernetes hosts retain local logout.

Verified browser enrollment can seal an HttpOnly hint cookie bound to the exact session, provider UID, origin, spec/resource identities, issuer, client and redirect URI. The raw ID token is neither persisted nor returned to JavaScript. The public continuation checks those original bindings against a ready captured provider and checks its original installed credential fingerprint once. It then redirects only to the trusted discovery end_session_endpoint, with the original hint and fresh state. Changed or unavailable capabilities return locally. Providers without an endpoint retain their previous metadata trust identity.

The callback authenticates a separate encrypted state cookie, exact provider and original deadlines, clears it and returns to the configured app prefix. It cannot issue a session or restore a revoked one. Unknown or duplicate query fields and phase confusion refuse. Cookie deletion provides normal browser consumption; there is no durable logout replay tombstone. Replaying copied valid callback state grants only the same safe local redirect.

sequenceDiagram
    actor B as browser
    participant K as Kudurru API
    participant I as identity provider
    B->>K: POST /auth/logout/browser with original CSRF
    K->>K: Commit exact session revocation#59; clear cookies
    K-->>B: Optional same-origin continuation path
    B->>B: Clear session/cache/CSRF
    B->>K: GET continuation with encrypted logout cookie
    K->>K: Check original provider, credential and expiry
    K-->>B: Redirect to trusted end-session endpoint
    B->>I: Original ID-token hint and fixed callback/state
    I-->>B: Logout callback
    B->>K: GET callback with authenticated state
    K-->>B: Configured local app prefix#59; no session issuance

Register an additional OP return URI derived from the configured login callback: replace its final /callback with /logout/callback, for example https://host/prefix/api/v1/auth/oidc/corp/logout/callback. The configured login URI must end in canonical /api/v1/auth/oidc/{idp}/callback, without query, fragment, userinfo or escaped path. Otherwise remote logout stays local. Neither Host headers nor a next parameter determines the destination.

The hint expires at the earliest original verified token, enrollment absolute or idle deadline, without renewal. Continuation and callback also cap at two minutes. Raw hints over 2000 bytes, plaintext over 2500 bytes or sealed cookies over 3800 bytes safely fall back to local logout. Missing, expired or cross-session hints do the same. If the OP becomes unavailable after navigation, local revocation and cookie clearing have already committed.

SQLite stores independent external identity and enrollment records. Grants are frozen at sign-in and intersected with current authority on every request. That re-evaluation never contacts the identity provider (D212): each request reopens the sealed login evidence stored with the session, applies the provider's current claim policy to it, recomputes the grants the current bindings give and keeps only those the session already held, and checks the account's disabled state and revocation floors. kudurru keeps no refresh token and never asks the provider about a signed-in user again, so a change made at the provider (a removed group, a disabled user) takes effect at the next sign-in, when the session expires, or when an administrator disables or signs out the account (external account administration). The legacy Kubernetes stack does not store OIDC users. Session defaults remain twelve hours absolute and thirty minutes idle; current settings and durable revocation floors govern SQLite enrollments. Startup provider resets can revoke old sessions and pending browser attempts even when the configuration bytes are unchanged. On Kubernetes the five sign-in controls are restart-bound; GET /api/v1/settings/_schema marks each restartRequired: true. See the deployment capability matrix for the unsupported account, session and CLI OIDC operations and their hints.

Stored providers can read only exact file paths granted by the operator in credentials.allowedFiles. This node setting is host-only and requires a restart; it is excluded from canonical cluster settings and replication. The resolver bounds reads to 64 KiB, requires a regular file, and redacts credential-resolution errors. credentials.allowedEnvironment grants named environment variables to credential references; values remain local. A host-configured auth.identityProviders entry separately delegates access to its configured secret file, without granting that path to stored objects. Config entries retain precedence over same-name stored providers even if their secret disappears: a failed config entry cannot activate another issuer.

flowchart LR
    Stored["Stored provider reference"] --> Grant["Exact host file grant"]
    Host["Host-configured provider"] --> Private["Entry's own file capability"]
    Grant --> Read["Bounded background credential read"]
    Private --> Read
    Read --> Registry["OIDC registry; config names stay reserved"]
flowchart LR
    KEY["KUDURRU_ENCRYPTION_KEY<br/>(+ _PREVIOUS while rotating)"] --> HK1["HKDF-SHA256<br/>info kudurru/session/v1"]
    KEY --> HK2["HKDF-SHA256<br/>info kudurru/oidc-preauth/v1"]
    KEY --> HK3["HKDF-SHA256<br/>info kudurru/internal/v1"]
    KEY --> HK4["HKDF-SHA256<br/>info kudurru/internal-ca/v1"]
    HK1 --> C1["session cookie<br/>AES-256-GCM: sid, principal,<br/>grants, exp, idle_exp, csrf"]
    HK2 --> C2["OIDC pre-auth cookie"]
    HK3 --> C3["node token (:8082)"]
    HK4 --> C4["Ed25519 CA → node<br/>certificates (90 days)"]

Because every node derives the same keys from the shared encryption key, any replica can open any session, and nodes trust each other on :8082, without a shared session store or an extra Secret. The cookie is __Host-kudurru_session when it is Secure (the default, since the API serves a self-signed certificate unless told otherwise), HttpOnly and SameSite=Lax, and is re-sealed at most once a minute to slide the idle timeout.

Local sessions now carry the account UID in their sealed principal, and personal and service-account tokens carry it in spec.owner.uid. Deleting and recreating an account cannot inherit credentials, even within the same second. Token creation reads the current account and refuses a supplied stale UID; authentication reads memory snapshots. Legacy local cookies without a UID require a fresh login.

SQLite schema 3 binds existing tokens before normal decoding, in the same transaction as the schema upgrade. Hashes, ownership, status, object metadata and audit history are preserved. Missing owners and tokens predating their owner remain unbound and cannot authenticate. Equal creation timestamps require audit evidence that the current account was created before the token; without that evidence, reissue the token. An invalid stored document rolls back the entire upgrade, and older binaries reject the newer database schema. Kubernetes legacy token conversion uses the explicit offline IAM migration; an unbound token is never silently rebound during authentication.

Service-account bootstrap authority lives in private PrincipalState objects, keyed by the account UID. ServiceAccount specs no longer contain a builtinAdmin field. Schema 4 moves the old flag and its identity binding in one transaction; a conflicting private row aborts the upgrade. New bootstrap accounts use an atomic create-only precondition. If an account already exists without matching private authority, bootstrap refuses to elevate it. A crash between creating a new account and recording authority can leave an unprivileged account; local administrator recovery remains available. Ordinary annotations and name reuse cannot grant bootstrap privileges.

ServiceAccount, RoleBinding and IdentityProvider now share the public CRD object model. Safe exports include their configuration while continuing to omit LocalUser, APIToken and PrincipalState. IdentityProvider uses clientSecretRef with exactly one secretRef, file or env capability; the old clientSecretFile field remains accepted only in host configuration. Credential Secret namespaces are chosen by the operator, never by public spec.

The provider schema also distinguishes scalar claim rules from bounded CEL expressions. A rule selects exactly one claim or expression; mappings may keep their existing defaults or select one form. Scalar comparison defaults to an empty required value. Each expression is limited to 4 KiB, with at most 64 validation rules. The captured offline provider compiles them (claim policy); the legacy live provider adapter, which the Kubernetes store still uses, rejects expressions before resolving a credential, so a stored restriction cannot be silently ignored.

SQLite schema 5 converts the old file/Secret references in the migration transaction, preserving UIDs, creation order, ownership, status and token hashes. It validates public admission and rolls back the entire upgrade if a legacy document is malformed, ambiguous or exceeds the migration bounds. Conversion does not read a file or grant its path. Kubernetes uses new server-issued CRD UIDs. The offline kudurru iam migrate command preserves original Secrets, archives the complete pinned source set and creates targets with private exact UID receipts. An uncertain Create cannot be adopted from matching public annotations or contents. Resume requires an explicit offline acknowledgment and the exact inspected journal resource version; see the upgrade runbook.

The token verifier has an optional migration resolver for private cutover proof. It verifies the token hash and expiry first, then checks the current account's disabled state, exact target UID, original token UID and original account creation floor. The resolver cannot supply roles or bootstrap authority. Local accounts retain their original UID and creation instant; name reuse, absent proof and later replacements fail closed. Kubernetes runtime admission captures status and immutable bindings from the same uncached, verified journal cut. It rechecks the journal UID and resourceVersion after verification. Native installs return no migration bindings; incomplete state and errors close remote admission.

The gate runs before identity bootstrap and outside the HTTP authentication stack, including login and OIDC callbacks. It admits at most eight concurrent checks, each bounded to five seconds. Closed admission returns a sanitized 503 with retry advice; IAM mutations independently recheck current admission before writing. Every unfinished initialization attempt captures fresh admission before priming and bootstrap. A startup API outage defers initialization and retries; it does not permanently disable user or token bootstrap. Explicitly disabled bootstrap stays disabled. DNS snapshots exclude management IAM kinds and DNS queries never call this gate. These reads do not provide a multi-object Kubernetes transaction: migration still requires all readers and writers to remain stopped. Complete immutable authentication publication and durable session state exist only on the complete SQLite runtime; Kubernetes keeps sealed-cookie sessions. Ordinary object backups do not yet carry raw migration journals and archives; protect them with the Kubernetes backup described in the runbook.

flowchart LR
    Legacy["Legacy IAM configuration"] --> Convert["Offline bounded conversion"]
    Convert --> Journal["Private archives and exact UID receipts"]
    Journal --> Complete["Completion CAS"]
    Convert --> Public["Public SA / RoleBinding / IdP"]
    Public --> Ref["Credential reference"]
    Ref --> Host["Host-granted resolver"]
    Private["Private token / user / PrincipalState"] --> UID["Exact account UID binding"]
    UID --> Public
    Complete --> Gate["Verified journal cut and admission"]
    Gate --> HTTP["Login, callbacks and authenticated HTTP"]
    Gate --> Writes["Current IAM write admission"]

The CLI

kudurru login --token kdr_… verifies and stores a token. Local username login signs in once, creates a personal token (kudurru-cli@<host>), attempts session logout, verifies the token, and stores it in the OS keyring or a 0600 fallback file. An enrolled authenticator uses --totp for a hidden terminal prompt or --totp-stdin for a six-digit code line. Combined password/code stdin uses one bounded reader, with the password first. Neither a code-valued flag nor a TOTP environment variable is supported, and codes are never persisted.

Typed login, token creation and logout refuse every redirect using a private client copy for each dispatch. Generic client requests retain their existing policy. The login flow makes no discovery probe, second login or automatic mutation retry; printable credential-chain errors use static safe messages. A lost response can follow a successful remote commit, so it leaves an uncertain outcome requiring explicit inspection. Only a verified personal token is saved. Public CLI browser and device sign-in use the D286/D287 flows below.

Authorization

Kudurru ServiceAccount binding subjects share one exact namespace/name across Kudurru and Kubernetes identities (D254). They do not select a provider. Authentication, account UIDs and disable/revocation lifecycles remain distinct; API-token scopes narrow both authorization paths. Use different names or namespaces for different grants and review account-creation rights and both binding/SAR paths. See the service-account binding contract.

flowchart TD
    R(["route permission"]) --> PUB{"public?"}
    PUB -- "yes" --> H["handler"]
    PUB -- "no" --> WHO{"principal?"}
    WHO -- "no" --> E401["401 unauthenticated"]
    WHO -- "yes" --> AU{"authenticated-only route?"}
    AU -- "yes" --> H
    AU -- "no" --> PW{"must change password?"}
    PW -- "yes" --> E403P["403 password_change_required"]
    PW -- "no" --> ROOT{"LocalRoot?"}
    ROOT -- "yes" --> H
    ROOT -- "no" --> SC{"token scopes cover<br/>resource.verb at scope?"}
    SC -- "no" --> DENY
    SC -- "yes" --> BA{"built-in admin, or an<br/>implicit grant (Node)?"}
    BA -- "yes" --> H
    BA -- "no" --> KSA{"Kubernetes<br/>ServiceAccount?"}
    KSA -- "yes" --> SAR{"SubjectAccessReview on<br/>kudurru.io/<resource> allows?"}
    SAR -- "yes" --> H
    SAR -- "no" --> BIND
    KSA -- "no" --> BIND{"a RoleBinding (or a frozen grant<br/>still backed by one) grants it?"}
    BIND -- "yes" --> H
    BIND -- "no" --> SCOP{"scopable route<br/>(lists, apply)?"}
    SCOP -- "yes" --> HF["handler filters<br/>per object"]
    SCOP -- "no" --> DENY["403 forbidden<br/>hint: missing resource, verb, scope<br/>(audited)"]

internal/rbac/permissions.yaml is the single source for resources, verbs and roles; it generates the aggregated ClusterRoles in the chart, and a lint fails the build when a route declares no permission.

RoleCan
viewerread zones, records, lists, groups, policies, stats, cache, settings (redacted)
auditorviewer + the query log (with client addresses), its export, the audit log
operatorviewer + the query log (no export); write records, lists, groups, policies, clients; flush the cache; toggle blocking; decide unblock requests
zone-admineverything on one zone or one zone group (the only scoped role: zone-admin@zone:<name> or zone-admin@zonegroup:<group>)
admin*.*

Some routes check more than their declared permission, or a permission that the role names do not suggest:

  • POST /queries/{id}/actions declares blocklists.write for the list edit and also checks querylog.read before it reads the logged query by ID.
  • GET /queries/export needs querylog.export; GET /queries needs querylog.read.
  • The migration reads GET /imports/existing, GET /imports/runs and GET /imports/runs/{id} need settings.write, the permission that starts and changes imports, so only admin reads import runs.

A lint runs both ways (D393). Every route declares a permission that permissions.yaml defines (TestRoutePermissionLint), and every declared verb is checked by a mounted route or a handler, or is listed under reserved: in permissions.yaml with the release that is to use it (TestPermissionVerbsAreUsedOrReserved). Reserved verbs (for example zones.sign, groups.*) can appear in roles but allow nothing yet. Each reservation names its target release: the IAM administration verbs (groups.*, users.delete, serviceaccounts.write, serviceaccounts.delete, identityproviders.write, identityproviders.delete) are still v0.2 surfaces; the rest are v1.0. The integration administration verbs are in use (D400): integrations.write and integrations.delete guard Integration writes on the object routes, and integrations.secrets is checked besides integrations.write by a write that binds or changes spec.credentials, or that changes spec.type, spec.unifi.endpoint, spec.unifi.tlsFingerprint or spec.webhook.endpoint while credentials are bound, on the object the write is compare-and-swapped against (in the SQLite current command, on its own read). The source scan credits a handler check only through the known check helpers (require, allowed, authorize, permission, zoneRequirement, servingHTTPCluster) and permission literal types (perm, rbac.Attributes, the auth stack Route); a resource and verb pair of the same shape anywhere else fails the lint until the helper is added to the scan or the code is changed.

A binding gives a role at a scope (cluster, zone:<name> or zonegroup:<group>) to users, groups (the prefixed IdP group names) or service accounts.

Zone groups (D385)

A zone group is a label: a DNSZone belongs to group prod when it carries kudurru.io/zonegroup: prod (at most one group per zone; no label, no group). A zonegroup:prod binding covers each member zone and the record sets whose zoneRef names one. Routes still present only cluster and zone scopes; the code that resolves the zone of a request also states the zone's group in the authorization attributes, read from the same source as the zone:

flowchart LR
    REQ["request on zone:a<br/>(route, item, list filter)"] --> SRC{"runtime"}
    SRC -- "complete SQLite" --> CUT["the request's captured<br/>publication: DNSZone a"]
    SRC -- "Kubernetes" --> ST["store read: DNSZone a"]
    CUT --> ATTR["attributes: zone:a,<br/>group = label value"]
    ST --> ATTR
    ATTR --> AZ{"binding or grant scope<br/>cluster, zone:a or<br/>zonegroup of that label?"}
    AZ --> CMD["SQLite command: the transaction<br/>reads DNSZone a again and<br/>replaces the group before reauthorizing"]
  • A zone that is absent or unlabeled is in no group, so a group binding grants nothing for it; cluster and zone bindings never depend on the label.
  • A command transaction (and the primary, for a follower's forwarded command) discards the caller's group and resolves it from its own read, so a label removed or a binding deleted before commit denies the write. A follower's early admission uses its own captured publication.
  • Putting a zone into a group, moving it, or taking it out is access control: a DNSZone write that changes the label needs zones.write at cluster scope, on both drivers. Creating a zone already needs it. On Kubernetes both rules are decided again on the read the write is compare-and-swapped against (its resourceVersion): a label removed while a group member's PUT is in flight cannot be put back by that PUT, and a zone an administrator deletes while a group member's or zone admin's PUT is in flight is not created again by it (that read finds no zone, so the PUT is a create and needs cluster scope; a delete after that read fails the compare-and-swap with 409). A SQLite command reads and authorizes in one transaction, so it has no such window.
  • On Kubernetes every API write that changes the label (adds it, changes it or removes it, all by a cluster-scope writer) takes the zone over as a whole-object PUT (the forced takeover used for bootstrap defaults): other field managers' ownership (kubectl, a GitOps tool) moves to api, and every field the document omits is removed, not only the label. This applies when the zone's kudurru.io/managed-by is empty, api or bootstrap; a zone managed by another writer answers 409 managed_by first. Without it, server-side apply would keep a label kubectl also owns and the removal would answer 200 with the zone still in its group. The answer is checked: a written zone whose label is still not the requested one answers 409 instead of 200. A GitOps tool that applies the label again puts the zone back; change it at its source.
  • The group is resolved only when the decision without it is a denial (Scope.Admits only adds coverage), at most once per zone per request, and lists decide each zone on the listed object. A zone that cannot be read answers 503 (authorizer unavailable), not a denial, also in lists and GET /auth/me: a record set list that needs the group of an unreadable zone, or a permission matrix with a verb that cannot be decided, fails as a whole with 503 instead of answering 200 with the items or verbs left out.
  • Lists (GET /zones, GET /objects/dnszones, GET /objects/dnsrecordsets) filter per item through the same rule. GET /zones reports each zone's zoneGroup; GET /auth/me reports scopedPermissions["zonegroup:<group>"].
  • API token scopes and frozen session grants may name zonegroup:<group>; they intersect with live bindings exactly like zone scopes.
  • On Kubernetes the label is an ordinary label, so whoever may edit DNSZone objects with kubectl may change a zone's group; SubjectAccessReview has no zone group concept and still names the zone (resourceNames).

On the Kubernetes driver a session carries the grants resolved at sign-in (D48), not the groups that matched. A frozen grant is honored only while a current binding still provides it and no binding change removed it after the session's grants were resolved. Each replica records such removals as revocation floors, persists them in the kudurru-grant-floors Secret (a commutative maximum under resourceVersion CAS) and periodically merges every replica's floors. A restarted replica, or one that missed the change, therefore cannot revive an earlier session after the binding is granted again. Until a replica first loads the floors, frozen grants are refused; live bindings and built-in authority still apply. A removal that happens while no replica is running is not observed. Kubernetes identities can instead be authorized by Kubernetes RBAC through SubjectAccessReview on the kudurru.io resources, including virtual ones such as querylogs and caches; a request is allowed when either path allows it, and the audit record names the path.

Kubernetes impersonation (opt-in, D386)

auth.kubernetes.mode is sar by default: kudurru authorizes every request itself (bindings, SubjectAccessReview for Kubernetes service accounts) and then writes to the apiserver as its own ServiceAccount. With impersonate (kube driver only) kudurru still authorizes the request exactly as above, and the kube driver then sends each API write of a kudurru.io object (server-side apply, create, delete, and the managed-fields takeover of a forced write) with Impersonate-User and Impersonate-Group headers for the request's principal. Kubernetes RBAC must therefore allow the write too, and the apiserver audit log records the principal as impersonatedUser.

PrincipalKubernetes userKubernetes groups
Kubernetes service accountsystem:serviceaccount:<namespace>:<name>the groups of its token
Local user (password session or API token)kudurru:user:<name>kudurru:group:<group> for each of its stored groups
OIDC user, bearer JWTkudurru:user:<name> (the provider-prefixed username, for example corp:alice)kudurru:group:<group> for each group in the token (provider-prefixed)
OIDC user, dashboard session or personal API tokenkudurru:user:<name>none (D48)
Kudurru service account and its API tokenskudurru:serviceaccount:<namespace>:<name>none
Unix-socket peer (kudurru admin), peer nodesnot impersonated: kudurru's own ServiceAccount
flowchart LR
    REQ(["API write"]) --> AZ{"kudurru authorization<br/>(bindings, SAR)"}
    AZ -- "deny" --> F1["403 forbidden"]
    AZ -- "allow" --> MODE{"auth.kubernetes.mode"}
    MODE -- "sar" --> SA["apiserver write as<br/>the kudurru ServiceAccount"]
    MODE -- "impersonate" --> IMP["apiserver write with<br/>Impersonate-User/Group"]
    IMP --> K8S{"Kubernetes RBAC<br/>allows the principal?"}
    K8S -- "yes" --> OK["written; audit names<br/>the principal"]
    K8S -- "no" --> F2["403 forbidden<br/>(nothing written)"]
    IMP -- "credential ended" --> F3["401 unauthenticated<br/>(nothing sent)"]
    IMP -- "kudurru lacks impersonate" --> F4["503 unavailable<br/>(nothing written)"]

Groups reach Kubernetes only when the request itself carries them. D48 keeps an OIDC user's identity-provider groups out of the sealed session cookie and out of personal API tokens (they hold resolved kudurru grants instead), so a dashboard or personal-token write by an OIDC user is sent with no Impersonate-Group: a Kubernetes binding to kudurru:group:<idp>:<group> does not match it. Bind those users by name (kudurru:user:<idp>:<name>). Group bindings work for local users, whose stored groups are reloaded on every request, and for OIDC bearer JWTs, which carry their groups claim.

Only those writes are impersonated. The managedBy and resourceVersion reads before them, reads and lists, informers, status and finalizer updates, Leases, the internal kinds kudurru keeps in Secrets (local users, API tokens, principal state, migration runs, and the zone, integration and TSIG runtime kinds), the audit log, and writes without a requesting principal (controllers, RFC 2136 UPDATE, the external-dns webhook, integrations) run as kudurru. Sessions are sealed cookies and write nothing. RoleBinding, ServiceAccount and IdentityProvider are kudurru.io custom resources, so their API writes are impersonated like any other kudurru.io object and need Kubernetes RBAC on rolebindings, serviceaccounts and identityproviders in the kudurru.io group.

A write whose principal's credential bounds ended during the request (or that names no user) is 401 unauthenticated, and one whose name is not a valid Kubernetes user or group name is 403 forbidden; neither is ever sent as kudurru. Any other Kubernetes 403 for an impersonated write is 403 forbidden with the apiserver's reason: usually Kubernetes RBAC for the principal, but an admission webhook or a terminating namespace refuses the same way. When kudurru's own identity lacks the impersonate verb (on Kubernetes 1.35 and later the apiserver's constrained impersonation reports it as impersonate-on: on the object), the write is 503 unavailable and the server logs the apiserver's message; the API answer does not name kudurru's ServiceAccount. Only a 403 in the apiserver's own form counts as that refusal: ... forbidden: User "<requester>" cannot impersonate..., where the quoted requester is not the impersonated user. A principal whose name contains that phrase, or a webhook message that uses it, stays a 403 forbidden. Server-side apply needs create and patch (plus delete for deletes) on the resource, and a forced write's managed-fields takeover needs patch. A multi-object API operation (a zone with its record sets) can be refused part way, like any other Kubernetes error between its writes.

The chart's ClusterRole gains impersonate on users, groups and serviceaccounts only when its value auth.kubernetes.mode is impersonate. The kustomize bases never carry that rule: a kustomize deployment that sets the mode in its node configuration must add it to the kudurru ClusterRole itself (see Helm, impersonation). Kubernetes cannot narrow that verb to the kudurru: names, so a compromised kudurru pod can act as any identity in the cluster: it is cluster-admin-equivalent (D55). SubjectAccessReview stays the default for that reason. After enabling it, give the bootstrap admin (kudurru:user:admin) and every other principal the Kubernetes RBAC they need, for example by binding the chart's aggregated <release>-admin ClusterRole.

Kubernetes account commands (D387)

The Kubernetes driver does not offer authenticator (TOTP) management or the local-user commands. Kubernetes accounts use their identity provider's second factor. GET /auth/status reports this in capabilities before a client tries (factorManagement, localUserCommands and iamObjectCommands, all false on Kubernetes and true on the complete SQLite runtime), and the routes answer (each without Retry-After, with a hint):

RouteAnswer on Kubernetes
GET /auth/totp, POST /auth/totp/{setup,confirm,disable}, POST /iam/users/{name}/totp/recover503 factor_management_unavailable
POST /iam/users, POST /iam/users/{name}/password, PATCH and DELETE /iam/users/{name}503 user_management_unavailable
POST /iam/serviceaccounts, PUT/DELETE /iam/serviceaccounts/{namespace}/{name}, POST .../{name}/tokens, POST /iam/identityproviders, PUT/DELETE /iam/identityproviders/{name}503 iam_management_unavailable (D396)
POST /auth/login with totpCode503 factor_unavailable

Password change for the signed-in local user (POST /auth/password) and the kudurru admin socket commands (reset-password, create-token) still work.

IAM writers (D396)

The complete SQLite runtime adds reviewed writers for the remaining IAM objects, built like the RoleBinding commands (D294):

OperationPermissionReviewEffect in the same commit
PATCH /iam/users/{name}users.writeuid, resourceVersiondisplay name, groups, disabled; a group or disabled change raises the account floor and deletes the account's tokens
DELETE /iam/users/{name}users.deleteuid, resourceVersionaccount floor, token deletion
POST /iam/serviceaccountsserviceaccounts.writeabsent targetcreate only
PUT /iam/serviceaccounts/{namespace}/{name}serviceaccounts.writeuid, resourceVersiondescription, disabled; disabling raises the floor and deletes the tokens
DELETE /iam/serviceaccounts/{namespace}/{name}serviceaccounts.deleteuid, resourceVersionaccount floor, token deletion
POST /iam/serviceaccounts/{namespace}/{name}/tokensserviceaccounts.write and tokens.writeuidone token; its secret only in the answer
POST /iam/identityprovidersidentityproviders.writeabsent target, id not in the configuration filecreate only
PUT/DELETE /iam/identityproviders/{name}identityproviders.write/.deleteuid, resourceVersionprovider floor for a changed spec or a deletion

Each command checks the declared permission and cookie CSRF against the request's original view before the body is read, decodes the body strictly (no duplicate or unknown keys), and then runs one current command that verifies the original raw credential again for every attribute, compares the exact reviewed UID and resourceVersion, requires the API manager, stages the object through security.Apply/security.Delete (which stage the account or provider floor) and deletes the ended tokens. The object audit row commits with them. The built-in admin, accounts of other managers and service accounts with private bootstrap authority (PrincipalState) are refused by replace, delete and token issuance alike (serviceAccountAdministrable): a bootstrap-authority token would carry admin with no binding to revoke. A token issued for a service account expires no later than the caller's own API token, as in POST /auth/tokens, and within auth.tokens.maxLifetime. It must authenticate from its stored form inside the transaction before the answer carries it; only its hash is stored, and no log, audit row or error contains the secret. A provider object holds a credential reference, never a value. After the commit the provider coordinator republishes the provider set as for any other source change, and a new provider is offered after its discovery and license admission.

sequenceDiagram
    participant A as Administrator
    participant H as API route
    participant C as Current SQLite command
    A->>H: Read exact UID and resourceVersion
    A->>H: Reviewed command
    H->>H: Permission, CSRF, strict body (follower: 503 primary_required)
    H->>C: Original raw proof, review, desired state
    C->>C: Reauthorize, compare review and manager
    C->>C: Stage object + floor + token deletion + audit
    opt Historical floors reach compaction trigger or section is full
        C->>C: Remove affected enrollments and tokens; collect orphan factor rows
        C->>C: Fold eligible floors into monotonic revocation checkpoint
    end
    C-->>H: Commit or roll back everything
    H-->>A: Object, 204, or token shown once

D413 replaces permanent historical floor growth with transactional compaction. At 256 retained floors, before admitting a row to a full section, or when an encoded write would exceed the byte budget, the writer materializes each floor's effect: it removes affected local/external session enrollments and pending browser attempts, deletes affected API tokens, and collects TOTP replay records whose exact local account UID no longer exists. Absent enrollments and attempts deny replay. New IDs come from the server's cryptographic random generator. Unaffected stored sessions and API tokens retain their original lifetime and identity; disabled-factor replay for a live UID stays.

The same command folds eligible floors into the greatest historical revocation time in the root's monotonic checkpoint. Raw OIDC proof and previously sealed JWT request evidence must have an issue time strictly after that checkpoint; an older OIDC token requires fresh authentication, even if its provider gave it a much longer expiry. New enrollment times also must be strictly later. External issuance rechecks the original JWT after any compaction in its command; assigning a newer session timestamp cannot make old proof fresh. No arbitrary retention TTL or maximum OIDC token lifetime is assumed.

External account floors remain because they bind administrative revisions and prevent missing tuples from silently reprovisioning. Exact provider floors remain while enrolled external proof still needs them: that proof's original issue time can precede the enrollment time. Provider plans accept a staged checkpoint at or after their required revocation time when compaction replaced their exact floor. The object change, affected-token deletion, session removal, checkpoint, manifest and audit share the original command's commit and rollback, and replicate together. A near-full database can recover on its next authorized IAM write.

The section still has servingauth.MaxRows (4096) rows and a 4 MiB byte limit, shared with live sessions, factor state, external identities, browser attempts and other owners. Compaction preserves other owners and refuses malformed history. When genuinely retained state fills those bounds, a new admission returns ErrBounds (503 unavailable) and rolls back the entire command. The shared-state refusal and recovery from a full historical inventory have separate mounted API regressions; more than 4,096 real account create/enroll/delete cycles, restart, replica promotion, old proof rejection and unrelated credential continuity are covered by the security-owner tests.

All of these operations are primary in the follower contract (D368). On Kubernetes they refuse as listed above; GET /iam/serviceaccounts/{namespace}/{name} and GET /iam/identityproviders/{name} read the object there too.

The dashboard's Identity tab (Access page) is a client of these commands (dashboard/src/components/access/). A local-account command takes the UID and resourceVersion of the row the operator chose (GET /iam/users carries both); a ServiceAccount, IdentityProvider or RoleBinding command first reads the item (GET .../{name}) and sends that read's values, and refuses an object whose kudurru.io/managed-by is not api before sending anything. A replace sends the whole object: the dashboard carries the stored labels, operator annotations (never the manager annotation) and the provider fields its form does not edit. Each dialog sends one request and never repeats it: a 4xx is shown as a refusal and locks a reviewed command; no answer, a 5xx, or a bare 503 unavailable (the catch-all of servingHTTPAuthError, which the security-row bound also answers) is shown as an unknown outcome and locks the dialog; the follower, static, and driver refusals (primary_required, read_only, user_management_unavailable, iam_management_unavailable) are refusals. Controls are disabled with the reason from the session's permissions, static mode, the follower table (dashboard/src/lib/follower.ts) and GET /auth/status capabilities.localUserCommands/iamObjectCommands. An issued service account token lives only in the token dialog's component state: it is not in a query or mutation cache, and it is gone when the dialog closes.

Node to node (:8082)

RouteUsed by
GET /internal/statusthe Nodes page (GET /api/v1/nodes fetches every peer's status), edge supervisors
GET /internal/lists/{digest}replicas pulling list bodies from the leader
GET /internal/zonesedge supervisors (zone serials)
GET /internal/catalogue, /internal/catalogue/adguardreplicas pulling the services catalogue

Always TLS with the derived CA, always the bearer node token, rate-limited per client. The same token is accepted on :8080 as a Node principal with viewer and auditor.

External account administration (D289)

The complete SQLite runtime exposes persisted external identities through GET /api/v1/iam/external-users and GET /api/v1/iam/external-users/{name}. The account name is the existing provider-incarnation/issuer/subject digest; the independent account UID is separate from the provider UID. A read returns a revision binding the identity profile, disabled state and account revocation floor. Pages bind the security epoch and reject continuation after it changes. Responses expose profile data, never token hashes or session evidence.

POST .../{name}/disable, /enable and /logout require the reviewed UID and revision plus current cluster users.write. Cookie requests retain CSRF checks; commands reverify the original raw credential against the transaction, including current permissions, dependencies, writer admission and final credential time. Disable and logout raise the exact account floor, revoke its enrolled sessions and delete its personal tokens atomically. Token deletion matches immutable UID/provider/issuer/subject ownership, including tokens under an earlier username. Another identity with the same display name is unaffected. Enable preserves all floors and does not restore any revoked credential or grant a role.

sequenceDiagram
    participant A as Administrator
    participant H as Captured HTTP request
    participant C as Current SQLite command
    participant P as Publication
    A->>H: Read exact account UID and revision
    A->>H: Confirm disable, enable or logout
    H->>C: Original raw proof, reviewed UID and revision
    C->>C: Reauthorize, compare revision, stage account/token/session changes
    C->>C: Append local audit#59; final credential and writer checks
    C-->>H: Commit or roll back all changes
    H-->>A: 204 or explicit refusal
    C->>P: Publish committed account state
    A->>H: New read observes publication

The audit event and token deletions share the same transaction and rollback boundary. The local audit record does not itself advance the replicated image. Account state, floors, sessions and token deletions survive restart and replica installation/promotion. The dashboard does not optimistically acknowledge a published revision; it retires the selection after a command and observes the result with a new read. An uncertain mutation is never automatically retried.

Legacy and Kubernetes Stack hosts return external_users_unavailable after normal permission checks. Local administrators can revoke external accounts even when the provider license is unavailable; enabling does not bypass provider licensing or ordinary login admission. This is Kudurru account administration, not remote identity-provider logout or external identity provisioning.

Public CLI browser login (D286)

Without local-password or explicit token options, kudurru login --server https://dns.example --provider corp uses the provider's explicit public CLIClientID. Register http://127.0.0.1:8000/callback and http://127.0.0.1:18000/callback for that public client with code flow and S256 PKCE. The second port is used only when the first is already in use. API and OP connections require verified HTTPS; --ca-file configures API trust and --oidc-ca-file configures OP trust. Browser trust must also recognize the OP.

The CLI opens the platform browser and owns a bounded loopback callback with independent state, nonce and PKCE verifier. It exchanges the one-time code with the OP as a public client, then supplies the exact raw ID token to the server's read-only verification route. The normal credential store keeps that original ID token and its original expiry. No Kudurru PAT, browser session or server-side CLI session is issued, and no refresh token is retained or automatically used. The existing local-password login continues to mint a personal token; explicit token login and logout retain their prior semantics.

The provider list/prepare/verify routes bind the complete original provider UID, origin, spec, policy, resource and installed credential identity. A short-lived AEAD receipt only correlates the source and flow; it is reusable and is not an identity grant. Verification requires ordinary raw bearer admission, exact public CLI audience/azp, nonce and at_hash when supplied, original time bounds, and current captured source. Later writes retain the normal original raw proof and transaction reauthorization/final-commit checks. Public preparation is bounded per normalized client IP, independently of username lockout buckets.

Local acceptance uses a real TLS OP with signed JWTs, actual loopback sockets and installed Chrome. It does not certify every vendor's public-client setup; operators must register the public client and both exact loopback redirects.

Public CLI device login (D287)

Use kudurru login --server https://dns.example --provider corp --device on hosts without a browser. The provider must advertise a trusted HTTPS device endpoint, the RFC 8628 device grant and public none token authentication for its explicit CLIClientID. An omitted capability is unsupported. The CLI displays the provider, public client, verification URI and user code; it never displays the device code or opens verification_uri_complete automatically. Follow the provider's verification instructions on another device.

Polling retains the original grant and deadline. The first wait uses the advertised interval (five seconds when omitted); authorization_pending waits again and slow_down adds five seconds to every later wait. A connection timeout before a response doubles the wait; other HTTP refusals, redirects, unknown OAuth errors and body-read timeouts stop the flow. The deadline is the earliest of the caller, original source receipt and OP expires_in measured before the authorization request. Work is capped at 600 polls. Cancellation and caller expiry retain their context errors; no new grant or receipt repairs a failure.

Success still requires ordinary raw ID-token bearer admission, exact CLI audience/azp, optional at_hash and the captured provider/source/installed credential/time bounds. Device verification does not fabricate a browser nonce or browser proof marker. RFC 8628 does not standardize a nonce binding between a device code and the returned ID token; the receipt is reusable source correlation, and the raw token must independently qualify. The CLI stores only the original verified ID token, with no RP enrollment, refresh-token storage or new durable credential issuer. Explicit --device does not consume an ambient API bearer or silently switch to local-password login.

Routes the Kubernetes authentication stack does not implement

On the Kubernetes driver the API forwards /auth and /iam requests to the legacy authentication stack. Public CLI login and provider logout continuation need the captured provider resources of the complete SQLite runtime, so that stack refuses them explicitly instead of leaving them unregistered:

RouteAnswer on Kubernetes
GET /auth/cli/providers, POST /auth/cli/{idp}/prepare, POST /auth/cli/{idp}/verify503 cli_login_unavailable with a hint to use an API token or a local account
GET /auth/oidc/{idp}/logout, GET /auth/oidc/{idp}/logout/callback503 provider_logout_unavailable; POST /auth/logout/browser already ended the local session and never returns a continuation path there
GET /iam/rolebindings/{namespace}/{name}the RoleBinding object from the same cache as the list (read only)
any other forwarded route without a handler503 unavailable with the hint "requires the complete SQLite runtime"

kudurru login without --token or --username reads the provider list first. It recognizes cli_login_unavailable and prints a fixed message that names the two supported modes; it stores nothing. No forwarded route answers with the HTTP multiplexer's plain-text 404.

Auth control reload

Complete SQLite serving applies five public settings through its original immutable auth View: auth.localLogin, auth.session.idleTimeout, auth.session.lifetime, auth.session.secure and auth.tokens.maxLifetime. New local/external enrollment and token issuance use the same effective controls as status, including installed environment locks. The entire canonical document validates before those locks apply. Exact copied lock values participate in the View dependency identity used by current commands.

flowchart LR
    C["validated canonical auth controls"] --> V["complete immutable auth View"]
    H["installed host environment locks"] --> V
    V --> R["original request capture"]
    R --> K["cookie selection, writes and clears"]
    R --> T["actual current-command transaction"]
    T --> E["new credential with fixed deadlines"]
    E --> S["postcommit cookie-policy check"]
    S --> OK["seal once or refuse without reissuance"]

The new lifetimes affect only newly issued credentials. Existing absolute, idle and token expiry timestamps survive reload and restart unchanged; this change does not slide idle deadlines. localLogin controls new password/TOTP enrollment while retaining existing-session and break-glass behavior.

Cookie selection and every complete session, browser, logout, factor and password write/clear use the request's original View with its immutable host name/path template. No old-name alias is accepted after the new publication. A naming or security change may require a fresh sign-in or browser flow. If cookie policy changes between enrollment commit and sealing publication, the response refuses to seal a cookie and never repeats issuance.

Settings metadata reports these keys as hot only when the runtime explicitly implements this lifecycle. Legacy Stack/Kubernetes remains restart-bound. The ten host auth inputs also remain startup/restart-bound: bootstrap password file (initial bootstrap only), file-defined providers, provider allowed/local origins, algorithms, system/CA trust, Kubernetes mode and admin-socket path/group. Durable IdentityProvider object changes retain their separate existing lifecycle.

Mounted qualification covers host-lock issuance/status parity, live PATCH, true server stop/restart with retained deadlines, TLS API/OP browser/logout, changed cookie clear paths, old-alias refusal and postcommit mismatch without another issuance. Replica tests cover local host locks, writer refusal and retained revocation. These results do not qualify hot auth controls on Kubernetes.

Source: docs/architecture/access.md