diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index d4da70ed1d..20143e0ec2 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -12,6 +12,7 @@ import ( "github.com/stacklok/toolhive/pkg/authserver" "github.com/stacklok/toolhive/pkg/authserver/oauthparams" + "github.com/stacklok/toolhive/pkg/authserver/server/registration" "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" "github.com/stacklok/toolhive/pkg/oauthproto" ) @@ -1982,6 +1983,20 @@ type OAuth2UpstreamConfig struct { // //nolint:lll // CEL validation rules exceed line length limit type DCRUpstreamConfig struct { + // ClientName is the optional RFC 7591 "client_name" registration metadata + // sent when ToolHive registers with the upstream. When empty, ToolHive + // registers as "ToolHive MCP Client". It is display-only metadata: the + // upstream shows it on its authorization screen, and it is never used as + // a key. Changing it does not rename an already-registered client; the + // new value applies only the next time ToolHive registers a fresh client, + // for example after rotating via RotationKey, or when the upstream + // rejects the cached registration. Names with leading or trailing + // whitespace, or containing control or format characters, are rejected. + // +optional + // +kubebuilder:validation:MaxLength=256 + // +kubebuilder:validation:Pattern=`^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$` + ClientName string `json:"clientName,omitempty"` + // DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver // issues a single GET against this URL (no well-known-path fallback) and // reads registration_endpoint, authorization_endpoint, token_endpoint, @@ -3192,6 +3207,10 @@ const ( // MaxSoftwareStatementLength matches the MaxLength marker on // DCRUpstreamConfig.SoftwareStatement. MaxSoftwareStatementLength = 16384 + + // MaxDCRClientNameLength matches the MaxLength marker on + // DCRUpstreamConfig.ClientName. + MaxDCRClientNameLength = 256 ) // validateUpstreamCABundleRef validates the source shape shared by OIDC and @@ -3239,6 +3258,9 @@ func ValidateOIDCDCRConfig(cfg *OIDCUpstreamConfig) error { if l := len(cfg.DCRConfig.SoftwareStatement); l > MaxSoftwareStatementLength { return fmt.Errorf("oidcConfig.dcrConfig.softwareStatement: length %d exceeds maximum %d", l, MaxSoftwareStatementLength) } + if err := registration.ValidateClientName(cfg.DCRConfig.ClientName); err != nil { + return fmt.Errorf("oidcConfig.dcrConfig.clientName: %w", err) + } return nil } @@ -3293,6 +3315,9 @@ func ValidateOAuth2DCRConfig(cfg *OAuth2UpstreamConfig) error { "oauth2Config.dcrConfig.softwareStatement: length %d exceeds maximum %d", l, MaxSoftwareStatementLength) } + if err := registration.ValidateClientName(cfg.DCRConfig.ClientName); err != nil { + return fmt.Errorf("oauth2Config.dcrConfig.clientName: %w", err) + } return nil } diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go index 436b183b52..c9d0c3dc10 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go @@ -19,6 +19,13 @@ func makeStringOfLen(n int) string { return strings.Repeat("a", n) } +// makeMultibyteStringOfRunes returns a string of exactly n runes, each 3 bytes +// ("あ"), so its byte length is 3n. Useful for boundary-length tests that must +// distinguish rune counts from byte counts. +func makeMultibyteStringOfRunes(n int) string { + return strings.Repeat("あ", n) +} + // makeURLOfLen returns an https URL whose total length is exactly n. // The host is padded with 'a' characters; useful for boundary-length tests // against +kubebuilder:validation:Pattern URL regexes that require a host. @@ -1939,6 +1946,141 @@ func TestMCPExternalAuthConfig_validateUpstreamProvider(t *testing.T) { expectErr: true, errMsg: "dcrConfig.softwareStatement: length", }, + { + name: "OAuth2 provider with DCRConfig clientName at MaxLength is accepted", + provider: UpstreamProviderConfig{ + Name: "dcr-client-name-at-cap", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + ClientName: makeStringOfLen(MaxDCRClientNameLength), + }, + }, + }, + expectErr: false, + }, + { + name: "OAuth2 provider with DCRConfig clientName over MaxLength is rejected", + provider: UpstreamProviderConfig{ + Name: "dcr-client-name-over-cap", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + ClientName: makeStringOfLen(MaxDCRClientNameLength + 1), + }, + }, + }, + expectErr: true, + errMsg: "dcrConfig.clientName: must be at most 256 characters", + }, + { + name: "OIDC provider with DCRConfig clientName at MaxLength is accepted", + provider: UpstreamProviderConfig{ + Name: "oidc-dcr-client-name-at-cap", + Type: UpstreamProviderTypeOIDC, + OIDCConfig: &OIDCUpstreamConfig{ + IssuerURL: "https://idp.example.com", + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + ClientName: makeStringOfLen(MaxDCRClientNameLength), + }, + }, + }, + expectErr: false, + }, + { + name: "OIDC provider with DCRConfig clientName over MaxLength is rejected", + provider: UpstreamProviderConfig{ + Name: "oidc-dcr-client-name-over-cap", + Type: UpstreamProviderTypeOIDC, + OIDCConfig: &OIDCUpstreamConfig{ + IssuerURL: "https://idp.example.com", + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + ClientName: makeStringOfLen(MaxDCRClientNameLength + 1), + }, + }, + }, + expectErr: true, + errMsg: "oidcConfig.dcrConfig.clientName: must be at most 256 characters", + }, + { + name: "OAuth2 provider with DCRConfig clientName of 256 multibyte runes is accepted", + provider: UpstreamProviderConfig{ + Name: "dcr-client-name-multibyte-at-cap", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + ClientName: makeMultibyteStringOfRunes(MaxDCRClientNameLength), + }, + }, + }, + expectErr: false, + }, + { + name: "OAuth2 provider with DCRConfig clientName of 257 multibyte runes is rejected", + provider: UpstreamProviderConfig{ + Name: "dcr-client-name-multibyte-over-cap", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + ClientName: makeMultibyteStringOfRunes(MaxDCRClientNameLength + 1), + }, + }, + }, + expectErr: true, + errMsg: "dcrConfig.clientName: must be at most 256 characters", + }, + { + name: "OAuth2 provider with DCRConfig whitespace-only clientName is rejected", + provider: UpstreamProviderConfig{ + Name: "dcr-client-name-whitespace-only", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + ClientName: " ", + }, + }, + }, + expectErr: true, + errMsg: "dcrConfig.clientName: must not have leading or trailing whitespace", + }, + { + name: "OIDC provider with DCRConfig whitespace-only clientName is rejected", + provider: UpstreamProviderConfig{ + Name: "oidc-dcr-client-name-whitespace-only", + Type: UpstreamProviderTypeOIDC, + OIDCConfig: &OIDCUpstreamConfig{ + IssuerURL: "https://idp.example.com", + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + ClientName: " ", + }, + }, + }, + expectErr: true, + errMsg: "oidcConfig.dcrConfig.clientName: must not have leading or trailing whitespace", + }, { name: "OAuth2 provider with identityFromToken empty subjectPath rejected", provider: UpstreamProviderConfig{ diff --git a/cmd/thv-operator/pkg/controllerutil/authserver.go b/cmd/thv-operator/pkg/controllerutil/authserver.go index e9c4ff5d31..271970b4a8 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver.go @@ -1718,6 +1718,7 @@ func buildDCRUpstreamRunConfig( initialAccessTokenEnvVar string, ) *authserver.DCRUpstreamConfig { rc := &authserver.DCRUpstreamConfig{ + ClientName: dcr.ClientName, DiscoveryURL: dcr.DiscoveryURL, RegistrationEndpoint: dcr.RegistrationEndpoint, RotationKey: dcr.RotationKey, diff --git a/cmd/thv-operator/pkg/controllerutil/authserver_test.go b/cmd/thv-operator/pkg/controllerutil/authserver_test.go index 2a6de5c8a6..620cde2c2f 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver_test.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver_test.go @@ -1760,6 +1760,7 @@ func TestBuildAuthServerRunConfig(t *testing.T) { TokenEndpoint: "https://idp.example.com/token", UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, DCRConfig: &mcpv1beta1.DCRUpstreamConfig{ + ClientName: "Acme MCP Client", DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", SoftwareID: "toolhive", SoftwareStatement: "jwt-statement", @@ -1782,6 +1783,7 @@ func TestBuildAuthServerRunConfig(t *testing.T) { assert.Empty(t, upstream.OAuth2Config.ClientID, "ClientID should be empty when DCRConfig is used") require.NotNil(t, upstream.OAuth2Config.DCRConfig) + assert.Equal(t, "Acme MCP Client", upstream.OAuth2Config.DCRConfig.ClientName) assert.Equal(t, "https://idp.example.com/.well-known/openid-configuration", upstream.OAuth2Config.DCRConfig.DiscoveryURL) diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml index dd15107102..6acc6e3870 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -1821,6 +1821,20 @@ spec: runtime rather than being pre-provisioned, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -2278,6 +2292,20 @@ spec: and ClientSecretRef must be omitted. If neither discoveryUrl nor registrationEndpoint is set, discovery is derived from issuerUrl. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -4997,6 +5025,20 @@ spec: runtime rather than being pre-provisioned, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -5454,6 +5496,20 @@ spec: and ClientSecretRef must be omitted. If neither discoveryUrl nor registrationEndpoint is set, discovery is derived from issuerUrl. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml index c03b3bec25..d88e8b8a88 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -1708,6 +1708,20 @@ spec: runtime rather than being pre-provisioned, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -2165,6 +2179,20 @@ spec: and ClientSecretRef must be omitted. If neither discoveryUrl nor registrationEndpoint is set, discovery is derived from issuerUrl. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -7276,6 +7304,20 @@ spec: runtime rather than being pre-provisioned, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -7733,6 +7775,20 @@ spec: and ClientSecretRef must be omitted. If neither discoveryUrl nor registrationEndpoint is set, discovery is derived from issuerUrl. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml index 5be6a3c7dc..4adfa14b41 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -1824,6 +1824,20 @@ spec: runtime rather than being pre-provisioned, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -2281,6 +2295,20 @@ spec: and ClientSecretRef must be omitted. If neither discoveryUrl nor registrationEndpoint is set, discovery is derived from issuerUrl. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -5000,6 +5028,20 @@ spec: runtime rather than being pre-provisioned, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -5457,6 +5499,20 @@ spec: and ClientSecretRef must be omitted. If neither discoveryUrl nor registrationEndpoint is set, discovery is derived from issuerUrl. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml index 8cd3fe82d9..a00180c45e 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -1711,6 +1711,20 @@ spec: runtime rather than being pre-provisioned, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -2168,6 +2182,20 @@ spec: and ClientSecretRef must be omitted. If neither discoveryUrl nor registrationEndpoint is set, discovery is derived from issuerUrl. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -7279,6 +7307,20 @@ spec: runtime rather than being pre-provisioned, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver @@ -7736,6 +7778,20 @@ spec: and ClientSecretRef must be omitted. If neither discoveryUrl nor registrationEndpoint is set, discovery is derived from issuerUrl. properties: + clientName: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. Changing it does not rename an already-registered client; the + new value applies only the next time ToolHive registers a fresh client, + for example after rotating via RotationKey, or when the upstream + rejects the cached registration. Names with leading or trailing + whitespace, or containing control or format characters, are rejected. + maxLength: 256 + pattern: ^[^\p{Cc}\p{Cf}\p{Z}]([^\p{Cc}\p{Cf}]*[^\p{Cc}\p{Cf}\p{Z}])?$ + type: string discoveryUrl: description: |- DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver diff --git a/docs/arch/11-auth-server-storage.md b/docs/arch/11-auth-server-storage.md index 7660e79b0c..7aa52ead42 100644 --- a/docs/arch/11-auth-server-storage.md +++ b/docs/arch/11-auth-server-storage.md @@ -87,7 +87,7 @@ The storage layer implements multiple interfaces from the [fosite](https://githu - `PendingAuthorizationStorage` — In-flight authorization tracking. Interactive requests have a single-use `awaiting` consent stage before upstream login; only an `approved` record can complete a callback. Each `PendingAuthorization` carries a `BrowserBindingHash`, the SHA-256 of a random cookie value set on the user agent. The consent POST and `/oauth/callback` require the matching cookie before consuming their respective records. Only the hash is stored; an older row without a binding or approval stage cannot complete the flow and must be restarted. `PendingDeviceLogin` carries the same browser binding for the separate device-flow verification-page login, which shares `/oauth/callback`. - `RememberedConsentStorage` — Optional server-side browser sessions and one approval per `(userID, clientID)`. The browser holds only a random `__Host-thv_consent_` secret; storage holds its SHA-256 digest. Each approval records the redirect URI, scopes, and resource selected for that client. Memory and Redis implement this capability; decorators expose the underlying backend via `storage.Unwrap`. See [Interactive client approval](#interactive-client-approval). - `UserStorage` — Internal user accounts and provider identity linking -- `DCRCredentialStore` — DCR client metadata and credential persistence; intentionally NOT embedded in `Storage` (each backend implements it separately and call sites reach it via an explicit `stor.(DCRCredentialStore)` type assertion). Secret-based clients store hashed secrets; `private_key_jwt` clients store their inline public JWKS and signing algorithm. Outbound (upstream) registrations resolved by `pkg/auth/dcr` are keyed by `(Issuer, UpstreamID, RedirectURI, ScopesHash)` plus the optional operator-set `dcrConfig.rotationKey`. Changing the rotation key addresses a new row, so the next start registers a fresh upstream client; the previous row stays in place and carries no TTL unless the upstream asserted `client_secret_expires_at`. The client registers with the token endpoint auth method the resolver prefers among those the upstream advertises (`client_secret_basic`, then `client_secret_post`, then `none`), or with the OAuth2 upstream's `tokenEndpointAuthMethod` when it is set, for an upstream whose token endpoint does not accept the preferred method. A registration response that names another method than the configured one is refused, and so is a resolution that still names one, such as a row a replica on an older configuration stored first; the next start or recheck replaces that row. On a cache hit the resolver also checks the cached client against the upstream and replaces the row when the upstream rejects it, or when the row was registered with another method than the configured `tokenEndpointAuthMethod`, provided the store implements `dcr.Replacer`. `dcrConfig.registrationProbe` selects the check: `tokenEndpoint` (default) redeems a random authorization code and reads `invalid_client` as "gone"; `authorizationEndpoint` sends an authorization request without following redirects and reads a direct 400/401/403 carrying an RFC 6749 JSON error object with `error` `invalid_client`, `unauthorized_client` or `invalid_request` as "gone" (RFC 6749 §4.1.2.1); `none` skips the upstream check but not the method check above. Each setting has a blind spot the rotation key covers: `tokenEndpoint` misses an upstream that validates the grant before authenticating a public client (it then answers `invalid_grant` for any client_id) and skips `private_key_jwt` clients, which it cannot sign for; `authorizationEndpoint` misses an upstream that renders its unknown-client error with 200, a redirect, or a page rather than a JSON error object; with `none` only the rotation key, or a change of the configured method, retires a registration. A false rejection by either probe re-registers at every start and, when registration also fails, fails startup. The check runs at start; `dcrConfig.registrationProbeInterval` (a Go duration of at least `1m`) repeats it while the server runs. Each tick re-runs the resolution against the stored row: a rejected registration is replaced, a missing one is registered, and when the result names a different client than the one in use, including a row another replica replaced, the upstream provider switches to it in place (`upstream.ClientCredentialsUpdater`; OIDC providers also replace their ID token verifier). A failed tick is logged and leaves the provider on its current client. An authorization started under the previous client and completed after the switch redeems its code with the new client, and upstream refresh tokens bound to the previous client stop refreshing, as with a restart. Each tick sends at most one probe request to the upstream from every replica (none with `registrationProbe: none`), plus a registration request when the probe rejects the client; the `tokenEndpoint` probe appears in upstream logs as a failed code redemption, so an interval of 5m to 15m suits most upstreams. Endpoints the run config leaves to discovery follow the new registration, and each replica waits a random part of the interval before its first tick and the interval ±10% after that. +- `DCRCredentialStore` — DCR client metadata and credential persistence; intentionally NOT embedded in `Storage` (each backend implements it separately and call sites reach it via an explicit `stor.(DCRCredentialStore)` type assertion). Secret-based clients store hashed secrets; `private_key_jwt` clients store their inline public JWKS and signing algorithm. Outbound (upstream) registrations resolved by `pkg/auth/dcr` are keyed by `(Issuer, UpstreamID, RedirectURI, ScopesHash)` plus the optional operator-set `dcrConfig.rotationKey`. `dcrConfig.clientName` sets the RFC 7591 `client_name` sent at registration; when empty, ToolHive registers as "ToolHive MCP Client". It is display-only metadata shown on the upstream's authorization screen and is never part of the registration's cache key, so changing it does not rename an already-registered client: the new value applies only the next time ToolHive registers a fresh client, for example after rotating via `rotationKey`. It is capped at 256 characters. Names with leading or trailing whitespace, or containing control or format characters, are rejected. Changing the rotation key addresses a new row, so the next start registers a fresh upstream client; the previous row stays in place and carries no TTL unless the upstream asserted `client_secret_expires_at`. The client registers with the token endpoint auth method the resolver prefers among those the upstream advertises (`client_secret_basic`, then `client_secret_post`, then `none`), or with the OAuth2 upstream's `tokenEndpointAuthMethod` when it is set, for an upstream whose token endpoint does not accept the preferred method. A registration response that names another method than the configured one is refused, and so is a resolution that still names one, such as a row a replica on an older configuration stored first; the next start or recheck replaces that row. On a cache hit the resolver also checks the cached client against the upstream and replaces the row when the upstream rejects it, or when the row was registered with another method than the configured `tokenEndpointAuthMethod`, provided the store implements `dcr.Replacer`. `dcrConfig.registrationProbe` selects the check: `tokenEndpoint` (default) redeems a random authorization code and reads `invalid_client` as "gone"; `authorizationEndpoint` sends an authorization request without following redirects and reads a direct 400/401/403 carrying an RFC 6749 JSON error object with `error` `invalid_client`, `unauthorized_client` or `invalid_request` as "gone" (RFC 6749 §4.1.2.1); `none` skips the upstream check but not the method check above. Each setting has a blind spot the rotation key covers: `tokenEndpoint` misses an upstream that validates the grant before authenticating a public client (it then answers `invalid_grant` for any client_id) and skips `private_key_jwt` clients, which it cannot sign for; `authorizationEndpoint` misses an upstream that renders its unknown-client error with 200, a redirect, or a page rather than a JSON error object; with `none` only the rotation key, or a change of the configured method, retires a registration. A false rejection by either probe re-registers at every start and, when registration also fails, fails startup. The check runs at start; `dcrConfig.registrationProbeInterval` (a Go duration of at least `1m`) repeats it while the server runs. Each tick re-runs the resolution against the stored row: a rejected registration is replaced, a missing one is registered, and when the result names a different client than the one in use, including a row another replica replaced, the upstream provider switches to it in place (`upstream.ClientCredentialsUpdater`; OIDC providers also replace their ID token verifier). A failed tick is logged and leaves the provider on its current client. An authorization started under the previous client and completed after the switch redeems its code with the new client, and upstream refresh tokens bound to the previous client stop refreshing, as with a restart. Each tick sends at most one probe request to the upstream from every replica (none with `registrationProbe: none`), plus a registration request when the probe rejects the client; the `tokenEndpoint` probe appears in upstream logs as a failed code redemption, so an interval of 5m to 15m suits most upstreams. Endpoints the run config leaves to discovery follow the new registration, and each replica waits a random part of the interval before its first tick and the interval ±10% after that. - `AssertionJWTConsumer` — atomic single-use consumption for validated JWT assertions. It is deliberately separate from `Storage`, so only assertion-grant composition requires replay protection. - `ExchangeGrantStorage` — optional server-side records behind refresh tokens issued through RFC 8693 token exchange. A callable discovers it with `storage.Unwrap(stor).(ExchangeGrantStorage)`. Memory and Redis implement it. See [Exchange grant storage](#exchange-grant-storage). diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index f80621a716..00f92194e9 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -1964,6 +1964,7 @@ _Appears in:_ | Field | Description | Default | Validation | | --- | --- | --- | --- | +| `clientName` _string_ | ClientName is the optional RFC 7591 "client_name" registration metadata
sent when ToolHive registers with the upstream. When empty, ToolHive
registers as "ToolHive MCP Client". It is display-only metadata: the
upstream shows it on its authorization screen, and it is never used as
a key. Changing it does not rename an already-registered client; the
new value applies only the next time ToolHive registers a fresh client,
for example after rotating via RotationKey, or when the upstream
rejects the cached registration. Names with leading or trailing
whitespace, or containing control or format characters, are rejected. | | MaxLength: 256
Pattern: `^[^\p\{Cc\}\p\{Cf\}\p\{Z\}]([^\p\{Cc\}\p\{Cf\}]*[^\p\{Cc\}\p\{Cf\}\p\{Z\}])?$`
Optional: \{\}
| | `discoveryUrl` _string_ | DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver
issues a single GET against this URL (no well-known-path fallback) and
reads registration_endpoint, authorization_endpoint, token_endpoint,
token_endpoint_auth_methods_supported, and scopes_supported from the
response.
Mutually exclusive with RegistrationEndpoint.
HTTPS is required because the registration endpoint resolved from this
document carries the initial access token and the issued client_secret
(RFC 7591 §3, RFC 8414 §3). MaxLength is a defensive size cap (etcd
object budget, regex evaluation cost) and matches the conventional URL
length cap. | | MaxLength: 2048
Pattern: `^https://[^\s?#]+[^/\s?#]$`
Optional: \{\}
| | `registrationEndpoint` _string_ | RegistrationEndpoint is the RFC 7591 registration endpoint URL used
directly, bypassing discovery. When using this field, the caller is
expected to also supply AuthorizationEndpoint, TokenEndpoint, and an
explicit Scopes list on the parent OAuth2UpstreamConfig.
Mutually exclusive with DiscoveryURL.
HTTPS is required because the registration endpoint carries the initial
access token and the issued client_secret (RFC 7591 §3, RFC 8414 §3).
MaxLength is a defensive size cap (etcd object budget, regex evaluation
cost) and matches the conventional URL length cap. | | MaxLength: 2048
Pattern: `^https://[^\s?#]+[^/\s?#]$`
Optional: \{\}
| | `rotationKey` _string_ | RotationKey is an optional operator-chosen label that is part of the
cached registration's identity but is never sent to the upstream.
Change it to make the proxies register a fresh client at their next
start instead of reusing the cached one: for example after the
upstream has dropped the registration, or when a rotation is required.
At start ToolHive checks the cached client at the upstream (see
RegistrationProbe) and registers a new one by itself when the upstream
rejects it. Where the configured probe cannot tell, the stale client_id
may only be rejected in the user's browser, and changing this key is
the remedy. The previous registration's row stays in storage, and
upstream refresh tokens bound to the previous client_id stop
refreshing, so affected users sign in again. | | MaxLength: 64
Pattern: `^[A-Za-z0-9._-]+$`
Optional: \{\}
| diff --git a/docs/server/docs.go b/docs/server/docs.go index b4af426c0f..fa512bbf32 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -141,6 +141,10 @@ const docTemplate = `{ "authserver.DCRUpstreamConfig": { "description": "DCRConfig enables RFC 7591 Dynamic Client Registration against the\nupstream authorization server. When set, the client credentials are\nobtained at runtime rather than being pre-provisioned via ClientID /\nClientSecretFile / ClientSecretEnvVar, and ClientID must be left empty.\nMutually exclusive with ClientID.", "properties": { + "client_name": { + "description": "ClientName is the optional RFC 7591 \"client_name\" registration metadata\nsent when ToolHive registers with the upstream. When empty, ToolHive\nregisters as \"ToolHive MCP Client\". It is display-only metadata: the\nupstream shows it on its authorization screen, and it is never used as\na key. It is capped at 256 characters, matching the client_name bound\nthe authserver enforces on inbound registrations. Names with leading\nor trailing whitespace, or containing control or format characters,\nare rejected.\n\nChanging it does not rename an already-registered client: the cached\nregistration is keyed without the client name, so the new value applies\nonly the next time ToolHive registers a fresh client — for example\nafter rotating via RotationKey, or when the upstream rejects the cached\nregistration.", + "type": "string" + }, "discovery_url": { "description": "DiscoveryURL is the exact RFC 8414 / OIDC Discovery document URL to\nfetch at runtime. The resolver issues a single GET against this URL\n(no well-known-path fallback) and reads registration_endpoint,\nauthorization_endpoint, token_endpoint,\ntoken_endpoint_auth_methods_supported, and scopes_supported from the\nresponse. Per RFC 8414 §3.3, the document's \"issuer\" field must\nexactly match the upstream issuer configured on the parent\nrun-config.\n\nUse this field when the upstream publishes discovery metadata at a\npath that differs from the issuer-derived well-known paths — for\nexample a multi-tenant IdP whose metadata lives at\nhttps://idp.example.com/tenants/acme/.well-known/openid-configuration.\n\nMutually exclusive with RegistrationEndpoint.", "type": "string" diff --git a/docs/server/swagger.json b/docs/server/swagger.json index e398fc00bc..0cd2d39876 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -134,6 +134,10 @@ "authserver.DCRUpstreamConfig": { "description": "DCRConfig enables RFC 7591 Dynamic Client Registration against the\nupstream authorization server. When set, the client credentials are\nobtained at runtime rather than being pre-provisioned via ClientID /\nClientSecretFile / ClientSecretEnvVar, and ClientID must be left empty.\nMutually exclusive with ClientID.", "properties": { + "client_name": { + "description": "ClientName is the optional RFC 7591 \"client_name\" registration metadata\nsent when ToolHive registers with the upstream. When empty, ToolHive\nregisters as \"ToolHive MCP Client\". It is display-only metadata: the\nupstream shows it on its authorization screen, and it is never used as\na key. It is capped at 256 characters, matching the client_name bound\nthe authserver enforces on inbound registrations. Names with leading\nor trailing whitespace, or containing control or format characters,\nare rejected.\n\nChanging it does not rename an already-registered client: the cached\nregistration is keyed without the client name, so the new value applies\nonly the next time ToolHive registers a fresh client — for example\nafter rotating via RotationKey, or when the upstream rejects the cached\nregistration.", + "type": "string" + }, "discovery_url": { "description": "DiscoveryURL is the exact RFC 8414 / OIDC Discovery document URL to\nfetch at runtime. The resolver issues a single GET against this URL\n(no well-known-path fallback) and reads registration_endpoint,\nauthorization_endpoint, token_endpoint,\ntoken_endpoint_auth_methods_supported, and scopes_supported from the\nresponse. Per RFC 8414 §3.3, the document's \"issuer\" field must\nexactly match the upstream issuer configured on the parent\nrun-config.\n\nUse this field when the upstream publishes discovery metadata at a\npath that differs from the issuer-derived well-known paths — for\nexample a multi-tenant IdP whose metadata lives at\nhttps://idp.example.com/tenants/acme/.well-known/openid-configuration.\n\nMutually exclusive with RegistrationEndpoint.", "type": "string" diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml index ad31f13168..de4e4393ff 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -160,6 +160,23 @@ components: ClientSecretFile / ClientSecretEnvVar, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + client_name: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. It is capped at 256 characters, matching the client_name bound + the authserver enforces on inbound registrations. Names with leading + or trailing whitespace, or containing control or format characters, + are rejected. + + Changing it does not rename an already-registered client: the cached + registration is keyed without the client name, so the new value applies + only the next time ToolHive registers a fresh client — for example + after rotating via RotationKey, or when the upstream rejects the cached + registration. + type: string discovery_url: description: |- DiscoveryURL is the exact RFC 8414 / OIDC Discovery document URL to diff --git a/pkg/authserver/config.go b/pkg/authserver/config.go index 9e8e6771cc..0073337602 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -1548,6 +1548,22 @@ type OAuth2UpstreamRunConfig struct { // surface), this field becomes a confused-deputy SSRF vector. Hardening is // tracked in https://github.com/stacklok/toolhive/issues/5135. type DCRUpstreamConfig struct { + // ClientName is the optional RFC 7591 "client_name" registration metadata + // sent when ToolHive registers with the upstream. When empty, ToolHive + // registers as "ToolHive MCP Client". It is display-only metadata: the + // upstream shows it on its authorization screen, and it is never used as + // a key. It is capped at 256 characters, matching the client_name bound + // the authserver enforces on inbound registrations. Names with leading + // or trailing whitespace, or containing control or format characters, + // are rejected. + // + // Changing it does not rename an already-registered client: the cached + // registration is keyed without the client name, so the new value applies + // only the next time ToolHive registers a fresh client — for example + // after rotating via RotationKey, or when the upstream rejects the cached + // registration. + ClientName string `json:"client_name,omitempty" yaml:"client_name,omitempty"` + // DiscoveryURL is the exact RFC 8414 / OIDC Discovery document URL to // fetch at runtime. The resolver issues a single GET against this URL // (no well-known-path fallback) and reads registration_endpoint, @@ -2730,10 +2746,8 @@ func (c *DCRUpstreamConfig) Validate() error { "dcr_config: initial_access_token_file and initial_access_token_env_var are mutually exclusive") } - // Mirrors the CRD's Pattern/MaxLength markers on rotationKey for the - // YAML and CLI run-config paths, which have no admission-time schema. - if c.RotationKey != "" && !dcrRotationKeyPattern.MatchString(c.RotationKey) { - return fmt.Errorf("dcr_config: rotation_key must be 1-64 characters from [A-Za-z0-9._-]") + if err := c.validateRegistrationMetadata(); err != nil { + return err } // Mirrors the CRD's Enum marker on registrationProbe; the resolver owns @@ -2749,6 +2763,27 @@ func (c *DCRUpstreamConfig) Validate() error { return nil } +// validateRegistrationMetadata checks the DCR registration metadata fields: +// the rotation key shape and the client name length and character class. +// Split out of Validate to keep that method's cyclomatic complexity down +// instead of suppressing the linter. +func (c *DCRUpstreamConfig) validateRegistrationMetadata() error { + // Mirrors the CRD's Pattern/MaxLength markers on rotationKey for the + // YAML and CLI run-config paths, which have no admission-time schema. + if c.RotationKey != "" && !dcrRotationKeyPattern.MatchString(c.RotationKey) { + return fmt.Errorf("dcr_config: rotation_key must be 1-64 characters from [A-Za-z0-9._-]") + } + + // Length and character class are enforced by registration.ValidateClientName, + // which mirrors the CRD's MaxLength marker on clientName and the inbound + // registration bound (registration.MaxClientNameLength). The length is + // counted in characters, matching the CRD's maxLength semantics. + if err := registration.ValidateClientName(c.ClientName); err != nil { + return fmt.Errorf("dcr_config: client_name: %w", err) + } + return nil +} + // MinRegistrationProbeInterval is the shortest RegistrationProbeInterval // accepted: each check sends a request to the upstream from every replica. const MinRegistrationProbeInterval = time.Minute diff --git a/pkg/authserver/config_test.go b/pkg/authserver/config_test.go index 165954ef68..1b3754b4f1 100644 --- a/pkg/authserver/config_test.go +++ b/pkg/authserver/config_test.go @@ -2182,6 +2182,40 @@ func TestDCRUpstreamConfigValidate(t *testing.T) { wantErr: true, errMsg: "rotation_key must be 1-64 characters", }, + { + name: "client_name at the 256-character cap passes validation", + config: DCRUpstreamConfig{ + RegistrationEndpoint: "https://idp.example.com/register", + ClientName: strings.Repeat("a", registration.MaxClientNameLength), + }, + }, + { + name: "client_name longer than 256 characters rejects", + config: DCRUpstreamConfig{ + RegistrationEndpoint: "https://idp.example.com/register", + ClientName: strings.Repeat("a", registration.MaxClientNameLength+1), + }, + wantErr: true, + errMsg: "client_name: must be at most 256 characters", + }, + { + name: "client_name with only whitespace rejects", + config: DCRUpstreamConfig{ + RegistrationEndpoint: "https://idp.example.com/register", + ClientName: " ", + }, + wantErr: true, + errMsg: "client_name: must not have leading or trailing whitespace", + }, + { + name: "client_name with a control character rejects", + config: DCRUpstreamConfig{ + RegistrationEndpoint: "https://idp.example.com/register", + ClientName: "name\nwith-newline", + }, + wantErr: true, + errMsg: "client_name: must not contain control or format characters", + }, { name: "registration_probe authorizationEndpoint accepts", config: DCRUpstreamConfig{ diff --git a/pkg/authserver/runner/dcr_adapter.go b/pkg/authserver/runner/dcr_adapter.go index 3b392173e2..45cf13510e 100644 --- a/pkg/authserver/runner/dcr_adapter.go +++ b/pkg/authserver/runner/dcr_adapter.go @@ -91,6 +91,7 @@ func newDCRRequest(rc *authserver.UpstreamRunConfig, localIssuer string) (*dcr.R return &dcr.Request{ Issuer: localIssuer, RedirectURI: redirectURI, Scopes: scopes, DiscoveryURL: discoveryURL, RegistrationEndpoint: dcrConfig.RegistrationEndpoint, + ClientName: dcrConfig.ClientName, RotationKey: dcrConfig.RotationKey, RegistrationProbe: dcr.RegistrationProbe(dcrConfig.RegistrationProbe), TokenEndpointAuthMethod: authMethod, diff --git a/pkg/authserver/runner/dcr_adapter_test.go b/pkg/authserver/runner/dcr_adapter_test.go index 11678f0d6d..bb54f54b51 100644 --- a/pkg/authserver/runner/dcr_adapter_test.go +++ b/pkg/authserver/runner/dcr_adapter_test.go @@ -298,6 +298,7 @@ func TestNewDCRRequest(t *testing.T) { wantRotationKey string wantRegistrationProbe dcr.RegistrationProbe wantAuthMethod string + wantClientName string }{ { name: "discovery_url branch resolves file-based initial access token", @@ -362,6 +363,23 @@ func TestNewDCRRequest(t *testing.T) { wantRegistration: "https://idp.example.com/register", wantRotationKey: "2026-10", }, + { + // Pins the ClientName copy onto dcr.Request: without it a + // client_name configured on the run-config would silently keep + // registering as the hardcoded "ToolHive MCP Client". + name: "client_name propagates from run-config", + rc: &authserver.OAuth2UpstreamRunConfig{ + Scopes: []string{"openid"}, + DCRConfig: &authserver.DCRUpstreamConfig{ + RegistrationEndpoint: "https://idp.example.com/register", + ClientName: "Acme MCP Client", + }, + }, + localIssuer: "https://thv.example.com", + wantIssuer: "https://thv.example.com", + wantRegistration: "https://idp.example.com/register", + wantClientName: "Acme MCP Client", + }, { // Pins the RegistrationProbe copy onto dcr.Request: without it an // upstream configured for the authorization-endpoint probe would @@ -423,6 +441,7 @@ func TestNewDCRRequest(t *testing.T) { assert.Equal(t, tc.wantRotationKey, req.RotationKey) assert.Equal(t, tc.wantRegistrationProbe, req.RegistrationProbe) assert.Equal(t, tc.wantAuthMethod, req.TokenEndpointAuthMethod) + assert.Equal(t, tc.wantClientName, req.ClientName) }) } } diff --git a/pkg/authserver/server/registration/dcr.go b/pkg/authserver/server/registration/dcr.go index 740f3e2d2d..bef8626eb1 100644 --- a/pkg/authserver/server/registration/dcr.go +++ b/pkg/authserver/server/registration/dcr.go @@ -21,6 +21,8 @@ import ( "fmt" "slices" "strings" + "unicode" + "unicode/utf8" "github.com/go-jose/go-jose/v4" "github.com/ory/fosite" @@ -86,6 +88,34 @@ const ( MaxSoftwareIDLength = 256 ) +// ValidateClientName rejects client names longer than MaxClientNameLength +// characters (counted in runes, matching the CRD's maxLength semantics) and +// names that would reach an upstream authorization screen verbatim with +// control or format runes (newlines, NUL, bidi overrides, zero-width +// characters) or with leading or trailing whitespace, including +// whitespace-only names that would display blank. +// It mirrors the consent page's displayClientName stripping +// (pkg/authserver/server/handlers) as a rejection instead of a silent +// strip, so a bad value fails fast at admission, reconcile, and run-config +// time. An empty name is valid: it selects the default client name. +func ValidateClientName(name string) error { + if name == "" { + return nil + } + if l := utf8.RuneCountInString(name); l > MaxClientNameLength { + return fmt.Errorf("must be at most %d characters", MaxClientNameLength) + } + if strings.TrimSpace(name) != name { + return fmt.Errorf("must not have leading or trailing whitespace") + } + for _, r := range name { + if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + return fmt.Errorf("must not contain control or format characters") + } + } + return nil +} + // DCRError represents an OAuth 2.0 Dynamic Client Registration error // response per RFC 7591 Section 3.2.2. type DCRError struct { diff --git a/pkg/authserver/server/registration/dcr_test.go b/pkg/authserver/server/registration/dcr_test.go index f158568a55..a5b9e2103d 100644 --- a/pkg/authserver/server/registration/dcr_test.go +++ b/pkg/authserver/server/registration/dcr_test.go @@ -577,6 +577,43 @@ func TestValidateDCRRequest(t *testing.T) { } } +func TestValidateClientName(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + client string + wantErr bool + }{ + {name: "empty name is valid (selects the default)", client: ""}, + {name: "plain name is valid", client: "ToolHive MCP Client (ibkr)"}, + {name: "internal space is valid", client: "My Application"}, + {name: "whitespace-only name is rejected", client: " ", wantErr: true}, + {name: "leading whitespace is rejected", client: " lead", wantErr: true}, + {name: "trailing whitespace is rejected", client: "trail ", wantErr: true}, + {name: "newline is rejected", client: "line\nbreak", wantErr: true}, + {name: "NUL is rejected", client: "nul\x00byte", wantErr: true}, + {name: "bidi override is rejected", client: "a\u202eb", wantErr: true}, + {name: "zero-width space is rejected", client: "a\u200bb", wantErr: true}, + {name: "256 ASCII runes are accepted", client: strings.Repeat("a", MaxClientNameLength)}, + {name: "257 ASCII runes are rejected", client: strings.Repeat("a", MaxClientNameLength+1), wantErr: true}, + {name: "256 multibyte runes are accepted", client: strings.Repeat("あ", MaxClientNameLength)}, + {name: "257 multibyte runes are rejected", client: strings.Repeat("あ", MaxClientNameLength+1), wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := ValidateClientName(tt.client) + if tt.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } +} + func TestValidatePrivateKeyJWTRegistration(t *testing.T) { t.Parallel() validKey := jose.JSONWebKey{Key: testRSAPublicKey(t), KeyID: "key-1", Algorithm: string(jose.RS256), Use: "sig"} diff --git a/sdk/go/client/oas_json_gen.go b/sdk/go/client/oas_json_gen.go index 376d67596a..5fdc12b862 100644 --- a/sdk/go/client/oas_json_gen.go +++ b/sdk/go/client/oas_json_gen.go @@ -1027,6 +1027,12 @@ func (s *AuthenticationDCRUpstreamConfig) Encode(e *jx.Encoder) { // encodeFields encodes fields. func (s *AuthenticationDCRUpstreamConfig) encodeFields(e *jx.Encoder) { + { + if s.ClientName.Set { + e.FieldStart("client_name") + s.ClientName.Encode(e) + } + } { if s.DiscoveryURL.Set { e.FieldStart("discovery_url") @@ -1083,16 +1089,17 @@ func (s *AuthenticationDCRUpstreamConfig) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAuthenticationDCRUpstreamConfig = [9]string{ - 0: "discovery_url", - 1: "initial_access_token_env_var", - 2: "initial_access_token_file", - 3: "registration_endpoint", - 4: "registration_probe", - 5: "registration_probe_interval", - 6: "rotation_key", - 7: "software_id", - 8: "software_statement", +var jsonFieldsNameOfAuthenticationDCRUpstreamConfig = [10]string{ + 0: "client_name", + 1: "discovery_url", + 2: "initial_access_token_env_var", + 3: "initial_access_token_file", + 4: "registration_endpoint", + 5: "registration_probe", + 6: "registration_probe_interval", + 7: "rotation_key", + 8: "software_id", + 9: "software_statement", } // Decode decodes AuthenticationDCRUpstreamConfig from json. @@ -1103,6 +1110,16 @@ func (s *AuthenticationDCRUpstreamConfig) Decode(d *jx.Decoder) error { if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { switch string(k) { + case "client_name": + if err := func() error { + s.ClientName.Reset() + if err := s.ClientName.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"client_name\"") + } case "discovery_url": if err := func() error { s.DiscoveryURL.Reset() diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index a6bc35df43..33d2655c98 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -590,6 +590,20 @@ func (s *AuthenticationCIMDRunConfig) SetEnabled(val OptBool) { // Mutually exclusive with ClientID. // Ref: #/components/schemas/AuthenticationDCRUpstreamConfig type AuthenticationDCRUpstreamConfig struct { + // ClientName is the optional RFC 7591 "client_name" registration metadata + // sent when ToolHive registers with the upstream. When empty, ToolHive + // registers as "ToolHive MCP Client". It is display-only metadata: the + // upstream shows it on its authorization screen, and it is never used as + // a key. It is capped at 256 characters, matching the client_name bound + // the authserver enforces on inbound registrations. Names with leading + // or trailing whitespace, or containing control or format characters, + // are rejected. + // Changing it does not rename an already-registered client: the cached + // registration is keyed without the client name, so the new value applies + // only the next time ToolHive registers a fresh client — for example + // after rotating via RotationKey, or when the upstream rejects the cached + // registration. + ClientName OptString `json:"client_name"` // DiscoveryURL is the exact RFC 8414 / OIDC Discovery document URL to // fetch at runtime. The resolver issues a single GET against this URL // (no well-known-path fallback) and reads registration_endpoint, @@ -673,6 +687,11 @@ type AuthenticationDCRUpstreamConfig struct { SoftwareStatement OptString `json:"software_statement"` } +// GetClientName returns the value of ClientName. +func (s *AuthenticationDCRUpstreamConfig) GetClientName() OptString { + return s.ClientName +} + // GetDiscoveryURL returns the value of DiscoveryURL. func (s *AuthenticationDCRUpstreamConfig) GetDiscoveryURL() OptString { return s.DiscoveryURL @@ -718,6 +737,11 @@ func (s *AuthenticationDCRUpstreamConfig) GetSoftwareStatement() OptString { return s.SoftwareStatement } +// SetClientName sets the value of ClientName. +func (s *AuthenticationDCRUpstreamConfig) SetClientName(val OptString) { + s.ClientName = val +} + // SetDiscoveryURL sets the value of DiscoveryURL. func (s *AuthenticationDCRUpstreamConfig) SetDiscoveryURL(val OptString) { s.DiscoveryURL = val diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index 67d9178d18..9adadd2681 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -215,6 +215,10 @@ "AuthenticationDCRUpstreamConfig": { "description": "DCRConfig enables RFC 7591 Dynamic Client Registration against the\nupstream authorization server. When set, the client credentials are\nobtained at runtime rather than being pre-provisioned via ClientID /\nClientSecretFile / ClientSecretEnvVar, and ClientID must be left empty.\nMutually exclusive with ClientID.", "properties": { + "client_name": { + "description": "ClientName is the optional RFC 7591 \"client_name\" registration metadata\nsent when ToolHive registers with the upstream. When empty, ToolHive\nregisters as \"ToolHive MCP Client\". It is display-only metadata: the\nupstream shows it on its authorization screen, and it is never used as\na key. It is capped at 256 characters, matching the client_name bound\nthe authserver enforces on inbound registrations. Names with leading\nor trailing whitespace, or containing control or format characters,\nare rejected.\n\nChanging it does not rename an already-registered client: the cached\nregistration is keyed without the client name, so the new value applies\nonly the next time ToolHive registers a fresh client — for example\nafter rotating via RotationKey, or when the upstream rejects the cached\nregistration.", + "type": "string" + }, "discovery_url": { "description": "DiscoveryURL is the exact RFC 8414 / OIDC Discovery document URL to\nfetch at runtime. The resolver issues a single GET against this URL\n(no well-known-path fallback) and reads registration_endpoint,\nauthorization_endpoint, token_endpoint,\ntoken_endpoint_auth_methods_supported, and scopes_supported from the\nresponse. Per RFC 8414 §3.3, the document's \"issuer\" field must\nexactly match the upstream issuer configured on the parent\nrun-config.\n\nUse this field when the upstream publishes discovery metadata at a\npath that differs from the issuer-derived well-known paths — for\nexample a multi-tenant IdP whose metadata lives at\nhttps://idp.example.com/tenants/acme/.well-known/openid-configuration.\n\nMutually exclusive with RegistrationEndpoint.", "type": "string" diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml index 8075c91e15..91c1fedad4 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -236,6 +236,23 @@ components: ClientSecretFile / ClientSecretEnvVar, and ClientID must be left empty. Mutually exclusive with ClientID. properties: + client_name: + description: |- + ClientName is the optional RFC 7591 "client_name" registration metadata + sent when ToolHive registers with the upstream. When empty, ToolHive + registers as "ToolHive MCP Client". It is display-only metadata: the + upstream shows it on its authorization screen, and it is never used as + a key. It is capped at 256 characters, matching the client_name bound + the authserver enforces on inbound registrations. Names with leading + or trailing whitespace, or containing control or format characters, + are rejected. + + Changing it does not rename an already-registered client: the cached + registration is keyed without the client name, so the new value applies + only the next time ToolHive registers a fresh client — for example + after rotating via RotationKey, or when the upstream rejects the cached + registration. + type: string discovery_url: description: |- DiscoveryURL is the exact RFC 8414 / OIDC Discovery document URL to