When a workspace agent requests external auth, it can send a `chat_id`
(from `CODER_CHAT_ID`) so the current git branch is linked to that chat.
`gitsync.Worker.MarkStale` trusted that ID and never checked that the
chat belongs to the agent's workspace. As a result, any workspace agent
could set the git branch, origin, and PR shown on another user's chat,
and the refresh worker would then fetch PR status with that chat owner's
git token.
`MarkStale` now ignores the request and logs a warning unless both the
requested chat and the root chat that receives the ref are bound to the
calling agent's workspace. Subagent chats are created with their
parent's `workspace_id` (`coderd/x/chatd/subagent.go`), so their
legitimate updates still reach the root chat. The root is checked too
because rebinding a chat's workspace does not rebind its existing
subagent chats. Both external-auth handlers in
`coderd/workspaceagents.go` pass the chat ID through `MarkStale`, so
this single check covers both.
Tests:
- `TestWorker_MarkStale_WithChatID` is now table-driven. A chat on the
same workspace is updated. A chat on another workspace, a chat with no
workspace, and a missing chat get no update and no event.
- `TestWorker_MarkStale_SubagentChatID_UsesRootChat` binds the chats to
real workspaces and adds two calls that must not reach the root: one
from another workspace using the child's ID, and one from the old
workspace through a child after the root is rebound to a new workspace.
- `TestWorker_MarkStale_StripsOriginCredentials` binds its chat to the
caller's workspace, since that test relied on the missing check.
Refs CODAGT-1420, SEC-856. Affects v2.32.0 onward; backports are needed
for every supported release line from 2.32.
<details>
<summary>Investigation notes</summary>
- Source of the chat ID: `agent/agentproc/process.go` sets
`CODER_CHAT_ID` in the process environment, and `cli/gitaskpass.go`
sends it as `chat_id`. Anyone with access to the workspace can set this
value.
- The path without a chat ID already filtered by workspace
(`GetChatsByWorkspaceIDs`); only the chat-ID path skipped the check.
- Open question from the issue (do child chats inherit `workspace_id`?):
yes, `CreateChatWithID` in `subagent.go` sets `WorkspaceID:
parent.WorkspaceID`.
- Edge case (from review): `UpdateChatWorkspaceBinding` rebinds only the
chat it targets, so a child can stay bound to the old workspace after
its root is rebound. Checking only the requested chat let the old
workspace write to the rebound root, so the root's workspace is checked
too.
- I did not add a second rejection in the handlers (optional item 3 in
the issue). `MarkStale` is the only consumer of the chat ID, and
rejecting there would change the external-auth response for git
operations.
</details>
> 🤖 Generated by Coder Agents on behalf of @deansheather.