17 KiB
ADR 0001: Tenant-bound, scoped API keys
This is prerequisite 1 of the Werkmeister plan (platform/werkmeister ADR 0001), and it also settles the CI-licence gap (firmwerk#64, step 1).
- Deciders: Sharang (platform), reviewed by the platform team.
- Status: accepted 2026-10-13, with review corrections folded in (§9) and the user's decisions D1–D3 (§2, §5). Implemented in this repo: step 1 (migration 0015,
internal/scopes, verify, revoke, SHA-256 keys) and step 1b (POST /v1/licences/ci, integration keys, migrations 0016 and 0017). Open: the date for ending legacy keys.
Customers appear only as K-numbers.
0. Starting point: extend, don't replace
The registry already has tenant-bound keys with scopes:
| Part | Where |
|---|---|
| Table | api_keys (migration 0001): tenant_id, nullable product, scopes TEXT[], argon2id hash, 11-character prefix, revoked_at |
| Create, list, revoke | POST, GET and DELETE /v1/api-keys (AUTHZ group api-keys, held only by portal-svc) |
| Verify | POST /v1/internal/api-keys/verify (group api-keys.verify). It answers 200 {valid, tenant_id, product, scopes}. |
The plan's finding that "service clients aren't tenant-bound" is about Keycloak service clients. The keys themselves are tenant-bound. What's missing is narrower.
| # | Gap today | Found in |
|---|---|---|
| G1 | No scope vocabulary. Scopes are free text, and two conventions coexist: key scopes product:action (werkbank:runner) and AUTHZ groups resource.action (tenants.read). |
apikeys.go, Prüfwerk, authz.go |
| G2 | The portal never sends scopes (product select only, default "all products"), so almost every existing key has scopes = []. |
portal settings/api-keys/page.tsx:151 |
| G3 | Firmwerk ignores scopes. It checks product only and calls verify on every request, uncached. |
firmwerk-cloud-server auth.rs:109-123 |
| G4 | Verify checks neither expiry (there is no expires_at) nor tenant status nor entitlements. |
apikeys.go |
| G5 | The registry accepts no API keys on its own routes (requireAuth takes JWTs only). That's why there is no CI licence: POST /v1/licences needs a user JWT or a service client. |
server.go:211, licences.go:74 |
| G6 | DELETE /v1/api-keys/{id} doesn't check the tenant. The portal works around it by re-listing the tenant's keys. |
apikeys.go, portal page.tsx:77 |
| G7 | FindAPIKeyByPrefix uses QueryRow on a non-unique 48-bit prefix, so a collision makes a valid key fail. |
postgres.go:301 |
| G8 | argon2id with 64 MB per verify is costly on a hot path (Firmwerk per request, soon Werkmeister per block call). | apikeys.go |
| G9 | Prüfwerk's customer API is JWT-only, and its role gate uses org_roles, which a key doesn't have. Only the Werkbank runner route accepts keys. |
compliance-core auth.rs:139, role_gate.rs |
Unchanged:
- the key format
bp_+ 32 base64url characters; - the table (it is extended, not replaced);
- the verify request and the meaning of
200 valid=false; - Werkbank's
werkbank:runnerkeys; - the portal's IT_ADMIN-only key management.
1. Scope vocabulary (G1)
Format: <product>:<resource>.<action>. The product is a catalogue key, and <resource>.<action> mirrors the AUTHZ style. A grant <product>:<resource> also covers <resource>.read and <resource>.write, like Authz.Allowed.
- Catalogue: the registry owns it (
internal/scopes, a Go table with description and product; it is code, not DB rows, because products implement the scopes). - Create: refuses unknown scopes, and scopes for products the tenant isn't entitled to.
- Existing scopes stay valid as special cases:
werkbank:runnerandwerkbank:admin(product pruefwerk).certifai:*is test-only.
Initial catalogue (enough for W3 and firmwerk#64):
| Scope | Meaning |
|---|---|
firmwerk:licence, werkpilot:licence |
Fetch a CLI licence headlessly (§5) |
firmwerk:projects.read / .write |
Firmwerk cloud API |
pruefwerk:findings.read / .write |
List/read findings; set status, bulk status, feedback |
pruefwerk:sbom.read |
SBOM, filters, export, licences, quality, diff |
pruefwerk:scans.read / pruefwerk:scans.run |
Scan runs; start a scan (target, DAST) |
pruefwerk:enisa.read |
ENISA drafts (target/CVE). Releasing them stays a human action in the product UI. |
werkbank:runner, werkbank:admin |
As today |
The plan's placeholders (findings:read, scan:trigger) become pruefwerk:findings.read and pruefwerk:scans.run.
2. Existing keys with empty scopes (G2, G3)
Proposal: no backfill. scopes = [] stays a legacy full grant on the key's product (or on every entitled product if product is NULL), exactly as today.
- Verify returns
"legacy": truefor such keys. - The portal lists them as "Vollzugriff (alt)" with a hint to replace them.
- D3 (decided): legacy keys keep working as "Vollzugriff (alt)" and end after a 90-day notice; the user sets the date.
- New keys must carry at least one scope once the portal's scope picker ships. Until then the registry still accepts empty scopes for
kind=user;cikeys always need scopes. - After a 90-day notice, legacy keys stop being accepted. That is a separate decision for the user, with the date in the changelog.
Portal change (shared repo): a scope picker grouped by product, showing only entitled products, plus an optional expiry. The product select goes away; the product follows from the scopes.
3. Schema and verify (G4, G6, G7, G8)
Migration 0015 (0014 is the Werkmeister catalogue row, #69). Excerpt; migrations/0015_api_keys_scoped.up.sql also adds the checks "a hash is present" and "holder set exactly for integration":
ALTER TABLE api_keys
ADD COLUMN kind TEXT NOT NULL DEFAULT 'user' CHECK (kind IN ('user', 'ci', 'integration')),
ADD COLUMN holder TEXT, -- integration keys: holding product, e.g. 'werkmeister'
ADD COLUMN expires_at TIMESTAMPTZ, -- NULL = no expiry (user/integration); ci keys ≤ 365 d
ADD COLUMN hash_sha256 BYTEA UNIQUE; -- new keys; argon2 `hash` stays for existing rows
ALTER TABLE api_keys ALTER COLUMN hash DROP NOT NULL;
- Hashing (G8), a recommendation:
- New keys store
sha256(key)and are found by a unique index lookup. A key is 192 bits of randomness, so a slow KDF adds cost without adding security; GitHub tokens and Stripe keys follow the same practice. - Existing rows keep the argon2 path. The lookup loops over all active rows with the prefix (fixes G7).
- New keys store
- Verify response, additions only:
{"valid": true, "tenant_id": "…", "product": "…", "scopes": ["…"], "key_id": "…", "kind": "integration", "holder": "werkmeister", "expires_at": null, "tenant_status": "active", "legacy": false}scopesis intersected with the tenant's current entitlements: a key outlives a cancelled booking but no longer opens it.- An expired or revoked key returns
valid=false. tenant_statusis passed through. Products map it the way Firmwerk does today (402 read-only/suspended).
- Revoke (G6):
DELETE /v1/api-keys/{id}?tenant_id=…returns 404 if the key belongs to another tenant. The portal workaround can go. - Audit:
api_key.created/revokedstay as they are (creatednow recordskind). Later, not in step 1:api_key.usedat most once per key per day (likeseat.login), replacing thelast_used_atwrite per verify. - Catalogue endpoint:
GET /v1/api-keys/scopes(groupapi-keys) lists the scopes for the portal's picker.
4. Product acceptance contract (G3, G9)
Every product that accepts keys follows the same rules.
- Header:
Authorization: Bearer bp_…. A JWT and a key are told apart by thebp_prefix. - Verify: with the product's own
<product>-svc-<env>token. Cache positive and negative results for ≤ 60 s, keyed bysha256(key)(never the plaintext). Fail closed if the registry can't be reached and nothing is cached.- Revocation therefore takes up to 60 s to take effect in every product. The portal's revoke dialog says so.
- Tenant: taken only from the verify result. Never from the body, the path or a header.
- Scopes replace roles: each route declares its scope. A key principal is never IT_ADMIN, so admin routes (manual findings, credentials, user management) aren't reachable with a key at all.
- Audit in the product:
actor = apikey:<key_id>(plusholder). Werkmeister also sendsX-BP-Actor: <keycloak sub>when a person started the run. It is informational for the audit trail and not used for authorization.
What that means for each product:
- Prüfwerk: a second principal type next to the JWT in
compliance-core/auth.rs, a scope table inrole_gate.rsfor the routes in §1, and the cache. This is new work in Prüfwerk.- Exception to §2: in Prüfwerk a legacy key gets only the read scopes. Such keys never reached the customer API before, so a full grant there would widen what existing keys can do.
- Firmwerk: add the cache, check scopes for non-legacy keys, and accept the
firmwerk:licencekey in CI (§5). - Werkbank: no change.
5. API keys on registry routes: the CI licence (G5, firmwerk#64 step 1)
Narrow on purpose: one dedicated route, POST /v1/licences/ci, accepts a key. It is registered outside the JWT chain (like the heartbeat) rather than mixing key auth into requireAuth; the interactive POST /v1/licences is unchanged.
- Auth:
Authorization: Bearer bp_…with scope<product>:licence. The tenant comes from the key.device = ci:<runner host or name>, set by the CLI. - Licence:
sub = apikey:<key_id>,kind=ciin the claims;- TTL 24 h (a CI job fetches it at start; no heartbeat needed). A heartbeat never renews a CI licence: renewal would turn it into a regular 30-day licence;
- idempotent per (key_id, device, UTC day): a repeat request returns the existing unexpired licence instead of creating a new row per job;
- rate limit per key (60/h; above that
429); - the grace ladder applies unchanged.
- bp-licence: reads
BP_LICENCE_API_KEY. If it's set, it skips the device flow and callsPOST /v1/licences/ciwith the key anddevice= runner name. Store, verify and grace stay the same. Werkpilot and Firmwerk get CI mode by bumping the crate. - Key kind: a CI key is created in the portal with
kind=ci(picker preset "CI-Lizenz", scope<product>:licence, expiry required, at most 365 days).
Decided by the user (2026-10-13):
- D1, seats: a CI licence is not a seat. The CLI records the usage event
ci.licence(per key and day) instead ofseat.login; CI usage is metered, not seat-billed. - D2, Werkpilot in CI: a Werkpilot CI licence gets the per-tenant LiteLLM key, metered the same way, no billing for now.
- Werkpilot CI licences are reused per (key, device, UTC day) like the others. The LiteLLM key is generated with the licence (
duration: 1d, so LiteLLM expires it itself) and its secret is stored sealed on the licence row (AES-256-GCM under the new registry secretSECRETS_ENCRYPTION_KEY, bound to the licence id; migration 0017). The reused licence hands out the same key again. - Cost cap: at most 10 LiteLLM keys per API key and UTC day (distinct devices); beyond that the licence comes without a key (warning
llm_key_daily_cap). - Without
SECRETS_ENCRYPTION_KEYa reused licence comes without the key (warningllm_key_not_repeatable).
- Werkpilot CI licences are reused per (key, device, UTC day) like the others. The LiteLLM key is generated with the licence (
6. Werkmeister's own use
Werkmeister acts for a tenant against Prüfwerk and Firmwerk, and later the registry's documents, audit and notifications.
- Keycloak token exchange doesn't work here: scheduled, polled and webhook-triggered runs have no user present.
- Instead:
- One key per tenant and holder:
kind=integration,holder=werkmeister, namewerkmeister(fixed, soUNIQUE(tenant_id, name)holds). - Re-issuing means revoke, then create.
- Storage: encrypted in Werkmeister's database (AES-GCM, key
WERKMEISTER_KEK). In the cloud it comes from the orca project secret. On-prem (W5) it must also work without orca: an env var or a file (WERKMEISTER_KEK_FILE). - Visibility: shown in the portal list as "Werkmeister (Integration)", and the tenant can revoke it there.
- One key per tenant and holder:
Name uniqueness: migration 0016 makes (tenant_id, name) unique among active keys only, so a revoked key's name is free again (re-issue = revoke, then create; also lets portal users reuse a name).
Who creates it. Fork, with a decision proposal:
-
(a)
werkmeister-svc-<env>gets the AUTHZ groupapi-keys, and Werkmeister checks "caller is IT_ADMIN of that tenant" itself. This is rejected: it gives a product service client cross-tenant power to create keys, which is exactly what we want to avoid. -
(b), decided: the registry accepts user tokens on
POST /v1/api-keys, but only:- for the token's own tenant;
- with
org_roles ∋ IT_ADMIN; - for
kind=integration, with scopes from the holder's allowlist (integrationScopes["werkmeister"]in code).
AUTHZ: rules are keyed by
azp, and today'sapi-keysgroup also unlocks list and revoke, whosetenant_idcomes from the request. That group is effectively cross-tenant. So:- a new narrow group
api-keys.integrationreaches only these routes;werkmeister-<env>gets exactly this group, never plainapi-keys; - create:
POST /v1/api-keys, under the checks above; - list and revoke: for a user principal, the registry only allows the token's own tenant, only IT_ADMIN, and only
kind=integrationkeys.
The Werkmeister web client
werkmeister-<env>getstenant-registry-audienceas a second default scope. When an IT_ADMIN clicks "Prüfwerk verbinden" in the editor, Werkmeister forwards their token. The registry checks everything itself, and nothing else gains cross-tenant rights.Side effect: the portal could use the same path later instead of portal-svc (not part of this change).
Scopes of the integration key: the union of the block scopes the tenant's workflows need, limited by entitlements and the allowlist. Adding a block that needs a new scope prompts an IT_ADMIN to reconnect.
7. Order of work and ownership
| Step | Repo | Notes |
|---|---|---|
| 1 | tenant-registry | 0015, scope catalogue, verify extension, revoke fix, SHA-256 path; then key auth on POST /v1/licences and user-token create for integration |
| 2 | licence-client | BP_LICENCE_API_KEY, tag v0.1.4 |
| 3 | portal | scope picker, expiry, CI preset, legacy label, revoke-delay hint |
| 4 | firmwerk | cache, scopes, CI mode, gate() (firmwerk#64 step 2) |
| 5 | Prüfwerk | key principal, scope table, cache. Implemented from a short spec of §4; the prod promotion needs the user's go and is timed around the K-00001 pilot. |
| 6 | werkmeister | integration-key storage, "connect" flow, blocks call with keys |
Steps 1 and 2 unblock firmwerk#64. Steps 1 and 5 unblock Werkmeister's Prüfwerk blocks in W3; until then those blocks show "not connected: key acceptance in Prüfwerk pending".
8. Open questions
- End of legacy keys (§2, D3): the user sets the date; 90 days' notice.
- Verify cost: whether the registry also caches verify results itself, beyond the product caches. It's probably unnecessary with SHA-256.
- LiteLLM budget per tenant before billing starts: every LiteLLM key has its own MaxBudget, so a tenant's effective budget grows with its keys (devices, CI). Move the budget to the tenant (a LiteLLM team per tenant) before billing.
- Registry data for Werkmeister (documents, audit read, notifications): via the integration key, which means more registry routes accepting keys, or via
werkmeister-svcAUTHZ groups with tenant scoping enforced in Werkmeister.- Proposal: AUTHZ groups for read-only paths in W3, and keys once the registry route set is clear.
9. Review corrections (2026-10-13), folded in
- §6(b) AUTHZ: a narrow group
api-keys.integrationinstead ofapi-keys. Create, list and revoke for user principals are own tenant, IT_ADMIN andkind=integrationonly. - §5: CI licence issue is idempotent per (key_id, device, UTC day), with a rate limit of 60/h per key. Implemented as
POST /v1/licences/ci(200 for the reused licence, 201 for a new one, 429 above the limit). - §4: revocation takes up to 60 s to take effect (product cache TTL). This is stated in the ADR and in the portal's revoke dialog.
- §7 step 5: Prüfwerk implements it from a short spec of §4; its prod promotion is coordinated separately.
- §6: the KEK also works without orca (env or file) for on-prem (W5).
Start: tenant-registry step 1 once #69 is merged:
- migration 0015, the scope catalogue, the verify extension, the revoke fix and the SHA-256 path;
POST /v1/licenceswith keys, in the same PR or a second one.