Files
tenant-registry/internal/server/apikeys_integration_test.go
T
Sharang ParnerkarandClaude Opus 5.5 b89dd2ae4c
ci / shared (pull_request) Successful in 13s
ci / test (pull_request) Successful in 25m18s
ci / image (pull_request) Skipped
feat(api-keys): CI licences by API key and integration keys
Step 1b of ADR 0001, with the user's decisions D1–D3 recorded:

- POST /v1/licences/ci (PUBLIC_EXPLICIT, the bearer is a tenant API key
  with scope <product>:licence): 24 h licence with kind "ci", no
  heartbeat, not a seat (D1; the registry records ci.licence usage once
  per key and day). Reused per key, device and UTC day; at most 60
  calls per key and hour. Unblocks firmwerk#64 step 1.
- Werkpilot CI licences carry the tenant's LiteLLM key (D2) with a
  1-day LiteLLM expiry; the secret is sealed on the licence row
  (AES-256-GCM, new SECRETS_ENCRYPTION_KEY, migration 0017) so the
  reused licence hands out the same key. At most 10 keys per API key
  and day. Without the encryption key a reuse comes without the key.
- Integration keys: a tenant admin's user token from a holder product's
  web client (werkmeister-<env>) creates, lists and revokes that
  holder's key for its own tenant only; scopes from a per-holder
  allowlist, the holder product must be booked. A user token on the key
  routes is classified as AUTHZ group api-keys.integration, so plain
  api-keys stays a service grant.
- Migration 0016: key names are unique among active keys only, so a
  revoked name can be reused (re-issue = revoke, then create).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:32:01 +02:00

153 lines
6.3 KiB
Go

package server
import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
const integrationRules = "werkmeister-stage:api-keys.integration;werkmeister-svc-stage:entitlements;portal-svc:*"
func wmAdmin(tenantID string, roles ...string) *authn.Principal {
if len(roles) == 0 {
roles = []string{"IT_ADMIN"}
}
return &authn.Principal{Subject: "u-admin", ClientID: "werkmeister-stage", TenantID: tenantID, Email: "admin@acme.test", OrgRoles: roles}
}
func integrationFixture(t *testing.T, p func(tenantID string) *authn.Principal, bookWerkmeister bool) *teamFixture {
t.Helper()
// The principal needs the tenant id, which the fixture creates.
var principal authn.Principal
f := newTeamFixture(t, &principal, integrationRules)
principal = *p(f.tenant.ID)
if bookWerkmeister {
if _, err := f.s.Store.UpsertTenantProduct(context.Background(), store.TenantProduct{
TenantID: f.tenant.ID, Product: "werkmeister", Enabled: true, Config: map[string]interface{}{},
}); err != nil {
t.Fatal(err)
}
}
return f
}
func createIntegration(t *testing.T, f *teamFixture, body string) (int, string) {
t.Helper()
code, _, raw := f.call(t, "POST", "/v1/api-keys", body, nil)
return code, raw
}
func TestIntegrationKey_createdByTenantAdmin(t *testing.T) {
f := integrationFixture(t, func(id string) *authn.Principal { return wmAdmin(id) }, true)
code, raw := createIntegration(t, f, `{"tenant_id":"`+f.tenant.ID+`","scopes":["pruefwerk:findings.read","pruefwerk:scans.run"]}`)
if code != http.StatusCreated {
t.Fatalf("create: %d %s", code, raw)
}
var out createAPIKeyResp
_ = json.Unmarshal([]byte(raw), &out)
k := out.APIKey
if k.Kind != store.APIKeyKindIntegration || k.Holder != "werkmeister" || k.Name != "werkmeister" || k.TenantID != f.tenant.ID || k.CreatedBy != "admin@acme.test" {
t.Fatalf("key %+v", k)
}
if !strings.HasPrefix(out.Plaintext, "bp_") {
t.Fatal("no plaintext")
}
// One key per tenant and holder: re-issue is revoke, then create.
if code, _ := createIntegration(t, f, `{"scopes":["pruefwerk:findings.read"]}`); code != http.StatusConflict {
t.Fatalf("second create: %d, want 409", code)
}
}
func TestIntegrationKey_refusals(t *testing.T) {
cases := []struct {
name string
p func(string) *authn.Principal
book bool
body func(tenantID string) string
want int
}{
{"werkmeister not booked", func(id string) *authn.Principal { return wmAdmin(id) }, false,
func(string) string { return `{"scopes":["pruefwerk:findings.read"]}` }, http.StatusUnprocessableEntity},
{"not an admin", func(id string) *authn.Principal { return wmAdmin(id, "FINANCE") }, true,
func(string) string { return `{"scopes":["pruefwerk:findings.read"]}` }, http.StatusForbidden},
{"other tenant", func(id string) *authn.Principal { return wmAdmin(id) }, true,
func(string) string {
return `{"tenant_id":"00000000-0000-0000-0000-0000000000ff","scopes":["pruefwerk:findings.read"]}`
}, http.StatusForbidden},
{"scope outside the allowlist", func(id string) *authn.Principal { return wmAdmin(id) }, true,
func(string) string { return `{"scopes":["werkbank:runner"]}` }, http.StatusBadRequest},
{"no scopes", func(id string) *authn.Principal { return wmAdmin(id) }, true,
func(string) string { return `{}` }, http.StatusBadRequest},
{"wrong kind", func(id string) *authn.Principal { return wmAdmin(id) }, true,
func(string) string { return `{"kind":"ci","scopes":["pruefwerk:findings.read"]}` }, http.StatusBadRequest},
{"client without AUTHZ group", func(id string) *authn.Principal {
p := wmAdmin(id)
p.ClientID = "portal-stage"
return p
}, true, func(string) string { return `{"scopes":["pruefwerk:findings.read"]}` }, http.StatusForbidden},
{"service client of the product", func(string) *authn.Principal {
return &authn.Principal{Subject: "svc", ClientID: "werkmeister-svc-stage"}
}, true, func(id string) string {
return `{"tenant_id":"` + id + `","name":"x","scopes":["pruefwerk:findings.read"]}`
}, http.StatusForbidden},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := integrationFixture(t, tc.p, tc.book)
if code, raw := createIntegration(t, f, tc.body(f.tenant.ID)); code != tc.want {
t.Fatalf("status %d, want %d: %s", code, tc.want, raw)
}
})
}
}
func TestIntegrationKey_listAndRevokeOwnOnly(t *testing.T) {
f := integrationFixture(t, func(id string) *authn.Principal { return wmAdmin(id) }, true)
ctx := context.Background()
legacy, err := f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "portal-key", Prefix: "bp_legacy01", HashSHA256: hashKey("bp_legacy01xxxxxxxxxxxxxxxxxxxxxx")})
if err != nil {
t.Fatal(err)
}
code, raw := createIntegration(t, f, `{"scopes":["pruefwerk:findings.read"]}`)
if code != http.StatusCreated {
t.Fatalf("create: %d %s", code, raw)
}
var created createAPIKeyResp
_ = json.Unmarshal([]byte(raw), &created)
code, _, raw = f.call(t, "GET", "/v1/api-keys?tenant_id="+f.tenant.ID, "", nil)
var list struct{ Items []store.APIKey }
_ = json.Unmarshal([]byte(raw), &list)
if code != http.StatusOK || len(list.Items) != 1 || list.Items[0].ID != created.APIKey.ID {
t.Fatalf("list: %d %s", code, raw)
}
if code, _, _ := f.call(t, "GET", "/v1/api-keys?tenant_id=00000000-0000-0000-0000-0000000000ff", "", nil); code != http.StatusForbidden {
t.Fatalf("list other tenant: %d", code)
}
if code, _, _ := f.call(t, "DELETE", "/v1/api-keys/"+legacy.ID, "", nil); code != http.StatusNotFound {
t.Fatalf("revoke a portal key with a user token: %d, want 404", code)
}
if code, _, _ := f.call(t, "DELETE", "/v1/api-keys/"+created.APIKey.ID, "", nil); code != http.StatusNoContent {
t.Fatalf("revoke own integration key: %d", code)
}
if code, _ := createIntegration(t, f, `{"scopes":["pruefwerk:findings.read"]}`); code != http.StatusCreated {
t.Fatalf("re-issue after revoke: %d", code)
}
}
func TestIntegrationHolder(t *testing.T) {
for azp, want := range map[string]string{
"werkmeister-stage": "werkmeister", "werkmeister-prod": "werkmeister", "werkmeister": "werkmeister",
"portal-stage": "", "werkmeister-svc-stage": "", "": "",
} {
if got := integrationHolder(azp); got != want {
t.Errorf("integrationHolder(%q) = %q, want %q", azp, got, want)
}
}
}