mirror of
https://github.com/multica-ai/multica.git
synced 2026-07-27 21:33:41 +02:00
* 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>
227 lines
7.8 KiB
Go
227 lines
7.8 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/multica-ai/multica/server/internal/util"
|
|
db "github.com/multica-ai/multica/server/pkg/db/generated"
|
|
)
|
|
|
|
// Context keys for workspace-scoped request data.
|
|
type contextKey int
|
|
|
|
const (
|
|
ctxKeyWorkspaceID contextKey = iota
|
|
ctxKeyMember
|
|
)
|
|
|
|
// MemberFromContext returns the workspace member injected by the workspace middleware.
|
|
func MemberFromContext(ctx context.Context) (db.Member, bool) {
|
|
m, ok := ctx.Value(ctxKeyMember).(db.Member)
|
|
return m, ok
|
|
}
|
|
|
|
// WorkspaceIDFromContext returns the workspace ID injected by the workspace middleware.
|
|
func WorkspaceIDFromContext(ctx context.Context) string {
|
|
id, _ := ctx.Value(ctxKeyWorkspaceID).(string)
|
|
return id
|
|
}
|
|
|
|
// SetMemberContext injects workspace ID and member into the context.
|
|
// This is useful for handlers that resolve the workspace from an entity lookup
|
|
// and want to share the member with downstream code.
|
|
func SetMemberContext(ctx context.Context, workspaceID string, member db.Member) context.Context {
|
|
ctx = context.WithValue(ctx, ctxKeyWorkspaceID, workspaceID)
|
|
ctx = context.WithValue(ctx, ctxKeyMember, member)
|
|
return ctx
|
|
}
|
|
|
|
// errWorkspaceNotFound is returned when a slug was provided but doesn't match
|
|
// any workspace. This lets the middleware distinguish "no identifier provided"
|
|
// (400) from "identifier provided but invalid" (404).
|
|
var errWorkspaceNotFound = errors.New("workspace not found")
|
|
|
|
// ResolveWorkspaceIDFromRequest returns the workspace UUID for an HTTP
|
|
// request using the same priority order as the workspace middleware. This is
|
|
// the single source of truth for "which workspace is this request targeting?",
|
|
// shared by middleware-protected routes (via context fast path) and
|
|
// middleware-less routes (e.g. /api/upload-file) that must resolve the slug
|
|
// themselves.
|
|
//
|
|
// Priority:
|
|
// 1. middleware-injected context (fast path for middleware-protected routes)
|
|
// 2. X-Workspace-Slug header → GetWorkspaceBySlug → UUID (post-refactor frontend)
|
|
// 3. ?workspace_slug query → GetWorkspaceBySlug → UUID
|
|
// 4. X-Workspace-ID header (CLI/daemon compat)
|
|
// 5. ?workspace_id query (CLI/daemon compat)
|
|
//
|
|
// Returns "" when no identifier was provided OR a slug was provided but
|
|
// doesn't resolve to any workspace. Callers that need to distinguish "no
|
|
// identifier" (400) from "invalid slug" (404) should use the middleware's
|
|
// internal resolver instead — this helper collapses both cases to "" for
|
|
// simpler handler-level checks.
|
|
func ResolveWorkspaceIDFromRequest(r *http.Request, queries *db.Queries) string {
|
|
if id := WorkspaceIDFromContext(r.Context()); id != "" {
|
|
return id
|
|
}
|
|
if slug := r.Header.Get("X-Workspace-Slug"); slug != "" {
|
|
if ws, err := queries.GetWorkspaceBySlug(r.Context(), slug); err == nil {
|
|
return util.UUIDToString(ws.ID)
|
|
}
|
|
}
|
|
if slug := r.URL.Query().Get("workspace_slug"); slug != "" {
|
|
if ws, err := queries.GetWorkspaceBySlug(r.Context(), slug); err == nil {
|
|
return util.UUIDToString(ws.ID)
|
|
}
|
|
}
|
|
if id := r.Header.Get("X-Workspace-ID"); id != "" {
|
|
return id
|
|
}
|
|
return r.URL.Query().Get("workspace_id")
|
|
}
|
|
|
|
// workspaceResolver extracts a workspace UUID from the request.
|
|
// Returns ("", nil) if no workspace identifier was provided at all.
|
|
// Returns ("", errWorkspaceNotFound) if a slug was provided but doesn't exist.
|
|
// Returns (uuid, nil) on success.
|
|
type workspaceResolver func(r *http.Request) (string, error)
|
|
|
|
// resolveWorkspaceUUID builds a resolver that accepts slug-first identification.
|
|
//
|
|
// Priority:
|
|
// 1. X-Workspace-Slug header / ?workspace_slug query → GetWorkspaceBySlug → UUID
|
|
// 2. X-Workspace-ID header / ?workspace_id query → UUID directly (CLI/daemon compat)
|
|
//
|
|
// TODO: cache slug→UUID lookup (slug is immutable, safe to cache with short TTL)
|
|
func resolveWorkspaceUUID(queries *db.Queries) workspaceResolver {
|
|
return func(r *http.Request) (string, error) {
|
|
// Slug path (preferred — frontend sends this after the URL refactor)
|
|
if slug := r.URL.Query().Get("workspace_slug"); slug != "" {
|
|
ws, err := queries.GetWorkspaceBySlug(r.Context(), slug)
|
|
if err != nil {
|
|
return "", errWorkspaceNotFound
|
|
}
|
|
return util.UUIDToString(ws.ID), nil
|
|
}
|
|
if slug := r.Header.Get("X-Workspace-Slug"); slug != "" {
|
|
ws, err := queries.GetWorkspaceBySlug(r.Context(), slug)
|
|
if err != nil {
|
|
return "", errWorkspaceNotFound
|
|
}
|
|
return util.UUIDToString(ws.ID), nil
|
|
}
|
|
// UUID fallback (CLI, daemon, legacy clients)
|
|
if id := r.URL.Query().Get("workspace_id"); id != "" {
|
|
return id, nil
|
|
}
|
|
if id := r.Header.Get("X-Workspace-ID"); id != "" {
|
|
return id, nil
|
|
}
|
|
return "", nil
|
|
}
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, msg string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
w.Write([]byte(`{"error":"` + msg + `"}`))
|
|
}
|
|
|
|
// RequireWorkspaceMember resolves the workspace from slug (preferred) or UUID
|
|
// (fallback), validates membership, and injects the member and workspace ID
|
|
// into the request context.
|
|
func RequireWorkspaceMember(queries *db.Queries) func(http.Handler) http.Handler {
|
|
return buildMiddleware(queries, resolveWorkspaceUUID(queries), nil)
|
|
}
|
|
|
|
// RequireWorkspaceRole is like RequireWorkspaceMember but additionally checks
|
|
// that the member has one of the specified roles.
|
|
func RequireWorkspaceRole(queries *db.Queries, roles ...string) func(http.Handler) http.Handler {
|
|
return buildMiddleware(queries, resolveWorkspaceUUID(queries), roles)
|
|
}
|
|
|
|
// RequireWorkspaceMemberFromURL resolves the workspace ID from a chi URL
|
|
// parameter, validates membership, and injects into context.
|
|
func RequireWorkspaceMemberFromURL(queries *db.Queries, param string) func(http.Handler) http.Handler {
|
|
return buildMiddleware(queries, func(r *http.Request) (string, error) {
|
|
id := chi.URLParam(r, param)
|
|
if id == "" {
|
|
return "", nil
|
|
}
|
|
return id, nil
|
|
}, nil)
|
|
}
|
|
|
|
// RequireWorkspaceRoleFromURL is like RequireWorkspaceMemberFromURL but
|
|
// additionally checks that the member has one of the specified roles.
|
|
func RequireWorkspaceRoleFromURL(queries *db.Queries, param string, roles ...string) func(http.Handler) http.Handler {
|
|
return buildMiddleware(queries, func(r *http.Request) (string, error) {
|
|
id := chi.URLParam(r, param)
|
|
if id == "" {
|
|
return "", nil
|
|
}
|
|
return id, nil
|
|
}, roles)
|
|
}
|
|
|
|
func buildMiddleware(queries *db.Queries, resolve workspaceResolver, roles []string) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
workspaceID, resolveErr := resolve(r)
|
|
if resolveErr != nil {
|
|
writeError(w, http.StatusNotFound, "workspace not found")
|
|
return
|
|
}
|
|
if workspaceID == "" {
|
|
writeError(w, http.StatusBadRequest, "workspace_id or workspace_slug is required")
|
|
return
|
|
}
|
|
|
|
userID := r.Header.Get("X-User-ID")
|
|
if userID == "" {
|
|
writeError(w, http.StatusUnauthorized, "user not authenticated")
|
|
return
|
|
}
|
|
|
|
userUUID, err := util.ParseUUID(userID)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, "user not authenticated")
|
|
return
|
|
}
|
|
wsUUID, err := util.ParseUUID(workspaceID)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid workspace_id")
|
|
return
|
|
}
|
|
member, err := queries.GetMemberByUserAndWorkspace(r.Context(), db.GetMemberByUserAndWorkspaceParams{
|
|
UserID: userUUID,
|
|
WorkspaceID: wsUUID,
|
|
})
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "workspace not found")
|
|
return
|
|
}
|
|
|
|
if len(roles) > 0 {
|
|
allowed := false
|
|
for _, role := range roles {
|
|
if member.Role == role {
|
|
allowed = true
|
|
break
|
|
}
|
|
}
|
|
if !allowed {
|
|
writeError(w, http.StatusForbidden, "insufficient permissions")
|
|
return
|
|
}
|
|
}
|
|
|
|
ctx := SetMemberContext(r.Context(), workspaceID, member)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|