diff --git a/.github/conformance/baseline.yml b/.github/conformance/baseline.yml new file mode 100644 index 0000000..77f8e8c --- /dev/null +++ b/.github/conformance/baseline.yml @@ -0,0 +1,4 @@ +server: + # The streamable-HTTP endpoint is stateless (WithStateLess), so a + # 2025-11-25 initialize hands out no Mcp-Session-Id; the runner warns. + - server-sse-multiple-streams:server-sse-multiple-streams-session diff --git a/.github/workflows/conformance.yaml b/.github/workflows/conformance.yaml new file mode 100644 index 0000000..e28baa5 --- /dev/null +++ b/.github/workflows/conformance.yaml @@ -0,0 +1,58 @@ +name: MCP conformance + +on: + pull_request: {} + merge_group: {} + push: + branches: ['main'] + +permissions: {} + +concurrency: + group: conformance-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + server: + name: MCP conformance + runs-on: ubuntu-26.04 + permissions: + contents: read + env: + LISTEN: 127.0.0.1:38591 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - name: Find the mcp-toolkit version in go.mod + id: toolkit + run: echo "version=$(go list -m -f '{{.Version}}' github.com/giantswarm/mcp-toolkit)" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: giantswarm/mcp-toolkit + ref: ${{ steps.toolkit.outputs.version }} + path: .mcp-toolkit + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: .mcp-toolkit/conformance/.nvmrc + cache: npm + cache-dependency-path: .mcp-toolkit/conformance/package-lock.json + - name: Start the server + run: | + go build -o "$RUNNER_TEMP/server" . + "$RUNNER_TEMP/server" serve --listen "$LISTEN" & + - name: Run the conformance scenarios + env: + CONFORMANCE_BASELINE: ${{ github.workspace }}/.github/conformance/baseline.yml + CONFORMANCE_RESULTS: ${{ runner.temp }}/results + run: .mcp-toolkit/conformance/run.sh "http://$LISTEN/mcp" + - if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: conformance + path: ${{ runner.temp }}/results + retention-days: 7 diff --git a/README.md b/README.md index 7f1df20..2388003 100644 --- a/README.md +++ b/README.md @@ -10,3 +10,5 @@ Owns the Agent Platform's skill sources: lists their skills and pins skills and - Tools: [docs/tools.md](docs/tools.md) - REST API: [docs/api.md](docs/api.md) - Configuration: the chart's [values](helm/skill-manager/values.yaml) — `sources`, `github`, `cacheTTL`, `oauth`, `muster.mcpServer`, `serviceToken`. +- Upgrading: see [UPGRADE.md](UPGRADE.md) for what each release asks of an operator. +- OAuth: mcp-oauth's `OAUTH_*` variables (`oauthconfig.SettingsFromEnv`), rendered from `oauth.resourceServer` and `oauth.authorizationServer`. The MCP endpoint is stateless; `MCP_ALLOWED_HOSTS` and `MCP_ALLOWED_ORIGINS` (`mcp.allowedHosts`, `mcp.allowedOrigins`) admit a proxy's host and browser origins. diff --git a/UPGRADE.md b/UPGRADE.md new file mode 100644 index 0000000..90d770b --- /dev/null +++ b/UPGRADE.md @@ -0,0 +1,68 @@ +# Upgrade notes + +What an operator has to do or decide when upgrading, newest first. The +release notes on GitHub list every change; this file covers the actions. + +A section is headed with the version that ships it (`## 0.6.0 — `). +A pull request that adds notes heads them `## Next — <title>`; the release +renames each `Next` to its version. + +## Next — chart values on model-manager's layout + +The chart takes mcp-oauth's value names for MCP servers (`oauth.resourceServer`, +`oauth.authorizationServer`). The old names keep working, deprecated; the install +notes list each old name a release sets. Move to the new names before the release +that removes the old ones. + +| Old | New | +|---|---| +| `oauth.baseURL` | `oauth.authorizationServer.issuer` | +| `oauth.dex.issuerURL` | `oauth.authorizationServer.upstream.issuer` | +| `oauth.dex.clientID` | `oauth.authorizationServer.upstream.client.id` | +| `oauth.dex.clientSecret`, `oauth.existingSecret` | `oauth.authorizationServer.upstream.client.secretKeyRef` | +| `oauth.dex.caSecret` | `oauth.authorizationServer.upstream.certificateAuthority.secretKeyRef` | +| `oauth.trustedAudiences` | the `audiences` of an `oauth.resourceServer.trustedIssuers` entry | +| `oauth.sso.allowPrivateIPJWKSHosts` | the `allowPrivateIPJWKSHosts` of an `oauth.resourceServer.trustedIssuers` entry | +| `oauth.allowPublicClientRegistration` | nothing: MCP clients register with client ID metadata documents | +| `oauth.dex.allowPrivateURLs`, `oauth.sso.allowPrivateIPs` | nothing: they have no effect | +| `networkPolicy.ingressNamespaces` | a `networkPolicy.gatewayPeers` entry with a `namespaceSelector` | +| `networkPolicy.metricsNamespaces` | a `networkPolicy.metricsPeers` entry | + +- **Configuration through `OAUTH_*` variables.** The chart renders mcp-oauth's + `OAUTH_*` variables instead of the flags, and mounts the Dex client secret as a + file instead of `DEX_CLIENT_SECRET`. Dex becomes an `OAUTH_TRUSTED_ISSUERS` + entry marked as the OpenID Provider, accepting the same audiences. Outside the + chart, the old flags and variables (`--oauth-base-url`, `--dex-*`, + `--oauth-trusted-audiences`, `--sso-allow-private-ip-jwks-hosts`, + `--allow-public-client-registration` and their variables) keep working, log a + warning naming the replacement, and lose to an `OAUTH_*` variable. +- **Trusted issuers and a private Dex.** The entry the chart builds for Dex lists + the issuer host in `allowPrivateIPJWKSHosts`. An entry you write in + `oauth.resourceServer.trustedIssuers` is used as written: list a private JWKS + host in it, or every forwarded token is refused with 401. +- **No authorization server of its own.** When every caller brings a token from a + trusted issuer, as muster, agent-manager and the portal do, set + `oauth.authorizationServer.enabled: false` and list that issuer in + `oauth.resourceServer.authorizationServers`. The Dex client and its secret are + then not needed. `oauth.authorizationServer.issuer` stays set: it is the + server's public URL. +- **Token introspection.** `/oauth/introspect` is no longer served. Set + `OAUTH_ENABLE_INTROSPECTION_ENDPOINT=true` in `extraEnv` if a client uses it. +- **Who may reach the server.** The NetworkPolicy admits muster, agentgateway + and agent-manager in the release namespace (`networkPolicy.gatewayPeers`) + instead of every pod there, and the `alloy-metrics` scraper in `kube-system` + (`networkPolicy.metricsPeers`) instead of every pod in `kube-system`. A caller + in the release namespace with another `app.kubernetes.io/name` needs a + `gatewayPeers` entry. Namespaces listed in the deprecated + `ingressNamespaces` and `metricsNamespaces` stay admitted. +- **ServiceMonitor tenant.** `serviceMonitor.labels` defaults to + `observability.giantswarm.io/tenant: giantswarm`, and a ServiceMonitor without + that label fails to render. +- **HTTPRoute.** `httpRoute.*` renders an optional Gateway API route, off by + default. +- **Stateless endpoint.** `/mcp` hands out no `Mcp-Session-Id`; any replica + answers any request. +- **Browser and proxy access.** `/mcp` refuses cross-origin browser requests and, + on a loopback listener, a foreign `Host`. A proxy in the same pod that keeps the + public host needs `mcp.allowedHosts`; a web application on another origin + needs `mcp.allowedOrigins`. diff --git a/cmd/oauth_env.go b/cmd/oauth_env.go new file mode 100644 index 0000000..f0603d5 --- /dev/null +++ b/cmd/oauth_env.go @@ -0,0 +1,116 @@ +package cmd + +import ( + "errors" + "log/slog" + "os" + "strconv" + + "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 skill-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", "SKILL_MANAGER_OAUTH_BASE_URL", "OAUTH_ISSUER"}, o.oauthBaseURL}, + {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{"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", "SKILL_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) + if !present(option.Replacement) { + set[option.Replacement] = option.value + } + } + + // mcp-oauth refuses OAUTH_PROVIDER with the authorization server off. + 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" + } + return set, deprecated +} + +// loadOAuthSettings reads mcp-oauth's settings from the OAUTH_* variables, +// after setting those that deprecated options and skill-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 a later 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, and every caller is named by 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..724b4bb --- /dev/null +++ b/cmd/oauth_env_test.go @@ -0,0 +1,145 @@ +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: skill-manager's defaults fill the gaps", + environment: map[string]string{"OAUTH_ISSUER": "https://sm.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 options map to their replacements", + options: serveOptions{oauthBaseURL: "https://sm.example.com", dexIssuerURL: "https://dex.example.com", + dexClientID: "skill-manager", dexClientSecret: "secret", dexCAFile: "/ca/ca.crt", oauthTrustedAudiences: "agent-platform,kubernetes", + ssoAllowPrivateIPJWKSHosts: "keys.internal", allowPublicClientRegistration: true}, + wantSet: map[string]string{ + "OAUTH_ISSUER": "https://sm.example.com", "OAUTH_PROVIDER": "dex", "OAUTH_DEX_ISSUER_URL": "https://dex.example.com", + "OAUTH_DEX_CLIENT_ID": "skill-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", "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: "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"}, + }, + } + 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) { + clearOAuthEnvironment(t) + var output bytes.Buffer + settings, err := loadOAuthSettings(&serveOptions{oauthBaseURL: "https://sm.example.com", dexIssuerURL: "https://dex.example.com", + dexClientID: "skill-manager", dexClientSecret: "dex-secret-value", oauthTrustedAudiences: "agent-platform", + ssoAllowPrivateIPJWKSHosts: "keys.internal.example, jwks.internal.example"}, + 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://sm.example.com/oauth/callback", settings.Dex.RedirectURL) + assert.Equal(t, "https://sm.example.com", settings.Server.Issuer) + assert.Equal(t, []string{"agent-platform"}, settings.Server.TrustedAudiences) + assert.Equal(t, []string{"keys.internal.example", "jwks.internal.example"}, settings.Server.AllowPrivateIPJWKSHosts) + assert.True(t, settings.Server.EnableClientIDMetadataDocuments) + assert.Contains(t, output.String(), "--dex-issuer-url (DEX_ISSUER_URL) is deprecated and will be removed in a later release: set OAUTH_DEX_ISSUER_URL") + assert.NotContains(t, output.String(), "dex-secret-value", "no secret value is logged") +} + +func TestLoadOAuthSettingsRefusesGitHub(t *testing.T) { + clearOAuthEnvironment(t) + for name, value := range map[string]string{"OAUTH_ISSUER": "https://sm.example.com", "OAUTH_PROVIDER": "github", + "OAUTH_GITHUB_CLIENT_ID": "id", "OAUTH_GITHUB_CLIENT_SECRET": "secret", "OAUTH_GITHUB_REDIRECT_URL": "https://sm.example.com/oauth/callback"} { + t.Setenv(name, value) + } + _, err := loadOAuthSettings(&serveOptions{}, slog.New(slog.DiscardHandler)) + require.ErrorContains(t, err, "OAUTH_PROVIDER=github is not supported") +} + +// clearOAuthEnvironment empties the OAUTH_* variables loadOAuthSettings sets, +// so each test starts from none and its own settings do not leak. +func clearOAuthEnvironment(t *testing.T) { + t.Helper() + for _, name := range []string{"OAUTH_ISSUER", "OAUTH_PROVIDER", "OAUTH_DEX_ISSUER_URL", "OAUTH_DEX_CLIENT_ID", "OAUTH_DEX_CLIENT_SECRET", + "OAUTH_DEX_CA_FILE", "OAUTH_TRUSTED_AUDIENCES", "OAUTH_TRUSTED_ISSUERS", "OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS", + "OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION", "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS", "OAUTH_ENABLE_AUTHORIZATION_SERVER", + "OAUTH_AUTHORIZATION_SERVERS"} { + t.Setenv(name, "") + } +} + +// dexEnvironment sets the OAUTH_* variables of a Dex-backed resource server. +func dexEnvironment(t *testing.T) { + t.Helper() + clearOAuthEnvironment(t) + for name, value := range map[string]string{"OAUTH_ISSUER": "https://sm.example.com", "OAUTH_DEX_ISSUER_URL": "https://dex.example.com", + "OAUTH_DEX_CLIENT_ID": "skill-manager", "OAUTH_DEX_CLIENT_SECRET": "secret", "OAUTH_TRUSTED_AUDIENCES": "agent-platform"} { + t.Setenv(name, value) + } +} + +// The environment the chart renders with oauth.authorizationServer.enabled +// false loads: no provider, no Dex client, only the trusted issuer. +func TestLoadOAuthSettingsResourceServerOnly(t *testing.T) { + clearOAuthEnvironment(t) + for name, value := range map[string]string{ + "OAUTH_ISSUER": "https://sm.example.com", + "OAUTH_ENABLE_AUTHORIZATION_SERVER": "false", + "OAUTH_AUTHORIZATION_SERVERS": "https://dex.example.com", + "OAUTH_TRUSTED_ISSUERS": `[{"issuer":"https://dex.example.com","jwksURI":"https://dex.example.com/keys","audiences":["agent-platform"],"openIDProvider":true}]`, + } { + t.Setenv(name, value) + } + settings, err := loadOAuthSettings(&serveOptions{}, slog.New(slog.DiscardHandler)) + require.NoError(t, err) + assert.True(t, settings.Server.DisableAuthorizationServer) + assert.Nil(t, settings.Dex) + require.Len(t, settings.TrustedIssuers, 1) + assert.True(t, settings.TrustedIssuers[0].OpenIDProvider) +} diff --git a/cmd/serve.go b/cmd/serve.go index 5f0058c..6fad795 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -12,6 +12,7 @@ import ( "syscall" "time" + "github.com/giantswarm/mcp-toolkit/httpx" "github.com/giantswarm/mcp-toolkit/telemetry/metrics" "github.com/giantswarm/mcp-toolkit/telemetry/tracing" "github.com/spf13/cobra" @@ -112,17 +113,17 @@ environment variable named next to it; flags win over the environment.`, f.StringVar(&o.githubExchangeCAFile, "github-token-exchange-ca-file", envOr("SKILL_MANAGER_GITHUB_TOKEN_EXCHANGE_CA_FILE", ""), "Additional CA bundle for token exchange (SKILL_MANAGER_GITHUB_TOKEN_EXCHANGE_CA_FILE)") f.StringVar(&o.ociRegistries, "oci-registries", envOr("SKILL_MANAGER_OCI_REGISTRIES", strings.Join(oci.DefaultHosts, ",")), "Comma-separated OCI registry hosts (host or host:port) an OCI skill or plugin may come from; no other registry, and none by IP address, is asked. Empty: none (SKILL_MANAGER_OCI_REGISTRIES)") f.StringVar(&o.serviceToken, "service-token", envOr("SKILL_MANAGER_SERVICE_TOKEN", ""), "A bearer the REST API admits as the platform's own service caller, no person: agent-manager's migrate, which has no caller; no readability check applies to it. Prefer the environment (SKILL_MANAGER_SERVICE_TOKEN). Needs --enable-oauth") - f.BoolVar(&o.oauthEnabled, "enable-oauth", envBool(o.envErrs, "enable-oauth", "SKILL_MANAGER_OAUTH_ENABLED", false), "Require an OAuth 2.1 bearer token on the MCP endpoint and the REST API, validated against Dex (mcp-oauth) (SKILL_MANAGER_OAUTH_ENABLED)") - f.StringVar(&o.oauthBaseURL, "oauth-base-url", envOr("SKILL_MANAGER_OAUTH_BASE_URL", ""), "Public base URL of this server: the issuer of its OAuth metadata, https or loopback http (SKILL_MANAGER_OAUTH_BASE_URL)") - 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; prefer the environment (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(o.envErrs, "enable-oauth", "SKILL_MANAGER_OAUTH_ENABLED", false), "Require an OAuth 2.1 bearer token on the MCP endpoint and the REST API (mcp-oauth, configured by the OAUTH_* variables) (SKILL_MANAGER_OAUTH_ENABLED)") + f.StringVar(&o.oauthBaseURL, "oauth-base-url", envOr("SKILL_MANAGER_OAUTH_BASE_URL", ""), "Deprecated: set OAUTH_ISSUER. Public base URL of this server (SKILL_MANAGER_OAUTH_BASE_URL)") + f.StringVar(&o.dexIssuerURL, "dex-issuer-url", envOr("DEX_ISSUER_URL", ""), "Deprecated: set OAUTH_DEX_ISSUER_URL. 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 (DEX_CLIENT_ID)") + f.StringVar(&o.dexClientSecret, "dex-client-secret", envOr("DEX_CLIENT_SECRET", ""), "Deprecated: set OAUTH_DEX_CLIENT_SECRET_FILE. Dex client secret (DEX_CLIENT_SECRET)") + f.StringVar(&o.dexCAFile, "dex-ca-file", envOr("DEX_CA_FILE", ""), "Deprecated: set OAUTH_DEX_CA_FILE. PEM CA bundle of a Dex with a private certificate (DEX_CA_FILE)") f.BoolVar(&o.dexAllowPrivateIP, "allow-private-oauth-urls", envBool(o.envErrs, "allow-private-oauth-urls", "SKILL_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 (SKILL_MANAGER_OAUTH_ALLOW_PRIVATE_URLS)") - f.StringVar(&o.oauthTrustedAudiences, "oauth-trusted-audiences", envOr("OAUTH_TRUSTED_AUDIENCES", ""), "Comma-separated OAuth client IDs whose Dex id_tokens are accepted as bearer tokens: the platform client and the audiences muster requires (OAUTH_TRUSTED_AUDIENCES)") + f.StringVar(&o.oauthTrustedAudiences, "oauth-trusted-audiences", envOr("OAUTH_TRUSTED_AUDIENCES", ""), "Deprecated: list the provider in OAUTH_TRUSTED_ISSUERS. Comma-separated OAuth client IDs whose ID tokens are accepted as bearer tokens (OAUTH_TRUSTED_AUDIENCES)") f.BoolVar(&o.ssoAllowPrivateIPs, "sso-allow-private-ips", envBool(o.envErrs, "sso-allow-private-ips", "SSO_ALLOW_PRIVATE_IPS", false), "Deprecated, no effect: the issuer host of the configured provider may resolve to a private address for its JWKS 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(o.envErrs, "allow-public-client-registration", "SKILL_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION", false), "Accept unauthenticated dynamic client registration; labs only (SKILL_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. Comma-separated JWKS hosts, other than the issuer's own, that may resolve to an RFC 1918 or RFC 4193 address (SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS)") + f.BoolVar(&o.allowPublicClientRegistration, "allow-public-client-registration", envBool(o.envErrs, "allow-public-client-registration", "SKILL_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION", false), "Deprecated: set OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION. Accept unauthenticated dynamic client registration; labs only (SKILL_MANAGER_OAUTH_ALLOW_PUBLIC_REGISTRATION)") return cmd, o } @@ -151,9 +152,11 @@ func (o *serveOptions) tokenSource() (skills.TokenSource, error) { return skills.NewApp(o.githubAPIURL, o.appID, o.appInstall, key, nil) } -// serverConfig is the listener's configuration. -func (o *serveOptions) serverConfig() (server.Config, error) { - cfg := server.Config{Addr: o.listen, MCPPath: o.mcpPath} +// serverConfig is the listener's configuration. With --enable-oauth it reads +// mcp-oauth's settings from the OAUTH_* variables, after setting those the +// deprecated options supply. +func (o *serveOptions) serverConfig(log *slog.Logger) (server.Config, error) { + cfg := server.Config{Addr: o.listen, MCPPath: o.mcpPath, Origins: httpx.OriginPolicyFromEnv()} if err := validateGitHubExchange(o); err != nil { return server.Config{}, err } @@ -163,17 +166,11 @@ func (o *serveOptions) serverConfig() (server.Config, error) { if !o.oauthEnabled { return cfg, nil } - cfg.OAuth = &server.OAuthConfig{ - BaseURL: o.oauthBaseURL, - DexIssuerURL: o.dexIssuerURL, - DexClientID: o.dexClientID, - DexClientSecret: o.dexClientSecret, - DexCAFile: o.dexCAFile, - TrustedAudiences: splitList(o.oauthTrustedAudiences), - AllowPrivateIPJWKSHosts: splitList(o.ssoAllowPrivateIPJWKSHosts), - AllowPublicClientRegistration: o.allowPublicClientRegistration, - ServiceToken: strings.TrimSpace(o.serviceToken), + settings, err := loadOAuthSettings(o, log) + if err != nil { + return server.Config{}, err } + cfg.OAuth = &server.OAuthConfig{Settings: settings, ServiceToken: strings.TrimSpace(o.serviceToken)} return cfg, nil } @@ -202,7 +199,7 @@ func runServe(ctx context.Context, o *serveOptions) error { if err != nil { return err } - srvCfg, err := o.serverConfig() + srvCfg, err := o.serverConfig(log) if err != nil { return err } diff --git a/cmd/serve_test.go b/cmd/serve_test.go index 818e319..76e3469 100644 --- a/cmd/serve_test.go +++ b/cmd/serve_test.go @@ -94,7 +94,7 @@ func TestServeDefaults(t *testing.T) { // exchanges, and its options need the endpoint. func TestServeGitHubTokenExchangeOptions(t *testing.T) { exchange := []string{"--github-token-exchange-endpoint=https://muster.example.com/oauth/token", "--github-token-exchange-audience=skill-manager-app", "--github-token-exchange-client-id-file=/mounted/client-id", "--github-token-exchange-client-secret-file=/mounted/client-secret"} - _, err := parse(t, exchange...).serverConfig() + _, err := parse(t, exchange...).serverConfig(slog.New(slog.DiscardHandler)) assert.ErrorContains(t, err, "--enable-oauth") o := parse(t, exchange...) @@ -102,27 +102,31 @@ func TestServeGitHubTokenExchangeOptions(t *testing.T) { require.NoError(t, validateGitHubExchange(o), "the client ID may come from its file") assert.Equal(t, "skill-manager-app", o.gitHubExchangeConfig().Audience) - _, err = parse(t, "--github-token-exchange-audience=skill-manager-app").serverConfig() + _, err = parse(t, "--github-token-exchange-audience=skill-manager-app").serverConfig(slog.New(slog.DiscardHandler)) assert.ErrorContains(t, err, "--github-token-exchange-endpoint") } // The service token reaches the REST guard. func TestServeServiceToken(t *testing.T) { + dexEnvironment(t) t.Setenv("SKILL_MANAGER_SERVICE_TOKEN", "s3cret") - cfg, err := parse(t, "--enable-oauth").serverConfig() + cfg, err := parse(t, "--enable-oauth").serverConfig(slog.New(slog.DiscardHandler)) require.NoError(t, err) assert.Equal(t, "s3cret", cfg.OAuth.ServiceToken) - _, err = parse(t).serverConfig() + _, err = parse(t).serverConfig(slog.New(slog.DiscardHandler)) assert.ErrorContains(t, err, "--enable-oauth", "a service token without OAuth guards nothing") } -// The JWKS hosts allowed to resolve privately reach the OAuth configuration. -func TestServeAllowPrivateIPJWKSHosts(t *testing.T) { - t.Setenv("SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS", "keys.internal.example, jwks.internal.example") - cfg, err := parse(t, "--enable-oauth").serverConfig() +// The MCP endpoint's allowed hosts and trusted origins come from +// MCP_ALLOWED_HOSTS and MCP_ALLOWED_ORIGINS. +func TestServeOriginPolicy(t *testing.T) { + t.Setenv("MCP_ALLOWED_HOSTS", "skills.example.com") + t.Setenv("MCP_ALLOWED_ORIGINS", "https://portal.example.com") + cfg, err := parse(t).serverConfig(slog.New(slog.DiscardHandler)) require.NoError(t, err) - assert.Equal(t, []string{"keys.internal.example", "jwks.internal.example"}, cfg.OAuth.AllowPrivateIPJWKSHosts) + assert.Equal(t, []string{"skills.example.com"}, cfg.Origins.AllowedHosts) + assert.Equal(t, []string{"https://portal.example.com"}, cfg.Origins.TrustedOrigins) } // An environment value that does not parse fails the start, naming it. @@ -150,8 +154,9 @@ func TestServeFlagWinsOverAnUnparsableEnvironment(t *testing.T) { // The service token is trimmed: a Secret written with a trailing newline // still matches. func TestServeTrimsTheServiceToken(t *testing.T) { + dexEnvironment(t) t.Setenv("SKILL_MANAGER_SERVICE_TOKEN", "s3cret\n") - cfg, err := parse(t, "--enable-oauth").serverConfig() + cfg, err := parse(t, "--enable-oauth").serverConfig(slog.New(slog.DiscardHandler)) require.NoError(t, err) assert.Equal(t, "s3cret", cfg.OAuth.ServiceToken) } diff --git a/go.mod b/go.mod index f39e4eb..f6cb81d 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.26.0 require ( github.com/giantswarm/mcp-oauth v1.24.0 - github.com/giantswarm/mcp-toolkit v0.15.0 + github.com/giantswarm/mcp-toolkit v0.17.0 github.com/giantswarm/mcp-toolkit/telemetry v0.1.0 github.com/go-jose/go-jose/v4 v4.1.9 github.com/golang-jwt/jwt/v5 v5.4.0 @@ -24,6 +24,7 @@ require ( ) require ( + cloud.google.com/go/compute/metadata v0.9.0 // indirect code.dny.dev/ssrf v0.3.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect @@ -43,6 +44,7 @@ require ( github.com/prometheus/procfs v0.22.0 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect github.com/spf13/cast v1.7.1 // indirect + github.com/valkey-io/valkey-go v1.0.80 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/bridges/prometheus v0.72.0 // indirect diff --git a/go.sum b/go.sum index 3935538..b913676 100644 --- a/go.sum +++ b/go.sum @@ -17,8 +17,8 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= 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.15.0 h1:ls2oTnLpefo9r0CYi2cvLcpDUiLUQQg37VXKRzU+7JE= -github.com/giantswarm/mcp-toolkit v0.15.0/go.mod h1:5UaRc33/2JVBwtZKEnKxb9wIb5WixKHMEXDH8FLHrzo= +github.com/giantswarm/mcp-toolkit v0.17.0 h1:p85avooehCvyRFne7pkRPbqkZA6trJhN3x8Y+C1IPBg= +github.com/giantswarm/mcp-toolkit v0.17.0/go.mod h1:1xB75s1MpJPDHLvLJU0+Fc7fw+8NR3O8A+AMLgfuXaE= github.com/giantswarm/mcp-toolkit/telemetry v0.1.0 h1:NGpD274MxJs4NATtEBycoy9SzSJ4Rfb3UYE40gU4hi0= github.com/giantswarm/mcp-toolkit/telemetry v0.1.0/go.mod h1:1ts4TRPB1lhCv+ejw4g4zUbCVzjSqF4yQp3+W95uvok= github.com/go-jose/go-jose/v4 v4.1.9 h1:pKfeQkig1NmgK4hJrZYXLEYURXfoJB61Larw0uIW4gY= @@ -58,6 +58,8 @@ github.com/modelcontextprotocol/go-sdk v1.9.0 h1:XVjBrIMg82x7ff2bqwSPgRThLp4TC1l github.com/modelcontextprotocol/go-sdk v1.9.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/onsi/gomega v1.44.0 h1:eAiGl3Pw5jz5GQdDff0BcxYpAX1JxW8xD7mFUuwNfZQ= +github.com/onsi/gomega v1.44.0/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA= github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= diff --git a/helm/skill-manager/README.md b/helm/skill-manager/README.md index eda9023..56adc32 100644 --- a/helm/skill-manager/README.md +++ b/helm/skill-manager/README.md @@ -42,18 +42,36 @@ Owns the Agent Platform's skill sources, lists their skills and pins skills and | serviceToken.secretName | string | `""` | Existing Secret in the release namespace with a bearer the REST API admits as the platform's own caller, no person, for agent-manager's `migrate`; no readability check applies to it. Needs `oauth.enabled`. Empty: none. | | serviceToken.key | string | `"token"` | Key of the token in that Secret. | | mcp.path | string | `"/mcp"` | MCP endpoint path. | -| oauth.enabled | bool | `false` | Make skill-manager an OAuth 2.1 resource server (mcp-oauth): the MCP endpoint and the REST API require a bearer token Dex issued, validated against Dex's JWKS when its audience is in `trustedAudiences`. muster forwards the session's Dex id_token (`muster.mcpServer.auth`); agent-manager and the portal forward the person's. Off: no authentication at all, and private repositories are refused; only for a server nothing but a trusted proxy can reach. Off by default only because it needs the installation's Dex: the `agent-platform` meta chart turns it on. | -| oauth.baseURL | string | `""` | Public base URL of this server: the issuer of its own OAuth metadata (https, or http on loopback). Empty derives `https://<fullname>.<global.domain>` when `global.domain` is set. | -| 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 the `dex-ca-file` flag. Empty name falls back to `global.identity.ca.secretName` / `global.identity.ca.key`. | -| oauth.existingSecret | string | `""` | Existing Secret with the Dex client secret under `dex-client-secret`. Empty falls back to `global.identity.existingSecret`; without that, the chart renders a Secret from `oauth.dex.clientSecret`. | -| oauth.trustedAudiences | list | `[]` | OAuth client IDs whose Dex 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 of the configured provider may resolve to a private address for its JWKS without it; list any other JWKS host in allowPrivateIPJWKSHosts. | -| 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). | +| mcp.allowedHosts | list | `[]` | Host header values the MCP endpoint answers besides its own address (`MCP_ALLOWED_HOSTS`): list the public host name when a proxy in the same pod forwards to it and keeps that host. Empty: every Host, except that a request arriving on a loopback listener needs a loopback host. | +| mcp.allowedOrigins | list | `[]` | Browser origins (`https://host[:port]`) trusted to call the MCP endpoint from another origin (`MCP_ALLOWED_ORIGINS`). Empty: same-origin browsers and clients without browser headers (muster, agent-manager) only. | +| oauth.enabled | bool | `false` | Make skill-manager an OAuth 2.1 resource server (mcp-oauth): the MCP endpoint and the REST API require a bearer token, and every call carries the caller. muster forwards the session's ID token (`muster.mcpServer.auth`); agent-manager and the portal forward the person's. They are accepted from the provider people sign in with (`resourceServer.trustedIssuers`). Off: no authentication at all, and private repositories are refused; only for a server nothing but a trusted proxy can reach. Off by default only because it needs the installation's Dex: the `agent-platform` meta chart turns it on. | +| 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 REST API and the MCP endpoint are always protected resources. | +| 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 skill-manager a resource server only (`OAUTH_ENABLE_AUTHORIZATION_SERVER=false`): no client secret is needed. | +| 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://<fullname>.<global.domain>`. | +| oauth.authorizationServer.upstream.type | string | `"dex"` | The OpenID Provider people sign in with (`OAUTH_PROVIDER`). | +| 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`, else `global.identity.clientId`. | +| 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` (key `dex-client-secret`), else `global.identity.existingSecret`, else a Secret from the deprecated `oauth.dex.clientSecret`. | +| 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 (`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 is not shared between replicas. | +| oauth.baseURL | string | `""` | Deprecated: use `authorizationServer.issuer`. | +| 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":""}` | Deprecated: use `authorizationServer.upstream.certificateAuthority`. | +| oauth.existingSecret | string | `""` | Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. Existing Secret with the Dex client secret under `dex-client-secret`. | +| 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. | | muster.mcpServer.enabled | bool | `false` | Register this server with muster by rendering an `mcpservers.muster.giantswarm.io` CR in the release namespace. Tools then appear as `x_<name>_<tool>`. | | muster.mcpServer.name | string | `"skill-manager"` | MCPServer CR name (drives the tool prefix). | | muster.mcpServer.displayName | string | `"Skill Manager"` | Name the Dev Portal shows for this server, rendered as the MCPServer's `ui.giantswarm.io/display-name` annotation. Empty renders no annotation. | @@ -64,10 +82,12 @@ Owns the Agent Platform's skill sources, lists their skills and pins skills and | muster.mcpServer.timeout | int | `30` | How long muster waits for a tool's answer, in seconds (the MCPServer's `spec.timeout`, 1 to 300): muster's default. | | muster.mcpServer.auth | object | `{"forwardToken":true,"requiredAudiences":[]}` | How muster authenticates to this server; rendered only with `oauth.enabled`. `forwardToken` makes muster forward the session's Dex id_token byte-identical (the SSO path this chart trusts through its trusted audiences); with `github.tokenExchange` the CR also lists its `audience` under `auth.providerApps`. `requiredAudiences` are extra audiences that token must carry — the Dex cross-client audience the kube-apiserver trusts (`dex-k8s-authenticator` on Giant Swarm clusters; agentlab's is `kubernetes`); muster requests them at login, so users re-login after a change. They are trusted as bearer audiences by construction, since the server's trusted audiences are `oauth.trustedAudiences` plus this list. | | networkPolicy.enabled | bool | `true` | Create a Kubernetes NetworkPolicy for the pod. | -| networkPolicy.ingressNamespaces | list | `[]` | Namespaces allowed to reach the MCP endpoint and the REST API (label kubernetes.io/metadata.name), besides the release namespace. List muster's, agent-manager's and the portal's namespaces when they run elsewhere, or they cannot reach the server. | +| networkPolicy.gatewayPeers | list | `[{"podSelector":{"matchLabels":{"app.kubernetes.io/name":"muster"}}},{"podSelector":{"matchLabels":{"app.kubernetes.io/name":"agentgateway"}}},{"podSelector":{"matchLabels":{"app.kubernetes.io/name":"agent-manager"}}}]` | NetworkPolicy peers allowed to reach the MCP endpoint and the REST API: muster, agentgateway and agent-manager. Pod selectors alone match the release namespace; add a `namespaceSelector` for a caller elsewhere. | +| networkPolicy.ingressNamespaces | list | `[]` | Deprecated: list a `gatewayPeers` entry with a `namespaceSelector`. Namespaces whose every pod may reach the API (label kubernetes.io/metadata.name), in addition to `gatewayPeers`. | | networkPolicy.allowInternet | bool | `true` | Allow egress on 443 to every destination: GitHub, OCI registries and an external Dex. Vanilla NetworkPolicy cannot select by name; narrow with egressCIDRs instead when the addresses are known. With `oauth.enabled`, Dex's own port is opened from its issuer URL as well: its namespace for an in-cluster `<svc>.<namespace>.svc` host (e.g. port 5556), every address otherwise. | | networkPolicy.egressCIDRs | list | `[]` | Extra egress CIDRs. | -| networkPolicy.metricsNamespaces | list | `["kube-system"]` | Namespaces allowed to scrape the metrics port (label kubernetes.io/metadata.name), when `observability.metrics.enabled`. | +| networkPolicy.metricsPeers | list | `[{"namespaceSelector":{"matchLabels":{"kubernetes.io/metadata.name":"kube-system"}},"podSelector":{"matchLabels":{"app.kubernetes.io/instance":"alloy-metrics","app.kubernetes.io/name":"alloy"}}}]` | NetworkPolicy peers allowed to scrape the metrics port, when `observability.metrics.enabled`. | +| networkPolicy.metricsNamespaces | list | `[]` | Deprecated: list a `metricsPeers` entry. Namespaces whose every pod may scrape the metrics port, in addition to `metricsPeers`. | | serviceAccount.create | bool | `true` | Create a ServiceAccount. | | serviceAccount.annotations | object | `{}` | Annotations on the ServiceAccount. | | serviceAccount.name | string | `""` | ServiceAccount name (generated when empty). | @@ -77,6 +97,11 @@ Owns the Agent Platform's skill sources, lists their skills and pins skills and | securityContext | object | `{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]},"readOnlyRootFilesystem":true,"runAsGroup":1000,"runAsNonRoot":true,"runAsUser":1000,"seccompProfile":{"type":"RuntimeDefault"}}` | Container security context. | | service.type | string | `"ClusterIP"` | Service type. | | service.port | int | `8080` | Service port (the container listens on 8080). | +| httpRoute.enabled | bool | `false` | Expose the service through a Gateway API HTTPRoute. | +| httpRoute.parentRefs | list | `[]` | parentRefs of the HTTPRoute (required when enabled). | +| httpRoute.hostnames | list | `[]` | Hostnames matched by the route. | +| httpRoute.annotations | object | `{}` | Annotations on the HTTPRoute. | +| httpRoute.labels | object | `{}` | Labels on the HTTPRoute. | | resources | object | `{"limits":{"cpu":"500m","ephemeral-storage":"100Mi","memory":"256Mi"},"requests":{"cpu":"50m","ephemeral-storage":"50Mi","memory":"64Mi"}}` | Container resources. | | observability.otel.endpoint | string | `""` | OTLP collector URL for traces, e.g. `http://otlp-gateway.kube-system.svc:4317` (gRPC) or `https://tempo.example.com:4318` (with protocol `http/protobuf`). Empty exports nothing; inbound `traceparent` headers still propagate. With `networkPolicy.enabled` the policy opens egress to it: the Service's namespace for an in-cluster host, every address otherwise. | | observability.otel.protocol | string | `"grpc"` | OTLP protocol: `grpc` or `http/protobuf`. | @@ -88,7 +113,7 @@ Owns the Agent Platform's skill sources, lists their skills and pins skills and | observability.metrics.port | int | `9464` | Port of the metrics listener, apart from the MCP port so the OAuth guard never covers it. | | serviceMonitor.enabled | bool | `false` | Render a ServiceMonitor for the `metrics` port. Also needs `observability.metrics.enabled`. | | serviceMonitor.interval | string | `""` | Scrape interval; empty uses the Prometheus Operator default. | -| serviceMonitor.labels | object | `{}` | Labels on the ServiceMonitor, beside the chart's own. The Giant Swarm observability platform routes a scrape to a Mimir tenant by `observability.giantswarm.io/tenant`; a monitor without it writes to no tenant. | +| serviceMonitor.labels | object | `{"observability.giantswarm.io/tenant":"giantswarm"}` | Labels on the ServiceMonitor, beside the chart's own. The Giant Swarm observability platform routes a scrape to a Mimir tenant by `observability.giantswarm.io/tenant`, which the ServiceMonitor requires. | | logging.verbose | bool | `false` | Enable debug logging. | | extraArgs | list | `[]` | Extra container arguments. | | extraEnv | list | `[]` | Extra environment variables. | diff --git a/helm/skill-manager/ci/ci-values.yaml b/helm/skill-manager/ci/ci-values.yaml index da40b57..43fa4f7 100644 --- a/helm/skill-manager/ci/ci-values.yaml +++ b/helm/skill-manager/ci/ci-values.yaml @@ -2,4 +2,3 @@ # app-build-suite passes this file to `helm template` (see `helm-template-extra-values` in .abs/main.yaml), # so a value the chart marks `required` and cannot default (an external endpoint, say) is filled here. # These values are only used by CI; they are never installed. -{} diff --git a/helm/skill-manager/templates/NOTES.txt b/helm/skill-manager/templates/NOTES.txt index 6789eec..48763e7 100644 --- a/helm/skill-manager/templates/NOTES.txt +++ b/helm/skill-manager/templates/NOTES.txt @@ -3,8 +3,12 @@ skill-manager is running. MCP : http://{{ include "skill-manager.fullname" . }}.{{ .Release.Namespace }}.svc.cluster.local:{{ .Values.service.port }}{{ .Values.mcp.path }} REST: http://{{ include "skill-manager.fullname" . }}.{{ .Release.Namespace }}.svc.cluster.local:{{ .Values.service.port }}/v1 {{- if .Values.oauth.enabled }} +{{- $oauth := include "skill-manager.oauth" . | fromJson }} -Every call needs a Dex token whose audience is one of {{ include "skill-manager.oauthTrustedAudiences" . | quote }}. +Every call needs a bearer token from {{ if $oauth.authorizationServer }}this server ({{ $oauth.issuer }}) or {{ end }}a trusted issuer: +{{- range $oauth.trustedIssuers }} + {{ .issuer }} for {{ join ", " .audiences }} +{{- end }} {{- else }} WARNING: oauth.enabled is off: the API admits everyone, and no caller can read a private repository. @@ -21,3 +25,29 @@ The NetworkPolicy admits the release namespace{{ with .Values.networkPolicy.ingr With {{ .Values.replicaCount }} replicas, tokens this server issues itself live in one replica's memory; forwarded Dex tokens work on every replica. {{- end }} +{{- $o := .Values.oauth }} +{{- $deprecated := dict + "oauth.baseURL" (list $o.baseURL "oauth.authorizationServer.issuer") + "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.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") }} +{{- if not $o.enabled }}{{ $deprecated = dict }}{{ end }} +{{- $np := .Values.networkPolicy }} +{{- $_ := set $deprecated "networkPolicy.ingressNamespaces" (list $np.ingressNamespaces "a networkPolicy.gatewayPeers entry with a namespaceSelector") }} +{{- $_ = set $deprecated "networkPolicy.metricsNamespaces" (list $np.metricsNamespaces "a networkPolicy.metricsPeers entry") }} +{{- $set := list }} +{{- range $key := keys $deprecated | sortAlpha }}{{ if index $deprecated $key 0 }}{{ $set = append $set $key }}{{ end }}{{ end }} +{{- if $set }} + +Deprecated values, removed in a later release: +{{- range $set }} + {{ . }}: use {{ index $deprecated . 1 }} +{{- end }} +{{- end }} diff --git a/helm/skill-manager/templates/_helpers.tpl b/helm/skill-manager/templates/_helpers.tpl index d955615..b96723b 100644 --- a/helm/skill-manager/templates/_helpers.tpl +++ b/helm/skill-manager/templates/_helpers.tpl @@ -70,8 +70,9 @@ The platform identity contract (global.identity), an empty dict when absent. {{- end }} {{/* -Existing Secret with the Dex client secret: oauth.existingSecret, else the -platform's global.identity.existingSecret, else the chart-rendered one. +Existing Secret with the Dex client secret of the deprecated keys: +oauth.existingSecret, else the platform's global.identity.existingSecret, +else the chart-rendered one. */}} {{- define "skill-manager.oauthSecretName" -}} {{- $g := include "skill-manager.globalIdentity" . | fromJson -}} @@ -79,70 +80,109 @@ 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: the authorization server on, +no authorizationServer.upstream.client.secretKeyRef, no existing Secret named. */}} {{- define "skill-manager.oauthRendersSecret" -}} {{- $g := include "skill-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://<fullname>.<global.domain>. +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://<fullname>.<global.domain> + upstreamIssuer authorizationServer.upstream.issuer, dex.issuerURL, global.identity.issuerUrl + clientID authorizationServer.upstream.client.id, dex.clientID, global.identity.clientId + 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 Dex + (openIDProvider), accepting its ID tokens for the union, in + this order and without duplicates, of the deprecated + trustedAudiences (else clientID) and + muster.mcpServer.auth.requiredAudiences: every token muster + forwards carries those by construction, 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 "skill-manager.oauthBaseURL" -}} +{{- define "skill-manager.oauth" -}} +{{- $o := .Values.oauth -}} +{{- $as := $o.authorizationServer -}} +{{- $up := $as.upstream -}} +{{- $rs := $o.resourceServer -}} +{{- $g := include "skill-manager.globalIdentity" . | fromJson -}} {{- $domain := dig "domain" "" (.Values.global | default dict) -}} {{- $derived := "" -}} {{- if $domain }}{{ $derived = printf "https://%s.%s" (include "skill-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 "skill-manager.oauthDexIssuerURL" -}} -{{- $g := include "skill-manager.globalIdentity" . | fromJson -}} -{{- required "oauth.dex.issuerURL (or global.identity.issuerUrl) is required when oauth.enabled" (.Values.oauth.dex.issuerURL | default (dig "issuerUrl" "" $g)) }} -{{- end }} - -{{- define "skill-manager.oauthDexClientID" -}} -{{- $g := include "skill-manager.globalIdentity" . | fromJson -}} -{{- required "oauth.dex.clientID (or global.identity.clientId) is required when oauth.enabled" (.Values.oauth.dex.clientID | default (dig "clientId" "" $g)) }} -{{- end }} - -{{/* -CA Secret of a private-certificate Dex: oauth.dex.caSecret, else -global.identity.ca. Name empty means system trust. -*/}} -{{- define "skill-manager.oauthDexCASecretName" -}} -{{- $g := include "skill-manager.globalIdentity" . | fromJson -}} -{{- .Values.oauth.dex.caSecret.name | default (dig "ca" "secretName" "" $g) }} -{{- end }} - -{{- define "skill-manager.oauthDexCASecretKey" -}} -{{- $g := include "skill-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 }} -{{- end }} - -{{/* -Trusted audiences, comma-separated: the OAuth client ids whose Dex 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. -*/}} -{{- define "skill-manager.oauthTrustedAudiences" -}} -{{- $g := include "skill-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 -}} +{{- $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)) -}} +{{- $upstreamIssuer := $up.issuer | default $o.dex.issuerURL | default (dig "issuerUrl" "" $g) -}} +{{- $clientID := $up.client.id | default $o.dex.clientID | default (dig "clientId" "" $g) -}} +{{- $_ = 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 "skill-manager.oauthSecretName" .) "key" "dex-client-secret") -}} +{{- end -}} +{{- $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/skill-manager/idp-ca" -}} +{{- $_ = set $r "upstreamCA" $ca -}} +{{- $_ = set $r "mounts" (append $r.mounts $ca) -}} +{{- 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/skill-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)) (.Values.muster.mcpServer.auth.requiredAudiences | default list) -}} +{{- if and . (not (has . $audiences)) }}{{ $audiences = append $audiences . }}{{ end -}} +{{- end -}} +{{- if and $audiences $upstreamIssuer -}} +{{- /* Dex serves its JWKS at <issuer>/keys and signs ID tokens without a typ header. mcp-oauth does not imply the issuer host for private JWKS addresses on a trusted issuer, so it is listed. */ -}} +{{- $entry := dict "issuer" $upstreamIssuer "jwksURI" (printf "%s/keys" (trimSuffix "/" $upstreamIssuer)) "audiences" $audiences "openIDProvider" true "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 -}} +{{- $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 }} {{/* @@ -179,7 +219,7 @@ networkPolicy.allowInternet does not reach an in-cluster Dex on its own port. {{- define "skill-manager.dexEgress" -}} {{- if .Values.oauth.enabled -}} {{- $g := include "skill-manager.globalIdentity" . | fromJson -}} -{{- with (.Values.oauth.dex.issuerURL | default (dig "issuerUrl" "" $g)) -}} +{{- with (.Values.oauth.authorizationServer.upstream.issuer | default .Values.oauth.dex.issuerURL | default (dig "issuerUrl" "" $g)) -}} {{- $url := urlParse . -}} {{- $hostPort := splitList ":" $url.host -}} {{- $port := ternary (last $hostPort) "" (gt (len $hostPort) 1) -}} diff --git a/helm/skill-manager/templates/deployment.yaml b/helm/skill-manager/templates/deployment.yaml index 0cb1584..386aa9e 100644 --- a/helm/skill-manager/templates/deployment.yaml +++ b/helm/skill-manager/templates/deployment.yaml @@ -60,27 +60,6 @@ spec: {{- end }} {{- if .Values.oauth.enabled }} - --enable-oauth=true - - --oauth-base-url={{ include "skill-manager.oauthBaseURL" . }} - - --dex-issuer-url={{ include "skill-manager.oauthDexIssuerURL" . }} - - --dex-client-id={{ include "skill-manager.oauthDexClientID" . }} - {{- with include "skill-manager.oauthTrustedAudiences" . }} - - --oauth-trusted-audiences={{ . }} - {{- end }} - {{- if .Values.oauth.dex.allowPrivateURLs }} - - --allow-private-oauth-urls=true - {{- end }} - {{- if include "skill-manager.oauthDexCASecretName" . }} - - --dex-ca-file=/etc/skill-manager/idp-ca/{{ include "skill-manager.oauthDexCASecretKey" . }} - {{- 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 }} {{- end }} {{- if $exchange }} {{- with .Values.github.tokenExchange }} @@ -107,12 +86,74 @@ spec: entry (prometheus or none), so this block is unconditional. */}} env: + {{- with .Values.mcp.allowedHosts }} + - name: MCP_ALLOWED_HOSTS + value: {{ join "," . | quote }} + {{- end }} + {{- with .Values.mcp.allowedOrigins }} + - name: MCP_ALLOWED_ORIGINS + value: {{ join "," . | quote }} + {{- end }} {{- if .Values.oauth.enabled }} - - name: DEX_CLIENT_SECRET - valueFrom: - secretKeyRef: - name: {{ include "skill-manager.oauthSecretName" . }} - key: dex-client-secret + {{- /* mcp-oauth's settings (oauthconfig.SettingsFromEnv). */}} + {{- $oauth := include "skill-manager.oauth" . | fromJson }} + {{- $rs := .Values.oauth.resourceServer }} + {{- $as := .Values.oauth.authorizationServer }} + - name: OAUTH_ISSUER + value: {{ $oauth.issuer | quote }} + {{- with $rs.resource }} + - name: OAUTH_RESOURCE + value: {{ . | quote }} + {{- end }} + {{- 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: {{ $as.upstream.type | default "dex" | 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/skill-manager/oauth-registration/token + {{- end }} + {{- if .Values.oauth.allowPublicClientRegistration }} + - name: OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION + value: "true" + {{- end }} + - name: OAUTH_DEX_ISSUER_URL + value: {{ required "oauth.authorizationServer.upstream.issuer (or global.identity.issuerUrl) is required when oauth.enabled" $oauth.upstreamIssuer | quote }} + - name: OAUTH_DEX_CLIENT_ID + value: {{ required "oauth.authorizationServer.upstream.client.id (or global.identity.clientId) is required when oauth.enabled" $oauth.clientID | quote }} + - name: OAUTH_DEX_CLIENT_SECRET_FILE + value: /etc/skill-manager/oauth-client/client-secret + {{- with $oauth.upstreamCA }} + - name: OAUTH_DEX_CA_FILE + value: {{ printf "%s/%s" .dir .key | quote }} + {{- end }} + {{- end }} {{- with .Values.serviceToken.secretName }} - name: SKILL_MANAGER_SERVICE_TOKEN valueFrom: @@ -222,8 +263,8 @@ spec: failureThreshold: 3 resources: {{- toYaml .Values.resources | nindent 12 }} - {{- $idpCA := "" }} - {{- if .Values.oauth.enabled }}{{ $idpCA = include "skill-manager.oauthDexCASecretName" . }}{{ end }} + {{- $oauth := dict "mounts" list }} + {{- if .Values.oauth.enabled }}{{ $oauth = include "skill-manager.oauth" . | fromJson }}{{ end }} volumeMounts: - name: tmp mountPath: /tmp @@ -232,11 +273,21 @@ spec: mountPath: /etc/skill-manager/github-app readOnly: true {{- end }} - {{- if $idpCA }} - - name: idp-ca - mountPath: /etc/skill-manager/idp-ca + {{- range $oauth.mounts }} + - name: {{ .volume }} + mountPath: {{ .dir }} readOnly: true {{- end }} + {{- if $oauth.authorizationServer }} + - name: oauth-client + mountPath: /etc/skill-manager/oauth-client + readOnly: true + {{- if .Values.oauth.authorizationServer.dynamicClientRegistration.initialAccessToken.secretKeyRef.name }} + - name: oauth-registration + mountPath: /etc/skill-manager/oauth-registration + readOnly: true + {{- end }} + {{- end }} {{- if $exchange }} - name: github-token-exchange mountPath: /etc/skill-manager/github-token-exchange @@ -258,13 +309,38 @@ spec: - key: private-key path: private-key {{- end }} - {{- if $idpCA }} - - name: idp-ca + {{- range $oauth.mounts }} + - name: {{ .volume }} + {{- if .secret }} secret: - secretName: {{ $idpCA }} + secretName: {{ .secret }} + {{- else }} + configMap: + name: {{ .configMap }} + {{- end }} items: - - key: {{ include "skill-manager.oauthDexCASecretKey" . }} - path: {{ include "skill-manager.oauthDexCASecretKey" . }} + - key: {{ .key }} + path: {{ .key }} + {{- end }} + {{- if $oauth.authorizationServer }} + - name: oauth-client + secret: + secretName: {{ $oauth.clientSecret.name }} + defaultMode: 0440 + items: + - 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 $exchange }} {{- /* The whole Secret: a missing client-id key does not block the pod. */}} diff --git a/helm/skill-manager/templates/httproute.yaml b/helm/skill-manager/templates/httproute.yaml new file mode 100644 index 0000000..cb9af9c --- /dev/null +++ b/helm/skill-manager/templates/httproute.yaml @@ -0,0 +1,34 @@ +{{- if .Values.httpRoute.enabled }} +{{- if not .Values.httpRoute.parentRefs }} +{{- fail "httpRoute.parentRefs is required when httpRoute.enabled is true" }} +{{- end }} +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: {{ include "skill-manager.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "skill-manager.labels" . | nindent 4 }} + {{- with .Values.httpRoute.labels }} + {{- toYaml . | nindent 4 }} + {{- end }} + {{- with .Values.httpRoute.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + parentRefs: + {{- toYaml .Values.httpRoute.parentRefs | nindent 4 }} + {{- with .Values.httpRoute.hostnames }} + hostnames: + {{- toYaml . | nindent 4 }} + {{- end }} + rules: + - matches: + - path: + type: PathPrefix + value: / + backendRefs: + - name: {{ include "skill-manager.fullname" . }} + port: {{ .Values.service.port }} +{{- end }} diff --git a/helm/skill-manager/templates/networkpolicy.yaml b/helm/skill-manager/templates/networkpolicy.yaml index f8f3012..bca7261 100644 --- a/helm/skill-manager/templates/networkpolicy.yaml +++ b/helm/skill-manager/templates/networkpolicy.yaml @@ -14,8 +14,11 @@ spec: - Ingress - Egress ingress: + {{- if or .Values.networkPolicy.gatewayPeers .Values.networkPolicy.ingressNamespaces }} - from: - - podSelector: {} + {{- with .Values.networkPolicy.gatewayPeers }} + {{- toYaml . | nindent 8 }} + {{- end }} {{- range .Values.networkPolicy.ingressNamespaces }} - namespaceSelector: matchLabels: @@ -24,8 +27,12 @@ spec: ports: - protocol: TCP port: 8080 - {{- if and .Values.observability.metrics.enabled .Values.networkPolicy.metricsNamespaces }} + {{- end }} + {{- if and .Values.observability.metrics.enabled (or .Values.networkPolicy.metricsPeers .Values.networkPolicy.metricsNamespaces) }} - from: + {{- with .Values.networkPolicy.metricsPeers }} + {{- toYaml . | nindent 8 }} + {{- end }} {{- range .Values.networkPolicy.metricsNamespaces }} - namespaceSelector: matchLabels: diff --git a/helm/skill-manager/templates/oauth-secret.yaml b/helm/skill-manager/templates/oauth-secret.yaml index 8f649e1..eb6f3ca 100644 --- a/helm/skill-manager/templates/oauth-secret.yaml +++ b/helm/skill-manager/templates/oauth-secret.yaml @@ -1,6 +1,7 @@ {{- if include "skill-manager.oauthRendersSecret" . }} {{- /* -The Dex client secret when no existing Secret is named (neither +The Dex client secret of the deprecated oauth.dex.clientSecret, when no +Secret is named (neither oauth.authorizationServer.upstream.client.secretKeyRef, oauth.existingSecret nor the platform's global.identity.existingSecret). */}} apiVersion: v1 @@ -12,5 +13,5 @@ metadata: {{- include "skill-manager.labels" . | nindent 4 }} type: Opaque stringData: - dex-client-secret: {{ required "oauth.dex.clientSecret or oauth.existingSecret is required when oauth.enabled" .Values.oauth.dex.clientSecret | quote }} + dex-client-secret: {{ required "oauth.authorizationServer.upstream.client.secretKeyRef (or the deprecated oauth.existingSecret or oauth.dex.clientSecret) is required when oauth.enabled" .Values.oauth.dex.clientSecret | quote }} {{- end }} diff --git a/helm/skill-manager/templates/servicemonitor.yaml b/helm/skill-manager/templates/servicemonitor.yaml index 83fe256..ab7edf2 100644 --- a/helm/skill-manager/templates/servicemonitor.yaml +++ b/helm/skill-manager/templates/servicemonitor.yaml @@ -1,4 +1,5 @@ {{- if and .Values.observability.metrics.enabled .Values.serviceMonitor.enabled }} +{{- $tenant := required "serviceMonitor.labels[observability.giantswarm.io/tenant] must be set" (index .Values.serviceMonitor.labels "observability.giantswarm.io/tenant") }} apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: @@ -6,7 +7,8 @@ metadata: namespace: {{ .Release.Namespace }} labels: {{- include "skill-manager.labels" . | nindent 4 }} - {{- with .Values.serviceMonitor.labels }} + observability.giantswarm.io/tenant: {{ $tenant | quote }} + {{- with omit .Values.serviceMonitor.labels "observability.giantswarm.io/tenant" }} {{- toYaml . | nindent 4 }} {{- end }} spec: diff --git a/helm/skill-manager/tests/deployment_test.yaml b/helm/skill-manager/tests/deployment_test.yaml index a6002d9..bd0eb6c 100644 --- a/helm/skill-manager/tests/deployment_test.yaml +++ b/helm/skill-manager/tests/deployment_test.yaml @@ -257,38 +257,3 @@ tests: asserts: - failedTemplate: errorMessage: github.tokenExchange.existingSecret or github.tokenExchange.clientSecret is required with github.tokenExchange.tokenEndpoint - - - it: lists the JWKS hosts other than the issuer's that may resolve privately - set: - oauth: - enabled: true - existingSecret: platform-oauth - sso: - allowPrivateIPJWKSHosts: - - keys.internal.example - - jwks.internal.example - global: - domain: example.com - identity: - issuerUrl: https://dex.example.com - clientId: platform-client - 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 - set: - oauth: - enabled: true - existingSecret: platform-oauth - global: - domain: example.com - identity: - issuerUrl: https://dex.example.com - clientId: platform-client - asserts: - - notContains: - path: spec.template.spec.containers[0].args - any: true - content: --sso-allow-private-ip-jwks-hosts diff --git a/helm/skill-manager/tests/httproute_servicemonitor_test.yaml b/helm/skill-manager/tests/httproute_servicemonitor_test.yaml new file mode 100644 index 0000000..4b87992 --- /dev/null +++ b/helm/skill-manager/tests/httproute_servicemonitor_test.yaml @@ -0,0 +1,67 @@ +# The optional HTTPRoute, and the ServiceMonitor's tenant label. +# +# Run with: make helm-test (helm unittest helm/skill-manager) +suite: httproute and servicemonitor +templates: + - templates/httproute.yaml + - templates/servicemonitor.yaml +release: + name: skill-manager + namespace: agent-platform +tests: + - it: renders no HTTPRoute by default + template: templates/httproute.yaml + asserts: + - hasDocuments: + count: 0 + + - it: routes the service through the given gateway + template: templates/httproute.yaml + set: + httpRoute: + enabled: true + parentRefs: [{name: gateway, namespace: envoy-gateway-system}] + hostnames: [skills.example.com] + asserts: + - equal: + path: spec.hostnames + value: [skills.example.com] + - equal: + path: spec.rules[0].backendRefs[0] + value: {name: skill-manager, port: 8080} + + - it: needs parentRefs + template: templates/httproute.yaml + set: + httpRoute: + enabled: true + asserts: + - failedTemplate: + errorMessage: httpRoute.parentRefs is required when httpRoute.enabled is true + + - it: labels the ServiceMonitor with the giantswarm tenant by default + template: templates/servicemonitor.yaml + set: + observability: + metrics: + enabled: true + serviceMonitor: + enabled: true + asserts: + - equal: + path: metadata.labels["observability.giantswarm.io/tenant"] + value: giantswarm + + - it: refuses a ServiceMonitor without a tenant + template: templates/servicemonitor.yaml + set: + observability: + metrics: + enabled: true + serviceMonitor: + enabled: true + labels: + observability.giantswarm.io/tenant: null + asserts: + - failedTemplate: + errorMessage: serviceMonitor.labels[observability.giantswarm.io/tenant] must be set diff --git a/helm/skill-manager/tests/networkpolicy_test.yaml b/helm/skill-manager/tests/networkpolicy_test.yaml index 72712b5..bd1d0ca 100644 --- a/helm/skill-manager/tests/networkpolicy_test.yaml +++ b/helm/skill-manager/tests/networkpolicy_test.yaml @@ -1,5 +1,6 @@ -# The NetworkPolicy is on by default: ingress from the release namespace and -# the listed ones (muster's), egress to DNS and 443. +# The NetworkPolicy is on by default: ingress from muster, agentgateway and +# agent-manager in the release namespace, plus the deprecated listed +# namespaces; metrics from the alloy-metrics scraper; egress to DNS and 443. # # Run with: make helm-test (helm unittest helm/skill-manager) suite: networkpolicy @@ -9,14 +10,49 @@ release: name: skill-manager namespace: agent-platform tests: - - it: is rendered by default + - it: admits only the gateway peers by default asserts: - isKind: of: NetworkPolicy - - contains: + - equal: path: spec.ingress[0].from - content: - podSelector: {} + value: + - podSelector: + matchLabels: + app.kubernetes.io/name: muster + - podSelector: + matchLabels: + app.kubernetes.io/name: agentgateway + - podSelector: + matchLabels: + app.kubernetes.io/name: agent-manager + - lengthEqual: + path: spec.ingress + count: 2 + + - it: admits the alloy-metrics scraper to the metrics port + asserts: + - equal: + path: spec.ingress[1].from + value: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + app.kubernetes.io/name: alloy + app.kubernetes.io/instance: alloy-metrics + + - it: admits nothing without peers + set: + networkPolicy: + gatewayPeers: [] + observability: + metrics: + enabled: false + asserts: + - isNullOrEmpty: + path: spec.ingress - it: admits the listed namespaces set: diff --git a/helm/skill-manager/tests/notes_test.yaml b/helm/skill-manager/tests/notes_test.yaml new file mode 100644 index 0000000..6b6fac9 --- /dev/null +++ b/helm/skill-manager/tests/notes_test.yaml @@ -0,0 +1,57 @@ +# The install notes: the trusted issuers, and each deprecated value set with +# its replacement. +# +# Run with: make helm-test (helm unittest helm/skill-manager) +suite: notes +templates: + - templates/NOTES.txt +release: + name: skill-manager + namespace: agent-platform +tests: + - it: names each deprecated value set and its replacement + set: + oauth: + enabled: true + baseURL: https://skills.example.com + dex: + issuerURL: https://dex.example.com + clientID: skill-manager + existingSecret: skill-manager-oauth + sso: + allowPrivateIPs: true + asserts: + - matchRegexRaw: + pattern: "oauth.baseURL: use oauth.authorizationServer.issuer" + - matchRegexRaw: + pattern: "oauth.dex.issuerURL: use oauth.authorizationServer.upstream.issuer" + - matchRegexRaw: + pattern: "oauth.sso.allowPrivateIPs: use nothing: it has no effect" + - matchRegexRaw: + pattern: "https://dex.example.com for skill-manager" + + - it: names no deprecated value on the shared layout + set: + oauth: + enabled: true + authorizationServer: + issuer: https://skills.example.com + upstream: + issuer: https://dex.example.com + client: + id: skill-manager + secretKeyRef: {name: skill-manager-dex} + asserts: + - notMatchRegexRaw: + pattern: Deprecated values + + - it: names the deprecated NetworkPolicy namespaces + set: + networkPolicy: + ingressNamespaces: [kagent] + metricsNamespaces: [monitoring] + asserts: + - matchRegexRaw: + pattern: "networkPolicy.ingressNamespaces: use a networkPolicy.gatewayPeers entry with a namespaceSelector" + - matchRegexRaw: + pattern: "networkPolicy.metricsNamespaces: use a networkPolicy.metricsPeers entry" diff --git a/helm/skill-manager/tests/oauth_private_urls_test.yaml b/helm/skill-manager/tests/oauth_private_urls_test.yaml deleted file mode 100644 index e3234a4..0000000 --- a/helm/skill-manager/tests/oauth_private_urls_test.yaml +++ /dev/null @@ -1,22 +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 diff --git a/helm/skill-manager/tests/values_layout_test.yaml b/helm/skill-manager/tests/values_layout_test.yaml new file mode 100644 index 0000000..346ecfd --- /dev/null +++ b/helm/skill-manager/tests/values_layout_test.yaml @@ -0,0 +1,292 @@ +# The OAuth values on mcp-oauth's layout (oauth.resourceServer, +# oauth.authorizationServer), the deprecated keys they replace, and the MCP +# endpoint's allowed hosts and origins. +# +# Run with: make helm-test (helm unittest helm/skill-manager) +suite: values layout +templates: + - templates/deployment.yaml +release: + name: skill-manager + namespace: agent-platform +tests: + - it: renders the platform's Dex as the trusted OpenID Provider from global.identity + set: + oauth.enabled: true + global: + domain: example.com + identity: + issuerUrl: https://dex.example.com + clientId: platform-client + existingSecret: platform-oauth + muster.mcpServer.auth.requiredAudiences: [dex-k8s-authenticator, platform-client] + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ISSUER, value: https://skill-manager.example.com} + - contains: + path: spec.template.spec.containers[0].env + content: + name: OAUTH_TRUSTED_ISSUERS + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.com"],"audiences":["platform-client","dex-k8s-authenticator"],"issuer":"https://dex.example.com","jwksURI":"https://dex.example.com/keys","openIDProvider":true}]' + - 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.com} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_ID, value: platform-client} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_SECRET_FILE, value: /etc/skill-manager/oauth-client/client-secret} + - contains: + path: spec.template.spec.volumes + content: + name: oauth-client + secret: + secretName: platform-oauth + defaultMode: 0440 + items: + - key: dex-client-secret + path: client-secret + - notContains: + path: spec.template.spec.containers[0].args + content: --oauth-base-url=https://skill-manager.example.com + + - it: maps every deprecated key to the same settings + set: + oauth: + enabled: true + baseURL: https://skills.example.com + dex: + issuerURL: https://dex.example.com + clientID: skill-manager + caSecret: {name: dex-ca, key: root.pem} + allowPrivateURLs: true + existingSecret: skill-manager-oauth + trustedAudiences: [platform-client] + sso: + allowPrivateIPs: true + allowPrivateIPJWKSHosts: [keys.internal.example] + allowPublicClientRegistration: true + muster.mcpServer.auth.requiredAudiences: [dex-k8s-authenticator] + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ISSUER, value: https://skills.example.com} + - contains: + path: spec.template.spec.containers[0].env + content: + name: OAUTH_TRUSTED_ISSUERS + value: '[{"acceptedTypHeaders":["","JWT"],"allowPrivateIPJWKSHosts":["dex.example.com","keys.internal.example"],"audiences":["platform-client","dex-k8s-authenticator"],"caFile":"/etc/skill-manager/idp-ca/root.pem","issuer":"https://dex.example.com","jwksURI":"https://dex.example.com/keys","openIDProvider":true}]' + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_ID, value: skill-manager} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CA_FILE, value: /etc/skill-manager/idp-ca/root.pem} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ALLOW_PUBLIC_CLIENT_REGISTRATION, value: "true"} + - contains: + path: spec.template.spec.volumes + content: + name: idp-ca + secret: + secretName: dex-ca + items: + - key: root.pem + path: root.pem + - contains: + path: spec.template.spec.volumes + content: + name: oauth-client + secret: + secretName: skill-manager-oauth + defaultMode: 0440 + items: + - key: dex-client-secret + path: client-secret + - 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: prefers the shared layout over the deprecated keys + set: + oauth: + enabled: true + baseURL: https://old.example.com + dex: + issuerURL: https://old-dex.example.com + clientID: old-client + caSecret: {name: old-ca} + existingSecret: old-oauth + authorizationServer: + issuer: https://skills.example.com + upstream: + issuer: https://dex.example.com + client: + id: skill-manager + secretKeyRef: {name: skill-manager-dex, key: secret} + certificateAuthority: + secretKeyRef: {name: dex-ca, key: ca.crt} + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ISSUER, value: https://skills.example.com} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_ISSUER_URL, value: https://dex.example.com} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_DEX_CLIENT_ID, value: skill-manager} + - contains: + path: spec.template.spec.volumes + content: + name: oauth-client + secret: + secretName: skill-manager-dex + defaultMode: 0440 + items: + - key: secret + path: client-secret + - contains: + path: spec.template.spec.volumes + content: + name: idp-ca + secret: + secretName: dex-ca + items: + - key: ca.crt + path: ca.crt + + - it: runs as a resource server only, with no client secret + set: + oauth: + enabled: true + authorizationServer: + enabled: false + issuer: https://skills.example.com + resourceServer: + authorizationServers: [https://dex.example.com] + trustedIssuers: + - issuer: https://dex.example.com + jwksURI: https://dex.example.com/keys + audiences: [skill-manager] + openIDProvider: true + certificateAuthority: + configMapKeyRef: {name: dex-ca, key: ca.crt} + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_ENABLE_AUTHORIZATION_SERVER, value: "false"} + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_AUTHORIZATION_SERVERS, value: https://dex.example.com} + - contains: + path: spec.template.spec.containers[0].env + content: + name: OAUTH_TRUSTED_ISSUERS + value: '[{"audiences":["skill-manager"],"caFile":"/etc/skill-manager/trusted-issuer-ca/0/ca.crt","issuer":"https://dex.example.com","jwksURI":"https://dex.example.com/keys","openIDProvider":true}]' + - 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_SECRET_FILE} + - notContains: + path: spec.template.spec.volumes + any: true + content: {name: oauth-client} + - contains: + path: spec.template.spec.volumes + content: + name: trusted-issuer-ca-0 + configMap: + name: dex-ca + items: + - key: ca.crt + path: ca.crt + + - it: refuses a resource server only without the authorization servers MCP clients discover + set: + oauth: + enabled: true + authorizationServer: + enabled: false + issuer: https://skills.example.com + upstream: + issuer: https://dex.example.com + client: + id: skill-manager + asserts: + - failedTemplate: + errorMessage: "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" + + - it: refuses OAuth without an issuer + set: + oauth.enabled: true + oauth.existingSecret: skill-manager-oauth + asserts: + - failedTemplate: + errorMessage: oauth.authorizationServer.issuer is required when oauth.enabled (or set global.domain) + + - it: renders the initial access token dynamic client registration requires + set: + oauth: + enabled: true + existingSecret: skill-manager-oauth + authorizationServer: + issuer: https://skills.example.com + upstream: + issuer: https://dex.example.com + client: + id: skill-manager + dynamicClientRegistration: + initialAccessToken: + secretKeyRef: {name: registration, key: token} + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: OAUTH_INITIAL_ACCESS_TOKEN_FILE, value: /etc/skill-manager/oauth-registration/token} + - contains: + path: spec.template.spec.volumes + content: + name: oauth-registration + secret: + secretName: registration + defaultMode: 0440 + items: + - key: token + path: token + + - it: passes the MCP endpoint's allowed hosts and trusted origins + set: + mcp: + allowedHosts: [skills.example.com, skills.internal] + allowedOrigins: [https://portal.example.com] + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: {name: MCP_ALLOWED_HOSTS, value: "skills.example.com,skills.internal"} + - contains: + path: spec.template.spec.containers[0].env + content: {name: MCP_ALLOWED_ORIGINS, value: https://portal.example.com} + + - it: renders no allowed hosts or origins by default + asserts: + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: MCP_ALLOWED_HOSTS} + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: {name: MCP_ALLOWED_ORIGINS} diff --git a/helm/skill-manager/values.schema.json b/helm/skill-manager/values.schema.json index cbacf94..eeed669 100644 --- a/helm/skill-manager/values.schema.json +++ b/helm/skill-manager/values.schema.json @@ -161,6 +161,58 @@ "type": "object", "additionalProperties": true }, + "httpRoute": { + "type": "object", + "additionalProperties": false, + "properties": { + "annotations": { + "type": "object", + "description": "Annotations on the HTTPRoute.", + "additionalProperties": true + }, + "enabled": { + "type": "boolean", + "description": "Expose the service through a Gateway API HTTPRoute." + }, + "hostnames": { + "type": "array", + "description": "Hostnames matched by the route." + }, + "labels": { + "type": "object", + "description": "Labels on the HTTPRoute.", + "additionalProperties": true + }, + "parentRefs": { + "type": "array", + "description": "parentRefs of the HTTPRoute (required when enabled).", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "group": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "name": { + "type": "string" + }, + "namespace": { + "type": "string" + }, + "port": { + "type": "integer" + }, + "sectionName": { + "type": "string" + } + } + } + } + } + }, "image": { "type": "object", "additionalProperties": false, @@ -213,6 +265,20 @@ "type": "object", "additionalProperties": false, "properties": { + "allowedHosts": { + "type": "array", + "description": "Host header values the MCP endpoint answers besides its own address (`MCP_ALLOWED_HOSTS`): list the public host name when a proxy in the same pod forwards to it and keeps that host. Empty: every Host, except that a request arriving on a loopback listener needs a loopback host.", + "items": { + "type": "string" + } + }, + "allowedOrigins": { + "type": "array", + "description": "Browser origins (`https://host[:port]`) trusted to call the MCP endpoint from another origin (`MCP_ALLOWED_ORIGINS`). Empty: same-origin browsers and clients without browser headers (muster, agent-manager) only.", + "items": { + "type": "string" + } + }, "path": { "type": "string", "description": "MCP endpoint path." @@ -364,15 +430,56 @@ "type": "boolean", "description": "Create a Kubernetes NetworkPolicy for the pod." }, + "gatewayPeers": { + "type": "array", + "description": "NetworkPolicy peers allowed to reach the MCP endpoint and the REST API: muster, agentgateway and agent-manager. Pod selectors alone match the release namespace; add a `namespaceSelector` for a caller elsewhere.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "ipBlock": { + "type": "object", + "additionalProperties": true + }, + "namespaceSelector": { + "type": "object", + "additionalProperties": true + }, + "podSelector": { + "type": "object", + "additionalProperties": true + } + } + } + }, "ingressNamespaces": { "type": "array", - "description": "Namespaces allowed to reach the MCP endpoint and the REST API (label kubernetes.io/metadata.name), besides the release namespace. List muster's, agent-manager's and the portal's namespaces when they run elsewhere, or they cannot reach the server." + "description": "Deprecated: list a `gatewayPeers` entry with a `namespaceSelector`. Namespaces whose every pod may reach the API (label kubernetes.io/metadata.name), in addition to `gatewayPeers`." }, "metricsNamespaces": { "type": "array", - "description": "Namespaces allowed to scrape the metrics port (label kubernetes.io/metadata.name), when `observability.metrics.enabled`.", + "description": "Deprecated: list a `metricsPeers` entry. Namespaces whose every pod may scrape the metrics port, in addition to `metricsPeers`." + }, + "metricsPeers": { + "type": "array", + "description": "NetworkPolicy peers allowed to scrape the metrics port, when `observability.metrics.enabled`.", "items": { - "type": "string" + "type": "object", + "additionalProperties": false, + "properties": { + "ipBlock": { + "type": "object", + "additionalProperties": true + }, + "namespaceSelector": { + "type": "object", + "additionalProperties": true + }, + "podSelector": { + "type": "object", + "additionalProperties": true + } + } } } } @@ -388,11 +495,136 @@ "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 (`OAUTH_INITIAL_ACCESS_TOKEN_FILE`).", + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "name": { + "type": "string" + } + } + } + } + } + } + }, + "enabled": { + "type": "boolean", + "description": "Run the authorization server. Off makes skill-manager a resource server only (`OAUTH_ENABLE_AUTHORIZATION_SERVER=false`): no client secret is needed." + }, + "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://<fullname>.<global.domain>`." + }, + "storage": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Token storage (`OAUTH_STORAGE_BACKEND`). Memory loses every session on restart and is not shared between replicas.", + "enum": [ + "memory" + ] + } + } + }, + "upstream": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "The OpenID Provider people sign in with (`OAUTH_PROVIDER`).", + "enum": [ + "dex" + ] + }, + "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`, else `global.identity.clientId`." + }, + "secretKeyRef": { + "type": "object", + "description": "Secret key with the client secret, mounted as a file. Empty name uses the deprecated `oauth.existingSecret` (key `dex-client-secret`), else `global.identity.existingSecret`, else a Secret from the deprecated `oauth.dex.clientSecret`.", + "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://<fullname>.<global.domain>` when `global.domain` is set." + "description": "Deprecated: use `authorizationServer.issuer`." }, "dex": { "type": "object", @@ -400,11 +632,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 the `dex-ca-file` flag. Empty name falls back to `global.identity.ca.secretName` / `global.identity.ca.key`.", + "description": "Deprecated: use `authorizationServer.upstream.certificateAuthority`.", "additionalProperties": false, "properties": { "key": { @@ -417,25 +649,148 @@ }, "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`." } } }, "enabled": { "type": "boolean", - "description": "Make skill-manager an OAuth 2.1 resource server (mcp-oauth): the MCP endpoint and the REST API require a bearer token Dex issued, validated against Dex's JWKS when its audience is in `trustedAudiences`. muster forwards the session's Dex id_token (`muster.mcpServer.auth`); agent-manager and the portal forward the person's. Off: no authentication at all, and private repositories are refused; only for a server nothing but a trusted proxy can reach. Off by default only because it needs the installation's Dex: the `agent-platform` meta chart turns it on." + "description": "Make skill-manager an OAuth 2.1 resource server (mcp-oauth): the MCP endpoint and the REST API require a bearer token, and every call carries the caller. muster forwards the session's ID token (`muster.mcpServer.auth`); agent-manager and the portal forward the person's. They are accepted from the provider people sign in with (`resourceServer.trustedIssuers`). Off: no authentication at all, and private repositories are refused; only for a server nothing but a trusted proxy can reach. Off by default only because it needs the installation's Dex: the `agent-platform` meta chart turns it on." }, "existingSecret": { "type": "string", - "description": "Existing Secret with the Dex client secret under `dex-client-secret`. Empty falls back to `global.identity.existingSecret`; without that, the chart renders a Secret from `oauth.dex.clientSecret`." + "description": "Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. Existing Secret with the Dex client secret under `dex-client-secret`." + }, + "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 REST API and the MCP endpoint are always protected resources.", + "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", @@ -443,20 +798,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: 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." + "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 Dex 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" + } } } }, @@ -703,8 +1061,13 @@ }, "labels": { "type": "object", - "description": "Labels on the ServiceMonitor, beside the chart's own. The Giant Swarm observability platform routes a scrape to a Mimir tenant by `observability.giantswarm.io/tenant`; a monitor without it writes to no tenant.", - "additionalProperties": true + "description": "Labels on the ServiceMonitor, beside the chart's own. The Giant Swarm observability platform routes a scrape to a Mimir tenant by `observability.giantswarm.io/tenant`, which the ServiceMonitor requires.", + "additionalProperties": true, + "properties": { + "observability.giantswarm.io/tenant": { + "type": "string" + } + } } } }, diff --git a/helm/skill-manager/values.yaml b/helm/skill-manager/values.yaml index c001ae0..27b1738 100644 --- a/helm/skill-manager/values.yaml +++ b/helm/skill-manager/values.yaml @@ -31,7 +31,7 @@ fullnameOverride: "" # provides and this chart reads as fallbacks for `oauth.*`: # `global.identity.issuerUrl`, `global.identity.clientId`, # `global.identity.existingSecret`, `global.identity.ca.secretName` / `.key`, -# and `global.domain` for the OAuth base URL. Empty here; a chart installed on +# and `global.domain` for the OAuth issuer. Empty here; a chart installed on # its own sets `oauth.*` directly. global: {} # @schema type: object; additionalProperties: true @@ -117,62 +117,157 @@ serviceToken: mcp: # -- MCP endpoint path. path: /mcp + # -- Host header values the MCP endpoint answers besides its own address + # (`MCP_ALLOWED_HOSTS`): list the public host name when a proxy in the same + # pod forwards to it and keeps that host. Empty: every Host, except that a + # request arriving on a loopback listener needs a loopback host. + allowedHosts: [] # @schema item: string + # -- Browser origins (`https://host[:port]`) trusted to call the MCP + # endpoint from another origin (`MCP_ALLOWED_ORIGINS`). Empty: same-origin + # browsers and clients without browser headers (muster, agent-manager) only. + allowedOrigins: [] # @schema item: string oauth: # -- Make skill-manager an OAuth 2.1 resource server (mcp-oauth): the MCP - # endpoint and the REST API require a bearer token Dex issued, validated - # against Dex's JWKS when its audience is in `trustedAudiences`. muster - # forwards the session's Dex id_token (`muster.mcpServer.auth`); - # agent-manager and the portal forward the person's. Off: no - # authentication at all, and private repositories - # are refused; only for a server nothing but a trusted proxy can reach. Off - # by default only because it needs the installation's Dex: the - # `agent-platform` meta chart turns it on. + # endpoint and the REST API require a bearer token, and every call carries + # the caller. muster forwards the session's ID token + # (`muster.mcpServer.auth`); agent-manager and the portal forward the + # person's. They are accepted from the provider people sign in with + # (`resourceServer.trustedIssuers`). Off: no authentication at all, and + # private repositories are refused; only for a server nothing but a trusted + # proxy can reach. Off by default only because it needs the installation's + # Dex: the `agent-platform` meta chart turns it on. enabled: false - # -- Public base URL of this server: the issuer of its own OAuth metadata - # (https, or http on loopback). Empty derives - # `https://<fullname>.<global.domain>` 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 REST API and the MCP endpoint are + # always protected resources. + 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 skill-manager a resource + # server only (`OAUTH_ENABLE_AUTHORIZATION_SERVER=false`): no client + # secret is needed. + 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://<fullname>.<global.domain>`. + issuer: "" + upstream: + # -- The OpenID Provider people sign in with (`OAUTH_PROVIDER`). + type: dex # @schema enum: [dex] + # -- 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`, else `global.identity.clientId`. + id: "" + # -- Secret key with the client secret, mounted as a file. Empty name + # uses the deprecated `oauth.existingSecret` (key + # `dex-client-secret`), else `global.identity.existingSecret`, else a + # Secret from the deprecated `oauth.dex.clientSecret`. + 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 (`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 is not shared between replicas. + type: memory # @schema enum: [memory] + # -- Deprecated: use `authorizationServer.issuer`. baseURL: "" 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: 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 the `dex-ca-file` flag. Empty name falls back to - # `global.identity.ca.secretName` / `global.identity.ca.key`. + # -- Deprecated: use `authorizationServer.upstream.certificateAuthority`. caSecret: name: "" key: ca.crt - # -- Existing Secret with the Dex client secret under `dex-client-secret`. - # Empty falls back to `global.identity.existingSecret`; without that, the - # chart renders a Secret from `oauth.dex.clientSecret`. + # -- Deprecated: use `authorizationServer.upstream.client.secretKeyRef`. + # Existing Secret with the Dex client secret under `dex-client-secret`. existingSecret: "" - # -- OAuth client IDs whose Dex 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: 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. + # -- 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 muster: @@ -233,10 +328,22 @@ muster: networkPolicy: # -- Create a Kubernetes NetworkPolicy for the pod. enabled: true - # -- Namespaces allowed to reach the MCP endpoint and the REST API (label - # kubernetes.io/metadata.name), besides the release namespace. List - # muster's, agent-manager's and the portal's namespaces when they run - # elsewhere, or they cannot reach the server. + # -- NetworkPolicy peers allowed to reach the MCP endpoint and the REST + # API: muster, agentgateway and agent-manager. Pod selectors alone match + # the release namespace; add a `namespaceSelector` for a caller elsewhere. + gatewayPeers: # @schema item: object ; itemProperties: {podSelector: {type: object, additionalProperties: true}, namespaceSelector: {type: object, additionalProperties: true}, ipBlock: {type: object, additionalProperties: true}} + - podSelector: + matchLabels: + app.kubernetes.io/name: muster + - podSelector: + matchLabels: + app.kubernetes.io/name: agentgateway + - podSelector: + matchLabels: + app.kubernetes.io/name: agent-manager + # -- Deprecated: list a `gatewayPeers` entry with a `namespaceSelector`. + # Namespaces whose every pod may reach the API (label + # kubernetes.io/metadata.name), in addition to `gatewayPeers`. ingressNamespaces: [] # -- Allow egress on 443 to every destination: GitHub, OCI registries and # an external Dex. Vanilla NetworkPolicy cannot select by name; narrow with @@ -247,10 +354,19 @@ networkPolicy: allowInternet: true # -- Extra egress CIDRs. egressCIDRs: [] - # -- Namespaces allowed to scrape the metrics port (label - # kubernetes.io/metadata.name), when `observability.metrics.enabled`. - metricsNamespaces: - - kube-system + # -- NetworkPolicy peers allowed to scrape the metrics port, when + # `observability.metrics.enabled`. + metricsPeers: # @schema item: object ; itemProperties: {podSelector: {type: object, additionalProperties: true}, namespaceSelector: {type: object, additionalProperties: true}, ipBlock: {type: object, additionalProperties: true}} + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + app.kubernetes.io/name: alloy + app.kubernetes.io/instance: alloy-metrics + # -- Deprecated: list a `metricsPeers` entry. Namespaces whose every pod + # may scrape the metrics port, in addition to `metricsPeers`. + metricsNamespaces: [] serviceAccount: # -- Create a ServiceAccount. @@ -293,6 +409,18 @@ service: # -- Service port (the container listens on 8080). port: 8080 +httpRoute: + # -- Expose the service through a Gateway API HTTPRoute. + enabled: false + # -- parentRefs of the HTTPRoute (required when enabled). + parentRefs: [] # @schema item: object ; itemProperties: {name: {type: string}, namespace: {type: string}, sectionName: {type: string}, kind: {type: string}, group: {type: string}, port: {type: integer}} + # -- Hostnames matched by the route. + hostnames: [] + # -- Annotations on the HTTPRoute. + annotations: {} # @schema additionalProperties: true + # -- Labels on the HTTPRoute. + labels: {} # @schema additionalProperties: true + # -- Container resources. resources: requests: @@ -347,9 +475,9 @@ serviceMonitor: interval: "" # -- Labels on the ServiceMonitor, beside the chart's own. The Giant Swarm # observability platform routes a scrape to a Mimir tenant by - # `observability.giantswarm.io/tenant`; a monitor without it writes to no - # tenant. - labels: {} # @schema additionalProperties: true + # `observability.giantswarm.io/tenant`, which the ServiceMonitor requires. + labels: # @schema additionalProperties: true + observability.giantswarm.io/tenant: giantswarm logging: # -- Enable debug logging. diff --git a/internal/server/dexproxy_test.go b/internal/server/dexproxy_test.go index 2759658..16ffc8f 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,12 @@ func TestDexProviderFollowsProxyEnvironment(t *testing.T) { "-test.run=^TestDexProviderProxyChild$", "-test.count=1", "-test.v") command.Env = append(environmentWithoutProxy(), dexProxyChildEnv+"=1", + "OAUTH_ISSUER=https://skill-manager.example.com", + "OAUTH_PROVIDER=dex", + "OAUTH_DEX_ISSUER_URL=https://example.com", + "OAUTH_DEX_CLIENT_ID=skill-manager", + "OAUTH_DEX_CLIENT_SECRET=secret", + "OAUTH_TRUSTED_AUDIENCES=skill-manager", "HTTPS_PROXY="+proxy.server.URL, "NO_PROXY="+tc.noProxy, ) @@ -65,13 +72,15 @@ func TestDexProviderProxyChild(t *testing.T) { if os.Getenv(dexProxyChildEnv) != "1" { t.Skip("child process of TestDexProviderFollowsProxyEnvironment") } - _, err := newProvider(OAuthConfig{ - BaseURL: "https://skill-manager.example.com", - DexIssuerURL: "https://example.com", - DexClientID: "skill-manager", - DexClientSecret: "secret", - }, nil, slog.New(slog.DiscardHandler)) - t.Logf("newProvider: %v", err) + 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())) }) + } + t.Logf("OAuth setup: %v", err) } func environmentWithoutProxy() []string { diff --git a/internal/server/github_exchange.go b/internal/server/github_exchange.go index 0eeba2e..82d484c 100644 --- a/internal/server/github_exchange.go +++ b/internal/server/github_exchange.go @@ -3,6 +3,7 @@ package server import ( "context" "crypto/tls" + "crypto/x509" "errors" "fmt" "log/slog" @@ -138,3 +139,23 @@ func newGitHubExchange(configuration GitHubExchangeConfig, client *http.Client) } return catalog.GitHubGrant{App: app, Token: token} } + +// loadRootCAs is the system pool plus the PEM bundle at caFile; (nil, nil) +// without a file, selecting the system trust everywhere the pool is used. +func loadRootCAs(caFile string) (*x509.CertPool, error) { + if caFile == "" { + return nil, nil + } + pem, err := os.ReadFile(caFile) // #nosec G304 -- operator-provided path + if err != nil { + return nil, fmt.Errorf("read CA file %s: %w", caFile, err) + } + pool, err := x509.SystemCertPool() + if err != nil { + pool = x509.NewCertPool() + } + if !pool.AppendCertsFromPEM(pem) { + return nil, fmt.Errorf("no CA certificate in %s", caFile) + } + return pool, nil +} diff --git a/internal/server/http.go b/internal/server/http.go index 7ec71b9..43686c5 100644 --- a/internal/server/http.go +++ b/internal/server/http.go @@ -11,10 +11,10 @@ import ( "fmt" "log/slog" "net/http" - "net/url" "strings" "time" + "github.com/giantswarm/mcp-toolkit/httpx" mcpserver "github.com/mark3labs/mcp-go/server" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" @@ -31,6 +31,11 @@ type Config struct { // server's own, and every call carries the caller's identity. Off: // anonymous. OAuth *OAuthConfig + // Origins names the Host values a proxy in front of the listener keeps + // and the browser origins trusted on the MCP endpoint + // (httpx.OriginPolicyFromEnv). Empty: same-origin browsers and clients + // without browser headers only. + Origins httpx.OriginPolicy } // Server is the assembled HTTP server. @@ -85,15 +90,19 @@ func New(cfg Config, rest *api.REST, mcpSrv *mcpserver.MCPServer, log *slog.Logg mux.Handle(api.Prefix+"/", guarded) if mcpSrv != nil { + // Stateless: every request stands alone, so any replica answers it. + s.mcp = mcpserver.NewStreamableHTTPServer(mcpSrv, + mcpserver.WithEndpointPath(cfg.MCPPath), + mcpserver.WithStateLess(true), + mcpserver.WithAllowedHosts(cfg.Origins.AllowedHosts...)) + protected, err := httpx.ProtectOriginWith(s.guardMCP(s.mcp), cfg.Origins) + if err != nil { + return nil, fmt.Errorf("MCP origin policy: %w", err) + } // mcp-go reads a POST body whole before validating it // (CVE-2026-108859); the bound keeps that read to what the REST API // accepts. - s.mcp = mcpserver.NewStreamableHTTPServer(mcpSrv, mcpserver.WithEndpointPath(cfg.MCPPath)) - allowed := "" - if cfg.OAuth != nil { - allowed = origin(cfg.OAuth.BaseURL) - } - mux.Handle(cfg.MCPPath, http.MaxBytesHandler(checkOrigin(allowed, s.guardMCP(s.mcp)), maxMCPBodyBytes)) + mux.Handle(cfg.MCPPath, http.MaxBytesHandler(protected, maxMCPBodyBytes)) } s.http = &http.Server{ Addr: cfg.Addr, @@ -134,32 +143,6 @@ func (s *Server) guard(next http.Handler) http.Handler { return s.oauth.protectREST(next) } -// checkOrigin refuses an MCP request whose Origin header is present and not -// allowed with 403, as the Streamable HTTP transport requires against DNS -// rebinding. The MCP clients are servers (muster), which send no Origin; a -// browser is only admitted from allowed, this server's own public origin -// ("" admits none). -func checkOrigin(allowed string, next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if o := r.Header.Get("Origin"); o != "" && (allowed == "" || !strings.EqualFold(o, allowed)) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusForbidden) - _, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32600,"message":"origin not allowed"}}`)) - return - } - next.ServeHTTP(w, r) - }) -} - -// origin is the scheme://host[:port] of rawURL; "" when it has none. -func origin(rawURL string) string { - u, err := url.Parse(rawURL) - if err != nil || u.Scheme == "" || u.Host == "" { - return "" - } - return u.Scheme + "://" + u.Host -} - // maxMCPBodyBytes bounds an MCP request body, as the REST API bounds its own. const maxMCPBodyBytes = 1 << 20 @@ -194,7 +177,7 @@ func (s *Server) Run(ctx context.Context) error { } shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() - // The MCP sessions first: an open listening stream never goes idle, and + // The MCP streams first: an open listening stream never goes idle, and // Shutdown would wait for it to the deadline. if s.mcp != nil { if err := s.mcp.Shutdown(shutdownCtx); err != nil { diff --git a/internal/server/http_test.go b/internal/server/http_test.go index ce497f8..a54cf33 100644 --- a/internal/server/http_test.go +++ b/internal/server/http_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "github.com/giantswarm/mcp-toolkit/httpx" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -113,31 +114,68 @@ func TestShutdownClosesOpenMCPStreams(t *testing.T) { } } -// A request with a foreign Origin is refused before anything reads it; one -// without, as muster sends, and one from the server's own origin pass. -func TestMCPRefusesForeignOrigins(t *testing.T) { - ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) +// A browser request from a foreign origin is refused; one without browser +// headers, as muster sends, one from the server's own origin and one from a +// trusted origin pass. A proxy's Host is admitted once listed. +func TestMCPOriginPolicy(t *testing.T) { + svc := catalog.New(catalogtest.Lister{}, &catalogtest.Pinner{}) + srv, err := New(Config{Addr: "127.0.0.1:0", Origins: httpx.OriginPolicy{ + AllowedHosts: []string{"skills.example.com"}, + TrustedOrigins: []string{"https://portal.example.com"}, + }}, api.NewREST(svc, quiet()), api.NewMCPServer(svc, "test"), quiet()) + require.NoError(t, err) for name, tc := range map[string]struct { - allowed, origin string - want int + host, origin string + want int }{ - "no origin": {"https://skills.example.com", "", http.StatusOK}, - "own origin": {"https://skills.example.com", "https://skills.example.com", http.StatusOK}, - "foreign origin": {"https://skills.example.com", "https://evil.example", http.StatusForbidden}, - "null origin": {"https://skills.example.com", "null", http.StatusForbidden}, - "none allowed": {"", "http://localhost:8080", http.StatusForbidden}, - "none allowed, no hdr": {"", "", http.StatusOK}, + "no origin": {"skills.example.com", "", http.StatusOK}, + "own origin": {"skills.example.com", "https://skills.example.com", http.StatusOK}, + "trusted origin": {"skills.example.com", "https://portal.example.com", http.StatusOK}, + "foreign origin": {"skills.example.com", "https://evil.example", http.StatusForbidden}, + "unlisted host": {"evil.example", "", http.StatusForbidden}, + "listed, no port": {"skills.example.com:443", "", http.StatusOK}, } { t.Run(name, func(t *testing.T) { - r := httptest.NewRequest(http.MethodPost, "/mcp", nil) + body := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}` + r := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/mcp", strings.NewReader(body)) + r.Host = tc.host + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Accept", "application/json, text/event-stream") if tc.origin != "" { r.Header.Set("Origin", tc.origin) } w := httptest.NewRecorder() - checkOrigin(tc.allowed, ok).ServeHTTP(w, r) - assert.Equal(t, tc.want, w.Code) + srv.Handler().ServeHTTP(w, r) + assert.Equal(t, tc.want, w.Code, w.Body.String()) }) } - assert.Equal(t, "https://skills.example.com:8443", origin("https://skills.example.com:8443/mcp")) - assert.Empty(t, origin("not a url")) + require.Error(t, func() error { + _, err := New(Config{Origins: httpx.OriginPolicy{TrustedOrigins: []string{"portal.example.com"}}}, api.NewREST(svc, quiet()), api.NewMCPServer(svc, "test"), quiet()) + return err + }(), "a trusted origin without a scheme is refused") +} + +// The MCP endpoint is stateless: an initialize hands out no session, so any +// replica answers the next request. +func TestMCPIsStateless(t *testing.T) { + svc := catalog.New(catalogtest.Lister{}, &catalogtest.Pinner{}) + srv, err := New(Config{Addr: "127.0.0.1:0"}, api.NewREST(svc, quiet()), api.NewMCPServer(svc, "test"), quiet()) + require.NoError(t, err) + body := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}` + r := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/mcp", strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Accept", "application/json, text/event-stream") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, r) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + assert.Empty(t, w.Header().Get("Mcp-Session-Id")) + + list := `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}` + r = httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/mcp", strings.NewReader(list)) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Accept", "application/json, text/event-stream") + w = httptest.NewRecorder() + srv.Handler().ServeHTTP(w, r) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + assert.Contains(t, w.Body.String(), "list_skills", "a request without a session is answered") } diff --git a/internal/server/oauth.go b/internal/server/oauth.go index 766d437..946b122 100644 --- a/internal/server/oauth.go +++ b/internal/server/oauth.go @@ -3,185 +3,119 @@ package server import ( "context" "crypto/subtle" - "crypto/x509" "encoding/json" + "errors" "fmt" "log/slog" + "maps" "net/http" "net/url" - "os" "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" - "github.com/giantswarm/mcp-oauth/providers/dex" "github.com/giantswarm/mcp-oauth/providers/oidc" "github.com/giantswarm/mcp-oauth/security" - "github.com/giantswarm/mcp-oauth/storage/memory" + oauthserver "github.com/giantswarm/mcp-oauth/server" + "github.com/giantswarm/skill-manager/internal/api" "github.com/giantswarm/skill-manager/internal/identity" ) // OAuthConfig makes skill-manager an OAuth 2.1 resource server (mcp-oauth) -// in front of the MCP endpoint and the REST API, as agent-manager is. 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 agent-manager and the portal forward the person's -// id_token; it is validated here against the IdP's JWKS when its audience is -// one of TrustedAudiences (the platform's OAuth client). The caller's -// identity then travels with the request (identity package). +// in front of the MCP endpoint and the REST API. The OpenID Provider people +// sign in with is the authority: on the Agent Platform, muster forwards the +// session's ID token byte-identical (MCPServer auth.forwardToken), and +// agent-manager and the portal forward the person's ID token; it is +// validated against the provider's JWKS as a trusted issuer +// (OAUTH_TRUSTED_ISSUERS). The caller's identity then travels with the +// request (identity package). 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 - - // The platform's 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 - - // TrustedAudiences are the OAuth client ids whose IdP id_tokens are - // accepted as bearers (SSO token forwarding): the platform client, and - // the audiences the MCPServer requires — what the kube-apiserver trusts, - // which every token muster forwards carries by construction (the chart - // unions both). A portal session's id_token names the portal's own - // client, not the platform client. 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 // ServiceToken, when set, is a bearer the REST API admits as the // platform's own service caller (identity.ContextWithService): agent- // manager's migrate, which has no caller. Compared in constant time. ServiceToken string } -// 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 - } - if c.DexIssuerURL == "" || c.DexClientID == "" || c.DexClientSecret == "" { - return fmt.Errorf("oauth: dex issuer URL, client ID and client secret are required") - } - 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 *oauth.Server - handler *handler.Handler - store *memory.Store - cfg OAuthConfig - mcpPath string - log *slog.Logger + server *oauthserver.Server + handler *handler.Handler + cleanup func(context.Context) error + serviceToken string + mcpPath string + log *slog.Logger } func newOAuth(cfg OAuthConfig, mcpPath string, log *slog.Logger) (*oauthRuntime, error) { - if err := cfg.Validate(); err != nil { - return nil, err - } - rootCAs, err := loadRootCAs(cfg.DexCAFile) + settings := cfg.Settings + if settings.Server == nil { + return nil, errors.New("oauth: no server settings") + } + 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) } - provider, err := newProvider(cfg, rootCAs, log) - if err != nil { - return nil, err - } - store := memory.New() - srv, err := oauth.NewServer(provider, store, store, store, serverConfig(cfg, rootCAs), log, - oauth.WithAuditor(security.NewAuditor(log, true))) - if err != nil { - return nil, fmt.Errorf("oauth: server: %w", err) - } - log.Info("OAuth resource server enabled", "issuer", cfg.BaseURL, - "trustedAudiences", cfg.TrustedAudiences) - return &oauthRuntime{server: srv, handler: handler.New(srv, log), store: store, cfg: cfg, mcpPath: mcpPath, log: log}, nil -} - -// serverConfig is the mcp-oauth server configuration for cfg: this server's -// own issuer, the audiences it trusts as forwarded bearers and the CA bundle -// for the issuer's JWKS. -func serverConfig(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 newProvider(cfg OAuthConfig, rootCAs *x509.CertPool, log *slog.Logger) (providers.Provider, error) { - p, err := dex.NewProvider(&dex.Config{ - IssuerURL: cfg.DexIssuerURL, - ClientID: cfg.DexClientID, - ClientSecret: cfg.DexClientSecret, - RedirectURL: strings.TrimSuffix(cfg.BaseURL, "/") + "/oauth/callback", - RootCAs: rootCAs, - Logger: log, - }) - if err != nil { - return nil, fmt.Errorf("oauth: dex provider: %w", err) - } - return p, nil -} - -// loadRootCAs is the system pool plus the PEM bundle at caFile; (nil, nil) -// without a file, selecting the system trust everywhere the pool is used. -func loadRootCAs(caFile string) (*x509.CertPool, error) { - if caFile == "" { - return nil, nil + log.Info("OAuth resource server enabled", "issuer", serverConfig.Issuer, + "authorizationServer", !serverConfig.DisableAuthorizationServer, + "trustedAudiences", serverConfig.TrustedAudiences, "trustedIssuers", len(settings.TrustedIssuers)) + return &oauthRuntime{server: runtime.Server, handler: runtime.Handler, cleanup: cleanup, + serviceToken: cfg.ServiceToken, mcpPath: mcpPath, log: log}, nil +} + +// protectedResources adds the REST API and 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{} + } + // 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 } - pem, err := os.ReadFile(caFile) // #nosec G304 -- operator-provided path - if err != nil { - return nil, fmt.Errorf("read CA file %s: %w", caFile, err) + var advertised []string + if main, err := url.Parse(configuration.GetResourceIdentifier()); err == nil { + resource, _ := described(main.EscapedPath()) + advertised = resource.AuthorizationServers } - pool, err := x509.SystemCertPool() - if err != nil { - pool = x509.NewCertPool() - } - if !pool.AppendCertsFromPEM(pem) { - return nil, fmt.Errorf("no CA certificate in %s", caFile) + for _, path := range []string{api.Prefix, mcpPath} { + if path == "" || path == "/" { + continue + } + if _, ok := described(path); !ok { + resources[path] = oauthserver.ProtectedResourceConfig{AuthorizationServers: advertised} + } } - return pool, nil + return resources } func (o *oauthRuntime) register(mux *http.ServeMux) { - o.handler.RegisterAuthorizationServerMetadataRoutes(mux) - o.handler.RegisterProtectedResourceMetadataRoutes(mux, o.mcpPath) - mux.HandleFunc("/oauth/authorize", o.handler.ServeAuthorization) - mux.HandleFunc("/oauth/token", o.handler.ServeToken) - mux.HandleFunc("/oauth/callback", o.handler.ServeCallback) - mux.HandleFunc("/oauth/register", o.handler.ServeClientRegistration) - mux.HandleFunc("/oauth/revoke", o.handler.ServeTokenRevocation) - mux.HandleFunc("/oauth/introspect", o.handler.ServeTokenIntrospection) + o.handler.RegisterOAuthRoutes(mux, handler.OAuthRoutesOptions{MCPPath: o.mcpPath, IncludeMetadata: true}) } // 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 of a trusted issuer) +// and then attaches the caller to the request. func (o *oauthRuntime) protect(next http.Handler) http.Handler { return o.handler.ValidateToken(o.attachIdentity(next)) } @@ -192,8 +126,8 @@ func (o *oauthRuntime) protect(next http.Handler) http.Handler { func (o *oauthRuntime) protectREST(next http.Handler) http.Handler { plain := o.protect(next) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if o.cfg.ServiceToken != "" && r.Method == http.MethodPost && r.URL.Path == "/v1/resolve" && - subtle.ConstantTimeCompare([]byte(bearerToken(r)), []byte(o.cfg.ServiceToken)) == 1 { + if o.serviceToken != "" && r.Method == http.MethodPost && r.URL.Path == "/v1/resolve" && + subtle.ConstantTimeCompare([]byte(bearerToken(r)), []byte(o.serviceToken)) == 1 { ctx := identity.ContextWith(identity.ContextWithService(r.Context()), &identity.Identity{Subject: "service", Source: identity.SourceService}) next.ServeHTTP(w, r.WithContext(ctx)) return @@ -203,25 +137,24 @@ func (o *oauthRuntime) protectREST(next http.Handler) http.Handler { } // attachIdentity translates the validated mcp-oauth user into the request's -// identity. mcp-oauth also admits an IdP JWT whose audience is not trusted, -// through the IdP's userinfo endpoint (Dex answers for any token it signed); -// such a bearer is refused here, as agent-manager refuses it: only a -// trusted forwarded token or this server's own is a caller. +// identity, with the person's ID token: a forwarded one is the bearer +// itself, one this server issued has the provider's ID token stored next to +// it. A bearer that yields no ID token is refused: every caller is a person +// the provider signed in. func (o *oauthRuntime) attachIdentity(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. 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() { + if info.TokenSource == providers.TokenSourceSSO || info.TokenSource == providers.TokenSourceTrustedIssuer { id.Source = identity.SourceSSO } - idToken := o.idToken(ctx, r, info) - if idToken == "" { + idToken, err := handler.ProviderIDTokenFromContext(ctx) + if err != nil || idToken == "" { o.refuse(w, r, id) return } @@ -230,19 +163,16 @@ func (o *oauthRuntime) attachIdentity(next http.Handler) http.Handler { id.Delegated = true } } - o.log.Debug("authenticated request", "caller", id.String(), "source", id.Source, "path", r.URL.Path) + o.log.DebugContext(ctx, "authenticated request", slog.Any("user", info), "source", id.Source, "path", r.URL.Path) next.ServeHTTP(w, r.WithContext(identity.ContextWithToken(identity.ContextWith(ctx, id), idToken))) }) } -// refuse answers 401 for a caller mcp-oauth authenticated whose bearer is -// neither a trusted forwarded IdP token nor one of this server's own tokens -// with an IdP id_token stored next to it. An id_token for an untrusted -// audience never gets here; mcp-oauth refuses it and logs its aud next to the -// trusted audiences. +// refuse answers 401 for a caller mcp-oauth authenticated whose bearer yields +// no provider ID token. func (o *oauthRuntime) refuse(w http.ResponseWriter, r *http.Request, id *identity.Identity) { - const reason = "the bearer is neither an ID token of a trusted audience nor a token this server issued" - o.log.Warn("request refused: "+reason, "caller", id.String(), "source", id.Source, "path", r.URL.Path) + const reason = "the bearer is neither an ID token of a trusted issuer nor a token this server issued" + o.log.Warn("request refused: "+reason, "source", id.Source, "path", r.URL.Path) w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token", error_description="`+reason+`"`) writeError(w, http.StatusUnauthorized, "unauthorized: "+reason) } @@ -258,54 +188,12 @@ func bearerToken(r *http.Request) string { return strings.TrimSpace(token) } -// idToken is the caller's IdP token: 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. "" for any other bearer mcp-oauth admitted. -func (o *oauthRuntime) idToken(ctx context.Context, r *http.Request, info *providers.UserInfo) string { - bearer := bearerToken(r) - if bearer == "" { - return "" - } - if info.IsSSO() { - return bearer - } - tok, err := o.store.GetToken(ctx, bearer) - if err != nil || tok == nil { - return "" - } - // mcp-oauth keeps the provider's id_token as the oauth2 token extra. - idToken, _ := tok.Extra("id_token").(string) - return idToken -} - func (o *oauthRuntime) shutdown(ctx context.Context) { - // Shutdown stops the stores it was given. - if err := o.server.Shutdown(ctx); err != nil { + if err := o.cleanup(ctx); err != nil { 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) - } -} - // writeError is a refusal as the REST API's JSON error body. func writeError(w http.ResponseWriter, status int, message string) { w.Header().Set("Content-Type", "application/json") diff --git a/internal/server/oauth_realchain_test.go b/internal/server/oauth_realchain_test.go index a944ee9..028ca56 100644 --- a/internal/server/oauth_realchain_test.go +++ b/internal/server/oauth_realchain_test.go @@ -212,28 +212,29 @@ func resolveTestHosts(t *testing.T, ip net.IP, hosts ...string) { } func (p *privateIdP) idToken(t *testing.T, aud []string) string { + t.Helper() + return p.idTokenWith(t, aud, nil) +} + +// idTokenWith mints an ID token for aud with the claims of extra added. +func (p *privateIdP) idTokenWith(t *testing.T, aud []string, extra map[string]any) string { t.Helper() signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: p.key}, (&jose.SignerOptions{}).WithHeader("kid", privateTestKID).WithType("JWT")) require.NoError(t, err) claims := jwt.Claims{Issuer: p.issuer, Subject: "sub-admin", Audience: jwt.Audience(aud), Expiry: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute))} - extra := map[string]any{"email": "admin@lab.local", "email_verified": true, "name": "Lab Admin", "groups": []string{"platform-admins"}} - tok, err := jwt.Signed(signer).Claims(claims).Claims(extra).Serialize() + profile := map[string]any{"email": "admin@lab.local", "email_verified": true, "name": "Lab Admin", "groups": []string{"platform-admins"}} + tok, err := jwt.Signed(signer).Claims(claims).Claims(profile).Claims(extra).Serialize() require.NoError(t, err) return tok } -func (p *privateIdP) config(jwksHosts ...string) OAuthConfig { - return OAuthConfig{ - BaseURL: "http://localhost:8080", - 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 REST request with bearer through the production @@ -269,14 +270,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 API") } @@ -287,10 +288,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 9a9d2a9..f884447 100644 --- a/internal/server/oauth_test.go +++ b/internal/server/oauth_test.go @@ -21,14 +21,12 @@ import ( "testing" "time" - oauth "github.com/giantswarm/mcp-oauth" - "github.com/giantswarm/mcp-oauth/handler" - "github.com/giantswarm/mcp-oauth/providers" - "github.com/go-jose/go-jose/v4" - "github.com/go-jose/go-jose/v4/jwt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/giantswarm/mcp-oauth/oauthconfig" + oauthserver "github.com/giantswarm/mcp-oauth/server" + "github.com/giantswarm/skill-manager/internal/api" "github.com/giantswarm/skill-manager/internal/catalog" "github.com/giantswarm/skill-manager/internal/catalog/catalogtest" @@ -36,23 +34,16 @@ import ( ) // fakeIdP is a minimal OIDC issuer on https://localhost: a discovery -// document, enough for mcp-oauth's Dex provider to boot, and a key to mint -// id_tokens the way the platform's Dex does. +// document, enough for mcp-oauth's Dex provider to boot. type fakeIdP struct { issuer string - key *rsa.PrivateKey caFile string srv *httptest.Server } -const testKID = "test-key" - func newFakeIdP(t *testing.T) *fakeIdP { t.Helper() - key, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err) - - idp := &fakeIdP{key: key} + idp := &fakeIdP{} mux := http.NewServeMux() mux.HandleFunc("/dex/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { _ = json.NewEncoder(w).Encode(map[string]any{ @@ -109,129 +100,159 @@ func selfSignedLocalhost(t *testing.T) tls.Certificate { return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} } -// idToken mints an id_token the fake IdP signed. -func (f *fakeIdP) idToken(t *testing.T, aud []string, exp time.Time) string { +func (f *fakeIdP) config(t *testing.T) OAuthConfig { t.Helper() - signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: f.key}, - (&jose.SignerOptions{}).WithHeader("kid", testKID).WithType("JWT")) - require.NoError(t, err) - claims := jwt.Claims{Issuer: f.issuer, Subject: "sub-admin", Audience: jwt.Audience(aud), - Expiry: jwt.NewNumericDate(exp), IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute))} - extra := map[string]any{"email": "admin@lab.local", "email_verified": true, "name": "Lab Admin", "groups": []string{"platform-admins"}} - tok, err := jwt.Signed(signer).Claims(claims).Claims(extra).Serialize() - require.NoError(t, err) - return tok + return OAuthConfig{Settings: oauthSettings(t, dexEnvironment(f.issuer, f.caFile))} } -func (f *fakeIdP) config() OAuthConfig { - return OAuthConfig{ - BaseURL: "http://localhost:8080", - DexIssuerURL: f.issuer, - DexClientID: "agent-platform", - DexClientSecret: "lab-only", - DexCAFile: f.caFile, - TrustedAudiences: []string{"agent-platform"}, +// 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 := range []string{"OAUTH_TRUSTED_ISSUERS", "OAUTH_TRUSTED_AUDIENCES", "OAUTH_ENABLE_AUTHORIZATION_SERVER", + "OAUTH_AUTHORIZATION_SERVERS", "OAUTH_ALLOW_PRIVATE_IP_JWKS_HOSTS", "OAUTH_PROVIDER"} { + t.Setenv(name, "") + } + for name, value := range environment { + t.Setenv(name, value) + } + settings, err := oauthconfig.SettingsFromEnv() + require.NoError(t, err) + return settings +} + func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } -func TestOAuthConfigValidation(t *testing.T) { - dexOK := OAuthConfig{BaseURL: "https://am.example.com", DexIssuerURL: "x", DexClientID: "y", DexClientSecret: "z"} - require.Error(t, OAuthConfig{}.Validate()) - require.Error(t, OAuthConfig{BaseURL: "http://am.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://am.example.com"}.Validate(), "dex needs issuer + client") - bad := dexOK - bad.TrustedAudiences = []string{"agent-platform", " "} - require.Error(t, bad.Validate(), "empty audience") -} +// TestForwardedIDTokenBecomesTheCaller is the platform path: muster (or the +// portal through the gateway) forwards the provider's ID token; once +// mcp-oauth has validated it, the request carries the caller and the token. +// It holds both for the deprecated trusted audiences and for a trusted +// issuer marked as the OpenID Provider, which the chart renders. +func TestForwardedIDTokenBecomesTheCaller(t *testing.T) { + idp := newPrivateIdP(t, "") + for name, environment := range map[string]map[string]string{ + "trusted audiences": dexEnvironment(idp.issuer, idp.caFile), + "trusted issuer": trustedIssuerEnvironment(idp), + } { + t.Run(name, func(t *testing.T) { + o, err := newOAuth(OAuthConfig{Settings: oauthSettings(t, environment)}, "/mcp", quiet()) + require.NoError(t, err) + require.True(t, o.server.Config.EnableClientIDMetadataDocuments) + t.Cleanup(func() { o.shutdown(context.WithoutCancel(t.Context())) }) + + var seen struct { + id *identity.Identity + token string + ok bool + } + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen.id, seen.ok = identity.FromContext(r.Context()) + seen.token, _ = identity.TokenFromContext(r.Context()) + w.WriteHeader(http.StatusNoContent) + }) + call := func(bearer string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/v1/sources", nil) + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + rec := httptest.NewRecorder() + o.protect(next).ServeHTTP(rec, req) + return rec + } + + forwarded := idp.idToken(t, []string{"agent-platform"}) + rec := call(forwarded) + 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) + assert.False(t, seen.id.Delegated) + assert.Equal(t, forwarded, seen.token, "the forwarded ID token is the caller's token") -// verifiedUser is the user mcp-oauth hands on once it has validated a -// forwarded IdP id_token. -func verifiedUser() *providers.UserInfo { - return &providers.UserInfo{ID: "sub-admin", Email: "admin@lab.local", EmailVerified: true, Name: "Lab Admin", Groups: []string{"platform-admins"}, TokenSource: providers.TokenSourceSSO} + assert.Equal(t, http.StatusUnauthorized, call(idp.idToken(t, []string{"portal-client"})).Code, "an untrusted audience is refused") + assert.Equal(t, http.StatusUnauthorized, call("").Code, "no token, no caller") + }) + } } -// afterValidation runs next as if mcp-oauth had validated the bearer and -// admitted info. -func afterValidation(info *providers.UserInfo, next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - next.ServeHTTP(w, r.WithContext(handler.ContextWithUserInfo(r.Context(), info))) - }) +// trustedIssuerEnvironment is the OAUTH_* configuration the chart renders: +// the provider as a trusted issuer marked as the OpenID Provider. +func trustedIssuerEnvironment(idp *privateIdP) map[string]string { + environment := dexEnvironment(idp.issuer, idp.caFile) + environment["OAUTH_TRUSTED_AUDIENCES"] = "" + environment["OAUTH_TRUSTED_ISSUERS"] = `[{"issuer":"` + idp.issuer + `","jwksURI":"` + idp.issuer + `/keys","audiences":["agent-platform"],` + + `"acceptedTypHeaders":["","JWT"],"openIDProvider":true,"allowPrivateIPJWKSHosts":["` + privateIssuerHost + `"],"caFile":"` + idp.caFile + `"}]` + return environment } -// TestForwardedIDTokenBecomesTheCaller is the platform path: muster (or the -// portal through the gateway) forwards the IdP id_token for the platform -// client; once mcp-oauth has validated it, the request carries the caller. -func TestForwardedIDTokenBecomesTheCaller(t *testing.T) { - idp := newFakeIdP(t) - o, err := newOAuth(idp.config(), "/mcp", quiet()) +// An ID token carrying act marks the caller as delegated, so the person's +// GitHub grant is never fetched for it. mcp-oauth admits a delegated token +// only through a trusted issuer. +func TestAttachIdentityMarksDelegatedCallers(t *testing.T) { + idp := newPrivateIdP(t, "") + o, err := newOAuth(OAuthConfig{Settings: oauthSettings(t, trustedIssuerEnvironment(idp))}, "/mcp", quiet()) require.NoError(t, err) - require.True(t, o.server.Config.EnableClientIDMetadataDocuments) - t.Cleanup(func() { o.shutdown(context.Background()) }) - - var seen struct { - id *identity.Identity - token string - ok bool - } - next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - seen.id, seen.ok = identity.FromContext(r.Context()) - seen.token, _ = identity.TokenFromContext(r.Context()) - w.WriteHeader(http.StatusNoContent) - }) - call := func(info *providers.UserInfo, bearer string) *httptest.ResponseRecorder { + t.Cleanup(func() { o.shutdown(context.WithoutCancel(t.Context())) }) + for _, scenario := range []struct { + extra map[string]any + delegated bool + }{ + {}, + {extra: map[string]any{"act": map[string]any{"iss": "https://muster.example.com", "sub": "agent"}}, delegated: true}, + } { + var seen *identity.Identity + h := o.protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen, _ = identity.FromContext(r.Context()) + })) req := httptest.NewRequest(http.MethodGet, "/v1/sources", nil) - req.Header.Set("Authorization", "Bearer "+bearer) + req.Header.Set("Authorization", "Bearer "+idp.idTokenWith(t, []string{"agent-platform"}, scenario.extra)) rec := httptest.NewRecorder() - afterValidation(info, o.attachIdentity(next)).ServeHTTP(rec, req) - return rec + h.ServeHTTP(rec, req) + require.NotNil(t, seen, "%d %s %s", rec.Code, rec.Header().Get("WWW-Authenticate"), rec.Body.String()) + require.Equal(t, scenario.delegated, seen.Delegated) } +} - forwarded := idp.idToken(t, []string{"agent-platform"}, time.Now().Add(30*time.Minute)) - rec := call(verifiedUser(), forwarded) - 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) - assert.Equal(t, forwarded, seen.token, "the forwarded id_token is the caller's token") - - // mcp-oauth also admits an IdP JWT of an untrusted audience through the - // IdP's userinfo endpoint, without the SSO flag: no caller. - userinfo := verifiedUser() - userinfo.TokenSource = providers.TokenSourceOAuth - rec = call(userinfo, idp.idToken(t, []string{"portal-client", "kubernetes"}, time.Now().Add(30*time.Minute))) - assert.Equal(t, http.StatusUnauthorized, rec.Code) - assert.Contains(t, rec.Header().Get("WWW-Authenticate"), `error="invalid_token"`) - - // Nothing admitted, nothing attached. - rec = httptest.NewRecorder() - o.attachIdentity(next).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/v1/sources", nil)) +// Without a validated user nothing is attached. +func TestAttachIdentityWithoutUser(t *testing.T) { + o := &oauthRuntime{log: quiet()} + rec := httptest.NewRecorder() + o.attachIdentity(http.NotFoundHandler()).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/v1/sources", nil)) assert.Equal(t, http.StatusUnauthorized, rec.Code) } -func TestServerConfig(t *testing.T) { - pool := x509.NewCertPool() - cfg := OAuthConfig{ - BaseURL: "https://sm.example.com", - TrustedAudiences: []string{"agent-platform", "kubernetes"}, - AllowPrivateIPJWKSHosts: []string{"keys.internal.example"}, - AllowPublicClientRegistration: true, - } - assert.Equal(t, &oauth.ServerConfig{ - EnableClientIDMetadataDocuments: true, - Issuer: "https://sm.example.com", - AllowRefreshTokenRotation: true, - AllowPublicClientRegistration: true, - MaxClientsPerIP: 10, - TrustedAudiences: []string{"agent-platform", "kubernetes"}, - AllowPrivateIPJWKSHosts: []string{"keys.internal.example"}, - JWKSRootCAs: pool, - }, serverConfig(cfg, pool)) +func TestProtectedResources(t *testing.T) { + advertised := []string{"https://dex.example.com"} + configuration := &oauthserver.Config{Issuer: "https://sm.example.com", ResourceMetadataByPath: map[string]oauthserver.ProtectedResourceConfig{ + "/": {ResourceIdentifier: "https://sm.example.com", AuthorizationServers: advertised}, + "/mcp": {ResourceIdentifier: "https://sm.example.com/mcp", ScopesSupported: []string{"skills"}}, + }} + assert.Equal(t, map[string]oauthserver.ProtectedResourceConfig{ + "/": {ResourceIdentifier: "https://sm.example.com", AuthorizationServers: advertised}, + "/mcp": {ResourceIdentifier: "https://sm.example.com/mcp", ScopesSupported: []string{"skills"}}, + api.Prefix: {AuthorizationServers: advertised}, + }, protectedResources(configuration, "/mcp"), "a configured path keeps its entry; an added one advertises the main resource's servers") + assert.Len(t, configuration.ResourceMetadataByPath, 2, "the configuration is not changed") + + assert.Equal(t, map[string]oauthserver.ProtectedResourceConfig{api.Prefix: {}, "/mcp": {}}, + protectedResources(&oauthserver.Config{Issuer: "https://sm.example.com"}, "/mcp"), "nothing advertised: the server's own issuer") } // TestServerGuardsRESTAndMCPButNotProbes wires OAuth through the assembled @@ -240,7 +261,7 @@ func TestServerConfig(t *testing.T) { func TestServerGuardsRESTAndMCPButNotProbes(t *testing.T) { idp := newFakeIdP(t) svc := catalog.New(catalogtest.Lister{}, &catalogtest.Pinner{}) - cfg := idp.config() + cfg := idp.config(t) srv, err := New(Config{Addr: "127.0.0.1:0", OAuth: &cfg}, api.NewREST(svc, quiet()), api.NewMCPServer(svc, "test"), quiet()) require.NoError(t, err) t.Cleanup(func() { srv.oauth.shutdown(context.Background()) }) @@ -285,30 +306,6 @@ func TestBearerTokenMatchesTheSchemeCaseInsensitively(t *testing.T) { } } -// An ID token carrying act marks the caller as delegated, so the person's -// GitHub grant is never fetched for it. -func TestAttachIdentityMarksDelegatedCallers(t *testing.T) { - o := &oauthRuntime{log: quiet()} - for _, scenario := range []struct { - token string - delegated bool - }{ - {token: unsignedJWT(`{"sub":"alice"}`)}, - {token: unsignedJWT(`{"sub":"alice","act":{"sub":"agent"}}`), delegated: true}, - } { - var seen *identity.Identity - h := o.attachIdentity(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - seen, _ = identity.FromContext(r.Context()) - })) - req := httptest.NewRequest(http.MethodGet, "/v1/sources", nil) - req.Header.Set("Authorization", "Bearer "+scenario.token) - req = req.WithContext(handler.ContextWithUserInfo(req.Context(), &providers.UserInfo{ID: "alice", TokenSource: providers.TokenSourceSSO})) - h.ServeHTTP(httptest.NewRecorder(), req) - require.NotNil(t, seen) - require.Equal(t, scenario.delegated, seen.Delegated) - } -} - // newLocalhostTLSServer serves TLS with a certificate that covers the // hostname localhost. func newLocalhostTLSServer(t *testing.T, handler http.Handler) *httptest.Server { @@ -324,3 +321,66 @@ func newLocalhostTLSServer(t *testing.T, handler http.Handler) *httptest.Server func localhostURL(srv *httptest.Server) string { return strings.Replace(srv.URL, "127.0.0.1", "localhost", 1) } + +// With the authorization server off the server starts without a Dex client, +// validates a forwarded Dex ID token as a trusted issuer's, advertises Dex in +// its protected resource metadata and serves no authorization server +// endpoint. +func TestResourceServerOnlyValidatesForwardedDexToken(t *testing.T) { + idp := newPrivateIdP(t, "") + environment := map[string]string{ + "OAUTH_ISSUER": "https://skills.example.com", + "OAUTH_ENABLE_AUTHORIZATION_SERVER": "false", + "OAUTH_AUTHORIZATION_SERVERS": idp.issuer, + "OAUTH_TRUSTED_ISSUERS": `[{"issuer":"` + idp.issuer + `","jwksURI":"` + idp.issuer + `/keys","audiences":["agent-platform"],` + + `"acceptedTypHeaders":["","JWT"],"openIDProvider":true,"allowPrivateIPJWKSHosts":["` + privateIssuerHost + `"],"caFile":"` + idp.caFile + `"}]`, + "OAUTH_PROVIDER": "", + "OAUTH_DEX_ISSUER_URL": "", + "OAUTH_DEX_CLIENT_ID": "", + "OAUTH_DEX_CLIENT_SECRET": "", + "OAUTH_ENABLE_CLIENT_ID_METADATA_DOCUMENTS": "", + } + cfg := OAuthConfig{Settings: oauthSettings(t, environment)} + require.Nil(t, cfg.Settings.Dex, "no Dex client") + svc := catalog.New(catalogtest.Lister{}, &catalogtest.Pinner{}) + srv, err := New(Config{Addr: "127.0.0.1:0", OAuth: &cfg}, api.NewREST(svc, quiet()), api.NewMCPServer(svc, "test"), quiet()) + require.NoError(t, err) + t.Cleanup(func() { srv.oauth.shutdown(context.WithoutCancel(t.Context())) }) + require.True(t, srv.oauth.server.Config.DisableAuthorizationServer) + + call := func(path, bearer string) *httptest.ResponseRecorder { + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil) + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + rec := httptest.NewRecorder() + srv.Handler().ServeHTTP(rec, req) + return rec + } + rec := call("/v1/sources", idp.idToken(t, []string{"agent-platform"})) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Equal(t, http.StatusUnauthorized, call("/v1/sources", idp.idToken(t, []string{"portal-client"})).Code, "an untrusted audience is refused") + assert.Equal(t, http.StatusUnauthorized, call("/v1/sources", "").Code) + + for _, path := range []string{"/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp", "/.well-known/oauth-protected-resource/v1"} { + rec := call(path, "") + assert.Equal(t, http.StatusOK, rec.Code, path) + assert.Contains(t, rec.Body.String(), `"authorization_servers":["`+idp.issuer+`"]`, path) + } + for _, path := range []string{"/.well-known/oauth-authorization-server", "/oauth/authorize", "/oauth/token", "/oauth/register", "/oauth/callback", "/oauth/introspect"} { + assert.Equal(t, http.StatusNotFound, call(path, "").Code, path) + } +} + +// The authorization server, when on, serves no token introspection. +func TestIntrospectionIsOff(t *testing.T) { + idp := newPrivateIdP(t, "") + cfg := idp.config(t) + svc := catalog.New(catalogtest.Lister{}, &catalogtest.Pinner{}) + srv, err := New(Config{Addr: "127.0.0.1:0", OAuth: &cfg}, api.NewREST(svc, quiet()), api.NewMCPServer(svc, "test"), quiet()) + require.NoError(t, err) + t.Cleanup(func() { srv.oauth.shutdown(context.WithoutCancel(t.Context())) }) + rec := httptest.NewRecorder() + srv.Handler().ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/oauth/introspect", nil)) + assert.Equal(t, http.StatusNotFound, rec.Code) +}