feat(api-keys): Scope catalogue, kinds, expiry and sha256 keys
Step 1 of ADR 0001 (tenant-bound, scoped API keys; Werkmeister
prerequisite 1, firmwerk#64 step 1):
- internal/scopes: catalogue <product>:<resource>.<action>, validated
on create against the tenant's entitlements (422 not_entitled);
GET /v1/api-keys/scopes for the portal's picker.
- Migration 0015: kind (user|ci|integration), holder, expires_at,
hash_sha256. New keys are stored as sha256 (indexed lookup); older
keys keep argon2id and every prefix candidate is checked, so a
prefix collision no longer breaks a valid key.
- Verify returns key_id, kind, holder, expires_at, tenant_status and
legacy, and limits scopes to products booked right now. Expired
keys are invalid. Empty scopes stay a legacy full grant.
- ci keys need scopes and an expiry within 365 days; integration keys
are refused here (created by their holder product, next step).
- DELETE /v1/api-keys/{id}?tenant_id= refuses another tenant's key.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1d3b5ebbc5
commit
06d94dcceb
17 files changed
+988
-122
No files matched your search
@@ -0,0 +1,200 @@
|
||||
# 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). Step 1 is implemented in this repo: migration 0015, `internal/scopes`, verify, revoke and SHA-256 keys. Open: the user decisions in §5 (D1, D2) and §2 (end of 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:runner` keys;
|
||||
- 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:runner` and `werkbank: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": true` for such keys.
|
||||
- The portal lists them as "Vollzugriff (alt)" with a hint to replace them.
|
||||
- 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`; `ci` keys 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`":
|
||||
|
||||
```sql
|
||||
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).
|
||||
- **Verify response**, additions only:
|
||||
```json
|
||||
{"valid": true, "tenant_id": "…", "product": "…", "scopes": ["…"],
|
||||
"key_id": "…", "kind": "integration", "holder": "werkmeister",
|
||||
"expires_at": null, "tenant_status": "active", "legacy": false}
|
||||
```
|
||||
- `scopes` is **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_status` is 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` / `revoked` stay as they are (`created` now records `kind`). Later, not in step 1: `api_key.used` at most once per key per day (like `seat.login`), replacing the `last_used_at` write per verify.
|
||||
- **Catalogue endpoint:** `GET /v1/api-keys/scopes` (group `api-keys`) lists the scopes for the portal's picker.
|
||||
|
||||
## 4. Product acceptance contract (G3, G9)
|
||||
|
||||
Every product that accepts keys follows the same rules.
|
||||
|
||||
1. **Header:** `Authorization: Bearer bp_…`. A JWT and a key are told apart by the `bp_` prefix.
|
||||
2. **Verify:** with the product's own `<product>-svc-<env>` token. Cache **positive and negative** results for ≤ 60 s, keyed by `sha256(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.
|
||||
3. **Tenant:** taken **only** from the verify result. Never from the body, the path or a header.
|
||||
4. **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.
|
||||
5. **Audit in the product:** `actor = apikey:<key_id>` (plus `holder`). Werkmeister also sends `X-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 in `role_gate.rs` for 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:licence` key in CI (§5).
|
||||
- **Werkbank:** no change.
|
||||
|
||||
## 5. API keys on registry routes: the CI licence (G5, firmwerk#64 step 1)
|
||||
|
||||
Narrow on purpose: **only `POST /v1/licences`** accepts a key.
|
||||
|
||||
- **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=ci` in the claims;
|
||||
- **TTL 24 h** (a CI job fetches it at start; no heartbeat needed);
|
||||
- **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 calls `Registry::issue` with the key. 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).
|
||||
|
||||
**Two decisions for the user** (I don't decide these):
|
||||
- **D1, seats:** does a CI licence count as a seat?
|
||||
- Proposal: no. It records the usage event `ci.licence` (per key and day) instead of `seat.login`, and the plan's seat limit doesn't apply. CI usage is metered, not seat-billed.
|
||||
- **D2, Werkpilot in CI:** does a Werkpilot CI licence get the per-tenant LiteLLM key, as interactive licences do?
|
||||
- Proposal: yes. It's the same tenant key, metered the same way, with no billing for now.
|
||||
- Without it, Werkpilot can't run headless in CI.
|
||||
|
||||
## 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`, name `werkmeister` (fixed, so `UNIQUE(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.
|
||||
|
||||
**Who creates it.** Fork, with a decision proposal:
|
||||
- **(a)** `werkmeister-svc-<env>` gets the AUTHZ group `api-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's `api-keys` group also unlocks list and revoke, whose `tenant_id` comes from the request. That group is effectively cross-tenant. So:
|
||||
- a **new narrow group `api-keys.integration`** reaches only these routes; `werkmeister-<env>` gets exactly this group, **never** plain `api-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=integration` keys.
|
||||
|
||||
The Werkmeister web client `werkmeister-<env>` gets `tenant-registry-audience` as 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
|
||||
|
||||
- **D1 seats and D2 LLM key** (§5): the user decides.
|
||||
- **End of legacy keys** (§2): date and notice, the user decides.
|
||||
- **Verify cost:** whether the registry also caches verify results itself, beyond the product caches. It's probably unnecessary with SHA-256.
|
||||
- **Registry data for Werkmeister** (documents, audit read, notifications): via the integration key, which means more registry routes accepting keys, or via `werkmeister-svc` AUTHZ 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
|
||||
|
||||
1. **§6(b) AUTHZ:** a narrow group `api-keys.integration` instead of `api-keys`. Create, list and revoke for user principals are own tenant, IT_ADMIN and `kind=integration` only.
|
||||
2. **§5:** CI licence issue is idempotent per (key_id, device, UTC day), with a rate limit of 60/h per key.
|
||||
3. **§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.
|
||||
4. **§7 step 5:** Prüfwerk implements it from a short spec of §4; its prod promotion is coordinated separately.
|
||||
5. **§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/licences` with keys, in the same PR or a second one.
|
||||
Reference in new issue
Block a user