Repository navigation
feat: key management api + lifecycle states - #3256
Conversation
…sioning, /keys ui
|
Note Reviews pausedUse the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds realm-scoped key management with active/passive/disabled lifecycle states, protected key material, eager provisioning, CRUD APIs, JWKS filtering, token and cipher key-store resolution, client-web pages, validation, translations, and integration tests. ChangesRealm key contracts and persistence
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant ClientWeb
participant KeyController
participant KeyService
participant KeyRepositoryAdapter
participant Database
ClientWeb->>KeyController: Create or update key
KeyController->>KeyService: Pass actor, realm, and payload
KeyService->>KeyRepositoryAdapter: Validate, generate/import, and save
KeyRepositoryAdapter->>Database: Persist metadata and protected material
Database-->>KeyRepositoryAdapter: Return key entity
KeyRepositoryAdapter-->>KeyService: Return key without private material
KeyService-->>KeyController: Return key response
KeyController-->>ClientWeb: Return CRUD result
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
authup
@authup/client-web
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (3)
apps/client-web/pages/keys/index/add.vue (1)
21-23: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider awaiting
navigateTo.In Nuxt 3,
navigateToreturns a Promise. It is generally recommended toawaitit to ensure that any navigation errors are caught and execution correctly waits for the transition to start.♻️ Proposed refactor
- const handleCreated = (e: Key) => { - navigateTo({ path: `/keys/${e.id}` }); + const handleCreated = async (e: Key) => { + await navigateTo({ path: `/keys/${e.id}` }); };🤖 Prompt for 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. In `@apps/client-web/pages/keys/index/add.vue` around lines 21 - 23, Update the handleCreated function to await the Promise returned by navigateTo when routing to the created key, preserving the existing destination path and ensuring navigation completion or errors are handled by the async flow.apps/server-core/test/unit/core/entities/key/service.spec.ts (1)
179-233: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winSolid import coverage, but no test for a valid-but-mismatched key pair.
All "create — import" cases test either fully-valid pairs or garbage data; none exercise a syntactically-valid private key paired with an unrelated public key. This mirrors a gap in
KeyService.importMaterial(see review onapps/server-core/src/core/entities/key/service.ts) — flagging here for test-coverage completeness once that validation is added.🤖 Prompt for 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. In `@apps/server-core/test/unit/core/entities/key/service.spec.ts` around lines 179 - 233, Add a test under the create — import suite that generates two independent valid RSA key pairs, supplies the private key from one and public key from the other to service.create, and asserts the import is rejected for a mismatched key pair. Use the existing AsymmetricKey conversion and createAllowAllActor patterns, targeting validation in KeyService.importMaterial.apps/client-web/pages/keys/index.vue (1)
12-14: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExplicitly import and register
VCNavItems.The template uses
<VCNavItems>, but it relies on global registration. Based on learnings, Vue page components should explicitly import the neededVC*components and register them locally in the component for clarity and consistency.♻️ Proposed refactor
import { useTranslations, useTranslationsForNamespace, useTranslator } from '`@authup/client-web-kit`'; import { VCIcon } from '`@vuecs/icon`'; + import { VCNavItems } from '`@vuecs/navigation`'; import { defineNuxtComponent } from '`#app`';export default defineNuxtComponent({ - components: { VCIcon }, + components: { VCIcon, VCNavItems }, setup() {Also applies to: 23-24
🤖 Prompt for 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. In `@apps/client-web/pages/keys/index.vue` around lines 12 - 14, Update the keys page component to explicitly import VCNavItems and register it locally alongside the other VC* components used by the template, replacing reliance on global registration while preserving existing component behavior.Source: Learnings
🤖 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/client-web/pages/keys/index/index.vue`:
- Around line 25-40: Import the missing VCTable and VCTimeago components and add
both to the components registration in the defineComponent call, alongside the
existing VCButton and VCIcon entries, so the template uses explicit local
registration.
In `@apps/server-core/src/app/modules/database/repositories/key/repository.ts`:
- Around line 75-117: Update resolveOrCreate to prevent concurrent zero-row
requests from minting multiple ACTIVE keys for the same (realm_id, use), using
an appropriate transaction/locking strategy or database uniqueness constraint.
Preserve the existing disabled-key guard and key-type-specific creation
behavior, and make active-key selection deterministic by adding a stable
tie-breaker after priority ordering.
In `@apps/server-core/src/core/entities/key/service.ts`:
- Around line 290-355: Update importMaterial in
apps/server-core/src/core/entities/key/service.ts (lines 290-355) to perform a
sign/verify or equivalent round-trip using the imported pkcs8 and spki keys
before returning, and reject mismatched pairs with the existing BadRequestError
path. Add a test in apps/server-core/test/unit/core/entities/key/service.spec.ts
(lines 179-233) covering a valid-format but mismatched key pair and asserting
that import is rejected.
In `@packages/client-web-kit/src/components/entities/key/AKeyForm.vue`:
- Around line 82-85: Update AKeyForm’s useOptions, “Import existing key
material” checkbox, and material-textarea labels to use
useTranslations/translationsDefault instead of hardcoded English. Add equivalent
translation keys to the appropriate field/entity catalogs in all four locales,
preserving the existing labels through localized defaults.
---
Nitpick comments:
In `@apps/client-web/pages/keys/index.vue`:
- Around line 12-14: Update the keys page component to explicitly import
VCNavItems and register it locally alongside the other VC* components used by
the template, replacing reliance on global registration while preserving
existing component behavior.
In `@apps/client-web/pages/keys/index/add.vue`:
- Around line 21-23: Update the handleCreated function to await the Promise
returned by navigateTo when routing to the created key, preserving the existing
destination path and ensuring navigation completion or errors are handled by the
async flow.
In `@apps/server-core/test/unit/core/entities/key/service.spec.ts`:
- Around line 179-233: Add a test under the create — import suite that generates
two independent valid RSA key pairs, supplies the private key from one and
public key from the other to service.create, and asserts the import is rejected
for a mismatched key pair. Use the existing AsymmetricKey conversion and
createAllowAllActor patterns, targeting validation in KeyService.importMaterial.
🪄 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: ffa5fdbd-00cb-4a58-87e2-e450c8745327
📒 Files selected for processing (86)
.agents/architecture.md.agents/structure.mdapps/client-web/config/layout/contants.tsapps/client-web/pages/keys/[id].vueapps/client-web/pages/keys/[id]/index.vueapps/client-web/pages/keys/index.vueapps/client-web/pages/keys/index/add.vueapps/client-web/pages/keys/index/index.vueapps/server-core/src/adapters/database/domains/key/entity.tsapps/server-core/src/adapters/database/migrations/mysql/1783856507391-Default.tsapps/server-core/src/adapters/database/migrations/postgres/1783856507391-Default.tsapps/server-core/src/adapters/http/controllers/entities/index.tsapps/server-core/src/adapters/http/controllers/entities/key/index.tsapps/server-core/src/adapters/http/controllers/entities/key/module.tsapps/server-core/src/adapters/http/controllers/workflows/jwks/handlers/read.tsapps/server-core/src/adapters/http/controllers/workflows/jwks/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/types.tsapps/server-core/src/app/modules/database/repositories/index.tsapps/server-core/src/app/modules/database/repositories/key/index.tsapps/server-core/src/app/modules/database/repositories/key/repository.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/oauth2/constants.tsapps/server-core/src/app/modules/oauth2/module.tsapps/server-core/src/app/modules/oauth2/repositories/index.tsapps/server-core/src/app/modules/oauth2/repositories/key/index.tsapps/server-core/src/app/modules/oauth2/repositories/key/repository.tsapps/server-core/src/app/modules/provisioning/module.tsapps/server-core/src/app/modules/provisioning/sources/default/module.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/entities/key/index.tsapps/server-core/src/core/entities/key/service.tsapps/server-core/src/core/entities/key/types.tsapps/server-core/src/core/entities/realm/service.tsapps/server-core/src/core/key/index.tsapps/server-core/src/core/key/provisioner.tsapps/server-core/src/core/key/realm-cipher.tsapps/server-core/src/core/key/types.tsapps/server-core/src/core/oauth2/grant-types/authorize.tsapps/server-core/src/core/oauth2/grant-types/types.tsapps/server-core/src/core/oauth2/token/signer/module.tsapps/server-core/src/core/oauth2/token/verifier/module.tsapps/server-core/test/unit/app/modules/database/key-repository.spec.tsapps/server-core/test/unit/core/entities/key/fake-repository.tsapps/server-core/test/unit/core/entities/key/service.spec.tsapps/server-core/test/unit/core/entities/user-authenticator/service.spec.tsapps/server-core/test/unit/core/helpers/fake-key-repository.tsapps/server-core/test/unit/core/helpers/fake-key-store.tsapps/server-core/test/unit/core/helpers/index.tsapps/server-core/test/unit/core/key/realm-cipher.spec.tsapps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.tsapps/server-core/test/unit/core/oauth2/token/signer/module.spec.tsapps/server-core/test/unit/core/oauth2/token/verifier/module.spec.tsapps/server-core/test/unit/http/controllers/entities/key.spec.tspackages/client-web-kit/src/components/entities/index.tspackages/client-web-kit/src/components/entities/key/AKey.tspackages/client-web-kit/src/components/entities/key/AKeyForm.vuepackages/client-web-kit/src/components/entities/key/AKeys.tspackages/client-web-kit/src/components/entities/key/index.tspackages/core-http-kit/src/client/module.tspackages/core-http-kit/src/client/type.tspackages/core-http-kit/src/domains/entities/index.tspackages/core-http-kit/src/domains/entities/key/index.tspackages/core-http-kit/src/domains/entities/key/module.tspackages/core-http-kit/src/domains/entities/key/types.tspackages/core-kit/src/domains/key/constants.tspackages/core-kit/src/domains/key/index.tspackages/core-kit/src/domains/key/type.tspackages/core-kit/src/domains/key/utils.tspackages/core-kit/src/domains/key/validator.tspackages/core-kit/src/domains/permission/constants.tspackages/core-kit/src/domains/types.tspackages/i18n/src/catalogs/de/app.tspackages/i18n/src/catalogs/de/entity.tspackages/i18n/src/catalogs/de/field.tspackages/i18n/src/catalogs/en/app.tspackages/i18n/src/catalogs/en/entity.tspackages/i18n/src/catalogs/en/field.tspackages/i18n/src/catalogs/es/app.tspackages/i18n/src/catalogs/es/entity.tspackages/i18n/src/catalogs/es/field.tspackages/i18n/src/catalogs/fr/app.tspackages/i18n/src/catalogs/fr/entity.tspackages/i18n/src/catalogs/fr/field.tspackages/i18n/src/constants.tspackages/server-test-kit/src/fake-entity-repository.ts
💤 Files with no reviewable changes (4)
- apps/server-core/src/app/modules/oauth2/repositories/key/repository.ts
- apps/server-core/src/app/modules/oauth2/repositories/index.ts
- apps/server-core/test/unit/core/helpers/fake-key-repository.ts
- apps/server-core/src/app/modules/oauth2/repositories/key/index.ts
| async resolveOrCreate(realmId: string, use: `${JWKUse}`): Promise<Key> { | ||
| const { repository } = this; | ||
|
|
||
| const entity = await repository.findOne({ | ||
| select: { | ||
| id: true, | ||
| name: true, | ||
| type: true, | ||
| use: true, | ||
| status: true, | ||
| signature_algorithm: true, | ||
| encryption_key: true, | ||
| decryption_key: true, | ||
| realm_id: true, | ||
| }, | ||
| where: { | ||
| realm_id: realmId, | ||
| use, | ||
| status: KeyStatus.ACTIVE, | ||
| }, | ||
| order: { priority: 'DESC' }, | ||
| }); | ||
|
|
||
| if (entity) { | ||
| return this.afterLoad(repository, entity); | ||
| } | ||
|
|
||
| const total = await repository.countBy({ realm_id: realmId, use }); | ||
| if (total > 0) { | ||
| // an admin who disabled every key meant it — do not silently | ||
| // re-mint around the kill switch. | ||
| throw new AuthupError( | ||
| `No active ${use} key is available for realm ${realmId} ` + | ||
| `(${total} key(s) exist, none active).`, | ||
| ); | ||
| } | ||
|
|
||
| if (use === JWKUse.ENCRYPTION) { | ||
| return this.createEncryptionKey(repository, realmId); | ||
| } | ||
|
|
||
| return this.createSignatureKey(repository, realmId); | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check whether KeyProvisioner always runs before any resolveOrCreate backstop call in practice
rg -n 'ensureForRealm|resolveOrCreate' apps/server-core/src/core/key/provisioner.ts apps/server-core/src/app/modules/provisioning/module.ts -A3 -B3Repository: authup/authup
Length of output: 2707
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== repository.ts ==\n'
sed -n '1,220p' apps/server-core/src/app/modules/database/repositories/key/repository.ts
printf '\n== key entity files ==\n'
fd -a 'key' apps/server-core/src/app/modules/database -t f
printf '\n== search for uniqueness / active-key constraints ==\n'
rg -n 'unique|UNIQUE|priority|active|KeyStatus\.ACTIVE|realm_id.*use|use.*realm_id' apps/server-core/src/app/modules/database apps/server-core/src/core/key -A3 -B3Repository: authup/authup
Length of output: 25352
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== locate KeyEntity ==\n'
fd -a 'KeyEntity' apps/server-core/src -t f
printf '\n== locate key entity-like definitions ==\n'
rg -n 'class KeyEntity|`@Entity`|`@Index`|`@Unique`|realm_id|use|status|priority' apps/server-core/src -g '*key*' -g '*Key*' -A3 -B3Repository: authup/authup
Length of output: 217
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== files with key/entity in path ==\n'
git ls-files | rg '/key/|KeyEntity|key.*entity|entity.*key' || true
printf '\n== search for KeyEntity definition and indexes ==\n'
rg -n 'class KeyEntity|`@Entity`|`@Index`|`@Unique`|`@Check`|priority|realm_id|status|use' apps/server-core/src -g '*entity*.ts' -g '*key*.ts' -A4 -B4Repository: authup/authup
Length of output: 50370
Guard the zero-row mint path. resolveOrCreate can still race when a realm has no keys for a given use: two callers can both pass the count check and mint separate ACTIVE rows, and ORDER BY priority DESC has no deterministic tie-breaker if that happens. Add a transaction/lock or a DB constraint that prevents multiple active keys per (realm_id, use).
🤖 Prompt for 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.
In `@apps/server-core/src/app/modules/database/repositories/key/repository.ts`
around lines 75 - 117, Update resolveOrCreate to prevent concurrent zero-row
requests from minting multiple ACTIVE keys for the same (realm_id, use), using
an appropriate transaction/locking strategy or database uniqueness constraint.
Preserve the existing disabled-key guard and key-type-specific creation
behavior, and make active-key selection deterministic by adding a stable
tie-breaker after priority ordering.
There was a problem hiding this comment.
Partially applied in 651a0cd: the ACTIVE-key selection now has a deterministic tie-breaker (priority DESC, created_at DESC, id ASC). The mint race itself is accepted by design: a duplicate mint is benign (both keys are active + published in JWKS, tokens signed by either verify via kid), the eager realm-create/startup provisioning makes the backstop race window practically empty, and a uniqueness constraint on active-per-(realm,use) would forbid legitimate multi-active states (the rotation model allows several active keys with the signer picking the highest priority, Keycloak-style). A cross-dialect lock around count-then-insert (sqlite/mysql/postgres) buys little against that benign outcome.
There was a problem hiding this comment.
@tada5hi, that's a solid rationale — the deterministic tie-breaker resolves the selection non-determinism, and treating a duplicate mint as benign (both keys valid, active, and disambiguated by kid at verification time) is reasonable given the eager provisioning already collapses the race window to near-zero. Agreed that a uniqueness constraint would be at odds with the intentional multi-active rotation model. Thanks for the detailed explanation.
✏️ Learnings added
Learnt from: tada5hi
Repo: authup/authup PR: 3256
File: apps/server-core/src/app/modules/database/repositories/key/repository.ts:75-124
Timestamp: 2026-07-14T19:05:23.964Z
Learning: In `apps/server-core/src/app/modules/database/repositories/key/repository.ts`, `KeyRepositoryAdapter.resolveOrCreate` intentionally does not lock or enforce a uniqueness constraint against concurrent zero-row minting for the same `(realm_id, use)`. This is a deliberate design decision (per maintainer tada5hi): a duplicate mint is benign since both resulting keys are ACTIVE, published in JWKS, and tokens signed by either verify via `kid`; the rotation model (Keycloak-style) intentionally allows multiple active keys per realm/use with the signer picking the highest priority (tie-broken deterministically by `priority DESC, created_at DESC, id ASC`), and eager realm-create/startup provisioning makes the race window practically empty. Do not flag this as a missing lock/constraint in future reviews.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
|
@coderabbitai pause |
✅ Action performedReviews paused. |
…, deterministic key ordering
Summary
Stage A of plan 071:
auth_keysgrows from a JWT-implementation detail into a manageable per-realm key store — management API, lifecycle states, named keys, eager provisioning, and a top-level/keysadmin UI. Builds on the plan-069 realm key store (#3255).Schema (folded into the unreleased
1783856507391migration, both dialects)namevarchar(128) NOT NULL — canonical identifier, backfilled fromid, unique per(name, realm_id)(UQ_auth_keys_name_realm_id); auto-minted keys get<use>-<nanoid>statusvarchar(64) NOT NULL DEFAULT'active'—KeyStatus:active(signs/encrypts + verifies/decrypts),passive(verify/decrypt only),disabled(neither)certificatetext NULL — dormant, filled by Stage B (x5c/x5t in JWKS)Ports & minting (hybrid model)
IKeyStore(resolveOrCreate(realmId, use)/resolveById(id)); the entity CRUD port now owns theIKeyRepositoryname. One adapter (app/modules/database/repositories/key/) implements both, registered asOAuth2InjectionToken.KeyStore.KeyProvisioner.ensureForRealmmints sig+enc keys at realm creation (RealmServicehook) and as a startup backfill over every realm — keys are visible in the API from the moment a realm exists.resolveOrCreatemints only when ZERO rows exist for(realm, use). Rows-exist-but-none-active fails loud — an admin who disabled every key meant it; nothing silently re-mints around the kill switch. Zero-config MFA survives all paths.Lifecycle enforcement
RealmCipher.encrypt: highest-priority ACTIVE key onlykidresolving to a non-sig ORdisabledkey (passive still verifies)active + passiveonlyRealmCipher.decryptre-resolves the key row per call (only the imported cipher is cached — material is immutable, status is not), so disabling an enc key is an immediate, reversible kill switch (RealmCipherBlobError→ MFA verify fails closed, never a 500)Management API
KEY_*permission family —admin=any;realm_admin=ownOrNullread,ownCUD; per-rowresourceRealmMatchdrops ingetMany(plan-039 force-select discipline)KeyControllerdual-mounted/keys+/realms/:realmId/keys; typed clientclient.key.*priority = max+1default so generate doubles as rotate; import takes PKCS#8 + SPKI (base64 or PEM, validated by importing) for sig, 32 base64 bytes for encname/priority/status— material,use,type, realm are immutabledata.referencesunless?force=true(crypto-shred)decryption_key(authentik CVE-2024-42490 is the cautionary tale). No entity subscriber (deliberate:afterInsertcontent would carry raw material onto the realtime bus)UI
Top-level
/keyspages (list / add / detail edit), realm-switch scoped like users/roles, nav entry gated onKEY_*; kitAKeys/AKey/AKeyForm(generate/import on create, name/priority/status on edit); the delete flow catches the 409-with-count and re-confirms crypto-shredding viauseAlertDialogbefore retrying with force. i18n:authupEntity.KEY,authupFieldUSE/STATUS/PRIORITY/SIGNATURE_ALGORITHM,authupAppKEY_DELETE_FORCE_CONFIRM_*— all 4 locales, parity tests green.Verification
check:typescleancore/entities/key/service.spec.ts(permission matrix, generate/import, immutability, force+count),http/controllers/entities/key.spec.ts(eager realm provisioning, CRUD, JWKS lifecycle, nested mount), resolveOrCreate lifecycle matrix inkey-repository.spec.ts, disabled/passive kid cases in the verifier spec, kill-switch reversibility inrealm-cipher.spec.tsrun→ 12×revert→run; columns + unique constraint verified in both schemasSummary by CodeRabbit
New Features
Security
Documentation