oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1package adopt
2
3import (
4 "context"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "sync/atomic"
9 "testing"
10
11 "amadan.net/oficina/alta/provision"
12)
13
14// site is a fake app origin: version, header, healthz and operations are
15// each settable.
16type site struct {
17 version, header string
18 health int
19 ops func(w http.ResponseWriter)
20 redirectVersion bool
21 versionHost atomic.Value // the Host the last /api/version asked
22 signIn func(w http.ResponseWriter) // GET /auth/start; nil is a 404
23 signIns atomic.Int64 // GET /auth/start requests
24 followed atomic.Int64 // requests that chased the redirect
25}
26
27// lastHost is the host the last version probe was addressed to.
28func (s *site) lastHost() string {
29 h, _ := s.versionHost.Load().(string)
30 return h
31}
32
33func (s *site) handler() http.Handler {
34 mux := http.NewServeMux()
35 mux.HandleFunc("/api/version", func(w http.ResponseWriter, r *http.Request) {
36 s.versionHost.Store(r.Host)
37 if s.redirectVersion {
38 http.Redirect(w, r, "/elsewhere", http.StatusFound)
39 return
40 }
41 w.Header().Set("X-Carlos-Version", s.header)
42 _, _ = w.Write([]byte(s.version))
43 })
44 mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(s.health) })
45 mux.HandleFunc("/auth/start", func(w http.ResponseWriter, r *http.Request) {
46 s.signIns.Add(1)
47 if s.signIn == nil {
48 http.NotFound(w, r)
49 return
50 }
51 s.signIn(w)
52 })
53 // Every https origin lands on this site, the issuer's too.
54 mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { s.followed.Add(1) })
55 mux.HandleFunc("/api/v1/operations", func(w http.ResponseWriter, r *http.Request) {
56 if s.ops == nil {
57 http.NotFound(w, r)
58 return
59 }
60 s.ops(w)
61 })
62 return mux
63}
64
65func agent401(w http.ResponseWriter) {
66 w.Header().Set("WWW-Authenticate", `Bearer realm="oficina"`)
67 w.Header().Set("Cache-Control", "no-store")
68 w.Header().Set("Content-Type", "application/json")
69 w.WriteHeader(401)
70 _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated","message":"x"}}`))
71}
72
73// respond answers status with headers and body.
74func respond(status int, headers map[string]string, body string) func(w http.ResponseWriter) {
75 return func(w http.ResponseWriter) {
76 for k, v := range headers {
77 w.Header().Set(k, v)
78 }
79 w.WriteHeader(status)
80 _, _ = w.Write([]byte(body))
81 }
82}
83
84// agent200 is a 200 in agent-access's headers, with body.
85func agent200(body string) func(w http.ResponseWriter) {
86 return respond(200, map[string]string{"Cache-Control": "no-store", "Content-Type": "application/json"}, body)
87}
88
89// agent401Body is a 401 in agent-access's headers, with body. A
90// WWW-Authenticate already set is kept, as agent-access keeps it.
91func agent401Body(body string) func(w http.ResponseWriter) {
92 return func(w http.ResponseWriter) {
93 if w.Header().Get("WWW-Authenticate") == "" {
94 w.Header().Set("WWW-Authenticate", "Bearer")
95 }
96 respond(401, map[string]string{"Cache-Control": "no-store", "Content-Type": "application/json"}, body)(w)
97 }
98}
99
100func probeOf(t *testing.T, s *site) Delivery {
101 t.Helper()
102 srv := httptest.NewServer(s.handler())
103 defer srv.Close()
104 d, err := Probe(context.Background(), srv.Client(), srv.URL)
105 if err != nil {
106 t.Fatalf("Probe: %v", err)
107 }
108 return d
109}
110
111func TestOperationsShapeDistinguishesAppMiddleware(t *testing.T) {
112 cases := map[string]struct {
113 ops func(w http.ResponseWriter)
114 want OpsShape
115 }{
116 "absent": {nil, "absent"},
117 "app-401": {func(w http.ResponseWriter) {
118 w.WriteHeader(401)
119 _, _ = w.Write([]byte(`{"error":"unauthorized"}`))
120 }, "app-401"},
121 "app-401-with-bearer-but-string-error": {func(w http.ResponseWriter) {
122 w.Header().Set("WWW-Authenticate", "Bearer")
123 w.Header().Set("Cache-Control", "no-store")
124 w.WriteHeader(401)
125 _, _ = w.Write([]byte(`{"error":"unauthorized"}`))
126 }, "app-401"},
127 "agent-401": {agent401, "agent-401"},
128 "agent-401-cache-missing": {func(w http.ResponseWriter) {
129 w.Header().Set("WWW-Authenticate", "Bearer")
130 w.WriteHeader(401)
131 _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated"}}`))
132 }, "app-401"},
133 "agent-401-wrong-scheme": {func(w http.ResponseWriter) {
134 w.Header().Set("WWW-Authenticate", "Basic")
135 w.Header().Set("Cache-Control", "no-store")
136 w.WriteHeader(401)
137 _, _ = w.Write([]byte(`{"error":{"code":"unauthenticated"}}`))
138 }, "app-401"},
139 "agent-401-wrong-code": {func(w http.ResponseWriter) {
140 w.Header().Set("WWW-Authenticate", "Bearer")
141 w.Header().Set("Cache-Control", "no-store")
142 w.WriteHeader(401)
143 _, _ = w.Write([]byte(`{"error":{"code":"other"}}`))
144 }, "app-401"},
145 "agent-200": {agent200(`{"operations":[]}` + "\n"), "agent-200"},
146 "agent-200-listed": {agent200(`{"operations":[{"name":"docs_read"}]}`), "agent-200"},
147 "other": {func(w http.ResponseWriter) { w.WriteHeader(500) }, "other"},
148 }
149 // Lookalike 200s: only agent-access's own list, in its own headers,
150 // counts.
151 for name, ops := range map[string]func(w http.ResponseWriter){
152 "200-empty-object": agent200(`{}`),
153 "200-html": respond(200, map[string]string{"Cache-Control": "no-store", "Content-Type": "text/html"}, `<!doctype html><p>app`),
154 "200-no-store-missing": respond(200, map[string]string{"Content-Type": "application/json"}, `{"operations":[]}`),
155 "200-json-missing": respond(200, map[string]string{"Cache-Control": "no-store"}, `{"operations":[]}`),
156 "200-null-list": agent200(`{"operations":null}`),
157 "200-object-list": agent200(`{"operations":{}}`),
158 "200-extra-key": agent200(`{"operations":[],"user":"x"}`),
159 "200-key-case": agent200(`{"Operations":[]}`),
160 "200-trailing": agent200(`{"operations":[]} {}`),
161 "200-bare-array": agent200(`[]`),
162 } {
163 cases[name] = struct {
164 ops func(w http.ResponseWriter)
165 want OpsShape
166 }{ops, "other"}
167 }
168 // Lookalike 401s: a Bearer challenge with no-store is not enough.
169 for name, ops := range map[string]func(w http.ResponseWriter){
170 "401-message-missing": agent401Body(`{"error":{"code":"unauthenticated"}}`),
171 "401-message-empty": agent401Body(`{"error":{"code":"unauthenticated","message":""}}`),
172 "401-extra-error-key": agent401Body(`{"error":{"code":"unauthenticated","message":"x","detail":"y"}}`),
173 "401-extra-top-key": agent401Body(`{"error":{"code":"unauthenticated","message":"x"},"login":"/signin"}`),
174 "401-key-case": agent401Body(`{"Error":{"Code":"unauthenticated","Message":"x"}}`),
175 "401-code-not-string": agent401Body(`{"error":{"code":401,"message":"x"}}`),
176 "401-other-code": agent401Body(`{"error":{"code":"forbidden","message":"x"}}`),
177 "401-trailing": agent401Body(`{"error":{"code":"unauthenticated","message":"x"}}x`),
178 "401-json-missing": respond(401, map[string]string{"WWW-Authenticate": "Bearer", "Cache-Control": "no-store"},
179 `{"error":{"code":"unauthenticated","message":"x"}}`),
180 "401-not-bearer-scheme": respond(401, map[string]string{"WWW-Authenticate": "Bearerish", "Cache-Control": "no-store", "Content-Type": "application/json"},
181 `{"error":{"code":"unauthenticated","message":"x"}}`),
182 "401-two-challenges": func(w http.ResponseWriter) {
183 w.Header().Add("WWW-Authenticate", "Bearer")
184 w.Header().Add("WWW-Authenticate", "Basic")
185 agent401Body(`{"error":{"code":"unauthenticated","message":"x"}}`)(w)
186 },
187 } {
188 cases[name] = struct {
189 ops func(w http.ResponseWriter)
190 want OpsShape
191 }{ops, "app-401"}
192 }
193 // agent-access's own variants of its challenge still count.
194 cases["agent-401-resource-metadata"] = struct {
195 ops func(w http.ResponseWriter)
196 want OpsShape
197 }{respond(401, map[string]string{"WWW-Authenticate": `Bearer resource_metadata="https://x.example/.well-known/oauth-protected-resource"`,
198 "Cache-Control": "no-store", "Content-Type": "application/json; charset=utf-8"}, `{"error":{"code":"unauthenticated","message":"Connect to Oficina first."}}`+"\n"), "agent-401"}
199 for name, c := range cases {
200 t.Run(name, func(t *testing.T) {
201 d := probeOf(t, &site{version: "v1", header: "v1", health: 200, ops: c.ops})
202 if d.Ops != c.want {
203 t.Fatalf("ops = %q, want %q", d.Ops, c.want)
204 }
205 })
206 }
207}
208
209func TestProbeRecordsVersionHeaderHealth(t *testing.T) {
210 d := probeOf(t, &site{version: "v1.2", header: "rel-9", health: 200})
211 if d.Version != "v1.2" || d.Header != "rel-9" || d.Health != 200 || d.Redirected || d.At.IsZero() {
212 t.Fatalf("delivery = %+v", d)
213 }
214}
215
216func TestProbeRefusesRedirect(t *testing.T) {
217 s := &site{version: "v1", header: "v1", health: 200, redirectVersion: true}
218 srv := httptest.NewServer(s.handler())
219 defer srv.Close()
220 d, err := Probe(context.Background(), srv.Client(), srv.URL)
221 if err != nil {
222 t.Fatalf("Probe: %v", err)
223 }
224 if !d.Redirected || d.Version != "" {
225 t.Fatalf("a redirect must be recorded, not followed: %+v", d)
226 }
227 before := Delivery{Version: "v1", Header: "v1", Health: 200, Ops: "absent"}
228 now := Delivery{Version: "v1", Header: "v1", Health: 200, Ops: "agent-401", Redirected: true}
229 if err := Delivered(appNamedStatic("docs"), before, now); err == nil {
230 t.Fatal("Delivered accepted a redirect")
231 }
232}
233
234func TestProbeRefusesNonLoopbackHTTP(t *testing.T) {
235 if _, err := Probe(context.Background(), http.DefaultClient, "http://example.com"); err == nil {
236 t.Fatal("plain http to a non-loopback origin was accepted")
237 }
238}
239
240func TestProbeErrorsCarryNoBody(t *testing.T) {
241 // The answer promises more bytes than it sends, so the body read fails
242 // after recognisable content has arrived.
243 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
244 w.Header().Set("Content-Length", "1000")
245 _, _ = w.Write([]byte("LEAKY-BODY-CONTENT"))
246 }))
247 defer srv.Close()
248 _, err := Probe(context.Background(), srv.Client(), srv.URL)
249 if err == nil {
250 t.Fatal("expected a body read failure")
251 }
252 for _, leak := range []string{"LEAKY-BODY-CONTENT", srv.URL, strings.TrimPrefix(srv.URL, "http://")} {
253 if strings.Contains(err.Error(), leak) {
254 t.Fatalf("error leaks %q: %v", leak, err)
255 }
256 }
257}
258
259func TestProbeKeepsBodyExactly(t *testing.T) {
260 s := &site{version: "v1\n", header: "v1", health: 200}
261 a := probeOf(t, s)
262 s.version = "v1"
263 b := probeOf(t, s)
264 if a.Version == b.Version {
265 t.Fatal("a whitespace-only change was hidden")
266 }
267 before := Delivery{Version: a.Version, Header: "v1", Health: 200, Ops: "absent"}
268 now := Delivery{Version: b.Version, Header: "v1", Health: 200, Ops: "agent-401"}
269 if err := Delivered(appNamedStatic("docs"), before, now); err == nil {
270 t.Fatal("Delivered approved a whitespace-only change")
271 }
272}
273
274func TestProbeRejectsOversizedBodies(t *testing.T) {
275 prefix := strings.Repeat("a", bodyLimit)
276 for _, tail := range []string{"x", "y"} {
277 body := prefix + tail
278 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(body)) }))
279 _, err := Probe(context.Background(), srv.Client(), srv.URL)
280 srv.Close()
281 if err == nil {
282 t.Fatalf("oversized body (%s) accepted", tail)
283 }
284 }
285 // Exactly the limit is fine.
286 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(prefix)) }))
287 defer srv.Close()
288 if _, err := Probe(context.Background(), srv.Client(), srv.URL); err != nil {
289 t.Fatalf("a body of exactly the limit refused: %v", err)
290 }
291}
292
293func dl(v, h string, health int, ops OpsShape) Delivery {
294 return Delivery{Version: v, Header: h, Health: health, Ops: ops}
295}
296
297func TestDeliveredRefusesVersionOrHeaderChange(t *testing.T) {
298 before := dl("v1", "v1", 200, "absent")
299 docs := appNamedStatic("docs")
300 if err := Delivered(docs, before, dl("v1", "v1", 200, "agent-401")); err != nil {
301 t.Fatalf("good delivery refused: %v", err)
302 }
303 if err := Delivered(docs, before, dl("v1", "v1", 200, "agent-200")); err != nil {
304 t.Fatalf("agent-200 refused: %v", err)
305 }
306 bad := map[string]Delivery{
307 "version": dl("v2", "v1", 200, "agent-401"),
308 "header": dl("v1", "v2", 200, "agent-401"),
309 "health": dl("v1", "v1", 503, "agent-401"),
310 "still-absent": dl("v1", "v1", 200, "absent"),
311 "still-app-401": dl("v1", "v1", 200, "app-401"),
312 "other": dl("v1", "v1", 200, "other"),
313 "redirect": {Version: "v1", Header: "v1", Health: 200, Ops: "agent-401", Redirected: true},
314 }
315 for n, now := range bad {
316 if err := Delivered(appNamedStatic("docs"), before, now); err == nil {
317 t.Errorf("%s: accepted", n)
318 }
319 }
320 // Before already agent-shaped: nothing was delivered by this run.
321 if err := Delivered(docs, dl("v1", "v1", 200, "agent-401"), dl("v1", "v1", 200, "agent-401")); err == nil {
322 t.Error("an already agent-shaped before was accepted")
323 }
324}
325
326// The operations door must move as the app's must (Paul, 2026-11-17): for
327// four apps a 404 to agent-access's challenge or list, for Slides, Calls
328// and Equipo their own 401 to agent-access's challenge, for Base its own
329// agent-shaped 401 held (approved 2026-11-23, docs/base-adoption.md), and nothing else.
330func TestDeliveredHoldsEachAppToItsTransition(t *testing.T) {
331 d := func(ops OpsShape) Delivery { return dl("v1", "v1", 200, ops) }
332 for _, a := range provision.Apps {
333 t.Run(a.Slug, func(t *testing.T) {
334 var good, bad [][2]OpsShape
335 switch a.Slug {
336 case "base":
337 good = [][2]OpsShape{{OpsAgent401, OpsAgent401}}
338 bad = [][2]OpsShape{{OpsAgent401, OpsAgent200}, {OpsAgent401, OpsOther}, {OpsAgent401, OpsApp401},
339 {OpsAgent401, OpsAbsent}, {OpsAbsent, OpsAgent401}, {OpsApp401, OpsAgent401}}
340 case "slides", "calls", "equipo":
341 good = [][2]OpsShape{{OpsApp401, OpsAgent401}}
342 bad = [][2]OpsShape{{OpsApp401, OpsAgent200}, {OpsApp401, OpsOther}, {OpsApp401, OpsApp401},
343 {OpsAbsent, OpsAgent401}, {OpsAbsent, OpsAgent200}}
344 default:
345 good = [][2]OpsShape{{OpsAbsent, OpsAgent401}, {OpsAbsent, OpsAgent200}}
346 bad = [][2]OpsShape{{OpsAbsent, OpsOther}, {OpsAbsent, OpsApp401}, {OpsAbsent, OpsAbsent},
347 {OpsApp401, OpsAgent401}, {OpsApp401, OpsAgent200}}
348 }
349 for _, before := range []OpsShape{OpsOther, OpsAgent200, OpsAgent401, ""} {
350 if before != BaselineOps(a) {
351 bad = append(bad, [2]OpsShape{before, OpsAgent401})
352 }
353 }
354 for _, c := range good {
355 if err := Delivered(a, d(c[0]), d(c[1])); err != nil {
356 t.Errorf("%s -> %s refused: %v", c[0], c[1], err)
357 }
358 }
359 for _, c := range bad {
360 if err := Delivered(a, d(c[0]), d(c[1])); err == nil {
361 t.Errorf("%q -> %q accepted", c[0], c[1])
362 }
363 }
364 })
365 }
366}
367
368func TestBaselineOps(t *testing.T) {
369 for _, a := range provision.Apps {
370 want := OpsAbsent
371 switch a.Slug {
372 case "slides", "calls", "equipo":
373 want = OpsApp401
374 case "base":
375 want = OpsAgent401
376 }
377 if got := BaselineOps(a); got != want {
378 t.Fatalf("%s: %q, want %q", a.Slug, got, want)
379 }
380 }
381}
382
383func TestRevertedRequiresBeforeShape(t *testing.T) {
384 before := dl("v1", "v1", 200, "app-401")
385 if err := Reverted(before, dl("v1", "v1", 200, "app-401")); err != nil {
386 t.Fatalf("good revert refused: %v", err)
387 }
388 bad := map[string]Delivery{
389 "still-agent": dl("v1", "v1", 200, "agent-401"),
390 "version": dl("v2", "v1", 200, "app-401"),
391 "header": dl("v1", "v2", 200, "app-401"),
392 "health": dl("v1", "v1", 503, "app-401"),
393 "other-shape": dl("v1", "v1", 200, "absent"),
394 }
395 for n, now := range bad {
396 if err := Reverted(before, now); err == nil {
397 t.Errorf("%s: accepted", n)
398 }
399 }
400}
401