diff --git a/README.md b/README.md index 3602646..f804388 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ Env vars (override at the shell): | `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` | +| `TELEMETRY_OTLP_TOKEN` | empty (`POST /v1/telemetry` answers 503) | Secret. Bearer token for the collector's ingest (`bearertokenauth/ingest`); sent only in the `Authorization` header. On-prem it needs `TELEMETRY_OTLP_URL` set explicitly | +| `TELEMETRY_OTLP_URL` | `https://otel.breakpilot.com/v1/metrics` | OTLP/HTTP JSON metrics endpoint the CLI telemetry relay forwards to | | `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) | diff --git a/go.mod b/go.mod index 026abc9..68e8823 100644 --- a/go.mod +++ b/go.mod @@ -16,8 +16,10 @@ require ( go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 go.opentelemetry.io/otel/sdk v1.47.0 go.opentelemetry.io/otel/trace v1.47.0 + go.opentelemetry.io/proto/otlp v1.11.0 golang.org/x/crypto v0.58.0 golang.org/x/image v0.48.0 + google.golang.org/protobuf v1.36.12 ) require ( @@ -86,7 +88,6 @@ require ( go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect go.opentelemetry.io/otel/log v1.47.0 // indirect go.opentelemetry.io/otel/metric v1.47.0 // indirect - go.opentelemetry.io/proto/otlp v1.11.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/net v0.62.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect @@ -96,5 +97,4 @@ require ( google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect google.golang.org/grpc v1.83.2 // indirect - google.golang.org/protobuf v1.36.12 // indirect ) diff --git a/internal/config/config.go b/internal/config/config.go index 31ecb62..598ccd9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -136,6 +136,12 @@ type Config struct { LiteLLMModels []string LiteLLMBudgetTrial float64 LiteLLMBudgetDefault float64 + + // Product telemetry relay (POST /v1/telemetry, werkpilot#87): batches + // from the CLIs go on to the collector as OTLP/HTTP JSON with this + // bearer token. An empty token turns the relay off (503). + TelemetryOTLPURL string + TelemetryOTLPToken string } func Load() (*Config, error) { @@ -235,6 +241,9 @@ func Load() (*Config, error) { LiteLLMBudgetTrial: getfloat("LITELLM_BUDGET_TRIAL", 5), LiteLLMBudgetDefault: getfloat("LITELLM_BUDGET_DEFAULT", 50), + TelemetryOTLPURL: getenv("TELEMETRY_OTLP_URL", "https://otel.breakpilot.com/v1/metrics"), + TelemetryOTLPToken: os.Getenv("TELEMETRY_OTLP_TOKEN"), + Products: getlist("PRODUCTS", nil), LaunchURLs: launch, ProvisionURLs: provision, @@ -280,6 +289,9 @@ func (c *Config) checkOnPrem() error { if c.LiteLLMMasterKey != "" { need("LITELLM_BASE_URL") } + if c.TelemetryOTLPToken != "" { + need("TELEMETRY_OTLP_URL") + } if len(missing) > 0 { return fmt.Errorf("APP_ENV=onprem needs %s", strings.Join(missing, ", ")) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index b5e93fa..73ca5a7 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -9,6 +9,8 @@ func TestLoad_defaults(t *testing.T) { t.Setenv("ADDR", "") t.Setenv("KEYCLOAK_ISSUER", "") t.Setenv("DATABASE_URL", "") + t.Setenv("TELEMETRY_OTLP_URL", "") + t.Setenv("TELEMETRY_OTLP_TOKEN", "") cfg, err := Load() if err != nil { @@ -26,6 +28,9 @@ func TestLoad_defaults(t *testing.T) { if cfg.DatabaseURL != "" { t.Errorf("DatabaseURL = %q, want empty default", cfg.DatabaseURL) } + if cfg.TelemetryOTLPURL != "https://otel.breakpilot.com/v1/metrics" || cfg.TelemetryOTLPToken != "" { + t.Errorf("telemetry = %q token set %v", cfg.TelemetryOTLPURL, cfg.TelemetryOTLPToken != "") + } } func TestLoad_overrides(t *testing.T) { diff --git a/internal/config/onprem_test.go b/internal/config/onprem_test.go index 551d73b..171b4f4 100644 --- a/internal/config/onprem_test.go +++ b/internal/config/onprem_test.go @@ -33,6 +33,7 @@ func onPremEnv(t *testing.T) { t.Setenv(k, v) } for _, k := range []string{"ERP_BASE_URL", "ERP_WEBHOOK_SECRET", "CONTRACT_DOCUMENTS", "LITELLM_MASTER_KEY", "LITELLM_BASE_URL", "SMTP_USER", + "TELEMETRY_OTLP_TOKEN", "TELEMETRY_OTLP_URL", "LEGAL_IMPRINT_URL", "LEGAL_PRIVACY_URL", "MAIL_CONTACT", "MAIL_FROM_NAME"} { t.Setenv(k, "") } @@ -73,6 +74,7 @@ func TestLoad_onPremRefusesCloudDefaults(t *testing.T) { {"an ERP", "ERP_BASE_URL", "https://erp.onprem.test", "no ERP"}, {"contract documents", "CONTRACT_DOCUMENTS", "on", "contract documents"}, {"LLM key without gateway", "LITELLM_MASTER_KEY", "x", "LITELLM_BASE_URL"}, + {"telemetry token without collector", "TELEMETRY_OTLP_TOKEN", "x", "TELEMETRY_OTLP_URL"}, {"product without tile", "PRODUCTS", "pruefwerk,firmwerk", `"firmwerk"`}, {"our sender", "MAIL_FROM", "noreply@breakpilot.com", "MAIL_FROM points at breakpilot.com"}, {"our portal", "PORTAL_URL", "https://app.breakpilot.com", "PORTAL_URL points"}, diff --git a/internal/otlp/otlp.go b/internal/otlp/otlp.go new file mode 100644 index 0000000..ba10302 --- /dev/null +++ b/internal/otlp/otlp.go @@ -0,0 +1,224 @@ +// Package otlp builds OTLP/HTTP JSON metric exports and sends them to a +// collector: the relay for product telemetry (werkpilot#87). Only delta +// counters (monotonic sums) and explicit-bucket histograms are supported. +package otlp + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strconv" + "time" +) + +// aggregationDelta is AGGREGATION_TEMPORALITY_DELTA; OTLP JSON encodes +// enums as integers. +const aggregationDelta = 1 + +const maxResponse = 1 << 20 + +// Metric is one data point. Histogram false: a counter, Value. Histogram +// true: Count, Sum, Bounds and BucketCounts (len(Bounds)+1). +type Metric struct { + Name string + Attributes map[string]string + Histogram bool + Value uint64 + Count uint64 + Sum float64 + Bounds []float64 + BucketCounts []uint64 +} + +// Attribute is a resource attribute; the order given is the order sent. +type Attribute struct { + Key, Value string +} + +// MetricsRequest is the ExportMetricsServiceRequest for one resource and +// one interval. Points of the same name become one metric with several +// data points, in the order the names first appear; point attributes are +// sorted by key. +func MetricsRequest(resource []Attribute, scope string, start, end time.Time, metrics []Metric) ([]byte, error) { + startNano, endNano := strconv.FormatInt(start.UnixNano(), 10), strconv.FormatInt(end.UnixNano(), 10) + var order []string + byName := map[string]*metricJSON{} + for _, m := range metrics { + out, seen := byName[m.Name] + if !seen { + out = &metricJSON{Name: m.Name} + byName[m.Name] = out + order = append(order, m.Name) + } + point := dataPointJSON{Attributes: attributes(m.Attributes), StartTimeUnixNano: startNano, TimeUnixNano: endNano} + switch { + case m.Histogram: + if out.Sum != nil { + return nil, fmt.Errorf("otlp: %s is both a counter and a histogram", m.Name) + } + if out.Histogram == nil { + out.Histogram = &histogramJSON{AggregationTemporality: aggregationDelta} + } + count, sum := strconv.FormatUint(m.Count, 10), m.Sum + point.Count, point.Sum = &count, &sum + point.BucketCounts = make([]string, len(m.BucketCounts)) + for i, n := range m.BucketCounts { + point.BucketCounts[i] = strconv.FormatUint(n, 10) + } + point.ExplicitBounds = append([]float64{}, m.Bounds...) + out.Histogram.DataPoints = append(out.Histogram.DataPoints, point) + default: + if out.Histogram != nil { + return nil, fmt.Errorf("otlp: %s is both a counter and a histogram", m.Name) + } + if out.Sum == nil { + out.Sum = &sumJSON{AggregationTemporality: aggregationDelta, IsMonotonic: true} + } + v := strconv.FormatUint(m.Value, 10) + point.AsInt = &v + out.Sum.DataPoints = append(out.Sum.DataPoints, point) + } + } + res := resourceMetricsJSON{Resource: resourceJSON{Attributes: []keyValueJSON{}}} + for _, a := range resource { + res.Resource.Attributes = append(res.Resource.Attributes, keyValueJSON{Key: a.Key, Value: anyValueJSON{StringValue: a.Value}}) + } + sm := scopeMetricsJSON{Scope: scopeJSON{Name: scope}, Metrics: []metricJSON{}} + for _, name := range order { + sm.Metrics = append(sm.Metrics, *byName[name]) + } + res.ScopeMetrics = []scopeMetricsJSON{sm} + return json.Marshal(exportJSON{ResourceMetrics: []resourceMetricsJSON{res}}) +} + +func attributes(in map[string]string) []keyValueJSON { + keys := make([]string, 0, len(in)) + for k := range in { + keys = append(keys, k) + } + sort.Strings(keys) + out := make([]keyValueJSON, 0, len(keys)) + for _, k := range keys { + out = append(out, keyValueJSON{Key: k, Value: anyValueJSON{StringValue: in[k]}}) + } + return out +} + +type exportJSON struct { + ResourceMetrics []resourceMetricsJSON `json:"resourceMetrics"` +} + +type resourceMetricsJSON struct { + Resource resourceJSON `json:"resource"` + ScopeMetrics []scopeMetricsJSON `json:"scopeMetrics"` +} + +type resourceJSON struct { + Attributes []keyValueJSON `json:"attributes"` +} + +type scopeMetricsJSON struct { + Scope scopeJSON `json:"scope"` + Metrics []metricJSON `json:"metrics"` +} + +type scopeJSON struct { + Name string `json:"name"` +} + +type metricJSON struct { + Name string `json:"name"` + Sum *sumJSON `json:"sum,omitempty"` + Histogram *histogramJSON `json:"histogram,omitempty"` +} + +type sumJSON struct { + AggregationTemporality int `json:"aggregationTemporality"` + IsMonotonic bool `json:"isMonotonic"` + DataPoints []dataPointJSON `json:"dataPoints"` +} + +type histogramJSON struct { + AggregationTemporality int `json:"aggregationTemporality"` + DataPoints []dataPointJSON `json:"dataPoints"` +} + +// dataPointJSON covers NumberDataPoint (AsInt) and HistogramDataPoint +// (Count, Sum, BucketCounts, ExplicitBounds). 64-bit integers are strings +// in OTLP JSON. +type dataPointJSON struct { + Attributes []keyValueJSON `json:"attributes"` + StartTimeUnixNano string `json:"startTimeUnixNano"` + TimeUnixNano string `json:"timeUnixNano"` + AsInt *string `json:"asInt,omitempty"` + Count *string `json:"count,omitempty"` + Sum *float64 `json:"sum,omitempty"` + BucketCounts []string `json:"bucketCounts,omitempty"` + ExplicitBounds []float64 `json:"explicitBounds,omitempty"` +} + +type keyValueJSON struct { + Key string `json:"key"` + Value anyValueJSON `json:"value"` +} + +type anyValueJSON struct { + StringValue string `json:"stringValue"` +} + +// Client posts exports. The zero value uses http.DefaultClient. +type Client struct { + HTTP *http.Client +} + +// ErrStatus is a non-2xx answer from the collector. Its message carries the +// status only, never the response body. +type ErrStatus struct{ Code int } + +func (e *ErrStatus) Error() string { return "otlp: status " + strconv.Itoa(e.Code) } + +// Export posts body (an ExportMetricsServiceRequest as JSON) to endpoint +// with the bearer token. The token goes in the Authorization header only; +// errors name neither it, the endpoint nor the collector's answer. +func (c *Client) Export(ctx context.Context, endpoint, token string, body []byte) error { + if token == "" { + return errors.New("otlp: no token") + } + u, err := url.Parse(endpoint) + if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") { + return errors.New("otlp: invalid collector url") + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(body)) + if err != nil { + return errors.New("otlp: build request") + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + hc := http.DefaultClient + if c != nil && c.HTTP != nil { + hc = c.HTTP + } + resp, err := hc.Do(req) + if err != nil { + var ue *url.Error + if errors.As(err, &ue) && ue.Timeout() { + return errors.New("otlp: request timed out") + } + if ctx.Err() != nil { + return fmt.Errorf("otlp: %w", ctx.Err()) + } + return errors.New("otlp: request failed") + } + defer func() { _ = resp.Body.Close() }() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponse)) + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return &ErrStatus{Code: resp.StatusCode} + } + return nil +} diff --git a/internal/server/authz.go b/internal/server/authz.go index c632eb5..97308eb 100644 --- a/internal/server/authz.go +++ b/internal/server/authz.go @@ -110,6 +110,8 @@ func routeGroup(method, path string) string { return "tenants.read" case strings.HasPrefix(path, "/v1/licences"): return "licences" + case path == "/v1/telemetry": + return "telemetry" case strings.HasPrefix(path, "/v1/trial-offers"): return "tenants.write" case strings.HasPrefix(path, "/v1/tenants"): @@ -151,6 +153,12 @@ func (s *Server) requireAuthz(next http.Handler) http.Handler { if p.IsUser() && isIntakeUserPath(r.URL.Path) { group = "intake.user" } + // A CLI that signs people in (group licences: werkpilot-cli, + // firmwerk-cli) may also relay their telemetry (werkpilot#87) + // without another grant; the handler takes user tokens only. + if group == "telemetry" && p.IsUser() && !s.Authz.Allowed(p.ClientID, group) && s.Authz.Allowed(p.ClientID, "licences") { + group = "licences" + } if !s.Authz.Allowed(p.ClientID, group) { s.Log.Warn("client not authorized for route group", "azp", p.ClientID, "group", group, "path", r.URL.Path) writeError(w, http.StatusForbidden, "FORBIDDEN_CLIENT", "client "+p.ClientID+" may not call "+group) diff --git a/internal/server/authz_test.go b/internal/server/authz_test.go index 4bc9099..07b1ccd 100644 --- a/internal/server/authz_test.go +++ b/internal/server/authz_test.go @@ -3,7 +3,7 @@ package server import "testing" func TestAuthzRules(t *testing.T) { - a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write,connections.read; werkpilot-svc:tenants.read; root:* ;broken") + a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write,connections.read; werkpilot-svc:tenants.read; werkpilot-cli:licences,usage; root:* ;broken") cases := []struct { azp, method, path string want bool @@ -30,6 +30,13 @@ func TestAuthzRules(t *testing.T) { {"portal-svc", "GET", "/v1/internal/connections/c1", false}, {"portal-svc", "POST", "/v1/tenants/t1/connections", true}, {"pruefwerk-svc", "POST", "/v1/tenants/t1/connection-invites", false}, + // Telemetry (werkpilot#87): its own group; CLI user tokens pass + // through requireAuthz (telemetry_relay_test.go). + {"werkpilot-cli", "POST", "/v1/telemetry", false}, + {"root", "POST", "/v1/telemetry", true}, + {"portal-svc", "PUT", "/v1/tenants/t1/products/werkpilot/telemetry", true}, + {"pruefwerk-svc", "GET", "/v1/tenants/t1/products/werkpilot/telemetry", true}, + {"pruefwerk-svc", "PUT", "/v1/tenants/t1/products/werkpilot/telemetry", false}, } for _, c := range cases { if got := a.Allowed(c.azp, routeGroup(c.method, c.path)); got != c.want { diff --git a/internal/server/licence_telemetry_test.go b/internal/server/licence_telemetry_test.go new file mode 100644 index 0000000..f46eb63 --- /dev/null +++ b/internal/server/licence_telemetry_test.go @@ -0,0 +1,148 @@ +package server_test + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +type grantTelemetry struct { + Licence string `json:"licence"` + Telemetry *bool `json:"telemetry"` +} + +type heartbeatTelemetry struct { + Status string `json:"status"` + Telemetry *bool `json:"telemetry"` + Renewed *grantTelemetry `json:"renewed"` +} + +func telemetryPath(h *testHarness, product string) string { + return "/v1/tenants/" + h.tenant.ID + "/products/" + product + "/telemetry" +} + +// The grants and the heartbeat carry the workspace's current telemetry +// switch for the licence's product, false until an administrator turns it on. +func TestLicences_telemetryFollowsTheSetting(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + fake := newFakeLiteLLM(t) + h.app.LLMKeys = fake.client() + entitle(t, h, "werkpilot", true) + entitle(t, h, "firmwerk", true) + issue := func() grantTelemetry { + t.Helper() + resp, raw := h.do("POST", "/v1/licences", map[string]any{"tenant_id": h.tenant.ID, "product": "werkpilot", "device": "laptop"}) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("issue: %d %s", resp.StatusCode, raw) + } + return decode[grantTelemetry](t, raw) + } + beat := func(lic string) heartbeatTelemetry { + t.Helper() + _, raw := h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic}) + return decode[heartbeatTelemetry](t, raw) + } + key := ciKey(t, h, "ci", "werkpilot:licence", "firmwerk:licence") + ci := func(product, device string) bool { + t.Helper() + code, _, body := postCI(t, h, key, product, device) + g := decode[grantTelemetry](t, []byte(body)) + if code != http.StatusCreated && code != http.StatusOK || g.Telemetry == nil { + t.Fatalf("ci %s: %d %s", product, code, body) + } + return *g.Telemetry + } + + g := issue() + if g.Telemetry == nil || *g.Telemetry { + t.Fatalf("default grant: %+v", g) + } + if hb := beat(g.Licence); hb.Telemetry == nil || *hb.Telemetry { + t.Fatalf("default heartbeat: %+v", hb) + } + if ci("werkpilot", "r-1") { + t.Fatal("default CI grant says on") + } + resp, raw := h.do("GET", telemetryPath(h, "werkpilot"), nil) + if resp.StatusCode != http.StatusOK || !bytes.Contains(raw, []byte(`"enabled":false`)) { + t.Fatalf("default setting: %d %s", resp.StatusCode, raw) + } + + resp, raw = h.do("PUT", telemetryPath(h, "werkpilot"), map[string]any{"enabled": true}) + if resp.StatusCode != http.StatusOK || !bytes.Contains(raw, []byte(`"enabled":true`)) || !bytes.Contains(raw, []byte(`"updated_at"`)) { + t.Fatalf("turn on: %d %s", resp.StatusCode, raw) + } + if resp, raw := h.do("PUT", telemetryPath(h, "werkpilot"), map[string]any{"enabled": true}); resp.StatusCode != http.StatusOK { + t.Fatalf("unchanged: %d %s", resp.StatusCode, raw) + } + events, _, err := h.store.ListAudit(context.Background(), store.AuditFilter{TenantID: h.tenant.ID, Action: "product_settings.changed"}) + if err != nil || len(events) != 1 || events[0].TargetID != "werkpilot" || events[0].Metadata["setting"] != "telemetry" || + events[0].Metadata["old"] != false || events[0].Metadata["new"] != true { + t.Fatalf("audit (one change, the unchanged save writes nothing): %v %+v", err, events) + } + + // Licences issued before the change learn it at the next heartbeat; + // a renewal inside it carries it too. + if hb := beat(g.Licence); hb.Telemetry == nil || !*hb.Telemetry { + t.Fatalf("heartbeat after turning on: %+v", hb) + } + if g2 := issue(); !*g2.Telemetry { + t.Fatalf("grant after turning on: %+v", g2) + } + if !ci("werkpilot", "r-2") || ci("firmwerk", "r-1") { + t.Fatal("CI grants: werkpilot on, firmwerk (no telemetry) off") + } + // Past half-life of the 30-day licence: renewed. + h.app.Now = func() time.Time { return time.Now().Add(20 * 24 * time.Hour) } + hb := beat(g.Licence) + h.app.Now = nil + if hb.Renewed == nil || hb.Renewed.Telemetry == nil || !*hb.Renewed.Telemetry || !*hb.Telemetry { + t.Fatalf("renewal: %+v", hb) + } + + if resp, raw := h.do("PUT", telemetryPath(h, "werkpilot"), map[string]any{"enabled": false}); resp.StatusCode != http.StatusOK || !bytes.Contains(raw, []byte(`"enabled":false`)) { + t.Fatalf("turn off: %d %s", resp.StatusCode, raw) + } + if g3 := issue(); *g3.Telemetry { + t.Fatalf("grant after turning off: %+v", g3) + } + }) +} + +func TestProductTelemetry_isChecked(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + for _, body := range []string{`{}`, `{"enabled":"yes"}`, `{"enabled":null}`, `{"enabled":1}`, `{"enabled":true,"other":1}`, `[]`, `nope`} { + if resp, raw := h.doRaw("PUT", telemetryPath(h, "werkpilot"), body); resp.StatusCode != http.StatusBadRequest { + t.Errorf("%s: %d %s", body, resp.StatusCode, raw) + } + } + // Only products with a telemetry allowlist take the switch. + for _, product := range []string{"pruefwerk", "firmwerk", "nope"} { + if resp, _ := h.do("PUT", telemetryPath(h, product), map[string]any{"enabled": true}); resp.StatusCode != http.StatusNotFound { + t.Errorf("%s: %d", product, resp.StatusCode) + } + } + if resp, _ := h.do("GET", "/v1/tenants/00000000-0000-0000-0000-00000000dead/products/werkpilot/telemetry", nil); resp.StatusCode != http.StatusNotFound { + t.Errorf("unknown tenant: %d", resp.StatusCode) + } + // Other keys of the product's settings document survive. + if _, err := h.store.PutTenantProductSettings(context.Background(), store.TenantProductSettings{ + TenantID: h.tenant.ID, Product: "werkpilot", Settings: json.RawMessage(`{"keep":42}`), UpdatedAt: time.Now(), + }); err != nil { + t.Fatal(err) + } + if resp, raw := h.do("PUT", telemetryPath(h, "werkpilot"), map[string]any{"enabled": true}); resp.StatusCode != http.StatusOK { + t.Fatalf("turn on: %d %s", resp.StatusCode, raw) + } + row, err := h.store.GetTenantProductSettings(context.Background(), h.tenant.ID, "werkpilot") + var doc map[string]any + if err != nil || json.Unmarshal(row.Settings, &doc) != nil || doc["keep"] != float64(42) || doc["telemetry"] != true { + t.Fatalf("settings document: %v %s", err, row.Settings) + } + }) +} diff --git a/internal/server/licences.go b/internal/server/licences.go index 171f3bb..0c7d4d3 100644 --- a/internal/server/licences.go +++ b/internal/server/licences.go @@ -41,7 +41,10 @@ type licenceResp struct { // D6: Werkpilot grants carry a per-tenant LiteLLM virtual key. The // secret is returned in this response only — never persisted, never // returned again. Absent (with a warning) when LiteLLM is off/down. - LLMAPIKey string `json:"llm_api_key,omitempty"` + LLMAPIKey string `json:"llm_api_key,omitempty"` + // Telemetry is the workspace's telemetry switch for the product + // (werkpilot#87). Informational: POST /v1/telemetry enforces it itself. + Telemetry bool `json:"telemetry"` LLMBaseURL string `json:"llm_base_url,omitempty"` Warnings []string `json:"warnings,omitempty"` } @@ -150,7 +153,8 @@ func (s *Server) issue(ctx context.Context, r *http.Request, in issueLicenceReq, if err != nil { return nil, http.StatusInternalServerError, "internal", err.Error() } - out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: exp, Grace: licence.DefaultGrace, Status: "ok"} + out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: exp, Grace: licence.DefaultGrace, Status: "ok", + Telemetry: s.telemetryEnabled(ctx, t.ID, in.Product)} llmKey := s.provisionLLMKey(ctx, t, row, renewOf, out, "") s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "licence.issued", TargetID: row.ID, TargetType: "licence", ActorID: subject, Product: in.Product, Metadata: map[string]interface{}{"device": in.Device, "expires_at": exp.Format(time.RFC3339), "llm_key": llmKey}}) @@ -240,6 +244,7 @@ type heartbeatResp struct { ExpiresAt time.Time `json:"expires_at"` Reason string `json:"reason,omitempty"` Renewed *licenceResp `json:"renewed,omitempty"` + Telemetry bool `json:"telemetry"` } // licenceHeartbeat — POST /v1/licences/heartbeat (PUBLIC_EXPLICIT; the JWT @@ -282,6 +287,7 @@ func (s *Server) licenceHeartbeat(w http.ResponseWriter, r *http.Request) { return } out.TenantStatus = t.Status + out.Telemetry = s.telemetryEnabled(ctx, t.ID, row.Product) check, err := s.evaluateEntitlement(ctx, entitlementCheckReq{TenantID: t.ID, Product: row.Product}) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) diff --git a/internal/server/licences_ci.go b/internal/server/licences_ci.go index e3d0a42..045f01c 100644 --- a/internal/server/licences_ci.go +++ b/internal/server/licences_ci.go @@ -152,7 +152,8 @@ func (s *Server) issueCILicence(w http.ResponseWriter, r *http.Request) { 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"} + out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: row.ExpiresAt, Grace: licence.DefaultGrace, Status: "ok", + Telemetry: s.telemetryEnabled(ctx, t.ID, in.Product)} if in.Product == llmKeyProduct { if err := s.ciLLMKey(ctx, t, row, subject, day, out); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 3b05e94..f32d077 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -108,6 +108,10 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"POST", "/v1/licences/heartbeat"}, {"POST", "/v1/licences/ci"}, {"POST", "/v1/licences/00000000-0000-0000-0000-000000000001/revoke"}, + {"POST", "/v1/telemetry"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/werkpilot/telemetry"}, + {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/werkpilot/telemetry"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/pruefwerk/settings"}, {"GET", "/.well-known/licence-keys.json"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/managed-services"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/contracts"}, diff --git a/internal/server/product_telemetry.go b/internal/server/product_telemetry.go new file mode 100644 index 0000000..628cb37 --- /dev/null +++ b/internal/server/product_telemetry.go @@ -0,0 +1,167 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// ─── product telemetry switch (werkpilot#87) ────────────────────────────── +// +// A workspace opts in to content-free usage telemetry per product; off +// until an administrator turns it on. The choice is the "telemetry" key of +// the product's settings document (0025). Only products with a metric +// allowlist (telemetryMetrics) take it: the Prüfwerk settings PUT replaces +// its whole document, so the key must never land there. + +const telemetrySettingKey = "telemetry" + +type productTelemetryResp struct { + TenantID string `json:"tenant_id"` + Product string `json:"product"` + Enabled bool `json:"enabled"` + UpdatedBy string `json:"updated_by,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +// telemetryEnabled is the workspace's current choice for product. No +// settings, or settings that cannot be read, mean off. +func (s *Server) telemetryEnabled(ctx context.Context, tenantID, product string) bool { + on, _, err := s.loadProductTelemetry(ctx, tenantID, product) + if err != nil { + s.Log.Warn("telemetry setting unreadable; treated as off", "tenant_id", tenantID, "product", product, "err", err) + return false + } + return on +} + +// loadProductTelemetry returns the switch and the settings row (nil when +// none was saved). +func (s *Server) loadProductTelemetry(ctx context.Context, tenantID, product string) (bool, *store.TenantProductSettings, error) { + if _, ok := telemetryMetrics[product]; !ok { + return false, nil, nil + } + row, err := s.Store.GetTenantProductSettings(ctx, tenantID, product) + if errors.Is(err, store.ErrNotFound) { + return false, nil, nil + } + if err != nil { + return false, nil, err + } + var doc map[string]json.RawMessage + if err := json.Unmarshal(row.Settings, &doc); err != nil { + return false, nil, err + } + var on bool + if raw, ok := doc[telemetrySettingKey]; ok { + if err := json.Unmarshal(raw, &on); err != nil { + return false, nil, err + } + } + return on, row, nil +} + +// productTelemetryScope resolves the tenant and product of a setting route. +// User tokens need IT_ADMIN or OWNER in their own workspace; services pass +// with tenants.read / tenants.write. On false the response is written. +func (s *Server) productTelemetryScope(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, string, bool) { + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !p.IsTenantAdmin() { + writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "the telemetry setting requires the IT_ADMIN or OWNER org role") + return nil, "", false + } + product := r.PathValue("product") + if _, ok := telemetryMetrics[product]; !ok { + writeError(w, http.StatusNotFound, "not_found", "no telemetry for this product") + return nil, "", false + } + t, ok := s.tenantInScope(ctx, w, r) + return t, product, ok +} + +func productTelemetryAnswer(tenantID, product string, on bool, row *store.TenantProductSettings) productTelemetryResp { + out := productTelemetryResp{TenantID: tenantID, Product: product, Enabled: on} + if row != nil { + at := row.UpdatedAt + out.UpdatedBy, out.UpdatedAt = row.UpdatedBy, &at + } + return out +} + +// getProductTelemetry is GET /v1/tenants/{id}/products/{product}/telemetry. +func (s *Server) getProductTelemetry(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, product, ok := s.productTelemetryScope(ctx, w, r) + if !ok { + return + } + on, row, err := s.loadProductTelemetry(ctx, t.ID, product) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, productTelemetryAnswer(t.ID, product, on, row)) +} + +// putProductTelemetry is PUT /v1/tenants/{id}/products/{product}/telemetry +// with {"enabled": bool}. A save that changes nothing writes nothing. +func (s *Server) putProductTelemetry(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, product, ok := s.productTelemetryScope(ctx, w, r) + if !ok { + return + } + r.Body = http.MaxBytesReader(w, r.Body, 4096) + var in map[string]json.RawMessage + if !decodeJSON(w, r, &in) { + return + } + var next bool + raw, has := in["enabled"] + if in == nil || len(in) != 1 || !has || json.Unmarshal(raw, &next) != nil || string(raw) == "null" { + writeError(w, http.StatusBadRequest, "invalid_input", `the body is {"enabled": true|false}`) + return + } + cur, row, err := s.loadProductTelemetry(ctx, t.ID, product) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if cur == next { + writeJSON(w, http.StatusOK, productTelemetryAnswer(t.ID, product, cur, row)) + return + } + doc := map[string]json.RawMessage{} + if row != nil { + if err := json.Unmarshal(row.Settings, &doc); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + } + doc[telemetrySettingKey], _ = json.Marshal(next) + settings, _ := json.Marshal(doc) + actor := s.teamActor(r) + saved, err := s.Store.PutTenantProductSettings(ctx, store.TenantProductSettings{ + TenantID: t.ID, Product: product, Settings: settings, + UpdatedBy: firstNonEmpty(actor.Email, actor.ID), UpdatedAt: s.now(), + }) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "product_settings.changed", TargetID: product, TargetType: "product_settings", + TargetName: product, ActorID: actor.ID, ActorName: actor.Email, ActorType: actor.Type, Product: product, + Metadata: map[string]interface{}{"setting": telemetrySettingKey, "old": cur, "new": next}, + }) + writeJSON(w, http.StatusOK, productTelemetryAnswer(t.ID, product, next, saved)) +} diff --git a/internal/server/server.go b/internal/server/server.go index 1bff94b..e5aad03 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -24,6 +24,7 @@ import ( "git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs" "git.breakpilot.com/platform/tenant-registry/internal/licence" "git.breakpilot.com/platform/tenant-registry/internal/llmkeys" + "git.breakpilot.com/platform/tenant-registry/internal/otlp" "git.breakpilot.com/platform/tenant-registry/internal/product" "git.breakpilot.com/platform/tenant-registry/internal/secretbox" "git.breakpilot.com/platform/tenant-registry/internal/store" @@ -48,14 +49,16 @@ type Server struct { Objects storage.Objects // nil ⇒ document routes answer 503 (F2) Mail mail.Sender // nil ⇒ notifications queue up unsent (F3) Gitea *gitea.Client // Managed Git user lists (t81); nil ⇒ http.DefaultClient + OTLP *otlp.Client // product telemetry relay (werkpilot#87); nil ⇒ http.DefaultClient Now func() time.Time // injectable clock (tests); nil ⇒ time.Now // Contracts are the released contract documents; nil ⇒ the committed // ones (contractdocs.Default). Tests pass their own. Contracts *contractdocs.Catalogue - blocks blockCache // MemberBlocked answers for user tokens (team.go) - ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go) - connLimiter keyRateLimiter // codes entered per tenant and person (connections.go) + blocks blockCache // MemberBlocked answers for user tokens (team.go) + ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go) + connLimiter keyRateLimiter // codes entered per tenant and person (connections.go) + telemetryLimiter keyRateLimiter // telemetry batches per person (telemetry_relay.go) } func (s *Server) now() time.Time { @@ -237,6 +240,13 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("GET /v1/licences", s.listLicences) mux.HandleFunc("POST /v1/licences/{id}/revoke", s.revokeLicence) + // Product telemetry (werkpilot#87): the workspace's switch per product + // (tenants.read / tenants.write, admins for user tokens), and the relay + // the CLIs send their batches to (group "telemetry"). + mux.HandleFunc("GET /v1/tenants/{id}/products/{product}/telemetry", s.getProductTelemetry) + mux.HandleFunc("PUT /v1/tenants/{id}/products/{product}/telemetry", s.putProductTelemetry) + mux.HandleFunc("POST /v1/telemetry", s.postTelemetry) + // keycloak claims refresh — the URL the protocol mapper would call at // token issuance to grab the up-to-date entitlement bundle. Today the // dev realm projects user attributes (set by SyncClaims) — this is diff --git a/internal/server/telemetry_relay.go b/internal/server/telemetry_relay.go new file mode 100644 index 0000000..4526b43 --- /dev/null +++ b/internal/server/telemetry_relay.go @@ -0,0 +1,250 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "math" + "net/http" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/otlp" +) + +// ─── product telemetry relay (werkpilot#87) ─────────────────────────────── +// +// The CLIs send content-free usage metrics with the user's own token; the +// registry checks them against a fixed allowlist and forwards them to the +// collector as OTLP, so no ingest token sits on customer machines. Only +// workspaces that turned telemetry on for the product are forwarded. The +// tenant is the token's; the person (subject, e-mail) is never forwarded. + +const ( + telemetryMaxRequest = 256 << 10 + telemetryMaxMetrics = 200 + telemetryMaxBounds = 20 + telemetryPerHour = 120 + telemetryMaxSpan = 24 * time.Hour + telemetryMaxAhead = 10 * time.Minute + telemetryScope = "tenant-registry/telemetry-relay" +) + +type telemetryMetricSpec struct { + histogram bool + keys []string +} + +// telemetryMetrics is the content-free guarantee: per product, the only +// metric names, their kind and their attribute keys the relay forwards. +var telemetryMetrics = map[string]map[string]telemetryMetricSpec{ + "werkpilot": { + "werkpilot.sessions": {keys: []string{"loop", "interactive"}}, + "werkpilot.turns": {keys: []string{"loop", "stop_reason"}}, + "werkpilot.tool_calls": {keys: []string{"tool", "outcome"}}, + "werkpilot.text_tool_calls_recovered": {}, + "werkpilot.tokens": {keys: []string{"direction"}}, + "werkpilot.crashes": {}, + "werkpilot.turn_duration_ms": {histogram: true, keys: []string{"loop"}}, + "werkpilot.first_token_ms": {histogram: true, keys: []string{"loop"}}, + }, +} + +var ( + telemetryAttrValue = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,64}$`) + telemetryVersion = regexp.MustCompile(`^[A-Za-z0-9.+_-]{1,64}$`) +) + +type telemetryBatchIn struct { + Product string `json:"product"` + Version string `json:"version"` + IntervalStart string `json:"interval_start"` + IntervalEnd string `json:"interval_end"` + Metrics []telemetryMetricIn `json:"metrics"` +} + +// telemetryMetricIn keeps the integers raw so that 3.0, -1 or 1e3 are +// refused instead of rounded. +type telemetryMetricIn struct { + Name string `json:"name"` + Kind string `json:"kind"` + Value json.RawMessage `json:"value"` + Count json.RawMessage `json:"count"` + Sum *float64 `json:"sum"` + Bounds []float64 `json:"bounds"` + BucketCounts []json.RawMessage `json:"bucket_counts"` + Attributes map[string]json.RawMessage `json:"attributes"` +} + +func (s *Server) postTelemetry(w http.ResponseWriter, r *http.Request) { + cfg := s.cfg() + if cfg.TelemetryOTLPToken == "" { + writeError(w, http.StatusServiceUnavailable, "telemetry_unavailable", "telemetry is not configured") + return + } + p, has := authn.PrincipalFrom(r.Context()) + if !has || !p.IsUser() { + writeError(w, http.StatusForbidden, "user_token_required", "telemetry is sent with the token of the person using the product") + return + } + var in telemetryBatchIn + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, telemetryMaxRequest)).Decode(&in); err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + writeError(w, http.StatusRequestEntityTooLarge, "too_large", "a batch is at most "+strconv.Itoa(telemetryMaxRequest)+" bytes") + return + } + writeError(w, http.StatusBadRequest, "invalid_input", "request body is not valid JSON or has a field of the wrong type") + return + } + specs, ok := telemetryMetrics[in.Product] + if !ok { + writeError(w, http.StatusBadRequest, "invalid_input", fmt.Sprintf("product %q sends no telemetry", in.Product)) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + on, _, err := s.loadProductTelemetry(ctx, p.TenantID, in.Product) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", "telemetry setting unreadable") + return + } + if !on { + writeError(w, http.StatusForbidden, "telemetry_disabled", "the workspace has not turned on telemetry for "+in.Product) + return + } + now := s.now() + start, end, metrics, msg := in.check(specs, now) + if msg != "" { + writeError(w, http.StatusBadRequest, "invalid_input", msg) + return + } + if len(metrics) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + if !s.telemetryLimiter.allow(p.Subject, now, telemetryPerHour) { + writeError(w, http.StatusTooManyRequests, "rate_limited", "at most "+strconv.Itoa(telemetryPerHour)+" batches per hour") + return + } + slug := p.TenantSlug + if t, err := s.Store.GetTenant(ctx, p.TenantID); err == nil { + slug = t.Slug + } + body, err := otlp.MetricsRequest([]otlp.Attribute{ + {Key: "service.name", Value: in.Product}, + {Key: "service.version", Value: in.Version}, + {Key: "tenant.slug", Value: slug}, + {Key: "tenant.id", Value: p.TenantID}, + {Key: "deployment.environment", Value: firstNonEmpty(cfg.Env, "dev")}, + }, telemetryScope, start, end, metrics) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", "telemetry batch not encodable") + return + } + if err := s.OTLP.Export(ctx, cfg.TelemetryOTLPURL, cfg.TelemetryOTLPToken, body); err != nil { + s.Log.Error("telemetry batch not forwarded", "err", err, "tenant_id", p.TenantID, "product", in.Product, "metrics", len(metrics)) + writeError(w, http.StatusBadGateway, "telemetry_failed", "the batch could not be forwarded") + return + } + w.WriteHeader(http.StatusNoContent) +} + +// check validates the batch against the product's allowlist and returns +// what is forwarded; msg names the first offending field. +func (in *telemetryBatchIn) check(specs map[string]telemetryMetricSpec, now time.Time) (start, end time.Time, out []otlp.Metric, msg string) { + if !telemetryVersion.MatchString(in.Version) { + return start, end, nil, "version: 1 to 64 of A-Z a-z 0-9 . + _ -" + } + start, err := time.Parse(time.RFC3339, in.IntervalStart) + if err != nil { + return start, end, nil, "interval_start must be RFC3339" + } + end, err = time.Parse(time.RFC3339, in.IntervalEnd) + if err != nil { + return start, end, nil, "interval_end must be RFC3339" + } + switch { + case end.Before(start): + return start, end, nil, "interval_end is before interval_start" + case end.Sub(start) > telemetryMaxSpan: + return start, end, nil, "the interval is longer than 24 h" + case end.After(now.Add(telemetryMaxAhead)): + return start, end, nil, "interval_end is more than 10 minutes in the future" + } + if len(in.Metrics) > telemetryMaxMetrics { + return start, end, nil, "at most " + strconv.Itoa(telemetryMaxMetrics) + " metrics per batch" + } + for i, m := range in.Metrics { + at := fmt.Sprintf("metrics[%d]", i) + spec, ok := specs[m.Name] + if !ok { + return start, end, nil, fmt.Sprintf("%s: metric %q is not allowed", at, m.Name) + } + at += " (" + m.Name + ")" + want := "counter" + if spec.histogram { + want = "histogram" + } + if m.Kind != want { + return start, end, nil, fmt.Sprintf("%s: kind must be %s", at, want) + } + attrs := map[string]string{} + for k, raw := range m.Attributes { + if !slices.Contains(spec.keys, k) { + return start, end, nil, fmt.Sprintf("%s: attribute %q is not allowed", at, k) + } + var v string + if json.Unmarshal(raw, &v) != nil || !telemetryAttrValue.MatchString(v) { + return start, end, nil, fmt.Sprintf("%s: attribute %q must be a string of 1 to 64 of A-Z a-z 0-9 _ . : -", at, k) + } + attrs[k] = v + } + pt := otlp.Metric{Name: m.Name, Attributes: attrs, Histogram: spec.histogram} + if !spec.histogram { + if pt.Value, ok = telemetryUint(m.Value); !ok { + return start, end, nil, at + ": value must be a non-negative integer" + } + out = append(out, pt) + continue + } + if pt.Count, ok = telemetryUint(m.Count); !ok { + return start, end, nil, at + ": count must be a non-negative integer" + } + if m.Sum == nil || *m.Sum < 0 || math.IsNaN(*m.Sum) || math.IsInf(*m.Sum, 0) { + return start, end, nil, at + ": sum must be a non-negative number" + } + pt.Sum = *m.Sum + if len(m.Bounds) > telemetryMaxBounds { + return start, end, nil, fmt.Sprintf("%s: at most %d bounds", at, telemetryMaxBounds) + } + for j := 1; j < len(m.Bounds); j++ { + if m.Bounds[j] <= m.Bounds[j-1] { + return start, end, nil, at + ": bounds must be strictly increasing" + } + } + pt.Bounds = m.Bounds + if len(m.BucketCounts) != len(m.Bounds)+1 { + return start, end, nil, fmt.Sprintf("%s: bucket_counts needs len(bounds)+1 = %d entries", at, len(m.Bounds)+1) + } + pt.BucketCounts = make([]uint64, len(m.BucketCounts)) + for j, raw := range m.BucketCounts { + if pt.BucketCounts[j], ok = telemetryUint(raw); !ok { + return start, end, nil, fmt.Sprintf("%s: bucket_counts[%d] must be a non-negative integer", at, j) + } + } + out = append(out, pt) + } + return start, end, out, "" +} + +// telemetryUint reads a JSON integer literal >= 0. +func telemetryUint(raw json.RawMessage) (uint64, bool) { + n, err := strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 64) + return n, err == nil +} diff --git a/internal/server/telemetry_relay_test.go b/internal/server/telemetry_relay_test.go new file mode 100644 index 0000000..edfdd8d --- /dev/null +++ b/internal/server/telemetry_relay_test.go @@ -0,0 +1,518 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + colmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1" + metricspb "go.opentelemetry.io/proto/otlp/metrics/v1" + "google.golang.org/protobuf/encoding/protojson" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/config" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +const otlpTestToken = "sentinel-otlp-token-0123456789" + +// fakeCollector records the exports it is sent and answers with reply. +type fakeCollector struct { + srv *httptest.Server + mu sync.Mutex + got []collectorCall + reply func(w http.ResponseWriter) +} + +type collectorCall struct { + Path, RawQuery, Auth, ContentType string + Body []byte +} + +func newFakeCollector(t *testing.T) *fakeCollector { + t.Helper() + c := &fakeCollector{reply: func(w http.ResponseWriter) { w.WriteHeader(http.StatusOK) }} + c.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + c.mu.Lock() + c.got = append(c.got, collectorCall{Path: r.URL.Path, RawQuery: r.URL.RawQuery, Auth: r.Header.Get("Authorization"), + ContentType: r.Header.Get("Content-Type"), Body: body}) + c.mu.Unlock() + c.reply(w) + })) + t.Cleanup(c.srv.Close) + return c +} + +func (c *fakeCollector) calls() []collectorCall { + c.mu.Lock() + defer c.mu.Unlock() + return append([]collectorCall(nil), c.got...) +} + +type relayFixture struct { + s *Server + h http.Handler + collector *fakeCollector + acme *store.Tenant + other *store.Tenant + logs *bytes.Buffer + now time.Time +} + +// newRelayFixture: telemetry on for acme's werkpilot, off for "other"; the +// deployed AUTHZ_RULES shape (the CLIs hold licences and usage only). +func newRelayFixture(t *testing.T) *relayFixture { + t.Helper() + mem := store.NewMemory() + acme, _ := mem.GetTenantBySlug(context.Background(), "acme") + other, err := mem.CreateTenant(context.Background(), store.TenantCreate{Slug: "other", Name: "Other"}) + if err != nil { + t.Fatal(err) + } + f := &relayFixture{collector: newFakeCollector(t), acme: acme, other: other, logs: &bytes.Buffer{}, + now: time.Date(2026, 11, 23, 9, 20, 0, 0, time.UTC)} + user := func(client, sub, tenantID, email string) *authn.Principal { + return &authn.Principal{Subject: sub, ClientID: client, TenantID: tenantID, Email: email, OrgRoles: []string{"USER"}} + } + as := map[string]*authn.Principal{ + "user": user("werkpilot-cli", "u-1", acme.ID, "dev@acme.test"), + "colleague": user("werkpilot-cli", "u-2", acme.ID, ""), + "stranger": user("werkpilot-cli", "u-x", other.ID, "x@other.test"), + "firmwerk": user("firmwerk-cli", "u-3", acme.ID, ""), + "granted": user("other-cli", "u-4", acme.ID, ""), + "portal": user("portal-prod", "u-5", acme.ID, ""), + "service": {Subject: "svc-portal", ClientID: "portal-svc"}, + "firmwerk-svc": {Subject: "svc-fw", ClientID: "firmwerk-svc-prod"}, + } + f.s = &Server{ + Log: slog.New(slog.NewTextHandler(f.logs, nil)), Store: mem, Keycloak: keycloak.NewMock(), + Authz: ParseAuthzRules("portal-svc:*;werkpilot-cli:licences,usage;firmwerk-cli:licences,usage;" + + "portal-prod:role-dataset.user,intake.user;firmwerk-svc-prod:licences,usage;other-cli:telemetry"), + Cfg: &config.Config{Env: "stage", TelemetryOTLPURL: f.collector.srv.URL + "/v1/metrics", TelemetryOTLPToken: otlpTestToken}, + Now: func() time.Time { return f.now }, + } + f.setTelemetry(t, acme.ID, true) + router := NewRouter(f.s) + f.h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if p := as[r.Header.Get("X-Test-As")]; p != nil { + r = r.WithContext(authn.WithPrincipal(r.Context(), p)) + } + router.ServeHTTP(w, r) + }) + return f +} + +func (f *relayFixture) setTelemetry(t *testing.T, tenantID string, on bool) { + t.Helper() + doc, _ := json.Marshal(map[string]bool{"telemetry": on}) + if _, err := f.s.Store.PutTenantProductSettings(context.Background(), store.TenantProductSettings{TenantID: tenantID, Product: "werkpilot", Settings: doc}); err != nil { + t.Fatal(err) + } +} + +func (f *relayFixture) send(t *testing.T, as, body string) (int, map[string]any, string) { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/v1/telemetry", strings.NewReader(body)) + req.Header.Set("X-Test-As", as) + rr := httptest.NewRecorder() + f.h.ServeHTTP(rr, req) + var out map[string]any + _ = json.Unmarshal(rr.Body.Bytes(), &out) + return rr.Code, out, rr.Body.String() +} + +const ( + relayStart = "2026-11-23T09:00:00Z" + relayEnd = "2026-11-23T09:15:00Z" +) + +// relayBatch is a valid batch with the given metrics (JSON array text). +func relayBatch(metrics string, over ...string) string { + fields := map[string]string{"product": `"werkpilot"`, "version": `"0.3.1"`, "interval_start": `"` + relayStart + `"`, "interval_end": `"` + relayEnd + `"`, "metrics": metrics} + for i := 0; i+1 < len(over); i += 2 { + fields[over[i]] = over[i+1] + } + var parts []string + for _, k := range []string{"product", "version", "interval_start", "interval_end", "metrics"} { + if v, ok := fields[k]; ok && v != "" { + parts = append(parts, `"`+k+`":`+v) + } + } + return "{" + strings.Join(parts, ",") + "}" +} + +const ( + relayTurns = `{"name":"werkpilot.turns","kind":"counter","value":3,"attributes":{"loop":"state_machine","stop_reason":"end_turn"}}` + relayHist = `{"name":"werkpilot.turn_duration_ms","kind":"histogram","count":3,"sum":4521.5,"bounds":[100,500,1000,5000,15000,60000],"bucket_counts":[0,0,1,2,0,0,0],"attributes":{"loop":"legacy"}}` +) + +func TestTelemetryRelay_forwardsOTLP(t *testing.T) { + f := newRelayFixture(t) + batch := relayBatch(`[` + relayTurns + `,` + relayHist + `,` + + `{"name":"werkpilot.turns","kind":"counter","value":1,"attributes":{"stop_reason":"max_turns","loop":"legacy"}},` + + `{"name":"werkpilot.crashes","kind":"counter","value":0}]`) + code, _, raw := f.send(t, "user", batch) + if code != http.StatusNoContent || raw != "" { + t.Fatalf("send: %d %q", code, raw) + } + calls := f.collector.calls() + if len(calls) != 1 { + t.Fatalf("collector calls: %d", len(calls)) + } + c := calls[0] + if c.Path != "/v1/metrics" || c.RawQuery != "" || c.Auth != "Bearer "+otlpTestToken || c.ContentType != "application/json" { + t.Fatalf("request: %q %q %q %q", c.Path, c.RawQuery, c.Auth, c.ContentType) + } + + start := strconv.FormatInt(time.Date(2026, 11, 23, 9, 0, 0, 0, time.UTC).UnixNano(), 10) + end := strconv.FormatInt(time.Date(2026, 11, 23, 9, 15, 0, 0, time.UTC).UnixNano(), 10) + str := func(k, v string) string { return `{"key":"` + k + `","value":{"stringValue":"` + v + `"}}` } + times := `"startTimeUnixNano":"` + start + `","timeUnixNano":"` + end + `"` + want := `{"resourceMetrics":[{"resource":{"attributes":[` + + str("service.name", "werkpilot") + `,` + str("service.version", "0.3.1") + `,` + str("tenant.slug", "acme") + `,` + + str("tenant.id", f.acme.ID) + `,` + str("deployment.environment", "stage") + `]},` + + `"scopeMetrics":[{"scope":{"name":"tenant-registry/telemetry-relay"},"metrics":[` + + `{"name":"werkpilot.turns","sum":{"aggregationTemporality":1,"isMonotonic":true,"dataPoints":[` + + `{"attributes":[` + str("loop", "state_machine") + `,` + str("stop_reason", "end_turn") + `],` + times + `,"asInt":"3"},` + + `{"attributes":[` + str("loop", "legacy") + `,` + str("stop_reason", "max_turns") + `],` + times + `,"asInt":"1"}]}},` + + `{"name":"werkpilot.turn_duration_ms","histogram":{"aggregationTemporality":1,"dataPoints":[` + + `{"attributes":[` + str("loop", "legacy") + `],` + times + `,"count":"3","sum":4521.5,"bucketCounts":["0","0","1","2","0","0","0"],"explicitBounds":[100,500,1000,5000,15000,60000]}]}},` + + `{"name":"werkpilot.crashes","sum":{"aggregationTemporality":1,"isMonotonic":true,"dataPoints":[{"attributes":[],` + times + `,"asInt":"0"}]}}` + + `]}]}]}` + if string(c.Body) != want { + t.Fatalf("OTLP body:\n%s\nwant:\n%s", c.Body, want) + } + for _, person := range []string{"u-1", "dev@acme.test"} { + if bytes.Contains(c.Body, []byte(person)) { + t.Errorf("the person (%s) is forwarded", person) + } + } + + // The same bytes as the OTLP protobuf JSON mapping reads them. + var req colmetricspb.ExportMetricsServiceRequest + if err := protojson.Unmarshal(c.Body, &req); err != nil { + t.Fatalf("not an ExportMetricsServiceRequest: %v", err) + } + ms := req.GetResourceMetrics()[0].GetScopeMetrics()[0].GetMetrics() + sum, hist := ms[0].GetSum(), ms[1].GetHistogram() + if sum.GetAggregationTemporality() != metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA || !sum.GetIsMonotonic() || + sum.GetDataPoints()[0].GetAsInt() != 3 || sum.GetDataPoints()[0].GetStartTimeUnixNano() == 0 { + t.Fatalf("sum: %v", sum) + } + hp := hist.GetDataPoints()[0] + if hist.GetAggregationTemporality() != metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA || hp.GetCount() != 3 || + hp.GetSum() != 4521.5 || len(hp.GetBucketCounts()) != 7 || hp.GetBucketCounts()[3] != 2 || len(hp.GetExplicitBounds()) != 6 || + hp.GetTimeUnixNano()-hp.GetStartTimeUnixNano() != uint64(15*time.Minute) { + t.Fatalf("histogram: %v", hist) + } +} + +func TestTelemetryRelay_disabledTenant(t *testing.T) { + f := newRelayFixture(t) + if code, out, raw := f.send(t, "stranger", relayBatch(`[`+relayTurns+`]`)); code != http.StatusForbidden || out["error"] != "telemetry_disabled" { + t.Fatalf("never enabled: %d %s", code, raw) + } + f.setTelemetry(t, f.acme.ID, false) + if code, out, raw := f.send(t, "user", relayBatch(`[`+relayTurns+`]`)); code != http.StatusForbidden || out["error"] != "telemetry_disabled" { + t.Fatalf("turned off: %d %s", code, raw) + } + // A tenant_id in the batch changes nothing: the tenant is the token's. + if code, _, raw := f.send(t, "stranger", strings.Replace(relayBatch(`[`+relayTurns+`]`), "{", `{"tenant_id":"`+f.acme.ID+`",`, 1)); code != http.StatusForbidden { + t.Fatalf("tenant from the body: %d %s", code, raw) + } + if n := len(f.collector.calls()); n != 0 { + t.Fatalf("forwarded %d batches", n) + } +} + +func TestTelemetryRelay_unavailableWithoutToken(t *testing.T) { + f := newRelayFixture(t) + f.s.Cfg.TelemetryOTLPToken = "" + if code, out, raw := f.send(t, "user", relayBatch(`[`+relayTurns+`]`)); code != http.StatusServiceUnavailable || out["error"] != "telemetry_unavailable" { + t.Fatalf("no token: %d %s", code, raw) + } + f.s.Cfg = nil + if code, out, _ := f.send(t, "user", relayBatch(`[`+relayTurns+`]`)); code != http.StatusServiceUnavailable || out["error"] != "telemetry_unavailable" { + t.Fatalf("no config: %d %v", code, out) + } + if n := len(f.collector.calls()); n != 0 { + t.Fatalf("forwarded %d batches", n) + } +} + +func TestTelemetryRelay_allowlist(t *testing.T) { + f := newRelayFixture(t) + for name, c := range map[string]struct{ body, names string }{ + "unknown product": {relayBatch(`[`+relayTurns+`]`, "product", `"firmwerk"`), `"firmwerk"`}, + "no product": {relayBatch(`[`+relayTurns+`]`, "product", `""`), `product ""`}, + "unknown metric": {relayBatch(`[{"name":"werkpilot.prompts","kind":"counter","value":1}]`), `"werkpilot.prompts"`}, + "foreign prefix": {relayBatch(`[{"name":"firmwerk.turns","kind":"counter","value":1}]`), `"firmwerk.turns"`}, + "counter as hist": {relayBatch(`[{"name":"werkpilot.turns","kind":"histogram","count":1,"sum":1,"bounds":[],"bucket_counts":[1]}]`), "werkpilot.turns): kind must be counter"}, + "hist as counter": {relayBatch(`[{"name":"werkpilot.first_token_ms","kind":"counter","value":1}]`), "werkpilot.first_token_ms): kind must be histogram"}, + "no kind": {relayBatch(`[{"name":"werkpilot.turns","value":1}]`), "werkpilot.turns): kind must be counter"}, + "unlisted key": {relayBatch(`[{"name":"werkpilot.turns","kind":"counter","value":1,"attributes":{"prompt":"hi"}}]`), `attribute "prompt" is not allowed`}, + "key of other metric": {relayBatch(`[{"name":"werkpilot.tokens","kind":"counter","value":1,"attributes":{"tool":"shell"}}]`), `werkpilot.tokens): attribute "tool"`}, + "key on keyless": {relayBatch(`[{"name":"werkpilot.crashes","kind":"counter","value":1,"attributes":{"loop":"legacy"}}]`), `werkpilot.crashes): attribute "loop" is not allowed`}, + "value with space": {relayBatch(`[{"name":"werkpilot.tool_calls","kind":"counter","value":1,"attributes":{"tool":"rm -rf"}}]`), `attribute "tool" must be`}, + "value with slash": {relayBatch(`[{"name":"werkpilot.tool_calls","kind":"counter","value":1,"attributes":{"tool":"/home/x"}}]`), `attribute "tool" must be`}, + "value too long": {relayBatch(`[{"name":"werkpilot.tool_calls","kind":"counter","value":1,"attributes":{"tool":"` + strings.Repeat("a", 65) + `"}}]`), `attribute "tool" must be`}, + "empty value": {relayBatch(`[{"name":"werkpilot.tool_calls","kind":"counter","value":1,"attributes":{"outcome":""}}]`), `attribute "outcome" must be`}, + "bool value": {relayBatch(`[{"name":"werkpilot.sessions","kind":"counter","value":1,"attributes":{"interactive":true}}]`), `attribute "interactive" must be a string`}, + "number value": {relayBatch(`[{"name":"werkpilot.tokens","kind":"counter","value":1,"attributes":{"direction":3}}]`), `attribute "direction" must be a string`}, + "second metric": {relayBatch(`[` + relayTurns + `,{"name":"werkpilot.secret","kind":"counter","value":1}]`), `metrics[1]: metric "werkpilot.secret"`}, + } { + code, out, raw := f.send(t, "user", c.body) + if code != http.StatusBadRequest || out["error"] != "invalid_input" || !strings.Contains(out["message"].(string), c.names) { + t.Errorf("%s: %d %s", name, code, raw) + } + } + if n := len(f.collector.calls()); n != 0 { + t.Fatalf("forwarded %d batches", n) + } + // Every listed metric with every listed key passes; keys may be left out. + all := `[{"name":"werkpilot.sessions","kind":"counter","value":1,"attributes":{"loop":"legacy","interactive":"true"}},` + + `{"name":"werkpilot.turns","kind":"counter","value":2,"attributes":{"loop":"state_machine","stop_reason":"end_turn"}},` + + `{"name":"werkpilot.tool_calls","kind":"counter","value":3,"attributes":{"tool":"developer__shell","outcome":"ok"}},` + + `{"name":"werkpilot.text_tool_calls_recovered","kind":"counter","value":4},` + + `{"name":"werkpilot.tokens","kind":"counter","value":5,"attributes":{"direction":"input"}},` + + `{"name":"werkpilot.tokens","kind":"counter","value":6},` + + `{"name":"werkpilot.crashes","kind":"counter","value":7,"attributes":{}},` + + `{"name":"werkpilot.turn_duration_ms","kind":"histogram","count":1,"sum":10,"bounds":[100],"bucket_counts":[1,0],"attributes":{"loop":"legacy"}},` + + `{"name":"werkpilot.first_token_ms","kind":"histogram","count":0,"sum":0,"bounds":[],"bucket_counts":[0]}]` + if code, _, raw := f.send(t, "user", relayBatch(all)); code != http.StatusNoContent { + t.Fatalf("all listed: %d %s", code, raw) + } +} + +func TestTelemetryRelay_isChecked(t *testing.T) { + f := newRelayFixture(t) + counter := func(value string) string { + return relayBatch(`[{"name":"werkpilot.turns","kind":"counter","value":` + value + `}]`) + } + hist := func(fields string) string { + return relayBatch(`[{"name":"werkpilot.turn_duration_ms","kind":"histogram",` + fields + `}]`) + } + bounds21 := strings.TrimSuffix(strings.Repeat("1,", 21), ",") + for name, c := range map[string]struct { + body, msg string + code int + }{ + "negative counter": {counter("-1"), "value must be a non-negative integer", 400}, + "fractional counter": {counter("1.5"), "value must be", 400}, + "float-looking int": {counter("3.0"), "value must be", 400}, + "exponent counter": {counter("1e3"), "value must be", 400}, + "string counter": {counter(`"3"`), "value must be", 400}, + "no counter value": {relayBatch(`[{"name":"werkpilot.turns","kind":"counter"}]`), "value must be", 400}, + "no count": {hist(`"sum":1,"bounds":[1],"bucket_counts":[0,1]`), "count must be", 400}, + "negative count": {hist(`"count":-1,"sum":1,"bounds":[1],"bucket_counts":[0,1]`), "count must be", 400}, + "no sum": {hist(`"count":1,"bounds":[1],"bucket_counts":[0,1]`), "sum must be", 400}, + "negative sum": {hist(`"count":1,"sum":-0.5,"bounds":[1],"bucket_counts":[0,1]`), "sum must be", 400}, + "21 bounds": {hist(`"count":1,"sum":1,"bounds":[` + bounds21 + `],"bucket_counts":[]`), "at most 20 bounds", 400}, + "short buckets": {hist(`"count":1,"sum":1,"bounds":[1,2],"bucket_counts":[0,1]`), "bucket_counts needs len(bounds)+1 = 3", 400}, + "long buckets": {hist(`"count":1,"sum":1,"bounds":[1],"bucket_counts":[0,1,0]`), "bucket_counts needs", 400}, + "negative bucket": {hist(`"count":1,"sum":1,"bounds":[1],"bucket_counts":[0,-1]`), "bucket_counts[1] must be", 400}, + "unordered bounds": {hist(`"count":1,"sum":1,"bounds":[5,1],"bucket_counts":[0,1,0]`), "strictly increasing", 400}, + "repeated bound": {hist(`"count":1,"sum":1,"bounds":[1,1],"bucket_counts":[0,1,0]`), "strictly increasing", 400}, + "bad start": {relayBatch(`[]`, "interval_start", `"yesterday"`), "interval_start", 400}, + "no end": {relayBatch(`[]`, "interval_end", `""`), "interval_end", 400}, + "end before start": {relayBatch(`[]`, "interval_end", `"2026-11-23T08:59:59Z"`), "before interval_start", 400}, + "over 24 h": {relayBatch(`[]`, "interval_start", `"2026-11-22T09:14:59Z"`), "longer than 24 h", 400}, + "end too far ahead": {relayBatch(`[]`, "interval_end", `"2026-11-23T09:30:01Z"`), "in the future", 400}, + "no version": {relayBatch(`[]`, "version", `""`), "version", 400}, + "version with space": {relayBatch(`[]`, "version", `"0.3.1 (my machine)"`), "version", 400}, + "version path": {relayBatch(`[]`, "version", `"/home/x"`), "version", 400}, + "201 metrics": {relayBatch(`[` + strings.TrimSuffix(strings.Repeat(relayTurns+",", 201), ",") + `]`), "at most 200 metrics", 400}, + "not JSON": {`{"product":`, "not valid JSON", 400}, + "metrics not a list": {relayBatch(`{"name":"werkpilot.turns"}`), "wrong type", 400}, + "over 256 KiB": {relayBatch(`[`+relayTurns+`]`, "version", `"`+strings.Repeat("a", 256<<10)+`"`), "", 413}, + "over 256 KiB at end": {relayBatch(`[` + strings.TrimSuffix(strings.Repeat(relayHist+",", 2000), ",") + `]`), "", 413}, + } { + code, out, raw := f.send(t, "user", c.body) + want := "invalid_input" + if c.code == 413 { + want = "too_large" + } + if code != c.code || out["error"] != want || !strings.Contains(out["message"].(string), c.msg) { + t.Errorf("%s: %d %s", name, code, raw) + } + } + if n := len(f.collector.calls()); n != 0 { + t.Fatalf("forwarded %d batches", n) + } + // At the limits: 24 h exactly, end 10 minutes ahead, 200 metrics, 20 + // bounds; an empty list forwards nothing. + bounds20 := make([]string, 20) + for i := range bounds20 { + bounds20[i] = strconv.Itoa(i + 1) + } + for name, body := range map[string]string{ + "24 h": relayBatch(`[`+relayTurns+`]`, "interval_start", `"2026-11-22T09:15:00Z"`), + "10 min ahead": relayBatch(`[`+relayTurns+`]`, "interval_end", `"2026-11-23T09:30:00Z"`), + "200 metrics": relayBatch(`[` + strings.TrimSuffix(strings.Repeat(relayTurns+",", 200), ",") + `]`), + "20 bounds": hist(`"count":1,"sum":1,"bounds":[` + strings.Join(bounds20, ",") + `],"bucket_counts":[` + strings.TrimSuffix(strings.Repeat("0,", 21), ",") + `]`), + "zero length": relayBatch(`[`+relayTurns+`]`, "interval_start", `"`+relayEnd+`"`), + "semver build": relayBatch(`[`+relayTurns+`]`, "version", `"0.3.1-rc.1+g1a2b3c"`), + } { + if code, _, raw := f.send(t, "user", body); code != http.StatusNoContent { + t.Errorf("%s: %d %s", name, code, raw) + } + } + if n := len(f.collector.calls()); n != 6 { + t.Fatalf("forwarded %d batches, want 6", n) + } + if code, _, raw := f.send(t, "user", relayBatch(`[]`)); code != http.StatusNoContent || len(f.collector.calls()) != 6 { + t.Fatalf("empty batch: %d %s, %d forwarded", code, raw, len(f.collector.calls())) + } +} + +func TestTelemetryRelay_rateLimitedPerPerson(t *testing.T) { + f := newRelayFixture(t) + batch := relayBatch(`[` + relayTurns + `]`) + for i := range telemetryPerHour { + if code, _, raw := f.send(t, "user", batch); code != http.StatusNoContent { + t.Fatalf("batch %d: %d %s", i+1, code, raw) + } + if i == 0 { + f.now = f.now.Add(time.Minute) + } + } + if code, out, raw := f.send(t, "user", batch); code != http.StatusTooManyRequests || out["error"] != "rate_limited" { + t.Fatalf("121st: %d %s", code, raw) + } + // Refused and empty batches do not count; the limit is per person. + if code, _, _ := f.send(t, "user", relayBatch(`[{"name":"x","kind":"counter","value":1}]`)); code != http.StatusBadRequest { + t.Fatalf("invalid while limited: %d", code) + } + if code, _, _ := f.send(t, "user", relayBatch(`[]`)); code != http.StatusNoContent { + t.Fatalf("empty while limited: %d", code) + } + if code, _, raw := f.send(t, "colleague", batch); code != http.StatusNoContent { + t.Fatalf("colleague: %d %s", code, raw) + } + // An hour after the first batch, its slot is free again, and only it. + f.now = f.now.Add(59*time.Minute + 30*time.Second) + if code, _, raw := f.send(t, "user", batch); code != http.StatusNoContent { + t.Fatalf("after the hour: %d %s", code, raw) + } + if code, _, _ := f.send(t, "user", batch); code != http.StatusTooManyRequests { + t.Fatalf("second after the hour: %d", code) + } +} + +// When the collector fails the caller learns only that; neither its answer +// nor the token reaches the response or the log. +func TestTelemetryRelay_collectorFailureLeaksNothing(t *testing.T) { + const marker = "COLLECTOR-SAYS-SECRET-THING" + for name, reply := range map[string]func(w http.ResponseWriter){ + "500 with a body": func(w http.ResponseWriter) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"message":"` + marker + ` bearer ` + otlpTestToken + ` rejected"}`)) + }, + "401": func(w http.ResponseWriter) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(marker)) + }, + "302": func(w http.ResponseWriter) { + w.Header().Set("Location", "/elsewhere?"+marker) + w.WriteHeader(http.StatusFound) + }, + } { + t.Run(name, func(t *testing.T) { + f := newRelayFixture(t) + f.collector.reply = reply + code, out, raw := f.send(t, "user", relayBatch(`[`+relayTurns+`]`)) + if code != http.StatusBadGateway || out["error"] != "telemetry_failed" { + t.Fatalf("failure: %d %s", code, raw) + } + logs := f.logs.String() + for _, secret := range []string{marker, otlpTestToken, f.collector.srv.URL} { + if strings.Contains(raw, secret) || strings.Contains(logs, secret) { + t.Errorf("%q leaked:\n%s\n%s", secret, raw, logs) + } + } + if !strings.Contains(logs, "telemetry batch not forwarded") { + t.Errorf("failure not logged: %s", logs) + } + }) + } + t.Run("unreachable", func(t *testing.T) { + f := newRelayFixture(t) + addr := f.collector.srv.URL + f.collector.srv.Close() + code, out, raw := f.send(t, "user", relayBatch(`[`+relayTurns+`]`)) + if code != http.StatusBadGateway || out["error"] != "telemetry_failed" { + t.Fatalf("unreachable: %d %s", code, raw) + } + if all := raw + f.logs.String(); strings.Contains(all, otlpTestToken) || strings.Contains(all, addr) { + t.Fatalf("token or URL leaked: %s", all) + } + }) +} + +// The CLIs reach the relay with the grants they hold in the deployed +// AUTHZ_RULES (licences, usage); other clients need the telemetry group. +func TestTelemetryRelay_whoReachesIt(t *testing.T) { + f := newRelayFixture(t) + for _, as := range []string{"user", "firmwerk", "granted"} { + if code, _, raw := f.send(t, as, relayBatch(`[`+relayTurns+`]`)); code != http.StatusNoContent { + t.Errorf("%q: %d %s", as, code, raw) + } + } + for as, want := range map[string]string{ + "service": "user_token_required", + "": "user_token_required", // AUTH_ENABLED=false: no principal, no tenant + "portal": "FORBIDDEN_CLIENT", // a user token, but its client holds no licences + "firmwerk-svc": "FORBIDDEN_CLIENT", // licences, but a service token + } { + if code, out, raw := f.send(t, as, relayBatch(`[`+relayTurns+`]`)); code != http.StatusForbidden || out["error"] != want { + t.Errorf("%q: %d %s", as, code, raw) + } + } + if n := len(f.collector.calls()); n != 3 { + t.Fatalf("forwarded %d batches", n) + } +} + +// Only a workspace administrator reads or sets the switch, and only in its +// own workspace; another workspace's administrator gets a 404. +func TestProductTelemetry_adminsOnly(t *testing.T) { + acme := "00000000-0000-0000-0000-000000000001" + for _, c := range []struct { + name string + tenant string + roles []string + want int + }{ + {"plain user", acme, []string{"USER"}, http.StatusForbidden}, + {"cxo", acme, []string{"CXO"}, http.StatusForbidden}, + {"finance", acme, []string{"FINANCE"}, http.StatusForbidden}, + {"another workspace's admin", "11111111-1111-1111-1111-111111111111", []string{"IT_ADMIN"}, http.StatusNotFound}, + {"it admin", acme, []string{"IT_ADMIN"}, http.StatusOK}, + {"owner", acme, []string{"OWNER"}, http.StatusOK}, + } { + for _, rt := range []struct{ method, body string }{{http.MethodGet, ""}, {http.MethodPut, `{"enabled":true}`}} { + p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: c.tenant, OrgRoles: c.roles} + s, h, tenant := scopedServer(t, p) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(rt.method, "/v1/tenants/"+tenant.ID+"/products/werkpilot/telemetry", strings.NewReader(rt.body))) + if rr.Code != c.want { + t.Errorf("%s %s: %d %s", c.name, rt.method, rr.Code, rr.Body.String()) + } + on := s.telemetryEnabled(context.Background(), tenant.ID, "werkpilot") + if on != (rt.method == http.MethodPut && c.want == http.StatusOK) { + t.Errorf("%s %s: telemetry now %v", c.name, rt.method, on) + } + } + } +} diff --git a/openapi.yaml b/openapi.yaml index e92db7b..81635f0 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -793,6 +793,54 @@ paths: "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/products/{product}/telemetry: + get: + summary: The workspace's telemetry switch for a product (werkpilot#87). + description: | + Off until turned on. Only products with a telemetry allowlist take + the switch (today `werkpilot`; others 404). User tokens reach their + own tenant only and need IT_ADMIN or OWNER (else 403 + FORBIDDEN_ROLE); service clients read with tenants.read. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: product, required: true, schema: { type: string, example: werkpilot } } + responses: + "200": + description: The switch. + content: + application/json: { schema: { $ref: "#/components/schemas/ProductTelemetry" } } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + put: + summary: Turn product telemetry on or off. + description: | + Same roles as the GET; service clients write with tenants.write. + A change is audited as `product_settings.changed` (setting + `telemetry`, old and new value); a save that changes nothing writes + nothing. Licence grants and heartbeats report the switch as + `telemetry`, and POST /v1/telemetry forwards only while it is on. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: product, required: true, schema: { type: string, example: werkpilot } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [enabled] + additionalProperties: false + properties: + enabled: { type: boolean } + responses: + "200": + description: Saved (or unchanged). + content: + application/json: { schema: { $ref: "#/components/schemas/ProductTelemetry" } } + "400": { $ref: "#/components/responses/BadRequest" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/contracts: get: summary: The tenant's Vertragsunterlagen (trial, AVV, TOM, SaaS, contract documents). @@ -2635,6 +2683,72 @@ paths: "429": { description: "More than 60 calls for this key in the last hour." } "503": { description: Licence signer not configured. } + /v1/telemetry: + post: + summary: Relay a CLI's content-free usage metrics to the collector (werkpilot#87). + description: | + Sent with the person's own token; the tenant is the token's. Route + group `telemetry`; a user token from a client holding `licences` + (the CLIs) passes without it. Forwarded only while the workspace + has telemetry on for the product (403 `telemetry_disabled` + otherwise), as OTLP/HTTP JSON to TELEMETRY_OTLP_URL with resource + attributes service.name (product), service.version, tenant.slug, + tenant.id and deployment.environment; counters as monotonic DELTA + sums, histograms as DELTA explicit-bucket histograms, both spanning + interval_start..interval_end. The person (subject, e-mail) is never + forwarded. + + Allowlist (anything else is 400 `invalid_input`, naming the metric + or key): werkpilot.sessions (counter; loop, interactive), + werkpilot.turns (counter; loop, stop_reason), werkpilot.tool_calls + (counter; tool, outcome), werkpilot.text_tool_calls_recovered + (counter), werkpilot.tokens (counter; direction), + werkpilot.crashes (counter), werkpilot.turn_duration_ms + (histogram; loop), werkpilot.first_token_ms (histogram; loop). + Attribute values are strings matching `^[A-Za-z0-9_.:-]{1,64}$`; + listed keys may be left out. Counter values, histogram counts and + bucket counts are non-negative integer literals; sum is a + non-negative number; at most 20 strictly increasing bounds and + len(bounds)+1 bucket counts. At most 200 metrics; an empty list is + accepted and forwards nothing. The interval: end >= start, at most + 24 h, end at most 10 minutes ahead. At most 120 batches per person + and hour. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [product, version, interval_start, interval_end, metrics] + properties: + product: { type: string, enum: [werkpilot] } + version: { type: string, pattern: "^[A-Za-z0-9.+_-]{1,64}$", example: "0.3.1" } + interval_start: { type: string, format: date-time } + interval_end: { type: string, format: date-time } + metrics: + type: array + maxItems: 200 + items: + type: object + required: [name, kind] + properties: + name: { type: string, example: werkpilot.turns } + kind: { type: string, enum: [counter, histogram] } + value: { type: integer, minimum: 0, description: "counter" } + count: { type: integer, minimum: 0, description: "histogram" } + sum: { type: number, minimum: 0, description: "histogram" } + bounds: { type: array, maxItems: 20, items: { type: number }, description: "histogram" } + bucket_counts: { type: array, items: { type: integer, minimum: 0 }, description: "histogram; len(bounds)+1" } + attributes: { type: object, additionalProperties: { type: string } } + responses: + "204": { description: Forwarded (or nothing to forward). } + "400": { $ref: "#/components/responses/BadRequest" } + "403": { description: "telemetry_disabled, user_token_required, or the client holds neither telemetry nor licences (FORBIDDEN_CLIENT)." } + "413": { description: "The batch exceeds 256 KiB (too_large)." } + "429": { description: "More than 120 batches from this person in the last hour (rate_limited)." } + "502": { description: "The collector did not take the batch (telemetry_failed)." } + "503": { description: "TELEMETRY_OTLP_TOKEN not set (telemetry_unavailable)." } + /.well-known/licence-keys.json: get: summary: Licence verification keys (JWKS, OKP/Ed25519). PUBLIC_EXPLICIT. @@ -2829,6 +2943,12 @@ components: type: array items: { type: string, enum: [llm_key_unavailable] } description: Non-fatal issue notes; the licence itself is valid. + telemetry: + type: boolean + description: | + The workspace's telemetry switch for the licence's product + (werkpilot#87; default false). Informational, not a claim: + POST /v1/telemetry enforces the setting itself. LicenceHeartbeat: type: object properties: @@ -2837,6 +2957,18 @@ components: expires_at: { type: string, format: date-time } reason: { type: string } renewed: { $ref: "#/components/schemas/LicenceIssued" } + telemetry: + type: boolean + description: The workspace's current telemetry switch for the licence's product (false on revoked or unknown-tenant answers). + ProductTelemetry: + type: object + required: [tenant_id, product, enabled] + properties: + tenant_id: { type: string, format: uuid } + product: { type: string, example: werkpilot } + enabled: { type: boolean } + updated_by: { type: string } + updated_at: { type: string, format: date-time } TenantStatus: type: string enum: [demo, trial, active, warning, restricted, frozen, halted, archived]