mirror of
https://github.com/coder/coder.git
synced 2026-11-22 03:18:31 +08:00
55340de360af2ca55bdb718ab395a6cb778a6708
532
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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. |
||
|
|
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> |
||
|
|
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 |
||
|
|
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> |
||
|
|
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.
|
||
|
|
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.
|
||
|
|
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 --> |
||
|
|
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. |
||
|
|
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> |
||
|
|
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.
|
||
|
|
d0e22343f0 |
fix: make chat model sharing work for sharers without directory access (#28542)
## Problem
This is a bug fix. Chat model sharing UAT (main @
|
||
|
|
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. |
||
|
|
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 --> |
||
|
|
29995c9ef8 | feat: add a per-template workspace rename setting (#27558) | ||
|
|
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. |
||
|
|
eedc0ece47 | fix: avoid 500 when generating chat title from rename dialog and remove unused endpoint (#28306) | ||
|
|
26de6140fb | feat: add flag to disable workspace agent context sync (#28522) | ||
|
|
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 -->
|
||
|
|
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
|
||
|
|
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. |
||
|
|
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> |
||
|
|
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. |
||
|
|
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._ |
||
|
|
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._ |
||
|
|
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._ |
||
|
|
cb52f5339d | feat: show a premium paywall on the external auth settings page (#28435) | ||
|
|
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 |
||
|
|
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> |
||
|
|
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 |
||
|
|
8203b2ebaf | feat!: hide Coder Tasks behind the enable-ai-tasks flag (#28008) | ||
|
|
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 -->
|
||
|
|
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 -->
|
||
|
|
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 --> |
||
|
|
443e3b9b80 |
feat!: org-scope MCP server configs with RBAC (#27942)
Moves `mcp_server_configs` from deployment scope to organization scope
so each organization fully controls the MCP servers its members can use
with Coder Agents.
## Summary
- Migration: adds `organization_id` (NOT NULL, FK) and keeps existing
rows as the default organization's originals with credentials intact.
Other organizations start with no MCP servers and configure their own;
nothing is copied across organizations. Chats outside the default
organization keep any now-cross-organization `mcp_server_ids` entries;
the runtime already ignores IDs that do not resolve in the chat's
organization, so no data rewrite is needed. Slug uniqueness becomes
`(organization_id, slug)`.
- RBAC: new org-scoped `ResourceMCPServerConfig` with regosql converter
and `GetAuthorizedMCPServerConfigs`; org admins get in-org CRUD, org
members get read (replaced by ACL evaluation in the follow-up ACL PR in
this stack).
- API: all config routes nest under the organization, matching
templates: `POST|GET
/api/experimental/organizations/{organization}/mcp-servers` and
`GET|PATCH|DELETE .../mcp-servers/{mcpserverconfig}` (plus
`oauth2/connect`), resolved by a read-only param middleware that
conceals read-denied and cross-organization access as 404. Two routes
stay on the frozen `/api/experimental/mcp/servers/{mcpServer}` block:
the OAuth2 callback (the redirect URI baked into existing AS-side client
registrations) and `oauth2/disconnect`, which must remain reachable by
users removed from the organization so they can still revoke their token
grant.
- Chat runtime: selection validation and generation resolve configs
strictly by IDs, enabled state, and the chat's organization in SQL;
requested duplicates are normalized; invalid or cross-org IDs are
rejected with the precise ID list. IDs already persisted on a chat are
exempt from message-time rejection so disabling a selected server never
blocks sends; generation skips servers that are no longer usable.
- Frontend: API layer and admin settings pages target the new endpoints.
The admin page manages the default organization's servers; the org
picker is tracked separately (CODAGT-714).
- Security hardening from review: OAuth user grants are additionally
bound to `oauth2_revocation_url` (changing it invalidates grants, and a
racing OAuth callback gets 409 instead of recreating a grant).
Stack-wide SSRF protection for MCP config-directed traffic was split
into its own PR at the top of this stack (#28242) to keep this diff
reviewable; this PR keeps main's existing discovery IP-range guard.
OAuth2 auto-discovery now completes before the config row is inserted: a
failed discovery persists nothing, and there is no provisional row that
concurrent updates could race against.
Two follow-up PRs in this stack were split out to keep this diff
reviewable: #28064 completes the swagger annotations for the moved
routes (main already ships these experimental MCP handlers unannotated),
and #28065 carries hardening fixes and regression pins on top of the
cutover.
- Force On enforcement (landed on main mid-review) is org-scoped: the
forced set is read per chat organization
(`GetForcedMCPServerConfigsByOrganization`), so another organization's
`force_on` server never attaches to a chat.
## Breaking changes (experimental API)
The MCP server config endpoints move from the deployment-scoped
`/api/experimental/mcp/servers` block to organization-nested paths:
`POST|GET /api/experimental/organizations/{organization}/mcp-servers`
and `GET|PATCH|DELETE
/api/experimental/organizations/{organization}/mcp-servers/{mcpserverconfig}`
(plus `oauth2/connect`). The old paths are removed, so API consumers
must supply an organization. Two routes intentionally stay on the frozen
`/api/experimental/mcp/servers/{mcpServer}` block: the OAuth2 callback
(its redirect URI is baked into existing AS-side client registrations)
and `oauth2/disconnect` (must remain reachable by users removed from the
organization). These endpoints are under `/api/experimental`, so no
deprecation window is provided.
## Rolling upgrades
During a rolling deploy, an old replica creating an MCP config can fail
the new `NOT NULL organization_id` constraint until it is upgraded
(reads are unaffected: old binaries' generated queries select their own
column lists). This matches the repo's existing precedent for additive
NOT NULL migrations (000562) and affects only the admin config-create
path in the upgrade window.
Upgrades are expected to run in scheduled maintenance downtime with the
database locked during migration, so the migration ships no
rolling-upgrade compatibility machinery. The down migration deletes
organization-created configs (their chat references are cleaned by the
000510 delete trigger) and restores deployment-wide slug uniqueness.
Part of the MCP org-separation stack (CODAGT-711 -> CODAGT-717 audit ->
CODAGT-712 ACLs -> CODAGT-806 token RBAC).
Closes https://linear.app/codercom/issue/CODAGT-711
UAT: validated end to end on a two-org dogfood deployment, including a
real pre-migration to post-migration upgrade, cross-org isolation
(404s), same-slug-two-orgs, chat selection gating, and a live MCP tool
call through the org-scoped generation path. The migration was later
revised to keep existing rows in the default organization only (no
per-organization copies); that revision is covered by the migration test
suite.
> Mux (AI agent) authored this PR on Mike's behalf.
<!-- mux-attribution: model=claude-fable-5 thinking=high -->
---------
Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
|
||
|
|
821d91fabd | fix: log tailnet tunnel authorization decisions (#27819) | ||
|
|
166d92ba73 |
fix: bound request body size on JSON API endpoints (#28168)
## Summary `httpapi.Read` decoded request bodies with no size limit, so a single request could allocate memory without bound. This adds a 4 MiB default ceiling, leaves the endpoints that legitimately need more explicitly exempted, and counts the rejections so a limit set too tight is visible. This is the first of three PRs split out of #28048, covering the endpoints that answer in `codersdk.Response` shape. The OAuth2 decode paths (RFC 6749, RFC 7591) and the SCIM ones (RFC 7644) answer in their own error shapes and follow in separate PRs, along with the lint rule that pins the invariant. Closes PLAT-463. Remediates SEC-416 (CWE-770, CVSS 7.5) and SEC-392. ## Problem `httpapi.Read` calls `json.NewDecoder(r.Body).Decode(value)` with no ceiling, and no middleware in the chain bounds body size. The exposure is pre-authentication: login, OTP, and first-user creation all read a body before any authorization decision is reached. The existing rate limiter bounds request *rate*, which is orthogonal to the memory a single admitted request may consume. ## Fix `Read` is split into `Read` and `ReadLimit`. `ReadLimit` wraps `r.Body` in an `http.MaxBytesReader` and keeps the existing decode and validate logic; `Read` delegates to it with a new `DefaultMaxRequestBodyBytes` of 4 MiB, which covers the 124 remaining non-test callers at a single site. `http.MaxBytesReader` composes as tightest-wins, so the handlers that pre-wrapped their own bodies pass their limit to `ReadLimit` rather than wrapping, and each keeps its previous ceiling byte for byte. That matters most for the bulk secrets import at `8 * MaxSecretsFileBytes`: an unconditional wrap inside `Read` would have silently halved it to the default. `TestImportUserSecretsBodyLargerThanDefaultLimit` is the regression guard for that specific failure, and `TestMaxBytesReaderNesting` pins the composition behavior the whole requirement rests on. Every rejection site calls `httpapi.RecordRequestBodyLimit`, which names the limit that tripped on the request's existing log line and marks the request so `coderd_api_requests_too_large_total{reason="request_body"}` counts body rejections apart from the 413s coderd answers for other causes, such as agent log storage overflow. A limit set too tight for a legitimate payload therefore surfaces without waiting for a user report. The limit is a constant rather than a deployment option: an operator raising it to unblock something would reopen the vulnerability as configuration, where a security scan will not find it. A legitimate 413 is answered with a targeted `ReadLimit` on that endpoint. ## Behavior change `POST /api/v2/files` now answers 413 rather than 400 when a request body exceeds `HTTPFileMaxBytes`. It installed that bound already but reported the rejection as a read failure, which leaked the stdlib `http: request body too large` string through `Detail` and kept the largest limit in the tree off the metric. The separate 413 for an oversized expanded archive is unchanged. The task log snapshot endpoint now answers 413 rather than 400 when its 64 KiB cap is exceeded. Routing it through `ReadLimit` also changes its decode-failure message from "Failed to decode request payload." to "Request body must be valid JSON.", which is what every other endpoint answers. Its tests are updated to match both. `coderd_api_requests_too_large_total` is new, so there is no existing query to migrate. It counts the 413s coderd answers, labeled `method`, `path`, and `reason`. `reason="request_body"` is a rejection by one of the limits above; `reason="other"` is a 413 that has nothing to do with body size, such as agent log storage overflow. ## Reading this The commits are ordered to be read in sequence. Commits 1 and 2 are the security fix; commits 3 to 5 are the observability consequences, and commit 3 is the one that touches dashboards. Commit 7 documents the limit on the REST API reference index. Commits 6 and 8 add and revert an exhaustive `@Failure 413` annotation pass, which buried the fix under its regenerated swagger, and cancel out. |
||
|
|
d3f08b1983 |
feat: audit chat system instructions changes (#27668)
Adds an audit record for administrative events on the deployment-wide
chat instruction settings (system prompt, the include-default toggle,
and the plan-mode instructions), per CODAGT-719 and operator decision
D5. Each endpoint records under a stable identity: resource type
`chat_instruction_settings`, a fixed resource ID and a human-readable
target ("System prompt", "Plan mode instructions"), so two changes to
one setting share an ID and history-by-setting works. A real change
exports a Write entry with the old-to-new text visible; a
value-identical PUT still upserts and still returns 204 but records
nothing.
Attempts are recorded, not only transitions. Identity is assigned before
the authorization check, so a denied PUT exports a 403 row with an empty
diff (no request content reaches it), a validation failure exports a 400
row, and a write failure exports a 500 row, each with an empty diff; an
operator can tell "nothing changed" from "something changed and capture
degraded" by the status code.
The write path stays authoritative. The advisory lock and, on plan-mode,
the transaction exist only to serve change-detection; if any of that
machinery fails (lock, begin, commit, rollback), the handler runs main's
idempotent write path directly and derives the response from it, so a
member-visible failure of audit-only infrastructure can never replace
main's successful response. Accepted consequence: when the lock cannot
be taken, two concurrent identical writes can produce two rows instead
of one. That is audit degradation, which is allowed; changing a member's
response is not. Write failures keep the exact response the endpoint
produced before this wiring (transaction error for the system prompt,
which was always transactional; the raw write error for plan mode, which
was not), and the full transaction error is logged so rollback failures
cannot vanish.
<details>
<summary>CODAGT-66 plan entry: S1 (verbatim)</summary>
**S1 `feat: audit chat system instructions changes`** (CODAGT-719; base:
main)
- Struct: `database.ChatSystemPromptSettings{ID uuid.UUID; SystemPrompt
string; IncludeDefaultSystemPrompt bool; PlanModeInstructions string}`
in `coderd/database/types.go` (ticket-sketched shape; one struct, both
endpoints).
- Registration: union entry (diff.go), table.go entry (`id`
ActionIgnore, other three ActionTrack), `AuditActionMap` Write-only;
four request.go cases (`ResourceTarget` "", `ResourceID` from struct,
`ResourceType` new enum value `chat_system_prompt_settings`,
`ResourceRequiresOrgID` false with the "Artificial ID / deployment
singleton" comment convention).
- Migration: `ALTER TYPE resource_type ADD VALUE IF NOT EXISTS
'chat_system_prompt_settings';` comment-only no-op down (000558 shape);
number picked at push per the numbering constraint.
- codersdk: constant + prose `FriendlyString` ("chat system prompt
settings"); `TestAuditDBEnumsCovered` forces both. `coderd/audit.go`
presentation switches: rely on safe defaults (no link, generic
description); no FE changes (filter label falls back to capitalized
value; acceptable per precedent).
- Wiring `putChatSystemPrompt` and `putChatPlanModeInstructions`:
InitRequest with Action Write; artificial `ID: uuid.New()` on `New` only
when a change is detected; no-op suppression by leaving both aReq sides
unset (nil resource IDs skip the log, request.go skip rule); the write
path itself stays byte-identical (upserts still run unconditionally).
- `putChatSystemPrompt` (writes two keys conditionally in one existing
tx): inside that tx, read the pair via `GetChatSystemPromptConfig` for
`Old`, perform the conditional writes exactly as today, then RE-READ the
pair for `New`. The re-read is load-bearing:
`include_default_system_prompt` is computed from the toggle row AND the
prompt, so a prompt-only write can flip the effective value without the
request carrying the pointer. `PlanModeInstructions` stays zero on both
sides.
- `putChatPlanModeInstructions` (no tx exists today): wrap its
read-upsert in `InTx` (behavior-preserving: same single write);
`Old`/`New` populate only `PlanModeInstructions`; the two system-prompt
fields stay zero on both sides; no cross-key reads.
- Change detection compares the populated payload fields only (never the
artificial ID).
- Tests: handler-level coderdtest with `audit.NewMock()` asserting Write
entry on change and NO entry on a value-identical PUT, for both
endpoints (this also exercises `ResourceRequiresOrgID` end to end); the
fallback-flip case (no explicit include-default row, nonempty prompt set
to empty, effective boolean flips: entry emitted with the boolean diff);
diff assertions (old->new prompt text tracked, not secret) in
`enterprise/audit/diff_internal_test.go`; `TestAuditableResources`
passes by construction.
- Bookkeeping at PR open: correct CODAGT-719's no-op premise ("matches
the existing 204-on-unchanged behavior" does not exist on main;
suppression is new, write path unchanged).
- Review focus: Old capture and the New re-read inside the tx (three of
four existing singletons never set Old; do not copy them; and the
computed include-default value makes a naive New construction wrong);
the skip-on-no-op mechanism; prompt text deliberately visible in diffs.
</details>
Note: the plan excerpt above predates operator decision D5 (2026-07-30),
which this PR implements: the resource type is
`chat_instruction_settings` (not `chat_system_prompt_settings`), each
setting carries a stable ID and a display-name target (not a per-write
artificial ID and an empty target), no-op suppression runs through
`InitRequestWithCancel` (not the nil-ID skip), and attempts (denied,
failed, capture-degraded) record rows with real statuses and empty
diffs. Ticket bookkeeping for CODAGT-719 was corrected on Linear at
kickoff: the ticket's "matches the existing 204-on-unchanged behavior"
premise does not exist on main; suppression is new, and the write path
is unchanged.
> 🤖 This PR was created with the help of Coder Agents, and _will be_
reviewed by a human. 🏂🏻
---------
Co-authored-by: Michael Suchacz <203725896+ibetitsmike@users.noreply.github.com>
|
||
|
|
affeeaf9c8 |
feat: extend agent chat MCP tools for remote UAT evidence loops (#28233)
Extends the Agent-chat MCP tools so an unattended UAT evidence loop can
fetch artifacts, monitor long runs, and find prior runs without burning
model context.
## Backend
- New `chat_files_token` crypto key feature (migration 000571) with
rotator support and a dedicated signing keycache on coderd.
- `POST /api/experimental/chats/files/{file}/download-url`
(authenticated) mints a short-lived (5 min) signed URL and returns it
with `sha256`, `size_bytes`, `name`, `mime_type`, and `expires_at`.
- `GET /api/experimental/chats/files/{file}/download?token=` (no session
token) redeems the signed URL: verifies the JWS, requires the token's
`file_id` to match the path, and re-checks the minting user's RBAC
access live at redemption. Clients can `curl -o` artifacts with zero
credentials in the URL consumer.
- `ChatFileMetadata` gains `size_bytes` (via `octet_length`, no bytes
fetched).
## MCP tools (`codersdk/toolsdk`)
- `coder_download_chat_file`: by `file_id` or `chat_id`+`file_name`;
returns the signed URL plus checksum and size instead of base64.
- `coder_await_chat`: blocks (bounded `wait_secs`, 1-120) until a chat
leaves `running`/`interrupting`, using the existing watch stream with
subscribe-before-read.
- `coder_list_chats`: label, query, and limit filtering; chat
projections now include labels.
- `coder_get_chat_messages`: `after_id` forward cursor with
`next_after_id` (exact incremental reads), plus per-message `files`
metadata so artifact-bearing messages are identifiable.
- `coder_get_chat`: file listings now include `size_bytes` and
`created_at`.
- `coder_list_templates`: exposes `agents_allowed` for pre-flight
checks.
## Testing
- coderd: mint/redeem happy path with an unauthenticated client,
expired/tampered/file-mismatched tokens, auth still required on the
plain file endpoint, non-owner mint rejection.
- toolsdk: harness + integration coverage for all new/changed tools,
including signed-URL redemption with checksum verification,
forward-cursor exactness, await transition/timeout paths, and label
filtering.
- Remote dogfood UAT (dev.coder.com Coder Agent) passed all six
acceptance scenarios end to end over both MCP transports.
Note: `go test ./codersdk/toolsdk/` has a pre-existing goleak flake on
main (leaked `agentssh` non-PTY session goroutines from SSH exec tests;
reproduced 3/3 on clean `b4971bc49f1`). It is unrelated to this diff.
> Mux acted on Mike's behalf to create this PR.
<!-- mux-attribution: model=claude-sonnet-4-6 thinking=high -->
|
||
|
|
7724ee281a |
feat: defer MCP tool schemas behind a find_tools search (#28225)
## Summary When the `mcp-tool-search` experiment is enabled, chatd stops inlining connected MCP tool schemas into every generation. It instead exposes a built-in `find_tools` tool whose description carries a compact catalog of the deferred tools, and only ships full JSON schemas for tools the model has activated by searching or by calling them directly. Closes [CODAGT-760](https://linear.app/coder/issue/CODAGT-760). ## Problem Tool-heavy agent configurations (GitHub, Linear, Notion, and dev-tooling MCP servers) inline over 100k tokens of tool schema definitions into every generation. Initial uncached requests reached ~216k tokens with time-to-first-token close to nine minutes, while the model typically invokes only a handful of tools per turn. ## How it works - `decideMCPToolSearch` defers external and workspace `.mcp.json` MCP tools whenever the experiment is enabled. Native, dynamic, provider, skill, and transport tools are never deferred. - `find_tools` embeds a server-grouped catalog in its tool description (degrading to names-only, then counts-only, then a constant-size summary past a context-scaled size cap) and scores keyword matches across tool names, descriptions, parameter schemas, and server metadata. Queries can scope to one server with a `server:` prefix, and exact `names` arguments always activate. - Activation state is ephemeral: it is re-derived each generation from surviving chat history (`find_tools` results and direct calls to deferred tools), so activations naturally lapse when compaction summarizes them away. Aggregate activated schema weight is capped at 10% of the context window, shedding the least recently activated schemas first; `find_tools` shares that budget across parallel calls in one step. No new persistence. - Deferred tools stay registered for execution, so the model can call a cataloged tool directly without searching first; the schema is activated for subsequent steps. - Fail-open: the experiment being disabled, an empty candidate set, or an MCP tool named `find_tools` all disable deferral, leaving today's behavior byte-identical on the wire. - Prometheus counters/histograms track `find_tools` calls, matches, activations, and deferred token weight. - The conversation timeline renders `find_tools` calls with a collapsed search summary and expandable match list, falling back to the generic renderer on malformed payloads. ## Validation - Unit tests for the catalog, matcher, experiment-gated decision, and activation derivation; end-to-end chatd generation tests covering search-then-call, direct-call activation, experiment-off wire parity, compaction lapse, and subagent tool gating. - Storybook interaction tests for the timeline rendering and malformed-payload fallback. - Remote dogfood UAT on dev.coder.com passed: deferral with a real MCP server and Anthropic model, direct calls without prior search, activation persistence across turns, experiment-off parity, and clean UI/console. > Disclosure: Mux (AI agent) authored this PR on Mike's behalf. |
||
|
|
119f2b1dd9 |
feat: limit concurrent chat agents with pooled admission (#27902)
Limits concurrent chat generation on capped deployments to 5 root chats and 10 delegated subagent chats. The pools are deployment-wide and independent, so delegated work can continue while root capacity is full. The default caps live in AGPL code. Enterprise contributes only a licensing unlock, so unlicensed deployments stay capped and cannot fail open. Licensed deployments are uncapped while Agent Hours usage stays below an explicit hard limit. Deployments without a hard limit remain uncapped, and reaching the Agent Hours allocation only triggers warnings. Admission happens before a worker takes chat ownership. Capped deployments serialize admission across replicas with a transaction-scoped advisory lock and derive active and queued state from current ownership plus fresh runner heartbeats, rather than persisted queue markers or per-replica state. The acquisition query returns a bounded, pool-interleaved candidate set instead of ranking the whole backlog; a migration replaces the acquisition index with a pool-aware one. Refused chats stay running but unowned, and interrupt requests bypass admission so users can stop queued or over-cap chats. The single-chat API derives `queued_for_capacity` from live pool state; list endpoints do not report it. The UI polls that value every 5 seconds while a chat is running and shows a callout when the chat is waiting for capacity. Updates the administrator documentation and deployment-wide Prometheus gauges for active and queued agents. Replica-level values must be aggregated with `max`, not `sum`. > Mux updated this PR on Mike's behalf. |
||
|
|
fa8ffe4eda |
feat: report agent runtime hours usage in entitlements (#27985)
Populate `FeatureAgentRuntimeHours.Actual` on every entitlements refresh for licenses that grant the feature. A new `GetTotalUsageHBAgentRuntimeV1` query sums `runtime_ms` over the license's usage period, reading `usage_events` directly: `hb_agent_runtime_v1` is exactly one row per hourly bucket deployment-wide with `created_at` at the bucket start, enforced by the unique partial index introduced in #27983. The measurement reuses the shared `measureUsage` policy from #27984 through a new `AgentRuntimeMsFn` closure (usage publisher subject): failures publish the stable `LicenseAgentRuntimeUsageUnavailableErrorText` and log the cause. Usage is floored to whole hours, matching the unit of the `agent_runtime_hours_*` claims, and at most one warning is emitted per refresh: reaching the allocation supersedes the advisory soft limit. The dashboard renders the soft-limit advisory muted without a sales link and treats the runtime usage-unavailable text as a diagnostic. **Precise usage.** `Feature.ActualMs` (JSON `actual_ms`), set only for `agent_runtime_hours`, carries the exact stored milliseconds backing the floored `Actual` so clients can render fractional hours (e.g. `10.3`). It has the same freshness as `Actual`; the whole-hour warning thresholds are unchanged. **Unlimited licenses.** A license minted with the unlimited (`-1`) allocation decodes to an enabled feature with a nil `Limit` (#27984), so the warning write-back now guards the allocation dereference: no thresholds can exist for an unlimited license, so no runtime hours warning is ever emitted, while `Actual` is still measured and published. `Feature.Compare` is unchanged; for usage-period features the issued-at/end dates decide first, so a metered feature outranks an unlimited one only on an exact timestamp tie, an edge pinned by a `TestFeatureComparison` case and documented on `decodeAgentRuntimeHours`. **Grandfathered premium licenses.** Premium licenses without `agent_runtime_hours_*` claims are now granted the feature disabled with a zero limit over the license term, identical to an explicit `allocation: 0`: usage is measured and published for every Premium deployment, and chatd's pooled admission (#27902) caps concurrent agentic chats until a license with a positive allocation is added. The default carries a fixed early `UsagePeriod.IssuedAt` (2026-08-01, the same mechanism as the managed-agents default) so any license actually carrying the claims outranks it in the `AddFeature` merge regardless of the licenses' relative issue dates; the constant must stay earlier than the earliest legitimately issued claim-bearing license. Zero allocations (explicit or grandfathered) emit no deployment-wide warning banner: those deployments are steered by the in-page upgrade CTA and the concurrency cap. Enterprise licenses are unchanged. Part 3 of a 3-PR stack splitting up #27796 (see there for review history). Stack: #27983 → #27984 → this PR. Closes CODAGT-852. |
||
|
|
b5d18bb9c9 | feat: add redirect URL override for external auth (#28082) | ||
|
|
2d9b6eda8f |
feat: add experimental CLI to price unpriced AI models (#27926)
## Description AI Gateway computes the cost of an interception from `ai_model_prices`, which is seeded on every server start from a price book embedded in the binary. A model the price book does not cover records a NULL cost, so its spend is invisible to cost reporting and is not enforced against budgets. The only fix was to wait for a Coder release that added the model. This adds an experimental CLI, backed by an experimental HTTP endpoint, for pricing those models. Models the price book already covers are rejected, because the seeder re-applies the book on every start and would overwrite an operator price. Support for custom pricing will be handled in https://linear.app/codercom/issue/AIGOV-589/extend-experimental-cli-command-to-set-custom-ai-model-prices. ## Commands ``` coder exp ai-model-prices list [--provider] [--model] coder exp ai-model-prices update [file|-] [--provider] [--model] [--input-price] [--output-price] [--cache-read-price] [--cache-write-price] [--yes] ``` ## Changes - Add `GET` and `POST /api/experimental/ai/model-prices`, gated behind the AI Bridge entitlement and the existing `ai_model_price` RBAC resource. - Add a `GetAIModelPrices` query with optional `provider` and `model` filters applied in SQL. - Validate the whole request before writing anything, so one bad entry cannot leave the table half updated, and report every problem at once. - Reject prices for models the embedded price book already covers, through a new `prices.IsDefaultPriced`. - Add the `coder exp ai-model-prices` command with `list` and `update`. `update` accepts a JSON document or the single-model flags and prints a plan, asking to confirm unless the document is piped in or `--yes` is passed. - Consolidate the supported provider list into `coderd/aibridge/prices/providers` so the price generator and the server share one definition. - Add `codersdk` types and client methods for both endpoints, and bound the request body at 1 MiB. - Document the command in the AI Gateway cost controls page. Closes https://linear.app/codercom/issue/AIGOV-567/experimental-cli-command-to-set-prices-for-unpriced-ai-models > [!NOTE] > Initially generated by Claude Opus 5, modified and reviewed by @ssncferreira |
||
|
|
c424a76a12 | feat: wire chat search box to full-text search (#27973) | ||
|
|
0a7bb80a1e |
feat: make CLI/API doc generators emit front-matter metadata (Phase 2) (#27246)
## Summary
Phase 2 of the H1 → front-matter migration (`DOCS-483`; parent
`DOCS-477`). Makes the two reference-doc generators emit per-page
metadata as YAML front matter instead of a leading `# H1`, so generated
pages are self-describing and `make gen` stops reverting migrated pages
(Phase 3).
Phase 1 (`DOCS-482`) made the coder.com renderers prefer a front-matter
`title` (manifest fallback).
> [!NOTE]
> Rebased onto `main` and fully regenerated, and updated across two
rounds of Coder Agents Review — see **Review follow-ups** below.
## Changes
- **`scripts/clidocgen/command.tpl` + `gen.go` + `main.go`** — front
matter now carries `title` (from `fullName`) and `description` (from the
command's `Short`), and the leading `# H1` is dropped. The CLI index
page's front matter is taken from the manifest `Command Line` route
(title/description/icon_path).
- **`scripts/apidocgen/postprocess/main.go`** — reads the manifest and,
at write time, injects front matter carrying each section's `title` plus
any curated `description`, `state`, and `icon_path`. The API index
page's front matter is taken from the manifest `REST API` route.
- **`scripts/docgenenv`** (new shared code) — one `YAMLScalar`
front-matter escaper, one `Route`/`Manifest` schema +
`LoadManifest`/`FindRoute`, and one `FrontMatter(Route)` emitter, all
imported by both generators (no duplicated helpers, types, or emitters).
- Regenerated all **166 CLI + 31 API** reference pages.
### Metadata → front matter, and what stays in the manifest
Every *per-page* manifest field is mirrored into the page's front
matter: `title`, `description`, `state`, `icon_path`. The **structural**
fields stay in `manifest.json`:
- `children` — the nav tree (explicitly out of scope).
- `path` — the manifest's pointer to the file; a page carrying its own
path is redundant/error-prone, so it's treated like `children`.
The fields are **duplicated** into front matter and **`manifest.json` is
left unchanged**, so this is a **no-op for rendering today** (coder.com
strips front matter for `llms`, and Algolia + the renderer read only
`title`). Removing the fields from the manifest is the natural
follow-up, gated on the renderer reading them from front matter first.
### Why the API side changes the postprocessor, not the `.dot` templates
The issue text suggested editing
`scripts/apidocgen/markdown-template/*`. I deliberately did **not**,
because the postprocessor derives each page's **filename, section title,
and manifest route** from the leading `# {name}` line
(`extractSectionName`). Emitting front matter from the template would
break that extraction. Instead the widdershins templates still emit `#
{name}`, the postprocessor reads it (and now verifies it), and then
swaps the heading for a front-matter block as each section is written.
## Review follow-ups (Coder Agents Review)
### Round 1 — addressed in `e53d5e03` (all threads resolved)
- **CRF-1 / CRF-4** — de-duplicated the escaper and the
`route`/`manifest` schema + traversal into `scripts/docgenenv` (shared
by both generators).
- **CRF-2** — `YAMLScalar` now quotes YAML-reserved scalars
(`true/false/null/…`, numbers); no current value is affected.
- **CRF-3** — added unit tests: a `YAMLScalar` round-trip, `FindRoute`,
and `prependFrontMatter`.
- **CRF-5** — the CLI and API **index** pages now mirror their manifest
route's title/description/icon_path instead of a hardcoded
`coder`/`API`, fixing a rendered-heading regression (`REST API`/`Command
Line` were being overwritten).
- **CRF-6** — dropped the dead `#login` anchor in
`docs/support/support-bundle.md` (the migrated `login.md` no longer
mints that heading anchor).
- **CRF-7 / CRF-8 / CRF-11** — renamed to `prependFrontMatter`, switched
to `bytes.Cut`, and it now strips the first line only when it is the `#
{name}` heading (`extractSectionName` errors otherwise).
- **CRF-9** — removed the orphan `docs/reference/api/chat.md` (not in
the manifest, not linked; the real page is `chats.md`).
- **CRF-10** — the metadata read and the manifest rewrite now share one
`FindRoute` traversal.
- **CRF-13** — moot under squash-merge; this branch is a single
scopeless commit.
- **CRF-15** — the pre-existing `sort.Slice`/`slices.IsSorted`
comparator is left as-is per the review (out of scope; safe today
because section names are unique).
### Round 2 — addressed in `ee796e7107` (all threads resolved)
- **CRF-16** (P1) — removed three em-dashes from new doc comments (the
only `make lint` failure on the prior head); the emdash gate is green.
- **CRF-17 / CRF-18** — unified front-matter emission into one shared
`docgenenv.FrontMatter(Route)`, used by the API postprocessor directly
and by `command.tpl` via a `frontMatter` template func. This retires the
hand-written template YAML and the
`indexTitle`/`indexDescription`/`indexIconPath` closures, so a new
front-matter field is wired in one place, and it gives the CLI index the
`state` arm it previously lacked. Verified byte-identical: a full CLI +
API regen produces zero page changes.
- **CRF-19** — CLI child sort switched to `slices.SortFunc` +
`cmp.Compare` (typed comparator).
- **CRF-20** — reworded the `prependFrontMatter` comment:
`extractSectionName`'s fail-fast is the load-bearing guard; the prefix
check is a defensive backstop.
- **CRF-21** — added `icon_path`/`state` coverage in `docgenenv`'s
`TestFrontMatter/AllFields` (the branch the index page relies on,
previously at 0%).
- **CRF-22** — `YAMLScalar` no longer emits a trailing-space value as a
bare scalar (YAML strips it on read, so it would not round-trip); added
test coverage.
- **CRF-24** — the shared emitter removed the duplicated `cliIndexRoute`
doc comment; the rationale now lives in one place.
- **CRF-23** (Phase 3, out of scope here) — noted: the API generator
wipes and regenerates `reference/api/` from the manifest, so removing
curated metadata from the manifest in Phase 3 needs another source first
(a generator that preserves existing front matter, or metadata carried
alongside the swagger annotations).
- **Process (Mafu-san)** — the verification set below now leads with
`make lint`, the mandatory CI gate that the earlier list omitted.
## Cross-repo dependency
**Resolved — this PR no longer has a hard merge-ordering gate** (CRF-14
was right; the earlier "must merge after #968" note was stale).
The coder.com surfaces that would otherwise leak raw front matter from
`coder/coder` `main` are already front-matter-aware on merged PRs:
- **coder.com#964** (`DOCS-554`, llms-full.txt corpus + Algolia) —
**merged**.
- **coder.com#974** (`DOCS-574`, the `.md` proxy twin + `llms.txt` index
titles) — **merged**.
coder.com#968 (`DOCS-577`) was re-scoped to only the renderer
route-metadata generalization; it's a no-op on today's corpus and its
own description confirms the "deploy before the generators" constraint
no longer applies (that was driven by the llms corpus, now in #964).
Worth a final confirmation that #964/#974 are **deployed** before merge,
but there's no branch/PR ordering blocker left.
## Verification & evidence
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 manual verification.
- `make lint` (golangci-lint + the emdash gate) passes; `go build` / `go
vet` / `go test` are clean for the generators + `scripts/docgenenv`;
`pnpm check-docs` passes.
- `swagger.json`, `docs.go`, and `manifest.json` are **unchanged** —
metadata is duplicated into front matter; command/section names and
routes did not move.
- The diff is purely additive front matter
(`title`/`description`/`state`/`icon_path`) + the leading H1 removal; no
body reflow. A full CLI + API regen produces **zero** page changes
beyond the two index pages.
<details>
<summary>Terminal evidence</summary>
CLI `description` from the command's `Short` (`YAMLScalar` quotes when
needed, e.g. a `Short` with a colon):
```md
---
title: server
description: Start a Coder server
---
```
API pages inherit curated manifest metadata (only Agents/Chats have any
today):
```md
---
title: Chats
description: "REST endpoints for Coder Agents Chats API (programmatic agent sessions)."
state:
- early access
---
```
Diff scope + "no body changes" proof (uses an explicit `base..HEAD`
range, so it actually tests the claim):
```
$ git diff --shortstat origin/main
210 files changed, 1447 insertions(+), 344 deletions(-)
# = 166 CLI + 31 API reference pages + generators + scripts/docgenenv
# swagger.json / docs.go / manifest.json: NOT modified
# Every removed line under docs/reference is a leading "# H1"; nothing else:
$ git diff origin/main..HEAD -- docs/reference/ | grep '^-' | grep -v '^---' | grep -v '^-# '
(empty)
$ pnpm check-docs
Summary: 0 error(s)
```
</details>
Linear: DOCS-483
> This PR was created with AI assistance (Coder Agents).
|
||
|
|
6e07e2610f |
feat: add paginated API endpoint for groups (#27603)
backend-only changes from #27271; see that PR for summary of changes + implementation details |
||
|
|
9a57dfa642 |
feat: include agent metadata in workspace list responses (#27934)
Closes #27933. Related: #27897 (single-agent GET). Agent metadata is only readable via a per-agent watch stream, so reading it across N workspaces costs N+1 requests. This adds a batch read to the list endpoint: ```text GET /api/v2/workspaces?q=param:"pool=demo" include_agent_metadata:task_status ``` - New `include_agent_metadata` search key, repeatable and key-scoped. It expands the response, it does not filter workspaces. - `GetWorkspaces` aggregates the requested keys as JSON behind a `CASE`: without opt-in the response is unchanged and the subquery never runs. Runs only for the returned page, inside the same authorized query. - Agents in the response gain `metadata` (`[]codersdk.WorkspaceAgentMetadata`, `omitempty`), mapped by the `workspace_agent_id` each element carries. The collection script is omitted; it can be long. - `codersdk.WorkspaceFilter` gains `IncludeAgentMetadata []string`. - No wildcard, no schema change, no migration. --- Authored by Coder Agents on behalf of @Emyrk. |
||
|
|
0ac23e3ee1 |
feat: add per-template Coder Agents access control (#27285)
Relates to CODAGT-713 Depends on #27284 This makes the per-template `agents_allowed` field authoritative in the API and chatd. It adds optional create and metadata update fields with the intended default and omission semantics, supports `agents-allowed:` template search, includes the value in telemetry, and makes `list_templates`, `read_template`, and `create_workspace` read the template row directly. Existing-workspace retries remain idempotent, and blocked same-organisation templates return an actionable message. The experimental `/template-allowlist` routes remain temporarily because the shipped AI Settings page still calls them, but they no longer control chatd enforcement. #27514 moves that page to per-template metadata, #27515 removes the legacy storage, routes, SDK types, and utility, #27517 adds the CLI flags, and #27518 updates the platform controls documentation for the per-template model, directly addressing CRF-5 and CRF-6. The stack is intended to merge as a unit. |
||
|
|
0d0c6e53ba | fix(coderd): document HTTP 201 for workspace and build creation (#27903) | ||
|
|
4b9880afa6 |
feat: add --chat-hook-allow-insecure to allow plain HTTP chat hook URLs (#27896)
Adds a hidden `--chat-hook-allow-insecure` / `CODER_CHAT_HOOK_ALLOW_INSECURE` deployment option (default `false`) that allows the chat lifecycle hook URL to use plain HTTP for any host. The HTTPS requirement is enforced at two points, and the flag relaxes both: `DeploymentValues.Validate()` rejects `http` hook URLs at startup, and the hook dispatcher's `validateHookURL` allows `http` only for loopback hosts. With the flag set, any-host `http` is accepted; the host, fragment/userinfo, secret, and timeout checks are unchanged, and non-http(s) schemes still fail. This removes the need for an HTTPS reverse proxy when testing a hook consumer on a trusted network. Following security review feedback, the flag description and docs state that plain HTTP lets an on-path attacker forge hook responses (which control agent execution), and `coder server` logs a startup warning (with a redacted hook URL) when hooks run over plain HTTP. Docs, generated API types, and the server config golden are updated accordingly. > Mux acted on Mike's behalf to create this PR. |