mirror of
https://github.com/coder/coder.git
synced 2026-11-22 03:18:31 +08:00
531637744a4befed81b390cf389717e16e6694de
2879
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
42fcd332c6 |
fix: remove CORS from the OAuth2 authorization endpoint (#29143)
fix(oauth2): exclude authorization endpoint from permissive CORS - Apply standard CORS to `/oauth2/authorize`, with or without a trailing slash, as required by OAuth 2.1 §3.1. - Normalize repeated slashes before selecting the policy to prevent exclusion bypasses, including in wsproxy. - Preserve permissive CORS for other OAuth2 endpoints, discovery documents, and MCP. Same-origin consent behavior is unchanged. - Add middleware and router regression tests and update provider security docs. |
||
|
|
a763e2ea6a |
chore(docs): update release docs for v2.36.5 (#29177)
Automated docs update for v2.36.5 release. Created by `releasetui`. |
||
|
|
80c2621f9d |
docs: document missing AI model price notifications (#28775)
Documents the weekly **Missing AI Model Prices** notification, its recipients, limits, and delivery defaults. Follows up on #28419. --- Created by Coder Agents on behalf of @evgeniy-scherbina. --------- Co-authored-by: Susana Ferreira <susana@coder.com> |
||
|
|
fef0763820 | feat: report template builder build failure reasons in telemetry (#28586) | ||
|
|
8a4f2f80fa |
refactor: implement standard IdP sync settings (#28935)
> 🤖 This PR was written by Coder Agents on behalf of Jake Howell. Refactors the IdP sync settings pages to use the shared settings patterns and make group and role mapping management clearer. It also separates claim-value loading between the two tabs so each form consistently reflects its configured sync field. - reorganizes group and role sync controls into clearer settings sections (standard components) - preserves the group and role tabs while loading claim values independently - adds a typed confirmation dialog before deleting group mappings - consolidates policy export and unseen-claim UI into shared components | <img width="2880" height="1800" alt="idp-sync-group-settings" src="https://github.com/user-attachments/assets/bc0cca7d-f56d-459b-a284-518a551386bb" /> | <img width="2880" height="1800" alt="idp-sync-delete-dialog" src="https://github.com/user-attachments/assets/702a8435-8f0c-4232-b515-1df4210f1500" /> | | --- | --- | --------- Co-authored-by: Tyler <tyler.tate@coder.com> |
||
|
|
8e3c36ec5a |
fix: standardize org use in the mcp server tools (#29141)
Addresses https://linear.app/codercom/issue/CODAGT-970/expose-mcp-tools-for-organization-selection. Currently our MCP server does not handle organizations consistently. Some tools, like `create_template`, use a random organization if the user is in multiple orgs. Others, like `create_chat`, pick the organization which contains the latest chat the user spawned. This PR standardizes organization use in the MCP server tools. Organization ID is now in the argument schema of all tools that depend on it. It's always optional. If the user is only a member of one organization, tools default to that organization. If the user is a member of multiple organizations, tools return an error asking to supply an organization id. This PR also adds a new `list_organizations` tool to allow MCP clients to view the organizations that the user has membership in. |
||
|
|
d8e3f4fcf7 |
feat: evict the oldest attachments at the chat file cap (#29063)
Closes CODAGT-933 Long agent sessions were hitting the 50 attachment cap, after which every upload, screenshot and `attach_file` call was rejected, so people were abandoning otherwise healthy chats. Rather than raise the cap (which just moves the cliff and multiplies the worst-case per-chat `bytea` storage), a chat now keeps its 50 most recent attachments. `LinkChatFilesAfterLock` deletes the oldest `chat_files` rows in the same statement and the cascade drops their links. Files in the incoming batch are never evicted, so the only remaining rejection is a single message with more than 50 files. Nothing in the product ever linked one file to two chats, so rather than guard the eviction against it, this adds `UNIQUE (file_id)` on `chat_file_links`, with the migration dropping any existing duplicates in favour of the oldest chat. Evicted attachments render as the existing "Attachment expired" tile. A `pinned` flag is the obvious follow-up if someone needs to keep a specific file around. |
||
|
|
1818844069 |
fix: ignore unrecognized parameters at the token endpoint (#29139)
fix(oauth2): ignore unrecognized token request parameters Align `/oauth2/tokens` with OAuth 2.1 §3.2 and `/oauth2/authorize` by ignoring unknown parameters and logging only their names at debug level, never values. Continue rejecting duplicate known parameters, with tests covering all nine and shared unknown-parameter inputs across both endpoints. Misspelled optional parameters are now ignored rather than returning 400. Changes are limited to `coderd/oauth2provider`, with no new endpoints or schema changes. Closes https://linear.app/codercom/issue/PLAT-577 |
||
|
|
716a3fdbfd |
fix: match OAuth2 redirect_uri against every registered redirect URI (#29014)
- Fix OAuth2 redirect validation to accept any registered URI, resolving Cursor’s rejection when using its second callback (fixes #28910; stacked on #29013). - Deduplicate primary and alternate callbacks, validate every registered entry, preserve primary-callback defaults and existing code-to-token redirect checks, and stop exposing registered URLs in errors. - Add regression tests and update documentation; defer admin removal of registered URIs (PLAT-619) and requiring redirect_uri when multiple URIs are registered (PLAT-620) to follow-ups. |
||
|
|
9f27e2b17c |
feat: let an OAuth2 refresh narrow the granted scope (#28751)
fix: honor scope narrowing on OAuth2 token refresh Allow `POST /oauth2/tokens` to mint an access token with the requested scope when covered by the consented grant. Narrowing affects only the new access token; the stored grant and rotated refresh token scope remain unchanged. Omitting `scope` uses the full grant. Validate scope names against the catalog, then compare permission coverage rather than set membership so `coder:all` grants can narrow. Reject unknown or uncovered scopes with `400 invalid_scope` without minting tokens or consuming the refresh token. Refresh still does not re-check the app's current allowlist. - Sanitize and cap token endpoint `error_description`, sharing the authorize path's length limit. - Rename the scope-coverage log field `allowlist` to `ceiling` and add `phase=refresh`. - Update provider docs for scoped refreshes, `invalid_scope`, composite scope caveats, and OAuth 2.1 draft -16. Part 1 of 3 for PLAT-481, the final phase of PLAT-470. |
||
|
|
b23d73d501 |
docs: retire the generated feature stage lists (#29113)
## Problem `docs/install/releases/feature-stages.md` advertised two generated lists, and neither one earned its place: - **Available early access features** rendered "Currently no experimental features are available." The generator read `ExperimentsSafe`, which is empty, while `ExperimentsKnown` in `codersdk/deployment.go` defines fourteen experiments. The page told readers no experimental features existed, which is false. - **Available beta features** rendered a table built from `state: beta` nodes in `docs/manifest.json`. It is only as accurate as those flags, which are easy to forget when a feature graduates. Both are drift surfaces that promise a completeness the docs cannot maintain. ## Change Retire the indexes rather than repair them: - Delete `scripts/release/docs_update_feature_stages.sh`. - Remove both generated sections from `feature-stages.md`, along with their `BEGIN`/`END` markers and `DO NOT EDIT` banners. - Drop the `docs/install/releases/feature-stages.md` Makefile target and its two generated-files-list entries, so the page is no longer treated as generated. The page keeps everything that describes the stages themselves: the stage comparison table, the early access / beta / GA guidance, and the `--experiments` enabling instructions. Nothing else links to the removed anchors. ## Verification - `make gen` leaves no unstaged changes beyond the three intended edits. - `pnpm run lint-docs` passes with 0 errors; `markdown-table-formatter` reports no formatting to apply. - `grep` confirms no remaining references to the deleted script, and no inbound links to `#available-beta-features` or `#available-early-access-features`. ## Context Supersedes #28949, which took the opposite approach and generated the experiments list from `ExperimentsKnown`. Following discussion with David, the decision is not to advertise either list. <details> <summary>Decision log</summary> **Why not fix the experiments list instead?** That was #28949: a new `scripts/experimentsdocgen` generator plus a committed `docs/experiments.json`, generating the table from `ExperimentsKnown` with descriptions parsed out of the constants' comments. It worked, but it made the docs responsible for tracking an internal, unstable surface. Experiments are by definition subject to removal or rename without notice, and several of the constant comments are developer notes rather than user-facing prose. **Why remove the beta table too?** The original ask covered the experiments list. The beta table shares the same failure mode: it is a completeness claim maintained by proxy, through `state` flags in `docs/manifest.json`, with nothing that fails when a feature ships to GA and the flag is not updated. Deleting the script removes both, and David confirmed retiring both lists. **Why remove the Makefile target rather than leave a no-op?** With no generated regions left in the file, keeping the target would mean the `make -B gen` unstaged-files check still guards a page nothing generates. Removing it lets the page be edited as ordinary prose. **What was deliberately left alone.** The `state: beta` flags in `docs/manifest.json` stay: they drive badges elsewhere in the docs and are not part of this change. `ExperimentsSafe` and `ExperimentsKnown` in `codersdk` are untouched. The feature-stage definitions and the `--experiments` instructions stay, since readers still need to know what the stages mean and how to opt in, and that content does not go stale as features move between stages. </details> I have read the AI Contribution guidelines. --- Linear: [DOCS-878](https://linear.app/codercom/issue/DOCS-878/remove-the-feature-stages-generator-script-and-retire-the-generated) 🤖 Generated with Coder Agents on behalf of @nickvigilante. <details> <summary>CI note: unrelated flakes on the first run</summary> The initial run of `test-go-pg-17` failed in `cli` and `coderd`: - `TestSSH_OneShotCommandMode/{ClosesStdinOnEOF,DoesNotRequestPTY,PropagatesExitCode,RequestsPTYWithFlag}` - `TestWorkspaceUpdateAutostart/{DST_start,friday_to_monday,monday_to_tuesday}` - `TestWorkspaceFilterManual/FilterQueryHasAgentTimeout` - The `cli` package then hit `panic: test timed out after 25m0s`. This PR changes no Go code and no CI configuration; the diff is one deleted shell script, one Markdown page, and the Makefile wiring between them. Re-running the failed jobs turned everything green with no code changes. </details> |
||
|
|
65d01ef9b7 | fix: error on CLI HTTP redirects instead of following them (#29104) | ||
|
|
8472a6884f |
chore!: remove env-based AI provider configuration (#29053)
> AI tools were used to create this PR Removes deprecated AI provider configuration through environment variables, CLI flags, and YAML. Deletion includes indexed providers and legacy OpenAI, Anthropic, and Bedrock options under both AI Gateway and AI Bridge branding, eg. `CODER_AI_GATEWAY_PROVIDER_<N>_*` or `CODER_AI_GATEWAY_ANTHROPIC_KEY`. Removes the associated startup-seeding code. Updates tests and documentation. **Breaking change:** Remove [obsolete AI provider CLI flags and YAML keys](https://coder.com/docs/ai-coder/ai-gateway/providers#database-management-of-providers) before upgrading, otherwise Coder will fail to start with an `unknown flag` or `unknown option` error. Provider environment variables are ignored and no longer seed the database. Existing database-stored provider configuration is preserved. |
||
|
|
df4a7644fd | feat: import template metadata from README frontmatter on push (#28465) | ||
|
|
0ad8eebbf7 |
fix: allow any port on loopback OAuth2 redirect URIs (#29013)
Fix: Allow variable ports for registered HTTP loopback redirect URIs (127.0.0.1, [::1], and localhost), enabling native apps to use dynamically assigned ports. Apply this registration-matching exception at both authorization and token endpoints while preserving the presented port. Safeguards: Keep all other URI components and non-loopback matching unchanged, and retain exact code-to-token redirect URI matching, including the port. Implementation and verification: Add shared matching logic, automated tests, and updated documentation. All 29 manual scenarios passed, although browser click-through to a listener on an OS-chosen port was not tested. |
||
|
|
dbd4924f51 |
chore: make content-guidelines canonical for evidence-versus-claim rule (#28594)
Agent-authored docs PRs kept leaking implementation detail into user-facing pages: chat status enum values and `root_chat_id` on the auto-archive page (#28570, flagged by reviewers), and RBAC resource names and response fields in the first revision of #28482. The correction pattern was the same each time: state the behavior in the reader's terms. This encodes that pattern as one canonical rule with citations in every file that carries the exact-values instruction: - `docs/.style/content-guidelines.md`: new guiding principle "Evidence justifies a claim; it does not belong in the claim". The test is scoped to the task the page documents, with a first-match ladder: exact value where the reader types or receives it, visible product wording where the screen shows it, plain reader's-terms prose otherwise. An identifier set described as a set resolves at the lowest rung any member reaches. Stripped identifiers are named (file and symbol) in the PR discussion as a best-effort pointer for the reviewer. Cross-linked with verify-exact-values, describe-current-version, the routing table, and word-choice. Also repairs a pre-existing broken feature-stages link. - `docs/.style/style-guide/word-choice.md`: the internal-references section notes that implementation identifiers follow the (conditional) canonical rule, covering the prose-edit route that AGENTS.md sends to the prose style guide. - `.claude/docs/DOCS_STYLE_GUIDE.md`: the Accuracy Standards section head and Key Principles item 2 carry the same qualifier, since this always-loaded file is where agents get the unqualified exact-values instruction. - `.claude/skills/write-docs/SKILL.md`: workflow step 1 marks copied identifiers as verification inputs with a forward link; citation-only "Evidence versus claim" section; matching anti-pattern bullet and a checklist item that defers the stripped-identifier disclosure to the canonical rule. - `.claude/skills/doc-check/SKILL.md`: "Evidence versus claim" check scoped to identifiers the change adds or touches, working from the diff (doc-check does not police the disclosure, which it cannot see); pre-existing violations on untouched pages are informational only. The motivating page (`chat-auto-archive.md`) was fixed separately in #28570 (DOCS-722, merged). Corpus sweep for other violations: DOCS-730. Lint and link coverage for the `.claude` and `docs/.style` trees: DOCS-729. Linear: DOCS-728 https://linear.app/codercom/issue/DOCS-728 <details> <summary>CI note (docs-only PR)</summary> This PR changes only Markdown under `docs/.style/` and `.claude/` (no `site/src` or other product code). - The `ci` workflow's docs-relevant jobs pass on the head commit: `changes`, `gen`, `lint`, `lint-docs`, `fmt`, `offlinedocs`, `required`. Heavy build/test jobs are correctly skipped for a docs-only change. (Run: https://github.com/coder/coder/actions/runs/32986743037) - `Pixel / Review` (frontend visual snapshots) is unrelated to the changed paths and is treated as an unrelated flake. </details> > This PR was created with AI assistance (Coder Agents). |
||
|
|
760fd15e21 |
docs: add detail on testing bedrock provider with curl (#29077)
Adds directions on testing a Bedrock provider through AI Gateway via `curl`. |
||
|
|
7846490770 |
docs: reconcile H1/label mismatches into front-matter titles (Phase 3) (#28036)
## Summary **Batch B of Phase 3** of the H1 → front-matter migration (`DOCS-484`; parent `DOCS-477`), the editorial follow-up to Batch A (#28030). For the **124** hand-authored pages whose leading body H1 differed from the manifest nav label, this promotes the richer body H1 to the front-matter **page title** and drops the duplicate H1, while keeping the short manifest **label** as the sidebar entry. Policy agreed with the docs owner: - Short sidebar labels win. Duplicate sidebar labels are acceptable. - Identical **page titles** across two pages are not. On a collision, rename the non-generated page's title. ## Page-title collisions resolved Promoting the H1 created 4 page-title collisions; each is disambiguated by renaming the non-generated / secondary page (sidebar labels left unchanged): | page | sidebar label | body H1 | → page title | |------|---------------|---------|--------------| | `install/index.md` | Install | Installing Coder | **Install Coder in your infrastructure** | | `install/cli.md` | Coder CLI | Installing Coder | **Install the Coder CLI** | | `ai-gateway/clients/jetbrains.md` | JetBrains | JetBrains IDEs | **JetBrains** | | `workspace-access/web-ides.md` | Web IDEs and Coder Apps | Web IDEs | Web IDEs *(kept — primary user guide)* | | `extending-templates/web-ides.md` | Web IDEs and Coder Apps | Web IDEs | **Web IDEs in templates** | | `workspace-management.md` | Workspace Management | Workspaces | **Manage workspaces** *(vs generated `api/workspaces.md`)* | These titles are the only non-mechanical editorial calls in this PR. ## Deliberately excluded: generated pages `admin/security/audit-logs.md` and `admin/setup/configuration-reference.md` are `make gen` outputs (`auditdocgen` / `configdocgen`) that Phase 2 did **not** update, so a hand-added title would be reverted on the next generation. They're excluded here and need their generators taught to emit front matter first (Phase 2 pattern), tracked as `DOCS-631`. Batch A (#28030) had the same issue for three other generated pages; it has been corrected there too. ## Verification AI was the primary author of this PR (see disclosure below); per the [AI Contribution Guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING) here is the manual verification. - Promote = set front-matter `title` to the body H1 (or the disambiguated title above) and remove that one duplicate H1. No other body prose is reflowed. - Every added front-matter block parses as YAML; all files pass `pnpm check-docs` (markdownlint-cli2 + table formatter): `Summary: 0 error(s)`. - Removing the H1 orphaned one in-page fragment (`[MCP](#mcp)` in `ai-gateway/mcp.md`), now repointed. A cross-file fragment audit into the retitled pages found no real breakage. Anchor-change note Unlike Batch A (title unchanged, a rendered no-op), Batch B changes each page's effective title from the manifest label to the body H1, so the rendered H1 **anchor slug changes**. An audit of cross-file `.md#fragment` links into these pages surfaced no links that break as a result (the only hits were false positives against a still-present `## TLS & Reverse Proxy` heading). Same-file fragments are enforced by markdownlint MD051, which is green. ## Title casing (follow-up, DOCS-742) A follow-up commit puts the promoted titles into sentence case and removes leading gerunds (for example, `Managing workspace schedules` → `Manage workspace schedules`): 57 of the 120 titles changed, the other 63 were already compliant. Proper nouns and branded names (Coder Validated Architecture, JetBrains, File Browser, Dev Containers, Island), acronyms (API, CLI, IDE, MCP, OIDC, URL, UI, CI/CD), the Premium license tier, and maturity labels (Beta, Experimental) are preserved. The four `Nk-users` pages become `Reference architecture: up to N users` (lowercase, matching the CVA landing page's own usage); the CVA landing page keeps its branded title. `pnpm check-docs`: `Summary: 0 error(s)`. Linear: DOCS-484, DOCS-742 > This PR was created with AI assistance (Coder Agents). |
||
|
|
e9946e81c5 |
feat: Add search to AI Gateway SessionTimeline (#28424)
This pull request: - Wires debounced search into AI Gateway session details - Filters prompts, tool calls, inputs, and network destinations - Highlights matches and expands relevant content - Reports matching events and loaded-data limitations Stack details: - #28422 - #28424 (this PR) > Generated by Coder Agents on behalf of @johnstcn --------- Co-authored-by: Sas Swart <sas.swart.cdk@gmail.com> |
||
|
|
486d2faa81 |
refactor: modernize the create user page (#28894)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell. Redesigns the create user flow using the settings page layout and renames it to "New user." The form includes clearer field guidance, explicit authentication-method loading, error, and empty states, updated documentation, and aligned end-to-end selectors. | Old | New | | --- | --- | | <img width="2560" height="2516" alt="02-create-user" src="https://github.com/user-attachments/assets/c79fb42b-3b0f-47fa-b03d-801c81584dba"/> | <img width="2560" height="2748" alt="02-create-user-page" src="https://github.com/user-attachments/assets/2d2dd777-3ae9-444d-9811-082f30eb8387"/> | Depends on #28893. <details> <summary>Stack</summary> 1. #28893 - Edit user page redesign 2. #28894 - Create user page redesign (this PR) </details> |
||
|
|
3b1828db5b |
refactor: modernize the edit user page (#28893)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell. Redesigns the edit user page using the settings page layout, with clearer field guidance, explicit loading and error states, documentation and back links, and access to the shared user administration menu. Successful updates refresh the page heading and query cache without resetting an in-progress form during background refetches. | Old | New | | --- | --- | | <img width="2560" height="1800" alt="03-edit-user-member" src="https://github.com/user-attachments/assets/915434fe-9587-49e9-b962-cc1ebeca3ea4" /> | <img width="2560" height="1800" alt="02-edit-user-page" src="https://github.com/user-attachments/assets/2b188c26-4268-4498-96a0-4fd1825a6a49" /> | | `** didnt exist **` | <img width="2560" height="1800" alt="03-edit-user-page-action-menu" src="https://github.com/user-attachments/assets/1e657626-ab43-4d49-a375-414896728fb9" /> | <details> <summary>Stack</summary> 1. #28893 - Edit user page redesign (this PR) 2. #28894 - Create user page redesign </details> |
||
|
|
ab1959d661 |
chore(docs): update release docs for v2.37.1 (#29076)
Automated docs update for v2.37.1 release. Created by `releasetui`. |
||
|
|
93089d447f |
fix: resolve Bedrock application inference profile ARNs (#28877)
AWS recommends [application inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/cost-mgmt-application-inference-profiles.html) for attributing Bedrock spend to a team or workload, which requires invoking Bedrock with the profile ARN as the `modelId`. AI Gateway used the configured Bedrock model for both the invocation target and model capability detection, and capability detection is substring matching against model IDs. Application inference profile ARNs are opaque, so they matched nothing. Reproduced against a profile wrapping `anthropic.claude-opus-4-8`: the client sent `thinking.type: "adaptive"`, the gateway rewrote it to `enabled` + `budget_tokens` because the ARN did not look like an adaptive-capable model, and Bedrock returned ```text 400 "thinking.type.enabled" is not supported for this model. Use "thinking.type.adaptive" and "output_config.effort" to control thinking behavior. ``` Models that accept both shapes, such as Sonnet 4.6, did not fail but had adaptive thinking silently downgraded. The ARN was also recorded as the interception model, so those requests never matched a price and may appear in the weekly Missing AI Model Prices report. The gateway now resolves application inference profile ARNs through `GetInferenceProfile` and uses the model behind them for capability detection, usage records, pricing, and metrics, while still invoking the profile so AWS records the cost attribution. Resolution runs only for `application-inference-profile` ARNs, so plain model IDs and system-defined inference profile ARNs, which already carry the model ID, cost no AWS call and need no new permission. Deployments that do configure a profile must grant `bedrock:GetInferenceProfile` to the identity the gateway already uses, including any assumed role. Resolution failure fails provider construction, matching how other misconfigured providers behave: the failure is logged and the provider is reported as errored rather than serving requests it would shape incorrectly. ## Concerns **Every provider reload re-resolves every application inference profile.** Any provider create/update/delete publishes on `AIProvidersChangedChannel`, and each subscriber responds by rebuilding its whole snapshot: `Reload` fetches all providers and `BuildProvidersFromProto` constructs every one of them from scratch before `ReplaceProviders` swaps the snapshot in. That rebuild used to be purely local work. This PR makes it hit the network: a Bedrock provider configured with an AIP ARN now performs a synchronous `GetInferenceProfile` call during construction, sequentially, before the snapshot is published. So editing an unrelated OpenAI provider re-resolves every AIP in the deployment. Consequences: - Reload latency grows with the number of AIP-configured providers, bounded by the 30s resolution timeout per provider. - A transient AWS failure during an unrelated provider edit drops the Bedrock provider from the new snapshot until the next reload, surfacing as a 404 for a provider whose configuration never changed. An ARN-keyed resolution cache would remove this: the Bedrock API has no `UpdateInferenceProfile`, so a profile's underlying model is fixed at creation and repointing requires a new ARN, hence a config change and a reload. A process-lifetime cache is therefore sound with no invalidation logic. Left out of this PR to keep it scoped. ## Improvement Options 1. Keep it as is. 2. Add a per-process in-memory cache that maps AIP ARNs to models. 3. Add a database-level cache for AIP-to-model resolution. 4. Move AIP resolution to the per-LLM-request path and cache the result there. My choice would be either 3 or 4. See the relevant P1s: - https://github.com/coder/coder/pull/28877#discussion_r3936255218 - https://github.com/coder/coder/pull/28877#discussion_r3936255211 Closes https://linear.app/codercom/issue/AIGOV-488 Created by Coder Agents on behalf of @evgeniy-scherbina. |
||
|
|
837879c67c |
docs: update cn import guidance (#28945)
> 🤖 This PR was written by Coder Agents on behalf of Jake Howell. Updates the frontend contribution guide to import `cn` directly from the package after #28931 removes the `#/utils/cn` barrel module. Depends on #28931. |
||
|
|
1cd49cc7e4 |
chore(docs): update release docs for v2.34.10 (#28979)
Automated docs update for v2.34.10 release. Created by `releasetui`. |
||
|
|
07f9018c61 |
feat: re-check the app allowlist at OAuth2 code redemption (#28740)
**TL;DR** Second of the PLAT-480 stack. #28237 made the negotiated scope bound the issued token; this PR makes a narrowing of an app's registered scopes apply to codes that were already issued. | PR | What it does | |---|---| | #28237 (merged) | Mints access tokens with the negotiated scope, so a grant for one scope stops behaving as full access, and reports the granted scope per RFC 6749 §5.1. | | **#28740 (this)** | Re-checks the code's scope against the app's registered scopes at redemption, closing the ten minute window in which a narrowing was ignored. | | #28744 | Makes code redemption single-use under concurrency. Carries no scope logic and is independent of this PR. | - #28237 has merged, so this targets main. - No new endpoints and no schema change. --- An authorization code is valid for ten minutes, and its scope is checked against the app's registered scopes exactly once, when the code is issued. A registration narrowed inside that window had the narrowing ignored: the code still redeemed for a token carrying the wider scope. - The token exchange re-checks the code's scope against the registration as it stands at redemption and refuses with `invalid_grant`. RFC 6749 §5.2 reserves `invalid_scope` for the scope the client asked for, and this one comes from the stored grant. - The check is coverage rather than membership, and reuses the comparison the authorize endpoint already runs. That comparison now goes through a new `rbac.FirstScopeNotCovered`, which expands the allowlist once rather than once per granted scope. - Only the client can change its registered `scope`, through RFC 7592; no administrator surface writes the column. The re-check reflects the registration at redemption rather than constraining the client. - Refresh keeps the scope originally granted. That is a product choice, not an RFC requirement: a narrowing applies at the next authorization rather than mid-session, so tightening an app's scopes does not break integrations already running. - Codes issued before migration 000569 carry `coder:all`. For an app registered with a narrower `scope` those are refused at redemption until they expire, at most ten minutes. Stack: #28237 (merged), this PR, #28744. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
68ca033d67 |
fix: deliver the rest of the invalid_request class to the client (#28736)
**TL;DR** Fifth of the stack, split out of #28045. #28450 delivered the errors raised *after* the callback is trusted and left the parameter failures behind. This PR delivers those, and replaces the implicit ordering that decided where an answer went with an explicit classification. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. | | #28178 | The authorize endpoint negotiates the scope against the app's allowlist and persists it on the code. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's callback. | | #28450 | The same delivery for every other error raised once the callback is trusted. | | **#28736 (this)** | The parameter failures #28450 left behind, and the classification that decides where each answer goes. | - Stacked on #28450. Review that first. - Nothing about what a token can do changes here. This is delivery, not enforcement. **Contract change** A rejected parameter now arrives at the app's registered callback with `error=invalid_request`, a description naming every failing field, and the request's `state`. Both verbs. | Verb | Was | |---|---| | GET | static "Invalid Query Parameters" page, 400 | | POST | `WriteOAuth2Error`, 400 | An integrator watching for either now reads the error from its own callback instead. **Two failures still answer on Coder**, because in neither case is the callback trustworthy yet: - A `redirect_uri` that does not parse, or does not exactly match the registration. Redirecting to it would defeat the check that just rejected it. - A `client_id` sent more than once, or naming something other than the app the callback was matched against. Coder cannot tell whose registration it is about to redirect to. An absent query `client_id` is **not** in that group. `httpmw` also reads the POST form body and the §2.3.1 Basic credential, so an absent query parameter still names a client and its failure is deliverable. **Precedence change.** An app whose *registered* callback does not parse, or uses a rejected scheme, now answers 500 even when the request also carries parameter errors; that used to answer 400. Decided before any parameter is read, so the others are never detected. Only reachable for an app row that bypassed registration. `DangerousCallbackSchemeOutranksParseFailure` pins it. **Also in this PR** - **Unrecognized parameters are ignored**, as §3.1 requires, rather than rejected by `ErrorExcessParams`. An OIDC `nonce` or a vendor extension no longer fails the request. Repeats of parameters the endpoint does read are still rejected. - **Every unsupported `response_type` gets one code.** Read as text rather than through the SDK enum, so a value with no Go constant behind it answers `unsupported_response_type` like `token` does, instead of splitting on whether the SDK names it. - **A malformed `resource` answers `invalid_target`** (RFC 8707 §2), but only when nothing else failed. A client retrying on `invalid_target` would otherwise resend a request still broken in a field it never heard about. - **`error_description` is bounded and readable.** Capped at 2048 characters and marked `(truncated)` before the log field or the `Location` header is written. Entries read `field: reason` joined with `; `, not the parser's debug shape, whose details contain commas and cannot be split apart again. - **A repeated `state` is charged to the client, not the callback.** Reading `state` shares a function with the `redirect_uri` match, so it used to fall into that carve-out and answer on Coder. **Where in the OAuth Flow** <details> <summary>Diagram: the three-way dispatch, and what licenses a redirect</summary> ```mermaid flowchart TD NEW["newAuthorizeResponse<br/>parses the registered callback, checks its scheme,<br/>exact-matches any redirect_uri, reads state"] NEW -->|"registration unusable"| C500["500 on Coder<br/>server_error, value logged not echoed"] NEW --> PARSE["extractAuthorizeParams<br/>reads every parameter, collects all failures"] PARSE -->|"no failure"| OK["GET: consent page<br/>POST: authorization code"] PARSE -->|"failure"| KIND{"authorizeFailure.kind()"} KIND -->|"corrupt registration"| C500 KIND -->|"redirect_uri or client_id at fault"| CODER["400 on Coder<br/>RFC 6749 4.1.2.1 carve-out"] KIND -->|"anything else"| CLIENT["302 to the callback<br/>invalid_request or invalid_target, with state"] ``` </details> - Authorize endpoint only, both verbs. Token exchange, refresh, and revocation are untouched, and `ErrorExcessParams` still guards the token endpoint. - `validatedCallbackURL` becomes `authorizeResponse`, built only by `newAuthorizeResponse`, which runs the scheme check and the exact match in that order. Holding one is what licenses a redirect, so the ordering is structural rather than a convention each call site remembers. - The scheme is checked on the *registered* URL, since `p.RedirectURL` returns the client's URI on a mismatch and checking that would blame the app for a request it never made. - `state` moves onto the type, out of the parameter lists of `withQuery`, `errorURL`, `codeURL`, and `redirectAuthorizeError`, so no call site can emit a response the client cannot correlate. - `extractAuthorizeParams` returns one `authorizeFailure` instead of two trailing values, and both handlers dispatch on `kind()` rather than re-deriving precedence from field checks. **What it satisfies** - RFC 6749 §4.1.2.1: a failure that is not a bad redirection URI or client identifier is reported through the redirection URI. That is the whole PR. Its two exceptions "MUST NOT" be redirected to, hence the carve-outs. - RFC 6749 §3.1: unrecognized parameters MUST be ignored, and no parameter may appear more than once. Both now hold here. - RFC 6749 Appendix A: `error_description` is confined to the permitted set, on the decoded value. - RFC 8707 §2: a `resource` that is not an absolute URI without a fragment answers `invalid_target`. - RFC 7636 §4.4.1: a malformed `code_challenge` is rejected at the authorization request rather than deferred to token exchange, where the error would point at the `code_verifier`. - Not yet: CRF-26 (the `server_error` sites) and CRF-13 (fragment delivery), both as in #28450. **Docs and Swagger.** `docs/admin/integrations/oauth2-provider.md` gains entries for the redirected parameter errors, `invalid_target`, and the two failures that stay on Coder. Both authorize verbs document their 400 and 500 responses and stop advertising `response_type=token`, which meant declaring the parameter as a `string`, since `Enums` appends to what swaggo derives from the type. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Fifth of the stack, stacked on #28450. ## Manual Tests Verified by hand against a local dev deployment (`v2.37.0-devel+1145d35a47`, dev Postgres), in addition to the automated suite. The build string was checked first, because `develop.sh` builds from whatever the tree held when it started and every result below would otherwise be describing the wrong binary. Two scenario groups need state the API cannot produce. The scope allowlist is reachable only through dynamic client registration, which was enabled for the run and disabled again at the end. A registered callback that does not parse, or that uses a blocked scheme, is refused at registration, so those rows were planted directly with `psql` on a purpose-built client and restored afterwards. **28 scenarios, all passing.** No correctness or security defect was found in the code this PR changes. Seven observations came out of the run: six are consistency, documentation or diagnosability points, and one is a small defect that predates this PR. <details> <summary><b>Scenario summary, all 28</b></summary> | # | Scenario | Result | |---|----------|--------| | 1 | A well-formed request still succeeds on both verbs, and the consent page renders | Pass | | 2 | A rejected parameter now reaches the client's callback on `POST` | Pass | | 3 | The same on `GET`, and the consent page does not render first | Pass | | 4 | The description names every failing field, joined with `; ` | Pass | | 5 | A mismatched `redirect_uri` is answered on Coder with no `Location` on either verb | Pass | | 6 | An unparseable `redirect_uri` likewise, and the echoed value is HTML escaped | Pass | | 7 | A repeated `client_id` is answered on Coder although the callback was valid | Pass | | 8 | A single query `client_id` cannot disagree with the resolved app over HTTP | Pass | | 9 | A `client_id` supplied only in the `POST` form body is delivered, not withheld | Pass | | 10 | A `{UPPERCASE}` `client_id` is delivered, and also succeeds end to end | Pass | | 11 | A repeated `state` is delivered rather than charged to the redirect carve-out | Pass | | 12 | A registered callback with a blocked scheme answers 500 on both verbs | Pass | | 13 | An unparseable registered callback answers 500, indistinguishably to the caller | Pass | | 14 | Corrupt registration outranks a deliverable failure and both carve-outs | Pass | | 15 | The corrupt value is logged with the app ID and never appears in a response | Pass | | 16 | Restoring the row restores normal behaviour with no restart | Pass | | 17 | Every unsupported `response_type` gets one code; an empty one is `invalid_request` | Pass | | 18 | An unsupported `response_type` is not recast as a missing `code_challenge` | Pass | | 19 | Unrecognized parameters are ignored, including a case-variant `REDIRECT_URI` | Pass | | 20 | A misspelled `redirect_url` is ignored and cannot smuggle a destination | Pass | | 21 | Repeated known parameters are still rejected | Pass | | 22 | `resource` answers `invalid_target` alone and `invalid_request` in company | Pass | | 23 | A fragment in `resource` is rejected | Pass, with one gap | | 24 | A long description is capped at 2048 and marked `(truncated)`, on both verbs | Pass | | 25 | The description is sanitized to the RFC 6749 §4.1.2.1 character set | Pass | | 26 | The registered callback query is retained except the reserved names | Pass | | 27 | Scope rejections still reach the callback, and no consent page renders | Pass | | 28 | Declining consent carries `access_denied` and issues no code | Pass | </details> <details> <summary><b>Observations, all 7</b></summary> | # | Observation | Severity | |---|-------------|----------| | 1 | `invalid_request` is returned in three description shapes: the parser's `Invalid query params: field: reason; ...` aggregate, the PKCE validator's single message, and `scopeFailureResponse`'s. A client cannot parse all three with one rule. | Consistency, reviewer call | | 2 | The phase 2 runbook for #28045 asserts the old `field: x detail: y` message shape, which this PR replaces. That doc needs a one-line update. | Docs follow-up | | 3 | `clientIDInDoubt`'s `default` branch is unreachable over HTTP, because `httpmw` derives `app.ID` from the same query value the parser reads. Defensive rather than dead, but the comment does not say so. | Comment clarity | | 4 | A `POST` supplying `client_id` only in the form body always fails with `client_id ... is required and cannot be empty`, naming a parameter it did supply. `httpmw` reads the body, `RequiredNotEmpty` reads the query. Pre-existing. | Misleading diagnostic | | 5 | A misspelled parameter is invisible from every angle at default verbosity. The client gets a 302 with a code, its redirect is silently replaced by the registered one, and the `ignoring unrecognized authorization parameters` line is `logger.Debug` so it is not emitted. | Diagnosability | | 6 | `resource` sent twice answers `invalid_target` rather than `invalid_request`. RFC 8707 §2 frames `invalid_target` as being about the resource value; a duplicated parameter is a malformed request under RFC 6749 §3.1. | Low, error code choice | | 7 | `resource=https://api.example.com/#` (trailing `#`, empty fragment) is accepted and stored with the `#` intact, so the persisted audience is not textually equal to the fragment-free form. `url.Parse` maps empty and absent fragments both to `Fragment == ""`. Pre-existing, in `tokens.go`. | Defect, low severity | </details> **One note for anyone re-running this.** Every request below depends on `$CHALLENGE` from the most recent `new_pkce` call. Forgetting to call it sends an empty `code_challenge`, which fails with the fixed "is required and cannot be empty" message at 98 characters and looks exactly like a cap or a validator failing to fire. That cost one wrong measurement during this run before the numbers below were taken. <details> <summary><b>Shell helpers used throughout</b></summary> ```bash export BASE_URL=http://localhost:3000 export AUTH_HEADER="Coder-Session-Token: $(cat ./.coderv2/session)" export PGPASSWORD=$(cat ./.coderv2/postgres/password) export PGPORT=$(cat ./.coderv2/postgres/port) pg() { psql -h localhost -p "$PGPORT" -U coder -d coder -tAc "$1"; } plant_callback() { pg "UPDATE oauth2_provider_apps SET callback_url = '$2' WHERE id = '$1';"; } urlenc() { jq -rn --arg v "$1" '$v|@uri'; } # 43 unreserved characters every time. Base64url of the raw 32 bytes. new_pkce() { VERIFIER=$(openssl rand 32 | base64 | tr -d '\n=' | tr '+/' '-_') CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_') STATE=$(openssl rand -hex 16) } authz_url() { local url="$BASE_URL/oauth2/authorize?client_id=$1&response_type=code" url="$url&redirect_uri=$(urlenc "$2")&state=$STATE" url="$url&code_challenge=$CHALLENGE&code_challenge_method=S256" printf '%s' "$url" } # The core assertion of the whole run: what answer, delivered where. answer() { curl -s -o /dev/null -D - -X "$1" "$2" -H "$AUTH_HEADER" | grep -iE '^HTTP/|^location:'; } show_callback() { python3 - "$1" <<'PY' import sys, urllib.parse q = urllib.parse.urlparse(sys.argv[1]).query for k, v in urllib.parse.parse_qsl(q, keep_blank_values=True): print(f"{k} = {v}") PY } ``` Fixtures, all registered through DCR: ```text plat479-plain http://localhost:9876/callback plat479-query http://localhost:9876/callback?tenant=acme&error=stale plat479-corrupt http://localhost:9876/callback (overwritten by psql in 12 to 16) plat479-reserved http://localhost:9876/callback?tenant=acme&code=FAKECODE&error=stale&error_description=oldmsg&state=oldstate&keep=yes plat479-ci http://localhost:9876/callback (scope allowlist coder:workspaces.access) ``` </details> <details> <summary><b>1. Baseline: a well-formed request still succeeds</b></summary> ```bash new_pkce; answer GET "$(authz_url "$APP_ID" http://localhost:9876/callback)" new_pkce; answer POST "$(authz_url "$APP_ID" http://localhost:9876/callback)" ``` ```text === GET === HTTP/1.1 200 OK === POST === HTTP/1.1 302 Found Location: http://localhost:9876/callback?code=coder_dzvaCPf9W1_...&state=e321bd5d5b594a1fae8a2d5da654b84a ``` `GET` carries no `Location` at all, so the consent page really rendered rather than redirecting. The `state` echoed is the one sent. The code persisted as `coder:all`, this app having no allowlist, with `redirect_uri` recorded because the request supplied one. Also driven through a real browser rather than curl, so the consent form's `nosurf` token is the one submitted rather than the session-token header alone. Clicking **Allow** delivered `code` and `state` to the callback. Both request shapes agree on the success case. Not to be misread: `oauth2_provider_app_codes` holds one row after both POSTs, not two. `ProcessAuthorize` opens its transaction with `DeleteOAuth2ProviderAppCodesByAppAndUserID`, so a row count is not a count of successful authorizations. That predates this PR. </details> <details> <summary><b>2 to 4. A rejected parameter now reaches the client's callback</b></summary> ```bash new_pkce BAD="$BASE_URL/oauth2/authorize?client_id=$APP_ID&response_type=code" BAD="$BAD&redirect_uri=$(urlenc http://localhost:9876/callback)&state=$STATE" BAD="$BAD&code_challenge=short&code_challenge_method=S256" answer POST "$BAD" answer GET "$BAD" ``` ```text HTTP/1.1 302 Found Location: http://localhost:9876/callback?error=invalid_request&error_description=Invalid+query+params%3A+code_challenge%3A+must+be+43+to+128+characters+from+the+unreserved+character+set+%5BA-Za-z0-9-._~%5D&state=e89f4d98d4c8c347e5ae25175748b731 ``` Identical on both verbs. Decoded: ```text error = invalid_request error_description = Invalid query params: code_challenge: must be 43 to 128 characters from the unreserved character set [A-Za-z0-9-._~] state = e89f4d98d4c8c347e5ae25175748b731 ``` The `GET` body confirms no page was rendered, against the baseline: | Request | Body size | Occurrences of "Allow" | |---|---|---| | Malformed `code_challenge` | 263 bytes | 0 | | Well formed (scenario 1) | 4928 bytes | 2 | 263 bytes is Go's redirect stub. There is no consent form in it, so there is no Allow button to press for a request the server has already refused. Multiple failures are reported together (scenario 4): ```text error_description = Invalid query params: code_challenge: must be 43 to 128 characters from the unreserved character set [A-Za-z0-9-._~]; resource: must be an absolute URI without fragment ``` The separator is `; `, and no entry uses the older `field: x detail: y` shape. The code is `invalid_request` rather than `invalid_target` even though `resource` is one of the two failures, which is the scenario 22 guard firing. The same request also carried `code_challenge_method=plain`, which is invalid and is *not* mentioned, because the method is validated after `extractAuthorizeParams` returns and a parse failure short-circuits first. Sent alone it is rejected as `code_challenge_method 'plain' is not supported; use 'S256'`, with no `Invalid query params: ` prefix. That difference is observation 1. </details> <details> <summary><b>5 and 6. The redirect_uri carve-out keeps the answer here</b></summary> ```bash new_pkce EVIL="$BASE_URL/oauth2/authorize?client_id=$APP_ID&response_type=code" EVIL="$EVIL&redirect_uri=$(urlenc http://evil.example/steal)&state=$STATE" EVIL="$EVIL&code_challenge=$CHALLENGE&code_challenge_method=S256" answer POST "$EVIL"; answer GET "$EVIL" ``` ```text HTTP/1.1 400 Bad Request HTTP/1.1 400 Bad Request ``` **The absence in that output is the assertion**: no `Location` on either verb, so nothing redirects to `evil.example`. Stronger, `evil.example` appears zero times in either full response, headers and body together, so the attacker-supplied host is not reflected into the page either. ```json {"error":"invalid_request","error_description":"Invalid query params: redirect_uri: Query param \"redirect_uri\" must exactly match http://localhost:9876/callback"} ``` The `GET` page names the *registered* callback as the value the parameter had to match, which is the app's own configuration and safe to display. An unparseable `redirect_uri` reaches the same outcome by a different route, having never parsed at all: ```json {"error":"invalid_request","error_description":"Invalid query params: redirect_uri: Query param \"redirect_uri\" must be a valid url: parse \"http://%zz\": invalid URL escape \"%zz\""} ``` That message echoes the caller's value, unlike the mismatch case, so the `GET` path was probed with markup in it: ```text input: http://%zz"><img src=x onerror=BAD> page: ...must be a valid url: parse "http://%zz\"><img src=x onerror=BAD>"... literal `<img` in body: 0 entity encoded `<img`: 1 ``` Escaped correctly by the template layer. Recorded as a negative result so a future change to the error page has something to regress against. One note for the docs: this detail contains colons, so a client splitting `field: reason` entries must split each on its **first** colon only. </details> <details> <summary><b>7 to 10. The client_id carve-out, and its negatives</b></summary> A repeated `client_id` in an otherwise perfect request: ```text HTTP/1.1 400 Bad Request (both verbs, no Location) {"error":"invalid_request","error_description":"Invalid query params: client_id: Query param \"client_id\" provided more than once, found 2 times. Only provide 1 instance of this query param."} ``` This is the one carve-out not implied by the response's shape. The `redirect_uri` matched the registration, so `canRedirect()` was true and there *was* somewhere to send the answer; it was withheld because `extractAuthorizeParams` assigns `failure.redirect` only when `clientIDInDoubt` is false. **The `default` branch of that function is unreachable over HTTP** (observation 3). `httpmw` resolves the app from `r.URL.Query().Get("client_id")`, so `app.ID` and the parsed value derive from the same string and cannot disagree. Three experiments: ```text one query client_id, bad challenge -> 302 delivered two DIFFERENT client_id values -> 400, caught by the repeated branch query names app A, form body names app B -> 302 to app A; the body is ignored ``` The negatives matter as much as the positives. An identifier absent from the query but present in the `POST` form body is **delivered**, correctly: ```text HTTP/1.1 302 Found Location: ...error=invalid_request&error_description=Invalid+query+params%3A+client_id%3A+...is+required+and+cannot+be+empty%3B+code_challenge%3A+... ``` That is observation 4: the description says `client_id` is required for a request that supplied it. With everything else valid the same shape still fails, while the identical request carrying `client_id` in the query succeeds with a code. `RequiredNotEmpty` reads the query; `httpmw` reads the body. Pre-existing, and arguably the parser is the layer in the right, since RFC 6749 §4.1.1 puts authorization parameters in the query string and §3.2.1 is the endpoint that uses a form body. A braced upper-case UUID is delivered, and succeeds end to end: ```text {UPPERCASE} client_id, bad challenge -> 302, description names ONLY code_challenge {UPPERCASE} client_id, all valid -> 302 with a real code GET, all valid -> 200, consent page, heading resolves to the app's real name ``` `uuid.Parse` accepts that spelling and `httpmw` resolved through it, so a string comparison here would withhold an answer the client is entitled to, for no reason it could diagnose. </details> <details> <summary><b>11. A repeated state is delivered, not withheld</b></summary> ```text HTTP/1.1 302 Found (both verbs) error = invalid_request error_description = Invalid query params: state: Query param 'state' provided more than once, found 2 times. Only provide 1 instance of this query param. ``` Reading `state` happens inside `newAuthorizeResponse`, the same function that runs the `redirect_uri` match. A count of errors across those two lines would charge this to the redirect carve-out and answer 400. It answered 302, so the field-specific test is doing the work. The asymmetry with scenario 7 is deliberate: a repeated `client_id` leaves the server unsure whose callback it holds, a repeated `state` leaves the callback fully settled. The response carries **no `state`**, since `parseSingle` collapsed the repeat to the empty string and `withQuery` only sets it when non-empty. Unavoidable rather than wrong: picking one of two values could satisfy a CSRF check the client meant to be strict. </details> <details> <summary><b>12 to 16. A corrupt registration outranks everything</b></summary> DCR refuses both planted values, which is why `psql` is needed and why 500 is the right answer: a stored one is not something a client did. ```json {"error":"invalid_client_metadata","error_description":"invalid redirect_uris: redirect URI at index 0: redirect URI uses dangerous scheme javascript which is not allowed"} {"error":"invalid_client_metadata","error_description":"invalid redirect_uris: redirect URI at index 0 is not a valid URL: parse \"http://%zz\": invalid URL escape \"%zz\""} ``` ```bash plant_callback "$APP_CORRUPT_ID" 'javascript:alert(1)' new_pkce CORRUPT="$BASE_URL/oauth2/authorize?client_id=$APP_CORRUPT_ID&response_type=code&state=$STATE" CORRUPT="$CORRUPT&code_challenge=$CHALLENGE&code_challenge_method=S256" answer POST "$CORRUPT"; answer GET "$CORRUPT" ``` ```text HTTP/1.1 500 Internal Server Error {"error":"server_error","error_description":"The application's registered callback URL is not usable"} GET: HTTP/1.1 500, page reads "500 - Invalid Callback URL", 3346 bytes, 0 Allow buttons ``` The unparseable callback is **indistinguishable to the caller**: same description, and a `GET` page of exactly 3346 bytes, matching byte for byte. Two different defects in stored state, one answer. Correct, since neither is actionable by the client. Note the request carried no `redirect_uri` of its own and still failed, because the scheme is checked on the *registered* URL before the client's value is consulted. Precedence was tested against all three competitors, not one: | Also wrong in the request | Would answer alone | Actually answered | |---|---|---| | `code_challenge=short` | 302 to the callback | **500** | | `client_id` repeated | 400 kept here | **500** | | `redirect_uri` mismatched | 400 kept here | **500** | Reading the source, this is stronger than precedence. `newAuthorizeResponse` runs at `authorize.go:250`, before any of `client_id`, `code_challenge`, `scope` or `resource` is read, and the early return discards whatever `p.Errors` already held. In rows two and three those failures are never detected at all, so `kind()` ranking `failureCorruptRegistration` first is belt and braces for a failure constructed some other way. **The value is logged and never echoed.** A distinctive marker was planted and five requests fired: ```text [erro] coderd: oauth2 app has an unusable registered callback URL request_id=01ca4796-c743-4923-a06b-afc1f3decc95 app_id=12f9ca3b-7a2c-4c54-8ed7-723698c62bd1 callback_url="javascript:alert(\"plat479-6d-marker\")" error= redirect URI uses dangerous scheme javascript which is not allowed: codersdk/oauth2_validation.go:116 ``` Five requests, five lines, in request order. Occurrences of the marker in the POST body, the rendered GET page, and the response headers: **0, 0, 0**. The `request_id` joins that line to the request log entry whose `response_body` field holds the vague message, so the server's own record confirms what it sent for the same request rather than a replay. The log is also where the two causes diverge, naming `validateScheme` and its source line, which the response cannot do. Restoring the row restores normal behaviour immediately, with no restart: ```text POST -> 302 with a code GET -> 200 consent page ``` That is a control rather than housekeeping: it rules out the app having been poisoned lastingly, and rules out a cached parse outliving the `UPDATE`. </details> <details> <summary><b>17 and 18. Every unsupported response_type gets one code</b></summary> | `response_type` sent | `error` | `error_description` | |---|---|---| | `token` | `unsupported_response_type` | Only response_type=code is supported | | `banana` | `unsupported_response_type` | Only response_type=code is supported | | `code token` | `unsupported_response_type` | Only response_type=code is supported | | `CODE` | `unsupported_response_type` | Only response_type=code is supported | | `code_extra` | `unsupported_response_type` | Only response_type=code is supported | | empty string | `invalid_request` | Invalid query params: response_type: Query param 'response_type' is required and cannot be empty | `token` has a Go constant behind it and `banana` does not, so their agreement is what reading the value as text bought. Three rows are more interesting than `banana`: `code token` is a legal RFC 6749 §3.1.1 space-delimited list used by OIDC's hybrid flow, `CODE` confirms the comparison is case sensitive, and `code_extra` confirms it is equality rather than a prefix match. The empty string is correctly the exception. A valueless parameter is *missing*, not unsupported, and RFC 6749 §3.1 requires it be treated as omitted. **The error is in the query, not the fragment.** `response_type=token` is the implicit grant's own value, so a fragment would be arguable, but this deployment advertises `"response_types_supported":["code"]` alone, and a fragment is never sent to the server, so it would be unreadable to the client's backend. PKCE is not recast, which the controls show: | `response_type`, no `code_challenge` sent | `error` | |---|---| | `token` | `unsupported_response_type`, zero mentions of `code_challenge` | | `banana` | `unsupported_response_type`, zero mentions of `code_challenge` | | `code` | `invalid_request`, naming `code_challenge` | Without the `if params.responseType == responseTypeCode` guard, a client sending `token` would be told its `code_challenge` was missing, add one, resend, and be told the same thing again. </details> <details> <summary><b>19 to 21. Unrecognized parameters ignored, repeats still rejected</b></summary> Eight unknown parameters, each on an otherwise valid request, every one issuing a code: | Unknown parameter | Result | |---|---| | `nonce`, `prompt`, `login_hint`, `acr_values`, `max_age`, `ui_locales` | code issued | | `code_challenge_methods=S256` | code issued | | `REDIRECT_URI=http://evil.example/steal` | code issued, **to the registered callback** | Five of those are OpenID Connect Core parameters, so an OIDC client pointed here degrades to plain OAuth2 rather than failing. The ignored parameters are **dropped, not forwarded**: the callback receives only `code` and `state`. The last two rows are the ones with teeth. Query parameter names are case sensitive, so `REDIRECT_URI` must be ignored, and a misspelled `redirect_url` likewise: ```text case variant alongside a valid redirect_uri : Location host localhost:9876 case variant as the only redirect parameter : Location host localhost:9876 redirect_url typo, no valid redirect_uri : Location host localhost:9876, code issued evil.example occurrences in any Location : 0 ``` The consent page renders for the typo case too, and even its cancel link targets the registered callback. A parser matching names case-insensitively would have redirected to `evil.example` with a valid code attached. **Observation 5.** The `ignoring unrecognized authorization parameters` line was never emitted. Three requests carrying a distinctive marker produced no new server output at all, because the call is `logger.Debug` (`authorize.go:307`) and the deployment runs with `verbose: null`. The behaviour is correct and required by RFC 6749 §3.1, but at default verbosity the misspelling is invisible from every angle: the client sees a 302 with a code, its redirect is silently replaced, and nothing is logged. The comment claiming the typo "surfaces here" is optimistic. Repeats of known parameters are still rejected, which the replacement of `ErrorExcessParams` had to leave alone: | Repeated parameter | HTTP | `error` | Answered at | |---|---|---|---| | `code_challenge` | 302 | `invalid_request`, two entries one field | client callback | | `code_challenge_method` | 302 | `invalid_request` | client callback | | `response_type` | 302 | `invalid_request` | client callback | | `redirect_uri` | 400 | withheld | **Coder** | | `scope` | 302 | `invalid_request` | client callback | | `resource` | 302 | `invalid_target` | client callback | `redirect_uri` being withheld confirms the carve-out keys on the field name rather than the kind of mistake. `code_challenge` collects two entries for one mistake, because `parseSingle` collapses the value to empty and the PKCE block then reports it missing. The `resource` row is observation 6. </details> <details> <summary><b>22 and 23. resource, its own code, and the fragment rule</b></summary> Both sides of the rule, since a check enforced too broadly would reject a valid URN: | `resource` sent | `error` | Stored `resource_uri` | |---|---|---| | `not a uri` | `invalid_target` | not stored | | `/api` relative | `invalid_target` | not stored | | `https://api.example.com` | none, code issued | as sent | | `https://api.example.com/v1?q=1` | none, code issued | as sent, query is not a fragment | | `urn:example:resource` | none, code issued | as sent | | empty string | none, code issued | `NULL`, same as omitted | `invalid_target` applies only when `resource` is the sole failure. Add any second failure in any other field and the code becomes `invalid_request` naming both, which is the retry-loop guard: ```text resource + bad code_challenge -> invalid_request, both named resource + repeated scope -> invalid_request, both named resource + repeated state -> invalid_request, both named resource alone (control) -> invalid_target ``` Fragments are rejected in all three placements, with or without a path: ```text https://api.example.com/#x -> invalid_target https://api.example.com#x -> invalid_target https://api.example.com/v1#frag -> invalid_target https://api.example.com/# -> code issued, stored as https://api.example.com/# ``` **The last row is observation 7, and it predates this PR.** Go cannot represent the distinction: ```text https://a.example.com/ Fragment="" String()="https://a.example.com/" https://a.example.com/# Fragment="" String()="https://a.example.com/" https://a.example.com/#x Fragment="x" String()="https://a.example.com/#x" ``` `url.Parse` collapses "no fragment" and "empty fragment", so `if u.Fragment != ""` in `validateResourceParameter` (`coderd/oauth2provider/tokens.go:591`) cannot see a trailing `#`. RFC 3986 §3.5 permits a zero-length fragment, which RFC 8707 §2's "MUST NOT include a fragment component" reads as forbidding. Validation parses the value but persistence stores the raw string, so the `#` reaches `resource_uri` and the stored audience is not textually equal to the fragment-free form. A client appending a harmless-looking `#` would get a token bound to an audience nothing matches. The authorize-side call to `validateResourceParameter` is context in this diff rather than an added line; this PR added the `invalid_target` code for the failure. </details> <details> <summary><b>24 and 25. The description cap and character set</b></summary> The obvious probe does not exercise the cap: a 4000-character `code_challenge` produces a 116-character description, because that message is fixed text and never quotes the offending value. The descriptions that echo caller input come from a validator's own error. | Request | `error` | Description length | Truncated | `Location` length | |---|---|---|---|---| | `code_challenge_method` = 4000 chars | `invalid_request` | 2060 | **yes** | 2176 | | `scope` = 4000 chars | `invalid_scope` | 2060 | **yes** | 2174 | | `code_challenge_method` = 2000 chars | `invalid_request` | 2035 | no | 2147 | | `code_challenge` = 4000 chars | `invalid_request` | 116 | no | 234 | 2060 is exactly `maxErrorDescription` plus `" (truncated)"`. Row three is the boundary control, so the cap fires on length rather than on the presence of echoed input. Measured from the `Location` header rather than a log line, since the stated reason for the cap is that the header must survive intermediary proxies; the longest observed was 2176 bytes. Both verbs agree, the cap living in the shared `redirectAuthorizeError`: ```text GET, long method : desc_len=2060 truncated=True GET, long scope : desc_len=2060 truncated=True ``` The character set is enforced independently, later, in `errorURL`: ```text input: pl"ain\back<newline>tab<tab>end~unicode description: unsupported code_challenge_method: pl'ainback tab end~ nicode chars outside the RFC 6749 §4.1.2.1 set: [] ``` `"` becomes `'`, `\` is dropped so it cannot escape the rewritten quote, and anything below 0x20 or above 0x7E becomes a space. Checked programmatically rather than by eye. The RFC sets no length limit, so the 2048 cap is policy; the character set is conformance. </details> <details> <summary><b>26. The registered callback query, retained except reserved names</b></summary> `plat479-reserved` registers a callback carrying all four reserved names plus two ordinary ones, and DCR stores it unchanged: ```text http://localhost:9876/callback?tenant=acme&code=FAKECODE&error=stale&error_description=oldmsg&state=oldstate&keep=yes ``` Success response, no `redirect_uri` sent: ```text code = coder_WXwBpvYR5u_... keep = yes state = 516abeea9976119eb33ddc10f0ca04ed tenant = acme ``` Failure response, same app: ```text error = invalid_request error_description = Invalid query params: code_challenge: must be 43 to 128 characters... keep = yes state = 3a17bdd75dfcf740bda36124cd161fb7 tenant = acme ``` Stale registered values in either response: `FAKECODE` 0, `stale` 0, `oldmsg` 0, `oldstate` 0. Without the deletion step a registered `error=stale` would ride out on the **success** response, and a client reading `error` before `code`, the conventional order, would discard a valid authorization code. `FAKECODE` is the mirror image on a failure response. The cancel link obeys the same rule, being built by the same `withQuery` path: ```text http://localhost:9876/callback?error=access_denied&error_description=The+resource+owner...&keep=yes&state=e15b5f0f...&tenant=acme ``` RFC 6749 §3.1.2 requires the registered query be retained when adding parameters, which is the `tenant` and `keep` half. It does not say what to do when the registered query collides with the response parameters §4.1.2 adds, so dropping the registered copies is the resolution that keeps the client's read unambiguous. </details> <details> <summary><b>27 and 28. Scope rejections, and declining consent</b></summary> `plat479-ci` carries the allowlist `coder:workspaces.access`. ```text scope=template:update (outside) -> error = invalid_scope 'template:update': scope requests permissions beyond this app's allowed scopes GET, same request -> 302, 225 bytes, 0 Allow buttons, no consent page scope=workspace:ssh (covered) -> code issued, persisted scope workspace:ssh GET, same request -> 200, 5182 bytes, consent page naming the scope ``` `workspace:ssh` is granted although the allowlist names the composite rather than that scope, which is the coverage-not-spelling rule from #28045. This run only checks that the changes here left it delivering the same answers. The consent page for a narrow scope reads differently from the unrestricted one: "to access your **admin** account with these permissions?", the scope as `<li role="listitem">workspace:ssh`, and the caution "These are technical permission names. Grant them only to an application you trust." The scope description shape differs from the parser's, coming from `scopeFailureResponse` rather than the field join, which is the third producer behind observation 1. Declining consent, clicked in a real browser: ```text error = access_denied error_description = The resource owner or authorization server denied the request state = a8bd538b365b61f54586892c73968b80 ``` The page carries exactly one `href` and it is the cancel link. The `state` matches, there is no `code`, and the code count for the app is unchanged, the link being a plain `GET` to the client's callback that never reaches `ProcessAuthorize`. The description is RFC 6749 §4.1.2.1's own definition of `access_denied`, word for word. That shared construction is what makes the `#nosec G203` annotation on `CancelURI` sound: the URL is injected as a trusted `htmltemplate.URL`, safe only because `newAuthorizeResponse` validated the registered scheme before the response object could exist. Scenario 12 is the other half, an app with a rejected scheme never reaching this page at all. </details> <details> <summary><b>Where the consent page renders, across every GET case</b></summary> Only `GET` can render anything, and body size identifies which of four renderers ran, so this is the table to check when a status code alone looks right. | Case | Status | Body bytes | Allow buttons | Rendered | |---|---|---|---|---| | well formed | 200 | 4928 | 1 | **consent page** | | bad `code_challenge` | 302 | 263 | 0 | redirect stub | | two bad fields | 302 | 319 | 0 | redirect stub | | mismatched `redirect_uri` | 400 | 3814 | 0 | 400 error page | | unparseable `redirect_uri` | 400 | 3846 | 0 | 400 error page | | repeated `client_id` | 400 | 3846 | 0 | 400 error page | | `client_id` in form body only | 400 | 77 | 0 | `httpmw` JSON, unstyled | | `{UPPERCASE}` `client_id` | 200 | 4940 | 1 | **consent page** | | repeated `state` | 302 | 239 | 0 | redirect stub | | corrupt callback, blocked scheme | 500 | 3346 | 0 | 500 error page | | corrupt callback, unparseable | 500 | 3346 | 0 | 500 error page | | `response_type=token` | 302 | 187 | 0 | redirect stub | | `banana` / `code token` / `CODE` | 302 | 187 | 0 | redirect stub | | empty `response_type` | 302 | 243 | 0 | redirect stub | | `token`, no PKCE | 302 | 187 | 0 | redirect stub | | `code`, no PKCE | 302 | 245 | 0 | redirect stub | | unknown params, valid request | 200 | 4932 | 1 | **consent page** | | `redirect_url` typo, valid request | 200 | 4932 | 1 | **consent page** | | `resource` malformed | 302 | 214 | 0 | redirect stub | | `resource` valid absolute URI | 200 | 4932 | 1 | **consent page** | | `resource=.../#` empty fragment | 200 | 4932 | 1 | **consent page**, observation 7 | | reserved params in registered callback | 200 | 4973 | 1 | **consent page** | | `scope` outside allowlist | 302 | 225 | 0 | redirect stub | | `scope` covered by allowlist | 200 | 5182 | 1 | **consent page** | The invariant: the page renders if and only if `extractAuthorizeParams` returned no failure, so no input asks the owner to approve a request the server has already refused. The `evil.example` rows are worth reading carefully rather than alarming: RFC 6749 §3.1 requires a case variant and a typo to be ignored, so from the server's view nothing was wrong with either request, and both cancel links target the registered callback. About 4930 bytes is the consent page, about 3800 the 400 page, 3346 the 500 page, 77 the unstyled `httpmw` JSON, and low hundreds is Go's redirect stub, whose length tracks the `Location` it embeds. Every `unsupported_response_type` answer is exactly 187 bytes because they share one description. Small variations within a renderer are expected: the consent page moves 4928 to 4940 with a fresh CSRF token and the app name. As a regression signal, body size is more sensitive than the status line. A change that rendered a page alongside a redirect would still report 302, but the stub would come back at thousands of bytes rather than hundreds. </details> <details> <summary><b>Cleanup</b></summary> ```bash for id in $(pg "SELECT id FROM oauth2_provider_apps WHERE name LIKE 'plat479%';"); do curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$id" -H "$AUTH_HEADER" \ -o /dev/null -w "$id -> %{http_code}\n" done pg "SELECT count(*) FROM oauth2_provider_apps WHERE name LIKE 'plat479%';" ./scripts/coder-dev.sh oauth2-provider dcr disable ``` All planted callback rows were restored before deletion, so no fixture was left holding a value DCR would refuse. </details> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
eb9fe95308 | docs(docs/ai-coder/agent-relay): update Cursor BYOM reference to Self-Hosted Machines (#28934) | ||
|
|
e035967ef1 |
feat: mint access tokens with the negotiated scope (#28237)
**TL;DR** First of PLAT-480, continuing the merged PLAT-479 stack. #28178 decided what the scope is and #28179 reported it; this PR is the one that makes it bind. Until now the scope negotiated at `/oauth2/authorize` was recorded on the grant but never reached the token: every OAuth2 access key was minted with `coder:all`, so a client that asked for `coder:workspaces.access` still got full API access. | PR | What it does | |---|---| | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. Merged. | | #28178 | The authorize endpoint checks the request against the scope catalog, grants it only if the app's filtered allowlist covers it, and persists the result on the code. Merged. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's own callback per RFC 6749 §4.1.2.1. Merged. | | **#28237 (this)** | The exchange mints the API key with the stored scope, and the token response states what was granted. | | #28740 | Re-checks the app allowlist at redemption, for a code whose app was narrowed after the code was issued. | | #28751 | Lets a refresh narrow the granted scope, which is the `scope` request parameter this PR still ignores. | - #28179 has merged, so this diff is against main and reviews on its own. - **This is the first PR in the stack where a token's authority actually changes.** Everything before it recorded and reported. That is the blast radius worth reviewing: a grant that negotiated a narrow scope now gets a key that is genuinely narrower, and anything that was quietly relying on `coder:all` will start seeing 403. - Grants that predate the scope columns carry what migration 000569 backfilled, `coder:all`, so they refresh unrestricted and reach what they reached before. Pinned by `BackfilledScopeRefreshesUnrestricted`, seeded the way the migration leaves a row rather than exchanged. - The actor that writes the key stays `rbac.ScopeAll`. Narrowing it to the granted scope would deny `api_key:create` and fail the exchange. The bound lives on `api_keys.scopes`, which dbauthz reads on every request, not on the actor doing the insert. **Where in the flow** <details> <summary>Diagram: where the stored scope turns into a bound on the token</summary> ```mermaid flowchart TD AZ["GET or POST /oauth2/authorize<br/>negotiates the scope and persists it on the code<br/>PR 28178, merged"] AZ --> TK["POST /oauth2/tokens"] TK --> GT{"grant_type"} GT -->|authorization_code| S1["scope read from codes.scope"] GT -->|refresh_token| S2["scope read from tokens.scope<br/>req.Scope is parsed and ignored, PR 28751"] S1 --> CV["scopeStringToAPIKeyScopes, this PR<br/>every name must be in the api_key_scope enum<br/>an empty list is an error, not coder:all"] S2 --> CV CV -->|"unknown name, or empty"| ERR["400 invalid_grant, this PR<br/>error_description names the offending value"] CV -->|mintable| GEN["apikey.Generate with Scopes, this PR<br/>was: no Scopes, so every key defaulted to coder:all"] GEN --> KEY["api_keys.scopes<br/>read by dbauthz on every later request:<br/>this is where the grant becomes a bound"] GEN --> ROW["the new tokens row carries the same scope,<br/>so the next refresh reads back the same grant"] KEY --> RESP["200 with scope in the token response, this PR<br/>RFC 6749 5.1, OAuth 2.1 1.4.1"] ROW --> RESP ``` </details> - Token endpoint only, both grants. Authorize is untouched apart from two comments that said the scope was not yet enforced. - `scopeStringToAPIKeyScopes` turns the stored scope string into `database.APIKeyScopes` for `apikey.Generate`. Names are checked there rather than inside `apikey.Generate`, whose error would surface as a 500 rather than an OAuth2 error. - An empty list is an error, not an unrestricted key. `apikey.Generate` defaults an empty scope list to `coder:all`, so an empty stored scope would silently widen the grant instead of failing it. The same reasoning is why the `expandRBACScope` comment in `modelmethods.go` was stale: that function already errored on an empty list while its comment still promised `rbac.ScopeAll`. - A stored scope outside the `api_key_scope` enum answers 400 `invalid_grant` rather than 500, with the offending name in `error_description`. Not `invalid_scope`: RFC 6749 §5.2 and OAuth 2.1 §3.2.4 both scope that code to what the client requested, and this value is server state the client cannot change by asking differently. The grant is what is unusable, and re-authorizing is the only way out. - Refresh copies the presented token's scope onto both the new API key and the rotated refresh row. `req.Scope` is parsed but ignored; #28751 is where it starts being honoured. - The swagger annotation moves from `oauth2.Token` to `codersdk.OAuth2TokenResponse`, because `oauth2.Token` has no `scope` field to document. - `EveryCatalogNameMintable` pins the catalog against the `api_key_scope` enum. The two are maintained separately, and a name negotiable at authorization but unmintable at exchange would leave a client holding a code it can never redeem. **What it satisfies** Checked against both RFC 6749 and the OAuth 2.1 draft (draft-ietf-oauth-v2-1-15). The 2.1 draft moves the scope-reporting rule from RFC 6749 §5.1 into §1.4.1 and grades it in §3.2.3, but the requirement is the same one. - RFC 6749 §5.1, OAuth 2.1 §1.4.1 — "If the issued access token scope is different from the one requested by the client, the authorization server MUST include the `scope` response parameter in the token response". OAuth 2.1 §3.2.3 grades `scope` as "RECOMMENDED, if identical to the scope requested by the client; otherwise, REQUIRED". Both grants set it unconditionally, which covers both grades. Without it, a client whose request was narrowed against the app's allowlist, or defaulted because it requested nothing, first learns its bounds from an unexplained 403. Pinned by `IssuedTokenBoundsTheAPI`, which requests no scope and asserts the response names what it got. - OAuth 2.1 §1.4.1 — "The authorization server MAY fully or partially ignore the scope requested by the client, based on the authorization server policy or the resource owner's instructions." This is what licenses ignoring `scope` on a refresh, and the licence is conditional on reporting the actual grant. Before this PR the exchange both ignored the request and said nothing, which is the half that was not defensible. - OAuth 2.1 §4.3.1, RFC 6749 §6 — the refresh `scope` parameter is OPTIONAL and "if omitted is treated as equal to the scope originally granted by the resource owner". Exactly what `refreshTokenGrant` does with `dbToken.Scope`. - OAuth 2.1 §4.3.3 — "If a new refresh token is issued, the refresh token scope MUST be identical to that of the refresh token included by the client in the request." Rotation copies `dbToken.Scope` onto the new refresh row. - OAuth 2.1 §3.2.3 — "If refresh tokens are issued, those refresh tokens MUST be bound to the scope and resource servers as consented by the resource owner. This is to prevent privilege escalation by the legitimate client". The refresh row has carried the negotiated scope since #28178; this PR is what makes the access token minted from it carry the same bound. Pinned by `RefreshDoesNotWidenTheScope`. - OAuth 2.1 §1.4.1 — a client that omits `scope` must be met with "a pre-defined default value or fail the request indicating an invalid scope", and the server "SHOULD document its scope requirements and default value". #28178 chose the default; `scopes_supported` and the integration guide document it. Unchanged here, but it is why `IssuedTokenBoundsTheAPI` can request nothing and still receive a bounded token. - Not yet: OAuth 2.1 §4.3.1 also says "The requested scope MUST NOT include any scope not originally granted by the resource owner." A refresh naming a narrower scope is ignored rather than honoured, and one naming a wider scope is ignored rather than rejected with `invalid_scope` (§3.2.4, "exceeds the scope granted by the resource owner"). Neither case widens a token, so there is no escalation, and §1.4.1's MAY plus the `scope` response parameter keep the client correctly informed in the meantime. #28751 is where narrowing lands. Documented under Limitations until then. --- First of three, [PLAT-480](https://linear.app/codercom/issue/PLAT-480). Depends on #28179, which has merged, so this reviews against main. #28178 decided the scope and #28179 reported it. This PR is the one that makes a token feel it. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
54e21f29a1 |
fix: deliver four more authorize errors to the client (#28450)
**TL;DR** Fourth of the stack, split out of #28045. #28179 sent `invalid_scope` to the client's own callback; this PR sends the rest of the errors raised after the callback has been verified, behind one URL builder they all now share. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. | | #28178 | The authorize endpoint negotiates the scope against the app's allowlist and persists it on the code. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's callback per RFC 6749 §4.1.2.1. | | **#28450 (this)** | The same delivery for every other error raised once the callback is trusted. | - #28179 has merged, so this diff is against main and reviews on its own. - Nothing about what a token can do changes here. This is delivery, not enforcement. **Contract change** Four failures now arrive at the app's registered callback instead of terminating on Coder, so an integrator with error handling on its callback starts seeing codes it never received. | Verb | Condition | Error code | Was | |------|-----------|------------|-----| | GET | `response_type != code` | `unsupported_response_type` | static "Unsupported Response Type" page, 400 | | POST | `response_type != code` | `unsupported_response_type` | `WriteOAuth2Error`, 400 | | POST | `code_challenge_method=plain` | `invalid_request` | `WriteOAuth2Error`, 400 | | GET | `code_challenge_method=plain` | `invalid_request` | consent page, 200, refused after Allow | The GET static error page loses its only caller. The last row is what review found: the method was checked on POST only, so the user approved a request that could never succeed. **Where in the OAuth Flow** <details> <summary>Diagram: where these errors are raised, and what licenses the redirect</summary> ```mermaid flowchart TD EX["GET or POST /oauth2/authorize<br/>extractAuthorizeParams exact-matches redirect_uri<br/>against the app's registered callback"] EX -->|"no match, rejected scheme, unparsable,<br/>other param failures"| CODER["Answers on Coder<br/>RFC 6749 3.1.2.4: MUST NOT redirect"] EX -->|"matched: a validatedCallbackURL,<br/>which is what licenses a redirect"| RT{"response_type == code?"} RT -->|no| E1["unsupported_response_type (this PR)"] RT -->|yes| PK{"code_challenge_method S256 or omitted?"} PK -->|no| E2["invalid_request (this PR, and newly checked on GET)"] PK -->|yes| SC{"scope negotiable?"} SC -->|no| E3["invalid_scope (previous PR)"] SC -->|yes| OK["GET: consent page, cancel link is access_denied<br/>POST: authorization code"] E1 --> OUT E2 --> OUT E3 --> OUT OK --> OUT["One builder produces every URL the flow emits:<br/>error redirect, cancel link, success code"] ``` </details> - Authorize endpoint only, both verbs. The token exchange, refresh, and revocation are untouched. - Every redirect is licensed by a `validatedCallbackURL`, a type produced only where `extractAuthorizeParams` exact-matches the URI against the app's registration. A guard, not a proof: no other package can fabricate one, this one still can. - One builder now produces every response URL, including the consent page's cancel link, which rolled its own and edited the shared URL in place rather than copying it. - Each rejection logs. The error leaves in a `Location` header, which `loggermw` does not record, so a failed authorization used to look exactly like a successful one. **Three smaller behavior changes** - A callback registered with `code`, `error`, `error_description`, or `state` in its own query no longer receives that value back. A registered `error=` rode out on the success redirect, where a client that reads `error` first discards a valid code. The rest of the registered query is kept, as §3.1.2 requires. - `error_description` is confined to the NQSCHAR set Appendix A permits. Descriptions name the offending value with `%q`, so every `invalid_scope` Coder emits today carries excluded characters. Quotes now render as apostrophes. - An unparsable `redirect_uri` returns 400 instead of 500. It reached a nil dereference in `httpapi.RedirectURL`, which `POST /oauth2/tokens` also uses, and that endpoint takes no API key. **What it satisfies** - RFC 6749 §4.1.2.1 — on a failure that is not a bad redirection URI, the server informs the client through the redirection URI. That is the whole PR. - RFC 6749 §3.1.2.4 and §4.1.2.1 — a missing, invalid, or mismatching redirection URI "MUST NOT" be redirected to. A mismatched URI, and a registered URI with a rejected scheme, still answer on Coder. Pinned by `MismatchedRedirectURINotRedirected` and `DangerousCallbackSchemeNotRedirected`. - RFC 6749 Appendix A — `error_description` is NQSCHAR, and the rule is on the decoded value, so percent-encoding on the wire does not satisfy it. - RFC 6749 §4.1.2 and §3.1.2 — the four reserved response parameters are dropped from the registered query; everything else in it is retained. - Not yet: the remaining parameter failures do have a trusted callback in hand, but the parser reports one verdict for every field at once, so the caller cannot say which field failed. A follow-up classifies them. The two `server_error` sites also stay put: sending an internal fault outbound with a Coder-written description wants its own review. **Docs and Swagger.** `docs/admin/integrations/oauth2-provider.md` gains a Common Issues entry per newly redirected code, and the implicit-grant limitation now says where the error arrives. Both authorize verbs document the 302, the GET side for the first time. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Fourth of the stack. #28179 has merged, so this reviews against main. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
8b8c80614d |
feat: expose template builder agents and per-module agent (#28905)
Part of [DEVEX-556](https://linear.app/codercom/issue/DEVEX-556). Builds on the base agent metadata added in #28794. ## Summary Surfaces the backend multi-agent support through the SDK and HTTP API: the bases endpoint returns each base's agents, and compose/create-template accept a per-module `agent_name`. ## What changed - `codersdk/templatebuilder.go`: added `TemplateBuilderBaseAgent`, `TemplateBuilderBase.Agents`, and `TemplateBuilderComposeModule.AgentName` (`agent_name,omitempty`). - `coderd/templatebuilder_handler.go`: added `baseAgentsToSDK`; the bases endpoint returns agents, and the compose and create-template endpoints forward `AgentName`. - `make gen` regenerated `site/src/api/typesGenerated.ts`, `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`, `docs/reference/api/schemas.md`, and `docs/reference/api/templatebuilder.md`. - `wizardState.test.ts`: added `agents: []` to the base fixture now that the field is required on the generated type. ## Scope SDK/API plumbing only. `ComposeModule.AgentName` now has a producer (the handlers) but no caller sets it yet — the wizard UI (follow-up) is what will populate it. No DB change, so `enterprise/audit/table.go` is unaffected. ## Testing - Bases endpoint asserts each base returns agents with exactly one default (and the `dev`/`main` names). - Per-module `agent_name` round-trip and unknown-agent (400) compose tests. - `make gen` (idempotent), `make fmt` (no changes), `golangci-lint ./coderd/... ./codersdk/...`, the Go template-builder tests, frontend `tsc` + `biome check`, and docs markdownlint all pass. <details> <summary>Design note</summary> `display_name` is intentionally returned as `""` for now: every base is single-agent, so no base authors a per-agent label. The field exists for multi-agent bases where the wizard radio needs a human-readable name; consumers fall back to the agent `name` when it is empty. </details> --- 🤖 Generated by Coder Agents on behalf of @jeremyruppel. Co-authored-by: Coder Agents <agents@coder.com> |
||
|
|
4875ae218a |
feat: enforce user secret file policy (#28518)
Adds the deployment option `--user-secrets-disable-file-path` / `CODER_USER_SECRETS_DISABLE_FILE_PATH` / `userSecretsDisableFilePath` (default `false`). When it is set, the create and batch-create user-secret endpoints reject requests with a non-empty file path, and PATCH validates the post-update state under a `SELECT ... FOR UPDATE` row lock, rejecting a new or changed file path as well as enabled states that would have no effective delivery target. Legacy stored paths are preserved, so users can still edit, disable, clear the path, or migrate the secret to env delivery. This is PR 1 of a 4-PR stack; follow-ups cover manifest filtering, the dashboard, and CLI/docs. Refs #27488 Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder. |
||
|
|
521c923ac3 |
docs(docs/install): add template builder registry URL to Artifactory mirror guide (#28904)
## Summary Documents the Coder server environment variable needed to point the in-product **template builder** at a JFrog Artifactory registry mirror, and cross-links the two relevant install guides. The Artifactory guide already covered mirroring the Coder Registry and configuring the Terraform CLI on Coder, but it never mentioned `CODER_TEMPLATE_BUILDER_REGISTRY_URL`, which the template builder needs so it generates module source paths against the mirror instead of `registry.coder.com`. This env var was only documented in the [air-gapped deployments](https://coder.com/docs/install/airgap) guide. ## Changes - `docs/install/registry-mirror-artifactory.md`: new **Step 6: Point the template builder at your mirror** - Documents `CODER_TEMPLATE_BUILDER_REGISTRY_URL=<your-artifactory-host>` and the accepted value format (bare host, optional port; scheme/trailing slash stripped; path/query/fragment/credentials rejected at startup). - Notes the `CODER_DISABLE_TEMPLATE_BUILDER=true` fallback for fully air-gapped deployments. - Links to the air-gapped deployments doc's Template builder section. - `docs/install/airgap.md`: the Template builder section now cross-links to the Artifactory mirror guide. ## Validation - `pnpm run format-docs` — no changes - `pnpm run lint-docs` — 0 errors --- This PR was generated by Coder Agents on behalf of @jeremyruppel. |
||
|
|
cb6c98147f |
docs: add Agent Relay docs (#28786)
## What this adds Two new docs pages for **Agent Relay**, a feature that connects a supported cloud-hosted AI agent provider's hosted sessions to self-hosted Coder workspaces. The provider's orchestration and AI inference stay cloud-hosted; a worker process inside the workspace executes the agent's tool calls. - `docs/ai-coder/agent-relay/index.md` — top-level overview: what it is, what it does, what it is and isn't, business value, current state, and supported providers. - `docs/ai-coder/agent-relay/cursor.md` — the Cursor-specific child page, naming Cursor Cloud Agents and Cursor's own bring-your-own-machine (BYOM) terminology. Both pages are tagged `"state": ["early access"]` in the manifest and state the feature is in **closed preview with select customers**, pointing readers to their Coder account team or `sales@coder.com` for access. ## Also included - `docs/user-guides/workspace-management.md`: broadened the workspace definition to include coding agents alongside developers. - `docs/reference/glossary.md`: added an Agent Relay entry (alphabetized between Agent Firewall and AI Gateway) and added it to the existing "agent" term-disambiguation callout, since it's easy to conflate with Coder Agents. ## Scope note for reviewers `Agent Relay` itself (the underlying service, config, and worker implementation) lives in a separate, non-public repository. I don't have access to that source from this environment, so I deliberately kept both pages high-level and didn't invent specifics like CLI flags, config file structure, or exact command syntax. Before this goes further, someone with access to that repo should verify the mechanics described here (workspace-per-session lifecycle, provider pool mapping, worker connection model) against the real implementation, and a follow-up PR should add a step-by-step "Getting started" section once the feature moves past closed preview to something self-serve. ## Validation - `docs/manifest.json` is valid JSON. - `markdownlint-cli2`: 0 issues across all changed/added Markdown files. - `vale --no-exit`: 0 errors on every changed/added file (a handful of pre-existing gerund-heading warnings on `workspace-management.md` and `glossary.md` predate this branch and aren't touched here). - `scripts/check_emdash.sh`: passes. - Confirmed every relative link target in the new pages resolves to a real file in the repo. <details> <summary>Decision log</summary> - Dropped an "air-gap capable" claim and a "Coder AI Gateway" claim that would have been present in an earlier draft: the integration requires the in-workspace worker to hold an outbound connection to the cloud provider for inference/orchestration, so true air-gapping isn't possible, and Coder's AI Gateway isn't in the inference path for this feature. - Named the specific Cursor product as **Cursor Cloud Agents** and linked Cursor's own "bring-your-own-machine (BYOM)" terminology (`cursor.com/docs/cloud-agent/bring-your-own-machine`) rather than inventing Coder-specific naming for the same concept. - Kept "workspace" lowercase per the existing style guide (`workspace` is the documented generic-concept casing, distinct from named features like "Workspace Proxy"), while still linking the term to the Workspace Management page. - Used "closed preview with select customers" rather than "Preview," and removed a blanket "not feature-complete or stable" disclaimer sentence per explicit direction. </details> --- 🤖 This PR was created by Coder Agents on behalf of @mattvollmer. --------- Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com> |
||
|
|
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. |
||
|
|
805b47aa00 |
chore: make pre-commit hook checks opt-in (#28895)
The pre-commit hook currently runs `make pre-commit` or `make pre-commit-light` on every commit for everyone who has the repository hooks installed. This makes it opt-in, mirroring how `scripts/githooks/pre-push` already works: checks run only when `git config coder.pre-commit true` is set or the workspace owner is on the hook's allowlist, and `git config coder.pre-commit false` opts out explicitly. By default the hook prints a one-line skip message and exits 0. Hook installation (`core.hooksPath`) and the linked-worktree hooksPath shield are unchanged, so `post-checkout` and `pre-push` keep working as before. `.claude/docs/WORKFLOWS.md` and `docs/about/contributing/CONTRIBUTING.md` describe the new opt-in. > Xum (an AI coding agent) authored this PR on behalf of @ibetitsmike. |
||
|
|
9368917813 |
feat: report the negotiated scope to the user and the client (#28179)
**TL;DR** Last of the stack, split out of #28045. #28178 decided what the scope is; this PR is everything that reports it, to the user on the consent page and to the client on rejection. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. Every code is still stamped unrestricted. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name, and fails closed on any shape it does not model. Added with no production callers. | | #28178 | The authorize endpoint checks the request against the scope catalog, grants it only if the app's filtered allowlist covers it, and persists the result on the code. | | **#28179 (this)** | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's own callback per RFC 6749 §4.1.2.1 instead of a Coder error page. Retires the interim plumbing #28178 left behind. | - #28178 has merged, so this diff is against main and reviews on its own. It is still worth reading first: nothing here decides a scope, it only reports the one `negotiateScope` already returns. - **The consent page HTML is not final.** Layout and wording in `site/static/oauth2allow.html` are still being refined. It is in this branch so the scope-enforcement flow can be exercised end to end in a browser, not because the markup is settled. The reviewable part of Half A is the Go side that decides what the page states; the presentation will change. - An unrestricted grant still reads as full access, not as a scope name. Nothing about what a token can do changes in this PR either. **Where in the flow** - Authorize endpoint only, both verbs. GET decides what the consent page states; both verbs send `invalid_scope` to the callback. The token exchange, refresh, and revocation are untouched. - `negotiateScope` is unchanged from #28178, so which requests succeed is unchanged. This PR reads its result twice: once to decide what the page lists, once to decide where the rejection goes. - The endpoint sits behind `apiKeyMiddlewareRedirect`, so the user is authenticated before any of this runs. That matters for the redirect, not just for the page. - Consent page rendering moves a decision into Go rather than the template: `RenderOAuthAllowData` carries `Scopes` and `Unrestricted` separately, and the template branches on `Unrestricted` alone. **What it satisfies** - RFC 6749 §4.1.2.1 — on a failure that is not a bad redirection URI, the server "informs the client by adding the following parameters to the query component of the redirection URI". `invalid_scope` now goes there. #28178's interim delivery, a static error page on GET and an error body on POST, is what this replaces. - RFC 6749 §4.1.2.1 — `state` is "REQUIRED if a `state` parameter was present in the client authorization request", so it is echoed only when the client sent one, never synthesized. Pinned by `OmittedStateNotEchoed`. - RFC 6749 §3.1.2.4 and §4.1.2.1 — on a "missing, invalid, or mismatching redirection URI" the server "MUST NOT automatically redirect the user-agent to the invalid redirection URI". This is the whole ordering argument, and the file's other error paths keep their existing delivery precisely because several of them are where that validation fails. - RFC 9700 §2.1 — pre-registered redirection URIs "MUST utilize exact string matching". `extractAuthorizeParams` already did this before the stack; Half B depends on it rather than adding it. - RFC 9700 §4.11.2 — names this exact hazard: an attacker who registers a client can "intentionally send an erroneous authorization request, e.g., by using an invalid scope value, thus instructing the authorization server to redirect the user agent to its phishing site". The destination is still only ever a URI that client registered, so this is a phishing surface that costs an attacker a registration, not an open redirect. The precaution the section requires, authenticating the user first, is what `apiKeyMiddlewareRedirect` provides. - RFC 9700 §4.12 — a server redirecting a request that may carry credentials "MUST NOT use the HTTP 307 status code". 302, matching the success redirect beside it. - RFC 6749 §4.1.2.1 — `server_error` exists "because a 500 Internal Server Error HTTP status code cannot be returned to the client via an HTTP redirect". An unusable registered callback is the one case with nowhere to redirect, so it answers 500 on both verbs and logs the app and URL for an operator to correlate by. - Not yet: §1.4.1 still wants `scope` in the token response when the grant differs from the request. Tokens are untouched here, as in #28178, so that lands with enforcement. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Last of three. #28178 has merged, so this reviews against main. #28178 decided what the scope is. This PR is everything that tells someone about it. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
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> |
||
|
|
fe545d5e3a | chore(docs): update release docs for v2.37.0 (#28830) | ||
|
|
72872c4f2c |
docs(docs/admin/templates/extending-templates): document module caching and the disable toggle (#28800)
Coder caches resolved Terraform modules per template version and reuses
them across workspace builds instead of re-fetching from origin. This is
enabled by default and can be disabled per-template with
`disable_module_cache`, but neither the caching behavior nor the toggle
were documented anywhere outside the generated API reference.
Documents module caching in the Terraform Modules guide (what gets
cached, the 20MB archive limit, and how to disable it), and cross-links
it from the existing "Module not loaded" troubleshooting entry in the
Dynamic Parameters doc, since both describe the same module archive.
Also documents a second cause of "Module not loaded" warnings: template
versions published before Coder started archiving modules for Dynamic
Parameters have no cache at all, so every module in the template shows
the warning in the workspace creation form. Workspace builds still
succeed, since Terraform fetches modules from their original sources
during the build regardless of the cache; only the form's ability to
evaluate module-backed parameter values is affected. Publishing a new
template version regenerates the archive and resolves it.
<details>
<summary>Verification notes</summary>
Behavior confirmed by reading the source, not assumed:
- `coderd/provisionerdserver/provisionerdserver.go`: skips fetching
`CachedModuleFiles` for a workspace build when
`template.DisableModuleCache` is set. The same file's comment ("Older
templates (before dynamic parameters) will not have cached module
files") confirms why some template versions have no archive at all.
- `provisioner/terraform/provision.go` + `provisionerd/runner/init.go`:
the cached archive is extracted into `.terraform/modules` before
`terraform init` runs, so modules already present are not re-downloaded;
anything missing (e.g. skipped for size, or no archive at all) is still
fetched normally by Terraform during the build.
- `provisioner/terraform/modules.go`: `MaximumModuleArchiveSize` = 20MB.
-
`coderd/database/migrations/000416_workspace_module_reuse_toggle.up.sql`:
`disable_module_cache` defaults to `false`, i.e. caching is on by
default.
- `site/.../TemplateSettingsForm.tsx`: exact dashboard label and warning
copy reused verbatim in the doc.
</details>
> Generated by Coder Agents
|
||
|
|
47184d78c8 |
feat: enable Coder.OneSentencePerLine (#28779)
Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com> |
||
|
|
fb71beee01 |
docs: add a nested AGENTS.md for docs prose (#28780)
Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com> |
||
|
|
3d2cf5fcc6 |
docs: correct Coder Tasks deprecation version to v2.34 (#28764)
Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com> |
||
|
|
aaafe2d105 |
docs(docs/.style): apply one sentence per line (#28776)
The style guide requires one sentence per Markdown source line, but the pages under `docs/.style` were themselves wrapped to a fixed column width. This reflows them so the style guide adheres to the style guide. Requested by @nickvigilante in coder/coder#28764 (review). ## Scope 10 files under `docs/.style`, including `content-guidelines.md` (previously the second worst offender in the whole docs tree at 126 wrapped continuation lines) and every page under `style-guide/`. Line breaks only. No wording changes. ## How it was done A script joined each paragraph, list item, and blockquote into a single logical unit, then re-split it at sentence boundaries. Code fences, tables, front matter, HTML blocks, and indented code are untouched. Abbreviations (`e.g.`, `i.e.`, `q.v.`, `et al.`, and similar) are matched on word boundaries so they do not trigger a split, and a fragment that starts lowercase is treated as a continuation rather than a new sentence. ## Verification - Text content is byte-identical after normalizing whitespace and blockquote markers: 10 of 10 files match. - `markdownlint-cli2` reports the same 2 findings as `main` (both pre-existing `MD059` hits on the deliberate "Don't" examples in `accessibility-and-inclusion.md`). No new findings. - `markdown-table-formatter --check` reports no changes needed. ## Note on the rest of the corpus This PR is deliberately limited to `docs/.style`. For the wider tree, 237 of 267 files still use fixed-column wrapping (about 5,645 continuation lines), which is worth knowing when deciding whether a rule can be enforced repo-wide. Per the review discussion, those pages get converted as PRs touch them rather than in a dedicated refactor. Created on behalf of @matifali --------- Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com> |
||
|
|
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.
|
||
|
|
1fa6ebe5c3 |
fix: support first-user-trial in non-interactive login (#28321)
## Summary `coder login --first-user-trial=true` was unusable in non-interactive environments: the trial info fields could only be collected via interactive prompts, so scripted setup failed with a bare `EOF`. This adds flags and env vars for every trial info field, extracts the functions into a helper, turns the EOF into an actionable error, and fixes a related quirk where enabling the trial via env didn't reliably suppress the trial prompt. Fixes coder/coder#23264 ## Changes * Add a flag + env var for each trial field (matching the existing `first-user-*` convention): `--first-user-trial-{first-name,last-name,phone-number,job-title,company-name,country,developers}` and their `CODER_FIRST_USER_TRIAL_*` env vars. * When a trial field is missing with no input available, return an error naming the exact flag/env instead of a raw EOF. * Read `CODER_FIRST_USER_TRIAL` from `inv.Environ` instead of `os.Getenv` so the flag binding and the "Start a trial?" prompt gate agree (previously the env toggle could hit an EOF prompt that silently reset `trial` to `false`). * Regenerate `coder_login_--help.golden` and `docs/reference/cli/login.md`. ## Testing * Non-interactive login via flags and via env vars (env test asserts the trial is actually provisioned via a recording `TrialGenerator`). * Missing trial info returns the clear flag-naming error instead of hanging. * Existing interactive `TestLogin` subtests pass; `golangci-lint` clean. ## Notes No strict CLI validation of `country`/`developers` against the UI option lists: the server doesn't enforce them, and the existing fixture uses `developers=10-50` which isn't in the CLI bucket list. Can add if preferred. --- *Created by Coder Agents on behalf of* @snagles\*.\* |
||
|
|
c73f34c35d |
feat: honor the deployment registry mirror in template builder bases (#28727)
## Summary Threads the deployment's configured module registry (`CODER_TEMPLATE_BUILDER_REGISTRY_URL`) into template-builder **base** rendering, so a base that embeds a catalog module (e.g. the quickstart base's `git-clone`) resolves its `source` through a registry mirror the same way wizard-composed modules already do. Previously base-embedded module sources hardcoded `registry.coder.com`, so on a mirror/private-registry deployment a base-embedded module reached the public registry while wizard modules used the mirror. Implements [DOCS-610](https://linear.app/codercom/issue/DOCS-610). ## What changed * `BaseRenderContext.RegistryBase` (new field), mirroring `ModuleRenderContext.RegistryBase`. `Compose` threads the deployment registry through `renderBase` into the base render context, and the four hardcoded base module sources (`quickstart` git-clone, `azure-linux`/`gcp-linux`/`gcp-windows` region modules) now use `{{ .RegistryBase }}`. Because the value defaults back to `registry.coder.com`, rendered sources stay byte-identical; the only golden change is the removal of the now-stale quickstart "follow-up" note. * **Boot-time validation.** `codersdk.ValidateTemplateBuilderRegistryURL` runs in `DeploymentValues.Validate()`, gated on the builder being enabled, matching the chat-hook precedent. A malformed value fails at server start naming the option, instead of surfacing as a per-request error to a template author who cannot fix it. It uses `net/url` in authority form to reject a scheme, path, query, fragment, trailing slash, or credentials and accept a bare `host[:port]`; it does not canonicalize the host. * `Compose` **trusts the validated value**, defaulting an unset one and defensively rejecting a malformed one for direct callers that bypass boot. ## Tests * `codersdk`: validator accept/reject matrix (incl. credentials-without-echo) and a `DeploymentValues.Validate` boundary test with a disabled-skips-validation case. * `templatebuilder`: a base honors the mirror and falls back to the default when unset, plus a defensive-reject case; existing compose tests updated to bare-host registry values. <details><summary>Design decision log</summary> This PR is a deliberately minimal reimplementation of the [DOCS-610](https://linear.app/codercom/issue/DOCS-610/template-builder-base-embedded-modules-should-honor-the-deployment) scope, started fresh from `main` rather than carrying forward an earlier, larger draft (coder/coder#28480). Key decisions: * **Scope kept to the ticket.** The ticket's fix is three bullets: add a registry field to `BaseRenderContext`, thread the deployment `RegistryURL` through `Compose` -> `renderBase`, and use it in base module sources. Independent hardening explored in the earlier draft was dropped as out of scope: `terraform-svchost`-based IDN/punycode/port canonicalization, a rendered-HCL backstop with a 500 mapping, and HCL module-source extraction helpers. Telemetry misclassification of mirror modules is tracked separately ([DOCS-712](https://linear.app/codercom/issue/DOCS-712/telemetry-misclassifies-registry-mirror-modules-as-non-coder)) and is not addressed here. * **Default lives in the render layer.** `templatebuilder.DefaultRegistryBase` holds the fallback host; `codersdk` keeps its own option-default literal. An earlier version exported the constant from `codersdk`, which only emitted a dead `typesGenerated.ts` entry that nothing in the frontend consumed, so it was moved out. The `codersdk` validator is a function, so it generates no TS type. * **Validate at the config boundary, fail fast.** The repo convention is to hard-fail structurally invalid config in `DeploymentValues.Validate()` (access URL, OAuth lifetimes, chat hook URL) and to warn only for functional-but-risky settings. A malformed registry host is structurally invalid, so it fails at boot. This also puts the error in front of the admin who set it, rather than a template author hitting a per-request error they cannot fix. * `net/url`**, not a regex.** The codebase validates identifiers/names with regexes but host/URL-shaped config with `url.Parse` (chat hook URL, OAuth redirect URIs, AI provider base URL). This value is host-shaped, so it follows that convention. `url.Parse("//" + v)` with `u.Host == v` rejects a scheme/path/query/fragment/trailing-slash in one check. </details> > This PR was created with AI assistance (Coder Agents). |
||
|
|
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.
|