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>
This commit is contained in:
1 parent
97284b5008
commit
b89dd2ae4c
28 files changed
+1208
-39
No files matched your search
@@ -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/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/...
|
||||
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/...
|
||||
|
||||
- name: coverage gate
|
||||
run: |
|
||||
|
||||
@@ -59,6 +59,7 @@ 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) |
|
||||
| `SECRETS_ENCRYPTION_KEY` | empty | base64, 32 bytes (`openssl rand -base64 32`). Seals the LiteLLM key of a Werkpilot CI licence so the reused licence hands it out again (ADR 0001 §5). Empty: a reused CI licence comes without the key (warning `llm_key_not_repeatable`). |
|
||||
| `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,Qwen3.8-27B` | Comma list of models a tenant key may call |
|
||||
|
||||
+11
-1
@@ -19,6 +19,7 @@ import (
|
||||
"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/secretbox"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/server"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
"git.breakpilot.com/platform/tenant-registry/migrations"
|
||||
@@ -126,6 +127,15 @@ func main() {
|
||||
slog.Info("licence signer configured", "kid", signer.KID(), "issuer", signer.Issuer())
|
||||
}
|
||||
|
||||
secrets, err := secretbox.New(cfg.SecretsEncryptionKey)
|
||||
if err != nil {
|
||||
slog.Error("secrets encryption key invalid", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if !secrets.Enabled() {
|
||||
slog.Warn("SECRETS_ENCRYPTION_KEY not set — a reused Werkpilot CI licence cannot hand out its LiteLLM key again")
|
||||
}
|
||||
|
||||
// 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})
|
||||
@@ -157,7 +167,7 @@ func main() {
|
||||
if mc := (mail.Config{Host: cfg.SMTPHost, Port: cfg.SMTPPort, User: cfg.SMTPUser, Password: cfg.SMTPPassword, From: cfg.MailFrom, FromName: cfg.MailFromName}); mc.Configured() {
|
||||
mailer = &mail.SMTP{Cfg: mc}
|
||||
}
|
||||
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Objects: objects, Mail: mailer}
|
||||
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Secrets: secrets, Objects: objects, Mail: mailer}
|
||||
handler := server.NewRouter(app)
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
This is prerequisite 1 of the Werkmeister plan (platform/werkmeister ADR 0001), and it also settles the CI-licence gap (firmwerk#64, step 1).
|
||||
|
||||
- **Deciders:** Sharang (platform), reviewed by the platform team.
|
||||
- **Status:** accepted 2026-10-13, with review corrections folded in (§9). Step 1 is implemented in this repo: migration 0015, `internal/scopes`, verify, revoke and SHA-256 keys. Open: the user decisions in §5 (D1, D2) and §2 (end of legacy keys).
|
||||
- **Status:** accepted 2026-10-13, with review corrections folded in (§9) and the user's decisions D1–D3 (§2, §5). Implemented in this repo: step 1 (migration 0015, `internal/scopes`, verify, revoke, SHA-256 keys) and step 1b (`POST /v1/licences/ci`, integration keys, migrations 0016 and 0017). Open: the date for ending legacy keys.
|
||||
|
||||
Customers appear only as K-numbers.
|
||||
|
||||
@@ -65,6 +65,7 @@ The plan's placeholders (`findings:read`, `scan:trigger`) become `pruefwerk:find
|
||||
**Proposal: no backfill. `scopes = []` stays a legacy full grant** on the key's `product` (or on every entitled product if `product` is NULL), exactly as today.
|
||||
- Verify returns `"legacy": true` for such keys.
|
||||
- The portal lists them as "Vollzugriff (alt)" with a hint to replace them.
|
||||
- **D3 (decided):** legacy keys keep working as "Vollzugriff (alt)" and end after a 90-day notice; the user sets the date.
|
||||
- New keys **must** carry at least one scope **once the portal's scope picker ships**. Until then the registry still accepts empty scopes for `kind=user`; `ci` keys always need scopes.
|
||||
- After a 90-day notice, legacy keys stop being accepted. That is a separate decision for the user, with the date in the changelog.
|
||||
|
||||
@@ -118,7 +119,7 @@ What that means for each product:
|
||||
|
||||
## 5. API keys on registry routes: the CI licence (G5, firmwerk#64 step 1)
|
||||
|
||||
Narrow on purpose: **only `POST /v1/licences`** accepts a key.
|
||||
Narrow on purpose: one dedicated route, **`POST /v1/licences/ci`**, accepts a key. It is registered outside the JWT chain (like the heartbeat) rather than mixing key auth into `requireAuth`; the interactive `POST /v1/licences` is unchanged.
|
||||
|
||||
- **Auth:** `Authorization: Bearer bp_…` with scope `<product>:licence`. The tenant comes from the key. `device = ci:<runner host or name>`, set by the CLI.
|
||||
- **Licence:**
|
||||
@@ -127,15 +128,15 @@ Narrow on purpose: **only `POST /v1/licences`** accepts a key.
|
||||
- **idempotent per (key_id, device, UTC day):** a repeat request returns the existing unexpired licence instead of creating a new row per job;
|
||||
- **rate limit per key** (60/h; above that `429`);
|
||||
- the grace ladder applies unchanged.
|
||||
- **bp-licence:** reads `BP_LICENCE_API_KEY`. If it's set, it skips the device flow and calls `Registry::issue` with the key. Store, verify and grace stay the same. Werkpilot and Firmwerk get CI mode by bumping the crate.
|
||||
- **bp-licence:** reads `BP_LICENCE_API_KEY`. If it's set, it skips the device flow and calls `POST /v1/licences/ci` with the key and `device` = runner name. Store, verify and grace stay the same. Werkpilot and Firmwerk get CI mode by bumping the crate.
|
||||
- **Key kind:** a CI key is created in the portal with `kind=ci` (picker preset "CI-Lizenz", scope `<product>:licence`, expiry required, at most 365 days).
|
||||
|
||||
**Two decisions for the user** (I don't decide these):
|
||||
- **D1, seats:** does a CI licence count as a seat?
|
||||
- Proposal: no. It records the usage event `ci.licence` (per key and day) instead of `seat.login`, and the plan's seat limit doesn't apply. CI usage is metered, not seat-billed.
|
||||
- **D2, Werkpilot in CI:** does a Werkpilot CI licence get the per-tenant LiteLLM key, as interactive licences do?
|
||||
- Proposal: yes. It's the same tenant key, metered the same way, with no billing for now.
|
||||
- Without it, Werkpilot can't run headless in CI.
|
||||
**Decided by the user (2026-10-13):**
|
||||
- **D1, seats:** a CI licence is **not** a seat. The CLI records the usage event `ci.licence` (per key and day) instead of `seat.login`; CI usage is metered, not seat-billed.
|
||||
- **D2, Werkpilot in CI:** a Werkpilot CI licence **gets the per-tenant LiteLLM key**, metered the same way, no billing for now.
|
||||
- Werkpilot CI licences are reused per (key, device, UTC day) like the others. The LiteLLM key is generated with the licence (`duration: 1d`, so LiteLLM expires it itself) and its secret is stored **sealed** on the licence row (AES-256-GCM under the new registry secret `SECRETS_ENCRYPTION_KEY`, bound to the licence id; migration 0017). The reused licence hands out the same key again.
|
||||
- Cost cap: at most 10 LiteLLM keys per API key and UTC day (distinct devices); beyond that the licence comes without a key (warning `llm_key_daily_cap`).
|
||||
- Without `SECRETS_ENCRYPTION_KEY` a reused licence comes without the key (warning `llm_key_not_repeatable`).
|
||||
|
||||
## 6. Werkmeister's own use
|
||||
|
||||
@@ -148,6 +149,8 @@ Werkmeister acts for a tenant against Prüfwerk and Firmwerk, and later the regi
|
||||
- **Storage:** encrypted in Werkmeister's database (AES-GCM, key `WERKMEISTER_KEK`). In the cloud it comes from the orca project secret. On-prem (W5) it must also work without orca: an env var or a file (`WERKMEISTER_KEK_FILE`).
|
||||
- **Visibility:** shown in the portal list as "Werkmeister (Integration)", and the tenant can revoke it there.
|
||||
|
||||
**Name uniqueness:** migration 0016 makes `(tenant_id, name)` unique among **active** keys only, so a revoked key's name is free again (re-issue = revoke, then create; also lets portal users reuse a name).
|
||||
|
||||
**Who creates it.** Fork, with a decision proposal:
|
||||
- **(a)** `werkmeister-svc-<env>` gets the AUTHZ group `api-keys`, and Werkmeister checks "caller is IT_ADMIN of that tenant" itself. This is rejected: it gives a product service client cross-tenant power to create keys, which is exactly what we want to avoid.
|
||||
- **(b), decided:** the registry accepts **user tokens** on `POST /v1/api-keys`, but only:
|
||||
@@ -181,16 +184,16 @@ Steps 1 and 2 unblock firmwerk#64. Steps 1 and 5 unblock Werkmeister's Prüfwerk
|
||||
|
||||
## 8. Open questions
|
||||
|
||||
- **D1 seats and D2 LLM key** (§5): the user decides.
|
||||
- **End of legacy keys** (§2): date and notice, the user decides.
|
||||
- **End of legacy keys** (§2, D3): the user sets the date; 90 days' notice.
|
||||
- **Verify cost:** whether the registry also caches verify results itself, beyond the product caches. It's probably unnecessary with SHA-256.
|
||||
- **LiteLLM budget per tenant before billing starts:** every LiteLLM key has its own MaxBudget, so a tenant's effective budget grows with its keys (devices, CI). Move the budget to the tenant (a LiteLLM team per tenant) before billing.
|
||||
- **Registry data for Werkmeister** (documents, audit read, notifications): via the integration key, which means more registry routes accepting keys, or via `werkmeister-svc` AUTHZ groups with tenant scoping enforced in Werkmeister.
|
||||
- Proposal: AUTHZ groups for read-only paths in W3, and keys once the registry route set is clear.
|
||||
|
||||
## 9. Review corrections (2026-10-13), folded in
|
||||
|
||||
1. **§6(b) AUTHZ:** a narrow group `api-keys.integration` instead of `api-keys`. Create, list and revoke for user principals are own tenant, IT_ADMIN and `kind=integration` only.
|
||||
2. **§5:** CI licence issue is idempotent per (key_id, device, UTC day), with a rate limit of 60/h per key.
|
||||
2. **§5:** CI licence issue is idempotent per (key_id, device, UTC day), with a rate limit of 60/h per key. Implemented as `POST /v1/licences/ci` (200 for the reused licence, 201 for a new one, 429 above the limit).
|
||||
3. **§4:** revocation takes up to 60 s to take effect (product cache TTL). This is stated in the ADR and in the portal's revoke dialog.
|
||||
4. **§7 step 5:** Prüfwerk implements it from a short spec of §4; its prod promotion is coordinated separately.
|
||||
5. **§6:** the KEK also works without orca (env or file) for on-prem (W5).
|
||||
|
||||
@@ -62,8 +62,11 @@ type Config struct {
|
||||
|
||||
// CLI licences (decision 13). Empty key ⇒ ephemeral (dev only, logged).
|
||||
LicenceSigningKey string
|
||||
LicenceIssuer string
|
||||
LicenceTTLDays int
|
||||
// SecretsEncryptionKey — base64, 32 bytes; seals secrets the registry
|
||||
// hands out again (CI licences' LiteLLM keys). Empty ⇒ not stored.
|
||||
SecretsEncryptionKey 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.
|
||||
@@ -138,9 +141,10 @@ func Load() (*Config, error) {
|
||||
HaltAfterDays: getint("ERP_HALT_AFTER_DAYS", 30),
|
||||
ExportWindowDays: getint("ERP_EXPORT_WINDOW_DAYS", 30),
|
||||
|
||||
LicenceSigningKey: os.Getenv("LICENCE_SIGNING_KEY"),
|
||||
LicenceIssuer: getenv("LICENCE_ISSUER", "tenant-registry"),
|
||||
LicenceTTLDays: getint("LICENCE_TTL_DAYS", 30),
|
||||
LicenceSigningKey: os.Getenv("LICENCE_SIGNING_KEY"),
|
||||
SecretsEncryptionKey: os.Getenv("SECRETS_ENCRYPTION_KEY"),
|
||||
LicenceIssuer: getenv("LICENCE_ISSUER", "tenant-registry"),
|
||||
LicenceTTLDays: getint("LICENCE_TTL_DAYS", 30),
|
||||
|
||||
DocumentsS3Endpoint: os.Getenv("DOCUMENTS_S3_ENDPOINT"),
|
||||
DocumentsS3Region: getenv("DOCUMENTS_S3_REGION", "nbg1"),
|
||||
|
||||
@@ -41,6 +41,9 @@ type Claims struct {
|
||||
Device string `json:"device,omitempty"`
|
||||
Grace GracePolicy `json:"grace"`
|
||||
Heartbeat string `json:"heartbeat_url,omitempty"`
|
||||
// Kind is "ci" for a licence fetched with an API key in CI (no seat,
|
||||
// no heartbeat); empty for interactive licences.
|
||||
Kind string `json:"kind,omitempty"`
|
||||
}
|
||||
|
||||
// Signer holds the Ed25519 key. Ephemeral is true when no key was
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Package secretbox seals small secrets the registry must hand out again
|
||||
// (a CI licence's LiteLLM key, ADR 0001 §5) with AES-256-GCM under the
|
||||
// SECRETS_ENCRYPTION_KEY. Format: nonce (12 bytes) || ciphertext+tag.
|
||||
package secretbox
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Box seals and opens with one key. A nil *Box is valid and disabled.
|
||||
type Box struct {
|
||||
aead cipher.AEAD
|
||||
}
|
||||
|
||||
// New parses a base64 (std or raw URL) encoded 32-byte key. Empty ⇒ nil, nil
|
||||
// (disabled: callers fall back to not storing the secret).
|
||||
func New(b64 string) (*Box, error) {
|
||||
if b64 == "" {
|
||||
return nil, nil
|
||||
}
|
||||
key, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
if key, err = base64.RawURLEncoding.DecodeString(b64); err != nil {
|
||||
return nil, errors.New("SECRETS_ENCRYPTION_KEY is not base64")
|
||||
}
|
||||
}
|
||||
if len(key) != 32 {
|
||||
return nil, fmt.Errorf("SECRETS_ENCRYPTION_KEY must be 32 bytes, got %d", len(key))
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Box{aead: aead}, nil
|
||||
}
|
||||
|
||||
// Enabled reports whether a key is configured.
|
||||
func (b *Box) Enabled() bool { return b != nil }
|
||||
|
||||
// Seal encrypts plain; ad binds the ciphertext to its row (e.g. the licence id).
|
||||
func (b *Box) Seal(plain, ad []byte) ([]byte, error) {
|
||||
if b == nil {
|
||||
return nil, errors.New("secretbox: disabled")
|
||||
}
|
||||
nonce := make([]byte, b.aead.NonceSize())
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.aead.Seal(nonce, nonce, plain, ad), nil
|
||||
}
|
||||
|
||||
// Open decrypts what Seal produced with the same ad.
|
||||
func (b *Box) Open(sealed, ad []byte) ([]byte, error) {
|
||||
if b == nil {
|
||||
return nil, errors.New("secretbox: disabled")
|
||||
}
|
||||
n := b.aead.NonceSize()
|
||||
if len(sealed) < n {
|
||||
return nil, errors.New("secretbox: ciphertext too short")
|
||||
}
|
||||
return b.aead.Open(nil, sealed[:n], sealed[n:], ad)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package secretbox
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func key(t *testing.T) string {
|
||||
t.Helper()
|
||||
k := make([]byte, 32)
|
||||
_, _ = rand.Read(k)
|
||||
return base64.StdEncoding.EncodeToString(k)
|
||||
}
|
||||
|
||||
func TestSealOpen(t *testing.T) {
|
||||
b, err := New(key(t))
|
||||
if err != nil || !b.Enabled() {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sealed, err := b.Seal([]byte("sk-secret"), []byte("licence-1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Contains(sealed, []byte("sk-secret")) {
|
||||
t.Fatal("plaintext visible in ciphertext")
|
||||
}
|
||||
got, err := b.Open(sealed, []byte("licence-1"))
|
||||
if err != nil || string(got) != "sk-secret" {
|
||||
t.Fatalf("open: %q %v", got, err)
|
||||
}
|
||||
if _, err := b.Open(sealed, []byte("licence-2")); err == nil {
|
||||
t.Fatal("ciphertext opened under another row id")
|
||||
}
|
||||
other, _ := New(key(t))
|
||||
if _, err := other.Open(sealed, []byte("licence-1")); err == nil {
|
||||
t.Fatal("ciphertext opened with another key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
if b, err := New(""); b != nil || err != nil || b.Enabled() {
|
||||
t.Fatal("empty key must disable the box")
|
||||
}
|
||||
if _, err := New("not base64!"); err == nil {
|
||||
t.Error("bad base64 accepted")
|
||||
}
|
||||
if _, err := New(base64.StdEncoding.EncodeToString([]byte("short"))); err == nil {
|
||||
t.Error("short key accepted")
|
||||
}
|
||||
var b *Box
|
||||
if _, err := b.Seal([]byte("x"), nil); err == nil {
|
||||
t.Error("disabled box sealed")
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,12 @@ import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/scopes"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
@@ -56,6 +58,10 @@ func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
if !decodeJSON(w, r, &in) {
|
||||
return
|
||||
}
|
||||
if p, ok := authn.PrincipalFrom(r.Context()); ok && p.IsUser() {
|
||||
s.createIntegrationKey(w, r, p, in)
|
||||
return
|
||||
}
|
||||
if in.TenantID == "" || in.Name == "" {
|
||||
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and name are required")
|
||||
return
|
||||
@@ -126,15 +132,13 @@ func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusInternalServerError, "internal", "key generation failed")
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256([]byte(plain))
|
||||
|
||||
k, err := s.Store.CreateAPIKey(ctx, store.APIKeyCreate{
|
||||
TenantID: in.TenantID,
|
||||
Product: in.Product,
|
||||
Name: in.Name,
|
||||
Scopes: in.Scopes,
|
||||
Prefix: plain[:prefixLen],
|
||||
HashSHA256: sum[:],
|
||||
HashSHA256: hashKey(plain),
|
||||
Kind: in.Kind,
|
||||
ExpiresAt: in.ExpiresAt,
|
||||
CreatedBy: in.CreatedBy,
|
||||
@@ -174,7 +178,17 @@ func (s *Server) listAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
list, err := s.Store.ListAPIKeys(ctx, tenantID)
|
||||
var list []store.APIKey
|
||||
var err error
|
||||
if p, ok := authn.PrincipalFrom(r.Context()); ok && p.IsUser() {
|
||||
holder, ok := integrationCaller(w, p, tenantID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
list, err = s.integrationKeys(ctx, tenantID, holder)
|
||||
} else {
|
||||
list, err = s.Store.ListAPIKeys(ctx, tenantID)
|
||||
}
|
||||
if err != nil {
|
||||
if mapStoreError(w, err) {
|
||||
return
|
||||
@@ -192,6 +206,24 @@ func (s *Server) revokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
defer cancel()
|
||||
id := r.PathValue("id")
|
||||
tenantID := r.URL.Query().Get("tenant_id")
|
||||
if p, ok := authn.PrincipalFrom(r.Context()); ok && p.IsUser() {
|
||||
// A user token revokes only its holder's integration keys, in its
|
||||
// own tenant.
|
||||
holder, ok := integrationCaller(w, p, tenantID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
tenantID = p.TenantID
|
||||
keys, err := s.integrationKeys(ctx, tenantID, holder)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
if !slices.ContainsFunc(keys, func(k store.APIKey) bool { return k.ID == id }) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "api key not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.Store.RevokeAPIKey(ctx, id, tenantID); err != nil {
|
||||
if mapStoreError(w, err) {
|
||||
return
|
||||
@@ -284,8 +316,7 @@ func (s *Server) verifyAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
// sha256 (indexed), older ones by prefix + argon2id. Prefixes are not
|
||||
// unique, so every active candidate is checked.
|
||||
func (s *Server) findAPIKey(ctx context.Context, plain string) (*store.APIKey, error) {
|
||||
sum := sha256.Sum256([]byte(plain))
|
||||
k, err := s.Store.FindAPIKeyBySHA256(ctx, sum[:])
|
||||
k, err := s.Store.FindAPIKeyBySHA256(ctx, hashKey(plain))
|
||||
if err == nil || !errors.Is(err, store.ErrNotFound) {
|
||||
return k, err
|
||||
}
|
||||
@@ -328,6 +359,12 @@ func (s *Server) entitledProducts(ctx context.Context, tenantID string) (map[str
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
// hashKey is the stored form of keys since migration 0015.
|
||||
func hashKey(plain string) []byte {
|
||||
sum := sha256.Sum256([]byte(plain))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
func generateAPIKey() (string, error) {
|
||||
buf := make([]byte, keyEntropyBy)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/scopes"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// ─── integration keys (ADR 0001 §6) ───────────────────────────────────────
|
||||
//
|
||||
// A product that acts for a tenant without a person present (Werkmeister's
|
||||
// scheduled and triggered runs) holds one key per tenant. It is created with
|
||||
// the token of the tenant's admin, through the product's web client: the
|
||||
// registry checks tenant, role, holder and scopes itself, so no service
|
||||
// client gains cross-tenant power. AUTHZ group: api-keys.integration (a user
|
||||
// token on any /v1/api-keys route is classified so, see requireAuthz).
|
||||
|
||||
// integrationScopes is the allowlist per holder product.
|
||||
var integrationScopes = map[string][]string{
|
||||
"werkmeister": {
|
||||
"firmwerk:projects.read", "firmwerk:projects.write",
|
||||
"pruefwerk:enisa.read", "pruefwerk:findings.read", "pruefwerk:findings.write",
|
||||
"pruefwerk:sbom.read", "pruefwerk:scans.read", "pruefwerk:scans.run",
|
||||
},
|
||||
}
|
||||
|
||||
// integrationHolder maps a web client id (azp) to the holder product:
|
||||
// "werkmeister-stage" → "werkmeister". Empty when the client may not hold
|
||||
// integration keys.
|
||||
func integrationHolder(azp string) string {
|
||||
h := azp
|
||||
for _, env := range []string{"-stage", "-prod", "-dev"} {
|
||||
h = strings.TrimSuffix(h, env)
|
||||
}
|
||||
if _, ok := integrationScopes[h]; !ok {
|
||||
return ""
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// integrationCaller checks a user principal for the integration routes and
|
||||
// returns its holder; on failure it has written the response.
|
||||
func integrationCaller(w http.ResponseWriter, p *authn.Principal, tenantID string) (string, bool) {
|
||||
holder := integrationHolder(p.ClientID)
|
||||
if holder == "" {
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN_CLIENT", "client "+p.ClientID+" may not hold integration keys")
|
||||
return "", false
|
||||
}
|
||||
if !p.IsTenantAdmin() {
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "only a tenant admin may manage integration keys")
|
||||
return "", false
|
||||
}
|
||||
if tenantID != "" && tenantID != p.TenantID {
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN_TENANT", "integration keys only for your own tenant")
|
||||
return "", false
|
||||
}
|
||||
return holder, true
|
||||
}
|
||||
|
||||
func (s *Server) createIntegrationKey(w http.ResponseWriter, r *http.Request, p *authn.Principal, in createAPIKeyReq) {
|
||||
holder, ok := integrationCaller(w, p, in.TenantID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if in.Kind != "" && in.Kind != store.APIKeyKindIntegration {
|
||||
writeError(w, http.StatusBadRequest, "invalid_kind", "a user token creates integration keys only")
|
||||
return
|
||||
}
|
||||
if in.Name != "" && in.Name != holder {
|
||||
writeError(w, http.StatusBadRequest, "invalid_name", "an integration key is named after its holder ("+holder+")")
|
||||
return
|
||||
}
|
||||
if in.ExpiresAt != nil || in.Product != "" {
|
||||
writeError(w, http.StatusBadRequest, "invalid_input", "integration keys take no product and no expiry")
|
||||
return
|
||||
}
|
||||
if len(in.Scopes) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "invalid_scopes", "integration keys need at least one scope")
|
||||
return
|
||||
}
|
||||
norm, err := scopes.Validate(in.Scopes, "")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_scopes", err.Error())
|
||||
return
|
||||
}
|
||||
for _, sc := range norm {
|
||||
if !slices.Contains(integrationScopes[holder], sc) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_scopes", "scope "+sc+" is not allowed for "+holder)
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
entitled, _, err := s.entitledProducts(ctx, p.TenantID)
|
||||
if err != nil {
|
||||
if mapStoreError(w, err) {
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
for _, prod := range append(scopes.Products(norm), holder) {
|
||||
if !entitled[prod] {
|
||||
writeError(w, http.StatusUnprocessableEntity, "not_entitled", "tenant is not entitled to "+prod)
|
||||
return
|
||||
}
|
||||
}
|
||||
plain, err := generateAPIKey()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", "key generation failed")
|
||||
return
|
||||
}
|
||||
sum := hashKey(plain)
|
||||
createdBy := p.Email
|
||||
if createdBy == "" {
|
||||
createdBy = p.Subject
|
||||
}
|
||||
k, err := s.Store.CreateAPIKey(ctx, store.APIKeyCreate{
|
||||
TenantID: p.TenantID, Name: holder, Scopes: norm, Prefix: plain[:prefixLen], HashSHA256: sum,
|
||||
Kind: store.APIKeyKindIntegration, Holder: holder, CreatedBy: createdBy,
|
||||
})
|
||||
if err != nil {
|
||||
if mapStoreError(w, err) {
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
s.emitAudit(ctx, r, store.AuditEvent{
|
||||
TenantID: p.TenantID, Action: "api_key.created", TargetID: k.ID, TargetType: "api_key", TargetName: holder,
|
||||
Metadata: map[string]interface{}{"scopes": norm, "kind": store.APIKeyKindIntegration, "holder": holder},
|
||||
})
|
||||
writeJSON(w, http.StatusCreated, createAPIKeyResp{
|
||||
APIKey: *k, Plaintext: plain, WarningMsg: "Store this value now — it cannot be retrieved later.",
|
||||
})
|
||||
}
|
||||
|
||||
// integrationKeys lists the caller holder's integration keys of its tenant.
|
||||
func (s *Server) integrationKeys(ctx context.Context, tenantID, holder string) ([]store.APIKey, error) {
|
||||
all, err := s.Store.ListAPIKeys(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []store.APIKey{}
|
||||
for _, k := range all {
|
||||
if k.Kind == store.APIKeyKindIntegration && k.Holder == holder {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
const integrationRules = "werkmeister-stage:api-keys.integration;werkmeister-svc-stage:entitlements;portal-svc:*"
|
||||
|
||||
func wmAdmin(tenantID string, roles ...string) *authn.Principal {
|
||||
if len(roles) == 0 {
|
||||
roles = []string{"IT_ADMIN"}
|
||||
}
|
||||
return &authn.Principal{Subject: "u-admin", ClientID: "werkmeister-stage", TenantID: tenantID, Email: "admin@acme.test", OrgRoles: roles}
|
||||
}
|
||||
|
||||
func integrationFixture(t *testing.T, p func(tenantID string) *authn.Principal, bookWerkmeister bool) *teamFixture {
|
||||
t.Helper()
|
||||
// The principal needs the tenant id, which the fixture creates.
|
||||
var principal authn.Principal
|
||||
f := newTeamFixture(t, &principal, integrationRules)
|
||||
principal = *p(f.tenant.ID)
|
||||
if bookWerkmeister {
|
||||
if _, err := f.s.Store.UpsertTenantProduct(context.Background(), store.TenantProduct{
|
||||
TenantID: f.tenant.ID, Product: "werkmeister", Enabled: true, Config: map[string]interface{}{},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func createIntegration(t *testing.T, f *teamFixture, body string) (int, string) {
|
||||
t.Helper()
|
||||
code, _, raw := f.call(t, "POST", "/v1/api-keys", body, nil)
|
||||
return code, raw
|
||||
}
|
||||
|
||||
func TestIntegrationKey_createdByTenantAdmin(t *testing.T) {
|
||||
f := integrationFixture(t, func(id string) *authn.Principal { return wmAdmin(id) }, true)
|
||||
code, raw := createIntegration(t, f, `{"tenant_id":"`+f.tenant.ID+`","scopes":["pruefwerk:findings.read","pruefwerk:scans.run"]}`)
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("create: %d %s", code, raw)
|
||||
}
|
||||
var out createAPIKeyResp
|
||||
_ = json.Unmarshal([]byte(raw), &out)
|
||||
k := out.APIKey
|
||||
if k.Kind != store.APIKeyKindIntegration || k.Holder != "werkmeister" || k.Name != "werkmeister" || k.TenantID != f.tenant.ID || k.CreatedBy != "admin@acme.test" {
|
||||
t.Fatalf("key %+v", k)
|
||||
}
|
||||
if !strings.HasPrefix(out.Plaintext, "bp_") {
|
||||
t.Fatal("no plaintext")
|
||||
}
|
||||
// One key per tenant and holder: re-issue is revoke, then create.
|
||||
if code, _ := createIntegration(t, f, `{"scopes":["pruefwerk:findings.read"]}`); code != http.StatusConflict {
|
||||
t.Fatalf("second create: %d, want 409", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationKey_refusals(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
p func(string) *authn.Principal
|
||||
book bool
|
||||
body func(tenantID string) string
|
||||
want int
|
||||
}{
|
||||
{"werkmeister not booked", func(id string) *authn.Principal { return wmAdmin(id) }, false,
|
||||
func(string) string { return `{"scopes":["pruefwerk:findings.read"]}` }, http.StatusUnprocessableEntity},
|
||||
{"not an admin", func(id string) *authn.Principal { return wmAdmin(id, "FINANCE") }, true,
|
||||
func(string) string { return `{"scopes":["pruefwerk:findings.read"]}` }, http.StatusForbidden},
|
||||
{"other tenant", func(id string) *authn.Principal { return wmAdmin(id) }, true,
|
||||
func(string) string {
|
||||
return `{"tenant_id":"00000000-0000-0000-0000-0000000000ff","scopes":["pruefwerk:findings.read"]}`
|
||||
}, http.StatusForbidden},
|
||||
{"scope outside the allowlist", func(id string) *authn.Principal { return wmAdmin(id) }, true,
|
||||
func(string) string { return `{"scopes":["werkbank:runner"]}` }, http.StatusBadRequest},
|
||||
{"no scopes", func(id string) *authn.Principal { return wmAdmin(id) }, true,
|
||||
func(string) string { return `{}` }, http.StatusBadRequest},
|
||||
{"wrong kind", func(id string) *authn.Principal { return wmAdmin(id) }, true,
|
||||
func(string) string { return `{"kind":"ci","scopes":["pruefwerk:findings.read"]}` }, http.StatusBadRequest},
|
||||
{"client without AUTHZ group", func(id string) *authn.Principal {
|
||||
p := wmAdmin(id)
|
||||
p.ClientID = "portal-stage"
|
||||
return p
|
||||
}, true, func(string) string { return `{"scopes":["pruefwerk:findings.read"]}` }, http.StatusForbidden},
|
||||
{"service client of the product", func(string) *authn.Principal {
|
||||
return &authn.Principal{Subject: "svc", ClientID: "werkmeister-svc-stage"}
|
||||
}, true, func(id string) string {
|
||||
return `{"tenant_id":"` + id + `","name":"x","scopes":["pruefwerk:findings.read"]}`
|
||||
}, http.StatusForbidden},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := integrationFixture(t, tc.p, tc.book)
|
||||
if code, raw := createIntegration(t, f, tc.body(f.tenant.ID)); code != tc.want {
|
||||
t.Fatalf("status %d, want %d: %s", code, tc.want, raw)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationKey_listAndRevokeOwnOnly(t *testing.T) {
|
||||
f := integrationFixture(t, func(id string) *authn.Principal { return wmAdmin(id) }, true)
|
||||
ctx := context.Background()
|
||||
legacy, err := f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "portal-key", Prefix: "bp_legacy01", HashSHA256: hashKey("bp_legacy01xxxxxxxxxxxxxxxxxxxxxx")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, raw := createIntegration(t, f, `{"scopes":["pruefwerk:findings.read"]}`)
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("create: %d %s", code, raw)
|
||||
}
|
||||
var created createAPIKeyResp
|
||||
_ = json.Unmarshal([]byte(raw), &created)
|
||||
|
||||
code, _, raw = f.call(t, "GET", "/v1/api-keys?tenant_id="+f.tenant.ID, "", nil)
|
||||
var list struct{ Items []store.APIKey }
|
||||
_ = json.Unmarshal([]byte(raw), &list)
|
||||
if code != http.StatusOK || len(list.Items) != 1 || list.Items[0].ID != created.APIKey.ID {
|
||||
t.Fatalf("list: %d %s", code, raw)
|
||||
}
|
||||
if code, _, _ := f.call(t, "GET", "/v1/api-keys?tenant_id=00000000-0000-0000-0000-0000000000ff", "", nil); code != http.StatusForbidden {
|
||||
t.Fatalf("list other tenant: %d", code)
|
||||
}
|
||||
if code, _, _ := f.call(t, "DELETE", "/v1/api-keys/"+legacy.ID, "", nil); code != http.StatusNotFound {
|
||||
t.Fatalf("revoke a portal key with a user token: %d, want 404", code)
|
||||
}
|
||||
if code, _, _ := f.call(t, "DELETE", "/v1/api-keys/"+created.APIKey.ID, "", nil); code != http.StatusNoContent {
|
||||
t.Fatalf("revoke own integration key: %d", code)
|
||||
}
|
||||
if code, _ := createIntegration(t, f, `{"scopes":["pruefwerk:findings.read"]}`); code != http.StatusCreated {
|
||||
t.Fatalf("re-issue after revoke: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationHolder(t *testing.T) {
|
||||
for azp, want := range map[string]string{
|
||||
"werkmeister-stage": "werkmeister", "werkmeister-prod": "werkmeister", "werkmeister": "werkmeister",
|
||||
"portal-stage": "", "werkmeister-svc-stage": "", "": "",
|
||||
} {
|
||||
if got := integrationHolder(azp); got != want {
|
||||
t.Errorf("integrationHolder(%q) = %q, want %q", azp, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,3 +229,21 @@ func sha256Sum(s string) []byte {
|
||||
sum := sha256.Sum256([]byte(s))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
func TestAPIKey_nameReusableAfterRevoke(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
code, k, _ := createKey(t, h, map[string]any{"name": "deploy"})
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("create: %d", code)
|
||||
}
|
||||
if code, _, _ := createKey(t, h, map[string]any{"name": "deploy"}); code != http.StatusConflict {
|
||||
t.Fatalf("duplicate active name: %d, want 409", code)
|
||||
}
|
||||
if resp, _ := h.do("DELETE", "/v1/api-keys/"+k.ID, nil); resp.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("revoke: %d", resp.StatusCode)
|
||||
}
|
||||
if code, _, body := createKey(t, h, map[string]any{"name": "deploy"}); code != http.StatusCreated {
|
||||
t.Fatalf("reuse after revoke: %d %s", code, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -125,6 +125,12 @@ func (s *Server) requireAuthz(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
group := routeGroup(r.Method, r.URL.Path)
|
||||
// A user token on the key routes can only reach the integration
|
||||
// path (apikeys_integration.go), which checks tenant and role
|
||||
// itself; plain "api-keys" (any tenant) stays a service grant.
|
||||
if group == "api-keys" && p.IsUser() {
|
||||
group = "api-keys.integration"
|
||||
}
|
||||
if !s.Authz.Allowed(p.ClientID, group) {
|
||||
s.Log.Warn("client not authorized for route group", "azp", p.ClientID, "group", group, "path", r.URL.Path)
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN_CLIENT", "client "+p.ClientID+" may not call "+group)
|
||||
|
||||
@@ -150,7 +150,7 @@ func (s *Server) issue(ctx context.Context, r *http.Request, in issueLicenceReq,
|
||||
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)
|
||||
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, "", ""
|
||||
@@ -160,7 +160,8 @@ func (s *Server) issue(ctx context.Context, r *http.Request, in issueLicenceReq,
|
||||
// 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 {
|
||||
// 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 ""
|
||||
}
|
||||
@@ -188,6 +189,7 @@ func (s *Server) provisionLLMKey(ctx context.Context, t *store.Tenant, row *stor
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
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 "<product>: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
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/secretbox"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
type ciLicence struct {
|
||||
ID string `json:"id"`
|
||||
Licence string `json:"licence"`
|
||||
Warnings []string `json:"warnings"`
|
||||
}
|
||||
|
||||
func postCI(t *testing.T, h *testHarness, key, product, device string) (int, ciLicence, string) {
|
||||
t.Helper()
|
||||
buf, _ := json.Marshal(map[string]string{"product": product, "device": device})
|
||||
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/licences/ci", bytes.NewReader(buf))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if key != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+key)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
var out ciLicence
|
||||
_ = json.Unmarshal(body, &out)
|
||||
return resp.StatusCode, out, string(body)
|
||||
}
|
||||
|
||||
func jwtClaims(t *testing.T, token string) map[string]any {
|
||||
t.Helper()
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
t.Fatalf("not a JWT: %q", token)
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var c map[string]any
|
||||
_ = json.Unmarshal(raw, &c)
|
||||
return c
|
||||
}
|
||||
|
||||
func ciKey(t *testing.T, h *testHarness, name string, scopes ...string) string {
|
||||
t.Helper()
|
||||
code, _, plain := createKey(t, h, map[string]any{
|
||||
"name": name, "kind": "ci", "scopes": scopes,
|
||||
"expires_at": time.Now().Add(30 * 24 * time.Hour).UTC().Format(time.RFC3339),
|
||||
})
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("create ci key: %d %s", code, plain)
|
||||
}
|
||||
return plain
|
||||
}
|
||||
|
||||
func TestCILicence_issuedOncePerKeyDeviceAndDay(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
entitle(t, h, "firmwerk", true)
|
||||
key := ciKey(t, h, "fw-ci", "firmwerk:licence")
|
||||
|
||||
code, first, body := postCI(t, h, key, "firmwerk", "runner-1")
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("first: %d %s", code, body)
|
||||
}
|
||||
c := jwtClaims(t, first.Licence)
|
||||
if c["kind"] != "ci" || c["device"] != "ci:runner-1" || !strings.HasPrefix(c["sub"].(string), "apikey:") || c["heartbeat_url"] != nil {
|
||||
t.Fatalf("claims %v", c)
|
||||
}
|
||||
if exp := time.Unix(int64(c["exp"].(float64)), 0); exp.After(time.Now().Add(25 * time.Hour)) {
|
||||
t.Fatalf("CI licence lives too long: %v", exp)
|
||||
}
|
||||
|
||||
code, again, _ := postCI(t, h, key, "firmwerk", "runner-1")
|
||||
if code != http.StatusOK || again.ID != first.ID {
|
||||
t.Fatalf("same key/device/day must reuse the licence: %d %s vs %s", code, again.ID, first.ID)
|
||||
}
|
||||
code, other, _ := postCI(t, h, key, "firmwerk", "runner-2")
|
||||
if code != http.StatusCreated || other.ID == first.ID {
|
||||
t.Fatalf("another device gets its own licence: %d", code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCILicence_refusals(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
entitle(t, h, "firmwerk", true)
|
||||
entitle(t, h, "pruefwerk", true)
|
||||
_, _, legacy := createKey(t, h, map[string]any{"name": "legacy"})
|
||||
wrong := ciKey(t, h, "pf-ci", "pruefwerk:scans.run")
|
||||
fw := ciKey(t, h, "fw-ci", "firmwerk:licence")
|
||||
cases := []struct {
|
||||
name, key, product string
|
||||
want int
|
||||
}{
|
||||
{"no key", "", "firmwerk", http.StatusUnauthorized},
|
||||
{"unknown key", "bp_unknownunknownunknownunknown00", "firmwerk", http.StatusUnauthorized},
|
||||
{"legacy key without scope", legacy, "firmwerk", http.StatusForbidden},
|
||||
{"key without licence scope", wrong, "firmwerk", http.StatusForbidden},
|
||||
{"scope for another product", fw, "werkpilot", http.StatusForbidden},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if code, _, body := postCI(t, h, tc.key, tc.product, "runner"); code != tc.want {
|
||||
t.Errorf("%s: %d, want %d (%s)", tc.name, code, tc.want, body)
|
||||
}
|
||||
}
|
||||
// The booking ends: the key no longer fetches licences.
|
||||
entitle(t, h, "firmwerk", false)
|
||||
if code, _, _ := postCI(t, h, fw, "firmwerk", "runner"); code != http.StatusForbidden {
|
||||
t.Errorf("after the booking ended: %d, want 403", code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func wpCall(t *testing.T, h *testHarness, key, device string) (int, licenceLLMOut) {
|
||||
t.Helper()
|
||||
buf, _ := json.Marshal(map[string]string{"product": "werkpilot", "device": device})
|
||||
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/licences/ci", bytes.NewReader(buf))
|
||||
req.Header.Set("Authorization", "Bearer "+key)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
var out licenceLLMOut
|
||||
_ = json.NewDecoder(resp.Body).Decode(&out)
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
func testBox(t *testing.T) *secretbox.Box {
|
||||
t.Helper()
|
||||
b, err := secretbox.New(base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Decision D2: a Werkpilot CI licence carries the tenant's LiteLLM key
|
||||
// (expiring in LiteLLM after a day). The reused licence hands out the same
|
||||
// key again from its sealed copy; another device gets its own key.
|
||||
func TestCILicence_werkpilotReusesSealedLLMKey(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
fake := newFakeLiteLLM(t)
|
||||
h.app.LLMKeys = fake.client()
|
||||
h.app.Secrets = testBox(t)
|
||||
entitle(t, h, "werkpilot", true)
|
||||
key := ciKey(t, h, "wp-ci", "werkpilot:licence")
|
||||
|
||||
code, first := wpCall(t, h, key, "runner-1")
|
||||
if code != http.StatusCreated || !strings.HasPrefix(first.LLMAPIKey, "sk-fake-") || len(first.Warnings) != 0 {
|
||||
t.Fatalf("first: %d %+v", code, first)
|
||||
}
|
||||
code, again := wpCall(t, h, key, "runner-1")
|
||||
if code != http.StatusOK || again.ID != first.ID || again.LLMAPIKey != first.LLMAPIKey || again.LLMBaseURL == "" {
|
||||
t.Fatalf("reuse must return the same key: %d %+v", code, again)
|
||||
}
|
||||
code, other := wpCall(t, h, key, "runner-2")
|
||||
if code != http.StatusCreated || other.LLMAPIKey == "" || other.LLMAPIKey == first.LLMAPIKey {
|
||||
t.Fatalf("second device: %d %+v", code, other)
|
||||
}
|
||||
fake.mu.Lock()
|
||||
defer fake.mu.Unlock()
|
||||
if len(fake.gen) != 2 || fake.gen[0]["duration"] != "1d" {
|
||||
t.Fatalf("LiteLLM generate calls: %v", fake.gen)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCILicence_werkpilotWithoutEncryptionKey(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
fake := newFakeLiteLLM(t)
|
||||
h.app.LLMKeys = fake.client()
|
||||
entitle(t, h, "werkpilot", true)
|
||||
key := ciKey(t, h, "wp-ci", "werkpilot:licence")
|
||||
if code, first := wpCall(t, h, key, "runner"); code != http.StatusCreated || first.LLMAPIKey == "" {
|
||||
t.Fatalf("first: %d %+v", code, first)
|
||||
}
|
||||
code, again := wpCall(t, h, key, "runner")
|
||||
if code != http.StatusOK || again.LLMAPIKey != "" || len(again.Warnings) != 1 || again.Warnings[0] != "llm_key_not_repeatable" {
|
||||
t.Fatalf("reuse without SECRETS_ENCRYPTION_KEY: %d %+v", code, again)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCILicence_werkpilotDailyKeyCap(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
fake := newFakeLiteLLM(t)
|
||||
h.app.LLMKeys = fake.client()
|
||||
h.app.Secrets = testBox(t)
|
||||
entitle(t, h, "werkpilot", true)
|
||||
key := ciKey(t, h, "wp-ci", "werkpilot:licence")
|
||||
for i := 0; i < 10; i++ {
|
||||
if code, out := wpCall(t, h, key, "runner-"+string(rune('a'+i))); code != http.StatusCreated || out.LLMAPIKey == "" {
|
||||
t.Fatalf("device %d: %d %+v", i, code, out)
|
||||
}
|
||||
}
|
||||
code, out := wpCall(t, h, key, "runner-z")
|
||||
if code != http.StatusCreated || out.LLMAPIKey != "" || len(out.Warnings) != 1 || out.Warnings[0] != "llm_key_daily_cap" {
|
||||
t.Fatalf("11th device: %d %+v", code, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCILicence_recordsUsageNotSeat(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
entitle(t, h, "firmwerk", true)
|
||||
key := ciKey(t, h, "fw-ci", "firmwerk:licence")
|
||||
for _, d := range []string{"a", "b", "a"} {
|
||||
if code, _, body := postCI(t, h, key, "firmwerk", d); code >= 300 {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
}
|
||||
evs, err := h.store.ListUsageEvents(context.Background(), store.UsageFilter{TenantID: h.tenant.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n := 0
|
||||
for _, ev := range evs {
|
||||
if ev.Metric == "ci.licence" {
|
||||
n++
|
||||
}
|
||||
if ev.Metric == "seat.login" {
|
||||
t.Error("a CI licence must not record a seat")
|
||||
}
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("ci.licence events: %d, want 1 per key and day", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCILicence_rateLimitedPerKey(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
entitle(t, h, "firmwerk", true)
|
||||
key := ciKey(t, h, "fw-ci", "firmwerk:licence")
|
||||
for i := 0; i < 60; i++ {
|
||||
if code, _, body := postCI(t, h, key, "firmwerk", "runner"); code >= 300 {
|
||||
t.Fatalf("call %d: %d %s", i+1, code, body)
|
||||
}
|
||||
}
|
||||
if code, _, _ := postCI(t, h, key, "firmwerk", "runner"); code != http.StatusTooManyRequests {
|
||||
t.Fatalf("61st call: %d, want 429", code)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -78,6 +78,7 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
|
||||
{"GET", "/v1/usage/events?tenant_id=00000000-0000-0000-0000-000000000001"},
|
||||
{"POST", "/v1/licences"},
|
||||
{"POST", "/v1/licences/heartbeat"},
|
||||
{"POST", "/v1/licences/ci"},
|
||||
{"POST", "/v1/licences/00000000-0000-0000-0000-000000000001/revoke"},
|
||||
{"GET", "/.well-known/licence-keys.json"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/managed-services"},
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"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/secretbox"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
@@ -34,14 +35,17 @@ type Server struct {
|
||||
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)
|
||||
Objects storage.Objects // nil ⇒ document routes answer 503 (F2)
|
||||
Mail mail.Sender // nil ⇒ notifications queue up unsent (F3)
|
||||
Now func() time.Time // injectable clock (tests); nil ⇒ time.Now
|
||||
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)
|
||||
// Secrets seals CI licences' LiteLLM keys for reuse; nil ⇒ not stored.
|
||||
Secrets *secretbox.Box
|
||||
Objects storage.Objects // nil ⇒ document routes answer 503 (F2)
|
||||
Mail mail.Sender // nil ⇒ notifications queue up unsent (F3)
|
||||
Now func() time.Time // injectable clock (tests); nil ⇒ time.Now
|
||||
|
||||
blocks blockCache // MemberBlocked answers for user tokens (team.go)
|
||||
blocks blockCache // MemberBlocked answers for user tokens (team.go)
|
||||
ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go)
|
||||
}
|
||||
|
||||
func (s *Server) now() time.Time {
|
||||
@@ -95,6 +99,9 @@ func NewRouter(s *Server) http.Handler {
|
||||
root.HandleFunc("GET /v1/legal/trial-terms", s.legalTrialTerms)
|
||||
root.HandleFunc("GET /v1/legal/trial-terms/{file}", s.legalTrialTermsFile)
|
||||
root.HandleFunc("POST /v1/licences/heartbeat", s.licenceHeartbeat)
|
||||
// PUBLIC_EXPLICIT: CI licences are authenticated by the tenant API key in
|
||||
// the Authorization header (scope <product>:licence), checked in the handler.
|
||||
root.HandleFunc("POST /v1/licences/ci", s.issueCILicence)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
|
||||
@@ -369,7 +369,7 @@ func (m *Memory) CreateAPIKey(_ context.Context, in APIKeyCreate) (*APIKey, erro
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
for _, k := range m.apiKeys {
|
||||
if k.TenantID == in.TenantID && k.Name == in.Name {
|
||||
if k.TenantID == in.TenantID && k.Name == in.Name && k.RevokedAt == nil {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
if len(in.HashSHA256) > 0 && bytes.Equal(k.HashSHA256, in.HashSHA256) {
|
||||
|
||||
@@ -272,6 +272,26 @@ func (m *Memory) GetLicence(_ context.Context, id string) (*Licence, error) {
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (m *Memory) FindReusableLicence(_ context.Context, tenantID, product, subject, device string, since, now time.Time) (*Licence, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
var best *Licence
|
||||
for _, l := range m.licences {
|
||||
if l.TenantID != tenantID || l.Product != product || l.Subject != subject || l.Device != device ||
|
||||
l.CreatedAt.Before(since) || !l.ExpiresAt.After(now) || l.RevokedAt != nil {
|
||||
continue
|
||||
}
|
||||
if best == nil || l.CreatedAt.After(best.CreatedAt) {
|
||||
best = l
|
||||
}
|
||||
}
|
||||
if best == nil {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
cp := *best
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListLicences(_ context.Context, tenantID string) ([]Licence, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
@@ -319,6 +339,17 @@ func (m *Memory) TouchLicence(_ context.Context, id string, at time.Time) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) SetLicenceLLMSecret(_ context.Context, id string, sealed []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
l, ok := m.licences[id]
|
||||
if !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
l.LLMKeySecret = append([]byte(nil), sealed...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) SetLicenceLLMKey(_ context.Context, id string, keyID string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
@@ -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, COALESCE(llm_key_id, '')
|
||||
SELECT id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at, COALESCE(llm_key_id, ''), llm_key_secret_enc
|
||||
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, &l.LLMKeyID)
|
||||
err := row.Scan(&l.ID, &l.Kid, &l.TenantID, &l.Product, &l.Subject, &l.Device, &l.ExpiresAt, &revoked, &seen, &l.CreatedAt, &l.LLMKeyID, &l.LLMKeySecret)
|
||||
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, COALESCE(llm_key_id, '')`,
|
||||
RETURNING id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at, COALESCE(llm_key_id, ''), llm_key_secret_enc`,
|
||||
id, l.Kid, l.TenantID, l.Product, l.Subject, l.Device, l.ExpiresAt))
|
||||
if err != nil {
|
||||
if isFKViolation(err) || isInvalidUUID(err) {
|
||||
@@ -373,6 +373,13 @@ func (p *Postgres) GetLicence(ctx context.Context, id string) (*Licence, error)
|
||||
return l, err
|
||||
}
|
||||
|
||||
func (p *Postgres) FindReusableLicence(ctx context.Context, tenantID, product, subject, device string, since, now time.Time) (*Licence, error) {
|
||||
return scanLicence(p.pool.QueryRow(ctx, licenceSelect+`
|
||||
WHERE tenant_id = $1::uuid AND product = $2 AND subject = $3 AND device = $4
|
||||
AND created_at >= $5 AND expires_at > $6 AND revoked_at IS NULL
|
||||
ORDER BY created_at DESC LIMIT 1`, tenantID, product, subject, device, since, now))
|
||||
}
|
||||
|
||||
func (p *Postgres) ListLicences(ctx context.Context, tenantID string) ([]Licence, error) {
|
||||
if _, err := p.GetTenant(ctx, tenantID); err != nil {
|
||||
return nil, err
|
||||
@@ -407,6 +414,20 @@ func (p *Postgres) RevokeLicence(ctx context.Context, id string, at time.Time) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Postgres) SetLicenceLLMSecret(ctx context.Context, id string, sealed []byte) error {
|
||||
tag, err := p.pool.Exec(ctx, `UPDATE licences SET llm_key_secret_enc = $2 WHERE id = $1::uuid`, id, sealed)
|
||||
if err != nil {
|
||||
if isInvalidUUID(err) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
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 {
|
||||
|
||||
@@ -138,10 +138,17 @@ type Store interface {
|
||||
CreateLicence(ctx context.Context, l Licence) (*Licence, error)
|
||||
GetLicence(ctx context.Context, id string) (*Licence, error)
|
||||
ListLicences(ctx context.Context, tenantID string) ([]Licence, error)
|
||||
// FindReusableLicence returns the newest licence for (tenant, product,
|
||||
// subject, device) created at or after since that is neither revoked
|
||||
// nor expired at now; ErrNotFound otherwise. CI licences are reused
|
||||
// per key, device and UTC day instead of one row per job.
|
||||
FindReusableLicence(ctx context.Context, tenantID, product, subject, device string, since, now time.Time) (*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
|
||||
// SetLicenceLLMSecret stores the sealed LiteLLM secret of a CI licence.
|
||||
SetLicenceLLMSecret(ctx context.Context, id string, sealed []byte) error
|
||||
|
||||
// Documents (0008). ID and ObjectKey are chosen by the caller (the object
|
||||
// is stored before the row). ListDocuments with publishedOnly hides drafts.
|
||||
|
||||
@@ -254,6 +254,9 @@ type Licence struct {
|
||||
// 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"`
|
||||
// LLMKeySecret — the sealed LiteLLM secret of a CI licence (migration
|
||||
// 0017), so a reused CI licence can hand it out again. Never serialised.
|
||||
LLMKeySecret []byte `json:"-"`
|
||||
}
|
||||
|
||||
// Document — a file BreakPilot hands to a tenant (migration 0008). Staff
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Fails if a revoked and an active key share a name; rename one first.
|
||||
DROP INDEX IF EXISTS api_keys_tenant_name_active_idx;
|
||||
ALTER TABLE api_keys ADD CONSTRAINT api_keys_tenant_id_name_key UNIQUE (tenant_id, name);
|
||||
@@ -0,0 +1,4 @@
|
||||
-- A key name is unique among a tenant's ACTIVE keys only, so a revoked key's
|
||||
-- name can be reused (re-issuing an integration key = revoke, then create).
|
||||
ALTER TABLE api_keys DROP CONSTRAINT api_keys_tenant_id_name_key;
|
||||
CREATE UNIQUE INDEX api_keys_tenant_name_active_idx ON api_keys (tenant_id, name) WHERE revoked_at IS NULL;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE licences DROP COLUMN llm_key_secret_enc;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- A CI licence's LiteLLM key is handed out again when the licence is reused
|
||||
-- (same API key, device and UTC day; ADR 0001 §5). The secret is stored
|
||||
-- AES-256-GCM sealed under SECRETS_ENCRYPTION_KEY, bound to the licence id.
|
||||
ALTER TABLE licences ADD COLUMN llm_key_secret_enc BYTEA;
|
||||
+43
-1
@@ -1493,6 +1493,48 @@ paths:
|
||||
"401": { description: "Signature invalid or licence unknown." }
|
||||
"503": { description: Licence signer not configured. }
|
||||
|
||||
/v1/licences/ci:
|
||||
post:
|
||||
summary: CI licence (PUBLIC_EXPLICIT — a tenant API key is the credential).
|
||||
description: |
|
||||
For CI jobs without a browser (ADR 0001 §5). The bearer is a registry
|
||||
API key with scope `<product>:licence`; the tenant comes from the key.
|
||||
The licence lives 24 h, carries `kind: ci`, has no heartbeat and is
|
||||
not a seat. A repeat for the same key, device and UTC day returns the
|
||||
existing licence (200) — except Werkpilot, whose licence carries a
|
||||
LiteLLM key (expiring after 1 day) and is issued fresh each call.
|
||||
At most 60 calls per key and hour.
|
||||
security: []
|
||||
parameters:
|
||||
- in: header
|
||||
name: Authorization
|
||||
required: true
|
||||
schema: { type: string, example: "Bearer bp_…" }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [product, device]
|
||||
properties:
|
||||
product: { type: string }
|
||||
device: { type: string, maxLength: 200, description: "runner name; stored as ci:<device>" }
|
||||
responses:
|
||||
"200":
|
||||
description: The licence already issued today for this key and device.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/LicenceIssued" } }
|
||||
"201":
|
||||
description: Issued.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/LicenceIssued" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"401": { description: "API key missing, unknown, revoked or expired." }
|
||||
"403": { description: "Scope <product>:licence missing or product not booked." }
|
||||
"429": { description: "More than 60 calls for this key in the last hour." }
|
||||
"503": { description: Licence signer not configured. }
|
||||
|
||||
/.well-known/licence-keys.json:
|
||||
get:
|
||||
summary: Licence verification keys (JWKS, OKP/Ed25519). PUBLIC_EXPLICIT.
|
||||
@@ -1992,7 +2034,7 @@ components:
|
||||
project_id: { type: string, format: uuid }
|
||||
actor_id: { type: string }
|
||||
actor_name: { type: string }
|
||||
actor_type: { type: string }
|
||||
actor_type: { type: string, description: "user | service | staff | system | apikey (actor_id apikey:<key_id>)" }
|
||||
action: { type: string }
|
||||
target_id: { type: string }
|
||||
target_type: { type: string }
|
||||
|
||||
Reference in new issue
Block a user