| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/hmac" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "fmt" |
| 11 | "net/http/httptest" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/equipo" |
| 17 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 18 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 19 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 20 | ) |
| 21 | |
| 22 | func TestPersonAPIAuthAudiences(t *testing.T) { |
| 23 | f, x, principal, request, _ := nativeConversationFixture(t) |
| 24 | token := func(b byte) string { |
| 25 | return base64.RawURLEncoding.EncodeToString([]byte(strings.Repeat(string(b), 32))) |
| 26 | } |
| 27 | runner, cleanup, coordinator := token('r'), token('c'), token('o') |
| 28 | hash := func(aud, token string) string { |
| 29 | sum := sha256.Sum256([]byte(aud + "\x00" + token)) |
| 30 | return hex.EncodeToString(sum[:]) |
| 31 | } |
| 32 | f.exec(t, "UPDATE runner_credentials SET token_hash=?,expires_at=? WHERE id='fixture-credential'", hash(runnerproto.RunnerAudience, runner), time.Now().Add(time.Hour)) |
| 33 | f.exec(t, `INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) |
| 34 | 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)) |
| 35 | f.exec(t, "UPDATE runner_cleanups SET token_hash=? WHERE assignment_id=?", hash(runnerproto.CleanupAudience, cleanup), request.AssignmentID) |
| 36 | type claims struct{ Instance, Audience, Address string } |
| 37 | sign := func(c claims) string { |
| 38 | payload := base64.RawURLEncoding.EncodeToString([]byte(jsonBody(t, c))) |
| 39 | mac := hmac.New(sha256.New, []byte("deterministic-person-test-key")) |
| 40 | mac.Write([]byte(payload)) |
| 41 | return payload + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) |
| 42 | } |
| 43 | native := sign(claims{f.TeamID, "person", owner.Address}) |
| 44 | foreign := sign(claims{"other-instance", "person", owner.Address}) |
| 45 | reason := "" |
| 46 | verifier := func(_ context.Context, token string) (personapi.PersonPrincipal, error) { |
| 47 | deny := func(why string) (personapi.PersonPrincipal, error) { |
| 48 | reason = why |
| 49 | return personapi.PersonPrincipal{}, fmt.Errorf("fixture: %s", why) |
| 50 | } |
| 51 | for _, c := range []struct{ table, aud, why string }{{"runner_credentials", runnerproto.RunnerAudience, "runner_audience"}, {"runner_cleanups", runnerproto.CleanupAudience, "cleanup_audience"}} { |
| 52 | if f.count(t, "SELECT count(*) FROM "+c.table+" WHERE token_hash=?", hash(c.aud, token)) > 0 { |
| 53 | return deny(c.why) |
| 54 | } |
| 55 | } |
| 56 | parts := strings.Split(token, ".") |
| 57 | if len(parts) != 2 { |
| 58 | return deny("invalid_token") |
| 59 | } |
| 60 | mac := hmac.New(sha256.New, []byte("deterministic-person-test-key")) |
| 61 | mac.Write([]byte(parts[0])) |
| 62 | sig, err := base64.RawURLEncoding.DecodeString(parts[1]) |
| 63 | if err != nil || !hmac.Equal(sig, mac.Sum(nil)) { |
| 64 | return deny("invalid_signature") |
| 65 | } |
| 66 | raw, err := base64.RawURLEncoding.DecodeString(parts[0]) |
| 67 | if err != nil { |
| 68 | return deny("invalid_token") |
| 69 | } |
| 70 | var c claims |
| 71 | if json.Unmarshal(raw, &c) != nil { |
| 72 | return deny("invalid_token") |
| 73 | } |
| 74 | if c.Audience != "person" { |
| 75 | return deny("wrong_audience") |
| 76 | } |
| 77 | if c.Instance != f.TeamID { |
| 78 | return deny("other_instance") |
| 79 | } |
| 80 | reason = "accepted" |
| 81 | return personapi.PersonPrincipal{Address: c.Address, CredentialID: "test-device", SessionEpoch: time.Now().Unix()}, nil |
| 82 | } |
| 83 | apiRouter(t, f, verifier) |
| 84 | do := func(method, path, auth, body string, cookie bool) *httptest.ResponseRecorder { |
| 85 | r := httptest.NewRequest(method, path, strings.NewReader(body)) |
| 86 | r.Header.Set("Authorization", auth) |
| 87 | r.Header.Set("Content-Type", "application/json") |
| 88 | if cookie { |
| 89 | r.AddCookie(f.Cookies[owner.Address]) |
| 90 | r.Header.Set("Origin", origin) |
| 91 | } |
| 92 | w := httptest.NewRecorder() |
| 93 | f.Handler.ServeHTTP(w, r) |
| 94 | return w |
| 95 | } |
| 96 | // Prove each protocol credential is valid on its own production lane. |
| 97 | expectHTTP(t, do("POST", "/api/runner/v2/heartbeat", "Bearer "+runner, `{"version":2,"request_id":"heartbeat"}`, false), 200) |
| 98 | request.RequestID = "audience-intent" |
| 99 | request.Intent = &team.IntentSpec{Key: "audience-turn", Operation: team.OpProviderCall, Payload: []byte(`{"task":"research"}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}} |
| 100 | action, err := x.Mutate(ctx, principal, "intend", request) |
| 101 | must(t, err) |
| 102 | request.ActionID = action.(team.ActionID) |
| 103 | request.Intent = nil |
| 104 | request.RequestID = "audience-observation" |
| 105 | request.Receipt = &team.Receipt{ID: "audience-receipt", Outcome: "success"} |
| 106 | wire, err := runnerproto.Marshal(request) |
| 107 | must(t, err) |
| 108 | expectHTTP(t, do("POST", "/api/runner/v2/receipts", "Bearer "+runner, string(wire), false), 200) |
| 109 | request.RequestID = "audience-cleanup" |
| 110 | wire, err = runnerproto.Marshal(request) |
| 111 | must(t, err) |
| 112 | expectHTTP(t, do("POST", "/api/runner/v2/receipts", "Cleanup "+cleanup, string(wire), false), 200) |
| 113 | expectHTTP(t, do("GET", "/api/v1/me", "Bearer "+native, "", false), 200) |
| 114 | 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"}} { |
| 115 | t.Run(tc.name, func(t *testing.T) { |
| 116 | reason = "" |
| 117 | w := do("GET", "/api/v1/me", "Bearer "+tc.token, "", false) |
| 118 | expectHTTP(t, w, 401) |
| 119 | if reason != tc.reason { |
| 120 | t.Fatalf("rejection reason %q, want %q", reason, tc.reason) |
| 121 | } |
| 122 | if !strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") { |
| 123 | t.Fatal("auth returned HTML") |
| 124 | } |
| 125 | }) |
| 126 | } |
| 127 | expectHTTP(t, do("GET", "/api/v1/me", "Bearer "+native, "", true), 401) |
| 128 | expectHTTP(t, apiRequest(t, f, equipo.Actor{}, "GET", "/api/v1/me", "", "", ""), 401) |
| 129 | expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"x","person":"peer@example.com"}`, "forged", ""), 422) |
| 130 | f.exec(t, "DELETE FROM sessions WHERE subject=?", owner.Address) |
| 131 | expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/me", "", "", ""), 401) |
| 132 | } |
| 133 | |