mirror of
https://github.com/coder/coder.git
synced 2026-11-20 09:58:59 +08:00
25af21b5d5d86ab7d9253e1e72d33b2da170e4f8
4537
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
25af21b5d5 |
feat!: remove has_ai_task and the task build reasons (#29085)
Drops the `has_ai_task` column from `template_versions` and `workspace_builds` (with its index and view projections) and removes the three task build reasons (`task_auto_pause`, `task_manual_pause`, `task_resume`) from the `build_reason` enum. Existing rows are remapped before the enum swap: automatic pauses become `autostop`, manual pauses and resumes become `initiator`, and `workspace_build_orchestrations.child_reason` follows the same mapping. The query filters, provisionerdserver flag writes, and audit ignore entries for the column go with it. **Migration cost:** recreating `build_reason` rewrites `workspace_builds`. `TestMigration000593TaskBuildReasonRewriteTiming` seeds 1,000 workspaces, 100,000 builds (30,000 with task reasons) and 5,000 orchestrations and asserts the migration stays under a two-minute bound; locally it takes about 0.7 to 1.0 s. The test is skipped under `-short`. **Breaking change:** the down migration re-adds `has_ai_task` as `false` and restores the enum values; remapped reasons keep their new values. **Review changes:** the migration test now asserts only the row remaps (schema and enum introspection removed per review); renumbered from 000592 to 000593. **Stack context:** Coder Tasks removal stack (CODAGT-642): #28743 frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084 notifications → **#29085 build reasons** → #29086 tables → #28750 permissions. The last four PRs replace the single data-drop migration that used to live in #28750; each carries one concern and its own migration number. > Created by Xum (AI agent) on behalf of @ibetitsmike. |
||
|
|
f809776229 |
feat!: remove the task notification templates (#29084)
Removes the six Coder Tasks notification templates (their preferences and inbox history go with them via cascade) and the `preference_task_notification_alert_dismissed` user setting with its two queries. The `task` value of `ai_seat_usage_reason` stays: seats consumed through tasks remain consumed, and remapping their reason would misstate billing history. **Breaking change:** migration 000592 deletes data. The down migration restores the template definitions, not the deleted preferences or notification history. **Review changes:** dropped the `ai_seat_state` remap and enum swap and the migration unit test (both per review); moved the migration from 000591 to 000592 because main took 000591. **Stack context:** Coder Tasks removal stack (CODAGT-642): #28743 frontend → #28788 CLI → #28789 API → #28790 provisioner → **#29084 notifications** → #29085 build reasons → #29086 tables → #28750 permissions. The last four PRs replace the single data-drop migration that used to live in #28750; each carries one concern and its own migration number. > Created by Xum (AI agent) on behalf of @ibetitsmike. |
||
|
|
9cd38b5373 |
feat!: remove the Tasks API from coderd and codersdk (#28789)
Removes the Tasks API and task orchestration from coderd and codersdk: the `/api/v2/tasks` handlers, task middleware and search filters, task name generation, autobuild pause/resume logic, task notification enqueues, telemetry, and the codersdk task types. Regenerates apidoc, the API reference docs, and `typesGenerated.ts`. **Breaking change:** the Tasks API is removed; requests to `/api/v2/tasks` fail. Tasks was deprecated in v2.34. **Stack context:** Coder Tasks removal stack (CODAGT-642): #28743 frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084 notifications → #29085 build reasons → #29086 tables → #28750 permissions. The last four PRs replace the single data-drop migration that used to live in #28750; each carries one concern and its own migration number. **Why:** with the UI (#28743) and CLI (#28788) gone, this deletes the server surface. Database tables, RBAC, and notification templates stay until the top of the stack so every layer builds and migrates independently. **What to scrutinize:** - The `enable-ai-tasks` option is removed outright (review feedback): configs still carrying `enableAITasks` fail to parse until the key is deleted. - provisionerdserver now writes `HasAITask: false` on template/build flags; the column and these lines are dropped in #29085. - `codersdk.ResourceTypeTask` stays so audit logs recorded before the removal keep rendering. **Validation:** `go build ./...`, `go vet ./...`, `go test ./codersdk/...`, site biome and tsc, CLI goldens regenerated, pre-commit hooks. **Size:** +242/-10,792 over 76 files; additions are regenerated docs/goldens and test fixture updates. > Created by Xum (AI agent) on behalf of @ibetitsmike. |
||
|
|
42fcd332c6 |
fix: remove CORS from the OAuth2 authorization endpoint (#29143)
fix(oauth2): exclude authorization endpoint from permissive CORS - Apply standard CORS to `/oauth2/authorize`, with or without a trailing slash, as required by OAuth 2.1 §3.1. - Normalize repeated slashes before selecting the policy to prevent exclusion bypasses, including in wsproxy. - Preserve permissive CORS for other OAuth2 endpoints, discovery documents, and MCP. Same-origin consent behavior is unchanged. - Add middleware and router regression tests and update provider security docs. |
||
|
|
fef0763820 | feat: report template builder build failure reasons in telemetry (#28586) | ||
|
|
0aae890d03 |
feat: return per-app session counts from workspace agent stats queries (#29134)
- Make all six raw session-count queries return a session_counts JSONB object keyed by app name instead of fixed per-family columns. Fold the results into existing family fields in Go using the shared SDK registry, including unrecognized names under unknown. - Remove the registry parameters and associated dbauthz validation from these queries, which no longer perform family attribution in SQL. Preserve existing deployment stats, Prometheus, and telemetry outputs. - Select session maps directly in the two latest-row queries instead of decomposing and reaggregating a single row. Keep byte, connection, and latency aggregates independent of per-app expansion. - Add regressions for latest eligible rows, empty session maps, distinct same-family app names, labels, and unchanged traffic aggregates. |
||
|
|
da45488208 |
feat: attribute session counts by app family (#28337)
- Centralize app-to-family attribution in the SDK registry so recognized app aliases contribute to their family's session counts and usage minutes without duplicating name lists across SQL queries. - Pass the registry into agent stats queries, insights, and usage rollups. - Validate its structure in dbauthz so missing or renamed families fail explicitly instead of silently producing zero counts. - Decompose session maps once per row for per-agent sums while retaining the key-presence checks used by insights. Update reporting consumers and add coverage for alias attribution and registry validation. |
||
|
|
3ed8548e78 |
fix: unblock AI price book refresh for gpt-6-astra and qwen3.8-max (#29170)
The weekly `aigateway-prices-refresh` job [failed](https://github.com/coder/coder/actions/runs/34458761592) because two upstream-guard assertions in the generator tripped: models.dev now lists OpenAI's `gpt-6-astra` (so its `overrides.jq` injection must be dropped), and the curated OpenRouter `qwen/qwen3.8-max` identifier was renamed upstream to `qwen/qwen3.8-max-0902`. This removes the `gpt-6-astra` injection, repoints the qwen curation entry to `qwen/qwen3.8-max-0902` (with a `displayName` override to keep the clean "Qwen3.8 Max" label in the UI), and regenerates `prices.json` and `knownModelsGenerated.json`. Note: because the artifacts regenerate from live models.dev, this diff also carries unrelated upstream drift, the same content the scheduled refresh PR would produce. > [!NOTE] > Generated with Coder Agents on behalf of @ssncferreira. |
||
|
|
d8e3f4fcf7 |
feat: evict the oldest attachments at the chat file cap (#29063)
Closes CODAGT-933 Long agent sessions were hitting the 50 attachment cap, after which every upload, screenshot and `attach_file` call was rejected, so people were abandoning otherwise healthy chats. Rather than raise the cap (which just moves the cliff and multiplies the worst-case per-chat `bytea` storage), a chat now keeps its 50 most recent attachments. `LinkChatFilesAfterLock` deletes the oldest `chat_files` rows in the same statement and the cascade drops their links. Files in the incoming batch are never evicted, so the only remaining rejection is a single message with more than 50 files. Nothing in the product ever linked one file to two chats, so rather than guard the eviction against it, this adds `UNIQUE (file_id)` on `chat_file_links`, with the migration dropping any existing duplicates in favour of the oldest chat. Evicted attachments render as the existing "Attachment expired" tile. A `pinned` flag is the obvious follow-up if someone needs to keep a specific file around. |
||
|
|
1818844069 |
fix: ignore unrecognized parameters at the token endpoint (#29139)
fix(oauth2): ignore unrecognized token request parameters Align `/oauth2/tokens` with OAuth 2.1 §3.2 and `/oauth2/authorize` by ignoring unknown parameters and logging only their names at debug level, never values. Continue rejecting duplicate known parameters, with tests covering all nine and shared unknown-parameter inputs across both endpoints. Misspelled optional parameters are now ignored rather than returning 400. Changes are limited to `coderd/oauth2provider`, with no new endpoints or schema changes. Closes https://linear.app/codercom/issue/PLAT-577 |
||
|
|
716a3fdbfd |
fix: match OAuth2 redirect_uri against every registered redirect URI (#29014)
- Fix OAuth2 redirect validation to accept any registered URI, resolving Cursor’s rejection when using its second callback (fixes #28910; stacked on #29013). - Deduplicate primary and alternate callbacks, validate every registered entry, preserve primary-callback defaults and existing code-to-token redirect checks, and stop exposing registered URLs in errors. - Add regression tests and update documentation; defer admin removal of registered URIs (PLAT-619) and requiring redirect_uri when multiple URIs are registered (PLAT-620) to follow-ups. |
||
|
|
9f27e2b17c |
feat: let an OAuth2 refresh narrow the granted scope (#28751)
fix: honor scope narrowing on OAuth2 token refresh Allow `POST /oauth2/tokens` to mint an access token with the requested scope when covered by the consented grant. Narrowing affects only the new access token; the stored grant and rotated refresh token scope remain unchanged. Omitting `scope` uses the full grant. Validate scope names against the catalog, then compare permission coverage rather than set membership so `coder:all` grants can narrow. Reject unknown or uncovered scopes with `400 invalid_scope` without minting tokens or consuming the refresh token. Refresh still does not re-check the app's current allowlist. - Sanitize and cap token endpoint `error_description`, sharing the authorize path's length limit. - Rename the scope-coverage log field `allowlist` to `ceiling` and add `phase=refresh`. - Update provider docs for scoped refreshes, `invalid_scope`, composite scope caveats, and OAuth 2.1 draft -16. Part 1 of 3 for PLAT-481, the final phase of PLAT-470. |
||
|
|
74d1eef834 |
feat: support non-Anthropic models on Bedrock Mantle (#28404)
Migrates bedrock-typed provider construction to the standalone Bedrock provider introduced by #28420, then removes the legacy Bedrock behavior from the Anthropic provider. Existing provider and integration tests are updated to use the new type; legacy environment configuration preserves the `anthropic` route name while reporting provider type `bedrock`. Adds chatd model-ID inference for Bedrock providers: `anthropic.*` models keep the Anthropic Messages client, while other models use the OpenAI Responses client. BYOK header format follows the inferred wire shape. A credential-gated live integration test discovers the Mantle catalog from `/v1/models` and probes every model through the bridge. The `openai.gpt-oss-*`, `google.gemma-4-*`, and `xai.grok-*` families are documented as currently unsupported because Mantle serves them only on routes the prefix-based rules cannot reach. Depends on #28420. ## Smoke tests Validated against a local `develop.sh` server on August 22, 2026: - Coder Agents passed with Anthropic over InvokeModel, and Anthropic, OpenAI, and Mistral models over Mantle. - Claude Code passed the InvokeModel and Mantle Anthropic flows. - Crush passed all four flows, including Mantle OpenAI and third-party Chat Completions. Models tested: `us.anthropic.claude-sonnet-4-6`, `anthropic.claude-sonnet-5`, `openai.gpt-5.6-luna`, and `mistral.ministral-3-14b-instruct`. > Generated by Coder Agents |
||
|
|
d5e2ca74cd |
chore: rename recorderTranslation to DRPCRecorder (#29133)
The old name, `recorderTranslation`, did not clarify from what calls were being translated, nor to what they were being translated. The new name, `DRPCRecorder`, immediately explains that calls are being recorded over DRPC. This was a readability hurdle while trying to investigate touch points for AIGOV-358. This is the first step towards implementing either a /dev/null-esque recorder or a logging recorder as per the requirements in AIGOV-358. |
||
|
|
45fb985ce6 |
fix(coderd/database): exclude system users from AI budgets (#28698)
## Description Group AI budget totals counted system users, including the prebuilds user, even though they are excluded from the displayed member count. The budget queries now exclude system users when calculating group totals and over-budget user counts. ## Changes - Exclude system users from group AI budget totals. - Exclude system users from over-budget user counts. - Add database regression coverage. Closes https://linear.app/codercom/issue/AIGOV-595 > [!NOTE] > Generated by Coder Agents on behalf of @ssncferreira. |
||
|
|
8472a6884f |
chore!: remove env-based AI provider configuration (#29053)
> AI tools were used to create this PR Removes deprecated AI provider configuration through environment variables, CLI flags, and YAML. Deletion includes indexed providers and legacy OpenAI, Anthropic, and Bedrock options under both AI Gateway and AI Bridge branding, eg. `CODER_AI_GATEWAY_PROVIDER_<N>_*` or `CODER_AI_GATEWAY_ANTHROPIC_KEY`. Removes the associated startup-seeding code. Updates tests and documentation. **Breaking change:** Remove [obsolete AI provider CLI flags and YAML keys](https://coder.com/docs/ai-coder/ai-gateway/providers#database-management-of-providers) before upgrading, otherwise Coder will fail to start with an `unknown flag` or `unknown option` error. Provider environment variables are ignored and no longer seed the database. Existing database-stored provider configuration is preserved. |
||
|
|
0ad8eebbf7 |
fix: allow any port on loopback OAuth2 redirect URIs (#29013)
Fix: Allow variable ports for registered HTTP loopback redirect URIs (127.0.0.1, [::1], and localhost), enabling native apps to use dynamically assigned ports. Apply this registration-matching exception at both authorization and token endpoints while preserving the presented port. Safeguards: Keep all other URI components and non-loopback matching unchanged, and retain exact code-to-token redirect URI matching, including the port. Implementation and verification: Add shared matching logic, automated tests, and updated documentation. All 29 manual scenarios passed, although browser click-through to a listener on an OS-chosen port was not tested. |
||
|
|
96ee8d171a |
fix: make OAuth2 code redemption single-use under concurrency (#28744)
TL;DR Third PR in the PLAT-480 stack, on top of #28740. Fixes a race where the same authorization code could be redeemed twice concurrently. The redeeming delete now returns the deleted row. If another request already redeemed the code, the delete returns sql.ErrNoRows and redemption fails with invalid_grant. Each redemption runs in its own transaction, so concurrent requests serialize on the code row and only one succeeds. The test now races two concurrent redemptions to verify single-use behavior. No scope logic, new endpoints, or schema changes. Depends on #28740. Stack: #28237, #28740, this PR. |
||
|
|
150c680a4b |
fix: return MCP server tool execution errors as tool results (#29051)
Coder's MCP server currently sends most tool execution failures as
top-level JSON-RPC errors. The underlying error text is transmitted like
this:
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32603,
"message": "workspace name cannot be empty"
}
}
```
Not all clients handle it well, and some may return a generic "MCP tool
request failed." to the model instead of passing the details as tool
output.
This PR starts returning execution failures as tool results with
`isError: true` and descriptive content like this:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"isError": true,
"content": [
{
"type": "text",
"text": "workspace name cannot be empty"
}
]
}
}
```
This should make the MCP server work better across a broader range of
MCP clients.
|
||
|
|
d544f394d4 |
fix(coderd): keep parameter values when the render is incomplete (#29108)
Closes #29099 ([ENG-3324](https://linear.app/codercom/issue/ENG-3324)). Follow-up to #29102, which stopped the loss propagating through stop builds but left start builds truncating. ## What this does A render carrying a `module_not_loaded` diagnostic could not see the whole template, so a parameter's absence from it is not evidence the template stopped declaring that parameter. Keep the unmatched values instead of deleting them. ## Why preserve rather than fail provisionerd resolves modules itself, so only coderd's render is degraded. Keeping the value produces a correct apply and the workspace keeps building. Failing the build would turn silent data loss into an inability to start every workspace on an affected template version. A complete render is still authoritative and still narrows the set, so unrelated warnings and legitimate parameter removals behave exactly as before. ## Tests - `TestResolveParameters/IncompleteRender`: complete render drops, `module_not_loaded` preserves previous and build values, unrelated warning drops. - `TestDynamicParametersModuleCachePurged` now continues into the start build. On `main` it fails with `start build must not drop the module parameter`. <details> <summary>Notes for the reviewer</summary> ### Detection `preview` tags the warning with `types.DiagnosticCode(diag, types.DiagnosticModuleNotLoaded)`, so the check is `previewtypes.ExtractDiagnosticExtra(diag).Code == previewtypes.DiagnosticModuleNotLoaded` over the second render's diagnostics. Adding future completeness codes is a one-line change in `incompleteRender`. ### Departure from the issue's sketch The issue proposed also gating on `v.Source != sourceDefault`, to keep discarding values that only ever came from a default. That check cannot fire: `sourceDefault` is only assigned to parameters present in the render output, so an unmatched value is never default-sourced. A default stored by an earlier build arrives as `sourcePrevious` and is indistinguishable from user input at this layer. The condition is omitted rather than left in as dead code. ### Not covered Nothing surfaces the degraded render to the operator. `wsbuilder` has no logger, and `render.go` still discards preview's diagnostics (`Logger: slog.New(slog.DiscardHandler)`). That is the follow-up work listed in the issue. </details> --- 🤖 Authored by Coder Agents on behalf of @Emyrk. |
||
|
|
36ea6eaf80 |
fix(coderd): do not narrow the parameter set on non-start builds (#29102)
Fixes part of #29099 ([ENG-3324](https://linear.app/codercom/issue/ENG-3324)). ## What this does Only a start build may narrow the stored set. A stop or delete build does not change which parameters a workspace has. ## Why A stop or delete build re-resolves the workspace parameters and deletes every stored value the render did not return. - When a template version's `cached_module_files` is NULL the renderer cannot load modules, and the parameters are dropped. Any `restart` or `coder update`, uses the broken version for `stop` and all parameters are removed before the fixed `start`. - This can happen on any broken template version ## Scope This does not fix a start build that resolves against a version with a NULL module cache, which still truncates. That is the completeness-aware discard loop described in the issue, and it lands separately. ## Tests - `TestResolveParameters/UnmatchedValues` covers all three transitions at the resolver level. - `TestDynamicParametersModuleCachePurged` is an end-to-end regression test: create a workspace with a module declared parameter, remove the module cache, stop, and assert the value survives. It fails on `main`. <details> <summary>Implementation plan</summary> ### Problem `dynamicparameters.ResolveParameters` ends with an unconditional discard loop (`coderd/dynamicparameters/resolver.go`) that deletes every stored value whose parameter is absent from the render output. With a NULL module cache the render is incomplete, `preview` reports `module_not_loaded` at warning severity, and the reduced parameter set is treated as authoritative. `wsbuilder.getParameters()` is transition-agnostic, so a stop build persists that truncated set. `cli/update.go` stops first against the workspace's current version, then starts against the active version, and the start build reads the truncated set via `getLastBuildParameters()`. ### Coverage | Case | Fixed here | |---|---| | `coder update`, old version purged, active version healthy | yes | | Workspace sits on a purged version, autostop then autostart | no, needs the discard loop fix | | `require_active_version` where the active version is purged | no, needs the discard loop fix | ### Changes 1. `resolver.go`: gate the discard loop on the build transition. Ephemeral trimming, immutability, monotonicity, and default backfill are unchanged. 2. `wsbuilder.go`: pass `b.trans`. Single non-test caller. ### Deliberate calls - `delete` is treated like `stop`. Neither transition changes which parameters a workspace has, and it keeps the condition to one comparison. - The transition is passed rather than a second boolean flag, so the call site stays unambiguous next to `firstBuild`. </details> --- 🤖 Authored by Coder Agents on behalf of @Emyrk. |
||
|
|
c12355d6e5 |
fix(coderd/x/chatd): carry unanswered user messages through compaction verbatim (#28645)
Fixes [CODAGT-737](https://linear.app/codercom/issue/CODAGT-737/compaction-can-treat-the-last-user-message-as-an-assistant-message) ## Problem Auto-compaction can trigger on a turn whose last history message is a fresh, unanswered **user** message. Two things go wrong: 1. The summary instruction is appended as another user message. Providers that merge consecutive same-role messages (verified against fantasy's Anthropic conversion) fuse it with the user's message, and the summarizer misattributes the user's instruction as assistant intent. 2. After compaction the original user row falls outside the prompt window, so the instruction survives only through summary fidelity. ## Fix Carry unanswered trailing user messages through compaction verbatim instead of summarizing them. All logic lives in `chatd`; `chatloop` is unchanged apart from prompt wording. - **Prepare** (`generation_preparer.go`): `pendingUserSegmentStart` locates the trailing user rows on the persisted rows, before provider-switch sanitization (which can drop the assistant row separating them from an already-answered message). Head and tail are converted separately so the summarizer input excludes the tail exactly. Falls back to summarizing everything when no usable segment exists. - **Commit** (`buildCompactionMessages`): replays the tail after the boundary trio as uncompressed, model-only user rows. The existing prompt window query includes them; no SQL, UI, or turn-guard changes. Replay rows carry no usage, so compaction cannot immediately re-fire. - **Prompt** (`chatloop/compaction.go`): the summary prefix no longer claims the assistant "was actively working", which is false in this case. The summarizer prompt is unchanged. - `ARCHITECTURE.md` compaction section updated. ## Testing `go test ./coderd/x/chatd/...` green. New: `TestBuildCompactionMessages_ReplaysPendingUserMessages`, `TestPendingUserSegmentStart`, `TestPendingUserSegmentConversionEquivalence`, `TestPendingUserSegmentDerivedBeforeProviderSwitchSanitization`, `TestDecisionGeneratesAfterCompactionWithReplayedPendingUser`. <details> <summary>Root-cause repro</summary> Replaying the reported scenario through fantasy's Anthropic provider against a capture server: ``` === fantasy prompt (roles as chatd builds them) === [2] role=user "You'll hit compaction now, we'll need to go through some fin..." [3] role=user "You are performing a context compaction. Summarize the conve..." === wire request to Anthropic === [2] role=user, 2 content block(s) block[0]: "You'll hit compaction now, we'll need to go through some final checks..." block[1]: "You are performing a context compaction. Summarize the conversation so..." ``` </details> --- 🤖 This PR was generated by Coder Agents on behalf of @f0ssel. |
||
|
|
257c6f1dca |
refactor: move shared AI model UI into modules/aiModels (#29040)
> 🤖 Refactoring with Cursor.
AI settings was importing model form fields, ModelSelector, and
ProviderIcon from AgentsPage. Those now live in
`site/src/modules/aiModels`.
No user-facing behavior change.
- Move ProviderIcon, ModelSelector, and the model admin form fields into
`modules/aiModels`
- Point AgentsPage and AI settings at the new paths
- Drop the leftover ChatModelAdminPanel ProviderIcon duplicate and the
knownModels barrel
- Update the known-models catalog generator paths
|
||
|
|
90c7533204 |
perf: store workspace agent session counts as JSONB (#28126)
Replace fixed session_count_* columns with a sparse session_counts JSONB object so new session types require no schema changes. Convert retained and unrolled-up activity, warning on backlogs spanning more than 24 hours. Update batching, queries, and rollups while preserving existing API shapes and compatibility with older agents. Add migration, query, and batcher coverage. |
||
|
|
fcaa14f456 |
fix: validate mcp input (#28702)
Addresses [CODAGT-994](https://linear.app/codercom/issue/CODAGT-994/return-validation-errors-for-invalid-mcp-tool-arguments). The MCP server currently does not validate tool call arguments against the MCP JSON schema. Additionally, when a client passes invalid arguments to a Coder MCP server tool call, currently the server returns only: ```json { "error": "MCP tool request failed." } ``` In this PR we start validating arguments and returning an informative validation error instead: ```json { "error": "invalid arguments: ...", "expectedSchema": { ... } } ``` |
||
|
|
dc1faecbf8 |
test: bind more server tests to loopback (#29042)
Follow up to https://github.com/coder/coder/pull/28980. The tests modified in this PR have the same flake potential as the test fixed in #28980. Fixes https://linear.app/codercom/issue/PLAT-583/flake-testserveryamlwritethenreadconfig |
||
|
|
ac824cd235 |
chore(coderd): remove dead code from chatd (#29008)
Removes production code in `coderd/x/chatd` that nothing reaches, the tests that only existed to exercise it, and option/config fields that callers filled in but chatd never read. No runtime behaviour changes; the only edits outside `coderd/x/chatd` drop the now-nonexistent fields at their three call sites (`coderd/coderd.go`, `coderd/exp_chats.go`, `coderd/coderdtest`). Net: 42 files, +147 / -1065. Verification method for every item: `golang.org/x/tools/cmd/deadcode` (with and without `-test`) rooted at `cmd/coder`, `enterprise/cmd/coder` and every package that imports chatd; a `go/packages` pass counting `TypesInfo.Uses` per declared type, const, var, field and method across the same roots, split into test and non-test use sites, plus a read-vs-write split for struct fields; `rg` over the whole repo including `site/src` for json tag names; then `go build ./...`, `go vet ./coderd/x/chatd/...`, `golangci-lint run ./coderd/x/chatd/... ./coderd/ ./coderd/coderdtest/`, and `go test ./coderd/x/chatd/...` (all 20 packages) locally. <details> <summary>Evidence per deletion</summary> | Removed | What it was | Why unused | |---|---|---| | `subagent.go` `resolveConfiguredModelOverride`, `parseModelOverride`, `parsedModelOverride` (~135 lines) + `TestResolveConfiguredModelOverride_*`, `TestParseModelOverride` | raw-string model override resolver | Only callers were its two tests; production resolves overrides through `resolveOrganizationModelOverride` (`title_override.go`, `compaction_override.go`, `subagent.go`). | | `chatd.go` `removeSkillIndexMessages`, `isSkillIndexMessage` + `TestSkillIndexRefreshReplacesStaleAliases` | skill-index refresh helpers | Zero production references; the test simulated a refresh path no production code performs. | | `chatd.go` `chatMessage`, `newChatMessage`, `withCreatedBy`, `appendMessageFields`, `BuildSingleChatMessageInsertParams` (~90 lines) | insert-params builder | Exported, but every caller was a `chatd_test` file (6 sites). Replaced by a 25-line `singleChatMessageInsertParams` helper in `chatd_helpers_test.go`. | | `chatd.go` `Server.closeInflightAdmission` | one-line wrapper around `inflightClosed.Store(true)` | Single call site (`Close`); inlined. | | `chatd.go` `Server.workerID`, `instructionLookupTimeout`, `pendingChatAcquireInterval`, `maxChatsPerAcquire`, `chatHeartbeatInterval` | Server struct fields | Assigned in `New` and never read anywhere (the values reach the worker through `chatWorkerOptions`, not these fields). | | `Config.InstructionLookupTimeout`, `homeInstructionLookupTimeout`, `coderd.Options.ChatdInstructionLookupTimeout`, `coderdtest.Options.ChatdInstructionLookupTimeout` | timeout plumbing | The value only landed in the dead `Server.instructionLookupTimeout`; no CLI flag sets it and nothing reads it. | | `PromoteQueuedOptions.CreatedBy` | option field | Set by `coderd/exp_chats.go` and three tests, never read in chatd (promotion keeps the queued row's `created_by`). | | `SubmitToolResultsOptions.DynamicTools` | option field | Set by `coderd/exp_chats.go` (which re-read `chat.DynamicTools` just to pass it) and three tests, never read in chatd. | | `attachments.go` `buildAssistantPartsForPersist` (whole file) | assistant part builder | Stale copy left by #26270; production uses `buildAssistantParts` in `message_conversion.go`. Its six tests were retargeted to the live function (now `message_conversion_internal_test.go`) and a dead-copy assertion in `subagent_internal_test.go` was dropped. | | `chatloop.RunOptions` (94 lines) | old loop options struct | Only two of 23 fields were ever populated, for one internal call to `prepareMessagesForRequest`, which now takes `model, logger` directly and no longer returns the ignored canonical slice. `GenerateAssistantOptions` / `ExecuteLocalToolsOptions` are the live types. | | `chatloop.ErrDynamicToolCall`, `ErrStopAfterTool`, `PendingToolCall`, `PersistedStep.PendingDynamicToolCalls` | dynamic-tool exit protocol | Zero references outside their declarations (one stale comment in `chatdebug/service.go` updated). | | `chatloop.CompactionOptions.Persist`, `.OnError` | callbacks | `Persist` had zero references; `OnError` was set only by two tests that asserted it was never invoked. | | `chatloop` `stepResult.shouldContinue` + its computation | flag | Written once, never read. | | `chatloop.StateWaiting` | metric label const | Zero references. | | `generation.go` `generationOutcome.InsertedMessages`, `runnerActionMessage` | outcome field | Built on every commit, never read. | | `chatstate` `ExecutionState.IsArchived`, `AllOwnershipStates`, `OwnershipState`/`StateU`/`StateO`, `TransitionAcquire` | state-machine leftovers | Zero references (the ownership consts became dead once `AllOwnershipStates` went). | | `chatstate` `ExecutionState.QueueNonEmpty` | predicate | Only referenced by the test asserting its own table; the sibling `IsRunnable` check in that test is kept. | | `chatdebug.Attempt.RetryClassification`, `.RetryDelayMs` | json fields | Never assigned anywhere, `omitempty`, and `retry_classification`/`retry_delay_ms` do not appear in `site/src` or `typesGenerated.ts`. | | `chatdebug.RunContext.Kind`, `StepContext.HistoryTipMessageID`, `RecorderOptions.Provider`/`.Model`, `stepHandle.opts`/`.usage`/`.err` | context/handle fields | Written (from `chatd.go`, `chatloop/compaction.go`, `modelcall.go`, `recorder.go`) and never read. The DB run row keeps its own `kind` column. | | `chatprovider.MergeProviderAPIKeys` + `TestMergeProviderAPIKeys_PreservesProviderRegions` | key merge | Superseded by `ResolveUserProviderKeys`, whose region test already covers the same behaviour. | | `chatprovider` `providerCreationError` | one-line `xerrors.Errorf` wrapper | Single call site; inlined with identical message. | | `chatretry.IsRetryable` | classifier wrapper | Zero references. | | `computeruse.IsTool` + `TestComputerUseTool` | one-line forwarder to `fantasyopenai.IsComputerUseTool` | No production caller; two test assertions now call the fantasy function directly, and the dropped test only asserted the library's own constructor. | | `chatprompt.ToolResultToPart` | one-line forwarder to `codersdk.ChatMessageToolResult` | Single call site; inlined. | | `subagent_catalog.go` `formatSubagentDefinitions` | forwarder with `nil` overrides | Single call site; inlined. | | `worker.go` `chatWorker.chatWorkerID` | getter | Only tests called it; they read `opts.WorkerID` directly now. | | `chattest.AnthropicErrorResponse`, `OpenAIServerErrorResponse`, `ChatMessageWithParts` (`messages.go` removed) | test fixtures | Zero references. | | `chattest` `AnthropicRequest.Options`, `OpenAIRequest.Options` | `json:",inline"` map fields | `encoding/json` has no inline tag (the TODO on each said so); never populated, never read. | </details> <details> <summary>Considered and kept</summary> - `chatstate.CreateChat` (test-only thin wrapper over `insertChat`, production uses `CreateChatWithID`): documented package API with 25 test call sites; not worth the churn. - `chatprompt.MarshalContent` / `MarshalToolResult`: test-only, but they deliberately produce legacy-format DB rows so the read path's legacy handling stays covered. - `chatstate.AllowedExecutionTransitionsFrom` / `AllowedInputStates` / `AllowedExecutionTransitionOutputs`, `chatdebug.StepFromContext`, `WithClock`, `WithStaleThreshold`, `WaitUntilIdleForTest`, `PublishBuffer.BufferedChannels`, `chattool.NewWorkspaceMCPTool`: test seams that tests actively use to reach otherwise unexported state. - `AgentCapacityLimiter` interface (one production implementation): tests inject fakes. - `applyHookResultMessages` / `appendHookResultMessages`: a named pair over one placement enum, both used. - Nil-receiver guards on `*Metrics`, `*Result`, `*streamSyncPoller`, `*runnerDebugTurn`: nil is a supported "disabled" value on those paths. - Tests flagged by heuristics as assertion-light (`TestNopMetrics_DoesNotPanic`, `TestStepHandleFinish_NilHandle`, `TestRetry_OnRetryNilDoesNotPanic`, the `chatstate` synthetic-cancellation tests that assert through helpers): they cover real nil-safety or delegate assertions to helpers; kept. </details> <details> <summary>Out-of-scope findings (not changed here)</summary> - `chatdebug.Service.FinalizeStale` has had no production caller since #26270 removed the background sweep loop; only its tests call it, and comments in `chatd_debug.go` and `database/querier.go` still describe the loop. Deleting it would erase the implementation a fix needs, so it is left for a decision. - `coderd_chatd_chats` (gauge) and `coderd_chatd_stream_buffer_dropped_total` (counter) are registered and documented in `docs/admin/integrations/prometheus.md` but never set or incremented in production; `Metrics.RecordStreamBufferDropped` is test-only. Removing them changes the exported metric set and the docs, so they are left alone. </details> ## Declined review findings None yet. > Xum (AI agent) opened this PR on behalf of @ibetitsmike. |
||
|
|
52142e6e94 |
fix(coderd/templatebuilder): strip prerequisite markers from delivered README (#28953)
## Problem Template builder base READMEs delimit their prerequisites section with HTML comment markers (`<!-- prerequisites:start -->` / `<!-- prerequisites:end -->`). `ExtractPrerequisites` uses these to populate the builder's Prerequisites step, which works correctly. However, `Compose` embeds the **full** base README verbatim into the generated template's tarball. Because `react-markdown` renders raw HTML comments as literal text, the markers were visible when the delivered README is viewed via `MemoizedMarkdown`. <img width="876" height="586" alt="Screenshot 2026-09-03 at 3 28 08 PM" src="https://github.com/user-attachments/assets/70353ee2-1ff6-4e70-9b5d-7ac0521b945f" /> ## Fix Strip the prerequisite markers from the README before writing it into the tarball (Option 2), keeping the change contained to the template builder and leaving global markdown rendering untouched. - `prerequisites.go`: new `StripPrerequisiteMarkers` removes each marker line (plus an optional trailing blank line so no gap is left) while preserving the content between them. - `compose.go`: new `composedReadme` helper applies the strip in both `Compose` return paths; returns `nil` for an empty README, preserving the existing "omit README.md when empty" behavior. - `ExtractPrerequisites` still reads the markers from the source `BaseReadme`, so the builder's Prerequisites step is unaffected. ## Testing - `TestStripPrerequisiteMarkers` covers both markers, no markers, single markers, missing trailing blank line, and end-of-file cases. - Extended the compose test to assert the delivered README contains no marker text. - `go test ./coderd/templatebuilder/`, `go vet`, and `golangci-lint run ./coderd/templatebuilder/...` all pass. <details> <summary>Approach considered</summary> Two options were on the table: 1. Skip HTML comments in the shared `MemoizedMarkdown` component (fixes any stray comment globally, but changes shared rendering behavior app-wide). 2. Strip the markers from the README before inserting it into the template zipball (targeted; markers have no purpose in the delivered README since prerequisites are already extracted separately). Option 2 was chosen for being contained and easily unit-tested. </details> --- _This PR was created by Coder Agents on behalf of @jeremyruppel._ --------- Co-authored-by: Andrew Aquino <dawneraq@gmail.com> |
||
|
|
a6938e69db | fix: re-resolve PR when stored URL's branch is stale (#28983) | ||
|
|
9f7d08a26d | fix: default chat compaction threshold to 30% for large-context models (#28899) | ||
|
|
9cd66d3773 | feat: add GPT-6 Astra to the known models catalog, price book, and chatd (#28955) | ||
|
|
ced03dc30b |
fix(coderd/x/chatd): avoid closing poller hint channels (#28746)
Closes SEC-515 Prevent a `send on closed channel` panic when a chat stream unregisters during polling. The poller no longer owns or closes subscriber channels. This is safe because delivery is guarded by the stream context, and unregister removes the subscriber from future polls. |
||
|
|
07f9018c61 |
feat: re-check the app allowlist at OAuth2 code redemption (#28740)
**TL;DR** Second of the PLAT-480 stack. #28237 made the negotiated scope bound the issued token; this PR makes a narrowing of an app's registered scopes apply to codes that were already issued. | PR | What it does | |---|---| | #28237 (merged) | Mints access tokens with the negotiated scope, so a grant for one scope stops behaving as full access, and reports the granted scope per RFC 6749 §5.1. | | **#28740 (this)** | Re-checks the code's scope against the app's registered scopes at redemption, closing the ten minute window in which a narrowing was ignored. | | #28744 | Makes code redemption single-use under concurrency. Carries no scope logic and is independent of this PR. | - #28237 has merged, so this targets main. - No new endpoints and no schema change. --- An authorization code is valid for ten minutes, and its scope is checked against the app's registered scopes exactly once, when the code is issued. A registration narrowed inside that window had the narrowing ignored: the code still redeemed for a token carrying the wider scope. - The token exchange re-checks the code's scope against the registration as it stands at redemption and refuses with `invalid_grant`. RFC 6749 §5.2 reserves `invalid_scope` for the scope the client asked for, and this one comes from the stored grant. - The check is coverage rather than membership, and reuses the comparison the authorize endpoint already runs. That comparison now goes through a new `rbac.FirstScopeNotCovered`, which expands the allowlist once rather than once per granted scope. - Only the client can change its registered `scope`, through RFC 7592; no administrator surface writes the column. The re-check reflects the registration at redemption rather than constraining the client. - Refresh keeps the scope originally granted. That is a product choice, not an RFC requirement: a narrowing applies at the next authorization rather than mid-session, so tightening an app's scopes does not break integrations already running. - Codes issued before migration 000569 carry `coder:all`. For an app registered with a narrower `scope` those are refused at redemption until they expire, at most ten minutes. Stack: #28237 (merged), this PR, #28744. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
156c8b6e41 |
fix: prevent coderd crashes from unsupported Tailnet RPCs (#28429)
Workspace agents could call RefreshResumeToken and WorkspaceUpdates, even though agent connections do not configure the providers those RPCs require. The resulting nil dereference panicked a DRPC handler and crashed coderd. Limit the agent Tailnet surface to its supported RPCs, return `Unimplemented` when optional providers are absent, and recover panics in Coder-owned DRPC servers so they return an internal error instead of crashing the process. Refs: https://linear.app/codercom/issue/PLAT-464 |
||
|
|
68ca033d67 |
fix: deliver the rest of the invalid_request class to the client (#28736)
**TL;DR** Fifth of the stack, split out of #28045. #28450 delivered the errors raised *after* the callback is trusted and left the parameter failures behind. This PR delivers those, and replaces the implicit ordering that decided where an answer went with an explicit classification. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. | | #28178 | The authorize endpoint negotiates the scope against the app's allowlist and persists it on the code. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's callback. | | #28450 | The same delivery for every other error raised once the callback is trusted. | | **#28736 (this)** | The parameter failures #28450 left behind, and the classification that decides where each answer goes. | - Stacked on #28450. Review that first. - Nothing about what a token can do changes here. This is delivery, not enforcement. **Contract change** A rejected parameter now arrives at the app's registered callback with `error=invalid_request`, a description naming every failing field, and the request's `state`. Both verbs. | Verb | Was | |---|---| | GET | static "Invalid Query Parameters" page, 400 | | POST | `WriteOAuth2Error`, 400 | An integrator watching for either now reads the error from its own callback instead. **Two failures still answer on Coder**, because in neither case is the callback trustworthy yet: - A `redirect_uri` that does not parse, or does not exactly match the registration. Redirecting to it would defeat the check that just rejected it. - A `client_id` sent more than once, or naming something other than the app the callback was matched against. Coder cannot tell whose registration it is about to redirect to. An absent query `client_id` is **not** in that group. `httpmw` also reads the POST form body and the §2.3.1 Basic credential, so an absent query parameter still names a client and its failure is deliverable. **Precedence change.** An app whose *registered* callback does not parse, or uses a rejected scheme, now answers 500 even when the request also carries parameter errors; that used to answer 400. Decided before any parameter is read, so the others are never detected. Only reachable for an app row that bypassed registration. `DangerousCallbackSchemeOutranksParseFailure` pins it. **Also in this PR** - **Unrecognized parameters are ignored**, as §3.1 requires, rather than rejected by `ErrorExcessParams`. An OIDC `nonce` or a vendor extension no longer fails the request. Repeats of parameters the endpoint does read are still rejected. - **Every unsupported `response_type` gets one code.** Read as text rather than through the SDK enum, so a value with no Go constant behind it answers `unsupported_response_type` like `token` does, instead of splitting on whether the SDK names it. - **A malformed `resource` answers `invalid_target`** (RFC 8707 §2), but only when nothing else failed. A client retrying on `invalid_target` would otherwise resend a request still broken in a field it never heard about. - **`error_description` is bounded and readable.** Capped at 2048 characters and marked `(truncated)` before the log field or the `Location` header is written. Entries read `field: reason` joined with `; `, not the parser's debug shape, whose details contain commas and cannot be split apart again. - **A repeated `state` is charged to the client, not the callback.** Reading `state` shares a function with the `redirect_uri` match, so it used to fall into that carve-out and answer on Coder. **Where in the OAuth Flow** <details> <summary>Diagram: the three-way dispatch, and what licenses a redirect</summary> ```mermaid flowchart TD NEW["newAuthorizeResponse<br/>parses the registered callback, checks its scheme,<br/>exact-matches any redirect_uri, reads state"] NEW -->|"registration unusable"| C500["500 on Coder<br/>server_error, value logged not echoed"] NEW --> PARSE["extractAuthorizeParams<br/>reads every parameter, collects all failures"] PARSE -->|"no failure"| OK["GET: consent page<br/>POST: authorization code"] PARSE -->|"failure"| KIND{"authorizeFailure.kind()"} KIND -->|"corrupt registration"| C500 KIND -->|"redirect_uri or client_id at fault"| CODER["400 on Coder<br/>RFC 6749 4.1.2.1 carve-out"] KIND -->|"anything else"| CLIENT["302 to the callback<br/>invalid_request or invalid_target, with state"] ``` </details> - Authorize endpoint only, both verbs. Token exchange, refresh, and revocation are untouched, and `ErrorExcessParams` still guards the token endpoint. - `validatedCallbackURL` becomes `authorizeResponse`, built only by `newAuthorizeResponse`, which runs the scheme check and the exact match in that order. Holding one is what licenses a redirect, so the ordering is structural rather than a convention each call site remembers. - The scheme is checked on the *registered* URL, since `p.RedirectURL` returns the client's URI on a mismatch and checking that would blame the app for a request it never made. - `state` moves onto the type, out of the parameter lists of `withQuery`, `errorURL`, `codeURL`, and `redirectAuthorizeError`, so no call site can emit a response the client cannot correlate. - `extractAuthorizeParams` returns one `authorizeFailure` instead of two trailing values, and both handlers dispatch on `kind()` rather than re-deriving precedence from field checks. **What it satisfies** - RFC 6749 §4.1.2.1: a failure that is not a bad redirection URI or client identifier is reported through the redirection URI. That is the whole PR. Its two exceptions "MUST NOT" be redirected to, hence the carve-outs. - RFC 6749 §3.1: unrecognized parameters MUST be ignored, and no parameter may appear more than once. Both now hold here. - RFC 6749 Appendix A: `error_description` is confined to the permitted set, on the decoded value. - RFC 8707 §2: a `resource` that is not an absolute URI without a fragment answers `invalid_target`. - RFC 7636 §4.4.1: a malformed `code_challenge` is rejected at the authorization request rather than deferred to token exchange, where the error would point at the `code_verifier`. - Not yet: CRF-26 (the `server_error` sites) and CRF-13 (fragment delivery), both as in #28450. **Docs and Swagger.** `docs/admin/integrations/oauth2-provider.md` gains entries for the redirected parameter errors, `invalid_target`, and the two failures that stay on Coder. Both authorize verbs document their 400 and 500 responses and stop advertising `response_type=token`, which meant declaring the parameter as a `string`, since `Enums` appends to what swaggo derives from the type. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Fifth of the stack, stacked on #28450. ## Manual Tests Verified by hand against a local dev deployment (`v2.37.0-devel+1145d35a47`, dev Postgres), in addition to the automated suite. The build string was checked first, because `develop.sh` builds from whatever the tree held when it started and every result below would otherwise be describing the wrong binary. Two scenario groups need state the API cannot produce. The scope allowlist is reachable only through dynamic client registration, which was enabled for the run and disabled again at the end. A registered callback that does not parse, or that uses a blocked scheme, is refused at registration, so those rows were planted directly with `psql` on a purpose-built client and restored afterwards. **28 scenarios, all passing.** No correctness or security defect was found in the code this PR changes. Seven observations came out of the run: six are consistency, documentation or diagnosability points, and one is a small defect that predates this PR. <details> <summary><b>Scenario summary, all 28</b></summary> | # | Scenario | Result | |---|----------|--------| | 1 | A well-formed request still succeeds on both verbs, and the consent page renders | Pass | | 2 | A rejected parameter now reaches the client's callback on `POST` | Pass | | 3 | The same on `GET`, and the consent page does not render first | Pass | | 4 | The description names every failing field, joined with `; ` | Pass | | 5 | A mismatched `redirect_uri` is answered on Coder with no `Location` on either verb | Pass | | 6 | An unparseable `redirect_uri` likewise, and the echoed value is HTML escaped | Pass | | 7 | A repeated `client_id` is answered on Coder although the callback was valid | Pass | | 8 | A single query `client_id` cannot disagree with the resolved app over HTTP | Pass | | 9 | A `client_id` supplied only in the `POST` form body is delivered, not withheld | Pass | | 10 | A `{UPPERCASE}` `client_id` is delivered, and also succeeds end to end | Pass | | 11 | A repeated `state` is delivered rather than charged to the redirect carve-out | Pass | | 12 | A registered callback with a blocked scheme answers 500 on both verbs | Pass | | 13 | An unparseable registered callback answers 500, indistinguishably to the caller | Pass | | 14 | Corrupt registration outranks a deliverable failure and both carve-outs | Pass | | 15 | The corrupt value is logged with the app ID and never appears in a response | Pass | | 16 | Restoring the row restores normal behaviour with no restart | Pass | | 17 | Every unsupported `response_type` gets one code; an empty one is `invalid_request` | Pass | | 18 | An unsupported `response_type` is not recast as a missing `code_challenge` | Pass | | 19 | Unrecognized parameters are ignored, including a case-variant `REDIRECT_URI` | Pass | | 20 | A misspelled `redirect_url` is ignored and cannot smuggle a destination | Pass | | 21 | Repeated known parameters are still rejected | Pass | | 22 | `resource` answers `invalid_target` alone and `invalid_request` in company | Pass | | 23 | A fragment in `resource` is rejected | Pass, with one gap | | 24 | A long description is capped at 2048 and marked `(truncated)`, on both verbs | Pass | | 25 | The description is sanitized to the RFC 6749 §4.1.2.1 character set | Pass | | 26 | The registered callback query is retained except the reserved names | Pass | | 27 | Scope rejections still reach the callback, and no consent page renders | Pass | | 28 | Declining consent carries `access_denied` and issues no code | Pass | </details> <details> <summary><b>Observations, all 7</b></summary> | # | Observation | Severity | |---|-------------|----------| | 1 | `invalid_request` is returned in three description shapes: the parser's `Invalid query params: field: reason; ...` aggregate, the PKCE validator's single message, and `scopeFailureResponse`'s. A client cannot parse all three with one rule. | Consistency, reviewer call | | 2 | The phase 2 runbook for #28045 asserts the old `field: x detail: y` message shape, which this PR replaces. That doc needs a one-line update. | Docs follow-up | | 3 | `clientIDInDoubt`'s `default` branch is unreachable over HTTP, because `httpmw` derives `app.ID` from the same query value the parser reads. Defensive rather than dead, but the comment does not say so. | Comment clarity | | 4 | A `POST` supplying `client_id` only in the form body always fails with `client_id ... is required and cannot be empty`, naming a parameter it did supply. `httpmw` reads the body, `RequiredNotEmpty` reads the query. Pre-existing. | Misleading diagnostic | | 5 | A misspelled parameter is invisible from every angle at default verbosity. The client gets a 302 with a code, its redirect is silently replaced by the registered one, and the `ignoring unrecognized authorization parameters` line is `logger.Debug` so it is not emitted. | Diagnosability | | 6 | `resource` sent twice answers `invalid_target` rather than `invalid_request`. RFC 8707 §2 frames `invalid_target` as being about the resource value; a duplicated parameter is a malformed request under RFC 6749 §3.1. | Low, error code choice | | 7 | `resource=https://api.example.com/#` (trailing `#`, empty fragment) is accepted and stored with the `#` intact, so the persisted audience is not textually equal to the fragment-free form. `url.Parse` maps empty and absent fragments both to `Fragment == ""`. Pre-existing, in `tokens.go`. | Defect, low severity | </details> **One note for anyone re-running this.** Every request below depends on `$CHALLENGE` from the most recent `new_pkce` call. Forgetting to call it sends an empty `code_challenge`, which fails with the fixed "is required and cannot be empty" message at 98 characters and looks exactly like a cap or a validator failing to fire. That cost one wrong measurement during this run before the numbers below were taken. <details> <summary><b>Shell helpers used throughout</b></summary> ```bash export BASE_URL=http://localhost:3000 export AUTH_HEADER="Coder-Session-Token: $(cat ./.coderv2/session)" export PGPASSWORD=$(cat ./.coderv2/postgres/password) export PGPORT=$(cat ./.coderv2/postgres/port) pg() { psql -h localhost -p "$PGPORT" -U coder -d coder -tAc "$1"; } plant_callback() { pg "UPDATE oauth2_provider_apps SET callback_url = '$2' WHERE id = '$1';"; } urlenc() { jq -rn --arg v "$1" '$v|@uri'; } # 43 unreserved characters every time. Base64url of the raw 32 bytes. new_pkce() { VERIFIER=$(openssl rand 32 | base64 | tr -d '\n=' | tr '+/' '-_') CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_') STATE=$(openssl rand -hex 16) } authz_url() { local url="$BASE_URL/oauth2/authorize?client_id=$1&response_type=code" url="$url&redirect_uri=$(urlenc "$2")&state=$STATE" url="$url&code_challenge=$CHALLENGE&code_challenge_method=S256" printf '%s' "$url" } # The core assertion of the whole run: what answer, delivered where. answer() { curl -s -o /dev/null -D - -X "$1" "$2" -H "$AUTH_HEADER" | grep -iE '^HTTP/|^location:'; } show_callback() { python3 - "$1" <<'PY' import sys, urllib.parse q = urllib.parse.urlparse(sys.argv[1]).query for k, v in urllib.parse.parse_qsl(q, keep_blank_values=True): print(f"{k} = {v}") PY } ``` Fixtures, all registered through DCR: ```text plat479-plain http://localhost:9876/callback plat479-query http://localhost:9876/callback?tenant=acme&error=stale plat479-corrupt http://localhost:9876/callback (overwritten by psql in 12 to 16) plat479-reserved http://localhost:9876/callback?tenant=acme&code=FAKECODE&error=stale&error_description=oldmsg&state=oldstate&keep=yes plat479-ci http://localhost:9876/callback (scope allowlist coder:workspaces.access) ``` </details> <details> <summary><b>1. Baseline: a well-formed request still succeeds</b></summary> ```bash new_pkce; answer GET "$(authz_url "$APP_ID" http://localhost:9876/callback)" new_pkce; answer POST "$(authz_url "$APP_ID" http://localhost:9876/callback)" ``` ```text === GET === HTTP/1.1 200 OK === POST === HTTP/1.1 302 Found Location: http://localhost:9876/callback?code=coder_dzvaCPf9W1_...&state=e321bd5d5b594a1fae8a2d5da654b84a ``` `GET` carries no `Location` at all, so the consent page really rendered rather than redirecting. The `state` echoed is the one sent. The code persisted as `coder:all`, this app having no allowlist, with `redirect_uri` recorded because the request supplied one. Also driven through a real browser rather than curl, so the consent form's `nosurf` token is the one submitted rather than the session-token header alone. Clicking **Allow** delivered `code` and `state` to the callback. Both request shapes agree on the success case. Not to be misread: `oauth2_provider_app_codes` holds one row after both POSTs, not two. `ProcessAuthorize` opens its transaction with `DeleteOAuth2ProviderAppCodesByAppAndUserID`, so a row count is not a count of successful authorizations. That predates this PR. </details> <details> <summary><b>2 to 4. A rejected parameter now reaches the client's callback</b></summary> ```bash new_pkce BAD="$BASE_URL/oauth2/authorize?client_id=$APP_ID&response_type=code" BAD="$BAD&redirect_uri=$(urlenc http://localhost:9876/callback)&state=$STATE" BAD="$BAD&code_challenge=short&code_challenge_method=S256" answer POST "$BAD" answer GET "$BAD" ``` ```text HTTP/1.1 302 Found Location: http://localhost:9876/callback?error=invalid_request&error_description=Invalid+query+params%3A+code_challenge%3A+must+be+43+to+128+characters+from+the+unreserved+character+set+%5BA-Za-z0-9-._~%5D&state=e89f4d98d4c8c347e5ae25175748b731 ``` Identical on both verbs. Decoded: ```text error = invalid_request error_description = Invalid query params: code_challenge: must be 43 to 128 characters from the unreserved character set [A-Za-z0-9-._~] state = e89f4d98d4c8c347e5ae25175748b731 ``` The `GET` body confirms no page was rendered, against the baseline: | Request | Body size | Occurrences of "Allow" | |---|---|---| | Malformed `code_challenge` | 263 bytes | 0 | | Well formed (scenario 1) | 4928 bytes | 2 | 263 bytes is Go's redirect stub. There is no consent form in it, so there is no Allow button to press for a request the server has already refused. Multiple failures are reported together (scenario 4): ```text error_description = Invalid query params: code_challenge: must be 43 to 128 characters from the unreserved character set [A-Za-z0-9-._~]; resource: must be an absolute URI without fragment ``` The separator is `; `, and no entry uses the older `field: x detail: y` shape. The code is `invalid_request` rather than `invalid_target` even though `resource` is one of the two failures, which is the scenario 22 guard firing. The same request also carried `code_challenge_method=plain`, which is invalid and is *not* mentioned, because the method is validated after `extractAuthorizeParams` returns and a parse failure short-circuits first. Sent alone it is rejected as `code_challenge_method 'plain' is not supported; use 'S256'`, with no `Invalid query params: ` prefix. That difference is observation 1. </details> <details> <summary><b>5 and 6. The redirect_uri carve-out keeps the answer here</b></summary> ```bash new_pkce EVIL="$BASE_URL/oauth2/authorize?client_id=$APP_ID&response_type=code" EVIL="$EVIL&redirect_uri=$(urlenc http://evil.example/steal)&state=$STATE" EVIL="$EVIL&code_challenge=$CHALLENGE&code_challenge_method=S256" answer POST "$EVIL"; answer GET "$EVIL" ``` ```text HTTP/1.1 400 Bad Request HTTP/1.1 400 Bad Request ``` **The absence in that output is the assertion**: no `Location` on either verb, so nothing redirects to `evil.example`. Stronger, `evil.example` appears zero times in either full response, headers and body together, so the attacker-supplied host is not reflected into the page either. ```json {"error":"invalid_request","error_description":"Invalid query params: redirect_uri: Query param \"redirect_uri\" must exactly match http://localhost:9876/callback"} ``` The `GET` page names the *registered* callback as the value the parameter had to match, which is the app's own configuration and safe to display. An unparseable `redirect_uri` reaches the same outcome by a different route, having never parsed at all: ```json {"error":"invalid_request","error_description":"Invalid query params: redirect_uri: Query param \"redirect_uri\" must be a valid url: parse \"http://%zz\": invalid URL escape \"%zz\""} ``` That message echoes the caller's value, unlike the mismatch case, so the `GET` path was probed with markup in it: ```text input: http://%zz"><img src=x onerror=BAD> page: ...must be a valid url: parse "http://%zz\"><img src=x onerror=BAD>"... literal `<img` in body: 0 entity encoded `<img`: 1 ``` Escaped correctly by the template layer. Recorded as a negative result so a future change to the error page has something to regress against. One note for the docs: this detail contains colons, so a client splitting `field: reason` entries must split each on its **first** colon only. </details> <details> <summary><b>7 to 10. The client_id carve-out, and its negatives</b></summary> A repeated `client_id` in an otherwise perfect request: ```text HTTP/1.1 400 Bad Request (both verbs, no Location) {"error":"invalid_request","error_description":"Invalid query params: client_id: Query param \"client_id\" provided more than once, found 2 times. Only provide 1 instance of this query param."} ``` This is the one carve-out not implied by the response's shape. The `redirect_uri` matched the registration, so `canRedirect()` was true and there *was* somewhere to send the answer; it was withheld because `extractAuthorizeParams` assigns `failure.redirect` only when `clientIDInDoubt` is false. **The `default` branch of that function is unreachable over HTTP** (observation 3). `httpmw` resolves the app from `r.URL.Query().Get("client_id")`, so `app.ID` and the parsed value derive from the same string and cannot disagree. Three experiments: ```text one query client_id, bad challenge -> 302 delivered two DIFFERENT client_id values -> 400, caught by the repeated branch query names app A, form body names app B -> 302 to app A; the body is ignored ``` The negatives matter as much as the positives. An identifier absent from the query but present in the `POST` form body is **delivered**, correctly: ```text HTTP/1.1 302 Found Location: ...error=invalid_request&error_description=Invalid+query+params%3A+client_id%3A+...is+required+and+cannot+be+empty%3B+code_challenge%3A+... ``` That is observation 4: the description says `client_id` is required for a request that supplied it. With everything else valid the same shape still fails, while the identical request carrying `client_id` in the query succeeds with a code. `RequiredNotEmpty` reads the query; `httpmw` reads the body. Pre-existing, and arguably the parser is the layer in the right, since RFC 6749 §4.1.1 puts authorization parameters in the query string and §3.2.1 is the endpoint that uses a form body. A braced upper-case UUID is delivered, and succeeds end to end: ```text {UPPERCASE} client_id, bad challenge -> 302, description names ONLY code_challenge {UPPERCASE} client_id, all valid -> 302 with a real code GET, all valid -> 200, consent page, heading resolves to the app's real name ``` `uuid.Parse` accepts that spelling and `httpmw` resolved through it, so a string comparison here would withhold an answer the client is entitled to, for no reason it could diagnose. </details> <details> <summary><b>11. A repeated state is delivered, not withheld</b></summary> ```text HTTP/1.1 302 Found (both verbs) error = invalid_request error_description = Invalid query params: state: Query param 'state' provided more than once, found 2 times. Only provide 1 instance of this query param. ``` Reading `state` happens inside `newAuthorizeResponse`, the same function that runs the `redirect_uri` match. A count of errors across those two lines would charge this to the redirect carve-out and answer 400. It answered 302, so the field-specific test is doing the work. The asymmetry with scenario 7 is deliberate: a repeated `client_id` leaves the server unsure whose callback it holds, a repeated `state` leaves the callback fully settled. The response carries **no `state`**, since `parseSingle` collapsed the repeat to the empty string and `withQuery` only sets it when non-empty. Unavoidable rather than wrong: picking one of two values could satisfy a CSRF check the client meant to be strict. </details> <details> <summary><b>12 to 16. A corrupt registration outranks everything</b></summary> DCR refuses both planted values, which is why `psql` is needed and why 500 is the right answer: a stored one is not something a client did. ```json {"error":"invalid_client_metadata","error_description":"invalid redirect_uris: redirect URI at index 0: redirect URI uses dangerous scheme javascript which is not allowed"} {"error":"invalid_client_metadata","error_description":"invalid redirect_uris: redirect URI at index 0 is not a valid URL: parse \"http://%zz\": invalid URL escape \"%zz\""} ``` ```bash plant_callback "$APP_CORRUPT_ID" 'javascript:alert(1)' new_pkce CORRUPT="$BASE_URL/oauth2/authorize?client_id=$APP_CORRUPT_ID&response_type=code&state=$STATE" CORRUPT="$CORRUPT&code_challenge=$CHALLENGE&code_challenge_method=S256" answer POST "$CORRUPT"; answer GET "$CORRUPT" ``` ```text HTTP/1.1 500 Internal Server Error {"error":"server_error","error_description":"The application's registered callback URL is not usable"} GET: HTTP/1.1 500, page reads "500 - Invalid Callback URL", 3346 bytes, 0 Allow buttons ``` The unparseable callback is **indistinguishable to the caller**: same description, and a `GET` page of exactly 3346 bytes, matching byte for byte. Two different defects in stored state, one answer. Correct, since neither is actionable by the client. Note the request carried no `redirect_uri` of its own and still failed, because the scheme is checked on the *registered* URL before the client's value is consulted. Precedence was tested against all three competitors, not one: | Also wrong in the request | Would answer alone | Actually answered | |---|---|---| | `code_challenge=short` | 302 to the callback | **500** | | `client_id` repeated | 400 kept here | **500** | | `redirect_uri` mismatched | 400 kept here | **500** | Reading the source, this is stronger than precedence. `newAuthorizeResponse` runs at `authorize.go:250`, before any of `client_id`, `code_challenge`, `scope` or `resource` is read, and the early return discards whatever `p.Errors` already held. In rows two and three those failures are never detected at all, so `kind()` ranking `failureCorruptRegistration` first is belt and braces for a failure constructed some other way. **The value is logged and never echoed.** A distinctive marker was planted and five requests fired: ```text [erro] coderd: oauth2 app has an unusable registered callback URL request_id=01ca4796-c743-4923-a06b-afc1f3decc95 app_id=12f9ca3b-7a2c-4c54-8ed7-723698c62bd1 callback_url="javascript:alert(\"plat479-6d-marker\")" error= redirect URI uses dangerous scheme javascript which is not allowed: codersdk/oauth2_validation.go:116 ``` Five requests, five lines, in request order. Occurrences of the marker in the POST body, the rendered GET page, and the response headers: **0, 0, 0**. The `request_id` joins that line to the request log entry whose `response_body` field holds the vague message, so the server's own record confirms what it sent for the same request rather than a replay. The log is also where the two causes diverge, naming `validateScheme` and its source line, which the response cannot do. Restoring the row restores normal behaviour immediately, with no restart: ```text POST -> 302 with a code GET -> 200 consent page ``` That is a control rather than housekeeping: it rules out the app having been poisoned lastingly, and rules out a cached parse outliving the `UPDATE`. </details> <details> <summary><b>17 and 18. Every unsupported response_type gets one code</b></summary> | `response_type` sent | `error` | `error_description` | |---|---|---| | `token` | `unsupported_response_type` | Only response_type=code is supported | | `banana` | `unsupported_response_type` | Only response_type=code is supported | | `code token` | `unsupported_response_type` | Only response_type=code is supported | | `CODE` | `unsupported_response_type` | Only response_type=code is supported | | `code_extra` | `unsupported_response_type` | Only response_type=code is supported | | empty string | `invalid_request` | Invalid query params: response_type: Query param 'response_type' is required and cannot be empty | `token` has a Go constant behind it and `banana` does not, so their agreement is what reading the value as text bought. Three rows are more interesting than `banana`: `code token` is a legal RFC 6749 §3.1.1 space-delimited list used by OIDC's hybrid flow, `CODE` confirms the comparison is case sensitive, and `code_extra` confirms it is equality rather than a prefix match. The empty string is correctly the exception. A valueless parameter is *missing*, not unsupported, and RFC 6749 §3.1 requires it be treated as omitted. **The error is in the query, not the fragment.** `response_type=token` is the implicit grant's own value, so a fragment would be arguable, but this deployment advertises `"response_types_supported":["code"]` alone, and a fragment is never sent to the server, so it would be unreadable to the client's backend. PKCE is not recast, which the controls show: | `response_type`, no `code_challenge` sent | `error` | |---|---| | `token` | `unsupported_response_type`, zero mentions of `code_challenge` | | `banana` | `unsupported_response_type`, zero mentions of `code_challenge` | | `code` | `invalid_request`, naming `code_challenge` | Without the `if params.responseType == responseTypeCode` guard, a client sending `token` would be told its `code_challenge` was missing, add one, resend, and be told the same thing again. </details> <details> <summary><b>19 to 21. Unrecognized parameters ignored, repeats still rejected</b></summary> Eight unknown parameters, each on an otherwise valid request, every one issuing a code: | Unknown parameter | Result | |---|---| | `nonce`, `prompt`, `login_hint`, `acr_values`, `max_age`, `ui_locales` | code issued | | `code_challenge_methods=S256` | code issued | | `REDIRECT_URI=http://evil.example/steal` | code issued, **to the registered callback** | Five of those are OpenID Connect Core parameters, so an OIDC client pointed here degrades to plain OAuth2 rather than failing. The ignored parameters are **dropped, not forwarded**: the callback receives only `code` and `state`. The last two rows are the ones with teeth. Query parameter names are case sensitive, so `REDIRECT_URI` must be ignored, and a misspelled `redirect_url` likewise: ```text case variant alongside a valid redirect_uri : Location host localhost:9876 case variant as the only redirect parameter : Location host localhost:9876 redirect_url typo, no valid redirect_uri : Location host localhost:9876, code issued evil.example occurrences in any Location : 0 ``` The consent page renders for the typo case too, and even its cancel link targets the registered callback. A parser matching names case-insensitively would have redirected to `evil.example` with a valid code attached. **Observation 5.** The `ignoring unrecognized authorization parameters` line was never emitted. Three requests carrying a distinctive marker produced no new server output at all, because the call is `logger.Debug` (`authorize.go:307`) and the deployment runs with `verbose: null`. The behaviour is correct and required by RFC 6749 §3.1, but at default verbosity the misspelling is invisible from every angle: the client sees a 302 with a code, its redirect is silently replaced, and nothing is logged. The comment claiming the typo "surfaces here" is optimistic. Repeats of known parameters are still rejected, which the replacement of `ErrorExcessParams` had to leave alone: | Repeated parameter | HTTP | `error` | Answered at | |---|---|---|---| | `code_challenge` | 302 | `invalid_request`, two entries one field | client callback | | `code_challenge_method` | 302 | `invalid_request` | client callback | | `response_type` | 302 | `invalid_request` | client callback | | `redirect_uri` | 400 | withheld | **Coder** | | `scope` | 302 | `invalid_request` | client callback | | `resource` | 302 | `invalid_target` | client callback | `redirect_uri` being withheld confirms the carve-out keys on the field name rather than the kind of mistake. `code_challenge` collects two entries for one mistake, because `parseSingle` collapses the value to empty and the PKCE block then reports it missing. The `resource` row is observation 6. </details> <details> <summary><b>22 and 23. resource, its own code, and the fragment rule</b></summary> Both sides of the rule, since a check enforced too broadly would reject a valid URN: | `resource` sent | `error` | Stored `resource_uri` | |---|---|---| | `not a uri` | `invalid_target` | not stored | | `/api` relative | `invalid_target` | not stored | | `https://api.example.com` | none, code issued | as sent | | `https://api.example.com/v1?q=1` | none, code issued | as sent, query is not a fragment | | `urn:example:resource` | none, code issued | as sent | | empty string | none, code issued | `NULL`, same as omitted | `invalid_target` applies only when `resource` is the sole failure. Add any second failure in any other field and the code becomes `invalid_request` naming both, which is the retry-loop guard: ```text resource + bad code_challenge -> invalid_request, both named resource + repeated scope -> invalid_request, both named resource + repeated state -> invalid_request, both named resource alone (control) -> invalid_target ``` Fragments are rejected in all three placements, with or without a path: ```text https://api.example.com/#x -> invalid_target https://api.example.com#x -> invalid_target https://api.example.com/v1#frag -> invalid_target https://api.example.com/# -> code issued, stored as https://api.example.com/# ``` **The last row is observation 7, and it predates this PR.** Go cannot represent the distinction: ```text https://a.example.com/ Fragment="" String()="https://a.example.com/" https://a.example.com/# Fragment="" String()="https://a.example.com/" https://a.example.com/#x Fragment="x" String()="https://a.example.com/#x" ``` `url.Parse` collapses "no fragment" and "empty fragment", so `if u.Fragment != ""` in `validateResourceParameter` (`coderd/oauth2provider/tokens.go:591`) cannot see a trailing `#`. RFC 3986 §3.5 permits a zero-length fragment, which RFC 8707 §2's "MUST NOT include a fragment component" reads as forbidding. Validation parses the value but persistence stores the raw string, so the `#` reaches `resource_uri` and the stored audience is not textually equal to the fragment-free form. A client appending a harmless-looking `#` would get a token bound to an audience nothing matches. The authorize-side call to `validateResourceParameter` is context in this diff rather than an added line; this PR added the `invalid_target` code for the failure. </details> <details> <summary><b>24 and 25. The description cap and character set</b></summary> The obvious probe does not exercise the cap: a 4000-character `code_challenge` produces a 116-character description, because that message is fixed text and never quotes the offending value. The descriptions that echo caller input come from a validator's own error. | Request | `error` | Description length | Truncated | `Location` length | |---|---|---|---|---| | `code_challenge_method` = 4000 chars | `invalid_request` | 2060 | **yes** | 2176 | | `scope` = 4000 chars | `invalid_scope` | 2060 | **yes** | 2174 | | `code_challenge_method` = 2000 chars | `invalid_request` | 2035 | no | 2147 | | `code_challenge` = 4000 chars | `invalid_request` | 116 | no | 234 | 2060 is exactly `maxErrorDescription` plus `" (truncated)"`. Row three is the boundary control, so the cap fires on length rather than on the presence of echoed input. Measured from the `Location` header rather than a log line, since the stated reason for the cap is that the header must survive intermediary proxies; the longest observed was 2176 bytes. Both verbs agree, the cap living in the shared `redirectAuthorizeError`: ```text GET, long method : desc_len=2060 truncated=True GET, long scope : desc_len=2060 truncated=True ``` The character set is enforced independently, later, in `errorURL`: ```text input: pl"ain\back<newline>tab<tab>end~unicode description: unsupported code_challenge_method: pl'ainback tab end~ nicode chars outside the RFC 6749 §4.1.2.1 set: [] ``` `"` becomes `'`, `\` is dropped so it cannot escape the rewritten quote, and anything below 0x20 or above 0x7E becomes a space. Checked programmatically rather than by eye. The RFC sets no length limit, so the 2048 cap is policy; the character set is conformance. </details> <details> <summary><b>26. The registered callback query, retained except reserved names</b></summary> `plat479-reserved` registers a callback carrying all four reserved names plus two ordinary ones, and DCR stores it unchanged: ```text http://localhost:9876/callback?tenant=acme&code=FAKECODE&error=stale&error_description=oldmsg&state=oldstate&keep=yes ``` Success response, no `redirect_uri` sent: ```text code = coder_WXwBpvYR5u_... keep = yes state = 516abeea9976119eb33ddc10f0ca04ed tenant = acme ``` Failure response, same app: ```text error = invalid_request error_description = Invalid query params: code_challenge: must be 43 to 128 characters... keep = yes state = 3a17bdd75dfcf740bda36124cd161fb7 tenant = acme ``` Stale registered values in either response: `FAKECODE` 0, `stale` 0, `oldmsg` 0, `oldstate` 0. Without the deletion step a registered `error=stale` would ride out on the **success** response, and a client reading `error` before `code`, the conventional order, would discard a valid authorization code. `FAKECODE` is the mirror image on a failure response. The cancel link obeys the same rule, being built by the same `withQuery` path: ```text http://localhost:9876/callback?error=access_denied&error_description=The+resource+owner...&keep=yes&state=e15b5f0f...&tenant=acme ``` RFC 6749 §3.1.2 requires the registered query be retained when adding parameters, which is the `tenant` and `keep` half. It does not say what to do when the registered query collides with the response parameters §4.1.2 adds, so dropping the registered copies is the resolution that keeps the client's read unambiguous. </details> <details> <summary><b>27 and 28. Scope rejections, and declining consent</b></summary> `plat479-ci` carries the allowlist `coder:workspaces.access`. ```text scope=template:update (outside) -> error = invalid_scope 'template:update': scope requests permissions beyond this app's allowed scopes GET, same request -> 302, 225 bytes, 0 Allow buttons, no consent page scope=workspace:ssh (covered) -> code issued, persisted scope workspace:ssh GET, same request -> 200, 5182 bytes, consent page naming the scope ``` `workspace:ssh` is granted although the allowlist names the composite rather than that scope, which is the coverage-not-spelling rule from #28045. This run only checks that the changes here left it delivering the same answers. The consent page for a narrow scope reads differently from the unrestricted one: "to access your **admin** account with these permissions?", the scope as `<li role="listitem">workspace:ssh`, and the caution "These are technical permission names. Grant them only to an application you trust." The scope description shape differs from the parser's, coming from `scopeFailureResponse` rather than the field join, which is the third producer behind observation 1. Declining consent, clicked in a real browser: ```text error = access_denied error_description = The resource owner or authorization server denied the request state = a8bd538b365b61f54586892c73968b80 ``` The page carries exactly one `href` and it is the cancel link. The `state` matches, there is no `code`, and the code count for the app is unchanged, the link being a plain `GET` to the client's callback that never reaches `ProcessAuthorize`. The description is RFC 6749 §4.1.2.1's own definition of `access_denied`, word for word. That shared construction is what makes the `#nosec G203` annotation on `CancelURI` sound: the URL is injected as a trusted `htmltemplate.URL`, safe only because `newAuthorizeResponse` validated the registered scheme before the response object could exist. Scenario 12 is the other half, an app with a rejected scheme never reaching this page at all. </details> <details> <summary><b>Where the consent page renders, across every GET case</b></summary> Only `GET` can render anything, and body size identifies which of four renderers ran, so this is the table to check when a status code alone looks right. | Case | Status | Body bytes | Allow buttons | Rendered | |---|---|---|---|---| | well formed | 200 | 4928 | 1 | **consent page** | | bad `code_challenge` | 302 | 263 | 0 | redirect stub | | two bad fields | 302 | 319 | 0 | redirect stub | | mismatched `redirect_uri` | 400 | 3814 | 0 | 400 error page | | unparseable `redirect_uri` | 400 | 3846 | 0 | 400 error page | | repeated `client_id` | 400 | 3846 | 0 | 400 error page | | `client_id` in form body only | 400 | 77 | 0 | `httpmw` JSON, unstyled | | `{UPPERCASE}` `client_id` | 200 | 4940 | 1 | **consent page** | | repeated `state` | 302 | 239 | 0 | redirect stub | | corrupt callback, blocked scheme | 500 | 3346 | 0 | 500 error page | | corrupt callback, unparseable | 500 | 3346 | 0 | 500 error page | | `response_type=token` | 302 | 187 | 0 | redirect stub | | `banana` / `code token` / `CODE` | 302 | 187 | 0 | redirect stub | | empty `response_type` | 302 | 243 | 0 | redirect stub | | `token`, no PKCE | 302 | 187 | 0 | redirect stub | | `code`, no PKCE | 302 | 245 | 0 | redirect stub | | unknown params, valid request | 200 | 4932 | 1 | **consent page** | | `redirect_url` typo, valid request | 200 | 4932 | 1 | **consent page** | | `resource` malformed | 302 | 214 | 0 | redirect stub | | `resource` valid absolute URI | 200 | 4932 | 1 | **consent page** | | `resource=.../#` empty fragment | 200 | 4932 | 1 | **consent page**, observation 7 | | reserved params in registered callback | 200 | 4973 | 1 | **consent page** | | `scope` outside allowlist | 302 | 225 | 0 | redirect stub | | `scope` covered by allowlist | 200 | 5182 | 1 | **consent page** | The invariant: the page renders if and only if `extractAuthorizeParams` returned no failure, so no input asks the owner to approve a request the server has already refused. The `evil.example` rows are worth reading carefully rather than alarming: RFC 6749 §3.1 requires a case variant and a typo to be ignored, so from the server's view nothing was wrong with either request, and both cancel links target the registered callback. About 4930 bytes is the consent page, about 3800 the 400 page, 3346 the 500 page, 77 the unstyled `httpmw` JSON, and low hundreds is Go's redirect stub, whose length tracks the `Location` it embeds. Every `unsupported_response_type` answer is exactly 187 bytes because they share one description. Small variations within a renderer are expected: the consent page moves 4928 to 4940 with a fresh CSRF token and the app name. As a regression signal, body size is more sensitive than the status line. A change that rendered a page alongside a redirect would still report 302, but the stub would come back at thousands of bytes rather than hundreds. </details> <details> <summary><b>Cleanup</b></summary> ```bash for id in $(pg "SELECT id FROM oauth2_provider_apps WHERE name LIKE 'plat479%';"); do curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$id" -H "$AUTH_HEADER" \ -o /dev/null -w "$id -> %{http_code}\n" done pg "SELECT count(*) FROM oauth2_provider_apps WHERE name LIKE 'plat479%';" ./scripts/coder-dev.sh oauth2-provider dcr disable ``` All planted callback rows were restored before deletion, so no fixture was left holding a value DCR would refuse. </details> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
b938495bf5 |
chore: refresh AI model price book (#28939)
## Price book changes 7 models added, 0 models removed, 15 models changed. <details> <summary>Added</summary> - openrouter/meta/muse-spark-1.3 - openrouter/meta/muse-spark-1.3-contributor - vercel/alibaba/qwen3.8-max-0902 - vercel/google/gemini-3.8-flash - vercel/meta/muse-spark-1.3 - vercel/meta/muse-spark-1.3-contributor - vercel/zai/glm-5.3-promo-50 </details> <details> <summary>Changed</summary> - azure/gpt-5.6-sol - openrouter/deepseek/deepseek-v4-flash - openrouter/deepseek/deepseek-v4-flash-vision-exp - openrouter/deepseek/deepseek-v4-pro - openrouter/deepseek/deepseek-v4-pro-0813 - openrouter/meta-llama/llama-3.3-70b-instruct - openrouter/meta/muse-glimmer-30b - openrouter/nvidia/nemotron-3-nano-30b-a3b - openrouter/nvidia/nemotron-3-ultra-550b-a55b - openrouter/qwen/qwen3.5-397b-a17b - openrouter/qwen/qwen3.8-2.4t-a95b - openrouter/tencent/hy3 - openrouter/z-ai/glm-4.6 - openrouter/z-ai/glm-5.3 - openrouter/~z-ai/glm-latest </details> ## Review notes Regenerated by `make gen/aibridge-prices` from the live [models.dev](https://models.dev) catalog. Both artifacts come from one snapshot, so they ship together: - `coderd/aibridge/prices/data/prices.json` - `site/src/pages/AgentsPage/components/ChatModelAdminPanel/knownModels/knownModelsGenerated.json` These are customer-visible cost numbers taken from upstream data, so this PR is never merged automatically. The summary above lists what moved; check the diff for exact figures before approving. Opened automatically by the [aigateway-prices-refresh workflow](https://github.com/coder/coder/actions/runs/33736992948). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
56255e5121 |
fix: accept connection reset as auth rejection in nats auth tests (#28918)
Flaked on Windows because the server can close the rejected route connection before nats.go reads the `-ERR 'Authorization Violation'` |
||
|
|
99554ed65c | fix: fix flaky TestExecutorAutostartSkipsWhenNoProvisionersAvailable (#28917) | ||
|
|
524745da5d |
feat: filter blocked user secret file targets (#28519)
When `DisableUserSecretFilePath` is set, coderd strips file targets while building the agent manifest: env-only secrets are unchanged, dual-target secrets keep the env var with an empty file path, and file-only secrets are omitted so their plaintext never crosses DRPC. Stored paths stay in the database and reappear on the next manifest fetch once the option is cleared. Agents converge on reconnect; no protobuf, provisioner, or agent-side changes are needed, and files already written to workspace disks are left alone. Also exposes the positive capability as the `user-secret-file-path-enabled` embedded metadata tag, which the next PR in the stack consumes in the dashboard. Builds on #28518. Refs #27488. Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder. |
||
|
|
e035967ef1 |
feat: mint access tokens with the negotiated scope (#28237)
**TL;DR** First of PLAT-480, continuing the merged PLAT-479 stack. #28178 decided what the scope is and #28179 reported it; this PR is the one that makes it bind. Until now the scope negotiated at `/oauth2/authorize` was recorded on the grant but never reached the token: every OAuth2 access key was minted with `coder:all`, so a client that asked for `coder:workspaces.access` still got full API access. | PR | What it does | |---|---| | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. Merged. | | #28178 | The authorize endpoint checks the request against the scope catalog, grants it only if the app's filtered allowlist covers it, and persists the result on the code. Merged. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's own callback per RFC 6749 §4.1.2.1. Merged. | | **#28237 (this)** | The exchange mints the API key with the stored scope, and the token response states what was granted. | | #28740 | Re-checks the app allowlist at redemption, for a code whose app was narrowed after the code was issued. | | #28751 | Lets a refresh narrow the granted scope, which is the `scope` request parameter this PR still ignores. | - #28179 has merged, so this diff is against main and reviews on its own. - **This is the first PR in the stack where a token's authority actually changes.** Everything before it recorded and reported. That is the blast radius worth reviewing: a grant that negotiated a narrow scope now gets a key that is genuinely narrower, and anything that was quietly relying on `coder:all` will start seeing 403. - Grants that predate the scope columns carry what migration 000569 backfilled, `coder:all`, so they refresh unrestricted and reach what they reached before. Pinned by `BackfilledScopeRefreshesUnrestricted`, seeded the way the migration leaves a row rather than exchanged. - The actor that writes the key stays `rbac.ScopeAll`. Narrowing it to the granted scope would deny `api_key:create` and fail the exchange. The bound lives on `api_keys.scopes`, which dbauthz reads on every request, not on the actor doing the insert. **Where in the flow** <details> <summary>Diagram: where the stored scope turns into a bound on the token</summary> ```mermaid flowchart TD AZ["GET or POST /oauth2/authorize<br/>negotiates the scope and persists it on the code<br/>PR 28178, merged"] AZ --> TK["POST /oauth2/tokens"] TK --> GT{"grant_type"} GT -->|authorization_code| S1["scope read from codes.scope"] GT -->|refresh_token| S2["scope read from tokens.scope<br/>req.Scope is parsed and ignored, PR 28751"] S1 --> CV["scopeStringToAPIKeyScopes, this PR<br/>every name must be in the api_key_scope enum<br/>an empty list is an error, not coder:all"] S2 --> CV CV -->|"unknown name, or empty"| ERR["400 invalid_grant, this PR<br/>error_description names the offending value"] CV -->|mintable| GEN["apikey.Generate with Scopes, this PR<br/>was: no Scopes, so every key defaulted to coder:all"] GEN --> KEY["api_keys.scopes<br/>read by dbauthz on every later request:<br/>this is where the grant becomes a bound"] GEN --> ROW["the new tokens row carries the same scope,<br/>so the next refresh reads back the same grant"] KEY --> RESP["200 with scope in the token response, this PR<br/>RFC 6749 5.1, OAuth 2.1 1.4.1"] ROW --> RESP ``` </details> - Token endpoint only, both grants. Authorize is untouched apart from two comments that said the scope was not yet enforced. - `scopeStringToAPIKeyScopes` turns the stored scope string into `database.APIKeyScopes` for `apikey.Generate`. Names are checked there rather than inside `apikey.Generate`, whose error would surface as a 500 rather than an OAuth2 error. - An empty list is an error, not an unrestricted key. `apikey.Generate` defaults an empty scope list to `coder:all`, so an empty stored scope would silently widen the grant instead of failing it. The same reasoning is why the `expandRBACScope` comment in `modelmethods.go` was stale: that function already errored on an empty list while its comment still promised `rbac.ScopeAll`. - A stored scope outside the `api_key_scope` enum answers 400 `invalid_grant` rather than 500, with the offending name in `error_description`. Not `invalid_scope`: RFC 6749 §5.2 and OAuth 2.1 §3.2.4 both scope that code to what the client requested, and this value is server state the client cannot change by asking differently. The grant is what is unusable, and re-authorizing is the only way out. - Refresh copies the presented token's scope onto both the new API key and the rotated refresh row. `req.Scope` is parsed but ignored; #28751 is where it starts being honoured. - The swagger annotation moves from `oauth2.Token` to `codersdk.OAuth2TokenResponse`, because `oauth2.Token` has no `scope` field to document. - `EveryCatalogNameMintable` pins the catalog against the `api_key_scope` enum. The two are maintained separately, and a name negotiable at authorization but unmintable at exchange would leave a client holding a code it can never redeem. **What it satisfies** Checked against both RFC 6749 and the OAuth 2.1 draft (draft-ietf-oauth-v2-1-15). The 2.1 draft moves the scope-reporting rule from RFC 6749 §5.1 into §1.4.1 and grades it in §3.2.3, but the requirement is the same one. - RFC 6749 §5.1, OAuth 2.1 §1.4.1 — "If the issued access token scope is different from the one requested by the client, the authorization server MUST include the `scope` response parameter in the token response". OAuth 2.1 §3.2.3 grades `scope` as "RECOMMENDED, if identical to the scope requested by the client; otherwise, REQUIRED". Both grants set it unconditionally, which covers both grades. Without it, a client whose request was narrowed against the app's allowlist, or defaulted because it requested nothing, first learns its bounds from an unexplained 403. Pinned by `IssuedTokenBoundsTheAPI`, which requests no scope and asserts the response names what it got. - OAuth 2.1 §1.4.1 — "The authorization server MAY fully or partially ignore the scope requested by the client, based on the authorization server policy or the resource owner's instructions." This is what licenses ignoring `scope` on a refresh, and the licence is conditional on reporting the actual grant. Before this PR the exchange both ignored the request and said nothing, which is the half that was not defensible. - OAuth 2.1 §4.3.1, RFC 6749 §6 — the refresh `scope` parameter is OPTIONAL and "if omitted is treated as equal to the scope originally granted by the resource owner". Exactly what `refreshTokenGrant` does with `dbToken.Scope`. - OAuth 2.1 §4.3.3 — "If a new refresh token is issued, the refresh token scope MUST be identical to that of the refresh token included by the client in the request." Rotation copies `dbToken.Scope` onto the new refresh row. - OAuth 2.1 §3.2.3 — "If refresh tokens are issued, those refresh tokens MUST be bound to the scope and resource servers as consented by the resource owner. This is to prevent privilege escalation by the legitimate client". The refresh row has carried the negotiated scope since #28178; this PR is what makes the access token minted from it carry the same bound. Pinned by `RefreshDoesNotWidenTheScope`. - OAuth 2.1 §1.4.1 — a client that omits `scope` must be met with "a pre-defined default value or fail the request indicating an invalid scope", and the server "SHOULD document its scope requirements and default value". #28178 chose the default; `scopes_supported` and the integration guide document it. Unchanged here, but it is why `IssuedTokenBoundsTheAPI` can request nothing and still receive a bounded token. - Not yet: OAuth 2.1 §4.3.1 also says "The requested scope MUST NOT include any scope not originally granted by the resource owner." A refresh naming a narrower scope is ignored rather than honoured, and one naming a wider scope is ignored rather than rejected with `invalid_scope` (§3.2.4, "exceeds the scope granted by the resource owner"). Neither case widens a token, so there is no escalation, and §1.4.1's MAY plus the `scope` response parameter keep the client correctly informed in the meantime. #28751 is where narrowing lands. Documented under Limitations until then. --- First of three, [PLAT-480](https://linear.app/codercom/issue/PLAT-480). Depends on #28179, which has merged, so this reviews against main. #28178 decided the scope and #28179 reported it. This PR is the one that makes a token feel it. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
54e21f29a1 |
fix: deliver four more authorize errors to the client (#28450)
**TL;DR** Fourth of the stack, split out of #28045. #28179 sent `invalid_scope` to the client's own callback; this PR sends the rest of the errors raised after the callback has been verified, behind one URL builder they all now share. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. | | #28178 | The authorize endpoint negotiates the scope against the app's allowlist and persists it on the code. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's callback per RFC 6749 §4.1.2.1. | | **#28450 (this)** | The same delivery for every other error raised once the callback is trusted. | - #28179 has merged, so this diff is against main and reviews on its own. - Nothing about what a token can do changes here. This is delivery, not enforcement. **Contract change** Four failures now arrive at the app's registered callback instead of terminating on Coder, so an integrator with error handling on its callback starts seeing codes it never received. | Verb | Condition | Error code | Was | |------|-----------|------------|-----| | GET | `response_type != code` | `unsupported_response_type` | static "Unsupported Response Type" page, 400 | | POST | `response_type != code` | `unsupported_response_type` | `WriteOAuth2Error`, 400 | | POST | `code_challenge_method=plain` | `invalid_request` | `WriteOAuth2Error`, 400 | | GET | `code_challenge_method=plain` | `invalid_request` | consent page, 200, refused after Allow | The GET static error page loses its only caller. The last row is what review found: the method was checked on POST only, so the user approved a request that could never succeed. **Where in the OAuth Flow** <details> <summary>Diagram: where these errors are raised, and what licenses the redirect</summary> ```mermaid flowchart TD EX["GET or POST /oauth2/authorize<br/>extractAuthorizeParams exact-matches redirect_uri<br/>against the app's registered callback"] EX -->|"no match, rejected scheme, unparsable,<br/>other param failures"| CODER["Answers on Coder<br/>RFC 6749 3.1.2.4: MUST NOT redirect"] EX -->|"matched: a validatedCallbackURL,<br/>which is what licenses a redirect"| RT{"response_type == code?"} RT -->|no| E1["unsupported_response_type (this PR)"] RT -->|yes| PK{"code_challenge_method S256 or omitted?"} PK -->|no| E2["invalid_request (this PR, and newly checked on GET)"] PK -->|yes| SC{"scope negotiable?"} SC -->|no| E3["invalid_scope (previous PR)"] SC -->|yes| OK["GET: consent page, cancel link is access_denied<br/>POST: authorization code"] E1 --> OUT E2 --> OUT E3 --> OUT OK --> OUT["One builder produces every URL the flow emits:<br/>error redirect, cancel link, success code"] ``` </details> - Authorize endpoint only, both verbs. The token exchange, refresh, and revocation are untouched. - Every redirect is licensed by a `validatedCallbackURL`, a type produced only where `extractAuthorizeParams` exact-matches the URI against the app's registration. A guard, not a proof: no other package can fabricate one, this one still can. - One builder now produces every response URL, including the consent page's cancel link, which rolled its own and edited the shared URL in place rather than copying it. - Each rejection logs. The error leaves in a `Location` header, which `loggermw` does not record, so a failed authorization used to look exactly like a successful one. **Three smaller behavior changes** - A callback registered with `code`, `error`, `error_description`, or `state` in its own query no longer receives that value back. A registered `error=` rode out on the success redirect, where a client that reads `error` first discards a valid code. The rest of the registered query is kept, as §3.1.2 requires. - `error_description` is confined to the NQSCHAR set Appendix A permits. Descriptions name the offending value with `%q`, so every `invalid_scope` Coder emits today carries excluded characters. Quotes now render as apostrophes. - An unparsable `redirect_uri` returns 400 instead of 500. It reached a nil dereference in `httpapi.RedirectURL`, which `POST /oauth2/tokens` also uses, and that endpoint takes no API key. **What it satisfies** - RFC 6749 §4.1.2.1 — on a failure that is not a bad redirection URI, the server informs the client through the redirection URI. That is the whole PR. - RFC 6749 §3.1.2.4 and §4.1.2.1 — a missing, invalid, or mismatching redirection URI "MUST NOT" be redirected to. A mismatched URI, and a registered URI with a rejected scheme, still answer on Coder. Pinned by `MismatchedRedirectURINotRedirected` and `DangerousCallbackSchemeNotRedirected`. - RFC 6749 Appendix A — `error_description` is NQSCHAR, and the rule is on the decoded value, so percent-encoding on the wire does not satisfy it. - RFC 6749 §4.1.2 and §3.1.2 — the four reserved response parameters are dropped from the registered query; everything else in it is retained. - Not yet: the remaining parameter failures do have a trusted callback in hand, but the parser reports one verdict for every field at once, so the caller cannot say which field failed. A follow-up classifies them. The two `server_error` sites also stay put: sending an internal fault outbound with a Coder-written description wants its own review. **Docs and Swagger.** `docs/admin/integrations/oauth2-provider.md` gains a Common Issues entry per newly redirected code, and the implicit-grant limitation now says where the error arrives. Both authorize verbs document the 302, the GET side for the first time. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Fourth of the stack. #28179 has merged, so this reviews against main. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
3aeb7f85d9 |
feat: correlate coder CLI workspace sessions with client_session_id (#28313)
## Summary Implements DEVEX-664: the coder CLI commands that open a workspace connection now generate a client session ID and attach it to their requests, logs, and existing network telemetry, per the connection-log RFC. Commands opt in explicitly with a `client_session_id` annotation. The opted-in set is `coder ssh`, `coder start`, `coder stop`, and `coder update`. Long-running daemon commands (`coder server`, `agent`, `provisionerd`, and so on) deliberately stay out, so they never carry a meaningless session ID in their logs, request baggage, or telemetry. - **Generate / resolve**: a 16-byte lowercase-hex session ID is generated per opted-in invocation. When `CODER_TRACE_SESSION_ID` is set (so Toolbox and the VS Code plugin can correlate the CLI they spawn), that value is used verbatim; a warning is logged if it is not the canonical 32-char lowercase hex form, since coderd/agent middleware drop non-canonical values. - **Requests**: the ID is attached to every request as `client_session_id` W3C baggage via a transport wrapper, independent of whether tracing is enabled. The already-merged coderd tracing middleware (#27671) reads it. - **Coordinate websocket**: the ID is also set explicitly as baggage on the tailnet coordinate handshake in `workspacesdk.DialAgent`, so coderd's `/api/v2/workspaceagents/{id}/coordinate` endpoint logs it (it does not rely on the CLI transport for that dial). - **Logs**: the ID is added to the command's log context. - **Existing telemetry**: the ID is added to tailnet `TelemetryEvent` (`client_session_id`, new field 20; proto minor version bumped) and plumbed from the CLI through `workspacesdk.DialAgent`. Scope is the coder CLI client only (RFC glossary + requirement 5), and within the CLI only the opted-in workspace-connecting commands above. This PR is independent of #28039 (the agent middleware that consumes the baggage); it depends only on `tracing.SessionIDBaggageKey`, which is already on `main` via #27671. ## Out of scope RFC requirements 7-16 (connection-state change logging, `connection_logs` columns, log buffering, routing/disconnect-reason logs, coordination-protocol plumbing, `agentssh`/`reconnectingpty` command logging, support-bundle log capture) and requirements 4.2/4.3 (VS Code telemetry, Prometheus stats) are separate tickets. IDE plugins, Toolbox, and the daemon commands are also out of scope. ## Testing - `go test ./coderd/tracing/... ./cli/... ./tailnet/... ./codersdk/workspacesdk/...` (unit tests for the generator, the env/generate resolver, per-command opt-in, the baggage transport wrapper, the coordinate-dial baggage helper, and the telemetry field). - `go build ./...`, `go vet`, and `golangci-lint` pass on the touched packages. - `make tailnet/proto/tailnet.pb.go` regenerated the proto; the proto minor version was bumped and `postStartup` now connects at the current agent API version so `TestWorkspaceAgent_Startup/OK` tracks it. > Note: the pre-commit `enterprise/cli/.gen-golden` step could not run in this environment (no Postgres: `open postgres connection: EOF`). `cli/testdata/.gen-golden` passed; this change adds no serpent flags, so there is no CLI help/golden drift. <details> <summary>Implementation plan</summary> ### Scope mapping (RFC -> DEVEX-664) In scope (the CLI workspace-connecting subset of RFC phase 2): - Req 1: generate a 16-byte session ID as 32-char lowercase hex. - Req 2: add the session ID to every log the command makes for the session. - Req 3: attach the session ID to every API request via `client_session_id` baggage, including the coordinate websocket handshake. (The query-param fallback is browser-only; not applicable to the CLI.) - Req 4.1: attach the session ID to CLI network telemetry. - Req 5 / 5.3: support `CODER_TRACE_SESSION_ID`; when set, use it instead of generating. ### Resolved decisions - Scope: opt-in per command via a `client_session_id` annotation; opted-in set is `coder ssh`, `coder start`, `coder stop`, `coder update`. Daemon commands are excluded. - `CODER_TRACE_SESSION_ID`: when set, use the value verbatim; warn if it is not canonical 32-char lowercase hex. When unset, generate a fresh ID. - Existing telemetry = CLI network telemetry (tailnet `TelemetryEvent`); requires a new proto field + plumbing and a proto minor version bump. - Coordinate endpoint: set the session ID as baggage on the coordinate handshake explicitly in `DialAgent` (header, not query param) so it is logged server-side without relying on the CLI transport. - Shared helper: add `tracing.NewSessionID()` and export the validator as `tracing.ValidSessionID` for a single source of truth. ### Implementation 1. `coderd/tracing`: add `NewSessionID()` (16 random bytes, hex-encoded); export `ValidSessionID`. 2. `cli`: resolve the ID from `CODER_TRACE_SESSION_ID` or generate; attach `client_session_id` baggage to every request via `wrapTransportWithSessionIDHeader`, gated on the `annotationClientSessionID` opt-in; add it to the command log context. 3. `tailnet` + `codersdk/workspacesdk`: add `client_session_id` to `TelemetryEvent`, an `Options.ClientSessionID`/`Conn.clientSessionID` set in `newTelemetryEvent`, a `DialAgentOptions.ClientSessionID` plumbed from the opted-in commands, and the coordinate-handshake baggage in `DialAgent`. </details> --- _This PR was created by Coder Agents on behalf of @aqandrew._ |
||
|
|
a8f7591627 | chore: add Gemini 3.8 Flash to the known models catalog and price book (#28909) | ||
|
|
8b8c80614d |
feat: expose template builder agents and per-module agent (#28905)
Part of [DEVEX-556](https://linear.app/codercom/issue/DEVEX-556). Builds on the base agent metadata added in #28794. ## Summary Surfaces the backend multi-agent support through the SDK and HTTP API: the bases endpoint returns each base's agents, and compose/create-template accept a per-module `agent_name`. ## What changed - `codersdk/templatebuilder.go`: added `TemplateBuilderBaseAgent`, `TemplateBuilderBase.Agents`, and `TemplateBuilderComposeModule.AgentName` (`agent_name,omitempty`). - `coderd/templatebuilder_handler.go`: added `baseAgentsToSDK`; the bases endpoint returns agents, and the compose and create-template endpoints forward `AgentName`. - `make gen` regenerated `site/src/api/typesGenerated.ts`, `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`, `docs/reference/api/schemas.md`, and `docs/reference/api/templatebuilder.md`. - `wizardState.test.ts`: added `agents: []` to the base fixture now that the field is required on the generated type. ## Scope SDK/API plumbing only. `ComposeModule.AgentName` now has a producer (the handlers) but no caller sets it yet — the wizard UI (follow-up) is what will populate it. No DB change, so `enterprise/audit/table.go` is unaffected. ## Testing - Bases endpoint asserts each base returns agents with exactly one default (and the `dev`/`main` names). - Per-module `agent_name` round-trip and unknown-agent (400) compose tests. - `make gen` (idempotent), `make fmt` (no changes), `golangci-lint ./coderd/... ./codersdk/...`, the Go template-builder tests, frontend `tsc` + `biome check`, and docs markdownlint all pass. <details> <summary>Design note</summary> `display_name` is intentionally returned as `""` for now: every base is single-agent, so no base authors a per-agent label. The field exists for multi-agent bases where the wizard radio needs a human-readable name; consumers fall back to the agent `name` when it is empty. </details> --- 🤖 Generated by Coder Agents on behalf of @jeremyruppel. Co-authored-by: Coder Agents <agents@coder.com> |
||
|
|
4875ae218a |
feat: enforce user secret file policy (#28518)
Adds the deployment option `--user-secrets-disable-file-path` / `CODER_USER_SECRETS_DISABLE_FILE_PATH` / `userSecretsDisableFilePath` (default `false`). When it is set, the create and batch-create user-secret endpoints reject requests with a non-empty file path, and PATCH validates the post-update state under a `SELECT ... FOR UPDATE` row lock, rejecting a new or changed file path as well as enabled states that would have no effective delivery target. Legacy stored paths are preserved, so users can still edit, disable, clear the path, or migrate the secret to env delivery. This is PR 1 of a 4-PR stack; follow-ups cover manifest filtering, the dashboard, and CLI/docs. Refs #27488 Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder. |
||
|
|
6db09ed9a6 | fix: sync pinned chat MCP context resources on agent push (#28796) | ||
|
|
55340de360 |
feat: add deployment setting to disable the Codernauts game (#27662)
Adds a `codernauts_enabled` runtime setting (default: enabled) that controls whether the Codernauts game link appears in the user dropdown menu. A toggle at the bottom of the Deployment > Appearance page controls it, and the value persists in `site_configs`, so it survives restarts and upgrades without any CLI flags or environment variables. The setting works on all licenses: `GET /api/v2/appearance` reports it from both the enterprise and the default (AGPL) appearance fetchers, and `PUT /api/v2/appearance` persists it gated only by the deployment-config RBAC permission, not by an entitlement. On the Appearance page the toggle renders outside the Premium paywall introduced in #27948; the other appearance fields keep their existing licensing behavior. Note: a pure AGPL-only build of coderd does not register the `/api/v2/appearance` routes at all, so the toggle cannot be saved there. The standard `coder server` binary is unaffected regardless of license state. <details> <summary>Implementation notes</summary> - `coderd/database/queries/siteconfig.sql`: new `GetCodernautsEnabled` / `UpsertCodernautsEnabled` queries backed by a `codernauts_enabled` key in `site_configs`; defaults to `true` when unset (no migration needed). - `coderd/database/dbauthz`: read has no authz checks (matching other appearance reads); write requires `ResourceDeploymentConfig` update. Coverage added to `dbauthz_test.go`. - `codersdk`: `codernauts_enabled` added to `AppearanceConfig` and `UpdateAppearanceConfig`. - `coderd/appearance`: the default fetcher takes a `database.Store` and reads the setting from the database so unlicensed deployments serve it too. - `enterprise/coderd/appearance.go`: fetches the value in `Fetch` and persists it in `putAppearance`. - Frontend: "Codernauts game" toggle section on Deployment > Appearance saving immediately via the existing appearance mutation; `codernauts_enabled` threaded from `useDashboard().appearance` through Navbar to `UserDropdownContent`, which renders the menu item only when enabled. Storybook stories with `play` functions cover toggling (entitled and not) and the dropdown hiding the link when disabled. </details> --- 🤖 This PR was generated by Coder Agents on behalf of @bartekgatzcoder. |
||
|
|
560ef00c15 |
chore: add Claude Fable 5.1 and other new models to the known models catalog (#28887)
Add the models that landed on models.dev since the August curation pass to the Agents-page known models list, so they appear as suggestions when an admin adds a chat model in `/agents` settings. | Model | Providers | |---|---| | Claude Fable 5.1 | anthropic, azure, bedrock (plus `global.` alias), openrouter, vercel | | Claude Opus 5 | anthropic (already curated on the other providers) | | Gemini 3.7 Flash | google | | GLM 5.3 | openrouter, vercel | Fable 5.1 and Opus 5 use `reasoningEffort: high` like their curated siblings, and new entries sort ahead of the models they supersede. `knownModelsGenerated.json` and `coderd/aibridge/prices/data/prices.json` are both regenerated with `make gen/aibridge-prices` from the same models.dev snapshot; the `prices.json` changes are upstream drift since the last weekly refresh. Left out pending a decision: azure now lists `claude-mythos-5` upstream but it is not curated for azure here, and `copilot` has no curation entries at all. > Xum opened this PR on behalf of @ibetitsmike. |
||
|
|
fb0bdd3feb | chore: remove tasks frontend (#28743) | ||
|
|
117c0f7b11 |
feat: distinct NewUser and Product trial sources (#28882)
* [DEVEX-847/distinct-newuser-and-product-trial-sources](https://linear.app/codercom/issue/DEVEX-847/distinct-newuser-and-product-trial-sources) * for premium trial signups with a new user account creation, passes the `NewUser` trial source. * for premium trial signups from the /deployment/premium account page, passes the `Product` trial source |