Files
tenant-registry/internal/server/apikeys_scoped_test.go
sharang 5b4590d3bc
ci / shared (push) Successful in 13s
ci / test (push) Successful in 25m10s
ci / image (push) Successful in 36s
feat(api-keys): CI licences by API key and integration keys (#71)
2026-10-13 22:12:05 +00:00

250 lines
9.1 KiB
Go

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[:]
}
func TestAPIKey_nameReusableAfterRevoke(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
code, k, _ := createKey(t, h, map[string]any{"name": "deploy"})
if code != http.StatusCreated {
t.Fatalf("create: %d", code)
}
if code, _, _ := createKey(t, h, map[string]any{"name": "deploy"}); code != http.StatusConflict {
t.Fatalf("duplicate active name: %d, want 409", code)
}
if resp, _ := h.do("DELETE", "/v1/api-keys/"+k.ID, nil); resp.StatusCode != http.StatusNoContent {
t.Fatalf("revoke: %d", resp.StatusCode)
}
if code, _, body := createKey(t, h, map[string]any{"name": "deploy"}); code != http.StatusCreated {
t.Fatalf("reuse after revoke: %d %s", code, body)
}
})
}