From a2c0391a4560ddf3f86ac3fbfd98d8b4063a8aec Mon Sep 17 00:00:00 2001 From: QuentinBisson Date: Fri, 27 Nov 2026 09:29:14 +0100 Subject: [PATCH 1/5] feat: configure OAuth through mcp-oauth OAUTH_* variables The server reads its OAuth settings with oauthconfig.SettingsFromEnv (mcp-oauth v1.24.0). The --oauth-*, --dex-*, --google-*, --sso-allow-private-ip-jwks-hosts and --allow-public-client-registration flags and their variables map onto the OAUTH_* names for one more release and log a deprecation warning. OAUTH_PROVIDER=github is refused at startup: it issues no ID token. Created clusters' OIDC takes the Dex issuer from OAUTH_DEX_ISSUER_URL and its CA from OAUTH_DEX_CA_FILE. The chart renders the OAUTH_* variables from its existing values and no longer passes the no-op allowPrivateURLs and allowPrivateIPs values. --- cmd/oauth_env.go | 127 ++++++++++ cmd/oauth_env_test.go | 121 ++++++++++ cmd/serve.go | 136 +++++++---- cmd/serve_test.go | 59 ++++- go.mod | 2 +- go.sum | 4 +- helm/cluster-manager/README.md | 6 +- .../cluster-manager/templates/deployment.yaml | 59 ++--- .../cluster-manager/tests/oauth_env_test.yaml | 115 +++++++++ .../oauth_private_ip_jwks_hosts_test.yaml | 28 +++ .../tests/oauth_private_urls_test.yaml | 49 ---- helm/cluster-manager/values.schema.json | 6 +- helm/cluster-manager/values.yaml | 15 +- internal/server/dexproxy_test.go | 18 +- internal/server/oauth.go | 221 +++++++----------- internal/server/oauth_metadata_test.go | 2 +- internal/server/oauth_realchain_test.go | 26 +-- internal/server/oauth_test.go | 103 ++++---- 18 files changed, 744 insertions(+), 353 deletions(-) create mode 100644 cmd/oauth_env.go create mode 100644 cmd/oauth_env_test.go create mode 100644 helm/cluster-manager/tests/oauth_env_test.yaml create mode 100644 helm/cluster-manager/tests/oauth_private_ip_jwks_hosts_test.yaml delete mode 100644 helm/cluster-manager/tests/oauth_private_urls_test.yaml diff --git a/cmd/oauth_env.go b/cmd/oauth_env.go new file mode 100644 index 0000000..6f99197 --- /dev/null +++ b/cmd/oauth_env.go @@ -0,0 +1,127 @@ +package cmd + +import ( + "errors" + "log/slog" + "os" + "strconv" + "strings" + + "github.com/giantswarm/mcp-oauth/oauthconfig" +) + +// deprecatedOAuthOption is a flag whose setting mcp-oauth's OAUTH_* variable +// Replacement holds. Env is the variable that also sets the flag, if any. +type deprecatedOAuthOption struct { + Flag string + Env string + Replacement string +} + +// oauthEnvironment returns the OAUTH_* variables to set before +// oauthconfig.SettingsFromEnv reads them: each deprecated option's value under +// its replacement, then cluster-manager's defaults. A variable lookup finds +// wins over both. The second result lists the deprecated options in use. +func oauthEnvironment(o *serveOptions, lookup func(string) (string, bool)) (map[string]string, []deprecatedOAuthOption) { + set := map[string]string{} + var deprecated []deprecatedOAuthOption + present := func(name string) bool { + if _, ok := set[name]; ok { + return true + } + for _, candidate := range []string{name, name + "_FILE"} { + if v, ok := lookup(candidate); ok && v != "" { + return true + } + } + return false + } + value := func(name string) string { + if v, ok := set[name]; ok { + return v + } + v, _ := lookup(name) + return v + } + + authorizationServer := true + if raw, ok := lookup("OAUTH_ENABLE_AUTHORIZATION_SERVER"); ok { + if parsed, err := strconv.ParseBool(raw); err == nil { + authorizationServer = parsed + } + } + publicRegistration := "" + if o.allowPublicClientRegistration { + publicRegistration = "true" + } + for _, option := range []struct { + deprecatedOAuthOption + value string + }{ + {deprecatedOAuthOption{"oauth-base-url", "CLUSTER_MANAGER_OAUTH_BASE_URL", "OAUTH_ISSUER"}, o.oauthBaseURL}, + {deprecatedOAuthOption{"oauth-provider", "CLUSTER_MANAGER_OAUTH_PROVIDER", "OAUTH_PROVIDER"}, o.oauthProvider}, + {deprecatedOAuthOption{"dex-issuer-url", "DEX_ISSUER_URL", "OAUTH_DEX_ISSUER_URL"}, o.dexIssuerURL}, + {deprecatedOAuthOption{"dex-client-id", "DEX_CLIENT_ID", "OAUTH_DEX_CLIENT_ID"}, o.dexClientID}, + {deprecatedOAuthOption{"dex-client-secret", "DEX_CLIENT_SECRET", "OAUTH_DEX_CLIENT_SECRET"}, o.dexClientSecret}, + {deprecatedOAuthOption{"dex-ca-file", "DEX_CA_FILE", "OAUTH_DEX_CA_FILE"}, o.dexCAFile}, + {deprecatedOAuthOption{"google-client-id", "GOOGLE_CLIENT_ID", "OAUTH_GOOGLE_CLIENT_ID"}, o.googleClientID}, + {deprecatedOAuthOption{"google-client-secret", "GOOGLE_CLIENT_SECRET", "OAUTH_GOOGLE_CLIENT_SECRET"}, o.googleClientSecret}, + {deprecatedOAuthOption{"oauth-trusted-audiences", "", "OAUTH_TRUSTED_AUDIENCES"}, o.oauthTrustedAudiences}, + {deprecatedOAuthOption{"sso-allow-private-ip-jwks-hosts", "SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS", "OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS"}, o.ssoAllowPrivateIPJWKSHosts}, + {deprecatedOAuthOption{"allow-public-client-registration", "CLUSTER_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION", "OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION"}, publicRegistration}, + } { + // The flag's default is the replacement itself when Env is empty. + if option.value == "" || option.value == value(option.Replacement) { + continue + } + deprecated = append(deprecated, option.deprecatedOAuthOption) + // mcp-oauth refuses OAUTH_PROVIDER with the authorization server off. + if option.Replacement == "OAUTH_PROVIDER" && !authorizationServer { + continue + } + if !present(option.Replacement) { + set[option.Replacement] = option.value + } + } + + if authorizationServer && !present("OAUTH_PROVIDER") { + set["OAUTH_PROVIDER"] = "dex" + } + if !present("OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS") { + set["OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS"] = "true" + } + if issuer := value("OAUTH_ISSUER"); value("OAUTH_PROVIDER") == "google" && issuer != "" && !present("OAUTH_GOOGLE_REDIRECT_URL") { + set["OAUTH_GOOGLE_REDIRECT_URL"] = strings.TrimRight(issuer, "/") + "/oauth/callback" + } + return set, deprecated +} + +// loadOAuthSettings reads mcp-oauth's settings from the OAUTH_* variables, +// after setting those that deprecated options and cluster-manager's defaults +// supply. +func loadOAuthSettings(o *serveOptions, log *slog.Logger) (oauthconfig.Settings, error) { + set, deprecated := oauthEnvironment(o, os.LookupEnv) + for _, option := range deprecated { + source := "--" + option.Flag + if option.Env != "" { + source += " (" + option.Env + ")" + } + log.Warn(source+" is deprecated and will be removed in the next minor release: set "+option.Replacement, + "replacement", option.Replacement) + } + for name, v := range set { + if err := os.Setenv(name, v); err != nil { + return oauthconfig.Settings{}, err + } + } + settings, err := oauthconfig.SettingsFromEnv() + if err != nil { + return oauthconfig.Settings{}, err + } + // GitHub issues no ID token: the caller's identity and, with + // --downstream-oauth, the token presented to Kubernetes come from one. + if settings.GitHub != nil { + return oauthconfig.Settings{}, errors.New("OAUTH_PROVIDER=github is not supported: use dex or google, which issue OpenID Connect ID tokens") + } + return settings, nil +} diff --git a/cmd/oauth_env_test.go b/cmd/oauth_env_test.go new file mode 100644 index 0000000..9f009d3 --- /dev/null +++ b/cmd/oauth_env_test.go @@ -0,0 +1,121 @@ +package cmd + +import ( + "bytes" + "log/slog" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestOAuthEnvironment(t *testing.T) { + tests := []struct { + name string + options serveOptions + environment map[string]string + wantSet map[string]string + wantDeprecated []string + }{ + { + name: "OAUTH_* only: cluster-manager's defaults fill the gaps", + environment: map[string]string{"OAUTH_ISSUER": "https://cm.example.com", "OAUTH_DEX_ISSUER_URL": "https://dex.example.com"}, + wantSet: map[string]string{"OAUTH_PROVIDER": "dex", "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "true"}, + }, + { + name: "deprecated dex options map to their replacements", + options: serveOptions{oauthBaseURL: "https://cm.example.com", oauthProvider: "dex", dexIssuerURL: "https://dex.example.com", + dexClientID: "cluster-manager", dexClientSecret: "secret", dexCAFile: "/ca/ca.crt", oauthTrustedAudiences: "agent-platform,kubernetes", + ssoAllowPrivateIPJWKSHosts: "keys.internal", allowPublicClientRegistration: true}, + wantSet: map[string]string{ + "OAUTH_ISSUER": "https://cm.example.com", "OAUTH_PROVIDER": "dex", "OAUTH_DEX_ISSUER_URL": "https://dex.example.com", + "OAUTH_DEX_CLIENT_ID": "cluster-manager", "OAUTH_DEX_CLIENT_SECRET": "secret", "OAUTH_DEX_CA_FILE": "/ca/ca.crt", + "OAUTH_TRUSTED_AUDIENCES": "agent-platform,kubernetes", "OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS": "keys.internal", + "OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION": "true", "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "true", + }, + wantDeprecated: []string{"oauth-base-url", "oauth-provider", "dex-issuer-url", "dex-client-id", "dex-client-secret", "dex-ca-file", + "oauth-trusted-audiences", "sso-allow-private-ip-jwks-hosts", "allow-public-client-registration"}, + }, + { + name: "deprecated google options get the callback as redirect URL", + options: serveOptions{oauthBaseURL: "https://cm.example.com/", oauthProvider: "google", googleClientID: "id", googleClientSecret: "secret"}, + wantSet: map[string]string{ + "OAUTH_ISSUER": "https://cm.example.com/", "OAUTH_PROVIDER": "google", "OAUTH_GOOGLE_CLIENT_ID": "id", + "OAUTH_GOOGLE_CLIENT_SECRET": "secret", "OAUTH_GOOGLE_REDIRECT_URL": "https://cm.example.com/oauth/callback", + "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "true", + }, + wantDeprecated: []string{"oauth-base-url", "oauth-provider", "google-client-id", "google-client-secret"}, + }, + { + name: "an OAUTH_* variable wins over the deprecated option, which is still reported", + options: serveOptions{dexIssuerURL: "https://old.example.com", dexClientSecret: "old"}, + environment: map[string]string{"OAUTH_DEX_ISSUER_URL": "https://new.example.com", "OAUTH_DEX_CLIENT_SECRET_FILE": "/secret", + "OAUTH_PROVIDER": "dex", "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "false"}, + wantSet: map[string]string{}, + wantDeprecated: []string{"dex-issuer-url", "dex-client-secret"}, + }, + { + name: "trusted audiences read from their own variable are not a deprecated option", + options: serveOptions{oauthTrustedAudiences: "agent-platform"}, + environment: map[string]string{"OAUTH_TRUSTED_AUDIENCES": "agent-platform"}, + wantSet: map[string]string{"OAUTH_PROVIDER": "dex", "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "true"}, + }, + { + name: "no provider default with the authorization server off", + environment: map[string]string{"OAUTH_ENABLE_AUTHORIZATION_SERVER": "false"}, + wantSet: map[string]string{"OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "true"}, + }, + { + name: "a deprecated provider is reported but not set with the authorization server off", + options: serveOptions{oauthProvider: "dex"}, + environment: map[string]string{"OAUTH_ENABLE_AUTHORIZATION_SERVER": "false"}, + wantSet: map[string]string{"OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "true"}, + wantDeprecated: []string{"oauth-provider"}, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + lookup := func(name string) (string, bool) { + v, ok := tc.environment[name] + return v, ok + } + set, deprecated := oauthEnvironment(&tc.options, lookup) + assert.Equal(t, tc.wantSet, set) + var flags []string + for _, option := range deprecated { + flags = append(flags, option.Flag) + } + assert.Equal(t, tc.wantDeprecated, flags) + }) + } +} + +func TestLoadOAuthSettingsFromDeprecatedOptions(t *testing.T) { + for _, name := range []string{"OAUTH_ISSUER", "OAUTH_PROVIDER", "OAUTH_DEX_ISSUER_URL", "OAUTH_DEX_CLIENT_ID", "OAUTH_DEX_CLIENT_SECRET", + "OAUTH_TRUSTED_AUDIENCES", "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS"} { + t.Setenv(name, "") + } + var output bytes.Buffer + settings, err := loadOAuthSettings(&serveOptions{oauthBaseURL: "https://cm.example.com", dexIssuerURL: "https://dex.example.com", + dexClientID: "cluster-manager", dexClientSecret: "dex-secret-value", oauthTrustedAudiences: "agent-platform"}, + slog.New(slog.NewTextHandler(&output, nil))) + require.NoError(t, err) + require.NotNil(t, settings.Dex) + assert.Equal(t, "https://dex.example.com", settings.Dex.IssuerURL) + assert.Equal(t, "https://cm.example.com/oauth/callback", settings.Dex.RedirectURL) + assert.Equal(t, "https://cm.example.com", settings.Server.Issuer) + assert.Equal(t, []string{"agent-platform"}, settings.Server.TrustedAudiences) + assert.True(t, settings.Server.EnableClientIDMetadataDocuments) + assert.Contains(t, output.String(), "--dex-issuer-url (DEX_ISSUER_URL) is deprecated and will be removed in the next minor release: set OAUTH_DEX_ISSUER_URL") + assert.NotContains(t, output.String(), "dex-secret-value", "no secret value is logged") +} + +func TestLoadOAuthSettingsRefusesGitHub(t *testing.T) { + for name, value := range map[string]string{"OAUTH_ISSUER": "https://cm.example.com", "OAUTH_PROVIDER": "github", + "OAUTH_GITHUB_CLIENT_ID": "id", "OAUTH_GITHUB_CLIENT_SECRET": "secret", "OAUTH_GITHUB_REDIRECT_URL": "https://cm.example.com/oauth/callback"} { + t.Setenv(name, value) + } + t.Setenv("OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS", "") + _, err := loadOAuthSettings(&serveOptions{}, slog.New(slog.DiscardHandler)) + require.ErrorContains(t, err, "OAUTH_PROVIDER=github is not supported") +} diff --git a/cmd/serve.go b/cmd/serve.go index 350300f..4ac9372 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -2,6 +2,7 @@ package cmd import ( "context" + "encoding/json" "errors" "fmt" "log/slog" @@ -9,11 +10,12 @@ import ( "os" "os/signal" "strconv" - "strings" "syscall" "time" "github.com/giantswarm/gitops-commit/commit" + "github.com/giantswarm/mcp-oauth/oauthconfig" + oauthserver "github.com/giantswarm/mcp-oauth/server" "github.com/giantswarm/mcp-toolkit/metrics" "github.com/giantswarm/mcp-toolkit/tracing" "github.com/spf13/cobra" @@ -99,25 +101,25 @@ environment variable named next to it; flags win over the environment.`, f.BoolVar(&o.operatorDCGMExporter, "gpu-operator-dcgm-exporter", envBool("CLUSTER_MANAGER_GPU_OPERATOR_DCGM_EXPORTER", false), "Run NVIDIA's DCGM exporter on the GPU pools' nodes through the composed -gpu-operator release (its dcgmExporter.enabled), for an installation whose observability scrapes it; off by default — nothing scrapes it out of the box, and on a fresh pool node it is an image pull and a pod initialising DCGM on the GPU while the device plugin brings nvidia.com/gpu up (CLUSTER_MANAGER_GPU_OPERATOR_DCGM_EXPORTER)") f.StringVar(&o.installation, "installation", envOr("CLUSTER_MANAGER_INSTALLATION", ""), "Name of the installation: the Cluster of that name is reported as the installation's own cluster by list_clusters (CLUSTER_MANAGER_INSTALLATION)") f.DurationVar(&o.applyBudget, "apply-budget", envDuration("CLUSTER_MANAGER_APPLY_BUDGET", tools.DefaultApplyBudget), "How long a write call (create_node_pool, enable_model_serving, delete_node_pool, disable_model_serving) may take before it stops writing and answers with what it did, the rest pending for the re-run: the aggregator's deadline for an upstream tool call less the answer's way back; a deadline the request carries wins when earlier (CLUSTER_MANAGER_APPLY_BUDGET)") - f.StringVar(&o.clusterOIDCClientID, "cluster-oidc-client-id", envOr("CLUSTER_MANAGER_CLUSTER_OIDC_CLIENT_ID", ""), "Audience a cluster create_cluster makes accepts in the person's id_token: the cross-client audience muster requests at login, the one the installation's own apiserver trusts (dex-k8s-authenticator on Giant Swarm installations). With the Dex issuer (--dex-issuer-url, its CA from --dex-ca-file) it is composed into the cluster's global.controlPlane.oidc; empty composes none and the cluster trusts no identity provider (CLUSTER_MANAGER_CLUSTER_OIDC_CLIENT_ID)") + f.StringVar(&o.clusterOIDCClientID, "cluster-oidc-client-id", envOr("CLUSTER_MANAGER_CLUSTER_OIDC_CLIENT_ID", ""), "Audience a cluster create_cluster makes accepts in the person's id_token: the cross-client audience muster requests at login, the one the installation's own apiserver trusts (dex-k8s-authenticator on Giant Swarm installations). With the Dex issuer (OAUTH_DEX_ISSUER_URL, its CA from OAUTH_DEX_CA_FILE), else the OAUTH_TRUSTED_ISSUERS entry marked openIDProvider (its caFile), it is composed into the cluster's global.controlPlane.oidc; empty composes none and the cluster trusts no identity provider (CLUSTER_MANAGER_CLUSTER_OIDC_CLIENT_ID)") f.StringVar(&o.clusterOIDCUsernameClaim, "cluster-oidc-username-claim", envOr("CLUSTER_MANAGER_CLUSTER_OIDC_USERNAME_CLAIM", "email"), "id_token claim a created cluster's apiserver takes as the username (CLUSTER_MANAGER_CLUSTER_OIDC_USERNAME_CLAIM)") f.StringVar(&o.clusterOIDCGroupsClaim, "cluster-oidc-groups-claim", envOr("CLUSTER_MANAGER_CLUSTER_OIDC_GROUPS_CLAIM", "groups"), "id_token claim a created cluster's apiserver takes as the groups (CLUSTER_MANAGER_CLUSTER_OIDC_GROUPS_CLAIM)") f.BoolVar(&o.mcpEnabled, "mcp-enabled", envBool("CLUSTER_MANAGER_MCP_ENABLED", true), "Serve the MCP streamable-HTTP endpoint (CLUSTER_MANAGER_MCP_ENABLED)") f.StringVar(&o.mcpPath, "mcp-path", envOr("CLUSTER_MANAGER_MCP_PATH", "/mcp"), "MCP endpoint path (CLUSTER_MANAGER_MCP_PATH)") - f.BoolVar(&o.oauthEnabled, "enable-oauth", envBool("CLUSTER_MANAGER_OAUTH_ENABLED", false), "Require an OAuth 2.1 bearer token on the MCP endpoint, validated against the platform IdP (mcp-oauth); the caller's identity travels with every request (CLUSTER_MANAGER_OAUTH_ENABLED)") - f.StringVar(&o.oauthBaseURL, "oauth-base-url", envOr("CLUSTER_MANAGER_OAUTH_BASE_URL", ""), "Public base URL of this server: the issuer of its OAuth metadata, https or loopback http (CLUSTER_MANAGER_OAUTH_BASE_URL)") - f.StringVar(&o.oauthProvider, "oauth-provider", envOr("CLUSTER_MANAGER_OAUTH_PROVIDER", server.ProviderDex), "Identity provider: dex or google (CLUSTER_MANAGER_OAUTH_PROVIDER)") - f.StringVar(&o.dexIssuerURL, "dex-issuer-url", envOr("DEX_ISSUER_URL", ""), "Dex issuer URL (DEX_ISSUER_URL)") - f.StringVar(&o.dexClientID, "dex-client-id", envOr("DEX_CLIENT_ID", ""), "Dex client ID (DEX_CLIENT_ID)") - f.StringVar(&o.dexClientSecret, "dex-client-secret", envOr("DEX_CLIENT_SECRET", ""), "Dex client secret (DEX_CLIENT_SECRET)") - f.StringVar(&o.dexCAFile, "dex-ca-file", envOr("DEX_CA_FILE", ""), "PEM CA bundle of a Dex with a private certificate; verifies discovery, token and JWKS calls (DEX_CA_FILE)") + f.BoolVar(&o.oauthEnabled, "enable-oauth", envBool("CLUSTER_MANAGER_OAUTH_ENABLED", false), "Require an OAuth 2.1 bearer token on the MCP endpoint (mcp-oauth, configured by the OAUTH_* variables); the caller's identity travels with every request (CLUSTER_MANAGER_OAUTH_ENABLED)") + f.StringVar(&o.oauthBaseURL, "oauth-base-url", envOr("CLUSTER_MANAGER_OAUTH_BASE_URL", ""), "Deprecated: set OAUTH_ISSUER, the public base URL of this server (CLUSTER_MANAGER_OAUTH_BASE_URL)") + f.StringVar(&o.oauthProvider, "oauth-provider", envOr("CLUSTER_MANAGER_OAUTH_PROVIDER", ""), "Deprecated: set OAUTH_PROVIDER (dex, the default, or google) (CLUSTER_MANAGER_OAUTH_PROVIDER)") + f.StringVar(&o.dexIssuerURL, "dex-issuer-url", envOr("DEX_ISSUER_URL", ""), "Deprecated: set OAUTH_DEX_ISSUER_URL (DEX_ISSUER_URL)") + f.StringVar(&o.dexClientID, "dex-client-id", envOr("DEX_CLIENT_ID", ""), "Deprecated: set OAUTH_DEX_CLIENT_ID (DEX_CLIENT_ID)") + f.StringVar(&o.dexClientSecret, "dex-client-secret", envOr("DEX_CLIENT_SECRET", ""), "Deprecated: set OAUTH_DEX_CLIENT_SECRET or OAUTH_DEX_CLIENT_SECRET_FILE (DEX_CLIENT_SECRET)") + f.StringVar(&o.dexCAFile, "dex-ca-file", envOr("DEX_CA_FILE", ""), "Deprecated: set OAUTH_DEX_CA_FILE, the PEM CA bundle of a Dex with a private certificate (DEX_CA_FILE)") f.BoolVar(&o.dexAllowPrivateIP, "allow-private-oauth-urls", envBool("CLUSTER_MANAGER_OAUTH_ALLOW_PRIVATE_URLS", false), "Deprecated, no effect: the Dex client reaches private addresses and follows HTTP_PROXY, HTTPS_PROXY and NO_PROXY without it (CLUSTER_MANAGER_OAUTH_ALLOW_PRIVATE_URLS)") - f.StringVar(&o.googleClientID, "google-client-id", envOr("GOOGLE_CLIENT_ID", ""), "Google OAuth client ID (GOOGLE_CLIENT_ID)") - f.StringVar(&o.googleClientSecret, "google-client-secret", envOr("GOOGLE_CLIENT_SECRET", ""), "Google OAuth client secret (GOOGLE_CLIENT_SECRET)") - f.StringVar(&o.oauthTrustedAudiences, "oauth-trusted-audiences", envOr("OAUTH_TRUSTED_AUDIENCES", ""), "Comma-separated OAuth client IDs whose IdP id_tokens are accepted as bearer tokens — the platform client muster forwards tokens for and the portal logs in with (OAUTH_TRUSTED_AUDIENCES)") + f.StringVar(&o.googleClientID, "google-client-id", envOr("GOOGLE_CLIENT_ID", ""), "Deprecated: set OAUTH_GOOGLE_CLIENT_ID (GOOGLE_CLIENT_ID)") + f.StringVar(&o.googleClientSecret, "google-client-secret", envOr("GOOGLE_CLIENT_SECRET", ""), "Deprecated: set OAUTH_GOOGLE_CLIENT_SECRET or OAUTH_GOOGLE_CLIENT_SECRET_FILE (GOOGLE_CLIENT_SECRET)") + f.StringVar(&o.oauthTrustedAudiences, "oauth-trusted-audiences", envOr("OAUTH_TRUSTED_AUDIENCES", ""), "Deprecated flag: set OAUTH_TRUSTED_AUDIENCES, the comma-separated OAuth client IDs whose IdP id_tokens are accepted as bearer tokens") f.BoolVar(&o.ssoAllowPrivateIPs, "sso-allow-private-ips", envBool("SSO_ALLOW_PRIVATE_IPS", false), "Deprecated, no effect: the issuer host's JWKS endpoint may resolve to a private address without it; list any other JWKS host in --sso-allow-private-ip-jwks-hosts (SSO_ALLOW_PRIVATE_IPS)") - f.StringVar(&o.ssoAllowPrivateIPJWKSHosts, "sso-allow-private-ip-jwks-hosts", envOr("SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS", ""), "Comma-separated hosts, other than the issuer's own, whose JWKS may resolve to an RFC 1918 or RFC 4193 address: a jwks_uri the IdP's discovery document puts on another host. Loopback and link-local stay refused (SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS)") - f.BoolVar(&o.allowPublicClientRegistration, "allow-public-client-registration", envBool("CLUSTER_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION", false), "Accept unauthenticated dynamic client registration; labs only (CLUSTER_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION)") + f.StringVar(&o.ssoAllowPrivateIPJWKSHosts, "sso-allow-private-ip-jwks-hosts", envOr("SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS", ""), "Deprecated: set OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS (SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS)") + f.BoolVar(&o.allowPublicClientRegistration, "allow-public-client-registration", envBool("CLUSTER_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION", false), "Deprecated: set OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION (CLUSTER_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION)") f.BoolVar(&o.downstreamOAuth, "downstream-oauth", envBool("CLUSTER_MANAGER_DOWNSTREAM_OAUTH", false), "Call the Kubernetes API as the caller, with the caller's IdP token, for everything a request does — the ServiceAccount holds no permissions (the chart renders none). Needs --enable-oauth and an apiserver that trusts the IdP (CLUSTER_MANAGER_DOWNSTREAM_OAUTH)") f.StringVar(&o.githubAPIURL, "github-api-url", envOr("CLUSTER_MANAGER_GITHUB_API_URL", server.DefaultGitHubAPIURL), "GitHub REST API base URL for GET /user on the fetched grant and commit mode's pull request (CLUSTER_MANAGER_GITHUB_API_URL)") f.StringVar(&o.githubExchangeEndpoint, "github-token-exchange-endpoint", envOr("CLUSTER_MANAGER_GITHUB_TOKEN_EXCHANGE_ENDPOINT", ""), "RFC 8693 endpoint (muster's broker) that releases the person's GitHub App user grant for commit mode, in place of the App-pinned registration (CLUSTER_MANAGER_GITHUB_TOKEN_EXCHANGE_ENDPOINT)") @@ -144,7 +146,14 @@ func runServe(ctx context.Context, o *serveOptions) error { if o.downstreamOAuth && !o.oauthEnabled { return fmt.Errorf("--downstream-oauth needs --enable-oauth: without OAuth there is no caller token to present to the Kubernetes API") } - if err := validateGitHubExchange(o); err != nil { + var oauthSettings oauthconfig.Settings + if o.oauthEnabled { + var err error + if oauthSettings, err = loadOAuthSettings(o, log); err != nil { + return fmt.Errorf("oauth: %w", err) + } + } + if err := validateGitHubExchange(o, oauthSettings.Dex != nil); err != nil { return err } @@ -200,7 +209,7 @@ func runServe(ctx context.Context, o *serveOptions) error { return tools.Clients{Dynamic: target.Dynamic, Discovery: target.Discovery}, nil } toolsCfg := tools.Config{Installation: o.installation, ModelManagerNamespace: o.modelManagerNamespace, ServingNamespace: o.servingNamespace, CacheClaimName: o.servingCacheClaim, SliceChartVersion: o.sliceChartVersion, TenantServiceAccount: o.tenantServiceAccount, CertificateIssuer: o.certificateIssuer, OperatorDCGMExporter: o.operatorDCGMExporter, ApplyBudget: o.applyBudget} - if toolsCfg.ClusterOIDC, err = o.clusterOIDC(); err != nil { + if toolsCfg.ClusterOIDC, err = o.clusterOIDC(oauthSettings, log); err != nil { return err } opts := []tools.Option{ @@ -228,20 +237,7 @@ func runServe(ctx context.Context, o *serveOptions) error { cfg := server.Config{Addr: o.listen, MCPEnabled: o.mcpEnabled, MCPPath: o.mcpPath} if o.oauthEnabled { - cfg.OAuth = &server.OAuthConfig{ - BaseURL: o.oauthBaseURL, - Provider: o.oauthProvider, - DexIssuerURL: o.dexIssuerURL, - DexClientID: o.dexClientID, - DexClientSecret: o.dexClientSecret, - DexCAFile: o.dexCAFile, - GoogleClientID: o.googleClientID, - GoogleClientSecret: o.googleClientSecret, - TrustedAudiences: splitList(o.oauthTrustedAudiences), - AllowPrivateIPJWKSHosts: splitList(o.ssoAllowPrivateIPJWKSHosts), - AllowPublicClientRegistration: o.allowPublicClientRegistration, - DownstreamOAuth: o.downstreamOAuth, - } + cfg.OAuth = &server.OAuthConfig{Settings: oauthSettings, DownstreamOAuth: o.downstreamOAuth} } srv, err := server.New(cfg, api.NewMCPServer(svc, version), log) if err != nil { @@ -254,16 +250,6 @@ func runServe(ctx context.Context, o *serveOptions) error { return srv.Run(ctx) } -func splitList(s string) []string { - var out []string - for _, p := range strings.Split(s, ",") { - if p = strings.TrimSpace(p); p != "" { - out = append(out, p) - } - } - return out -} - func envOr(key, def string) string { if v, ok := os.LookupEnv(key); ok && v != "" { return v @@ -296,38 +282,86 @@ func envBool(key string, def bool) bool { } // clusterOIDC is the identity provider a created cluster is composed to -// trust: the Dex this server validates the person's id_token against, with -// the audience the installation's apiserver accepts. Nil without a Dex or an -// audience. -func (o *serveOptions) clusterOIDC() (*compose.ClusterOIDC, error) { - if !o.oauthEnabled || o.oauthProvider != server.ProviderDex || o.dexIssuerURL == "" || o.clusterOIDCClientID == "" { +// trust: the Dex this server signs people in with, else the trusted issuer +// marked as the OpenID Provider (its CA from its caFile), with the audience +// the installation's apiserver accepts. Nil without an audience or such a +// provider; the latter is logged, since the --cluster-oidc-* flags then have +// no effect. +func (o *serveOptions) clusterOIDC(settings oauthconfig.Settings, log *slog.Logger) (*compose.ClusterOIDC, error) { + if !o.oauthEnabled || o.clusterOIDCClientID == "" { + return nil, nil + } + var issuer, caFile string + switch provider, ok := openIDProvider(settings.TrustedIssuers); { + case settings.Dex != nil && settings.Dex.IssuerURL != "": + issuer, caFile = settings.Dex.IssuerURL, os.Getenv("OAUTH_DEX_CA_FILE") + case ok: + issuer = provider.Issuer + var err error + if caFile, err = trustedIssuerCAFile(os.Getenv("OAUTH_TRUSTED_ISSUERS"), issuer); err != nil { + return nil, err + } + default: + log.Warn("created clusters trust no identity provider: --cluster-oidc-client-id is set, but there is neither a Dex provider (OAUTH_DEX_ISSUER_URL) nor a trusted issuer marked openIDProvider (OAUTH_TRUSTED_ISSUERS)") return nil, nil } - out := &compose.ClusterOIDC{IssuerURL: o.dexIssuerURL, ClientID: o.clusterOIDCClientID, UsernameClaim: o.clusterOIDCUsernameClaim, GroupsClaim: o.clusterOIDCGroupsClaim} - if o.dexCAFile != "" { - ca, err := os.ReadFile(o.dexCAFile) + out := &compose.ClusterOIDC{IssuerURL: issuer, ClientID: o.clusterOIDCClientID, UsernameClaim: o.clusterOIDCUsernameClaim, GroupsClaim: o.clusterOIDCGroupsClaim} + if caFile != "" { + ca, err := os.ReadFile(caFile) // #nosec G304 G703 -- operator-provided path if err != nil { - return nil, fmt.Errorf("read the Dex CA for the created clusters' OIDC: %w", err) + return nil, fmt.Errorf("read the identity provider's CA for the created clusters' OIDC: %w", err) } out.CAPem = string(ca) } return out, nil } +// openIDProvider is the trusted issuer people sign in with, if one is marked. +func openIDProvider(issuers []oauthserver.TrustedIssuer) (oauthserver.TrustedIssuer, bool) { + for _, issuer := range issuers { + if issuer.OpenIDProvider { + return issuer, true + } + } + return oauthserver.TrustedIssuer{}, false +} + +// trustedIssuerCAFile is the caFile of the OAUTH_TRUSTED_ISSUERS entry for +// issuer: mcp-oauth keeps only the loaded pool, and a created cluster needs +// the PEM. +func trustedIssuerCAFile(raw, issuer string) (string, error) { + if raw == "" { + return "", nil + } + var entries []struct { + Issuer string `json:"issuer"` + CAFile string `json:"caFile"` + } + if err := json.Unmarshal([]byte(raw), &entries); err != nil { + return "", fmt.Errorf("OAUTH_TRUSTED_ISSUERS: %w", err) + } + for _, entry := range entries { + if entry.Issuer == issuer { + return entry.CAFile, nil + } + } + return "", nil +} + func (o *serveOptions) gitHubExchangeConfig() server.GitHubExchangeConfig { return server.GitHubExchangeConfig{TokenEndpoint: o.githubExchangeEndpoint, ClientID: o.githubExchangeClient, ClientIDFile: o.githubExchangeClientFile, ClientSecretFile: o.githubExchangeSecretFile, Audience: o.githubExchangeAudience, CAFile: o.githubExchangeCAFile, APIURL: o.githubAPIURL} } // validateGitHubExchange checks the token exchange options: the exchange's // subject is the caller's IdP token, so it needs Dex and downstream OAuth. -func validateGitHubExchange(o *serveOptions) error { +func validateGitHubExchange(o *serveOptions, dex bool) error { if o.githubExchangeEndpoint == "" { if o.githubExchangeClient != "" || o.githubExchangeClientFile != "" || o.githubExchangeSecretFile != "" || o.githubExchangeAudience != "" || o.githubExchangeCAFile != "" { return errors.New("GitHub token exchange options require --github-token-exchange-endpoint") } return nil } - if !o.oauthEnabled || !o.downstreamOAuth || o.oauthProvider != server.ProviderDex { + if !o.oauthEnabled || !o.downstreamOAuth || !dex { return errors.New("GitHub token exchange requires Dex OAuth and downstream OAuth") } return o.gitHubExchangeConfig().Validate() diff --git a/cmd/serve_test.go b/cmd/serve_test.go index 263d4e5..f635503 100644 --- a/cmd/serve_test.go +++ b/cmd/serve_test.go @@ -3,25 +3,33 @@ package cmd import ( "bytes" "log/slog" + "os" + "path/filepath" "testing" + "github.com/giantswarm/mcp-oauth/oauthconfig" + "github.com/giantswarm/mcp-oauth/providers/dex" + "github.com/giantswarm/mcp-oauth/providers/google" + oauthserver "github.com/giantswarm/mcp-oauth/server" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/giantswarm/cluster-manager/internal/compose" "github.com/giantswarm/cluster-manager/internal/server" ) func TestValidateGitHubExchange(t *testing.T) { exchange := func() *serveOptions { return &serveOptions{ // #nosec G101 -- configuration fixture with a path, no secret value - oauthEnabled: true, downstreamOAuth: true, oauthProvider: server.ProviderDex, + oauthEnabled: true, downstreamOAuth: true, githubExchangeEndpoint: "https://muster.example/oauth/token", githubExchangeClient: "cluster-manager", githubExchangeSecretFile: "/etc/cluster-manager/github-token-exchange/client-secret", githubExchangeAudience: "github-cluster-manager", githubAPIURL: server.DefaultGitHubAPIURL, } } - require.NoError(t, validateGitHubExchange(&serveOptions{}), "no exchange configured") - require.NoError(t, validateGitHubExchange(exchange())) + require.NoError(t, validateGitHubExchange(&serveOptions{}, true), "no exchange configured") + require.NoError(t, validateGitHubExchange(exchange(), true)) + require.ErrorContains(t, validateGitHubExchange(exchange(), false), "requires Dex OAuth and downstream OAuth", "the subject token must be a Dex token") for name, scenario := range map[string]struct { change func(*serveOptions) @@ -30,14 +38,13 @@ func TestValidateGitHubExchange(t *testing.T) { "option without endpoint": {func(o *serveOptions) { o.githubExchangeEndpoint = "" }, "require --github-token-exchange-endpoint"}, "without OAuth": {func(o *serveOptions) { o.oauthEnabled = false }, "requires Dex OAuth and downstream OAuth"}, "without downstream OAuth": {func(o *serveOptions) { o.downstreamOAuth = false }, "requires Dex OAuth and downstream OAuth"}, - "with Google": {func(o *serveOptions) { o.oauthProvider = server.ProviderGoogle }, "requires Dex OAuth and downstream OAuth"}, "plain HTTP endpoint": {func(o *serveOptions) { o.githubExchangeEndpoint = "http://muster.example/oauth/token" }, "HTTPS token endpoint"}, "without audience": {func(o *serveOptions) { o.githubExchangeAudience = "" }, "an audience"}, } { t.Run(name, func(t *testing.T) { options := exchange() scenario.change(options) - require.ErrorContains(t, validateGitHubExchange(options), scenario.want) + require.ErrorContains(t, validateGitHubExchange(options, true), scenario.want) }) } } @@ -64,3 +71,45 @@ func TestWarnDeprecatedOAuthOptions(t *testing.T) { }) } } + +func TestClusterOIDC(t *testing.T) { + caFile := filepath.Join(t.TempDir(), "ca.crt") + require.NoError(t, os.WriteFile(caFile, []byte("dex-ca-pem"), 0o600)) + t.Setenv("OAUTH_DEX_CA_FILE", caFile) + t.Setenv("OAUTH_TRUSTED_ISSUERS", `[{"issuer":"https://other.example.com","caFile":"/nowhere"},{"issuer":"https://idp.example.com","caFile":"`+caFile+`","openIDProvider":true}]`) + options := &serveOptions{oauthEnabled: true, clusterOIDCClientID: "dex-k8s-authenticator", clusterOIDCUsernameClaim: "email", clusterOIDCGroupsClaim: "groups"} + want := func(issuer string) *compose.ClusterOIDC { + return &compose.ClusterOIDC{IssuerURL: issuer, ClientID: "dex-k8s-authenticator", UsernameClaim: "email", GroupsClaim: "groups", CAPem: "dex-ca-pem"} + } + var output bytes.Buffer + log := slog.New(slog.NewTextHandler(&output, nil)) + + got, err := options.clusterOIDC(oauthconfig.Settings{Dex: &dex.Config{IssuerURL: "https://dex.example.com"}}, log) + require.NoError(t, err) + require.Equal(t, want("https://dex.example.com"), got, "the Dex provider people sign in with") + + openIDProvider := []oauthserver.TrustedIssuer{{Issuer: "https://other.example.com"}, {Issuer: "https://idp.example.com", OpenIDProvider: true}} + got, err = options.clusterOIDC(oauthconfig.Settings{TrustedIssuers: openIDProvider}, log) + require.NoError(t, err) + require.Equal(t, want("https://idp.example.com"), got, "without Dex settings: the trusted issuer marked openIDProvider, with its caFile") + require.Empty(t, output.String()) + + got, err = options.clusterOIDC(oauthconfig.Settings{TrustedIssuers: openIDProvider[:1]}, log) + require.NoError(t, err) + require.Nil(t, got, "no OpenID Provider: created clusters trust none") + require.Contains(t, output.String(), "created clusters trust no identity provider") + + output.Reset() + got, err = options.clusterOIDC(oauthconfig.Settings{Google: &google.Config{}}, log) + require.NoError(t, err) + require.Nil(t, got, "a Google provider is not composed into created clusters") + require.Contains(t, output.String(), "created clusters trust no identity provider") + + output.Reset() + withoutAudience := *options + withoutAudience.clusterOIDCClientID = "" + got, err = withoutAudience.clusterOIDC(oauthconfig.Settings{Dex: &dex.Config{IssuerURL: "https://dex.example.com"}}, log) + require.NoError(t, err) + require.Nil(t, got) + require.Empty(t, output.String(), "nothing to warn about without the flags") +} diff --git a/go.mod b/go.mod index 4eb4900..44d8c36 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( filippo.io/age v1.3.2 github.com/Masterminds/semver/v3 v3.5.0 github.com/giantswarm/gitops-commit v0.11.10 - github.com/giantswarm/mcp-oauth v1.17.0 + github.com/giantswarm/mcp-oauth v1.24.0 github.com/giantswarm/mcp-toolkit v0.11.0 github.com/giantswarm/mcp-toolkit/k8s v0.1.1 github.com/go-jose/go-jose/v4 v4.1.9 diff --git a/go.sum b/go.sum index b38aab1..ce9b60c 100644 --- a/go.sum +++ b/go.sum @@ -181,8 +181,8 @@ github.com/getsops/sops/v3 v3.13.3 h1:saYczbT88kD1saNChe1cAbFQe5mrRhTIfEw3TaEcmK github.com/getsops/sops/v3 v3.13.3/go.mod h1:3mUuUtKnJ63IzIvU4LQoDXdp0ZvorY5s2hEc7UVNfx8= github.com/giantswarm/gitops-commit v0.11.10 h1:RfwCyml97MUrpoVuWtdg/NJl+416ZvR8t8XGHZrUmL4= github.com/giantswarm/gitops-commit v0.11.10/go.mod h1:X9KxzmbALsJVg7664WRTs5DlZCx1Nd7hhtJN1Lw83Ws= -github.com/giantswarm/mcp-oauth v1.17.0 h1:WFc03UhoMWjP9ub5PQaYgBtWJ5mOBhRN5QZk9UZ+3P4= -github.com/giantswarm/mcp-oauth v1.17.0/go.mod h1:7A5o9iQ3j5cTbOqG7PludvCVrgSHNd+gbM5Dk5LYFo8= +github.com/giantswarm/mcp-oauth v1.24.0 h1:xLP86BZkVkmMj4a2wu+HeBCeHMvntOd+fS4tZSXnMrI= +github.com/giantswarm/mcp-oauth v1.24.0/go.mod h1:CejmfrIg1cGdqzTb/F0N0zwpa1fXgpvH3cpDcswf5yY= github.com/giantswarm/mcp-toolkit v0.11.0 h1:0aKacfBYAvxDgMqa3j1dKXikcqJYzA2jcSBx+vluHSo= github.com/giantswarm/mcp-toolkit v0.11.0/go.mod h1:o6nUYtYy4g8MVVuGyUl0sJH/MZQdnDuVyhM7WICdpwc= github.com/giantswarm/mcp-toolkit/k8s v0.1.1 h1:KC381ujW0KnrVGwAiTWVjumTDiKPTzU8KSeHu1LAL24= diff --git a/helm/cluster-manager/README.md b/helm/cluster-manager/README.md index 02ca1aa..fe4af12 100644 --- a/helm/cluster-manager/README.md +++ b/helm/cluster-manager/README.md @@ -56,13 +56,13 @@ from the platform identity contract (`global.identity`, `global.domain`). | oauth.dex.issuerURL | string | `""` | Dex issuer URL. Empty falls back to `global.identity.issuerUrl`. | | oauth.dex.clientID | string | `""` | Dex OAuth client ID. Empty falls back to `global.identity.clientId`. | | oauth.dex.clientSecret | string | `""` | Dex OAuth client secret (prefer `oauth.existingSecret`). | -| oauth.dex.allowPrivateURLs | bool | `false` | Deprecated, no effect: the Dex client reaches private addresses and follows HTTP_PROXY, HTTPS_PROXY and NO_PROXY without it. | -| oauth.dex.caSecret | object | `{"key":"ca.crt","name":""}` | Secret with the CA of a Dex that serves a private certificate; mounted and passed as `--dex-ca-file`. Empty name falls back to `global.identity.ca.secretName` / `global.identity.ca.key`. | +| oauth.dex.allowPrivateURLs | bool | `false` | Deprecated, no effect, not passed to the server: the Dex client reaches private addresses and follows HTTP_PROXY, HTTPS_PROXY and NO_PROXY without it. Remove it from your values; the key goes away in a later release. | +| oauth.dex.caSecret | object | `{"key":"ca.crt","name":""}` | Secret with the CA of a Dex that serves a private certificate; mounted and passed as `OAUTH_DEX_CA_FILE`. Empty name falls back to `global.identity.ca.secretName` / `global.identity.ca.key`. | | oauth.google.clientID | string | `""` | Google OAuth client ID (not secret; may also come from the Secret key `google-client-id` when empty). | | oauth.google.clientSecret | string | `""` | Google OAuth client secret (prefer `oauth.existingSecret`). | | oauth.existingSecret | string | `""` | Existing Secret with the provider credentials: `dex-client-secret` (dex) or `google-client-secret` (+ optional `google-client-id`) (google). Empty falls back to `global.identity.existingSecret`, whose `dex-client-secret` is the platform client's; without that, the chart renders a Secret from the values above. | | oauth.trustedAudiences | list | `[]` | OAuth client IDs whose IdP id_tokens are accepted as bearer tokens (SSO token forwarding). Empty falls back to `[global.identity.clientId]`, the platform client MCP clients and the muster CLI log in with. The server trusts the union of this list and `muster.mcpServer.auth.requiredAudiences` (in that order, without duplicates): every token muster forwards carries the required audiences by construction and they are what the kube-apiserver trusts, so a portal session — whose id_token carries them but not the platform client — is accepted without listing its client here. | -| oauth.sso.allowPrivateIPs | bool | `false` | Deprecated, no effect: the issuer host's JWKS endpoint may resolve to a private address without it; list any other JWKS host in allowPrivateIPJWKSHosts. | +| oauth.sso.allowPrivateIPs | bool | `false` | Deprecated, no effect, not passed to the server: the issuer host's JWKS endpoint may resolve to a private address without it; list any other JWKS host in allowPrivateIPJWKSHosts. Remove it from your values; the key goes away in a later release. | | oauth.sso.allowPrivateIPJWKSHosts | list | `[]` | Hosts, other than the issuer's own, whose JWKS may resolve to an RFC 1918 or RFC 4193 address: a jwks_uri the IdP's discovery document puts on another host. Exact hostnames, no port. Loopback and link-local stay refused. | | oauth.allowPublicClientRegistration | bool | `false` | Accept unauthenticated dynamic client registration (labs only). | | oauth.downstream.enabled | bool | `true` | Call the Kubernetes API as the caller: everything a request does presents the caller's IdP token, so the caller's RBAC governs — the apiserver must trust the IdP and the token's audience (a Dex install lists that audience in `muster.mcpServer.auth.requiredAudiences`; a Google install's client id is the apiserver's `--oidc-client-id`). This is cluster-manager's rule (every write as the person), so it is on by default and takes effect with `oauth.enabled`. The ServiceAccount then holds no permissions: the chart renders no RBAC for it (`rbac.create` is moot). | diff --git a/helm/cluster-manager/templates/deployment.yaml b/helm/cluster-manager/templates/deployment.yaml index 0947e87..ea8e4fd 100644 --- a/helm/cluster-manager/templates/deployment.yaml +++ b/helm/cluster-manager/templates/deployment.yaml @@ -62,20 +62,6 @@ spec: - --mcp-path={{ .Values.mcp.path }} {{- if .Values.oauth.enabled }} - --enable-oauth=true - - --oauth-base-url={{ include "cluster-manager.oauthBaseURL" . }} - - --oauth-provider={{ .Values.oauth.provider }} - {{- with include "cluster-manager.oauthTrustedAudiences" . }} - - --oauth-trusted-audiences={{ . }} - {{- end }} - {{- if .Values.oauth.sso.allowPrivateIPs }} - - --sso-allow-private-ips=true - {{- end }} - {{- with .Values.oauth.sso.allowPrivateIPJWKSHosts }} - - --sso-allow-private-ip-jwks-hosts={{ join "," . }} - {{- end }} - {{- if .Values.oauth.allowPublicClientRegistration }} - - --allow-public-client-registration=true - {{- end }} {{- if .Values.oauth.downstream.enabled }} - --downstream-oauth=true {{- end }} @@ -95,14 +81,6 @@ spec: - --github-api-url={{ .Values.github.apiURL }} {{- end }} {{- if eq .Values.oauth.provider "dex" }} - - --dex-issuer-url={{ include "cluster-manager.oauthDexIssuerURL" . }} - - --dex-client-id={{ include "cluster-manager.oauthDexClientID" . }} - {{- if .Values.oauth.dex.allowPrivateURLs }} - - --allow-private-oauth-urls=true - {{- end }} - {{- if include "cluster-manager.oauthDexCASecretName" . }} - - --dex-ca-file=/etc/cluster-manager/idp-ca/{{ include "cluster-manager.oauthDexCASecretKey" . }} - {{- end }} {{- with .Values.createdClusters.oidc.clientID | default (first (.Values.muster.mcpServer.auth.requiredAudiences | default list)) }} - --cluster-oidc-client-id={{ . }} - --cluster-oidc-username-claim={{ $.Values.createdClusters.oidc.usernameClaim }} @@ -132,28 +110,57 @@ spec: value: none {{- end }} {{- if .Values.oauth.enabled }} + {{- /* mcp-oauth's settings (oauthconfig.SettingsFromEnv). */}} + - name: OAUTH_ISSUER + value: {{ include "cluster-manager.oauthBaseURL" . | quote }} + - name: OAUTH_PROVIDER + value: {{ .Values.oauth.provider | quote }} + - name: OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS + value: "true" + {{- with include "cluster-manager.oauthTrustedAudiences" . }} + - name: OAUTH_TRUSTED_AUDIENCES + value: {{ . | quote }} + {{- end }} + {{- with .Values.oauth.sso.allowPrivateIPJWKSHosts }} + - name: OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS + value: {{ join "," . | quote }} + {{- end }} + {{- if .Values.oauth.allowPublicClientRegistration }} + - name: OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION + value: "true" + {{- end }} {{- if eq .Values.oauth.provider "google" }} {{- if .Values.oauth.google.clientID }} - - name: GOOGLE_CLIENT_ID + - name: OAUTH_GOOGLE_CLIENT_ID value: {{ .Values.oauth.google.clientID | quote }} {{- else }} - - name: GOOGLE_CLIENT_ID + - name: OAUTH_GOOGLE_CLIENT_ID valueFrom: secretKeyRef: name: {{ include "cluster-manager.oauthSecretName" . }} key: google-client-id {{- end }} - - name: GOOGLE_CLIENT_SECRET + - name: OAUTH_GOOGLE_CLIENT_SECRET valueFrom: secretKeyRef: name: {{ include "cluster-manager.oauthSecretName" . }} key: google-client-secret + - name: OAUTH_GOOGLE_REDIRECT_URL + value: {{ printf "%s/oauth/callback" (include "cluster-manager.oauthBaseURL" . | trimSuffix "/") | quote }} {{- else }} - - name: DEX_CLIENT_SECRET + - name: OAUTH_DEX_ISSUER_URL + value: {{ include "cluster-manager.oauthDexIssuerURL" . | quote }} + - name: OAUTH_DEX_CLIENT_ID + value: {{ include "cluster-manager.oauthDexClientID" . | quote }} + - name: OAUTH_DEX_CLIENT_SECRET valueFrom: secretKeyRef: name: {{ include "cluster-manager.oauthSecretName" . }} key: dex-client-secret + {{- if include "cluster-manager.oauthDexCASecretName" . }} + - name: OAUTH_DEX_CA_FILE + value: /etc/cluster-manager/idp-ca/{{ include "cluster-manager.oauthDexCASecretKey" . }} + {{- end }} {{- end }} {{- end }} {{- with .Values.extraEnv }} diff --git a/helm/cluster-manager/tests/oauth_env_test.yaml b/helm/cluster-manager/tests/oauth_env_test.yaml new file mode 100644 index 0000000..9e5d309 --- /dev/null +++ b/helm/cluster-manager/tests/oauth_env_test.yaml @@ -0,0 +1,115 @@ +suite: OAuth settings as mcp-oauth OAUTH_* variables +templates: + - templates/deployment.yaml +set: + oauth.enabled: true + oauth.baseURL: https://manager.example.test + oauth.dex.issuerURL: https://dex.example.test + oauth.dex.clientID: manager + oauth.existingSecret: manager-oauth + oauth.trustedAudiences: + - agent-platform +tests: + - it: renders the Dex settings as OAUTH_* variables and no OAuth arguments besides the switches + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ISSUER, value: https://manager.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_PROVIDER, value: dex} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS, value: "true"} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_ISSUER_URL, value: https://dex.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_ID, value: manager} + - contains: + path: spec.template.spec.containers[0].env + content: + name: OAUTH_DEX_CLIENT_SECRET + valueFrom: + secretKeyRef: {name: manager-oauth, key: dex-client-secret} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_TRUSTED_AUDIENCES, value: agent-platform} + - contains: + path: spec.template.spec.containers[0].args + content: --enable-oauth=true + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: OAUTH_DEX_CA_FILE} + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION} + - notMatchRegex: + path: spec.template.spec.containers[0].args[*] + pattern: ^--(oauth-|dex-|sso-|google-|allow-private-oauth-urls|allow-public-client-registration) + + - it: points OAUTH_DEX_CA_FILE at the mounted CA + set: + oauth.dex.caSecret.name: dex-ca + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CA_FILE, value: /etc/cluster-manager/idp-ca/ca.crt} + + - it: renders the Google settings with the callback as redirect URL + set: + oauth.provider: google + oauth.baseURL: https://manager.example.test/ + oauth.google.clientID: google-client + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_PROVIDER, value: google} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_GOOGLE_CLIENT_ID, value: google-client} + - contains: + path: spec.template.spec.containers[0].env + content: + name: OAUTH_GOOGLE_CLIENT_SECRET + valueFrom: + secretKeyRef: {name: manager-oauth, key: google-client-secret} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_GOOGLE_REDIRECT_URL, value: https://manager.example.test/oauth/callback} + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: OAUTH_DEX_ISSUER_URL} + + - it: passes public client registration when allowed + set: + oauth.allowPublicClientRegistration: true + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION, value: "true"} + + - it: still accepts the deprecated no-op values and passes nothing for them + set: + oauth.dex.allowPrivateURLs: true + oauth.sso.allowPrivateIPs: true + asserts: + - notContains: + path: spec.template.spec.containers[0].args + content: --allow-private-oauth-urls=true + - notContains: + path: spec.template.spec.containers[0].args + content: --sso-allow-private-ips=true + + - it: renders no OAuth settings with OAuth off + set: + oauth.enabled: false + asserts: + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: OAUTH_ISSUER} diff --git a/helm/cluster-manager/tests/oauth_private_ip_jwks_hosts_test.yaml b/helm/cluster-manager/tests/oauth_private_ip_jwks_hosts_test.yaml new file mode 100644 index 0000000..d2537ad --- /dev/null +++ b/helm/cluster-manager/tests/oauth_private_ip_jwks_hosts_test.yaml @@ -0,0 +1,28 @@ +suite: JWKS hosts that may resolve to private addresses +templates: + - templates/deployment.yaml +set: + oauth.enabled: true + oauth.baseURL: https://manager.example.test + oauth.dex.issuerURL: https://dex.example.test + oauth.dex.clientID: manager + oauth.existingSecret: manager-oauth +tests: + - it: lists the JWKS hosts other than the issuer's that may resolve privately + set: + oauth.sso.allowPrivateIPJWKSHosts: + - keys.internal.example + - jwks.internal.example + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS + value: keys.internal.example,jwks.internal.example + - it: renders no JWKS host list by default + asserts: + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: + name: OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS diff --git a/helm/cluster-manager/tests/oauth_private_urls_test.yaml b/helm/cluster-manager/tests/oauth_private_urls_test.yaml deleted file mode 100644 index 13f09f5..0000000 --- a/helm/cluster-manager/tests/oauth_private_urls_test.yaml +++ /dev/null @@ -1,49 +0,0 @@ -suite: deprecated Dex private URL setting -templates: - - templates/deployment.yaml -set: - oauth.enabled: true - oauth.baseURL: https://manager.example.test - oauth.dex.issuerURL: https://dex.example.test - oauth.dex.clientID: manager - oauth.existingSecret: manager-oauth -tests: - - it: still renders and passes the deprecated flag when allowPrivateURLs is true - set: - oauth.dex.allowPrivateURLs: true - asserts: - - contains: - path: spec.template.spec.containers[0].args - content: --allow-private-oauth-urls=true - - it: omits the deprecated flag by default - asserts: - - notContains: - path: spec.template.spec.containers[0].args - content: --allow-private-oauth-urls=true - - it: still renders and passes the deprecated JWKS flag when sso.allowPrivateIPs is true - set: - oauth.sso.allowPrivateIPs: true - asserts: - - contains: - path: spec.template.spec.containers[0].args - content: --sso-allow-private-ips=true - - it: omits the deprecated JWKS flag by default - asserts: - - notContains: - path: spec.template.spec.containers[0].args - content: --sso-allow-private-ips=true - - it: lists the JWKS hosts other than the issuer's that may resolve privately - set: - oauth.sso.allowPrivateIPJWKSHosts: - - keys.internal.example - - jwks.internal.example - asserts: - - contains: - path: spec.template.spec.containers[0].args - content: --sso-allow-private-ip-jwks-hosts=keys.internal.example,jwks.internal.example - - it: renders no JWKS host list by default - asserts: - - notContains: - path: spec.template.spec.containers[0].args - any: true - content: --sso-allow-private-ip-jwks-hosts diff --git a/helm/cluster-manager/values.schema.json b/helm/cluster-manager/values.schema.json index abf3a86..501422a 100644 --- a/helm/cluster-manager/values.schema.json +++ b/helm/cluster-manager/values.schema.json @@ -327,11 +327,11 @@ "properties": { "allowPrivateURLs": { "type": "boolean", - "description": "Deprecated, no effect: the Dex client reaches private addresses and follows HTTP_PROXY, HTTPS_PROXY and NO_PROXY without it." + "description": "Deprecated, no effect, not passed to the server: the Dex client reaches private addresses and follows HTTP_PROXY, HTTPS_PROXY and NO_PROXY without it. Remove it from your values; the key goes away in a later release." }, "caSecret": { "type": "object", - "description": "Secret with the CA of a Dex that serves a private certificate; mounted and passed as `--dex-ca-file`. Empty name falls back to `global.identity.ca.secretName` / `global.identity.ca.key`.", + "description": "Secret with the CA of a Dex that serves a private certificate; mounted and passed as `OAUTH_DEX_CA_FILE`. Empty name falls back to `global.identity.ca.secretName` / `global.identity.ca.key`.", "additionalProperties": false, "properties": { "key": { @@ -405,7 +405,7 @@ }, "allowPrivateIPs": { "type": "boolean", - "description": "Deprecated, no effect: the issuer host's JWKS endpoint may resolve to a private address without it; list any other JWKS host in allowPrivateIPJWKSHosts." + "description": "Deprecated, no effect, not passed to the server: the issuer host's JWKS endpoint may resolve to a private address without it; list any other JWKS host in allowPrivateIPJWKSHosts. Remove it from your values; the key goes away in a later release." } } }, diff --git a/helm/cluster-manager/values.yaml b/helm/cluster-manager/values.yaml index ad2a0f8..09b35b9 100644 --- a/helm/cluster-manager/values.yaml +++ b/helm/cluster-manager/values.yaml @@ -147,11 +147,13 @@ oauth: clientID: "" # -- Dex OAuth client secret (prefer `oauth.existingSecret`). clientSecret: "" - # -- Deprecated, no effect: the Dex client reaches private addresses and - # follows HTTP_PROXY, HTTPS_PROXY and NO_PROXY without it. + # -- Deprecated, no effect, not passed to the server: the Dex client + # reaches private addresses and follows HTTP_PROXY, HTTPS_PROXY and + # NO_PROXY without it. Remove it from your values; the key goes away in a + # later release. allowPrivateURLs: false # -- Secret with the CA of a Dex that serves a private certificate; - # mounted and passed as `--dex-ca-file`. Empty name falls back to + # mounted and passed as `OAUTH_DEX_CA_FILE`. Empty name falls back to # `global.identity.ca.secretName` / `global.identity.ca.key`. caSecret: name: "" @@ -178,9 +180,10 @@ oauth: # but not the platform client — is accepted without listing its client here. trustedAudiences: [] sso: - # -- Deprecated, no effect: the issuer host's JWKS endpoint may resolve to - # a private address without it; list any other JWKS host in - # allowPrivateIPJWKSHosts. + # -- Deprecated, no effect, not passed to the server: the issuer host's + # JWKS endpoint may resolve to a private address without it; list any + # other JWKS host in allowPrivateIPJWKSHosts. Remove it from your values; + # the key goes away in a later release. allowPrivateIPs: false # -- Hosts, other than the issuer's own, whose JWKS may resolve to an # RFC 1918 or RFC 4193 address: a jwks_uri the IdP's discovery document puts diff --git a/internal/server/dexproxy_test.go b/internal/server/dexproxy_test.go index cd46111..4984d94 100644 --- a/internal/server/dexproxy_test.go +++ b/internal/server/dexproxy_test.go @@ -14,6 +14,7 @@ import ( "testing" "time" + "github.com/giantswarm/mcp-oauth/oauthconfig" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -42,6 +43,11 @@ func TestDexProviderFollowsProxyEnvironment(t *testing.T) { "-test.run=^TestDexProviderProxyChild$", "-test.count=1", "-test.v") command.Env = append(environmentWithoutProxy(), dexProxyChildEnv+"=1", + "OAUTH_ISSUER=https://cluster-manager.example.com", + "OAUTH_PROVIDER=dex", + "OAUTH_DEX_ISSUER_URL=https://example.com", + "OAUTH_DEX_CLIENT_ID=cluster-manager", + "OAUTH_DEX_CLIENT_SECRET=secret", "HTTPS_PROXY="+proxy.server.URL, "NO_PROXY="+tc.noProxy, ) @@ -65,13 +71,11 @@ func TestDexProviderProxyChild(t *testing.T) { if os.Getenv(dexProxyChildEnv) != "1" { t.Skip("child process of TestDexProviderFollowsProxyEnvironment") } - runtime, err := newOAuth(OAuthConfig{ - BaseURL: "https://cluster-manager.example.com", - Provider: ProviderDex, - DexIssuerURL: "https://example.com", - DexClientID: "cluster-manager", - DexClientSecret: "secret", - }, "/mcp", slog.New(slog.DiscardHandler)) + settings, err := oauthconfig.SettingsFromEnv() + if err != nil { + t.Fatalf("OAuth settings: %v", err) + } + runtime, err := newOAuth(OAuthConfig{Settings: settings}, "/mcp", slog.New(slog.DiscardHandler)) if runtime != nil { t.Cleanup(func() { runtime.shutdown(context.WithoutCancel(t.Context())) }) } diff --git a/internal/server/oauth.go b/internal/server/oauth.go index a120bd8..011560b 100644 --- a/internal/server/oauth.go +++ b/internal/server/oauth.go @@ -2,73 +2,36 @@ package server import ( "context" - "crypto/x509" + "errors" "fmt" "log/slog" + "maps" "net/http" "net/url" "strings" - oauth "github.com/giantswarm/mcp-oauth" "github.com/giantswarm/mcp-oauth/handler" "github.com/giantswarm/mcp-oauth/oauthconfig" - "github.com/giantswarm/mcp-oauth/providers/dex" - "github.com/giantswarm/mcp-oauth/providers/google" "github.com/giantswarm/mcp-oauth/security" oauthserver "github.com/giantswarm/mcp-oauth/server" "github.com/giantswarm/cluster-manager/internal/identity" ) -// OAuth providers. -const ( - ProviderDex = "dex" - ProviderGoogle = "google" -) - -// OAuthConfig makes cluster-manager an OAuth 2.1 resource server (mcp-oauth) in -// front of the MCP endpoint and the REST API. The platform's identity -// provider is the authority: on the Agent Platform, muster forwards the -// session's IdP id_token byte-identical (MCPServer auth.forwardToken) and the -// portal sends the signed-in user's id_token through the gateway; both are -// validated here against the IdP's JWKS when their audience is one of -// TrustedAudiences (the platform's OAuth client). The caller's identity then -// travels with the request (identity package) and, with DownstreamOAuth, so -// does the token — the Kubernetes API is called as the caller. +// OAuthConfig makes cluster-manager an OAuth 2.1 resource server (mcp-oauth) +// in front of the MCP endpoint. The platform's identity provider is the +// authority: on the Agent Platform, muster forwards the session's IdP +// id_token byte-identical (MCPServer auth.forwardToken) and the portal sends +// the signed-in user's id_token through the gateway; both are validated +// against the IdP's JWKS when their audience is one of the trusted audiences +// (OAUTH_TRUSTED_AUDIENCES, the platform's OAuth client). The caller's +// identity then travels with the request (identity package) and, with +// DownstreamOAuth, so does the token: the Kubernetes API is called as the +// caller. type OAuthConfig struct { - // BaseURL is the public URL of this server: the OAuth issuer identifier - // of its own authorization-server metadata (https, or http on loopback). - BaseURL string - // Provider is the IdP: dex (default) or google. - Provider string - - // Dex provider (Provider == dex). - DexIssuerURL string - DexClientID string - DexClientSecret string - // DexCAFile is a PEM CA bundle for an IdP with a private certificate; - // verifies discovery, token and JWKS calls. Empty: system trust. - DexCAFile string - - // Google provider (Provider == google). - GoogleClientID string - GoogleClientSecret string - - // TrustedAudiences are the OAuth client ids whose IdP id_tokens are - // accepted as bearer tokens (SSO token forwarding): the platform client - // MCP clients and the muster CLI log in with, plus the audiences the - // MCPServer requires — every forwarded token carries those and the - // kube-apiserver trusts them (the chart passes both). Empty: only tokens - // this server issued itself. - TrustedAudiences []string - // AllowPrivateIPJWKSHosts lists the hosts, other than the issuer's own, - // whose JWKS may resolve to RFC 1918 and RFC 4193 addresses: a jwks_uri - // the IdP's discovery document puts on another host. The issuer host needs - // no entry. Loopback, link-local and metadata addresses stay refused. - AllowPrivateIPJWKSHosts []string - // AllowPublicClientRegistration lets MCP clients register over DCR - // without a token (labs only). - AllowPublicClientRegistration bool + // Settings is mcp-oauth's configuration, read from the OAUTH_* variables + // by oauthconfig.SettingsFromEnv. + Settings oauthconfig.Settings // DownstreamOAuth puts the caller's IdP token on the request so // Kubernetes API calls are made as the caller instead of the // ServiceAccount (the apiserver must trust the IdP and the token's @@ -77,84 +40,79 @@ type OAuthConfig struct { DownstreamOAuth bool } -// Validate checks required fields. -func (c OAuthConfig) Validate() error { - if c.BaseURL == "" { - return fmt.Errorf("oauth: base URL is required") - } - if err := validateHTTPS(c.BaseURL); err != nil { - return err - } - switch c.provider() { - case ProviderDex: - if c.DexIssuerURL == "" || c.DexClientID == "" || c.DexClientSecret == "" { - return fmt.Errorf("oauth: dex issuer URL, client ID and client secret are required") - } - case ProviderGoogle: - if c.GoogleClientID == "" || c.GoogleClientSecret == "" { - return fmt.Errorf("oauth: google client ID and client secret are required") - } - default: - return fmt.Errorf("oauth: provider %q: want %s or %s", c.Provider, ProviderDex, ProviderGoogle) - } - for _, a := range c.TrustedAudiences { - if strings.TrimSpace(a) == "" { - return fmt.Errorf("oauth: trusted audiences must not be empty strings") - } - } - return nil +type oauthRuntime struct { + server *oauthserver.Server + handler *handler.Handler + cleanup func(context.Context) error + downstreamOAuth bool + mcpPath string + log *slog.Logger } -func (c OAuthConfig) provider() string { - if c.Provider == "" { - return ProviderDex +func newOAuth(cfg OAuthConfig, mcpPath string, log *slog.Logger) (*oauthRuntime, error) { + settings := cfg.Settings + if settings.Server == nil { + return nil, errors.New("oauth: no server settings") } - return c.Provider -} - -type oauthRuntime struct { - server *oauth.Server - handler *handler.Handler - cleanup func(context.Context) error - cfg OAuthConfig - mcpPath string - log *slog.Logger + serverConfig := *settings.Server + serverConfig.ResourceMetadataByPath = protectedResources(&serverConfig, mcpPath) + settings.Server = &serverConfig + settings.Logger = log + if settings.Dex != nil { + dexConfig := *settings.Dex + dexConfig.Logger = log + settings.Dex = &dexConfig + } + runtime, cleanup, err := oauthconfig.Setup(settings, oauthserver.WithAuditor(security.NewAuditor(log, true))) + if err != nil { + return nil, fmt.Errorf("oauth: %w", err) + } + log.Info("OAuth resource server enabled", "provider", providerName(settings), "issuer", serverConfig.Issuer, + "trustedAudiences", serverConfig.TrustedAudiences, "trustedIssuers", len(settings.TrustedIssuers), + "downstreamOAuth", cfg.DownstreamOAuth) + return &oauthRuntime{server: runtime.Server, handler: runtime.Handler, cleanup: cleanup, + downstreamOAuth: cfg.DownstreamOAuth, mcpPath: mcpPath, log: log}, nil } -func newOAuth(cfg OAuthConfig, mcpPath string, log *slog.Logger) (*oauthRuntime, error) { - if err := cfg.Validate(); err != nil { - return nil, err +// protectedResources adds the MCP endpoint to the protected resources the +// configuration names. A path the configuration already describes keeps its +// entry; an added one advertises the main resource's authorization servers, +// as OAUTH_ADDITIONAL_RESOURCES entries do. +func protectedResources(configuration *oauthserver.Config, mcpPath string) map[string]oauthserver.ProtectedResourceConfig { + resources := maps.Clone(configuration.ResourceMetadataByPath) + if resources == nil { + resources = map[string]oauthserver.ProtectedResourceConfig{} } - redirect := strings.TrimSuffix(cfg.BaseURL, "/") + "/oauth/callback" - settings := oauthconfig.Settings{Server: oauthServerConfig(cfg, nil), RootCAFile: cfg.DexCAFile, Logger: log} - if mcpPath != "" && mcpPath != "/" { - settings.Server.ResourceMetadataByPath = map[string]oauthserver.ProtectedResourceConfig{mcpPath: {}} + // Metadata lookup ignores a trailing slash, so "/mcp/" describes "/mcp". + described := func(path string) (oauthserver.ProtectedResourceConfig, bool) { + for key, resource := range resources { + if strings.TrimRight(key, "/") == strings.TrimRight(path, "/") { + return resource, true + } + } + return oauthserver.ProtectedResourceConfig{}, false } - if cfg.provider() == ProviderGoogle { - settings.Google = &google.Config{ClientID: cfg.GoogleClientID, ClientSecret: cfg.GoogleClientSecret, RedirectURL: redirect} - } else { - settings.Dex = &dex.Config{IssuerURL: cfg.DexIssuerURL, ClientID: cfg.DexClientID, ClientSecret: cfg.DexClientSecret, RedirectURL: redirect, Logger: log} + var advertised []string + if main, err := url.Parse(configuration.GetResourceIdentifier()); err == nil { + resource, _ := described(main.EscapedPath()) + advertised = resource.AuthorizationServers } - runtime, cleanup, err := oauthconfig.Setup(settings, - oauth.WithAuditor(security.NewAuditor(log, true))) - if err != nil { - return nil, fmt.Errorf("oauth: server: %w", err) + if mcpPath != "" && mcpPath != "/" { + if _, ok := described(mcpPath); !ok { + resources[mcpPath] = oauthserver.ProtectedResourceConfig{AuthorizationServers: advertised} + } } - log.Info("OAuth resource server enabled", "provider", cfg.provider(), "issuer", cfg.BaseURL, - "trustedAudiences", cfg.TrustedAudiences, "downstreamOAuth", cfg.DownstreamOAuth) - return &oauthRuntime{server: runtime.Server, handler: runtime.Handler, cleanup: cleanup, cfg: cfg, mcpPath: mcpPath, log: log}, nil + return resources } -func oauthServerConfig(cfg OAuthConfig, rootCAs *x509.CertPool) *oauth.ServerConfig { - return &oauth.ServerConfig{ - EnableClientIDMetadataDocuments: true, - Issuer: cfg.BaseURL, - AllowRefreshTokenRotation: true, - AllowPublicClientRegistration: cfg.AllowPublicClientRegistration, - MaxClientsPerIP: 10, - TrustedAudiences: cfg.TrustedAudiences, - AllowPrivateIPJWKSHosts: cfg.AllowPrivateIPJWKSHosts, - JWKSRootCAs: rootCAs, +func providerName(settings oauthconfig.Settings) string { + switch { + case settings.Dex != nil: + return "dex" + case settings.Google != nil: + return "google" + default: + return "none" } } @@ -167,7 +125,7 @@ func (o *oauthRuntime) register(mux *http.ServeMux) { // trusted) and then attaches the caller to the request. func (o *oauthRuntime) protect(next http.Handler) http.Handler { protected := o.attachIdentity(next) - if o.cfg.DownstreamOAuth { + if o.downstreamOAuth { protected = o.handler.RequireProviderIDToken(protected) } return o.handler.ValidateToken(protected) @@ -193,7 +151,7 @@ func (o *oauthRuntime) attachIdentity(next http.Handler) http.Handler { id.Source = identity.SourceSSO } ctx = identity.ContextWith(ctx, id) - if o.cfg.DownstreamOAuth { + if o.downstreamOAuth { token, err := handler.ProviderIDTokenFromContext(ctx) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) @@ -211,24 +169,3 @@ func (o *oauthRuntime) shutdown(ctx context.Context) { o.log.Warn("oauth server shutdown", "error", err) } } - -// validateHTTPS enforces OAuth 2.1's HTTPS requirement, allowing plain HTTP -// only for loopback development. -func validateHTTPS(baseURL string) error { - u, err := url.Parse(baseURL) - if err != nil { - return fmt.Errorf("oauth: invalid base URL: %w", err) - } - switch u.Scheme { - case "https": - return nil - case "http": - host := u.Hostname() - if host == "localhost" || host == "127.0.0.1" || host == "::1" { - return nil - } - return fmt.Errorf("oauth: base URL must use https (http is allowed for loopback only): %s", baseURL) - default: - return fmt.Errorf("oauth: base URL scheme must be http or https: %s", baseURL) - } -} diff --git a/internal/server/oauth_metadata_test.go b/internal/server/oauth_metadata_test.go index f00d7af..1341c8f 100644 --- a/internal/server/oauth_metadata_test.go +++ b/internal/server/oauth_metadata_test.go @@ -12,7 +12,7 @@ import ( ) func TestResourceSpecificOAuthChallenge(t *testing.T) { - runtime, err := newOAuth(OAuthConfig{BaseURL: "https://manager.example.test", Provider: ProviderGoogle, GoogleClientID: "client", GoogleClientSecret: "test-secret"}, "/mcp", slog.New(slog.DiscardHandler)) + runtime, err := newOAuth(OAuthConfig{Settings: googleSettings(t)}, "/mcp", slog.New(slog.DiscardHandler)) require.NoError(t, err) t.Cleanup(func() { runtime.shutdown(context.WithoutCancel(t.Context())) }) mux := http.NewServeMux() diff --git a/internal/server/oauth_realchain_test.go b/internal/server/oauth_realchain_test.go index 384336f..7321a6b 100644 --- a/internal/server/oauth_realchain_test.go +++ b/internal/server/oauth_realchain_test.go @@ -226,17 +226,11 @@ func (p *privateIdP) idToken(t *testing.T, aud []string) string { return tok } -func (p *privateIdP) config(jwksHosts ...string) OAuthConfig { - return OAuthConfig{ - BaseURL: "http://localhost:8080", - Provider: ProviderDex, - DexIssuerURL: p.issuer, - DexClientID: "agent-platform", - DexClientSecret: "lab-only", - DexCAFile: p.caFile, - TrustedAudiences: []string{"agent-platform"}, - AllowPrivateIPJWKSHosts: jwksHosts, - } +func (p *privateIdP) config(t *testing.T, jwksHosts ...string) OAuthConfig { + t.Helper() + environment := dexEnvironment(p.issuer, p.caFile) + environment["OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS"] = strings.Join(jwksHosts, ",") + return OAuthConfig{Settings: oauthSettings(t, environment)} } // callThroughChain sends one request with bearer through the production @@ -270,14 +264,14 @@ func callThroughChain(t *testing.T, cfg OAuthConfig, bearer string) (int, string func TestForwardedTokenThroughTheProductionChain(t *testing.T) { idp := newPrivateIdP(t, "") - code, caller := callThroughChain(t, idp.config(), idp.idToken(t, []string{"agent-platform"})) + code, caller := callThroughChain(t, idp.config(t), idp.idToken(t, []string{"agent-platform"})) require.Equal(t, http.StatusNoContent, code) require.Equal(t, "admin@lab.local", caller) - code, _ = callThroughChain(t, idp.config(), idp.idToken(t, []string{"someone-else"})) + code, _ = callThroughChain(t, idp.config(t), idp.idToken(t, []string{"someone-else"})) require.Equal(t, http.StatusUnauthorized, code, "an untrusted audience is refused") - code, _ = callThroughChain(t, idp.config(), "") + code, _ = callThroughChain(t, idp.config(t), "") require.Equal(t, http.StatusUnauthorized, code, "no token, no MCP") } @@ -288,10 +282,10 @@ func TestJWKSOnAnotherPrivateHost(t *testing.T) { idp := newPrivateIdP(t, privateKeysHost) token := idp.idToken(t, []string{"agent-platform"}) - code, _ := callThroughChain(t, idp.config(), token) + code, _ := callThroughChain(t, idp.config(t), token) require.Equal(t, http.StatusUnauthorized, code, "an unlisted private JWKS host is refused") - code, caller := callThroughChain(t, idp.config(privateKeysHost), token) + code, caller := callThroughChain(t, idp.config(t, privateKeysHost), token) require.Equal(t, http.StatusNoContent, code) require.Equal(t, "admin@lab.local", caller) } diff --git a/internal/server/oauth_test.go b/internal/server/oauth_test.go index 7dd9c84..e53562a 100644 --- a/internal/server/oauth_test.go +++ b/internal/server/oauth_test.go @@ -21,9 +21,10 @@ import ( "testing" "time" - oauth "github.com/giantswarm/mcp-oauth" "github.com/giantswarm/mcp-oauth/handler" + "github.com/giantswarm/mcp-oauth/oauthconfig" "github.com/giantswarm/mcp-oauth/providers" + oauthserver "github.com/giantswarm/mcp-oauth/server" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -98,36 +99,50 @@ func selfSignedLocalhost(t *testing.T) tls.Certificate { return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} } -func (f *fakeIdP) config(downstream bool) OAuthConfig { - return OAuthConfig{ - BaseURL: "http://localhost:8080", - Provider: ProviderDex, - DexIssuerURL: f.issuer, - DexClientID: "agent-platform", - DexClientSecret: "lab-only", - DexCAFile: f.caFile, - TrustedAudiences: []string{"agent-platform"}, - DownstreamOAuth: downstream, +func (f *fakeIdP) config(t *testing.T, downstream bool) OAuthConfig { + t.Helper() + return OAuthConfig{Settings: oauthSettings(t, dexEnvironment(f.issuer, f.caFile)), DownstreamOAuth: downstream} +} + +// dexEnvironment is the OAUTH_* configuration of a Dex at issuer whose +// forwarded id_tokens for the platform client are accepted. +func dexEnvironment(issuer, caFile string) map[string]string { + return map[string]string{ + "OAUTH_ISSUER": "http://localhost:8080", + "OAUTH_PROVIDER": "dex", + "OAUTH_DEX_ISSUER_URL": issuer, + "OAUTH_DEX_CLIENT_ID": "agent-platform", + "OAUTH_DEX_CLIENT_SECRET": "lab-only", + "OAUTH_DEX_CA_FILE": caFile, + "OAUTH_TRUSTED_AUDIENCES": "agent-platform", + "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "true", + } +} + +// oauthSettings reads mcp-oauth's settings from environment the way the +// serve command does. +func oauthSettings(t *testing.T, environment map[string]string) oauthconfig.Settings { + t.Helper() + for name, value := range environment { + t.Setenv(name, value) } + settings, err := oauthconfig.SettingsFromEnv() + require.NoError(t, err) + return settings } -func TestOAuthConfigValidation(t *testing.T) { - dexOK := OAuthConfig{BaseURL: "https://mm.example.com", DexIssuerURL: "x", DexClientID: "y", DexClientSecret: "z"} - require.Error(t, OAuthConfig{}.Validate()) - require.Error(t, OAuthConfig{BaseURL: "http://mm.example.com", DexIssuerURL: "x", DexClientID: "y", DexClientSecret: "z"}.Validate(), "plain http only on loopback") - require.NoError(t, OAuthConfig{BaseURL: "http://localhost:8080", DexIssuerURL: "x", DexClientID: "y", DexClientSecret: "z"}.Validate()) - require.NoError(t, dexOK.Validate()) - require.Error(t, OAuthConfig{BaseURL: "https://mm.example.com", Provider: ProviderDex}.Validate(), "dex needs issuer + client") - require.Error(t, OAuthConfig{BaseURL: "https://mm.example.com", Provider: ProviderGoogle, GoogleClientID: "id"}.Validate(), "google needs the secret") - require.NoError(t, OAuthConfig{BaseURL: "https://mm.example.com", Provider: ProviderGoogle, GoogleClientID: "id", GoogleClientSecret: "s", TrustedAudiences: []string{"id"}}.Validate()) - require.Error(t, OAuthConfig{BaseURL: "https://mm.example.com", Provider: "okta"}.Validate(), "unknown provider") - bad := dexOK - bad.TrustedAudiences = []string{"agent-platform", " "} - require.Error(t, bad.Validate(), "empty audience") +// googleSettings is a Google provider configuration for a server at +// https://manager.example.test. +func googleSettings(t *testing.T) oauthconfig.Settings { + t.Helper() + return oauthSettings(t, map[string]string{ + "OAUTH_ISSUER": "https://manager.example.test", "OAUTH_PROVIDER": "google", "OAUTH_GOOGLE_CLIENT_ID": "client", + "OAUTH_GOOGLE_CLIENT_SECRET": "test-secret", "OAUTH_GOOGLE_REDIRECT_URL": "https://manager.example.test/oauth/callback", + }) } func newTestOAuthRuntime(cfg OAuthConfig) *oauthRuntime { - return &oauthRuntime{cfg: cfg, log: slog.New(slog.NewTextHandler(io.Discard, nil))} + return &oauthRuntime{downstreamOAuth: cfg.DownstreamOAuth, log: slog.New(slog.NewTextHandler(io.Discard, nil))} } // authenticated is a request mcp-oauth has validated: its user info is on the @@ -154,7 +169,7 @@ var forwardedUser = &providers.UserInfo{ // OAuth, the caller's token. func TestAttachIdentityForwardedIDToken(t *testing.T) { identityProvider := newPrivateIdP(t, "") - configuration := identityProvider.config() + configuration := identityProvider.config(t) configuration.DownstreamOAuth = true o, err := newOAuth(configuration, "/mcp", slog.New(slog.DiscardHandler)) require.NoError(t, err) @@ -209,7 +224,7 @@ func TestAttachIdentityDownstreamOffKeepsTheServiceAccount(t *testing.T) { // issued, the provider's id_token stored next to it is what the Kubernetes API // sees; without one the request is refused. func TestAttachIdentityIssuedTokenNeedsStoredIDToken(t *testing.T) { - configuration := OAuthConfig{BaseURL: "https://manager.example.test", Provider: ProviderGoogle, GoogleClientID: "client", GoogleClientSecret: "test-secret", DownstreamOAuth: true} + configuration := OAuthConfig{Settings: googleSettings(t), DownstreamOAuth: true} o, err := newOAuth(configuration, "/mcp", slog.New(slog.DiscardHandler)) require.NoError(t, err) t.Cleanup(func() { o.shutdown(context.WithoutCancel(t.Context())) }) @@ -229,7 +244,7 @@ func TestAttachIdentityIssuedTokenNeedsStoredIDToken(t *testing.T) { // probes and the OAuth metadata stay open, the MCP endpoint demands a token. func TestServerGuardsMCPButNotProbes(t *testing.T) { idp := newFakeIdP(t) - cfg := idp.config(false) + cfg := idp.config(t, false) srv, err := New(Config{Addr: "127.0.0.1:0", MCPEnabled: true, OAuth: &cfg}, api.NewMCPServer(nil, "test"), slog.New(slog.NewTextHandler(io.Discard, nil))) require.NoError(t, err) t.Cleanup(func() { srv.oauth.shutdown(context.Background()) }) @@ -258,17 +273,23 @@ func TestServerGuardsMCPButNotProbes(t *testing.T) { assert.Equal(t, http.StatusOK, status(http.MethodGet, "/.well-known/oauth-authorization-server", ""), "metadata stays public") } -func TestOAuthServerConfig(t *testing.T) { - rootCAs := x509.NewCertPool() - cfg := OAuthConfig{BaseURL: "https://mm.example.com", TrustedAudiences: []string{"agent-platform", "kubernetes"}, AllowPrivateIPJWKSHosts: []string{"keys.example.com"}, AllowPublicClientRegistration: true} - assert.Equal(t, &oauth.ServerConfig{ - EnableClientIDMetadataDocuments: true, - Issuer: "https://mm.example.com", - AllowRefreshTokenRotation: true, - AllowPublicClientRegistration: true, - MaxClientsPerIP: 10, - TrustedAudiences: []string{"agent-platform", "kubernetes"}, - AllowPrivateIPJWKSHosts: []string{"keys.example.com"}, - JWKSRootCAs: rootCAs, - }, oauthServerConfig(cfg, rootCAs)) +func TestProtectedResources(t *testing.T) { + advertised := []string{"https://dex.example.com"} + configuration := &oauthserver.Config{Issuer: "https://cm.example.com", ResourceMetadataByPath: map[string]oauthserver.ProtectedResourceConfig{ + "/": {ResourceIdentifier: "https://cm.example.com", AuthorizationServers: advertised}, + }} + assert.Equal(t, map[string]oauthserver.ProtectedResourceConfig{ + "/": {ResourceIdentifier: "https://cm.example.com", AuthorizationServers: advertised}, + "/mcp": {AuthorizationServers: advertised}, + }, protectedResources(configuration, "/mcp"), "an added path advertises the main resource's servers") + assert.Len(t, configuration.ResourceMetadataByPath, 1, "the configuration is not changed") + + assert.Equal(t, map[string]oauthserver.ProtectedResourceConfig{"/mcp": {}}, + protectedResources(&oauthserver.Config{Issuer: "https://cm.example.com"}, "/mcp"), "nothing advertised: the server's own issuer") + + trailing := &oauthserver.Config{Issuer: "https://cm.example.com", ResourceMetadataByPath: map[string]oauthserver.ProtectedResourceConfig{ + "/mcp/": {ResourceIdentifier: "https://cm.example.com/mcp/", ScopesSupported: []string{"clusters"}}, + }} + assert.Equal(t, map[string]oauthserver.ProtectedResourceConfig{"/mcp/": {ResourceIdentifier: "https://cm.example.com/mcp/", ScopesSupported: []string{"clusters"}}}, + protectedResources(trailing, "/mcp"), "a configured path with a trailing slash describes the MCP endpoint") } From 4558d42b9f5638be1b0f552bf5ca6060d1c3dc79 Mon Sep 17 00:00:00 2001 From: QuentinBisson Date: Fri, 27 Nov 2026 09:32:20 +0100 Subject: [PATCH 2/5] feat(chart): adopt mcp-oauth's values layout and trust Dex as the OpenID Provider The chart reads oauth.resourceServer (resource, additionalResources, authorizationServers, trustedIssuers, requireResourceAccessTokens) and oauth.authorizationServer (enabled, issuer, upstream type/issuer/client/certificateAuthority, dynamicClientRegistration, clientIDMetadataDocuments, storage), and renders them as OAUTH_* variables with client secrets mounted as files. Without trustedIssuers it lists the provider people sign in with in OAUTH_TRUSTED_ISSUERS as the openIDProvider, accepting its ID tokens for the platform client and the MCPServer's requiredAudiences, in place of OAUTH_TRUSTED_AUDIENCES. The earlier oauth.* keys still work for one more release; NOTES names each one that is set. --- README.md | 15 +- cmd/oauth_env_test.go | 79 +++++ hack/verify-chart.sh | 2 +- helm/cluster-manager/README.md | 44 ++- helm/cluster-manager/templates/NOTES.txt | 25 ++ helm/cluster-manager/templates/_helpers.tpl | 185 +++++++---- .../cluster-manager/templates/deployment.yaml | 145 ++++++--- helm/cluster-manager/templates/mcpserver.yaml | 6 +- .../templates/oauth-secret.yaml | 7 +- .../cluster-manager/tests/oauth_env_test.yaml | 72 ++++- .../oauth_private_ip_jwks_hosts_test.yaml | 28 -- .../tests/oauth_values_layout_test.yaml | 255 ++++++++++++++++ helm/cluster-manager/values.schema.json | 286 +++++++++++++++++- helm/cluster-manager/values.yaml | 173 ++++++++--- internal/server/oauth_realchain_test.go | 59 ++++ 15 files changed, 1165 insertions(+), 216 deletions(-) delete mode 100644 helm/cluster-manager/tests/oauth_private_ip_jwks_hosts_test.yaml create mode 100644 helm/cluster-manager/tests/oauth_values_layout_test.yaml diff --git a/README.md b/README.md index 1d502dc..dfa7a8b 100644 --- a/README.md +++ b/README.md @@ -117,10 +117,19 @@ HelmRelease. cluster-manager serve --kubeconfig ~/.kube/config ``` -Every flag has an environment variable named next to it in `--help`; flags win. The chart in +Every flag has an environment variable named next to it in `--help`; flags win. OAuth is +configured by mcp-oauth's `OAUTH_*` variables (`OAUTH_ISSUER`, `OAUTH_PROVIDER`, +`OAUTH_DEX_ISSUER_URL`, `OAUTH_DEX_CLIENT_ID`, `OAUTH_DEX_CLIENT_SECRET_FILE`, `OAUTH_DEX_CA_FILE`, +`OAUTH_TRUSTED_ISSUERS`, …); the `--oauth-*`, `--dex-*`, `--google-*` flags and their variables +still map onto them for one more release and log a deprecation warning. The chart in `helm/cluster-manager` renders the Deployment, the Service, the `MCPServer` CR for muster and, -with `oauth.enabled`, the mcp-oauth resource-server flags from the platform identity contract -(`global.identity`). +with `oauth.enabled`, those variables from the platform identity contract (`global.identity`). +It lists the IdP in `OAUTH_TRUSTED_ISSUERS` as the OpenID Provider people sign in with +(`openIDProvider`), accepting its ID tokens for the platform's OAuth client plus the +MCPServer's `requiredAudiences`; any other audience is refused with 401. The chart's values +follow mcp-oauth's layout for MCP servers (`oauth.resourceServer`, `oauth.authorizationServer`); +the earlier `oauth.*` keys still work for one more release and the release notes name each one +that is set. Traces go out over OTLP when `OTEL_EXPORTER_OTLP_ENDPOINT` is set (the chart's `observability.otel.endpoint`); the standard `OTEL_*` variables configure the exporter and the diff --git a/cmd/oauth_env_test.go b/cmd/oauth_env_test.go index 9f009d3..42c348f 100644 --- a/cmd/oauth_env_test.go +++ b/cmd/oauth_env_test.go @@ -2,9 +2,16 @@ package cmd import ( "bytes" + "context" "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" "testing" + "github.com/giantswarm/mcp-oauth/oauthconfig" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -119,3 +126,75 @@ func TestLoadOAuthSettingsRefusesGitHub(t *testing.T) { _, err := loadOAuthSettings(&serveOptions{}, slog.New(slog.DiscardHandler)) require.ErrorContains(t, err, "OAUTH_PROVIDER=github is not supported") } + +func TestLoadOAuthInitialAccessToken(t *testing.T) { + for _, test := range []struct { + name string + current string + legacy string + file bool + want string + }{ + {name: "initial access token", current: "current-secret", want: "current-secret"}, + {name: "deprecated token", legacy: "legacy-secret", want: "legacy-secret"}, + {name: "new name wins", current: "current-secret", legacy: "legacy-secret", want: "current-secret"}, + {name: "mounted initial access token", current: "current-secret", file: true, want: "current-secret"}, + {name: "deprecated mounted token", legacy: "legacy-secret", file: true, want: "legacy-secret"}, + {name: "new file wins", current: "current-secret", legacy: "legacy-secret", file: true, want: "current-secret"}, + } { + t.Run(test.name, func(t *testing.T) { + for name, value := range map[string]string{ + "OAUTH_ISSUER": "https://cm.example.com", "OAUTH_PROVIDER": "google", + "OAUTH_GOOGLE_CLIENT_ID": "cluster-manager", "OAUTH_GOOGLE_CLIENT_SECRET": "provider-secret", + "OAUTH_INITIAL_ACCESS_TOKEN": "", + "OAUTH_INITIAL_ACCESS_TOKEN_FILE": "", "OAUTH_REGISTRATION_ACCESS_TOKEN": "", + "OAUTH_REGISTRATION_ACCESS_TOKEN_FILE": "", + } { + t.Setenv(name, value) + } + for name, value := range map[string]string{"OAUTH_INITIAL_ACCESS_TOKEN": test.current, "OAUTH_REGISTRATION_ACCESS_TOKEN": test.legacy} { + if test.file && value != "" { + path := filepath.Join(t.TempDir(), "token") + require.NoError(t, os.WriteFile(path, []byte(value+"\n"), 0600)) + t.Setenv(name+"_FILE", path) + } else { + t.Setenv(name, value) + } + } + var output bytes.Buffer + logger := slog.New(slog.NewTextHandler(&output, nil)) + previous := slog.Default() + slog.SetDefault(logger) + t.Cleanup(func() { slog.SetDefault(previous) }) + settings, err := loadOAuthSettings(&serveOptions{}, logger) + require.NoError(t, err) + require.Equal(t, test.want, settings.Server.InitialAccessToken) + settings.Logger = logger + runtime, cleanup, err := oauthconfig.Setup(settings) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, cleanup(context.WithoutCancel(t.Context()))) }) + for _, token := range []string{"", "wrong-secret", test.want} { + request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/oauth/register", strings.NewReader(`{"client_name":"fixture","redirect_uris":["http://127.0.0.1:50123/callback"],"token_endpoint_auth_method":"client_secret_basic"}`)) + request.Header.Set("Content-Type", "application/json") + if token != "" { + request.Header.Set("Authorization", "Bearer "+token) + } + response := httptest.NewRecorder() + runtime.Handler.ServeClientRegistration(response, request) + status := http.StatusUnauthorized + if token == test.want { + status = http.StatusCreated + } + require.Equal(t, status, response.Code, response.Body.String()) + } + if test.legacy != "" { + require.Contains(t, output.String(), "DEPRECATED:") + require.Contains(t, output.String(), "OAUTH_INITIAL_ACCESS_TOKEN") + } else { + require.NotContains(t, output.String(), "DEPRECATED:") + } + require.NotContains(t, output.String(), "current-secret") + require.NotContains(t, output.String(), "legacy-secret") + }) + } +} diff --git a/hack/verify-chart.sh b/hack/verify-chart.sh index 944d5e7..1679b29 100755 --- a/hack/verify-chart.sh +++ b/hack/verify-chart.sh @@ -152,7 +152,7 @@ done <<'REFUSALS' --set github.tokenExchange.tokenEndpoint=https://m.example/t --set github.tokenExchange.audience=a --set github.tokenExchange.existingSecret=s|github.enabled is false --set github.enabled=true --set github.tokenExchange.tokenEndpoint=https://m.example/t --set github.tokenExchange.existingSecret=s|github.tokenExchange.audience is required --set github.enabled=true --set github.tokenExchange.tokenEndpoint=https://m.example/t --set github.tokenExchange.audience=a|github.tokenExchange.existingSecret or github.tokenExchange.clientSecret ---set github.enabled=true --set github.tokenExchange.tokenEndpoint=https://m.example/t --set github.tokenExchange.audience=a --set github.tokenExchange.existingSecret=s --set oauth.downstream.enabled=false|set oauth.enabled with oauth.provider dex and oauth.downstream.enabled +--set github.enabled=true --set github.tokenExchange.tokenEndpoint=https://m.example/t --set github.tokenExchange.audience=a --set github.tokenExchange.existingSecret=s --set oauth.downstream.enabled=false|set oauth.enabled with the dex provider (oauth.authorizationServer.upstream.type) and oauth.downstream.enabled --set github.enabled=true --set github.tokenExchange.tokenEndpoint=https://m.example/t --set github.tokenExchange.audience=a --set github.tokenExchange.existingSecret=s --set muster.mcpServer.enabled=true --set muster.mcpServer.auth.forwardToken=false|set muster.mcpServer.auth.forwardToken --set github.enabled=true --set github.tokenExchange.audience=a|github.tokenExchange.tokenEndpoint is required when any other github.tokenExchange value is set --set github.enabled=true --set github.tokenExchange.tokenEndpoint=https://m.example/t --set github.tokenExchange.audience=GitHub_App --set github.tokenExchange.existingSecret=s|/github/tokenExchange/audience diff --git a/helm/cluster-manager/README.md b/helm/cluster-manager/README.md index fe4af12..bf864fa 100644 --- a/helm/cluster-manager/README.md +++ b/helm/cluster-manager/README.md @@ -50,21 +50,37 @@ from the platform identity contract (`global.identity`, `global.domain`). | flux.tenantServiceAccount | string | `"automation"` | ServiceAccount in every org namespace the installation's Flux runs a composed release under when the release's objects live in that namespace: the pool release (its Cluster API objects) and the `-agent-platform` slice release (its child HelmReleases). Giant Swarm installations enforce the `flux-multi-tenancy` policy on every HelmRelease in `org-` — a `serviceAccountName` or a kubeconfig on each —, and `automation` is the org's tenant ServiceAccount there. A release installing into a cluster (the `-gpu-operator` release, the slice's children) is delivered through the cluster's `-kubeconfig` Secret instead, the installation's own cluster included. Empty renders none, for a lab without the policy. | | mcp.enabled | bool | `true` | Serve the MCP streamable-HTTP endpoint (the server's only surface). | | mcp.path | string | `"/mcp"` | MCP endpoint path. | -| oauth.enabled | bool | `false` | Make cluster-manager an OAuth 2.1 resource server (mcp-oauth): the MCP endpoint requires a bearer token the platform identity provider issued, and every call carries the caller's identity. On the Agent Platform muster forwards the session's IdP id_token to this server (MCPServer `auth.forwardToken`, rendered below) and the portal's calls arrive the same way through muster; both are validated against the IdP's JWKS when their audience is in `trustedAudiences`. Off: anonymous, acting as the ServiceAccount — only for a server nothing but a trusted proxy can reach. | -| oauth.baseURL | string | `""` | Public base URL of this server: the issuer of its own OAuth metadata (https, or http on loopback). Empty derives `https://.` when `global.domain` is set. | -| oauth.provider | string | `"dex"` | Identity provider: `dex` or `google`. | -| oauth.dex.issuerURL | string | `""` | Dex issuer URL. Empty falls back to `global.identity.issuerUrl`. | -| oauth.dex.clientID | string | `""` | Dex OAuth client ID. Empty falls back to `global.identity.clientId`. | -| oauth.dex.clientSecret | string | `""` | Dex OAuth client secret (prefer `oauth.existingSecret`). | +| oauth.enabled | bool | `false` | Make cluster-manager an OAuth 2.1 resource server (mcp-oauth): the MCP endpoint requires a bearer token, and every call carries the caller's identity. On the Agent Platform muster forwards the session's IdP ID token to this server (MCPServer `auth.forwardToken`, rendered below) and the portal's calls arrive the same way through muster; both are accepted from the provider people sign in with (`resourceServer.trustedIssuers`). Off: anonymous, acting as the ServiceAccount, only for a server nothing but a trusted proxy can reach. | +| oauth.resourceServer.resource | string | `""` | The main protected resource, by its full URL (`OAUTH_RESOURCE`). Empty uses the issuer. | +| oauth.resourceServer.additionalResources | list | `[]` | Further protected resources on the same origin, each by its full URL (`OAUTH_ADDITIONAL_RESOURCES`). The MCP endpoint is always a protected resource. | +| oauth.resourceServer.authorizationServers | list | `[]` | Issuer identifiers the resource metadata advertises (`OAUTH_AUTHORIZATION_SERVERS`, RFC 9728 `authorization_servers`): this server's issuer or a trusted issuer. Empty advertises this server's issuer; required with `authorizationServer.enabled` false, since MCP clients find the authorization server here. | +| oauth.resourceServer.trustedIssuers | list | `[]` | The issuers whose JWTs are accepted (`OAUTH_TRUSTED_ISSUERS`). A trust anchor: set it only from the release's own values or a GitOps-managed ConfigMap that only installation administrators write. Each entry: `issuer`, `jwksURI` and `audiences` (required), `subjectClaim` (`sub` or `email`), `acceptedTypHeaders`, `allowedClaims`, `allowPrivateIPJWKSHosts`, `openIDProvider` (true for the provider people sign in with, whose bearers are their ID tokens), and `certificateAuthority` with a `secretKeyRef` or `configMapKeyRef` (`name`, `key`). Empty trusts the provider people sign in with (`authorizationServer.upstream`) as `openIDProvider`: its ID tokens are accepted as bearer tokens, a deviation from MCP's audience rule until per-backend tokens (ID-JAG, giantswarm/giantswarm#39102). They are accepted for the client people sign in with (`authorizationServer.upstream.client.id`, or the deprecated `oauth.trustedAudiences`) and `muster.mcpServer.auth.requiredAudiences`, in that order and without duplicates. | +| oauth.resourceServer.requireResourceAccessTokens | bool | `false` | Accept only tokens whose audience names this server's resource (`OAUTH_REQUIRE_RESOURCE_ACCESS_TOKENS`), as MCP requires. Off while the platform forwards ID tokens (giantswarm/giantswarm#39102). | +| oauth.authorizationServer.enabled | bool | `true` | Run the authorization server. Off makes cluster-manager a resource server only (`OAUTH_ENABLE_AUTHORIZATION_SERVER=false`). | +| oauth.authorizationServer.issuer | string | `""` | Public base URL of this server, the issuer of its tokens and metadata (`OAUTH_ISSUER`; https, or http on loopback). Empty uses the deprecated `oauth.baseURL`, else `https://.`. | +| oauth.authorizationServer.upstream.type | string | `""` | The OpenID Provider people sign in with: `dex` or `google` (`OAUTH_PROVIDER`). Empty uses the deprecated `oauth.provider`, else `dex`. | +| oauth.authorizationServer.upstream.issuer | string | `""` | Dex issuer URL. Empty uses the deprecated `oauth.dex.issuerURL`, else `global.identity.issuerUrl`. | +| oauth.authorizationServer.upstream.client.id | string | `""` | OAuth client ID at the provider. Empty uses the deprecated `oauth.dex.clientID` or `oauth.google.clientID`, else `global.identity.clientId` (dex). | +| oauth.authorizationServer.upstream.client.secretKeyRef | object | `{"key":"client-secret","name":""}` | Secret key with the client secret, mounted as a file. Empty name uses the deprecated `oauth.existingSecret`, else `global.identity.existingSecret`, else a Secret from the deprecated inline client secret. | +| oauth.authorizationServer.upstream.certificateAuthority.secretKeyRef | object | `{"key":"ca.crt","name":""}` | Secret key with the CA of a Dex that serves a private certificate (`OAUTH_DEX_CA_FILE`). Empty name uses the deprecated `oauth.dex.caSecret`, else `global.identity.ca`. | +| oauth.authorizationServer.dynamicClientRegistration.enabled | bool | `true` | Serve RFC 7591 dynamic client registration (`OAUTH_ENABLE_DYNAMIC_CLIENT_REGISTRATION`). MCP 2026-07-28 deprecates it in favour of client ID metadata documents; it stays on for clients that still register this way. | +| oauth.authorizationServer.dynamicClientRegistration.initialAccessToken.secretKeyRef | object | `{"key":"token","name":""}` | Secret key with the RFC 7591 initial access token a registration must present (mcp-oauth reads it from `OAUTH_INITIAL_ACCESS_TOKEN_FILE`). | +| oauth.authorizationServer.clientIDMetadataDocuments.enabled | bool | `true` | Accept URL client IDs (client ID metadata documents) (`OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS`). | +| oauth.authorizationServer.storage.type | string | `"memory"` | Token storage (`OAUTH_STORAGE_BACKEND`). Memory loses every session on restart and needs one replica. | +| oauth.baseURL | string | `""` | Deprecated: use `authorizationServer.issuer`. | +| oauth.provider | string | `""` | Deprecated: use `authorizationServer.upstream.type`. | +| oauth.dex.issuerURL | string | `""` | Deprecated: use `authorizationServer.upstream.issuer`. | +| oauth.dex.clientID | string | `""` | Deprecated: use `authorizationServer.upstream.client.id`. | +| oauth.dex.clientSecret | string | `""` | Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. | | oauth.dex.allowPrivateURLs | bool | `false` | Deprecated, no effect, not passed to the server: the Dex client reaches private addresses and follows HTTP_PROXY, HTTPS_PROXY and NO_PROXY without it. Remove it from your values; the key goes away in a later release. | -| oauth.dex.caSecret | object | `{"key":"ca.crt","name":""}` | Secret with the CA of a Dex that serves a private certificate; mounted and passed as `OAUTH_DEX_CA_FILE`. Empty name falls back to `global.identity.ca.secretName` / `global.identity.ca.key`. | -| oauth.google.clientID | string | `""` | Google OAuth client ID (not secret; may also come from the Secret key `google-client-id` when empty). | -| oauth.google.clientSecret | string | `""` | Google OAuth client secret (prefer `oauth.existingSecret`). | -| oauth.existingSecret | string | `""` | Existing Secret with the provider credentials: `dex-client-secret` (dex) or `google-client-secret` (+ optional `google-client-id`) (google). Empty falls back to `global.identity.existingSecret`, whose `dex-client-secret` is the platform client's; without that, the chart renders a Secret from the values above. | -| oauth.trustedAudiences | list | `[]` | OAuth client IDs whose IdP id_tokens are accepted as bearer tokens (SSO token forwarding). Empty falls back to `[global.identity.clientId]`, the platform client MCP clients and the muster CLI log in with. The server trusts the union of this list and `muster.mcpServer.auth.requiredAudiences` (in that order, without duplicates): every token muster forwards carries the required audiences by construction and they are what the kube-apiserver trusts, so a portal session — whose id_token carries them but not the platform client — is accepted without listing its client here. | -| oauth.sso.allowPrivateIPs | bool | `false` | Deprecated, no effect, not passed to the server: the issuer host's JWKS endpoint may resolve to a private address without it; list any other JWKS host in allowPrivateIPJWKSHosts. Remove it from your values; the key goes away in a later release. | -| oauth.sso.allowPrivateIPJWKSHosts | list | `[]` | Hosts, other than the issuer's own, whose JWKS may resolve to an RFC 1918 or RFC 4193 address: a jwks_uri the IdP's discovery document puts on another host. Exact hostnames, no port. Loopback and link-local stay refused. | -| oauth.allowPublicClientRegistration | bool | `false` | Accept unauthenticated dynamic client registration (labs only). | +| oauth.dex.caSecret | object | `{"key":"ca.crt","name":""}` | Deprecated: use `authorizationServer.upstream.certificateAuthority`. | +| oauth.google.clientID | string | `""` | Deprecated: use `authorizationServer.upstream.client.id`. Empty reads the Secret key `google-client-id`. | +| oauth.google.clientSecret | string | `""` | Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. | +| oauth.existingSecret | string | `""` | Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. Existing Secret with `dex-client-secret` (dex) or `google-client-secret` (+ optional `google-client-id`) (google). | +| oauth.trustedAudiences | list | `[]` | Deprecated: list the provider in `resourceServer.trustedIssuers` with these `audiences`. The OAuth client IDs whose ID tokens of the provider people sign in with are accepted. | +| oauth.sso.allowPrivateIPs | bool | `false` | Deprecated, no effect, not passed to the server: the issuer host of the configured provider may resolve to a private address for its JWKS without it; list any other JWKS host in allowPrivateIPJWKSHosts. Remove it from your values; the key goes away in a later release. | +| oauth.sso.allowPrivateIPJWKSHosts | list | `[]` | Deprecated: list the provider in `resourceServer.trustedIssuers` with these `allowPrivateIPJWKSHosts`. Hosts, other than the issuer's own, whose JWKS may resolve to an RFC 1918 or RFC 4193 address. | +| oauth.allowPublicClientRegistration | bool | `false` | Deprecated, removed in a later release: accept dynamic client registration without an initial access token, public clients included (labs only). MCP clients register with client ID metadata documents. | | oauth.downstream.enabled | bool | `true` | Call the Kubernetes API as the caller: everything a request does presents the caller's IdP token, so the caller's RBAC governs — the apiserver must trust the IdP and the token's audience (a Dex install lists that audience in `muster.mcpServer.auth.requiredAudiences`; a Google install's client id is the apiserver's `--oidc-client-id`). This is cluster-manager's rule (every write as the person), so it is on by default and takes effect with `oauth.enabled`. The ServiceAccount then holds no permissions: the chart renders no RBAC for it (`rbac.create` is moot). | | github.enabled | bool | `false` | Offer commit mode (`mode: commit` on `create_cluster`, `delete_cluster`, `create_node_pool` and `delete_node_pool`: the pull request opened as the person in the repository that owns the cluster). Needs `oauth.enabled` and `tokenExchange.tokenEndpoint`: muster keeps forwarding the person's ID token as the bearer (`muster.mcpServer.auth.forwardToken`) and the server fetches the person's GitHub App user token for each commit (RFC 8693). Off: commit mode is refused. | | github.apiURL | string | `"https://api.github.com"` | GitHub's REST API, for `GET /user` and the pull request. | diff --git a/helm/cluster-manager/templates/NOTES.txt b/helm/cluster-manager/templates/NOTES.txt index babc302..9d47ed2 100644 --- a/helm/cluster-manager/templates/NOTES.txt +++ b/helm/cluster-manager/templates/NOTES.txt @@ -21,3 +21,28 @@ Try it: muster registers the server as MCPServer "{{ .Values.muster.mcpServer.name }}"; tools appear as x_{{ .Values.muster.mcpServer.name }}_. {{- end }} +{{- $o := .Values.oauth }} +{{- $deprecated := dict + "oauth.baseURL" (list $o.baseURL "oauth.authorizationServer.issuer") + "oauth.provider" (list $o.provider "oauth.authorizationServer.upstream.type") + "oauth.dex.issuerURL" (list $o.dex.issuerURL "oauth.authorizationServer.upstream.issuer") + "oauth.dex.clientID" (list $o.dex.clientID "oauth.authorizationServer.upstream.client.id") + "oauth.dex.clientSecret" (list $o.dex.clientSecret "oauth.authorizationServer.upstream.client.secretKeyRef") + "oauth.dex.caSecret.name" (list $o.dex.caSecret.name "oauth.authorizationServer.upstream.certificateAuthority.secretKeyRef") + "oauth.google.clientID" (list $o.google.clientID "oauth.authorizationServer.upstream.client.id") + "oauth.google.clientSecret" (list $o.google.clientSecret "oauth.authorizationServer.upstream.client.secretKeyRef") + "oauth.existingSecret" (list $o.existingSecret "oauth.authorizationServer.upstream.client.secretKeyRef") + "oauth.trustedAudiences" (list $o.trustedAudiences "the audiences of an oauth.resourceServer.trustedIssuers entry") + "oauth.sso.allowPrivateIPJWKSHosts" (list $o.sso.allowPrivateIPJWKSHosts "the allowPrivateIPJWKSHosts of an oauth.resourceServer.trustedIssuers entry") + "oauth.allowPublicClientRegistration" (list $o.allowPublicClientRegistration "nothing: MCP clients register with client ID metadata documents") + "oauth.dex.allowPrivateURLs" (list $o.dex.allowPrivateURLs "nothing: it has no effect") + "oauth.sso.allowPrivateIPs" (list $o.sso.allowPrivateIPs "nothing: it has no effect") }} +{{- $set := list }} +{{- range $key := keys $deprecated | sortAlpha }}{{ if index $deprecated $key 0 }}{{ $set = append $set $key }}{{ end }}{{ end }} +{{- if and $o.enabled $set }} + +Deprecated values, removed in a later release: +{{- range $set }} + {{ . }}: use {{ index $deprecated . 1 }} +{{- end }} +{{- end }} diff --git a/helm/cluster-manager/templates/_helpers.tpl b/helm/cluster-manager/templates/_helpers.tpl index 532b4e4..bfd4234 100644 --- a/helm/cluster-manager/templates/_helpers.tpl +++ b/helm/cluster-manager/templates/_helpers.tpl @@ -72,8 +72,9 @@ The platform identity contract (global.identity), an empty dict when absent. {{- end }} {{/* -Existing Secret with the provider credentials: oauth.existingSecret, else the -platform's global.identity.existingSecret, else the chart-rendered one. +Existing Secret with the provider credentials of the deprecated keys: +oauth.existingSecret, else the platform's global.identity.existingSecret, +else the chart-rendered one. */}} {{- define "cluster-manager.oauthSecretName" -}} {{- $g := include "cluster-manager.globalIdentity" . | fromJson -}} @@ -81,73 +82,153 @@ platform's global.identity.existingSecret, else the chart-rendered one. {{- end }} {{/* -Whether the chart renders its own OAuth Secret (no existing one named). +Whether the chart renders its own OAuth Secret: no +authorizationServer.upstream.client.secretKeyRef, no existing Secret named. */}} {{- define "cluster-manager.oauthRendersSecret" -}} {{- $g := include "cluster-manager.globalIdentity" . | fromJson -}} -{{- if and .Values.oauth.enabled (not .Values.oauth.existingSecret) (not (dig "existingSecret" "" $g)) }}true{{ end }} +{{- $o := .Values.oauth -}} +{{- if and $o.enabled $o.authorizationServer.enabled (not $o.authorizationServer.upstream.client.secretKeyRef.name) (not $o.existingSecret) (not (dig "existingSecret" "" $g)) }}true{{ end }} {{- end }} {{/* -OAuth base URL: oauth.baseURL, else https://.. +The provider people sign in with: authorizationServer.upstream.type, else the +deprecated oauth.provider, else global.identity.type, else dex. */}} -{{- define "cluster-manager.oauthBaseURL" -}} -{{- $domain := dig "domain" "" (.Values.global | default dict) -}} -{{- $derived := "" -}} -{{- if $domain }}{{ $derived = printf "https://%s.%s" (include "cluster-manager.fullname" .) $domain }}{{ end -}} -{{- required "oauth.baseURL is required when oauth.enabled (or set global.domain)" (.Values.oauth.baseURL | default $derived) }} -{{- end }} - -{{/* -Dex issuer / client id with the global.identity fallbacks. -*/}} -{{- define "cluster-manager.oauthDexIssuerURL" -}} -{{- $g := include "cluster-manager.globalIdentity" . | fromJson -}} -{{- required "oauth.dex.issuerURL (or global.identity.issuerUrl) is required for the dex provider" (.Values.oauth.dex.issuerURL | default (dig "issuerUrl" "" $g)) }} -{{- end }} - -{{- define "cluster-manager.oauthDexClientID" -}} +{{- define "cluster-manager.oauthProvider" -}} {{- $g := include "cluster-manager.globalIdentity" . | fromJson -}} -{{- required "oauth.dex.clientID (or global.identity.clientId) is required for the dex provider" (.Values.oauth.dex.clientID | default (dig "clientId" "" $g)) }} +{{- .Values.oauth.authorizationServer.upstream.type | default .Values.oauth.provider | default (dig "type" "" $g) | default "dex" }} {{- end }} {{/* -CA Secret of a private-certificate Dex: oauth.dex.caSecret, else -global.identity.ca. Name empty means system trust. +The audiences, as JSON, that muster requests at login and the forwarded ID +token then carries for the Kubernetes API server: muster.mcpServer.auth.requiredAudiences, +else global.identity.kubernetes.audiences. */}} -{{- define "cluster-manager.oauthDexCASecretName" -}} -{{- $g := include "cluster-manager.globalIdentity" . | fromJson -}} -{{- .Values.oauth.dex.caSecret.name | default (dig "ca" "secretName" "" $g) }} -{{- end }} - -{{- define "cluster-manager.oauthDexCASecretKey" -}} +{{- define "cluster-manager.requiredAudiences" -}} {{- $g := include "cluster-manager.globalIdentity" . | fromJson -}} -{{- if .Values.oauth.dex.caSecret.name }}{{ .Values.oauth.dex.caSecret.key | default "ca.crt" }}{{ else }}{{ dig "ca" "key" "" $g | default .Values.oauth.dex.caSecret.key | default "ca.crt" }}{{ end }} +{{- .Values.muster.mcpServer.auth.requiredAudiences | default (dig "kubernetes" "audiences" list $g) | toJson }} {{- end }} {{/* -Trusted audiences, comma-separated: the OAuth client ids whose IdP id_tokens -this server accepts as bearer tokens. The union, in this order and without -duplicates, of - - oauth.trustedAudiences, else the platform client (global.identity.clientId) - — the client MCP clients and the muster CLI log in with; - - muster.mcpServer.auth.requiredAudiences — every token muster forwards to - this server carries them by construction (muster requests them at login) - and they are the audiences the kube-apiserver trusts, so a portal - session's token, which carries them but not the platform client, is - accepted too. The pair is what the management clusters' mcp-kubernetes - trusts as well. -A Google install has no cross-client audiences (requiredAudiences empty) and -trusts the client id alone. +The OAuth settings the Deployment renders, as JSON. Each comes from the +shared layout (oauth.resourceServer, oauth.authorizationServer), else from +the deprecated key it replaces, else from global.identity: + issuer authorizationServer.issuer, baseURL, https://. + provider authorizationServer.upstream.type, provider, global.identity.type, dex + upstreamIssuer authorizationServer.upstream.issuer, dex.issuerURL, global.identity.issuerUrl + clientID authorizationServer.upstream.client.id, dex.clientID or google.clientID, + global.identity.clientId (dex) + clientSecret authorizationServer.upstream.client.secretKeyRef, existingSecret, + global.identity.existingSecret, the chart-rendered Secret + upstreamCA authorizationServer.upstream.certificateAuthority.secretKeyRef, + dex.caSecret, global.identity.ca + trustedIssuers resourceServer.trustedIssuers, else one entry for the + provider people sign in with (openIDProvider), accepting its + ID tokens for the union, in this order and without + duplicates, of the deprecated trustedAudiences (else + clientID, else global.identity.clientId) and + cluster-manager.requiredAudiences: every token muster + forwards carries those by construction and the + kube-apiserver trusts them, so a portal session's ID token + is accepted too +A CA is a mount: {volume, secret or configMap, key, dir}; caFile is dir/key. */}} -{{- define "cluster-manager.oauthTrustedAudiences" -}} +{{- define "cluster-manager.oauth" -}} +{{- $o := .Values.oauth -}} +{{- $as := $o.authorizationServer -}} +{{- $up := $as.upstream -}} +{{- $rs := $o.resourceServer -}} {{- $g := include "cluster-manager.globalIdentity" . | fromJson -}} -{{- $base := .Values.oauth.trustedAudiences | default (list (dig "clientId" "" $g)) -}} -{{- $auds := list -}} -{{- range concat $base (.Values.muster.mcpServer.auth.requiredAudiences | default list) -}} -{{- if and . (not (has . $auds)) }}{{ $auds = append $auds . }}{{ end -}} +{{- $domain := dig "domain" "" (.Values.global | default dict) -}} +{{- $derived := "" -}} +{{- if $domain }}{{ $derived = printf "https://%s.%s" (include "cluster-manager.fullname" .) $domain }}{{ end -}} +{{- $r := dict "authorizationServer" $as.enabled "mounts" list -}} +{{- $_ := set $r "issuer" (required "oauth.authorizationServer.issuer is required when oauth.enabled (or set global.domain)" ($as.issuer | default $o.baseURL | default $derived)) -}} +{{- $provider := include "cluster-manager.oauthProvider" . -}} +{{- $_ = set $r "provider" $provider -}} +{{- $upstreamIssuer := "" -}} +{{- $clientID := "" -}} +{{- if eq $provider "dex" -}} +{{- $upstreamIssuer = $up.issuer | default $o.dex.issuerURL | default (dig "issuerUrl" "" $g) -}} +{{- $clientID = $up.client.id | default $o.dex.clientID | default (dig "clientId" "" $g) -}} +{{- else -}} +{{- $upstreamIssuer = "https://accounts.google.com" -}} +{{- $clientID = $up.client.id | default $o.google.clientID -}} +{{- end -}} +{{- $_ = set $r "upstreamIssuer" $upstreamIssuer -}} +{{- $_ = set $r "clientID" $clientID -}} +{{- if $up.client.secretKeyRef.name -}} +{{- $_ = set $r "clientSecret" (dict "name" $up.client.secretKeyRef.name "key" (required "oauth.authorizationServer.upstream.client.secretKeyRef.key is required with its name" $up.client.secretKeyRef.key)) -}} +{{- else -}} +{{- $_ = set $r "clientSecret" (dict "name" (include "cluster-manager.oauthSecretName" .) "key" (printf "%s-client-secret" $provider)) -}} +{{- if and (eq $provider "google") (not $clientID) -}} +{{- $_ = set $r "clientIDSecret" (dict "name" (include "cluster-manager.oauthSecretName" .) "key" "google-client-id") -}} +{{- end -}} +{{- end -}} +{{- if eq $provider "dex" -}} +{{- $ca := dict -}} +{{- if $up.certificateAuthority.secretKeyRef.name -}} +{{- $ca = dict "secret" $up.certificateAuthority.secretKeyRef.name "key" ($up.certificateAuthority.secretKeyRef.key | default "ca.crt") -}} +{{- else if $o.dex.caSecret.name -}} +{{- $ca = dict "secret" $o.dex.caSecret.name "key" ($o.dex.caSecret.key | default "ca.crt") -}} +{{- else if dig "ca" "secretName" "" $g -}} +{{- $ca = dict "secret" (dig "ca" "secretName" "" $g) "key" (dig "ca" "key" "" $g | default $o.dex.caSecret.key | default "ca.crt") -}} +{{- end -}} +{{- if $ca.secret -}} +{{- $_ = set $ca "volume" "idp-ca" -}} +{{- $_ = set $ca "dir" "/etc/cluster-manager/idp-ca" -}} +{{- $_ = set $r "upstreamCA" $ca -}} +{{- $_ = set $r "mounts" (append $r.mounts $ca) -}} +{{- end -}} +{{- end -}} +{{- $issuers := list -}} +{{- range $i, $entry := $rs.trustedIssuers -}} +{{- $out := omit $entry "certificateAuthority" -}} +{{- with $entry.certificateAuthority -}} +{{- $ca := dict "volume" (printf "trusted-issuer-ca-%d" $i) "dir" (printf "/etc/cluster-manager/trusted-issuer-ca/%d" $i) -}} +{{- if .secretKeyRef -}} +{{- $_ := set $ca "secret" (required (printf "oauth.resourceServer.trustedIssuers[%d].certificateAuthority.secretKeyRef.name is required" $i) .secretKeyRef.name) -}} +{{- $_ = set $ca "key" (.secretKeyRef.key | default "ca.crt") -}} +{{- else -}} +{{- $_ := set $ca "configMap" (required (printf "oauth.resourceServer.trustedIssuers[%d].certificateAuthority needs secretKeyRef or configMapKeyRef" $i) (dig "configMapKeyRef" "name" "" .)) -}} +{{- $_ = set $ca "key" (dig "configMapKeyRef" "key" "" . | default "ca.crt") -}} +{{- end -}} +{{- $_ := set $out "caFile" (printf "%s/%s" $ca.dir $ca.key) -}} +{{- $_ = set $r "mounts" (append $r.mounts $ca) -}} +{{- end -}} +{{- $issuers = append $issuers $out -}} +{{- end -}} +{{- if not $issuers -}} +{{- $audiences := list -}} +{{- range concat ($o.trustedAudiences | default (list ($clientID | default (dig "clientId" "" $g)))) (include "cluster-manager.requiredAudiences" . | fromJsonArray) -}} +{{- if and . (not (has . $audiences)) }}{{ $audiences = append $audiences . }}{{ end -}} +{{- end -}} +{{- if and $audiences $upstreamIssuer -}} +{{- $entry := dict "issuer" $upstreamIssuer "audiences" $audiences "openIDProvider" true -}} +{{- if eq $provider "dex" -}} +{{- /* Dex serves its JWKS at /keys and signs ID tokens without a typ header. mcp-oauth does not imply the issuer host for private JWKS addresses, so it is listed. */ -}} +{{- $_ := set $entry "jwksURI" (printf "%s/keys" (trimSuffix "/" $upstreamIssuer)) -}} +{{- $_ = set $entry "acceptedTypHeaders" (list "" "JWT") -}} +{{- $_ = set $entry "allowPrivateIPJWKSHosts" (concat (list (urlParse $upstreamIssuer).hostname) $o.sso.allowPrivateIPJWKSHosts | uniq) -}} +{{- with $r.upstreamCA }}{{ $_ = set $entry "caFile" (printf "%s/%s" .dir .key) }}{{ end -}} +{{- else -}} +{{- $_ := set $entry "jwksURI" "https://www.googleapis.com/oauth2/v3/certs" -}} +{{- $_ = set $entry "acceptedTypHeaders" (list "JWT") -}} +{{- end -}} +{{- $issuers = list $entry -}} +{{- end -}} +{{- end -}} +{{- if not $as.enabled -}} +{{- if not $issuers -}} +{{- fail "oauth.authorizationServer.enabled false accepts only trusted issuer tokens: set oauth.resourceServer.trustedIssuers, or the upstream issuer and client ID it is derived from" -}} +{{- end -}} +{{- if not $rs.authorizationServers -}} +{{- fail "oauth.authorizationServer.enabled false needs oauth.resourceServer.authorizationServers: MCP clients discover the authorization server from the protected resource metadata (RFC 9728), and this server then runs none" -}} +{{- end -}} {{- end -}} -{{- join "," $auds -}} +{{- $_ = set $r "trustedIssuers" $issuers -}} +{{- toJson $r -}} {{- end }} {{/* @@ -203,8 +284,8 @@ client secret. {{- if not .Values.github.enabled }} {{- fail "github.tokenExchange.tokenEndpoint is set but github.enabled is false: set github.enabled to fetch the person's GitHub grant per commit, or clear github.tokenExchange" }} {{- end }} -{{- if not (and .Values.oauth.enabled (eq .Values.oauth.provider "dex") .Values.oauth.downstream.enabled) }} -{{- fail "github.tokenExchange exchanges the person's Dex ID token: set oauth.enabled with oauth.provider dex and oauth.downstream.enabled" }} +{{- if not (and .Values.oauth.enabled (eq (include "cluster-manager.oauthProvider" .) "dex") .Values.oauth.downstream.enabled) }} +{{- fail "github.tokenExchange exchanges the person's Dex ID token: set oauth.enabled with the dex provider (oauth.authorizationServer.upstream.type) and oauth.downstream.enabled" }} {{- end }} {{- if and .Values.muster.mcpServer.enabled (not .Values.muster.mcpServer.auth.forwardToken) }} {{- fail "github.tokenExchange lists its audience under the MCPServer's auth.providerApps, which muster accepts only with forwardToken: set muster.mcpServer.auth.forwardToken" }} diff --git a/helm/cluster-manager/templates/deployment.yaml b/helm/cluster-manager/templates/deployment.yaml index ea8e4fd..b14cd3a 100644 --- a/helm/cluster-manager/templates/deployment.yaml +++ b/helm/cluster-manager/templates/deployment.yaml @@ -80,8 +80,8 @@ spec: {{- end }} - --github-api-url={{ .Values.github.apiURL }} {{- end }} - {{- if eq .Values.oauth.provider "dex" }} - {{- with .Values.createdClusters.oidc.clientID | default (first (.Values.muster.mcpServer.auth.requiredAudiences | default list)) }} + {{- if eq (include "cluster-manager.oauthProvider" .) "dex" }} + {{- with .Values.createdClusters.oidc.clientID | default (first (include "cluster-manager.requiredAudiences" . | fromJsonArray)) }} - --cluster-oidc-client-id={{ . }} - --cluster-oidc-username-claim={{ $.Values.createdClusters.oidc.usernameClaim }} - --cluster-oidc-groups-claim={{ $.Values.createdClusters.oidc.groupsClaim }} @@ -111,55 +111,79 @@ spec: {{- end }} {{- if .Values.oauth.enabled }} {{- /* mcp-oauth's settings (oauthconfig.SettingsFromEnv). */}} + {{- $oauth := include "cluster-manager.oauth" . | fromJson }} + {{- $rs := .Values.oauth.resourceServer }} + {{- $as := .Values.oauth.authorizationServer }} - name: OAUTH_ISSUER - value: {{ include "cluster-manager.oauthBaseURL" . | quote }} - - name: OAUTH_PROVIDER - value: {{ .Values.oauth.provider | quote }} - - name: OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS - value: "true" - {{- with include "cluster-manager.oauthTrustedAudiences" . }} - - name: OAUTH_TRUSTED_AUDIENCES + value: {{ $oauth.issuer | quote }} + {{- with $rs.resource }} + - name: OAUTH_RESOURCE value: {{ . | quote }} {{- end }} - {{- with .Values.oauth.sso.allowPrivateIPJWKSHosts }} - - name: OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS + {{- with $rs.additionalResources }} + - name: OAUTH_ADDITIONAL_RESOURCES + value: {{ $resources := list }}{{ range . }}{{ $resources = append $resources (dict "resource" .) }}{{ end }}{{ toJson $resources | quote }} + {{- end }} + {{- with $rs.authorizationServers }} + - name: OAUTH_AUTHORIZATION_SERVERS value: {{ join "," . | quote }} {{- end }} + {{- with $oauth.trustedIssuers }} + - name: OAUTH_TRUSTED_ISSUERS + value: {{ toJson . | quote }} + {{- end }} + {{- if $rs.requireResourceAccessTokens }} + - name: OAUTH_REQUIRE_RESOURCE_ACCESS_TOKENS + value: "true" + {{- end }} + {{- if not $oauth.authorizationServer }} + - name: OAUTH_ENABLE_AUTHORIZATION_SERVER + value: "false" + {{- else }} + - name: OAUTH_PROVIDER + value: {{ $oauth.provider | quote }} + - name: OAUTH_STORAGE_BACKEND + value: {{ $as.storage.type | quote }} + - name: OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS + value: {{ $as.clientIDMetadataDocuments.enabled | quote }} + {{- if not $as.dynamicClientRegistration.enabled }} + - name: OAUTH_ENABLE_DYNAMIC_CLIENT_REGISTRATION + value: "false" + {{- end }} + {{- if $as.dynamicClientRegistration.initialAccessToken.secretKeyRef.name }} + - name: OAUTH_INITIAL_ACCESS_TOKEN_FILE + value: /etc/cluster-manager/oauth-registration/token + {{- end }} {{- if .Values.oauth.allowPublicClientRegistration }} - name: OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION value: "true" {{- end }} - {{- if eq .Values.oauth.provider "google" }} - {{- if .Values.oauth.google.clientID }} - - name: OAUTH_GOOGLE_CLIENT_ID - value: {{ .Values.oauth.google.clientID | quote }} - {{- else }} + {{- if eq $oauth.provider "google" }} + {{- with $oauth.clientIDSecret }} - name: OAUTH_GOOGLE_CLIENT_ID valueFrom: secretKeyRef: - name: {{ include "cluster-manager.oauthSecretName" . }} - key: google-client-id + name: {{ .name }} + key: {{ .key }} + {{- else }} + - name: OAUTH_GOOGLE_CLIENT_ID + value: {{ $oauth.clientID | quote }} {{- end }} - - name: OAUTH_GOOGLE_CLIENT_SECRET - valueFrom: - secretKeyRef: - name: {{ include "cluster-manager.oauthSecretName" . }} - key: google-client-secret + - name: OAUTH_GOOGLE_CLIENT_SECRET_FILE + value: /etc/cluster-manager/oauth-client/client-secret - name: OAUTH_GOOGLE_REDIRECT_URL - value: {{ printf "%s/oauth/callback" (include "cluster-manager.oauthBaseURL" . | trimSuffix "/") | quote }} + value: {{ printf "%s/oauth/callback" ($oauth.issuer | trimSuffix "/") | quote }} {{- else }} - name: OAUTH_DEX_ISSUER_URL - value: {{ include "cluster-manager.oauthDexIssuerURL" . | quote }} + value: {{ required "oauth.authorizationServer.upstream.issuer (or global.identity.issuerUrl) is required for the dex provider" $oauth.upstreamIssuer | quote }} - name: OAUTH_DEX_CLIENT_ID - value: {{ include "cluster-manager.oauthDexClientID" . | quote }} - - name: OAUTH_DEX_CLIENT_SECRET - valueFrom: - secretKeyRef: - name: {{ include "cluster-manager.oauthSecretName" . }} - key: dex-client-secret - {{- if include "cluster-manager.oauthDexCASecretName" . }} + value: {{ required "oauth.authorizationServer.upstream.client.id (or global.identity.clientId) is required for the dex provider" $oauth.clientID | quote }} + - name: OAUTH_DEX_CLIENT_SECRET_FILE + value: /etc/cluster-manager/oauth-client/client-secret + {{- with $oauth.upstreamCA }} - name: OAUTH_DEX_CA_FILE - value: /etc/cluster-manager/idp-ca/{{ include "cluster-manager.oauthDexCASecretKey" . }} + value: {{ printf "%s/%s" .dir .key | quote }} + {{- end }} {{- end }} {{- end }} {{- end }} @@ -202,17 +226,27 @@ spec: failureThreshold: 3 resources: {{- toYaml .Values.resources | nindent 12 }} - {{- $idpCA := "" }} {{- $githubExchange := include "cluster-manager.githubTokenExchange" . }} - {{- if and .Values.oauth.enabled (eq .Values.oauth.provider "dex") }}{{ $idpCA = include "cluster-manager.oauthDexCASecretName" . }}{{ end }} + {{- $oauth := dict "mounts" list }} + {{- if .Values.oauth.enabled }}{{ $oauth = include "cluster-manager.oauth" . | fromJson }}{{ end }} volumeMounts: - name: tmp mountPath: /tmp - {{- if $idpCA }} - - name: idp-ca - mountPath: /etc/cluster-manager/idp-ca + {{- range $oauth.mounts }} + - name: {{ .volume }} + mountPath: {{ .dir }} readOnly: true {{- end }} + {{- if $oauth.authorizationServer }} + - name: oauth-client + mountPath: /etc/cluster-manager/oauth-client + readOnly: true + {{- if .Values.oauth.authorizationServer.dynamicClientRegistration.initialAccessToken.secretKeyRef.name }} + - name: oauth-registration + mountPath: /etc/cluster-manager/oauth-registration + readOnly: true + {{- end }} + {{- end }} {{- if $githubExchange }} - name: github-token-exchange mountPath: /etc/cluster-manager/github-token-exchange @@ -231,13 +265,38 @@ spec: {{- else }} emptyDir: {} {{- end }} - {{- if $idpCA }} - - name: idp-ca + {{- range $oauth.mounts }} + - name: {{ .volume }} + {{- if .secret }} + secret: + secretName: {{ .secret }} + {{- else }} + configMap: + name: {{ .configMap }} + {{- end }} + items: + - key: {{ .key }} + path: {{ .key }} + {{- end }} + {{- if $oauth.authorizationServer }} + - name: oauth-client secret: - secretName: {{ $idpCA }} + secretName: {{ $oauth.clientSecret.name }} + defaultMode: 0440 items: - - key: {{ include "cluster-manager.oauthDexCASecretKey" . }} - path: {{ include "cluster-manager.oauthDexCASecretKey" . }} + - key: {{ $oauth.clientSecret.key }} + path: client-secret + {{- with .Values.oauth.authorizationServer.dynamicClientRegistration.initialAccessToken.secretKeyRef }} + {{- if .name }} + - name: oauth-registration + secret: + secretName: {{ .name }} + defaultMode: 0440 + items: + - key: {{ required "oauth.authorizationServer.dynamicClientRegistration.initialAccessToken.secretKeyRef.key is required with its name" .key }} + path: token + {{- end }} + {{- end }} {{- end }} {{- if $githubExchange }} - name: github-token-exchange diff --git a/helm/cluster-manager/templates/mcpserver.yaml b/helm/cluster-manager/templates/mcpserver.yaml index 860889e..5cac1c9 100644 --- a/helm/cluster-manager/templates/mcpserver.yaml +++ b/helm/cluster-manager/templates/mcpserver.yaml @@ -6,8 +6,8 @@ {{- /* Registers this server with muster. Tools appear as x__. With oauth.enabled the CR carries the auth block: muster forwards the session's IdP -id_token (forwardToken), which this server validates against its trusted -audiences (oauth.trustedAudiences plus the requiredAudiences below), and +ID token (forwardToken), which this server accepts from the OpenID Provider for +the platform client and the requiredAudiences below (cluster-manager.oauth), and requests the requiredAudiences at login. Without OAuth muster connects anonymously. With github.enabled and github.tokenExchange the auth lists github.tokenExchange.audience under providerApps: muster answers the server's @@ -48,7 +48,7 @@ spec: providerApps: - {{ .Values.github.tokenExchange.audience | quote }} {{- end }} - {{- with .Values.muster.mcpServer.auth.requiredAudiences }} + {{- with include "cluster-manager.requiredAudiences" . | fromJsonArray }} requiredAudiences: {{- toYaml . | nindent 6 }} {{- end }} diff --git a/helm/cluster-manager/templates/oauth-secret.yaml b/helm/cluster-manager/templates/oauth-secret.yaml index c5c0e3d..3b3732f 100644 --- a/helm/cluster-manager/templates/oauth-secret.yaml +++ b/helm/cluster-manager/templates/oauth-secret.yaml @@ -1,7 +1,8 @@ {{- if include "cluster-manager.oauthRendersSecret" . }} {{- /* -Provider credentials when no existing Secret is named (neither -oauth.existingSecret nor the platform's global.identity.existingSecret). +Provider credentials from the deprecated inline values, when no Secret is +named (no authorizationServer.upstream.client.secretKeyRef, oauth.existingSecret +or global.identity.existingSecret). */}} apiVersion: v1 kind: Secret @@ -12,7 +13,7 @@ metadata: {{- include "cluster-manager.labels" . | nindent 4 }} type: Opaque stringData: - {{- if eq .Values.oauth.provider "google" }} + {{- if eq (include "cluster-manager.oauthProvider" .) "google" }} google-client-secret: {{ required "oauth.google.clientSecret or oauth.existingSecret is required when oauth.enabled with the google provider" .Values.oauth.google.clientSecret | quote }} {{- with .Values.oauth.google.clientID }} google-client-id: {{ . | quote }} diff --git a/helm/cluster-manager/tests/oauth_env_test.yaml b/helm/cluster-manager/tests/oauth_env_test.yaml index 9e5d309..ffe2240 100644 --- a/helm/cluster-manager/tests/oauth_env_test.yaml +++ b/helm/cluster-manager/tests/oauth_env_test.yaml @@ -1,4 +1,4 @@ -suite: OAuth settings as mcp-oauth OAUTH_* variables +suite: OAuth settings from the deprecated keys templates: - templates/deployment.yaml set: @@ -18,6 +18,9 @@ tests: - contains: path: spec.template.spec.containers[0].env content: {name: OAUTH_PROVIDER, value: dex} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_STORAGE_BACKEND, value: memory} - contains: path: spec.template.spec.containers[0].env content: {name: OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS, value: "true"} @@ -29,13 +32,15 @@ tests: content: {name: OAUTH_DEX_CLIENT_ID, value: manager} - contains: path: spec.template.spec.containers[0].env - content: - name: OAUTH_DEX_CLIENT_SECRET - valueFrom: - secretKeyRef: {name: manager-oauth, key: dex-client-secret} + content: {name: OAUTH_DEX_CLIENT_SECRET_FILE, value: /etc/cluster-manager/oauth-client/client-secret} - contains: - path: spec.template.spec.containers[0].env - content: {name: OAUTH_TRUSTED_AUDIENCES, value: agent-platform} + path: spec.template.spec.volumes + content: + name: oauth-client + secret: + secretName: manager-oauth + defaultMode: 0440 + items: [{key: dex-client-secret, path: client-secret}] - contains: path: spec.template.spec.containers[0].args content: --enable-oauth=true @@ -43,6 +48,10 @@ tests: path: spec.template.spec.containers[0].env any: true content: {name: OAUTH_DEX_CA_FILE} + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: OAUTH_TRUSTED_AUDIENCES} - notContains: path: spec.template.spec.containers[0].env any: true @@ -51,19 +60,37 @@ tests: path: spec.template.spec.containers[0].args[*] pattern: ^--(oauth-|dex-|sso-|google-|allow-private-oauth-urls|allow-public-client-registration) - - it: points OAUTH_DEX_CA_FILE at the mounted CA + - it: trusts Dex as the OpenID Provider for the trusted audiences + asserts: + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.test"],"audiences":["agent-platform"],"issuer":"https://dex.example.test","jwksURI":"https://dex.example.test/keys","openIDProvider":true}]' + + - it: adds the deprecated JWKS hosts and the CA to the Dex entry set: oauth.dex.caSecret.name: dex-ca + oauth.sso.allowPrivateIPJWKSHosts: [keys.internal.example] asserts: - contains: path: spec.template.spec.containers[0].env content: {name: OAUTH_DEX_CA_FILE, value: /etc/cluster-manager/idp-ca/ca.crt} + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.test","keys.internal.example"],"audiences":["agent-platform"],"caFile":"/etc/cluster-manager/idp-ca/ca.crt","issuer":"https://dex.example.test","jwksURI":"https://dex.example.test/keys","openIDProvider":true}]' + - contains: + path: spec.template.spec.volumes + content: + name: idp-ca + secret: + secretName: dex-ca + items: [{key: ca.crt, path: ca.crt}] - it: renders the Google settings with the callback as redirect URL set: oauth.provider: google oauth.baseURL: https://manager.example.test/ oauth.google.clientID: google-client + oauth.trustedAudiences: [google-client] asserts: - contains: path: spec.template.spec.containers[0].env @@ -73,18 +100,37 @@ tests: content: {name: OAUTH_GOOGLE_CLIENT_ID, value: google-client} - contains: path: spec.template.spec.containers[0].env + content: {name: OAUTH_GOOGLE_CLIENT_SECRET_FILE, value: /etc/cluster-manager/oauth-client/client-secret} + - contains: + path: spec.template.spec.volumes content: - name: OAUTH_GOOGLE_CLIENT_SECRET - valueFrom: - secretKeyRef: {name: manager-oauth, key: google-client-secret} + name: oauth-client + secret: + secretName: manager-oauth + defaultMode: 0440 + items: [{key: google-client-secret, path: client-secret}] - contains: path: spec.template.spec.containers[0].env content: {name: OAUTH_GOOGLE_REDIRECT_URL, value: https://manager.example.test/oauth/callback} + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":["JWT"],"audiences":["google-client"],"issuer":"https://accounts.google.com","jwksURI":"https://www.googleapis.com/oauth2/v3/certs","openIDProvider":true}]' - notContains: path: spec.template.spec.containers[0].env any: true content: {name: OAUTH_DEX_ISSUER_URL} + - it: reads the Google client ID from the Secret without a value + set: + oauth.provider: google + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: OAUTH_GOOGLE_CLIENT_ID + valueFrom: + secretKeyRef: {name: manager-oauth, key: google-client-id} + - it: passes public client registration when allowed set: oauth.allowPublicClientRegistration: true @@ -113,3 +159,7 @@ tests: path: spec.template.spec.containers[0].env any: true content: {name: OAUTH_ISSUER} + - notContains: + path: spec.template.spec.volumes + any: true + content: {name: oauth-client} diff --git a/helm/cluster-manager/tests/oauth_private_ip_jwks_hosts_test.yaml b/helm/cluster-manager/tests/oauth_private_ip_jwks_hosts_test.yaml deleted file mode 100644 index d2537ad..0000000 --- a/helm/cluster-manager/tests/oauth_private_ip_jwks_hosts_test.yaml +++ /dev/null @@ -1,28 +0,0 @@ -suite: JWKS hosts that may resolve to private addresses -templates: - - templates/deployment.yaml -set: - oauth.enabled: true - oauth.baseURL: https://manager.example.test - oauth.dex.issuerURL: https://dex.example.test - oauth.dex.clientID: manager - oauth.existingSecret: manager-oauth -tests: - - it: lists the JWKS hosts other than the issuer's that may resolve privately - set: - oauth.sso.allowPrivateIPJWKSHosts: - - keys.internal.example - - jwks.internal.example - asserts: - - contains: - path: spec.template.spec.containers[0].env - content: - name: OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS - value: keys.internal.example,jwks.internal.example - - it: renders no JWKS host list by default - asserts: - - notContains: - path: spec.template.spec.containers[0].env - any: true - content: - name: OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS diff --git a/helm/cluster-manager/tests/oauth_values_layout_test.yaml b/helm/cluster-manager/tests/oauth_values_layout_test.yaml new file mode 100644 index 0000000..ad78ce7 --- /dev/null +++ b/helm/cluster-manager/tests/oauth_values_layout_test.yaml @@ -0,0 +1,255 @@ +suite: OAuth settings from the shared values layout +templates: + - templates/deployment.yaml +set: + oauth: + enabled: true + authorizationServer: + issuer: https://manager.example.test + upstream: + type: dex + issuer: https://dex.example.test + client: + id: manager + secretKeyRef: {name: manager-dex, key: secret} + certificateAuthority: + secretKeyRef: {name: dex-ca, key: bundle.pem} +tests: + - it: renders the upstream from the layout + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ISSUER, value: https://manager.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_ISSUER_URL, value: https://dex.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_ID, value: manager} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CA_FILE, value: /etc/cluster-manager/idp-ca/bundle.pem} + - contains: + path: spec.template.spec.volumes + content: + name: oauth-client + secret: + secretName: manager-dex + defaultMode: 0440 + items: [{key: secret, path: client-secret}] + + - it: takes the layout's keys over the deprecated ones + set: + oauth.baseURL: https://old.example.test + oauth.provider: google + oauth.dex.issuerURL: https://old-dex.example.test + oauth.dex.clientID: old + oauth.existingSecret: old-secret + oauth.dex.caSecret.name: old-ca + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ISSUER, value: https://manager.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_PROVIDER, value: dex} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_ISSUER_URL, value: https://dex.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_ID, value: manager} + - contains: + path: spec.template.spec.volumes + content: + name: idp-ca + secret: + secretName: dex-ca + items: [{key: bundle.pem, path: bundle.pem}] + + - it: takes the deprecated keys over global.identity + set: + global.identity: {issuerUrl: https://global-dex.example.test, clientId: platform-client, existingSecret: idp} + oauth.authorizationServer.upstream: {type: "", issuer: "", client: {id: "", secretKeyRef: {name: "", key: client-secret}}, certificateAuthority: {secretKeyRef: {name: "", key: ca.crt}}} + oauth.dex.issuerURL: https://old-dex.example.test + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_ISSUER_URL, value: https://old-dex.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_ID, value: platform-client} + - contains: + path: spec.template.spec.volumes + content: + name: oauth-client + secret: + secretName: idp + defaultMode: 0440 + items: [{key: dex-client-secret, path: client-secret}] + + - it: renders the listed trusted issuers instead of the derived one, with their CAs mounted + set: + oauth.resourceServer: + trustedIssuers: + - issuer: https://dex.example.test + jwksURI: https://dex.example.test/keys + audiences: [agent-platform] + acceptedTypHeaders: [""] + openIDProvider: true + certificateAuthority: + configMapKeyRef: {name: idp-trust, key: ca.crt} + asserts: + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":[""],"audiences":["agent-platform"],"caFile":"/etc/cluster-manager/trusted-issuer-ca/0/ca.crt","issuer":"https://dex.example.test","jwksURI":"https://dex.example.test/keys","openIDProvider":true}]' + - contains: + path: spec.template.spec.volumes + content: + name: trusted-issuer-ca-0 + configMap: + name: idp-trust + items: [{key: ca.crt, path: ca.crt}] + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: {name: trusted-issuer-ca-0, mountPath: /etc/cluster-manager/trusted-issuer-ca/0, readOnly: true} + + - it: renders the resource server settings + set: + oauth.resourceServer: + resource: https://manager.example.test/mcp + additionalResources: [https://manager.example.test/admin] + authorizationServers: [https://manager.example.test] + requireResourceAccessTokens: true + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_RESOURCE, value: https://manager.example.test/mcp} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ADDITIONAL_RESOURCES, value: '[{"resource":"https://manager.example.test/admin"}]'} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_AUTHORIZATION_SERVERS, value: https://manager.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_REQUIRE_RESOURCE_ACCESS_TOKENS, value: "true"} + + - it: renders the registration settings + set: + oauth.authorizationServer.clientIDMetadataDocuments.enabled: false + oauth.authorizationServer.dynamicClientRegistration: + initialAccessToken: + secretKeyRef: {name: registration, key: token} + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS, value: "false"} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_INITIAL_ACCESS_TOKEN_FILE, value: /etc/cluster-manager/oauth-registration/token} + - contains: + path: spec.template.spec.volumes + content: + name: oauth-registration + secret: + secretName: registration + defaultMode: 0440 + items: [{key: token, path: token}] + - equal: + path: spec.template.spec.securityContext.fsGroup + value: 1000 + - equal: + path: spec.template.spec.containers[0].securityContext.runAsNonRoot + value: true + - equal: + path: spec.template.spec.containers[0].securityContext.allowPrivilegeEscalation + value: false + - equal: + path: spec.template.spec.containers[0].securityContext.capabilities.drop + value: [ALL] + - equal: + path: spec.template.spec.containers[0].securityContext.seccompProfile.type + value: RuntimeDefault + + - it: turns dynamic client registration off + set: + oauth.authorizationServer.dynamicClientRegistration.enabled: false + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ENABLE_DYNAMIC_CLIENT_REGISTRATION, value: "false"} + + - it: runs as a resource server only with the authorization server off + set: + oauth.authorizationServer.enabled: false + oauth.trustedAudiences: [agent-platform] + oauth.resourceServer.authorizationServers: [https://dex.example.test] + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_AUTHORIZATION_SERVERS, value: https://dex.example.test} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ENABLE_AUTHORIZATION_SERVER, value: "false"} + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: OAUTH_PROVIDER} + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: OAUTH_DEX_CLIENT_ID} + - notContains: + path: spec.template.spec.volumes + any: true + content: {name: oauth-client} + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.test"],"audiences":["agent-platform"],"caFile":"/etc/cluster-manager/idp-ca/bundle.pem","issuer":"https://dex.example.test","jwksURI":"https://dex.example.test/keys","openIDProvider":true}]' + + - it: refuses a resource server only without an advertised authorization server + set: + oauth.authorizationServer.enabled: false + asserts: + - failedTemplate: + errorPattern: needs oauth.resourceServer.authorizationServers + + - it: refuses a resource server only without a trusted issuer + set: + oauth.authorizationServer.enabled: false + oauth.authorizationServer.upstream.issuer: "" + oauth.resourceServer.authorizationServers: [https://dex.example.test] + asserts: + - failedTemplate: + errorPattern: accepts only trusted issuer tokens + + - it: refuses a trusted issuer entry with an unknown key + set: + oauth.resourceServer: + trustedIssuers: + - issuer: https://dex.example.test + jwksURI: https://dex.example.test/keys + audiences: [agent-platform] + jwksUrl: https://typo.example.test + asserts: + - failedTemplate: {} + + - it: takes the provider type and the Kubernetes audiences from global.identity + set: + oauth.authorizationServer.upstream.type: "" + oauth.authorizationServer.upstream.client.id: "" + global.identity: {type: dex, clientId: platform-client, kubernetes: {audiences: [dex-k8s-authenticator]}} + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_PROVIDER, value: dex} + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.test"],"audiences":["platform-client","dex-k8s-authenticator"],"caFile":"/etc/cluster-manager/idp-ca/bundle.pem","issuer":"https://dex.example.test","jwksURI":"https://dex.example.test/keys","openIDProvider":true}]' + + - it: trusts the upstream client it signs in with by default + asserts: + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.test"],"audiences":["manager"],"caFile":"/etc/cluster-manager/idp-ca/bundle.pem","issuer":"https://dex.example.test","jwksURI":"https://dex.example.test/keys","openIDProvider":true}]' diff --git a/helm/cluster-manager/values.schema.json b/helm/cluster-manager/values.schema.json index 501422a..7a37281 100644 --- a/helm/cluster-manager/values.schema.json +++ b/helm/cluster-manager/values.schema.json @@ -315,11 +315,138 @@ "properties": { "allowPublicClientRegistration": { "type": "boolean", - "description": "Accept unauthenticated dynamic client registration (labs only)." + "description": "Deprecated, removed in a later release: accept dynamic client registration without an initial access token, public clients included (labs only). MCP clients register with client ID metadata documents." + }, + "authorizationServer": { + "type": "object", + "additionalProperties": false, + "properties": { + "clientIDMetadataDocuments": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean", + "description": "Accept URL client IDs (client ID metadata documents) (`OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS`)." + } + } + }, + "dynamicClientRegistration": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean", + "description": "Serve RFC 7591 dynamic client registration (`OAUTH_ENABLE_DYNAMIC_CLIENT_REGISTRATION`). MCP 2026-07-28 deprecates it in favour of client ID metadata documents; it stays on for clients that still register this way." + }, + "initialAccessToken": { + "type": "object", + "additionalProperties": false, + "properties": { + "secretKeyRef": { + "type": "object", + "description": "Secret key with the RFC 7591 initial access token a registration must present (mcp-oauth reads it from `OAUTH_INITIAL_ACCESS_TOKEN_FILE`).", + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "name": { + "type": "string" + } + } + } + } + } + } + }, + "enabled": { + "type": "boolean", + "description": "Run the authorization server. Off makes cluster-manager a resource server only (`OAUTH_ENABLE_AUTHORIZATION_SERVER=false`)." + }, + "issuer": { + "type": "string", + "description": "Public base URL of this server, the issuer of its tokens and metadata (`OAUTH_ISSUER`; https, or http on loopback). Empty uses the deprecated `oauth.baseURL`, else `https://.`." + }, + "storage": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Token storage (`OAUTH_STORAGE_BACKEND`). Memory loses every session on restart and needs one replica.", + "enum": [ + "memory" + ] + } + } + }, + "upstream": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "The OpenID Provider people sign in with: `dex` or `google` (`OAUTH_PROVIDER`). Empty uses the deprecated `oauth.provider`, else `dex`.", + "enum": [ + "", + "dex", + "google" + ] + }, + "certificateAuthority": { + "type": "object", + "additionalProperties": false, + "properties": { + "secretKeyRef": { + "type": "object", + "description": "Secret key with the CA of a Dex that serves a private certificate (`OAUTH_DEX_CA_FILE`). Empty name uses the deprecated `oauth.dex.caSecret`, else `global.identity.ca`.", + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "name": { + "type": "string" + } + } + } + } + }, + "client": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "description": "OAuth client ID at the provider. Empty uses the deprecated `oauth.dex.clientID` or `oauth.google.clientID`, else `global.identity.clientId` (dex)." + }, + "secretKeyRef": { + "type": "object", + "description": "Secret key with the client secret, mounted as a file. Empty name uses the deprecated `oauth.existingSecret`, else `global.identity.existingSecret`, else a Secret from the deprecated inline client secret.", + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "name": { + "type": "string" + } + } + } + } + }, + "issuer": { + "type": "string", + "description": "Dex issuer URL. Empty uses the deprecated `oauth.dex.issuerURL`, else `global.identity.issuerUrl`." + } + } + } + } }, "baseURL": { "type": "string", - "description": "Public base URL of this server: the issuer of its own OAuth metadata (https, or http on loopback). Empty derives `https://.` when `global.domain` is set." + "description": "Deprecated: use `authorizationServer.issuer`." }, "dex": { "type": "object", @@ -331,7 +458,7 @@ }, "caSecret": { "type": "object", - "description": "Secret with the CA of a Dex that serves a private certificate; mounted and passed as `OAUTH_DEX_CA_FILE`. Empty name falls back to `global.identity.ca.secretName` / `global.identity.ca.key`.", + "description": "Deprecated: use `authorizationServer.upstream.certificateAuthority`.", "additionalProperties": false, "properties": { "key": { @@ -344,15 +471,15 @@ }, "clientID": { "type": "string", - "description": "Dex OAuth client ID. Empty falls back to `global.identity.clientId`." + "description": "Deprecated: use `authorizationServer.upstream.client.id`." }, "clientSecret": { "type": "string", - "description": "Dex OAuth client secret (prefer `oauth.existingSecret`)." + "description": "Deprecated: use `authorizationServer.upstream.client.secretKeyRef`." }, "issuerURL": { "type": "string", - "description": "Dex issuer URL. Empty falls back to `global.identity.issuerUrl`." + "description": "Deprecated: use `authorizationServer.upstream.issuer`." } } }, @@ -368,11 +495,11 @@ }, "enabled": { "type": "boolean", - "description": "Make cluster-manager an OAuth 2.1 resource server (mcp-oauth): the MCP endpoint requires a bearer token the platform identity provider issued, and every call carries the caller's identity. On the Agent Platform muster forwards the session's IdP id_token to this server (MCPServer `auth.forwardToken`, rendered below) and the portal's calls arrive the same way through muster; both are validated against the IdP's JWKS when their audience is in `trustedAudiences`. Off: anonymous, acting as the ServiceAccount — only for a server nothing but a trusted proxy can reach." + "description": "Make cluster-manager an OAuth 2.1 resource server (mcp-oauth): the MCP endpoint requires a bearer token, and every call carries the caller's identity. On the Agent Platform muster forwards the session's IdP ID token to this server (MCPServer `auth.forwardToken`, rendered below) and the portal's calls arrive the same way through muster; both are accepted from the provider people sign in with (`resourceServer.trustedIssuers`). Off: anonymous, acting as the ServiceAccount, only for a server nothing but a trusted proxy can reach." }, "existingSecret": { "type": "string", - "description": "Existing Secret with the provider credentials: `dex-client-secret` (dex) or `google-client-secret` (+ optional `google-client-id`) (google). Empty falls back to `global.identity.existingSecret`, whose `dex-client-secret` is the platform client's; without that, the chart renders a Secret from the values above." + "description": "Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. Existing Secret with `dex-client-secret` (dex) or `google-client-secret` (+ optional `google-client-id`) (google)." }, "google": { "type": "object", @@ -380,17 +507,145 @@ "properties": { "clientID": { "type": "string", - "description": "Google OAuth client ID (not secret; may also come from the Secret key `google-client-id` when empty)." + "description": "Deprecated: use `authorizationServer.upstream.client.id`. Empty reads the Secret key `google-client-id`." }, "clientSecret": { "type": "string", - "description": "Google OAuth client secret (prefer `oauth.existingSecret`)." + "description": "Deprecated: use `authorizationServer.upstream.client.secretKeyRef`." } } }, "provider": { "type": "string", - "description": "Identity provider: `dex` or `google`." + "description": "Deprecated: use `authorizationServer.upstream.type`.", + "enum": [ + "", + "dex", + "google" + ] + }, + "resourceServer": { + "type": "object", + "additionalProperties": false, + "properties": { + "additionalResources": { + "type": "array", + "description": "Further protected resources on the same origin, each by its full URL (`OAUTH_ADDITIONAL_RESOURCES`). The MCP endpoint is always a protected resource.", + "items": { + "type": "string" + } + }, + "authorizationServers": { + "type": "array", + "description": "Issuer identifiers the resource metadata advertises (`OAUTH_AUTHORIZATION_SERVERS`, RFC 9728 `authorization_servers`): this server's issuer or a trusted issuer. Empty advertises this server's issuer; required with `authorizationServer.enabled` false, since MCP clients find the authorization server here.", + "items": { + "type": "string" + } + }, + "requireResourceAccessTokens": { + "type": "boolean", + "description": "Accept only tokens whose audience names this server's resource (`OAUTH_REQUIRE_RESOURCE_ACCESS_TOKENS`), as MCP requires. Off while the platform forwards ID tokens (giantswarm/giantswarm#39102)." + }, + "resource": { + "type": "string", + "description": "The main protected resource, by its full URL (`OAUTH_RESOURCE`). Empty uses the issuer." + }, + "trustedIssuers": { + "type": "array", + "description": "The issuers whose JWTs are accepted (`OAUTH_TRUSTED_ISSUERS`). A trust anchor: set it only from the release's own values or a GitOps-managed ConfigMap that only installation administrators write. Each entry: `issuer`, `jwksURI` and `audiences` (required), `subjectClaim` (`sub` or `email`), `acceptedTypHeaders`, `allowedClaims`, `allowPrivateIPJWKSHosts`, `openIDProvider` (true for the provider people sign in with, whose bearers are their ID tokens), and `certificateAuthority` with a `secretKeyRef` or `configMapKeyRef` (`name`, `key`). Empty trusts the provider people sign in with (`authorizationServer.upstream`) as `openIDProvider`: its ID tokens are accepted as bearer tokens, a deviation from MCP's audience rule until per-backend tokens (ID-JAG, giantswarm/giantswarm#39102). They are accepted for the client people sign in with (`authorizationServer.upstream.client.id`, or the deprecated `oauth.trustedAudiences`) and `muster.mcpServer.auth.requiredAudiences`, in that order and without duplicates.", + "items": { + "type": "object", + "required": [ + "issuer", + "jwksURI", + "audiences" + ], + "additionalProperties": false, + "properties": { + "acceptedTypHeaders": { + "type": "array", + "items": { + "type": "string" + } + }, + "allowPrivateIPJWKSHosts": { + "type": "array", + "items": { + "type": "string" + } + }, + "allowedClaims": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "audiences": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1 + }, + "certificateAuthority": { + "type": "object", + "additionalProperties": false, + "properties": { + "configMapKeyRef": { + "type": "object", + "required": [ + "name", + "key" + ], + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "secretKeyRef": { + "type": "object", + "required": [ + "name", + "key" + ], + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "name": { + "type": "string" + } + } + } + } + }, + "issuer": { + "type": "string" + }, + "jwksURI": { + "type": "string" + }, + "openIDProvider": { + "type": "boolean" + }, + "subjectClaim": { + "type": "string", + "enum": [ + "", + "sub", + "email" + ] + } + } + } + } + } }, "sso": { "type": "object", @@ -398,20 +653,23 @@ "properties": { "allowPrivateIPJWKSHosts": { "type": "array", - "description": "Hosts, other than the issuer's own, whose JWKS may resolve to an RFC 1918 or RFC 4193 address: a jwks_uri the IdP's discovery document puts on another host. Exact hostnames, no port. Loopback and link-local stay refused.", + "description": "Deprecated: list the provider in `resourceServer.trustedIssuers` with these `allowPrivateIPJWKSHosts`. Hosts, other than the issuer's own, whose JWKS may resolve to an RFC 1918 or RFC 4193 address.", "items": { "type": "string" } }, "allowPrivateIPs": { "type": "boolean", - "description": "Deprecated, no effect, not passed to the server: the issuer host's JWKS endpoint may resolve to a private address without it; list any other JWKS host in allowPrivateIPJWKSHosts. Remove it from your values; the key goes away in a later release." + "description": "Deprecated, no effect, not passed to the server: the issuer host of the configured provider may resolve to a private address for its JWKS without it; list any other JWKS host in allowPrivateIPJWKSHosts. Remove it from your values; the key goes away in a later release." } } }, "trustedAudiences": { "type": "array", - "description": "OAuth client IDs whose IdP id_tokens are accepted as bearer tokens (SSO token forwarding). Empty falls back to `[global.identity.clientId]`, the platform client MCP clients and the muster CLI log in with. The server trusts the union of this list and `muster.mcpServer.auth.requiredAudiences` (in that order, without duplicates): every token muster forwards carries the required audiences by construction and they are what the kube-apiserver trusts, so a portal session — whose id_token carries them but not the platform client — is accepted without listing its client here." + "description": "Deprecated: list the provider in `resourceServer.trustedIssuers` with these `audiences`. The OAuth client IDs whose ID tokens of the provider people sign in with are accepted.", + "items": { + "type": "string" + } } } }, diff --git a/helm/cluster-manager/values.yaml b/helm/cluster-manager/values.yaml index 09b35b9..d2dcfd4 100644 --- a/helm/cluster-manager/values.yaml +++ b/helm/cluster-manager/values.yaml @@ -126,71 +126,156 @@ mcp: oauth: # -- Make cluster-manager an OAuth 2.1 resource server (mcp-oauth): the MCP - # endpoint requires a bearer token the platform identity provider issued, - # and every call carries the caller's identity. On the Agent Platform muster - # forwards the session's IdP id_token to this server (MCPServer - # `auth.forwardToken`, rendered below) and the portal's calls arrive the - # same way through muster; both are validated against the IdP's JWKS when - # their audience is in `trustedAudiences`. Off: anonymous, acting as the - # ServiceAccount — only for a server nothing but a trusted proxy can reach. + # endpoint requires a bearer token, and every call carries the caller's + # identity. On the Agent Platform muster forwards the session's IdP ID token + # to this server (MCPServer `auth.forwardToken`, rendered below) and the + # portal's calls arrive the same way through muster; both are accepted from + # the provider people sign in with (`resourceServer.trustedIssuers`). Off: + # anonymous, acting as the ServiceAccount, only for a server nothing but a + # trusted proxy can reach. enabled: false - # -- Public base URL of this server: the issuer of its own OAuth metadata - # (https, or http on loopback). Empty derives - # `https://.` when `global.domain` is set. + # The protected resource: which tokens are accepted (mcp-oauth's values + # layout for MCP servers). + resourceServer: + # -- The main protected resource, by its full URL (`OAUTH_RESOURCE`). + # Empty uses the issuer. + resource: "" + # -- Further protected resources on the same origin, each by its full URL + # (`OAUTH_ADDITIONAL_RESOURCES`). The MCP endpoint is always a protected + # resource. + additionalResources: [] # @schema item: string + # -- Issuer identifiers the resource metadata advertises + # (`OAUTH_AUTHORIZATION_SERVERS`, RFC 9728 `authorization_servers`): this + # server's issuer or a trusted issuer. Empty advertises this server's + # issuer; required with `authorizationServer.enabled` false, since MCP + # clients find the authorization server here. + authorizationServers: [] # @schema item: string + # -- The issuers whose JWTs are accepted (`OAUTH_TRUSTED_ISSUERS`). A + # trust anchor: set it only from the release's own values or a + # GitOps-managed ConfigMap that only installation administrators write. + # Each entry: `issuer`, `jwksURI` and `audiences` (required), + # `subjectClaim` (`sub` or `email`), `acceptedTypHeaders`, + # `allowedClaims`, `allowPrivateIPJWKSHosts`, `openIDProvider` (true for + # the provider people sign in with, whose bearers are their ID tokens), + # and `certificateAuthority` with a `secretKeyRef` or `configMapKeyRef` + # (`name`, `key`). Empty trusts the provider people sign in with + # (`authorizationServer.upstream`) as `openIDProvider`: its ID tokens are + # accepted as bearer tokens, a deviation from MCP's audience rule until + # per-backend tokens (ID-JAG, giantswarm/giantswarm#39102). They are + # accepted for the client people sign in with + # (`authorizationServer.upstream.client.id`, or the deprecated + # `oauth.trustedAudiences`) and `muster.mcpServer.auth.requiredAudiences`, + # in that order and without duplicates. + trustedIssuers: [] # @schema item: object ; itemRequired: [issuer, jwksURI, audiences] ; itemProperties: {issuer: {type: string}, jwksURI: {type: string}, audiences: {type: array, minItems: 1, items: {type: string}}, subjectClaim: {type: string, enum: ['', sub, email]}, acceptedTypHeaders: {type: array, items: {type: string}}, allowedClaims: {type: object, additionalProperties: {type: string}}, allowPrivateIPJWKSHosts: {type: array, items: {type: string}}, openIDProvider: {type: boolean}, certificateAuthority: {type: object, additionalProperties: false, properties: {secretKeyRef: {type: object, additionalProperties: false, required: [name, key], properties: {name: {type: string}, key: {type: string}}}, configMapKeyRef: {type: object, additionalProperties: false, required: [name, key], properties: {name: {type: string}, key: {type: string}}}}}} + # -- Accept only tokens whose audience names this server's resource + # (`OAUTH_REQUIRE_RESOURCE_ACCESS_TOKENS`), as MCP requires. Off while the + # platform forwards ID tokens (giantswarm/giantswarm#39102). + requireResourceAccessTokens: false + # This server's own authorization server: people sign in through the + # upstream provider and MCP clients get tokens from this server. + authorizationServer: + # -- Run the authorization server. Off makes cluster-manager a resource + # server only (`OAUTH_ENABLE_AUTHORIZATION_SERVER=false`). + enabled: true + # -- Public base URL of this server, the issuer of its tokens and metadata + # (`OAUTH_ISSUER`; https, or http on loopback). Empty uses the deprecated + # `oauth.baseURL`, else `https://.`. + issuer: "" + upstream: + # -- The OpenID Provider people sign in with: `dex` or `google` + # (`OAUTH_PROVIDER`). Empty uses the deprecated `oauth.provider`, else + # `dex`. + type: "" # @schema enum: ["", dex, google] + # -- Dex issuer URL. Empty uses the deprecated `oauth.dex.issuerURL`, + # else `global.identity.issuerUrl`. + issuer: "" + client: + # -- OAuth client ID at the provider. Empty uses the deprecated + # `oauth.dex.clientID` or `oauth.google.clientID`, else + # `global.identity.clientId` (dex). + id: "" + # -- Secret key with the client secret, mounted as a file. Empty name + # uses the deprecated `oauth.existingSecret`, else + # `global.identity.existingSecret`, else a Secret from the deprecated + # inline client secret. + secretKeyRef: + name: "" + key: client-secret + certificateAuthority: + # -- Secret key with the CA of a Dex that serves a private + # certificate (`OAUTH_DEX_CA_FILE`). Empty name uses the deprecated + # `oauth.dex.caSecret`, else `global.identity.ca`. + secretKeyRef: + name: "" + key: ca.crt + dynamicClientRegistration: + # -- Serve RFC 7591 dynamic client registration + # (`OAUTH_ENABLE_DYNAMIC_CLIENT_REGISTRATION`). MCP 2026-07-28 + # deprecates it in favour of client ID metadata documents; it stays on + # for clients that still register this way. + enabled: true + initialAccessToken: + # -- Secret key with the RFC 7591 initial access token a + # registration must present (mcp-oauth reads it from + # `OAUTH_INITIAL_ACCESS_TOKEN_FILE`). + secretKeyRef: + name: "" + key: token + clientIDMetadataDocuments: + # -- Accept URL client IDs (client ID metadata documents) + # (`OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS`). + enabled: true + storage: + # -- Token storage (`OAUTH_STORAGE_BACKEND`). Memory loses every + # session on restart and needs one replica. + type: memory # @schema enum: [memory] + # -- Deprecated: use `authorizationServer.issuer`. baseURL: "" - # -- Identity provider: `dex` or `google`. - provider: dex + # -- Deprecated: use `authorizationServer.upstream.type`. + provider: "" # @schema enum: ["", dex, google] dex: - # -- Dex issuer URL. Empty falls back to `global.identity.issuerUrl`. + # -- Deprecated: use `authorizationServer.upstream.issuer`. issuerURL: "" - # -- Dex OAuth client ID. Empty falls back to `global.identity.clientId`. + # -- Deprecated: use `authorizationServer.upstream.client.id`. clientID: "" - # -- Dex OAuth client secret (prefer `oauth.existingSecret`). + # -- Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. clientSecret: "" # -- Deprecated, no effect, not passed to the server: the Dex client # reaches private addresses and follows HTTP_PROXY, HTTPS_PROXY and # NO_PROXY without it. Remove it from your values; the key goes away in a # later release. allowPrivateURLs: false - # -- Secret with the CA of a Dex that serves a private certificate; - # mounted and passed as `OAUTH_DEX_CA_FILE`. Empty name falls back to - # `global.identity.ca.secretName` / `global.identity.ca.key`. + # -- Deprecated: use `authorizationServer.upstream.certificateAuthority`. caSecret: name: "" key: ca.crt google: - # -- Google OAuth client ID (not secret; may also come from the Secret key - # `google-client-id` when empty). + # -- Deprecated: use `authorizationServer.upstream.client.id`. Empty + # reads the Secret key `google-client-id`. clientID: "" - # -- Google OAuth client secret (prefer `oauth.existingSecret`). + # -- Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. clientSecret: "" - # -- Existing Secret with the provider credentials: `dex-client-secret` - # (dex) or `google-client-secret` (+ optional `google-client-id`) (google). - # Empty falls back to `global.identity.existingSecret`, whose - # `dex-client-secret` is the platform client's; without that, the chart - # renders a Secret from the values above. + # -- Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. + # Existing Secret with `dex-client-secret` (dex) or `google-client-secret` + # (+ optional `google-client-id`) (google). existingSecret: "" - # -- OAuth client IDs whose IdP id_tokens are accepted as bearer tokens (SSO - # token forwarding). Empty falls back to `[global.identity.clientId]`, the - # platform client MCP clients and the muster CLI log in with. The server - # trusts the union of this list and `muster.mcpServer.auth.requiredAudiences` - # (in that order, without duplicates): every token muster forwards carries - # the required audiences by construction and they are what the - # kube-apiserver trusts, so a portal session — whose id_token carries them - # but not the platform client — is accepted without listing its client here. - trustedAudiences: [] + # -- Deprecated: list the provider in `resourceServer.trustedIssuers` with + # these `audiences`. The OAuth client IDs whose ID tokens of the provider + # people sign in with are accepted. + trustedAudiences: [] # @schema item: string sso: - # -- Deprecated, no effect, not passed to the server: the issuer host's - # JWKS endpoint may resolve to a private address without it; list any - # other JWKS host in allowPrivateIPJWKSHosts. Remove it from your values; - # the key goes away in a later release. + # -- Deprecated, no effect, not passed to the server: the issuer host of + # the configured provider may resolve to a private address for its JWKS + # without it; list any other JWKS host in allowPrivateIPJWKSHosts. Remove + # it from your values; the key goes away in a later release. allowPrivateIPs: false - # -- Hosts, other than the issuer's own, whose JWKS may resolve to an - # RFC 1918 or RFC 4193 address: a jwks_uri the IdP's discovery document puts - # on another host. Exact hostnames, no port. Loopback and link-local stay - # refused. + # -- Deprecated: list the provider in `resourceServer.trustedIssuers` + # with these `allowPrivateIPJWKSHosts`. Hosts, other than the issuer's + # own, whose JWKS may resolve to an RFC 1918 or RFC 4193 address. allowPrivateIPJWKSHosts: [] # @schema item: string - # -- Accept unauthenticated dynamic client registration (labs only). + # -- Deprecated, removed in a later release: accept dynamic client + # registration without an initial access token, public clients included + # (labs only). MCP clients register with client ID metadata documents. allowPublicClientRegistration: false downstream: # -- Call the Kubernetes API as the caller: everything a request does diff --git a/internal/server/oauth_realchain_test.go b/internal/server/oauth_realchain_test.go index 7321a6b..876dfc9 100644 --- a/internal/server/oauth_realchain_test.go +++ b/internal/server/oauth_realchain_test.go @@ -289,3 +289,62 @@ func TestJWKSOnAnotherPrivateHost(t *testing.T) { require.Equal(t, http.StatusNoContent, code) require.Equal(t, "admin@lab.local", caller) } + +// trustedIssuerConfig declares the IdP as the OpenID Provider people sign in +// with (an OAUTH_TRUSTED_ISSUERS entry with openIDProvider) instead of +// trusting audiences of forwarded ID tokens, as the chart renders it. +func (p *privateIdP) trustedIssuerConfig(t *testing.T, downstream bool, jwksHosts ...string) OAuthConfig { + t.Helper() + environment := dexEnvironment(p.issuer, p.caFile) + delete(environment, "OAUTH_TRUSTED_AUDIENCES") + entry, err := json.Marshal([]map[string]any{{ + "issuer": p.issuer, + "jwksURI": p.issuer + "/keys", + "audiences": []string{"agent-platform", "kubernetes"}, + "acceptedTypHeaders": []string{"", "JWT"}, + "caFile": p.caFile, + "allowPrivateIPJWKSHosts": jwksHosts, + "openIDProvider": true, + }}) + require.NoError(t, err) + environment["OAUTH_TRUSTED_ISSUERS"] = string(entry) + return OAuthConfig{Settings: oauthSettings(t, environment), DownstreamOAuth: downstream} +} + +// TestOpenIDProviderTrustedIssuer pins that the IdP as a trusted issuer +// marked openIDProvider admits what audience trust admits: the same caller, +// and with downstream OAuth the bearer itself as the token presented to the +// Kubernetes API. +func TestOpenIDProviderTrustedIssuer(t *testing.T) { + idp := newPrivateIdP(t, "") + token := idp.idToken(t, []string{"kubernetes"}) + + code, _ := callThroughChain(t, idp.trustedIssuerConfig(t, false), token) + require.Equal(t, http.StatusUnauthorized, code, "a private JWKS host must be listed") + + code, caller := callThroughChain(t, idp.trustedIssuerConfig(t, false, privateIssuerHost), token) + require.Equal(t, http.StatusNoContent, code) + require.Equal(t, "admin@lab.local", caller) + + code, _ = callThroughChain(t, idp.trustedIssuerConfig(t, false, privateIssuerHost), idp.idToken(t, []string{"someone-else"})) + require.Equal(t, http.StatusUnauthorized, code, "an untrusted audience is refused") + + o, err := newOAuth(idp.trustedIssuerConfig(t, true, privateIssuerHost), "/mcp", slog.New(slog.NewTextHandler(io.Discard, nil))) + require.NoError(t, err) + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), 5*time.Second) + defer cancel() + o.shutdown(ctx) + }) + var presented string + h := o.protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + presented, _ = identity.TokenFromContext(r.Context()) + w.WriteHeader(http.StatusNoContent) + })) + req := httptest.NewRequest(http.MethodPost, "/mcp", nil) + req.Header.Set("Authorization", "Bearer "+token) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + require.Equal(t, http.StatusNoContent, rec.Code) + require.Equal(t, token, presented, "the forwarded ID token is what the Kubernetes API sees") +} From 956d9673eaaa93081827941ce83d5d9c4cc8e230 Mon Sep 17 00:00:00 2001 From: QuentinBisson Date: Fri, 27 Nov 2026 09:35:12 +0100 Subject: [PATCH 3/5] feat: log the user from mcp-oauth's UserInfo as user.* and drop the identity package The request's user is mcp-oauth's validated providers.UserInfo: the authenticated-request debug line names it as user.issuer, user.subject and user.actor.* (UserInfo.LogValue, no profile data) with token_source, instead of caller and source, and create_cluster binds the creator from UserInfo's email. The ID token presented to Kubernetes under --downstream-oauth lives in internal/idtoken; the GitHub App user access token commit mode opens the pull request with is tools.GitHubUserAccessToken. --- cmd/serve.go | 4 +- internal/identity/identity.go | 156 ------------------------ internal/identity/identity_test.go | 56 --------- internal/idtoken/idtoken.go | 25 ++++ internal/idtoken/idtoken_test.go | 18 +++ internal/kube/client.go | 6 +- internal/kube/client_test.go | 10 +- internal/server/github_exchange.go | 8 +- internal/server/github_exchange_test.go | 14 +-- internal/server/oauth.go | 77 ++++++------ internal/server/oauth_realchain_test.go | 9 +- internal/server/oauth_test.go | 120 +++++++++++------- internal/tools/cluster_create_test.go | 11 +- internal/tools/cluster_rbac.go | 10 +- internal/tools/commit.go | 26 ++-- internal/tools/commit_test.go | 16 ++- internal/tools/nodepool_commit.go | 3 +- 17 files changed, 217 insertions(+), 352 deletions(-) delete mode 100644 internal/identity/identity.go delete mode 100644 internal/identity/identity_test.go create mode 100644 internal/idtoken/idtoken.go create mode 100644 internal/idtoken/idtoken_test.go diff --git a/cmd/serve.go b/cmd/serve.go index 4ac9372..9f6696f 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -120,7 +120,7 @@ environment variable named next to it; flags win over the environment.`, f.BoolVar(&o.ssoAllowPrivateIPs, "sso-allow-private-ips", envBool("SSO_ALLOW_PRIVATE_IPS", false), "Deprecated, no effect: the issuer host's JWKS endpoint may resolve to a private address without it; list any other JWKS host in --sso-allow-private-ip-jwks-hosts (SSO_ALLOW_PRIVATE_IPS)") f.StringVar(&o.ssoAllowPrivateIPJWKSHosts, "sso-allow-private-ip-jwks-hosts", envOr("SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS", ""), "Deprecated: set OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS (SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS)") f.BoolVar(&o.allowPublicClientRegistration, "allow-public-client-registration", envBool("CLUSTER_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION", false), "Deprecated: set OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION (CLUSTER_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION)") - f.BoolVar(&o.downstreamOAuth, "downstream-oauth", envBool("CLUSTER_MANAGER_DOWNSTREAM_OAUTH", false), "Call the Kubernetes API as the caller, with the caller's IdP token, for everything a request does — the ServiceAccount holds no permissions (the chart renders none). Needs --enable-oauth and an apiserver that trusts the IdP (CLUSTER_MANAGER_DOWNSTREAM_OAUTH)") + f.BoolVar(&o.downstreamOAuth, "downstream-oauth", envBool("CLUSTER_MANAGER_DOWNSTREAM_OAUTH", false), "Call the Kubernetes API as the caller, with the caller's ID token, for everything a request does — the ServiceAccount holds no permissions (the chart renders none). Needs --enable-oauth and an apiserver that trusts the IdP (CLUSTER_MANAGER_DOWNSTREAM_OAUTH)") f.StringVar(&o.githubAPIURL, "github-api-url", envOr("CLUSTER_MANAGER_GITHUB_API_URL", server.DefaultGitHubAPIURL), "GitHub REST API base URL for GET /user on the fetched grant and commit mode's pull request (CLUSTER_MANAGER_GITHUB_API_URL)") f.StringVar(&o.githubExchangeEndpoint, "github-token-exchange-endpoint", envOr("CLUSTER_MANAGER_GITHUB_TOKEN_EXCHANGE_ENDPOINT", ""), "RFC 8693 endpoint (muster's broker) that releases the person's GitHub App user grant for commit mode, in place of the App-pinned registration (CLUSTER_MANAGER_GITHUB_TOKEN_EXCHANGE_ENDPOINT)") f.StringVar(&o.githubExchangeClient, "github-token-exchange-client-id", envOr("CLUSTER_MANAGER_GITHUB_TOKEN_EXCHANGE_CLIENT_ID", ""), "Confidential token exchange client ID; wins over --github-token-exchange-client-id-file (CLUSTER_MANAGER_GITHUB_TOKEN_EXCHANGE_CLIENT_ID)") @@ -353,7 +353,7 @@ func (o *serveOptions) gitHubExchangeConfig() server.GitHubExchangeConfig { } // validateGitHubExchange checks the token exchange options: the exchange's -// subject is the caller's IdP token, so it needs Dex and downstream OAuth. +// subject is the caller's ID token, so it needs Dex and downstream OAuth. func validateGitHubExchange(o *serveOptions, dex bool) error { if o.githubExchangeEndpoint == "" { if o.githubExchangeClient != "" || o.githubExchangeClientFile != "" || o.githubExchangeSecretFile != "" || o.githubExchangeAudience != "" || o.githubExchangeCAFile != "" { diff --git a/internal/identity/identity.go b/internal/identity/identity.go deleted file mode 100644 index d99b3b0..0000000 --- a/internal/identity/identity.go +++ /dev/null @@ -1,156 +0,0 @@ -// Package identity carries the authenticated caller through a request: who -// the OAuth layer validated (subject, email, groups) and, when the server is -// configured to act on the caller's behalf towards the Kubernetes API, the -// caller's own IdP token. Background work that runs without a caller (the -// wiring reconciler, a job that outlives its request's token) sees no identity -// and acts as the ServiceAccount. -package identity - -import ( - "context" - "encoding/base64" - "encoding/json" - "log/slog" - "strings" - "time" -) - -// Source says how the caller was authenticated. -type Source string - -const ( - // SourceSSO is an IdP id_token forwarded by a trusted aggregator (muster) - // or sent by the portal through the gateway, validated against the IdP's - // JWKS. - SourceSSO Source = "sso" - // SourceOAuth is an access token issued by this server's own OAuth 2.1 - // flow (a client that authenticated directly, e.g. mcp-debug). - SourceOAuth Source = "oauth" -) - -// Identity is the authenticated caller. -type Identity struct { - // Subject is the IdP's stable user id (the `sub` claim). - Subject string - // Email is the caller's email when the IdP provided one. - Email string - // Name is the display name when the IdP provided one. - Name string - // Groups are the IdP group claims (Dex `groups`; empty for Google). - Groups []string - // Source is how the token was validated. - Source Source -} - -// String is the caller as logged and recorded on jobs: the email, else the -// subject. -func (id *Identity) String() string { - if id == nil { - return "" - } - if id.Email != "" { - return id.Email - } - return id.Subject -} - -type ctxKey int - -const ( - identityKey ctxKey = iota - tokenKey - gitHubKey -) - -// ContextWith returns ctx carrying id. -func ContextWith(ctx context.Context, id *Identity) context.Context { - if id == nil { - return ctx - } - return context.WithValue(ctx, identityKey, id) -} - -// FromContext returns the caller, if any. -func FromContext(ctx context.Context) (*Identity, bool) { - id, ok := ctx.Value(identityKey).(*Identity) - return id, ok && id != nil -} - -// Caller is the caller's String(), or "" without one. -func Caller(ctx context.Context) string { - id, _ := FromContext(ctx) - return id.String() -} - -// LogAttr is the structured-log attribute every mutation carries: the caller, -// or the ServiceAccount marker when the operation runs without one. -func LogAttr(ctx context.Context) slog.Attr { - if c := Caller(ctx); c != "" { - return slog.String("caller", c) - } - return slog.String("caller", "service-account") -} - -// ContextWithToken returns ctx carrying the caller's IdP token for downstream -// Kubernetes API calls. Only set when the server runs with downstream OAuth on. -func ContextWithToken(ctx context.Context, token string) context.Context { - if token == "" { - return ctx - } - return context.WithValue(ctx, tokenKey, token) -} - -// TokenFromContext returns the caller's IdP token, if any. -func TokenFromContext(ctx context.Context) (string, bool) { - t, ok := ctx.Value(tokenKey).(string) - return t, ok && t != "" -} - -// TokenExpiry reads the `exp` claim of a JWT without verifying it — the token -// was validated when the request came in; this only decides whether a -// background continuation may still present it. Zero when the token is not a -// JWT or carries no exp. -func TokenExpiry(token string) time.Time { - parts := strings.Split(token, ".") - if len(parts) != 3 { - return time.Time{} - } - payload, err := base64.RawURLEncoding.DecodeString(parts[1]) - if err != nil { - return time.Time{} - } - var claims struct { - Exp json.Number `json:"exp"` - } - if err := json.Unmarshal(payload, &claims); err != nil { - return time.Time{} - } - exp, err := claims.Exp.Int64() - if err != nil || exp <= 0 { - return time.Time{} - } - return time.Unix(exp, 0) -} - -// GitHub is the caller's GitHub identity for one commit: the person's user -// token of the App giantswarm-cluster-manager, fetched from muster's broker, -// and the login GET /user answered for it. Commit mode opens the pull -// request with that token. -type GitHub struct { - Login string - Token string -} - -// ContextWithGitHub returns ctx carrying the caller's GitHub identity. -func ContextWithGitHub(ctx context.Context, gh *GitHub) context.Context { - if gh == nil || gh.Token == "" { - return ctx - } - return context.WithValue(ctx, gitHubKey, gh) -} - -// GitHubFromContext returns the caller's GitHub identity, if any. -func GitHubFromContext(ctx context.Context) (*GitHub, bool) { - gh, ok := ctx.Value(gitHubKey).(*GitHub) - return gh, ok && gh != nil -} diff --git a/internal/identity/identity_test.go b/internal/identity/identity_test.go deleted file mode 100644 index a5e6a19..0000000 --- a/internal/identity/identity_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package identity - -import ( - "context" - "encoding/base64" - "encoding/json" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestContextRoundTrip(t *testing.T) { - ctx := context.Background() - _, ok := FromContext(ctx) - assert.False(t, ok) - assert.Equal(t, "service-account", LogAttr(ctx).Value.String()) - assert.Equal(t, "", Caller(ctx)) - - id := &Identity{Subject: "sub-1", Email: "admin@lab.local", Groups: []string{"platform-admins"}, Source: SourceSSO} - ctx = ContextWith(ctx, id) - got, ok := FromContext(ctx) - require.True(t, ok) - assert.Equal(t, id, got) - assert.Equal(t, "admin@lab.local", Caller(ctx)) - assert.Equal(t, "admin@lab.local", LogAttr(ctx).Value.String()) - - assert.Equal(t, "sub-1", (&Identity{Subject: "sub-1"}).String(), "email wins, subject is the fallback") - assert.Equal(t, "", (*Identity)(nil).String()) - - _, ok = TokenFromContext(ctx) - assert.False(t, ok) - ctx = ContextWithToken(ctx, "tok") - tok, ok := TokenFromContext(ctx) - require.True(t, ok) - assert.Equal(t, "tok", tok) - assert.Same(t, ctx, ContextWithToken(ctx, ""), "an empty token adds nothing") - assert.Same(t, ctx, ContextWith(ctx, nil), "a nil identity adds nothing") -} - -func TestTokenExpiry(t *testing.T) { - exp := time.Now().Add(time.Hour).Truncate(time.Second) - assert.Equal(t, exp, TokenExpiry(jwt(t, map[string]any{"exp": exp.Unix()}))) - assert.True(t, TokenExpiry(jwt(t, map[string]any{"sub": "x"})).IsZero(), "no exp claim") - assert.True(t, TokenExpiry("opaque-token").IsZero()) - assert.True(t, TokenExpiry("a.!!!.c").IsZero()) -} - -func jwt(t *testing.T, claims map[string]any) string { - t.Helper() - header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`)) - payload, err := json.Marshal(claims) - require.NoError(t, err) - return header + "." + base64.RawURLEncoding.EncodeToString(payload) + ".sig" -} diff --git a/internal/idtoken/idtoken.go b/internal/idtoken/idtoken.go new file mode 100644 index 0000000..fbc393b --- /dev/null +++ b/internal/idtoken/idtoken.go @@ -0,0 +1,25 @@ +// Package idtoken carries the user's OpenID Connect ID token on a request +// context. It is set only when the server calls the Kubernetes API as the +// user (--downstream-oauth): mcp-oauth's handler.ProviderIDTokenFromContext +// returns a forwarded ID token in either mode, so it cannot tell the two +// apart. A request without one selects the ServiceAccount's clients and +// reads no workload cluster. +package idtoken + +import "context" + +type contextKey struct{} + +// ContextWith returns ctx carrying token. An empty token adds nothing. +func ContextWith(ctx context.Context, token string) context.Context { + if token == "" { + return ctx + } + return context.WithValue(ctx, contextKey{}, token) +} + +// FromContext returns the user's ID token, if the request carries one. +func FromContext(ctx context.Context) (string, bool) { + token, ok := ctx.Value(contextKey{}).(string) + return token, ok && token != "" +} diff --git a/internal/idtoken/idtoken_test.go b/internal/idtoken/idtoken_test.go new file mode 100644 index 0000000..39cf290 --- /dev/null +++ b/internal/idtoken/idtoken_test.go @@ -0,0 +1,18 @@ +package idtoken + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestContextRoundTrip(t *testing.T) { + ctx := t.Context() + _, ok := FromContext(ctx) + require.False(t, ok) + require.Equal(t, ctx, ContextWith(ctx, ""), "an empty token adds nothing") + + token, ok := FromContext(ContextWith(ctx, "id-token")) + require.True(t, ok) + require.Equal(t, "id-token", token) +} diff --git a/internal/kube/client.go b/internal/kube/client.go index d2fddcf..31c0539 100644 --- a/internal/kube/client.go +++ b/internal/kube/client.go @@ -19,7 +19,7 @@ import ( toolkitk8s "github.com/giantswarm/mcp-toolkit/k8s" - "github.com/giantswarm/cluster-manager/internal/identity" + "github.com/giantswarm/cluster-manager/internal/idtoken" ) // Factory selects explicitly configured application clients or caller clients. @@ -95,7 +95,7 @@ func fromRESTConfig(restCfg *rest.Config) (*Factory, error) { // the installation's identity provider). Without a caller token there is no // identity to present and the target is not read. func (c *Factory) ForTarget(ctx context.Context, apiServer string, ca []byte) (*toolkitk8s.Clients, error) { - token, ok := identity.TokenFromContext(ctx) + token, ok := idtoken.FromContext(ctx) if !ok { return nil, fmt.Errorf("no caller token: a workload cluster is read as the caller only") } @@ -110,7 +110,7 @@ func (c *Factory) ForTarget(ctx context.Context, apiServer string, ca []byte) (* // For selects caller clients when a token is present, including after expiry. // Calls without a token use the explicitly configured base clients. func (c *Factory) For(ctx context.Context) (*toolkitk8s.Clients, error) { - token, ok := identity.TokenFromContext(ctx) + token, ok := idtoken.FromContext(ctx) if !ok { return c.Clients, nil } diff --git a/internal/kube/client_test.go b/internal/kube/client_test.go index 46e16e2..0880d2a 100644 --- a/internal/kube/client_test.go +++ b/internal/kube/client_test.go @@ -17,7 +17,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/rest" - "github.com/giantswarm/cluster-manager/internal/identity" + "github.com/giantswarm/cluster-manager/internal/idtoken" ) func TestForSelectsExplicitClientsOrCaller(t *testing.T) { @@ -26,14 +26,14 @@ func TestForSelectsExplicitClientsOrCaller(t *testing.T) { application, err := clients.For(t.Context()) require.NoError(t, err) require.Same(t, clients.Clients, application) - callerContext := identity.ContextWithToken(t.Context(), jwt(t, time.Now().Add(time.Hour))) + callerContext := idtoken.ContextWith(t.Context(), jwt(t, time.Now().Add(time.Hour))) caller, err := clients.For(callerContext) require.NoError(t, err) require.NotSame(t, application, caller) cached, err := clients.For(callerContext) require.NoError(t, err) require.Same(t, caller, cached) - expiredContext := identity.ContextWithToken(t.Context(), jwt(t, time.Now().Add(-time.Minute))) + expiredContext := idtoken.ContextWith(t.Context(), jwt(t, time.Now().Add(-time.Minute))) expired, err := clients.For(expiredContext) require.NoError(t, err) require.NotSame(t, application, expired) @@ -55,7 +55,7 @@ func TestForConstructionFailureSendsNoServiceAccountRequest(t *testing.T) { clients, err := fromRESTConfig(&rest.Config{Host: api.URL, BearerToken: "application-token", TLSClientConfig: rest.TLSClientConfig{CAFile: caFile}}) require.NoError(t, err) require.NoError(t, os.Remove(caFile)) - caller, err := clients.For(identity.ContextWithToken(t.Context(), "caller-token")) + caller, err := clients.For(idtoken.ContextWith(t.Context(), "caller-token")) require.ErrorContains(t, err, "caller-token Kubernetes clients") require.Nil(t, caller) require.Zero(t, requests.Load()) @@ -73,7 +73,7 @@ func TestForExpiredTokenReachesAPIAsCaller(t *testing.T) { t.Cleanup(api.Close) clients, err := fromRESTConfig(&rest.Config{Host: api.URL, BearerToken: "application-token"}) require.NoError(t, err) - caller, err := clients.For(identity.ContextWithToken(t.Context(), token)) + caller, err := clients.For(idtoken.ContextWith(t.Context(), token)) require.NoError(t, err) _, err = caller.Clientset.CoreV1().ConfigMaps("default").List(t.Context(), metav1.ListOptions{}) require.True(t, apierrors.IsUnauthorized(err), "%v", err) diff --git a/internal/server/github_exchange.go b/internal/server/github_exchange.go index ec1c75d..5a831f3 100644 --- a/internal/server/github_exchange.go +++ b/internal/server/github_exchange.go @@ -18,7 +18,7 @@ import ( "github.com/giantswarm/mcp-oauth/oauthconfig" "github.com/giantswarm/mcp-oauth/providers/oidc" - "github.com/giantswarm/cluster-manager/internal/identity" + "github.com/giantswarm/cluster-manager/internal/idtoken" "github.com/giantswarm/cluster-manager/internal/tools" ) @@ -104,9 +104,9 @@ func newGitHubExchange(configuration GitHubExchangeConfig, client *http.Client, grantRequired := func(reason string) error { return &tools.ErrGrantRequired{App: configuration.Audience, Reason: fmt.Sprintf(reason, configuration.Audience, configuration.Audience)} } - return func(ctx context.Context) (*identity.GitHub, error) { + return func(ctx context.Context) (*tools.GitHubUserAccessToken, error) { validatedUser, ok := handler.UserInfoFromContext(ctx) - subjectToken, hasToken := identity.TokenFromContext(ctx) + subjectToken, hasToken := idtoken.FromContext(ctx) if !ok || validatedUser == nil || validatedUser.Issuer == "" || validatedUser.ID == "" || !hasToken || subjectToken == "" { return nil, &tools.ErrRefused{Reason: "commit mode needs your verified platform identity to fetch your GitHub authorization"} } @@ -169,7 +169,7 @@ func newGitHubExchange(configuration GitHubExchangeConfig, client *http.Client, if response.StatusCode != http.StatusOK || json.NewDecoder(io.LimitReader(response.Body, 16*1024)).Decode(&user) != nil || user.Login == "" { return nil, fmt.Errorf("GitHub user verification is unavailable (status %d)", response.StatusCode) } - return &identity.GitHub{Login: user.Login, Token: result.AccessToken}, nil + return &tools.GitHubUserAccessToken{Login: user.Login, Token: result.AccessToken}, nil } } diff --git a/internal/server/github_exchange_test.go b/internal/server/github_exchange_test.go index f78b397..a6ed0a3 100644 --- a/internal/server/github_exchange_test.go +++ b/internal/server/github_exchange_test.go @@ -23,7 +23,7 @@ import ( "github.com/giantswarm/mcp-oauth/providers/oidc" "github.com/stretchr/testify/require" - "github.com/giantswarm/cluster-manager/internal/identity" + "github.com/giantswarm/cluster-manager/internal/idtoken" "github.com/giantswarm/cluster-manager/internal/tools" ) @@ -106,19 +106,19 @@ func TestGitHubExchange(t *testing.T) { switch scenario { case "delegated actor": user.ActorIssuer, user.ActorSubject = "https://agents.example.test", "agent" - ctx = identity.ContextWithToken(ctx, personToken) + ctx = idtoken.ContextWith(ctx, personToken) case "unvalidated identity token": - ctx = identity.ContextWithToken(t.Context(), personToken) + ctx = idtoken.ContextWith(t.Context(), personToken) case "missing identity token": default: - ctx = identity.ContextWithToken(ctx, personToken) + ctx = idtoken.ContextWith(ctx, personToken) } resolve, err := NewGitHubExchange(configuration, slog.New(slog.NewJSONHandler(&logged, nil))) require.NoError(t, err) result, err := resolve(ctx) if scenario == "success" { require.NoError(t, err) - require.Equal(t, &identity.GitHub{Login: "alice", Token: "fixture-user-grant"}, result) // #nosec G101 -- synthetic broker response + require.Equal(t, &tools.GitHubUserAccessToken{Login: "alice", Token: "fixture-user-grant"}, result) // #nosec G101 -- synthetic broker response _, err = resolve(ctx) require.NoError(t, err) require.Equal(t, 2, exchanges) @@ -218,7 +218,7 @@ func TestGitHubExchangeTrustsOnlyItsCA(t *testing.T) { upstream, _ := newLocalhostTLSServer(t, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true })) resolve, err := NewGitHubExchange(GitHubExchangeConfig{TokenEndpoint: upstream.URL + "/token", ClientID: "manager-client", ClientSecretFile: secretFile, Audience: "manager-app", APIURL: upstream.URL}, slog.New(slog.DiscardHandler)) require.NoError(t, err) - ctx := identity.ContextWithToken(oauthhandler.ContextWithUserInfo(t.Context(), &providers.UserInfo{ID: "alice", Issuer: "https://issuer.example.test"}), personToken) + ctx := idtoken.ContextWith(oauthhandler.ContextWithUserInfo(t.Context(), &providers.UserInfo{ID: "alice", Issuer: "https://issuer.example.test"}), personToken) _, err = resolve(ctx) require.ErrorContains(t, err, "GitHub authorization service is unavailable") _, isGrant := errors.AsType[*tools.ErrGrantRequired](err) @@ -264,7 +264,7 @@ func TestGitHubExchangeRefusesIPLiteralEndpoint(t *testing.T) { require.NoError(t, err) require.True(t, roots.AppendCertsFromPEM(pemBytes)) client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}}} - ctx := identity.ContextWithToken(oauthhandler.ContextWithUserInfo(t.Context(), &providers.UserInfo{ID: "alice", Issuer: "https://issuer.example.test"}), personToken) + ctx := idtoken.ContextWith(oauthhandler.ContextWithUserInfo(t.Context(), &providers.UserInfo{ID: "alice", Issuer: "https://issuer.example.test"}), personToken) for _, scenario := range []struct { endpoint string diff --git a/internal/server/oauth.go b/internal/server/oauth.go index 011560b..65f1e48 100644 --- a/internal/server/oauth.go +++ b/internal/server/oauth.go @@ -15,7 +15,7 @@ import ( "github.com/giantswarm/mcp-oauth/security" oauthserver "github.com/giantswarm/mcp-oauth/server" - "github.com/giantswarm/cluster-manager/internal/identity" + "github.com/giantswarm/cluster-manager/internal/idtoken" ) // OAuthConfig makes cluster-manager an OAuth 2.1 resource server (mcp-oauth) @@ -23,20 +23,19 @@ import ( // authority: on the Agent Platform, muster forwards the session's IdP // id_token byte-identical (MCPServer auth.forwardToken) and the portal sends // the signed-in user's id_token through the gateway; both are validated -// against the IdP's JWKS when their audience is one of the trusted audiences -// (OAUTH_TRUSTED_AUDIENCES, the platform's OAuth client). The caller's -// identity then travels with the request (identity package) and, with -// DownstreamOAuth, so does the token: the Kubernetes API is called as the -// caller. +// against the provider's JWKS as a trusted issuer (OAUTH_TRUSTED_ISSUERS). +// The user mcp-oauth validated (providers.UserInfo) then travels with the +// request and, with DownstreamOAuth, so does their ID token: the Kubernetes +// API is called as the user. type OAuthConfig struct { // Settings is mcp-oauth's configuration, read from the OAUTH_* variables // by oauthconfig.SettingsFromEnv. Settings oauthconfig.Settings - // DownstreamOAuth puts the caller's IdP token on the request so - // Kubernetes API calls are made as the caller instead of the - // ServiceAccount (the apiserver must trust the IdP and the token's - // audience). The ServiceAccount holds no permissions then, so a request - // that yields no IdP token to present is refused (401). + // DownstreamOAuth puts the user's ID token on the request so Kubernetes + // API calls are made as the user instead of the ServiceAccount (the + // apiserver must trust the provider and the token's audience). The + // ServiceAccount holds no permissions then, so a request that yields no + // ID token to present is refused (401). DownstreamOAuth bool } @@ -121,46 +120,42 @@ func (o *oauthRuntime) register(mux *http.ServeMux) { } // protect requires a valid bearer token (mcp-oauth ValidateToken: this -// server's own access tokens, or a forwarded IdP id_token whose audience is -// trusted) and then attaches the caller to the request. +// server's own access tokens, or a forwarded ID token from a trusted issuer), +// which puts the validated user on the request. With DownstreamOAuth the +// request also needs the user's ID token (RequireProviderIDToken), which +// attachIDToken hands to the Kubernetes clients; the ServiceAccount then +// holds no permissions, so there is nothing else to run as. func (o *oauthRuntime) protect(next http.Handler) http.Handler { - protected := o.attachIdentity(next) + protected := o.logUser(next) if o.downstreamOAuth { - protected = o.handler.RequireProviderIDToken(protected) + protected = o.handler.RequireProviderIDToken(attachIDToken(protected)) } return o.handler.ValidateToken(protected) } -// attachIdentity translates the validated mcp-oauth user into the request's -// identity and, with DownstreamOAuth, resolves the IdP token to present to -// the Kubernetes API: a forwarded id_token is the bearer itself; for a token -// this server issued, the provider's id_token is looked up in the store. A -// request that yields neither is refused: the ServiceAccount holds no -// permissions, so there is nothing else to run as. -func (o *oauthRuntime) attachIdentity(next http.Handler) http.Handler { +// logUser logs at debug level who a request authenticated as and how +// mcp-oauth validated the bearer. +func (o *oauthRuntime) logUser(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - info, ok := handler.UserInfoFromContext(ctx) - if !ok || info == nil { - // ValidateToken admits nothing without user info; defensive. + if user, ok := handler.UserInfoFromContext(r.Context()); ok && user != nil { + o.log.DebugContext(r.Context(), "authenticated request", slog.Any("user", user), "token_source", user.TokenSource, "path", r.URL.Path) + } + next.ServeHTTP(w, r) + }) +} + +// attachIDToken puts the user's ID token on the request for the Kubernetes +// clients: a forwarded ID token is the bearer itself; for a token this server +// issued, the provider's ID token stored with it. A request without one is +// refused. +func attachIDToken(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token, err := handler.ProviderIDTokenFromContext(r.Context()) + if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } - id := &identity.Identity{Subject: info.ID, Email: info.Email, Name: info.Name, Groups: info.Groups, Source: identity.SourceOAuth} - if info.IsSSO() { - id.Source = identity.SourceSSO - } - ctx = identity.ContextWith(ctx, id) - if o.downstreamOAuth { - token, err := handler.ProviderIDTokenFromContext(ctx) - if err != nil { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - ctx = identity.ContextWithToken(ctx, token) - } - o.log.Debug("authenticated request", "caller", id.String(), "source", id.Source, "path", r.URL.Path) - next.ServeHTTP(w, r.WithContext(ctx)) + next.ServeHTTP(w, r.WithContext(idtoken.ContextWith(r.Context(), token))) }) } diff --git a/internal/server/oauth_realchain_test.go b/internal/server/oauth_realchain_test.go index 876dfc9..5bf348e 100644 --- a/internal/server/oauth_realchain_test.go +++ b/internal/server/oauth_realchain_test.go @@ -22,12 +22,13 @@ import ( "testing" "time" + "github.com/giantswarm/mcp-oauth/handler" "github.com/go-jose/go-jose/v4" "github.com/go-jose/go-jose/v4/jwt" "github.com/stretchr/testify/require" "golang.org/x/net/dns/dnsmessage" - "github.com/giantswarm/cluster-manager/internal/identity" + "github.com/giantswarm/cluster-manager/internal/idtoken" ) // privateIdP is an OIDC issuer the production chain reaches as it reaches @@ -246,7 +247,9 @@ func callThroughChain(t *testing.T, cfg OAuthConfig, bearer string) (int, string }) var caller string h := o.protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - caller = identity.Caller(r.Context()) + if user, ok := handler.UserInfoFromContext(r.Context()); ok { + caller = user.Email + } w.WriteHeader(http.StatusNoContent) })) req := httptest.NewRequest(http.MethodPost, "/mcp", nil) @@ -338,7 +341,7 @@ func TestOpenIDProviderTrustedIssuer(t *testing.T) { }) var presented string h := o.protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - presented, _ = identity.TokenFromContext(r.Context()) + presented, _ = idtoken.FromContext(r.Context()) w.WriteHeader(http.StatusNoContent) })) req := httptest.NewRequest(http.MethodPost, "/mcp", nil) diff --git a/internal/server/oauth_test.go b/internal/server/oauth_test.go index e53562a..c47afcc 100644 --- a/internal/server/oauth_test.go +++ b/internal/server/oauth_test.go @@ -1,6 +1,7 @@ package server import ( + "bytes" "context" "crypto/rand" "crypto/rsa" @@ -29,7 +30,7 @@ import ( "github.com/stretchr/testify/require" "github.com/giantswarm/cluster-manager/internal/api" - "github.com/giantswarm/cluster-manager/internal/identity" + "github.com/giantswarm/cluster-manager/internal/idtoken" ) // fakeIdP is a minimal OIDC issuer on https://localhost serving the discovery @@ -141,10 +142,6 @@ func googleSettings(t *testing.T) oauthconfig.Settings { }) } -func newTestOAuthRuntime(cfg OAuthConfig) *oauthRuntime { - return &oauthRuntime{downstreamOAuth: cfg.DownstreamOAuth, log: slog.New(slog.NewTextHandler(io.Discard, nil))} -} - // authenticated is a request mcp-oauth has validated: its user info is on the // context, as ValidateToken leaves it. func authenticated(bearer string, info *providers.UserInfo) *http.Request { @@ -158,16 +155,11 @@ func authenticated(bearer string, info *providers.UserInfo) *http.Request { return req } -var forwardedUser = &providers.UserInfo{ - ID: "sub-admin", Email: "admin@lab.local", Name: "Lab Admin", Groups: []string{"platform-admins"}, - TokenSource: providers.TokenSourceSSO, -} - -// TestAttachIdentityForwardedIDToken is the platform path after validation: -// muster (or the portal through the gateway) forwarded the IdP id_token for -// the platform client; the request carries the caller and, with downstream -// OAuth, the caller's token. -func TestAttachIdentityForwardedIDToken(t *testing.T) { +// TestForwardedIDTokenBecomesTheUser is the platform path: muster (or the +// portal through the gateway) forwards the ID token for the platform client; +// once mcp-oauth has validated it, the request carries the user and, with +// downstream OAuth, their ID token. +func TestForwardedIDTokenBecomesTheUser(t *testing.T) { identityProvider := newPrivateIdP(t, "") configuration := identityProvider.config(t) configuration.DownstreamOAuth = true @@ -176,13 +168,13 @@ func TestAttachIdentityForwardedIDToken(t *testing.T) { t.Cleanup(func() { o.shutdown(context.WithoutCancel(t.Context())) }) forwardedToken := identityProvider.idToken(t, []string{"agent-platform"}) var seen struct { - id *identity.Identity + user *providers.UserInfo token string ok bool } h := o.protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - seen.id, seen.ok = identity.FromContext(r.Context()) - seen.token, _ = identity.TokenFromContext(r.Context()) + seen.user, seen.ok = handler.UserInfoFromContext(r.Context()) + seen.token, _ = idtoken.FromContext(r.Context()) w.WriteHeader(http.StatusNoContent) })) @@ -191,11 +183,11 @@ func TestAttachIdentityForwardedIDToken(t *testing.T) { request.Header.Set("Authorization", "bEaReR "+forwardedToken) h.ServeHTTP(rec, request) require.Equal(t, http.StatusNoContent, rec.Code, rec.Body.String()) - require.True(t, seen.ok, "the caller reaches the handler") - assert.Equal(t, "admin@lab.local", seen.id.Email) - assert.Equal(t, "sub-admin", seen.id.Subject) - assert.Equal(t, []string{"platform-admins"}, seen.id.Groups) - assert.Equal(t, identity.SourceSSO, seen.id.Source) + require.True(t, seen.ok, "the user reaches the handler") + assert.Equal(t, "admin@lab.local", seen.user.Email) + assert.Equal(t, "sub-admin", seen.user.ID) + assert.Equal(t, []string{"platform-admins"}, seen.user.Groups) + assert.True(t, seen.user.IsSSO(), "a forwarded id_token") assert.Equal(t, forwardedToken, seen.token, "downstream OAuth: the forwarded id_token is what the Kubernetes API will see") seen.ok = false @@ -203,41 +195,79 @@ func TestAttachIdentityForwardedIDToken(t *testing.T) { h.ServeHTTP(rec, authenticated("untrusted-token", nil)) assert.Equal(t, http.StatusUnauthorized, rec.Code, "no validated user, no caller") assert.False(t, seen.ok) + + // No validated user, no ID token to attach. + rec = httptest.NewRecorder() + attachIDToken(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/mcp", nil)) + assert.Equal(t, http.StatusUnauthorized, rec.Code) } -func TestAttachIdentityDownstreamOffKeepsTheServiceAccount(t *testing.T) { - o := newTestOAuthRuntime(OAuthConfig{}) - var caller string +func TestDownstreamOffKeepsTheServiceAccount(t *testing.T) { + identityProvider := newPrivateIdP(t, "") + o, err := newOAuth(identityProvider.config(t), "/mcp", slog.New(slog.DiscardHandler)) + require.NoError(t, err) + t.Cleanup(func() { o.shutdown(context.WithoutCancel(t.Context())) }) + var attributed string var hasToken bool - h := o.attachIdentity(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - caller = identity.Caller(r.Context()) - _, hasToken = identity.TokenFromContext(r.Context()) + h := o.protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if user, ok := handler.UserInfoFromContext(r.Context()); ok { + attributed = user.Email + } + _, hasToken = idtoken.FromContext(r.Context()) })) + request := httptest.NewRequest(http.MethodGet, "/mcp", nil) + request.Header.Set("Authorization", "Bearer "+identityProvider.idToken(t, []string{"agent-platform"})) rec := httptest.NewRecorder() - h.ServeHTTP(rec, authenticated("forwarded-id-token", forwardedUser)) - require.Equal(t, http.StatusOK, rec.Code) - assert.Equal(t, "admin@lab.local", caller, "the caller is known and attributed") + h.ServeHTTP(rec, request) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Equal(t, "admin@lab.local", attributed, "the user is known and attributed") assert.False(t, hasToken, "but nothing is presented to the Kubernetes API") } -// TestAttachIdentityIssuedTokenNeedsStoredIDToken: for a token this server -// issued, the provider's id_token stored next to it is what the Kubernetes API -// sees; without one the request is refused. -func TestAttachIdentityIssuedTokenNeedsStoredIDToken(t *testing.T) { - configuration := OAuthConfig{Settings: googleSettings(t), DownstreamOAuth: true} +// TestDownstreamNeedsAnIDToken: a bearer mcp-oauth validates from a trusted +// issuer that is not the OpenID Provider is no ID token, so under downstream +// OAuth there is nothing to present to the Kubernetes API: the request is +// refused and the handler never runs. Without downstream OAuth the same +// bearer is admitted. +func TestDownstreamNeedsAnIDToken(t *testing.T) { + identityProvider := newPrivateIdP(t, "") + bearer := identityProvider.idToken(t, []string{"kubernetes"}) + + configuration := identityProvider.trustedIssuerConfig(t, true, privateIssuerHost) + configuration.Settings.TrustedIssuers[0].OpenIDProvider = false o, err := newOAuth(configuration, "/mcp", slog.New(slog.DiscardHandler)) require.NoError(t, err) t.Cleanup(func() { o.shutdown(context.WithoutCancel(t.Context())) }) - var token string - h := o.protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - token, _ = identity.TokenFromContext(r.Context()) + ran := false + h := o.protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + ran = true + w.WriteHeader(http.StatusNoContent) })) - rec := httptest.NewRecorder() - h.ServeHTTP(rec, authenticated("unknown-access-token", nil)) - require.Equal(t, http.StatusUnauthorized, rec.Code) - assert.Contains(t, rec.Header().Get("WWW-Authenticate"), `error="invalid_token"`) - assert.Empty(t, token) + h.ServeHTTP(rec, authenticated(bearer, nil)) + require.Equal(t, http.StatusUnauthorized, rec.Code, rec.Body.String()) + require.False(t, ran, "the handler never runs without an ID token to present") + + configuration.DownstreamOAuth = false + code, caller := callThroughChain(t, configuration, bearer) + require.Equal(t, http.StatusNoContent, code, "the bearer itself is valid") + require.Equal(t, "admin@lab.local", caller) +} + +func TestLogUserNamesTheUserWithoutProfileData(t *testing.T) { + var logs bytes.Buffer + o := &oauthRuntime{log: slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))} + user := &providers.UserInfo{Issuer: "https://dex.example.test", ID: "sub-admin", Email: "admin@lab.local", TokenSource: providers.TokenSourceSSO} + request := httptest.NewRequest(http.MethodGet, "/mcp", nil) + request = request.WithContext(handler.ContextWithUserInfo(request.Context(), user)) + + o.logUser(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })).ServeHTTP(httptest.NewRecorder(), request) + + var line map[string]any + require.NoError(t, json.Unmarshal(logs.Bytes(), &line)) + require.Equal(t, map[string]any{"issuer": "https://dex.example.test", "subject": "sub-admin"}, line["user"]) + require.Equal(t, string(providers.TokenSourceSSO), line["token_source"]) + require.NotContains(t, logs.String(), "admin@lab.local") } // TestServerGuardsMCPButNotProbes wires OAuth through the assembled server: diff --git a/internal/tools/cluster_create_test.go b/internal/tools/cluster_create_test.go index 8360916..68671d1 100644 --- a/internal/tools/cluster_create_test.go +++ b/internal/tools/cluster_create_test.go @@ -7,6 +7,8 @@ import ( "path/filepath" "testing" + "github.com/giantswarm/mcp-oauth/handler" + "github.com/giantswarm/mcp-oauth/providers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -17,7 +19,6 @@ import ( k8stesting "k8s.io/client-go/testing" "github.com/giantswarm/cluster-manager/internal/compose" - "github.com/giantswarm/cluster-manager/internal/identity" ) // releaseCharts is the registry as the release tests need it: release-aws @@ -281,7 +282,7 @@ func TestCreateClusterBindsTheCreatorAndTheOrgAdmins(t *testing.T) { oidc := &compose.ClusterOIDC{IssuerURL: "https://dex.gazelle.example", ClientID: "dex-k8s-authenticator", UsernameClaim: "email", GroupsClaim: "groups"} l := newLab(t, "releases.yaml") svc := l.service(Config{Installation: "gazelle", ClusterOIDC: oidc}, WithChartReader(releaseCharts(t))) - ctx := identity.ContextWith(context.Background(), &identity.Identity{Subject: "CgVqYW5l", Email: "jane@acme.example", Source: identity.SourceSSO}) + ctx := handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example", TokenSource: providers.TokenSourceSSO}) in := dev01() in.DryRun = true got, err := svc.CreateCluster(ctx, in) @@ -322,7 +323,7 @@ func TestCreateClusterBindsTheCreatorAndTheOrgAdmins(t *testing.T) { // cluster's usernamePrefix (the apiserver flag's "-" for none), the // installation's OIDC settings under the cluster's. func TestCreatorUsername(t *testing.T) { - ctx := identity.ContextWith(context.Background(), &identity.Identity{Subject: "CgVqYW5l", Email: "jane@acme.example"}) + ctx := handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example"}) oidc := func(block map[string]any) map[string]any { return map[string]any{"global": map[string]any{"controlPlane": map[string]any{"oidc": block}}} } @@ -345,7 +346,7 @@ func TestCreatorUsername(t *testing.T) { } }) } - got, note := creatorUsername(identity.ContextWith(context.Background(), &identity.Identity{Subject: "CgVqYW5l"}), nil, oidc(map[string]any{"usernameClaim": "email"})) + got, note := creatorUsername(handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l"}), nil, oidc(map[string]any{"usernameClaim": "email"})) assert.Empty(t, got) assert.Contains(t, note, "your sign-in carries no email") } @@ -409,7 +410,7 @@ func TestCreateClusterRBACNotes(t *testing.T) { assert.Empty(t, got.RBAC.Users) assert.Contains(t, got.RBAC.Note, "without a signed-in person") - ctx := identity.ContextWith(context.Background(), &identity.Identity{Subject: "CgVqYW5l", Email: "jane@acme.example"}) + ctx := handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example"}) got, err = plain.CreateCluster(ctx, in) require.NoError(t, err) assert.Empty(t, got.RBAC.Users) diff --git a/internal/tools/cluster_rbac.go b/internal/tools/cluster_rbac.go index b0e656f..cc34284 100644 --- a/internal/tools/cluster_rbac.go +++ b/internal/tools/cluster_rbac.go @@ -6,13 +6,13 @@ import ( "sort" "strings" + "github.com/giantswarm/mcp-oauth/handler" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/client-go/dynamic" "github.com/giantswarm/cluster-manager/internal/compose" - "github.com/giantswarm/cluster-manager/internal/identity" "github.com/giantswarm/cluster-manager/internal/registry" ) @@ -118,8 +118,8 @@ func orgAdmins(ctx context.Context, dyn dynamic.Interface, ns string) (compose.C // takes the username from the email claim — the claim cluster-manager // composes. Otherwise empty, with the note saying why. func creatorUsername(ctx context.Context, installation, values map[string]any) (string, string) { - id, ok := identity.FromContext(ctx) - if !ok { + user, ok := handler.UserInfoFromContext(ctx) + if !ok || user == nil { return "", "this call runs without a signed-in person, so no creator is bound" } oidc := map[string]any{} @@ -132,14 +132,14 @@ func creatorUsername(ctx context.Context, installation, values map[string]any) ( if claim != "email" { return "", fmt.Sprintf("the cluster takes the username from the %q claim, not the email, so you are not bound — add yourself through %s", orDefault(claim, "sub"), valuesBindings) } - if id.Email == "" { + if user.Email == "" { return "", fmt.Sprintf("your sign-in carries no email, the claim the cluster takes the username from, so you are not bound — add yourself through %s", valuesBindings) } prefix, _ := oidc["usernamePrefix"].(string) if prefix == "-" { // the apiserver flag's "no prefix" prefix = "" } - return prefix + id.Email, "" + return prefix + user.Email, "" } func unique(ss []string) []string { diff --git a/internal/tools/commit.go b/internal/tools/commit.go index b3d63f9..2fb66d7 100644 --- a/internal/tools/commit.go +++ b/internal/tools/commit.go @@ -16,8 +16,6 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" sigsyaml "sigs.k8s.io/yaml" - - "github.com/giantswarm/cluster-manager/internal/identity" ) // The Flux objects commit mode follows from a cluster to the repository that @@ -67,8 +65,18 @@ func WithGitHub(remote RemoteFor) Option { return func(s *Service) { s.remote = remote } } -// GitHubUser fetches the person's GitHub grant for one call. -type GitHubUser func(context.Context) (*identity.GitHub, error) +// GitHubUserAccessToken is the person's GitHub App user access token for one +// call, obtained through muster's broker, with the login GET /user answered +// for it. Commit mode opens the pull request with that token. +type GitHubUserAccessToken struct { + Login string + Token string +} + +// GitHubUser fetches the person's GitHub App user access token for one call. +type GitHubUser func(context.Context) (*GitHubUserAccessToken, error) + +type gitHubKey struct{} // WithGitHubUser fetches the person's grant on demand for commit mode; // without it commit mode refuses every call. @@ -216,14 +224,14 @@ func (s *Service) authorizeCommit(ctx context.Context, mode string) (context.Con if gh == nil || gh.Token == "" { return nil, errNoGitHub } - return identity.ContextWithGitHub(ctx, gh), nil + return context.WithValue(ctx, gitHubKey{}, gh), nil } // gitHubFor is the caller's GitHub remote, or the refusal naming the // consent that gives one. -func (s *Service) gitHubFor(ctx context.Context) (GitHubRemote, *identity.GitHub, error) { - gh, ok := identity.GitHubFromContext(ctx) - if !ok { +func (s *Service) gitHubFor(ctx context.Context) (GitHubRemote, *GitHubUserAccessToken, error) { + gh, ok := ctx.Value(gitHubKey{}).(*GitHubUserAccessToken) + if !ok || gh == nil { return nil, nil, errNoGitHub } remote, err := s.remote(gh.Token) @@ -319,7 +327,7 @@ func (p *commitPlan) actions() []CommitFile { // open lands the plan as one pull request as the caller, or reports it on a // dry run. Nothing to change opens none. -func (p *commitPlan) open(ctx context.Context, gh *identity.GitHub, branch, title, body string, dryRun bool) (*CommitResult, error) { +func (p *commitPlan) open(ctx context.Context, gh *GitHubUserAccessToken, branch, title, body string, dryRun bool) (*CommitResult, error) { out := &CommitResult{ Repository: p.target.Repository, Base: p.target.Branch, Directory: p.target.Path, Kustomization: p.target.Kustomization, Prune: p.target.Prune, Branch: branch, Files: p.actions(), Author: gh.Login, diff --git a/internal/tools/commit_test.go b/internal/tools/commit_test.go index c15c8b3..7217de5 100644 --- a/internal/tools/commit_test.go +++ b/internal/tools/commit_test.go @@ -14,8 +14,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" dynamicfake "k8s.io/client-go/dynamic/fake" - - "github.com/giantswarm/cluster-manager/internal/identity" ) var fleet = commit.Repository{Owner: "acme", Name: "workload-clusters-fleet"} @@ -62,15 +60,15 @@ type personKey struct{} func withFake(fake *commit.Fake) Option { return func(s *Service) { WithGitHub(func(string) (GitHubRemote, error) { return fake, nil })(s) - WithGitHubUser(func(ctx context.Context) (*identity.GitHub, error) { - gh, _ := ctx.Value(personKey{}).(*identity.GitHub) + WithGitHubUser(func(ctx context.Context) (*GitHubUserAccessToken, error) { + gh, _ := ctx.Value(personKey{}).(*GitHubUserAccessToken) return gh, nil })(s) } } func asPerson(ctx context.Context) context.Context { - return context.WithValue(ctx, personKey{}, &identity.GitHub{Login: "jane", Token: "the-persons-token"}) + return context.WithValue(ctx, personKey{}, &GitHubUserAccessToken{Login: "jane", Token: "the-persons-token"}) } func commitMode(in CreateNodePoolInput) CreateNodePoolInput { @@ -219,11 +217,11 @@ func TestCreateNodePoolCommitRefusals(t *testing.T) { func TestCommitAsksForTheGrant(t *testing.T) { l, fake := commitLab(t, map[string][]byte{".sops.yaml": sopsAge(t)}) granted := false - user := WithGitHubUser(func(context.Context) (*identity.GitHub, error) { + user := WithGitHubUser(func(context.Context) (*GitHubUserAccessToken, error) { if !granted { return nil, &ErrGrantRequired{App: "github", Reason: "grant it"} } - return &identity.GitHub{Login: "jane", Token: "the-persons-grant"}, nil + return &GitHubUserAccessToken{Login: "jane", Token: "the-persons-grant"}, nil }) svc := l.service(Config{Installation: "gazelle"}, withFake(fake), user) in := commitMode(l4("wc1", "gpu-l4", false)) @@ -265,7 +263,7 @@ func TestCommitFetchesTheGrantFirst(t *testing.T) { t.Run(name, func(t *testing.T) { l, fake := commitLab(t, map[string][]byte{".sops.yaml": sopsAge(t)}) fetches := 0 - user := WithGitHubUser(func(context.Context) (*identity.GitHub, error) { + user := WithGitHubUser(func(context.Context) (*GitHubUserAccessToken, error) { fetches++ return nil, &ErrGrantRequired{App: "github", Reason: "grant it"} }) @@ -289,7 +287,7 @@ func TestCommitFetchesTheGrantFirst(t *testing.T) { // TestApplyNeverFetchesTheGrant: mode apply needs no GitHub grant. func TestApplyNeverFetchesTheGrant(t *testing.T) { l, fake := commitLab(t, map[string][]byte{".sops.yaml": sopsAge(t)}) - user := WithGitHubUser(func(context.Context) (*identity.GitHub, error) { + user := WithGitHubUser(func(context.Context) (*GitHubUserAccessToken, error) { t.Fatal("mode apply fetched the GitHub grant") return nil, nil }) diff --git a/internal/tools/nodepool_commit.go b/internal/tools/nodepool_commit.go index a0fb1ae..1d9e75f 100644 --- a/internal/tools/nodepool_commit.go +++ b/internal/tools/nodepool_commit.go @@ -12,7 +12,6 @@ import ( "k8s.io/client-go/dynamic" "github.com/giantswarm/cluster-manager/internal/compose" - "github.com/giantswarm/cluster-manager/internal/identity" ) // poolCommit is a node-pool write in commit mode: the releases go into the @@ -23,7 +22,7 @@ import ( type poolCommit struct { loc commitLocation remote GitHubRemote - gh *identity.GitHub + gh *GitHubUserAccessToken } // newPoolCommit resolves the cluster's repository and the caller's GitHub From cfd2ccb8191c6219a27eaf67ac71a0acf9157029 Mon Sep 17 00:00:00 2001 From: QuentinBisson Date: Fri, 27 Nov 2026 13:00:54 +0100 Subject: [PATCH 4/5] fix: preserve resource-only OAuth and verified cluster identity --- README.md | 2 +- cmd/serve.go | 44 +++++++---- cmd/serve_test.go | 25 +++++-- docs/development.md | 13 ++++ helm/cluster-manager/README.md | 4 +- helm/cluster-manager/templates/_helpers.tpl | 2 +- .../tests/oauth_values_layout_test.yaml | 20 +++++ helm/cluster-manager/values.schema.json | 4 +- helm/cluster-manager/values.yaml | 12 +-- internal/server/oauth_protocol_test.go | 75 +++++++++++++++++++ internal/tools/cluster_create_test.go | 10 ++- internal/tools/cluster_rbac.go | 3 + 12 files changed, 181 insertions(+), 33 deletions(-) create mode 100644 internal/server/oauth_protocol_test.go diff --git a/README.md b/README.md index dfa7a8b..e7afac7 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Through muster the tools appear as `x_cluster-manager_`. [docs/tools.md](d | `get_info` | Version, mode capabilities (`apply`, `commit`, and `commitTools`: the tools that take mode `commit`), the tool list and whether the installation serves the Cluster API (`clusterApi`) | | `list_clusters` | The installation's clusters: name, organization, release version, own-cluster flag, the availability zones of the cluster's node subnets (`zones[]`, from its `AWSCluster` — what a pool may be pinned to, the choices `create_node_pool`'s `zones` is checked against; `zonesNote` when they cannot be read), GPU operator and serving presence with their provider (serving is present with a KServe controller — its Deployment, its release or the platform's discovery ConfigMap — never with the KServe CRDs alone, which Helm leaves behind when a serving layer goes: those are `absent` with the served APIs noted; a child `HelmRelease` of cluster-manager's slice release that is not Ready is named in the evidence with its condition's reason and message, since the slice's meta release reports Ready whether or not its children installed), the GPU pool releases (`ready`, and `deleting` while one is removed), the commit target; empty with a `clusterApi` note on an installation without the Cluster API. `LLMInferenceServiceConfig`s left terminating in the release namespace are named in `serving.evidence`. Beside `status`/`provider`/`evidence` both components carry `readiness`, structured, nothing to parse — `gpuOperator.readiness`: `release{name, namespace, ready, reason, message, since, deletedAt}` (the provider's operator release), `clusterPolicy{name, state}` (its `status.state`: `ready`, `notReady`, `ignored`), `operands[]{name, namespace, desired, ready}` (the device plugin and GPU feature discovery DaemonSets on the GPU nodes), `operandsMessage` (why `operands` is empty although a ClusterPolicy exists: the operator creates them once a GPU node joins, so a pool at scale-to-zero has none), `operandsError` (the DaemonSets could not be listed); `serving.readiness`: `release` (cluster-manager's slice release — `ready` only once every child release it renders is Ready too: the meta release reports Ready about 30 s before its children have installed, `kserve-llmisvc-resources` last, so until then `ready` is `false` with `reason` `ChildNotReady` and `message` naming each pending child with its condition), `children[]` (every child release of the slice with its Ready condition — the five KServe charts, the connectivity child, `kserve-runtime-configs`), `controllers[]{name, namespace, available, replicas}` (the KServe controller Deployments), `configs{count}` (the `LLMInferenceServiceConfig`s of the release namespace), `backend{registered, backend, namespace, name, error}` (the kserve backend cluster-manager registered with model-manager for this cluster: `backend` its name — `kserve` for the own cluster, `kserve-` for a workload cluster —, `namespace`/`name` its ConfigMap; `registered` is `true` or `false` when the ConfigMap was read and omitted, with `error` set, when it could not be read — never a bare `false` for a failed read), `presets{count}` (the published serving presets), `modelsGateway{name, namespace, ready, reason}` (the Gateway listening on `models.`, its Programmed condition), `webhook{configurations[], namespace, service, endpoints, ready, reason, message}` (the llmisvc admission webhook: the configurations admitting `LLMInferenceService`s and the Service they call — `ready` only once the Service has a ready endpoint and every configuration carries its CA bundle, named in the evidence until then: the controller's release reads Ready and its Deployment counts an available replica before the webhook answers, and a `load_model` in that window fails admission), `cache{enabled, claim}` (the model cache as cluster-manager's slice release states it in its values: whether the predictors mount a claim and which — `modelServing.cache.pvc.name`, the chart's default `hf-cache` when the values name none; `null` where the slice release is not cluster-manager's), `cacheClaims[]{namespace, name, phase, volume, zone, error}` (every model cache `PersistentVolumeClaim` of the serving namespace — the one of before, `hf-cache`, and the claims per zone, `hf-cache-`, kept when the pool goes — each with the zone its bound volume's node affinity names, where a pool mounting it lands; empty for none, `null` when the cluster cannot be read); a count is `null` where the cluster cannot be read; for a cluster `create_cluster` made, `admins{users, groups}` it binds as `cluster-admin`, read from its values (`adminsNote` when they cannot be read). Every read is concurrent: the call stays inside the aggregator's deadline. | | `list_releases` | The installation's releases (Release CRs), newest first per provider line: state (`active`, `deprecated`, `wip`, `preview`), Kubernetes version, the cluster chart the release pins and its release chart (`release-` at the release's version, the cluster chart renamed by the releases repository) with `published`, whether the registry lists the tag (`null` with a note when the registry cannot be read); `offered` says whether `create_cluster` creates a cluster of it — active, published, a provider line it offers (`providers`: `aws`, `azure`, `eks`) — and `note` why not; on an installation without the Release CRD an empty list with a `note` naming it | -| `create_cluster` | Create a workload cluster ([giantswarm/giantswarm#37614](https://github.com/giantswarm/giantswarm/issues/37614)): in `org-`, a HelmRelease named after the cluster installing the release chart through an OCIRepository at the release's tag (`release` defaults to the newest active one), reading the installation's `cluster-app-installation-values` first and the cluster's `-values` ConfigMap second — the `values` given with the name, organization, description, release version and cloud `identity` composed on top. The cluster's apiserver trusts the installation's Dex: `global.controlPlane.oidc` is composed from the issuer this server validates tokens against, the audience muster requests at login (`createdClusters.oidc.clientID`, else the first of `muster.mcpServer.auth.requiredAudiences`), the `email` and `groups` claims and the Dex CA of a private certificate, so the tools that call the cluster as the caller are authenticated there; a caller's own `global.controlPlane.oidc` in `values` wins whole, and the answer's `oidc` names what the cluster trusts (`installation`, `values` or `none`). The creator and the organization's admins are `cluster-admin` on the new cluster: the cluster chart's rbac-bootstrap app binds the caller's email (the username the cluster takes from the `email` claim) and the users and groups `org-`'s RoleBindings bind to `cluster-admin` (rbac-operator's `write-all-customer-group` among them), after the bindings the release installs anyway; `global.apps.rbacBootstrap.values.bindings` in `values` replaces them whole (`[]` binds nobody), a caller who may not list the organization's RoleBindings is refused naming that key, and the answer's `rbac` names who is bound (`composed`, `values` or `none`, with a note on who is left out); `list_clusters` reads them back (`admins`). A cluster created before is brought along by a re-run with the same arguments, which updates its `-values`. Refused before any write: a name that is not a DNS label of at most 20 characters or that a Cluster on the installation uses, a release that is not active or whose tag is not published, an organization without the installation's values, in mode `apply` an organization whose tenant ServiceAccount is not bound yet (rbac-operator's `write-all-customer-sa` RoleBinding follows the namespace within minutes), and values that, over the chart's defaults and the installation's, do not match the release chart's own `values.schema.json` (each violation named with its path). Mode `apply` as the caller; a re-run changes nothing; mode `commit` follows | +| `create_cluster` | Create a workload cluster ([giantswarm/giantswarm#37614](https://github.com/giantswarm/giantswarm/issues/37614)): in `org-`, a HelmRelease named after the cluster installing the release chart through an OCIRepository at the release's tag (`release` defaults to the newest active one), reading the installation's `cluster-app-installation-values` first and the cluster's `-values` ConfigMap second — the `values` given with the name, organization, description, release version and cloud `identity` composed on top. The cluster's apiserver trusts the installation's Dex: `global.controlPlane.oidc` is composed from the issuer this server validates tokens against, the audience muster requests at login (`createdClusters.oidc.clientID`, else the first of `muster.mcpServer.auth.requiredAudiences`), the `email` and `groups` claims and the Dex CA of a private certificate, so the tools that call the cluster as the caller are authenticated there; a caller's own `global.controlPlane.oidc` in `values` wins whole, and the answer's `oidc` names what the cluster trusts (`installation`, `values` or `none`). The creator and the organization's admins are `cluster-admin` on the new cluster: the cluster chart's rbac-bootstrap app binds the caller's verified email (the username the cluster takes from the `email` claim) and the users and groups `org-`'s RoleBindings bind to `cluster-admin` (rbac-operator's `write-all-customer-group` among them), after the bindings the release installs anyway; `global.apps.rbacBootstrap.values.bindings` in `values` replaces them whole (`[]` binds nobody), a caller who may not list the organization's RoleBindings is refused naming that key, and the answer's `rbac` names who is bound (`composed`, `values` or `none`, with a note on who is left out); `list_clusters` reads them back (`admins`). A cluster created before is brought along by a re-run with the same arguments, which updates its `-values`. Refused before any write: a name that is not a DNS label of at most 20 characters or that a Cluster on the installation uses, a release that is not active or whose tag is not published, an organization without the installation's values, in mode `apply` an organization whose tenant ServiceAccount is not bound yet (rbac-operator's `write-all-customer-sa` RoleBinding follows the namespace within minutes), and values that, over the chart's defaults and the installation's, do not match the release chart's own `values.schema.json` (each violation named with its path). Mode `apply` as the caller; a re-run changes nothing; mode `commit` follows | | `delete_cluster` | Remove a cluster `create_cluster` created, as the caller, in two calls with the same arguments. The first removes the kserve backend cluster-manager registered for the cluster, then the cluster's HelmRelease (helm-controller uninstalls the cluster and its default apps; the GPU pool, operator and slice releases go with the Cluster through their ownerReference), its OCIRepository and its `-values` ConfigMap, listing those releases (`withCluster`) and the models served on the cluster (`models`). The second, once the Cluster is gone, removes what the uninstall left in `org-`: the cluster's HelmReleases and OCIRepositories rendered by Helm or cluster-manager, and cluster-manager's own source and values. A call that finds nothing of the cluster left answers not found with a structured `{"notFound": {"cluster", "namespace", "nothingLeft": true}}` block as a second text content of the tool error: the removal is complete, readable without parsing the text. Refused before any write: a release cluster-manager did not create, the installation's own cluster, a release in a Flux Kustomization's inventory, a release helm-controller has not reconciled since its last write. Mode `apply`; `commit` follows | | `list_node_pools` | The pools of one cluster — its MachinePools, and the pool releases whose MachinePool is not there yet (right after `create_node_pool`) or gone already (while helm-controller uninstalls it) — with the pool's Kubernetes version and the control plane's as two fields, replicas, instance and accelerator types, the owning HelmRelease, and the pool's lifecycle: `phase` is `creating` (release not Ready, or MachinePool not created or not ready), `ready` (every step done; `readyReplicas` may be 0 at scale-to-zero), `scaling` (NodeClaims launching or terminating, nodes registering, or a node Karpenter could not launch), `removing` (release or MachinePool deleted, or a teardown re-run pending) or `failed` (release `Ready=False`, the reason in the step); `steps[]{name, state, since, finishedAt, message}` are `release` (the pool release Ready), `machinePool` (its Ready condition, else `infrastructureReady`) and `nodes` (Karpenter's NodeClaims of the pool on the cluster — launching, ready, terminating, with counts, a terminating node named with its deletion time: `0 NodeClaim(s) launching, 0 ready, 1 terminating — ip-… terminating since 2026-09-18T03:36:08Z (Karpenter drains the node and terminates its instance; the NodeClaim goes once the instance is terminated, minutes later)` —, on a GPU pool of cluster-manager's the ready nodes that hold nothing (no GPU workload, no predictor) named idle since their last pod left (`1 node(s) ready (aws:///…), 1 idle since 2026-09-17T22:55:41Z (ip-…): delete_node_pool removes an idle node with the pool`) and a MachinePool still listing instances the cluster no longer has said so (`0 nodes on the cluster: the MachinePool still lists 1 gone (…), its list follows within minutes`), else `readyReplicas` of `replicas` where the cluster cannot be read; a node Karpenter could not launch keeps the step `inProgress` since the last refusal, never `done` with none, with the refusal in a line — every size and every zone refused: the pool's sizes and every zone it may use (its `pool.zones` pin, else the cluster's node-subnet zones, the `AWSCluster`'s subnets tagged for nodes) when the reason is `InsufficientCapacityError`, since Karpenter gives a claim up for capacity only once every offering it asked for was refused and cuts its event after the first fleet error (giantswarm/cluster-manager#75); AWS's per-error hint of zones with capacity relayed only for zones outside the refused set, the next error of the same answer refusing the zone the first one named —, Karpenter's reason and message verbatim, and the way around it, naming what decided where the launch was tried (giantswarm/cluster-manager#65) and, as candidates for `zones`, only the cluster's node-subnet zones the answer did not refuse: `1 NodeClaim could not launch, the last (-5hpxb) at 2026-09-18T12:14:47Z — InsufficientInstanceCapacity for every size of the pool (g6e.2xlarge, g6e.4xlarge, g6e.8xlarge) in eu-central-1b, the zone the pool is pinned to (InsufficientCapacityError); Karpenter: "creating instance, insufficient capacity, …"; it retries while a pod waits — the pool is pinned to eu-central-1b — the model cache claim model-serving/hf-cache (volume pvc-…) lives in eu-central-1b and the pool's slice mounts it: re-run create_node_pool on the pool with zones naming one zone with capacity — not refused in this answer: eu-central-1a, eu-central-1c (the cluster's other node-subnet zones; capacity there is not promised) — with the cache on its slice then mounts that zone's model cache claim (the one Bound there, else hf-cache-, created there and kept; the weights downloaded once more), with cache false it serves from the node's local disk; wider sizes or another accelerator (a re-run of create_node_pool) give it more to choose from` — for a pool with no pin `… in every zone the pool may use (eu-central-1a, eu-central-1b, eu-central-1c — the cluster's node-subnet zones; the pool has no pin) …; it retries while a pod waits — every zone the pool may use was refused in the same answer, so there is no zone to move to (zones on a re-run would only pin the pool to one of them); Karpenter retries every few minutes (its unavailable-offering cache is three minutes) and the pool launches its node on its own once the family has capacity again; wider sizes or another accelerator …` — read from the NodeClaims that carry the refusal (`Launched` or `Registered` `False`) and, for a claim Karpenter deleted at once for want of capacity, from its Warning event on the claim in the `default` namespace, which outlives the claim for the API server's event TTL; a refusal counts until Karpenter creates a claim after it), each `pending`, `inProgress`, `done` or `failed`, `since` the condition's `lastTransitionTime` or the object's creation (RFC3339), `finishedAt` for a done step. A pool created with `prewarm` carries a fourth step, `prewarm`: the placeholder Job's pod in the release namespace — `pending` while the pool release is not Ready and the Job does not exist (the chart creates it with the release's install; the release step says where the install stands), `inProgress` while the pod is `pending` (the first node launching, the scheduler's message beside it — or, when Karpenter could not launch it, the refusal in a line: `the placeholder waits for the pool's first node, which Karpenter could not launch — InsufficientInstanceCapacity for g6e.2xlarge in eu-central-1a (the nodes step carries Karpenter's message)`), `holding node ` or being preempted, `done` once `preempted` by the first workload or `finished` (the hold ended without one), `failed` when no node came within the Job's deadline (naming Karpenter's refusal when the nodes step has one), and `done` with a message when the Job is absent after the release installed (its TTL removed it, or prewarm was set on an existing pool); the step never decides the phase, and a pool without the option shows no such step. A pool under `delete_node_pool` stays listed with `phase: removing`, `deleting: true` and `pending[]` — the teardown's objects still present, `pending` or `terminating` — until its HelmRelease is gone, and by its MachinePool — `removing`, the terminating node named in the `nodes` step — until Karpenter's NodeClaim has gone with the terminated instance, minutes later (the release's uninstall does not wait for it; see `create_node_pool`). `backend` names the cluster's kserve backend with model-manager as `list_clusters`' `serving.readiness.backend` does: the backend a model on the cluster's pools is checked and loaded through. Every read is concurrent: the call stays inside the aggregator's deadline. | | `create_node_pool` | Create a GPU node pool for a cluster, or update the pool of that name: the pool release of the `gpu-node-pool` chart (HelmRelease and OCIRepository in `org-`, following the chart from `compose.MinPoolChartVersion` to the next major, or pinned exactly with `chartVersion`) with the Kubernetes version and Flatcar machine image of the cluster's current release — refused when the release runs ahead of the control plane — and a credential-free snapshot of the cluster's settings (registry credentials go into a `valuesFrom` Secret). A pool node boots with the NVIDIA driver from Flatcar's prebuilt, release-matched `nvidia-drivers` system extension (gpu-node-pool 0.7.4 pinned; the chart's default `pool.nvidiaDriver.source: flatcar-sysext` since 0.6.0; cluster-manager writes no `nvidiaDriver` block): the bootstrap enables the extension in `/etc/flatcar/enabled-sysext.conf`, the OS downloads it for its own version right after Ignition and merges it into `/usr` before the system starts, and the CDI unit loads the modules, creates the device nodes and writes the CDI specification the toolkit serves — no driver is built at boot. The extension ships with Flatcar 4344.0.0 and newer: a cluster whose release pins an older Flatcar is refused before anything is composed, naming its version and the way out — the pool needs a cluster release with a newer Flatcar (the chart's `image-build` source is not offered). Its `/var/lib` — containerd's image unpacks, the kubelet's directories, the pods' emptyDirs (a model's weights where no cache claim is mounted) and the containers' writable layers — is the node's NVMe instance store (gpu-node-pool 0.7.0, the chart's default `pool.volumes.libSource: instance-store`; cluster-manager writes no `volumes` block): the bootstrap formats the first `Amazon EC2 NVMe Instance Storage` device as the `lib` filesystem and mounts it at `/var/lib`, no gp3 volume is provisioned for it, and the EC2NodeClass carries `instanceStorePolicy: RAID0` so Karpenter counts the store as the node's ephemeral storage. The store is local to the host, included in the instance price and goes with the node — nothing of a pool node outlives it. Every size of the curated families has one — 250 GB on an `xlarge`, 450 on a `2xlarge`, 600 on a `4xlarge`; the `8xlarge` of g6 and g6e carry two devices of 450 GB and `/var/lib` gets the first, g5's and g4dn's `8xlarge` one of 900; g4dn's smaller sizes 125 and 225 GB — so no size is refused, and the answer's `sizes[]` rows name it (`instanceStoreGB` across `instanceStoreDisks` devices of `instanceStoreDiskGB`; the last is what a node gives its pods). Its containerd runs with an unlimited locked-memory limit (gpu-node-pool 0.7.1, the bootstrap's `memlock.conf` drop-in, `LimitMEMLOCK=infinity`): a container inherits containerd's limit and has no `CAP_IPC_LOCK` to raise it, so under the unit's 8 MB default a serving runtime that `mlock()`s its weights died at engine start (giantswarm/agent-platform#564). `mode: apply` lands the objects as the caller, owned by the `Cluster`; `dryRun` returns the manifests and, on a re-run, the difference. A GitOps-owned object is never patched. When no GPU operator runs on the cluster (detected as the caller on the cluster itself), the `-gpu-operator` release of the catalog's `gpu-operator` chart comes with the pool, configured from the two-row table read off the nodes (Flatcar: driver and toolkit off — the extension carries the driver, the image the toolkit, and the pool chart's bootstrap makes the toolkit serve them, see the chart's image contract; `nvidia.com/gpu.deploy.driver=pre-installed`: toolkit on; anything else refused), with Node Feature Discovery's worker pinned to the cluster's GPU pools (`gpu-operator.node-feature-discovery.worker.affinity`: `giantswarm.io/machine-pool In [-, …]`, the pool being created included; a re-run moves the pin) — the worker is what asserts `nvidia.com/gpu.present`, so GPU-family nodes of the general pool without a driver get neither the label nor the operands — and polling every 10 s (`gpu-operator.node-feature-discovery.worker.config.core.sleepInterval: 10s`; upstream's default is 60 s): the operator rolls the toolkit, device plugin and GPU feature discovery onto a node only once the worker has labelled it, so on a node that joins for one predictor a minute's poll was most of the ~100 s between `Ready` and `nvidia.com/gpu` allocatable; the rest of `worker.config` (the chart's PCI device class whitelist) merges in unchanged. On a pool node the release runs the validator's driver and toolkit validations (what proves the image's driver and CDI) without the validator's workload pods (`validator.cuda.env` and `validator.plugin.env` carry `WITH_WORKLOAD=false`; the chart's default starts a `nvidia-cuda-validator-*` pod on every fresh node beside the device plugin's start), the device plugin (what advertises `nvidia.com/gpu`, once the toolkit validation has written `toolkit-ready`) and GPU feature discovery (model-manager reads its `nvidia.com/gpu.count`, `.memory` and `.product` labels for its node budget) — and not mig-manager (`migManager.enabled: false`: the pool's accelerators have no MIG, and the operator schedules it on MIG-capable GPUs only) nor the DCGM exporter (`dcgmExporter.enabled: false`: nothing scrapes it out of the box, and on a fresh node it was an image pull and a pod initialising DCGM on the GPU while the device plugin brought the GPU up; an installation whose observability scrapes it turns it on with the chart's `gpuOperator.dcgmExporter` / `--gpu-operator-dcgm-exporter`). The worker and the operands tolerate the node's start-up taints that DaemonSets remove (`gpu-operator.node-feature-discovery.worker.tolerations` and `gpu-operator.daemonsets.tolerations`: the chart's defaults plus `node.cluster.x-k8s.io/uninitialized` and `ebs.csi.aws.com/agent-not-ready`, `operator: Exists`), so they are created as soon as the kubelet registers and the CNI is up and pull their images before the runtime pre-pull saturates the node — with the defaults alone the worker's pod waited for the taint remover and the EBS CSI node plugin to pull and run, 12–49 s after `Ready` on an installation, and `nvidia.com/gpu` was allocatable 73–108 s after it; not the Cilium taint (the operands use the pod network and need the CNI before their sandbox anyway) and never `karpenter.sh/unregistered` (Karpenter removes it itself at registration). A release cluster-manager does not compose keeps the chart's defaults; an operator the platform's release or a person provides is never re-created. When nothing provides serving on the cluster, the cluster's `-agent-platform` slice release comes with the pool too (see `enable_model_serving`), updated in place on a re-run. After the pool, the cluster's own kserve backend is registered with model-manager — one per serving cluster: `kserve` (ConfigMap `model-backend-kserve`) for the installation's own cluster, `kserve-` (`model-backend-kserve-`) for a workload cluster, so pools on two workload clusters of one installation coexist, each cluster's models checked and loaded through its own backend (`backend.backend` in the answer); a workload cluster still registered under the shared `kserve` name by an earlier cluster-manager moves to its own name on the write, the shared document removed, and the own cluster's pool is refused while a workload cluster holds that name, naming the cluster and the re-run that frees it — the document naming every pool's instance shapes (the `sizes` below), so model-manager's `check_fit` judges a preset against a pool before it has a node and `load_model` refuses what no size hosts (model-manager 0.23.7 or newer): the one pool's as `spec.kserve.gpuPool.instances`, several pools' as `spec.kserve.gpuPools`, keyed by the pool's release name (the node label `giantswarm.io/machine-pool`, `-`), which model-manager judges and pins a model against (giantswarm/model-manager#152); `delete_node_pool` of a pool that is not the last re-writes it for the pools that remain. The answer lists the pool's sizes (`sizes`: the node as AWS lists it, its instance store and what it leaves a predictor after the kubelet's reservations and the fleet's daemonsets — a `g6.xlarge` leaves 3 vCPU / 11.9 GiB and gives its pods 250 GB of local disk) and, where the cluster publishes serving presets, the smallest size that hosts each (`presetFit`); a preset the accelerator could serve but no size of the pool hosts is a warning (`warnings`) — its predictor would sit Pending while Karpenter refuses every size (giantswarm/agent-platform#502). A size the family does not have is refused. `prewarm: true` launches the pool's first node with the release instead of with the first predictor (the chart's `pool.prewarm.enabled`): a one-shot placeholder Job in the release namespace holds one GPU at negative priority until the first workload preempts it, or its hold (the chart's default, 15 minutes) ends and Karpenter consolidates the empty node — a model named up front is served minutes earlier. The pool release does not wait for the chart's Jobs (`install`/`upgrade.disableWaitForJobs: true`; the operator and slice releases keep Helm's wait): Helm counts a Job as ready only once it completes, and the placeholder is meant to run until a workload preempts it — waited for, the install ran into its timeout and was uninstalled. Nor does its uninstall wait for the chart's objects to be gone (`uninstall.disableWait: true`; `uninstall.timeout` stays the default): the MachinePool goes only when EC2 has terminated the pool's last instance, minutes after its NodeClaim's delete and longer than helm-controller's timeout — waited for, the uninstall failed (`UninstallFailed`) and the release went with the retry minutes later; the MachinePool and the instance terminate on their own, `list_node_pools` naming the terminating node until they are gone. Only for the installation's own pool, where the release namespace is on the cluster the nodes join; a workload cluster's pool is refused, naming why. The Job is created with the release's install only: a re-run flips the value in place (`would-update`) but never launches a placeholder again; `prewarm: false` removes the block. **Where the pool runs is the person's, and the zone brings its own cache** (giantswarm/cluster-manager#65, #71): `zones: ["eu-central-1a"]` pins the pool's nodes to the named availability zone — `pool.zones` on the pool release, a `topology.kubernetes.io/zone In` requirement on the Karpenter NodePool, placeholder and predictors alike. The zone is checked against the cluster's node subnets (the `AWSCluster`'s `spec.network.subnets` tagged `giantswarm.io/role: nodes`, the ones the chart's EC2NodeClass selects): a zone the cluster has no node subnet in is refused, naming the zones it has. And the pool's serving slice mounts **that zone's model cache claim**: a cache claim outlives the pool and is one EBS volume, bound in one zone by the first predictor that mounted it (giantswarm/cluster-manager#59) — a pool whose nodes come up elsewhere strands the next predictor Pending, and one zonal claim pinned every pool to a zone that had no capacity for the accelerator —, so the cache is one claim per zone: the slice release carries `modelServing.cache.pvc.name` with the claim of the zone — the `hf-cache*` claim Bound there (the one claim of before, `hf-cache`, in the zone its first predictor was in — reused, not doubled), else `hf-cache-` (`-`, the base being `--serving-cache-claim`), which the connectivity chart creates where it does not exist and keeps: the first predictor of the pool binds it to a volume in the zone, a later pool in the zone reuses it, pools in other zones use theirs. **Any combination of zones stands with the cache on, and the pool follows its cache** (giantswarm/cluster-manager#79): with several zones the nodes are pinned to the zones named and the slice mounts the base claim, `hf-cache`, which the first predictor binds to a volume in its node's zone — one of the named — so that from then on every predictor mounting it runs there (the scheduler and Karpenter place a pod's node where its volume is), and a re-run of the same `create_node_pool` pins the pool's nodes to that zone; a claim Bound in one of the named zones already pins the pool to it at once, `zonesNote` naming the zones named, the one that stands and the ways out (`cache: false` to run across the zones, one zone alone to serve from it with its own claim). Claims Bound in several of the named zones are refused (`refused{cacheClaims{claims, remedies}}`: the slice mounts one, none is chosen for you), as is the base claim Bound outside every named zone (`refused{cacheZone{claim, claimZone, zones, remedies}}`: name its zone among the zones, one zone, or `cache: false`); a claim named after the one zone named but Bound elsewhere is refused as before (the ways out being to name the claim's zone, to pass `cache: false`, or to remove the claim). No claim is created per named zone up front: a claim binds only when a pod mounts it, and unbound claims are noise. Without `zones` the claims of the serving namespace decide: exactly one `hf-cache*` claim — Bound, the pool's nodes are pinned to its volume's zone (`pool.zones: [eu-central-1b]`) and the slice mounts it; not Bound yet, or its volume naming no zone (a network file system), nothing is pinned and `zonesNote` says what was found; its volume not readable as you, nothing is pinned and a `warnings` entry says why — never a guessed zone —; no claim, no `zones` block and nothing said (the chart creates `hf-cache`, bound by the first predictor); several claims are refused naming each with its zone and phase (`refused{cacheClaims{claims, remedies}}`): name `zones`. The claims not listable as you pin nothing and are a `warnings` entry. The answer names the pin and the claim: `zones`, `zonesNote` (`nodes pinned to eu-central-1a, the zone named on create; the slice mounts the zone's model cache claim model-serving/hf-cache-eu-central-1a, which does not exist yet: …` or `nodes pinned to eu-central-1b: the model cache (claim model-serving/hf-cache, volume pvc-…) lives there …`), `cache{enabled, claim, note}` (the claim the slice mounts and where it stands), `cacheClaim{namespace, name, phase, volume, zone}` (that claim as read on the cluster as you; `null` while it does not exist yet) and `cacheClaims[]` (every `hf-cache*` claim of the serving namespace as read); `dryRun` shows it, a re-run on an existing pool moves the pin and the claim (`would-update`, naming `spec.values.modelServing.cache.pvc.name`). The slice release is the cluster's one: its predictors mount the claim the last `create_node_pool` with the cache on named, so pools in several zones at once serve from the last-named zone's claim, and a predictor of another zone's pool restarted after that call waits for a node in the claim's zone. `cache` is off by default — without it the slice keeps its setting where the cluster's slice release runs, and a first slice serves without a cache (a claim is billed every month it exists and is never created unasked; `cache: true` is the opt-in) —; `cache: false` serves this pool's slice without the model cache: `modelServing.cache.enabled: false` on the `-agent-platform` release, so no claim is applied or mounted, every predictor downloads its weights into its pod's ephemeral storage (the node's local disk) at each start, no zone follows from a claim — the zones named stand, several of them allowed, or nothing pins — and the existing claims are left as they are (Helm keeps them); the answer says so (`cache{enabled, claim, note}`, the note naming the existing claims' state), a re-run with a changed value is the slice's upgrade (`would-update` naming `spec.values.modelServing.cache.enabled`), and it is refused where someone else provides serving — the setting is that layer's. A family not offered in a pinned zone fails its launch visibly, named in `list_node_pools`' `nodes` step with what pinned the pool and the re-run that moves it. `LLMInferenceServiceConfig`s a serving layer that went left terminating in the release namespace are removed first, finalizer and all, when no llm-d controller runs (`objects` lists them, `warnings` says why), so the slice's release creates them afresh instead of adopting and losing them. The slice's serving runtime is the slim one (`llm-d-slim/`) when every GPU pool of the cluster is A10G, L4 or L40S, else the chart's `llm-d-fast/`. `serving` (default `true`) is whether the pool serves models: `false` creates a plain GPU pool — the pool and, where none runs, the GPU operator — composing no slice, registering no backend and reading nothing only serving needs (the `ClusterIssuer`, the serving runtime, the presets); refused with `cache` true and where cluster-manager serves on the cluster already. Where the slice is composed, a `ClusterIssuer` the person may not read is refused naming the right (`get` on `clusterissuers.cert-manager.io` at cluster scope) and the subjects the cluster binds as cluster-admin. | diff --git a/cmd/serve.go b/cmd/serve.go index 9f6696f..6bcd039 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -153,7 +153,7 @@ func runServe(ctx context.Context, o *serveOptions) error { return fmt.Errorf("oauth: %w", err) } } - if err := validateGitHubExchange(o, oauthSettings.Dex != nil); err != nil { + if err := validateGitHubExchange(o, oauthSettings); err != nil { return err } @@ -292,12 +292,19 @@ func (o *serveOptions) clusterOIDC(settings oauthconfig.Settings, log *slog.Logg return nil, nil } var issuer, caFile string - switch provider, ok := openIDProvider(settings.TrustedIssuers); { + switch { case settings.Dex != nil && settings.Dex.IssuerURL != "": issuer, caFile = settings.Dex.IssuerURL, os.Getenv("OAUTH_DEX_CA_FILE") - case ok: + case settings.Google == nil: + provider, present, err := singleOpenIDProvider(settings.TrustedIssuers) + if err != nil { + return nil, err + } + if !present { + log.Warn("created clusters trust no identity provider: configure a Dex provider or one trusted issuer marked openIDProvider") + return nil, nil + } issuer = provider.Issuer - var err error if caFile, err = trustedIssuerCAFile(os.Getenv("OAUTH_TRUSTED_ISSUERS"), issuer); err != nil { return nil, err } @@ -316,14 +323,18 @@ func (o *serveOptions) clusterOIDC(settings oauthconfig.Settings, log *slog.Logg return out, nil } -// openIDProvider is the trusted issuer people sign in with, if one is marked. -func openIDProvider(issuers []oauthserver.TrustedIssuer) (oauthserver.TrustedIssuer, bool) { +func singleOpenIDProvider(issuers []oauthserver.TrustedIssuer) (oauthserver.TrustedIssuer, bool, error) { + var provider oauthserver.TrustedIssuer + present := false for _, issuer := range issuers { if issuer.OpenIDProvider { - return issuer, true + if present { + return oauthserver.TrustedIssuer{}, false, errors.New("OAUTH_TRUSTED_ISSUERS must mark exactly one openIDProvider to select the identity provider") + } + provider, present = issuer, true } } - return oauthserver.TrustedIssuer{}, false + return provider, present, nil } // trustedIssuerCAFile is the caFile of the OAUTH_TRUSTED_ISSUERS entry for @@ -352,17 +363,24 @@ func (o *serveOptions) gitHubExchangeConfig() server.GitHubExchangeConfig { return server.GitHubExchangeConfig{TokenEndpoint: o.githubExchangeEndpoint, ClientID: o.githubExchangeClient, ClientIDFile: o.githubExchangeClientFile, ClientSecretFile: o.githubExchangeSecretFile, Audience: o.githubExchangeAudience, CAFile: o.githubExchangeCAFile, APIURL: o.githubAPIURL} } -// validateGitHubExchange checks the token exchange options: the exchange's -// subject is the caller's ID token, so it needs Dex and downstream OAuth. -func validateGitHubExchange(o *serveOptions, dex bool) error { +// The exchange uses the caller's provider ID token and downstream authorization. +func validateGitHubExchange(o *serveOptions, settings oauthconfig.Settings) error { if o.githubExchangeEndpoint == "" { if o.githubExchangeClient != "" || o.githubExchangeClientFile != "" || o.githubExchangeSecretFile != "" || o.githubExchangeAudience != "" || o.githubExchangeCAFile != "" { return errors.New("GitHub token exchange options require --github-token-exchange-endpoint") } return nil } - if !o.oauthEnabled || !o.downstreamOAuth || !dex { - return errors.New("GitHub token exchange requires Dex OAuth and downstream OAuth") + hasProvider := settings.Dex != nil && settings.Dex.IssuerURL != "" + if !hasProvider && settings.Google == nil { + _, present, err := singleOpenIDProvider(settings.TrustedIssuers) + if err != nil { + return err + } + hasProvider = present + } + if !o.oauthEnabled || !o.downstreamOAuth || !hasProvider { + return errors.New("GitHub token exchange requires OAuth, downstream OAuth and an OpenID Provider") } return o.gitHubExchangeConfig().Validate() } diff --git a/cmd/serve_test.go b/cmd/serve_test.go index f635503..a72a302 100644 --- a/cmd/serve_test.go +++ b/cmd/serve_test.go @@ -19,6 +19,7 @@ import ( ) func TestValidateGitHubExchange(t *testing.T) { + dexSettings := oauthconfig.Settings{Dex: &dex.Config{IssuerURL: "https://dex.example.test"}} exchange := func() *serveOptions { return &serveOptions{ // #nosec G101 -- configuration fixture with a path, no secret value oauthEnabled: true, downstreamOAuth: true, @@ -27,24 +28,28 @@ func TestValidateGitHubExchange(t *testing.T) { githubAPIURL: server.DefaultGitHubAPIURL, } } - require.NoError(t, validateGitHubExchange(&serveOptions{}, true), "no exchange configured") - require.NoError(t, validateGitHubExchange(exchange(), true)) - require.ErrorContains(t, validateGitHubExchange(exchange(), false), "requires Dex OAuth and downstream OAuth", "the subject token must be a Dex token") + require.NoError(t, validateGitHubExchange(&serveOptions{}, dexSettings), "no exchange configured") + require.NoError(t, validateGitHubExchange(exchange(), dexSettings)) + resourceOnly := oauthconfig.Settings{TrustedIssuers: []oauthserver.TrustedIssuer{{Issuer: "https://dex.example.test", OpenIDProvider: true}}} + require.NoError(t, validateGitHubExchange(exchange(), resourceOnly)) + resourceOnly.TrustedIssuers = append(resourceOnly.TrustedIssuers, oauthserver.TrustedIssuer{Issuer: "https://other.example.test", OpenIDProvider: true}) + require.ErrorContains(t, validateGitHubExchange(exchange(), resourceOnly), "exactly one openIDProvider") + require.ErrorContains(t, validateGitHubExchange(exchange(), oauthconfig.Settings{}), "requires OAuth, downstream OAuth and an OpenID Provider", "the subject token must be a Dex token") for name, scenario := range map[string]struct { change func(*serveOptions) want string }{ "option without endpoint": {func(o *serveOptions) { o.githubExchangeEndpoint = "" }, "require --github-token-exchange-endpoint"}, - "without OAuth": {func(o *serveOptions) { o.oauthEnabled = false }, "requires Dex OAuth and downstream OAuth"}, - "without downstream OAuth": {func(o *serveOptions) { o.downstreamOAuth = false }, "requires Dex OAuth and downstream OAuth"}, + "without OAuth": {func(o *serveOptions) { o.oauthEnabled = false }, "requires OAuth, downstream OAuth and an OpenID Provider"}, + "without downstream OAuth": {func(o *serveOptions) { o.downstreamOAuth = false }, "requires OAuth, downstream OAuth and an OpenID Provider"}, "plain HTTP endpoint": {func(o *serveOptions) { o.githubExchangeEndpoint = "http://muster.example/oauth/token" }, "HTTPS token endpoint"}, "without audience": {func(o *serveOptions) { o.githubExchangeAudience = "" }, "an audience"}, } { t.Run(name, func(t *testing.T) { options := exchange() scenario.change(options) - require.ErrorContains(t, validateGitHubExchange(options, true), scenario.want) + require.ErrorContains(t, validateGitHubExchange(options, dexSettings), scenario.want) }) } } @@ -94,6 +99,14 @@ func TestClusterOIDC(t *testing.T) { require.Equal(t, want("https://idp.example.com"), got, "without Dex settings: the trusted issuer marked openIDProvider, with its caFile") require.Empty(t, output.String()) + for _, issuers := range [][]oauthserver.TrustedIssuer{ + {{Issuer: "https://one.example.test", OpenIDProvider: true}, {Issuer: "https://two.example.test", OpenIDProvider: true}}, + {{Issuer: "https://two.example.test", OpenIDProvider: true}, {Issuer: "https://one.example.test", OpenIDProvider: true}}, + } { + _, err := options.clusterOIDC(oauthconfig.Settings{TrustedIssuers: issuers}, log) + require.ErrorContains(t, err, "exactly one openIDProvider") + } + got, err = options.clusterOIDC(oauthconfig.Settings{TrustedIssuers: openIDProvider[:1]}, log) require.NoError(t, err) require.Nil(t, got, "no OpenID Provider: created clusters trust none") diff --git a/docs/development.md b/docs/development.md index 4390a70..b37f7a1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,18 @@ # Developing on cluster-manager +## Identity and cluster creation + +Creator RBAC uses an email username only when the provider verified that email. +An unverified or absent email leaves the creator out of the generated binding +and explains the omission in the result's RBAC note. + +Without a local Dex provider, automatic cluster OIDC configuration requires one +unambiguous trusted issuer marked `openIDProvider`. Multiple marked issuers are +refused rather than selecting an authority by list order. This configuration +flag permits provider ID-token recovery; it is not a JWT token-type assertion. + +## Checks + Run `go test ./...` and the repository's pre-commit checks before submitting changes. Caller-client construction failures stop the operation and never select ServiceAccount clients. diff --git a/helm/cluster-manager/README.md b/helm/cluster-manager/README.md index bf864fa..7ca4e94 100644 --- a/helm/cluster-manager/README.md +++ b/helm/cluster-manager/README.md @@ -54,10 +54,10 @@ from the platform identity contract (`global.identity`, `global.domain`). | oauth.resourceServer.resource | string | `""` | The main protected resource, by its full URL (`OAUTH_RESOURCE`). Empty uses the issuer. | | oauth.resourceServer.additionalResources | list | `[]` | Further protected resources on the same origin, each by its full URL (`OAUTH_ADDITIONAL_RESOURCES`). The MCP endpoint is always a protected resource. | | oauth.resourceServer.authorizationServers | list | `[]` | Issuer identifiers the resource metadata advertises (`OAUTH_AUTHORIZATION_SERVERS`, RFC 9728 `authorization_servers`): this server's issuer or a trusted issuer. Empty advertises this server's issuer; required with `authorizationServer.enabled` false, since MCP clients find the authorization server here. | -| oauth.resourceServer.trustedIssuers | list | `[]` | The issuers whose JWTs are accepted (`OAUTH_TRUSTED_ISSUERS`). A trust anchor: set it only from the release's own values or a GitOps-managed ConfigMap that only installation administrators write. Each entry: `issuer`, `jwksURI` and `audiences` (required), `subjectClaim` (`sub` or `email`), `acceptedTypHeaders`, `allowedClaims`, `allowPrivateIPJWKSHosts`, `openIDProvider` (true for the provider people sign in with, whose bearers are their ID tokens), and `certificateAuthority` with a `secretKeyRef` or `configMapKeyRef` (`name`, `key`). Empty trusts the provider people sign in with (`authorizationServer.upstream`) as `openIDProvider`: its ID tokens are accepted as bearer tokens, a deviation from MCP's audience rule until per-backend tokens (ID-JAG, giantswarm/giantswarm#39102). They are accepted for the client people sign in with (`authorizationServer.upstream.client.id`, or the deprecated `oauth.trustedAudiences`) and `muster.mcpServer.auth.requiredAudiences`, in that order and without duplicates. | +| oauth.resourceServer.trustedIssuers | list | `[]` | The issuers whose JWTs are accepted (`OAUTH_TRUSTED_ISSUERS`). A trust anchor: set it only from the release's own values or a GitOps-managed ConfigMap that only installation administrators write. Each entry: `issuer`, `jwksURI` and `audiences` (required), `subjectClaim` (`sub` or `email`), `acceptedTypHeaders`, `allowedClaims`, `allowPrivateIPJWKSHosts`, `openIDProvider` (true for the provider whose accepted bearers are used as ID tokens), and `certificateAuthority` with a `secretKeyRef` or `configMapKeyRef` (`name`, `key`). Empty trusts the provider people sign in with (`authorizationServer.upstream`) as `openIDProvider`: its ID tokens are accepted as bearer tokens, a deviation from MCP's audience rule until per-backend tokens (ID-JAG, giantswarm/giantswarm#39102). They are accepted for `oauth.trustedAudiences`, else `global.identity.clientId`, else `authorizationServer.upstream.client.id`, together with `muster.mcpServer.auth.requiredAudiences`, in that order and without duplicates. | | oauth.resourceServer.requireResourceAccessTokens | bool | `false` | Accept only tokens whose audience names this server's resource (`OAUTH_REQUIRE_RESOURCE_ACCESS_TOKENS`), as MCP requires. Off while the platform forwards ID tokens (giantswarm/giantswarm#39102). | | oauth.authorizationServer.enabled | bool | `true` | Run the authorization server. Off makes cluster-manager a resource server only (`OAUTH_ENABLE_AUTHORIZATION_SERVER=false`). | -| oauth.authorizationServer.issuer | string | `""` | Public base URL of this server, the issuer of its tokens and metadata (`OAUTH_ISSUER`; https, or http on loopback). Empty uses the deprecated `oauth.baseURL`, else `https://.`. | +| oauth.authorizationServer.issuer | string | `""` | Public base URL of this server, the issuer of its tokens and metadata (`OAUTH_ISSUER`; https, or http on loopback). Empty uses the deprecated `oauth.baseURL`, else `https://.`. Required also with this authorization server disabled: the library uses this public base URL for resource metadata; it does not advertise an active AS. | | oauth.authorizationServer.upstream.type | string | `""` | The OpenID Provider people sign in with: `dex` or `google` (`OAUTH_PROVIDER`). Empty uses the deprecated `oauth.provider`, else `dex`. | | oauth.authorizationServer.upstream.issuer | string | `""` | Dex issuer URL. Empty uses the deprecated `oauth.dex.issuerURL`, else `global.identity.issuerUrl`. | | oauth.authorizationServer.upstream.client.id | string | `""` | OAuth client ID at the provider. Empty uses the deprecated `oauth.dex.clientID` or `oauth.google.clientID`, else `global.identity.clientId` (dex). | diff --git a/helm/cluster-manager/templates/_helpers.tpl b/helm/cluster-manager/templates/_helpers.tpl index bfd4234..9319ff6 100644 --- a/helm/cluster-manager/templates/_helpers.tpl +++ b/helm/cluster-manager/templates/_helpers.tpl @@ -201,7 +201,7 @@ A CA is a mount: {volume, secret or configMap, key, dir}; caFile is dir/key. {{- end -}} {{- if not $issuers -}} {{- $audiences := list -}} -{{- range concat ($o.trustedAudiences | default (list ($clientID | default (dig "clientId" "" $g)))) (include "cluster-manager.requiredAudiences" . | fromJsonArray) -}} +{{- range concat ($o.trustedAudiences | default (list (dig "clientId" "" $g | default $clientID))) (include "cluster-manager.requiredAudiences" . | fromJsonArray) -}} {{- if and . (not (has . $audiences)) }}{{ $audiences = append $audiences . }}{{ end -}} {{- end -}} {{- if and $audiences $upstreamIssuer -}} diff --git a/helm/cluster-manager/tests/oauth_values_layout_test.yaml b/helm/cluster-manager/tests/oauth_values_layout_test.yaml index ad78ce7..b2fca5a 100644 --- a/helm/cluster-manager/tests/oauth_values_layout_test.yaml +++ b/helm/cluster-manager/tests/oauth_values_layout_test.yaml @@ -15,6 +15,26 @@ set: certificateAuthority: secretKeyRef: {name: dex-ca, key: bundle.pem} tests: + - it: preserves the platform audience with a deprecated manager client ID + set: + oauth.authorizationServer.upstream.client.id: "" + oauth.dex.clientID: manager-client + global.identity.clientId: platform-client + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_ID, value: manager-client} + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.test"],"audiences":["platform-client"],"caFile":"/etc/cluster-manager/idp-ca/bundle.pem","issuer":"https://dex.example.test","jwksURI":"https://dex.example.test/keys","openIDProvider":true}]' + - it: keeps explicit trusted audiences authoritative + set: + global.identity.clientId: platform-client + oauth.trustedAudiences: [explicit-client] + asserts: + - equal: + path: spec.template.spec.containers[0].env[?(@.name=="OAUTH_TRUSTED_ISSUERS")].value + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.test"],"audiences":["explicit-client"],"caFile":"/etc/cluster-manager/idp-ca/bundle.pem","issuer":"https://dex.example.test","jwksURI":"https://dex.example.test/keys","openIDProvider":true}]' - it: renders the upstream from the layout asserts: - contains: diff --git a/helm/cluster-manager/values.schema.json b/helm/cluster-manager/values.schema.json index 7a37281..4eec2ca 100644 --- a/helm/cluster-manager/values.schema.json +++ b/helm/cluster-manager/values.schema.json @@ -366,7 +366,7 @@ }, "issuer": { "type": "string", - "description": "Public base URL of this server, the issuer of its tokens and metadata (`OAUTH_ISSUER`; https, or http on loopback). Empty uses the deprecated `oauth.baseURL`, else `https://.`." + "description": "Public base URL of this server, the issuer of its tokens and metadata (`OAUTH_ISSUER`; https, or http on loopback). Empty uses the deprecated `oauth.baseURL`, else `https://.`. Required also with this authorization server disabled: the library uses this public base URL for resource metadata; it does not advertise an active AS." }, "storage": { "type": "object", @@ -552,7 +552,7 @@ }, "trustedIssuers": { "type": "array", - "description": "The issuers whose JWTs are accepted (`OAUTH_TRUSTED_ISSUERS`). A trust anchor: set it only from the release's own values or a GitOps-managed ConfigMap that only installation administrators write. Each entry: `issuer`, `jwksURI` and `audiences` (required), `subjectClaim` (`sub` or `email`), `acceptedTypHeaders`, `allowedClaims`, `allowPrivateIPJWKSHosts`, `openIDProvider` (true for the provider people sign in with, whose bearers are their ID tokens), and `certificateAuthority` with a `secretKeyRef` or `configMapKeyRef` (`name`, `key`). Empty trusts the provider people sign in with (`authorizationServer.upstream`) as `openIDProvider`: its ID tokens are accepted as bearer tokens, a deviation from MCP's audience rule until per-backend tokens (ID-JAG, giantswarm/giantswarm#39102). They are accepted for the client people sign in with (`authorizationServer.upstream.client.id`, or the deprecated `oauth.trustedAudiences`) and `muster.mcpServer.auth.requiredAudiences`, in that order and without duplicates.", + "description": "The issuers whose JWTs are accepted (`OAUTH_TRUSTED_ISSUERS`). A trust anchor: set it only from the release's own values or a GitOps-managed ConfigMap that only installation administrators write. Each entry: `issuer`, `jwksURI` and `audiences` (required), `subjectClaim` (`sub` or `email`), `acceptedTypHeaders`, `allowedClaims`, `allowPrivateIPJWKSHosts`, `openIDProvider` (true for the provider whose accepted bearers are used as ID tokens), and `certificateAuthority` with a `secretKeyRef` or `configMapKeyRef` (`name`, `key`). Empty trusts the provider people sign in with (`authorizationServer.upstream`) as `openIDProvider`: its ID tokens are accepted as bearer tokens, a deviation from MCP's audience rule until per-backend tokens (ID-JAG, giantswarm/giantswarm#39102). They are accepted for `oauth.trustedAudiences`, else `global.identity.clientId`, else `authorizationServer.upstream.client.id`, together with `muster.mcpServer.auth.requiredAudiences`, in that order and without duplicates.", "items": { "type": "object", "required": [ diff --git a/helm/cluster-manager/values.yaml b/helm/cluster-manager/values.yaml index d2dcfd4..a447fae 100644 --- a/helm/cluster-manager/values.yaml +++ b/helm/cluster-manager/values.yaml @@ -156,15 +156,15 @@ oauth: # Each entry: `issuer`, `jwksURI` and `audiences` (required), # `subjectClaim` (`sub` or `email`), `acceptedTypHeaders`, # `allowedClaims`, `allowPrivateIPJWKSHosts`, `openIDProvider` (true for - # the provider people sign in with, whose bearers are their ID tokens), + # the provider whose accepted bearers are used as ID tokens), # and `certificateAuthority` with a `secretKeyRef` or `configMapKeyRef` # (`name`, `key`). Empty trusts the provider people sign in with # (`authorizationServer.upstream`) as `openIDProvider`: its ID tokens are # accepted as bearer tokens, a deviation from MCP's audience rule until # per-backend tokens (ID-JAG, giantswarm/giantswarm#39102). They are - # accepted for the client people sign in with - # (`authorizationServer.upstream.client.id`, or the deprecated - # `oauth.trustedAudiences`) and `muster.mcpServer.auth.requiredAudiences`, + # accepted for `oauth.trustedAudiences`, else `global.identity.clientId`, + # else `authorizationServer.upstream.client.id`, together with + # `muster.mcpServer.auth.requiredAudiences`, # in that order and without duplicates. trustedIssuers: [] # @schema item: object ; itemRequired: [issuer, jwksURI, audiences] ; itemProperties: {issuer: {type: string}, jwksURI: {type: string}, audiences: {type: array, minItems: 1, items: {type: string}}, subjectClaim: {type: string, enum: ['', sub, email]}, acceptedTypHeaders: {type: array, items: {type: string}}, allowedClaims: {type: object, additionalProperties: {type: string}}, allowPrivateIPJWKSHosts: {type: array, items: {type: string}}, openIDProvider: {type: boolean}, certificateAuthority: {type: object, additionalProperties: false, properties: {secretKeyRef: {type: object, additionalProperties: false, required: [name, key], properties: {name: {type: string}, key: {type: string}}}, configMapKeyRef: {type: object, additionalProperties: false, required: [name, key], properties: {name: {type: string}, key: {type: string}}}}}} # -- Accept only tokens whose audience names this server's resource @@ -179,7 +179,9 @@ oauth: enabled: true # -- Public base URL of this server, the issuer of its tokens and metadata # (`OAUTH_ISSUER`; https, or http on loopback). Empty uses the deprecated - # `oauth.baseURL`, else `https://.`. + # `oauth.baseURL`, else `https://.`. Required also + # with this authorization server disabled: the library uses this public + # base URL for resource metadata; it does not advertise an active AS. issuer: "" upstream: # -- The OpenID Provider people sign in with: `dex` or `google` diff --git a/internal/server/oauth_protocol_test.go b/internal/server/oauth_protocol_test.go new file mode 100644 index 0000000..8a913da --- /dev/null +++ b/internal/server/oauth_protocol_test.go @@ -0,0 +1,75 @@ +package server + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + mcpserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/require" +) + +func TestResourceServerOnlyMCPProtocol(t *testing.T) { + provider := newPrivateIdP(t, "") + trusted, err := json.Marshal([]map[string]any{{ + "issuer": provider.issuer, "jwksURI": provider.issuer + "/keys", + "audiences": []string{"platform-client"}, "openIDProvider": true, + "acceptedTypHeaders": []string{"JWT"}, "caFile": provider.caFile, + "allowPrivateIPJWKSHosts": []string{privateIssuerHost}, + }}) + require.NoError(t, err) + settings := oauthSettings(t, map[string]string{ + "OAUTH_ISSUER": "https://manager.example.test", + "OAUTH_ENABLE_AUTHORIZATION_SERVER": "false", + "OAUTH_AUTHORIZATION_SERVERS": provider.issuer, + "OAUTH_TRUSTED_ISSUERS": string(trusted), + }) + runtime, err := newOAuth(OAuthConfig{Settings: settings, DownstreamOAuth: true}, "/mcp", slog.New(slog.DiscardHandler)) + require.NoError(t, err) + t.Cleanup(func() { runtime.shutdown(context.WithoutCancel(t.Context())) }) + protocol := mcpserver.NewStreamableHTTPServer(mcpserver.NewMCPServer("fixture", "test", mcpserver.WithToolCapabilities(false)), mcpserver.WithStateLess(true), mcpserver.WithDisableStreaming(true)) + endpoint := httptest.NewServer(runtime.protect(protocol)) + t.Cleanup(endpoint.Close) + for _, scenario := range []struct { + name, token string + status int + }{ + {"no token", "", http.StatusUnauthorized}, + {"platform audience", provider.idToken(t, []string{"platform-client"}), http.StatusOK}, + {"other audience", provider.idToken(t, []string{"manager-client"}), http.StatusUnauthorized}, + } { + t.Run(scenario.name, func(t *testing.T) { + request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, endpoint.URL+"/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"fixture","version":"test"},"io.modelcontextprotocol/clientCapabilities":{}}}}`)) + require.NoError(t, err) + request.Header.Set("Content-Type", "application/json") + request.Header.Set("Accept", "application/json, text/event-stream") + request.Header.Set("MCP-Protocol-Version", "2026-07-28") + request.Header.Set("Mcp-Method", "tools/list") + if scenario.token != "" { + request.Header.Set("Authorization", "Bearer "+scenario.token) + } + response, err := endpoint.Client().Do(request) + require.NoError(t, err) + defer func() { _ = response.Body.Close() }() + answer, err := io.ReadAll(response.Body) + require.NoError(t, err) + require.Equal(t, scenario.status, response.StatusCode, string(answer)) + if scenario.status == http.StatusOK { + var result struct { + Result struct { + Tools []any `json:"tools"` + } `json:"result"` + Error any `json:"error"` + } + require.NoError(t, json.Unmarshal(answer, &result)) + require.Nil(t, result.Error) + require.NotNil(t, result.Result.Tools) + } + }) + } +} diff --git a/internal/tools/cluster_create_test.go b/internal/tools/cluster_create_test.go index 68671d1..ab43dd3 100644 --- a/internal/tools/cluster_create_test.go +++ b/internal/tools/cluster_create_test.go @@ -282,7 +282,7 @@ func TestCreateClusterBindsTheCreatorAndTheOrgAdmins(t *testing.T) { oidc := &compose.ClusterOIDC{IssuerURL: "https://dex.gazelle.example", ClientID: "dex-k8s-authenticator", UsernameClaim: "email", GroupsClaim: "groups"} l := newLab(t, "releases.yaml") svc := l.service(Config{Installation: "gazelle", ClusterOIDC: oidc}, WithChartReader(releaseCharts(t))) - ctx := handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example", TokenSource: providers.TokenSourceSSO}) + ctx := handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example", EmailVerified: true, TokenSource: providers.TokenSourceSSO}) in := dev01() in.DryRun = true got, err := svc.CreateCluster(ctx, in) @@ -323,7 +323,7 @@ func TestCreateClusterBindsTheCreatorAndTheOrgAdmins(t *testing.T) { // cluster's usernamePrefix (the apiserver flag's "-" for none), the // installation's OIDC settings under the cluster's. func TestCreatorUsername(t *testing.T) { - ctx := handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example"}) + ctx := handler.ContextWithUserInfo(t.Context(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example", EmailVerified: true}) oidc := func(block map[string]any) map[string]any { return map[string]any{"global": map[string]any{"controlPlane": map[string]any{"oidc": block}}} } @@ -349,6 +349,10 @@ func TestCreatorUsername(t *testing.T) { got, note := creatorUsername(handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l"}), nil, oidc(map[string]any{"usernameClaim": "email"})) assert.Empty(t, got) assert.Contains(t, note, "your sign-in carries no email") + unverified := handler.ContextWithUserInfo(t.Context(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example"}) + got, note = creatorUsername(unverified, nil, oidc(map[string]any{"usernameClaim": "email"})) + assert.Empty(t, got) + assert.Contains(t, note, "does not verify your email") } // TestCreateClusterRBACOverrides: the caller's own bindings win whole — @@ -410,7 +414,7 @@ func TestCreateClusterRBACNotes(t *testing.T) { assert.Empty(t, got.RBAC.Users) assert.Contains(t, got.RBAC.Note, "without a signed-in person") - ctx := handler.ContextWithUserInfo(context.Background(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example"}) + ctx := handler.ContextWithUserInfo(t.Context(), &providers.UserInfo{ID: "CgVqYW5l", Email: "jane@acme.example", EmailVerified: true}) got, err = plain.CreateCluster(ctx, in) require.NoError(t, err) assert.Empty(t, got.RBAC.Users) diff --git a/internal/tools/cluster_rbac.go b/internal/tools/cluster_rbac.go index cc34284..8c44f53 100644 --- a/internal/tools/cluster_rbac.go +++ b/internal/tools/cluster_rbac.go @@ -135,6 +135,9 @@ func creatorUsername(ctx context.Context, installation, values map[string]any) ( if user.Email == "" { return "", fmt.Sprintf("your sign-in carries no email, the claim the cluster takes the username from, so you are not bound — add yourself through %s", valuesBindings) } + if !user.EmailVerified { + return "", fmt.Sprintf("your sign-in does not verify your email, so you are not bound; verify it with your identity provider or add yourself through %s", valuesBindings) + } prefix, _ := oidc["usernamePrefix"].(string) if prefix == "-" { // the apiserver flag's "no prefix" prefix = "" From 1028e4ea44ca1e56c4d7d8f12a0230f7f115af1b Mon Sep 17 00:00:00 2001 From: QuentinBisson Date: Fri, 27 Nov 2026 13:21:38 +0100 Subject: [PATCH 5/5] fix: clarify supported GitHub exchange providers --- cmd/serve.go | 7 +++++-- cmd/serve_test.go | 7 ++++--- docs/development.md | 6 +++++- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/cmd/serve.go b/cmd/serve.go index 6bcd039..32ca5fd 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -379,8 +379,11 @@ func validateGitHubExchange(o *serveOptions, settings oauthconfig.Settings) erro } hasProvider = present } - if !o.oauthEnabled || !o.downstreamOAuth || !hasProvider { - return errors.New("GitHub token exchange requires OAuth, downstream OAuth and an OpenID Provider") + if !o.oauthEnabled || !o.downstreamOAuth { + return errors.New("GitHub token exchange requires OAuth and downstream OAuth") + } + if !hasProvider { + return errors.New("GitHub token exchange requires a Dex upstream or exactly one trusted openIDProvider in resource-server-only mode") } return o.gitHubExchangeConfig().Validate() } diff --git a/cmd/serve_test.go b/cmd/serve_test.go index a72a302..a53087f 100644 --- a/cmd/serve_test.go +++ b/cmd/serve_test.go @@ -34,15 +34,16 @@ func TestValidateGitHubExchange(t *testing.T) { require.NoError(t, validateGitHubExchange(exchange(), resourceOnly)) resourceOnly.TrustedIssuers = append(resourceOnly.TrustedIssuers, oauthserver.TrustedIssuer{Issuer: "https://other.example.test", OpenIDProvider: true}) require.ErrorContains(t, validateGitHubExchange(exchange(), resourceOnly), "exactly one openIDProvider") - require.ErrorContains(t, validateGitHubExchange(exchange(), oauthconfig.Settings{}), "requires OAuth, downstream OAuth and an OpenID Provider", "the subject token must be a Dex token") + require.ErrorContains(t, validateGitHubExchange(exchange(), oauthconfig.Settings{}), "requires a Dex upstream or exactly one trusted openIDProvider in resource-server-only mode") + require.ErrorContains(t, validateGitHubExchange(exchange(), oauthconfig.Settings{Google: &google.Config{}}), "requires a Dex upstream or exactly one trusted openIDProvider in resource-server-only mode") for name, scenario := range map[string]struct { change func(*serveOptions) want string }{ "option without endpoint": {func(o *serveOptions) { o.githubExchangeEndpoint = "" }, "require --github-token-exchange-endpoint"}, - "without OAuth": {func(o *serveOptions) { o.oauthEnabled = false }, "requires OAuth, downstream OAuth and an OpenID Provider"}, - "without downstream OAuth": {func(o *serveOptions) { o.downstreamOAuth = false }, "requires OAuth, downstream OAuth and an OpenID Provider"}, + "without OAuth": {func(o *serveOptions) { o.oauthEnabled = false }, "requires OAuth and downstream OAuth"}, + "without downstream OAuth": {func(o *serveOptions) { o.downstreamOAuth = false }, "requires OAuth and downstream OAuth"}, "plain HTTP endpoint": {func(o *serveOptions) { o.githubExchangeEndpoint = "http://muster.example/oauth/token" }, "HTTPS token endpoint"}, "without audience": {func(o *serveOptions) { o.githubExchangeAudience = "" }, "an audience"}, } { diff --git a/docs/development.md b/docs/development.md index b37f7a1..c380908 100644 --- a/docs/development.md +++ b/docs/development.md @@ -6,11 +6,15 @@ Creator RBAC uses an email username only when the provider verified that email. An unverified or absent email leaves the creator out of the generated binding and explains the omission in the result's RBAC note. -Without a local Dex provider, automatic cluster OIDC configuration requires one +In resource-server-only mode, automatic cluster OIDC configuration requires one unambiguous trusted issuer marked `openIDProvider`. Multiple marked issuers are refused rather than selecting an authority by list order. This configuration flag permits provider ID-token recovery; it is not a JWT token-type assertion. +GitHub exchange requires downstream OAuth and either a local Dex upstream or +one trusted `openIDProvider` in resource-server-only mode. An active Google +upstream is not supported. + ## Checks Run `go test ./...` and the repository's pre-commit checks before submitting changes.