Commit Graph
682 Commits
Author SHA1 Message Date
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
david-fraley fef0763820 feat: report template builder build failure reasons in telemetry (#28586) 2026-09-10 08:21:29 -04:00
Garrett Delfosse 65d01ef9b7 fix: error on CLI HTTP redirects instead of following them (#29104) 2026-09-09 07:34:51 -04: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
Harsh Singh Panwar df4a7644fd feat: import template metadata from README frontmatter on push (#28465) 2026-09-08 21:45:43 -06: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
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
Jeremy RuppelandCoder Agents 8b8c80614d feat: expose template builder agents and per-module agent (#28905)
Part of [DEVEX-556](https://linear.app/codercom/issue/DEVEX-556). Builds
on the base agent metadata added in #28794.

## Summary

Surfaces the backend multi-agent support through the SDK and HTTP API:
the bases endpoint returns each base's agents, and
compose/create-template accept a per-module `agent_name`.

## What changed

- `codersdk/templatebuilder.go`: added `TemplateBuilderBaseAgent`,
`TemplateBuilderBase.Agents`, and
`TemplateBuilderComposeModule.AgentName` (`agent_name,omitempty`).
- `coderd/templatebuilder_handler.go`: added `baseAgentsToSDK`; the
bases endpoint returns agents, and the compose and create-template
endpoints forward `AgentName`.
- `make gen` regenerated `site/src/api/typesGenerated.ts`,
`coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`,
`docs/reference/api/schemas.md`, and
`docs/reference/api/templatebuilder.md`.
- `wizardState.test.ts`: added `agents: []` to the base fixture now that
the field is required on the generated type.

## Scope

SDK/API plumbing only. `ComposeModule.AgentName` now has a producer (the
handlers) but no caller sets it yet — the wizard UI (follow-up) is what
will populate it. No DB change, so `enterprise/audit/table.go` is
unaffected.

## Testing

- Bases endpoint asserts each base returns agents with exactly one
default (and the `dev`/`main` names).
- Per-module `agent_name` round-trip and unknown-agent (400) compose
tests.
- `make gen` (idempotent), `make fmt` (no changes), `golangci-lint
./coderd/... ./codersdk/...`, the Go template-builder tests, frontend
`tsc` + `biome check`, and docs markdownlint all pass.

<details>
<summary>Design note</summary>

`display_name` is intentionally returned as `""` for now: every base is
single-agent, so no base authors a per-agent label. The field exists for
multi-agent bases where the wizard radio needs a human-readable name;
consumers fall back to the agent `name` when it is empty.

</details>

---
🤖 Generated by Coder Agents on behalf of @jeremyruppel.

Co-authored-by: Coder Agents <agents@coder.com>
2026-09-02 12:51:33 -04: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
Matt VollmerandNick Vigilante cb6c98147f docs: add Agent Relay docs (#28786)
## What this adds

Two new docs pages for **Agent Relay**, a feature that connects a
supported cloud-hosted AI agent provider's hosted sessions to
self-hosted Coder workspaces. The provider's orchestration and AI
inference stay cloud-hosted; a worker process inside the workspace
executes the agent's tool calls.

- `docs/ai-coder/agent-relay/index.md` — top-level overview: what it is,
what it does, what it is and isn't, business value, current state, and
supported providers.
- `docs/ai-coder/agent-relay/cursor.md` — the Cursor-specific child
page, naming Cursor Cloud Agents and Cursor's own bring-your-own-machine
(BYOM) terminology.

Both pages are tagged `"state": ["early access"]` in the manifest and
state the feature is in **closed preview with select customers**,
pointing readers to their Coder account team or `sales@coder.com` for
access.

## Also included

- `docs/user-guides/workspace-management.md`: broadened the workspace
definition to include coding agents alongside developers.
- `docs/reference/glossary.md`: added an Agent Relay entry (alphabetized
between Agent Firewall and AI Gateway) and added it to the existing
"agent" term-disambiguation callout, since it's easy to conflate with
Coder Agents.

## Scope note for reviewers

`Agent Relay` itself (the underlying service, config, and worker
implementation) lives in a separate, non-public repository. I don't have
access to that source from this environment, so I deliberately kept both
pages high-level and didn't invent specifics like CLI flags, config file
structure, or exact command syntax. Before this goes further, someone
with access to that repo should verify the mechanics described here
(workspace-per-session lifecycle, provider pool mapping, worker
connection model) against the real implementation, and a follow-up PR
should add a step-by-step "Getting started" section once the feature
moves past closed preview to something self-serve.

## Validation

- `docs/manifest.json` is valid JSON.
- `markdownlint-cli2`: 0 issues across all changed/added Markdown files.
- `vale --no-exit`: 0 errors on every changed/added file (a handful of
pre-existing gerund-heading warnings on `workspace-management.md` and
`glossary.md` predate this branch and aren't touched here).
- `scripts/check_emdash.sh`: passes.
- Confirmed every relative link target in the new pages resolves to a
real file in the repo.

<details>
<summary>Decision log</summary>

- Dropped an "air-gap capable" claim and a "Coder AI Gateway" claim that
would have been present in an earlier draft: the integration requires
the in-workspace worker to hold an outbound connection to the cloud
provider for inference/orchestration, so true air-gapping isn't
possible, and Coder's AI Gateway isn't in the inference path for this
feature.
- Named the specific Cursor product as **Cursor Cloud Agents** and
linked Cursor's own "bring-your-own-machine (BYOM)" terminology
(`cursor.com/docs/cloud-agent/bring-your-own-machine`) rather than
inventing Coder-specific naming for the same concept.
- Kept "workspace" lowercase per the existing style guide (`workspace`
is the documented generic-concept casing, distinct from named features
like "Workspace Proxy"), while still linking the term to the Workspace
Management page.
- Used "closed preview with select customers" rather than "Preview," and
removed a blanket "not feature-complete or stable" disclaimer sentence
per explicit direction.

</details>

---

🤖 This PR was created by Coder Agents on behalf of @mattvollmer.

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-09-02 09:19:49 -04:00
Bartek Gatz 55340de360 feat: add deployment setting to disable the Codernauts game (#27662)
Adds a `codernauts_enabled` runtime setting (default: enabled) that
controls whether the Codernauts game link appears in the user dropdown
menu. A toggle at the bottom of the Deployment > Appearance page
controls it, and the value persists in `site_configs`, so it survives
restarts and upgrades without any CLI flags or environment variables.

The setting works on all licenses: `GET /api/v2/appearance` reports it
from both the enterprise and the default (AGPL) appearance fetchers, and
`PUT /api/v2/appearance` persists it gated only by the deployment-config
RBAC permission, not by an entitlement. On the Appearance page the
toggle renders outside the Premium paywall introduced in #27948; the
other appearance fields keep their existing licensing behavior.

Note: a pure AGPL-only build of coderd does not register the
`/api/v2/appearance` routes at all, so the toggle cannot be saved there.
The standard `coder server` binary is unaffected regardless of license
state.

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

- `coderd/database/queries/siteconfig.sql`: new `GetCodernautsEnabled` /
`UpsertCodernautsEnabled` queries backed by a `codernauts_enabled` key
in `site_configs`; defaults to `true` when unset (no migration needed).
- `coderd/database/dbauthz`: read has no authz checks (matching other
appearance reads); write requires `ResourceDeploymentConfig` update.
Coverage added to `dbauthz_test.go`.
- `codersdk`: `codernauts_enabled` added to `AppearanceConfig` and
`UpdateAppearanceConfig`.
- `coderd/appearance`: the default fetcher takes a `database.Store` and
reads the setting from the database so unlicensed deployments serve it
too.
- `enterprise/coderd/appearance.go`: fetches the value in `Fetch` and
persists it in `putAppearance`.
- Frontend: "Codernauts game" toggle section on Deployment > Appearance
saving immediately via the existing appearance mutation;
`codernauts_enabled` threaded from `useDashboard().appearance` through
Navbar to `UserDropdownContent`, which renders the menu item only when
enabled. Storybook stories with `play` functions cover toggling
(entitled and not) and the dropdown hiding the link when disabled.

</details>

---

🤖 This PR was generated by Coder Agents on behalf of @bartekgatzcoder.
2026-09-02 11:29:35 +02: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
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
57cbca585f feat: negotiate and persist authorization scope (#28178)
**TL;DR**

Middle of the stack, split out of #28045, that makes an OAuth2 app's
scope allowlist actually restrict what a client can be granted. The
authorize endpoint has always parsed `scope` and then thrown it away.

| 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 (this)** | 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. Both GET and POST negotiate, so
a doomed request fails before the consent page renders. |
| #28179 | The consent page states what was negotiated, and
`invalid_scope` is delivered to the client's own callback per RFC 6749
§4.1.2.1 instead of a Coder error page. |

- Each earlier PR is inert alone: the columns carry a placeholder, the
coverage rules have no caller.
- Visible on upgrade, unlike the rest of the stack. A scope name outside
the catalog, OIDC vocabulary included, now gets `invalid_scope`, on
admin-created apps as well as DCR ones.
- Tokens are unaffected. This changes which authorization requests
succeed, not what a token can do.

**Where in the flow**

- Authorize endpoint only, both legs: GET before the consent page
renders, POST before the code is minted. The token exchange, refresh,
and revocation are untouched.
- The result is persisted on the authorization code. The exchange copies
it onto the token row, but the API key it mints still carries no scope,
so nothing is enforced at request time yet.
- Registration and discovery are unchanged. The catalog checked against
is the `scopes_supported` both discovery documents already advertise.

**What it satisfies**

- OAuth 2.1 §1.4.1 — the server "MAY fully or partially ignore the scope
requested by the client, based on the authorization server policy". The
app's allowlist is that policy; until now the server ignored scope in
every direction.
- OAuth 2.1 §1.4.1 — on an omitted scope it "MUST either process the
request using a pre-defined default value or fail the request". The
filtered allowlist is that default; an allowlist filtering to nothing
takes the second branch. Same rule as RFC 6749 §3.3.
- OAuth 2.1 §1.4.1 — scope values "are defined by the authorization
server", and OIDC is named there as an extension that defines its own.
Hence `invalid_scope` for openid/profile/email rather than silent
acceptance.
- OAuth 2.1 §4.1.2.1 — `invalid_scope` is "invalid, unknown, or
malformed", which now covers an uncatalogued name and an over-broad one
alike. Delivery is interim here (static page on GET, error body on
POST); §4.1.2.1 wants it redirected to the client's callback, which is
#28179.
- OAuth 2.1 §4.1.1 — `scope` stays OPTIONAL. Omitting it selects a
default, never an error.
- RFC 7591 §2 — a registered `scope` is the list "the client can use
when requesting access tokens", a ceiling rather than a menu. Enforced
here for the first time; a client that registered an unsupportable one
repairs it via RFC 7592.
- RFC 8414 §2 — `scopes_supported` is that catalog, advertised since
before this stack, so a conformant client had no grounds to send a name
outside it.
- Not yet: §1.4.1 also requires `scope` in the token response when the
grant differs from the request. Tokens are untouched here, so that lands
with enforcement.

---

Split out of #28045
([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). #28167 has
merged, so this diff is against main and reviews on its own.

The authorize endpoint parsed scope and threw it away, so an app's
allowlist never restricted anything and a client asking for too much was
never told no. Phase 1 added the columns that carry a negotiated scope
from a code to the token, but nothing wrote one.

**What changes**

- Requested names must be in the external scope catalog. The app's
stored allowlist is filtered through that same catalog, which only ever
narrows.
- The allowlist bounds authority, not spelling. A request is granted
when every permission it grants is also granted by the allowlist, named
or not, so an app allowed coder:workspaces.access can approve a client
asking only for workspace:ssh.
- Omitting scope grants the filtered allowlist (RFC 6749 §3.3).
- Both handlers negotiate, so a request that cannot succeed fails before
the consent page renders rather than after the user clicks Allow.
- Two paths produce an empty result and stay distinct. No allowlist and
no request keeps the previous unrestricted grant, written as an explicit
sentinel because the column is NOT NULL with a non-empty CHECK. An
allowlist filtering to nothing is rejected, since falling back would
grant more than it ever permitted.

**Accepted compatibility break, and it is wider than DCR.** The catalog
check runs before the allowlist is consulted, so it covers admin-created
apps too.

- Admin-created apps store no allowlist and had scope discarded
outright. A client sending OIDC vocabulary (openid, profile, email) now
gets invalid_scope on upgrade.
- DCR apps registered with openid, read or admin also hold allowlists
this server cannot grant from, and fail in both directions.
- scopes_supported has always been advertised on both discovery
documents, predating this stack, so a conformant client had no grounds
to send an uncatalogued name. RFC 6749 §4.1.2.1 makes invalid_scope the
answer for one that does.
- Grandfathering would seed the enforcement path with values it cannot
evaluate: a visible error now, a silent hole later.
- The rejection names the registered scopes and the remedy. Pinned in
TestOAuth2AuthorizeDCRScopeCompatibility.

**Interim error delivery, replaced in PR 3.** Rejections go out however
each handler already reports errors: a static error page on GET, an
OAuth2 error body on POST. #28179 delivers them to the client's own
callback (RFC 6749 §4.1.2.1) and rewrites the requireInvalidScope
helper. About 25 lines here are interim on purpose and flagged as such
in that helper.

**Not changed.** Issued tokens are still unrestricted. The exchange
copies the negotiated scope onto the token record, but the API key it
mints carries no scope. This changes which authorization requests
succeed, not what a token can do.

Stack: #28167 (merged), this PR, then #28179 for the consent page and
the invalid_scope redirect.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
2026-08-31 09:29:27 -07:00
Stefan Naglee 589e313e83 fix: emit provisioner tags query param as string in swagger (#28311)
## Summary

The `tags` query parameter on the "Get provisioner daemons" and "Get
provisioner jobs" endpoints was annotated as `@Param tags query object`,
which caused Swagger to emit `"type": "object"` for a query parameter.
Query parameters cannot be of type `object` in the OpenAPI 2.0 spec, so
this produced an invalid schema that breaks spec validators and client
generators.

As noted in the doc, the value is actually a single JSON-encoded string
(parsed via `QueryParamParser.JSONStringMap`), so the correct type is
`string`. This is a doc only concern as generators do not use this file.

## Changes

- Change the `tags` query param annotation from `object` to `string` in:
- `coderd/provisionerdaemons.go` (`GET
/api/v2/organizations/{organization}/provisionerdaemons`)
- `coderd/provisionerjobs.go` (`GET
/api/v2/organizations/{organization}/provisionerjobs`)
- Regenerate API docs (`make coderd/apidoc/.gen`):
`coderd/apidoc/swagger.json`, `coderd/apidoc/docs.go`, and the reference
markdown.

The description still documents the expected JSON form
(`{'tag1':'value1','tag2':'value2'}`), so no behavior changes for
callers.

> [!NOTE]
> This PR was generated by Coder Agents on behalf of @snagles.
2026-08-31 11:36:43 -04:00
Stefan Naglee 1fa6ebe5c3 fix: support first-user-trial in non-interactive login (#28321)
## Summary

`coder login --first-user-trial=true` was unusable in non-interactive
environments: the trial info fields could only be collected via
interactive prompts, so scripted setup failed with a bare `EOF`.

This adds flags and env vars for every trial info field, extracts the
functions into a helper, turns the EOF into an actionable error, and
fixes a related quirk where enabling the trial via env didn't reliably
suppress the trial prompt.

Fixes coder/coder#23264

## Changes

* Add a flag + env var for each trial field (matching the existing
`first-user-*` convention):
`--first-user-trial-{first-name,last-name,phone-number,job-title,company-name,country,developers}`
and their `CODER_FIRST_USER_TRIAL_*` env vars.
* When a trial field is missing with no input available, return an error
naming the exact flag/env instead of a raw EOF.
* Read `CODER_FIRST_USER_TRIAL` from `inv.Environ` instead of
`os.Getenv` so the flag binding and the "Start a trial?" prompt gate
agree (previously the env toggle could hit an EOF prompt that silently
reset `trial` to `false`).
* Regenerate `coder_login_--help.golden` and
`docs/reference/cli/login.md`.

## Testing

* Non-interactive login via flags and via env vars (env test asserts the
trial is actually provisioned via a recording `TrialGenerator`).
* Missing trial info returns the clear flag-naming error instead of
hanging.
* Existing interactive `TestLogin` subtests pass; `golangci-lint` clean.

## Notes

No strict CLI validation of `country`/`developers` against the UI option
lists: the server doesn't enforce them, and the existing fixture uses
`developers=10-50` which isn't in the CLI bucket list. Can add if
preferred.

---

*Created by Coder Agents on behalf of* @snagles\*.\*
2026-08-31 11:35:59 -04: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 8e49655e13 docs: remove early access label from chats API reference (#28760)
The Coder Agents chats API was promoted from `/api/experimental` to
`/api/v2` (CODAGT-921), but the docs still labeled the Chats API
reference as early access. This removes the early access state from the
Chats entry in `docs/manifest.json` and regenerates
`docs/reference/api/chats.md` so its front matter drops the label.

The generated reference already documents the promoted endpoints under
`/api/v2`. Intentionally unchanged: the computer-use desktop stream
endpoint stays documented under `/api/experimental` with its
experimental note, and the Advisor and Virtual desktop pages keep their
early access state, since those features remain experimental.

Validated with `make coderd/apidoc/.gen` (no drift), `pnpm check-docs`,
and `make lint/docs-html`. Remote dogfood UAT ran against the pushed
head and passed.

> 🤖 Xum created this PR on behalf of @ibetitsmike.
2026-08-30 21:01:08 +02: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
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
Hank Hwang c9dedc65e6 fix: model nullable UUID fields as uuid strings in Swagger (#28684)
## TLDR
Updated `.swaggo` file to include new rule to replace all
`uuid.NullUUID` with a `type: string` and `format: uuid` in
`swagger.json`. One such property example is `context_file_agent_id`

## What

Nullable UUID fields (`uuid.NullUUID`) were rendered in the
Swagger/OpenAPI spec as nested objects (with `UUID` and `Valid`
sub-fields) instead of as a plain UUID string. This adds a swaggo
`replace` directive so `uuid.NullUUID` is modeled as a `string` with
uuid format, matching how these fields serialize over the wire and how
other UUID fields are already documented.

## Changes

- `.swaggo`: add `replace github.com/google/uuid.NullUUID string` (with
an explanatory comment), alongside the existing `NullTime` replacement.
- `coderd/apidoc/docs.go` and `coderd/apidoc/swagger.json`: regenerated
output reflecting the new modeling.

## Testing

- Generated docs via the standard `make gen` flow; `docs.go` and
`swagger.json` are the regenerated artifacts.

---

> This PR was created by Coder Agents on behalf of @hwang251.
2026-08-27 09:13:33 -07:00
Rowan SmithandClaude Opus 5 4830010c8e chore: update tailscale fork version used by coder to remove hairpin probes (#28682)
Updates the version of tailscale used by Coder to pull in
coder/tailscale/pull/132 in order to remove hairpin probes, a feature
long ago removed from upstream tailscale. Requested by a customer.

https://linear.app/codercom/issue/PLAT-537

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 14:40:37 +02:00
Ethan 0f5c7b3154 refactor!: remove default organization model routes (#28632)
> [!IMPORTANT]
> Most of the added lines in this PR are generated API reference content
for publishing the organization-scoped `GET` and `POST
/api/v2/organizations/{organization}/chats/models` replacements. There
is no matching generated-doc deletion because the three removed
default-organization endpoints are experimental and are not present in
the generated public API reference on the current base. The removed
paths remain only as explicit 404 reservations, with no
default-organization shim or functional handler.

## Summary

Remove the unused default-organization chat model collection routes:

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

Use the organization-scoped collection instead:

```text
GET  /api/v2/organizations/{organization}/chats/models
POST /api/v2/organizations/{organization}/chats/models
```

## Context

The intention of PR #28440 was to consolidate model availability into
the organization-scoped models collection for CODAGT-898 and remove the
superseded collection routes. That PR removed
`/organizations/{organization}/chats/models/available`, but it missed
these older default-organization routes and explicitly retained one of
them. This PR completes the intended #28440 cutover. The repository has
no SDK, CLI, or frontend consumer for the removed routes.

This change also prevents PR #28496 from promoting the missed
default-organization `/chats/models` route into the stable `/api/v2`
API.

This change is separate from the one-release `/api/experimental`
compatibility window in CODAGT-921. That window preserves experimental
versions of the intended stable API. It does not require compatibility
routes for unused deployment-scoped endpoints.

Refs CODAGT-898.

## Breaking change

Clients that call the removed routes must use the organization-scoped
model collection and provide an organization.

## Changelog

Remove unused default-organization Coder Agents model API routes. API
clients must use the organization-scoped chat models collection.

> [!NOTE]
> Coder Agents generated this pull request on Ethan Dickson's behalf.
2026-08-27 10:49:14 +01:00
EthanandMichael Suchacz d0e22343f0 fix: make chat model sharing work for sharers without directory access (#28542)
## Problem

This is a bug fix. Chat model sharing UAT (main @ 3c32408) found two
bugs when a delegated "Model Sharer" role holds only
`chat_model_config:read` + `chat_model_config:share`:

This state is reachable entirely through the UI in a normal
least-privilege setup:

1. An org admin restricts **Organization Settings → Workspace Sharing**
to `none` or `service_accounts`.
2. Under **Organization → Roles**, they create a custom role with only
the advanced permissions `chat_model_config:read` and
`chat_model_config:share`.
3. Under **Organization → Members**, they assign that role to the person
responsible for managing model access.
4. An admin creates a chat model and may initially share it with a
group.
5. The delegated sharer signs in, opens **AI Settings → Models → [model]
→ Share model**, where the failures below occur.

- **UAT-05 / UAT-08:** with workspace sharing set to `none`, the sharing
dialog errored out entirely ("Resource not found or you do not have
access to this resource"). The sharer couldn't view, add, or even remove
grants.
- **UAT-04:** with workspace sharing set to `service_accounts`, existing
group grants rendered as raw UUIDs, and groups didn't appear in the
add-principal search.

Both have the same cause. The ACL GET returned bare UUID→role maps, so
to display names (and to power its add-principal search) the dialog
called the generic org directory APIs: list organization members and
list groups. Those APIs require `organization_member:read` and
`group:read`, which the sharer role doesn't have. Ordinary members only
get them as a side effect of a *different* feature:
`OrgMemberPermissions` grants member read when the org's workspace
sharing mode isn't `none` (so users can pick coworkers to share a
workspace with), and group read only when it's `everyone`. The chat
dialog was silently borrowing those workspace-sharing permissions, so it
only worked when that unrelated org setting happened to grant them:

- `none`: no member read → dbauthz rejects the member listing → the
dialog's query chain 404s and everything blanks (UAT-05/08).
- `service_accounts`: member read but no group read → the group listing
silently filters to empty → group grants can't be resolved past their
UUIDs (UAT-04).

In short: an org setting about who can share workspaces was deciding
whether a delegated sharer could manage a chat model ACL.

## Fix

Stop borrowing directory permissions entirely; authorize everything
through the model's own share permission, using the two patterns the
repo already has for ACL editors:

- **Hydrate the ACL GET** to return resolved users and groups instead of
UUID maps, like `workspaceACL` and the per-chat ACL already do. Fixes
the raw UUIDs.
- **Add `GET .../acl/available`** returning assignable org members and
groups for the autocomplete, modeled directly on
`templateAvailablePermissions` (same query semantics, same
share-gate-then-system-context lookup that every sibling ACL endpoint
uses). Fixes candidate discovery. The new endpoint exists only because
the dialog has no permission-safe way to enumerate principals today; it
is plumbing for the fix, not a new feature.

This is exactly how template sharing already solves the same problem:
`templateACL` returns hydrated principals, and
`templateAvailablePermissions` gates on the template then does the
lookups under a system context because, per its own comment, "the caller
might not have permission to read all users". We differ from the
template version only where newer conventions exist:

| | Template | This PR |
|---|---|---|
| Gate | `ActionUpdate` on the template (predates `share`) |
`ActionShare` on the model, matching the workspace/chat/MCP ACL
endpoints |
| User candidates | Site-wide `GetUsers` | Non-system members of the
model's org only |
| Group hydration | Full member rosters | Member counts, batched in one
query |

The dialog now runs off the hydrated ACL plus the new endpoint, so all
three sharing modes take the same code path, and a discovery failure no
longer blanks existing grants. `OrgMemberPermissions`, the directory
APIs, and the PATCH (still a sparse UUID→role delta) are untouched.

## Diff breakdown

+1274/−191, but only about a third is product code:

- **Product (~450):** the two endpoints and hydration helpers
(`exp_chats_model_acl.go`, ~240), the dialog rework plus a new colocated
autocomplete component (~200), and SDK/site API plumbing (~60).
- **Tests (~625):** backend tests updated to hydrated shapes plus new
tests that reproduce the two failing UAT sharing modes end-to-end
(+418), rewritten and new story play tests (+198), and query/mock
updates.
- **Generated (~200):** swagger, apidocs, `typesGenerated.ts`, API
reference docs.

Depends on #28498 (stacked on the `/api/v2` chat API promotion; the new
endpoint is registered under both prefixes like its siblings).

---------

Co-authored-by: Michael Suchacz <203725896+ibetitsmike@users.noreply.github.com>
2026-08-27 10:49:13 +01:00
Susana Ferreira 276d0a8586 fix: expose effective member AI budgets (#28410)
## Description

The group members page could not distinguish an unlimited Everyone
fallback from a configured budget on the Everyone group when viewing
another group, so it incorrectly displayed `Unlimited` and `Everyone
(not allocated)` despite the configured Everyone budget.

The member spend response now includes `effective_budget` as the
canonical budget that currently applies to the user. The existing
`group_budget` field remains for backward compatibility and is
deprecated in favor of `effective_budget`.

## Changes

- Add `effective_budget` to group member AI spend responses.
- Deprecate `group_budget` in favor of `effective_budget`.
- Display budgeted Everyone as the governing group instead of
`Unlimited` and `Everyone (not allocated)`.
- Add database, API, conversion, and Storybook coverage.

Closes https://linear.app/codercom/issue/AIGOV-588

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-08-26 16:17:07 +01:00
Michael Suchacz 351bb14032 feat: mount chat API routes under /api/v2 (#28496)
## Stack context

This is the base of a 3-PR stack promoting the chat API from
`/api/experimental` to `/api/v2`: server compatibility mounts (this PR),
codersdk promotion (#28497), and frontend path updates (#28498).

## Summary

Double-mount the stable chat and MCP handlers under `/api/v2` while
retaining the existing experimental routes for the one-release
compatibility window decided in CODAGT-921. CODAGT-922 tracks removing
the compatibility mounts.

The shared route builders preserve existing authentication and
middleware behavior. Experiment-gated, debug, tombstone, and legacy
default-organization model routes remain experimental-only. Signed file
URLs, external OAuth callback URLs, and mixed-version replica relays
also remain on the experimental prefix during the transition.

Update Swagger and the generated API reference for the promoted routes,
including the workspace lookup and a runnable raw-body chat file upload
example. Retain internal endpoints outside the published reference,
share chat-file rate limits across both prefixes, enable CORS for the v2
MCP routes, and cover dual mounts plus exclusions with compatibility
tests. Remote dogfood UAT passed for the promoted chat, model, MCP, and
file flows.

> [!NOTE]
> Xum acted on Mike's behalf in this pull request.
<!-- xum-attribution: model=claude-fable-5 thinking=high -->
2026-08-26 16:17:06 +02:00
Michael Suchacz 845790e652 feat: enable Coder Agents for organization members (#28186)
## Summary

- make Coder Agents available to organization members without a separate
built-in role
- remove the obsolete role from backend and frontend role surfaces
- update authorization, UI, documentation, and regression coverage

## Database note

This PR intentionally ships no migration so it backports cleanly across
diverged migration numbers. Stale `agents-access` grants may remain in
user role arrays and org default member roles; the retired name is
treated as a grant of nothing (role expansion drops it, assignment
validation ignores it, and the name stays reserved). A follow-up PR will
add the data cleanup migration.

## Validation

- `make gen`
- `make lint`
- repository pre-commit checks
- targeted RBAC, migration, chat API, enterprise, site, Storybook, and
race tests
- `git diff --check`

## Rollback note

Rolling back the deployment restores the previous behavior directly: no
data changed, and older binaries still resolve any lingering
`agents-access` grants.

> Mux created this pull request on Mike's behalf.
2026-08-26 13:33:13 +02:00
McKayla はな 29995c9ef8 feat: add a per-template workspace rename setting (#27558) 2026-08-25 11:05:42 -06:00
Garrett Delfosse 378ac91b49 fix: stem chat search terms with the english text search config (#28319)
Chat message search used the `simple` text search config, which folds
case but does no stemming, so `refactor` did not match messages
containing `refactoring`. Message bodies now index and query with the
`english` config, which stems both sides. Titles, PR titles, and all
other filters are unchanged.

Migration `000585` adds a `chat_messages.search_tsv_config` enum column
recording which config produced each stored vector and stamps existing
vectors `'simple'` (a column-only update; vectors and indexes are
untouched, since rewriting `search_tsv` would block message writes on
large tables). The dbpurge sweep gains a bounded
`ReindexStaleChatMessagesSearchTsv` pass that rewrites stale vectors
newest first and stops for the process lifetime once drained. Until a
row is rewritten, `GetChats` matches it with the config that produced
it, so pre-migration exact-form searches keep working during the drain.
Vectors written by old binaries mid rolling upgrade cannot stamp the
config, stay pending, and self-heal on the next upgraded sweep.
Steady-state DB load is unchanged.

The down migration resets `english` vectors to `NULL` so the parent
version's existing sweep rewrites them with `simple`.

Closes
[CODAGT-867](https://linear.app/codercom/issue/CODAGT-867/backend-search-improvements-to-handle-partial-matches)

<details>
<summary>Decision log</summary>

- **`english` stemming over prefix matching.** On a 300k-row corpus a
stemmed lookup is a single GIN entry-tree probe, while `term:*` prefix
matching unions posting lists of every lexeme sharing the prefix (up to
a full scan for short prefixes), is asymmetric, and loses the
`websearch_to_tsquery` phrase/OR/negation UX. `pg_trgm` rejected as a
heavier index with different semantics.
- **Scope to message bodies only** (review). Titles and PR titles keep
their `simple` FTS expressions and indexes, identical to main.
- **Config-versioned queue over migration-time reset** (review). An
unqualified `UPDATE ... SET search_tsv = NULL` rewrites every indexed
row in the migration transaction, and an old replica could backfill
reset rows with `simple` vectors that permanently leave the `search_tsv
IS NULL` queue. The config column makes staleness explicit and both
problems disappear.
- **Enum over `text`** (review) for the config column.
- **Trade-offs.** English stopwords are dropped from message search
(stopword-only queries match no messages); stemming is English-specific;
titles do not stem; prefix matching remains out of scope.

</details>

---

🤖 This PR was generated by Coder Agents on behalf of @f0ssel.
2026-08-25 09:08:52 -04:00
Garrett Delfosse eedc0ece47 fix: avoid 500 when generating chat title from rename dialog and remove unused endpoint (#28306) 2026-08-25 06:52:45 -04:00
Jon Ayers 26de6140fb feat: add flag to disable workspace agent context sync (#28522) 2026-08-24 19:58:30 -05:00
Michael Suchacz b6d7653231 fix: apply MCP server selection when editing a chat message (#28471)
## Problem

Editing a user message in an Agent chat silently dropped the MCP server
selection. The composer renders the MCP picker in edit mode and toggles
update local client state, so the picker displayed the new selection,
but the edit request omitted `mcp_server_ids` at every layer (frontend
request builder, `codersdk.EditChatMessageRequest`, the `PATCH
/chats/{chat}/messages/{message}` handler, and `chatd.EditMessage`). The
chat's persisted selection never changed and the regenerated turn ran
without the newly enabled MCP tools. Two dogfood users hit this within
hours; there is no error anywhere and the UI shows the opposite of the
server state.

## Changes

- `codersdk`: add `MCPServerIDs *[]uuid.UUID` to
`EditChatMessageRequest`, mirroring `CreateChatMessageRequest` (nil
preserves the current selection).
- `chatd`: extract the send path's MCP update block into one shared
`applyRequestedMCPServerIDs` helper (explore-subagent snapshot
immutability guard plus Force On enforcement, Cure53 CDM-02-010) and
call it from both `SendMessage` and `EditMessage`, so enforcement cannot
drift between the two paths.
- `coderd`: extract the send handler's request validation (dedupe,
enabled-in-organization check, persisted-ID exemption) into
`normalizeRequestedChatMCPServerIDs` and wire it into the edit handler,
which now threads the selection into `EditMessageOptions`.
- Frontend: the edit request now includes `mcp_server_ids:
[...effectiveMCPServerIds]`, exactly like the send path, making the
picker's displayed state real.
- `make gen` artifacts (swagger, API docs, `typesGenerated.ts`).

## Tests

Each layer is covered and was proven with independent red toggles
(removing one layer's wiring fails only that layer's tests):

- chatd (`TestEditMessage_MCPServerIDs`): edit applies a provided
selection, nil preserves it, an emptied list cannot remove a `force_on`
server, and explore subagent chats keep the spawn-time snapshot.
- API (`TestPatchChatMessage/MCPServerIDsApplied`,
`MCPServerIDsInvalidRejected`): persistence via the endpoint, omission
preserves, unknown IDs get the same 400 as the send path.
- Storybook (`EditAppliesMCPServerSelection`): toggling a server on
during an edit puts it in the edit request payload.

Note: the `AgentChatPage.stories.tsx` story "Queued For Capacity After
Polling" fails locally on current main as well (verified against the
main baseline with this branch's changes reverted); it is unrelated to
this diff.

Remote dogfood UAT ran on the exact head and passed, including proof
that the regenerated turn actually gains the newly enabled MCP server's
tools.

> 🤖 Xum acted on Mike's (@ibetitsmike) behalf. • Model:
`anthropic:claude-fable-5`
<!-- xum-attribution: model=anthropic:claude-fable-5 -->
2026-08-24 17:39:52 +02: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
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
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
Michael SuchaczandEthan Dickson 0ef331fcd0 feat!: scope chat model override settings to organizations (#28442)
Moves chat model override settings from deployment scope to organization
scope, following the org-scoping of chat model configs in #28440.

Depends on #28440 (based on
`ethan/chat-models-availability-consolidation`).

Remote dogfood UAT passed on this change, including multi-organization
scenarios on a licensed deployment with real models.

## Problem

Chat model configs are now owned by organizations, but the override
settings that reference them stayed deployment-wide: admin
subagent/title/compaction overrides in `site_configs`, personal
overrides in `user_configs`, and the advisor model embedded in the
advisor runtime JSON. A single deployment-level override can only point
at one organization's model config, so overrides effectively worked for
the default organization only, and title generation had to soften its
hard-failure contract to tolerate unusable overrides.

## Fix

Admin overrides (general, explore, title generation, compaction,
advisor) and personal overrides (root, general, explore) become
organization-scoped rows in two new typed tables,
`chat_organization_model_overrides` and `chat_user_model_overrides`.
Composite foreign keys on `(organization_id, model_config_id)` make
cross-organization model references unrepresentable. The migration
deletes the legacy serialized `site_configs`/`user_configs` override
keys instead of migrating them; admins and users re-select models in the
new organization-scoped settings.

New endpoints live under
`/api/experimental/organizations/{organization}/chats/model-overrides`
(admin defaults) and
`/api/experimental/organizations/{organization}/members/{user}/chats/model-overrides`
(personal overrides); the legacy deployment-level routes are removed.
chatd resolves overrides via the chat's organization, restoring the
hard-failure contract for configured-but-unusable title generation
overrides. The deployment-level `AllowUsers` switch and advisor runtime
limits stay deployment-scoped.

The Coder Agents settings UI gains a per-organization "Defaults &
overrides" page under AI Settings > Models, and the personal overrides
page gains an organization selector for users in multiple organizations.
Advisor telemetry now reports per-organization override rows.

**BREAKING CHANGE**: Existing deployment-level overrides are dropped,
not migrated. Every organization starts with no overrides after upgrade,
and model selections must be re-applied in the new settings. The legacy
deployment-level override endpoints are removed.

Closes https://linear.app/coder/issue/CODAGT-872

> [!NOTE]
> Xum (AI agent) authored this PR on behalf of @ibetitsmike.

<!-- xum-attribution: model=claude-opus-4-6 thinking=high -->

---------

Co-authored-by: Ethan Dickson <ethan@coder.com>
2026-08-24 11:20:26 +01:00
Ethan 3809314b31 refactor!: consolidate chat model availability (#28440)
## Summary

Consolidate chat model management and runtime availability into a single
organization model collection contract. The organization model response
now includes provider availability, unavailable reasons, and
unsupported-provider details, so callers no longer need a separate
availability request.

Depends on #28439.

## Problem

The organization-scoped API exposes two overlapping representations of
the same chat models:

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

The collection route returns organization-owned model configurations and
redacted provider descriptors. The availability route returns a second
catalog-oriented response with provider availability and synthetic
catalog entries. Callers must fetch, reconcile, and cache both responses
even though they describe the same effective set of models.

This creates duplicated server logic and separate SDK, OpenAPI, and
frontend types. It can also produce inconsistent client state when one
request succeeds while the other fails or when the two responses are
refreshed at different times.

## Fix

Return all model-management and runtime-availability information from
the organization model collection route:

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

`OrganizationChatModelsResponse` continues to return the caller-readable
organization model configurations and redacted provider descriptors.
Provider descriptors now also include:

- `available`
- `unavailable_reason`

The response additionally includes `unsupported_providers`, allowing
clients to explain configurations that the Agents harness cannot use.

Frontend model settings, agent creation, existing chat recovery, and
model override surfaces now consume this single collection query. This
keeps model ownership, caller visibility, provider availability, and
unsupported-provider guidance in one cache entry and one authorization
path.

The default-organization compatibility route remains available:

```text
GET /api/experimental/chats/models
```

It now returns the same consolidated `OrganizationChatModelsResponse`
contract instead of the former availability response.

## Breaking change

This removes the separate organization model availability endpoint:

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

Clients using that endpoint must migrate to:

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

This PR also removes the corresponding public experimental client and
schema surface:

- `ExperimentalClient.ChatModelAvailability`
- `ChatModelAvailabilityResponse`
- `ChatModelProvider`
- `ChatModelCatalogEntry`
- The generated OpenAPI schema and frontend API/query types for the
availability endpoint

Callers must use `ExperimentalClient.ChatModels` and
`OrganizationChatModelsResponse` instead. Availability is now reported
on each `ChatModelProviderDescriptor`, and unsupported providers are
returned in `OrganizationChatModelsResponse.UnsupportedProviders`.

The default-organization compatibility route retains its URL, but its
response schema changes from `ChatModelAvailabilityResponse` to
`OrganizationChatModelsResponse`. Direct HTTP clients and generated
clients that decode the previous response type must be updated even if
they do not use the removed organization-scoped `/available` route.
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
Ethan 9bd8899359 refactor: clarify chat model resource names (#27958)
Rename the admin-managed SDK resource from `ChatModelConfig` to
`ChatModel`. Rename catalog entries from `ChatModel` to
`ChatModelCatalogEntry` and replace `ChatModelsResponse` with
`ChatModelAvailabilityResponse`.

API routes and JSON fields do not change. Experimental SDK and OpenAPI
schema names do change.

Depends on #27957

_This pull request description was generated by Coder Agents._
2026-08-24 09:43:45 +00:00
Ethan cbe24a3da5 feat: add chat model config RBAC resource (#27957)
Add the `chat_model_config` RBAC resource, actions, and API key scopes.
This layer includes the scope migration and generated API types. Model
list queries apply token scopes, SQL authorization filters, and row
ACLs.

Write and default-management handlers keep deployment configuration
authorization until the next API layer replaces it.

Depends on #27956

_This pull request description was generated by Coder Agents._
2026-08-24 09:43:45 +00:00
david-fraley cb52f5339d feat: show a premium paywall on the external auth settings page (#28435) 2026-08-21 11:45:38 -05:00
david-fraley a2afb458c5 feat: add premium paywall conversion telemetry (#28425)
**TLDR:** When someone using free Coder taps a "Start trial for free"
button, we now write down which page they tapped it on, and whether they
went on to actually start the trial. That tells us which locked features
make people want Premium.

## Brief summary

- Records two things: the button being clicked, and a trial actually
being started.
- Each click gets a random ID that travels with the person to the trial
form, so we can tell who finished from who walked away.
- Records a short label for the page (like `appearance` or `audit_log`),
never the web address, so no customer names are collected.

#28226 added the trial form and has since merged, so this now targets
`main`.

## Description

Today the "Start trial for free" button just moves you to the Premium
page and nothing is recorded, so there is no way to know which feature
convinced someone.

This adds two events:

| Event | Happens when |
|---|---|
| `cta_click` | Someone clicks "Start trial for free" |
| `trial_signup` | A trial licence is actually issued |

The click generates a random ID. It rides along to the trial form and
gets saved on the signup, so a click and a signup can be matched up
later. Clicks with no matching signup are the people who gave up. Trials
started without a paywall (for example straight from the sidebar) are
labelled `direct`, so "no label" never gets confused with "broken".

A few small choices worth knowing:

- The ID is kept in browser session storage, not in the web address, so
the URL stays clean. It expires after 30 minutes.
- The trial signup event is recorded by the server, not the browser, so
nobody can fake a signup.
- The browser cannot say which kind of event it is sending. It can only
report a click; the server labels it.
- Only people allowed to start a trial are counted. The server rejects
the rest, which matters because a few paywalls show their button to
everyone.
- Nothing is recorded at all when telemetry is turned off.

There is deliberately no "paywall was shown" event. Every admin page
visit would report one, which is a lot of noise for little insight.

Every paywall in the [Premium Copy
Updates](https://www.notion.so/coderhq/Premium-Copy-Updates-3c1d579be59280a59557cabd54fd8a1f)
table has a label. The rows that do not are badges and alerts with no
button to click.

## Proof

Ran a local Coder with no licence and clicked the paywall button on the
Appearance page.

What the browser sent, and the reply:

```json
POST /api/v2/deployment/premium-funnel-events  ->  204 No Content
{"id":"92d96afa-f975-4789-b8a7-b1fd19d4df85","source":"appearance","variant":"premium"}
```

What the browser saved for the trial form, same ID:

```json
{"id":"92d96afa-f975-4789-b8a7-b1fd19d4df85","source":"appearance","createdAt":1787268520857}
```

The click then landed on the Premium page with the trial form.
Screenshots of the network panel, the saved value, and the Premium page
are attached below. The form itself was not submitted, since that would
contact the real licence server.

## Testing

- Backend tests: a click is recorded with the server's own label, an
unknown page label is refused, and a normal member is refused.
- Storybook tests: button clicked and ID saved on all three paywall
styles, plus the case where the viewer only sees guidance text and has
nothing to click.
- Unit tests for the saved ID: expiry, bad data, unknown page label, and
the `direct` fallback.
- `make gen` is clean, and lint, types, and formatting pass.

Two stories fail on `main` today and fail the same way here:
`ExternalAuthSettingsPageView > Page` and `PremiumPageView > No
License`. Neither file is touched by this branch; both were verified
failing on `main` with this branch checked out elsewhere.

## Follow-up

coder/coder-telemetry-server#45 saves these events for reporting. It
merges after this one.

<details>
<summary>Plan and decisions</summary>

**Goal:** find out which Premium paywall drives trial signups, and tell
abandons apart from completions.

**Options considered and dropped:**

1. Put `?from=appearance` in the URL. Rejected: messy for users.
2. Use router state. Rejected: lost if the page is refreshed.
3. Let the browser report the signup. Rejected: it could be faked or
lost during the redirect.
4. Work out the page from the URL. Rejected: URLs contain organization
and template names.
5. Report every paywall impression. Rejected: one event per admin page
visit is noise, and the click is the signal.
6. Separate event types and tables. Rejected: makes the matching query
harder for no gain.

**Event shape:**

```go
type PremiumFunnelEvent struct {
	ID            uuid.UUID // event ID; for a click this is also the matching ID
	EventType     string    // cta_click | trial_signup, set by the server
	Source        string    // appearance, audit_log, ..., direct
	Variant       string    // which paywall design was shown
	AttributionID uuid.UUID // the click this signup came from
	UserID        uuid.UUID
	CreatedAt     time.Time
}
```

**Where the code lives:** nothing under `components/` imports from
`modules/`, so the paywall components stay presentational and only gain
an `onCTAClick` prop. New wrappers in `modules/paywall/` own the
reporting, one per paywall style, each taking a fixed `source`.

**Self-review:** the `frontend-review` skill caught that reading
permissions inside the wrapper forced an auth context into
presentational page views, which broke their stories. Every call site
already passes `canViewPremium={permissions.viewAllLicenses}` and the
button only renders when that is true, so the wrapper no longer reads
permissions and the server stays the gate. It also flagged one
unattributed paywall on the Security page, now wired up as
`browser_only`.

</details>

> Generated with [Coder Agents](https://coder.com/agents) on behalf of
@david-fraley
2026-08-21 10:31:01 -04:00
Samuel VolinandMatt Vollmer f44a3b59d7 feat: Premium Page CTA updates and form handling (#28226)
* Premium page has form for signing up for a trial
* Input validation and normalization for trial form fields
* api endpoint definition to make this processes seamless 
* license page updates to access `?success=true` queryparam and confetti

<img width="1512" height="833" alt="Screenshot 2026-08-17 at 10 08
41 PM"
src="https://github.com/user-attachments/assets/1766e724-c63a-4da9-b2bd-a98e6b66cc9b"
/>

<img width="1510" height="874" alt="Aug-17-2026 22-12-38"
src="https://github.com/user-attachments/assets/3a2a0f35-1176-4290-aa0d-b3f7d66c15d6"
/>


```mermaid
sequenceDiagram
    autonumber
    actor Owner
    participant UI as UI<br/>TrialRequestForm + PremiumPage
    participant API as API<br/>api.ts + coderd middleware
    participant Coderd as Coderd<br/>postTrialLicense + trialer
    participant Licensor as Licensor<br/>v2-licensor + Postgres + pubsub + cache

    Note over UI: mutation.status = "idle"

    Owner->>UI: fills 10 fields, checks acknowledgement
    UI->>UI: Yup validate, strip "acknowledged", submit
    UI->>API: POST /api/v2/licenses/trial<br/>cookie + X-CSRF-TOKEN
    Note over UI: mutation.status = "pending"

    API->>API: verify CSRF, apiRateLimiter,<br/>apiKeyMiddleware sets actor
    API->>Coderd: dispatch

    Coderd->>Coderd: audit.InitRequest, authorize license:create,<br/>httpapi.Read validates, HasLicense is false
    Coderd->>Licensor: POST trial request<br/>deployment_id unspoofable, 10s deadline
    Licensor-->>Coderd: 200, raw signed JWT

    Coderd->>Coderd: ParseClaimsIgnoreNbf, uuid.Parse
    Coderd->>Licensor: InsertLicense, updateEntitlements,<br/>publish PubsubEventLicense, commit audit log
    Licensor-->>Coderd: database.License
    Coderd-->>API: 201 codersdk.License
    API-->>UI: 201 codersdk.License

    Note over UI: mutation.status = "success"
    UI->>Licensor: invalidate entitlements + licenses keys
    UI->>Owner: navigate /deployment/premium?success=true
    Note over Owner: confetti fires on the success param
```

---------

Co-authored-by: Matt Vollmer <matthewjvollmer@outlook.com>
2026-08-21 09:54:54 -04:00
Susana Ferreira 50ecd6959f feat: add a source filter to the AI model price list (#28329)
## Description

With prices from the price book and prices set through the API both in the table, `list` showed only the price in effect and gave no way to tell where it came from. There was also no way to see the price book's entry for a model that had been overridden, since the listing resolves to the custom price.

This adds a `source` column to the output and a `--source` filter for narrowing to one source, or to every row with `all`.

Note: `--source` selects rows rather than models. A model carrying both a price book price and a custom one appears under either value, so the two filtered listings do not sum to the unfiltered one. `--source all` reports both rows at once.

## Changes

- Add `Source` to `codersdk.AIModelPrice` and `AIModelPricesFilter`, and map it in `db2sdk`, which previously dropped it.
- Filter `GetAIModelPrices` by source before resolution, so the price book's row for an overridden model stays reachable.
- Accept `all` as a source, which reports every price a model holds instead of resolving to one.
- Accept a `source` query parameter on the list endpoint, rejected with a 400 when outside the enum.
- Add `--source` to the list command and a `source` column to its output.
- Document the column and the filter, and lead the price section with `coder exp ai-model-prices list`.
- Distinguish a deployment's default prices from the price book that ships with each release.

Closes https://linear.app/codercom/issue/AIGOV-593

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by @ssncferreira
2026-08-20 11:56:58 +01: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
Michael Suchacz f2bc9ab1f5 docs: complete swagger annotations for organization-scoped MCP routes (#28064)
Adds the missing swagger annotations for the eight organization-scoped
MCP server config routes introduced in #27942 and checks in the
regenerated API artifacts (`coderd/apidoc`, `docs/reference/api`). No
behavior changes: 58 hand-written annotation lines, the rest is
generated output.

## Stack context

Part of the MCP org-separation stack (CODAGT-711 org scope -> apidocs ->
hardening -> CODAGT-717 audit -> CODAGT-712 ACLs -> CODAGT-806 token
RBAC). Split out of #27942 to keep the core cutover reviewable; these
routes live under `/api/experimental`, where main already ships several
MCP handlers without annotations, so the base PR is consistent with
existing precedent until this lands.

Closes nothing on its own; documentation completion for CODAGT-711.

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

<!-- mux-attribution: model=claude-fable-5 thinking=high -->
2026-08-19 18:36:25 +00:00