From 06d94dcceb55f8d29fdb99723f3fa109ae5f4757 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:36:46 +0200 Subject: [PATCH] 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 :., 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 --- .gitea/workflows/ci.yaml | 2 +- docs/adr/0001-tenant-scoped-api-keys.md | 200 ++++++++++++++++++++ internal/scopes/scopes.go | 112 +++++++++++ internal/scopes/scopes_test.go | 47 +++++ internal/server/apikeys.go | 224 +++++++++++++++++----- internal/server/apikeys_scoped_test.go | 231 +++++++++++++++++++++++ internal/server/apikeys_test.go | 3 +- internal/server/openapi_test.go | 1 + internal/server/server.go | 1 + internal/server/team_test.go | 2 +- internal/store/memory.go | 57 ++++-- internal/store/postgres.go | 94 ++++----- internal/store/store.go | 34 +++- internal/store/types.go | 10 + migrations/0015_api_keys_scoped.down.sql | 13 ++ migrations/0015_api_keys_scoped.up.sql | 18 ++ openapi.yaml | 61 +++++- 17 files changed, 988 insertions(+), 122 deletions(-) create mode 100644 docs/adr/0001-tenant-scoped-api-keys.md create mode 100644 internal/scopes/scopes.go create mode 100644 internal/scopes/scopes_test.go create mode 100644 internal/server/apikeys_scoped_test.go create mode 100644 migrations/0015_api_keys_scoped.down.sql create mode 100644 migrations/0015_api_keys_scoped.up.sql diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 176430d..9bc758e 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -83,7 +83,7 @@ jobs: # own test binary — and including it triggers a covdata-tool error # on packages with no _test.go files. -coverpkg makes the server's # exercise of store/* count toward coverage. - run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... + run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... - name: coverage gate run: | diff --git a/docs/adr/0001-tenant-scoped-api-keys.md b/docs/adr/0001-tenant-scoped-api-keys.md new file mode 100644 index 0000000..5784264 --- /dev/null +++ b/docs/adr/0001-tenant-scoped-api-keys.md @@ -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:** `:.`. The product is a catalogue key, and `.` mirrors the AUTHZ style. A grant `:` also covers `.read` and `.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 `-svc-` 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:` (plus `holder`). Werkmeister also sends `X-BP-Actor: ` 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 `:licence`. The tenant comes from the key. `device = ci:`, set by the CLI. +- **Licence:** + - `sub = apikey:`, `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 `: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-` 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-` 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-` 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. diff --git a/internal/scopes/scopes.go b/internal/scopes/scopes.go new file mode 100644 index 0000000..2b1f884 --- /dev/null +++ b/internal/scopes/scopes.go @@ -0,0 +1,112 @@ +// Package scopes is the catalogue of API key scopes (ADR: tenant-bound, +// scoped API keys). A scope is ":."; the product +// part names the catalogue product whose entitlement the scope needs. The +// catalogue is code, not data: every scope here is implemented by a product. +package scopes + +import ( + "fmt" + "sort" + "strings" +) + +// Scope describes one grantable permission. +type Scope struct { + Name string `json:"name"` + Product string `json:"product"` // catalogue product the tenant must be entitled to + Description string `json:"description"` +} + +// catalogue — keep sorted by name. werkbank:* predate the naming scheme and +// keep their names; they need the pruefwerk entitlement (Werkbank is an +// add-on of Prüfwerk). +var catalogue = []Scope{ + {"firmwerk:licence", "firmwerk", "Fetch a Firmwerk CLI licence without a browser (CI)"}, + {"firmwerk:projects.read", "firmwerk", "Read Firmwerk cloud projects"}, + {"firmwerk:projects.write", "firmwerk", "Create and change Firmwerk cloud projects"}, + {"pruefwerk:enisa.read", "pruefwerk", "Read ENISA report drafts"}, + {"pruefwerk:findings.read", "pruefwerk", "Read findings"}, + {"pruefwerk:findings.write", "pruefwerk", "Set finding status and feedback"}, + {"pruefwerk:sbom.read", "pruefwerk", "Read SBOMs, licences and SBOM quality"}, + {"pruefwerk:scans.read", "pruefwerk", "Read scan runs"}, + {"pruefwerk:scans.run", "pruefwerk", "Start scans"}, + {"werkbank:admin", "pruefwerk", "Manage Werkbank runners"}, + {"werkbank:runner", "pruefwerk", "Act as a Werkbank runner"}, + {"werkpilot:licence", "werkpilot", "Fetch a Werkpilot CLI licence without a browser (CI)"}, +} + +var byName = func() map[string]Scope { + m := make(map[string]Scope, len(catalogue)) + for _, s := range catalogue { + m[s.Name] = s + } + return m +}() + +// All returns the catalogue, sorted by name. +func All() []Scope { + out := append([]Scope(nil), catalogue...) + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} + +// Lookup returns the catalogue entry for name. +func Lookup(name string) (Scope, bool) { + s, ok := byName[name] + return s, ok +} + +// Validate checks that every name is in the catalogue and, when product is +// set, that every scope belongs to it. It returns the normalised (sorted, +// de-duplicated) list. +func Validate(names []string, product string) ([]string, error) { + seen := map[string]bool{} + out := make([]string, 0, len(names)) + for _, n := range names { + n = strings.TrimSpace(n) + s, ok := byName[n] + if !ok { + return nil, fmt.Errorf("unknown scope %q", n) + } + if product != "" && s.Product != product { + return nil, fmt.Errorf("scope %q belongs to product %q, not %q", n, s.Product, product) + } + if !seen[n] { + seen[n] = true + out = append(out, n) + } + } + sort.Strings(out) + return out, nil +} + +// Products returns the distinct products the given scopes need. Unknown +// names are skipped. +func Products(names []string) []string { + set := map[string]bool{} + for _, n := range names { + if s, ok := byName[n]; ok { + set[s.Product] = true + } + } + out := make([]string, 0, len(set)) + for p := range set { + out = append(out, p) + } + sort.Strings(out) + return out +} + +// Effective filters a key's stored scopes down to those whose product is in +// entitled. Names outside the catalogue (keys created before it existed) are +// kept unchanged: the products that issued them still interpret them. +func Effective(names []string, entitled map[string]bool) []string { + out := make([]string, 0, len(names)) + for _, n := range names { + if s, ok := byName[n]; ok && !entitled[s.Product] { + continue + } + out = append(out, n) + } + return out +} diff --git a/internal/scopes/scopes_test.go b/internal/scopes/scopes_test.go new file mode 100644 index 0000000..57bbac7 --- /dev/null +++ b/internal/scopes/scopes_test.go @@ -0,0 +1,47 @@ +package scopes + +import ( + "reflect" + "testing" +) + +func TestCatalogueIsWellFormed(t *testing.T) { + for _, s := range All() { + if s.Product == "" || s.Description == "" { + t.Errorf("%s: product and description are required", s.Name) + } + if _, ok := Lookup(s.Name); !ok { + t.Errorf("%s: not found by Lookup", s.Name) + } + } +} + +func TestValidate(t *testing.T) { + got, err := Validate([]string{"pruefwerk:scans.run", " pruefwerk:findings.read", "pruefwerk:scans.run"}, "") + if err != nil { + t.Fatal(err) + } + if want := []string{"pruefwerk:findings.read", "pruefwerk:scans.run"}; !reflect.DeepEqual(got, want) { + t.Fatalf("got %v, want %v", got, want) + } + if _, err := Validate([]string{"certifai:read"}, ""); err == nil { + t.Error("unknown scope accepted") + } + if _, err := Validate([]string{"firmwerk:licence"}, "pruefwerk"); err == nil { + t.Error("scope of another product accepted") + } + if _, err := Validate([]string{"werkbank:runner"}, "pruefwerk"); err != nil { + t.Errorf("werkbank scopes belong to pruefwerk: %v", err) + } +} + +func TestProductsAndEffective(t *testing.T) { + names := []string{"firmwerk:licence", "pruefwerk:findings.read", "werkbank:runner", "legacy:thing"} + if got := Products(names); !reflect.DeepEqual(got, []string{"firmwerk", "pruefwerk"}) { + t.Fatalf("Products = %v", got) + } + got := Effective(names, map[string]bool{"pruefwerk": true}) + if want := []string{"pruefwerk:findings.read", "werkbank:runner", "legacy:thing"}; !reflect.DeepEqual(got, want) { + t.Fatalf("Effective = %v, want %v", got, want) + } +} diff --git a/internal/server/apikeys.go b/internal/server/apikeys.go index 7863a0a..2b20dd5 100644 --- a/internal/server/apikeys.go +++ b/internal/server/apikeys.go @@ -3,6 +3,7 @@ package server import ( "context" "crypto/rand" + "crypto/sha256" "encoding/base64" "errors" "net/http" @@ -10,12 +11,14 @@ import ( "golang.org/x/crypto/argon2" + "git.breakpilot.com/platform/tenant-registry/internal/scopes" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // Plaintext key format: `bp_<32 base64 chars>`. Prefix stored for UI is -// the first 11 chars (`bp_<8 chars>`). Hash is argon2id with sensible -// dev params (raise in M6+ once we see the verify call rate in prod). +// the first 11 chars (`bp_<8 chars>`). New keys are stored as sha256 of the +// plaintext: 192 random bits need no slow KDF, and the lookup is an index +// hit. Keys created before migration 0015 keep their argon2id hash. const ( keyPrefix = "bp_" prefixLen = 11 // bp_ + 8 @@ -29,12 +32,17 @@ var ( argonKeyLen uint32 = 32 ) +// ciKeyMaxTTL bounds a CI key's lifetime; CI keys must expire. +const ciKeyMaxTTL = 365 * 24 * time.Hour + type createAPIKeyReq struct { - TenantID string `json:"tenant_id"` - Name string `json:"name"` - Product string `json:"product,omitempty"` - Scopes []string `json:"scopes,omitempty"` - CreatedBy string `json:"created_by,omitempty"` + TenantID string `json:"tenant_id"` + Name string `json:"name"` + Product string `json:"product,omitempty"` + Scopes []string `json:"scopes,omitempty"` + Kind string `json:"kind,omitempty"` // user (default) | ci + ExpiresAt *time.Time `json:"expires_at,omitempty"` + CreatedBy string `json:"created_by,omitempty"` } type createAPIKeyResp struct { @@ -56,28 +64,80 @@ func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "invalid_name", "name too long") return } + switch in.Kind { + case "": + in.Kind = store.APIKeyKindUser + case store.APIKeyKindUser, store.APIKeyKindCI: + case store.APIKeyKindIntegration: + writeError(w, http.StatusBadRequest, "invalid_kind", "integration keys are created by their holder product") + return + default: + writeError(w, http.StatusBadRequest, "invalid_kind", "kind must be user or ci") + return + } + now := time.Now().UTC() + if in.ExpiresAt != nil && !in.ExpiresAt.After(now) { + writeError(w, http.StatusBadRequest, "invalid_expiry", "expires_at must be in the future") + return + } + if in.Kind == store.APIKeyKindCI { + if in.ExpiresAt == nil || in.ExpiresAt.After(now.Add(ciKeyMaxTTL)) { + writeError(w, http.StatusBadRequest, "invalid_expiry", "ci keys need expires_at within 365 days") + return + } + if len(in.Scopes) == 0 { + writeError(w, http.StatusBadRequest, "invalid_scopes", "ci keys need at least one scope") + return + } + } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() if in.Product != "" && !s.knownProduct(ctx, in.Product) { writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog") return } + // Empty scopes = legacy full grant on product (portal keys before the + // scope picker); scoped keys only for products the tenant has booked. + if len(in.Scopes) > 0 { + norm, err := scopes.Validate(in.Scopes, in.Product) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid_scopes", err.Error()) + return + } + in.Scopes = norm + entitled, _, err := s.entitledProducts(ctx, in.TenantID) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + for _, p := range scopes.Products(in.Scopes) { + if !entitled[p] { + writeError(w, http.StatusUnprocessableEntity, "not_entitled", "tenant is not entitled to "+p) + return + } + } + } plain, err := generateAPIKey() if err != nil { writeError(w, http.StatusInternalServerError, "internal", "key generation failed") return } - hash := hashAPIKey(plain) + sum := sha256.Sum256([]byte(plain)) k, err := s.Store.CreateAPIKey(ctx, store.APIKeyCreate{ - TenantID: in.TenantID, - Product: in.Product, - Name: in.Name, - Scopes: in.Scopes, - Prefix: plain[:prefixLen], - Hash: hash, - CreatedBy: in.CreatedBy, + TenantID: in.TenantID, + Product: in.Product, + Name: in.Name, + Scopes: in.Scopes, + Prefix: plain[:prefixLen], + HashSHA256: sum[:], + Kind: in.Kind, + ExpiresAt: in.ExpiresAt, + CreatedBy: in.CreatedBy, }) if err != nil { if mapStoreError(w, err) { @@ -90,7 +150,7 @@ func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: in.TenantID, Action: "api_key.created", TargetID: k.ID, TargetType: "api_key", TargetName: in.Name, - Metadata: map[string]interface{}{"product": in.Product, "scopes": in.Scopes}, + Metadata: map[string]interface{}{"product": in.Product, "scopes": in.Scopes, "kind": in.Kind}, }) writeJSON(w, http.StatusCreated, createAPIKeyResp{ @@ -100,6 +160,12 @@ func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) { }) } +// listAPIKeyScopes — GET /v1/api-keys/scopes: the scope catalogue, for the +// portal's scope picker. +func (s *Server) listAPIKeyScopes(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"items": scopes.All()}) +} + func (s *Server) listAPIKeys(w http.ResponseWriter, r *http.Request) { tenantID := r.URL.Query().Get("tenant_id") if tenantID == "" { @@ -119,11 +185,14 @@ func (s *Server) listAPIKeys(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"items": list}) } +// revokeAPIKey — DELETE /v1/api-keys/{id}[?tenant_id=…]. With tenant_id the +// key must belong to that tenant (404 otherwise). func (s *Server) revokeAPIKey(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() id := r.PathValue("id") - if err := s.Store.RevokeAPIKey(ctx, id); err != nil { + tenantID := r.URL.Query().Get("tenant_id") + if err := s.Store.RevokeAPIKey(ctx, id, tenantID); err != nil { if mapStoreError(w, err) { return } @@ -131,7 +200,7 @@ func (s *Server) revokeAPIKey(w http.ResponseWriter, r *http.Request) { return } s.emitAudit(ctx, r, store.AuditEvent{ - Action: "api_key.revoked", TargetID: id, TargetType: "api_key", + TenantID: tenantID, Action: "api_key.revoked", TargetID: id, TargetType: "api_key", }) w.WriteHeader(http.StatusNoContent) } @@ -141,15 +210,24 @@ type verifyAPIKeyReq struct { } type verifyAPIKeyResp struct { - Valid bool `json:"valid"` - TenantID string `json:"tenant_id,omitempty"` - Product string `json:"product,omitempty"` - Scopes []string `json:"scopes,omitempty"` + Valid bool `json:"valid"` + TenantID string `json:"tenant_id,omitempty"` + Product string `json:"product,omitempty"` + Scopes []string `json:"scopes,omitempty"` + KeyID string `json:"key_id,omitempty"` + Kind string `json:"kind,omitempty"` + Holder string `json:"holder,omitempty"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + TenantStatus string `json:"tenant_status,omitempty"` + // Legacy — the key has no scopes and grants everything on Product (or + // on every entitled product when Product is empty), as before scopes. + Legacy bool `json:"legacy,omitempty"` } -// verifyAPIKey — POST /v1/internal/api-keys/verify. Used by headless products -// to validate inbound keys. Returns 200 with valid=false rather than 401 so -// the caller can decide what to do. +// verifyAPIKey — POST /v1/internal/api-keys/verify. Used by products to +// validate inbound keys. Returns 200 with valid=false rather than 401 so the +// caller can decide what to do. Products cache results for at most 60 s, so +// a revocation takes up to a minute to reach them. func (s *Server) verifyAPIKey(w http.ResponseWriter, r *http.Request) { var in verifyAPIKeyReq if !decodeJSON(w, r, &in) { @@ -163,31 +241,89 @@ func (s *Server) verifyAPIKey(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() - k, hash, err := s.Store.FindAPIKeyByPrefix(ctx, in.Key[:prefixLen]) + k, err := s.findAPIKey(ctx, in.Key) + if errors.Is(err, store.ErrNotFound) { + writeJSON(w, http.StatusOK, verifyAPIKeyResp{Valid: false}) + return + } if err != nil { - if errors.Is(err, store.ErrNotFound) { - writeJSON(w, http.StatusOK, verifyAPIKeyResp{Valid: false}) - return - } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } - if !verifyHash(in.Key, hash) { + if k.ExpiresAt != nil && !k.ExpiresAt.After(time.Now()) { writeJSON(w, http.StatusOK, verifyAPIKeyResp{Valid: false}) return } + entitled, status, err := s.entitledProducts(ctx, k.TenantID) + if errors.Is(err, store.ErrNotFound) { + writeJSON(w, http.StatusOK, verifyAPIKeyResp{Valid: false}) + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } // Best-effort touch — failures are non-fatal. if err := s.Store.TouchAPIKeyUsed(ctx, k.ID); err != nil { s.Log.Warn("touch api_key failed", "err", err) } - writeJSON(w, http.StatusOK, verifyAPIKeyResp{ - Valid: true, - TenantID: k.TenantID, - Product: k.Product, - Scopes: k.Scopes, - }) + resp := verifyAPIKeyResp{ + Valid: true, TenantID: k.TenantID, Product: k.Product, + KeyID: k.ID, Kind: k.Kind, Holder: k.Holder, ExpiresAt: k.ExpiresAt, + TenantStatus: status, Legacy: len(k.Scopes) == 0, + } + if !resp.Legacy { + resp.Scopes = scopes.Effective(k.Scopes, entitled) + } + writeJSON(w, http.StatusOK, resp) +} + +// findAPIKey resolves a plaintext key: keys since migration 0015 by their +// sha256 (indexed), older ones by prefix + argon2id. Prefixes are not +// unique, so every active candidate is checked. +func (s *Server) findAPIKey(ctx context.Context, plain string) (*store.APIKey, error) { + sum := sha256.Sum256([]byte(plain)) + k, err := s.Store.FindAPIKeyBySHA256(ctx, sum[:]) + if err == nil || !errors.Is(err, store.ErrNotFound) { + return k, err + } + cands, err := s.Store.FindAPIKeysByPrefix(ctx, plain[:prefixLen]) + if err != nil { + return nil, err + } + for i := range cands { + if verifyHash(plain, cands[i].Hash) { + return &cands[i].APIKey, nil + } + } + return nil, store.ErrNotFound +} + +// entitledProducts returns the products the tenant may use now (enabled, not +// expired) and the tenant status. Archived and halted tenants are entitled +// to nothing. +func (s *Server) entitledProducts(ctx context.Context, tenantID string) (map[string]bool, string, error) { + t, err := s.Store.GetTenant(ctx, tenantID) + if err != nil { + return nil, "", err + } + out := map[string]bool{} + if t.Status == store.StatusArchived || t.Status == store.StatusHalted { + return out, t.Status, nil + } + tps, err := s.Store.ListTenantProducts(ctx, t.ID) + if err != nil { + return nil, "", err + } + now := time.Now() + for _, tp := range tps { + if tp.Enabled && (tp.ExpiresAt == nil || tp.ExpiresAt.After(now)) { + out[tp.Product] = true + } + } + return out, t.Status, nil } // ─── helpers ────────────────────────────────────────────────────────────── @@ -210,19 +346,9 @@ func looksLikeKey(k string) bool { return true } -func hashAPIKey(plain string) string { - salt := make([]byte, 16) - _, _ = rand.Read(salt) - hash := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen) - // Encode as $argon2id$v=19$m=...,t=...,p=...$salt$hash so we can shift - // parameters later without re-keying. - return "argon2id|" + - base64.RawStdEncoding.EncodeToString(salt) + "|" + - base64.RawStdEncoding.EncodeToString(hash) -} - +// verifyHash checks a key created before migration 0015 against its stored +// argon2id hash. Format: argon2id||. func verifyHash(plain, stored string) bool { - // Format: argon2id|| if len(stored) < 12 || stored[:9] != "argon2id|" { return false } diff --git a/internal/server/apikeys_scoped_test.go b/internal/server/apikeys_scoped_test.go new file mode 100644 index 0000000..333c76f --- /dev/null +++ b/internal/server/apikeys_scoped_test.go @@ -0,0 +1,231 @@ +package server_test + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "net/http" + "reflect" + "testing" + "time" + + "golang.org/x/crypto/argon2" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +type verifyResult struct { + Valid bool `json:"valid"` + TenantID string `json:"tenant_id"` + Product string `json:"product"` + Scopes []string `json:"scopes"` + KeyID string `json:"key_id"` + Kind string `json:"kind"` + ExpiresAt *time.Time `json:"expires_at"` + TenantStatus string `json:"tenant_status"` + Legacy bool `json:"legacy"` +} + +func entitle(t *testing.T, h *testHarness, product string, enabled bool) { + t.Helper() + if _, err := h.store.UpsertTenantProduct(context.Background(), store.TenantProduct{ + TenantID: h.tenant.ID, Product: product, Enabled: enabled, Config: map[string]interface{}{}, + }); err != nil { + t.Fatal(err) + } +} + +func createKey(t *testing.T, h *testHarness, in map[string]any) (int, store.APIKey, string) { + t.Helper() + in["tenant_id"] = h.tenant.ID + resp, body := h.do("POST", "/v1/api-keys", in) + if resp.StatusCode != http.StatusCreated { + return resp.StatusCode, store.APIKey{}, string(body) + } + out := decode[struct { + APIKey store.APIKey `json:"api_key"` + Plaintext string `json:"plaintext"` + }](t, body) + return resp.StatusCode, out.APIKey, out.Plaintext +} + +func verify(t *testing.T, h *testHarness, key string) verifyResult { + t.Helper() + resp, body := h.do("POST", "/v1/internal/api-keys/verify", map[string]any{"key": key}) + if resp.StatusCode != http.StatusOK { + t.Fatalf("verify status = %d, body=%s", resp.StatusCode, body) + } + return decode[verifyResult](t, body) +} + +func TestScopedKey_verifyReportsKeyAndFiltersByEntitlement(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + entitle(t, h, "pruefwerk", true) + entitle(t, h, "firmwerk", true) + code, k, plain := createKey(t, h, map[string]any{ + "name": "werkmeister-test", "scopes": []string{"pruefwerk:findings.read", "firmwerk:licence", "pruefwerk:findings.read"}, + }) + if code != http.StatusCreated { + t.Fatalf("create: %d %s", code, plain) + } + if k.Kind != store.APIKeyKindUser || !reflect.DeepEqual(k.Scopes, []string{"firmwerk:licence", "pruefwerk:findings.read"}) { + t.Fatalf("created key %+v: want kind user and normalised scopes", k) + } + v := verify(t, h, plain) + if !v.Valid || v.KeyID != k.ID || v.Kind != "user" || v.Legacy || v.TenantStatus == "" || len(v.Scopes) != 2 { + t.Fatalf("verify = %+v", v) + } + + // Booking ends: the key keeps working for what is still booked. + entitle(t, h, "firmwerk", false) + v = verify(t, h, plain) + if !v.Valid || !reflect.DeepEqual(v.Scopes, []string{"pruefwerk:findings.read"}) { + t.Fatalf("after firmwerk ends: %+v", v) + } + }) +} + +func TestScopedKey_createValidation(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + entitle(t, h, "pruefwerk", true) + entitle(t, h, "werkpilot", false) + soon := time.Now().Add(24 * time.Hour).UTC().Format(time.RFC3339) + cases := []struct { + name string + in map[string]any + want int + }{ + {"unknown scope", map[string]any{"scopes": []string{"certifai:read"}}, http.StatusBadRequest}, + {"scope of another product", map[string]any{"product": "pruefwerk", "scopes": []string{"firmwerk:licence"}}, http.StatusBadRequest}, + {"not entitled", map[string]any{"scopes": []string{"werkpilot:licence"}}, http.StatusUnprocessableEntity}, + {"integration via service", map[string]any{"kind": "integration", "scopes": []string{"pruefwerk:findings.read"}}, http.StatusBadRequest}, + {"unknown kind", map[string]any{"kind": "robot"}, http.StatusBadRequest}, + {"ci without expiry", map[string]any{"kind": "ci", "scopes": []string{"pruefwerk:scans.run"}}, http.StatusBadRequest}, + {"ci too long", map[string]any{"kind": "ci", "scopes": []string{"pruefwerk:scans.run"}, "expires_at": time.Now().Add(400 * 24 * time.Hour).UTC().Format(time.RFC3339)}, http.StatusBadRequest}, + {"ci without scopes", map[string]any{"kind": "ci", "expires_at": soon}, http.StatusBadRequest}, + {"expiry in the past", map[string]any{"expires_at": time.Now().Add(-time.Hour).UTC().Format(time.RFC3339)}, http.StatusBadRequest}, + {"ci ok", map[string]any{"kind": "ci", "scopes": []string{"pruefwerk:scans.run"}, "expires_at": soon}, http.StatusCreated}, + } + for i, tc := range cases { + tc.in["name"] = "case-" + string(rune('a'+i)) + if code, _, body := createKey(t, h, tc.in); code != tc.want { + t.Errorf("%s: status %d, want %d (%s)", tc.name, code, tc.want, body) + } + } + }) +} + +func TestScopedKey_ciKeyCarriesExpiry(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + entitle(t, h, "pruefwerk", true) + exp := time.Now().Add(48 * time.Hour).UTC().Truncate(time.Second) + code, k, plain := createKey(t, h, map[string]any{ + "name": "ci", "kind": "ci", "scopes": []string{"pruefwerk:scans.run"}, "expires_at": exp.Format(time.RFC3339), + }) + if code != http.StatusCreated { + t.Fatalf("create: %d %s", code, plain) + } + v := verify(t, h, plain) + if !v.Valid || v.Kind != "ci" || v.ExpiresAt == nil || !v.ExpiresAt.Equal(exp) || k.ExpiresAt == nil { + t.Fatalf("verify = %+v", v) + } + }) +} + +func TestScopedKey_expiredKeyIsInvalid(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + past := time.Now().Add(-time.Minute) + plain := "bp_expiredexpiredexpiredexpired0" + sum := sha256Sum(plain) + if _, err := h.store.CreateAPIKey(context.Background(), store.APIKeyCreate{ + TenantID: h.tenant.ID, Name: "old-ci", Prefix: plain[:11], HashSHA256: sum, + Kind: store.APIKeyKindCI, ExpiresAt: &past, + }); err != nil { + t.Fatal(err) + } + if v := verify(t, h, plain); v.Valid { + t.Fatalf("expired key verified: %+v", v) + } + }) +} + +func TestScopedKey_revokeChecksTenant(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + code, k, plain := createKey(t, h, map[string]any{"name": "legacy"}) + if code != http.StatusCreated { + t.Fatalf("create: %d", code) + } + other := "00000000-0000-0000-0000-0000000000ff" + if resp, _ := h.do("DELETE", "/v1/api-keys/"+k.ID+"?tenant_id="+other, nil); resp.StatusCode != http.StatusNotFound { + t.Fatalf("revoke by another tenant: %d, want 404", resp.StatusCode) + } + if v := verify(t, h, plain); !v.Valid || !v.Legacy { + t.Fatalf("key must survive a foreign revoke and be legacy: %+v", v) + } + if resp, _ := h.do("DELETE", "/v1/api-keys/"+k.ID+"?tenant_id="+h.tenant.ID, nil); resp.StatusCode != http.StatusNoContent { + t.Fatalf("revoke by owner: %d", resp.StatusCode) + } + if v := verify(t, h, plain); v.Valid { + t.Fatal("revoked key still verifies") + } + }) +} + +// Keys created before migration 0015 carry only an argon2id hash and share +// an 8-character display prefix by chance; both must verify. +func TestLegacyArgonKeys_prefixCollision(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + a := "bp_SAMEPREFaaaaaaaaaaaaaaaaaaaaaaa" + b := "bp_SAMEPREFbbbbbbbbbbbbbbbbbbbbbbb" + for i, plain := range []string{a, b} { + if _, err := h.store.CreateAPIKey(context.Background(), store.APIKeyCreate{ + TenantID: h.tenant.ID, Name: "old-" + string(rune('a'+i)), Prefix: plain[:11], Hash: argonHash(plain), + }); err != nil { + t.Fatal(err) + } + } + for _, plain := range []string{a, b} { + if v := verify(t, h, plain); !v.Valid || !v.Legacy || v.Kind != "user" { + t.Errorf("legacy key %s…: %+v", plain[:11], v) + } + } + if v := verify(t, h, "bp_SAMEPREFccccccccccccccccccccccc"); v.Valid { + t.Error("unknown key with a known prefix verified") + } + }) +} + +func TestAPIKeyScopes_catalogue(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + resp, body := h.do("GET", "/v1/api-keys/scopes", nil) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status %d", resp.StatusCode) + } + out := decode[struct { + Items []struct{ Name, Product string } `json:"items"` + }](t, body) + found := false + for _, s := range out.Items { + if s.Name == "werkbank:runner" && s.Product == "pruefwerk" { + found = true + } + } + if !found { + t.Fatalf("werkbank:runner missing from %v", out.Items) + } + }) +} + +// argonHash mirrors the pre-0015 key hashing (argon2id|salt|hash). +func argonHash(plain string) string { + salt := make([]byte, 16) + _, _ = rand.Read(salt) + sum := argon2.IDKey([]byte(plain), salt, 1, 64*1024, 4, 32) + return "argon2id|" + base64.RawStdEncoding.EncodeToString(salt) + "|" + base64.RawStdEncoding.EncodeToString(sum) +} + +func sha256Sum(s string) []byte { + sum := sha256.Sum256([]byte(s)) + return sum[:] +} diff --git a/internal/server/apikeys_test.go b/internal/server/apikeys_test.go index 896425a..88358c5 100644 --- a/internal/server/apikeys_test.go +++ b/internal/server/apikeys_test.go @@ -9,9 +9,10 @@ import ( func TestCreateAPIKey_then_verify(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { + entitle(t, h, "pruefwerk", true) resp, body := h.do("POST", "/v1/api-keys", map[string]any{ "tenant_id": h.tenant.ID, "name": "ci-bot", "product": "pruefwerk", - "scopes": []string{"certifai:read", "certifai:write"}, + "scopes": []string{"pruefwerk:findings.read", "pruefwerk:scans.run"}, }) if resp.StatusCode != http.StatusCreated { t.Fatalf("create status = %d, body=%s", resp.StatusCode, body) diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index a24a7b2..4c14fc9 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -43,6 +43,7 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"GET", "/v1/tenants/by-slug/acme"}, {"GET", "/v1/entitlements?tenant_id=00000000-0000-0000-0000-000000000001"}, {"GET", "/v1/api-keys?tenant_id=00000000-0000-0000-0000-000000000001"}, + {"GET", "/v1/api-keys/scopes"}, {"GET", "/v1/catalog"}, {"GET", "/v1/audit?limit=10"}, {"POST", "/v1/internal/keycloak/claims"}, diff --git a/internal/server/server.go b/internal/server/server.go index f2740ee..08d4210 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -145,6 +145,7 @@ func NewRouter(s *Server) http.Handler { // api keys mux.HandleFunc("POST /v1/api-keys", s.createAPIKey) mux.HandleFunc("GET /v1/api-keys", s.listAPIKeys) + mux.HandleFunc("GET /v1/api-keys/scopes", s.listAPIKeyScopes) mux.HandleFunc("DELETE /v1/api-keys/{id}", s.revokeAPIKey) mux.HandleFunc("POST /v1/internal/api-keys/verify", s.verifyAPIKey) diff --git a/internal/server/team_test.go b/internal/server/team_test.go index b1ccf73..e896de4 100644 --- a/internal/server/team_test.go +++ b/internal/server/team_test.go @@ -184,7 +184,7 @@ func TestTeam_blockAndUnblock(t *testing.T) { mine, _ := f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "ci", Prefix: "bp_aaaa1", Hash: "h1", CreatedBy: "fin@acme.test"}) _, _ = f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "other", Prefix: "bp_aaaa2", Hash: "h2", CreatedBy: "admin@acme.test"}) gone, _ := f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "old", Prefix: "bp_aaaa3", Hash: "h3", CreatedBy: "u-fin"}) - _ = f.s.Store.RevokeAPIKey(ctx, gone.ID) + _ = f.s.Store.RevokeAPIKey(ctx, gone.ID, "") code, out, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin) if code != http.StatusOK || out.Status != "blocked" || out.Member.Status != "blocked" || !out.SessionsEnded { diff --git a/internal/store/memory.go b/internal/store/memory.go index ed0859d..f5e5daa 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -1,6 +1,7 @@ package store import ( + "bytes" "context" "sort" "strings" @@ -19,7 +20,6 @@ type Memory struct { bySlug map[string]string // slug → id products map[string]map[string]*TenantProduct // tenant_id → product → row apiKeys map[string]*apiKeyWithHash // id → key - byPrefix map[string]string // prefix → id audit []*AuditEvent auditID int64 catalog []Product @@ -44,7 +44,8 @@ type Memory struct { type apiKeyWithHash struct { APIKey - Hash string + Hash string + HashSHA256 []byte } // NewMemory returns a fresh in-memory store with the seed acme tenant. @@ -54,7 +55,6 @@ func NewMemory() *Memory { bySlug: make(map[string]string), products: make(map[string]map[string]*TenantProduct), apiKeys: make(map[string]*apiKeyWithHash), - byPrefix: make(map[string]string), catalog: DefaultProducts(), subs: make(map[string]*Subscription), usageKey: make(map[string]int64), @@ -368,6 +368,18 @@ func (m *Memory) CreateAPIKey(_ context.Context, in APIKeyCreate) (*APIKey, erro if _, ok := m.tenants[in.TenantID]; !ok { return nil, ErrNotFound } + for _, k := range m.apiKeys { + if k.TenantID == in.TenantID && k.Name == in.Name { + return nil, ErrConflict + } + if len(in.HashSHA256) > 0 && bytes.Equal(k.HashSHA256, in.HashSHA256) { + return nil, ErrConflict + } + } + kind := in.Kind + if kind == "" { + kind = APIKeyKindUser + } now := time.Now().UTC() k := &apiKeyWithHash{ APIKey: APIKey{ @@ -377,30 +389,42 @@ func (m *Memory) CreateAPIKey(_ context.Context, in APIKeyCreate) (*APIKey, erro Name: in.Name, Scopes: append([]string{}, in.Scopes...), Prefix: in.Prefix, + Kind: kind, + Holder: in.Holder, + ExpiresAt: in.ExpiresAt, CreatedBy: in.CreatedBy, CreatedAt: now, }, - Hash: in.Hash, + Hash: in.Hash, + HashSHA256: append([]byte(nil), in.HashSHA256...), } m.apiKeys[k.ID] = k - m.byPrefix[k.Prefix] = k.ID cp := k.APIKey return &cp, nil } -func (m *Memory) FindAPIKeyByPrefix(_ context.Context, prefix string) (*APIKey, string, error) { +func (m *Memory) FindAPIKeyBySHA256(_ context.Context, sum []byte) (*APIKey, error) { m.mu.RLock() defer m.mu.RUnlock() - id, ok := m.byPrefix[prefix] - if !ok { - return nil, "", ErrNotFound + for _, k := range m.apiKeys { + if k.RevokedAt == nil && len(k.HashSHA256) > 0 && bytes.Equal(k.HashSHA256, sum) { + cp := k.APIKey + return &cp, nil + } } - k := m.apiKeys[id] - if k.RevokedAt != nil { - return nil, "", ErrNotFound + return nil, ErrNotFound +} + +func (m *Memory) FindAPIKeysByPrefix(_ context.Context, prefix string) ([]APIKeyCandidate, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var out []APIKeyCandidate + for _, k := range m.apiKeys { + if k.Prefix == prefix && k.RevokedAt == nil && k.Hash != "" { + out = append(out, APIKeyCandidate{APIKey: k.APIKey, Hash: k.Hash}) + } } - cp := k.APIKey - return &cp, k.Hash, nil + return out, nil } func (m *Memory) TouchAPIKeyUsed(_ context.Context, id string) error { @@ -415,11 +439,11 @@ func (m *Memory) TouchAPIKeyUsed(_ context.Context, id string) error { return nil } -func (m *Memory) RevokeAPIKey(_ context.Context, id string) error { +func (m *Memory) RevokeAPIKey(_ context.Context, id, tenantID string) error { m.mu.Lock() defer m.mu.Unlock() k, ok := m.apiKeys[id] - if !ok { + if !ok || k.RevokedAt != nil || (tenantID != "" && k.TenantID != tenantID) { return ErrNotFound } now := time.Now().UTC() @@ -521,7 +545,6 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error { delete(m.products, id) for kid, k := range m.apiKeys { if k.TenantID == id { - delete(m.byPrefix, k.Prefix) delete(m.apiKeys, kid) } } diff --git a/internal/store/postgres.go b/internal/store/postgres.go index 9657f6f..061ef1e 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -245,14 +245,23 @@ func (p *Postgres) ListTenantProducts(ctx context.Context, tenantID string) ([]T // ─── api keys ───────────────────────────────────────────────────────────── func (p *Postgres) CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error) { - var product any + var product, createdBy, hash, holder any if in.Product != "" { product = in.Product } - var createdBy any if in.CreatedBy != "" { createdBy = in.CreatedBy } + if in.Hash != "" { + hash = in.Hash + } + if in.Holder != "" { + holder = in.Holder + } + kind := in.Kind + if kind == "" { + kind = APIKeyKindUser + } // Coerce nil to an empty slice — the schema's NOT NULL DEFAULT only // fires when the column is omitted, not when an explicit NULL is sent. scopes := in.Scopes @@ -260,11 +269,10 @@ func (p *Postgres) CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, scopes = []string{} } row := p.pool.QueryRow(ctx, ` - INSERT INTO api_keys (tenant_id, product, name, scopes, hash, prefix, created_by) - VALUES ($1::uuid, $2, $3, $4, $5, $6, $7) - RETURNING id::text, tenant_id::text, COALESCE(product,''), name, scopes, prefix, - COALESCE(created_by,''), last_used_at, revoked_at, created_at`, - in.TenantID, product, in.Name, scopes, in.Hash, in.Prefix, createdBy, + INSERT INTO api_keys (tenant_id, product, name, scopes, hash, hash_sha256, prefix, kind, holder, expires_at, created_by) + VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + RETURNING `+apiKeyCols, + in.TenantID, product, in.Name, scopes, hash, in.HashSHA256, in.Prefix, kind, holder, in.ExpiresAt, createdBy, ) k, err := scanAPIKey(row) if err != nil { @@ -280,41 +288,47 @@ func (p *Postgres) CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, return k, nil } -func scanAPIKey(row pgx.Row) (*APIKey, error) { +// apiKeyCols is the column list scanAPIKey reads, in order. +const apiKeyCols = `id::text, tenant_id::text, COALESCE(product,''), name, scopes, prefix, + kind, COALESCE(holder,''), expires_at, COALESCE(created_by,''), last_used_at, revoked_at, created_at` + +func scanAPIKey(row pgx.Row, extra ...any) (*APIKey, error) { var k APIKey - var lastUsed, revoked *time.Time - err := row.Scan(&k.ID, &k.TenantID, &k.Product, &k.Name, &k.Scopes, &k.Prefix, - &k.CreatedBy, &lastUsed, &revoked, &k.CreatedAt) + dest := append([]any{&k.ID, &k.TenantID, &k.Product, &k.Name, &k.Scopes, &k.Prefix, + &k.Kind, &k.Holder, &k.ExpiresAt, &k.CreatedBy, &k.LastUsedAt, &k.RevokedAt, &k.CreatedAt}, extra...) + err := row.Scan(dest...) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, err } - k.LastUsedAt = lastUsed - k.RevokedAt = revoked return &k, nil } -func (p *Postgres) FindAPIKeyByPrefix(ctx context.Context, prefix string) (*APIKey, string, error) { - row := p.pool.QueryRow(ctx, ` - SELECT id::text, tenant_id::text, COALESCE(product,''), name, scopes, prefix, - COALESCE(created_by,''), last_used_at, revoked_at, created_at, hash - FROM api_keys WHERE prefix = $1 AND revoked_at IS NULL`, prefix) - var k APIKey - var lastUsed, revoked *time.Time - var hash string - err := row.Scan(&k.ID, &k.TenantID, &k.Product, &k.Name, &k.Scopes, &k.Prefix, - &k.CreatedBy, &lastUsed, &revoked, &k.CreatedAt, &hash) - if errors.Is(err, pgx.ErrNoRows) { - return nil, "", ErrNotFound - } +func (p *Postgres) FindAPIKeyBySHA256(ctx context.Context, sum []byte) (*APIKey, error) { + return scanAPIKey(p.pool.QueryRow(ctx, ` + SELECT `+apiKeyCols+` FROM api_keys WHERE hash_sha256 = $1 AND revoked_at IS NULL`, sum)) +} + +func (p *Postgres) FindAPIKeysByPrefix(ctx context.Context, prefix string) ([]APIKeyCandidate, error) { + rows, err := p.pool.Query(ctx, ` + SELECT `+apiKeyCols+`, hash FROM api_keys + WHERE prefix = $1 AND revoked_at IS NULL AND hash IS NOT NULL`, prefix) if err != nil { - return nil, "", err + return nil, err } - k.LastUsedAt = lastUsed - k.RevokedAt = revoked - return &k, hash, nil + defer rows.Close() + var out []APIKeyCandidate + for rows.Next() { + var hash string + k, err := scanAPIKey(rows, &hash) + if err != nil { + return nil, err + } + out = append(out, APIKeyCandidate{APIKey: *k, Hash: hash}) + } + return out, rows.Err() } func (p *Postgres) TouchAPIKeyUsed(ctx context.Context, id string) error { @@ -328,8 +342,10 @@ func (p *Postgres) TouchAPIKeyUsed(ctx context.Context, id string) error { return nil } -func (p *Postgres) RevokeAPIKey(ctx context.Context, id string) error { - tag, err := p.pool.Exec(ctx, `UPDATE api_keys SET revoked_at = NOW() WHERE id = $1::uuid AND revoked_at IS NULL`, id) +func (p *Postgres) RevokeAPIKey(ctx context.Context, id, tenantID string) error { + tag, err := p.pool.Exec(ctx, ` + UPDATE api_keys SET revoked_at = NOW() + WHERE id = $1::uuid AND revoked_at IS NULL AND ($2 = '' OR tenant_id::text = $2)`, id, tenantID) if err != nil { return err } @@ -344,24 +360,18 @@ func (p *Postgres) ListAPIKeys(ctx context.Context, tenantID string) ([]APIKey, return nil, err } rows, err := p.pool.Query(ctx, ` - SELECT id::text, tenant_id::text, COALESCE(product,''), name, scopes, prefix, - COALESCE(created_by,''), last_used_at, revoked_at, created_at - FROM api_keys WHERE tenant_id = $1::uuid ORDER BY created_at DESC`, tenantID) + SELECT `+apiKeyCols+` FROM api_keys WHERE tenant_id = $1::uuid ORDER BY created_at DESC`, tenantID) if err != nil { return nil, err } defer rows.Close() out := []APIKey{} for rows.Next() { - var k APIKey - var lastUsed, revoked *time.Time - if err := rows.Scan(&k.ID, &k.TenantID, &k.Product, &k.Name, &k.Scopes, &k.Prefix, - &k.CreatedBy, &lastUsed, &revoked, &k.CreatedAt); err != nil { + k, err := scanAPIKey(rows) + if err != nil { return nil, err } - k.LastUsedAt = lastUsed - k.RevokedAt = revoked - out = append(out, k) + out = append(out, *k) } return out, rows.Err() } diff --git a/internal/store/store.go b/internal/store/store.go index 5f6160a..00223bb 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -42,13 +42,24 @@ type TenantUpdate struct { // APIKeyCreate is the input shape for Store.CreateAPIKey. type APIKeyCreate struct { - TenantID string - Product string // empty = applies to all products - Name string - Scopes []string - Prefix string - Hash string // argon2id encoded - CreatedBy string + TenantID string + Product string // empty = applies to all products + Name string + Scopes []string + Prefix string + Hash string // argon2id encoded; keys created before migration 0015 only + HashSHA256 []byte // sha256 of the plaintext; every new key + Kind string // user | ci | integration; empty = user + Holder string // integration keys only + ExpiresAt *time.Time + CreatedBy string +} + +// APIKeyCandidate is an active key found by its display prefix, with the +// stored argon2id hash the caller must check. +type APIKeyCandidate struct { + APIKey + Hash string } // AuditFilter narrows /v1/audit GET results. @@ -88,9 +99,14 @@ type Store interface { // API keys CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error) - FindAPIKeyByPrefix(ctx context.Context, prefix string) (*APIKey, string, error) // returns key + hash + // FindAPIKeyBySHA256 returns the active (not revoked) key with this hash. + FindAPIKeyBySHA256(ctx context.Context, sum []byte) (*APIKey, error) + // FindAPIKeysByPrefix returns every active argon2id key with this prefix; + // prefixes are not unique, the caller checks each hash. + FindAPIKeysByPrefix(ctx context.Context, prefix string) ([]APIKeyCandidate, error) TouchAPIKeyUsed(ctx context.Context, id string) error - RevokeAPIKey(ctx context.Context, id string) error + // RevokeAPIKey revokes key id; a non-empty tenantID must own it, else ErrNotFound. + RevokeAPIKey(ctx context.Context, id, tenantID string) error ListAPIKeys(ctx context.Context, tenantID string) ([]APIKey, error) // Audit diff --git a/internal/store/types.go b/internal/store/types.go index 7658c17..94df1dd 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -43,6 +43,13 @@ type TenantProduct struct { UpdatedAt time.Time `json:"updated_at"` } +// API key kinds (migration 0015). +const ( + APIKeyKindUser = "user" + APIKeyKindCI = "ci" + APIKeyKindIntegration = "integration" +) + // APIKey — portal-owned. Plaintext key is shown ONCE on creation; // stored as argon2id hash + prefix for UI display. type APIKey struct { @@ -52,6 +59,9 @@ type APIKey struct { Name string `json:"name"` Scopes []string `json:"scopes"` Prefix string `json:"prefix"` + Kind string `json:"kind"` // user | ci | integration + Holder string `json:"holder,omitempty"` // integration keys: holding product + ExpiresAt *time.Time `json:"expires_at,omitempty"` CreatedBy string `json:"created_by,omitempty"` LastUsedAt *time.Time `json:"last_used_at,omitempty"` RevokedAt *time.Time `json:"revoked_at,omitempty"` diff --git a/migrations/0015_api_keys_scoped.down.sql b/migrations/0015_api_keys_scoped.down.sql new file mode 100644 index 0000000..2c481cf --- /dev/null +++ b/migrations/0015_api_keys_scoped.down.sql @@ -0,0 +1,13 @@ +-- Keys created with only a sha256 hash cannot be represented before 0015; +-- rolling back drops them (they stop working either way). +DELETE FROM api_keys WHERE hash IS NULL; +DROP INDEX IF EXISTS api_keys_hash_sha256_idx; +ALTER TABLE api_keys + DROP CONSTRAINT IF EXISTS api_keys_holder_kind, + DROP CONSTRAINT IF EXISTS api_keys_hash_present; +ALTER TABLE api_keys ALTER COLUMN hash SET NOT NULL; +ALTER TABLE api_keys + DROP COLUMN hash_sha256, + DROP COLUMN expires_at, + DROP COLUMN holder, + DROP COLUMN kind; diff --git a/migrations/0015_api_keys_scoped.up.sql b/migrations/0015_api_keys_scoped.up.sql new file mode 100644 index 0000000..af0af25 --- /dev/null +++ b/migrations/0015_api_keys_scoped.up.sql @@ -0,0 +1,18 @@ +-- Tenant-bound, scoped API keys (ADR: prerequisite 1 of the Werkmeister plan). +-- kind: user (portal, a person's key), ci (CLI licences in CI), integration +-- (held by a product for a tenant, e.g. Werkmeister). New keys are stored as +-- sha256 of the 192-bit random key (indexed lookup); rows created before this +-- migration keep their argon2id hash. +ALTER TABLE api_keys + ADD COLUMN kind TEXT NOT NULL DEFAULT 'user' CHECK (kind IN ('user', 'ci', 'integration')), + ADD COLUMN holder TEXT, + ADD COLUMN expires_at TIMESTAMPTZ, + ADD COLUMN hash_sha256 BYTEA; + +ALTER TABLE api_keys ALTER COLUMN hash DROP NOT NULL; + +ALTER TABLE api_keys + ADD CONSTRAINT api_keys_hash_present CHECK (hash IS NOT NULL OR hash_sha256 IS NOT NULL), + ADD CONSTRAINT api_keys_holder_kind CHECK ((kind = 'integration') = (holder IS NOT NULL)); + +CREATE UNIQUE INDEX api_keys_hash_sha256_idx ON api_keys (hash_sha256) WHERE hash_sha256 IS NOT NULL; diff --git a/openapi.yaml b/openapi.yaml index 4067eee..3bf5ead 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -1084,15 +1084,42 @@ paths: application/json: { schema: { $ref: "#/components/schemas/APIKeyCreated" } } "400": { $ref: "#/components/responses/BadRequest" } "404": { $ref: "#/components/responses/NotFound" } + "409": { $ref: "#/components/responses/Conflict" } + "422": + description: A scope needs a product the tenant is not entitled to. + content: + application/json: { schema: { $ref: "#/components/schemas/Error" } } + + /v1/api-keys/scopes: + get: + summary: The API key scope catalogue (for the portal's scope picker). + responses: + "200": + description: Every grantable scope. + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: { $ref: "#/components/schemas/APIKeyScope" } /v1/api-keys/{id}: delete: summary: Revoke an API key (sets revoked_at). + description: With tenant_id the key must belong to that tenant, else 404. + Products cache verify results for up to 60 s, so a revocation takes + up to a minute to reach them. parameters: - in: path name: id required: true schema: { type: string, format: uuid } + - in: query + name: tenant_id + required: false + schema: { type: string, format: uuid } responses: "204": description: Revoked. @@ -1895,6 +1922,9 @@ components: name: { type: string } scopes: { type: array, items: { type: string } } prefix: { type: string } + kind: { type: string, enum: [user, ci, integration] } + holder: { type: string, description: "integration keys: the holding product" } + expires_at: { type: string, format: date-time, nullable: true } created_by: { type: string } last_used_at: { type: string, format: date-time, nullable: true } revoked_at: { type: string, format: date-time, nullable: true } @@ -1907,9 +1937,23 @@ components: tenant_id: { type: string, format: uuid } name: { type: string, maxLength: 100 } product: { type: string } - scopes: { type: array, items: { type: string } } + scopes: + type: array + items: { type: string } + description: Names from GET /v1/api-keys/scopes. Empty = legacy full + grant on product (deprecated); required for kind ci. + kind: { type: string, enum: [user, ci], default: user } + expires_at: { type: string, format: date-time, description: "required for kind ci, at most 365 days ahead" } created_by: { type: string } + APIKeyScope: + type: object + required: [name, product, description] + properties: + name: { type: string, example: "pruefwerk:findings.read" } + product: { type: string, description: "catalogue product the tenant must be entitled to" } + description: { type: string } + APIKeyCreated: type: object required: [api_key, plaintext, warning] @@ -1925,7 +1969,20 @@ components: valid: { type: boolean } tenant_id: { type: string, format: uuid } product: { type: string } - scopes: { type: array, items: { type: string } } + scopes: + type: array + items: { type: string } + description: The key's scopes limited to products the tenant is + entitled to right now. + key_id: { type: string, format: uuid } + kind: { type: string, enum: [user, ci, integration] } + holder: { type: string } + expires_at: { type: string, format: date-time } + tenant_status: { type: string } + legacy: + type: boolean + description: The key has no scopes and grants everything on product + (or on every entitled product when product is empty). AuditAppend: type: object -- 2.54.1