# 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`, `onprem` (see [On-prem](#on-prem)) | | `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) | | `SMTP_TLS` | `tls` on port 465, else `starttls` | `starttls`, `tls` or `none` (a plain relay inside the customer's network; refused together with `SMTP_USER`) | | `PRODUCTS` | empty (the catalog's own enabled flags) | Comma list of the products this installation offers; a listed product is offered even if its row is disabled | | `PRODUCT_LAUNCH_URLS` / `PRODUCT_PROVISION_URLS` | empty (the URLs seeded per environment) | `key=url,key=url` overrides; a provision URL carries `{id}`. Checked at start | | `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` / `28` / `30` | Ladder timing: days after the Mahnung until read-only / halted; export window | | `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 | | `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 | | PUT | `/v1/admin/tenants/{id}/managed-services/{sid}/admin-token` | Set or clear a Git instance's `read:admin` token (staff; sealed, write-only) | | GET | `/v1/admin/tenants/{id}/module-users?month=` | Module users per month (staff) | | GET | `/v1/tenants/{id}/module-users?month=` | Module users per month (tenant; `portal:billing.view`) | | POST | `/v1/internal/module-users/count` | Run the daily module-user count now (group `module-users`) | State-changing endpoints emit audit events automatically. The OpenAPI contract test (`openapi_test.go`) asserts every listed path resolves against the committed spec. ## On-prem `APP_ENV=onprem` runs the registry on a customer's own node (the package in `platform/onprem`). Differences from the cloud: - No ERP: the outbox takes nothing, the ERP webhook is off, and `ERP_BASE_URL` / `ERP_WEBHOOK_SECRET` must be empty. - No trial: a new workspace starts `active`, and the ladder never escalates by time (the licence is the contract). - No sign-up and no sales requests: the trial-offer, trial-terms, catalog request, trial request and admin trial routes answer 404 `not_available`. - Products and URLs only from `PRODUCTS` and `PRODUCT_*_URLS`. The seeded `stage`/`prod` URLs are never used, so provisioning never reaches a Breakpilot host (the test install in `platform/onprem` checks all outbound traffic). Each listed product needs a launch URL; an unknown key stops the start. The catalog offers no trials. - Accounts only from the customer's directory (Keycloak federates their AD; the package's `keycloak/realm-policy.sh` keeps passwords in AD). The workspace's first admin (`admin_email`) and every invited member must be an existing directory user: they are added to the organization with their role, get no set-password mail and sign in with their directory password. An unknown address answers `not_in_directory`; there is no invitation to resend (`no_invite_mail`). - No cloud defaults: the registry refuses to start without `AUTH_ENABLED=true`, `AUTHZ_RULES`, `LICENCE_SIGNING_KEY`, `DATABASE_URL`, the Keycloak admin settings, `PORTAL_URL`, `INVITE_CLIENT_ID`, `INVITE_REDIRECT_URI`, `MAIL_FROM` and `PRODUCTS`, and without `LITELLM_BASE_URL` when `LITELLM_MASTER_KEY` is set. Contract documents stay off. ## 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` (never more: see below); `payment_entry.submit` → `active`; `subscription.cancel` → `halted`. - **Late payment needs a Mahnung** (AGB § 10: restriction only "trotz Mahnung und angemessener Nachfrist"). An overdue invoice alone means `warning`. The reconcile pass reads the customer's submitted, unresolved ERPNext **Dunnings**. The earliest one that names a still-open invoice sets the clock: `restricted` (read-only) `ERP_RESTRICT_AFTER_DAYS` (14) after its posting date, `halted` a further 14 days after the restriction (so `ERP_HALT_AFTER_DAYS`, 28, after a Mahnung seen on time). A tenant is always read-only before it is halted. A Mahnung for paid invoices does not count. The ERP API user needs read access to Dunning. - **Reconcile** every `ERP_RECONCILE_INTERVAL` (15 min): re-reads ERP Subscriptions and overdue invoices + Dunnings per customer (safety net for lost webhooks) and applies the time-based steps: trial expiry → `restricted`, `restricted` → `halted` after a further 14 d (`ERP_HALT_AFTER_DAYS` − `ERP_RESTRICT_AFTER_DAYS`), `halted` → `archived` after `ERP_EXPORT_WINDOW_DAYS` (30). A `warning` never escalates by time alone. - 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--`, `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": []}`; 404 tolerated). The audit event records `llm_key_deleted`. Firmwerk licences get no key. - `GET /v1/internal/erp/status` reports `llm_keys_enabled`. ## Module users (t81) The registry counts the users of each module per tenant and Europe/Berlin month (migration `0031`). Counting only: invoicing, usage events and the included amounts come later with t72. | Module | Who counts | Month value | |---|---|---| | `managed-git` | Workspace members who have signed in to the tenant's active Git instance(s) at least once | Peak of the daily counts (`peak_day` = the earliest peak day) | | `werkpilot`, `firmwerk` | People whose own CLI licence was created or seen in the month | Distinct people in the month | - **Managed Git**: each Gitea is read with its own token of scope `read:admin` (`GET {url}/api/v1/admin/users`, paged). Customers sign in only through Keycloak, so Gitea's `login_name` is the Keycloak user id; the count is the users whose `login_name` is a current workspace member's id and whose `last_login` is set. Staff (company realm, other ids) and the CI bot `breakpilot-ci` (local account, empty `login_name`) drop out. A person on two instances of the tenant counts once. A tenant with a failing instance, a missing token or a Keycloak error is reported and not written (never a 0); a re-run overwrites the day. - **Werkpilot / Firmwerk**: from `licences`; CI licences (`apikey:` subject, `ci:` device) and licences issued by a service client (`service:`) don't count. `last_seen_at` keeps only the latest time, so the job adds people to the month's set while it runs (`module_users_seen`). Each run sweeps the times in the current and the previous Berlin month, each into its own month, so a run after midnight still credits the evening before. - **Job**: once per Berlin day in the background (checked every 15 min; also once after a start, a re-run is harmless), or now with `POST /v1/internal/module-users/count`. The report lists errors per tenant and service id. - **Token**: `PUT /v1/admin/tenants/{id}/managed-services/{sid}/admin-token` with `{"token": "…"}` (`""` clears). Stored AES-256-GCM sealed under `SECRETS_ENCRYPTION_KEY` (bound to the service id); without that key the PUT answers 503 and Managed Git is not counted. Never returned or logged; the admin view shows `admin_token_set`. ## 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).