Brings the ERPNext sales catalogue in line with the frozen Leistungsbeschreibungen 1.0.0. This PR changes code and tests only. No ERP was called; the live run is yours, using the erpsetup CLI. ## Dry run first (with the flag; only this path prints `field old → new`) ```sh ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… ERP_WEBHOOK_SECRET=… \ go run ./cmd/erpsetup -webhook-url https://registry.breakpilot.com/v1/internal/erp/webhook -sync-catalog -dry-run ``` (`ERP_LEAD_DOCTYPE` is optional, as before.) Leave out `-dry-run` for the real run. ## What a run does with and without `-sync-catalog` | | without the flag (as today) | with `-sync-catalog` | |---|---|---| | New items, unit "Prüftag", their list prices | created | created | | Item **description** | **updated (this already happens on every run today)** | updated | | Item `item_name`, `disabled` | untouched | updated when they differ | | Standard Selling `price_list_rate` (rows without a customer) | set once, never changed | updated when it differs | | Customer-specific Item Prices | untouched | untouched | | Quote print format (Mehrverbrauch row) | updated | updated | **A plain run is not inert.** It creates the 5 new items, the new unit and 5 new prices, rewrites every changed description, and updates the quote template. Only names, the disabled flags and price changes wait for the flag. Nothing is ever deleted. Only the doctypes Item, Item Price and UOM are touched beyond what erpsetup already manages. ## Catalogue changes | Code | Status | Price old → new (EUR) | |---|---|---| | PLT-CORE-CLD-STD/BUS/ENT | keep (name "Breakpilot …", new text) | 290 / 790 / 1990 (unchanged) | | PLT-BNDL-CLD-STD | **new** Starter-Modulpaket | 990 | | PLT-BNDL-CLD-ADD | **new** Weiteres Modul | 499 | | CRA-CSA-CLD-STD | keep | **1490 → 490** | | CRA-CSA-CLD-BUS | keep | **3990 → 1290** | | CRA-CSA-CLD-ENT | keep | **9900 → 0** (Preis nach Vereinbarung: a quote shows 0,00 € unless the rate is entered by hand) | | CRA-CSA-CLD-TGT | **new** extra Prüfobjekt / Monat | 5.99 | | CRA-CSA-CLD-DAY | **new** Prüftag (unit Prüftag) | 9.99 | | CRA-CSA-CLD-SCAN | **disable** | 12 (unchanged) | | CRA-WBK-CLD-STD/BUS/ENT | **disable** | unchanged | | DEV-WP-CLD-STD | keep ("Werkpilot Cloud") | 59 | | DEV-WP-CLD-BUS/ENT | **disable** | unchanged | | DEV-WP-OPR-*, DEV-FWK-OPR-*, INF-GIT-OPR-*, INF-CI-OPR-* | keep, new texts | unchanged | | DEV-FWK-CLD-STD | keep ("Firmwerk Cloud") | 89 | | DEV-FWK-CLD-BUS/ENT | **disable** | unchanged | | INF-GIT-CLD-STD/BUS/ENT | keep, new texts | 190 / 390 / 790 | | INF-GIT-CLD-USR | **new** extra user | 19 | | INF-CI-CLD-STD/BUS/ENT | keep, new texts | 149 / 290 / 590 | The item group stays "BreakPilot Abonnements". Correction to the spec, applied here: PLT-CORE-CLD-STD no longer mentions "Rechnungen", because LB Plattform §2(3) says the portal provides no invoices. The text is now "Arbeitsbereich mit Anmeldung und Team für bis 25 Nutzer, Standard-Support. Module werden einzeln gebucht." No other item text mentions invoices, and a test now checks that none does. ## Other changes - `sku.Disabled` is sent to ERPNext as the Item field `disabled: 1`. Disabled items stay in ERPNext so old documents keep working. Since the disabled items already exist on prod, their flag only changes with `-sync-catalog`. - **Quote, Mehrverbrauch row:** "Zusätzliche Prüfobjekte werden mit {TGT} netto je Monat berechnet, Prüftage nach verbrauchtem Monatskontingent mit {DAY} netto (Leistungsbeschreibung Prüfwerk, Abschnitt 7)." If a rate is missing, the text says "gemäß der jeweils gültigen Preisliste" instead, per rate. If both are missing, one combined sentence is printed. Quotes with INF-GIT-CLD-STD/BUS/ENT or PLT-BNDL-* add the sentence on extra users (Leistungsbeschreibung Breakpilot Plattform, Abschnitt 4). The Jinja was parsed and rendered locally with jinja2 against mocks for eight item mixes. - **Migration 0026** adds CRA-CSA-CLD-TGT and -DAY to the `pruefwerk` product. SCAN stays so old orders still map. The up is guarded so it can run twice; the down removes the two SKUs. `DefaultProducts` and the ERP mock's SKU list follow. **Run `migrate-up` with the deploy.** Without it, TGT/DAY lines on an order log "sales order item without catalog product". - **0 € module lines:** nothing needed fixing. Neither the webhook path nor reconcile reads the rate: the webhook template sends only `item_code` and `qty`, and `SubscriptionPlan` has no rate. A new test covers both paths: a bundle order with modules at rate 0 and qty 15 gives an active tenant, plan standard, and seats 15 per module. ## Decisions the spec did not cover 1. **No Prüfwerk Mehrverbrauch sentence on Enterprise quotes.** CRA-CSA-CLD-ENT is "ohne Begrenzung". Edge case: a quote with both -STD and -ENT also prints no Prüfwerk sentence. The extra-users sentence is not affected. 2. The run without the flag still writes descriptions, as `Run` has done until now (see the table). 3. `-sync-catalog` only changes Item Price rows without a `customer`. If there are several such rows for an item, the run reports "not synced". If there are none, it creates the list price. 4. The quote template's Item Price lookup still has no customer filter (unchanged from before). 5. INF-GIT-OPR texts: STD uses the spec text exactly, so "kein Quellcode verlässt das Haus" is gone. BUS keeps "für mittelgroße Teams" and loses "schnellerer Patch-Rhythmus", like CI. ENT says "für große Entwicklungsorganisationen". 6. INF-CI-OPR texts differ only by size ("mindestens 2 vCPU / 4 GB" etc.); "für größere/umfangreiche Builds" was dropped. 7. DEV-WP-OPR and DEV-FWK-OPR texts: the tier phrase sits after "im eigenen Netz", e.g. "Werkpilot im eigenen Netz für mittlere Teams, mit einem vom Kunden betriebenen KI-Modell; …". 8. TGT/DAY quantities on an order or subscription count toward Prüfwerk `seats`, exactly as SCAN already does. Not changed here. 9. Bundle revenue goes to cost center Plattform (PLT-*). Module lines at 0 € book nothing on Prüfwerk, Firmwerk or Werkpilot. Whether to allocate it is an accounting decision for you. 10. The dry run prints texts in full (no truncation), so the wording can be read before it goes live. 11. `TestEverySKUHasAListPrice` now allows exactly one item at 0: CRA-CSA-CLD-ENT. 12. The ERP mock's `DefaultSKUs` now also lists PLT-BNDL-* and CRA-CSA-CLD-TGT/DAY. ## Tests `go build ./... && go vet ./... && go test ./...` all pass. The Postgres testcontainers suites ran (podman socket) with no skips: server 463 s, migrations 32 s. New tests: - catalogue consistency: unique codes, units, disabled set, prices including 5.99/9.99, brand spelling - `TestSyncCatalog`: the dry run writes nothing and names every change; the run updates name, description, disabled and price and keeps the customer price; a second run makes no updates; without the flag only the description changes - quote template phrases - `TestMigrate_productsSeedMatchesDefaults`: seed equals `DefaultProducts`, 0026 applied twice, down - `TestErp_zeroRateModuleLinesEntitle`: webhook and reconcile, memory and Postgres 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Reviewed-on: #115
tenant-registry
Multi-tenant glue: orgs, entitlements, API keys, audit.
Part of the Breakpilot Platform. For the big picture see
platform/docs: Architecture · Infrastructure · Product Integration Spec · Implementation Plan
What this is
Multi-tenant glue: orgs, entitlements, API keys, audit. Scaffolded under milestone M4.1. See platform/docs for the full architecture context.
Plane: Control Owner: @sharang Status: pre-alpha Linked milestone: M4.1
Run locally
# 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) |
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. 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(writeserp_customer_id), usage event →usage.record, catalog request →lead.create. The worker runs everyERP_OUTBOX_INTERVAL(15 s) with backoff 1 m / 5 m / 15 m / 1 h. WithERP_BASE_URLunset it idles and the rows accumulate. - Webhooks (
POST /v1/internal/erp/webhook, HMACERP_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,restrictedfromERP_RESTRICT_AFTER_DAYS(14),haltedfromERP_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→restrictedafter 14 d,restricted→haltedafter 30 d total,halted→archivedafterERP_EXPORT_WINDOW_DAYS(30). - Every status change syncs the coarse
tenant_statusclaim 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:
{
"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_TRIALfor tenants intrial, elseLITELLM_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, migration0007), whichGET /v1/licencesexposes asllm_key_id. - Failure never fails the licence: with
LITELLM_MASTER_KEYunset or LiteLLM unreachable the JWT is issued, the LLM fields are omitted andwarningscarriesllm_key_unavailable. - Heartbeat renewal does not mint a second key: the handle moves to the
renewed licence row, the renewed grant carries
llm_base_urlbut nollm_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 recordsllm_key_deleted. Firmwerk licences get no key. GET /v1/internal/erp/statusreportsllm_keys_enabled.
Storage
The service picks its store based on DATABASE_URL:
- empty → in-memory store, pre-seeded with the
acmetenant (id: 00000000-0000-0000-0000-000000000001). Useful for portal dev without spinning Postgres. - set → pgx-backed Postgres. Run
make migrate-upagainst 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)
# 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 — service name
tenant-registry - Audit events: Tenant Registry
/audit(Retraced-shape schema) - On-call:
oncall@breakpilot.com· runbook atplatform/docs/runbooks/tenant-registry.md
Contributing
See 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.