Files
coder/coderd/oauth2_security_test.go
T
Bobby Ho fbac602456 feat!: add admin-controlled dynamic client registration toggle (#27316)
`POST /oauth2/register` (RFC 7591 Dynamic Client Registration) has
exactly one gate today: `ExperimentOAuth2`, a static, process-lifetime
flag that wraps the entire `/oauth2/*` route tree as an all-or-nothing
switch. That flag is scheduled for removal at GA, which would leave DCR
with zero admin control at all once it is gone.

Add a persistent, DCR-specific `oauth2_dcr_enabled` deployment setting,
independent of the experiment system, so admin control over DCR survives
GA. `POST /oauth2/register` checks the flag and rejects new
registrations with an RFC 7591-shaped `403` when disabled; discovery
metadata (`GET /.well-known/oauth-authorization-server`) conditionally
omits `registration_endpoint`. A new audited `GET`/`PUT
/api/v2/oauth2-provider/settings` endpoint lets an owner toggle it live,
no restart required. The setting defaults to disabled, matching the
canonical design proposal; disabling only stops new self-registrations,
clients that already registered continue to authorize and exchange
tokens normally.

Address issue described in
[ENG-3056](https://linear.app/codercom/issue/ENG-3056/oauth2-dcr-admin-configurable-enabledisable).

## Where this sits in the request path

```mermaid
sequenceDiagram
    autonumber
    participant A as Admin
    participant S as coderd
    participant DB as site_configs<br/>(oauth2_dcr_enabled)
    participant C as OAuth2/MCP Client

    Note over A,S: Admin toggles DCR (new)
    A->>S: PUT /api/v2/oauth2-provider/settings<br/>{dynamic_client_registration_enabled: false}
    S->>S: authorizeContext(ActionUpdate, ResourceDeploymentConfig)
    S->>DB: UPSERT oauth2_dcr_enabled = false
    S-->>A: 200 OK (audited)

    Note over C,S: Client discovery + registration afterward
    C->>S: GET /.well-known/oauth-authorization-server
    S->>DB: GetOAuth2DCREnabled (system ctx, every request, no cache)
    DB-->>S: false
    S-->>C: 200 metadata, registration_endpoint omitted

    C->>S: POST /oauth2/register
    S->>DB: GetOAuth2DCREnabled (system ctx, every request, no cache)
    DB-->>S: false
    S-->>C: 403 invalid_request,<br/>"Dynamic client registration is disabled"

    Note over C,S: A client that registered before the change is unaffected
    C->>S: GET /oauth2/authorize?client_id=...
    Note over S: no DCR-enabled check on this path
    S-->>C: 200 (proceeds normally)

    C->>S: PUT/DELETE /oauth2/clients/{client_id} (RFC 7592 self-management)
    Note over S: no DCR-enabled check on this path either
    S-->>C: 200 (proceeds normally)
```

## Files changed: manual vs. generated

Reviewers should focus on the **manual** files. The **generated** ones
are `make gen` output that follows mechanically from the manual changes
and don't need direct review.

<details>
<summary><b>Manual files (26)</b> — click to expand, grouped the same
way as "Suggested review order" below</summary>

**1. Database**

| File | What changed |
|---|---|
| `coderd/database/queries/siteconfig.sql` | New
`GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled` query pair on the
existing generic `site_configs` table. No schema change. |
| `coderd/database/dbauthz/dbauthz.go` | RBAC check
(`rbac.ResourceDeploymentConfig`) on the two new query methods; extends
the `subjectSystemOAuth2` system-actor role with read-only
`ResourceDeploymentConfig` access, needed so the public
discovery/registration endpoints can read the flag via
`dbauthz.AsSystemOAuth2`. |
| `coderd/database/dbauthz/dbauthz_test.go` | RBAC assertion coverage
for `GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled` in the
method-coverage test suite. |

**2. Request gating (the actual feature)**

| File | What changed |
|---|---|
| `coderd/oauth2provider/registration.go` | The actual gate:
`CreateDynamicClientRegistration` reads the flag first and returns an
RFC 7591-shaped `403` when disabled (defaults disabled if never
configured). |
| `coderd/oauth2provider/registration_test.go` | New unit test,
`TestCreateDynamicClientRegistration_DCREnabled`: calls the handler
directly (no HTTP server), covering enabled / explicitly disabled /
never-configured. |
| `coderd/oauth2provider/metadata.go` | `GetAuthorizationServerMetadata`
conditionally omits `registration_endpoint` from discovery metadata when
DCR is disabled. |
| `coderd/oauth2provider/metadata_test.go` | New unit test,
`TestGetAuthorizationServerMetadata_DCREnabled`: same three states, for
the discovery handler. |

**3. Admin settings endpoint**

| File | What changed |
|---|---|
| `codersdk/oauth2.go` | New `OAuth2ProviderSettings` SDK type plus
`Client.OAuth2ProviderSettings`/`PutOAuth2ProviderSettings` methods. |
| `coderd/oauth2.go` | New
`oauth2ProviderSettings`/`putOAuth2ProviderSettings` admin handlers
(audited via `audit.InitRequest`); updates the
`GetAuthorizationServerMetadata` call site to pass `api.Database`. |
| `coderd/coderd.go` | Registers `GET`/`PUT
/api/v2/oauth2-provider/settings`. |
| `coderd/oauth2_provider_settings_test.go` | New test file: admin
`GET`/`PUT` round-trip, default-disabled-before-any-`PUT`, and `403` for
a non-owner on both `GET` and `PUT`. |

**4. Audit wiring**

| File | What changed |
|---|---|
| `coderd/database/types.go` | New `database.OAuth2ProviderSettings`
audit-only struct (mirrors `NotificationsSettings`). |
| `coderd/audit/diff.go` | Adds the new struct to the `Auditable` type
union. |
| `coderd/audit/request.go` | Adds the new struct to all four dispatch
switches (`ResourceTarget`, `ResourceID`, `ResourceType`,
`ResourceRequiresOrgID`). |
| `codersdk/audit.go` | New API-facing
`ResourceTypeOAuth2ProviderSettings` constant and its `FriendlyString`
case. |
| `enterprise/audit/table.go` | Field-level audit action map
(`ActionTrack`/`ActionIgnore`) for the new struct. |
|
`coderd/database/migrations/000546_audit_oauth2_provider_settings.up.sql`
| Adds `oauth2_provider_settings` to the `resource_type` Postgres enum,
required for the audit wiring above (`resource_type` is a real enum, not
a Go-only value). |
|
`coderd/database/migrations/000546_audit_oauth2_provider_settings.down.sql`
| No-op (`ALTER TYPE ... ADD VALUE` can't be reverted). |

**5. Test-suite ripple from the disabled-by-default flip**

| File | What changed |
|---|---|
| `coderd/oauth2provider/oauth2providertest/helpers.go` | New shared
test helper, `EnableDCR`, since DCR now defaults to disabled and many
pre-existing tests need it turned on to register a client. |
| `coderd/oauth2_test.go` | Adds
`TestOAuth2DynamicClientRegistrationDisabled` (registers a client,
disables DCR, verifies new registration is rejected while the existing
client's self-management, authorize, and token exchange all keep
working); calls `EnableDCR` in every pre-existing test that registers a
client. |
| `coderd/oauth2_error_compliance_test.go` | Calls `EnableDCR` in every
test that registers a client, so RFC-error-format assertions aren't
masked by the new disabled-by-default gate. |
| `coderd/oauth2_metadata_validation_test.go` | Same: `EnableDCR` added
to every registration-dependent test. |
| `coderd/oauth2_security_test.go` | Same. |
| `coderd/oauth2provider/validation_test.go` | Same (near-duplicate of
`oauth2_metadata_validation_test.go` in a different package). |
| `coderd/oauth2provider/provider_test.go` | Same. |
| `coderd/mcp/mcp_e2e_test.go` | Same, for the MCP end-to-end
dynamic-registration flow test. |

</details>

<details>
<summary><b>Generated files (12)</b> — from <code>make gen</code>, no
need to review directly</summary>

`coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`,
`coderd/database/dbmetrics/querymetrics.go`,
`coderd/database/dbmock/dbmock.go`, `coderd/database/dump.sql`,
`coderd/database/models.go`, `coderd/database/querier.go`,
`coderd/database/queries.sql.go`, `docs/admin/security/audit-logs.md`,
`docs/reference/api/enterprise.md`, `docs/reference/api/schemas.md`,
`site/src/api/typesGenerated.ts`.

</details>

## Suggested review order

### 1. Database

Establishes the persisted setting and its RBAC rule; everything else
builds on `GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled`.

1. `coderd/database/queries/siteconfig.sql` — the two new queries. Same
boolean-encoding pattern as the existing
`oauth2_github_default_eligible` key right above them in the same file.
2. `coderd/database/dbauthz/dbauthz.go` — the RBAC wrapper for those two
queries, plus the `subjectSystemOAuth2` role extension (search this file
for `ResourceDeploymentConfig`, it appears in both spots).
3. `coderd/database/dbauthz/dbauthz_test.go` — asserts the RBAC checks
from (2) actually fire.

### 2. Request gating (the actual feature)

Where `POST /oauth2/register` and discovery metadata change behavior.

1. `coderd/oauth2provider/registration.go` — the primary gate. Read this
first; it's the feature.
2. `coderd/oauth2provider/registration_test.go` — its new unit test,
exercising the gate's three states directly against the handler.
3. `coderd/oauth2provider/metadata.go` — the same gating pattern applied
to the discovery `GET` endpoint.
4. `coderd/oauth2provider/metadata_test.go` — its new unit test.

### 3. Admin settings endpoint

How an owner flips the setting live.

1. `codersdk/oauth2.go` — the `OAuth2ProviderSettings` SDK type and
`Client` methods first; this is the public contract everything below
implements against.
2. `coderd/oauth2.go` — the `GET`/`PUT` handlers themselves.
3. `coderd/coderd.go` — route registration, to see where those handlers
get wired in.
4. `coderd/oauth2_provider_settings_test.go` — round-trip and permission
tests.

### 4. Audit wiring

Plumbing required so step 3's `PUT` is auditable; mechanical except for
(3).

1. `coderd/database/types.go` — the audit-only struct; everything else
in this layer exists to plumb it through.
2. `coderd/audit/diff.go` — adds it to the `Auditable` type union (the
compiler enforces this one).
3. `coderd/audit/request.go` — the four dispatch switches; the one part
of this layer worth reading closely.
4. `codersdk/audit.go` — the API-facing resource type constant.
5. `enterprise/audit/table.go` — the field-action map.
6.
`coderd/database/migrations/000546_audit_oauth2_provider_settings.{up,down}.sql`
— read last; a consequence of needing a new `resource_type` enum value
for (1)-(5), not a design decision of its own.

### 5. Test-suite ripple from the disabled-by-default flip

1. `coderd/oauth2provider/oauth2providertest/helpers.go` — the new
`EnableDCR` helper. Read first to understand the fix pattern before
seeing it applied repeatedly.
2. `coderd/oauth2_test.go` — next, since it also contains the new
`TestOAuth2DynamicClientRegistrationDisabled`, not just `EnableDCR` call
sites.
3. The rest, in any order, they're mechanical repeats of the same
one-line addition: `coderd/oauth2_error_compliance_test.go`,
`coderd/oauth2_metadata_validation_test.go`,
`coderd/oauth2_security_test.go`,
`coderd/oauth2provider/validation_test.go`,
`coderd/oauth2provider/provider_test.go`, `coderd/mcp/mcp_e2e_test.go`.

## Explicitly out of scope

Per the design proposal: rate limiting on `POST /oauth2/register`
(tracked separately), retroactively affecting already-registered clients
when DCR is disabled (this only gates new self-registration), and an
Initial Access Token requirement (a separate, follow-up ticket).
2026-07-28 16:59:33 -07:00

526 lines
17 KiB
Go

package coderd_test
import (
"errors"
"fmt"
"net/http"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/oauth2provider/oauth2providertest"
"github.com/coder/coder/v2/codersdk"
)
// TestOAuth2ClientIsolation tests that OAuth2 clients cannot access other clients' data
func TestOAuth2ClientIsolation(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
ctx := t.Context()
// Create two separate OAuth2 clients with unique identifiers
client1Name := fmt.Sprintf("test-client-1-%s-%d", t.Name(), time.Now().UnixNano())
client1Req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://client1.example.com/callback"},
ClientName: client1Name,
ClientURI: "https://client1.example.com",
}
client1Resp, err := client.PostOAuth2ClientRegistration(ctx, client1Req)
require.NoError(t, err)
client2Name := fmt.Sprintf("test-client-2-%s-%d", t.Name(), time.Now().UnixNano())
client2Req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://client2.example.com/callback"},
ClientName: client2Name,
ClientURI: "https://client2.example.com",
}
client2Resp, err := client.PostOAuth2ClientRegistration(ctx, client2Req)
require.NoError(t, err)
t.Run("ClientsCannotAccessOtherClientData", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Client 1 should not be able to access Client 2's data using Client 1's token
_, err := client.GetOAuth2ClientConfiguration(ctx, client2Resp.ClientID, client1Resp.RegistrationAccessToken)
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
require.Equal(t, http.StatusUnauthorized, httpErr.StatusCode())
// Client 2 should not be able to access Client 1's data using Client 2's token
_, err = client.GetOAuth2ClientConfiguration(ctx, client1Resp.ClientID, client2Resp.RegistrationAccessToken)
require.Error(t, err)
require.ErrorAs(t, err, &httpErr)
require.Equal(t, http.StatusUnauthorized, httpErr.StatusCode())
})
t.Run("ClientsCannotUpdateOtherClients", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Client 1 should not be able to update Client 2 using Client 1's token
updateReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://malicious.example.com/callback"},
ClientName: "Malicious Update",
}
_, err := client.PutOAuth2ClientConfiguration(ctx, client2Resp.ClientID, client1Resp.RegistrationAccessToken, updateReq)
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
require.Equal(t, http.StatusUnauthorized, httpErr.StatusCode())
})
t.Run("ClientsCannotDeleteOtherClients", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Client 1 should not be able to delete Client 2 using Client 1's token
err := client.DeleteOAuth2ClientConfiguration(ctx, client2Resp.ClientID, client1Resp.RegistrationAccessToken)
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
require.Equal(t, http.StatusUnauthorized, httpErr.StatusCode())
// Verify Client 2 still exists and is accessible with its own token
config, err := client.GetOAuth2ClientConfiguration(ctx, client2Resp.ClientID, client2Resp.RegistrationAccessToken)
require.NoError(t, err)
require.Equal(t, client2Resp.ClientID, config.ClientID)
})
}
// TestOAuth2RegistrationTokenSecurity tests security aspects of registration access tokens
func TestOAuth2RegistrationTokenSecurity(t *testing.T) {
t.Parallel()
// Single instance shared across all sub-tests. Each registers
// independent OAuth2 apps with unique client names.
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
t.Run("InvalidTokenFormats", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Register a client to use for testing
clientName := fmt.Sprintf("test-client-%s-%d", t.Name(), time.Now().UnixNano())
regReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: clientName,
}
regResp, err := client.PostOAuth2ClientRegistration(ctx, regReq)
require.NoError(t, err)
invalidTokens := []string{
"", // Empty token
"invalid", // Too short
"not-base64-!@#$%^&*", // Invalid characters
strings.Repeat("a", 1000), // Too long
"Bearer " + regResp.RegistrationAccessToken, // With Bearer prefix (incorrect)
}
for i, token := range invalidTokens {
t.Run(fmt.Sprintf("InvalidToken_%d", i), func(t *testing.T) {
t.Parallel()
_, err := client.GetOAuth2ClientConfiguration(ctx, regResp.ClientID, token)
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
require.Equal(t, http.StatusUnauthorized, httpErr.StatusCode())
})
}
})
t.Run("TokenNotReusableAcrossClients", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Register first client
client1Name := fmt.Sprintf("test-client-1-%s-%d", t.Name(), time.Now().UnixNano())
regReq1 := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: client1Name,
}
regResp1, err := client.PostOAuth2ClientRegistration(ctx, regReq1)
require.NoError(t, err)
// Register another client
client2Name := fmt.Sprintf("test-client-2-%s-%d", t.Name(), time.Now().UnixNano())
regReq2 := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example2.com/callback"},
ClientName: client2Name,
}
regResp2, err := client.PostOAuth2ClientRegistration(ctx, regReq2)
require.NoError(t, err)
// Try to use client1's token on client2
_, err = client.GetOAuth2ClientConfiguration(ctx, regResp2.ClientID, regResp1.RegistrationAccessToken)
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
require.Equal(t, http.StatusUnauthorized, httpErr.StatusCode())
})
t.Run("TokenNotExposedInGETResponse", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Register a client
clientName := fmt.Sprintf("test-client-%s-%d", t.Name(), time.Now().UnixNano())
regReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: clientName,
}
regResp, err := client.PostOAuth2ClientRegistration(ctx, regReq)
require.NoError(t, err)
// Get client configuration
config, err := client.GetOAuth2ClientConfiguration(ctx, regResp.ClientID, regResp.RegistrationAccessToken)
require.NoError(t, err)
// Registration access token should not be returned in GET responses (RFC 7592)
require.Empty(t, config.RegistrationAccessToken)
})
}
// TestOAuth2PrivilegeEscalation tests that clients cannot escalate their privileges
func TestOAuth2PrivilegeEscalation(t *testing.T) {
t.Parallel()
t.Run("CannotEscalateScopeViaUpdate", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
ctx := t.Context()
// Register a basic client
clientName := fmt.Sprintf("test-client-%d", time.Now().UnixNano())
regReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: clientName,
Scope: "read", // Limited scope
}
regResp, err := client.PostOAuth2ClientRegistration(ctx, regReq)
require.NoError(t, err)
// Try to escalate scope through update
updateReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: clientName,
Scope: "read write admin", // Trying to escalate to admin
}
// This should succeed (scope changes are allowed in updates)
// but the system should validate scope permissions appropriately
updatedConfig, err := client.PutOAuth2ClientConfiguration(ctx, regResp.ClientID, regResp.RegistrationAccessToken, updateReq)
if err == nil {
// If update succeeds, verify the scope was set appropriately
// (The actual scope validation would happen during token issuance)
require.Contains(t, updatedConfig.Scope, "read")
}
})
t.Run("CustomSchemeRedirectURIs", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
ctx := t.Context()
// Test valid custom schemes per RFC 7591/8252
validCustomSchemeRequests := []codersdk.OAuth2ClientRegistrationRequest{
{
RedirectURIs: []string{"com.example.myapp://callback"},
ClientName: fmt.Sprintf("native-app-1-%d", time.Now().UnixNano()),
TokenEndpointAuthMethod: "none", // Required for public clients using custom schemes
},
{
RedirectURIs: []string{"com.example.app://oauth"},
ClientName: fmt.Sprintf("native-app-2-%d", time.Now().UnixNano()),
TokenEndpointAuthMethod: "none", // Required for public clients using custom schemes
},
{
RedirectURIs: []string{"urn:ietf:wg:oauth:2.0:oob"},
ClientName: fmt.Sprintf("native-app-3-%d", time.Now().UnixNano()),
TokenEndpointAuthMethod: "none", // Required for public clients
},
}
for i, req := range validCustomSchemeRequests {
t.Run(fmt.Sprintf("ValidCustomSchemeRequest_%d", i), func(t *testing.T) {
t.Parallel()
_, err := client.PostOAuth2ClientRegistration(ctx, req)
// Valid custom schemes should be allowed per RFC 7591/8252
require.NoError(t, err)
})
}
// Test that dangerous schemes are properly rejected for security
dangerousSchemeRequests := []struct {
req codersdk.OAuth2ClientRegistrationRequest
scheme string
}{
{
req: codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"javascript:alert('test')"},
ClientName: fmt.Sprintf("native-app-js-%d", time.Now().UnixNano()),
TokenEndpointAuthMethod: "none",
},
scheme: "javascript",
},
{
req: codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"data:text/html,<html></html>"},
ClientName: fmt.Sprintf("native-app-data-%d", time.Now().UnixNano()),
TokenEndpointAuthMethod: "none",
},
scheme: "data",
},
}
for _, test := range dangerousSchemeRequests {
t.Run(fmt.Sprintf("DangerousScheme_%s", test.scheme), func(t *testing.T) {
t.Parallel()
_, err := client.PostOAuth2ClientRegistration(ctx, test.req)
// Dangerous schemes should be rejected for security
require.Error(t, err)
require.Contains(t, err.Error(), "dangerous scheme")
})
}
})
}
// TestOAuth2InformationDisclosure tests that error messages don't leak sensitive information
func TestOAuth2InformationDisclosure(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
ctx := t.Context()
// Register a client for testing
clientName := fmt.Sprintf("test-client-%d", time.Now().UnixNano())
regReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: clientName,
}
regResp, err := client.PostOAuth2ClientRegistration(ctx, regReq)
require.NoError(t, err)
t.Run("ErrorsDoNotLeakClientSecrets", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Try various invalid operations and ensure they don't leak the client secret
_, err := client.GetOAuth2ClientConfiguration(ctx, regResp.ClientID, "invalid-token")
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
// Error message should not contain any part of the client secret or registration token
errorText := strings.ToLower(httpErr.Message + httpErr.Detail)
require.NotContains(t, errorText, strings.ToLower(regResp.ClientSecret))
require.NotContains(t, errorText, strings.ToLower(regResp.RegistrationAccessToken))
})
t.Run("ErrorsDoNotLeakDatabaseDetails", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Try to access non-existent client
_, err := client.GetOAuth2ClientConfiguration(ctx, "non-existent-client-id", regResp.RegistrationAccessToken)
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
// Error message should not leak database schema information
errorText := strings.ToLower(httpErr.Message + httpErr.Detail)
require.NotContains(t, errorText, "sql")
require.NotContains(t, errorText, "database")
require.NotContains(t, errorText, "table")
require.NotContains(t, errorText, "row")
require.NotContains(t, errorText, "constraint")
})
t.Run("ErrorsAreConsistentForInvalidClients", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Test with various invalid client IDs to ensure consistent error responses
invalidClientIDs := []string{
"non-existent-1",
"non-existent-2",
"totally-different-format",
}
var errorMessages []string
for _, clientID := range invalidClientIDs {
_, err := client.GetOAuth2ClientConfiguration(ctx, clientID, regResp.RegistrationAccessToken)
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
errorMessages = append(errorMessages, httpErr.Message)
}
// All error messages should be similar (not leaking which client IDs exist vs don't exist)
for i := 1; i < len(errorMessages); i++ {
require.Equal(t, errorMessages[0], errorMessages[i])
}
})
}
// TestOAuth2ConcurrentSecurityOperations tests security under concurrent operations
func TestOAuth2ConcurrentSecurityOperations(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
ctx := t.Context()
// Register a client for testing
clientName := fmt.Sprintf("test-client-%d", time.Now().UnixNano())
regReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: clientName,
}
regResp, err := client.PostOAuth2ClientRegistration(ctx, regReq)
require.NoError(t, err)
t.Run("ConcurrentAccessAttempts", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
const numGoroutines = 20
var wg sync.WaitGroup
errors := make([]error, numGoroutines)
// Launch concurrent attempts to access the client configuration
for i := 0; i < numGoroutines; i++ {
wg.Go(func() {
_, err := client.GetOAuth2ClientConfiguration(ctx, regResp.ClientID, regResp.RegistrationAccessToken)
errors[i] = err
})
}
wg.Wait()
// All requests should succeed (they're all valid)
for i, err := range errors {
require.NoError(t, err, "Request %d failed", i)
}
})
t.Run("ConcurrentInvalidAccessAttempts", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
const numGoroutines = 20
var wg sync.WaitGroup
statusCodes := make([]int, numGoroutines)
// Launch concurrent attempts with invalid tokens
for i := 0; i < numGoroutines; i++ {
wg.Go(func() {
_, err := client.GetOAuth2ClientConfiguration(ctx, regResp.ClientID, fmt.Sprintf("invalid-token-%d", i))
if err == nil {
t.Errorf("Expected error for goroutine %d", i)
return
}
var httpErr *codersdk.Error
if !errors.As(err, &httpErr) {
t.Errorf("Expected codersdk.Error for goroutine %d", i)
return
}
statusCodes[i] = httpErr.StatusCode()
})
}
wg.Wait()
// All requests should fail with 401 status
for i, statusCode := range statusCodes {
require.Equal(t, http.StatusUnauthorized, statusCode, "Request %d had unexpected status", i)
}
})
t.Run("ConcurrentClientDeletion", func(t *testing.T) {
t.Parallel()
ctx := t.Context()
// Register a client specifically for deletion testing
deleteClientName := fmt.Sprintf("delete-test-client-%d", time.Now().UnixNano())
deleteRegReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://delete-test.example.com/callback"},
ClientName: deleteClientName,
}
deleteRegResp, err := client.PostOAuth2ClientRegistration(ctx, deleteRegReq)
require.NoError(t, err)
const numGoroutines = 5
var wg sync.WaitGroup
deleteResults := make([]error, numGoroutines)
// Launch concurrent deletion attempts
for i := 0; i < numGoroutines; i++ {
wg.Go(func() {
err := client.DeleteOAuth2ClientConfiguration(ctx, deleteRegResp.ClientID, deleteRegResp.RegistrationAccessToken)
deleteResults[i] = err
})
}
wg.Wait()
// Only one deletion should succeed, others should fail
successCount := 0
for _, err := range deleteResults {
if err == nil {
successCount++
}
}
// At least one should succeed, and multiple successes are acceptable (idempotent operation)
require.Greater(t, successCount, 0, "At least one deletion should succeed")
// Verify the client is actually deleted
_, err = client.GetOAuth2ClientConfiguration(ctx, deleteRegResp.ClientID, deleteRegResp.RegistrationAccessToken)
require.Error(t, err)
var httpErr *codersdk.Error
require.ErrorAs(t, err, &httpErr)
require.True(t, httpErr.StatusCode() == http.StatusUnauthorized || httpErr.StatusCode() == http.StatusNotFound)
})
}