Files
tenant-registry/internal/server/licences.go
T
Sharang ParnerkarandClaude Opus 5.5 e37e2944e1
ci / shared (pull_request) Successful in 14s
ci / test (pull_request) Successful in 25m14s
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:34:42 +02:00

377 lines
14 KiB
Go

package server
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/licence"
"git.breakpilot.com/platform/tenant-registry/internal/llmkeys"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// ─── CLI licences (decision 13) ───────────────────────────────────────────
//
// `werkpilot login` / `firmwerk login` do the device flow on the realm
// (clients werkpilot-cli / firmwerk-cli, audience tenant-registry) and call
// POST /v1/licences with the user token; the tenant comes from the token's
// tenant-context claims. The CLI stores the JWT, verifies it offline against
// /.well-known/licence-keys.json and phones home hourly via the heartbeat.
type issueLicenceReq struct {
TenantID string `json:"tenant_id,omitempty"` // service callers only; users get their own tenant
Product string `json:"product"`
Device string `json:"device,omitempty"`
TTLDays int `json:"ttl_days,omitempty"`
}
type licenceResp struct {
ID string `json:"id"`
Licence string `json:"licence"`
Kid string `json:"kid"`
ExpiresAt time.Time `json:"expires_at"`
Grace licence.GracePolicy `json:"grace"`
Status string `json:"status"`
// D6: Werkpilot grants carry a per-tenant LiteLLM virtual key. The
// secret is returned in this response only — never persisted, never
// returned again. Absent (with a warning) when LiteLLM is off/down.
LLMAPIKey string `json:"llm_api_key,omitempty"`
LLMBaseURL string `json:"llm_base_url,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
// warnLLMKeyUnavailable — the licence was issued but LiteLLM did not hand
// out a key (disabled, unreachable or refused). The CLI keeps working; the
// operator sees the reason in the logs.
const warnLLMKeyUnavailable = "llm_key_unavailable"
// llmKeyProduct — the only product whose licences get a LiteLLM key today.
const llmKeyProduct = "werkpilot"
func (s *Server) licenceKeys(w http.ResponseWriter, _ *http.Request) {
if s.Licences == nil {
writeError(w, http.StatusServiceUnavailable, "licences_disabled", "licence signer not configured")
return
}
w.Header().Set("Cache-Control", "public, max-age=3600")
writeJSON(w, http.StatusOK, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{s.Licences.PublicJWK()}})
}
func (s *Server) issueLicence(w http.ResponseWriter, r *http.Request) {
if s.Licences == nil {
writeError(w, http.StatusServiceUnavailable, "licences_disabled", "licence signer not configured")
return
}
var in issueLicenceReq
if !decodeJSON(w, r, &in) {
return
}
p, _ := authn.PrincipalFrom(r.Context())
subject := "service:" + in.TenantID
if p != nil {
subject = p.Subject
if p.IsUser() {
in.TenantID = p.TenantID
}
}
if in.TenantID == "" || in.Product == "" {
writeError(w, http.StatusBadRequest, "invalid_input", "product is required (tenant_id for service callers)")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
resp, code, kind, msg := s.issue(ctx, r, in, subject, nil)
if code != http.StatusCreated {
writeError(w, code, kind, msg)
return
}
writeJSON(w, http.StatusCreated, resp)
}
// issue evaluates the entitlement, records the licence row, signs the JWT
// and — for Werkpilot — provisions the LiteLLM key. renewOf is the licence
// being renewed by a heartbeat (nil for a fresh issue): its LiteLLM key, if
// any, moves to the new row instead of a second key being generated (the
// secret cannot be re-read; the CLI keeps the one it stored).
func (s *Server) issue(ctx context.Context, r *http.Request, in issueLicenceReq, subject string, renewOf *store.Licence) (*licenceResp, int, string, string) {
check, err := s.evaluateEntitlement(ctx, entitlementCheckReq{TenantID: in.TenantID, Product: in.Product})
if err != nil {
return nil, http.StatusInternalServerError, "internal", err.Error()
}
if !check.Allowed {
return nil, http.StatusForbidden, "not_entitled", "tenant is not entitled to " + in.Product + " (" + check.Reason + ")"
}
t, err := s.Store.GetTenant(ctx, in.TenantID)
if err != nil {
return nil, http.StatusNotFound, "not_found", "tenant not found"
}
ttl := in.TTLDays
if ttl <= 0 {
ttl = s.cfg().LicenceTTLDays
}
if ttl <= 0 {
ttl = 30
}
now := s.now()
exp := now.Add(time.Duration(ttl) * 24 * time.Hour)
if check.ExpiresAt != nil && check.ExpiresAt.Before(exp) {
exp = check.ExpiresAt.UTC()
}
seats := 0
if v, ok := check.Limits["seats"]; ok {
seats = int(toFloat(v))
}
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 {
return nil, http.StatusInternalServerError, "internal", err.Error()
}
heartbeat := ""
if r != nil {
scheme := "https"
if r.TLS == nil && (r.Host == "" || isLoopback(r.Host)) {
scheme = "http"
}
heartbeat = scheme + "://" + r.Host + "/v1/licences/heartbeat"
}
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(exp)},
TenantID: t.ID, TenantSlug: t.Slug, Product: in.Product, Plan: t.Plan, Seats: seats, Device: in.Device,
Grace: licence.DefaultGrace, Heartbeat: heartbeat,
})
if err != nil {
return nil, http.StatusInternalServerError, "internal", err.Error()
}
out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: exp, Grace: licence.DefaultGrace, Status: "ok"}
llmKey := s.provisionLLMKey(ctx, t, row, renewOf, out, "")
s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "licence.issued", TargetID: row.ID, TargetType: "licence",
ActorID: subject, Product: in.Product, Metadata: map[string]interface{}{"device": in.Device, "expires_at": exp.Format(time.RFC3339), "llm_key": llmKey}})
return out, http.StatusCreated, "", ""
}
// provisionLLMKey fills the grant's LLM fields for a Werkpilot licence and
// returns what happened for the audit record: "issued" | "transferred" |
// "unavailable" | "" (not applicable). LiteLLM failures never fail the
// licence — the grant carries warnings: ["llm_key_unavailable"] instead.
// duration, when set, makes LiteLLM expire the key itself (CI licences).
func (s *Server) provisionLLMKey(ctx context.Context, t *store.Tenant, row *store.Licence, renewOf *store.Licence, out *licenceResp, duration string) string {
if row.Product != llmKeyProduct {
return ""
}
if renewOf != nil && renewOf.LLMKeyID != "" {
// Renewal: the device already holds the secret; move the handle so
// revoking the new licence (not the superseded one) deletes the key.
if err := s.Store.SetLicenceLLMKey(ctx, row.ID, renewOf.LLMKeyID); err != nil {
s.Log.Warn("llm key: transfer to renewed licence failed", "licence", row.ID, "from", renewOf.ID, "err", err)
out.Warnings = append(out.Warnings, warnLLMKeyUnavailable)
return "unavailable"
}
_ = s.Store.SetLicenceLLMKey(ctx, renewOf.ID, "")
row.LLMKeyID = renewOf.LLMKeyID
out.LLMBaseURL = s.LLMKeys.BaseURL()
return "transferred"
}
if !s.LLMKeys.Enabled() {
out.Warnings = append(out.Warnings, warnLLMKeyUnavailable)
return "unavailable"
}
trial := t.Status == store.StatusTrial
key, err := s.LLMKeys.Generate(ctx, llmkeys.GenerateRequest{
KeyAlias: llmKeyProduct + "-" + t.Slug + "-" + row.ID,
Models: s.LLMKeys.Models(),
MaxBudget: s.LLMKeys.Budget(trial),
BudgetDuration: s.LLMKeys.BudgetDuration(),
Metadata: map[string]any{"tenant_id": t.ID, "tenant_slug": t.Slug, "licence_id": row.ID, "product": llmKeyProduct, "plan": t.Plan, "tenant_status": t.Status},
Duration: duration,
})
if err != nil {
s.Log.Warn("llm key: generate failed; licence issued without key", "licence", row.ID, "tenant", t.ID, "err", err)
out.Warnings = append(out.Warnings, warnLLMKeyUnavailable)
return "unavailable"
}
if err := s.Store.SetLicenceLLMKey(ctx, row.ID, key.TokenID); err != nil {
// Never hand out a key we cannot revoke later: best-effort delete.
s.Log.Error("llm key: persisting key id failed; deleting key", "licence", row.ID, "err", err)
if derr := s.LLMKeys.Delete(ctx, key.TokenID); derr != nil {
s.Log.Error("llm key: orphaned LiteLLM key", "licence", row.ID, "key_id", key.TokenID, "err", derr)
}
out.Warnings = append(out.Warnings, warnLLMKeyUnavailable)
return "unavailable"
}
row.LLMKeyID = key.TokenID
out.LLMAPIKey = key.Key
out.LLMBaseURL = s.LLMKeys.BaseURL()
return "issued"
}
// deleteLLMKey removes the licence's LiteLLM key (revoke path); 404 from
// LiteLLM is fine, other failures are logged — the licence is revoked
// regardless and the key id stays on the row for a manual retry.
func (s *Server) deleteLLMKey(ctx context.Context, row *store.Licence) bool {
if row.LLMKeyID == "" {
return false
}
if !s.LLMKeys.Enabled() {
s.Log.Warn("llm key: LiteLLM disabled, key not deleted", "licence", row.ID, "key_id", row.LLMKeyID)
return false
}
if err := s.LLMKeys.Delete(ctx, row.LLMKeyID); err != nil {
s.Log.Error("llm key: delete failed", "licence", row.ID, "key_id", row.LLMKeyID, "err", err)
return false
}
return true
}
type heartbeatReq struct {
Licence string `json:"licence"`
}
type heartbeatResp struct {
Status string `json:"status"` // ok | warning | degraded | hard_stop | revoked
TenantStatus string `json:"tenant_status,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
Reason string `json:"reason,omitempty"`
Renewed *licenceResp `json:"renewed,omitempty"`
}
// licenceHeartbeat — POST /v1/licences/heartbeat (PUBLIC_EXPLICIT; the JWT
// is the credential). Reports the grace state, records last_seen and hands
// out a fresh token when the current one is past half-life and the tenant
// is still entitled.
func (s *Server) licenceHeartbeat(w http.ResponseWriter, r *http.Request) {
if s.Licences == nil {
writeError(w, http.StatusServiceUnavailable, "licences_disabled", "licence signer not configured")
return
}
var in heartbeatReq
if !decodeJSON(w, r, &in) {
return
}
claims, err := s.Licences.Verify(in.Licence)
if err != nil {
writeError(w, http.StatusUnauthorized, "invalid_licence", "licence signature or issuer invalid")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
row, err := s.Store.GetLicence(ctx, claims.ID)
if err != nil {
writeError(w, http.StatusUnauthorized, "unknown_licence", "licence is not on record")
return
}
now := s.now()
_ = s.Store.TouchLicence(ctx, row.ID, now)
out := heartbeatResp{ExpiresAt: row.ExpiresAt}
if row.RevokedAt != nil {
out.Status, out.Reason = "revoked", "licence_revoked"
writeJSON(w, http.StatusOK, out)
return
}
t, err := s.Store.GetTenant(ctx, row.TenantID)
if err != nil {
out.Status, out.Reason = "hard_stop", "tenant_not_found"
writeJSON(w, http.StatusOK, out)
return
}
out.TenantStatus = t.Status
check, err := s.evaluateEntitlement(ctx, entitlementCheckReq{TenantID: t.ID, Product: row.Product})
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
grace := claims.Grace
if grace == (licence.GracePolicy{}) {
grace = licence.DefaultGrace
}
switch {
case !check.Allowed:
// Not entitled any more (halted / archived / cancelled): the token
// keeps working through its own grace ladder, no renewal.
out.Status, out.Reason = grace.State(row.ExpiresAt, now), check.Reason
if out.Status == "ok" {
out.Status = "warning"
}
case check.ReadOnly:
out.Status, out.Reason = "degraded", "tenant_"+t.Status
case t.Status == store.StatusWarning:
out.Status, out.Reason = "warning", "tenant_warning"
default:
out.Status = grace.State(row.ExpiresAt, now)
}
// Renewal: entitled, not read-only, past half-life (or expired). CI
// licences (fetched with an API key, subject "apikey:<id>") are never
// renewed here: they live 24 h and the job fetches a new one.
if check.Allowed && !check.ReadOnly && !strings.HasPrefix(row.Subject, "apikey:") {
half := row.CreatedAt.Add(row.ExpiresAt.Sub(row.CreatedAt) / 2)
if now.After(half) {
renewed, code, _, _ := s.issue(ctx, r, issueLicenceReq{TenantID: t.ID, Product: row.Product, Device: row.Device}, row.Subject, row)
if code == http.StatusCreated {
out.Renewed = renewed
out.Status = "ok"
out.Reason = "renewed"
}
}
}
writeJSON(w, http.StatusOK, out)
}
func (s *Server) listLicences(w http.ResponseWriter, r *http.Request) {
tenantID := r.URL.Query().Get("tenant_id")
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() {
tenantID = p.TenantID
}
if tenantID == "" {
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
list, err := s.Store.ListLicences(ctx, tenantID)
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"items": list})
}
func (s *Server) revokeLicence(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
row, err := s.Store.GetLicence(ctx, r.PathValue("id"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && p.TenantID != row.TenantID {
writeError(w, http.StatusNotFound, "not_found", "licence not found")
return
}
if err := s.Store.RevokeLicence(ctx, row.ID, s.now()); err != nil && !errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
keyDeleted := s.deleteLLMKey(ctx, row)
s.emitAudit(ctx, r, store.AuditEvent{TenantID: row.TenantID, Action: "licence.revoked", TargetID: row.ID, TargetType: "licence", Product: row.Product,
Metadata: map[string]interface{}{"llm_key_deleted": keyDeleted}})
row, _ = s.Store.GetLicence(ctx, row.ID)
writeJSON(w, http.StatusOK, row)
}
func isLoopback(host string) bool {
return len(host) >= 9 && (host[:9] == "127.0.0.1" || host[:9] == "localhost")
}