Files
tenant-registry/internal/server/licences_ci.go
sharangandSharang Parnerkar c6de35858e
ci / shared (push) Successful in 12s
ci / test (push) Successful in 6m30s
ci / image (push) Successful in 38s
feat(connections): connect two workspaces by code (#138) (#145)
## What

- **Codes:** two workspaces connect by code. One administrator creates a code; another workspace's administrator enters it, and the two are connected at once. Each side sees only the other's display name.
- **Ending:** either side can end a connection. Archiving a workspace ends all of its connections. When a workspace is purged, the other side keeps the ended connection under the name it knew.
- **Product routes:** products (Prüfwerk's supplier SBOM releases first) list a tenant's active connections and check one before each delivery, under a new route group `connections.read`.

## Why

Closes #138. This is phase 4 of platform/pruefwerk#1028. Prüfwerk's agent is on stage and already calls the two internal routes; without them the release screen warns that connections can't be read (see the comment on #138).

Linked milestone: **n/a** (Prüfwerk #1028, phase 4)

## How

**Routes:**

| Call | Group | Answer |
|---|---|---|
| `POST /v1/tenants/{id}/connection-invites` | tenants.write | `201 {id, code, created_at, expires_at}`; the code is in this answer only |
| `GET /v1/tenants/{id}/connection-invites` | tenants.read | open codes, without the codes |
| `DELETE /v1/tenants/{id}/connection-invites/{invite}` | tenants.write | `204`, withdraws an unused code |
| `POST /v1/tenants/{id}/connections` `{code}` | tenants.write | `201 {id, peer_name, state, created_at, ended_by_us}` |
| `GET /v1/tenants/{id}/connections` | tenants.read | `{items: [...]}`, newest first |
| `POST /v1/tenants/{id}/connections/{connection}/end` | tenants.write | `200`; ending one that has ended answers it unchanged |
| `GET /v1/internal/tenants/{id}/connections?state=active` | **connections.read** | `{items: [{id, peer_tenant_id, peer_name}]}`; 404 for an unknown tenant |
| `GET /v1/internal/connections/{connection}` | **connections.read** | `{active, tenant_ids}`; 404 for an unknown id |

The two internal answers match what `compliance-agent/src/registry.rs` reads. A test pins the `items` key, because the agent defaults a missing key to "no connections".

**Codes:**
- 160 random bits (`crypto/rand`), shown as eight groups of four base32 letters.
- Stored as SHA-256 only, looked up by hash; case, spaces and dashes don't matter.
- Valid for 14 days, single use, at most 20 open per workspace.
- Every code that doesn't work gets the same 404 `invalid_code`: unknown, used, expired, withdrawn, the workspace's own, or either workspace archived.
- 409 `already_connected` when the two are connected already; the code then stays open.
- Entering codes is limited to 20 per hour per workspace, and per person when the call names one (`keyRateLimiter` now takes its limit as an argument; CI licences keep theirs). A call from the portal's own client that names nobody has only the workspace limit. Otherwise every workspace would share one limit through that client. **portal#201 must send `X-Portal-User-Subject`.**

**Redeeming** is one transaction. `SELECT … FOR UPDATE` on the code, insert the connection, then mark the code used. A partial unique index allows at most one connection per pair of workspaces that hasn't ended. A race test has two workspaces enter one code at the same time: exactly one connects.

**Active** is derived on every read: not ended, both workspaces exist, and neither is archived. So no delivery can go to an archived workspace, even if writing the end failed.

**Ending on archive:** every status change passes through `syncTenantStatus`, which now ends an archived workspace's connections. The admin purge calls the same step again before `DeleteTenant`, as a safety net. The foreign keys are `ON DELETE SET NULL`, with name snapshots, so the other side keeps its history.

**Audit:** `connection.invite_created`, `connection.invite_withdrawn`, `connection.created` and `connection.ended` go into both workspaces' logs.
- The acting side's entry names the actor.
- The other side's entry is a system entry with `by: peer`: no person, IP or user agent, only the connection id and the acting side's display name.
- Ends caused by archiving carry `reason: tenant_archived`.

**Product routes refuse user tokens** (403 `FORBIDDEN_CLIENT`), whatever groups the token's client holds, because they carry the peer's tenant id.

**Who may:** user tokens need IT_ADMIN or OWNER in their own workspace (the existing team gate, `IsTenantAdmin`). Another workspace's administrator gets a 404. The portal calls as its service client, naming the person in `X-Portal-User-*`.

**Side fix:** the Postgres `GetTenant` now answers a non-UUID id as not found (404), as the memory store does. It was a 500, which the new internal route hit.

## Test plan

- [x] Unit tests: route groups in `authz_test`, roles and cross-tenant scoping in `connections_scope_test`, and the OpenAPI contract cases.
- [x] Integration tests on memory **and Postgres (testcontainers)** in `connections_test.go`, run locally:
  - connect, list, product view, check, and the re-connect after end;
  - every invalid code gives the same answer, including expiry with an injected clock;
  - archive, then purge;
  - unknown ids;
  - the rate limit;
  - the redeem race.
- [x] The whole `internal/server` suite runs against Postgres locally (`go test -count=1 ./internal/server/`, 236 s, green). `-race` is green on the connection tests. `go vet` and `golangci-lint` v2.12.2: 0 issues.
- [ ] Playwright e2e: n/a, there's no UI here (portal#201).
- [ ] Manual smoke on stage after deploy, once `AUTHZ_RULES` carries the grant below. Prüfwerk's release screen should then show no warning.

## Risk

**Blast radius:** new tables and routes only. Existing routes change in two small ways: the `GetTenant` 500→404 for non-UUID ids, and the archive path now also ends connections.

**What could break:**
- **Migration number:** `0032` is also used by the open onprem PRs (#142/#143, `0032_werkpilot_description`). Whichever merges second must renumber. A duplicate version fails the migrations test loudly. I didn't pick 0033, because golang-migrate would silently skip a 0032 that merges after it.
- **Deployment grant:** the new group needs a grant in stage and prod `AUTHZ_RULES`. That config isn't in this repo: `pruefwerk-svc-stage:…,connections.read`, and the same for prod. Until it's added, Prüfwerk keeps getting 403.

**Rollback plan:** revert the PR and redeploy. The down migration drops both tables.

## Decided (2026-11-20, by the product owner)

- **Archived only** ends connections. A `halted` workspace keeps them, so a returning customer finds them again. Active stays false while a side is archived.
- **IT_ADMIN or OWNER** may create, enter and end, using the existing team gate rather than a new catalogue right.

## Open points for review

1. **Retention:** a purged workspace's display name stays visible to its former peers through the name snapshot, with no time limit. Should it be dropped after a while?
2. **Additions to the sketch:** the create answer now carries the invite `id`, which the withdraw route needs, and there's a list of open codes, without the codes.

## Checklist

- [x] Docs updated: the OpenAPI spec and the package doc in `connections.go` (no separate docs page for registry routes)
- [x] Audit events emitted for state changes
- [x] Secrets via Infisical, never in repo (none involved)
- [x] Migration is forward-only (new tables; down drops them)
- [x] Tenant scoping enforced on every DB query
- [x] OpenAPI spec updated
- [ ] `featureFlags.evaluate()`: n/a (nothing toggleable)
- [ ] CHANGELOG entry: n/a (generated by git-cliff on release)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #145
2026-11-20 08:54:44 +00:00

267 lines
9.5 KiB
Go

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, ciLicenceRate) {
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, limit int) 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) >= limit {
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
}