Skip to content

Commit f519d23

Browse files
committed
feat(oauth2): add RFC 8707 resource indicators and audience validation
Implements RFC 8707 Resource Indicators for OAuth2 provider to enable proper audience validation and token binding for multi-tenant scenarios. Key changes: - Add resource parameter support to authorization and token endpoints - Implement server-side audience validation for opaque tokens - Add database fields: ResourceUri (codes) and Audience (tokens) - Add comprehensive resource parameter validation logic - Add cross-resource audience validation in API middleware - Add extensive test coverage for RFC 8707 scenarios - Enhance PKCE implementation with timing attack protection This enables OAuth2 clients to specify target resource servers and prevents token abuse across different Coder deployments through proper audience binding. Change-Id: I3924cb2139e837e3ac0b0bd40a5aeb59637ebc1b Signed-off-by: Thomas Kosiewski <tk@coder.com>
1 parent f211bdd commit f519d23

File tree

13 files changed

+569
-7
lines changed

13 files changed

+569
-7
lines changed

CLAUDE.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ Read [cursor rules](.cursorrules).
8989
- Format: `{number}_{description}.{up|down}.sql`
9090
- Number must be unique and sequential
9191
- Always include both up and down migrations
92+
- **Use helper scripts**:
93+
- `./coderd/database/migrations/create_migration.sh "migration name"` - Creates new migration files
94+
- `./coderd/database/migrations/fix_migration_numbers.sh` - Renumbers migrations to avoid conflicts
95+
- `./coderd/database/migrations/create_fixture.sh "fixture name"` - Creates test fixtures for migrations
9296

9397
2. **Update database queries**:
9498
- MUST DO! Any changes to database - adding queries, modifying queries should be done in the `coderd/database/queries/*.sql` files
@@ -125,6 +129,29 @@ Read [cursor rules](.cursorrules).
125129
4. Run `make gen` again
126130
5. Run `make lint` to catch any remaining issues
127131

132+
### In-Memory Database Testing
133+
134+
When adding new database fields:
135+
136+
- **CRITICAL**: Update `coderd/database/dbmem/dbmem.go` in-memory implementations
137+
- The `Insert*` functions must include ALL new fields, not just basic ones
138+
- Common issue: Tests pass with real database but fail with in-memory database due to missing field mappings
139+
- Always verify in-memory database functions match the real database schema after migrations
140+
141+
Example pattern:
142+
143+
```go
144+
// In dbmem.go - ensure ALL fields are included
145+
code := database.OAuth2ProviderAppCode{
146+
ID: arg.ID,
147+
CreatedAt: arg.CreatedAt,
148+
// ... existing fields ...
149+
ResourceUri: arg.ResourceUri, // New field
150+
CodeChallenge: arg.CodeChallenge, // New field
151+
CodeChallengeMethod: arg.CodeChallengeMethod, // New field
152+
}
153+
```
154+
128155
## Architecture
129156

130157
### Core Components
@@ -209,6 +236,12 @@ When working on OAuth2 provider features:
209236
- Avoid dependency on referer headers for security decisions
210237
- Support proper state parameter validation
211238

239+
6. **RFC 8707 Resource Indicators**:
240+
- Store resource parameters in database for server-side validation (opaque tokens)
241+
- Validate resource consistency between authorization and token requests
242+
- Support audience validation in refresh token flows
243+
- Resource parameter is optional but must be consistent when provided
244+
212245
### OAuth2 Error Handling Pattern
213246

214247
```go
@@ -265,3 +298,6 @@ Always run the full test suite after OAuth2 changes:
265298
4. **Missing newlines** - Ensure files end with newline character
266299
5. **Tests passing locally but failing in CI** - Check if `dbmem` implementation needs updating
267300
6. **OAuth2 endpoints returning wrong error format** - Ensure OAuth2 endpoints return RFC 6749 compliant errors
301+
7. **OAuth2 tests failing but scripts working** - Check in-memory database implementations in `dbmem.go`
302+
8. **Resource indicator validation failing** - Ensure database stores and retrieves resource parameters correctly
303+
9. **PKCE tests failing** - Verify both authorization code storage and token exchange handle PKCE fields

coderd/database/dbauthz/dbauthz.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2165,6 +2165,25 @@ func (q *querier) GetOAuth2ProviderAppSecretsByAppID(ctx context.Context, appID
21652165
return q.db.GetOAuth2ProviderAppSecretsByAppID(ctx, appID)
21662166
}
21672167

2168+
func (q *querier) GetOAuth2ProviderAppTokenByAPIKeyID(ctx context.Context, apiKeyID string) (database.OAuth2ProviderAppToken, error) {
2169+
token, err := q.db.GetOAuth2ProviderAppTokenByAPIKeyID(ctx, apiKeyID)
2170+
if err != nil {
2171+
return database.OAuth2ProviderAppToken{}, err
2172+
}
2173+
2174+
// Get the associated API key to check ownership
2175+
apiKey, err := q.db.GetAPIKeyByID(ctx, token.APIKeyID)
2176+
if err != nil {
2177+
return database.OAuth2ProviderAppToken{}, err
2178+
}
2179+
2180+
if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceOauth2AppCodeToken.WithOwner(apiKey.UserID.String())); err != nil {
2181+
return database.OAuth2ProviderAppToken{}, err
2182+
}
2183+
2184+
return token, nil
2185+
}
2186+
21682187
func (q *querier) GetOAuth2ProviderAppTokenByPrefix(ctx context.Context, hashPrefix []byte) (database.OAuth2ProviderAppToken, error) {
21692188
token, err := q.db.GetOAuth2ProviderAppTokenByPrefix(ctx, hashPrefix)
21702189
if err != nil {

coderd/database/dbauthz/dbauthz_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5370,6 +5370,21 @@ func (s *MethodTestSuite) TestOAuth2ProviderAppTokens() {
53705370
})
53715371
check.Args(token.HashPrefix).Asserts(rbac.ResourceOauth2AppCodeToken.WithOwner(user.ID.String()), policy.ActionRead)
53725372
}))
5373+
s.Run("GetOAuth2ProviderAppTokenByAPIKeyID", s.Subtest(func(db database.Store, check *expects) {
5374+
user := dbgen.User(s.T(), db, database.User{})
5375+
key, _ := dbgen.APIKey(s.T(), db, database.APIKey{
5376+
UserID: user.ID,
5377+
})
5378+
app := dbgen.OAuth2ProviderApp(s.T(), db, database.OAuth2ProviderApp{})
5379+
secret := dbgen.OAuth2ProviderAppSecret(s.T(), db, database.OAuth2ProviderAppSecret{
5380+
AppID: app.ID,
5381+
})
5382+
token := dbgen.OAuth2ProviderAppToken(s.T(), db, database.OAuth2ProviderAppToken{
5383+
AppSecretID: secret.ID,
5384+
APIKeyID: key.ID,
5385+
})
5386+
check.Args(token.APIKeyID).Asserts(rbac.ResourceOauth2AppCodeToken.WithOwner(user.ID.String()), policy.ActionRead).Returns(token)
5387+
}))
53735388
s.Run("DeleteOAuth2ProviderAppTokensByAppAndUserID", s.Subtest(func(db database.Store, check *expects) {
53745389
dbtestutil.DisableForeignKeysAndTriggers(s.T(), db)
53755390
user := dbgen.User(s.T(), db, database.User{})

coderd/database/dbmem/dbmem.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4050,6 +4050,19 @@ func (q *FakeQuerier) GetOAuth2ProviderAppSecretsByAppID(_ context.Context, appI
40504050
return []database.OAuth2ProviderAppSecret{}, sql.ErrNoRows
40514051
}
40524052

4053+
func (q *FakeQuerier) GetOAuth2ProviderAppTokenByAPIKeyID(_ context.Context, apiKeyID string) (database.OAuth2ProviderAppToken, error) {
4054+
q.mutex.Lock()
4055+
defer q.mutex.Unlock()
4056+
4057+
for _, token := range q.oauth2ProviderAppTokens {
4058+
if token.APIKeyID == apiKeyID {
4059+
return token, nil
4060+
}
4061+
}
4062+
4063+
return database.OAuth2ProviderAppToken{}, sql.ErrNoRows
4064+
}
4065+
40534066
func (q *FakeQuerier) GetOAuth2ProviderAppTokenByPrefix(_ context.Context, hashPrefix []byte) (database.OAuth2ProviderAppToken, error) {
40544067
q.mutex.Lock()
40554068
defer q.mutex.Unlock()

coderd/database/dbmetrics/querymetrics.go

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/database/dbmock/dbmock.go

Lines changed: 15 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/database/querier.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/database/queries.sql.go

Lines changed: 20 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/database/queries/oauth2.sql

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,9 @@ INSERT INTO oauth2_provider_app_tokens (
136136
-- name: GetOAuth2ProviderAppTokenByPrefix :one
137137
SELECT * FROM oauth2_provider_app_tokens WHERE hash_prefix = $1;
138138

139+
-- name: GetOAuth2ProviderAppTokenByAPIKeyID :one
140+
SELECT * FROM oauth2_provider_app_tokens WHERE api_key_id = $1;
141+
139142
-- name: GetOAuth2ProviderAppsByUserID :many
140143
SELECT
141144
COUNT(DISTINCT oauth2_provider_app_tokens.id) as token_count,

coderd/httpmw/apikey.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"golang.org/x/oauth2"
1919
"golang.org/x/xerrors"
2020

21+
"cdr.dev/slog"
2122
"github.com/coder/coder/v2/coderd/database"
2223
"github.com/coder/coder/v2/coderd/database/dbauthz"
2324
"github.com/coder/coder/v2/coderd/database/dbtime"
@@ -240,6 +241,17 @@ func ExtractAPIKey(rw http.ResponseWriter, r *http.Request, cfg ExtractAPIKeyCon
240241
})
241242
}
242243

244+
// Validate OAuth2 provider app token audience (RFC 8707) if applicable
245+
if key.LoginType == database.LoginTypeOAuth2ProviderApp {
246+
if err := validateOAuth2ProviderAppTokenAudience(ctx, cfg.DB, *key, r); err != nil {
247+
// Log the detailed error for debugging but don't expose it to the client
248+
cfg.Logger.Info(ctx, "OAuth2 token audience validation failed", slog.Error(err))
249+
return optionalWrite(http.StatusForbidden, codersdk.Response{
250+
Message: "Token audience validation failed",
251+
})
252+
}
253+
}
254+
243255
// We only check OIDC stuff if we have a valid APIKey. An expired key means we don't trust the requestor
244256
// really is the user whose key they have, and so we shouldn't be doing anything on their behalf including possibly
245257
// refreshing the OIDC token.
@@ -446,6 +458,47 @@ func ExtractAPIKey(rw http.ResponseWriter, r *http.Request, cfg ExtractAPIKeyCon
446458
return key, &actor, true
447459
}
448460

461+
// validateOAuth2ProviderAppTokenAudience validates that an OAuth2 provider app token
462+
// is being used with the correct audience/resource server (RFC 8707).
463+
func validateOAuth2ProviderAppTokenAudience(ctx context.Context, db database.Store, key database.APIKey, r *http.Request) error {
464+
// Get the OAuth2 provider app token to check its audience
465+
//nolint:gocritic // System needs to access token for audience validation
466+
token, err := db.GetOAuth2ProviderAppTokenByAPIKeyID(dbauthz.AsSystemRestricted(ctx), key.ID)
467+
if err != nil {
468+
return xerrors.Errorf("failed to get OAuth2 token: %w", err)
469+
}
470+
471+
// If no audience is set, allow the request (for backward compatibility)
472+
if !token.Audience.Valid || token.Audience.String == "" {
473+
return nil
474+
}
475+
476+
// Extract the expected audience from the request
477+
expectedAudience := extractExpectedAudience(r)
478+
479+
// Validate that the token's audience matches the expected audience
480+
if token.Audience.String != expectedAudience {
481+
return xerrors.Errorf("token audience %q does not match expected audience %q",
482+
token.Audience.String, expectedAudience)
483+
}
484+
485+
return nil
486+
}
487+
488+
// extractExpectedAudience determines the expected audience for the current request.
489+
// This should match the resource parameter used during authorization.
490+
func extractExpectedAudience(r *http.Request) string {
491+
// For MCP compliance, the audience should be the canonical URI of the resource server
492+
// This typically matches the access URL of the Coder deployment
493+
scheme := "https"
494+
if r.TLS == nil {
495+
scheme = "http"
496+
}
497+
498+
// Use the Host header to construct the canonical audience URI
499+
return fmt.Sprintf("%s://%s", scheme, r.Host)
500+
}
501+
449502
// UserRBACSubject fetches a user's rbac.Subject from the database. It pulls all roles from both
450503
// site and organization scopes. It also pulls the groups, and the user's status.
451504
func UserRBACSubject(ctx context.Context, db database.Store, userID uuid.UUID, scope rbac.ExpandableScope) (rbac.Subject, database.UserStatus, error) {

coderd/identityprovider/authorize.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,15 @@ func extractAuthorizeParams(r *http.Request, callbackURL *url.URL) (authorizePar
4545
codeChallenge: p.String(vals, "", "code_challenge"),
4646
codeChallengeMethod: p.String(vals, "", "code_challenge_method"),
4747
}
48+
// Validate resource indicator syntax (RFC 8707): must be absolute URI without fragment
49+
if params.resource != "" {
50+
if u, err := url.Parse(params.resource); err != nil || u.Scheme == "" || u.Fragment != "" {
51+
p.Errors = append(p.Errors, codersdk.ValidationError{
52+
Field: "resource",
53+
Detail: "must be an absolute URI without fragment",
54+
})
55+
}
56+
}
4857

4958
p.ErrorExcessParams(vals)
5059
if len(p.Errors) > 0 {

coderd/identityprovider/tokens.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ var (
3434
errBadToken = xerrors.New("Invalid token")
3535
// errInvalidPKCE means the PKCE verification failed.
3636
errInvalidPKCE = xerrors.New("invalid code_verifier")
37+
// errInvalidResource means the resource parameter validation failed.
38+
errInvalidResource = xerrors.New("invalid resource parameter")
3739
)
3840

3941
type tokenParams struct {
@@ -74,6 +76,15 @@ func extractTokenParams(r *http.Request, callbackURL *url.URL) (tokenParams, []c
7476
codeVerifier: p.String(vals, "", "code_verifier"),
7577
resource: p.String(vals, "", "resource"),
7678
}
79+
// Validate resource parameter syntax (RFC 8707): must be absolute URI without fragment
80+
if params.resource != "" {
81+
if u, err := url.Parse(params.resource); err != nil || u.Scheme == "" || u.Fragment != "" {
82+
p.Errors = append(p.Errors, codersdk.ValidationError{
83+
Field: "resource",
84+
Detail: "must be an absolute URI without fragment",
85+
})
86+
}
87+
}
7788

7889
p.ErrorExcessParams(vals)
7990
if len(p.Errors) > 0 {
@@ -150,6 +161,10 @@ func Tokens(db database.Store, lifetimes codersdk.SessionLifetime) http.HandlerF
150161
httpapi.WriteOAuth2Error(ctx, rw, http.StatusBadRequest, "invalid_grant", "The PKCE code verifier is invalid")
151162
return
152163
}
164+
if errors.Is(err, errInvalidResource) {
165+
httpapi.WriteOAuth2Error(ctx, rw, http.StatusBadRequest, "invalid_target", "The resource parameter is invalid")
166+
return
167+
}
153168
if errors.Is(err, errBadToken) {
154169
httpapi.WriteOAuth2Error(ctx, rw, http.StatusBadRequest, "invalid_grant", "The refresh token is invalid or expired")
155170
return
@@ -226,6 +241,20 @@ func authorizationCodeGrant(ctx context.Context, db database.Store, app database
226241
}
227242
}
228243

244+
// Verify resource parameter consistency (RFC 8707)
245+
if dbCode.ResourceUri.Valid && dbCode.ResourceUri.String != "" {
246+
// Resource was specified during authorization - it must match in token request
247+
if params.resource == "" {
248+
return oauth2.Token{}, errInvalidResource
249+
}
250+
if params.resource != dbCode.ResourceUri.String {
251+
return oauth2.Token{}, errInvalidResource
252+
}
253+
} else if params.resource != "" {
254+
// Resource was not specified during authorization but is now provided
255+
return oauth2.Token{}, errInvalidResource
256+
}
257+
229258
// Generate a refresh token.
230259
refreshToken, err := GenerateSecret()
231260
if err != nil {
@@ -332,6 +361,14 @@ func refreshTokenGrant(ctx context.Context, db database.Store, app database.OAut
332361
return oauth2.Token{}, errBadToken
333362
}
334363

364+
// Verify resource parameter consistency for refresh tokens (RFC 8707)
365+
if params.resource != "" {
366+
// If resource is provided in refresh request, it must match the original token's audience
367+
if !dbToken.Audience.Valid || dbToken.Audience.String != params.resource {
368+
return oauth2.Token{}, errInvalidResource
369+
}
370+
}
371+
335372
// Grab the user roles so we can perform the refresh as the user.
336373
//nolint:gocritic // There is no user yet so we must use the system.
337374
prevKey, err := db.GetAPIKeyByID(dbauthz.AsSystemRestricted(ctx), dbToken.APIKeyID)

0 commit comments

Comments
 (0)