Skip to content

feat: key management api + lifecycle states - #3256

Merged
tada5hi merged 2 commits into
masterfrom
feat/key-store-management
Jul 14, 2026
Merged

tada5hi merged 2 commits into
masterfrom
feat/key-store-management

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Stage A of plan 071: auth_keys grows from a JWT-implementation detail into a manageable per-realm key store — management API, lifecycle states, named keys, eager provisioning, and a top-level /keys admin UI. Builds on the plan-069 realm key store (#3255).

Schema (folded into the unreleased 1783856507391 migration, both dialects)

  • name varchar(128) NOT NULL — canonical identifier, backfilled from id, unique per (name, realm_id) (UQ_auth_keys_name_realm_id); auto-minted keys get <use>-<nanoid>
  • status varchar(64) NOT NULL DEFAULT 'active' — KeyStatus: active (signs/encrypts + verifies/decrypts), passive (verify/decrypt only), disabled (neither)
  • certificate text NULL — dormant, filled by Stage B (x5c/x5t in JWKS)

Ports & minting (hybrid model)

  • The 069 material-resolution port is renamed IKeyStore (resolveOrCreate(realmId, use) / resolveById(id)); the entity CRUD port now owns the IKeyRepository name. One adapter (app/modules/database/repositories/key/) implements both, registered as OAuth2InjectionToken.KeyStore.
  • Eager provisioning: KeyProvisioner.ensureForRealm mints sig+enc keys at realm creation (RealmService hook) and as a startup backfill over every realm — keys are visible in the API from the moment a realm exists.
  • Self-healing backstop: resolveOrCreate mints 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

  • Signer + RealmCipher.encrypt: highest-priority ACTIVE key only
  • Verifier: rejects a kid resolving to a non-sig OR disabled key (passive still verifies)
  • Both JWKS surfaces publish active + passive only
  • RealmCipher.decrypt re-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

  • New auto-provisioned KEY_* permission family — admin = any; realm_admin = ownOrNull read, own CUD; per-row resourceRealmMatch drops in getMany (plan-039 force-select discipline)
  • KeyController dual-mounted /keys + /realms/:realmId/keys; typed client client.key.*
  • POST create discriminates generate vs import by material presence: generate supports RS256/384/512 + ES256/384/512 (HS* rejected — JWKS cannot publish shared secrets) with priority = max+1 default so generate doubles as rotate; import takes PKCS#8 + SPKI (base64 or PEM, validated by importing) for sig, 32 base64 bytes for enc
  • Update mounts only name / priority / status — material, use, type, realm are immutable
  • DELETE on an enc key with live cipher-blob references (today: MFA seeds) answers 409 + data.references unless ?force=true (crypto-shred)
  • Private material never leaves the server — every read surface and the create response null decryption_key (authentik CVE-2024-42490 is the cautionary tale). No entity subscriber (deliberate: afterInsert content would carry raw material onto the realtime bus)

UI

Top-level /keys pages (list / add / detail edit), realm-switch scoped like users/roles, nav entry gated on KEY_*; kit AKeys / AKey / AKeyForm (generate/import on create, name/priority/status on edit); the delete flow catches the 409-with-count and re-confirms crypto-shredding via useAlertDialog before retrying with force. i18n: authupEntity.KEY, authupField USE/STATUS/PRIORITY/SIGNATURE_ALGORITHM, authupApp KEY_DELETE_FORCE_CONFIRM_* — all 4 locales, parity tests green.

Verification

  • server-core: 153 files / 1,629 tests green; check:types clean
  • New specs: core/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 in key-repository.spec.ts, disabled/passive kid cases in the verifier spec, kill-switch reversibility in realm-cipher.spec.ts
  • Migration round-trip on MySQL + PostgreSQL: run → 12× revert → run; columns + unique constraint verified in both schemas
  • i18n 77 green, client-web-kit 141 green, core-kit / core-http-kit / server-test-kit green; client-web (vue-tsc) build clean

Summary by CodeRabbit

  • New Features

    • Added a Keys management area for creating, importing, viewing, editing, rotating, and deleting realm keys.
    • Added permission-controlled key management APIs and client support.
    • Added key lifecycle statuses and priority-based rotation support.
    • New realms automatically receive signing and encryption keys.
  • Security

    • Private key material is never returned to the client.
    • Disabled keys are excluded from JWKS and token operations.
    • Protected encryption keys require confirmation before forced deletion.
  • Documentation

    • Updated key management, realm navigation, lifecycle, and provisioning guidance.

Copilot AI review requested due to automatic review settings July 14, 2026 18:29

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

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

Adds 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.

Changes

Realm key contracts and persistence

Layer / File(s) Summary
Key model, validation, and schema
.agents/architecture.md, packages/core-kit/src/domains/key/*, apps/server-core/src/adapters/database/...
Adds key names, lifecycle status, certificate metadata, validation rules, permissions, and database constraints for unique names per realm.
Key storage and service
apps/server-core/src/app/modules/database/repositories/key/*, apps/server-core/src/core/entities/key/*
Implements protected key-material persistence, generation/import flows, realm-scoped CRUD, priority handling, authorization, reference counting, and forced deletion.
Key-store wiring and cryptographic consumers
apps/server-core/src/core/key/*, apps/server-core/src/core/oauth2/*, apps/server-core/src/app/modules/...
Adds eager/self-healing provisioning, replaces repository lookups with key-store resolution, filters disabled keys, and validates realm-bound encrypted blobs.
HTTP and client management surfaces
apps/server-core/src/adapters/http/controllers/entities/key/*, packages/core-http-kit/src/domains/entities/key/*, apps/client-web/pages/keys/*, packages/client-web-kit/src/components/entities/key/*
Adds key CRUD endpoints, client APIs, navigation, list/detail pages, create/update forms, and 409 force-delete confirmation handling.
Tests and supporting fixtures
apps/server-core/test/unit/..., packages/server-test-kit/*
Covers provisioning, generation/import, lifecycle selection, protected material, cipher behavior, OAuth2 consumers, permissions, HTTP CRUD, and deletion rules.

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
Loading

Possibly related PRs

  • authup/authup#3175: Both changes update OAuth2 token-controller dependency wiring and token context contracts.
  • authup/authup#3255: Overlaps in key usage discrimination, realm-bound RealmCipher behavior, JWKS filtering, and token key resolution.

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
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately captures the main change: a key management API plus key lifecycle state support.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/key-store-management

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@3256

@authup/client-web

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

@authup/server-core

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

@authup/access

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

@authup/client-web-kit

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

@authup/client-web-kit-theme

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

@authup/client-web-nuxt

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

@authup/client-web-theme

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

@authup/core-http-kit

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

@authup/core-kit

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

@authup/core-realtime-kit

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

@authup/errors

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

@authup/i18n

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

@authup/kit

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

@authup/server-adapter-kit

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

@authup/server-adapter-node

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

@authup/server-adapter-socket-io

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

@authup/server-adapter-web

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

@authup/server-kit

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

@authup/server-test-kit

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

@authup/specs

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

commit: cf64167

@tada5hi tada5hi changed the title feat: key management api + lifecycle states (plan 071 stage a) feat: key management api + lifecycle states Jul 14, 2026

@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: 4

🧹 Nitpick comments (3)
apps/client-web/pages/keys/index/add.vue (1)

21-23: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider awaiting navigateTo.

In Nuxt 3, navigateTo returns a Promise. It is generally recommended to await it 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 win

Solid 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 on apps/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 value

Explicitly import and register VCNavItems.

The template uses <VCNavItems>, but it relies on global registration. Based on learnings, Vue page components should explicitly import the needed VC* 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

📥 Commits

Reviewing files that changed from the base of the PR and between 090998f and cf64167.

📒 Files selected for processing (86)
  • .agents/architecture.md
  • .agents/structure.md
  • apps/client-web/config/layout/contants.ts
  • apps/client-web/pages/keys/[id].vue
  • apps/client-web/pages/keys/[id]/index.vue
  • apps/client-web/pages/keys/index.vue
  • apps/client-web/pages/keys/index/add.vue
  • apps/client-web/pages/keys/index/index.vue
  • 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/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/key/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/key/module.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/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/src/app/modules/database/repositories/key/index.ts
  • apps/server-core/src/app/modules/database/repositories/key/repository.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/index.ts
  • apps/server-core/src/app/modules/oauth2/repositories/key/index.ts
  • apps/server-core/src/app/modules/oauth2/repositories/key/repository.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/key/index.ts
  • apps/server-core/src/core/entities/key/service.ts
  • apps/server-core/src/core/entities/key/types.ts
  • apps/server-core/src/core/entities/realm/service.ts
  • apps/server-core/src/core/key/index.ts
  • apps/server-core/src/core/key/provisioner.ts
  • apps/server-core/src/core/key/realm-cipher.ts
  • apps/server-core/src/core/key/types.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/token/signer/module.ts
  • apps/server-core/src/core/oauth2/token/verifier/module.ts
  • apps/server-core/test/unit/app/modules/database/key-repository.spec.ts
  • apps/server-core/test/unit/core/entities/key/fake-repository.ts
  • apps/server-core/test/unit/core/entities/key/service.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/fake-key-store.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/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/key.spec.ts
  • packages/client-web-kit/src/components/entities/index.ts
  • packages/client-web-kit/src/components/entities/key/AKey.ts
  • packages/client-web-kit/src/components/entities/key/AKeyForm.vue
  • packages/client-web-kit/src/components/entities/key/AKeys.ts
  • packages/client-web-kit/src/components/entities/key/index.ts
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/client/type.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-http-kit/src/domains/entities/key/index.ts
  • packages/core-http-kit/src/domains/entities/key/module.ts
  • packages/core-http-kit/src/domains/entities/key/types.ts
  • packages/core-kit/src/domains/key/constants.ts
  • packages/core-kit/src/domains/key/index.ts
  • packages/core-kit/src/domains/key/type.ts
  • packages/core-kit/src/domains/key/utils.ts
  • packages/core-kit/src/domains/key/validator.ts
  • packages/core-kit/src/domains/permission/constants.ts
  • packages/core-kit/src/domains/types.ts
  • packages/i18n/src/catalogs/de/app.ts
  • packages/i18n/src/catalogs/de/entity.ts
  • packages/i18n/src/catalogs/de/field.ts
  • packages/i18n/src/catalogs/en/app.ts
  • packages/i18n/src/catalogs/en/entity.ts
  • packages/i18n/src/catalogs/en/field.ts
  • packages/i18n/src/catalogs/es/app.ts
  • packages/i18n/src/catalogs/es/entity.ts
  • packages/i18n/src/catalogs/es/field.ts
  • packages/i18n/src/catalogs/fr/app.ts
  • packages/i18n/src/catalogs/fr/entity.ts
  • packages/i18n/src/catalogs/fr/field.ts
  • packages/i18n/src/constants.ts
  • packages/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

Comment on lines +75 to +117
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);
}

@coderabbitai coderabbitai Bot Jul 14, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 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 -B3

Repository: 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 -B3

Repository: 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 -B3

Repository: 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 -B4

Repository: 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@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.

@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
tada5hi merged commit c69e9a2 into master Jul 14, 2026
21 checks passed
@tada5hi
tada5hi deleted the feat/key-store-management branch July 14, 2026 19:07
@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