Commit Graph
758 Commits
Author SHA1 Message Date
Michael Suchacz 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.
2026-09-11 10:47:43 +02:00
Michael Suchacz 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.
2026-09-11 08:05:53 +00:00
Michael Suchacz 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.
2026-09-11 01:48:56 +00:00
Bobby Ho 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.
2026-09-10 10:49:28 -07:00
Jake HowellandTyler 8a4f2f80fa refactor: implement standard IdP sync settings (#28935)
> 🤖 This PR was written by Coder Agents on behalf of Jake Howell.

Refactors the IdP sync settings pages to use the shared settings
patterns and make group and role mapping management clearer. It also
separates claim-value loading between the two tabs so each form
consistently reflects its configured sync field.

- reorganizes group and role sync controls into clearer settings
sections (standard components)
- preserves the group and role tabs while loading claim values
independently
- adds a typed confirmation dialog before deleting group mappings
- consolidates policy export and unseen-claim UI into shared components

| <img width="2880" height="1800" alt="idp-sync-group-settings"
src="https://github.com/user-attachments/assets/bc0cca7d-f56d-459b-a284-518a551386bb"
/> | <img width="2880" height="1800" alt="idp-sync-delete-dialog"
src="https://github.com/user-attachments/assets/702a8435-8f0c-4232-b515-1df4210f1500"
/> |
| --- | --- |

---------

Co-authored-by: Tyler <tyler.tate@coder.com>
2026-09-10 20:28:09 +10:00
Bobby Ho 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
2026-09-09 11:42:57 -07:00
Bobby Ho 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.
2026-09-09 11:25:17 -07:00
Bobby Ho 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.
2026-09-09 11:08:34 -07:00
Paweł Banaszewski 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.
2026-09-09 10:16:24 +02:00
Bobby Ho 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.
2026-09-08 17:40:10 -07:00
Nick Vigilante 7846490770 docs: reconcile H1/label mismatches into front-matter titles (Phase 3) (#28036)
## Summary

**Batch B of Phase 3** of the H1 → front-matter migration (`DOCS-484`;
parent `DOCS-477`), the editorial follow-up to Batch A (#28030). For the
**124** hand-authored pages whose leading body H1 differed from the
manifest nav label, this promotes the richer body H1 to the front-matter
**page title** and drops the duplicate H1, while keeping the short
manifest **label** as the sidebar entry.

Policy agreed with the docs owner:
- Short sidebar labels win. Duplicate sidebar labels are acceptable.
- Identical **page titles** across two pages are not. On a collision,
rename the non-generated page's title.

## Page-title collisions resolved

Promoting the H1 created 4 page-title collisions; each is disambiguated
by renaming the non-generated / secondary page (sidebar labels left
unchanged):

| page | sidebar label | body H1 | → page title |
|------|---------------|---------|--------------|
| `install/index.md` | Install | Installing Coder | **Install Coder in
your infrastructure** |
| `install/cli.md` | Coder CLI | Installing Coder | **Install the Coder
CLI** |
| `ai-gateway/clients/jetbrains.md` | JetBrains | JetBrains IDEs |
**JetBrains** |
| `workspace-access/web-ides.md` | Web IDEs and Coder Apps | Web IDEs |
Web IDEs *(kept — primary user guide)* |
| `extending-templates/web-ides.md` | Web IDEs and Coder Apps | Web IDEs
| **Web IDEs in templates** |
| `workspace-management.md` | Workspace Management | Workspaces |
**Manage workspaces** *(vs generated `api/workspaces.md`)* |

These titles are the only non-mechanical editorial calls in this PR.

## Deliberately excluded: generated pages

`admin/security/audit-logs.md` and
`admin/setup/configuration-reference.md` are `make gen` outputs
(`auditdocgen` / `configdocgen`) that Phase 2 did **not** update, so a
hand-added title would be reverted on the next generation. They're
excluded here and need their generators taught to emit front matter
first (Phase 2 pattern), tracked as `DOCS-631`. Batch A (#28030) had the
same issue for three other generated pages; it has been corrected there
too.

## Verification

AI was the primary author of this PR (see disclosure below); per the [AI
Contribution
Guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING)
here is the manual verification.

- Promote = set front-matter `title` to the body H1 (or the
disambiguated title above) and remove that one duplicate H1. No other
body prose is reflowed.
- Every added front-matter block parses as YAML; all files pass `pnpm
check-docs` (markdownlint-cli2 + table formatter): `Summary: 0
error(s)`.
- Removing the H1 orphaned one in-page fragment (`[MCP](#mcp)` in
`ai-gateway/mcp.md`), now repointed. A cross-file fragment audit into
the retitled pages found no real breakage.


Anchor-change note

Unlike Batch A (title unchanged, a rendered no-op), Batch B changes each
page's effective title from the manifest label to the body H1, so the
rendered H1 **anchor slug changes**. An audit of cross-file
`.md#fragment` links into these pages surfaced no links that break as a
result (the only hits were false positives against a still-present `##
TLS & Reverse Proxy` heading). Same-file fragments are enforced by
markdownlint MD051, which is green.

## Title casing (follow-up, DOCS-742)

A follow-up commit puts the promoted titles into sentence case and
removes leading gerunds (for example, `Managing workspace schedules` →
`Manage workspace schedules`): 57 of the 120 titles changed, the other
63 were already compliant. Proper nouns and branded names (Coder
Validated Architecture, JetBrains, File Browser, Dev Containers,
Island), acronyms (API, CLI, IDE, MCP, OIDC, URL, UI, CI/CD), the
Premium license tier, and maturity labels (Beta, Experimental) are
preserved. The four `Nk-users` pages become `Reference architecture: up
to N users` (lowercase, matching the CVA landing page's own usage); the
CVA landing page keeps its branded title. `pnpm check-docs`: `Summary: 0
error(s)`.

Linear: DOCS-484, DOCS-742

> This PR was created with AI assistance (Coder Agents).
2026-09-08 16:34:00 +00:00
Jake Howell 486d2faa81 refactor: modernize the create user page (#28894)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

Redesigns the create user flow using the settings page layout and
renames it to "New user." The form includes clearer field guidance,
explicit authentication-method loading, error, and empty states, updated
documentation, and aligned end-to-end selectors.

| Old | New |
| --- | --- |
| <img width="2560" height="2516" alt="02-create-user"
src="https://github.com/user-attachments/assets/c79fb42b-3b0f-47fa-b03d-801c81584dba"/>
| <img width="2560" height="2748" alt="02-create-user-page"
src="https://github.com/user-attachments/assets/2d2dd777-3ae9-444d-9811-082f30eb8387"/>
|

Depends on #28893.

<details>
<summary>Stack</summary>

1. #28893 - Edit user page redesign
2. #28894 - Create user page redesign (this PR)

</details>
2026-09-09 00:35:42 +10:00
Jake Howell 3b1828db5b refactor: modernize the edit user page (#28893)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

Redesigns the edit user page using the settings page layout, with
clearer field guidance, explicit loading and error states, documentation
and back links, and access to the shared user administration menu.

Successful updates refresh the page heading and query cache without
resetting an in-progress form during background refetches.

| Old | New |
| --- | --- |
| <img width="2560" height="1800" alt="03-edit-user-member"
src="https://github.com/user-attachments/assets/915434fe-9587-49e9-b962-cc1ebeca3ea4"
/> | <img width="2560" height="1800" alt="02-edit-user-page"
src="https://github.com/user-attachments/assets/2b188c26-4268-4498-96a0-4fd1825a6a49"
/> |
| `** didnt exist **` | <img width="2560" height="1800"
alt="03-edit-user-page-action-menu"
src="https://github.com/user-attachments/assets/1e657626-ab43-4d49-a375-414896728fb9"
/> |

<details>
<summary>Stack</summary>

1. #28893 - Edit user page redesign (this PR)
2. #28894 - Create user page redesign

</details>
2026-09-09 00:21:16 +10:00
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>
2026-09-03 18:29:11 -07:00
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 &#34;http://%zz\&#34;&gt;&lt;img src=x onerror=BAD&gt;&#34;...
literal `<img` in body: 0     entity encoded `&lt;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>
2026-09-03 10:54:34 -07:00
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>
2026-09-02 13:14:44 -07:00
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>
2026-09-02 12:43:32 -07:00
dylanhuff-at-coder 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.
2026-09-02 09:21:36 -07:00
9368917813 feat: report the negotiated scope to the user and the client (#28179)
**TL;DR**

Last of the stack, split out of #28045. #28178 decided what the scope
is; this PR is everything that reports it, to the user on the consent
page and to the client on rejection.

| PR | What it does |
|---|---|
| #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated
scope has somewhere to live. Every code is still stamped unrestricted. |
| #28167 | `ScopesCover` compares an allowlist against a request by
permission coverage rather than by name, and fails closed on any shape
it does not model. Added with no production callers. |
| #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. |
| **#28179 (this)** | The consent page lists the negotiated permissions,
and `invalid_scope` reaches the client's own callback per RFC 6749
§4.1.2.1 instead of a Coder error page. Retires the interim plumbing
#28178 left behind. |

- #28178 has merged, so this diff is against main and reviews on its
own. It is still worth reading first: nothing here decides a scope, it
only reports the one `negotiateScope` already returns.
- **The consent page HTML is not final.** Layout and wording in
`site/static/oauth2allow.html` are still being refined. It is in this
branch so the scope-enforcement flow can be exercised end to end in a
browser, not because the markup is settled. The reviewable part of Half
A is the Go side that decides what the page states; the presentation
will change.
- An unrestricted grant still reads as full access, not as a scope name.
Nothing about what a token can do changes in this PR either.

**Where in the flow**

- Authorize endpoint only, both verbs. GET decides what the consent page
states; both verbs send `invalid_scope` to the callback. The token
exchange, refresh, and revocation are untouched.
- `negotiateScope` is unchanged from #28178, so which requests succeed
is unchanged. This PR reads its result twice: once to decide what the
page lists, once to decide where the rejection goes.
- The endpoint sits behind `apiKeyMiddlewareRedirect`, so the user is
authenticated before any of this runs. That matters for the redirect,
not just for the page.
- Consent page rendering moves a decision into Go rather than the
template: `RenderOAuthAllowData` carries `Scopes` and `Unrestricted`
separately, and the template branches on `Unrestricted` alone.

**What it satisfies**

- RFC 6749 §4.1.2.1 — on a failure that is not a bad redirection URI,
the server "informs the client by adding the following parameters to the
query component of the redirection URI". `invalid_scope` now goes there.
#28178's interim delivery, a static error page on GET and an error body
on POST, is what this replaces.
- RFC 6749 §4.1.2.1 — `state` is "REQUIRED if a `state` parameter was
present in the client authorization request", so it is echoed only when
the client sent one, never synthesized. Pinned by
`OmittedStateNotEchoed`.
- RFC 6749 §3.1.2.4 and §4.1.2.1 — on a "missing, invalid, or
mismatching redirection URI" the server "MUST NOT automatically redirect
the user-agent to the invalid redirection URI". This is the whole
ordering argument, and the file's other error paths keep their existing
delivery precisely because several of them are where that validation
fails.
- RFC 9700 §2.1 — pre-registered redirection URIs "MUST utilize exact
string matching". `extractAuthorizeParams` already did this before the
stack; Half B depends on it rather than adding it.
- RFC 9700 §4.11.2 — names this exact hazard: an attacker who registers
a client can "intentionally send an erroneous authorization request,
e.g., by using an invalid scope value, thus instructing the
authorization server to redirect the user agent to its phishing site".
The destination is still only ever a URI that client registered, so this
is a phishing surface that costs an attacker a registration, not an open
redirect. The precaution the section requires, authenticating the user
first, is what `apiKeyMiddlewareRedirect` provides.
- RFC 9700 §4.12 — a server redirecting a request that may carry
credentials "MUST NOT use the HTTP 307 status code". 302, matching the
success redirect beside it.
- RFC 6749 §4.1.2.1 — `server_error` exists "because a 500 Internal
Server Error HTTP status code cannot be returned to the client via an
HTTP redirect". An unusable registered callback is the one case with
nowhere to redirect, so it answers 500 on both verbs and logs the app
and URL for an operator to correlate by.
- Not yet: §1.4.1 still wants `scope` in the token response when the
grant differs from the request. Tokens are untouched here, as in #28178,
so that lands with enforcement.

---

Split out of #28045
([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Last of three.
#28178 has merged, so this reviews against main.

#28178 decided what the scope is. This PR is everything that tells
someone about it.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
2026-09-01 09:16:08 -07:00
Bobby Ho 20a41c067e feat: reject secret creation and fix reporting for public clients (#28097)
**TL;DR**

On top of #28047, closing the last two gaps in the stack split out of
#27873. A public client can now register (#28046) and exchange a code
(#28047), but the admin secrets API will still issue it a secret that
authenticates nothing, and the registration responses still report an
auth method the token endpoint will not accept.

| PR | What it does |
|---|---|
| #27712 | Schema: `app_secret_id` becomes nullable and tokens gain an
always-populated `app_id`, so ownership checks work without a secret
row. |
| #28041 | Accepts bare custom-scheme redirect URIs (`vscode://`,
`cursor://`) that native apps actually register. |
| #28043 | Derives and stores `client_type` (public vs confidential)
from the requested `token_endpoint_auth_method`, and pins it across
updates. |
| #28046 | Registration issues no secret for a public client and returns
no `client_secret`. |
| #28047 | The token endpoint accepts the exchange without a
`client_secret`. Discovery advertises `none`. |
| **#28097 (this)** | The admin secrets API refuses to create a secret
for a public client, and registration, read, and update report the auth
method the token endpoint actually enforces. |

A public client can only come into existence through dynamic client
registration, which is off by default, so neither guard is reachable
until DCR is enabled.

**Where in the flow**

- `POST /oauth2-provider/apps/{app}/secrets`, the admin secrets API. The
rest of the secret lifecycle is untouched: `GET` and `DELETE` are
unchanged, and a confidential app behaves exactly as before.
- The three RFC 7591 and 7592 responses that carry
`token_endpoint_auth_method`: registration (`POST`), read (`GET`), and
update (`PUT`). Only what is reported changes; the stored column is left
as the client sent it.
- Authorize, token exchange, refresh, and revocation are untouched.

**What it satisfies**

- RFC 7591 §2: `none` means the client is public and "does not have a
client secret", so the secrets API should not create one for it.
- RFC 7591 §3.2.1: the server MUST return all registered metadata and
MAY replace a requested value with a suitable one. Reporting the
enforced method in place of a stored one that contradicts `client_type`
is that substitution.
- RFC 7592 §2.2: an update MUST include all metadata as returned by a
previous registration, read, or update. Because clients echo back what
Coder reports, reporting the enforced method is what lets a legacy row
heal on the client's next `PUT`.
- RFC 7591 §2 default: an app with no stored method reports
`client_secret_basic`, which is both the RFC default and what
`ApplyDefaults` substitutes on update.
- OAuth 2.1 §3.2.1: the token endpoint enforces on `client_type`, so a
reported method that disagrees with it tells a client to authenticate in
a way the server will reject.

---

- `CreateAppSecret` returns 400 for a public client before generating
anything. The secret would authenticate nothing, since the token
endpoint no longer checks one for a public client. Deleting it would be
worse: `oauth2_provider_app_tokens.app_secret_id` is `ON DELETE
CASCADE`, so removing a confidential app's secret takes its tokens with
it, but a public client's tokens carry a NULL `app_secret_id` (#27712)
and survive. An admin who deleted the secret would think they had cut
off the client when they had not.
- `reportedAuthMethod()` replaces the raw stored value in all three
registration responses. It returns the stored method when it agrees with
`client_type`, `none` for a public app, and `client_secret_basic`
otherwise.
- The rows that can disagree are clients registered before #28043
derived the type from the method: the method was stored as sent while
the type was always `confidential`. Such a client holds a secret its
exchange still requires, while `GET` reported `none` and told it to drop
that secret.
- The stored column is deliberately not rewritten, so the response can
still differ from the row. That divergence is what a read-modify-write
client resolves on its next update, and the test asserts the row keeps
what the client sent.
- Coverage: the secrets guard asserts the 400 and that no partial secret
row was left behind. A table test walks `GET` then `PUT` over six
stored-method and client-type pairs: the legacy mismatch in both resend
shapes, the reverse mismatch that registration cannot produce but the
function still handles, an empty stored method, and the single pair that
already agrees and must be reported as stored.
- Docs: the client type is fixed at registration and a type-changing
update is rejected with `invalid_client_metadata` (behavior from #28043
that was never written down), plus what a legacy `none` client now sees.

Refs
https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client



## Manual Tests

Verified by hand against a local dev deployment
(`v2.36.3-devel+c85e4621ef`, dev Postgres), in addition to the automated
suite.

Both guards are reachable only through dynamic client registration,
which was confirmed off by default on this deployment and enabled for
the run. Two of the scenarios need a row where `client_type` and
`token_endpoint_auth_method` disagree, which registration cannot produce
since #28043 derives one from the other, so those rows were seeded by
updating the method column directly on a purpose-built client.

| # | Scenario | Result |
|---|----------|--------|
| 1 | Secrets API refuses a public client, with the guard's own message
| Pass |
| 2 | No partial secret row is left behind by the rejection | Pass |
| 3 | A confidential app's secret create, list, and delete are unchanged
| Pass |
| 4 | Admin-created apps are always confidential, so the guard is
unreachable there | Pass |
| 5 | When stored method and client type agree, the stored value is
reported unchanged | Pass |
| 6 | A legacy confidential row storing `none` reports
`client_secret_basic` | Pass |
| 7 | The reported method is the one the token endpoint enforces, in
both directions | Pass |
| 8 | An update resending the stored value is accepted and leaves the
row alone | Pass |
| 9 | An update resending the reported value heals the row | Pass |
| 10 | The reverse mismatch, a public row storing a secret method,
reports `none` | Pass |
| 11 | An empty or unrecognized stored method falls back to
`client_secret_basic` | Pass |
| 12 | Type-changing updates are rejected both ways,
`client_secret_basic` to `client_secret_post` is allowed | Pass |
| 13 | Regression sweep of the merged stack, discovery through
revocation | Pass |
| 14 | Every claim in the new docs paragraphs matches observed behavior
| Pass |

No correctness defects found. Commands and captured output for each
scenario below.

**Two notes for anyone re-running this.**

The previous runbook for this stack asserts the opposite of scenario 12:
it flips a confidential client to public with a `PUT` and records `200`.
That was correct before #28043 pinned the client type. The `400` here is
the fix, not a regression.

Generate the PKCE verifier with enough entropy that stripping `=+/`
still leaves 43 characters. The `openssl rand -base64 32 | tr -d "=+/" |
cut -c -43` recipe yields 38 to 43, so most runs are rejected by the
token endpoint under RFC 7636 section 4.1 with an error that looks
unrelated. Same trap noted in #28045.

<details>
<summary>Shell helpers used throughout</summary>

```bash
export BASE_URL=http://localhost:3000
export AUTH_HEADER="Coder-Session-Token: $(cat ./.coderv2/session)"
export PGURL="postgres://coder@localhost:$(cat ./.coderv2/postgres/port)/coder?sslmode=disable&password=$(cat ./.coderv2/postgres/password)"

# Enable DCR; both guards are unreachable without it.
curl -s -X PUT "$BASE_URL/api/v2/oauth2-provider/settings" -H "$AUTH_HEADER" \
  -H "Content-Type: application/json" \
  -d '{"dynamic_client_registration_enabled": true}'

# Print "HTTP <code>" then the body.
show() {
  local out; out=$(curl -s -w '\n%{http_code}' "$@")
  echo "HTTP $(printf '%s\n' "$out" | tail -n1)"
  printf '%s\n' "$out" | sed '$d' | jq . 2>/dev/null || printf '%s\n' "$out" | sed '$d'
}

# $1=name, $2=auth method ("" to omit the field).
register() {
  local body
  if [ -z "$2" ]; then
    body=$(jq -nc --arg n "$1" '{client_name:$n,redirect_uris:["http://localhost:9876/callback"]}')
  else
    body=$(jq -nc --arg n "$1" --arg m "$2" '{client_name:$n,redirect_uris:["http://localhost:9876/callback"],token_endpoint_auth_method:$m}')
  fi
  curl -s -X POST "$BASE_URL/oauth2/register" -H "Content-Type: application/json" -d "$body"
}

# The stored row, as opposed to what the API reports.
stored() {
  psql "$PGURL" -At -c "select client_type || ' | ' || coalesce(token_endpoint_auth_method,'<NULL>')
    from oauth2_provider_apps where id = '$1';"
}

# 43 characters from the unreserved set, always. See the note above.
gen_verifier() { openssl rand -base64 96 | tr -d "=+/\n" | cut -c -43; }
challenge_for() { printf '%s' "$1" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_'; }

# Full PKCE authorize plus exchange. $1=client_id, $2=client_secret ("" for none).
exchange() {
  local verifier challenge redirect code args
  verifier=$(gen_verifier); challenge=$(challenge_for "$verifier")
  redirect=$(curl -s -X POST \
    "$BASE_URL/oauth2/authorize?client_id=$1&response_type=code&redirect_uri=http://localhost:9876/callback&state=$(openssl rand -hex 16)&code_challenge=$challenge&code_challenge_method=S256" \
    -H "$AUTH_HEADER" -w '\n%{redirect_url}' -o /dev/null)
  code=$(printf '%s' "$redirect" | grep -oE 'code=[^&]+' | sed 's/code=//')
  args=(-d "grant_type=authorization_code" -d "code=$code" -d "client_id=$1"
        -d "redirect_uri=http://localhost:9876/callback" -d "code_verifier=$verifier")
  [ -n "$2" ] && args+=(-d "client_secret=$2")
  curl -s -X POST "$BASE_URL/oauth2/tokens" -H "Content-Type: application/x-www-form-urlencoded" "${args[@]}"
}
```

</details>

<details>
<summary>1. Secrets API refuses a public client</summary>

A bare non-`201` would also be produced by a request that failed on
authentication, routing, or a malformed UUID before reaching the guard,
so the status and the message are both asserted.

```bash
PUB=$(register manual-28097-public none)
PUB_ID=$(echo "$PUB" | jq -r '.client_id')
stored "$PUB_ID"
show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$PUB_ID/secrets" -H "$AUTH_HEADER"
```

```text
public | none
HTTP 400
{
  "message": "Cannot create a client secret for a public OAuth2 app.",
  "detail": "Public clients authenticate with PKCE and have no client secret. The client type is fixed at registration, so register a new confidential client instead."
}
```

The message is the guard's own, so execution reached `CreateAppSecret`
and returned at the `IsPublic()` check. The detail points at registering
a new confidential client, which scenario 12 confirms is the only
remedy.

</details>

<details>
<summary>2. No partial secret row is left behind</summary>

The guard returns before `GenerateSecret()`, so nothing should exist at
either layer. The count was already `0` at registration, and a
confidential app is queried the same way as a control, so `0` is not
merely what this query always returns.

```bash
curl -s "$BASE_URL/api/v2/oauth2-provider/apps/$PUB_ID/secrets" -H "$AUTH_HEADER" | jq -c .
psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$PUB_ID';"
psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$CONF_ID';"
```

```text
[]
0
1
```

</details>

<details>
<summary>3. A confidential app's secret lifecycle is unchanged</summary>

```bash
CONF=$(register manual-28097-confidential "")
CONF_ID=$(echo "$CONF" | jq -r '.client_id')
show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets" -H "$AUTH_HEADER"
curl -s "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets" -H "$AUTH_HEADER" | jq -c '[.[].id]'
curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets/$SECRET_ID" \
  -H "$AUTH_HEADER" -o /dev/null -w "delete: HTTP %{http_code}\n"
```

```text
HTTP 201
{
  "id": "da7a1029-47c4-435e-988a-557ffa4aeacf",
  "client_secret_full": "coder_POUtoElODM_<redacted>"
}
["b2fc55b6-...","da7a1029-...","24f8f8c2-..."]
delete: HTTP 204
["b2fc55b6-...","da7a1029-..."]
```

Create, list, and delete all behave as before. The guard keys on
`client_type` and nothing else on this path changed.

Unrelated observation, not a finding against this PR: the listing
returns two different `client_secret_truncated` formats. Secrets issued
at registration are asterisk-padded (`***...TzqEOt`, from
`createDisplaySecret`), while secrets issued through the admin API show
the bare last six characters (`Rixs60`). Both write the same column and
surface through the same field. Cosmetic and pre-existing, but a UI
listing both kinds together would render them inconsistently.

</details>

<details>
<summary>4. Admin-created apps are always confidential</summary>

`postOAuth2ProviderApp` hardcodes the client type, so the guard is
unreachable through the admin create path.

```bash
ADMIN_APP=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps" -H "$AUTH_HEADER" \
  -H "Content-Type: application/json" \
  -d '{"name":"manual-28097-admin","callback_url":"http://localhost:9876/callback"}')
ADMIN_ID=$(echo "$ADMIN_APP" | jq -r '.id')
stored "$ADMIN_ID"
show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$ADMIN_ID/secrets" -H "$AUTH_HEADER"
```

```text
confidential | client_secret_post
HTTP 201
{
  "id": "a77ab276-ea74-4711-ba8b-955a8cb97951",
  "client_secret_full": "coder_eGlt04LhYg_<redacted>"
}
```

Together with scenario 1 this brackets the guard: it fires for a
dynamically registered public client and for nothing else. Note the
admin API stores `client_secret_post`, not the RFC 7591 section 2
default, so every admin-created app is an agreement case for scenario 5.
Such apps carry no registration access token, so they cannot reach the
RFC 7592 endpoints where the reporting change applies at all.

</details>

<details>
<summary>5. Agreement cases report the stored value unchanged</summary>

The `client_secret_post` case is the one that matters. An implementation
that substituted the type default on every call would still pass the
public case, since `none` is the public default, but would rewrite this
client to `client_secret_basic` and tell it to send its secret in the
wrong place.

```bash
curl -s "$BASE_URL/oauth2/clients/$PUB_ID" -H "Authorization: Bearer $PUB_RAT" \
  | jq -c '{reported: .token_endpoint_auth_method}'

POST_REG=$(register manual-28097-post client_secret_post)
POST_ID=$(echo "$POST_REG" | jq -r '.client_id')
echo "$POST_REG" | jq -c '{reported_on_register: .token_endpoint_auth_method}'
curl -s "$BASE_URL/oauth2/clients/$POST_ID" -H "Authorization: Bearer $POST_RAT" \
  | jq -c '.token_endpoint_auth_method'
stored "$POST_ID"
```

```text
{"reported":"none"}
{"reported_on_register":"client_secret_post"}
"client_secret_post"
confidential | client_secret_post
```

Registration and read both report the stored value. The update site is
covered by scenarios 8 and 9.

</details>

<details>
<summary>6. A legacy confidential row storing `none` reports
`client_secret_basic`</summary>

Seeded from a real confidential client so it genuinely holds the secret
its exchange requires, with only the method column rewritten. This is
the pre-#28043 shape and cannot be produced through the API any more.

```bash
LEGACY=$(register manual-28097-legacy "")
LEGACY_ID=$(echo "$LEGACY" | jq -r '.client_id')
LEGACY_SECRET=$(echo "$LEGACY" | jq -r '.client_secret')
stored "$LEGACY_ID"

psql "$PGURL" -c "update oauth2_provider_apps set token_endpoint_auth_method = 'none'
  where id = '$LEGACY_ID';"
stored "$LEGACY_ID"
psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$LEGACY_ID';"

curl -s "$BASE_URL/oauth2/clients/$LEGACY_ID" -H "Authorization: Bearer $LEGACY_RAT" \
  | jq -c '{reported: .token_endpoint_auth_method}'
stored "$LEGACY_ID"
```

```text
confidential | client_secret_basic
UPDATE 1
confidential | none
1
{"reported":"client_secret_basic"}
confidential | none
```

The response substitutes and the row is deliberately not rewritten. A
read has no side effects.

</details>

<details>
<summary>7. The reported method is the one actually enforced</summary>

The token endpoint enforces on `client_type`, which is still
confidential, so the secret is required regardless of what the method
column says.

```bash
exchange "$LEGACY_ID" "$LEGACY_SECRET" | jq -c '{has_access: has("access_token"), error, error_description}'
exchange "$LEGACY_ID" ""               | jq -c '{has_access: has("access_token"), error, error_description}'
```

```text
{"has_access":true,"error":null,"error_description":null}
{"has_access":false,"error":"invalid_request","error_description":"Missing required parameter: client_secret"}
```

The second line is the pre-fix breakage reproduced. A client that read
`"token_endpoint_auth_method": "none"` from `GET` and dropped its secret
accordingly, which is what RFC 7592 tells it to do, would have hit
exactly this on its next exchange. The old response was not internally
inconsistent, it was actionable and wrong.

Scenario 10 shows the same property in the opposite direction.

</details>

<details>
<summary>8. An update resending the stored value is accepted and changes
nothing</summary>

```bash
show -X PUT "$BASE_URL/oauth2/clients/$LEGACY_ID" \
  -H "Authorization: Bearer $LEGACY_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-legacy","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}'
stored "$LEGACY_ID"
```

```text
HTTP 200
  "token_endpoint_auth_method": "client_secret_basic",
confidential | none
```

Three things at once. The update is accepted, which is why the
type-change guard requires the auth method to actually change: the
requested `none` implies a public client while the row is confidential,
so a guard keyed on the type mismatch alone would reject this and lock a
legacy client out of managing its own registration. The `PUT` reports
the same substituted value as the `GET`, covering the third call site.
The row keeps what the client sent, so the divergence persists until
scenario 9.

</details>

<details>
<summary>9. An update resending the reported value heals the
row</summary>

```bash
show -X PUT "$BASE_URL/oauth2/clients/$LEGACY_ID" \
  -H "Authorization: Bearer $LEGACY_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-legacy","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_basic"}'
stored "$LEGACY_ID"
curl -s "$BASE_URL/oauth2/clients/$LEGACY_ID" -H "Authorization: Bearer $LEGACY_RAT" \
  | jq -c '{reported: .token_endpoint_auth_method}'
exchange "$LEGACY_ID" "$LEGACY_SECRET" | jq -c '{has_access: has("access_token")}'
```

```text
HTTP 200
  "token_endpoint_auth_method": "client_secret_basic",
confidential | client_secret_basic
{"reported":"client_secret_basic"}
{"has_access":true}
```

The row healed through an ordinary read-modify-write cycle, with no
migration, backfill, or admin action. That works only because scenario 8
keeps the door open and this response gives the client a correct value
to echo back; remove either and the row stays inconsistent indefinitely.

</details>

<details>
<summary>10. The reverse mismatch reports `none`</summary>

Registration cannot produce this direction either, but
`reportedAuthMethod` branches on the general disagreement rather than
the one shape known to exist, so it is covered.

```bash
REVERSE=$(register manual-28097-reverse none)
REVERSE_ID=$(echo "$REVERSE" | jq -r '.client_id')
psql "$PGURL" -c "update oauth2_provider_apps set token_endpoint_auth_method = 'client_secret_basic'
  where id = '$REVERSE_ID';"
stored "$REVERSE_ID"
curl -s "$BASE_URL/oauth2/clients/$REVERSE_ID" -H "Authorization: Bearer $REVERSE_RAT" \
  | jq -c '{reported: .token_endpoint_auth_method}'
exchange "$REVERSE_ID" "" | jq -c '{has_access: has("access_token"), error}'
```

```text
public | client_secret_basic
{"reported":"none"}
{"has_access":true,"error":null}
```

This client has no secret row at all and the token endpoint does not ask
for one, so `none` is what the response should say. Reporting the stored
`client_secret_basic` would have instructed it to send a secret that
does not exist.

Both resend shapes behave symmetrically with scenarios 8 and 9:

```text
resend stored (client_secret_basic) -> reported "none", row unchanged
resend reported (none)              -> reported "none", row now public | none
```

</details>

<details>
<summary>11. Empty or unrecognized stored methods fall back to the
default</summary>

`NULL` and `''` are indistinguishable once read into `sql.NullString`. A
third case was added because the function gates on validity rather than
emptiness.

```bash
for v in "null" "''" "'private_key_jwt'"; do
  psql "$PGURL" -At -c "update oauth2_provider_apps set token_endpoint_auth_method = $v where id = '$CONF_ID';"
  stored "$CONF_ID"
  curl -s "$BASE_URL/oauth2/clients/$CONF_ID" -H "Authorization: Bearer $CONF_RAT" \
    | jq -c '.token_endpoint_auth_method'
done
```

```text
confidential | <NULL>
"client_secret_basic"
confidential |
"client_secret_basic"
confidential | private_key_jwt
"client_secret_basic"
```

`private_key_jwt` is a real RFC 7591 method that Coder does not
implement. Reporting it back would advertise an authentication scheme
the token endpoint cannot honor, which is the same class of problem as
the legacy `none` report in scenario 7.

</details>

<details>
<summary>12. Type-changing updates are rejected both ways</summary>

```bash
show -X PUT "$BASE_URL/oauth2/clients/$CONF_ID" \
  -H "Authorization: Bearer $CONF_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-confidential","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}'
stored "$CONF_ID"

show -X PUT "$BASE_URL/oauth2/clients/$PUB_ID" \
  -H "Authorization: Bearer $PUB_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-public","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_basic"}'
stored "$PUB_ID"

show -X PUT "$BASE_URL/oauth2/clients/$CONF_ID" \
  -H "Authorization: Bearer $CONF_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-confidential","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_post"}'
stored "$CONF_ID"
```

```text
HTTP 400
{
  "error": "invalid_client_metadata",
  "error_description": "token_endpoint_auth_method cannot move an existing client between public and confidential (stored \"client_secret_basic\", requested \"none\"); the client type is fixed at registration, so register a new client instead"
}
confidential | client_secret_basic

HTTP 400
{
  "error": "invalid_client_metadata",
  "error_description": "token_endpoint_auth_method cannot move an existing client between public and confidential (stored \"none\", requested \"client_secret_basic\"); the client type is fixed at registration, so register a new client instead"
}
public | none

HTTP 200
  "token_endpoint_auth_method": "client_secret_post",
confidential | client_secret_post
```

Both rejections leave the row and its secrets untouched. A partial
application would be the dangerous outcome here, a client left
confidential while its caller believes it went public.

The third case is the control. Two `400`s alone would be equally
consistent with a guard that rejects every `token_endpoint_auth_method`
change, a considerably more disruptive rule than the documented one. The
`200` pins the guard to the derived client type rather than the method
string.

The second case is also what backs scenario 1. If public to confidential
were permitted, the workaround to a refused secret request would be to
flip the type and ask again. The two guards close that loop, which is
why the same remedy appears in both error messages.

</details>

<details>
<summary>13. Regression sweep of the merged stack</summary>

Nothing here is new in this PR, but the guards sit on top of it.

```text
discovery token_endpoint_auth_methods_supported : ["client_secret_basic","client_secret_post","none"]
public registration, client_secret key present  : false
confidential registration, secret issued        : true, method defaulted to client_secret_basic
PKCE-only exchange, no client_secret sent       : access + refresh issued
access token against /api/v2/users/me           : 200
token row app_id / app_secret_id                : populated / NULL
RFC 7009 revoke of own refresh token            : 200, access token then 401
authorized-apps listing while a token is live   : [{"name":"manual-28097-public"}]
bulk DELETE /oauth2/tokens                      : 204, listing then []
```

The NULL `app_secret_id` is what makes the secrets guard necessary. That
column is `ON DELETE CASCADE`, so deleting a confidential app's secret
takes its tokens with it, while a public client's tokens would survive.
An admin who deleted such a secret would believe access was cut off when
it was not.

PKCE failure modes were checked separately, since the token endpoint
distinguishes two the previous runbook treated as one:

```text
verifier omitted                     : invalid_request, RFC 7636 section 4.1 bounds
well-formed 43 chars but wrong       : invalid_grant, "The PKCE code verifier is invalid"
correct verifier, replaying that code: invalid_grant, "invalid or expired"
```

The third confirms the failed check destroys the code, so a leaked code
cannot absorb repeated verifier guesses.

</details>

<details>
<summary>14. The new docs paragraphs match observed behavior</summary>

`pnpm run lint-docs` reports 0 errors across 501 files, `pnpm run
format-docs` rewrites nothing, and Vale reports 0 errors with 2
warnings, both on pre-existing gerund headings that the same file on
`main` also produces. The new prose is one sentence per line.

| Documented claim | Verified by |
|---|---|
| A client's type is fixed when it registers | 12 |
| A type-changing update is rejected with `invalid_client_metadata` |
12, both directions |
| The client either holds a secret that would stop being required or has
none and no way to be issued one | 12 (2 secrets), 1 and 12 (0 secrets,
issuance refused) |
| Switching between `client_secret_basic` and `client_secret_post` is
allowed | 12 |
| To change type, register a new client | matches the remedy in both
errors and in scenario 1's detail |
| Legacy `none` clients are stored as confidential and still require
their `client_secret` | 6, 7 |
| Coder reports `client_secret_basic` for those clients | 6 |
| So that what it reports matches what it enforces | 7, both directions
|
| The mismatch clears itself the next time the client updates its
registration | 9 |

One wording note. Scenario 8 shows the mismatch does not clear on an
update that resends the stored value, so strictly it clears on the next
update carrying the reported value. A read-modify-write client, which is
what RFC 7592 section 2.2 prescribes, always carries the reported value,
so the sentence holds for the client it describes. A client that
hardcodes its own metadata would not self-heal, but it would also not be
following RFC 7592.

</details>

<details>
<summary>Cleanup</summary>

```bash
for id in "$PUB_ID" "$CONF_ID" "$POST_ID" "$LEGACY_ID" "$REVERSE_ID" "$ADMIN_ID"; do
  curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$id" -H "$AUTH_HEADER" \
    -o /dev/null -w "%{http_code}\n"
done
curl -s -X PUT "$BASE_URL/api/v2/oauth2-provider/settings" -H "$AUTH_HEADER" \
  -H "Content-Type: application/json" -d '{"dynamic_client_registration_enabled": false}'
show -X POST "$BASE_URL/oauth2/register" -H "Content-Type: application/json" \
  -d '{"client_name":"should-fail","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}'
```

```text
204 (x6)
{"dynamic_client_registration_enabled":false}
HTTP 403
{"error":"invalid_request","error_description":"Dynamic client registration is disabled on this deployment"}
```

All six test apps deleted with no orphaned secret or token rows. Both
seeded rows had already healed to a consistent state before deletion.
DCR is back off, confirmed by a registration attempt rather than by
reading the flag back.

</details>
2026-09-01 08:58:01 -07:00
Ben Potter 72872c4f2c docs(docs/admin/templates/extending-templates): document module caching and the disable toggle (#28800)
Coder caches resolved Terraform modules per template version and reuses
them across workspace builds instead of re-fetching from origin. This is
enabled by default and can be disabled per-template with
`disable_module_cache`, but neither the caching behavior nor the toggle
were documented anywhere outside the generated API reference.

Documents module caching in the Terraform Modules guide (what gets
cached, the 20MB archive limit, and how to disable it), and cross-links
it from the existing "Module not loaded" troubleshooting entry in the
Dynamic Parameters doc, since both describe the same module archive.

Also documents a second cause of "Module not loaded" warnings: template
versions published before Coder started archiving modules for Dynamic
Parameters have no cache at all, so every module in the template shows
the warning in the workspace creation form. Workspace builds still
succeed, since Terraform fetches modules from their original sources
during the build regardless of the cache; only the form's ability to
evaluate module-backed parameter values is affected. Publishing a new
template version regenerates the archive and resolves it.

<details>
<summary>Verification notes</summary>

Behavior confirmed by reading the source, not assumed:

- `coderd/provisionerdserver/provisionerdserver.go`: skips fetching
`CachedModuleFiles` for a workspace build when
`template.DisableModuleCache` is set. The same file's comment ("Older
templates (before dynamic parameters) will not have cached module
files") confirms why some template versions have no archive at all.
- `provisioner/terraform/provision.go` + `provisionerd/runner/init.go`:
the cached archive is extracted into `.terraform/modules` before
`terraform init` runs, so modules already present are not re-downloaded;
anything missing (e.g. skipped for size, or no archive at all) is still
fetched normally by Terraform during the build.
- `provisioner/terraform/modules.go`: `MaximumModuleArchiveSize` = 20MB.
-
`coderd/database/migrations/000416_workspace_module_reuse_toggle.up.sql`:
`disable_module_cache` defaults to `false`, i.e. caching is on by
default.
- `site/.../TemplateSettingsForm.tsx`: exact dashboard label and warning
copy reused verbatim in the doc.

</details>

> Generated by Coder Agents
2026-09-01 01:13:52 +00:00
Bobby Ho 9be61a0c65 feat: accept PKCE-only token exchange for public clients (#28047)
**TL;DR**

Last of the stack, split out of #27873, that makes Coder usable by
public OAuth2 clients (CLIs, IDE plugins, MCP clients), which cannot
hold a secret and authenticate with PKCE alone.

| PR | What it does |
|---|---|
| #27712 | Schema: `app_secret_id` becomes nullable and tokens gain an
always-populated `app_id`, so ownership checks work without a secret
row. |
| #28041 | Accepts bare custom-scheme redirect URIs (`vscode://`,
`cursor://`) that native apps actually register. |
| #28043 | Derives and stores `client_type` (public vs confidential)
from the requested `token_endpoint_auth_method`, and pins it across
updates. |
| #28046 | Registration issues no secret for a public client and returns
no `client_secret`. |
| **#28047 (this)** | The token endpoint accepts the exchange without a
`client_secret`, so a public client can finally get a token. Discovery
now advertises `none`. |

Each of the earlier PRs is inert on its own: until this one, a
registered public client still could not complete a flow. Dynamic client
registration is off by default, so nothing here is user-visible until it
is enabled.

**Where in the flow**

- Token endpoint only — the `authorization_code` exchange. Authorize,
consent, and code issuance are untouched.
- Refresh and revocation come along for free: both already bind by
app_id, so a secretless token row works as-is.
- Discovery starts advertising `none`.

**What it satisfies**

- OAuth 2.1 §3.2.1 — only *confidential* clients must authenticate at
the token endpoint. A public client is no longer rejected for a missing
secret.
- OAuth 2.1 §4.1.3 — for a public client the server must instead ensure
the code was issued to the request's client_id. That check already
existed; here it becomes the sole binding.
- OAuth 2.1 §4.1.3 — client_id is required when the client does not
authenticate, and a code yields a token at most once: a failed PKCE
comparison consumes the code, so a leaked one cannot be brute-forced.
- OAuth 2.1 §2.1 + RFC 7591 §2 — `none` means public client with no
secret. The type is derived at registration (#28043) and read here.
- RFC 7636 §4.1 / §4.6 — a malformed verifier is `invalid_request`, a
wrong one `invalid_grant`. PKCE was already mandatory for every code
flow, so public clients inherit it.
- RFC 8414 §2 — advertised auth methods now match what the token
endpoint actually accepts.
- RFC 7009 — a cross-app revoke of a public client's token still returns
200 without revoking.

---

- The token endpoint stops requiring client_secret for a public client,
in both the presence check and secret validation. PKCE was already
mandatory for every authorization_code flow, so public clients inherit
it with no new validation code.
- The code ownership check (dbCode.AppID != app.ID) becomes the only
binding between the exchange and the app named by client_id for a public
client, where it was defense in depth for confidential ones. Retained,
now covered with a public client on both sides.
- Public client tokens carry a NULL app_secret_id rather than
referencing a secret row that does not exist. Refresh and revocation
already verify ownership via app_id, so they change only comments and
coverage.
- Discovery advertises `none` now that the token endpoint honors it.
- Valid() derives from the single canonical auth method list, so what
registration accepts and what discovery advertises cannot disagree.
- Swagger marks client_secret confidential-only.

Refs
https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client
2026-08-31 09:55:58 -07:00
Jeremy Ruppel c73f34c35d feat: honor the deployment registry mirror in template builder bases (#28727)
## Summary

Threads the deployment's configured module registry
(`CODER_TEMPLATE_BUILDER_REGISTRY_URL`) into template-builder **base**
rendering, so a base that embeds a catalog module (e.g. the quickstart
base's `git-clone`) resolves its `source` through a registry mirror the
same way wizard-composed modules already do. Previously base-embedded
module sources hardcoded `registry.coder.com`, so on a
mirror/private-registry deployment a base-embedded module reached the
public registry while wizard modules used the mirror.

Implements [DOCS-610](https://linear.app/codercom/issue/DOCS-610).

## What changed

* `BaseRenderContext.RegistryBase` (new field), mirroring
`ModuleRenderContext.RegistryBase`. `Compose` threads the deployment
registry through `renderBase` into the base render context, and the four
hardcoded base module sources (`quickstart` git-clone,
`azure-linux`/`gcp-linux`/`gcp-windows` region modules) now use `{{
.RegistryBase }}`. Because the value defaults back to
`registry.coder.com`, rendered sources stay byte-identical; the only
golden change is the removal of the now-stale quickstart "follow-up"
note.
* **Boot-time validation.**
`codersdk.ValidateTemplateBuilderRegistryURL` runs in
`DeploymentValues.Validate()`, gated on the builder being enabled,
matching the chat-hook precedent. A malformed value fails at server
start naming the option, instead of surfacing as a per-request error to
a template author who cannot fix it. It uses `net/url` in authority form
to reject a scheme, path, query, fragment, trailing slash, or
credentials and accept a bare `host[:port]`; it does not canonicalize
the host.
* `Compose` **trusts the validated value**, defaulting an unset one and
defensively rejecting a malformed one for direct callers that bypass
boot.

## Tests

* `codersdk`: validator accept/reject matrix (incl.
credentials-without-echo) and a `DeploymentValues.Validate` boundary
test with a disabled-skips-validation case.
* `templatebuilder`: a base honors the mirror and falls back to the
default when unset, plus a defensive-reject case; existing compose tests
updated to bare-host registry values.

<details><summary>Design decision log</summary>

This PR is a deliberately minimal reimplementation of the
[DOCS-610](https://linear.app/codercom/issue/DOCS-610/template-builder-base-embedded-modules-should-honor-the-deployment)
scope, started fresh from `main` rather than carrying forward an
earlier, larger draft (coder/coder#28480). Key decisions:

* **Scope kept to the ticket.** The ticket's fix is three bullets: add a
registry field to `BaseRenderContext`, thread the deployment
`RegistryURL` through `Compose` -> `renderBase`, and use it in base
module sources. Independent hardening explored in the earlier draft was
dropped as out of scope: `terraform-svchost`-based IDN/punycode/port
canonicalization, a rendered-HCL backstop with a 500 mapping, and HCL
module-source extraction helpers. Telemetry misclassification of mirror
modules is tracked separately
([DOCS-712](https://linear.app/codercom/issue/DOCS-712/telemetry-misclassifies-registry-mirror-modules-as-non-coder))
and is not addressed here.
* **Default lives in the render layer.**
`templatebuilder.DefaultRegistryBase` holds the fallback host;
`codersdk` keeps its own option-default literal. An earlier version
exported the constant from `codersdk`, which only emitted a dead
`typesGenerated.ts` entry that nothing in the frontend consumed, so it
was moved out. The `codersdk` validator is a function, so it generates
no TS type.
* **Validate at the config boundary, fail fast.** The repo convention is
to hard-fail structurally invalid config in
`DeploymentValues.Validate()` (access URL, OAuth lifetimes, chat hook
URL) and to warn only for functional-but-risky settings. A malformed
registry host is structurally invalid, so it fails at boot. This also
puts the error in front of the admin who set it, rather than a template
author hitting a per-request error they cannot fix.
* `net/url`**, not a regex.** The codebase validates identifiers/names
with regexes but host/URL-shaped config with `url.Parse` (chat hook URL,
OAuth redirect URIs, AI provider base URL). This value is host-shaped,
so it follows that convention. `url.Parse("//" + v)` with `u.Host == v`
rejects a scheme/path/query/fragment/trailing-slash in one check.

</details>

> This PR was created with AI assistance (Coder Agents).
2026-08-31 09:32:24 -04:00
Michael Suchacz d6b67e8e31 feat: enforce SSRF protection for MCP config-directed traffic (#28242)
Routes all MCP config-directed traffic from coderd and chatd through a
shared SSRF-protected HTTP client, now that organization admins, not
only deployment admins, control MCP server URLs (#27942 and its stack
below).

## Summary

- Uses the [`coder/safedial`](https://github.com/coder/safedial)
library: it blocks private and special-purpose destinations at dial time
(validating resolved addresses at connection time so DNS rebinding
cannot bypass the check) and rejects cross-origin redirects.
- Covers the complete traffic surface: OAuth2 discovery, dynamic client
registration, code exchange, token refresh, revocation, and runtime MCP
connections from chatd.
- Deployments that intentionally host internal MCP servers opt in via
the new `--mcp-allowed-private-cidrs`
(`CODER_MCP_ALLOWED_PRIVATE_CIDRS`) option.
- Includes the deployment configuration surface, generated docs, CLI
goldens, TypeScript types, and regression coverage for each traffic
path.

## Merge window

This protection originally lived inside #27942 and was split out to keep
that diff reviewable. Until this PR lands, the stack below ships with
only main's existing discovery IP-range guard
(`CODER_MCP_OAUTH2_DISCOVERY_ALLOWED_IP_RANGES`), while org admins can
already point MCP configs at arbitrary URLs. This PR should merge
promptly after the stack below it.

Top of the MCP org-separation stack (CODAGT-711 -> CODAGT-717 audit ->
CODAGT-712 ACLs -> CODAGT-806 token RBAC -> CODAGT-714 org picker ->
this PR).

> Mux (AI agent) authored this PR on Mike's behalf.

<!-- mux-attribution: model=claude-fable-5 thinking=high -->
2026-08-30 13:09:17 +02:00
Jaayden HalkoandMathias Fredriksson 8bf271c503 feat: add Prometheus metrics for the usage publisher (#28368)
The Tallyman usage publisher (`enterprise/coderd/usage/publisher.go`)
had no metrics; failures were only visible in logs and the
`usage_events.failure_message` column.

This adds five metrics under `coderd_usage_events_*`:

| Metric | Type | Meaning |
|---|---|---|
| `publish_results_total{result, event_type}` | counter | Per-event
outcomes from real Tallyman responses (`accepted`,
`rejected_temporarily`, `rejected_permanently`; events missing from the
response count as temporary) |
| `publish_send_errors_total` | counter | Ingest requests that failed
entirely (HTTP error, non-200, decode error), one per request |
| `pending` | gauge | Unpublished events still inside the 30-day
publishing window |
| `pending_oldest_age_seconds` | gauge | Age of the oldest pending event
(0 when none) |
| `expired` | gauge | Unpublished events older than 30 days that will
never be published |

Send errors and per-event results never double-count: when a request
fails, the publisher fakes an all-temporarily-rejected response for the
DB update, but only `publish_send_errors_total` increments, so
`publish_results_total` reflects only real Tallyman verdicts.

The gauges are backed by a new read-only `GetUsageEventsStats` query
(authorized as `ActionRead` on `ResourceUsageEvent`) and refreshed from
the publish loop after each attempt, so they update roughly every 17
minutes.

Metrics are created with `promauto.With(reg)` where the registerer
defaults to nil, so existing callers and tests need no changes;
`enterprise/cli/server.go` wires in the deployment's
`PrometheusRegistry` via the new `PublisherWithPrometheusRegisterer`
option.

Closes
https://linear.app/codercom/issue/CODAGT-833/e3-prometheus-metrics-for-the-usage-publisher

---------

Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
2026-08-28 15:44:31 +07:00
Nick Vigilante bc77c40296 docs: add front-matter titles to mechanical and no-H1 pages (Phase 3) (#28030)
## Summary

**Batch A of Phase 3** of the H1 → front-matter migration (`DOCS-484`;
parent `DOCS-477`). Adds a front-matter `title` to every navigable docs
page whose title can be migrated **mechanically**, with no editorial
judgment.

This is the content step that Phase 1 (renderers prefer front-matter
title, `DOCS-482`) and Phase 2 (tooling + generators front-matter-aware,
`DOCS-483`) unblocked. Both are merged; coder.com #964/#974 are merged
and live.

**Rendered no-op.** The renderers already resolve the page title from
the manifest and hide the leading body H1 (Phase 1), so no page changes
visually. This just moves the title into front matter where Fumadocs and
the migrated tooling can read it.

## What's in this batch

Dry-run on `main` (464 navigable pages) splits into:

| category | count | this PR |
|----------|-------|---------|
| already has front-matter title (Reference, from Phase 2 generators) |
196 | skipped (idempotent) |
| **mechanical** — leading body H1 equals the manifest label | 138 | ✅
add front-matter `title`, drop the duplicate H1 |
| **no body H1** — renders under the manifest label only | 4 | ✅ add
front-matter `title` only |
| **mismatch** — body H1 differs from the manifest label | 126 | ⏭️
deferred (needs an editorial decision, see below) |

142 files changed, all under `docs/`.

## Deliberately out of scope: the 126 mismatches

Pages where the body H1 is richer than the short sidebar label (e.g.
label **Modules** / H1 *Contributing modules*, label **Install** / H1
*Installing Coder*) need a canonical-title decision, not a script. A few
even look like the body H1 is the redundant one (`install/cli.md` and
`install/index.md` both carry the H1 *Installing Coder*). These will
land in follow-up batches **by nav section** once the policy is set, so
each gets real review.

## Verification

AI was the primary author of this PR (see disclosure below); per the [AI
Contribution
Guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING)
here is the manual verification.

- Every added front-matter block parses as YAML and its `title`
round-trips to the manifest label (checked programmatically across all
142 files).
- Every removed line is a leading `# H1` that equalled the manifest
title; no body prose was reflowed. Front matter is correctly hoisted
above pre-existing `<!-- markdownlint-disable -->` comments on the two
pages that had them.
- `pnpm check-docs` (markdownlint-cli2 + table formatter) passes on the
changed set: `Summary: 0 error(s)`. `MD041` stays off (re-enabled in
Phase 4); `MD025` is not tripped because the duplicate body H1s are
removed.

```
$ pnpm exec markdownlint-cli2 $(git diff --name-only origin/main)
Linting: 142 file(s)
Summary: 0 error(s)
```

Linear: DOCS-484

> This PR was created with AI assistance (Coder Agents).
2026-08-27 12:34:13 -04:00
Nick VigilanteandIan Evans 47a77016c4 feat(docs/.style): enable Coder.SelectClick, use "select" over "click" (#28599)
Adds a Vale rule enforcing the existing "select, not click" style
guidance: "click" assumes the reader has a mouse, and touch, keyboard,
and assistive-technology users don't click.

`Coder.SelectClick` (warning severity) flags
`click`/`clicks`/`clicked`/`clicking` in prose, exempting:

- Literal mouse-button phrasing (`left-click`, `right-click`,
`middle-click`, `mouse click`, and combinations) — these name an actual
mouse action with no device-agnostic equivalent.
- `one-click`/`single-click` as a compound feature descriptor
("one-click install").

Reworded every existing instructional "click" in `docs/` to the matching
`select` form (`select`/`selects`/`selections`/`selected`/`selecting`)
so the rule ships with a clean baseline, per this repo's Vale-rule
doctrine.

Left alone, deliberately: two generated API reference pages
(`docs/reference/api/enterprise.md`, `schemas.md`) use "click" as an
analytics-event noun, tied to a Go source doc comment and an operation
ID (`report-a-premium-paywall-click`). Fixing those means editing
generated code and an API operation ID, which is out of scope for a
docs-style PR — see the rule's own comments for the reasoning. That
leaves 2 non-zero-baseline findings for this rule.

---
🤖 Built with AI assistance.

---------

Co-authored-by: Ian Evans <5760366+ianjevans@users.noreply.github.com>
2026-08-27 16:24:06 +00:00
Mathias Fredriksson f208fc0c83 refactor: rename edit_files wire type to old_text/new_text (#28467)
The schema has advertised old_text/new_text since #25658, but the
shared wire type still encoded search/replace.

Decode accepts the deprecated keys only when both new fields are
empty, through the pre-rename tags, so old coderd and cached MCP
schemas keep working. Marshal emits both key sets so old agents keep
working after a coderd upgrade. Both shims are removed in the first
release after Coder Agents GA (2026-09).

The Go field rename is a deliberate source break: FileEdit carries
no codersdk stability guarantee.

Fixes CODAGT-523
Refs CODAGT-483
2026-08-27 16:06:21 +03:00
Bobby HoandMcKayla はな c9fc5b7ea1 fix: canonicalize API key scope aliases at ingress (#28322)
`rbac.IsExternalScope` accepts `all` and `application_connect`, neither
of which is an `api_key_scope` enum member. The plural `Scopes` field
stored the name as given, so `{"scopes":["all"]}` passed validation and
then 500'd inside `apikey.Generate` with `invalid API key scope: "all"`.
Reachable from `coder tokens create --scope all`, from the spellings
`docs/admin/users/sessions-tokens.md` taught, and from the `codersdk`
constants exported for exactly this purpose.

- Canonicalize inside `apikey.Generate`, in the loop that already
validates each name. One statement covers every caller and all three
input paths: plural `Scopes`, deprecated singular `Scope`, and the
default. Replaces two open-coded switches and the handler's own
per-element copy, so one place decides the stored spelling and the
handler only decides what may be requested.
- Deduplicate in the same pass. An alias and its canonical spelling are
two names going in and one name in the column.
- `ExternalScopeNames()` lists every name `IsExternalScope` accepts,
instead of dropping catalog entries that fail to parse. A curated entry
that cannot be stored used to pass every test and 500 at runtime; it now
fails two.
- Split the 400. A misspelled name and an internal `api_key_scope`
member need different words, since no re-spelling makes the second
requestable. Both rejection sites share one helper that names the case
and links the docs.
- Add reject-path tests for `not_a_real_scope` and `debug_info:read`.
The second is a valid enum member the rbac catalog treats as internal,
so before this both handler guards could be deleted with the suite still
green. A further case pins that plural `Scopes` wins when a caller sets
both fields.
- `TestExternalScopesAreStorable` pins the class rather than the two
known instances: every public rbac scope name must be storable.
`coderd/rbac` cannot assert this itself, since `database` imports `rbac`
and not the reverse.
- Docs use the canonical spellings, link the `codersdk.APIKeyScope`
schema, and say which scopes a token cannot request.

Egress is unchanged: `convertAPIKey` still derives a legacy singular
name on the way out. `ExternalScopeNames()` returns the same 57 names as
before, and `codersdk/apikey_scopes_gen.go` regenerates identically.

`rbac.CanonicalScopeName` merged with #28167, so this applies to `main`
and reviews on its own. The OAuth2 provider ignores scopes entirely
today (`authorize.go:237`, `tokens.go:377`, `tokens.go:520`), so it is
unaffected until those TODOs resolve.

Deferred from review: PLAT-528, PLAT-529, PLAT-530, and PLAT-532.
PLAT-532 covers `{"scopes":[]}` and `{"allow_list":[]}` defaulting open,
which predates this PR.

---------

Co-authored-by: McKayla はな <mckayla@hey.com>
2026-08-25 17:12:51 -07:00
McKayla はな 895c5c77a1 feat: add a template parameter settings page (#27559) 2026-08-25 15:06:30 -06:00
McKayla はな 29995c9ef8 feat: add a per-template workspace rename setting (#27558) 2026-08-25 11:05:42 -06:00
Jon Ayers 26de6140fb feat: add flag to disable workspace agent context sync (#28522) 2026-08-24 19:58:30 -05:00
J. Scott Miller 76962273d8 feat: add coder organizations edit for default member roles (#28227)
`default_org_member_roles` was only settable through Terraform or a raw
`PATCH /api/v2/organizations/{organization}`. This adds a CLI
equivalent.

```console
coder organizations edit --org acme --default-org-member-roles organization-workspace-access,organization-template-admin
coder organizations edit --org acme --default-org-member-roles ""   # grant no roles
```

- The flag replaces the organization's current list rather than adding
to it. It accepts a comma-separated list, may be repeated, and
de-duplicates. An empty value removes every role.
- Removing a role prompts for confirmation, listing the roles being
removed, unless `-y` is passed. Adding roles applies without a prompt.
- The resulting set is printed, so no follow-up command is needed to
confirm what was applied.
- The organization is chosen with `-O/--org` or `$CODER_ORGANIZATION`,
and is implicit when the caller belongs to exactly one organization.

The org update endpoint is behind `FeatureMultipleOrganizations`, so the
command is enterprise/premium only. Non-built-in roles are rejected by
the server, and `dbauthz` already prevents a caller from setting a
default they could not assign to a member individually.

<details>
<summary>Implementation notes</summary>

## Shape

`codersdk.UpdateOrganizationRequest.DefaultOrgMemberRoles *[]string` and
the enterprise `patchOrganization` handler already existed; only the CLI
was missing, and nothing in `cli/` called `UpdateOrganization` at all.
No server or SDK changes are needed.

`organizations edit` follows the partial-update pattern of `coder groups
edit`: check `ParsedFlags().Changed(...)`, populate only the fields the
user set, and leave the rest nil so the handler preserves them. Passing
no flags is an error.

Two earlier shapes were tried and dropped:

- **A `default-org-member-roles` entry in the `organizations settings`
registry.** Every sibling entry unmarshals an SDK type that maps 1:1 to
a dedicated endpoint; this field has no such endpoint. Reusing
`UpdateOrganizationRequest` for the piped JSON meant a stray `name`
field could rename the org, and the documented `show > file`, edit, `set
< file` workflow failed on the default organization, whose name is
reserved.
- **A `--default-org-member-roles` flag on `organizations create`.**
`create` cannot set display name, description, or icon either, so a
roles-only flag there is asymmetric. It would also require
`CreateOrganizationRequest` to grow the field plus server-side
validation.

## Known sharp edge

`serpent.StringArray` resets its slice when any flag value is empty, so
`--default-org-member-roles a --default-org-member-roles ""` clears the
list rather than keeping `a`. This is pinned by a test and called out in
a code comment. The confirmation prompt catches it interactively; a
script passing `-y` would not. A custom flag value that ignores empty
occurrences was prototyped and reverted as more machinery than the
behavior warranted.

## Validation

Manually verified against a local dev deployment with a premium license:
setting, adding, clearing, prompt accepted and declined, duplicate and
whitespace handling, invalid role rejection, and a plain member being
denied. Confirmed with `/authcheck` that a member loses workspace-create
access when the roles are cleared and regains it when restored, and that
the change is recorded in the audit log.

## Follow-ups worth considering

- `--name`, `--display-name`, `--description`, and `--icon` on
`organizations edit`; all already exist on `UpdateOrganizationRequest`.
Rename deserves its own discussion.
- Setting the defaults to `organization-admin` makes every member an org
admin, including the ability to edit the org further, and those users
still render as plain members in member listings. Reachable today via
the API, UI, and Terraform; a warning on privileged roles would help.
- `dbauthz.InsertOrganization` has no `canAssignRoles` check, unlike
`UpdateOrganization`. Harmless while the only caller passes the
deployment default constant.
- `docs/admin/users/organizations.md` still points users at the
dashboard or a raw `PATCH`.
</details>

---

Created by Coder Agents on behalf of @jscottmiller.
2026-08-24 09:41:21 -05:00
Ben PotterandNick Vigilante 3bdd395faa docs(docs/admin/templates/extending-templates): clarify coder_env merge_strategy does not include host environment (#28466)
`merge_strategy` on `coder_env` only combines values across `coder_env`
resources targeting the same name. It does not know about the value
already set by the workspace's image or host, such as the base `PATH`. A
user hit this in #27501: appending to `PATH` with three `coder_env`
resources replaced the host's `PATH` entirely, since none of them
referenced the existing value.

Clarify this in the docs, and update the `PATH` example to show
referencing `$PATH` in one of the resources so the host's original value
is kept.

Refs #27501

<details>
<summary>Investigation notes</summary>

- `coderd/provisionerdserver/provisionerdserver.go` builds the merged
env starting from an empty map (`MergeExtraEnvs`), only combining
`coder_env` resources with each other.
- `agent/agent.go`'s `updateCommandEnv` applies the result with
`os.ExpandEnv(v)`, which expands `$VARNAME` against the agent's real
process environment.
- Confirmed with a standalone repro that `value =
"$PATH:/usr/local/cuda/bin"` preserves the host's real `PATH` and
appends the extra directory, and that this composes correctly across
multiple `coder_env` resources with `merge_strategy = "append"` as long
as one of them references `$PATH`.
- A companion PR updates the `terraform-provider-coder` schema
description and example that feed the registry docs:
https://github.com/coder/terraform-provider-coder (branch
`bpmct/docs-env-merge-host`).

</details>

---
*Opened by Coder Agents on behalf of @bpmct.*

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-08-24 07:55:23 -05:00
Cian Johnston 042421694f fix: surface duplicate AI provider hostname as warning, not error (#28208)
Two live `ai_providers` rows can share the same `base_url` hostname.
This is an intended configuration (AIGOV-97): the direct routing path
(`/api/v2/ai-gateway/{name}/...`) routes by provider name and fully
supports it. Only the MITM proxy path (`aibridgeproxyd`) cannot
disambiguate, because its `nameByHost` map is 1:1.

`classifyProviderRow` marked the second provider as
`ProviderStatusError`, which surfaced as a misleading log warning and a
`status=error` Prometheus label. The provider is not actually broken; it
is fully routable via the direct path. The error was only visible in
server logs and Prometheus, not in the API or UI.

This change:

- Extracts `BaseURLHostname` into `coderd/aibridged` and eliminates
three duplicate implementations (proxy classifier, chatprovider, and the
API layer now uses it for status checks).
- Downgrades the proxy classifier from `ProviderStatusError` to a new
`ProviderStatusProxyExcluded` status. The provider is not broken; it is
just not reachable via the MITM proxy path.
- Adds `Status *AIProviderStatus` to `codersdk.AIProvider` with
`Warnings []string`, matching the `WorkspaceProxy` precedent.
- Populates warnings on create, update, GET, and list when a provider's
hostname collides with another enabled provider.
- Adds an integration test proving that a duplicate provider is routable
via the direct path but not via the proxy path.

Refs AIGOV-596

Generated by Coder Agents



https://github.com/user-attachments/assets/bf323837-5121-4d1b-ab19-593f1d32374e
2026-08-24 13:27:22 +01:00
df6a33ad37 docs: fix broken extending-templates examples (dynamic-parameters, docker-in-workspaces) (#28100)
## Summary

Fixes broken examples on the `extending-templates` pages surfaced by the
DOCS-637 runtime drift sweep, and completes the dangling `external-auth`
reference. Verified against `main` and the CLI source (`coder templates
init --id`, `coder templates push`).

## Changes

| Page | Fix |
|------|-----|
| `dynamic-parameters.md` | The **Dynamic Validation** snippet
referenced an undefined `show_cpu_cores` through a stray `count =
data.coder_parameter.show_cpu_cores.value ? 1 : 0` line copied from the
earlier Hide/Show Options example. Standalone copy failed `terraform
validate`. Removed the `count` line (and its misleading "Only show this
parameter" comment) so the snippet is self-contained. The valid
occurrence in the Hide/Show example (where `show_cpu_cores` is defined)
is untouched. |
| `docker-in-workspaces.md` | The rootless Podman step used `echo
"kubernetes-with-podman" \| coder templates init`, but
`kubernetes-with-podman` isn't a built-in starter id, so the command
scaffolds nothing. Step 4 now starts from the built-in `kubernetes`
starter (`coder templates init --id kubernetes`) and shows the minimal
Podman delta inline: the maintained `codercom/example-podman:ubuntu`
base image, the `container.apparmor.security.beta.kubernetes.io/dev =
unconfined` pod annotation, and a `github.com/fuse` device limit. The
starter already runs as UID/GID 1000 with `run_as_non_root`, which
rootless Podman needs. Also switches the deprecated `coder templates
create` to `coder templates push`. Follow-up from review: swapped
`ghcr.io/coder/podman` for the maintained
`codercom/example-podman:ubuntu` image and linked its source, added a
note that the AppArmor annotation is deprecated on Kubernetes 1.30+
(`securityContext.appArmorProfile`), and added an EKS Auto Mode caveat
to the Bottlerocket section. |
| `external-auth.md` | The **External Auth Providers** sentence
dead-ended at "...in the Coder Control Plane. See" with no link.
Completed it with a link to the admin External Authentication page
(`../../external-auth/index.md`), the target chosen in review. |

## Dependency

The `docker-in-workspaces.md` example now references
`codercom/example-podman:ubuntu`, published by coder/images#339. That PR
is approved but should merge (and publish the image to Docker Hub)
before this PR merges, so the docs don't point at an image that doesn't
exist yet.

Linear: https://linear.app/codercom/issue/DOCS-645

> This PR was created with AI assistance (Coder Agents).

---------

Co-authored-by: Ben Potter <me@bpmct.net>
Co-authored-by: Ben Potter <ben@coder.com>
2026-08-24 08:24:26 -04:00
Ethan c275327fb7 feat: audit operational agent settings (#28369)
Depends on #28394.

Audit changes to seven operational agent settings through a typed
`chat_operational_settings` resource. Each handler serializes baseline
capture and mutation with a per-setting advisory lock, keeps both
operations in one transaction, and records field-specific diffs.

Effective no-op requests now skip both the database upsert and the
success audit, including absent rows whose effective value is already
the default. The change also retains the allowlisted raw `site_configs`
query, updates generated audit and API surfaces, adds failure and
concurrency coverage, and reuses the existing AuditPage resource-filter
story pattern.

Relates to CODAGT-720.
2026-08-24 11:53:47 +01:00
Ethan a53c6e6366 feat: audit chat model config changes (#28439)
Adds audit logging for chat model config creates, updates, deletes, ACL
changes, and automatic default-model transitions. Audit records use the
config display name or ID as the target and are emitted only after
successful transactions.

Depends on #27960.
2026-08-24 11:20:26 +01:00
Ethan aefc761fcf feat!: enforce organization scope for chat models (#27959)
## Summary

Move chat model management and runtime availability to
organization-scoped API routes. The API now identifies the organization
in every model-management operation, applies chat model RBAC and ACLs
within that organization, and returns only models the caller can use
there.

Depends on #27958.

## Problem

Chat model configurations now belong to organizations, but the existing
experimental management and discovery APIs are deployment-shaped. Their
routes do not identify an organization, SDK methods do not accept an
organization ID, and item operations address a model configuration by ID
alone.

That contract cannot safely expose organization-owned model
configurations. It also does not provide the organization-specific
provider information, authorization behavior, ACL management, or
recovery guidance needed by the settings and chat clients later in the
stack.

## Fix

Add organization-scoped chat model endpoints under:

```text
/api/experimental/organizations/{organization}/chats/models
```

The new API provides:

- Organization-scoped model listing and creation.
- Model get, update, and delete operations scoped by both organization
and model ID.
- Model ACL read and update operations.
- Organization-scoped runtime availability and provider status.
- Redacted provider descriptors for model-management clients.
- Chat model RBAC and row ACL enforcement for writes, runtime discovery,
and Chatd model selection.
- Recovery guidance when a chat's organization has no usable local
model.

Historical chats can retain a model reference owned by another
organization, but runtime selection uses an authorized local default
when one is available. Foreign, inaccessible, disabled, and otherwise
unusable models are not exposed as usable selections for the
organization.

The existing collection and availability routes remain as
default-organization compatibility endpoints in this layer:

```text
GET  /api/experimental/chats/model-configs
POST /api/experimental/chats/model-configs
GET  /api/experimental/chats/models
```

These compatibility routes do not provide access to models in
non-default organizations. The previous unscoped item update and delete
routes are removed because item operations must include the owning
organization.

## Breaking change

This changes the experimental HTTP API and Go SDK contracts for chat
model management.

Clients must migrate model-management and availability requests to the
organization-scoped routes and provide an organization identifier. In
the Go SDK, the following methods now require an organization ID:

- `ChatModelAvailability`
- `ChatModels`
- `CreateChatModel`
- `UpdateChatModel`
- `DeleteChatModel`

`ChatModels` also changes its return value from `[]ChatModel` to
`OrganizationChatModelsResponse`, which includes the organization models
and the redacted provider descriptors required by management clients.
New item and ACL methods likewise require both the organization ID and
model ID.

The default-organization compatibility routes reduce the immediate
impact for collection and availability callers, but they do not preserve
the previous item API or SDK method signatures. Generated clients and
direct consumers of the experimental API must be updated before adopting
this change.

_This pull request description was generated by Coder Agents._
2026-08-24 11:20:25 +01:00
Paweł BanaszewskiandNick Vigilante 4ce8e8ed56 docs: address AI Gateway documentation review feedback (#28309)
Applies the review feedback from #27794. Prose only.

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-08-23 19:42:48 +00:00
Bobby Ho 6348c83142 feat: register public clients without a secret (#28046)
Third in the stack, split out of #27873. This is where dynamic client
registration first produces a public client.

- A registration requesting token_endpoint_auth_method `none` issues no
secret and persists the client_type derived in #28043. The response
omits client_secret entirely, per RFC 7591 §3.2.1.
- Discovery still advertises only the two secret-based methods. `none`
is withheld until the token endpoint honors it, so a conforming client
is not told to attempt an exchange that would be rejected.
- The app and its secret are written in one transaction. They were two
independent inserts, so a failed second one left a committed app that
could never authenticate while still holding a registration access
token. Pre-existing, but a public client's missing secret row makes the
orphaned case unspottable by inspection.
- registration_client_uri uses url.JoinPath, fixing a trailing-slash
access URL producing //oauth2/clients/{id}.
- Docs state both limits above, so the page does not describe a flow
that returns 400 until #28047 lands.

A client registered here cannot obtain a token yet; #28047 adds that.
Dynamic client registration is off by default, so none of this is
user-visible until then.

Refs
https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client
2026-08-20 12:49:47 -07:00
david-fraley 8203b2ebaf feat!: hide Coder Tasks behind the enable-ai-tasks flag (#28008) 2026-08-19 14:46:10 -05:00
Michael Suchacz 7ca7c30f40 feat: add group and user ACLs to MCP server configs (#27944)
Adds group and user ACLs to org-scoped MCP server configs so
organizations can restrict specific MCP servers to subsets of members,
mirroring the template ACL pattern.

## Summary

- Migration adds `group_acl`/`user_acl` JSONB columns (nested `{"<id>":
{"permissions": [...]}}` shape) and seeds every existing config with its
organization's Everyone group read entry (the Everyone group ID equals
the org ID), so member access is unchanged by default. Creation seeds
the same entry.
- The blanket org-member read grant from the base PR is replaced by ACL
evaluation: Rego requires org membership for every ACL grant, and
`GetAuthorizedMCPServerConfigs` compiles ACL-aware SQL filters.
- New `ActionShare` (org admins) gates `GET|PATCH
/api/experimental/organizations/{organization}/mcp-servers/{mcpserverconfig}/acl`
(nested under the organization like the rest of the config surface).
PATCH validates principals against the config's organization, merges
sparse updates under a row lock, stamps `updated_by`/`updated_at`, and
is audited as a Write with `Old` captured before authorization. A config
deleted concurrently between the middleware fetch and the locked
re-fetch is concealed as 404, matching the update and delete handlers.
ACL columns are tracked in the audit table.
- ACL management is available in all editions (no enterprise
entitlement), documented in the MCP servers page. Revoking an ACL does
not retro-strip already-selected configs from existing chats; new
selection is blocked at chat create.
- Force On respects the ACL: the forced set is loaded as the chat owner,
so a `force_on` server whose ACL denies the owner never attaches at
create, send, or generation time.
- No rolling-upgrade machinery: upgrades run in scheduled maintenance
downtime, so the migration only backfills existing rows; the API sets
the Everyone read grant explicitly on every insert.

Stacked on #27943. Part of the MCP org-separation stack.

Closes https://linear.app/codercom/issue/CODAGT-712

UAT: verified on a dogfood instance with two members and a custom group:
Everyone-seed default visibility, group grant with Everyone removal
(non-member loses list/fetch/selection), foreign-principal rejection,
non-admin share denial (audited 403 / concealed 404), user_acl restore,
and audited ACL diffs.

> Mux (AI agent) authored this PR on Mike's behalf.

<!-- mux-attribution: model=claude-fable-5 thinking=high -->
2026-08-19 19:25:18 +00:00
Michael Suchacz 299e72ad30 feat: audit MCP server config changes (#27943)
Adds enterprise audit logging for MCP server config create, update, and
delete, with strict secret redaction. MCP configs hold credentials
(OAuth2 client secrets, API keys, custom headers), so admin changes to
them need an audit trail.

## Summary

- `enterprise/audit/table.go` gains an `MCPServerConfig` entry
enumerating every column: `oauth2_client_secret`, `api_key_value`, and
`custom_headers` are `ActionSecret` (never appear in diffs); dbcrypt
`*_key_id` bookkeeping, IDs, and timestamps are ignored; the remaining
config fields, including the endpoint URL fields, are tracked so
auditors can see which endpoints a config points at.
- Type registration in `coderd/audit` (diff, request, resource target
with org attribution), `codersdk/audit.go`, and a `resource_type` enum
migration.
- Handlers wire `audit.InitRequest`: create records `New`; update and
delete record `Old` from the param middleware before the
write-authorization check, so a readable-but-not-writable caller
produces an audited 403 while read-denied callers stay concealed as
unaudited 404s.
- Tests: create/update/delete audit entries, write-denied and
delete-denied 403 auditing, cross-org concealment producing zero
entries, and a serializer-level regression test proving none of the
three secret classes can reach a serialized diff.
- Review round: MCP config audit entries link to
`/ai/settings/mcp-servers/{id}`, audit table comments are trimmed per
review, and a fault-injection test pins that a config row surviving a
failed post-discovery credential update still gets its creation audit
entry.

Stacked on #27942 (org-scoped MCP configs). Part of the MCP
org-separation stack.

Closes https://linear.app/codercom/issue/CODAGT-717

UAT: verified on a trial-licensed dogfood instance: audit entries for
the full CRUD lifecycle with correct actor/org/target, redacted secrets
in the update and OAuth2 create diffs, and a full plaintext scan of the
audit dump finding zero secret leaks.

> Mux (AI agent) authored this PR on Mike's behalf.

<!-- mux-attribution: model=claude-fable-5 thinking=high -->
2026-08-19 19:11:52 +00:00
Nick Vigilante 31e95f7096 docs: fix prebuilt-workspaces example syntax and defaults (#28088) 2026-08-19 09:56:15 -04:00
Jon Ayers 821d91fabd fix: log tailnet tunnel authorization decisions (#27819) 2026-08-18 18:21:50 -05:00
Bobby Ho 166d92ba73 fix: bound request body size on JSON API endpoints (#28168)
## Summary

`httpapi.Read` decoded request bodies with no size limit, so a single
request could allocate memory without bound. This adds a 4 MiB default
ceiling, leaves the endpoints that legitimately need more explicitly
exempted, and counts the rejections so a limit set too tight is visible.

This is the first of three PRs split out of #28048, covering the
endpoints that answer in `codersdk.Response` shape. The OAuth2 decode
paths (RFC 6749, RFC 7591) and the SCIM ones (RFC 7644) answer in their
own error shapes and follow in separate PRs, along with the lint rule
that pins the invariant.

Closes PLAT-463. Remediates SEC-416 (CWE-770, CVSS 7.5) and SEC-392.

## Problem

`httpapi.Read` calls `json.NewDecoder(r.Body).Decode(value)` with no
ceiling, and no middleware in the chain bounds body size. The exposure
is pre-authentication: login, OTP, and first-user creation all read a
body before any authorization decision is reached. The existing rate
limiter bounds request *rate*, which is orthogonal to the memory a
single admitted request may consume.

## Fix

`Read` is split into `Read` and `ReadLimit`. `ReadLimit` wraps `r.Body`
in an `http.MaxBytesReader` and keeps the existing decode and validate
logic; `Read` delegates to it with a new `DefaultMaxRequestBodyBytes` of
4 MiB, which covers the 124 remaining non-test callers at a single site.

`http.MaxBytesReader` composes as tightest-wins, so the handlers that
pre-wrapped their own bodies pass their limit to `ReadLimit` rather than
wrapping, and each keeps its previous ceiling byte for byte. That
matters most for the bulk secrets import at `8 * MaxSecretsFileBytes`:
an unconditional wrap inside `Read` would have silently halved it to the
default. `TestImportUserSecretsBodyLargerThanDefaultLimit` is the
regression guard for that specific failure, and
`TestMaxBytesReaderNesting` pins the composition behavior the whole
requirement rests on.

Every rejection site calls `httpapi.RecordRequestBodyLimit`, which names
the limit that tripped on the request's existing log line and marks the
request so `coderd_api_requests_too_large_total{reason="request_body"}`
counts body rejections apart from the 413s coderd answers for other
causes, such as agent log storage overflow. A limit set too tight for a
legitimate payload therefore surfaces without waiting for a user report.

The limit is a constant rather than a deployment option: an operator
raising it to unblock something would reopen the vulnerability as
configuration, where a security scan will not find it. A legitimate 413
is answered with a targeted `ReadLimit` on that endpoint.

## Behavior change

`POST /api/v2/files` now answers 413 rather than 400 when a request body
exceeds `HTTPFileMaxBytes`. It installed that bound already but reported
the rejection as a read failure, which leaked the stdlib `http: request
body too large` string through `Detail` and kept the largest limit in
the tree off the metric. The separate 413 for an oversized expanded
archive is unchanged.

The task log snapshot endpoint now answers 413 rather than 400 when its
64 KiB cap is exceeded. Routing it through `ReadLimit` also changes its
decode-failure message from "Failed to decode request payload." to
"Request body must be valid JSON.", which is what every other endpoint
answers. Its tests are updated to match both.

`coderd_api_requests_too_large_total` is new, so there is no existing
query to migrate. It counts the 413s coderd answers, labeled `method`,
`path`, and `reason`. `reason="request_body"` is a rejection by one of
the limits above; `reason="other"` is a 413 that has nothing to do with
body size, such as agent log storage overflow.

## Reading this

The commits are ordered to be read in sequence. Commits 1 and 2 are the
security fix; commits 3 to 5 are the observability consequences, and
commit 3 is the one that touches dashboards. Commit 7 documents the
limit on the REST API reference index. Commits 6 and 8 add and revert an
exhaustive `@Failure 413` annotation pass, which buried the fix under
its regenerated swagger, and cancel out.
2026-08-18 12:54:45 -07:00
Mathias FredrikssonandMichael Suchacz d3f08b1983 feat: audit chat system instructions changes (#27668)
Adds an audit record for administrative events on the deployment-wide
chat instruction settings (system prompt, the include-default toggle,
and the plan-mode instructions), per CODAGT-719 and operator decision
D5. Each endpoint records under a stable identity: resource type
`chat_instruction_settings`, a fixed resource ID and a human-readable
target ("System prompt", "Plan mode instructions"), so two changes to
one setting share an ID and history-by-setting works. A real change
exports a Write entry with the old-to-new text visible; a
value-identical PUT still upserts and still returns 204 but records
nothing.

Attempts are recorded, not only transitions. Identity is assigned before
the authorization check, so a denied PUT exports a 403 row with an empty
diff (no request content reaches it), a validation failure exports a 400
row, and a write failure exports a 500 row, each with an empty diff; an
operator can tell "nothing changed" from "something changed and capture
degraded" by the status code.

The write path stays authoritative. The advisory lock and, on plan-mode,
the transaction exist only to serve change-detection; if any of that
machinery fails (lock, begin, commit, rollback), the handler runs main's
idempotent write path directly and derives the response from it, so a
member-visible failure of audit-only infrastructure can never replace
main's successful response. Accepted consequence: when the lock cannot
be taken, two concurrent identical writes can produce two rows instead
of one. That is audit degradation, which is allowed; changing a member's
response is not. Write failures keep the exact response the endpoint
produced before this wiring (transaction error for the system prompt,
which was always transactional; the raw write error for plan mode, which
was not), and the full transaction error is logged so rollback failures
cannot vanish.

<details>
<summary>CODAGT-66 plan entry: S1 (verbatim)</summary>

**S1 `feat: audit chat system instructions changes`** (CODAGT-719; base:
main)

- Struct: `database.ChatSystemPromptSettings{ID uuid.UUID; SystemPrompt
string; IncludeDefaultSystemPrompt bool; PlanModeInstructions string}`
in `coderd/database/types.go` (ticket-sketched shape; one struct, both
endpoints).
- Registration: union entry (diff.go), table.go entry (`id`
ActionIgnore, other three ActionTrack), `AuditActionMap` Write-only;
four request.go cases (`ResourceTarget` "", `ResourceID` from struct,
`ResourceType` new enum value `chat_system_prompt_settings`,
`ResourceRequiresOrgID` false with the "Artificial ID / deployment
singleton" comment convention).
- Migration: `ALTER TYPE resource_type ADD VALUE IF NOT EXISTS
'chat_system_prompt_settings';` comment-only no-op down (000558 shape);
number picked at push per the numbering constraint.
- codersdk: constant + prose `FriendlyString` ("chat system prompt
settings"); `TestAuditDBEnumsCovered` forces both. `coderd/audit.go`
presentation switches: rely on safe defaults (no link, generic
description); no FE changes (filter label falls back to capitalized
value; acceptable per precedent).
- Wiring `putChatSystemPrompt` and `putChatPlanModeInstructions`:
InitRequest with Action Write; artificial `ID: uuid.New()` on `New` only
when a change is detected; no-op suppression by leaving both aReq sides
unset (nil resource IDs skip the log, request.go skip rule); the write
path itself stays byte-identical (upserts still run unconditionally).
- `putChatSystemPrompt` (writes two keys conditionally in one existing
tx): inside that tx, read the pair via `GetChatSystemPromptConfig` for
`Old`, perform the conditional writes exactly as today, then RE-READ the
pair for `New`. The re-read is load-bearing:
`include_default_system_prompt` is computed from the toggle row AND the
prompt, so a prompt-only write can flip the effective value without the
request carrying the pointer. `PlanModeInstructions` stays zero on both
sides.
- `putChatPlanModeInstructions` (no tx exists today): wrap its
read-upsert in `InTx` (behavior-preserving: same single write);
`Old`/`New` populate only `PlanModeInstructions`; the two system-prompt
fields stay zero on both sides; no cross-key reads.
- Change detection compares the populated payload fields only (never the
artificial ID).
- Tests: handler-level coderdtest with `audit.NewMock()` asserting Write
entry on change and NO entry on a value-identical PUT, for both
endpoints (this also exercises `ResourceRequiresOrgID` end to end); the
fallback-flip case (no explicit include-default row, nonempty prompt set
to empty, effective boolean flips: entry emitted with the boolean diff);
diff assertions (old->new prompt text tracked, not secret) in
`enterprise/audit/diff_internal_test.go`; `TestAuditableResources`
passes by construction.
- Bookkeeping at PR open: correct CODAGT-719's no-op premise ("matches
the existing 204-on-unchanged behavior" does not exist on main;
suppression is new, write path unchanged).
- Review focus: Old capture and the New re-read inside the tx (three of
four existing singletons never set Old; do not copy them; and the
computed include-default value makes a naive New construction wrong);
the skip-on-no-op mechanism; prompt text deliberately visible in diffs.

</details>

Note: the plan excerpt above predates operator decision D5 (2026-07-30),
which this PR implements: the resource type is
`chat_instruction_settings` (not `chat_system_prompt_settings`), each
setting carries a stable ID and a display-name target (not a per-write
artificial ID and an empty target), no-op suppression runs through
`InitRequestWithCancel` (not the nil-ID skip), and attempts (denied,
failed, capture-degraded) record rows with real statuses and empty
diffs. Ticket bookkeeping for CODAGT-719 was corrected on Linear at
kickoff: the ticket's "matches the existing 204-on-unchanged behavior"
premise does not exist on main; suppression is new, and the write path
is unchanged.

> 🤖 This PR was created with the help of Coder Agents, and _will be_
reviewed by a human. 🏂🏻

---------

Co-authored-by: Michael Suchacz <203725896+ibetitsmike@users.noreply.github.com>
2026-08-18 20:03:06 +02:00
Michael Suchacz 7724ee281a feat: defer MCP tool schemas behind a find_tools search (#28225)
## Summary

When the `mcp-tool-search` experiment is enabled, chatd stops inlining
connected MCP tool schemas into every generation. It instead exposes a
built-in `find_tools` tool whose description carries a compact catalog
of the deferred tools, and only ships full JSON schemas for tools the
model has activated by searching or by calling them directly.

Closes [CODAGT-760](https://linear.app/coder/issue/CODAGT-760).

## Problem

Tool-heavy agent configurations (GitHub, Linear, Notion, and dev-tooling
MCP servers) inline over 100k tokens of tool schema definitions into
every generation. Initial uncached requests reached ~216k tokens with
time-to-first-token close to nine minutes, while the model typically
invokes only a handful of tools per turn.

## How it works

- `decideMCPToolSearch` defers external and workspace `.mcp.json` MCP
tools whenever the experiment is enabled. Native, dynamic, provider,
skill, and transport tools are never deferred.
- `find_tools` embeds a server-grouped catalog in its tool description
(degrading to names-only, then counts-only, then a constant-size summary
past a context-scaled size cap) and scores keyword matches across tool
names, descriptions, parameter schemas, and server metadata. Queries can
scope to one server with a `server:` prefix, and exact `names` arguments
always activate.
- Activation state is ephemeral: it is re-derived each generation from
surviving chat history (`find_tools` results and direct calls to
deferred tools), so activations naturally lapse when compaction
summarizes them away. Aggregate activated schema weight is capped at 10%
of the context window, shedding the least recently activated schemas
first; `find_tools` shares that budget across parallel calls in one
step. No new persistence.
- Deferred tools stay registered for execution, so the model can call a
cataloged tool directly without searching first; the schema is activated
for subsequent steps.
- Fail-open: the experiment being disabled, an empty candidate set, or
an MCP tool named `find_tools` all disable deferral, leaving today's
behavior byte-identical on the wire.
- Prometheus counters/histograms track `find_tools` calls, matches,
activations, and deferred token weight.
- The conversation timeline renders `find_tools` calls with a collapsed
search summary and expandable match list, falling back to the generic
renderer on malformed payloads.

## Validation

- Unit tests for the catalog, matcher, experiment-gated decision, and
activation derivation; end-to-end chatd generation tests covering
search-then-call, direct-call activation, experiment-off wire parity,
compaction lapse, and subagent tool gating.
- Storybook interaction tests for the timeline rendering and
malformed-payload fallback.
- Remote dogfood UAT on dev.coder.com passed: deferral with a real MCP
server and Anthropic model, direct calls without prior search,
activation persistence across turns, experiment-off parity, and clean
UI/console.

> Disclosure: Mux (AI agent) authored this PR on Mike's behalf.
2026-08-18 19:12:47 +02:00
Michael Suchacz 119f2b1dd9 feat: limit concurrent chat agents with pooled admission (#27902)
Limits concurrent chat generation on capped deployments to 5 root chats
and 10 delegated subagent chats. The pools are deployment-wide and
independent, so delegated work can continue while root capacity is full.

The default caps live in AGPL code. Enterprise contributes only a
licensing unlock, so unlicensed deployments stay capped and cannot fail
open. Licensed deployments are uncapped while Agent Hours usage stays
below an explicit hard limit. Deployments without a hard limit remain
uncapped, and reaching the Agent Hours allocation only triggers
warnings.

Admission happens before a worker takes chat ownership. Capped
deployments serialize admission across replicas with a
transaction-scoped advisory lock and derive active and queued state from
current ownership plus fresh runner heartbeats, rather than persisted
queue markers or per-replica state. The acquisition query returns a
bounded, pool-interleaved candidate set instead of ranking the whole
backlog; a migration replaces the acquisition index with a pool-aware
one. Refused chats stay running but unowned, and interrupt requests
bypass admission so users can stop queued or over-cap chats.

The single-chat API derives `queued_for_capacity` from live pool state;
list endpoints do not report it. The UI polls that value every 5 seconds
while a chat is running and shows a callout when the chat is waiting for
capacity.

Updates the administrator documentation and deployment-wide Prometheus
gauges for active and queued agents. Replica-level values must be
aggregated with `max`, not `sum`.

> Mux updated this PR on Mike's behalf.
2026-08-18 16:55:43 +02:00