Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
test(inbox): walk every /api/inbox route for the owner gate (MUL-9595) (#10921)
Jiayuan Zhang482ea80f595c
diff --git a/server/cmd/server/inbox_owner_gate_routes_test.go b/server/cmd/server/inbox_owner_gate_routes_test.gonew file mode 100644index 0000000000..eee1ef1d56--- /dev/null+++ b/server/cmd/server/inbox_owner_gate_routes_test.go@@ -0,0 +1,189 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "regexp"+ "sort"+ "strings"+ "testing"++ "github.com/go-chi/chi/v5"+ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+)++// inboxRoutesWithoutOwnerGate lists the /api/inbox routes that may serve an+// agent the inbox owner gate (requireInboxOwnerAccess) would deny, keyed+// "METHOD pattern", each with the reason it is safe. Every other route must+// answer 403 to both machine credentials in+// TestEveryInboxRouteDeniesMachineCredentialsWithoutOwnerTrigger.+var inboxRoutesWithoutOwnerGate = map[string]string{}++// inboxRouteParams resolves each URL parameter an /api/inbox route declares to+// a row of the owner's fixture, so a missing gate reaches the owner's data+// instead of failing on a lookup.+var inboxRouteParams = map[string]func(inboxOwnerGateFixture) string{+ "id": func(f inboxOwnerGateFixture) string { return f.itemID },+ "issueId": func(f inboxOwnerGateFixture) string { return f.issueID },+}++var chiRouteParam = regexp.MustCompile(`\{([^}:]+)(:[^}]*)?\}`)++type inboxOwnerGateFixture struct {+ db *dbfx.Fixture+ issueID, itemID string+}++type inboxRoute struct{ method, pattern string }++func (r inboxRoute) key() string { return r.method + " " + r.pattern }++func walkInboxRoutes(t *testing.T, router chi.Routes) []inboxRoute {+ t.Helper()+ var routes []inboxRoute+ err := chi.Walk(router, func(method, pattern string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {+ if pattern == "/api/inbox" || strings.HasPrefix(pattern, "/api/inbox/") {+ routes = append(routes, inboxRoute{method, pattern})+ }+ return nil+ })+ if err != nil {+ t.Fatalf("walk router: %v", err)+ }+ if len(routes) == 0 {+ t.Fatal("router has no /api/inbox routes; the walk no longer reaches the inbox group")+ }+ sort.Slice(routes, func(i, j int) bool { return routes[i].key() < routes[j].key() })+ return routes+}++func (f inboxOwnerGateFixture) path(t *testing.T, pattern string) string {+ t.Helper()+ return chiRouteParam.ReplaceAllStringFunc(pattern, func(param string) string {+ name := chiRouteParam.FindStringSubmatch(param)[1]+ value, ok := inboxRouteParams[name]+ if !ok {+ t.Fatalf("%s declares {%s}; add a fixture value for it to inboxRouteParams", pattern, name)+ }+ return value(f)+ })+}++func (f inboxOwnerGateFixture) requireItemUntouched(t *testing.T) {+ t.Helper()+ if f.db.Count(t, `SELECT count(*) FROM inbox_item WHERE id = $1`, f.itemID) != 1 {+ t.Fatal("denied call deleted the owner's notification")+ }+ var read, archived, snoozed bool+ f.db.QueryRow(t, `SELECT read, archived, snoozed_until IS NOT NULL FROM inbox_item WHERE id = $1`, f.itemID).Scan(&read, &archived, &snoozed)+ if read || archived || snoozed {+ t.Fatalf("denied call changed the owner's notification: read=%v archived=%v snoozed=%v", read, archived, snoozed)+ }+}++func mintInboxTaskToken(t *testing.T, f *dbfx.Fixture, taskID, agentID string) string {+ t.Helper()+ token := "mat_" + uuid.NewString()+ f.InsertNoID(t, "task_token", dbfx.Cols{+ "token_hash": auth.HashToken(token), "task_id": taskID, "agent_id": agentID,+ "workspace_id": f.WorkspaceID, "user_id": f.UserID,+ "expires_at": dbfx.Raw("now() + interval '1 hour'"),+ }, "token_hash = $1", auth.HashToken(token))+ return token+}++// Each handler under /api/inbox calls the owner gate itself, so a new route+// that forgets it would let an agent act on its runtime owner's inbox for any+// human. This walks the real router, so a new route is covered the moment it+// is registered: an agent run another human triggered, and a cloud-node+// credential claiming an owner-triggered run, must both be refused.+func TestEveryInboxRouteDeniesMachineCredentialsWithoutOwnerTrigger(t *testing.T) {+ db := dbfx.New(testPool, testWorkspaceID, testUserID)+ db.WorkspaceID = db.Workspace(t, "Inbox owner gate routes", "inbox-gate-routes-"+uuid.NewString())+ db.Member(t, db.WorkspaceID, db.UserID, "owner")+ db.Cleanup(t, `DELETE FROM inbox_item WHERE workspace_id = $1`, db.WorkspaceID)+ other := db.User(t, "Inbox gate other human", "inbox-gate-other-"+uuid.NewString()+"@example.test")+ runtimeID := db.Runtime(t, "Inbox gate runtime")+ agentID := db.Agent(t, "Inbox gate agent", runtimeID)+ runningTask := func(originator string) string {+ return db.Task(t, agentID, dbfx.Cols{"runtime_id": runtimeID, "status": "running",+ "originator_user_id": originator, "accountable_user_id": originator})+ }+ f := inboxOwnerGateFixture{db: db, issueID: db.Issue(t, "Inbox gate issue")}+ ownerTaskID := runningTask(db.UserID)+ ownerTriggered := mintInboxTaskToken(t, db, ownerTaskID, agentID)+ otherTriggered := mintInboxTaskToken(t, db, runningTask(other), agentID)++ cloudToken := "mcn_" + uuid.NewString()+ fleet := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var request struct {+ Token string `json:"token"`+ }+ if json.NewDecoder(r.Body).Decode(&request) != nil || request.Token != cloudToken {+ http.Error(w, "unexpected verification request", http.StatusBadRequest)+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"valid": true, "owner_id": db.UserID})+ }))+ t.Cleanup(fleet.Close)+ t.Setenv("MULTICA_CLOUD_URL", fleet.URL)+ router, _ := NewRouterWithOptions(testPool, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil, RouterOptions{})++ call := func(method, path string, headers ...string) *httptest.ResponseRecorder {+ req := httptest.NewRequest(method, path, nil)+ req.Header.Set("X-Workspace-ID", db.WorkspaceID)+ for i := 0; i+1 < len(headers); i += 2 {+ req.Header.Set(headers[i], headers[i+1])+ }+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ return rec+ }+ credentials := []struct {+ name string+ headers []string+ }{+ {"agent run another human triggered", []string{"Authorization", "Bearer " + otherTriggered}},+ {"cloud node claiming an owner-triggered run", []string{"Authorization", "Bearer " + cloudToken,+ "X-Actor-Source", "task_token", "X-Task-ID", ownerTaskID, "X-Agent-ID", agentID}},+ }++ // Control: the same agent, workspace and runtime pass the gate when the+ // owner triggered the run, so a 403 below is the gate's answer and not a+ // broken fixture.+ if rec := call(http.MethodGet, "/api/inbox", "Authorization", "Bearer "+ownerTriggered); rec.Code != http.StatusOK {+ t.Fatalf("owner-triggered control: status %d, want 200: %s", rec.Code, rec.Body)+ }++ routes := walkInboxRoutes(t, router)+ walked := map[string]bool{}+ for _, route := range routes {+ walked[route.key()] = true+ if _, exempt := inboxRoutesWithoutOwnerGate[route.key()]; exempt {+ continue+ }+ t.Run(route.key(), func(t *testing.T) {+ f := f+ f.itemID = db.Insert(t, "inbox_item", dbfx.Cols{"workspace_id": db.WorkspaceID, "issue_id": f.issueID,+ "recipient_type": "member", "recipient_id": db.UserID, "type": "new_comment", "severity": "info", "title": "Owner notice"})+ path := f.path(t, route.pattern)+ for _, cred := range credentials {+ if rec := call(route.method, path, cred.headers...); rec.Code != http.StatusForbidden {+ t.Errorf("%s: status %d, want 403; does the handler call requireInboxOwnerAccess? %s", cred.name, rec.Code, rec.Body)+ }+ f.requireItemUntouched(t)+ }+ })+ }+ for key := range inboxRoutesWithoutOwnerGate {+ if !walked[key] {+ t.Errorf("inboxRoutesWithoutOwnerGate lists %q, which the router no longer registers", key)+ }+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex ce322d6b31..3b618cd36d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2708,7 +2708,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/{id}/reject", h.RejectAppRequest)})- // Inbox+ // Inbox. Every handler here calls requireInboxOwnerAccess;+ // TestEveryInboxRouteDeniesMachineCredentialsWithoutOwnerTrigger+ // walks these routes and fails on one that skips it.r.Route("/api/inbox", func(r chi.Router) {r.Get("/", h.ListInbox)// Archived notifications, for the inbox's "Archived" sub-view.diff --git a/server/internal/handler/inbox_access_test.go b/server/internal/handler/inbox_access_test.goindex af5f0372db..396695882c 100644--- a/server/internal/handler/inbox_access_test.go+++ b/server/internal/handler/inbox_access_test.go@@ -2,11 +2,9 @@ package handlerimport ("context"- "encoding/json""errors""fmt""net/http"- "net/http/httptest""strings""testing""time"@@ -45,8 +43,8 @@ var inboxOwnerReads = []inboxOwnerRead{{"archived facets", "/api/inbox/archived/facets", "ArchivedInboxFacets", (*Handler).GetArchivedInboxFacets},}-func (e inboxOwnerRead) serve(h *Handler, cloud *auth.CloudPATVerifier) http.HandlerFunc {- return middleware.Auth(testHandler.Queries, nil, cloud, nil)(+func (e inboxOwnerRead) serve(h *Handler) http.HandlerFunc {+ return middleware.Auth(testHandler.Queries, nil, nil, nil)(middleware.RequireWorkspaceMember(testHandler.Queries)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {e.handler(h, w, r)})),@@ -108,7 +106,7 @@ func TestListInboxAccessLookupErrors(t *testing.T) {faults := &inboxAccessFailureDB{DBTX: testPool, query: query, err: tc.err}h := *testHandlerh.Queries = db.New(faults)- response := testutil.Call(t, e.serve(&h, nil), e.request(token, testWorkspaceID)).Want(tc.status)+ response := testutil.Call(t, e.serve(&h), e.request(token, testWorkspaceID)).Want(tc.status)if tc.status == http.StatusServiceUnavailable && response.Header().Get("Retry-After") != "1" {t.Fatal("temporary access-lookup failure must supply Retry-After")}@@ -129,8 +127,8 @@ func TestListInboxAccessLookupErrors(t *testing.T) {}}-func inboxAccessHandler(cloud *auth.CloudPATVerifier) http.HandlerFunc {- return inboxOwnerReads[0].serve(testHandler, cloud)+func inboxAccessHandler() http.HandlerFunc {+ return inboxOwnerReads[0].serve(testHandler)}func inboxCredentialRequest(token, workspaceID string) *http.Request {@@ -184,7 +182,7 @@ func TestListInboxTaskCredentialAccess(t *testing.T) {token := inboxTaskCredential(t, taskID, agentID, testWorkspaceID, testUserID)for _, e := range inboxOwnerReads {t.Run(e.name, func(t *testing.T) {- testutil.Call(t, e.serve(testHandler, nil), e.request(token, testWorkspaceID)).Want(tc.want)+ testutil.Call(t, e.serve(testHandler), e.request(token, testWorkspaceID)).Want(tc.want)})}})@@ -206,27 +204,9 @@ func TestListInboxRejectsForgedTaskIdentityAndWorkspace(t *testing.T) {req := testutil.WithHeaders(e.request(token, testWorkspaceID), "X-Task-ID", allowedTask, "X-Agent-ID", agentID,"X-Actor-Source", "member", "X-User-ID", other, "X-Originator-User-ID", testUserID)req.URL.RawQuery = "originator_user_id=" + testUserID + "&recipient_id=" + other- testutil.Call(t, e.serve(testHandler, nil), req).Want(http.StatusForbidden)+ testutil.Call(t, e.serve(testHandler), req).Want(http.StatusForbidden)- testutil.Call(t, e.serve(testHandler, nil), e.request(allowedToken, foreignWorkspace)).Want(http.StatusForbidden)- })- }-}--func TestListInboxCloudPATCannotBorrowTaskIdentity(t *testing.T) {- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- _ = json.NewEncoder(w).Encode(map[string]any{"valid": true, "owner_id": testUserID})- }))- defer srv.Close()- verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})- runtimeID := dbfx.Runtime(t, "Cloud inbox runtime")- agentID := dbfx.Agent(t, "Cloud inbox agent", runtimeID)- taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "running", "originator_user_id": testUserID, "accountable_user_id": testUserID})- for _, e := range inboxOwnerReads {- t.Run(e.name, func(t *testing.T) {- req := testutil.WithHeaders(e.request("mcn_inbox-test", testWorkspaceID),- "X-Actor-Source", "task_token", "X-Task-ID", taskID, "X-Agent-ID", agentID)- testutil.Call(t, e.serve(testHandler, verifier), req).Want(http.StatusForbidden)+ testutil.Call(t, e.serve(testHandler), e.request(allowedToken, foreignWorkspace)).Want(http.StatusForbidden)})}}@@ -267,7 +247,7 @@ func TestListInboxHumanCredentialsAndReadOnlyIsolation(t *testing.T) {req.Header.Set("X-User-ID", other)req.URL.RawQuery = "recipient_id=" + othervar items []InboxItemResponse- testutil.Call(t, inboxAccessHandler(nil), req).Want(http.StatusOK).JSON(&items)+ testutil.Call(t, inboxAccessHandler(), req).Want(http.StatusOK).JSON(&items)found := falsefor _, item := range items {if item.ID == otherItem || item.ID == foreign {@@ -311,7 +291,7 @@ func TestListInboxDelegatedOriginatorAndProjectVisibility(t *testing.T) {secret := insertSecretInboxItem(t, f, testUserID)list := func() map[string]bool {var items []InboxItemResponse- testutil.Call(t, inboxAccessHandler(nil), inboxCredentialRequest(token, testWorkspaceID)).Want(http.StatusOK).JSON(&items)+ testutil.Call(t, inboxAccessHandler(), inboxCredentialRequest(token, testWorkspaceID)).Want(http.StatusOK).JSON(&items)ids := map[string]bool{}for _, item := range items {ids[item.ID] = true@@ -330,7 +310,7 @@ func TestListInboxDelegatedOriginatorAndProjectVisibility(t *testing.T) {}// Loss of an upstream human must never borrow the accountable owner.dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=NULL,accountable_user_id=$2 WHERE id=$1`, taskID, testUserID)- testutil.Call(t, inboxAccessHandler(nil), inboxCredentialRequest(token, testWorkspaceID)).Want(http.StatusForbidden)+ testutil.Call(t, inboxAccessHandler(), inboxCredentialRequest(token, testWorkspaceID)).Want(http.StatusForbidden)var counterAfter int64dbfx.QueryRow(t, `SELECT issue_counter FROM workspace WHERE id=$1`, testWorkspaceID).Scan(&counterAfter)@@ -361,12 +341,12 @@ func TestArchivedInboxOwnerReadIsolation(t *testing.T) {reads := map[string]func(*testing.T, *http.Request) []InboxItemResponse{"archived": func(t *testing.T, req *http.Request) []InboxItemResponse {var items []InboxItemResponse- testutil.Call(t, inboxOwnerReads[1].serve(testHandler, nil), req).Want(http.StatusOK).JSON(&items)+ testutil.Call(t, inboxOwnerReads[1].serve(testHandler), req).Want(http.StatusOK).JSON(&items)return items},"archived page": func(t *testing.T, req *http.Request) []InboxItemResponse {var page archivedInboxPageResponse- testutil.Call(t, inboxOwnerReads[2].serve(testHandler, nil), req).Want(http.StatusOK).JSON(&page)+ testutil.Call(t, inboxOwnerReads[2].serve(testHandler), req).Want(http.StatusOK).JSON(&page)return page.Items},}diff --git a/server/internal/handler/inbox_write_access_test.go b/server/internal/handler/inbox_write_access_test.goindex 884cefc0c2..d85bb90015 100644--- a/server/internal/handler/inbox_write_access_test.go+++ b/server/internal/handler/inbox_write_access_test.go@@ -1,9 +1,7 @@package handlerimport (- "encoding/json""net/http"- "net/http/httptest""testing""time"@@ -15,7 +13,10 @@ import (// Every inbox endpoint beyond the list reads, writes included, shares the// list's owner gate: an agent acts on the runtime owner's inbox only when that-// owner triggered the task, and cloud-node credentials never do.+// owner triggered the task. This table drives the credential matrix and the+// allowed path; TestEveryInboxRouteDeniesMachineCredentialsWithoutOwnerTrigger+// (cmd/server) walks the router so every /api/inbox route, new ones included,+// denies the other human's run and cloud-node credentials.type inboxOwnerEndpoint struct {name, method string// path receives the inbox item and its issue; param names the chi URL@@ -81,21 +82,21 @@ func (f inboxWriteFixture) taskToken(t *testing.T, originator any) string {return inboxTaskCredential(t, taskID, f.agentID, f.workspaceID, testUserID)}-func serveInboxEndpoint(handler func(*Handler, http.ResponseWriter, *http.Request), cloud *auth.CloudPATVerifier) http.HandlerFunc {- return middleware.Auth(testHandler.Queries, nil, cloud, nil)(+func serveInboxEndpoint(handler func(*Handler, http.ResponseWriter, *http.Request)) http.HandlerFunc {+ return middleware.Auth(testHandler.Queries, nil, nil, nil)(middleware.RequireWorkspaceMember(testHandler.Queries)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {handler(testHandler, w, r)})),).ServeHTTP}-func (e inboxOwnerEndpoint) request(f inboxWriteFixture, item, token string, headers ...string) *http.Request {+func (e inboxOwnerEndpoint) request(f inboxWriteFixture, item, token string) *http.Request {var body anyif e.body != nil {body = e.body}req := testutil.WithHeaders(testutil.JSONRequest(e.method, e.path(item, f.issueID), body),- append([]string{"Authorization", "Bearer " + token, "X-Workspace-ID", f.workspaceID}, headers...)...)+ "Authorization", "Bearer "+token, "X-Workspace-ID", f.workspaceID)switch e.param {case "id":req = withURLParam(req, "id", item)@@ -128,13 +129,13 @@ func TestInboxEndpointsShareOwnerGate(t *testing.T) {for name, token := range map[string]string{"another human": foreignTriggered, "unattributed": unattributed} {t.Run(name, func(t *testing.T) {item := f.item(t)- testutil.Call(t, serveInboxEndpoint(e.handler, nil), e.request(f, item, token)).Want(http.StatusForbidden)+ testutil.Call(t, serveInboxEndpoint(e.handler), e.request(f, item, token)).Want(http.StatusForbidden)requireInboxItemUntouched(t, item)})}item := f.item(t)- testutil.Call(t, serveInboxEndpoint(e.handler, nil), e.request(f, item, allowed)).Want(http.StatusOK)+ testutil.Call(t, serveInboxEndpoint(e.handler), e.request(f, item, allowed)).Want(http.StatusOK)if changed := loadInboxItemState(t, item) != (inboxItemState{}); changed != e.changes {t.Fatalf("self-triggered call changed=%v, want %v", changed, e.changes)}@@ -142,25 +143,6 @@ func TestInboxEndpointsShareOwnerGate(t *testing.T) {}}-func TestInboxEndpointsRejectCloudPAT(t *testing.T) {- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- _ = json.NewEncoder(w).Encode(map[string]any{"valid": true, "owner_id": testUserID})- }))- defer srv.Close()- verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})- f := newInboxWriteFixture(t)- taskID := dbfx.Task(t, f.agentID, testutil.Cols{"runtime_id": f.runtimeID, "status": "running",- "originator_user_id": testUserID, "accountable_user_id": testUserID})- for _, e := range inboxOwnerEndpoints {- t.Run(e.name, func(t *testing.T) {- item := f.item(t)- req := e.request(f, item, "mcn_inbox-write-test", "X-Actor-Source", "task_token", "X-Task-ID", taskID, "X-Agent-ID", f.agentID)- testutil.Call(t, serveInboxEndpoint(e.handler, verifier), req).Want(http.StatusForbidden)- requireInboxItemUntouched(t, item)- })- }-}-// Per-item writes report how many notifications they actually changed, the// issue group included, so repeating one reports 0.func TestInboxItemWritesReportChangedCount(t *testing.T) {@@ -196,7 +178,7 @@ func TestInboxItemWritesReportChangedCount(t *testing.T) {ID string `json:"id"`Count *int64 `json:"count"`}- testutil.Call(t, serveInboxEndpoint(e.handler, nil), e.request(f, step.item, token)).Want(http.StatusOK).JSON(&resp)+ testutil.Call(t, serveInboxEndpoint(e.handler), e.request(f, step.item, token)).Want(http.StatusOK).JSON(&resp)if resp.ID != step.item || resp.Count == nil || *resp.Count != step.want {t.Fatalf("%s %s: id=%s count=%v, want %d", step.action, step.item, resp.ID, resp.Count, step.want)}@@ -208,12 +190,12 @@ func TestDeleteInboxItemIsHumanOnly(t *testing.T) {endpoint := inboxOwnerEndpoint{method: http.MethodDelete, path: func(item, _ string) string { return "/api/inbox/" + item }, param: "id"}item := f.item(t)- testutil.Call(t, serveInboxEndpoint((*Handler).DeleteInboxItem, nil), endpoint.request(f, item, f.taskToken(t, testUserID))).Want(http.StatusForbidden)+ testutil.Call(t, serveInboxEndpoint((*Handler).DeleteInboxItem), endpoint.request(f, item, f.taskToken(t, testUserID))).Want(http.StatusForbidden)requireInboxItemUntouched(t, item)pat := "mul_" + uuid.NewString()dbfx.Insert(t, "personal_access_token", testutil.Cols{"user_id": testUserID, "name": "Inbox delete test", "token_hash": auth.HashToken(pat), "token_prefix": pat[:12]})- testutil.Call(t, serveInboxEndpoint((*Handler).DeleteInboxItem, nil), endpoint.request(f, item, pat)).Want(http.StatusOK)+ testutil.Call(t, serveInboxEndpoint((*Handler).DeleteInboxItem), endpoint.request(f, item, pat)).Want(http.StatusOK)var remaining intdbfx.QueryRow(t, `SELECT count(*) FROM inbox_item WHERE id = $1`, item).Scan(&remaining)if remaining != 0 {