diff --git a/internal/infrastructure/postgres/edastore_eventtypes.go b/internal/infrastructure/postgres/edastore_eventtypes.go index 908f4e50e..ae88153ec 100644 --- a/internal/infrastructure/postgres/edastore_eventtypes.go +++ b/internal/infrastructure/postgres/edastore_eventtypes.go @@ -63,6 +63,17 @@ func (s *EDA) saveEventType(ctx context.Context, t eventtype.EventType, write fu if err := t.Validate(); err != nil { return err } + // A type is saved only on a source of the caller's own org: another org's + // rule would otherwise identify that org's captures. + if _, scoped := org.Scope(ctx); scoped { + src, err := s.GetSource(ctx, t.Source) + if err != nil { + return err + } + if src == nil { + return storecontract.ErrSourceNotFound + } + } rule, err := json.Marshal(t.Rule) if err != nil { return fmt.Errorf("edastore: encode event type rule: %w", err) diff --git a/internal/infrastructure/postgres/migrations/0042_org_backfill.sql b/internal/infrastructure/postgres/migrations/0042_org_backfill.sql new file mode 100644 index 000000000..291966297 --- /dev/null +++ b/internal/infrastructure/postgres/migrations/0042_org_backfill.sql @@ -0,0 +1,22 @@ +-- Rows written before their writers stamped an org took the column default, +-- the system org. Each takes the org of the record it belongs to: a task's +-- events, transitions, steps and tool calls the task's, and a source's event +-- types, bindings and mappings the source's. +-- +goose Up +UPDATE events e SET org_id = t.org_id, workspace_id = t.workspace_id +FROM tasks t WHERE e.task_id = t.id AND e.org_id <> t.org_id; +UPDATE transitions x SET org_id = t.org_id, workspace_id = t.workspace_id +FROM tasks t WHERE x.task_id = t.id AND x.org_id <> t.org_id; +UPDATE step_executions x SET org_id = t.org_id, workspace_id = t.workspace_id +FROM tasks t WHERE x.execution_id = t.id AND x.org_id <> t.org_id; +UPDATE tool_calls x SET org_id = t.org_id, workspace_id = t.workspace_id +FROM tasks t WHERE x.task_id = t.id AND x.org_id <> t.org_id; +UPDATE event_types x SET org_id = s.org_id, workspace_id = s.workspace_id +FROM sources s WHERE x.source = s.path AND x.org_id <> s.org_id; +UPDATE bindings x SET org_id = s.org_id, workspace_id = s.workspace_id +FROM sources s WHERE x.source = s.path AND x.org_id <> s.org_id; +UPDATE mappings x SET org_id = y.org_id, workspace_id = y.workspace_id +FROM event_types y WHERE x.event_type = y.id AND x.org_id <> y.org_id; + +-- +goose Down +SELECT 1; diff --git a/internal/infrastructure/postgres/postgresdb/tasks.sql.go b/internal/infrastructure/postgres/postgresdb/tasks.sql.go index 745fc8586..d8508b7ea 100644 --- a/internal/infrastructure/postgres/postgresdb/tasks.sql.go +++ b/internal/infrastructure/postgres/postgresdb/tasks.sql.go @@ -300,10 +300,11 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) { const clearTerminalTasks = `-- name: ClearTerminalTasks :execrows DELETE FROM tasks WHERE status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed') + AND ($1::text IS NULL OR org_id = $1) ` -func (q *Queries) ClearTerminalTasks(ctx context.Context) (int64, error) { - result, err := q.db.Exec(ctx, clearTerminalTasks) +func (q *Queries) ClearTerminalTasks(ctx context.Context, scopeOrg pgtype.Text) (int64, error) { + result, err := q.db.Exec(ctx, clearTerminalTasks, scopeOrg) if err != nil { return 0, err } @@ -386,7 +387,7 @@ func (q *Queries) EnqueueIssue(ctx context.Context, arg EnqueueIssueParams) (int const insertChatTask = `-- name: InsertChatTask :one INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, inputs, origin) -VALUES ( +SELECT $1, $2, COALESCE(( SELECT MAX(existing.issue_number) FROM tasks existing @@ -395,15 +396,16 @@ VALUES ( AND existing.source = 'chat' ), $3) + 1, $4, $5, 'chat', $6, 'chat', $7, - COALESCE( + owner_org.id, + $8, + $9 +FROM (SELECT COALESCE( (SELECT a.org_id FROM org_agents a WHERE a.identity_id = $7), (SELECT m.org_id FROM memberships m WHERE m.identity_id = $7 ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1), 'org-sys' - ), - $8, - $9 -) + ) AS id) AS owner_org +WHERE $10::text IS NULL OR owner_org.id = $10 RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key ` @@ -417,6 +419,7 @@ type InsertChatTaskParams struct { Identity string Inputs string Origin string + ScopeOrg pgtype.Text } // The synthetic issue number keeps chat-sourced tasks off the forge's real @@ -426,6 +429,8 @@ type InsertChatTaskParams struct { // inputs is the chat task's own workflow inputs; a binding dispatch passes // its inputs here too, so this insert is the single writer of the column and // StampTaskBinding adds only the provenance. +// The task runs in its identity's org; a caller confined to another org +// inserts nothing, so it cannot start work under an identity it does not own. func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams) (Task, error) { row := q.db.QueryRow(ctx, insertChatTask, arg.Owner, @@ -437,6 +442,7 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams) arg.Identity, arg.Inputs, arg.Origin, + arg.ScopeOrg, ) var i Task err := row.Scan( @@ -992,16 +998,23 @@ func (q *Queries) TaskByID(ctx context.Context, arg TaskByIDParams) (Task, error const taskByIssue = `-- name: TaskByIssue :one SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 + AND ($4::text IS NULL OR org_id = $4) ` type TaskByIssueParams struct { Owner string Repo string IssueNumber int64 + ScopeOrg pgtype.Text } func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task, error) { - row := q.db.QueryRow(ctx, taskByIssue, arg.Owner, arg.Repo, arg.IssueNumber) + row := q.db.QueryRow(ctx, taskByIssue, + arg.Owner, + arg.Repo, + arg.IssueNumber, + arg.ScopeOrg, + ) var i Task err := row.Scan( &i.ID, @@ -1056,6 +1069,7 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task, const taskByPR = `-- name: TaskByPR :one SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4 + AND ($5::text IS NULL OR org_id = $5) ` type TaskByPRParams struct { @@ -1063,6 +1077,7 @@ type TaskByPRParams struct { Repo string PrNumber int64 Status string + ScopeOrg pgtype.Text } // OpenTaskByPR is the live-task lookup: it only resolves a PR the task is @@ -1074,6 +1089,7 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error arg.Repo, arg.PrNumber, arg.Status, + arg.ScopeOrg, ) var i Task err := row.Scan( diff --git a/internal/infrastructure/postgres/queries/tasks.sql b/internal/infrastructure/postgres/queries/tasks.sql index 14f4188b8..e2e8c9bff 100644 --- a/internal/infrastructure/postgres/queries/tasks.sql +++ b/internal/infrastructure/postgres/queries/tasks.sql @@ -20,13 +20,15 @@ RETURNING *; SELECT * FROM tasks WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org)); -- name: TaskByIssue :one -SELECT * FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3; +SELECT * FROM tasks WHERE owner = sqlc.arg(owner) AND repo = sqlc.arg(repo) AND issue_number = sqlc.arg(issue_number) + AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org)); -- name: TaskByPR :one -- OpenTaskByPR is the live-task lookup: it only resolves a PR the task is -- currently tracking as open, so a merged or rejected task does not read as -- the owner of a PR number it no longer holds. -SELECT * FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4; +SELECT * FROM tasks WHERE owner = sqlc.arg(owner) AND repo = sqlc.arg(repo) AND pr_number = sqlc.arg(pr_number) AND status = sqlc.arg(status) + AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org)); -- name: ListTaskSummaries :many -- The dashboard's list. This projection is deliberately narrow: Plan gates @@ -61,8 +63,10 @@ SELECT status, count(*)::int AS count FROM tasks WHERE (sqlc.narg(scope_org)::te -- inputs is the chat task's own workflow inputs; a binding dispatch passes -- its inputs here too, so this insert is the single writer of the column and -- StampTaskBinding adds only the provenance. +-- The task runs in its identity's org; a caller confined to another org +-- inserts nothing, so it cannot start work under an identity it does not own. INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, inputs, origin) -VALUES ( +SELECT sqlc.arg(owner), sqlc.arg(repo), COALESCE(( SELECT MAX(existing.issue_number) FROM tasks existing @@ -71,15 +75,16 @@ VALUES ( AND existing.source = 'chat' ), sqlc.arg(fallback_issue_number)) + 1, sqlc.arg(title), sqlc.arg(body), 'chat', sqlc.arg(workflow), 'chat', sqlc.arg(identity), - COALESCE( + owner_org.id, + sqlc.arg(inputs), + sqlc.arg(origin) +FROM (SELECT COALESCE( (SELECT a.org_id FROM org_agents a WHERE a.identity_id = sqlc.arg(identity)), (SELECT m.org_id FROM memberships m WHERE m.identity_id = sqlc.arg(identity) ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1), 'org-sys' - ), - sqlc.arg(inputs), - sqlc.arg(origin) -) + ) AS id) AS owner_org +WHERE sqlc.narg(scope_org)::text IS NULL OR owner_org.id = sqlc.narg(scope_org) RETURNING *; -- name: ActiveTasksByOrigin :many @@ -135,7 +140,8 @@ WHERE id = $1 AND status = $4; -- name: ClearTerminalTasks :execrows DELETE FROM tasks -WHERE status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed'); +WHERE status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed') + AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org)); -- name: RecoverStaleTasks :execrows UPDATE tasks SET status = 'queued', updated_at = now() WHERE status = 'running'; diff --git a/internal/infrastructure/postgres/store.go b/internal/infrastructure/postgres/store.go index e137b94f3..6094d1d7d 100644 --- a/internal/infrastructure/postgres/store.go +++ b/internal/infrastructure/postgres/store.go @@ -160,11 +160,15 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w return nil, err } t, err := s.queries().InsertChatTask(ctx, postgresdb.InsertChatTaskParams{ - Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity, + ScopeOrg: scopeOrg(ctx), + Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity, Inputs: encoded, Origin: origin, FallbackIssueNumber: syntheticIssueNumberBase - 1, }) + if errors.Is(err, pgx.ErrNoRows) { + return nil, fmt.Errorf("identity %q belongs to another org", identity) + } if err != nil { return nil, err } @@ -689,7 +693,7 @@ func (s *Store) OpenPRs(ctx context.Context) ([]workflow.Task, error) { // ClearTerminalTasks deletes tasks whose status is terminal. func (s *Store) ClearTerminalTasks(ctx context.Context) (int64, error) { - return s.queries().ClearTerminalTasks(ctx) + return s.queries().ClearTerminalTasks(ctx, scopeOrg(ctx)) } // Tasks returns the most recently updated tasks. @@ -745,7 +749,7 @@ func (s *Store) StatusCounts(ctx context.Context) (map[string]int, error) { // TaskByIssue returns the task tracking an issue, or nil. func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) { t, err := s.queries().TaskByIssue(ctx, postgresdb.TaskByIssueParams{ - Owner: owner, Repo: repo, IssueNumber: int64(number), + ScopeOrg: scopeOrg(ctx), Owner: owner, Repo: repo, IssueNumber: int64(number), }) if errors.Is(err, pgx.ErrNoRows) { return nil, nil @@ -759,7 +763,7 @@ func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int) // OpenTaskByPR returns the live task that owns the given pull request, or nil. func (s *Store) OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) { t, err := s.queries().TaskByPR(ctx, postgresdb.TaskByPRParams{ - Owner: owner, Repo: repo, PrNumber: int64(number), Status: workflow.StatusPROpen, + ScopeOrg: scopeOrg(ctx), Owner: owner, Repo: repo, PrNumber: int64(number), Status: workflow.StatusPROpen, }) if errors.Is(err, pgx.ErrNoRows) { return nil, nil diff --git a/internal/infrastructure/postgres/task_org_test.go b/internal/infrastructure/postgres/task_org_test.go index c968f5474..c52d4a194 100644 --- a/internal/infrastructure/postgres/task_org_test.go +++ b/internal/infrastructure/postgres/task_org_test.go @@ -11,7 +11,8 @@ import ( // An org's tasks, their events and the stats built from them are invisible to // a request scoped to another org. An event a task emits belongs to the -// task's org whatever org the writer acts in. +// task's org whatever org the writer acts in, and a caller cannot start work +// under another org's identity. func TestTasksStayInTheirOrg(t *testing.T) { scoped := func(id org.OrgID) context.Context { return org.WithScope(org.WithOrg(t.Context(), id), id) @@ -75,4 +76,8 @@ func TestTasksStayInTheirOrg(t *testing.T) { } }) } + // An identity of the system org starts no work for a caller in acme. + if _, err := db.EnqueueChatTask(scoped("acme"), "o", "r", "t", "b", "deploy", "operator", "", nil); err == nil { + t.Fatal("acme started a task under a system-org identity") + } } diff --git a/internal/webui/server.go b/internal/webui/server.go index 7bdeace85..4151fadad 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -331,7 +331,7 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList) mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet) mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove) - mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", s.handleOrgAgentAssign) + mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", instanceOnly(s.handleOrgAgentAssign)) mux.HandleFunc("GET /api/tokens", s.handlePersonalTokensList) mux.HandleFunc("POST /api/tokens", s.handlePersonalTokenCreate) mux.HandleFunc("DELETE /api/tokens/{id}", s.handlePersonalTokenRevoke) @@ -351,9 +351,9 @@ func (s *Server) registerChatRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/chat/answer", s.handleChatAnswer) mux.HandleFunc("GET /api/chat/file/{token}", s.handleChatFile) mux.HandleFunc("POST /api/chat/persona", s.handleChatPersona) - mux.HandleFunc("GET /api/chat/update", s.handleChatUpdate) - mux.HandleFunc("POST /api/chat/update/defer", s.handleChatUpdateDefer) - mux.HandleFunc("POST /api/chat/update/install", s.handleChatUpdateInstall) + mux.HandleFunc("GET /api/chat/update", instanceOnly(s.handleChatUpdate)) + mux.HandleFunc("POST /api/chat/update/defer", instanceOnly(s.handleChatUpdateDefer)) + mux.HandleFunc("POST /api/chat/update/install", instanceOnly(s.handleChatUpdateInstall)) } func (s *Server) Handler() http.Handler {