Files
tenant-registry/README.md
T
sharangandClaude Opus 5.5 e0bff8c793
ci / shared (push) Successful in 13s
ci / test (push) Successful in 23m16s
ci / image (push) Successful in 36s
feat(notify): branded mails for published documents and new findings (#35)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-23 21:10:06 +00:00

279 lines
18 KiB
Markdown

# tenant-registry
Multi-tenant glue: orgs, entitlements, API keys, audit.
> Part of the **Breakpilot Platform**. For the big picture see [`platform/docs`](https://git.breakpilot.com/platform/docs):
> [Architecture](https://git.breakpilot.com/platform/docs/src/branch/main/PLATFORM_ARCHITECTURE.md) ·
> [Infrastructure](https://git.breakpilot.com/platform/docs/src/branch/main/INFRASTRUCTURE.md) ·
> [Product Integration Spec](https://git.breakpilot.com/platform/docs/src/branch/main/PRODUCT_INTEGRATION_SPEC.md) ·
> [Implementation Plan](https://git.breakpilot.com/platform/docs/src/branch/main/IMPLEMENTATION_PLAN.md)
## What this is
Multi-tenant glue: orgs, entitlements, API keys, audit. Scaffolded under milestone M4.1. See [`platform/docs`](https://git.breakpilot.com/platform/docs) for the full architecture context.
**Plane:** Control
**Owner:** @sharang
**Status:** pre-alpha
**Linked milestone:** [M4.1](https://git.breakpilot.com/platform/docs/src/branch/main/IMPLEMENTATION_PLAN.md)
## Run locally
```bash
# Prerequisites: Go 1.25+
# Dependencies (Keycloak, pg-app) come from the dev stack — see platform/orca-platform/dev.
# In one terminal — bring up dev dependencies (in the orca-platform clone):
cd /path/to/platform/orca-platform && make dev-up
# In another — run the service:
make dev # APP_ENV=dev, listens on :8090 (Keycloak owns :8080 in the dev stack)
make test # unit tests
make build # compile to ./bin/tenant-registry
```
Env vars (override at the shell):
| Var | Default | Purpose |
|---|---|---|
| `APP_ENV` | `dev` | one of `dev`, `stage`, `prod` |
| `ADDR` | `:8090` | listen address (avoids Keycloak's :8080) |
| `KEYCLOAK_ISSUER` | `http://localhost:8080/realms/breakpilot-dev` | OIDC issuer URL (the JWT signer) |
| `DATABASE_URL` | empty (in-memory store fallback) | Postgres DSN; service uses Memory when empty |
| `MIGRATE_ON_START` | unset | `true` ⇒ apply pending migrations before serving (orca has no shell to chain `/migrate`) |
| `KEYCLOAK_ADMIN_URL` | empty (Mock adapter used in dev) | KC base URL for the Admin API |
| `KEYCLOAK_REALM` | `breakpilot-dev` | Realm name for Admin API calls |
| `KEYCLOAK_CLIENT_ID` | empty | Service-account client id (Admin) |
| `KEYCLOAK_CLIENT_SECRET` | empty | Service-account client secret |
| `AUTH_ENABLED` / `AUTH_EXPECTED_AUDIENCE` | `false` / `tenant-registry` | Bearer-token gate on every non-health route |
| `AUTHZ_RULES` | empty (allow all — dev only) | Per-client route groups, e.g. `portal-svc-stage:tenants,catalog,api-keys,audit,users;pruefwerk-svc-stage:entitlements,tenants.read,api-keys.verify,audit.write` |
| `DOCUMENTS_S3_ENDPOINT` / `_REGION` / `_BUCKET` / `_ACCESS_KEY` / `_SECRET_KEY` | empty (document routes 503) | Object storage for tenant documents; the bucket is created in the region when missing |
| `DOCUMENTS_MAX_MB` | `200` | Upload limit per document |
| `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASSWORD` | empty (mail queues up unsent) | Relay for platform mail (STARTTLS on 587, TLS on 465) |
| `MAIL_FROM` / `MAIL_FROM_NAME` | `noreply@breakpilot.com` / `BreakPilot` | Sender of platform mail |
| `PORTAL_URL` | `https://app.breakpilot.com` | Portal origin for links in mail |
| `INVITE_CLIENT_ID` / `INVITE_REDIRECT_URI` | `dev-portal` / `https://breakpilot.com/onboard` | Keycloak invite mail client + landing URL (stage: `portal-stage`, `https://app-stage.breakpilot.com/start?invited=1`) |
| `ERP_BASE_URL` / `ERP_API_KEY` / `ERP_API_SECRET` | empty (outbox idle) | ERPNext / erpmock base URL + `token key:secret` credentials |
| `ERP_LEAD_DOCTYPE` | `Lead` | `CRM Lead` when the Frappe CRM app is used |
| `ERP_WEBHOOK_SECRET` | empty (receiver disabled) | HMAC secret for `POST /v1/internal/erp/webhook` |
| `ERP_OUTBOX_INTERVAL` / `ERP_RECONCILE_INTERVAL` | `15s` / `15m` | Worker cadence |
| `ERP_RESTRICT_AFTER_DAYS` / `ERP_HALT_AFTER_DAYS` / `ERP_EXPORT_WINDOW_DAYS` | `14` / `30` / `30` | Ladder timing |
| `LICENCE_SIGNING_KEY` / `LICENCE_ISSUER` / `LICENCE_TTL_DAYS` | empty (ephemeral) / `tenant-registry` / `30` | CLI licence signer (base64 Ed25519 seed) |
| `LITELLM_BASE_URL` | `https://llm.breakpilot.com` | LiteLLM proxy root; returned to Werkpilot as `llm_base_url` |
| `LITELLM_MASTER_KEY` | empty (LLM keys off — logged once at start) | LiteLLM admin key for `/key/generate` + `/key/delete` (secret) |
| `LITELLM_MODELS` | `Qwen3-Coder-30B-A3B-Instruct,gpt-oss-120b,Qwen3.8-27B` | Comma list of models a tenant key may call |
| `LITELLM_BUDGET_TRIAL` / `LITELLM_BUDGET_DEFAULT` | `5` / `50` | USD per 30 days (`budget_duration: 30d`) for trial / paying tenants |
## Endpoints
Authoritative spec: [`openapi.yaml`](./openapi.yaml). Summary:
| Method | Path | Purpose |
|---|---|---|
| GET | `/healthz` | Liveness |
| GET | `/readyz` | Pings the store |
| GET | `/v1/tenants` | List tenants (service-only, keyset paginated) |
| POST | `/v1/tenants` | Create a tenant |
| GET | `/v1/tenants/{id}` | Read by id |
| GET | `/v1/tenants/by-slug/{slug}` | Read by slug (portal middleware uses this) |
| POST | `/v1/tenants/{id}/activate` | trial → active |
| POST | `/v1/tenants/{id}/status` | Ladder transition (active/warning/restricted/halted/archived), syncs Keycloak |
| POST | `/v1/tenants/{id}/cancel` | active → halted |
| POST | `/v1/internal/entitlements/check` | Authoritative entitlement answer for products (cache ≤ 60 s) |
| GET | `/v1/entitlements?tenant_id={id}` | List product entitlements |
| GET | `/v1/catalog` | List requestable products |
| POST | `/v1/catalog/request` | Customer requests a product (sales follow-up) |
| POST | `/v1/catalog/trial-request` | Self-serve 14-day trial |
| GET | `/v1/api-keys?tenant_id={id}` | List keys |
| POST | `/v1/api-keys` | Create key (plaintext shown once) |
| DELETE | `/v1/api-keys/{id}` | Revoke |
| POST | `/v1/internal/api-keys/verify` | Used by headless products to validate inbound keys |
| POST | `/v1/audit` | Append an audit event |
| GET | `/v1/audit` | Query (cursor-paginated) |
| POST | `/v1/usage/events` | Products push usage facts (idempotent; forwarded to ERPNext via the outbox) |
| GET | `/v1/usage/events?tenant_id={id}` | Query usage |
| GET | `/v1/subscriptions?tenant_id={id}` | Subscriptions mirrored from ERPNext |
| POST | `/v1/internal/erp/webhook` | ERPNext webhook receiver (HMAC, no bearer) → ladder |
| GET | `/v1/internal/erp/status` | Outbox backlog + ERP/licence configuration |
| POST | `/v1/internal/erp/reconcile` | Run the reconcile pass now |
| POST | `/v1/licences` | Issue a CLI licence JWT (Werkpilot, Firmwerk) |
| GET | `/v1/licences?tenant_id={id}` | List licences |
| POST | `/v1/licences/{id}/revoke` | Revoke |
| POST | `/v1/licences/heartbeat` | CLI phone-home (licence JWT is the credential; renews past half-life) |
| GET | `/.well-known/licence-keys.json` | JWKS (Ed25519) for offline licence verification |
State-changing endpoints emit audit events automatically. The OpenAPI contract test (`openapi_test.go`) asserts every listed path resolves against the committed spec.
## ERP link (M-MIG-7)
ERPNext is the commercial authority; the registry mirrors it and moves tenants
on the ladder (`ERP/02 Billing and Entitlements`):
- **Outbox** (`erp_outbox`): tenant create → `customer.upsert` (writes
`erp_customer_id`), usage event → `usage.record`, catalog request →
`lead.create`. The worker runs every `ERP_OUTBOX_INTERVAL` (15 s) with
backoff 1 m / 5 m / 15 m / 1 h. With `ERP_BASE_URL` unset it idles and the
rows accumulate.
- **Webhooks** (`POST /v1/internal/erp/webhook`, HMAC `ERP_WEBHOOK_SECRET`):
`sales_order.submit` → subscriptions + `tenant_products` (SKU → product,
`-STD/-BUS/-ENT` → plan, add-on SKUs → limit, e.g. `runners`) + `active`;
`sales_invoice.overdue` → `warning`, `restricted` from
`ERP_RESTRICT_AFTER_DAYS` (14), `halted` from `ERP_HALT_AFTER_DAYS` (30);
`payment_entry.submit` → `active`; `subscription.cancel` → `halted`.
- **Reconcile** every `ERP_RECONCILE_INTERVAL` (15 min): re-reads ERP
Subscriptions per customer (safety net for lost webhooks) and applies the
time-based steps — trial expiry → `restricted`, `warning` → `restricted`
after 14 d, `restricted` → `halted` after 30 d total, `halted` →
`archived` after `ERP_EXPORT_WINDOW_DAYS` (30).
- Every status change syncs the coarse `tenant_status` claim to Keycloak.
**Staging uses the mock** (`cmd/erpmock`, decision 18): the Frappe REST
surface (`/api/resource/{Customer,Subscription,Usage Record,Lead,…}` with
`Authorization: token key:secret`), `GET /_mock/requests` for assertions and
`POST /_mock/fire/{sales-order-submit|invoice-overdue|payment-entry|subscription-cancel}`
which mutate the mock's docs and deliver the signed webhook to
`ERP_WEBHOOK_URL`. The live-ERP configuration (custom field `tenant_id`, API
user, Frappe Webhooks) is documented in `ERP/03` for the prod phase.
## CLI licences (decision 13)
`werkpilot login` / `firmwerk login` run the device flow on the realm and call
`POST /v1/licences` with the user token; the registry checks the entitlement,
records the licence and signs an EdDSA JWT (`LICENCE_SIGNING_KEY` = base64
32-byte Ed25519 seed; unset ⇒ ephemeral dev key). CLIs verify offline against
`/.well-known/licence-keys.json`, phone home hourly via `/v1/licences/heartbeat`
(ok → warning → degraded → hard_stop on the token's own clock after expiry,
plus the tenant ladder; renewal past half-life) and honour `revoked`.
### Werkpilot licences carry a LiteLLM key (D6)
For `product = "werkpilot"` the registry also provisions a **per-tenant
LiteLLM virtual key** (`POST /key/generate` on `LITELLM_BASE_URL` with
`LITELLM_MASTER_KEY`) and returns it in the grant:
```json
{
"id": "6a5e…", "licence": "eyJhbGciOiJFZERTQSIs…", "kid": "fe209240",
"expires_at": "2026-10-12T09:00:00Z",
"grace": { "warning_days": 7, "degraded_days": 14, "hard_stop_days": 30 },
"status": "ok",
"llm_api_key": "sk-…", // once — never stored, never returned again
"llm_base_url": "https://llm.breakpilot.com",
"warnings": ["llm_key_unavailable"] // only when LiteLLM is off / down / refused
}
```
- Key shape sent to LiteLLM: `key_alias = werkpilot-<tenant_slug>-<licence_id>`,
`models = LITELLM_MODELS`, `max_budget = LITELLM_BUDGET_TRIAL` for tenants in
`trial`, else `LITELLM_BUDGET_DEFAULT`, `budget_duration = "30d"`,
`metadata = {tenant_id, tenant_slug, licence_id, product, plan, tenant_status}`.
- The row keeps only LiteLLM's hashed token id (`licences.llm_key_id`,
migration `0007`), which `GET /v1/licences` exposes as `llm_key_id`.
- **Failure never fails the licence**: with `LITELLM_MASTER_KEY` unset or
LiteLLM unreachable the JWT is issued, the LLM fields are omitted and
`warnings` carries `llm_key_unavailable`.
- **Heartbeat renewal** does not mint a second key: the handle moves to the
renewed licence row, the renewed grant carries `llm_base_url` but no
`llm_api_key` (the CLI keeps the one it stored).
- **Revoke** (`POST /v1/licences/{id}/revoke`) deletes the key
(`POST /key/delete {"keys": [<token id>]}`; 404 tolerated). The audit event
records `llm_key_deleted`. Firmwerk licences get no key.
- `GET /v1/internal/erp/status` reports `llm_keys_enabled`.
## Storage
The service picks its store based on `DATABASE_URL`:
- **empty** → in-memory store, pre-seeded with the `acme` tenant (`id: 00000000-0000-0000-0000-000000000001`). Useful for portal dev without spinning Postgres.
- **set** → pgx-backed Postgres. Run `make migrate-up` against the same DSN first.
Both implementations pass the same test harness (`internal/server/server_test.go` → `eachStore`).
## Keycloak adapter (M4.3)
`internal/keycloak` is the seam between tenant-registry and Keycloak. The
`Adapter` interface has two implementations:
| Implementation | When used |
|---|---|
| `Mock` | Default in dev when `KEYCLOAK_ADMIN_URL` is empty |
| `HTTPAdapter` | Real KC Admin API client; activated when KC env vars are populated |
`POST /v1/tenants` now accepts `admin_email` and `admin_name`. When set, the
adapter creates a Keycloak organization (alias = the tenant slug), invites
the user as the IT_ADMIN, and triggers the verify-email + set-password
flow. The response body includes `invite_url` so dev testers can use it
without waiting for the email — production discards it.
**KC failures are non-fatal.** The tenant row still lands; a
`keycloak.provision_failed` audit event captures the error so the operator
can resend the invite from the KC UI.
`POST /v1/internal/keycloak/claims` resolves a tenant's current entitlement
bundle (tenant_id, slug, products, plan, status). The realm's protocol
mapper calls this at token-issuance time (or whenever user attributes
need a refresh).
For production, provision a service-account client in the realm with the
`realm-management:manage-users` + `manage-organizations` roles. Drop its
credentials in Infisical at `/{env}/tenant-registry/KEYCLOAK_CLIENT_*`.
## Schema migrations (M4.1)
```bash
# Apply all pending migrations against the dev Postgres (assumes
# `make dev-up` in platform/orca-platform is running):
make migrate-up
# Inspect current version:
make migrate-version
# Roll back the most recent migration:
make migrate-down
# Wipe everything (DESTRUCTIVE — only safe against a dev DB):
make migrate-down-all
# Create the next pair of empty migration files:
make migrate-create NAME=add_team_table
```
Migrations are embedded into both `cmd/server` and `cmd/migrate` via `migrations/embed.go`. In production, `cmd/migrate` ships as an Orca init container so the schema is applied before the API server starts (`IMPLEMENTATION_PLAN.md §1.7`: migrations are forward-only and run as an init container before the service).
The migrations package ships three integration tests (require Docker):
| Test | What it asserts |
|---|---|
| `TestMigrate_upDownRoundTrip` | up → all 6 tables + 4 enums exist; down → schema empty; up again succeeds |
| `TestSeed_canInsertAndQuery` | end-to-end insert across all 6 tables, FK cascade behaviour, `audit_log` SET-NULL on tenant delete |
| `TestSlugConstraint` | tenant slug regex enforced (rejects too-short / leading dash / uppercase / underscore) |
Run them with `make test`. Use `make test-short` in environments without Docker.
## Deployment
| Env | URL | How |
|---|---|---|
| dev | `http://localhost:8090` | `make dev` |
| stage | `https://tenant-registry.stage.breakpilot.com` | auto on merge to `main` |
| prod | `https://tenant-registry.breakpilot.com` | manual: tag `vX.Y.Z` + sign-off |
Rollback: `orca rollout undo tenant-registry --env={{env}}`.
## Observability
- Traces, logs, metrics: [SigNoz](https://signoz.meghsakha.com) — service name `tenant-registry`
- Audit events: Tenant Registry `/audit` (Retraced-shape schema)
- On-call: `oncall@breakpilot.com` · runbook at `platform/docs/runbooks/tenant-registry.md`
## Contributing
See [`CONTRIBUTING.md`](./CONTRIBUTING.md). TL;DR: branch from main, open a PR, 1 review + green CI, squash-merge.
## License
Proprietary — all rights reserved. Copyright (c) 2026 Sharang Parnerkar and Benjamin Boenisch. See [`LICENSE`](./LICENSE).