Skip to content

feat: realm key store - zero-config mfa seed encryption + optional secrets kek - #3255

Merged
tada5hi merged 3 commits into
masterfrom
feat/realm-key-store
Jul 14, 2026
Merged

tada5hi merged 3 commits into
masterfrom
feat/realm-key-store

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Implements plan 069: generalizes auth_keys into a per-realm key store, makes MFA seed encryption zero-config, and adds an optional KEK that wraps all stored key material at rest.

  • auth_keys gains a JWK use discriminator (sig | enc, RFC 7517 §4.2; existing rows default sig). Per-realm enc keys (32-byte oct) are minted lazily on first use, mirroring the existing RSA signing keys. Port promoted to core/key/ (IKeyRepository), adapter renamed KeyRepositoryAdapter.
  • Zero-config MFA: TOTP seeds encrypt under the user's realm enc key via self-describing v1.<key_id>.<blob> blobs (RealmCipher — key-id-addressed decrypt with realm-binding assert; unknown/foreign key fails closed as a plain verification failure). MFA_ENCRYPTION_KEY is removed (never released — no deployments, no legacy-blob path); MFA_ENABLED=true is now sufficient.
  • Optional SECRETS_ENCRYPTION_KEY (base64, 32 bytes): wraps ALL auth_keys material at rest — realm JWT signing private keys included — as wrapped.v1. blobs. Existing plaintext rows wrap lazily on read; a wrapped row met without a KEK fails loud; production boots without one log a single warning. Unset = Keycloak/authentik parity posture (both store OTP secrets and signing keys plaintext).
  • use hygiene is load-bearing: the signer supports HMAC (oct) signing keys, so without filtering it could sign tokens with a realm's MFA enc key. Signer + authorize grant (at_hash alg) request JWKUse.SIGNATURE, the verifier rejects a kid resolving to a non-sig key, and both JWKS surfaces filter use = sig — all pinned by tests.
  • Realm delete = crypto-shredding (cascade drops the enc keys).

Migration

auth_keys.use ALTER folded into the unreleased 1783856507391 migration (both dialects) per the fold-per-release convention. This PR should merge before the next server-core release — that keeps the MFA_ENCRYPTION_KEY removal a clean deletion and the fold window open.

Testing

  • Full server-core suite green (151 files / 1591 tests); check:types green.
  • New: core/key wrap + RealmCipher unit specs; KEK wrap/unwrap matrix over an isolated in-memory DataSource (test/unit/app/modules/oauth2/key-repository.spec.ts); http pin for zero-config enrollment + JWKS enc-key exclusion; verifier enc-kid rejection.
  • MFA http suites now run with no key config — proving the zero-config path end to end.
  • Migration run → 12× revert → run verified on MySQL and Postgres; use column present in both schemas.

Follow-up (plan 070): consume the cipher seam for client secret_encrypted (dormant todos), IdP client_secret, LDAP bind password.

Summary by CodeRabbit

  • New Features

    • MFA TOTP secrets are now encrypted automatically with realm-specific keys, requiring no separate MFA encryption key.
    • Added optional secretsEncryptionKey configuration to protect stored key material.
    • Encryption and signing keys are now managed separately, and encryption keys are excluded from JWKS and token verification.
    • Added fail-closed handling for invalid or unknown MFA encryption keys.
  • Documentation

    • Updated deployment and architecture documentation for realm key management and configuration changes.
  • Tests

    • Added coverage for key creation, wrapping, realm-bound encryption, MFA enrollment, and JWKS filtering.

…crets kek

- generalize auth_keys with a JWK use discriminator (sig | enc); per-realm
  oct enc keys are minted lazily, mirroring the existing RSA signing keys
  (port promoted to core/key IKeyRepository, adapter KeyRepositoryAdapter)
- MFA TOTP seeds encrypt under the user's realm enc key via self-describing
  v1.<key_id>.<blob> blobs (core/key RealmCipher, key-id addressed decrypt
  with realm binding assert) - MFA_ENCRYPTION_KEY is removed while still
  unreleased; MFA_ENABLED=true is now sufficient to enable MFA
- optional SECRETS_ENCRYPTION_KEY (base64, 32 bytes) wraps ALL auth_keys
  material at rest (realm signing private keys included) as wrapped.v1.
  blobs, with lazy wrap-on-read adoption, loud failure on a missing KEK,
  and a one-time production boot warning when unset
- use hygiene enforced at every sig consumer: signer + authorize grant
  request JWKUse.SIGNATURE, the verifier rejects a kid resolving to a
  non-sig key, and both JWKS surfaces filter use=sig
- auth_keys.use ALTER folded into unreleased migration 1783856507391
  (both dialects; run/revert/re-run verified on mysql + postgres)
Copilot AI review requested due to automatic review settings July 14, 2026 12:38

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR replaces configuration-based MFA encryption with per-realm encryption keys, adds JWK usage discrimination, introduces KEK wrapping and RealmCipher, updates OAuth2/JWKS paths to use signature keys only, and changes TOTP verification to fail closed for invalid or foreign key references.

Changes

Realm Key Store and MFA encryption

Layer / File(s) Summary
Key usage contracts and configuration
.agents/architecture.md, apps/server-core/src/adapters/database/..., apps/server-core/src/app/modules/config/..., apps/server-core/src/core/key/..., docs/src/guide/..., packages/core-kit/..., packages/specs/...
Adds sig/enc key usage, persists auth_keys.use, replaces mfaEncryptionKey with optional secretsEncryptionKey, and documents the Realm Key Store.
Key repository and protected material
apps/server-core/src/app/modules/oauth2/..., apps/server-core/src/core/key/wrap.ts, apps/server-core/test/unit/app/modules/oauth2/..., apps/server-core/test/unit/core/key/wrap.spec.ts
Adds KeyRepositoryAdapter, lazy signature/encryption key creation, optional KEK wrapping, lazy retroactive wrapping, and failure handling for unavailable KEKs.
Realm cipher and MFA integration
apps/server-core/src/core/key/realm-cipher.ts, apps/server-core/src/core/entities/user-authenticator/..., apps/server-core/src/app/modules/http/modules/controller.ts, apps/server-core/test/unit/core/...
Encrypts TOTP seeds into versioned realm-bound blobs, resolves and caches encryption keys, and treats decryption failures as verification failures.
Signature-only OAuth2 and JWKS consumers
apps/server-core/src/core/oauth2/..., apps/server-core/src/adapters/http/controllers/workflows/jwks/..., apps/server-core/src/adapters/http/controllers/workflows/token/types.ts, apps/server-core/test/unit/core/oauth2/...
Migrates consumers to IKeyRepository, selects signature keys explicitly, rejects encryption keys during token verification, and excludes them from JWKS output.
Application and integration validation
apps/server-core/test/unit/config/..., apps/server-core/test/unit/http/controllers/...
Updates MFA setups to omit explicit encryption keys and verifies automatic realm-key creation, encrypted TOTP storage, and JWKS exclusion.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant UserAuthenticatorService
  participant RealmCipher
  participant KeyRepositoryAdapter
  participant auth_keys
  UserAuthenticatorService->>RealmCipher: encrypt(realmId, TOTP seed)
  RealmCipher->>KeyRepositoryAdapter: resolve enc key
  KeyRepositoryAdapter->>auth_keys: create or load realm key
  auth_keys-->>RealmCipher: key id and material
  RealmCipher-->>UserAuthenticatorService: versioned encrypted blob
  UserAuthenticatorService->>RealmCipher: decrypt(blob, realmId)
  RealmCipher->>KeyRepositoryAdapter: resolve embedded key id
  RealmCipher-->>UserAuthenticatorService: seed or verification failure
Loading

Possibly related PRs

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: a realm key store with zero-config MFA seed encryption and optional secrets KEK.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/realm-key-store

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

authup

npm i https://pkg.pr.new/authup@3255

@authup/client-web

npm i https://pkg.pr.new/@authup/client-web@3255

@authup/server-core

npm i https://pkg.pr.new/@authup/server-core@3255

@authup/access

npm i https://pkg.pr.new/@authup/access@3255

@authup/client-web-kit

npm i https://pkg.pr.new/@authup/client-web-kit@3255

@authup/client-web-kit-theme

npm i https://pkg.pr.new/@authup/client-web-kit-theme@3255

@authup/client-web-nuxt

npm i https://pkg.pr.new/@authup/client-web-nuxt@3255

@authup/client-web-theme

npm i https://pkg.pr.new/@authup/client-web-theme@3255

@authup/core-http-kit

npm i https://pkg.pr.new/@authup/core-http-kit@3255

@authup/core-kit

npm i https://pkg.pr.new/@authup/core-kit@3255

@authup/core-realtime-kit

npm i https://pkg.pr.new/@authup/core-realtime-kit@3255

@authup/errors

npm i https://pkg.pr.new/@authup/errors@3255

@authup/i18n

npm i https://pkg.pr.new/@authup/i18n@3255

@authup/kit

npm i https://pkg.pr.new/@authup/kit@3255

@authup/server-adapter-kit

npm i https://pkg.pr.new/@authup/server-adapter-kit@3255

@authup/server-adapter-node

npm i https://pkg.pr.new/@authup/server-adapter-node@3255

@authup/server-adapter-socket-io

npm i https://pkg.pr.new/@authup/server-adapter-socket-io@3255

@authup/server-adapter-web

npm i https://pkg.pr.new/@authup/server-adapter-web@3255

@authup/server-kit

npm i https://pkg.pr.new/@authup/server-kit@3255

@authup/server-test-kit

npm i https://pkg.pr.new/@authup/server-test-kit@3255

@authup/specs

npm i https://pkg.pr.new/@authup/specs@3255

commit: 645c21b

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/server-core/src/adapters/database/migrations/postgres/1783856507391-Default.ts`:
- Around line 112-125: Keep the existing 1783856507391-Default migrations
immutable by removing the auth_keys.use schema changes from both
apps/server-core/src/adapters/database/migrations/postgres/1783856507391-Default.ts
(lines 112-125) and
apps/server-core/src/adapters/database/migrations/mysql/1783856507391-Default.ts
(lines 113-126), then add a new follow-up migration that adds auth_keys.use with
the same definition and reverses it in down().

In `@apps/server-core/src/core/entities/user-authenticator/service.ts`:
- Around line 740-747: Update the decryption catch block in the authenticator
service around this.cipher.decrypt to return false only for expected AuthupError
validation/decryption failures, using isAuthupError from `@authup/errors`.
Re-throw all other errors so infrastructure failures, including database
connection errors, propagate as internal server errors instead of being treated
as failed verification attempts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e62d0b7e-5b72-49f2-90a6-340e187ed149

📥 Commits

Reviewing files that changed from the base of the PR and between c83bdd3 and e293863.

📒 Files selected for processing (49)
  • .agents/architecture.md
  • apps/server-core/src/adapters/database/domains/key/entity.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1783856507391-Default.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1783856507391-Default.ts
  • apps/server-core/src/adapters/http/controllers/workflows/jwks/handlers/read.ts
  • apps/server-core/src/adapters/http/controllers/workflows/jwks/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/config/normalize.ts
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/config/validator.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/oauth2/constants.ts
  • apps/server-core/src/app/modules/oauth2/module.ts
  • apps/server-core/src/app/modules/oauth2/repositories/key/repository.ts
  • apps/server-core/src/core/entities/user-authenticator/service.ts
  • apps/server-core/src/core/entities/user-authenticator/types.ts
  • apps/server-core/src/core/index.ts
  • apps/server-core/src/core/key/constants.ts
  • apps/server-core/src/core/key/index.ts
  • apps/server-core/src/core/key/realm-cipher.ts
  • apps/server-core/src/core/key/types.ts
  • apps/server-core/src/core/key/wrap.ts
  • apps/server-core/src/core/oauth2/grant-types/authorize.ts
  • apps/server-core/src/core/oauth2/grant-types/types.ts
  • apps/server-core/src/core/oauth2/index.ts
  • apps/server-core/src/core/oauth2/key/types.ts
  • apps/server-core/src/core/oauth2/token/signer/module.ts
  • apps/server-core/src/core/oauth2/token/verifier/module.ts
  • apps/server-core/test/unit/app/modules/oauth2/key-repository.spec.ts
  • apps/server-core/test/unit/config/index.spec.ts
  • apps/server-core/test/unit/core/entities/user-authenticator/service.spec.ts
  • apps/server-core/test/unit/core/helpers/fake-key-repository.ts
  • apps/server-core/test/unit/core/helpers/index.ts
  • apps/server-core/test/unit/core/key/realm-cipher.spec.ts
  • apps/server-core/test/unit/core/key/wrap.spec.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts
  • apps/server-core/test/unit/core/oauth2/token/signer/module.spec.ts
  • apps/server-core/test/unit/core/oauth2/token/verifier/module.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/user-authenticator-email.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/user-authenticator.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/key-store.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password-mfa.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/id-token-claims.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/mfa-login-ticket.spec.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • packages/core-kit/src/domains/key/type.ts
  • packages/specs/src/json-web-key/constants.ts
💤 Files with no reviewable changes (7)
  • apps/server-core/test/unit/http/controllers/entities/user-authenticator-email.spec.ts
  • apps/server-core/src/core/oauth2/key/types.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/id-token-claims.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/user-authenticator.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/mfa-login-ticket.spec.ts
  • apps/server-core/src/core/oauth2/index.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password-mfa.spec.ts

@tada5hi

tada5hi commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews paused.

tada5hi added 2 commits July 14, 2026 15:03
…st, realm required

encrypt(plain, realmId) / decrypt(blob, realmId): the payload is the verb's
subject (shape-aligned with ISymmetricCipher.encrypt(plain) plus a scope
argument), and the previously optional decrypt realm becomes REQUIRED so the
foreign-realm binding assert can never be skipped - every consumer (MFA
devices, plan-070 client/IdP secrets) knows its entity's realm.
…blob-semantics errors

RealmCipher.decrypt now throws a dedicated RealmCipherBlobError (Symbol-marked,
isRealmCipherBlobError guard) for malformed blobs, unknown/foreign/non-enc key
references, and failed GCM authentication; verifyTotp maps ONLY that class to a
plain verification failure. Infrastructure errors - a database outage during
key resolution, KEK misconfiguration - bubble as 500s instead of silently
burning throttle attempts (spurious lockout risk flagged in review). Note the
review's isAuthupError suggestion would not have covered the KEK case: that
failure IS an AuthupError but is infrastructure, not blob semantics.
@tada5hi
tada5hi merged commit 090998f into master Jul 14, 2026
22 checks passed
@tada5hi
tada5hi deleted the feat/realm-key-store branch July 14, 2026 13:20
@github-actions github-actions Bot mentioned this pull request Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants