Files
tenant-registry/internal/server/telemetry_relay_test.go
Sharang ParnerkarandClaude Opus 5.5 849e79ada0
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Successful in 6m57s
ci / image (pull_request) Skipped
feat(telemetry): opt-in product telemetry relay and per-tenant switch
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
2026-11-23 15:25:43 +01:00

519 lines
25 KiB
Go

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)
}
}
}
}