package server import ( "context" "errors" "net/http" "slices" "strings" "sync" "time" "github.com/go-jose/go-jose/v4/jwt" "git.breakpilot.com/platform/tenant-registry/internal/licence" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // ─── CI licences (ADR 0001 §5, firmwerk#64) ─────────────────────────────── // // A CI job has no browser for the device flow, so the CLI sends a tenant API // key (BP_LICENCE_API_KEY) to POST /v1/licences/ci instead. The key needs the // scope ":licence"; the tenant comes from the key. The licence lives // 24 h, carries kind "ci", has no heartbeat and is not a seat (decision D1). // It is reused per (key, device, UTC day) so a busy pipeline does not add a // row per job. A Werkpilot licence carries the tenant's LiteLLM key // (decision D2), generated with the licence and expiring in LiteLLM after a // day; the secret is stored sealed (SECRETS_ENCRYPTION_KEY, migration 0017) // so the reused licence hands out the same key again. At most // ciLLMKeysPerDay keys per API key and day (distinct devices) bound the cost. const ( ciLicenceTTL = 24 * time.Hour ciLicenceRate = 60 // issues per key and hour ciDevicePrefix = "ci:" maxDeviceLen = 200 ciLLMKeyExpiry = "1d" // LiteLLM duration, matches ciLicenceTTL ciLLMKeysPerDay = 10 // LiteLLM keys per API key and UTC day // warnLLMKeyNotRepeatable — the reused licence has a LiteLLM key but its // secret was not stored (no SECRETS_ENCRYPTION_KEY) or cannot be opened. warnLLMKeyNotRepeatable = "llm_key_not_repeatable" // warnLLMKeyDailyCap — this API key reached ciLLMKeysPerDay today. warnLLMKeyDailyCap = "llm_key_daily_cap" ) type ciLicenceReq struct { Product string `json:"product"` Device string `json:"device"` } // issueCILicence — POST /v1/licences/ci. PUBLIC_EXPLICIT at the router: the // bearer is a registry API key, checked here, not a Keycloak token. func (s *Server) issueCILicence(w http.ResponseWriter, r *http.Request) { if s.Licences == nil { writeError(w, http.StatusServiceUnavailable, "licences_disabled", "licence signer not configured") return } plain, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !ok || !looksLikeKey(plain) { writeError(w, http.StatusUnauthorized, "API_KEY_MISSING", "Authorization: Bearer bp_… required") return } var in ciLicenceReq if !decodeJSON(w, r, &in) { return } in.Device = strings.TrimSpace(in.Device) if in.Product == "" || in.Device == "" || len(in.Device) > maxDeviceLen { writeError(w, http.StatusBadRequest, "invalid_input", "product and device (≤ 200 chars) are required") return } if !strings.HasPrefix(in.Device, ciDevicePrefix) { in.Device = ciDevicePrefix + in.Device } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() k, err := s.findAPIKey(ctx, plain) if errors.Is(err, store.ErrNotFound) { writeError(w, http.StatusUnauthorized, "API_KEY_INVALID", "unknown or revoked API key") return } if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } now := s.now() if k.ExpiresAt != nil && !k.ExpiresAt.After(now) { writeError(w, http.StatusUnauthorized, "API_KEY_INVALID", "API key expired") return } entitled, _, err := s.entitledProducts(ctx, k.TenantID) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } need := in.Product + ":licence" if !entitled[in.Product] || !slices.Contains(k.Scopes, need) { writeError(w, http.StatusForbidden, "scope_missing", "the key needs scope "+need+" and the tenant a booking of "+in.Product) return } if !s.ciLimiter.allow(k.ID, now) { writeError(w, http.StatusTooManyRequests, "rate_limited", "at most 60 CI licences per key and hour") return } subject := "apikey:" + k.ID day := now.Truncate(24 * time.Hour) row, err := s.Store.FindReusableLicence(ctx, k.TenantID, in.Product, subject, in.Device, day, now) reused := err == nil if err != nil && !errors.Is(err, store.ErrNotFound) { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } check, err := s.evaluateEntitlement(ctx, entitlementCheckReq{TenantID: k.TenantID, Product: in.Product}) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } if !check.Allowed { writeError(w, http.StatusForbidden, "not_entitled", "tenant is not entitled to "+in.Product+" ("+check.Reason+")") return } t, err := s.Store.GetTenant(ctx, k.TenantID) if err != nil { writeError(w, http.StatusNotFound, "not_found", "tenant not found") return } if !reused { exp := now.Add(ciLicenceTTL) if check.ExpiresAt != nil && check.ExpiresAt.Before(exp) { exp = check.ExpiresAt.UTC() } row, err = s.Store.CreateLicence(ctx, store.Licence{ Kid: s.Licences.KID(), TenantID: t.ID, Product: in.Product, Subject: subject, Device: in.Device, ExpiresAt: exp, }) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } } seats := 0 if v, ok := check.Limits["seats"]; ok { seats = int(toFloat(v)) } token, err := s.Licences.Issue(licence.Claims{ Claims: jwt.Claims{Subject: subject, ID: row.ID, Audience: jwt.Audience{in.Product}, IssuedAt: jwt.NewNumericDate(now), Expiry: jwt.NewNumericDate(row.ExpiresAt)}, TenantID: t.ID, TenantSlug: t.Slug, Product: in.Product, Plan: t.Plan, Seats: seats, Device: in.Device, Grace: licence.DefaultGrace, Kind: "ci", }) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: row.ExpiresAt, Grace: licence.DefaultGrace, Status: "ok"} if in.Product == llmKeyProduct { if err := s.ciLLMKey(ctx, t, row, subject, day, out); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } } if !reused { s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "licence.issued", TargetID: row.ID, TargetType: "licence", ActorID: subject, ActorType: "apikey", Product: in.Product, Metadata: map[string]interface{}{"device": in.Device, "expires_at": row.ExpiresAt.Format(time.RFC3339), "kind": "ci", "api_key_id": k.ID, "llm_key": out.LLMAPIKey != ""}}) // Decision D1: CI is metered, not a seat — one ci.licence event per // key and day (the CLI cannot report it: it holds no user session). if _, _, err := s.Store.InsertUsageEvent(ctx, store.UsageEvent{ IdempotencyKey: "ci.licence:" + k.ID + ":" + day.Format("2006-01-02"), TenantID: t.ID, Product: in.Product, Metric: "ci.licence", Quantity: 1, OccurredAt: now, Properties: map[string]interface{}{"api_key_id": k.ID}, }); err != nil { s.Log.Warn("ci.licence usage event failed", "tenant", t.ID, "err", err) } } if err := s.Store.TouchAPIKeyUsed(ctx, k.ID); err != nil { s.Log.Warn("touch api_key failed", "err", err) } code := http.StatusCreated if reused { code = http.StatusOK } writeJSON(w, code, out) } // keyRateLimiter is a per-key sliding window over one hour. The zero value // is ready to use; state is per process (the registry runs one replica). type keyRateLimiter struct { mu sync.Mutex hits map[string][]time.Time } func (l *keyRateLimiter) allow(key string, now time.Time) bool { l.mu.Lock() defer l.mu.Unlock() if l.hits == nil { l.hits = map[string][]time.Time{} } cutoff := now.Add(-time.Hour) kept := l.hits[key][:0] for _, t := range l.hits[key] { if t.After(cutoff) { kept = append(kept, t) } } if len(kept) >= ciLicenceRate { l.hits[key] = kept return false } l.hits[key] = append(kept, now) return true } // ciLLMKey fills the grant's LiteLLM fields of a Werkpilot CI licence: the // stored key of a reused licence, else a new one (within the daily cap), // which is then sealed onto the row for reuse. func (s *Server) ciLLMKey(ctx context.Context, t *store.Tenant, row *store.Licence, subject string, day time.Time, out *licenceResp) error { if row.LLMKeyID != "" { if len(row.LLMKeySecret) > 0 && s.Secrets.Enabled() && s.LLMKeys.Enabled() { plain, err := s.Secrets.Open(row.LLMKeySecret, []byte(row.ID)) if err == nil { out.LLMAPIKey, out.LLMBaseURL = string(plain), s.LLMKeys.BaseURL() return nil } s.Log.Warn("ci llm key: stored secret cannot be opened", "licence", row.ID, "err", err) } out.Warnings = append(out.Warnings, warnLLMKeyNotRepeatable) return nil } n, err := s.ciLLMKeysToday(ctx, t.ID, subject, day) if err != nil { return err } if n >= ciLLMKeysPerDay { out.Warnings = append(out.Warnings, warnLLMKeyDailyCap) return nil } if s.provisionLLMKey(ctx, t, row, nil, out, ciLLMKeyExpiry) != "issued" || !s.Secrets.Enabled() { return nil } sealed, err := s.Secrets.Seal([]byte(out.LLMAPIKey), []byte(row.ID)) if err == nil { err = s.Store.SetLicenceLLMSecret(ctx, row.ID, sealed) } if err != nil { // The licence still works; only a reuse today comes without the key. s.Log.Warn("ci llm key: storing the sealed secret failed", "licence", row.ID, "err", err) } return nil } // ciLLMKeysToday counts the CI licences of this API key (subject) that got a // LiteLLM key today. func (s *Server) ciLLMKeysToday(ctx context.Context, tenantID, subject string, day time.Time) (int, error) { ls, err := s.Store.ListLicences(ctx, tenantID) if err != nil { return 0, err } n := 0 for _, l := range ls { if l.Subject == subject && l.LLMKeyID != "" && !l.CreatedAt.Before(day) { n++ } } return n, nil }