feat(telemetry): opt-in product telemetry relay and per-tenant switch #148

Open
sharang wants to merge 1 commits from feat/telemetry-relay into main
pull from: feat/telemetry-relay
Owner

What

The server half of opt-in, content-free telemetry (platform/werkpilot#87).

  • Per-tenant, per-product switch, default off: GET/PUT /v1/tenants/{id}/products/{product}/telemetry.
  • telemetry boolean in the licence grants and the heartbeat, so the CLI knows the switch.
  • POST /v1/telemetry relay. It checks a batch against a fixed allowlist and forwards it to the collector as OTLP/HTTP JSON. No ingest token ever sits on a customer machine.

Why

Refs platform/werkpilot#87. The agreed design:

  • (a) registry relay, so there is no ingest token on customer machines;
  • (b) off unless enabled: telemetry is sent only when the tenant has enabled it and the machine hasn't opted out locally. The local opt-out is client-side.

The licence-client and werkpilot sides are built in parallel against this contract.

Linked milestone: n/a (werkpilot#87)

How

Setting

  • Stored as the telemetry key of the product's tenant_product_settings document (0025), so no migration. The PUT reads the document, sets the key and writes it back; other keys survive (tested).
  • Only products with a telemetry allowlist take the switch: today werkpilot, others 404. The Prüfwerk settings PUT replaces its whole document, so the key must never land there.
  • PUT {"enabled": true|false} (exactly that body, else 400) answers {tenant_id, product, enabled, updated_by, updated_at}.
  • Who may: user tokens need IT_ADMIN or OWNER in their own workspace (403 FORBIDDEN_ROLE; another workspace gets 404). Services use tenants.read / tenants.write; the portal calls as its service client, as for the Prüfwerk settings.
  • Audit: a change is audited as product_settings.changed (setting: telemetry, old, new). A save that changes nothing writes nothing.
  • The portal toggle is a follow-up; this PR has no UI.

Flag in the licence answers

  • telemetry (always present, default false) is a plain JSON field in the grant of POST /v1/licences, POST /v1/licences/ci and the renewed grant of a heartbeat. It is not a JWT claim.
  • The heartbeat answer carries it at the top level, next to status, read fresh on every call. It is false on the revoked / unknown-tenant answers.

Relay POST /v1/telemetry

  • Steps, in order:
    1. 503 telemetry_unavailable without a token.
    2. 403 user_token_required for anything but a user token.
    3. Decode, capped at 256 KiB (413 too_large).
    4. Product known (400).
    5. Tenant enabled, else 403 telemetry_disabled and nothing is forwarded.
    6. Allowlist and validation (400 invalid_input, naming the metric index and name, or the key).
    7. An empty metrics list answers 204 and forwards nothing.
    8. Rate limit (429 rate_limited): 120 per user subject per sliding hour, in memory. Refused and empty batches don't count.
    9. Forward: 204, or 502 telemetry_failed.
  • Allowlist: exactly the table in #87. Listed keys may be left out. Values must be JSON strings matching ^[A-Za-z0-9_.:-]{1,64}$.
  • Numbers: counter values, histogram count and bucket_counts must be JSON integer literals ≥ 0, so -1, 1.5, 3.0, 1e3 and "3" are refused. sum is a number ≥ 0. At most 20 bounds, and len(bounds)+1 bucket counts.
  • Batch limits: at most 200 metrics; the interval has end ≥ start, at most 24 h, and end at most 10 min ahead.
  • Forwarding: OTLP/HTTP JSON POST to TELEMETRY_OTLP_URL with Authorization: Bearer <TELEMETRY_OTLP_TOKEN>.
    • Resource: service.name (product), service.version, tenant.slug, tenant.id, deployment.environment (APP_ENV).
    • Counters: monotonic Sum, DELTA. Histograms: explicit-bucket Histogram, DELTA. Both use startTimeUnixNano/timeUnixNano from the interval.
    • Points of the same name become one metric with several data points; attributes are sorted.
    • The user's subject and e-mail are never forwarded (tested).
  • Collector failure: a non-2xx answer or a transport error is a 502. It is logged with the status only; the collector's body, the URL and the token never reach the response or the log.
  • Authz: new route group telemetry. A user token from a client holding licences (today werkpilot-cli, firmwerk-cli) passes without it, so the deployed AUTHZ_RULES need no change. A sign-in client without licences and a service token holding licences are refused (FORBIDDEN_CLIENT).
  • No audit for batches: CONTRIBUTING asks for audit events on state changes. The relay changes no registry state, and like POST /v1/usage/events it emits none; 120 batches per person and hour would flood the tenant's log. Only the setting change is audited.
  • On-prem: with TELEMETRY_OTLP_TOKEN set, TELEMETRY_OTLP_URL must be given explicitly, mirroring LiteLLM.
  • New package internal/otlp: the export builder and client.
  • Dependencies: go.opentelemetry.io/proto/otlp and google.golang.org/protobuf move from indirect to direct in go.mod (same versions, no new modules, go.sum unchanged). They are used only in a test, to check the forwarded body against the OTLP protobuf JSON mapping.

Stricter than #87 (declared in the spec):

  • version is the only free-text field that is forwarded. It is constrained to ^[A-Za-z0-9.+_-]{1,64}$, which covers semver with pre-release and build parts.
  • bounds must be strictly increasing, as OTLP requires.
  • Not checked: that count equals the sum of bucket_counts.

Overlap with #147 (feedback): both PRs edit the same spots: the requireAuthz exception, the routeGroup switch, the Server struct, the route block, the config/README/onprem lists and the spec. Whichever merges second gets textual conflicts to resolve (keep both). No identifiers are shared, so the merged code compiles once the conflicts are resolved.

Going live (orca, not in this PR)

After merge and deploy, the relay answers 503 until:

  1. Token: a TELEMETRY_OTLP_TOKEN is added to the collector's bearertokenauth/ingest token list in orca-infra, and the same value to the registry's deployment secret (platform-stage / platform-prod).
  2. Tenant: an administrator turns it on for the tenant (PUT /v1/tenants/{id}/products/werkpilot/telemetry {"enabled":true}; until the portal toggle exists, through the portal's service client or staff).

No tokens were created for this PR.

Test plan

  • Relay (telemetry_relay_test.go, fake collector):
    • 204 forwarding: the exact OTLP JSON (resource, scope, grouping, sorted attributes, string-encoded 64-bit integers, DELTA = 1, isMonotonic), the bearer header and path. The same bytes protojson.Unmarshal into ExportMetricsServiceRequest (temporality, monotonic, values, bucket counts, interval), and neither the subject nor the e-mail is present.
    • 403 telemetry_disabled: for a tenant never enabled, one turned off, and when the body names another tenant. Nothing is forwarded.
    • 503 without a token.
    • Allowlist rejections (17 cases): product, metric, kind, unlisted key, a key of another metric, a key on a key-less metric, a bad or long or empty value, and non-string values. Every listed metric and key passes.
    • Validation (29 cases): integers, sums, bounds, buckets, interval, version, 201 metrics, bad JSON, wrong types, and 413 at 256 KiB. The exact limits pass (24 h, +10 min, 200 metrics, 20 bounds, a zero-length interval, a semver build).
    • Rate limit: 120 per hour, the 121st gets 429. Invalid and empty batches don't count, a colleague is unaffected, and the window slides.
    • Collector failure: 500 with the token and a marker in its body, 401, 302, and unreachable. All give 502 with nothing leaked to the response or the log.
    • Who reaches it: werkpilot-cli and firmwerk-cli user tokens with the deployed rules, plus a client granted telemetry. A sign-in client without licences, a licences service token and a missing principal are refused.
    • Setting is admin-only: USER, CXO and FINANCE get 403 on GET and PUT; another workspace's admin gets 404; IT_ADMIN and OWNER pass.
  • Flag (licence_telemetry_test.go, through eachStore):
    • false by default in the grant, heartbeat and CI grant;
    • after turning it on: a heartbeat for the old licence says true, new grants and the werkpilot CI grant say true, firmwerk stays false, and the renewed grant says true;
    • after turning it off: false again.
  • Setting: one audit event for one change; the unchanged save writes nothing. Bad bodies give 400; other products and an unknown tenant give 404; other document keys survive.
  • Route tables, spec and config: authz_test route groups, openapi_test route cases, config defaults and the on-prem refusal.
  • Mutation checks: the tests fail with each of these removed: the authz exception, the key allowlist, the value pattern, the enabled check, the admin gate.
  • Local checks: gofmt -l . clean, go vet ./... clean, golangci-lint run (v2.12.2) 0 issues, go test -race -count=1 ./... green.
  • Postgres: the eachStore Postgres variants skipped locally (Docker is unreachable here), so they run only in CI. The store calls are the existing GetTenantProductSettings / PutTenantProductSettings / AppendAudit.
  • Real collector: not tested against otel.breakpilot.com; no ingest token exists. The body is validated against the OTLP protobuf JSON mapping, not against the collector's config.
  • Manual smoke on stage after deploy.

Risk

Blast radius:

  • Licence answers: they gain one field, which old clients ignore.
  • Relay: inert (503) until configured, and forwards nothing for a tenant that hasn't opted in.

What could break:

  • Licence issue and heartbeat: each does one more settings read. A read error is treated as off and logged; it does not fail the call.
  • Relay: a collector outage surfaces only as 502 to the CLI.

Rollback plan:

  • Relay: unset TELEMETRY_OTLP_TOKEN (503).
  • Tenant: set the switch off for the tenant.
  • Full: revert the PR and redeploy.

Checklist

  • Docs updated (README env table, OpenAPI)
  • Audit events emitted for state changes (product_settings.changed; relay batches not audited, see How)
  • Secrets via Infisical, never in repo (TELEMETRY_OTLP_TOKEN is a deployment secret)
  • Migration is forward-only + idempotent (or no migration): no migration
  • Tenant scoping enforced on every DB query (or no DB access): the tenant comes from the path (scoped) or the principal
  • OpenAPI spec updated
  • featureFlags.evaluate() used for any toggleable behavior: n/a, the per-tenant switch is stored data and the token's presence turns the relay on
  • CHANGELOG entry under "Unreleased": n/a, the file is generated by git-cliff on release

Screenshots / recordings

n/a (no UI; the portal toggle is a follow-up)

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q9inRayW7ztyk1uAtwMJPR

## What The server half of opt-in, content-free telemetry (platform/werkpilot#87). - **Per-tenant, per-product switch**, default **off**: `GET/PUT /v1/tenants/{id}/products/{product}/telemetry`. - **`telemetry` boolean in the licence grants and the heartbeat**, so the CLI knows the switch. - **`POST /v1/telemetry` relay.** It checks a batch against a fixed allowlist and forwards it to the collector as OTLP/HTTP JSON. No ingest token ever sits on a customer machine. ## Why Refs platform/werkpilot#87. The agreed design: - **(a) registry relay**, so there is no ingest token on customer machines; - **(b) off unless enabled**: telemetry is sent only when the tenant has enabled it and the machine hasn't opted out locally. The local opt-out is client-side. The licence-client and werkpilot sides are built in parallel against this contract. Linked milestone: **n/a** (werkpilot#87) ## How **Setting** - Stored as the `telemetry` key of the product's `tenant_product_settings` document (0025), so no migration. The PUT reads the document, sets the key and writes it back; other keys survive (tested). - Only products with a telemetry allowlist take the switch: today `werkpilot`, others 404. The Prüfwerk settings PUT replaces its whole document, so the key must never land there. - `PUT {"enabled": true|false}` (exactly that body, else 400) answers `{tenant_id, product, enabled, updated_by, updated_at}`. - **Who may:** user tokens need IT_ADMIN or OWNER in their own workspace (403 `FORBIDDEN_ROLE`; another workspace gets 404). Services use `tenants.read` / `tenants.write`; the portal calls as its service client, as for the Prüfwerk settings. - **Audit:** a change is audited as `product_settings.changed` (`setting: telemetry`, old, new). A save that changes nothing writes nothing. - **The portal toggle is a follow-up**; this PR has no UI. **Flag in the licence answers** - `telemetry` (always present, default false) is a plain JSON field in the grant of `POST /v1/licences`, `POST /v1/licences/ci` and the `renewed` grant of a heartbeat. It is not a JWT claim. - The heartbeat answer carries it at the top level, next to `status`, read fresh on every call. It is false on the `revoked` / unknown-tenant answers. **Relay `POST /v1/telemetry`** - **Steps, in order:** 1. 503 `telemetry_unavailable` without a token. 2. 403 `user_token_required` for anything but a user token. 3. Decode, capped at 256 KiB (413 `too_large`). 4. Product known (400). 5. Tenant enabled, else 403 `telemetry_disabled` and nothing is forwarded. 6. Allowlist and validation (400 `invalid_input`, naming the metric index and name, or the key). 7. An empty `metrics` list answers 204 and forwards nothing. 8. Rate limit (429 `rate_limited`): 120 per user subject per sliding hour, in memory. Refused and empty batches don't count. 9. Forward: 204, or 502 `telemetry_failed`. - **Allowlist:** exactly the table in #87. Listed keys may be left out. Values must be JSON strings matching `^[A-Za-z0-9_.:-]{1,64}$`. - **Numbers:** counter values, histogram `count` and `bucket_counts` must be JSON integer literals ≥ 0, so `-1`, `1.5`, `3.0`, `1e3` and `"3"` are refused. `sum` is a number ≥ 0. At most 20 bounds, and `len(bounds)+1` bucket counts. - **Batch limits:** at most 200 metrics; the interval has end ≥ start, at most 24 h, and end at most 10 min ahead. - **Forwarding:** OTLP/HTTP JSON POST to `TELEMETRY_OTLP_URL` with `Authorization: Bearer <TELEMETRY_OTLP_TOKEN>`. - **Resource:** `service.name` (product), `service.version`, `tenant.slug`, `tenant.id`, `deployment.environment` (`APP_ENV`). - **Counters:** monotonic Sum, DELTA. **Histograms:** explicit-bucket Histogram, DELTA. Both use `startTimeUnixNano`/`timeUnixNano` from the interval. - Points of the same name become one metric with several data points; attributes are sorted. - **The user's subject and e-mail are never forwarded** (tested). - **Collector failure:** a non-2xx answer or a transport error is a 502. It is logged with the status only; the collector's body, the URL and the token never reach the response or the log. - **Authz:** new route group `telemetry`. A user token from a client holding `licences` (today `werkpilot-cli`, `firmwerk-cli`) passes without it, so the deployed AUTHZ_RULES need no change. A sign-in client without `licences` and a service token holding `licences` are refused (`FORBIDDEN_CLIENT`). - **No audit for batches:** CONTRIBUTING asks for audit events on state changes. The relay changes no registry state, and like `POST /v1/usage/events` it emits none; 120 batches per person and hour would flood the tenant's log. Only the setting change is audited. - **On-prem:** with `TELEMETRY_OTLP_TOKEN` set, `TELEMETRY_OTLP_URL` must be given explicitly, mirroring LiteLLM. - **New package `internal/otlp`:** the export builder and client. - **Dependencies:** `go.opentelemetry.io/proto/otlp` and `google.golang.org/protobuf` move from indirect to direct in `go.mod` (same versions, no new modules, `go.sum` unchanged). They are used only in a test, to check the forwarded body against the OTLP protobuf JSON mapping. **Stricter than #87 (declared in the spec):** - **`version`** is the only free-text field that is forwarded. It is constrained to `^[A-Za-z0-9.+_-]{1,64}$`, which covers semver with pre-release and build parts. - **`bounds`** must be strictly increasing, as OTLP requires. - **Not checked:** that `count` equals the sum of `bucket_counts`. **Overlap with #147 (feedback):** both PRs edit the same spots: the `requireAuthz` exception, the `routeGroup` switch, the `Server` struct, the route block, the config/README/onprem lists and the spec. Whichever merges second gets textual conflicts to resolve (keep both). No identifiers are shared, so the merged code compiles once the conflicts are resolved. ## Going live (orca, not in this PR) After merge and deploy, the relay answers 503 until: 1. **Token:** a `TELEMETRY_OTLP_TOKEN` is added to the collector's `bearertokenauth/ingest` token list in orca-infra, and the same value to the registry's deployment secret (`platform-stage` / `platform-prod`). 2. **Tenant:** an administrator turns it on for the tenant (`PUT /v1/tenants/{id}/products/werkpilot/telemetry {"enabled":true}`; until the portal toggle exists, through the portal's service client or staff). No tokens were created for this PR. ## Test plan - [x] **Relay** (`telemetry_relay_test.go`, fake collector): - **204 forwarding:** the exact OTLP JSON (resource, scope, grouping, sorted attributes, string-encoded 64-bit integers, DELTA = 1, `isMonotonic`), the bearer header and path. The same bytes `protojson.Unmarshal` into `ExportMetricsServiceRequest` (temporality, monotonic, values, bucket counts, interval), and neither the subject nor the e-mail is present. - **403 `telemetry_disabled`:** for a tenant never enabled, one turned off, and when the body names another tenant. Nothing is forwarded. - **503** without a token. - **Allowlist rejections (17 cases):** product, metric, kind, unlisted key, a key of another metric, a key on a key-less metric, a bad or long or empty value, and non-string values. Every listed metric and key passes. - **Validation (29 cases):** integers, sums, bounds, buckets, interval, version, 201 metrics, bad JSON, wrong types, and 413 at 256 KiB. The exact limits pass (24 h, +10 min, 200 metrics, 20 bounds, a zero-length interval, a semver build). - **Rate limit:** 120 per hour, the 121st gets 429. Invalid and empty batches don't count, a colleague is unaffected, and the window slides. - **Collector failure:** 500 with the token and a marker in its body, 401, 302, and unreachable. All give 502 with nothing leaked to the response or the log. - **Who reaches it:** `werkpilot-cli` and `firmwerk-cli` user tokens with the deployed rules, plus a client granted `telemetry`. A sign-in client without `licences`, a `licences` service token and a missing principal are refused. - **Setting is admin-only:** USER, CXO and FINANCE get 403 on GET and PUT; another workspace's admin gets 404; IT_ADMIN and OWNER pass. - [x] **Flag** (`licence_telemetry_test.go`, through `eachStore`): - false by default in the grant, heartbeat and CI grant; - after turning it on: a heartbeat for the old licence says true, new grants and the werkpilot CI grant say true, firmwerk stays false, and the renewed grant says true; - after turning it off: false again. - [x] **Setting:** one audit event for one change; the unchanged save writes nothing. Bad bodies give 400; other products and an unknown tenant give 404; other document keys survive. - [x] **Route tables, spec and config:** `authz_test` route groups, `openapi_test` route cases, config defaults and the on-prem refusal. - [x] **Mutation checks:** the tests fail with each of these removed: the authz exception, the key allowlist, the value pattern, the enabled check, the admin gate. - [x] **Local checks:** `gofmt -l .` clean, `go vet ./...` clean, `golangci-lint run` (v2.12.2) 0 issues, `go test -race -count=1 ./...` green. - [ ] **Postgres:** the `eachStore` Postgres variants skipped locally (Docker is unreachable here), so they run only in CI. The store calls are the existing `GetTenantProductSettings` / `PutTenantProductSettings` / `AppendAudit`. - [ ] **Real collector:** not tested against otel.breakpilot.com; no ingest token exists. The body is validated against the OTLP protobuf JSON mapping, not against the collector's config. - [ ] Manual smoke on stage after deploy. ## Risk **Blast radius:** - **Licence answers:** they gain one field, which old clients ignore. - **Relay:** inert (503) until configured, and forwards nothing for a tenant that hasn't opted in. **What could break:** - **Licence issue and heartbeat:** each does one more settings read. A read error is treated as off and logged; it does not fail the call. - **Relay:** a collector outage surfaces only as 502 to the CLI. **Rollback plan:** - **Relay:** unset `TELEMETRY_OTLP_TOKEN` (503). - **Tenant:** set the switch off for the tenant. - **Full:** revert the PR and redeploy. ## Checklist - [x] Docs updated (README env table, OpenAPI) - [x] Audit events emitted for state changes (`product_settings.changed`; relay batches not audited, see How) - [x] Secrets via Infisical, never in repo (`TELEMETRY_OTLP_TOKEN` is a deployment secret) - [x] Migration is forward-only + idempotent (or no migration): no migration - [x] Tenant scoping enforced on every DB query (or no DB access): the tenant comes from the path (scoped) or the principal - [x] OpenAPI spec updated - [ ] `featureFlags.evaluate()` used for any toggleable behavior: n/a, the per-tenant switch is stored data and the token's presence turns the relay on - [ ] CHANGELOG entry under "Unreleased": n/a, the file is generated by git-cliff on release ## Screenshots / recordings n/a (no UI; the portal toggle is a follow-up) 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Q9inRayW7ztyk1uAtwMJPR
sharang added 1 commit 2026-11-23 14:26:27 +00:00
feat(telemetry): opt-in product telemetry relay and per-tenant switch
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Successful in 6m57s
ci / image (pull_request) Skipped
849e79ada0
Werkpilot's content-free usage metrics go through the registry, so no
collector token sits on customer machines, and only for workspaces that
turned telemetry on.

- GET/PUT /v1/tenants/{id}/products/{product}/telemetry: the switch,
  default off, kept as the "telemetry" key of the product's settings
  document (0025, no migration); IT_ADMIN/OWNER or services; audited as
  product_settings.changed
- "telemetry" in licence grants (POST /v1/licences, /v1/licences/ci,
  heartbeat renewals) and at the top of the heartbeat answer
- POST /v1/telemetry: checks a batch against a fixed allowlist and
  forwards it to TELEMETRY_OTLP_URL as OTLP/HTTP JSON (delta sums and
  histograms, tenant resource attributes, never the person); 120 batches
  per person and hour; CLI user tokens pass with their licences grant

Refs platform/werkpilot#87

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRayW7ztyk1uAtwMJPR
CODEOWNERS rules requested review from Benjamin_Boenisch 2026-11-23 14:26:27 +00:00
All checks were successful
ci / shared (pull_request) Successful in 12s
Required
Details
ci / test (pull_request) Successful in 6m57s
ci / image (pull_request) Skipped
You are not authorized to merge this pull request.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin feat/telemetry-relay:feat/telemetry-relay
git checkout feat/telemetry-relay
Sign in to join this conversation.