Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
108 commits
Select commit Hold shift + click to select a range
a672066
feat(coderd/rbac): compare scopes by permission coverage
BobbyHo Aug 14, 2026
4315706
Merge branch 'main' into plat479-1-rbac-scope-coverage
BobbyHo Aug 17, 2026
787c461
docs(coderd/rbac): shorten the ScopesCover doc comment
BobbyHo Aug 17, 2026
2d39e04
Merge branch 'main' into plat479-1-rbac-scope-coverage
BobbyHo Aug 18, 2026
2f6c44e
fix(coderd/rbac): guard allowed-side org and user permissions
BobbyHo Aug 18, 2026
bd40270
refactor(coderd/rbac): drop the unreachable negative skip in coverage
BobbyHo Aug 18, 2026
3139c54
test(coderd/rbac): pin the scope coverage table's weak assertions
BobbyHo Aug 18, 2026
9276bb8
refactor(coderd/rbac): make the coverage guards reachable from tests
BobbyHo Aug 18, 2026
865eb9a
refactor(coderd/rbac): share the alias table and name the canonical c…
BobbyHo Aug 18, 2026
26a6bed
docs(coderd/rbac): document the expansion invariant where it can be b…
BobbyHo Aug 18, 2026
7cca7b3
Merge branch 'main' into plat479-1-rbac-scope-coverage
BobbyHo Aug 19, 2026
1678a77
test(coderd/rbac): pin the coverage guards at one strength
BobbyHo Aug 19, 2026
aba3c6c
fix(coderd/rbac): name the scope once in expansion errors
BobbyHo Aug 19, 2026
9a08105
docs(coderd/rbac): correct the external scope list contract
BobbyHo Aug 19, 2026
2fcce8b
docs(coderd/rbac): trim the restated coverage invariant
BobbyHo Aug 19, 2026
a775a48
docs(coderd/rbac): correct the negative permission cross-reference
BobbyHo Aug 19, 2026
e0c0d4a
docs(coderd/rbac): name every category IsExternalScope admits
BobbyHo Aug 19, 2026
189740d
test(coderd/rbac): pin the alias list invariants on the alias table
BobbyHo Aug 19, 2026
7d08e49
Merge branch 'main' into plat479-1-rbac-scope-coverage
BobbyHo Aug 19, 2026
ca4dc52
feat(coderd/oauth2provider): negotiate and persist authorization scope
BobbyHo Aug 14, 2026
f402e1a
feat(site): state the negotiated scope on the OAuth2 consent page
BobbyHo Aug 14, 2026
28ef5ba
fix(coderd/oauth2provider): return invalid_scope to the client's call…
BobbyHo Aug 14, 2026
62950d3
test(coderd/rbac): close two mutation gaps in scope coverage tests
BobbyHo Aug 20, 2026
554a703
Merge branch 'main' into plat479-2-negotiate-scope
BobbyHo Aug 20, 2026
09bc1b4
refactor(coderd/oauth2provider): rename validateRequestedScope to neg…
BobbyHo Aug 21, 2026
6fe6c71
test(coderd/oauth2provider): bind the wire-level scope reasons to the…
BobbyHo Aug 21, 2026
e296dda
refactor(coderd): log undecidable oauth2 scope coverage instead of re…
BobbyHo Aug 21, 2026
2760db5
fix(coderd/oauth2provider): name the stored allowlist when none of it…
BobbyHo Aug 21, 2026
5b2ca57
refactor(coderd/oauth2provider): reword the oauth2 scope rejection re…
BobbyHo Aug 21, 2026
90a6f83
docs: correct what the oauth2 authorize scope parameter promises
BobbyHo Aug 21, 2026
77654a1
test(coderd/oauth2provider): fold the no-allowlist guarantee into one…
BobbyHo Aug 21, 2026
dfdd33f
Merge branch 'plat479-2-negotiate-scope' into plat479-3-report-negoti…
BobbyHo Aug 22, 2026
ba8a123
Merge branch 'main' into plat479-2-negotiate-scope
BobbyHo Aug 22, 2026
bc40908
test(coderd): close the consent-page and state-echo test gaps
BobbyHo Aug 23, 2026
cb7df2e
fix(site/static): left-align the consent permission list
BobbyHo Aug 23, 2026
41e9f40
fix(coderd/oauth2provider): validate the callback scheme before any r…
BobbyHo Aug 23, 2026
a56cdac
fix(coderd/oauth2provider): replace callback query params instead of …
BobbyHo Aug 23, 2026
009962c
feat: say that the consent permission names are technical
BobbyHo Aug 23, 2026
f983335
fix: state unrestricted OAuth2 consent in its own field
BobbyHo Aug 23, 2026
81bbfb0
docs: trim OAuth2 scope negotiation comments
BobbyHo Aug 23, 2026
b7f88f0
Merge branch 'plat479-2-negotiate-scope' into plat479-3-report-negoti…
BobbyHo Aug 23, 2026
2a2e006
Merge branch 'main' into plat479-2-negotiate-scope
BobbyHo Aug 23, 2026
a11d42c
test(coderd/oauth2provider): pin the consent list semantics and the s…
BobbyHo Aug 23, 2026
eb37c2f
test(coderd/oauth2provider): cover the error redirect in the query-pa…
BobbyHo Aug 23, 2026
a5e3f94
fix(coderd/oauth2provider): answer 500 and log on an unusable callbac…
BobbyHo Aug 23, 2026
60cbe59
fix: refuse to render a consent page for a grant with no permissions
BobbyHo Aug 23, 2026
fdc9532
docs: document invalid_scope rejections on the authorize endpoint
BobbyHo Aug 23, 2026
e63ff3a
docs(coderd): trim the scope test comments
BobbyHo Aug 25, 2026
a9ade4a
Merge branch 'plat479-2-negotiate-scope' into plat479-3-report-negoti…
BobbyHo Aug 25, 2026
5589bf6
docs: trim the consent page and error redirect comments
BobbyHo Aug 25, 2026
24b4f46
docs(coderd): drop the godoc-style comments from the scope tests
BobbyHo Aug 25, 2026
b92b7f9
docs(coderd/oauth2provider): trim the authorize.go comments
BobbyHo Aug 25, 2026
e4cc41d
Merge branch 'plat479-2-negotiate-scope' into plat479-3-report-negoti…
BobbyHo Aug 25, 2026
20caa9c
docs(coderd): trim the scope reporting test comments
BobbyHo Aug 25, 2026
c7d3d53
docs(site): trim the consent page scope comments
BobbyHo Aug 25, 2026
98545a6
feat(coderd): mint OAuth2 tokens with the negotiated scope
BobbyHo Aug 15, 2026
641e45e
test(coderd/oauth2provider): cover the negotiated scope end to end
BobbyHo Aug 18, 2026
1a30a9c
feat(coderd/oauth2provider): report the granted scope in token responses
BobbyHo Aug 18, 2026
8b46823
refactor(coderd/oauth2provider): clarify the unmintable scope sentinel
BobbyHo Aug 18, 2026
da5b590
test(coderd/oauth2provider): derive the exchange query from authorize…
BobbyHo Aug 18, 2026
fc6eb77
docs: scope the OAuth2 refresh limitation to narrowing
BobbyHo Aug 18, 2026
589b8b8
docs(coderd): trim the negotiated scope comments
BobbyHo Aug 25, 2026
78fbab1
Merge branch 'main' into plat479-2-negotiate-scope
BobbyHo Aug 26, 2026
f675cf1
fix(site/static): make the whole consent page reachable by scrolling
BobbyHo Aug 27, 2026
6b5f01d
Merge branch 'plat479-3-report-negotiated-scope' into plat480-1-apply…
BobbyHo Aug 27, 2026
90821d8
docs: say the negotiated scope now bounds the issued token
BobbyHo Aug 27, 2026
72b8cb5
docs: annotate the token endpoint with the response it returns
BobbyHo Aug 27, 2026
b6f74c3
feat: re-check the app allowlist at OAuth2 code redemption
BobbyHo Aug 28, 2026
9f3193e
docs(coderd/oauth2provider): trim the allowlist re-check comments
BobbyHo Aug 28, 2026
9e98cef
fix(coderd): make OAuth2 code redemption single-use under concurrency
BobbyHo Aug 28, 2026
ceb3997
Update coderd/oauth2provider/authorize.go
BobbyHo Aug 31, 2026
2cd9b60
Update coderd/oauth2provider/authorize.go
BobbyHo Aug 31, 2026
d160bda
docs(coderd/oauth2provider): trim the errNoGrantableScope comment
BobbyHo Aug 31, 2026
b60eee6
refactor(coderd/oauth2provider): canonicalize scopes before the catal…
BobbyHo Aug 31, 2026
4732d1f
refactor(coderd/oauth2provider): canonicalize the allowlist in one pass
BobbyHo Aug 31, 2026
03df6a9
test(coderd/rbac): pin the field sets scope coverage reads
BobbyHo Aug 31, 2026
a2d2856
docs(coderd/rbac): trim the TestCoverageModelFields comment
BobbyHo Aug 31, 2026
d83636b
Merge branch 'plat479-2-negotiate-scope' into plat479-3-report-negoti…
BobbyHo Aug 31, 2026
037e744
Merge remote-tracking branch 'origin/main' into plat479-3-report-nego…
BobbyHo Aug 31, 2026
cd35b94
Merge branch 'plat479-3-report-negotiated-scope' into plat480-1-apply…
BobbyHo Aug 31, 2026
508d09e
Merge branch 'plat480-1-apply-negotiated-scope' into plat480-2-stale-…
BobbyHo Aug 31, 2026
fc40ac3
Merge branch 'plat480-2-stale-scope-recheck' into plat480-3-single-us…
BobbyHo Aug 31, 2026
433e449
docs(coderd/oauth2provider): trim scope negotiation comments
BobbyHo Aug 31, 2026
5dffb74
Merge branch 'plat479-3-report-negotiated-scope' into plat480-1-apply…
BobbyHo Aug 31, 2026
6aa7510
docs(coderd/oauth2provider): trim scope negotiation comments
BobbyHo Aug 31, 2026
a1eae58
Merge branch 'plat480-1-apply-negotiated-scope' into plat480-2-stale-…
BobbyHo Aug 31, 2026
e1ea400
docs(coderd/oauth2provider): trim scope negotiation comments
BobbyHo Aug 31, 2026
52567a4
Merge branch 'plat480-2-stale-scope-recheck' into plat480-3-single-us…
BobbyHo Aug 31, 2026
8efc783
docs(coderd/oauth2provider): trim the single-use code comment
BobbyHo Aug 31, 2026
35ce008
Merge branch 'main' into plat479-3-report-negotiated-scope
BobbyHo Aug 31, 2026
48d9c7f
fix(coderd/oauth2provider): return server_error for undecidable scope…
BobbyHo Sep 1, 2026
c8a3754
Merge branch 'plat479-3-report-negotiated-scope' into plat480-1-apply…
BobbyHo Sep 1, 2026
339aa34
Merge branch 'plat480-1-apply-negotiated-scope' into plat480-2-stale-…
BobbyHo Sep 1, 2026
6b29b13
Merge branch 'main' into plat480-1-apply-negotiated-scope
BobbyHo Sep 1, 2026
976335d
fix: answer invalid_grant for an unmintable stored scope
BobbyHo Sep 1, 2026
5ebc706
Merge branch 'plat480-1-apply-negotiated-scope' into plat480-2-stale-…
BobbyHo Sep 1, 2026
4a31118
Merge remote-tracking branch 'origin/main' into plat480-2-stale-scope…
BobbyHo Sep 2, 2026
cf7ddb7
Merge branch 'plat480-2-stale-scope-recheck' into plat480-3-single-us…
BobbyHo Sep 2, 2026
c54ccdb
fix(coderd): address the allowlist re-check review
BobbyHo Sep 2, 2026
d5c8a1c
docs(coderd): simplify the scope check comments
BobbyHo Sep 2, 2026
bb574d0
Merge branch 'plat480-2-stale-scope-recheck' into plat480-3-single-us…
BobbyHo Sep 2, 2026
d9d032d
test(coderd): cover replay and post-redemption state for single-use c…
BobbyHo Sep 3, 2026
8acedcd
Merge remote-tracking branch 'origin/main' into plat480-3-single-use-…
BobbyHo Sep 4, 2026
ec80733
test(coderd/oauth2provider): assert the winner's token survives a ref…
BobbyHo Sep 4, 2026
98e6191
refactor(coderd): fold the duplicated app code delete into one query
BobbyHo Sep 4, 2026
15cc66f
docs(coderd): say why the code is deleted, and where single use can b…
BobbyHo Sep 4, 2026
b64f111
test(coderd/oauth2provider): enforce the redemption overlap in the test
BobbyHo Sep 4, 2026
d5df1f6
Merge branch 'main' into plat480-3-single-use-code
BobbyHo Sep 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 2 additions & 9 deletions coderd/database/dbauthz/dbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -2401,15 +2401,8 @@ func (q *querier) DeleteOAuth2ProviderAppByID(ctx context.Context, id uuid.UUID)
return q.db.DeleteOAuth2ProviderAppByID(ctx, id)
}

func (q *querier) DeleteOAuth2ProviderAppCodeByID(ctx context.Context, id uuid.UUID) error {
code, err := q.db.GetOAuth2ProviderAppCodeByID(ctx, id)
if err != nil {
return err
}
if err := q.authorizeContext(ctx, policy.ActionDelete, code); err != nil {
return err
}
return q.db.DeleteOAuth2ProviderAppCodeByID(ctx, id)
func (q *querier) DeleteOAuth2ProviderAppCodeByID(ctx context.Context, id uuid.UUID) (database.OAuth2ProviderAppCode, error) {
return fetchAndQuery(q.log, q.auth, policy.ActionDelete, q.db.GetOAuth2ProviderAppCodeByID, q.db.DeleteOAuth2ProviderAppCodeByID)(ctx, id)
}

func (q *querier) DeleteOAuth2ProviderAppCodesByAppAndUserID(ctx context.Context, arg database.DeleteOAuth2ProviderAppCodesByAppAndUserIDParams) error {
Expand Down
2 changes: 1 addition & 1 deletion coderd/database/dbauthz/dbauthz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6316,7 +6316,7 @@ func (s *MethodTestSuite) TestOAuth2ProviderAppCodes() {
AppID: app.ID,
UserID: user.ID,
})
check.Args(code.ID).Asserts(code, policy.ActionDelete)
check.Args(code.ID).Asserts(code, policy.ActionDelete).Returns(code)
}))
s.Run("DeleteOAuth2ProviderAppCodesByAppAndUserID", s.Subtest(func(db database.Store, check *expects) {
dbtestutil.DisableForeignKeysAndTriggers(s.T(), db)
Expand Down
6 changes: 3 additions & 3 deletions coderd/database/dbmetrics/querymetrics.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions coderd/database/dbmock/dbmock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions coderd/database/querier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19426,6 +19426,35 @@ func TestOAuth2ProviderScopeNotEmpty(t *testing.T) {
})
}

func TestSingleUseDelete(t *testing.T) {
t.Parallel()
if testing.Short() {
t.SkipNow()
}

// Callers rely on this delete to arbitrate single use, so a delete that
// removed nothing must report sql.ErrNoRows rather than succeed.
t.Run("OAuth2ProviderAppCode", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
ctx := testutil.Context(t, testutil.WaitLong)

user := dbgen.User(t, db, database.User{})
app := dbgen.OAuth2ProviderApp(t, db, database.OAuth2ProviderApp{})
code := dbgen.OAuth2ProviderAppCode(t, db, database.OAuth2ProviderAppCode{
AppID: app.ID,
UserID: user.ID,
})

deleted, err := db.DeleteOAuth2ProviderAppCodeByID(ctx, code.ID)
require.NoError(t, err)
require.Equal(t, code, deleted)

_, err = db.DeleteOAuth2ProviderAppCodeByID(ctx, code.ID)
require.ErrorIs(t, err, sql.ErrNoRows)
})
}

func TestGetUnpricedAIModelsSince(t *testing.T) {
t.Parallel()

Expand Down
33 changes: 28 additions & 5 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 9 additions & 2 deletions coderd/database/queries/oauth2.sql
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,15 @@ INSERT INTO oauth2_provider_app_codes (
$13
) RETURNING *;

-- name: DeleteOAuth2ProviderAppCodeByID :exec
DELETE FROM oauth2_provider_app_codes WHERE id = $1;
-- name: DeleteOAuth2ProviderAppCodeByID :one
-- Returns sql.ErrNoRows when the delete removed nothing, so a caller can make
-- this the arbiter of single use. A prior read cannot arbitrate: its result is
-- stale the moment it returns.
--
-- Concurrent deletes are arbitrated at READ COMMITTED, the default isolation
-- level: the second transaction waits for the first, then removes nothing.
-- SERIALIZABLE would abort and retry it instead.
DELETE FROM oauth2_provider_app_codes WHERE id = $1 RETURNING *;

-- name: DeleteOAuth2ProviderAppCodesByAppAndUserID :exec
DELETE FROM oauth2_provider_app_codes WHERE app_id = $1 AND user_id = $2;
Expand Down
11 changes: 9 additions & 2 deletions coderd/oauth2provider/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ func revokeOAuth2CodeOnPKCEFailure(ctx context.Context, db database.Store, codeI
defer cancel()

//nolint:gocritic // OAuth2 system context, no authenticated user during token exchange
if err := db.DeleteOAuth2ProviderAppCodeByID(dbauthz.AsSystemOAuth2(revokeCtx), codeID); err != nil && !errors.Is(err, sql.ErrNoRows) {
if _, err := db.DeleteOAuth2ProviderAppCodeByID(dbauthz.AsSystemOAuth2(revokeCtx), codeID); err != nil && !errors.Is(err, sql.ErrNoRows) {
if rlogger := loggermw.RequestLoggerFromContext(ctx); rlogger != nil {
rlogger.WithFields(slog.F("oauth2_pkce_failure_code_revoke_error", err.Error()))
}
Expand Down Expand Up @@ -497,7 +497,14 @@ func authorizationCodeGrant(ctx context.Context, db database.Store, logger slog.

err = db.InTx(func(tx database.Store) error {
Comment thread
BobbyHo marked this conversation as resolved.
ctx := dbauthz.As(ctx, actor)
err = tx.DeleteOAuth2ProviderAppCodeByID(ctx, dbCode.ID)
// Spend the code. RFC 6749 §10.5 requires single use: a code that
// survived its own redemption could be replayed by anyone who
// intercepted it. Spending it inside the transaction ties it to the
// token, so a later failure leaves the code redeemable.
_, err := tx.DeleteOAuth2ProviderAppCodeByID(ctx, dbCode.ID)
if errors.Is(err, sql.ErrNoRows) {
return errBadCode
}
if err != nil {
return xerrors.Errorf("delete oauth2 app code: %w", err)
}
Expand Down
147 changes: 144 additions & 3 deletions coderd/oauth2provider/tokens_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ import (
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"testing"
"time"

"github.com/google/uuid"
"github.com/stretchr/testify/require"
"golang.org/x/xerrors"

"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database"
Expand Down Expand Up @@ -221,6 +224,124 @@ func TestOAuth2TokenExchangeScope(t *testing.T) {
})
}

// The redemptions race rather than run in sequence: a sequential pair passes
// whether or not the delete arbitrates single use. barrierStore makes that
// overlap deterministic instead of probabilistic.
func TestOAuth2TokenExchangeSingleUse(t *testing.T) {
t.Parallel()

db, pubsub := dbtestutil.NewDB(t)
var reads sync.WaitGroup
reads.Add(2)
client := coderdtest.New(t, &coderdtest.Options{
Database: barrierStore{Store: db, reads: &reads},
Pubsub: pubsub,
})
coderdtest.CreateFirstUser(t, client)
ctx := testutil.Context(t, testutil.WaitLong)

app := seedAppWithSecret(t, db, sql.NullString{})
code, verifier := authorizeCode(ctx, t, client, app.ID.String(), "")
form := tokenExchangeForm(app, code, verifier)

type exchange struct {
status int
body string
err error
}

redeem := func() exchange {
status, body, err := tryTokenRequest(ctx, t, client, form)
Comment thread
BobbyHo marked this conversation as resolved.
return exchange{status: status, body: body, err: err}
}

other := make(chan exchange, 1)
go func() { other <- redeem() }()
Comment thread
BobbyHo marked this conversation as resolved.
results := []exchange{redeem(), <-other}

var winner codersdk.OAuth2TokenResponse
var minted, rejected int
for _, result := range results {
require.NoError(t, result.err)
switch result.status {
case http.StatusOK:
winner = requireTokenResponse(t, result.status, result.body)
minted++
case http.StatusBadRequest:
require.Contains(t, result.body, string(codersdk.OAuth2ErrorCodeInvalidGrant), result.body)
rejected++
default:
t.Fatalf("unexpected status %d: %s", result.status, result.body)
}
}
require.Equal(t, 1, minted, "a code may mint at most one token")
require.Equal(t, 1, rejected)
requireTokenAuthenticates(ctx, t, client, winner.AccessToken)
}

// The ordinary replay: a client retries a redemption whose answer it never saw.
// Here the first read refuses it. The race test cannot cover this path
// deterministically, since which read or delete arbitrates there depends on
// scheduling.
func TestOAuth2TokenExchangeReplay(t *testing.T) {
Comment thread
BobbyHo marked this conversation as resolved.
t.Parallel()

db, pubsub := dbtestutil.NewDB(t)
client := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
})
coderdtest.CreateFirstUser(t, client)
ctx := testutil.Context(t, testutil.WaitLong)

app := seedAppWithSecret(t, db, sql.NullString{})
code, verifier := authorizeCode(ctx, t, client, app.ID.String(), "")
token := exchangeCode(ctx, t, client, app, code, verifier)

status, body := postTokenRequest(ctx, t, client, tokenExchangeForm(app, code, verifier))
requireTokenGrantError(t, status, body)
requireTokenAuthenticates(ctx, t, client, token.AccessToken)
}

// barrierStore holds each redemption at its code read until every redemption
// has read, so both reach the delete with the same stale view. Starting the
// requests together is not enough on its own: nothing stops one handler from
// committing before the other reads, and the read then refuses the second
// before the delete ever arbitrates.
//
// InTx hands its closure a fresh Store, so this intercepts only the read that
// precedes the transaction, which is the one that fixes the interleaving.
type barrierStore struct {
database.Store
reads *sync.WaitGroup
}

// GetOAuth2ProviderAppCodeByPrefix has one production caller, the code read in
// authorizationCodeGrant, so every arrival here is a redemption.
func (s barrierStore) GetOAuth2ProviderAppCodeByPrefix(ctx context.Context, prefix []byte) (database.OAuth2ProviderAppCode, error) {
Comment thread
BobbyHo marked this conversation as resolved.
code, err := s.Store.GetOAuth2ProviderAppCodeByPrefix(ctx, prefix)
s.reads.Done()
s.reads.Wait()
return code, err
}

// requireTokenAuthenticates asserts the accepted redemption's own credential
// still works. Callers grant coder:all so the probed endpoint is in scope.
//
// Row counts cannot show this: the grant deletes whatever key already holds
// the name it is about to write, and oauth2_provider_app_tokens cascades on
// that delete, so the rows converge on one key and one token however many
// redemptions succeed. Only the winner's token separates "its key survived"
// from "a second redemption rotated it out".
func requireTokenAuthenticates(ctx context.Context, t *testing.T, client *codersdk.Client, accessToken string) {
t.Helper()

asApp := codersdk.New(client.URL)
asApp.SetSessionToken(accessToken)
_, err := asApp.User(ctx, codersdk.Me)
require.NoError(t, err, "a refused redemption must leave the accepted one's token usable")
}

// appWithSecret is seeded directly because the management API registers no
// scope allowlist, and the allowlist is what these tests turn.
type appWithSecret struct {
Expand Down Expand Up @@ -401,15 +522,35 @@ func exchangeCode(ctx context.Context, t *testing.T, client *codersdk.Client, ap
func postTokenRequest(ctx context.Context, t *testing.T, client *codersdk.Client, form url.Values) (int, string) {
t.Helper()

req, err := http.NewRequestWithContext(ctx, http.MethodPost, client.URL.String()+"/oauth2/tokens", strings.NewReader(form.Encode()))
status, body, err := tryTokenRequest(ctx, t, client, form)
require.NoError(t, err)
return status, body
}

// tryTokenRequest returns the request error instead of asserting on it, so a
// caller on a spawned goroutine can carry it back to the test goroutine.
// require there runs runtime.Goexit, which skips whatever the goroutine still
// owed its parent.
func tryTokenRequest(ctx context.Context, t *testing.T, client *codersdk.Client, form url.Values) (int, string, error) {
t.Helper()

req, err := http.NewRequestWithContext(ctx, http.MethodPost, client.URL.String()+"/oauth2/tokens", strings.NewReader(form.Encode()))
if err != nil {
return 0, "", xerrors.Errorf("build token request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
if err != nil {
return 0, "", xerrors.Errorf("post token request: %w", err)
}
defer resp.Body.Close()

return resp.StatusCode, readBody(t, resp)
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, "", xerrors.Errorf("read token response: %w", err)
}
return resp.StatusCode, string(body), nil
}

func requireTokenResponse(t *testing.T, status int, body string) codersdk.OAuth2TokenResponse {
Expand Down
Loading