Files
tenant-registry/internal/server/telemetry_relay.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

251 lines
9.2 KiB
Go

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
}