Demonstration plan, phase D6 (registry side). A prospect trialling Werkpilot had no model access until someone created a LiteLLM key by hand. The registry issues one with the licence, scoped and budgeted per tenant. **On issue** (`product=werkpilot`): `POST /key/generate` on LiteLLM with `key_alias = werkpilot-<slug>-<licence id>`, `metadata` carrying tenant id/slug/licence/product, the model list and the plan's budget (trial and default, USD per 30 days). LiteLLM's hashed token id goes on the `licences` row (migration `0007`, exposed as `llm_key_id` on `GET /v1/licences`); the `sk-…` secret is returned in that one response as `llm_api_key`, together with `llm_base_url`, and is never stored or returned again. **On renewal** (licence heartbeat): the existing key moves to the new licence row rather than a second key being generated — the secret cannot be re-read, and the CLI still holds the one it stored. **On revoke:** the key is deleted; a 404 from LiteLLM is treated as already gone. If the delete fails, the licence is still revoked and the key id stays on the row so it can be retried by hand. **Failure is never fatal:** with `LITELLM_MASTER_KEY` unset, LiteLLM unreachable or refusing, the licence is issued anyway and the grant carries `warnings: ["llm_key_unavailable"]` with no LLM fields. Also, a key that cannot be persisted is deleted again rather than handed out un-revocable. Config: `LITELLM_BASE_URL` (default `https://llm.breakpilot.com`), `LITELLM_MASTER_KEY`, `LITELLM_MODELS` (default `Qwen3-Coder-30B-A3B-Instruct,gpt-oss-120b`), `LITELLM_BUDGET_TRIAL` (5), `LITELLM_BUDGET_DEFAULT` (50). Startup logs whether provisioning is on. Note the migration is numbered `0007`: `0006` is taken by the members PR (#28), which is independent of this one — merge order does not matter. Verified locally: `go vet ./...`, `gofmt` clean, `go test ./...` green, CI coverage command at **74.4%** (gate 70%). `internal/llmkeys` is tested against an httptest fake; no live LiteLLM call was made. Pairs with a `bp-licence` bump (the Rust `Grant` gains the optional fields) and with `LITELLM_MASTER_KEY` on `tenant-registry-stage`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Reviewed-on: #29
189 lines
7.7 KiB
Go
189 lines
7.7 KiB
Go
// Package server wires the HTTP surface for tenant-registry.
|
|
//
|
|
// All routes are registered in NewRouter; per-concern handlers live in
|
|
// peer files (tenants.go, catalog.go, apikeys.go, audit.go, keycloak.go).
|
|
package server
|
|
|
|
import (
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/config"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/erp"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/licence"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/llmkeys"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/product"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// Server bundles the dependencies every handler needs.
|
|
type Server struct {
|
|
Cfg *config.Config
|
|
Log *slog.Logger
|
|
Store store.Store
|
|
Keycloak keycloak.Adapter // never nil — main wires Mock when KC env is unset
|
|
Auth *authn.Verifier // nil ⇒ AUTH_ENABLED=false, API is open (dev only)
|
|
Authz *Authz // nil ⇒ AUTHZ_RULES unset, every client may call every route
|
|
Product product.Provisioner // never nil — main wires Noop when PRODUCT_API_URL is unset
|
|
|
|
// M-MIG-7
|
|
ERP *erp.Client // nil / disabled ⇒ outbox accumulates, reconcile idle
|
|
Licences *licence.Signer // nil ⇒ licence endpoints return 503
|
|
LLMKeys *llmkeys.Client // nil / disabled ⇒ Werkpilot grants carry no LiteLLM key (D6)
|
|
Now func() time.Time // injectable clock (tests); nil ⇒ time.Now
|
|
}
|
|
|
|
func (s *Server) now() time.Time {
|
|
if s.Now != nil {
|
|
return s.Now().UTC()
|
|
}
|
|
return time.Now().UTC()
|
|
}
|
|
|
|
func (s *Server) cfg() *config.Config {
|
|
if s.Cfg == nil {
|
|
return &config.Config{}
|
|
}
|
|
return s.Cfg
|
|
}
|
|
|
|
// productProvisioner guarantees the "never nil" invariant the struct documents.
|
|
// Tests construct Server directly and would otherwise panic; an unset provisioner
|
|
// simply means no downstream provisioning, never a crash mid-tenant-creation.
|
|
func (s *Server) productProvisioner() product.Provisioner {
|
|
if s.Product == nil {
|
|
return product.NoopProvisioner{}
|
|
}
|
|
return s.Product
|
|
}
|
|
|
|
// NewRouter builds the http.Handler with logging middleware applied.
|
|
//
|
|
// Route auth classes (ratified auth design): /healthz and /readyz are
|
|
// PUBLIC_EXPLICIT (orca probes, no auth by design); every other route is
|
|
// INTERNAL_SERVICE_ONLY and sits behind requireAuth. New routes land in
|
|
// the protected mux by construction — registering one on the root mux is
|
|
// the exception and needs a PUBLIC_EXPLICIT justification comment.
|
|
func NewRouter(s *Server) http.Handler {
|
|
root := http.NewServeMux()
|
|
|
|
// PUBLIC_EXPLICIT: health + status probes.
|
|
root.HandleFunc("GET /healthz", s.healthz)
|
|
root.HandleFunc("GET /readyz", s.readyz)
|
|
// PUBLIC_EXPLICIT: ERPNext webhooks carry no Keycloak token — the body
|
|
// is HMAC-signed with ERP_WEBHOOK_SECRET (receiver refuses without it).
|
|
root.HandleFunc("POST /v1/internal/erp/webhook", s.erpWebhook)
|
|
// PUBLIC_EXPLICIT: licence verification keys + heartbeat. The heartbeat
|
|
// is authenticated by the licence JWT it carries (offline CLIs hold no
|
|
// Keycloak session).
|
|
root.HandleFunc("GET /.well-known/licence-keys.json", s.licenceKeys)
|
|
root.HandleFunc("POST /v1/licences/heartbeat", s.licenceHeartbeat)
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
// tenants
|
|
mux.HandleFunc("POST /v1/tenants", s.createTenant)
|
|
mux.HandleFunc("GET /v1/tenants", s.listTenants)
|
|
mux.HandleFunc("GET /v1/tenants/{id}", s.getTenant)
|
|
mux.HandleFunc("GET /v1/tenants/by-slug/{slug}", s.getTenantBySlug)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/activate", s.activateTenant)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/cancel", s.cancelTenant)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/status", s.setTenantStatus)
|
|
// tenant members (D1) — portal Settings/Users. Route groups:
|
|
// GET members = tenants.read, POST invites = tenants.write.
|
|
//
|
|
// The GET is registered as a wildcard sub-resource, not as
|
|
// "GET /v1/tenants/{id}/members": ServeMux rejects that one as conflicting
|
|
// with "GET /v1/tenants/by-slug/{slug}", because both match
|
|
// "/v1/tenants/by-slug/members" and neither is the more specific pattern.
|
|
// "/v1/tenants/{id}/{sub}" *is* less specific than the by-slug lookup, so
|
|
// the two coexist and the lookup keeps winning for its own prefix.
|
|
mux.HandleFunc("GET /v1/tenants/{id}/{sub}", s.tenantSubresource)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/invites", s.inviteTenantMember)
|
|
|
|
// entitlements
|
|
mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts)
|
|
mux.HandleFunc("POST /v1/internal/entitlements/check", s.checkEntitlement)
|
|
|
|
// catalog
|
|
mux.HandleFunc("GET /v1/catalog", s.getCatalog)
|
|
mux.HandleFunc("POST /v1/catalog/request", s.catalogRequest)
|
|
mux.HandleFunc("POST /v1/catalog/trial-request", s.catalogTrialRequest)
|
|
|
|
// api keys
|
|
mux.HandleFunc("POST /v1/api-keys", s.createAPIKey)
|
|
mux.HandleFunc("GET /v1/api-keys", s.listAPIKeys)
|
|
mux.HandleFunc("DELETE /v1/api-keys/{id}", s.revokeAPIKey)
|
|
mux.HandleFunc("POST /v1/internal/api-keys/verify", s.verifyAPIKey)
|
|
|
|
// audit
|
|
mux.HandleFunc("POST /v1/audit", s.appendAudit)
|
|
mux.HandleFunc("GET /v1/audit", s.listAudit)
|
|
|
|
// usage (§9.2) + subscriptions + ERP ops + licences (M-MIG-7)
|
|
mux.HandleFunc("POST /v1/usage/events", s.postUsageEvents)
|
|
mux.HandleFunc("GET /v1/usage/events", s.listUsageEvents)
|
|
mux.HandleFunc("GET /v1/subscriptions", s.listSubscriptions)
|
|
mux.HandleFunc("GET /v1/internal/erp/status", s.erpStatus)
|
|
mux.HandleFunc("POST /v1/internal/erp/reconcile", s.erpReconcileNow)
|
|
mux.HandleFunc("POST /v1/licences", s.issueLicence)
|
|
mux.HandleFunc("GET /v1/licences", s.listLicences)
|
|
mux.HandleFunc("POST /v1/licences/{id}/revoke", s.revokeLicence)
|
|
|
|
// keycloak claims refresh — the URL the protocol mapper would call at
|
|
// token issuance to grab the up-to-date entitlement bundle. Today the
|
|
// dev realm projects user attributes (set by SyncClaims) — this is
|
|
// the "pull" complement for when the realm is reconfigured to fetch.
|
|
mux.HandleFunc("POST /v1/internal/keycloak/claims", s.kcClaims)
|
|
|
|
// memberships — the B2 membership authority: which tenants does a
|
|
// JWT subject belong to, with which org_roles and entitlements.
|
|
mux.HandleFunc("GET /v1/users/{id}/memberships", s.getUserMemberships)
|
|
|
|
root.Handle("/", s.requireAuth(s.requireAuthz(mux)))
|
|
return logRequest(s.Log)(root)
|
|
}
|
|
|
|
// requireAuth gates the INTERNAL_SERVICE_ONLY routes. With Auth nil
|
|
// (AUTH_ENABLED=false) it passes through — the startup log carries the
|
|
// warning, and the Auth-5 activation flips the env, not the code.
|
|
func (s *Server) requireAuth(next http.Handler) http.Handler {
|
|
if s.Auth == nil {
|
|
return next
|
|
}
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
p, err := s.Auth.Verify(r.Context(), r.Header.Get("Authorization"))
|
|
if err != nil {
|
|
if errors.Is(err, authn.ErrNoToken) {
|
|
writeError(w, http.StatusUnauthorized, "TOKEN_MISSING", "bearer token required")
|
|
return
|
|
}
|
|
// Signature, issuer, expiry, and audience failures all land
|
|
// here; the message says which without echoing the token.
|
|
writeError(w, http.StatusUnauthorized, "TOKEN_INVALID", err.Error())
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(authn.WithPrincipal(r.Context(), p)))
|
|
})
|
|
}
|
|
|
|
func (s *Server) healthz(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
|
}
|
|
|
|
func (s *Server) readyz(w http.ResponseWriter, r *http.Request) {
|
|
if err := s.Store.Ping(r.Context()); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, "store_unavailable", err.Error())
|
|
return
|
|
}
|
|
if err := s.Keycloak.Health(r.Context()); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ready"})
|
|
}
|