package plan3test import ( "context" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "net/http/httptest" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runnerproto" ) func TestPersonAPIAuthAudiences(t *testing.T) { f, x, principal, request, _ := nativeConversationFixture(t) token := func(b byte) string { return base64.RawURLEncoding.EncodeToString([]byte(strings.Repeat(string(b), 32))) } runner, cleanup, coordinator := token('r'), token('c'), token('o') hash := func(aud, token string) string { sum := sha256.Sum256([]byte(aud + "\x00" + token)) return hex.EncodeToString(sum[:]) } f.exec(t, "UPDATE runner_credentials SET token_hash=?,expires_at=? WHERE id='fixture-credential'", hash(runnerproto.RunnerAudience, runner), time.Now().Add(time.Hour)) f.exec(t, `INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) SELECT 'coordinator-credential',runner_id,instance_id,audience,person,machine_key_hash,?,expires_at FROM runner_credentials WHERE id='fixture-credential'`, hash(runnerproto.RunnerAudience, coordinator)) f.exec(t, "UPDATE runner_cleanups SET token_hash=? WHERE assignment_id=?", hash(runnerproto.CleanupAudience, cleanup), request.AssignmentID) type claims struct{ Instance, Audience, Address string } sign := func(c claims) string { payload := base64.RawURLEncoding.EncodeToString([]byte(jsonBody(t, c))) mac := hmac.New(sha256.New, []byte("deterministic-person-test-key")) mac.Write([]byte(payload)) return payload + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) } native := sign(claims{f.TeamID, "person", owner.Address}) foreign := sign(claims{"other-instance", "person", owner.Address}) reason := "" verifier := func(_ context.Context, token string) (personapi.PersonPrincipal, error) { deny := func(why string) (personapi.PersonPrincipal, error) { reason = why return personapi.PersonPrincipal{}, fmt.Errorf("fixture: %s", why) } for _, c := range []struct{ table, aud, why string }{{"runner_credentials", runnerproto.RunnerAudience, "runner_audience"}, {"runner_cleanups", runnerproto.CleanupAudience, "cleanup_audience"}} { if f.count(t, "SELECT count(*) FROM "+c.table+" WHERE token_hash=?", hash(c.aud, token)) > 0 { return deny(c.why) } } parts := strings.Split(token, ".") if len(parts) != 2 { return deny("invalid_token") } mac := hmac.New(sha256.New, []byte("deterministic-person-test-key")) mac.Write([]byte(parts[0])) sig, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil || !hmac.Equal(sig, mac.Sum(nil)) { return deny("invalid_signature") } raw, err := base64.RawURLEncoding.DecodeString(parts[0]) if err != nil { return deny("invalid_token") } var c claims if json.Unmarshal(raw, &c) != nil { return deny("invalid_token") } if c.Audience != "person" { return deny("wrong_audience") } if c.Instance != f.TeamID { return deny("other_instance") } reason = "accepted" return personapi.PersonPrincipal{Address: c.Address, CredentialID: "test-device", SessionEpoch: time.Now().Unix()}, nil } apiRouter(t, f, verifier) do := func(method, path, auth, body string, cookie bool) *httptest.ResponseRecorder { r := httptest.NewRequest(method, path, strings.NewReader(body)) r.Header.Set("Authorization", auth) r.Header.Set("Content-Type", "application/json") if cookie { r.AddCookie(f.Cookies[owner.Address]) r.Header.Set("Origin", origin) } w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) return w } // Prove each protocol credential is valid on its own production lane. expectHTTP(t, do("POST", "/api/runner/v2/heartbeat", "Bearer "+runner, `{"version":2,"request_id":"heartbeat"}`, false), 200) request.RequestID = "audience-intent" request.Intent = &team.IntentSpec{Key: "audience-turn", Operation: team.OpProviderCall, Payload: []byte(`{"task":"research"}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}} action, err := x.Mutate(ctx, principal, "intend", request) must(t, err) request.ActionID = action.(team.ActionID) request.Intent = nil request.RequestID = "audience-observation" request.Receipt = &team.Receipt{ID: "audience-receipt", Outcome: "success"} wire, err := runnerproto.Marshal(request) must(t, err) expectHTTP(t, do("POST", "/api/runner/v2/receipts", "Bearer "+runner, string(wire), false), 200) request.RequestID = "audience-cleanup" wire, err = runnerproto.Marshal(request) must(t, err) expectHTTP(t, do("POST", "/api/runner/v2/receipts", "Cleanup "+cleanup, string(wire), false), 200) expectHTTP(t, do("GET", "/api/v1/me", "Bearer "+native, "", false), 200) for _, tc := range []struct{ name, token, reason string }{{"runner", runner, "runner_audience"}, {"cleanup", cleanup, "cleanup_audience"}, {"coordinator", coordinator, "runner_audience"}, {"other-instance", foreign, "other_instance"}, {"invalid", "invalid", "invalid_token"}} { t.Run(tc.name, func(t *testing.T) { reason = "" w := do("GET", "/api/v1/me", "Bearer "+tc.token, "", false) expectHTTP(t, w, 401) if reason != tc.reason { t.Fatalf("rejection reason %q, want %q", reason, tc.reason) } if !strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") { t.Fatal("auth returned HTML") } }) } expectHTTP(t, do("GET", "/api/v1/me", "Bearer "+native, "", true), 401) expectHTTP(t, apiRequest(t, f, equipo.Actor{}, "GET", "/api/v1/me", "", "", ""), 401) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"x","person":"peer@example.com"}`, "forged", ""), 422) f.exec(t, "DELETE FROM sessions WHERE subject=?", owner.Address) expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/me", "", "", ""), 401) }