package server_test import ( "bytes" "context" "encoding/base64" "encoding/json" "io" "net/http" "strings" "testing" "time" "git.breakpilot.com/platform/tenant-registry/internal/secretbox" "git.breakpilot.com/platform/tenant-registry/internal/store" ) type ciLicence struct { ID string `json:"id"` Licence string `json:"licence"` Warnings []string `json:"warnings"` } func postCI(t *testing.T, h *testHarness, key, product, device string) (int, ciLicence, string) { t.Helper() buf, _ := json.Marshal(map[string]string{"product": product, "device": device}) req, _ := http.NewRequest("POST", h.srv.URL+"/v1/licences/ci", bytes.NewReader(buf)) req.Header.Set("Content-Type", "application/json") if key != "" { req.Header.Set("Authorization", "Bearer "+key) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer func() { _ = resp.Body.Close() }() body, _ := io.ReadAll(resp.Body) var out ciLicence _ = json.Unmarshal(body, &out) return resp.StatusCode, out, string(body) } func jwtClaims(t *testing.T, token string) map[string]any { t.Helper() parts := strings.Split(token, ".") if len(parts) != 3 { t.Fatalf("not a JWT: %q", token) } raw, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil { t.Fatal(err) } var c map[string]any _ = json.Unmarshal(raw, &c) return c } func ciKey(t *testing.T, h *testHarness, name string, scopes ...string) string { t.Helper() code, _, plain := createKey(t, h, map[string]any{ "name": name, "kind": "ci", "scopes": scopes, "expires_at": time.Now().Add(30 * 24 * time.Hour).UTC().Format(time.RFC3339), }) if code != http.StatusCreated { t.Fatalf("create ci key: %d %s", code, plain) } return plain } func TestCILicence_issuedOncePerKeyDeviceAndDay(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { entitle(t, h, "firmwerk", true) key := ciKey(t, h, "fw-ci", "firmwerk:licence") code, first, body := postCI(t, h, key, "firmwerk", "runner-1") if code != http.StatusCreated { t.Fatalf("first: %d %s", code, body) } c := jwtClaims(t, first.Licence) if c["kind"] != "ci" || c["device"] != "ci:runner-1" || !strings.HasPrefix(c["sub"].(string), "apikey:") || c["heartbeat_url"] != nil { t.Fatalf("claims %v", c) } if exp := time.Unix(int64(c["exp"].(float64)), 0); exp.After(time.Now().Add(25 * time.Hour)) { t.Fatalf("CI licence lives too long: %v", exp) } code, again, _ := postCI(t, h, key, "firmwerk", "runner-1") if code != http.StatusOK || again.ID != first.ID { t.Fatalf("same key/device/day must reuse the licence: %d %s vs %s", code, again.ID, first.ID) } code, other, _ := postCI(t, h, key, "firmwerk", "runner-2") if code != http.StatusCreated || other.ID == first.ID { t.Fatalf("another device gets its own licence: %d", code) } }) } // A heartbeat never renews a CI licence (it would become a 30-day licence). func TestCILicence_heartbeatDoesNotRenew(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { entitle(t, h, "firmwerk", true) key := ciKey(t, h, "fw-ci", "firmwerk:licence") code, lic, body := postCI(t, h, key, "firmwerk", "runner") if code != http.StatusCreated { t.Fatalf("issue: %d %s", code, body) } h.app.Now = func() time.Time { return time.Now().Add(20 * time.Hour) } resp, hb := h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic.Licence}) if resp.StatusCode != http.StatusOK || strings.Contains(string(hb), "renewed") { t.Fatalf("heartbeat past half-life: %d %s", resp.StatusCode, hb) } }) } func TestCILicence_refusals(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { entitle(t, h, "firmwerk", true) entitle(t, h, "pruefwerk", true) _, _, legacy := createKey(t, h, map[string]any{"name": "legacy"}) wrong := ciKey(t, h, "pf-ci", "pruefwerk:scans.run") fw := ciKey(t, h, "fw-ci", "firmwerk:licence") cases := []struct { name, key, product string want int }{ {"no key", "", "firmwerk", http.StatusUnauthorized}, {"unknown key", "bp_unknownunknownunknownunknown00", "firmwerk", http.StatusUnauthorized}, {"legacy key without scope", legacy, "firmwerk", http.StatusForbidden}, {"key without licence scope", wrong, "firmwerk", http.StatusForbidden}, {"scope for another product", fw, "werkpilot", http.StatusForbidden}, } for _, tc := range cases { if code, _, body := postCI(t, h, tc.key, tc.product, "runner"); code != tc.want { t.Errorf("%s: %d, want %d (%s)", tc.name, code, tc.want, body) } } // The booking ends: the key no longer fetches licences. entitle(t, h, "firmwerk", false) if code, _, _ := postCI(t, h, fw, "firmwerk", "runner"); code != http.StatusForbidden { t.Errorf("after the booking ended: %d, want 403", code) } }) } func wpCall(t *testing.T, h *testHarness, key, device string) (int, licenceLLMOut) { t.Helper() buf, _ := json.Marshal(map[string]string{"product": "werkpilot", "device": device}) req, _ := http.NewRequest("POST", h.srv.URL+"/v1/licences/ci", bytes.NewReader(buf)) req.Header.Set("Authorization", "Bearer "+key) resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer func() { _ = resp.Body.Close() }() var out licenceLLMOut _ = json.NewDecoder(resp.Body).Decode(&out) return resp.StatusCode, out } func testBox(t *testing.T) *secretbox.Box { t.Helper() b, err := secretbox.New(base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))) if err != nil { t.Fatal(err) } return b } // Decision D2: a Werkpilot CI licence carries the tenant's LiteLLM key // (expiring in LiteLLM after a day). The reused licence hands out the same // key again from its sealed copy; another device gets its own key. func TestCILicence_werkpilotReusesSealedLLMKey(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { fake := newFakeLiteLLM(t) h.app.LLMKeys = fake.client() h.app.Secrets = testBox(t) entitle(t, h, "werkpilot", true) key := ciKey(t, h, "wp-ci", "werkpilot:licence") code, first := wpCall(t, h, key, "runner-1") if code != http.StatusCreated || !strings.HasPrefix(first.LLMAPIKey, "sk-fake-") || len(first.Warnings) != 0 { t.Fatalf("first: %d %+v", code, first) } code, again := wpCall(t, h, key, "runner-1") if code != http.StatusOK || again.ID != first.ID || again.LLMAPIKey != first.LLMAPIKey || again.LLMBaseURL == "" { t.Fatalf("reuse must return the same key: %d %+v", code, again) } code, other := wpCall(t, h, key, "runner-2") if code != http.StatusCreated || other.LLMAPIKey == "" || other.LLMAPIKey == first.LLMAPIKey { t.Fatalf("second device: %d %+v", code, other) } fake.mu.Lock() defer fake.mu.Unlock() if len(fake.gen) != 2 || fake.gen[0]["duration"] != "1d" { t.Fatalf("LiteLLM generate calls: %v", fake.gen) } }) } func TestCILicence_werkpilotWithoutEncryptionKey(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { fake := newFakeLiteLLM(t) h.app.LLMKeys = fake.client() entitle(t, h, "werkpilot", true) key := ciKey(t, h, "wp-ci", "werkpilot:licence") if code, first := wpCall(t, h, key, "runner"); code != http.StatusCreated || first.LLMAPIKey == "" { t.Fatalf("first: %d %+v", code, first) } code, again := wpCall(t, h, key, "runner") if code != http.StatusOK || again.LLMAPIKey != "" || len(again.Warnings) != 1 || again.Warnings[0] != "llm_key_not_repeatable" { t.Fatalf("reuse without SECRETS_ENCRYPTION_KEY: %d %+v", code, again) } }) } func TestCILicence_werkpilotDailyKeyCap(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { fake := newFakeLiteLLM(t) h.app.LLMKeys = fake.client() h.app.Secrets = testBox(t) entitle(t, h, "werkpilot", true) key := ciKey(t, h, "wp-ci", "werkpilot:licence") for i := 0; i < 10; i++ { if code, out := wpCall(t, h, key, "runner-"+string(rune('a'+i))); code != http.StatusCreated || out.LLMAPIKey == "" { t.Fatalf("device %d: %d %+v", i, code, out) } } code, out := wpCall(t, h, key, "runner-z") if code != http.StatusCreated || out.LLMAPIKey != "" || len(out.Warnings) != 1 || out.Warnings[0] != "llm_key_daily_cap" { t.Fatalf("11th device: %d %+v", code, out) } }) } func TestCILicence_recordsUsageNotSeat(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { entitle(t, h, "firmwerk", true) key := ciKey(t, h, "fw-ci", "firmwerk:licence") for _, d := range []string{"a", "b", "a"} { if code, _, body := postCI(t, h, key, "firmwerk", d); code >= 300 { t.Fatalf("%d %s", code, body) } } evs, err := h.store.ListUsageEvents(context.Background(), store.UsageFilter{TenantID: h.tenant.ID}) if err != nil { t.Fatal(err) } n := 0 for _, ev := range evs { if ev.Metric == "ci.licence" { n++ } if ev.Metric == "seat.login" { t.Error("a CI licence must not record a seat") } } if n != 1 { t.Fatalf("ci.licence events: %d, want 1 per key and day", n) } }) } func TestCILicence_rateLimitedPerKey(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { entitle(t, h, "firmwerk", true) key := ciKey(t, h, "fw-ci", "firmwerk:licence") for i := 0; i < 60; i++ { if code, _, body := postCI(t, h, key, "firmwerk", "runner"); code >= 300 { t.Fatalf("call %d: %d %s", i+1, code, body) } } if code, _, _ := postCI(t, h, key, "firmwerk", "runner"); code != http.StatusTooManyRequests { t.Fatalf("61st call: %d, want 429", code) } }) }