Files
tenant-registry/internal/server/licences_llm_test.go
sharangandClaude Opus 5 13da983d1e
ci / shared (push) Successful in 14s
ci / test (push) Successful in 22m20s
ci / image (push) Successful in 26s
feat(llmkeys): allow Qwen3.8-27B on tenant LiteLLM keys (#31)
Add Qwen3.8-27B to the default LITELLM_MODELS allowlist for per-tenant LiteLLM keys. Existing keys are updated separately via LiteLLM /key/update.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FKb71CELE4iptE9em1ZEgv
2026-09-18 18:51:28 +00:00

242 lines
8.7 KiB
Go

package server_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/llmkeys"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// fakeLiteLLM — records /key/generate and /key/delete calls. Never the live
// admin API: this is the whole contract the registry relies on.
type fakeLiteLLM struct {
mu sync.Mutex
srv *httptest.Server
gen []map[string]any
deleted []string
auth []string
fail int // when non-zero, every call answers with this status
n int
}
func newFakeLiteLLM(t *testing.T) *fakeLiteLLM {
t.Helper()
f := &fakeLiteLLM{}
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
f.auth = append(f.auth, r.Header.Get("Authorization"))
if f.fail != 0 {
w.WriteHeader(f.fail)
_, _ = w.Write([]byte(`{"error":"boom"}`))
return
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
switch r.URL.Path {
case "/key/generate":
f.n++
f.gen = append(f.gen, body)
_ = json.NewEncoder(w).Encode(map[string]any{
"key": "sk-fake-" + strings.Repeat("x", f.n), "token": "hash-" + body["key_alias"].(string), "key_alias": body["key_alias"],
})
case "/key/delete":
for _, k := range body["keys"].([]any) {
f.deleted = append(f.deleted, k.(string))
}
_ = json.NewEncoder(w).Encode(map[string]any{"deleted_keys": body["keys"]})
default:
w.WriteHeader(404)
}
}))
t.Cleanup(f.srv.Close)
return f
}
func (f *fakeLiteLLM) client() *llmkeys.Client {
return llmkeys.New(llmkeys.Config{BaseURL: f.srv.URL, MasterKey: "sk-master-test"})
}
type licenceLLMOut struct {
licenceOut
LLMAPIKey string `json:"llm_api_key"`
LLMBaseURL string `json:"llm_base_url"`
Warnings []string `json:"warnings"`
}
func listLicences(t *testing.T, h *testHarness, tenantID string) []store.Licence {
t.Helper()
_, raw := h.do("GET", "/v1/licences?tenant_id="+tenantID, nil)
return decode[struct {
Items []store.Licence `json:"items"`
}](t, raw).Items
}
func TestLicences_llmKey_issueRenewRevoke(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
fake := newFakeLiteLLM(t)
h.app.LLMKeys = fake.client()
tn := newTenant(t, h, "llm-co")
h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "werkpilot"})
// issue → key present, request shape
resp, raw := h.do("POST", "/v1/licences", map[string]any{"tenant_id": tn.ID, "product": "werkpilot", "device": "laptop-1"})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("issue: %d %s", resp.StatusCode, raw)
}
lic := decode[licenceLLMOut](t, raw)
if lic.LLMAPIKey != "sk-fake-x" || lic.LLMBaseURL != fake.srv.URL || len(lic.Warnings) != 0 {
t.Fatalf("grant: %+v", lic)
}
if strings.Contains(string(raw), "llm_key_id") {
t.Fatalf("issue response must not carry the key id: %s", raw)
}
if len(fake.gen) != 1 || fake.auth[0] != "Bearer sk-master-test" {
t.Fatalf("generate calls: %d auth=%v", len(fake.gen), fake.auth)
}
g := fake.gen[0]
if g["key_alias"] != "werkpilot-llm-co-"+lic.ID || g["max_budget"] != 5.0 || g["budget_duration"] != "30d" {
t.Fatalf("generate body: %+v", g)
}
if models, _ := g["models"].([]any); len(models) != 3 || models[0] != "Qwen3-Coder-30B-A3B-Instruct" || models[1] != "gpt-oss-120b" || models[2] != "Qwen3.8-27B" {
t.Fatalf("models: %v", g["models"])
}
md, _ := g["metadata"].(map[string]any)
if md["tenant_id"] != tn.ID || md["tenant_slug"] != "llm-co" || md["licence_id"] != lic.ID || md["product"] != "werkpilot" {
t.Fatalf("metadata: %+v", md)
}
// the row carries the hashed id, not the secret
list := listLicences(t, h, tn.ID)
if len(list) != 1 || list[0].LLMKeyID != "hash-werkpilot-llm-co-"+lic.ID {
t.Fatalf("list: %+v", list)
}
if strings.Contains(string(raw), "hash-") {
t.Fatalf("grant leaks key id: %s", raw)
}
// active tenant → default budget
if resp, raw := h.do("POST", "/v1/tenants/"+tn.ID+"/activate", map[string]any{}); resp.StatusCode != 200 {
t.Fatalf("activate: %d %s", resp.StatusCode, raw)
}
resp, raw = h.do("POST", "/v1/licences", map[string]any{"tenant_id": tn.ID, "product": "werkpilot", "device": "laptop-2"})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("issue active: %d %s", resp.StatusCode, raw)
}
lic2 := decode[licenceLLMOut](t, raw)
if lic2.LLMAPIKey != "sk-fake-xx" || fake.gen[1]["max_budget"] != 50.0 {
t.Fatalf("active budget: %+v %+v", lic2, fake.gen[1])
}
// heartbeat renewal past half-life: key handle moves, no new key,
// no secret in the renewed grant
h.app.Now = func() time.Time { return time.Now().Add(20 * 24 * time.Hour) }
_, raw = h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic2.Licence})
h.app.Now = nil
hb := decode[struct {
Status string `json:"status"`
Renewed *licenceLLMOut `json:"renewed"`
}](t, raw)
if hb.Status != "ok" || hb.Renewed == nil {
t.Fatalf("renewal: %s", raw)
}
if hb.Renewed.LLMAPIKey != "" || hb.Renewed.LLMBaseURL != fake.srv.URL || len(hb.Renewed.Warnings) != 0 || len(fake.gen) != 2 {
t.Fatalf("renewed grant: %+v gen=%d", hb.Renewed, len(fake.gen))
}
byID := map[string]store.Licence{}
for _, l := range listLicences(t, h, tn.ID) {
byID[l.ID] = l
}
if byID[lic2.ID].LLMKeyID != "" || byID[hb.Renewed.ID].LLMKeyID != "hash-werkpilot-llm-co-"+lic2.ID {
t.Fatalf("transfer: old=%q new=%q", byID[lic2.ID].LLMKeyID, byID[hb.Renewed.ID].LLMKeyID)
}
// revoke the superseded licence → nothing to delete; revoke the
// renewed one → its (transferred) key is deleted
if resp, _ := h.do("POST", "/v1/licences/"+lic2.ID+"/revoke", nil); resp.StatusCode != 200 || len(fake.deleted) != 0 {
t.Fatalf("revoke superseded: %d deleted=%v", resp.StatusCode, fake.deleted)
}
if resp, _ := h.do("POST", "/v1/licences/"+hb.Renewed.ID+"/revoke", nil); resp.StatusCode != 200 || len(fake.deleted) != 1 || fake.deleted[0] != "hash-werkpilot-llm-co-"+lic2.ID {
t.Fatalf("revoke renewed: %d deleted=%v", resp.StatusCode, fake.deleted)
}
// revoke the first licence with LiteLLM failing → still revoked
fake.fail = 500
resp, raw = h.do("POST", "/v1/licences/"+lic.ID+"/revoke", nil)
if resp.StatusCode != 200 || !strings.Contains(string(raw), "revoked_at") || len(fake.deleted) != 1 {
t.Fatalf("revoke with litellm down: %d %s deleted=%v", resp.StatusCode, raw, fake.deleted)
}
fake.fail = 0
// firmwerk licences get no key and no LiteLLM call
h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "firmwerk"})
resp, raw = h.do("POST", "/v1/licences", map[string]any{"tenant_id": tn.ID, "product": "firmwerk", "device": "laptop-1"})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("firmwerk: %d %s", resp.StatusCode, raw)
}
if fw := decode[licenceLLMOut](t, raw); fw.LLMAPIKey != "" || fw.LLMBaseURL != "" || len(fw.Warnings) != 0 || len(fake.gen) != 2 {
t.Fatalf("firmwerk grant: %+v gen=%d", fw, len(fake.gen))
}
// status endpoint reports the feature
_, raw = h.do("GET", "/v1/internal/erp/status", nil)
if !strings.Contains(string(raw), `"llm_keys_enabled":true`) {
t.Fatalf("status: %s", raw)
}
})
}
func TestLicences_llmKey_unavailable(t *testing.T) {
h := newMemoryHarness(t)
defer h.Close()
tn := newTenant(t, h, "llm-down")
h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "werkpilot"})
issue := func() licenceLLMOut {
t.Helper()
resp, raw := h.do("POST", "/v1/licences", map[string]any{"tenant_id": tn.ID, "product": "werkpilot", "device": "d"})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("issue: %d %s", resp.StatusCode, raw)
}
return decode[licenceLLMOut](t, raw)
}
wantWarn := func(lic licenceLLMOut, why string) {
t.Helper()
if lic.Licence == "" || lic.LLMAPIKey != "" || lic.LLMBaseURL != "" || len(lic.Warnings) != 1 || lic.Warnings[0] != "llm_key_unavailable" {
t.Fatalf("%s: %+v", why, lic)
}
}
// feature off (no client / no master key)
h.app.LLMKeys = nil
wantWarn(issue(), "nil client")
h.app.LLMKeys = llmkeys.New(llmkeys.Config{})
wantWarn(issue(), "no master key")
_, raw := h.do("GET", "/v1/internal/erp/status", nil)
if !strings.Contains(string(raw), `"llm_keys_enabled":false`) {
t.Fatalf("status: %s", raw)
}
// LiteLLM answers 5xx
fake := newFakeLiteLLM(t)
fake.fail = 503
h.app.LLMKeys = fake.client()
wantWarn(issue(), "5xx")
// LiteLLM refuses (4xx)
fake.fail = 401
wantWarn(issue(), "401")
// LiteLLM unreachable
fake.srv.Close()
wantWarn(issue(), "connection refused")
for _, l := range listLicences(t, h, tn.ID) {
if l.LLMKeyID != "" {
t.Fatalf("no key id expected: %+v", l)
}
}
}