diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index dcd051705a3..2e78450741a 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -23218,6 +23218,10 @@ const docTemplate = `{ "oauth2_client_secret": { "type": "string" }, + "oauth2_resource": { + "description": "OAuth2Resource is the RFC 8707 resource indicator sent on\nauthorization, token, and refresh requests when set;\nauto-populated by OAuth2 discovery when omitted.", + "type": "string" + }, "oauth2_revocation_url": { "description": "OAuth2RevocationURL is the provider's RFC 7009 revocation\nendpoint; auto-populated by OAuth2 discovery when omitted.", "type": "string" @@ -25913,6 +25917,9 @@ const docTemplate = `{ "description": "OAuth2 fields (only populated for admins).", "type": "string" }, + "oauth2_resource": { + "type": "string" + }, "oauth2_revocation_url": { "type": "string" }, @@ -31224,6 +31231,10 @@ const docTemplate = `{ "oauth2_client_secret": { "type": "string" }, + "oauth2_resource": { + "description": "OAuth2Resource is the RFC 8707 resource indicator; a pointer\nto \"\" clears it.", + "type": "string" + }, "oauth2_revocation_url": { "description": "OAuth2RevocationURL is validated in the handler because a\nvalidate tag would reject the pointer to \"\" that clears it.", "type": "string" diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index 268f4719c04..4f00e7b64f3 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -21082,6 +21082,10 @@ "oauth2_client_secret": { "type": "string" }, + "oauth2_resource": { + "description": "OAuth2Resource is the RFC 8707 resource indicator sent on\nauthorization, token, and refresh requests when set;\nauto-populated by OAuth2 discovery when omitted.", + "type": "string" + }, "oauth2_revocation_url": { "description": "OAuth2RevocationURL is the provider's RFC 7009 revocation\nendpoint; auto-populated by OAuth2 discovery when omitted.", "type": "string" @@ -23668,6 +23672,9 @@ "description": "OAuth2 fields (only populated for admins).", "type": "string" }, + "oauth2_resource": { + "type": "string" + }, "oauth2_revocation_url": { "type": "string" }, @@ -28765,6 +28772,10 @@ "oauth2_client_secret": { "type": "string" }, + "oauth2_resource": { + "description": "OAuth2Resource is the RFC 8707 resource indicator; a pointer\nto \"\" clears it.", + "type": "string" + }, "oauth2_revocation_url": { "description": "OAuth2RevocationURL is validated in the handler because a\nvalidate tag would reject the pointer to \"\" that clears it.", "type": "string" diff --git a/coderd/database/dbgen/dbgen.go b/coderd/database/dbgen/dbgen.go index bddc8ce4825..b34a29e0d27 100644 --- a/coderd/database/dbgen/dbgen.go +++ b/coderd/database/dbgen/dbgen.go @@ -424,6 +424,7 @@ func MCPServerConfig(t testing.TB, db database.Store, seed database.MCPServerCon OAuth2AuthURL: seed.OAuth2AuthURL, OAuth2TokenURL: seed.OAuth2TokenURL, OAuth2RevocationURL: seed.OAuth2RevocationURL, + OAuth2Resource: seed.OAuth2Resource, OAuth2Scopes: seed.OAuth2Scopes, APIKeyHeader: seed.APIKeyHeader, APIKeyValue: seed.APIKeyValue, diff --git a/coderd/database/dump.sql b/coderd/database/dump.sql index 77d9cb26ca2..e5dd3a369a5 100644 --- a/coderd/database/dump.sql +++ b/coderd/database/dump.sql @@ -2710,6 +2710,7 @@ CREATE TABLE mcp_server_configs ( user_acl jsonb DEFAULT '{}'::jsonb NOT NULL, signing_secret text DEFAULT ''::text NOT NULL, signing_secret_key_id text, + oauth2_resource text DEFAULT ''::text NOT NULL, CONSTRAINT mcp_server_configs_auth_type_check CHECK ((auth_type = ANY (ARRAY['none'::text, 'oauth2'::text, 'api_key'::text, 'custom_headers'::text, 'user_oidc'::text]))), CONSTRAINT mcp_server_configs_availability_check CHECK ((availability = ANY (ARRAY['force_on'::text, 'default_on'::text, 'default_off'::text]))), CONSTRAINT mcp_server_configs_group_acl_is_object CHECK ((jsonb_typeof(group_acl) = 'object'::text)), diff --git a/coderd/database/migrations/000617_mcp_server_oauth2_resource.down.sql b/coderd/database/migrations/000617_mcp_server_oauth2_resource.down.sql new file mode 100644 index 00000000000..17a39f5e389 --- /dev/null +++ b/coderd/database/migrations/000617_mcp_server_oauth2_resource.down.sql @@ -0,0 +1 @@ +ALTER TABLE mcp_server_configs DROP COLUMN oauth2_resource; diff --git a/coderd/database/migrations/000617_mcp_server_oauth2_resource.up.sql b/coderd/database/migrations/000617_mcp_server_oauth2_resource.up.sql new file mode 100644 index 00000000000..d43ec5d5dfb --- /dev/null +++ b/coderd/database/migrations/000617_mcp_server_oauth2_resource.up.sql @@ -0,0 +1 @@ +ALTER TABLE mcp_server_configs ADD COLUMN oauth2_resource text NOT NULL DEFAULT ''; diff --git a/coderd/database/modelqueries.go b/coderd/database/modelqueries.go index 8e4c02f0bdb..8309c501a9c 100644 --- a/coderd/database/modelqueries.go +++ b/coderd/database/modelqueries.go @@ -1334,6 +1334,7 @@ func (q *sqlQuerier) GetAuthorizedMCPServerConfigs(ctx context.Context, organiza &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ); err != nil { return nil, err } diff --git a/coderd/database/models.go b/coderd/database/models.go index 4f585479aff..b83db75e931 100644 --- a/coderd/database/models.go +++ b/coderd/database/models.go @@ -5728,6 +5728,7 @@ type MCPServerConfig struct { UserACL ChatACL `db:"user_acl" json:"user_acl"` SigningSecret string `db:"signing_secret" json:"signing_secret"` SigningSecretKeyID sql.NullString `db:"signing_secret_key_id" json:"signing_secret_key_id"` + OAuth2Resource string `db:"oauth2_resource" json:"oauth2_resource"` } type MCPServerUserToken struct { diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index d60a46fa641..45f650276d1 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -19365,7 +19365,7 @@ func (q *sqlQuerier) DeleteMCPServerUserTokensByConfigID(ctx context.Context, mc const getEnabledMCPServerConfigsByOrganization = `-- name: GetEnabledMCPServerConfigsByOrganization :many SELECT - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource FROM mcp_server_configs WHERE @@ -19421,6 +19421,7 @@ func (q *sqlQuerier) GetEnabledMCPServerConfigsByOrganization(ctx context.Contex &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ); err != nil { return nil, err } @@ -19437,7 +19438,7 @@ func (q *sqlQuerier) GetEnabledMCPServerConfigsByOrganization(ctx context.Contex const getEnabledMCPServerConfigsByOrganizationAndIDs = `-- name: GetEnabledMCPServerConfigsByOrganizationAndIDs :many SELECT - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource FROM mcp_server_configs WHERE @@ -19499,6 +19500,7 @@ func (q *sqlQuerier) GetEnabledMCPServerConfigsByOrganizationAndIDs(ctx context. &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ); err != nil { return nil, err } @@ -19515,7 +19517,7 @@ func (q *sqlQuerier) GetEnabledMCPServerConfigsByOrganizationAndIDs(ctx context. const getForcedMCPServerConfigsByOrganization = `-- name: GetForcedMCPServerConfigsByOrganization :many SELECT - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource FROM mcp_server_configs WHERE @@ -19572,6 +19574,7 @@ func (q *sqlQuerier) GetForcedMCPServerConfigsByOrganization(ctx context.Context &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ); err != nil { return nil, err } @@ -19588,7 +19591,7 @@ func (q *sqlQuerier) GetForcedMCPServerConfigsByOrganization(ctx context.Context const getMCPServerConfigByID = `-- name: GetMCPServerConfigByID :one SELECT - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource FROM mcp_server_configs WHERE @@ -19635,13 +19638,14 @@ func (q *sqlQuerier) GetMCPServerConfigByID(ctx context.Context, id uuid.UUID) ( &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ) return i, err } const getMCPServerConfigByIDForUpdate = `-- name: GetMCPServerConfigByIDForUpdate :one SELECT - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource FROM mcp_server_configs WHERE @@ -19689,13 +19693,14 @@ func (q *sqlQuerier) GetMCPServerConfigByIDForUpdate(ctx context.Context, id uui &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ) return i, err } const getMCPServerConfigByOrganizationAndSlug = `-- name: GetMCPServerConfigByOrganizationAndSlug :one SELECT - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource FROM mcp_server_configs WHERE @@ -19748,13 +19753,14 @@ func (q *sqlQuerier) GetMCPServerConfigByOrganizationAndSlug(ctx context.Context &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ) return i, err } const getMCPServerConfigsByOrganization = `-- name: GetMCPServerConfigsByOrganization :many SELECT - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource FROM mcp_server_configs WHERE @@ -19811,6 +19817,7 @@ func (q *sqlQuerier) GetMCPServerConfigsByOrganization(ctx context.Context, orga &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ); err != nil { return nil, err } @@ -19951,6 +19958,7 @@ INSERT INTO mcp_server_configs ( oauth2_auth_url, oauth2_token_url, oauth2_revocation_url, + oauth2_resource, oauth2_scopes, api_key_header, api_key_value, @@ -19994,20 +20002,21 @@ INSERT INTO mcp_server_configs ( $21::text, $22::text, $23::text, - $24::text[], + $24::text, $25::text[], - $26::text, - $27::boolean, + $26::text[], + $27::text, $28::boolean, $29::boolean, $30::boolean, - $31, + $31::boolean, $32, - $33::uuid, - $34::uuid + $33, + $34::uuid, + $35::uuid ) RETURNING - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource ` type InsertMCPServerConfigParams struct { @@ -20026,6 +20035,7 @@ type InsertMCPServerConfigParams struct { OAuth2AuthURL string `db:"oauth2_auth_url" json:"oauth2_auth_url"` OAuth2TokenURL string `db:"oauth2_token_url" json:"oauth2_token_url"` OAuth2RevocationURL string `db:"oauth2_revocation_url" json:"oauth2_revocation_url"` + OAuth2Resource string `db:"oauth2_resource" json:"oauth2_resource"` OAuth2Scopes string `db:"oauth2_scopes" json:"oauth2_scopes"` APIKeyHeader string `db:"api_key_header" json:"api_key_header"` APIKeyValue string `db:"api_key_value" json:"api_key_value"` @@ -20064,6 +20074,7 @@ func (q *sqlQuerier) InsertMCPServerConfig(ctx context.Context, arg InsertMCPSer arg.OAuth2AuthURL, arg.OAuth2TokenURL, arg.OAuth2RevocationURL, + arg.OAuth2Resource, arg.OAuth2Scopes, arg.APIKeyHeader, arg.APIKeyValue, @@ -20122,6 +20133,7 @@ func (q *sqlQuerier) InsertMCPServerConfig(ctx context.Context, arg InsertMCPSer &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ) return i, err } @@ -20191,27 +20203,28 @@ SET oauth2_auth_url = $11::text, oauth2_token_url = $12::text, oauth2_revocation_url = $13::text, - oauth2_scopes = $14::text, - api_key_header = $15::text, - api_key_value = $16::text, - api_key_value_key_id = $17::text, - custom_headers = $18::text, - custom_headers_key_id = $19::text, - signing_secret = $20::text, - signing_secret_key_id = $21::text, - tool_allow_list = $22::text[], - tool_deny_list = $23::text[], - availability = $24::text, - enabled = $25::boolean, - model_intent = $26::boolean, - allow_in_plan_mode = $27::boolean, - forward_coder_headers = $28::boolean, - updated_by = $29::uuid, + oauth2_resource = $14::text, + oauth2_scopes = $15::text, + api_key_header = $16::text, + api_key_value = $17::text, + api_key_value_key_id = $18::text, + custom_headers = $19::text, + custom_headers_key_id = $20::text, + signing_secret = $21::text, + signing_secret_key_id = $22::text, + tool_allow_list = $23::text[], + tool_deny_list = $24::text[], + availability = $25::text, + enabled = $26::boolean, + model_intent = $27::boolean, + allow_in_plan_mode = $28::boolean, + forward_coder_headers = $29::boolean, + updated_by = $30::uuid, updated_at = NOW() WHERE - id = $30::uuid + id = $31::uuid RETURNING - id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id + id, display_name, slug, description, icon_url, transport, url, auth_type, oauth2_client_id, oauth2_client_secret, oauth2_client_secret_key_id, oauth2_auth_url, oauth2_token_url, oauth2_scopes, api_key_header, api_key_value, api_key_value_key_id, custom_headers, custom_headers_key_id, tool_allow_list, tool_deny_list, availability, enabled, created_by, updated_by, created_at, updated_at, model_intent, allow_in_plan_mode, forward_coder_headers, oauth2_revocation_url, organization_id, group_acl, user_acl, signing_secret, signing_secret_key_id, oauth2_resource ` type UpdateMCPServerConfigParams struct { @@ -20228,6 +20241,7 @@ type UpdateMCPServerConfigParams struct { OAuth2AuthURL string `db:"oauth2_auth_url" json:"oauth2_auth_url"` OAuth2TokenURL string `db:"oauth2_token_url" json:"oauth2_token_url"` OAuth2RevocationURL string `db:"oauth2_revocation_url" json:"oauth2_revocation_url"` + OAuth2Resource string `db:"oauth2_resource" json:"oauth2_resource"` OAuth2Scopes string `db:"oauth2_scopes" json:"oauth2_scopes"` APIKeyHeader string `db:"api_key_header" json:"api_key_header"` APIKeyValue string `db:"api_key_value" json:"api_key_value"` @@ -20262,6 +20276,7 @@ func (q *sqlQuerier) UpdateMCPServerConfig(ctx context.Context, arg UpdateMCPSer arg.OAuth2AuthURL, arg.OAuth2TokenURL, arg.OAuth2RevocationURL, + arg.OAuth2Resource, arg.OAuth2Scopes, arg.APIKeyHeader, arg.APIKeyValue, @@ -20318,6 +20333,7 @@ func (q *sqlQuerier) UpdateMCPServerConfig(ctx context.Context, arg UpdateMCPSer &i.UserACL, &i.SigningSecret, &i.SigningSecretKeyID, + &i.OAuth2Resource, ) return i, err } diff --git a/coderd/database/queries/mcpserverconfigs.sql b/coderd/database/queries/mcpserverconfigs.sql index 374103d66c1..e7222f2ce0c 100644 --- a/coderd/database/queries/mcpserverconfigs.sql +++ b/coderd/database/queries/mcpserverconfigs.sql @@ -88,6 +88,7 @@ INSERT INTO mcp_server_configs ( oauth2_auth_url, oauth2_token_url, oauth2_revocation_url, + oauth2_resource, oauth2_scopes, api_key_header, api_key_value, @@ -123,6 +124,7 @@ INSERT INTO mcp_server_configs ( @oauth2_auth_url::text, @oauth2_token_url::text, @oauth2_revocation_url::text, + @oauth2_resource::text, @oauth2_scopes::text, @api_key_header::text, @api_key_value::text, @@ -163,6 +165,7 @@ SET oauth2_auth_url = @oauth2_auth_url::text, oauth2_token_url = @oauth2_token_url::text, oauth2_revocation_url = @oauth2_revocation_url::text, + oauth2_resource = @oauth2_resource::text, oauth2_scopes = @oauth2_scopes::text, api_key_header = @api_key_header::text, api_key_value = @api_key_value::text, diff --git a/coderd/database/sqlc.yaml b/coderd/database/sqlc.yaml index c1a28b3a696..671bb3b48dc 100644 --- a/coderd/database/sqlc.yaml +++ b/coderd/database/sqlc.yaml @@ -307,6 +307,7 @@ sql: oauth2_auth_url: OAuth2AuthURL oauth2_token_url: OAuth2TokenURL oauth2_revocation_url: OAuth2RevocationURL + oauth2_resource: OAuth2Resource oauth2_scopes: OAuth2Scopes api_key_header: APIKeyHeader api_key_value: APIKeyValue diff --git a/coderd/mcp.go b/coderd/mcp.go index 6a6bdefc6ba..553b868eb10 100644 --- a/coderd/mcp.go +++ b/coderd/mcp.go @@ -330,6 +330,10 @@ func (api *API) createMCPServerConfig(rw http.ResponseWriter, r *http.Request) { } } + if !validateMCPOAuth2ResourceRequest(ctx, rw, req.OAuth2Resource) { + return + } + configID := uuid.New() // Validate auth-type-dependent fields. @@ -414,6 +418,9 @@ func (api *API) createMCPServerConfig(rw http.ResponseWriter, r *http.Request) { req.OAuth2AuthURL = result.authURL req.OAuth2TokenURL = result.tokenURL req.OAuth2RevocationURL = oauth2RevocationURL + if strings.TrimSpace(req.OAuth2Resource) == "" { + req.OAuth2Resource = result.resource + } req.OAuth2Scopes = oauth2Scopes } else if req.OAuth2ClientID == "" || req.OAuth2AuthURL == "" || req.OAuth2TokenURL == "" { // Partial manual config: all three fields are required together. @@ -463,6 +470,7 @@ func (api *API) createMCPServerConfig(rw http.ResponseWriter, r *http.Request) { OAuth2AuthURL: strings.TrimSpace(req.OAuth2AuthURL), OAuth2TokenURL: strings.TrimSpace(req.OAuth2TokenURL), OAuth2RevocationURL: strings.TrimSpace(req.OAuth2RevocationURL), + OAuth2Resource: strings.TrimSpace(req.OAuth2Resource), OAuth2Scopes: strings.TrimSpace(req.OAuth2Scopes), APIKeyHeader: strings.TrimSpace(req.APIKeyHeader), APIKeyValue: strings.TrimSpace(req.APIKeyValue), @@ -666,6 +674,10 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { } } + if req.OAuth2Resource != nil && !validateMCPOAuth2ResourceRequest(ctx, rw, *req.OAuth2Resource) { + return + } + // Pre-validate custom headers before entering the transaction. var customHeadersJSON string if req.CustomHeaders != nil { @@ -762,6 +774,11 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { oauth2RevocationURL = strings.TrimSpace(*req.OAuth2RevocationURL) } + oauth2Resource := existing.OAuth2Resource + if req.OAuth2Resource != nil { + oauth2Resource = strings.TrimSpace(*req.OAuth2Resource) + } + oauth2Scopes := existing.OAuth2Scopes if req.OAuth2Scopes != nil { oauth2Scopes = strings.TrimSpace(*req.OAuth2Scopes) @@ -841,6 +858,7 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { oauth2AuthURL = "" oauth2TokenURL = "" oauth2RevocationURL = "" + oauth2Resource = "" oauth2Scopes = "" apiKeyHeader = "" apiKeyValue = "" @@ -860,6 +878,7 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { oauth2AuthURL = "" oauth2TokenURL = "" oauth2RevocationURL = "" + oauth2Resource = "" oauth2Scopes = "" customHeaders = "{}" customHeadersKeyID = sql.NullString{} @@ -870,6 +889,7 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { oauth2AuthURL = "" oauth2TokenURL = "" oauth2RevocationURL = "" + oauth2Resource = "" oauth2Scopes = "" apiKeyHeader = "" apiKeyValue = "" @@ -884,6 +904,7 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { oauth2AuthURL = "" oauth2TokenURL = "" oauth2RevocationURL = "" + oauth2Resource = "" oauth2Scopes = "" apiKeyHeader = "" apiKeyValue = "" @@ -898,11 +919,12 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { } // User grants are bound to the destination, auth flow, token and revocation - // endpoints, and OAuth client. Invalidate them when any of these change so - // stored tokens cannot be sent to another endpoint or client. + // endpoints, OAuth client, and resource indicator. Invalidate them when any + // of these change so stored tokens cannot be sent to another endpoint, + // client, or resource. if serverURL != existing.Url || authType != existing.AuthType || oauth2TokenURL != existing.OAuth2TokenURL || oauth2RevocationURL != existing.OAuth2RevocationURL || - oauth2ClientID != existing.OAuth2ClientID { + oauth2ClientID != existing.OAuth2ClientID || oauth2Resource != existing.OAuth2Resource { if err := tx.DeleteMCPServerUserTokensByConfigID(ctx, existing.ID); err != nil { return xerrors.Errorf("invalidate MCP server user tokens: %w", err) } @@ -922,6 +944,7 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { OAuth2AuthURL: oauth2AuthURL, OAuth2TokenURL: oauth2TokenURL, OAuth2RevocationURL: oauth2RevocationURL, + OAuth2Resource: oauth2Resource, OAuth2Scopes: oauth2Scopes, APIKeyHeader: apiKeyHeader, APIKeyValue: apiKeyValue, @@ -1129,7 +1152,11 @@ func (api *API) mcpServerOAuth2Connect(rw http.ResponseWriter, r *http.Request) scopes = strings.Split(config.OAuth2Scopes, " ") } oauth2Config.Scopes = scopes - authURL := oauth2Config.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier)) + authOpts := []oauth2.AuthCodeOption{oauth2.S256ChallengeOption(verifier)} + if config.OAuth2Resource != "" { + authOpts = append(authOpts, oauth2.SetAuthURLParam("resource", config.OAuth2Resource)) + } + authURL := oauth2Config.AuthCodeURL(state, authOpts...) http.Redirect(rw, r, authURL, http.StatusTemporaryRedirect) } @@ -1240,6 +1267,9 @@ func (api *API) mcpServerOAuth2Callback(rw http.ResponseWriter, r *http.Request) if verifierCookie, err := r.Cookie("mcp_oauth2_verifier_" + config.ID.String()); err == nil { exchangeOpts = append(exchangeOpts, oauth2.VerifierOption(verifierCookie.Value)) } + if config.OAuth2Resource != "" { + exchangeOpts = append(exchangeOpts, oauth2.SetAuthURLParam("resource", config.OAuth2Resource)) + } // Clear the verifier cookie regardless of whether it was present. http.SetCookie(rw, api.DeploymentValues.HTTPCookies.Apply(&http.Cookie{ Name: "mcp_oauth2_verifier_" + config.ID.String(), @@ -1302,7 +1332,7 @@ func (api *API) mcpServerOAuth2Callback(rw http.ResponseWriter, r *http.Request) } if current.Url != config.Url || current.AuthType != config.AuthType || current.OAuth2TokenURL != config.OAuth2TokenURL || current.OAuth2RevocationURL != config.OAuth2RevocationURL || - current.OAuth2ClientID != config.OAuth2ClientID { + current.OAuth2ClientID != config.OAuth2ClientID || current.OAuth2Resource != config.OAuth2Resource { return errMCPConfigSupersededDuringAuth } _, err = tx.UpsertMCPServerUserToken(ctx, database.UpsertMCPServerUserTokenParams{ @@ -1629,6 +1659,7 @@ func convertMCPServerConfig(config database.MCPServerConfig) codersdk.MCPServerC OAuth2AuthURL: config.OAuth2AuthURL, OAuth2TokenURL: config.OAuth2TokenURL, OAuth2RevocationURL: config.OAuth2RevocationURL, + OAuth2Resource: config.OAuth2Resource, OAuth2Scopes: config.OAuth2Scopes, APIKeyHeader: config.APIKeyHeader, @@ -1666,6 +1697,7 @@ func convertMCPServerConfigRedacted(config database.MCPServerConfig) codersdk.MC c.OAuth2AuthURL = "" c.OAuth2TokenURL = "" c.OAuth2RevocationURL = "" + c.OAuth2Resource = "" c.OAuth2Scopes = "" c.APIKeyHeader = "" return c @@ -1709,6 +1741,89 @@ func coalesceStringSlice(ss []string) []string { return ss } +// validateMCPOAuth2Resource checks a non-empty RFC 8707 resource +// indicator: an absolute URI without a fragment (RFC 8707 section 2). +func validateMCPOAuth2Resource(resource string) error { + if strings.Contains(resource, "#") { + return xerrors.New("oauth2_resource must not contain a fragment") + } + parsed, err := url.Parse(resource) + if err != nil { + return xerrors.New("oauth2_resource must be a valid URI") + } + if !parsed.IsAbs() { + return xerrors.New("oauth2_resource must be an absolute URI") + } + return nil +} + +// validateMCPOAuth2ResourceRequest writes a 400 response and returns +// false when a non-empty oauth2_resource is invalid. An empty value is +// valid because it means no resource parameter is sent. +func validateMCPOAuth2ResourceRequest(ctx context.Context, rw http.ResponseWriter, resource string) bool { + trimmed := strings.TrimSpace(resource) + if trimmed == "" { + return true + } + if err := validateMCPOAuth2Resource(trimmed); err != nil { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "Invalid OAuth2 resource.", + Detail: err.Error(), + }) + return false + } + return true +} + +// mcpOAuth2ResourceIndicator picks the RFC 8707 resource indicator for +// an MCP server: the most specific advertised Protected Resource +// Metadata resource that covers the server URL, stored verbatim, else +// the server URL in canonical form. This matches the MCP Python SDK. +func mcpOAuth2ResourceIndicator(serverURL *url.URL, advertised []string) string { + serverPath := withTrailingSlash(serverURL.Path) + best := "" + bestPathLen := -1 + for _, raw := range advertised { + candidate := strings.TrimSpace(raw) + if candidate == "" || validateMCPOAuth2Resource(candidate) != nil { + continue + } + parsed, err := url.Parse(candidate) + if err != nil { + continue + } + if !strings.EqualFold(parsed.Scheme, serverURL.Scheme) || !strings.EqualFold(parsed.Host, serverURL.Host) { + continue + } + entryPath := withTrailingSlash(parsed.Path) + if !strings.HasPrefix(serverPath, entryPath) { + continue + } + if len(entryPath) > bestPathLen { + best = candidate + bestPathLen = len(entryPath) + } + } + if best != "" { + return best + } + + canonical := *serverURL + canonical.Scheme = strings.ToLower(canonical.Scheme) + canonical.Host = strings.ToLower(canonical.Host) + canonical.User = nil + canonical.Fragment = "" + canonical.RawFragment = "" + return canonical.String() +} + +func withTrailingSlash(path string) string { + if strings.HasSuffix(path, "/") { + return path + } + return path + "/" +} + // mcpOAuth2Discovery holds the result of MCP OAuth2 auto-discovery // and Dynamic Client Registration. type mcpOAuth2Discovery struct { @@ -1717,6 +1832,7 @@ type mcpOAuth2Discovery struct { authURL string tokenURL string revocationURL string + resource string // RFC 8707 resource indicator scopes string // space-separated } @@ -2081,6 +2197,7 @@ func discoverAndRegisterMCPOAuth2(ctx context.Context, httpClient *http.Client, authURL: asMeta.AuthorizationEndpoint, tokenURL: asMeta.TokenEndpoint, revocationURL: asMeta.RevocationEndpoint, + resource: mcpOAuth2ResourceIndicator(parsed, prm.Resource), scopes: scopes, }, nil } diff --git a/coderd/mcp_internal_test.go b/coderd/mcp_internal_test.go index c5ce6b333fb..faf5888be2d 100644 --- a/coderd/mcp_internal_test.go +++ b/coderd/mcp_internal_test.go @@ -3,6 +3,7 @@ package coderd import ( "context" "encoding/json" + "net/url" "sync/atomic" "testing" "time" @@ -267,3 +268,85 @@ func TestProtectedResourceMetadataResourceUnmarshal(t *testing.T) { }) } } + +func TestMCPOAuth2ResourceIndicator(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + serverURL string + advertised []string + want string + }{ + { + name: "ExactMatch", + serverURL: "https://mcp.agent.dagster.cloud/mcp", + advertised: []string{"https://mcp.agent.dagster.cloud/mcp"}, + want: "https://mcp.agent.dagster.cloud/mcp", + }, + { + name: "OriginCoversPath", + serverURL: "https://mcp.example.com/v1/mcp", + advertised: []string{"https://mcp.example.com"}, + want: "https://mcp.example.com", + }, + { + name: "CaseInsensitiveOriginKeptVerbatim", + serverURL: "https://mcp.example.com/mcp", + advertised: []string{"HTTPS://MCP.Example.com/mcp"}, + want: "HTTPS://MCP.Example.com/mcp", + }, + { + name: "PathCoversSubpath", + serverURL: "https://mcp.example.com/mcp/x", + advertised: []string{"https://mcp.example.com/mcp"}, + want: "https://mcp.example.com/mcp", + }, + { + name: "PathPrefixIsNotSegment", + serverURL: "https://mcp.example.com/mcp2", + advertised: []string{"https://mcp.example.com/mcp"}, + want: "https://mcp.example.com/mcp2", + }, + { + name: "OtherOriginFallsBack", + serverURL: "https://mcp.example.com/mcp", + advertised: []string{"https://other.example.com/mcp", "http://mcp.example.com/mcp", "https://mcp.example.com:8443/mcp"}, + want: "https://mcp.example.com/mcp", + }, + { + name: "MostSpecificWins", + serverURL: "https://mcp.example.com/a/b/c", + advertised: []string{ + "https://mcp.example.com/", + "https://mcp.example.com/a/b", + "https://mcp.example.com/a", + }, + want: "https://mcp.example.com/a/b", + }, + { + name: "NoEntriesFallsBack", + serverURL: "https://mcp.example.com/mcp", + want: "https://mcp.example.com/mcp", + }, + { + name: "FallbackIsCanonical", + serverURL: "HTTPS://user:pass@MCP.Example.COM:8443/Path/MCP?tenant=Acme#frag", + want: "https://mcp.example.com:8443/Path/MCP?tenant=Acme", + }, + { + name: "InvalidEntriesIgnored", + serverURL: "https://mcp.example.com/mcp", + advertised: []string{"https://mcp.example.com/#frag", "/mcp", "", " "}, + want: "https://mcp.example.com/mcp", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + serverURL, err := url.Parse(tc.serverURL) + require.NoError(t, err) + require.Equal(t, tc.want, mcpOAuth2ResourceIndicator(serverURL, tc.advertised)) + }) + } +} diff --git a/coderd/mcp_test.go b/coderd/mcp_test.go index 217343c4910..d3527338e4f 100644 --- a/coderd/mcp_test.go +++ b/coderd/mcp_test.go @@ -1122,6 +1122,7 @@ func TestMCPServerConfigsSecretsNeverLeaked(t *testing.T) { OAuth2AuthURL: "https://auth.example.com/authorize", OAuth2TokenURL: "https://auth.example.com/token", OAuth2RevocationURL: "https://auth.example.com/revoke", + OAuth2Resource: "https://mcp.example.com/secrets", OAuth2Scopes: "read write", APIKeyHeader: "X-Api-Key", APIKeyValue: "THIS-IS-A-SECRET-API-KEY", @@ -1156,6 +1157,7 @@ func TestMCPServerConfigsSecretsNeverLeaked(t *testing.T) { // Verify boolean indicators are set correctly. require.True(t, created.HasOAuth2Secret, "HasOAuth2Secret should be true") + require.Equal(t, "https://mcp.example.com/secrets", created.OAuth2Resource) require.True(t, created.HasAPIKey, "HasAPIKey should be true") require.True(t, created.HasCustomHeaders, "HasCustomHeaders should be true") @@ -1183,6 +1185,7 @@ func TestMCPServerConfigsSecretsNeverLeaked(t *testing.T) { assert.Empty(t, cfg.OAuth2AuthURL, "member should not see OAuth2AuthURL") assert.Empty(t, cfg.OAuth2TokenURL, "member should not see OAuth2TokenURL") assert.Empty(t, cfg.OAuth2RevocationURL, "member should not see OAuth2RevocationURL") + assert.Empty(t, cfg.OAuth2Resource, "member should not see OAuth2Resource") assert.Empty(t, cfg.APIKeyHeader, "member should not see APIKeyHeader") assert.Empty(t, cfg.OAuth2Scopes, "member should not see OAuth2Scopes") assert.Empty(t, cfg.URL, "member should not see URL") @@ -1197,6 +1200,7 @@ func TestMCPServerConfigsSecretsNeverLeaked(t *testing.T) { assert.Empty(t, memberSingle.OAuth2AuthURL, "member should not see OAuth2AuthURL") assert.Empty(t, memberSingle.OAuth2TokenURL, "member should not see OAuth2TokenURL") assert.Empty(t, memberSingle.OAuth2Scopes, "member should not see OAuth2Scopes") + assert.Empty(t, memberSingle.OAuth2Resource, "member should not see OAuth2Resource") assert.Empty(t, memberSingle.APIKeyHeader, "member should not see APIKeyHeader") assert.Empty(t, memberSingle.URL, "member should not see URL") assert.Empty(t, memberSingle.Transport, "member should not see Transport") @@ -1289,6 +1293,7 @@ func TestMCPServerConfigsUserOIDCClearsFields(t *testing.T) { OAuth2AuthURL: "https://auth.example.com/authorize", OAuth2TokenURL: "https://auth.example.com/token", OAuth2RevocationURL: "https://auth.example.com/revoke", + OAuth2Resource: "https://mcp.example.com/v1", OAuth2Scopes: "read write", Availability: "default_off", Enabled: true, @@ -1356,6 +1361,48 @@ func TestMCPServerConfigsUserOIDCClearsFields(t *testing.T) { require.NoError(t, err) require.Equal(t, newRevocationURL, updated.OAuth2RevocationURL) + // RFC 8707 resource indicators must be absolute URIs without a + // fragment, on both create and update. + for _, invalidResource := range []string{"https://mcp.example.com/v1#frag", "/v1/mcp"} { + _, err = client.UpdateMCPServerConfig(ctx, created.OrganizationID, created.ID, codersdk.UpdateMCPServerConfigRequest{ + OAuth2Resource: &invalidResource, + }) + require.ErrorAs(t, err, &sdkErr, invalidResource) + require.Equal(t, http.StatusBadRequest, sdkErr.StatusCode(), invalidResource) + + _, err = client.CreateMCPServerConfig(ctx, firstUser.OrganizationID, codersdk.CreateMCPServerConfigRequest{ + DisplayName: "Invalid Resource", + Slug: "invalid-resource", + Transport: "streamable_http", + URL: "https://mcp.example.com/invalid-resource", + AuthType: "oauth2", + OAuth2ClientID: "cid", + OAuth2AuthURL: "https://auth.example.com/authorize", + OAuth2TokenURL: "https://auth.example.com/token", + OAuth2Resource: invalidResource, + Availability: "default_on", + Enabled: true, + ToolAllowList: []string{}, + ToolDenyList: []string{}, + }) + require.ErrorAs(t, err, &sdkErr, invalidResource) + require.Equal(t, http.StatusBadRequest, sdkErr.StatusCode(), invalidResource) + } + + emptyResource := "" + updated, err = client.UpdateMCPServerConfig(ctx, created.OrganizationID, created.ID, codersdk.UpdateMCPServerConfigRequest{ + OAuth2Resource: &emptyResource, + }) + require.NoError(t, err) + require.Empty(t, updated.OAuth2Resource) + + newResource := "https://mcp.example.com/v2" + updated, err = client.UpdateMCPServerConfig(ctx, created.OrganizationID, created.ID, codersdk.UpdateMCPServerConfigRequest{ + OAuth2Resource: &newResource, + }) + require.NoError(t, err) + require.Equal(t, newResource, updated.OAuth2Resource) + newAuth := "user_oidc" updated, err = client.UpdateMCPServerConfig(ctx, created.OrganizationID, created.ID, codersdk.UpdateMCPServerConfigRequest{ AuthType: &newAuth, @@ -1369,6 +1416,7 @@ func TestMCPServerConfigsUserOIDCClearsFields(t *testing.T) { require.Empty(t, updated.OAuth2AuthURL) require.Empty(t, updated.OAuth2TokenURL) require.Empty(t, updated.OAuth2RevocationURL) + require.Empty(t, updated.OAuth2Resource) require.Empty(t, updated.OAuth2Scopes) require.Empty(t, updated.APIKeyHeader) } @@ -1609,6 +1657,20 @@ func TestMCPServerConfigsUpdateInvalidatesUserGrants(t *testing.T) { require.False(t, tokenExists(ctx, t, config.ID)) }) + t.Run("ResourceChangeDeletesGrants", func(t *testing.T) { + t.Parallel() + ctx := testutil.Context(t, testutil.WaitLong) + config := newConfig(ctx, t, "grant-resource-change") + seedToken(ctx, t, config.ID) + + resource := "https://mcp.example.com/grant-resource-change" + _, err := adminClient.UpdateMCPServerConfig(ctx, config.OrganizationID, config.ID, codersdk.UpdateMCPServerConfigRequest{ + OAuth2Resource: &resource, + }) + require.NoError(t, err) + require.False(t, tokenExists(ctx, t, config.ID)) + }) + t.Run("UnrelatedChangeKeepsGrants", func(t *testing.T) { t.Parallel() ctx := testutil.Context(t, testutil.WaitLong) @@ -1734,6 +1796,15 @@ func TestMCPServerConfigsOAuth2CallbackRejectsSupersededRevocationURL(t *testing }) } +func TestMCPServerConfigsOAuth2CallbackRejectsSupersededResource(t *testing.T) { + t.Parallel() + + movedResource := "https://attacker.example.com/mcp" + runMCPServerConfigsOAuth2CallbackSupersessionTest(t, "superseded-resource-callback", codersdk.UpdateMCPServerConfigRequest{ + OAuth2Resource: &movedResource, + }) +} + func runMCPServerConfigsOAuth2CallbackSupersessionTest( t *testing.T, slug string, @@ -2447,8 +2518,10 @@ func TestMCPServerConfigsOAuth2AutoDiscovery(t *testing.T) { require.Equal(t, authServer.URL+"/token", created.OAuth2TokenURL) require.Equal(t, authServer.URL+"/revoke", created.OAuth2RevocationURL) require.Equal(t, "read write", created.OAuth2Scopes) + // The origin-only PRM resource covers the /v1/mcp server URL. + require.Equal(t, mcpServer.URL, created.OAuth2Resource) - // An explicit revocation URL wins over the discovered one. + // Explicit values win over the discovered ones. overridden, err := client.CreateMCPServerConfig(ctx, firstUser.OrganizationID, codersdk.CreateMCPServerConfigRequest{ DisplayName: "Auto-Discovery Override", Slug: "auto-discovery-override", @@ -2456,6 +2529,7 @@ func TestMCPServerConfigsOAuth2AutoDiscovery(t *testing.T) { URL: mcpServer.URL + "/v1/mcp", AuthType: "oauth2", OAuth2RevocationURL: "https://override.example.com/revoke", + OAuth2Resource: "https://override.example.com/mcp", Availability: "default_on", Enabled: true, ToolAllowList: []string{}, @@ -2463,6 +2537,7 @@ func TestMCPServerConfigsOAuth2AutoDiscovery(t *testing.T) { }) require.NoError(t, err) require.Equal(t, "https://override.example.com/revoke", overridden.OAuth2RevocationURL) + require.Equal(t, "https://override.example.com/mcp", overridden.OAuth2Resource) }) t.Run("CreateOnlyScopeAllowed", func(t *testing.T) { @@ -3101,6 +3176,134 @@ func TestMCPServerConfigsOAuth2AutoDiscoverySSRF(t *testing.T) { } // nolint:bodyclose +// TestMCPServerOAuth2ResourceIndicator runs the connect and callback flow +// against an authorization server that, like Dagster+, rejects requests +// without the expected RFC 8707 resource parameter. +func TestMCPServerOAuth2ResourceIndicator(t *testing.T) { + t.Parallel() + + const resource = "https://mcp.example.com/mcp" + invalidTarget := func(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":"invalid_target","error_description":"MCP OAuth requests must include resource"}`)) + } + authServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/authorize": + if r.URL.Query().Get("resource") != resource { + invalidTarget(w) + return + } + redirect, err := url.Parse(r.URL.Query().Get("redirect_uri")) + if !assert.NoError(t, err) { + http.Error(w, "bad redirect_uri", http.StatusBadRequest) + return + } + q := redirect.Query() + q.Set("code", "resource-auth-code") + q.Set("state", r.URL.Query().Get("state")) + redirect.RawQuery = q.Encode() + http.Redirect(w, r, redirect.String(), http.StatusFound) + case "/token": + if err := r.ParseForm(); err != nil || r.PostForm.Get("resource") != resource { + invalidTarget(w) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"resource-access-token","token_type":"Bearer","expires_in":3600,"refresh_token":"resource-refresh-token"}`)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(authServer.Close) + + adminClient := newMCPClient(t) + firstUser := coderdtest.CreateFirstUser(t, adminClient) + memberClient, _ := coderdtest.CreateAnotherUser(t, adminClient, firstUser.OrganizationID) + memberClient.HTTPClient.CheckRedirect = func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + } + + createConfig := func(ctx context.Context, t *testing.T, slug, oauth2Resource string) codersdk.MCPServerConfig { + t.Helper() + created, err := adminClient.CreateMCPServerConfig(ctx, firstUser.OrganizationID, codersdk.CreateMCPServerConfigRequest{ + DisplayName: "Resource " + slug, + Slug: slug, + Transport: "streamable_http", + URL: "https://mcp.example.com/mcp", + AuthType: "oauth2", + OAuth2ClientID: "resource-client", + OAuth2AuthURL: authServer.URL + "/authorize", + OAuth2TokenURL: authServer.URL + "/token", + OAuth2Resource: oauth2Resource, + Availability: "default_on", + Enabled: true, + ToolAllowList: []string{}, + ToolDenyList: []string{}, + }) + require.NoError(t, err) + return created + } + + connect := func(ctx context.Context, t *testing.T, config codersdk.MCPServerConfig) (*url.URL, []*http.Cookie) { + t.Helper() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, memberClient.MCPServerOAuth2ConnectURL(config.OrganizationID, config.ID), nil) + require.NoError(t, err) + req.AddCookie(&http.Cookie{Name: codersdk.SessionTokenCookie, Value: memberClient.SessionToken()}) + res, err := memberClient.HTTPClient.Do(req) + require.NoError(t, err) + defer res.Body.Close() + require.Equal(t, http.StatusTemporaryRedirect, res.StatusCode) + location, err := res.Location() + require.NoError(t, err) + return location, res.Cookies() + } + + t.Run("ConfiguredResourceIsSent", func(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + config := createConfig(ctx, t, "resource-configured", resource) + authorizeURL, cookies := connect(ctx, t, config) + require.Equal(t, resource, authorizeURL.Query().Get("resource")) + + authReq, err := http.NewRequestWithContext(ctx, http.MethodGet, authorizeURL.String(), nil) + require.NoError(t, err) + authRes, err := memberClient.HTTPClient.Do(authReq) + require.NoError(t, err) + defer authRes.Body.Close() + require.Equal(t, http.StatusFound, authRes.StatusCode, "strict authorization server rejected the authorize request") + callbackURL, err := authRes.Location() + require.NoError(t, err) + + callbackReq, err := http.NewRequestWithContext(ctx, http.MethodGet, callbackURL.String(), nil) + require.NoError(t, err) + callbackReq.AddCookie(&http.Cookie{Name: codersdk.SessionTokenCookie, Value: memberClient.SessionToken()}) + for _, c := range cookies { + callbackReq.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value}) + } + callbackRes, err := memberClient.HTTPClient.Do(callbackReq) + require.NoError(t, err) + defer callbackRes.Body.Close() + require.Equal(t, http.StatusOK, callbackRes.StatusCode, "strict authorization server rejected the code exchange") + + fetched, err := memberClient.MCPServerConfigByID(ctx, config.OrganizationID, config.ID) + require.NoError(t, err) + require.True(t, fetched.AuthConnected, "callback must store the exchanged token") + }) + + t.Run("ManualConfigWithoutResourceSendsNone", func(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + config := createConfig(ctx, t, "resource-unset", "") + authorizeURL, _ := connect(ctx, t, config) + require.False(t, authorizeURL.Query().Has("resource"), + "manual configs without oauth2_resource must not send a resource parameter") + }) +} + func TestMCPServerOAuth2PKCE(t *testing.T) { t.Parallel() diff --git a/coderd/x/chatd/mcpclient/mcpclient.go b/coderd/x/chatd/mcpclient/mcpclient.go index 15359851ef8..8b59367437d 100644 --- a/coderd/x/chatd/mcpclient/mcpclient.go +++ b/coderd/x/chatd/mcpclient/mcpclient.go @@ -24,6 +24,7 @@ import ( "github.com/google/uuid" "github.com/modelcontextprotocol/go-sdk/mcp" "golang.org/x/oauth2" + "golang.org/x/oauth2/clientcredentials" "golang.org/x/sync/errgroup" "golang.org/x/xerrors" @@ -1475,8 +1476,9 @@ func RefreshFailureReason(err error) string { // RefreshOAuth2Token checks whether the given MCP user token is // expired (or within 10 seconds of expiry) and refreshes it using -// the OAuth2 credentials from the server config. If the token is -// still valid, no network call is made and Refreshed is false. +// the OAuth2 credentials from the server config, sending the config's +// RFC 8707 resource indicator when set. If the token is still valid, +// no network call is made and Refreshed is false. // // The caller is responsible for persisting the result when // Refreshed is true. @@ -1486,14 +1488,6 @@ func RefreshOAuth2Token( cfg database.MCPServerConfig, tok database.MCPServerUserToken, ) (RefreshResult, error) { - oauth2Cfg := &oauth2.Config{ - ClientID: cfg.OAuth2ClientID, - ClientSecret: cfg.OAuth2ClientSecret, - Endpoint: oauth2.Endpoint{ - TokenURL: cfg.OAuth2TokenURL, - }, - } - oldToken := &oauth2.Token{ AccessToken: tok.AccessToken, RefreshToken: tok.RefreshToken, @@ -1502,6 +1496,38 @@ func RefreshOAuth2Token( if tok.Expiry.Valid { oldToken.Expiry = tok.Expiry.Time } + // Valid uses a 10-second expiry window, so tokens about to + // expire are also refreshed proactively. + if oldToken.Valid() { + return RefreshResult{ + AccessToken: tok.AccessToken, + RefreshToken: tok.RefreshToken, + TokenType: tok.TokenType, + Expiry: oldToken.Expiry, + }, nil + } + if tok.RefreshToken == "" { + return RefreshResult{}, xerrors.New("refresh oauth2 token: token expired and refresh token is not set") + } + + params := url.Values{ + "grant_type": {"refresh_token"}, + "refresh_token": {tok.RefreshToken}, + } + if cfg.OAuth2Resource != "" { + params.Set("resource", cfg.OAuth2Resource) + } + // oauth2.Config cannot add parameters to refresh requests. The + // clientcredentials token source sends EndpointParams verbatim, + // allows overriding grant_type, and shares oauth2.Config's token + // request code: auth style detection, *oauth2.RetrieveError, and + // keeping the request's refresh_token when the response omits it. + refreshCfg := &clientcredentials.Config{ + ClientID: cfg.OAuth2ClientID, + ClientSecret: cfg.OAuth2ClientSecret, + TokenURL: cfg.OAuth2TokenURL, + EndpointParams: params, + } // Cap the refresh HTTP call so a stalled token endpoint // cannot block the entire MCP connection phase. The timeout @@ -1515,10 +1541,7 @@ func RefreshOAuth2Token( refreshClient.CheckRedirect = safedial.CheckSameOriginRedirect refreshCtx = context.WithValue(refreshCtx, oauth2.HTTPClient, &refreshClient) - // TokenSource automatically refreshes expired tokens. It - // uses a 10-second expiry window, so tokens about to expire - // are also refreshed proactively. - newToken, err := oauth2Cfg.TokenSource(refreshCtx, oldToken).Token() + newToken, err := refreshCfg.Token(refreshCtx) if err != nil { return RefreshResult{}, xerrors.Errorf("refresh oauth2 token: %w", err) } diff --git a/coderd/x/chatd/mcpclient/refresh_test.go b/coderd/x/chatd/mcpclient/refresh_test.go index 1336419729f..5ddac04c43f 100644 --- a/coderd/x/chatd/mcpclient/refresh_test.go +++ b/coderd/x/chatd/mcpclient/refresh_test.go @@ -6,12 +6,14 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "net/url" "strings" "sync/atomic" "testing" "time" "github.com/google/uuid" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/oauth2" "golang.org/x/xerrors" @@ -167,3 +169,118 @@ func TestBuildAuthHeadersSkipsFailedToken(t *testing.T) { require.Equal(t, "Bearer valid", headers["Authorization"]) }) } + +func TestRefreshOAuth2TokenResourceIndicator(t *testing.T) { + t.Parallel() + + const resource = "https://mcp.example.com/mcp" + cases := []struct { + name string + resource string + }{ + {name: "Set", resource: resource}, + {name: "Unset"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + forms := make(chan url.Values, 1) + tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !assert.NoError(t, r.ParseForm()) { + http.Error(w, "bad form", http.StatusBadRequest) + return + } + // Auth style auto-detection may retry a rejected request. + select { + case forms <- r.PostForm: + default: + } + w.Header().Set("Content-Type", "application/json") + if r.PostForm.Get("resource") != tc.resource { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":"invalid_target"}`)) + return + } + _, _ = w.Write([]byte(`{"access_token":"fresh","token_type":"Bearer","expires_in":3600}`)) + })) + defer tokenSrv.Close() + + cfg := database.MCPServerConfig{ + OAuth2ClientID: "cid", + OAuth2TokenURL: tokenSrv.URL, + OAuth2Resource: tc.resource, + } + tok := database.MCPServerUserToken{ + AccessToken: "expired", + RefreshToken: "refresh", + TokenType: "Bearer", + Expiry: sql.NullTime{Time: time.Now().Add(-time.Hour), Valid: true}, + } + + result, err := mcpclient.RefreshOAuth2Token(context.Background(), testMCPHTTPClient(nil), cfg, tok) + require.NoError(t, err) + require.True(t, result.Refreshed) + require.Equal(t, "fresh", result.AccessToken) + // The provider did not rotate, so the stored refresh token is kept. + require.Equal(t, "refresh", result.RefreshToken) + + form := <-forms + require.Equal(t, "refresh_token", form.Get("grant_type")) + require.Equal(t, "refresh", form.Get("refresh_token")) + require.False(t, form.Has("scope")) + if tc.resource == "" { + require.False(t, form.Has("resource")) + } + }) + } +} + +func TestRefreshOAuth2TokenWithoutRequest(t *testing.T) { + t.Parallel() + + var hits atomic.Int64 + tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"fresh","token_type":"Bearer","expires_in":3600}`)) + })) + t.Cleanup(tokenSrv.Close) + + cfg := database.MCPServerConfig{ + OAuth2ClientID: "cid", + OAuth2TokenURL: tokenSrv.URL, + OAuth2Resource: "https://mcp.example.com/mcp", + } + + t.Run("ValidToken", func(t *testing.T) { + t.Parallel() + expiry := time.Now().Add(time.Hour) + result, err := mcpclient.RefreshOAuth2Token(context.Background(), testMCPHTTPClient(nil), cfg, database.MCPServerUserToken{ + AccessToken: "still-valid", + RefreshToken: "refresh", + TokenType: "Bearer", + Expiry: sql.NullTime{Time: expiry, Valid: true}, + }) + require.NoError(t, err) + require.False(t, result.Refreshed) + require.Equal(t, "still-valid", result.AccessToken) + require.Equal(t, "refresh", result.RefreshToken) + require.Equal(t, "Bearer", result.TokenType) + require.True(t, expiry.Equal(result.Expiry)) + }) + + t.Run("ExpiredWithoutRefreshToken", func(t *testing.T) { + t.Parallel() + _, err := mcpclient.RefreshOAuth2Token(context.Background(), testMCPHTTPClient(nil), cfg, database.MCPServerUserToken{ + AccessToken: "expired", + TokenType: "Bearer", + Expiry: sql.NullTime{Time: time.Now().Add(-time.Hour), Valid: true}, + }) + require.Error(t, err) + }) + + t.Cleanup(func() { + require.Zero(t, hits.Load(), "no token request may be made") + }) +} diff --git a/codersdk/mcp.go b/codersdk/mcp.go index af3881cf6d5..0eac21927bf 100644 --- a/codersdk/mcp.go +++ b/codersdk/mcp.go @@ -73,6 +73,7 @@ type MCPServerConfig struct { OAuth2AuthURL string `json:"oauth2_auth_url,omitempty"` OAuth2TokenURL string `json:"oauth2_token_url,omitempty"` OAuth2RevocationURL string `json:"oauth2_revocation_url,omitempty"` + OAuth2Resource string `json:"oauth2_resource,omitempty"` OAuth2Scopes string `json:"oauth2_scopes,omitempty"` // API key fields (only populated for admins). @@ -161,11 +162,15 @@ type CreateMCPServerConfigRequest struct { OAuth2TokenURL string `json:"oauth2_token_url,omitempty" validate:"omitempty,url"` // OAuth2RevocationURL is the provider's RFC 7009 revocation // endpoint; auto-populated by OAuth2 discovery when omitted. - OAuth2RevocationURL string `json:"oauth2_revocation_url,omitempty" validate:"omitempty,url"` - OAuth2Scopes string `json:"oauth2_scopes,omitempty"` - APIKeyHeader string `json:"api_key_header,omitempty"` - APIKeyValue string `json:"api_key_value,omitempty"` - CustomHeaders map[string]string `json:"custom_headers,omitempty"` + OAuth2RevocationURL string `json:"oauth2_revocation_url,omitempty" validate:"omitempty,url"` + // OAuth2Resource is the RFC 8707 resource indicator sent on + // authorization, token, and refresh requests when set; + // auto-populated by OAuth2 discovery when omitted. + OAuth2Resource string `json:"oauth2_resource,omitempty"` + OAuth2Scopes string `json:"oauth2_scopes,omitempty"` + APIKeyHeader string `json:"api_key_header,omitempty"` + APIKeyValue string `json:"api_key_value,omitempty"` + CustomHeaders map[string]string `json:"custom_headers,omitempty"` ToolAllowList []string `json:"tool_allow_list,omitempty"` ToolDenyList []string `json:"tool_deny_list,omitempty"` @@ -200,11 +205,14 @@ type UpdateMCPServerConfigRequest struct { OAuth2TokenURL *string `json:"oauth2_token_url,omitempty" validate:"omitempty,url"` // OAuth2RevocationURL is validated in the handler because a // validate tag would reject the pointer to "" that clears it. - OAuth2RevocationURL *string `json:"oauth2_revocation_url,omitempty"` - OAuth2Scopes *string `json:"oauth2_scopes,omitempty"` - APIKeyHeader *string `json:"api_key_header,omitempty"` - APIKeyValue *string `json:"api_key_value,omitempty"` - CustomHeaders *map[string]string `json:"custom_headers,omitempty"` + OAuth2RevocationURL *string `json:"oauth2_revocation_url,omitempty"` + // OAuth2Resource is the RFC 8707 resource indicator; a pointer + // to "" clears it. + OAuth2Resource *string `json:"oauth2_resource,omitempty"` + OAuth2Scopes *string `json:"oauth2_scopes,omitempty"` + APIKeyHeader *string `json:"api_key_header,omitempty"` + APIKeyValue *string `json:"api_key_value,omitempty"` + CustomHeaders *map[string]string `json:"custom_headers,omitempty"` ToolAllowList *[]string `json:"tool_allow_list,omitempty"` ToolDenyList *[]string `json:"tool_deny_list,omitempty"` diff --git a/docs/admin/security/audit-logs.md b/docs/admin/security/audit-logs.md index 721b1b7aa7a..34cfc133759 100644 --- a/docs/admin/security/audit-logs.md +++ b/docs/admin/security/audit-logs.md @@ -479,6 +479,7 @@ Actions: `create`, `write`, `delete`
oauth2_client_idoauth2_client_secretoauth2_client_secret_key_idoauth2_resourceoauth2_revocation_urloauth2_scopesoauth2_token_url