Skip to content

fix: authenticate confidential clients on the OAuth2 refresh grant - #29207

Merged
BobbyHo merged 172 commits into
mainfrom
coder-plat-506-refresh-client-auth
Sep 15, 2026
Merged

BobbyHo merged 172 commits into
mainfrom
coder-plat-506-refresh-client-auth

Conversation

@BobbyHo

@BobbyHo BobbyHo commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

Second of three for SEC-348. The refresh grant never checked client_secret. Anyone holding a stolen refresh token and the app's public client_id could get new tokens without the app's credentials. RFC 6749 section 6 requires confidential clients to authenticate here. The token to app ownership check landed in #27712; this is the authentication half. Closes PLAT-506 (GHSA-whr4-xxrp-33vc).

PR What it does
#29206 Extracts the secret check into a helper.
this The refresh grant calls it. A refresh without a valid secret is refused.
#29208 The revocation endpoint calls it.
  • No migration, no new error codes. The 401 invalid_client path already exists for the code grant.
  • Breaking. A confidential client that refreshes without its secret, or with a wrong one, now gets 401 instead of 200. Sending the secret recovers it; the refresh token is not consumed by the refusal. Public clients are unaffected.

Implementation Details

The check

  • refreshTokenGrant calls authenticateClient for confidential clients before it parses the refresh token. A public client has no secret, and the existing app binding plus single-use rotation are what tie its refresh to the client.
  • The check runs first on purpose. If the token were checked first, a caller without the secret could tell a dead token (invalid_grant) from a live one (invalid_client). Now every unauthenticated request gets the same 401 and learns nothing about the token.
  • Refused at the grant, not the parser. RFC 6749 section 5.2 lists "no client authentication included" under invalid_client, which is a 401 with WWW-Authenticate. The parser's 400 for the code grant is left as is.

Logging

  • A failed client authentication at the token endpoint is logged at warn with the grant type and app id. Nothing from the request body, so the token the caller did present never reaches a log.

Two expectations flip

  • A refresh that presents another app's secret under the wrong client_id was invalid_grant from the ownership check. It is now invalid_client, because authentication runs first. The ownership check keeps its coverage through a new row where the other app authenticates as itself.
  • Refreshing after the presented secret was deleted was invalid_grant on fix: make OAuth2 refresh token redemption single-use under concurrency #28752, because the cascade removed the token. It is now invalid_client, because the deleted secret fails authentication first.

Docs

  • A behavior change note in Limitations, a Common Issues entry for the new 401, and a Security Considerations bullet. The refresh examples already showed the secret on every confidential request, so the docs described this behavior before the code did.
Tests
  • TestOAuth2RefreshClientAuthentication: missing secret, wrong secret, another app's valid secret, wrong secret with an unknown token (401, not 400), HTTP Basic, Basic and body in conflict, public client with no secret, public client with a secret sent anyway. Each refusal also checks the token row survived and a correct retry succeeds.
  • TestOAuth2ProviderTokenRefresh: the WrongApp row split into own-secret (invalid_grant) and other-secret (invalid_client), plus a wrong-secret row.
  • TestOAuth2RefreshRevokedToken/AppSecretDeleted now expects invalid_client.
  • Unchanged and still passing: the public client refresh in refreshedPublicClientSession, every refresh test that already sent the secret, and every token parser test.

Stack: #28752, #29206, this PR, #29208.

BobbyHo and others added 30 commits August 14, 2026 17:02
Add ScopesCover, which reports whether every permission a requested scope
grants is also granted by at least one of a set of allowed scopes. It
expands both sides and compares the resulting permissions, so
coder:workspaces.access covers workspace:read even though it never names
it, and coder:all covers everything.

The comparison is deliberately asymmetric. Positive permissions on the
allowed side that it does not model are dropped, which can only make the
answer stricter. Anything unmodelled on the requested side is an error
instead, because ignoring it would answer "covered" about authority that
was never compared. Negative permissions are the exception and fail closed
on both sides, since dropping an anti-grant from the ceiling would widen
it rather than narrow it.

Add CanonicalScopeName, which maps the backward-compatibility aliases
IsExternalScope accepts onto the names the api_key_scope enum stores.
IsExternalScope answers whether a name may be requested, not how that name
is spelled once persisted, so a caller that stores what it validated has
to canonicalize in between.

Both functions are added without production callers. The OAuth2 authorize
endpoint uses them to negotiate a requested scope against an app's
configured allowlist, which follows in a separate change.
State the rule the guards enforce, site-level grants only, instead of
describing the asymmetry abstractly. The allow-list case is now covered
alongside negative permissions, which the previous wording omitted even
though the code treats them identically.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
ScopesCover checked the requested scope for org and user grants but not
the allowed scopes, whose User and ByOrgID permissions were discarded
unread. A scope granting workspace:* at site level while negating
workspace:delete for the user would have covered a request for
workspace:delete, because the negative that carves the action back out
lives in the half coverage never examined.

No catalog scope populates those fields today, so nothing was
miscompared in practice. The gap mattered because these guards exist to
keep the comparison fail-closed, and this one failed open.

Both sides now run the same checkCoverable helper, which refuses a scope
carrying org or user grants, a negative permission, or a resource allow
list. The helper names the side, so an error reports which half of the
comparison was undecidable. The doc comment claimed an unmodeled grant
on the allowed side is dropped; nothing is dropped now, so it is gone.

ScopesCover builds every Scope it reads from ExpandScope, which cannot
produce these shapes, so the guards are unreachable through the public
API. scopes_internal_test.go drives synthetic Scope values through
checkCoverable instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
permissionCovered skipped negative permissions, but checkCoverable now
refuses a scope carrying one on either side, so the branch was dead. It
was never defense in depth. Had a negative reached it, skipping the
anti-grant would leave any wildcard beside it free to match, and a scope
granting workspace:* while negating workspace:delete would report
workspace:delete as covered. The skip widened the ceiling while looking
like it narrowed it.

The precondition moves to the doc comment, which names checkCoverable as
what enforces it and says why subsumption cannot answer the question an
anti-grant poses.

No behavior change: the branch was unreachable. permissionCovered goes
from 88.9% to 100% statement coverage.
Five review findings on the coverage tests, all in scopes_test.go.

CanonicalScopeName had both alias arms at zero coverage. Its only caller
in the tests loops over ExternalScopeNames, which yields canonical names
only, so the canonicalizing call returned its input unchanged on every
iteration and read as coverage without being any. Swapping the arms, so
that `all` persisted application_connect and the reverse, kept the suite
green. TestCanonicalScopeName now pins the mapping and the loop appends
the aliases, taking the function from 50% to 100%.

The appended aliases raise branch coverage and assert a requestable name
is comparable once canonicalized, but they cannot detect a swapped
mapping, since both aliases resolve to scopes that cover themselves. The
comment says so rather than implying the loop guards more than it does.

CompositeDoesNotCoverNonMember and
CompositeDoesNotCoverWiderActionOnCoveredResource both asked for an
ungranted action on a resource coder:workspaces.access does grant, so
they tested one branch twice and left "resource not granted at all"
untested. They are now split along that line, with names that describe
which failure each one is.

The three wantErr rows shared a bare require.Error, so any error passed
any row and a bug failing every input on the requested side would have
left the allowed-side row green. wantErrContains replaces the bool and
names the side. Rewording the allowed-side message as the requested-side
one now fails three rows that previously all passed.

Alias rejection was tested for one alias on one side. Both aliases are
now tested on both sides. The allowed-side rows are the ones that earn
their place: they are what would catch someone canonicalizing inside the
allowed loop and widening the contract without a caller asking.
ScopesCover expanded and compared in a single pass, so the invariant
guards only ever ran on scopes ExpandScope had produced. Every such scope
satisfies them, which left the guards unverified in the position that
matters: the existing test called checkCoverable directly and could not
tell whether ScopesCover consulted it on both sides, or at all.

Split the comparison into scopesCoverExpanded, which takes already
expanded scopes paired with the names they came from. Tests drive
synthetic Scope values through it, so dropping the guard from either side
now fails, as does an allowed scope that grants every workspace action
except delete answering a request for delete.

Expanding every allowed scope before any guard runs reorders two error
paths against each other: a requested scope that fails a guard alongside
an unknown allowed name now reports the expansion failure rather than the
guard failure. Both return (false, error), and no ScopeName reaches that
combination today.
…ontract

The knowledge of which spellings are backward-compatibility aliases lived
in two switches, one in IsExternalScope and one in CanonicalScopeName,
kept in step by discipline. Drift between them is asymmetric: a name the
first accepts and the second does not rewrite is declared public and then
fails to expand on every request naming it. Both now read one table, so
they agree by construction, and an internal test walks that table
asserting each alias is public, resolves to a public name, and resolves
to one ExpandScope accepts. A third alias is covered the day it is added.

ScopesCover stated "names must be canonical" in prose only, which is
wrong for exactly the two inputs IsExternalScope accepts and ExpandScope
does not. The parameters are now canonicalAllowed and canonicalRequested,
so the requirement shows up in editor hints at every call site rather
than only in a doc comment the caller may not have opened.

Naming the parameters was chosen over canonicalizing inside ScopesCover.
The single downstream caller already canonicalizes both sides in bulk
before comparing, so absorbing the step would remove nothing from it
while dissolving the distinction between a public spelling and a stored
one at the layer that should hold it.
…roken

The site-only, wildcard-allow-list, no-negatives invariant was described
on ScopesCover and enforced by its guards, but ExpandScope, which is what
produces those values, had no doc comment at all. Someone adding a scope
reads ExpandScope and its neighbors; nothing there warned that populating
User or adding a negative makes the scope uncomparable. State it there,
along with the canonicalization requirement, and name the consequence
rather than just the rule.

Also note on ScopesCover that a wildcard request needs a wildcard grant.
Enumerating today's concrete actions genuinely is narrower than
`workspace:*`, so the rejection is intended. The
OneActionDoesNotCoverResourceWildcard row already pins the behavior; the
note stops the next reader of an authorize endpoint from taking it for a
bug and closing the gap.

Comments only. Checked that the documented invariant actually holds for
all three builtin scopes and all seven composites.
TestScopesCoverAllowedNegativeDoesNotWiden drove the same scope shape as
the NegativeUserPermission row of TestScopesCoverGuards, but asserted only
that some error came back. The row asserts the message, the side it names,
and that the comparison reports no coverage, and it runs the shape on both
sides rather than one. The weaker copy could pass on a regression that
returned the wrong error or stopped naming the side. Fold the scenario it
documented into the row's comment and drop the copy.

Rename the shared permission fixtures after the value they hold. The site
prefix read as "belongs in Role.Site", while two of the three are placed in
Role.User to build the shapes the guards refuse, and the No suffix gave no
hint that it means Negate.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The allowed-side wrap printed the scope name and then wrapped an error that
prints it again, so the two sides of one comparison read differently:

  expand allowed scope "foo": no scope named "foo"
  expand requested scope: no scope named "foo"

Drop the redundant verb and let the inner error carry the name on both
sides.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The docstring said the list includes the `all` and `application_connect`
special scopes. It appends ScopeAll and ScopeApplicationConnect, which are
the `coder:` spellings, so the bare aliases are absent. Two callers already
compensate by appending them by hand, one of them with a comment stating
the mismatch. Describe what the function returns and name the helper that
bridges the gap.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The invariant that expansion populates Site only was stated in full on
ExpandScope, checkCoverable and ScopesCover, and the "everything except
delete" example appeared on checkCoverable and again on permissionCovered
twenty lines below. State it once on ScopesCover, which is the function
whose behaviour depends on it, and cross-reference from the other two. Drop
framing that ranked implementation choices nobody proposed, and cut the two
test comments down to the facts the assertions do not already carry.

Kept in full: what each guard in checkCoverable defends, since no other
comment says it, and the wildcard rule on ScopesCover.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
checkCoverable said a negative site permission would be skipped, naming
a branch permissionCovered no longer has. A negative reaching it matches
on resource type and action like any other grant, so the anti-grant
would read as a grant. Name that instead, so the cross-reference lands
on a doc that matches the code.
The docstring listed the aliases and the low-level scopes, omitting the
curated composites the function also accepts. A caller consulting it to
decide whether coder:workspaces.access is public read no from the doc
and yes from the code.
ExternalScopeNames promises it offers each scope under one canonical
spelling, and no test held it to that. TestScopesCoverEveryExternalScope
appended the two aliases, but canonicalized them back into names the
list already carries, so it re-ran assertions the list iteration had
made and left the promise itself unpinned.

Assert on the alias table instead: the list omits the alias and offers
its canonical target. Every offered name is already proven coverable, so
the aliases inherit coverage, and a third alias inherits both invariants
the day it is added rather than needing a third hardcoded pair here.
The authorize endpoint parsed the scope parameter and discarded it, so an
app's configured allowlist never restricted anything and a client asking
for more than it should get was never told no. Phase 1 added the columns
that carry a negotiated scope from a code to the token it becomes, but
nothing wrote one, so every code was stamped unrestricted.

Negotiate the scope at authorization time and persist the result:

- Requested names must be in the external scope catalog, and the app's
  stored allowlist is filtered through that same catalog. Filtering only
  ever narrows what can be granted.
- The allowlist bounds authority, not spelling. A request is granted when
  every permission it grants is also granted by the allowlist, whether or
  not the allowlist names it, so an app allowed coder:workspaces.access
  can approve a client asking only for workspace:ssh.
- Omitting scope grants the filtered allowlist, per RFC 6749 section 3.3.
- Both handlers negotiate, so a request that cannot succeed fails before
  the consent page renders rather than after the user clicks Allow. Each
  reports the failure the way it already reports its own errors: a static
  error page on the GET side, an OAuth2 error body on the POST side.
- Two paths produce an empty result and are deliberately 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 that filters to nothing is rejected, since falling
  back would grant strictly more than the allowlist ever permitted.

Dynamic client registration performs no catalog validation, so apps
registered with scopes such as openid or admin hold allowlists this
server cannot grant from. They now fail authorization in both directions.
Grandfathering unknown names would seed the enforcement path with values
it cannot evaluate, trading a visible negotiation-time error for a silent
enforcement-time hole. The failure names the registered scopes and the
remedy.

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.
The consent page told every user the app was getting full access to their
account, which stopped being true once the authorize endpoint began
negotiating a narrower scope. A user approving a request has no other place
to learn what they are handing over, so the page has to follow the grant
rather than a fixed sentence.

List the negotiated permissions when the grant is bounded, and keep the
original full-access wording when it is not. An unrestricted grant is
reported as full access rather than as "coder:all", since the scope name
tells a user less than the sentence does. The list collapses to the
full-access wording whenever the unrestricted scope is present, not only
when it stands alone: an allowlist registered as `coder:all
coder:workspaces.access` grants everything, and naming the narrower entry
beside it would describe the grant as bounded.

role="list" and role="listitem" are explicit because WebKit drops the
implicit list semantics from a list styled with list-style: none, which
would otherwise leave VoiceOver announcing the permissions as loose text.

Also narrow the fragment the tests match for one rejection branch. The GET
side renders its description into HTML, which escapes the apostrophe in
"this app's allowed scope list", so the fragment stops before it.
…back

A rejected authorization request answered on Coder, which reaches only the
user's screen. The client's error handling never ran, and the state it sent
was dropped, so it could not correlate the failure with the request that
caused it. RFC 6749 section 4.1.2.1 requires the error be delivered to the
client's redirect URI once the client is known.

Redirect to the app's registered callback with error, error_description,
and the state exactly as it arrived. Both handlers use this, replacing the
static error page on the GET side and the OAuth2 error body on the POST
side.

This is safe here specifically because of ordering: extractAuthorizeParams
exact-matches the redirect URI against the app's registered callback, and
it runs before the scope check, so the destination is the app's own no
matter what the request carried. Only errors raised after that point may
use this helper, which its precondition states. Errors from
extractAuthorizeParams itself must not, since the URI is unvalidated
there. MismatchedRedirectURINotRedirected pins the ordering: an
unregistered redirect_uri fails on Coder with no Location header on either
verb, even when the same request also carries a scope the app cannot be
granted.

The other error paths in this file are unchanged, since several of them are
where redirect URI validation fails.
permissionCovered could drop its action comparison and the suite stayed
green: no ScopeName expands to {*, <specific action>}, since the wildcard
entry in policy.RBACPermissions carries no actions and coder:all is the
only wildcard resource the catalog spells. Reach the shape through
scopesCoverExpanded instead, with a positive control so the case fails on
the action rather than on resource matching, and a mirror pinning that a
single-resource grant does not cover a request for every resource.

Every allowed-side error row named the bad scope as the only entry, so an
implementation that answers as soon as one entry covers the request never
reached it. Add a row where the bad name sits behind coder:all, the only
row that fails when ScopesCover expands inside the comparison loop rather
than up front.
…otiateScope

The function does not check a requested scope and hand back a verdict. It
decides what scope the code will carry, which for an omitted request is the
app's allowlist and for an app with no allowlist is coder:all. Neither is a
value the caller asked for, so the name promised the wrong thing.
… sentinels

The black-box tests assert on the description that reaches the client, and
they did so through hand-copied fragments of the sentinel messages. A
reworded sentinel would leave every case asserting on text no branch
produces, and each case would still pass through whichever branch happened
to match next.

The sentinels live in package oauth2provider and the tests live in
oauth2provider_test, so they are bound through exported values declared in
the package's internal test file, which compiles into the same binary.
…turning it

rbac.ScopesCover reports an error when it cannot expand one of the names it
was handed. That is a deployment-side condition: the app's stored allowlist
holds something RBAC will not resolve, and no client can fix it by asking
differently. Folding it into errScopeNotAllowed both told the client it had
asked for too much, which is not what happened, and rendered RBAC internals
into error_description.

The failure now goes to the log with the app that provoked it, and the
client receives a sentinel of its own. negotiateScope takes the whole app
rather than its scope alone so the log line can name it.
… is grantable

The rejection named the filter's input, rejoined from fields. For a
whitespace-only allowlist that input is empty, so the app owner was shown
"" as the value they had to change: the one configuration where the message
is the only clue anything is set at all.

It now names the stored value verbatim.
…asons

Two reasons said things the code does not do.

"scope is not in this app's allowed scope list" described membership, but
the check is permission coverage: a scope the allowlist never names is
granted when a listed composite already confers it. A client reading the
old text would go looking for its scope in a list it was never matched
against.

"re-register the app with supported scopes" prescribed the one remedy a DCR
client has. An admin-created app is edited, not re-registered, and a DCR
client can update itself in place through RFC 7592.

The new text carries an apostrophe on the path the GET handler renders
through an HTML template, so the helper that reads those responses now
unescapes before matching.
The swagger annotation said a requested scope must be within the app's
configured allowlist, which is wrong twice over. The allowlist is checked by
permission coverage, not name membership, and it is not the only gate: every
requested name must also be in this deployment's scope catalog, including
for an app that has no allowlist at all. The omitted-scope default was
likewise stated only for apps that have one.

Two code comments went stale the same way. The branch table called the
omitted-scope default the whole allowlist when it is the catalog-filtered
one, and the comment over the persisted scope said the token minted from the
code will carry it, which is the next phase's work, not this one's.
…lient

The inline rationale for the secret-to-app check was dropped when the
check moved into authenticateClient. Fold it into the doc comment so a
reader sees why the check is not redundant after the hash passes.
Document the conflict rule and the empty username case on
mergeBasicClientAuth, and the error contract on authenticateClient
without tying the return value to one caller. Pin the empty Basic
username branch with a test row, name the OtherAppsSecret case in the
test doc instead of counting rows, and drop the shadowed parameter on
the seed closure.
@BobbyHo

BobbyHo commented Sep 11, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@coder-agents-review

coder-agents-review Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Chat: Review in progress (19/19 reviewers complete) | View chat
Requested: 2026-09-11 04:16 UTC by @BobbyHo

deep-review v0.9.0 | Round 2 | 314e184..17f5833

Last posted: Round 2, 9 findings (1 P2, 1 P3, 3 Nit, 4 Note), COMMENT. Review

Finding inventory

Finding inventory - PR #29207

Findings

# Sev Status Location Summary Round Reviewer Posted
CRF-1 P2 Author fixed (17f5833) coderd/oauth2provider/tokens_test.go:670 FK-cascade comment orphaned; now misheads the new security test with false claims and TestOAuth2RefreshKeyMissing lost its rationale R1 Netero Yes
CRF-2 P3 Open coderd/oauth2provider/tokens.go:387 New Warn log fires once per failed client auth on an unauthenticated, unrate-limited endpoint; log amplification / alert fatigue R2 Razor P3, Chopper Note Yes
CRF-3 Nit Open coderd/oauth2provider/tokens_test.go:740 Comment pins assertion to "the fourth step", an ordinal into an unnumbered function R2 Gon Yes
CRF-4 Nit Open coderd/oauth2_test.go:726 New //nolint rationale copies the "OAauth2" typo R2 Leorio Yes
CRF-5 Nit Open coderd/oauth2provider/tokens_test.go:684 postForm re-implements the shared tryTokenRequest builder instead of extending it R2 Zoro Yes
CRF-6 Note Open coderd/oauth2provider/tokens.go:690 Confidential-client auth enforced per-handler, not structurally; future grant could omit it (structural alternative: authenticate in Tokens before the switch) R2 Pariston, Ryosuke, Meruem Yes
CRF-7 Note Open coderd/oauth2provider/tokens_test.go:984 seedPublicApp returns appWithSecret for a client with no secret; type name overstates the invariant R2 Gon, Zoro Yes
CRF-8 Note Open coderd/oauth2provider/tokens.go:813 New comment leans on rotation binding: refreshed row keeps minting secret's AppSecretID, so a token refreshed under a rotated secret still cascades when the old secret is deleted; confirm intended R2 Knov Yes
CRF-9 Note Open coderd/oauth2provider/tokens.go:383 Log comment says caller "lacked the credential" but the branch also fires for a wrong or foreign secret R2 Pariston Yes

Round log

Round 1

Netero-only first pass. 1 P2. Reviewed against 314e184..0f74b2a. P2 gate: panel deferred until mechanical finding is addressed.

Round 2

Churn guard: PROCEED. CRF-1 addressed in 17f5833. Panel round (17 reviewers). Reviewed against 314e184..17f5833. Netero: no new findings. 1 P3, 3 Nit, 4 Note new. No P0-P2. Panel converged that the security change is correct. Convergence: CRF-2 (Razor P3 / Chopper Note, log amplification), CRF-6 (Pariston/Ryosuke/Meruem, per-handler auth structural alternative), CRF-7 (Gon/Zoro, seedPublicApp naming). Knov's cross-grant error-code divergence (refresh 401 invalid_client vs code grant 400 invalid_request for a missing secret) folded into the review body as an observation on untouched code.

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Komugi flake/determinism
Kurapika security
Law decomposition
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First-pass review only. These are mechanical findings from Netero; the full review panel has not yet reviewed this PR. The panel will review after this finding is addressed. This defect is worth fixing before the panel spends parallel review time.

The change itself is clean: the refresh grant reuses the existing authenticateClient helper rather than copying the secret check, authentication runs before the token is parsed so an unauthenticated caller cannot distinguish a live token from a dead one, and every refusal path asserts the token row survived and a correct retry succeeds. Test density is 84.7% and the targeted tests pass against the built worktree. Docs cover the behavior change, the new 401, and a security bullet.

One P2, no P0/P1. Netero on the orphaned comment: "The api_key/FK-cascade/HTTP-500 comment now sits directly above TestOAuth2RefreshClientAuthentication... so it reads as documentation for the client-authentication test. That test uses the shared dbtestutil.NewDB(t) and disables no constraints, so the comment's claims are false for the function it now heads."


coderd/oauth2provider/tokens_test.go:670

P2 [CRF-1] Orphaned comment now misheads the new security test (Netero)

The api_key/FK-cascade/HTTP-500 comment (670-674) now sits directly above TestOAuth2RefreshClientAuthentication with no blank line separating it from that test's own comment (676-678), so it reads as documentation for the client-authentication test. That test uses the shared dbtestutil.NewDB(t) and disables no constraints, so the comment's claims (own database, constraints off, HTTP 500 on api_key read) are false for the function it now heads.

Inserting TestOAuth2RefreshClientAuthentication between this comment block and its original function (TestOAuth2RefreshKeyMissing, now at line 844) split the comment from what it documents. Two consequences: the new security test is headed by false claims about database isolation and HTTP 500, and TestOAuth2RefreshKeyMissing lost the non-obvious rationale for why it disables FK constraints and takes its own database. Move the 670-674 block down to immediately precede func TestOAuth2RefreshKeyMissing, leaving only the 676-678 comment above the new test.

🤖

🤖 This review was automatically generated with Coder Agents.

…KeyMissing

Inserting TestOAuth2RefreshClientAuthentication split the key-missing test
from its doc comment, so the new test read as if it disabled FK constraints.
Move the comment back and shorten both.
@BobbyHo

BobbyHo commented Sep 11, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed CRF-1 in 17f5833. The api_key/FK-cascade comment is back above TestOAuth2RefreshKeyMissing, and both that comment and the one on TestOAuth2RefreshClientAuthentication are shortened to the facts the test body does not show.

@BobbyHo

BobbyHo commented Sep 11, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Full panel review (17 reviewers). CRF-1 from the first pass is verified fixed at the root: the FK-cascade rationale heads TestOAuth2RefreshKeyMissing again and the new security test carries its own accurate comment.

The security change holds up under hard scrutiny. refreshTokenGrant authenticates confidential clients before the token is parsed, which closes the oracle a token-first order would open: an unauthenticated caller gets a uniform 401 invalid_client for both a live and a dead token, and WrongSecretUnknownToken pins that. It reuses authenticateClient verbatim rather than copying the four-step secret check, so the app-binding logic cannot drift from the code grant. Public clients fail closed via !app.IsPublic(), and the refused token is provably not consumed (requireRefused reads the row back and redeems it). The WrongApp split preserves the ownership-check coverage the new auth check would otherwise mask. Test density is 84.9% spent on behavior that matters. Hisoka put it well: "The tests test the right failures, not the easy ones, and the ordering was chosen for the leak I would have gone looking for."

Counts: 0 P0-P2, 1 P3, 3 Nits, 4 Notes. Nothing blocking.

The P3 is a log-level/amplification question on the new warn line; Razor and Chopper split on whether it needs changing (P3 vs Note), so it is your call with the tradeoff laid out inline. Three reviewers (Pariston, Ryosuke, Meruem) independently converged on the same structural observation: confidential-client authentication now lives in per-handler discipline across a four-PR stack, and a future grant can silently omit it. Not a defect in this PR, but the durable fix (authenticate once in Tokens before the switch) is worth weighing before the client-credentials grant lands.

One cross-grant observation on untouched code, from Knov: a missing client_secret now answers 401 invalid_client on refresh, while the code grant's parser answers 400 invalid_request for the same omission (tokens.go:206). Per RFC 6749 §5.2 the refresh path is the more correct of the two; flagging only because a client library that branches on error code will see different responses for the same failure class across grants. Not this PR's job to reconcile.


coderd/oauth2provider/tokens.go:813

Note [CRF-8] The new comment leans on rotation binding that outlives secret rotation (Knov)

[the comment] is accurate (line 813 copies dbToken.AppSecretID), but it means a token stays bound to its minting secret even after the client rotates to a different valid secret. Concrete consequence: app holds secrets A and B, token minted under A, client refreshes using B (authenticates fine), the rotated row still references A; deleting A then cascades away a session the client is actively driving with a live secret B.

This is pre-existing rotation behavior (#28752), not introduced here, and revoking sessions minted under a deleted secret is a defensible choice. Flagging because this PR's new comment now leans on the behavior; if the intent were "the authenticating secret binds the token," the code would pass dbSecret.ID through as the code grant does. Worth confirming the current binding is the intended one.

🤖

🤖 This review was automatically generated with Coder Agents.

Comment thread coderd/oauth2provider/tokens.go Resolved
Comment thread coderd/oauth2provider/tokens.go Resolved
Comment thread coderd/oauth2provider/tokens.go Resolved
Comment thread coderd/oauth2provider/tokens_test.go Resolved
Comment thread coderd/oauth2provider/tokens_test.go Resolved
Comment thread coderd/oauth2provider/tokens_test.go Resolved
Comment thread coderd/oauth2_test.go Resolved
… test helpers

- Reword the failed-client-authentication log comment to cover missing,
  wrong, and foreign secrets.
- Name the app-binding check in the SecretOfAnotherApp test comment
  instead of its position in authenticateClient.
- Extend tryTokenRequest with request options and the response header so
  postForm no longer copies the request construction.
- Spell OAuth2 correctly in the newly added nolint rationale.
…t' into coder-plat-506-refresh-client-auth

# Conflicts:
#	docs/admin/integrations/oauth2-provider.md
BobbyHo added a commit that referenced this pull request Sep 15, 2026
… helpers (#29206)

Refactor client authentication for SEC-348 by extracting shared helpers for confidential-client secret validation and HTTP Basic credential handling. This prepares the refresh grant (#29207) and revocation endpoint (#29208) to use the same checks. No behavior change; existing tests pass unchanged, with new coverage for client authentication and Basic auth merging. No migration, new errors, or docs.
Base automatically changed from coder-sec-348-authenticate-client to main September 15, 2026 00:40

@dylanhuff-at-coder dylanhuff-at-coder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@BobbyHo
BobbyHo merged commit 800629c into main Sep 15, 2026
31 checks passed
@BobbyHo
BobbyHo deleted the coder-plat-506-refresh-client-auth branch September 15, 2026 23:18
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 15, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release/breaking This label is applied to PRs to detect breaking changes as part of the release process

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants