feat(licences): per-tenant LiteLLM key with a Werkpilot grant #29

Merged
sharang merged 1 commits from feat/licence-llm-key into main 2026-09-14 08:27:26 +00:00
19 changed files with 890 additions and 13 deletions

No files matched your search

+1 -1
View File
@@ -83,7 +83,7 @@ jobs:
# own test binary — and including it triggers a covdata-tool error
# on packages with no _test.go files. -coverpkg makes the server's
# exercise of store/* count toward coverage.
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/...
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/...
- name: coverage gate
run: |
+39
View File
@@ -54,6 +54,10 @@ Env vars (override at the shell):
| `ERP_OUTBOX_INTERVAL` / `ERP_RECONCILE_INTERVAL` | `15s` / `15m` | Worker cadence |
| `ERP_RESTRICT_AFTER_DAYS` / `ERP_HALT_AFTER_DAYS` / `ERP_EXPORT_WINDOW_DAYS` | `14` / `30` / `30` | Ladder timing |
| `LICENCE_SIGNING_KEY` / `LICENCE_ISSUER` / `LICENCE_TTL_DAYS` | empty (ephemeral) / `tenant-registry` / `30` | CLI licence signer (base64 Ed25519 seed) |
| `LITELLM_BASE_URL` | `https://llm.breakpilot.com` | LiteLLM proxy root; returned to Werkpilot as `llm_base_url` |
| `LITELLM_MASTER_KEY` | empty (LLM keys off — logged once at start) | LiteLLM admin key for `/key/generate` + `/key/delete` (secret) |
| `LITELLM_MODELS` | `Qwen3-Coder-30B-A3B-Instruct,gpt-oss-120b` | Comma list of models a tenant key may call |
| `LITELLM_BUDGET_TRIAL` / `LITELLM_BUDGET_DEFAULT` | `5` / `50` | USD per 30 days (`budget_duration: 30d`) for trial / paying tenants |
## Endpoints
@@ -136,6 +140,41 @@ records the licence and signs an EdDSA JWT (`LICENCE_SIGNING_KEY` = base64
(ok → warning → degraded → hard_stop on the token's own clock after expiry,
plus the tenant ladder; renewal past half-life) and honour `revoked`.
### Werkpilot licences carry a LiteLLM key (D6)
For `product = "werkpilot"` the registry also provisions a **per-tenant
LiteLLM virtual key** (`POST /key/generate` on `LITELLM_BASE_URL` with
`LITELLM_MASTER_KEY`) and returns it in the grant:
```json
{
"id": "6a5e…", "licence": "eyJhbGciOiJFZERTQSIs…", "kid": "fe209240",
"expires_at": "2026-10-12T09:00:00Z",
"grace": { "warning_days": 7, "degraded_days": 14, "hard_stop_days": 30 },
"status": "ok",
"llm_api_key": "sk-…", // once — never stored, never returned again
"llm_base_url": "https://llm.breakpilot.com",
"warnings": ["llm_key_unavailable"] // only when LiteLLM is off / down / refused
}
```
- Key shape sent to LiteLLM: `key_alias = werkpilot-<tenant_slug>-<licence_id>`,
`models = LITELLM_MODELS`, `max_budget = LITELLM_BUDGET_TRIAL` for tenants in
`trial`, else `LITELLM_BUDGET_DEFAULT`, `budget_duration = "30d"`,
`metadata = {tenant_id, tenant_slug, licence_id, product, plan, tenant_status}`.
- The row keeps only LiteLLM's hashed token id (`licences.llm_key_id`,
migration `0007`), which `GET /v1/licences` exposes as `llm_key_id`.
- **Failure never fails the licence**: with `LITELLM_MASTER_KEY` unset or
LiteLLM unreachable the JWT is issued, the LLM fields are omitted and
`warnings` carries `llm_key_unavailable`.
- **Heartbeat renewal** does not mint a second key: the handle moves to the
renewed licence row, the renewed grant carries `llm_base_url` but no
`llm_api_key` (the CLI keeps the one it stored).
- **Revoke** (`POST /v1/licences/{id}/revoke`) deletes the key
(`POST /key/delete {"keys": [<token id>]}`; 404 tolerated). The audit event
records `llm_key_deleted`. Firmwerk licences get no key.
- `GET /v1/internal/erp/status` reports `llm_keys_enabled`.
## Storage
The service picks its store based on `DATABASE_URL`:
+12 -1
View File
@@ -15,6 +15,7 @@ import (
"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/server"
"git.breakpilot.com/platform/tenant-registry/internal/store"
@@ -123,7 +124,17 @@ func main() {
slog.Info("licence signer configured", "kid", signer.KID(), "issuer", signer.Issuer())
}
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer}
// LiteLLM virtual keys for Werkpilot licences (D6).
llmKeys := llmkeys.New(llmkeys.Config{BaseURL: cfg.LiteLLMBaseURL, MasterKey: cfg.LiteLLMMasterKey, Models: cfg.LiteLLMModels,
BudgetTrial: cfg.LiteLLMBudgetTrial, BudgetDefault: cfg.LiteLLMBudgetDefault})
if llmKeys.Enabled() {
slog.Info("litellm key provisioning configured", "url", llmKeys.BaseURL(), "models", llmKeys.Models(),
"budget_trial_usd", llmKeys.Budget(true), "budget_default_usd", llmKeys.Budget(false), "budget_duration", llmKeys.BudgetDuration())
} else {
slog.Warn("LITELLM_MASTER_KEY not set — Werkpilot licences are issued without a LiteLLM key")
}
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys}
handler := server.NewRouter(app)
srv := &http.Server{
Addr: cfg.Addr,
+42
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
@@ -63,6 +64,14 @@ type Config struct {
LicenceSigningKey string
LicenceIssuer string
LicenceTTLDays int
// LiteLLM virtual keys for Werkpilot licences (D6). Empty master key ⇒
// feature off, grants carry no LLM key. Budgets are USD per 30 days.
LiteLLMBaseURL string
LiteLLMMasterKey string
LiteLLMModels []string
LiteLLMBudgetTrial float64
LiteLLMBudgetDefault float64
}
func Load() (*Config, error) {
@@ -108,9 +117,42 @@ func Load() (*Config, error) {
LicenceSigningKey: os.Getenv("LICENCE_SIGNING_KEY"),
LicenceIssuer: getenv("LICENCE_ISSUER", "tenant-registry"),
LicenceTTLDays: getint("LICENCE_TTL_DAYS", 30),
LiteLLMBaseURL: getenv("LITELLM_BASE_URL", "https://llm.breakpilot.com"),
LiteLLMMasterKey: os.Getenv("LITELLM_MASTER_KEY"),
LiteLLMModels: getlist("LITELLM_MODELS", []string{"Qwen3-Coder-30B-A3B-Instruct", "gpt-oss-120b"}),
LiteLLMBudgetTrial: getfloat("LITELLM_BUDGET_TRIAL", 5),
LiteLLMBudgetDefault: getfloat("LITELLM_BUDGET_DEFAULT", 50),
}, nil
}
func getfloat(key string, fallback float64) float64 {
if v := os.Getenv(key); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f
}
}
return fallback
}
// getlist parses a comma-separated list, trimming blanks; empty ⇒ fallback.
func getlist(key string, fallback []string) []string {
v := os.Getenv(key)
if v == "" {
return fallback
}
var out []string
for _, s := range strings.Split(v, ",") {
if s = strings.TrimSpace(s); s != "" {
out = append(out, s)
}
}
if len(out) == 0 {
return fallback
}
return out
}
func getint(key string, fallback int) int {
if v := os.Getenv(key); v != "" {
if n, err := strconv.Atoi(v); err == nil {
+36
View File
@@ -50,3 +50,39 @@ func TestLoad_invalidEnv(t *testing.T) {
t.Fatal("expected error for invalid APP_ENV")
}
}
func TestLoad_litellmDefaultsAndOverrides(t *testing.T) {
t.Setenv("APP_ENV", "")
for _, k := range []string{"LITELLM_BASE_URL", "LITELLM_MASTER_KEY", "LITELLM_MODELS", "LITELLM_BUDGET_TRIAL", "LITELLM_BUDGET_DEFAULT"} {
t.Setenv(k, "")
}
cfg, err := Load()
if err != nil {
t.Fatal(err)
}
if cfg.LiteLLMBaseURL != "https://llm.breakpilot.com" || cfg.LiteLLMMasterKey != "" ||
len(cfg.LiteLLMModels) != 2 || cfg.LiteLLMModels[0] != "Qwen3-Coder-30B-A3B-Instruct" || cfg.LiteLLMModels[1] != "gpt-oss-120b" ||
cfg.LiteLLMBudgetTrial != 5 || cfg.LiteLLMBudgetDefault != 50 {
t.Errorf("litellm defaults: %+v", cfg)
}
t.Setenv("LITELLM_BASE_URL", "http://llm.local")
t.Setenv("LITELLM_MASTER_KEY", "sk-master")
t.Setenv("LITELLM_MODELS", " a , ,b ")
t.Setenv("LITELLM_BUDGET_TRIAL", "2.5")
t.Setenv("LITELLM_BUDGET_DEFAULT", "not-a-number")
cfg, err = Load()
if err != nil {
t.Fatal(err)
}
if cfg.LiteLLMBaseURL != "http://llm.local" || cfg.LiteLLMMasterKey != "sk-master" ||
len(cfg.LiteLLMModels) != 2 || cfg.LiteLLMModels[0] != "a" || cfg.LiteLLMModels[1] != "b" ||
cfg.LiteLLMBudgetTrial != 2.5 || cfg.LiteLLMBudgetDefault != 50 {
t.Errorf("litellm overrides: %+v", cfg)
}
// a list of only separators falls back to the default
t.Setenv("LITELLM_MODELS", " , ")
if cfg, _ = Load(); len(cfg.LiteLLMModels) != 2 {
t.Errorf("blank list should fall back: %v", cfg.LiteLLMModels)
}
}
+199
View File
@@ -0,0 +1,199 @@
// Package llmkeys is the LiteLLM key-management client (D6): when the
// registry issues a Werkpilot licence it also provisions a per-tenant
// LiteLLM virtual key (POST /key/generate) with a monthly budget by plan and
// deletes it again on revoke (POST /key/delete).
//
// Authentication is the proxy master key (`Authorization: Bearer <key>`).
// The client is disabled — Enabled() false — when no master key is set;
// grants then carry no LLM key.
package llmkeys
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const (
DefaultBaseURL = "https://llm.breakpilot.com"
DefaultBudgetDuration = "30d"
DefaultBudgetTrial = 5.0
DefaultBudgetDefault = 50.0
)
// DefaultModels are the models tenant keys may call.
var DefaultModels = []string{"Qwen3-Coder-30B-A3B-Instruct", "gpt-oss-120b"}
// ErrDisabled — no master key configured.
var ErrDisabled = errors.New("llmkeys: disabled (no master key)")
// ErrUnavailable wraps transport / 5xx failures.
var ErrUnavailable = errors.New("llmkeys: unavailable")
type Config struct {
BaseURL string
MasterKey string
Models []string
// USD per BudgetDuration window.
BudgetTrial float64
BudgetDefault float64
BudgetDuration string
Timeout time.Duration
}
type Client struct {
cfg Config
http *http.Client
}
// New returns a client; Enabled() is false when MasterKey is empty.
func New(cfg Config) *Client {
if cfg.BaseURL == "" {
cfg.BaseURL = DefaultBaseURL
}
cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/")
if len(cfg.Models) == 0 {
cfg.Models = append([]string(nil), DefaultModels...)
}
if cfg.BudgetTrial <= 0 {
cfg.BudgetTrial = DefaultBudgetTrial
}
if cfg.BudgetDefault <= 0 {
cfg.BudgetDefault = DefaultBudgetDefault
}
if cfg.BudgetDuration == "" {
cfg.BudgetDuration = DefaultBudgetDuration
}
if cfg.Timeout <= 0 {
cfg.Timeout = 10 * time.Second
}
return &Client{cfg: cfg, http: &http.Client{Timeout: cfg.Timeout}}
}
func (c *Client) Enabled() bool { return c != nil && c.cfg.MasterKey != "" }
// BaseURL is what tenants call (the OpenAI-compatible proxy root).
func (c *Client) BaseURL() string {
if c == nil {
return ""
}
return c.cfg.BaseURL
}
func (c *Client) Models() []string { return append([]string(nil), c.cfg.Models...) }
// Budget returns the monthly USD cap for a tenant: trial or default.
func (c *Client) Budget(trial bool) float64 {
if trial {
return c.cfg.BudgetTrial
}
return c.cfg.BudgetDefault
}
func (c *Client) BudgetDuration() string { return c.cfg.BudgetDuration }
// GenerateRequest — the /key/generate body subset we use.
type GenerateRequest struct {
KeyAlias string `json:"key_alias"`
Models []string `json:"models"`
MaxBudget float64 `json:"max_budget"`
BudgetDuration string `json:"budget_duration"`
Metadata map[string]any `json:"metadata,omitempty"`
TeamID string `json:"team_id,omitempty"`
Duration string `json:"duration,omitempty"` // key expiry, e.g. "30d"; empty ⇒ never
}
// Key — the secret (returned once) and the hashed token LiteLLM uses as the
// key's identifier (safe to persist; needed for /key/delete).
type Key struct {
Key string
TokenID string
}
// Generate provisions a virtual key.
func (c *Client) Generate(ctx context.Context, req GenerateRequest) (Key, error) {
if !c.Enabled() {
return Key{}, ErrDisabled
}
var out struct {
Key string `json:"key"`
Token string `json:"token"`
TokenID string `json:"token_id"`
}
if err := c.post(ctx, "/key/generate", req, &out); err != nil {
return Key{}, err
}
id := out.Token
if id == "" {
id = out.TokenID
}
if out.Key == "" || id == "" {
return Key{}, fmt.Errorf("llmkeys: /key/generate response lacks key/token")
}
return Key{Key: out.Key, TokenID: id}, nil
}
// Delete removes a key by its hashed token (or the sk-… secret). A key that
// is already gone (404) is not an error.
func (c *Client) Delete(ctx context.Context, tokenID string) error {
if !c.Enabled() {
return ErrDisabled
}
if tokenID == "" {
return nil
}
err := c.post(ctx, "/key/delete", map[string]any{"keys": []string{tokenID}}, nil)
var se *StatusError
if errors.As(err, &se) && se.Code == http.StatusNotFound {
return nil
}
return err
}
// StatusError — a non-2xx reply from LiteLLM.
type StatusError struct {
Code int
Body string
}
func (e *StatusError) Error() string {
return fmt.Sprintf("llmkeys: litellm responded %d: %s", e.Code, e.Body)
}
func (c *Client) post(ctx context.Context, path string, body any, out any) error {
buf, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.cfg.BaseURL+path, bytes.NewReader(buf))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.cfg.MasterKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("%w: %v", ErrUnavailable, err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode >= 500 {
return fmt.Errorf("%w: %d %s", ErrUnavailable, resp.StatusCode, strings.TrimSpace(string(raw)))
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return &StatusError{Code: resp.StatusCode, Body: strings.TrimSpace(string(raw))}
}
if out != nil {
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("llmkeys: decode %s: %w", path, err)
}
}
return nil
}
+144
View File
@@ -0,0 +1,144 @@
package llmkeys
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync"
"testing"
)
// fake — a minimal LiteLLM key-management stand-in.
type fake struct {
mu sync.Mutex
gen []map[string]any
deleted []string
auth []string
genCode int
delCode int
genReply map[string]any
}
func newFake(t *testing.T) (*fake, *httptest.Server) {
t.Helper()
f := &fake{genCode: 200, delCode: 200}
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"))
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
switch r.URL.Path {
case "/key/generate":
f.gen = append(f.gen, body)
w.WriteHeader(f.genCode)
reply := f.genReply
if reply == nil {
reply = map[string]any{"key": "sk-secret-1", "token": "hashed-1", "token_id": "hashed-1", "key_alias": body["key_alias"]}
}
_ = json.NewEncoder(w).Encode(reply)
case "/key/delete":
for _, k := range body["keys"].([]any) {
f.deleted = append(f.deleted, k.(string))
}
w.WriteHeader(f.delCode)
_ = json.NewEncoder(w).Encode(map[string]any{"deleted_keys": body["keys"]})
default:
w.WriteHeader(404)
}
}))
t.Cleanup(srv.Close)
return f, srv
}
func TestClient_generateAndDelete(t *testing.T) {
f, srv := newFake(t)
c := New(Config{BaseURL: srv.URL + "/", MasterKey: "sk-master"})
if !c.Enabled() || c.BaseURL() != srv.URL || c.Budget(true) != DefaultBudgetTrial || c.Budget(false) != DefaultBudgetDefault || c.BudgetDuration() != DefaultBudgetDuration {
t.Fatalf("defaults: %+v", c.cfg)
}
if m := c.Models(); len(m) != 2 || m[0] != DefaultModels[0] {
t.Fatalf("models: %v", m)
}
k, err := c.Generate(context.Background(), GenerateRequest{
KeyAlias: "werkpilot-acme-lic", Models: c.Models(), MaxBudget: 5, BudgetDuration: "30d",
Metadata: map[string]any{"tenant_id": "t1"},
})
if err != nil || k.Key != "sk-secret-1" || k.TokenID != "hashed-1" {
t.Fatalf("generate: %+v %v", k, err)
}
if len(f.gen) != 1 || f.gen[0]["key_alias"] != "werkpilot-acme-lic" || f.gen[0]["max_budget"] != 5.0 || f.gen[0]["budget_duration"] != "30d" {
t.Fatalf("request body: %+v", f.gen)
}
if _, ok := f.gen[0]["team_id"]; ok {
t.Fatalf("empty team_id must be omitted: %+v", f.gen[0])
}
if f.auth[0] != "Bearer sk-master" {
t.Fatalf("auth: %v", f.auth)
}
if err := c.Delete(context.Background(), "hashed-1"); err != nil || len(f.deleted) != 1 || f.deleted[0] != "hashed-1" {
t.Fatalf("delete: %v %v", err, f.deleted)
}
// 404 on delete is tolerated; empty id is a no-op.
f.delCode = 404
if err := c.Delete(context.Background(), "gone"); err != nil {
t.Fatalf("404: %v", err)
}
if err := c.Delete(context.Background(), ""); err != nil || len(f.deleted) != 2 {
t.Fatalf("empty: %v %v", err, f.deleted)
}
// other 4xx surfaces as StatusError
f.delCode = 400
var se *StatusError
if err := c.Delete(context.Background(), "x"); !errors.As(err, &se) || se.Code != 400 || se.Error() == "" {
t.Fatalf("400: %v", err)
}
}
func TestClient_failures(t *testing.T) {
f, srv := newFake(t)
c := New(Config{BaseURL: srv.URL, MasterKey: "m", Models: []string{"x"}, BudgetTrial: 1, BudgetDefault: 2, BudgetDuration: "7d"})
if c.Budget(true) != 1 || c.Budget(false) != 2 || c.BudgetDuration() != "7d" || c.Models()[0] != "x" {
t.Fatalf("overrides: %+v", c.cfg)
}
f.genCode = 500
if _, err := c.Generate(context.Background(), GenerateRequest{}); !errors.Is(err, ErrUnavailable) {
t.Fatalf("5xx: %v", err)
}
f.genCode = 401
var se *StatusError
if _, err := c.Generate(context.Background(), GenerateRequest{}); !errors.As(err, &se) || se.Code != 401 {
t.Fatalf("401: %v", err)
}
f.genCode = 200
f.genReply = map[string]any{"key": "sk-only"}
if _, err := c.Generate(context.Background(), GenerateRequest{}); err == nil {
t.Fatal("missing token must fail")
}
f.genReply = map[string]any{"key": "sk-2", "token_id": "tid-2"}
if k, err := c.Generate(context.Background(), GenerateRequest{}); err != nil || k.TokenID != "tid-2" {
t.Fatalf("token_id fallback: %+v %v", k, err)
}
// connection refused
srv.Close()
if _, err := c.Generate(context.Background(), GenerateRequest{}); !errors.Is(err, ErrUnavailable) {
t.Fatalf("down: %v", err)
}
// disabled / nil
var nilc *Client
if nilc.Enabled() || nilc.BaseURL() != "" {
t.Fatal("nil client must be disabled")
}
d := New(Config{})
if d.Enabled() || d.BaseURL() != DefaultBaseURL {
t.Fatalf("disabled: %+v", d.cfg)
}
if _, err := d.Generate(context.Background(), GenerateRequest{}); !errors.Is(err, ErrDisabled) {
t.Fatalf("disabled generate: %v", err)
}
if err := d.Delete(context.Background(), "x"); !errors.Is(err, ErrDisabled) {
t.Fatalf("disabled delete: %v", err)
}
}
+1
View File
@@ -588,6 +588,7 @@ func (s *Server) erpStatus(w http.ResponseWriter, r *http.Request) {
"webhook_enabled": s.cfg().ErpWebhookSecret != "",
"outbox_pending": pending,
"licences_enabled": s.Licences != nil,
"llm_keys_enabled": s.LLMKeys.Enabled(),
})
}
+101 -7
View File
@@ -11,6 +11,7 @@ import (
"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"
)
@@ -36,8 +37,22 @@ type licenceResp struct {
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")
@@ -70,7 +85,7 @@ func (s *Server) issueLicence(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
resp, code, kind, msg := s.issue(ctx, r, in, subject)
resp, code, kind, msg := s.issue(ctx, r, in, subject, nil)
if code != http.StatusCreated {
writeError(w, code, kind, msg)
return
@@ -78,8 +93,12 @@ func (s *Server) issueLicence(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, resp)
}
// issue evaluates the entitlement, records the licence row and signs the JWT.
func (s *Server) issue(ctx context.Context, r *http.Request, in issueLicenceReq, subject string) (*licenceResp, int, string, string) {
// 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()
@@ -130,9 +149,82 @@ func (s *Server) issue(ctx context.Context, r *http.Request, in issueLicenceReq,
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)}})
return &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: exp, Grace: licence.DefaultGrace, Status: "ok"}, http.StatusCreated, "", ""
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.
func (s *Server) provisionLLMKey(ctx context.Context, t *store.Tenant, row *store.Licence, renewOf *store.Licence, out *licenceResp) 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},
})
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 {
@@ -215,7 +307,7 @@ func (s *Server) licenceHeartbeat(w http.ResponseWriter, r *http.Request) {
if check.Allowed && !check.ReadOnly {
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)
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"
@@ -267,7 +359,9 @@ func (s *Server) revokeLicence(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{TenantID: row.TenantID, Action: "licence.revoked", TargetID: row.ID, TargetType: "licence", Product: row.Product})
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)
}
+241
View File
@@ -0,0 +1,241 @@
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) != 2 || models[0] != "Qwen3-Coder-30B-A3B-Instruct" || models[1] != "gpt-oss-120b" {
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)
}
}
}
+2
View File
@@ -15,6 +15,7 @@ import (
"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"
)
@@ -32,6 +33,7 @@ type Server struct {
// 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
}
+11
View File
@@ -318,3 +318,14 @@ func (m *Memory) TouchLicence(_ context.Context, id string, at time.Time) error
l.LastSeenAt = &t
return nil
}
func (m *Memory) SetLicenceLLMKey(_ context.Context, id string, keyID string) error {
m.mu.Lock()
defer m.mu.Unlock()
l, ok := m.licences[id]
if !ok {
return ErrNotFound
}
l.LLMKeyID = keyID
return nil
}
+17 -3
View File
@@ -323,13 +323,13 @@ func (p *Postgres) RecordWebhookReceipt(ctx context.Context, eventID string) (bo
}
const licenceSelect = `
SELECT id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at
SELECT id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at, COALESCE(llm_key_id, '')
FROM licences `
func scanLicence(row pgx.Row) (*Licence, error) {
var l Licence
var revoked, seen *time.Time
err := row.Scan(&l.ID, &l.Kid, &l.TenantID, &l.Product, &l.Subject, &l.Device, &l.ExpiresAt, &revoked, &seen, &l.CreatedAt)
err := row.Scan(&l.ID, &l.Kid, &l.TenantID, &l.Product, &l.Subject, &l.Device, &l.ExpiresAt, &revoked, &seen, &l.CreatedAt, &l.LLMKeyID)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
@@ -351,7 +351,7 @@ func (p *Postgres) CreateLicence(ctx context.Context, l Licence) (*Licence, erro
out, err := scanLicence(p.pool.QueryRow(ctx, `
INSERT INTO licences (id, kid, tenant_id, product, subject, device, expires_at)
VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3::uuid, $4, $5, $6, $7)
RETURNING id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at`,
RETURNING id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at, COALESCE(llm_key_id, '')`,
id, l.Kid, l.TenantID, l.Product, l.Subject, l.Device, l.ExpiresAt))
if err != nil {
if isFKViolation(err) || isInvalidUUID(err) {
@@ -407,6 +407,20 @@ func (p *Postgres) RevokeLicence(ctx context.Context, id string, at time.Time) e
return nil
}
func (p *Postgres) SetLicenceLLMKey(ctx context.Context, id string, keyID string) error {
tag, err := p.pool.Exec(ctx, `UPDATE licences SET llm_key_id = NULLIF($2, '') WHERE id = $1::uuid`, id, keyID)
if err != nil {
if isInvalidUUID(err) {
return ErrNotFound
}
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) TouchLicence(ctx context.Context, id string, at time.Time) error {
tag, err := p.pool.Exec(ctx, `UPDATE licences SET last_seen_at = $2 WHERE id = $1::uuid`, id, at)
if err != nil {
+2
View File
@@ -119,6 +119,8 @@ type Store interface {
ListLicences(ctx context.Context, tenantID string) ([]Licence, error)
RevokeLicence(ctx context.Context, id string, at time.Time) error
TouchLicence(ctx context.Context, id string, at time.Time) error
// SetLicenceLLMKey records (or clears, with "") the LiteLLM key id.
SetLicenceLLMKey(ctx context.Context, id string, keyID string) error
// Lifecycle
Close()
+3
View File
@@ -227,4 +227,7 @@ type Licence struct {
RevokedAt *time.Time `json:"revoked_at,omitempty"`
LastSeenAt *time.Time `json:"last_seen_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
// LLMKeyID — LiteLLM's hashed token id of the virtual key issued with a
// Werkpilot licence (D6); the handle for /key/delete. Never the secret.
LLMKeyID string `json:"llm_key_id,omitempty"`
}
+1
View File
@@ -0,0 +1 @@
ALTER TABLE licences DROP COLUMN llm_key_id;
+4
View File
@@ -0,0 +1,4 @@
-- D6: a Werkpilot licence carries a per-tenant LiteLLM virtual key. The
-- column holds LiteLLM's hashed token id (the handle for /key/delete); the
-- sk-… secret is returned once in the issue response and never stored.
ALTER TABLE licences ADD COLUMN llm_key_id TEXT;
+15
View File
@@ -114,6 +114,21 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
}
}
// Column assertions for later migrations (0007: licences.llm_key_id).
for _, c := range [][2]string{{"licences", "llm_key_id"}} {
var exists bool
err := db.QueryRow(
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)",
c[0], c[1],
).Scan(&exists)
if err != nil {
t.Fatalf("query for column %s.%s: %v", c[0], c[1], err)
}
if !exists {
t.Errorf("column %s.%s missing after migrate up", c[0], c[1])
}
}
// Enum assertions.
wantEnums := map[string][]string{
// 0002 appends the ladder values; enum values are never removed (down is a no-op).
+19 -1
View File
@@ -531,6 +531,7 @@ paths:
webhook_enabled: { type: boolean }
outbox_pending: { type: integer }
licences_enabled: { type: boolean }
llm_keys_enabled: { type: boolean }
/v1/internal/erp/reconcile:
post:
@@ -631,7 +632,11 @@ paths:
flow, tenant-context claims) get a licence for their own tenant;
service tokens pass tenant_id. Ed25519-signed (EdDSA), verifiable
offline against /.well-known/licence-keys.json; expiry = min(ttl,
entitlement expiry). Grace ladder inside the token.
entitlement expiry). Grace ladder inside the token. For
product=werkpilot the registry also provisions a per-tenant LiteLLM
virtual key (budget by plan) and returns it once as llm_api_key; a
LiteLLM failure does not fail the licence (warnings:
["llm_key_unavailable"]). Revoking the licence deletes the key.
requestBody:
required: true
content:
@@ -825,6 +830,7 @@ components:
revoked_at: { type: string, format: date-time }
last_seen_at: { type: string, format: date-time }
created_at: { type: string, format: date-time }
llm_key_id: { type: string, description: "LiteLLM hashed token id of the key issued with a Werkpilot licence (handle for revoke; never the secret)." }
LicenceIssued:
type: object
properties:
@@ -839,6 +845,18 @@ components:
degraded_days: { type: integer }
hard_stop_days: { type: integer }
status: { type: string }
llm_api_key:
type: string
description: |
Werkpilot only: per-tenant LiteLLM virtual key (sk-…). Returned in
THIS response only — never persisted, never returned again. Absent
on heartbeat renewals (the CLI keeps the key it stored) and when
LiteLLM is unavailable (see warnings).
llm_base_url: { type: string, description: "OpenAI-compatible proxy root the key is valid for." }
warnings:
type: array
items: { type: string, enum: [llm_key_unavailable] }
description: Non-fatal issue notes; the licence itself is valid.
LicenceHeartbeat:
type: object
properties: