package adopt import ( "context" "net/http" "net/http/httptest" "strings" "sync/atomic" "testing" "amadan.net/oficina/alta/provision" ) // site is a fake app origin: version, header, healthz and operations are // each settable. type site struct { version, header string health int ops func(w http.ResponseWriter) redirectVersion bool versionHost atomic.Value // the Host the last /api/version asked signIn func(w http.ResponseWriter) // GET /auth/start; nil is a 404 signIns atomic.Int64 // GET /auth/start requests followed atomic.Int64 // requests that chased the redirect } // lastHost is the host the last version probe was addressed to. func (s *site) lastHost() string { h, _ := s.versionHost.Load().(string) return h } func (s *site) handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("/api/version", func(w http.ResponseWriter, r *http.Request) { s.versionHost.Store(r.Host) if s.redirectVersion { http.Redirect(w, r, "/elsewhere", http.StatusFound) return } w.Header().Set("X-Carlos-Version", s.header) _, _ = w.Write([]byte(s.version)) }) mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(s.health) }) mux.HandleFunc("/auth/start", func(w http.ResponseWriter, r *http.Request) { s.signIns.Add(1) if s.signIn == nil { http.NotFound(w, r) return } s.signIn(w) }) // Every https origin lands on this site, the issuer's too. mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { s.followed.Add(1) }) mux.HandleFunc("/api/v1/operations", func(w http.ResponseWriter, r *http.Request) { if s.ops == nil { http.NotFound(w, r) return } s.ops(w) }) return mux } func agent401(w http.ResponseWriter) { w.Header().Set("WWW-Authenticate", `Bearer realm="oficina"`) w.Header().Set("Cache-Control", "no-store") w.Header().Set("Content-Type", "application/json") w.WriteHeader(401) _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated","message":"x"}}`)) } // respond answers status with headers and body. func respond(status int, headers map[string]string, body string) func(w http.ResponseWriter) { return func(w http.ResponseWriter) { for k, v := range headers { w.Header().Set(k, v) } w.WriteHeader(status) _, _ = w.Write([]byte(body)) } } // agent200 is a 200 in agent-access's headers, with body. func agent200(body string) func(w http.ResponseWriter) { return respond(200, map[string]string{"Cache-Control": "no-store", "Content-Type": "application/json"}, body) } // agent401Body is a 401 in agent-access's headers, with body. A // WWW-Authenticate already set is kept, as agent-access keeps it. func agent401Body(body string) func(w http.ResponseWriter) { return func(w http.ResponseWriter) { if w.Header().Get("WWW-Authenticate") == "" { w.Header().Set("WWW-Authenticate", "Bearer") } respond(401, map[string]string{"Cache-Control": "no-store", "Content-Type": "application/json"}, body)(w) } } func probeOf(t *testing.T, s *site) Delivery { t.Helper() srv := httptest.NewServer(s.handler()) defer srv.Close() d, err := Probe(context.Background(), srv.Client(), srv.URL) if err != nil { t.Fatalf("Probe: %v", err) } return d } func TestOperationsShapeDistinguishesAppMiddleware(t *testing.T) { cases := map[string]struct { ops func(w http.ResponseWriter) want OpsShape }{ "absent": {nil, "absent"}, "app-401": {func(w http.ResponseWriter) { w.WriteHeader(401) _, _ = w.Write([]byte(`{"error":"unauthorized"}`)) }, "app-401"}, "app-401-with-bearer-but-string-error": {func(w http.ResponseWriter) { w.Header().Set("WWW-Authenticate", "Bearer") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(401) _, _ = w.Write([]byte(`{"error":"unauthorized"}`)) }, "app-401"}, "agent-401": {agent401, "agent-401"}, "agent-401-cache-missing": {func(w http.ResponseWriter) { w.Header().Set("WWW-Authenticate", "Bearer") w.WriteHeader(401) _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated"}}`)) }, "app-401"}, "agent-401-wrong-scheme": {func(w http.ResponseWriter) { w.Header().Set("WWW-Authenticate", "Basic") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(401) _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated"}}`)) }, "app-401"}, "agent-401-wrong-code": {func(w http.ResponseWriter) { w.Header().Set("WWW-Authenticate", "Bearer") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(401) _, _ = w.Write([]byte(`{"error":{"code":"other"}}`)) }, "app-401"}, "agent-200": {agent200(`{"operations":[]}` + "\n"), "agent-200"}, "agent-200-listed": {agent200(`{"operations":[{"name":"docs_read"}]}`), "agent-200"}, "other": {func(w http.ResponseWriter) { w.WriteHeader(500) }, "other"}, } // Lookalike 200s: only agent-access's own list, in its own headers, // counts. for name, ops := range map[string]func(w http.ResponseWriter){ "200-empty-object": agent200(`{}`), "200-html": respond(200, map[string]string{"Cache-Control": "no-store", "Content-Type": "text/html"}, `

app`), "200-no-store-missing": respond(200, map[string]string{"Content-Type": "application/json"}, `{"operations":[]}`), "200-json-missing": respond(200, map[string]string{"Cache-Control": "no-store"}, `{"operations":[]}`), "200-null-list": agent200(`{"operations":null}`), "200-object-list": agent200(`{"operations":{}}`), "200-extra-key": agent200(`{"operations":[],"user":"x"}`), "200-key-case": agent200(`{"Operations":[]}`), "200-trailing": agent200(`{"operations":[]} {}`), "200-bare-array": agent200(`[]`), } { cases[name] = struct { ops func(w http.ResponseWriter) want OpsShape }{ops, "other"} } // Lookalike 401s: a Bearer challenge with no-store is not enough. for name, ops := range map[string]func(w http.ResponseWriter){ "401-message-missing": agent401Body(`{"error":{"code":"unauthenticated"}}`), "401-message-empty": agent401Body(`{"error":{"code":"unauthenticated","message":""}}`), "401-extra-error-key": agent401Body(`{"error":{"code":"unauthenticated","message":"x","detail":"y"}}`), "401-extra-top-key": agent401Body(`{"error":{"code":"unauthenticated","message":"x"},"login":"/signin"}`), "401-key-case": agent401Body(`{"Error":{"Code":"unauthenticated","Message":"x"}}`), "401-code-not-string": agent401Body(`{"error":{"code":401,"message":"x"}}`), "401-other-code": agent401Body(`{"error":{"code":"forbidden","message":"x"}}`), "401-trailing": agent401Body(`{"error":{"code":"unauthenticated","message":"x"}}x`), "401-json-missing": respond(401, map[string]string{"WWW-Authenticate": "Bearer", "Cache-Control": "no-store"}, `{"error":{"code":"unauthenticated","message":"x"}}`), "401-not-bearer-scheme": respond(401, map[string]string{"WWW-Authenticate": "Bearerish", "Cache-Control": "no-store", "Content-Type": "application/json"}, `{"error":{"code":"unauthenticated","message":"x"}}`), "401-two-challenges": func(w http.ResponseWriter) { w.Header().Add("WWW-Authenticate", "Bearer") w.Header().Add("WWW-Authenticate", "Basic") agent401Body(`{"error":{"code":"unauthenticated","message":"x"}}`)(w) }, } { cases[name] = struct { ops func(w http.ResponseWriter) want OpsShape }{ops, "app-401"} } // agent-access's own variants of its challenge still count. cases["agent-401-resource-metadata"] = struct { ops func(w http.ResponseWriter) want OpsShape }{respond(401, map[string]string{"WWW-Authenticate": `Bearer resource_metadata="https://x.example/.well-known/oauth-protected-resource"`, "Cache-Control": "no-store", "Content-Type": "application/json; charset=utf-8"}, `{"error":{"code":"unauthenticated","message":"Connect to Oficina first."}}`+"\n"), "agent-401"} for name, c := range cases { t.Run(name, func(t *testing.T) { d := probeOf(t, &site{version: "v1", header: "v1", health: 200, ops: c.ops}) if d.Ops != c.want { t.Fatalf("ops = %q, want %q", d.Ops, c.want) } }) } } func TestProbeRecordsVersionHeaderHealth(t *testing.T) { d := probeOf(t, &site{version: "v1.2", header: "rel-9", health: 200}) if d.Version != "v1.2" || d.Header != "rel-9" || d.Health != 200 || d.Redirected || d.At.IsZero() { t.Fatalf("delivery = %+v", d) } } func TestProbeRefusesRedirect(t *testing.T) { s := &site{version: "v1", header: "v1", health: 200, redirectVersion: true} srv := httptest.NewServer(s.handler()) defer srv.Close() d, err := Probe(context.Background(), srv.Client(), srv.URL) if err != nil { t.Fatalf("Probe: %v", err) } if !d.Redirected || d.Version != "" { t.Fatalf("a redirect must be recorded, not followed: %+v", d) } before := Delivery{Version: "v1", Header: "v1", Health: 200, Ops: "absent"} now := Delivery{Version: "v1", Header: "v1", Health: 200, Ops: "agent-401", Redirected: true} if err := Delivered(appNamedStatic("docs"), before, now); err == nil { t.Fatal("Delivered accepted a redirect") } } func TestProbeRefusesNonLoopbackHTTP(t *testing.T) { if _, err := Probe(context.Background(), http.DefaultClient, "http://example.com"); err == nil { t.Fatal("plain http to a non-loopback origin was accepted") } } func TestProbeErrorsCarryNoBody(t *testing.T) { // The answer promises more bytes than it sends, so the body read fails // after recognisable content has arrived. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Length", "1000") _, _ = w.Write([]byte("LEAKY-BODY-CONTENT")) })) defer srv.Close() _, err := Probe(context.Background(), srv.Client(), srv.URL) if err == nil { t.Fatal("expected a body read failure") } for _, leak := range []string{"LEAKY-BODY-CONTENT", srv.URL, strings.TrimPrefix(srv.URL, "http://")} { if strings.Contains(err.Error(), leak) { t.Fatalf("error leaks %q: %v", leak, err) } } } func TestProbeKeepsBodyExactly(t *testing.T) { s := &site{version: "v1\n", header: "v1", health: 200} a := probeOf(t, s) s.version = "v1" b := probeOf(t, s) if a.Version == b.Version { t.Fatal("a whitespace-only change was hidden") } before := Delivery{Version: a.Version, Header: "v1", Health: 200, Ops: "absent"} now := Delivery{Version: b.Version, Header: "v1", Health: 200, Ops: "agent-401"} if err := Delivered(appNamedStatic("docs"), before, now); err == nil { t.Fatal("Delivered approved a whitespace-only change") } } func TestProbeRejectsOversizedBodies(t *testing.T) { prefix := strings.Repeat("a", bodyLimit) for _, tail := range []string{"x", "y"} { body := prefix + tail srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(body)) })) _, err := Probe(context.Background(), srv.Client(), srv.URL) srv.Close() if err == nil { t.Fatalf("oversized body (%s) accepted", tail) } } // Exactly the limit is fine. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(prefix)) })) defer srv.Close() if _, err := Probe(context.Background(), srv.Client(), srv.URL); err != nil { t.Fatalf("a body of exactly the limit refused: %v", err) } } func dl(v, h string, health int, ops OpsShape) Delivery { return Delivery{Version: v, Header: h, Health: health, Ops: ops} } func TestDeliveredRefusesVersionOrHeaderChange(t *testing.T) { before := dl("v1", "v1", 200, "absent") docs := appNamedStatic("docs") if err := Delivered(docs, before, dl("v1", "v1", 200, "agent-401")); err != nil { t.Fatalf("good delivery refused: %v", err) } if err := Delivered(docs, before, dl("v1", "v1", 200, "agent-200")); err != nil { t.Fatalf("agent-200 refused: %v", err) } bad := map[string]Delivery{ "version": dl("v2", "v1", 200, "agent-401"), "header": dl("v1", "v2", 200, "agent-401"), "health": dl("v1", "v1", 503, "agent-401"), "still-absent": dl("v1", "v1", 200, "absent"), "still-app-401": dl("v1", "v1", 200, "app-401"), "other": dl("v1", "v1", 200, "other"), "redirect": {Version: "v1", Header: "v1", Health: 200, Ops: "agent-401", Redirected: true}, } for n, now := range bad { if err := Delivered(appNamedStatic("docs"), before, now); err == nil { t.Errorf("%s: accepted", n) } } // Before already agent-shaped: nothing was delivered by this run. if err := Delivered(docs, dl("v1", "v1", 200, "agent-401"), dl("v1", "v1", 200, "agent-401")); err == nil { t.Error("an already agent-shaped before was accepted") } } // The operations door must move as the app's must (Paul, 2026-11-17): for // four apps a 404 to agent-access's challenge or list, for Slides, Calls // and Equipo their own 401 to agent-access's challenge, for Base its own // agent-shaped 401 held (approved 2026-11-23, docs/base-adoption.md), and nothing else. func TestDeliveredHoldsEachAppToItsTransition(t *testing.T) { d := func(ops OpsShape) Delivery { return dl("v1", "v1", 200, ops) } for _, a := range provision.Apps { t.Run(a.Slug, func(t *testing.T) { var good, bad [][2]OpsShape switch a.Slug { case "base": good = [][2]OpsShape{{OpsAgent401, OpsAgent401}} bad = [][2]OpsShape{{OpsAgent401, OpsAgent200}, {OpsAgent401, OpsOther}, {OpsAgent401, OpsApp401}, {OpsAgent401, OpsAbsent}, {OpsAbsent, OpsAgent401}, {OpsApp401, OpsAgent401}} case "slides", "calls", "equipo": good = [][2]OpsShape{{OpsApp401, OpsAgent401}} bad = [][2]OpsShape{{OpsApp401, OpsAgent200}, {OpsApp401, OpsOther}, {OpsApp401, OpsApp401}, {OpsAbsent, OpsAgent401}, {OpsAbsent, OpsAgent200}} default: good = [][2]OpsShape{{OpsAbsent, OpsAgent401}, {OpsAbsent, OpsAgent200}} bad = [][2]OpsShape{{OpsAbsent, OpsOther}, {OpsAbsent, OpsApp401}, {OpsAbsent, OpsAbsent}, {OpsApp401, OpsAgent401}, {OpsApp401, OpsAgent200}} } for _, before := range []OpsShape{OpsOther, OpsAgent200, OpsAgent401, ""} { if before != BaselineOps(a) { bad = append(bad, [2]OpsShape{before, OpsAgent401}) } } for _, c := range good { if err := Delivered(a, d(c[0]), d(c[1])); err != nil { t.Errorf("%s -> %s refused: %v", c[0], c[1], err) } } for _, c := range bad { if err := Delivered(a, d(c[0]), d(c[1])); err == nil { t.Errorf("%q -> %q accepted", c[0], c[1]) } } }) } } func TestBaselineOps(t *testing.T) { for _, a := range provision.Apps { want := OpsAbsent switch a.Slug { case "slides", "calls", "equipo": want = OpsApp401 case "base": want = OpsAgent401 } if got := BaselineOps(a); got != want { t.Fatalf("%s: %q, want %q", a.Slug, got, want) } } } func TestRevertedRequiresBeforeShape(t *testing.T) { before := dl("v1", "v1", 200, "app-401") if err := Reverted(before, dl("v1", "v1", 200, "app-401")); err != nil { t.Fatalf("good revert refused: %v", err) } bad := map[string]Delivery{ "still-agent": dl("v1", "v1", 200, "agent-401"), "version": dl("v2", "v1", 200, "app-401"), "header": dl("v1", "v2", 200, "app-401"), "health": dl("v1", "v1", 503, "app-401"), "other-shape": dl("v1", "v1", 200, "absent"), } for n, now := range bad { if err := Reverted(before, now); err == nil { t.Errorf("%s: accepted", n) } } }