Files
multica/server/cmd/server/scope_authorizer.go
Bohan Jiang f628e48775 refactor(server): error-returning ParseUUID to prevent silent data loss
* refactor(server): make ParseUUID error-returning to prevent silent data loss (MUL-1410)

util.ParseUUID previously swallowed errors and returned a zero pgtype.UUID
on invalid input. When this zero UUID reached a write query (DELETE/UPDATE),
the SQL matched zero rows and the handler returned 2xx success — producing
silent data corruption. #1661 (DeleteIssue with identifier-style ID) was the
visible symptom; PR #1680 patched that one site, this commit closes the
class of bug.

Changes:

- util.ParseUUID now returns (pgtype.UUID, error). Add util.MustParseUUID
  for trusted round-trips that should panic on invalid input.
- handler/handler.go: parseUUID wrapper now calls MustParseUUID — any
  unguarded user-input string reaching it surfaces as a recovered panic
  (chi middleware.Recoverer → 500) instead of silently corrupting data.
  Add parseUUIDOrBadRequest(w, s, fieldName) for handler entry points.
- Convert every Queries.Delete*/Update* call site reachable from raw user
  input (autopilot, comment, project, skill, skill_file, label, pin,
  attachment, feedback, issue assignee, daemon runtime, workspace) to
  validate UUIDs explicitly with parseUUIDOrBadRequest, returning 400 on
  invalid input. Where a resolved entity.ID is already in scope, write
  queries now use it directly instead of re-parsing the URL string.
- Update getWorkspaceMember + loadIssueForUser to handle invalid UUIDs
  gracefully (404/400 instead of panic).
- Update util/middleware/cmd-level callers (subscriber_listeners,
  notification_listeners, activity_listeners, scope_authorizer,
  middleware/workspace) to use the error-returning API.
- Add server/internal/util/pgx_test.go covering valid/invalid input and
  the MustParseUUID panic contract.
- Add TestDeleteIssueByIdentifier + TestDeleteIssueRejectsInvalidUUID
  regression tests in handler_test.go (the original #1661 bug + the
  invalid-input case).
- Document the handler UUID parsing convention in CLAUDE.md so the rule
  is enforceable in future PR review.

* fix(server): address GPT-Boy review of #1748

P1 fixes from PR #1748 review:

1. Migrate remaining request-boundary UUIDs to parseUUIDOrBadRequest so
   malformed input returns 400 instead of panic/500. Was missing on:
   - issue.go: workspace_id in CreateIssue/ChildIssueProgress/ListIssues/
     SearchIssues/BatchUpdateIssues/BatchDeleteIssues; project_id /
     parent_issue_id / lead_id / assignee_id / assignee_ids / creator_id
     filters; batch issue_ids and assignee/parent/project fields in
     BatchUpdateIssues (skip on bad input via util.ParseUUID, matching
     the existing per-row continue semantics).
   - project.go: project id + workspace_id in GetProject/UpdateProject/
     DeleteProject; lead_id in CreateProject/UpdateProject;
     workspace_id in ListProjects + SearchProjects.
   - handler.go: resolveActor now uses util.ParseUUID for X-Agent-ID /
     X-Task-ID headers; invalid UUID falls back to "member" (matches
     pre-existing semantics) instead of panicking.
   - issue.go: validateAssigneePair returns 400 on invalid workspace_id
     instead of panicking.

2. Fix issue:deleted WS event payloads to emit uuidToString(issue.ID)
   instead of the raw URL string. After an identifier-path delete
   ("MUL-7"), the previous payload would have leaked the identifier to
   subscribers, leaving stale entries in frontend caches that key by
   UUID. Updated DeleteIssue (issue.go:1341) and BatchDeleteIssues
   (issue.go:1641). The slog "issue deleted" log line also now records
   the resolved UUID so logs match the WS payload.

3. Extend TestDeleteIssueByIdentifier to subscribe to the bus and
   assert issue:deleted.payload.issue_id is the resolved UUID, not
   the identifier.

* fix(server): validate remaining reviewed UUID inputs

* fix(server): validate remaining handler UUID inputs

* fix(server): finish request boundary UUID audit

* fix(server): validate remaining request body UUIDs

* fix(server): validate runtime path UUIDs

* fix(server): validate remaining audit UUID inputs

---------

Co-authored-by: Eve <eve@multica.ai>
2026-04-28 14:50:28 +08:00

97 lines
3.1 KiB
Go

package main
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/realtime"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// scopeAuthQuerier is the narrow subset of db.Queries used by the scope
// authorizer. Declared as an interface so the authorizer can be unit tested
// with an in-memory fake (no DB required).
type scopeAuthQuerier interface {
GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
GetIssue(ctx context.Context, id pgtype.UUID) (db.Issue, error)
GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)
}
// dbScopeAuthorizer implements realtime.ScopeAuthorizer for the per-task and
// per-chat scopes (workspace/user scopes are validated by the hub itself
// against the connection identity). It returns true only when the requested
// resource exists, belongs to the caller's workspace, and — for chat
// resources — was created by the caller (mirroring the HTTP creator-only
// access model).
type dbScopeAuthorizer struct{ q scopeAuthQuerier }
func newScopeAuthorizer(q scopeAuthQuerier) *dbScopeAuthorizer { return &dbScopeAuthorizer{q: q} }
func (a *dbScopeAuthorizer) AuthorizeScope(ctx context.Context, userID, workspaceID, scopeType, scopeID string) (bool, error) {
if workspaceID == "" || scopeID == "" {
return false, nil
}
wsUUID, err := util.ParseUUID(workspaceID)
if err != nil {
return false, nil
}
idUUID, err := util.ParseUUID(scopeID)
if err != nil {
return false, nil
}
switch scopeType {
case realtime.ScopeTask:
task, err := a.q.GetAgentTask(ctx, idUUID)
if err != nil {
return false, nil
}
// Issue tasks: visible to any workspace member.
if task.IssueID.Valid {
issue, err := a.q.GetIssue(ctx, task.IssueID)
if err != nil {
return false, nil
}
return issue.WorkspaceID == wsUUID, nil
}
// Chat tasks: only the chat session's creator may subscribe, mirroring
// the HTTP layer's creator-only access on chat resources.
if task.ChatSessionID.Valid {
sess, err := a.q.GetChatSession(ctx, task.ChatSessionID)
if err != nil {
return false, nil
}
if sess.WorkspaceID != wsUUID {
return false, nil
}
uidUUID, err := util.ParseUUID(userID)
if err != nil || sess.CreatorID != uidUUID {
return false, nil
}
return true, nil
}
return false, nil
case realtime.ScopeChat:
sess, err := a.q.GetChatSession(ctx, idUUID)
if err != nil {
return false, nil
}
if sess.WorkspaceID != wsUUID {
return false, nil
}
// Chat sessions are private to their creator (see handler/chat.go:
// GetChatSession / SendChatMessage / MarkChatSessionRead all enforce
// CreatorID == userID). The realtime layer must not weaken this:
// otherwise any workspace member who learns a session_id could
// subscribe to chat:message / chat:done / chat:session_read for a
// peer's private chat.
uidUUID, err := util.ParseUUID(userID)
if err != nil || sess.CreatorID != uidUUID {
return false, nil
}
return true, nil
default:
return false, nil
}
}