package dataplane_test import ( "context" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "net/url" "slices" "strings" "sync" "testing" "time" "tangled.org/guid.foo/simmer/api/v1alpha1" "tangled.org/guid.foo/simmer/dataplane" ) // fakeReviewer answers a TokenReview from a table of tokens. type fakeReviewer map[string]dataplane.Caller func (f fakeReviewer) Review(_ context.Context, token string) (dataplane.Caller, error) { caller, ok := f[token] if !ok { return dataplane.Caller{}, dataplane.ErrUnauthenticated } return caller, nil } // fakePods answers a pod read from a table keyed by namespace/name. type fakePods map[string]dataplane.Pod func (f fakePods) Pod(_ context.Context, namespace, name string) (dataplane.Pod, error) { pod, ok := f[namespace+"/"+name] if !ok { return dataplane.Pod{}, dataplane.ErrNoPod } return pod, nil } // fakeControl knows one Session, platform, and records each request. type fakeControl struct { mu sync.Mutex turn dataplane.Turn follows []string releases []string // holders answers the holders route, by key. holders map[string][]dataplane.Holder sessionUsage []dataplane.RateLimitInfo accountUsage map[string]dataplane.RateLimitInfo tokens []dataplane.TokensRequest // followUps records each follow-up set, as its duration and reason, // and cancels counts the cancels. refuse is what SetFollowUp // answers, when it is set. followUps []string cancels int refuse error // hooks records the Job of each hook context asked for. hooks []string // starts records the Job of each start, and refuseStart is what // Start answers, when it is set. starts []string refuseStart error } func (c *fakeControl) known(session dataplane.SessionRef) error { if session != platform { return dataplane.ErrUnknownSession } return nil } func (c *fakeControl) HookServiceAccount(_ context.Context, session dataplane.SessionRef) (string, error) { if session == platform { return "simmer-platform--status", nil } return "", dataplane.ErrUnknownSession } func (c *fakeControl) ServiceAccount(_ context.Context, session dataplane.SessionRef) (string, error) { switch session { case platform: return "simmer-platform", nil case dataplane.SessionRef{Namespace: "telemetry", Name: "platform-9c1d0"}: return "simmer-platform", nil } return "", dataplane.ErrUnknownSession } func (c *fakeControl) Turn(_ context.Context, session dataplane.SessionRef) (dataplane.Turn, error) { return c.turn, c.known(session) } func (c *fakeControl) Follow(_ context.Context, session dataplane.SessionRef, key string) error { c.mu.Lock() defer c.mu.Unlock() c.follows = append(c.follows, key) return c.known(session) } func (c *fakeControl) Release(_ context.Context, session dataplane.SessionRef, key string) error { c.mu.Lock() defer c.mu.Unlock() c.releases = append(c.releases, key) return c.known(session) } func (c *fakeControl) Holders(_ context.Context, session dataplane.SessionRef, key string) ([]dataplane.Holder, error) { return c.holders[key], c.known(session) } func (c *fakeControl) SessionUsage(_ context.Context, session dataplane.SessionRef, info dataplane.RateLimitInfo) error { c.mu.Lock() defer c.mu.Unlock() c.sessionUsage = append(c.sessionUsage, info) return c.known(session) } func (c *fakeControl) SessionTokens(_ context.Context, session dataplane.SessionRef, tokens dataplane.TokensRequest) error { c.mu.Lock() defer c.mu.Unlock() c.tokens = append(c.tokens, tokens) return c.known(session) } // followUpAt is when every follow-up that fakeControl sets falls due. var followUpAt = time.Date(2026, 10, 18, 16, 0, 0, 0, time.UTC) func (c *fakeControl) SetFollowUp(_ context.Context, session dataplane.SessionRef, after time.Duration, reason string) (time.Time, error) { c.mu.Lock() defer c.mu.Unlock() if c.refuse != nil { return time.Time{}, c.refuse } c.followUps = append(c.followUps, after.String()+" "+reason) return followUpAt, c.known(session) } func (c *fakeControl) CancelFollowUp(_ context.Context, session dataplane.SessionRef) error { c.mu.Lock() defer c.mu.Unlock() c.cancels++ return c.known(session) } // Hook knows one hook, the after hook of platform-7f3a2's first turn. func (c *fakeControl) Hook(_ context.Context, session dataplane.SessionRef, job string) (dataplane.HookContext, error) { c.mu.Lock() defer c.mu.Unlock() c.hooks = append(c.hooks, job) if err := c.known(session); err != nil { return dataplane.HookContext{}, err } if job != "platform-7f3a2-1-after" { return dataplane.HookContext{}, dataplane.ErrUnknownSession } return dataplane.HookContext{Hook: dataplane.HookAfter, Session: session.Name, Turn: 1, Outcome: v1alpha1.OutcomeSucceeded}, nil } func (c *fakeControl) AccountUsage(_ context.Context, account string, info dataplane.RateLimitInfo) error { c.mu.Lock() defer c.mu.Unlock() c.accountUsage[account] = info return nil } // jobPod builds a running Job pod with the token that speaks for it. // Its Job's name is the pod's name up to its last dash. func jobPod(namespace, name string, labels map[string]string) (dataplane.Caller, dataplane.Pod) { caller := dataplane.Caller{Namespace: namespace, ServiceAccount: "simmer-platform", Pod: name, PodUID: name + "-uid"} pod := dataplane.Pod{ Namespace: namespace, Name: name, UID: name + "-uid", Phase: "Running", ServiceAccount: "simmer-platform", Labels: labels, OwnedByJob: true, Job: name[:strings.LastIndex(name, "-")], } return caller, pod } type world struct { store dataplane.Store control *fakeControl handler http.Handler } // newWorld serves the data plane to a cluster with one pod for each // kind of caller, and names each caller's token for what it is. func newWorld(t *testing.T) world { t.Helper() reviewer, pods := fakeReviewer{}, fakePods{} add := func(token string, caller dataplane.Caller, pod dataplane.Pod) { reviewer[token] = caller pods[pod.Namespace+"/"+pod.Name] = pod } caller, pod := jobPod("telemetry", "platform-7f3a2-1-x8k2p", map[string]string{v1alpha1.LabelSession: "platform-7f3a2"}) add("own", caller, pod) caller, pod = jobPod("telemetry", "platform-9c1d0-1-q2w3e", map[string]string{v1alpha1.LabelSession: "platform-9c1d0"}) add("other-session", caller, pod) caller, pod = jobPod("simmer", "probe-personal-1-h7j8k", map[string]string{v1alpha1.LabelProbe: "personal"}) add("probe", caller, pod) caller, pod = jobPod("telemetry", "platform-7f3a2-2-done", map[string]string{v1alpha1.LabelSession: "platform-7f3a2"}) pod.Phase = "Succeeded" add("finished", caller, pod) // The kubelet reports Running a moment after the container starts, // so a turn's first request can come from a pod that still reads // Pending. caller, pod = jobPod("telemetry", "platform-7f3a2-3-start", map[string]string{v1alpha1.LabelSession: "platform-7f3a2"}) pod.Phase = "Pending" add("starting", caller, pod) caller, pod = jobPod("telemetry", "platform-7f3a2-bare", map[string]string{v1alpha1.LabelSession: "platform-7f3a2"}) pod.OwnedByJob = false add("not-a-job", caller, pod) // A pod of another Mandate's Job, which a template or a role let // label itself as a pod of platform-7f3a2. caller, pod = jobPod("telemetry", "platform-7f3a2-1-other", map[string]string{v1alpha1.LabelSession: "platform-7f3a2"}) caller.ServiceAccount, pod.ServiceAccount = "simmer-backups", "simmer-backups" add("other-mandate", caller, pod) // A pod of the right ServiceAccount and label whose Job is not one // of the Session's turns. caller, pod = jobPod("telemetry", "debug-x8k2p", map[string]string{v1alpha1.LabelSession: "platform-7f3a2"}) add("other-job", caller, pod) // The pod of the after hook of the Session's first turn. Its Job is // named for the Session, as a turn's is. The Duty's hooks run as a // ServiceAccount of their own. caller, pod = jobPod("telemetry", "platform-7f3a2-1-after-z9y8x", map[string]string{v1alpha1.LabelSession: "platform-7f3a2", v1alpha1.LabelHook: "after"}) caller.ServiceAccount, pod.ServiceAccount = "simmer-platform--status", "simmer-platform--status" add("hook", caller, pod) // A hook's pod of the Session that runs as the ServiceAccount of // the Session's turns, not of its hooks. caller, pod = jobPod("telemetry", "platform-7f3a2-1-before-a1b2c", map[string]string{v1alpha1.LabelSession: "platform-7f3a2", v1alpha1.LabelHook: "before"}) add("hook-as-the-turn", caller, pod) // A hook's pod of another Session. caller, pod = jobPod("telemetry", "platform-9c1d0-1-after-z9y8x", map[string]string{v1alpha1.LabelSession: "platform-9c1d0", v1alpha1.LabelHook: "after"}) add("other-hook", caller, pod) schedulePods(add) caller, _ = jobPod("telemetry", "platform-7f3a2-1-x8k2p", nil) caller.PodUID = "an-earlier-pod-uid" reviewer["earlier-pod"] = caller caller, _ = jobPod("telemetry", "platform-7f3a2-1-gone0", nil) reviewer["deleted-pod"] = caller caller, _ = jobPod("telemetry", "platform-7f3a2-1-x8k2p", nil) caller.Namespace = "other" reviewer["other-namespace"] = caller store := openStore(t) control := &fakeControl{accountUsage: map[string]dataplane.RateLimitInfo{}} return world{store: store, control: control, handler: dataplane.NewServer(store, control, reviewer, pods, "simmer")} } func (w world) send(method, path, token, body string) *httptest.ResponseRecorder { r := httptest.NewRequest(method, path, strings.NewReader(body)) if token != "" { r.Header.Set("Authorization", "Bearer "+token) } recorder := httptest.NewRecorder() w.handler.ServeHTTP(recorder, r) return recorder } const usageBody = `{"status":"allowed","unifiedWindows":{"five_hour":{"utilization":0.07,"resetsAt":1792174200},"seven_day":{"utilization":0.21,"resetsAt":1792425600}}}` var sessionRoutes = []struct{ method, path, body string }{ {"GET", "/v1/sessions/telemetry/platform-7f3a2/turn", ""}, {"GET", "/v1/sessions/telemetry/platform-7f3a2/transcript", ""}, {"PUT", "/v1/sessions/telemetry/platform-7f3a2/transcript", "archive"}, {"POST", "/v1/sessions/telemetry/platform-7f3a2/keys", `{"key":"k"}`}, {"DELETE", "/v1/sessions/telemetry/platform-7f3a2/keys", `{"key":"k"}`}, {"POST", "/v1/sessions/telemetry/platform-7f3a2/usage", usageBody}, {"POST", "/v1/sessions/telemetry/platform-7f3a2/tokens", `{"tokens":1200}`}, {"GET", "/v1/sessions/telemetry/platform-7f3a2/holders?key=k", ""}, {"PUT", "/v1/sessions/telemetry/platform-7f3a2/follow-up", `{"after":"2h","reason":"r"}`}, {"DELETE", "/v1/sessions/telemetry/platform-7f3a2/follow-up", ""}, } func TestEverySessionRouteChecksItsCaller(t *testing.T) { cases := []struct { token string want int }{ {"", http.StatusUnauthorized}, {"forged", http.StatusUnauthorized}, {"other-session", http.StatusForbidden}, {"probe", http.StatusForbidden}, {"finished", http.StatusForbidden}, {"not-a-job", http.StatusForbidden}, {"earlier-pod", http.StatusForbidden}, {"deleted-pod", http.StatusForbidden}, {"other-namespace", http.StatusForbidden}, {"other-mandate", http.StatusForbidden}, {"other-job", http.StatusForbidden}, {"hook", http.StatusForbidden}, } for _, route := range sessionRoutes { for _, c := range cases { t.Run(fmt.Sprintf("%s %s as %q", route.method, route.path, c.token), func(t *testing.T) { got := newWorld(t).send(route.method, route.path, c.token, route.body) if got.Code != c.want { t.Errorf("answered %d, want %d: %s", got.Code, c.want, got.Body) } }) } } } func TestTheHookRouteAcceptsOnlyTheSessionsHookPods(t *testing.T) { cases := []struct { token string want int }{ {"", http.StatusUnauthorized}, {"own", http.StatusForbidden}, {"other-hook", http.StatusForbidden}, {"probe", http.StatusForbidden}, {"finished", http.StatusForbidden}, {"hook-as-the-turn", http.StatusForbidden}, {"hook", http.StatusOK}, } for _, c := range cases { t.Run(c.token, func(t *testing.T) { got := newWorld(t).send("GET", "/v1/sessions/telemetry/platform-7f3a2/hook", c.token, "") if got.Code != c.want { t.Errorf("answered %d, want %d: %s", got.Code, c.want, got.Body) } }) } } func TestAHookReadsTheContextOfItsOwnJob(t *testing.T) { w := newWorld(t) context := decode[dataplane.HookContext](t, w.send("GET", "/v1/sessions/telemetry/platform-7f3a2/hook", "hook", "")) if fmt.Sprint(w.control.hooks) != "[platform-7f3a2-1-after]" { t.Errorf("the server asked for the hooks of %v", w.control.hooks) } if context.Hook != dataplane.HookAfter || context.Turn != 1 || context.Outcome != v1alpha1.OutcomeSucceeded { t.Errorf("context is %+v", context) } } func TestTheAccountsRouteAcceptsOnlyThatAccountsProbe(t *testing.T) { cases := []struct { token, account string want int }{ {"", "personal", http.StatusUnauthorized}, {"own", "personal", http.StatusForbidden}, {"probe", "work", http.StatusForbidden}, {"probe", "personal", http.StatusNoContent}, } for _, c := range cases { t.Run(c.token+" for "+c.account, func(t *testing.T) { got := newWorld(t).send("POST", "/v1/accounts/"+c.account+"/usage", c.token, usageBody) if got.Code != c.want { t.Errorf("answered %d, want %d: %s", got.Code, c.want, got.Body) } }) } } func TestAnUnknownSessionIsNotFound(t *testing.T) { w := newWorld(t) w.control.turn = dataplane.Turn{Number: 1} // The pod belongs to the Session, but the operator no longer knows // it, as after the Session finished. got := w.send("GET", "/v1/sessions/telemetry/platform-9c1d0/turn", "other-session", "") if got.Code != http.StatusNotFound { t.Errorf("answered %d: %s", got.Code, got.Body) } } func decode[T any](t *testing.T, r *httptest.ResponseRecorder) T { t.Helper() var v T if err := json.NewDecoder(r.Body).Decode(&v); err != nil { t.Fatalf("answered %d with %q: %v", r.Code, r.Body, err) } return v } func TestTheTurnCarriesTheEventsItTook(t *testing.T) { w := newWorld(t) w.control.turn = dataplane.Turn{Session: platform, UID: "8e0c", Number: 2, Skill: "alert-triage"} deliver(t, w.store, "a", "b") turn := decode[dataplane.Turn](t, w.send("GET", "/v1/sessions/telemetry/platform-7f3a2/turn", "own", "")) if got := fmt.Sprintf("%s %d %s", turn.Skill, len(turn.Events), turn.Events[0].ID); got != "alert-triage 2 a" { t.Errorf("turn is %s", got) } } func TestTheTurnTakesItsEventsUnderItsNumber(t *testing.T) { w := newWorld(t) w.control.turn = dataplane.Turn{Session: platform, Number: 2} deliver(t, w.store, "a") w.send("GET", "/v1/sessions/telemetry/platform-7f3a2/turn", "own", "") ack(t, w.store, 2) if got := pending(t, w.store); got != 0 { t.Errorf("pending is %d after the turn's ack", got) } } func TestAMissingTranscriptIsNotFound(t *testing.T) { got := newWorld(t).send("GET", "/v1/sessions/telemetry/platform-7f3a2/transcript", "own", "") if got.Code != http.StatusNotFound { t.Errorf("answered %d", got.Code) } } func TestATranscriptPutComesBack(t *testing.T) { w := newWorld(t) w.send("PUT", "/v1/sessions/telemetry/platform-7f3a2/transcript", "own", "archive bytes") got := w.send("GET", "/v1/sessions/telemetry/platform-7f3a2/transcript", "own", "") body, _ := io.ReadAll(got.Body) if string(body) != "archive bytes" { t.Errorf("answered %d with %q", got.Code, body) } } func TestFollowAndReleaseReachControl(t *testing.T) { w := newWorld(t) w.send("POST", "/v1/sessions/telemetry/platform-7f3a2/keys", "own", `{"key":"issue/200"}`) w.send("DELETE", "/v1/sessions/telemetry/platform-7f3a2/keys", "own", `{"key":"alert/x"}`) if got := fmt.Sprint(w.control.follows, w.control.releases); got != "[issue/200] [alert/x]" { t.Errorf("follows and releases are %s", got) } } func TestAKeyRequestWithoutAKeyIsABadRequest(t *testing.T) { got := newWorld(t).send("POST", "/v1/sessions/telemetry/platform-7f3a2/keys", "own", `{}`) if got.Code != http.StatusBadRequest { t.Errorf("answered %d", got.Code) } } func TestASessionsUsageReachesControl(t *testing.T) { w := newWorld(t) w.send("POST", "/v1/sessions/telemetry/platform-7f3a2/usage", "own", usageBody) got := w.control.sessionUsage[0].UnifiedWindows if got.FiveHour.Utilization != 0.07 || got.SevenDay.ResetsAt != 1792425600 { t.Errorf("usage is %+v", got) } } func TestASessionsTokensReachControl(t *testing.T) { w := newWorld(t) w.send("POST", "/v1/sessions/telemetry/platform-7f3a2/tokens", "own", `{"tokens":1200,"costUSD":0.75,"resumed":true}`) if len(w.control.tokens) != 1 || w.control.tokens[0] != (dataplane.TokensRequest{Tokens: 1200, CostUSD: 0.75, Resumed: true}) { t.Errorf("tokens are %v", w.control.tokens) } } func TestATokenCountOrACostBelowZeroIsRefused(t *testing.T) { for _, body := range []string{`{"tokens":-5}`, `{"tokens":5,"costUSD":-0.5}`} { t.Run(body, func(t *testing.T) { got := newWorld(t).send("POST", "/v1/sessions/telemetry/platform-7f3a2/tokens", "own", body) if got.Code != http.StatusBadRequest { t.Errorf("answered %d", got.Code) } }) } } func TestAProbesUsageReachesControl(t *testing.T) { w := newWorld(t) w.send("POST", "/v1/accounts/personal/usage", "probe", usageBody) if got := w.control.accountUsage["personal"].UnifiedWindows.SevenDay.Utilization; got != 0.21 { t.Errorf("seven-day usage is %v", got) } } func TestAPodThatStillReadsPendingIsServed(t *testing.T) { got := newWorld(t).send("POST", "/v1/sessions/telemetry/platform-7f3a2/keys", "starting", `{"key":"k"}`) if got.Code == http.StatusForbidden || got.Code == http.StatusUnauthorized { t.Errorf("answered %d: %s", got.Code, got.Body) } } // reviewerHolder is a Session of another Mandate that holds the pull // request https://forge.example/pulls/7. var reviewerHolder = dataplane.Holder{Namespace: "builders", Name: "factory-x7k2p", Mandate: "factory", Skill: "review"} func TestTheHoldersOfAKeyComeFromControl(t *testing.T) { cases := []struct { key string want []dataplane.Holder }{ {"https://forge.example/pulls/7", []dataplane.Holder{reviewerHolder}}, {"alert/x", nil}, } for _, c := range cases { t.Run(c.key, func(t *testing.T) { w := newWorld(t) w.control.holders = map[string][]dataplane.Holder{"https://forge.example/pulls/7": {reviewerHolder}} got := decode[dataplane.HoldersAnswer](t, w.send("GET", "/v1/sessions/telemetry/platform-7f3a2/holders?key="+url.QueryEscape(c.key), "own", "")) if !slices.Equal(got.Holders, c.want) { t.Errorf("holders are %+v, want %+v", got.Holders, c.want) } }) } } func TestAHoldersRequestWithoutAKeyIsABadRequest(t *testing.T) { got := newWorld(t).send("GET", "/v1/sessions/telemetry/platform-7f3a2/holders", "own", "") if got.Code != http.StatusBadRequest { t.Errorf("answered %d", got.Code) } } func TestAFollowUpReachesControlAndAnswersItsTime(t *testing.T) { w := newWorld(t) got := w.send("PUT", "/v1/sessions/telemetry/platform-7f3a2/follow-up", "own", `{"after":"90m","reason":"Read the p99."}`) answer := decode[dataplane.FollowUpAnswer](t, got) if got.Code != http.StatusOK || !answer.At.Equal(followUpAt) || fmt.Sprint(w.control.followUps) != "[1h30m0s Read the p99.]" { t.Errorf("answered %d with %v, and control got %v", got.Code, answer.At, w.control.followUps) } } // The data plane checks the bounds that hold in every Mandate before it // asks the operator, so a request out of them never reaches control. func TestAFollowUpOutOfItsBoundsIsABadRequest(t *testing.T) { cases := []struct{ name, body string }{ {"no duration", `{"after":"soon","reason":"r"}`}, {"a duration shorter than ten minutes", `{"after":"9m59s","reason":"r"}`}, {"no reason", `{"after":"2h"}`}, {"a reason of spaces", `{"after":"2h","reason":" "}`}, {"a reason over 500 characters", `{"after":"2h","reason":"` + strings.Repeat("é", 501) + `"}`}, {"no body", ``}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { w := newWorld(t) got := w.send("PUT", "/v1/sessions/telemetry/platform-7f3a2/follow-up", "own", c.body) if got.Code != http.StatusBadRequest || len(w.control.followUps) != 0 { t.Errorf("answered %d, and control got %v; want 400 and nothing", got.Code, w.control.followUps) } }) } } func TestAFollowUpOfTenMinutesAndAReasonOf500CharactersIsAllowed(t *testing.T) { w := newWorld(t) got := w.send("PUT", "/v1/sessions/telemetry/platform-7f3a2/follow-up", "own", `{"after":"10m","reason":"`+strings.Repeat("é", 500)+`"}`) if got.Code != http.StatusOK || len(w.control.followUps) != 1 { t.Errorf("answered %d: %s", got.Code, got.Body) } } func TestTheOperatorsRefusalsOfAFollowUpKeepTheirStatus(t *testing.T) { cases := []struct { refusal error want int }{ {fmt.Errorf("%w: past maxFollowUp", dataplane.ErrFollowUpOutOfBounds), http.StatusBadRequest}, {fmt.Errorf("%w: maxFollowUps", dataplane.ErrFollowUpRefused), http.StatusConflict}, } for _, c := range cases { t.Run(c.refusal.Error(), func(t *testing.T) { w := newWorld(t) w.control.refuse = c.refusal got := w.send("PUT", "/v1/sessions/telemetry/platform-7f3a2/follow-up", "own", `{"after":"2h","reason":"r"}`) if got.Code != c.want || !strings.Contains(got.Body.String(), c.refusal.Error()) { t.Errorf("answered %d with %s, want %d and the refusal", got.Code, got.Body, c.want) } }) } } func TestACancelOfAFollowUpReachesControl(t *testing.T) { w := newWorld(t) got := w.send("DELETE", "/v1/sessions/telemetry/platform-7f3a2/follow-up", "own", "") if got.Code != http.StatusNoContent || w.control.cancels != 1 { t.Errorf("answered %d, and control got %d cancels", got.Code, w.control.cancels) } }