Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8138: fix(auth): reject task-token requests targeting another workspace (#9422)

Multica Evee9b8868e816f
diff --git a/server/cmd/server/source_context_actor_integration_test.go b/server/cmd/server/source_context_actor_integration_test.go
index ecca42c5de..ef693ac9c8 100644
--- a/server/cmd/server/source_context_actor_integration_test.go
+++ b/server/cmd/server/source_context_actor_integration_test.go
@@ -59,10 +59,12 @@ func TestSourceContextRoutesRejectAuthoritativeTaskToken(t *testing.T) {
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
- // Auth must discard both spoofed values and stamp the token's
- // authoritative actor source and workspace before route guards run.
+ // Auth must discard the spoofed actor source and stamp the token's
+ // authoritative one before route guards run. A conflicting
+ // X-Workspace-ID is no longer overwritten but rejected outright
+ // (GitHub #9403), so it is deliberately not sent here: the 403s
+ // below must come from the human-only route guard.
req.Header.Set("X-Actor-Source", "member")
- req.Header.Set("X-Workspace-ID", "00000000-0000-0000-0000-000000000099")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("perform request: %v", err)
diff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.go
index e9bd644fe6..a5ba82c71f 100644
--- a/server/internal/middleware/auth.go
+++ b/server/internal/middleware/auth.go
@@ -123,10 +123,19 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATV
if rejectTemporarilyDisabledUser(w, r, userID, "", "task_token") {
return
}
+ boundWorkspaceID := uuidToString(tt.WorkspaceID)
+ // An explicit workspace selector that disagrees with the
+ // token's binding is rejected here, BEFORE the overwrite
+ // below erases what the client asked for. Silently
+ // swapping the target let a request for workspace B run
+ // against A (GitHub #9403).
+ if checkTaskTokenWorkspaceTarget(w, r, queries, boundWorkspaceID) {
+ return
+ }
r.Header.Set("X-User-ID", userID)
r.Header.Set("X-Agent-ID", uuidToString(tt.AgentID))
r.Header.Set("X-Task-ID", uuidToString(tt.TaskID))
- r.Header.Set("X-Workspace-ID", uuidToString(tt.WorkspaceID))
+ r.Header.Set("X-Workspace-ID", boundWorkspaceID)
// X-Actor-Source flags the auth path so resolveActor and
// any owner-only handler can deny without re-querying the
// token table. The value "task_token" is the only signal
diff --git a/server/internal/middleware/task_token_workspace.go b/server/internal/middleware/task_token_workspace.go
new file mode 100644
index 0000000000..8e14d56948
--- /dev/null
+++ b/server/internal/middleware/task_token_workspace.go
@@ -0,0 +1,134 @@
+package middleware
+
+import (
+ "errors"
+ "log/slog"
+ "net/http"
+ "net/url"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// errTaskTokenWorkspaceMismatch is the 403 body returned when a task-token
+// request explicitly targets a workspace other than the one bound into the
+// token. It matches the message buildMiddleware already uses for URL-param
+// conflicts so clients see one error for one condition.
+const errTaskTokenWorkspaceMismatch = "task token is bound to a different workspace"
+
+// checkTaskTokenWorkspaceTarget rejects a task-token request whose explicit
+// workspace selectors disagree with the token's bound workspace (GitHub
+// #9403).
+//
+// The token decides WHERE the agent may act; the selectors say where the
+// caller THINKS it is acting. The mat_ branch of Auth later overwrites
+// X-Workspace-ID with the bound workspace, and both resolvers short-circuit
+// on task_token, so without this check a request for workspace B silently
+// ran against A. Running it here, before the overwrite, also covers routes
+// that never pass through the workspace middleware (e.g. file upload).
+//
+// Every value of every selector is checked — X-Workspace-ID,
+// X-Workspace-Slug, ?workspace_id, ?workspace_slug — so a duplicated
+// parameter (`workspace_id=A&workspace_id=B`) cannot slip a conflicting
+// value past a first-value-only read. Empty values carry no target and are
+// treated like an absent selector, matching how every resolver and the CLI
+// (which may send `workspace_id=` when unset) already behave; they never
+// select a workspace, so they cannot cause the silent substitution.
+//
+// Returns true when it has written an error response; the caller must stop.
+// Status codes:
+// - 400 query string that cannot be fully parsed, or malformed workspace ID
+// - 404 unknown workspace slug
+// - 403 selector resolves to a different workspace than the token's
+// - 500 slug lookup failed for a reason other than "not found"
+func checkTaskTokenWorkspaceTarget(w http.ResponseWriter, r *http.Request, queries *db.Queries, boundWorkspaceID string) bool {
+ // r.URL.Query() silently drops pairs it cannot decode (bad percent
+ // escapes, unencoded ';'), so `workspace_slug=ws-b%zz` would look like
+ // "no selector" and fall through to the bound workspace. Parse strictly
+ // and refuse anything we cannot read in full.
+ query, err := url.ParseQuery(r.URL.RawQuery)
+ if err != nil {
+ slog.Warn("auth: task token request has malformed query string",
+ "path", r.URL.Path,
+ "method", r.Method,
+ "bound_workspace_id", boundWorkspaceID,
+ "error", err,
+ )
+ writeError(w, http.StatusBadRequest, "malformed query string")
+ return true
+ }
+
+ reject := func(status int, msg, selector, value string) bool {
+ slog.Warn("auth: task token workspace selector rejected",
+ "path", r.URL.Path,
+ "method", r.Method,
+ "selector", selector,
+ "value", value,
+ "bound_workspace_id", boundWorkspaceID,
+ "status", status,
+ )
+ writeError(w, status, msg)
+ return true
+ }
+
+ // UUID selectors: compare canonical forms so casing / formatting
+ // differences of the same workspace are not mistaken for a conflict.
+ idSelectors := []struct {
+ name string
+ values []string
+ }{
+ {"header:X-Workspace-ID", r.Header.Values("X-Workspace-ID")},
+ {"query:workspace_id", query["workspace_id"]},
+ }
+ for _, sel := range idSelectors {
+ for _, v := range sel.values {
+ if v == "" {
+ continue
+ }
+ parsed, err := util.ParseUUID(v)
+ if err != nil {
+ return reject(http.StatusBadRequest, "invalid workspace_id", sel.name, v)
+ }
+ if util.UUIDToString(parsed) != boundWorkspaceID {
+ return reject(http.StatusForbidden, errTaskTokenWorkspaceMismatch, sel.name, v)
+ }
+ }
+ }
+
+ // Slug selectors: resolve each to a UUID. A lookup failure must never
+ // fall back to the bound workspace.
+ slugSelectors := []struct {
+ name string
+ values []string
+ }{
+ {"header:X-Workspace-Slug", r.Header.Values("X-Workspace-Slug")},
+ {"query:workspace_slug", query["workspace_slug"]},
+ }
+ resolved := make(map[string]string)
+ for _, sel := range slugSelectors {
+ for _, slug := range sel.values {
+ if slug == "" {
+ continue
+ }
+ id, ok := resolved[slug]
+ if !ok {
+ ws, err := queries.GetWorkspaceBySlug(r.Context(), slug)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return reject(http.StatusNotFound, "workspace not found", sel.name, slug)
+ }
+ slog.Error("auth: task token workspace slug lookup failed", "path", r.URL.Path, "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to resolve workspace")
+ return true
+ }
+ id = util.UUIDToString(ws.ID)
+ resolved[slug] = id
+ }
+ if id != boundWorkspaceID {
+ return reject(http.StatusForbidden, errTaskTokenWorkspaceMismatch, sel.name, slug)
+ }
+ }
+ }
+ return false
+}
diff --git a/server/internal/middleware/task_token_workspace_test.go b/server/internal/middleware/task_token_workspace_test.go
new file mode 100644
index 0000000000..3eb3df537e
--- /dev/null
+++ b/server/internal/middleware/task_token_workspace_test.go
@@ -0,0 +1,252 @@
+package middleware
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Fixtures for the GitHub #9403 regression tests. The token is bound to
+// workspace A; B is a different workspace the agent's user can see.
+const (
+ ttTestToken = "mat_test_9403_token"
+ ttWorkspaceA = "0a0a0a0a-0000-4000-8000-00000000000a"
+ ttWorkspaceB = "0b0b0b0b-0000-4000-8000-00000000000b"
+ ttUserID = "11111111-0000-4000-8000-000000000001"
+ ttAgentID = "22222222-0000-4000-8000-000000000002"
+ ttTaskID = "33333333-0000-4000-8000-000000000003"
+ ttSlugA = "ws-a"
+ ttSlugB = "ws-b"
+ ttSlugDBError = "ws-db-error"
+)
+
+// fakeTaskTokenDB is a minimal db.DBTX that answers the two queries the
+// task-token auth path issues: GetTaskTokenByHash and GetWorkspaceBySlug.
+// Anything else fails the test, so an unexpected query on this path is
+// caught rather than silently returning zero values.
+type fakeTaskTokenDB struct {
+ t *testing.T
+}
+
+func (f *fakeTaskTokenDB) Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) {
+ f.t.Errorf("unexpected Exec on task-token auth path")
+ return pgconn.CommandTag{}, errors.New("unexpected Exec")
+}
+
+func (f *fakeTaskTokenDB) Query(context.Context, string, ...interface{}) (pgx.Rows, error) {
+ f.t.Errorf("unexpected Query on task-token auth path")
+ return nil, errors.New("unexpected Query")
+}
+
+func (f *fakeTaskTokenDB) QueryRow(_ context.Context, sql string, args ...interface{}) pgx.Row {
+ switch {
+ case strings.Contains(sql, "name: GetTaskTokenByHash"):
+ if len(args) != 1 || args[0] != auth.HashToken(ttTestToken) {
+ return fakeRow{err: pgx.ErrNoRows}
+ }
+ return fakeRow{scan: func(dest ...any) {
+ *dest[0].(*pgtype.UUID) = util.MustParseUUID("44444444-0000-4000-8000-000000000004")
+ *dest[2].(*pgtype.UUID) = util.MustParseUUID(ttTaskID)
+ *dest[3].(*pgtype.UUID) = util.MustParseUUID(ttAgentID)
+ *dest[4].(*pgtype.UUID) = util.MustParseUUID(ttWorkspaceA)
+ *dest[5].(*pgtype.UUID) = util.MustParseUUID(ttUserID)
+ }}
+ case strings.Contains(sql, "name: GetWorkspaceBySlug"):
+ var id string
+ switch args[0] {
+ case ttSlugA:
+ id = ttWorkspaceA
+ case ttSlugB:
+ id = ttWorkspaceB
+ case ttSlugDBError:
+ return fakeRow{err: errors.New("connection reset")}
+ default:
+ return fakeRow{err: pgx.ErrNoRows}
+ }
+ return fakeRow{scan: func(dest ...any) {
+ *dest[0].(*pgtype.UUID) = util.MustParseUUID(id)
+ }}
+ }
+ f.t.Errorf("unexpected QueryRow on task-token auth path: %s", sql)
+ return fakeRow{err: errors.New("unexpected QueryRow")}
+}
+
+type fakeRow struct {
+ err error
+ scan func(dest ...any)
+}
+
+func (r fakeRow) Scan(dest ...any) error {
+ if r.err != nil {
+ return r.err
+ }
+ r.scan(dest...)
+ return nil
+}
+
+// TestAuth_TaskTokenWorkspaceSelectors drives the real Auth middleware with a
+// mat_ token bound to workspace A and asserts that an explicit selector for
+// any other workspace is refused before the handler runs, instead of being
+// silently replaced by A (GitHub #9403).
+func TestAuth_TaskTokenWorkspaceSelectors(t *testing.T) {
+ cases := []struct {
+ name string
+ method string
+ target string
+ headers map[string][]string
+ wantStatus int
+ }{
+ // Allowed: no selector, or selectors that all name A.
+ {name: "no selector", method: "GET", target: "/api/projects", wantStatus: http.StatusOK},
+ {name: "header id same", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceA}}, wantStatus: http.StatusOK},
+ {name: "header id same, uppercase", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-ID": {strings.ToUpper(ttWorkspaceA)}}, wantStatus: http.StatusOK},
+ {name: "query id same", method: "GET", target: "/api/projects?workspace_id=" + ttWorkspaceA, wantStatus: http.StatusOK},
+ {name: "header slug same", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-Slug": {ttSlugA}}, wantStatus: http.StatusOK},
+ {name: "query slug same", method: "GET", target: "/api/projects?workspace_slug=" + ttSlugA, wantStatus: http.StatusOK},
+ {name: "all selectors same", method: "POST",
+ target: "/api/issues?workspace_id=" + ttWorkspaceA + "&workspace_slug=" + ttSlugA,
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceA}, "X-Workspace-Slug": {ttSlugA}},
+ wantStatus: http.StatusOK},
+ {name: "empty query id is no selector", method: "GET", target: "/api/projects?workspace_id=", wantStatus: http.StatusOK},
+
+ // Conflicts: each selector on its own.
+ {name: "header id conflict", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceB}}, wantStatus: http.StatusForbidden},
+ {name: "query id conflict", method: "GET", target: "/api/projects?workspace_id=" + ttWorkspaceB, wantStatus: http.StatusForbidden},
+ {name: "header slug conflict", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-Slug": {ttSlugB}}, wantStatus: http.StatusForbidden},
+ {name: "query slug conflict", method: "GET", target: "/api/projects?workspace_slug=" + ttSlugB, wantStatus: http.StatusForbidden},
+
+ // Contradicting selectors and duplicated parameters.
+ {name: "header A, query B", method: "GET", target: "/api/projects?workspace_id=" + ttWorkspaceB,
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceA}}, wantStatus: http.StatusForbidden},
+ {name: "id A, slug B", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceA}, "X-Workspace-Slug": {ttSlugB}}, wantStatus: http.StatusForbidden},
+ {name: "duplicate query id A then B", method: "GET",
+ target: "/api/projects?workspace_id=" + ttWorkspaceA + "&workspace_id=" + ttWorkspaceB, wantStatus: http.StatusForbidden},
+ {name: "duplicate header id A then B", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceA, ttWorkspaceB}}, wantStatus: http.StatusForbidden},
+ {name: "duplicate query slug A then B", method: "GET",
+ target: "/api/projects?workspace_slug=" + ttSlugA + "&workspace_slug=" + ttSlugB, wantStatus: http.StatusForbidden},
+
+ // Unresolvable selectors never fall back to A.
+ {name: "malformed header id", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-ID": {"not-a-uuid"}}, wantStatus: http.StatusBadRequest},
+ {name: "malformed query id", method: "GET", target: "/api/projects?workspace_id=nope", wantStatus: http.StatusBadRequest},
+ {name: "unknown slug", method: "GET", target: "/api/projects",
+ headers: map[string][]string{"X-Workspace-Slug": {"does-not-exist"}}, wantStatus: http.StatusNotFound},
+ {name: "slug lookup db error", method: "GET", target: "/api/projects?workspace_slug=" + ttSlugDBError,
+ wantStatus: http.StatusInternalServerError},
+
+ // Query strings that url.Query() would partially drop must be
+ // refused outright, not read as "no selector" (PR #9422 review).
+ {name: "bad escape in workspace_id", method: "POST",
+ target: "/api/projects?workspace_id=" + ttWorkspaceB + "%zz", wantStatus: http.StatusBadRequest},
+ {name: "bad escape in workspace_slug", method: "POST",
+ target: "/api/projects?workspace_slug=ws-b%zz", wantStatus: http.StatusBadRequest},
+ {name: "unencoded semicolon", method: "POST",
+ target: "/api/projects?workspace_id=" + ttWorkspaceB + ";ignored=1", wantStatus: http.StatusBadRequest},
+ {name: "valid A then malformed B", method: "POST",
+ target: "/api/projects?workspace_id=" + ttWorkspaceA + "&workspace_id=" + ttWorkspaceB + "%zz",
+ wantStatus: http.StatusBadRequest},
+ {name: "malformed non-selector param", method: "POST",
+ target: "/api/projects?workspace_id=" + ttWorkspaceA + "&q=%zz", wantStatus: http.StatusBadRequest},
+ {name: "encoded values still accepted", method: "GET",
+ target: "/api/projects?workspace_slug=ws%2Da&q=a%20b", wantStatus: http.StatusOK},
+
+ // Writes, including an auth-only route that never reaches the
+ // workspace middleware.
+ {name: "POST conflict", method: "POST", target: "/api/issues",
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceB}}, wantStatus: http.StatusForbidden},
+ {name: "PATCH conflict", method: "PATCH", target: "/api/issues/x?workspace_slug=" + ttSlugB, wantStatus: http.StatusForbidden},
+ {name: "upload conflict", method: "POST", target: "/api/upload-file",
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceB}}, wantStatus: http.StatusForbidden},
+ {name: "upload same", method: "POST", target: "/api/upload-file",
+ headers: map[string][]string{"X-Workspace-ID": {ttWorkspaceA}}, wantStatus: http.StatusOK},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ queries := db.New(&fakeTaskTokenDB{t: t})
+ var called bool
+ var gotWorkspace, gotSource string
+ handler := Auth(queries, nil, nil, nil)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ gotWorkspace = r.Header.Get("X-Workspace-ID")
+ gotSource = r.Header.Get("X-Actor-Source")
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(tc.method, tc.target, nil)
+ req.Header.Set("Authorization", "Bearer "+ttTestToken)
+ for k, vs := range tc.headers {
+ for _, v := range vs {
+ req.Header.Add(k, v)
+ }
+ }
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != tc.wantStatus {
+ t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, w.Body.String())
+ }
+ if tc.wantStatus != http.StatusOK {
+ if called {
+ t.Fatalf("handler must not run when the selector is rejected")
+ }
+ if tc.wantStatus == http.StatusForbidden && !strings.Contains(w.Body.String(), errTaskTokenWorkspaceMismatch) {
+ t.Fatalf("403 body = %s, want %q", w.Body.String(), errTaskTokenWorkspaceMismatch)
+ }
+ return
+ }
+ if !called {
+ t.Fatalf("handler was not called")
+ }
+ // Accepted requests still carry the token's binding, in
+ // canonical form, as the single X-Workspace-ID value.
+ if gotWorkspace != ttWorkspaceA {
+ t.Fatalf("X-Workspace-ID = %q, want bound workspace %q", gotWorkspace, ttWorkspaceA)
+ }
+ if gotSource != "task_token" {
+ t.Fatalf("X-Actor-Source = %q, want task_token", gotSource)
+ }
+ })
+ }
+}
+
+// TestAuth_JWTWorkspaceSelectorUntouched is the control for the task-token
+// check: human JWT sessions keep choosing their workspace through headers,
+// and Auth must neither validate nor rewrite that choice.
+func TestAuth_JWTWorkspaceSelectorUntouched(t *testing.T) {
+ var gotWorkspace string
+ handler := Auth(nil, nil, nil, nil)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotWorkspace = r.Header.Get("X-Workspace-ID")
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest("GET", "/api/projects?workspace_slug=anything", nil)
+ req.Header.Set("Authorization", "Bearer "+generateToken(validClaims(), auth.JWTSecret()))
+ req.Header.Set("X-Workspace-ID", ttWorkspaceB)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body %s)", w.Code, w.Body.String())
+ }
+ if gotWorkspace != ttWorkspaceB {
+ t.Fatalf("X-Workspace-ID = %q, want client value %q", gotWorkspace, ttWorkspaceB)
+ }
+}
diff --git a/server/internal/middleware/workspace.go b/server/internal/middleware/workspace.go
index f663d2b3c0..4fb58c33c8 100644
--- a/server/internal/middleware/workspace.go
+++ b/server/internal/middleware/workspace.go
@@ -71,7 +71,9 @@ func ResolveWorkspaceIDFromRequest(r *http.Request, queries *db.Queries) string
// after stripping any client-supplied X-Actor-Source. Any other
// workspace identifier on the request (slug header/query, ID
// query, URL param) is the agent trying to widen its blast
- // radius — ignore it.
+ // radius — ignore it. Explicit selectors that conflict with the
+ // binding were already rejected by Auth (checkTaskTokenWorkspaceTarget,
+ // GitHub #9403); this branch is the backstop.
if r.Header.Get("X-Actor-Source") == "task_token" {
return r.Header.Get("X-Workspace-ID")
}