diff --git a/cmd/mecak8s/identity_broker_harness_test.go b/cmd/mecak8s/identity_broker_harness_test.go index ad4dbb8f67..c9a89c699e 100644 --- a/cmd/mecak8s/identity_broker_harness_test.go +++ b/cmd/mecak8s/identity_broker_harness_test.go @@ -299,15 +299,20 @@ const ( // gatewayClientSecretEnv names the protected route's client secret, // which ToolHive reads at construction. gatewayClientSecretEnv = "MECATL_TEST_CALENDAR_CLIENT_SECRET" // #nosec G101 -- environment variable name, not a credential. + // gatewaySigningKeyPlaceholder stands in gatewaySettings for the path of + // the embedded gateway's signing key, which each test writes. + gatewaySigningKeyPlaceholder = "/GATEWAY-SIGNING-KEY.pem" ) // gatewaySettings declares the protected calendar route the gateway routes, -// in broker mode, the way an operator configures mecak8s's MCP servers. The +// in broker mode, the way an operator configures mecak8s's MCP servers, with +// the embedded gateway's signing key at gatewaySigningKeyPlaceholder. The // upstream is never dialled: the vMCP holds no upstream token for it. const gatewaySettings = `mcp: mode: broker broker: callback_url: ` + gatewayCallbackURL + ` + signing_key_file: ` + gatewaySigningKeyPlaceholder + ` servers: - name: calendar url: https://mcp.example/calendar @@ -344,13 +349,13 @@ const gatewaySettings = `mcp: // TestIdentityBrokerSessionToolCallThroughGateway: // // stand-in retired by -// test-only AS-2 trust and gateway seam #2533 and #2538 -// (IdentityBrokerAS2Trust, -// IdentityBrokerGatewayServers); AS-2's test -// trust names Alice's AS-1 subject, which -// exists only after her sign-in, so these -// tests run the real AS-1 outside mecak8s -// rather than the one mecak8s hosts +// test-only AS-2 trust (IdentityBrokerAS2Trust), #2533 +// which a gateway entry routing servers +// requires; AS-2's test trust names Alice's +// AS-1 subject, which exists only after her +// sign-in, so these tests run the real AS-1 +// outside mecak8s rather than the one +// mecak8s hosts // the embedded vMCP as the gateway, reached #2812 // in process // no gateway stand-in: the vMCP is real, but #2537 @@ -646,7 +651,8 @@ func serveGatewayIdentityBroker(t *testing.T, extraSettings string, extraArgs [] as1HTTP.Transport = faults t.Setenv(gatewayClientSecretEnv, "construction-only-secret") settings := filepath.Join(t.TempDir(), "settings.yaml") - if err := os.WriteFile(settings, []byte(gatewaySettings+extraSettings), 0o600); err != nil { + signingKey := brokerconfigtest.WriteKey(t, filepath.Join(t.TempDir(), "gateway-signing-key.pem"), brokerconfigtest.NewKey(t)) + if err := os.WriteFile(settings, []byte(strings.Replace(gatewaySettings, gatewaySigningKeyPlaceholder, signingKey, 1)+extraSettings), 0o600); err != nil { t.Fatal(err) } caFile := h.WriteCACert(t, t.TempDir()) @@ -659,9 +665,9 @@ func serveGatewayIdentityBroker(t *testing.T, extraSettings string, extraArgs [] Now: func() time.Time { return time.Now().Add(time.Duration(gw.clockOffset.Load())) }, }, identityBrokerServeOptions{ clientKey: a.Key, + gateways: []identitybroker.GatewayEntry{brokerconfigtest.EmbeddedGateway(gatewayAS2Issuer, "calendar")}, args: append([]string{"--permission-config", settings}, extraArgs...), edit: func(cfg *app.Config) { - cfg.IdentityBrokerGatewayServers = []string{"calendar"} cfg.IdentityBrokerAS2Trust = mcpbrokertest.TrustAS1(mcpbrokertest.AS1Trust{ Issuer: a.Issuer(), JWKSURL: a.JWKSURL(), CAFile: caFile, Subjects: []string{as1servertest.Subject(t, alice)}, @@ -675,6 +681,40 @@ func serveGatewayIdentityBroker(t *testing.T, extraSettings string, extraArgs [] return gw } +// TestGatewaySigningKeySettingNeedsAnEmbeddedGatewayEntry: mecak8s reads the +// embedded gateway's signing key from settings.yaml and refuses it without +// the identity broker and an embedded gateway entry in its configuration +// file. It is not parallel: the protected route's client secret is read from +// an environment variable. +func TestGatewaySigningKeySettingNeedsAnEmbeddedGatewayEntry(t *testing.T) { + t.Setenv(gatewayClientSecretEnv, "construction-only-secret") + settings := filepath.Join(t.TempDir(), "settings.yaml") + signingKey := brokerconfigtest.WriteKey(t, filepath.Join(t.TempDir(), "gateway-signing-key.pem"), brokerconfigtest.NewKey(t)) + if err := os.WriteFile(settings, []byte(strings.Replace(gatewaySettings, gatewaySigningKeyPlaceholder, signingKey, 1)), 0o600); err != nil { + t.Fatal(err) + } + base := []string{"--mock", "--no-shell", "--permission-mode=yolo", "--guardrails=off", "--session-lease-k8s-namespace", "", "--permission-config", settings} + for name, args := range map[string][]string{ + "identity broker off": base, + "no gateway entry": append(slices.Clone(base), "--enable-identity-broker", "--identity-broker-config", brokerconfigtest.Write(t, brokerconfigtest.Options{}).Path), + } { + t.Run(name, func(t *testing.T) { + cfg, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + built, err := buildIsolated(t, t.Context(), appConfig(cfg, port.NopDiagnostics{}, observability{})) + if err == nil { + built.Close() + t.Fatal("app.Build accepted the signing key") + } + if !strings.Contains(err.Error(), "mcp.broker.signing_key_file requires the identity broker") { + t.Fatalf("app.Build error = %v, want the signing key refused", err) + } + }) + } +} + // gatewayToolScript is a mock model whose first and third turns call the // gateway route's echo tool, each with its own call ID. const gatewayToolScript = `{"turns":[ @@ -1001,6 +1041,8 @@ type identityBrokerServeOptions struct { // clientKey is the broker client key, the key the AS-1 registered; nil // generates one. clientKey *ecdsa.PrivateKey + // gateways are the configuration file's gateway entries. + gateways []identitybroker.GatewayEntry // args are further flags. args []string // edit, when set, changes the application configuration before the @@ -1016,7 +1058,7 @@ type identityBrokerServeOptions struct { // the built application; both stop when t ends. func serveIdentityBroker(t *testing.T, tokens identityBrokerAS1Tokens, as1 *app.IdentityBrokerAS1, opts identityBrokerServeOptions) (string, *app.Built) { t.Helper() - brokerFile := brokerconfigtest.Write(t, brokerconfigtest.Options{BrokerClientKey: opts.clientKey}).Path + brokerFile := brokerconfigtest.Write(t, brokerconfigtest.Options{BrokerClientKey: opts.clientKey, Gateways: opts.gateways}).Path cfg, err := parseFlags(append([]string{ "--mock", "--enable-identity-broker", "--no-shell", // the identity broker refuses to run beside a shell diff --git a/deploy/helm/mecak8s/gateway_entry_test.go b/deploy/helm/mecak8s/gateway_entry_test.go new file mode 100644 index 0000000000..79eaac6ceb --- /dev/null +++ b/deploy/helm/mecak8s/gateway_entry_test.go @@ -0,0 +1,194 @@ +package mecak8s_test + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + + "github.com/stacklok/mecatl/internal/identitybroker" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/brokerconfig" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/brokerconfig/brokerconfigtest" +) + +// gatewayEntryValues adds to the production identity broker profile a +// protected MCP server, an embedded gateway entry for the embedded gateway +// mecak8s derives from its callback URL, and the embedded gateway's signing +// key with a fallback. +const gatewayEntryValues = ` +mcp: + broker: + callbackURL: https://mecatl.example.com/v1/mcp/authorization/callback + signingKey: + secretName: mcp-gateway-signing + key: key.pem + fallbacks: + - {secretName: mcp-gateway-signing-old, key: key.pem} + servers: + - name: calendar + url: https://calendar.example.com/mcp + auth: + mode: oauth + oauth: + issuer: https://calendar.example.com + client: + mode: preregistered + preregistered: + id: mecatl + secretKeyRef: {name: calendar-oauth, key: client-secret} + scopes: [openid] + network: {additionalOrigins: [], privateOrigins: [], maxRedirects: 0} +identityBroker: + gateways: + - kind: embedded + as2Issuer: https://mecatl.example.com/v1/mcp/broker + tokenEndpoint: https://mecatl.example.com/v1/mcp/broker/oauth/token + resource: https://mecatl.example.com/v1/mcp/broker/mcp + servers: [] +` + +// renderGatewayEntry renders the production identity broker profile with +// gatewayEntryValues and then extra values. +func renderGatewayEntry(t *testing.T, extra ...string) (string, error) { + t.Helper() + path := filepath.Join(t.TempDir(), "gateway-values.yaml") + if err := os.WriteFile(path, []byte(gatewayEntryValues), 0o600); err != nil { + t.Fatal(err) + } + args := []string{"template", "ib", ".", "-f", "ci/production-identity-broker-values.yaml", "-f", path} + for _, value := range extra { + args = append(args, "--set", value) + } + return helm(t, args...) +} + +// TestMecak8sHelmChart_GatewayEntryAndSigningKey pins the gateway entry in +// the identity broker's configuration file, which the broker's loader reads, +// and the embedded gateway's signing key, projected read-only to the paths +// settings.yaml names, which the runtime resolver carries to the MCP broker. +func TestMecak8sHelmChart_GatewayEntryAndSigningKey(t *testing.T) { + rendered, err := renderGatewayEntry(t) + if err != nil { + t.Fatalf("render: %v\n%s", err, rendered) + } + raw := identityBrokerConfigFromRender(t, rendered) + var doc struct { + Gateways []map[string]any `json:"gateways"` + } + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("identity-broker.json: %v", err) + } + wantEntry := map[string]any{ + "kind": "embedded", "as2_issuer": "https://mecatl.example.com/v1/mcp/broker", + "token_endpoint": "https://mecatl.example.com/v1/mcp/broker/oauth/token", + "resource": "https://mecatl.example.com/v1/mcp/broker/mcp", "servers": []any{}, + } + if len(doc.Gateways) != 1 || !reflect.DeepEqual(doc.Gateways[0], wantEntry) { + t.Fatalf("gateways = %v, want [%v]", doc.Gateways, wantEntry) + } + // The broker's own loader accepts the rendered entry beside the hosted + // AS-1, whose issuer is on the same host under another path. + const dir = "/var/run/secrets/identity-broker/" + keys := t.TempDir() + write := func(rel string) string { + path := filepath.Join(keys, rel) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + return path + } + client := brokerconfigtest.NewKey(t) + brokerconfigtest.WriteKey(t, write("agent-issuer/key.pem"), brokerconfigtest.NewKey(t)) + brokerconfigtest.WriteKey(t, write("broker-client/key.pem"), client) + brokerconfigtest.WriteKeySet(t, write("broker-client-key-set/jwks.json"), client) + brokerconfigtest.WriteKey(t, write("as1-signing/signing-key.pem"), brokerconfigtest.NewKey(t)) + configFile := filepath.Join(t.TempDir(), "identity-broker.json") + if err := os.WriteFile(configFile, []byte(strings.ReplaceAll(raw, dir, keys+"/")), 0o600); err != nil { + t.Fatal(err) + } + loaded, err := brokerconfig.Load(configFile, brokerconfig.Host{AS1: true, AS1Issuer: "https://mecatl.example.com/as1"}) + if err != nil { + t.Fatalf("brokerconfig.Load of the rendered file: %v", err) + } + if len(loaded.Gateways) != 1 || loaded.Gateways[0].Kind != identitybroker.GatewayEmbedded || len(loaded.Gateways[0].Servers) != 0 { + t.Fatalf("loaded gateways = %+v, want the embedded entry routing no servers", loaded.Gateways) + } + + profile := configMapFromRender(t, rendered, "ib-mecak8s-mcp").Data["settings.yaml"] + broker, ok := runtimeMCPAuthorityFromConfigMap(t, profile).Broker() + const keyDir = "/var/run/secrets/mcp-broker-signing-key/" + if !ok || broker.SigningKeyFile != keyDir+"signing-key/key.pem" || !slices.Equal(broker.FallbackKeyFiles, []string{keyDir + "fallback-0/key.pem"}) { + t.Fatalf("resolved signing key = %q %v, want the projected paths\n%s", broker.SigningKeyFile, broker.FallbackKeyFiles, profile) + } + spec := deploymentFromRender(t, rendered).Spec.Template.Spec + m := slices.IndexFunc(spec.Containers[0].VolumeMounts, func(m corev1.VolumeMount) bool { return m.Name == "mcp-broker-signing-key" }) + if m < 0 || !spec.Containers[0].VolumeMounts[m].ReadOnly || spec.Containers[0].VolumeMounts[m].MountPath != strings.TrimSuffix(keyDir, "/") { + t.Fatalf("the signing key is not mounted read-only at %s: %+v", keyDir, spec.Containers[0].VolumeMounts) + } + i := slices.IndexFunc(spec.Volumes, func(v corev1.Volume) bool { return v.Name == "mcp-broker-signing-key" }) + if i < 0 || spec.Volumes[i].Projected == nil || spec.Volumes[i].Projected.DefaultMode == nil || *spec.Volumes[i].Projected.DefaultMode != 0o440 { + t.Fatalf("mcp-broker-signing-key is not a 0440 projected volume: %+v", spec.Volumes) + } + projected := map[string]string{} + for _, source := range spec.Volumes[i].Projected.Sources { + for _, item := range source.Secret.Items { + projected[item.Path] = source.Secret.Name + "/" + item.Key + } + } + if want := map[string]string{"signing-key/key.pem": "mcp-gateway-signing/key.pem", "fallback-0/key.pem": "mcp-gateway-signing-old/key.pem"}; !reflect.DeepEqual(projected, want) { + t.Fatalf("projected signing keys = %v, want %v", projected, want) + } +} + +// TestMecak8sHelmChart_GatewayEntryRefusals mirrors mecak8s's startup rules +// at render time. +func TestMecak8sHelmChart_GatewayEntryRefusals(t *testing.T) { + for name, tc := range map[string]struct { + set []string + want string + }{ + "servers before AS-2 trusts AS-1": {[]string{"identityBroker.gateways[0].servers={calendar}"}, "must stay empty until the embedded gateway trusts AS-1"}, + "a server that is not an OAuth route": {[]string{"identityBroker.gateways[0].servers={github}"}, `"github" is not an mcp.servers name`}, + "an external entry": {[]string{"identityBroker.gateways[0].kind=external"}, "external gateways are not supported yet (#2812)"}, + "two entries": {[]string{ + "identityBroker.gateways[1].kind=embedded", "identityBroker.gateways[1].as2Issuer=https://other.example.com/v1/mcp/broker", + "identityBroker.gateways[1].tokenEndpoint=https://other.example.com/v1/mcp/broker/oauth/token", "identityBroker.gateways[1].resource=https://other.example.com/v1/mcp/broker/mcp", + }, "at most one entry"}, + "another issuer": {[]string{"identityBroker.gateways[0].as2Issuer=https://other.example.com/v1/mcp/broker"}, "gateways[0].as2Issuer must be https://mecatl.example.com/v1/mcp/broker"}, + "another token endpoint": {[]string{"identityBroker.gateways[0].tokenEndpoint=https://mecatl.example.com/token"}, "gateways[0].tokenEndpoint must be"}, + "another resource": {[]string{"identityBroker.gateways[0].resource=https://mecatl.example.com/mcp"}, "gateways[0].resource must be"}, + "AS-1's issuer": {[]string{ + "identityBroker.as1.issuer=https://mecatl.example.com/v1/mcp/broker", "oidc.issuer=", + }, "must differ from identityBroker.as1.issuer"}, + "AS-1's issuer with the default port and a trailing slash": {[]string{ + "identityBroker.as1.issuer=https://MECATL.example.com:443/v1/mcp/broker/", "oidc.issuer=", + }, "must differ from identityBroker.as1.issuer"}, + "no signing key": {[]string{"mcp.broker.signingKey.secretName=", "mcp.broker.signingKey.key=", "mcp.broker.signingKey.fallbacks=null"}, "identityBroker.gateways requires mcp.broker.signingKey"}, + "a signing key without an entry": {[]string{"identityBroker.gateways=null"}, "mcp.broker.signingKey requires identityBroker.enabled with an identityBroker.gateways entry"}, + "a signing key that is a broker key": {[]string{"mcp.broker.signingKey.secretName=identity-broker-agent-issuer"}, "name the same Secret key identity-broker-agent-issuer/key.pem"}, + "no embedded gateway": {[]string{"mcp.broker.callbackURL="}, ""}, + } { + t.Run(name, func(t *testing.T) { + output, err := renderGatewayEntry(t, tc.set...) + if err == nil || !strings.Contains(output, tc.want) { + t.Fatalf("render = %v, want failure %q:\n%s", err, tc.want, output) + } + }) + } + // mecak8s compares paths case-sensitively, so an AS-1 issuer whose path + // differs from AS-2's only in case is a different issuer and renders. + if output, err := renderGatewayEntry(t, "identityBroker.as1.issuer=https://mecatl.example.com/V1/mcp/broker", "oidc.issuer="); err != nil { + t.Fatalf("render with AS-1's issuer differing in path case = %v, want success:\n%s", err, output) + } + // With the broker off, a signing key fails the render. + output, err := helm(t, "template", "off", ".", "--set", "mockProvider=true,permissionMode=yolo,redis.local.enabled=true", + "--set", "mcp.broker.signingKey.secretName=mcp-gateway-signing,mcp.broker.signingKey.key=key.pem") + if err == nil || !strings.Contains(output, "mcp.broker.signingKey requires identityBroker.enabled") { + t.Fatalf("render with the broker off = %v, want the signing key refused:\n%s", err, output) + } +} diff --git a/deploy/helm/mecak8s/templates/_helpers.tpl b/deploy/helm/mecak8s/templates/_helpers.tpl index 29d086d173..2be3fdfbb0 100644 --- a/deploy/helm/mecak8s/templates/_helpers.tpl +++ b/deploy/helm/mecak8s/templates/_helpers.tpl @@ -87,7 +87,71 @@ client IDs from it; the chart renders the same derived values. {{- with $broker.keys.as1Signing -}}{{- if .secretName -}} {{- $_ := set $keys "as1_signing" (dict "key_file" (printf "%s/as1-signing/%s" $dir .key)) -}} {{- end -}}{{- end -}} -{{- dict "trust_domain" $broker.trustDomain "audience" $broker.audience "keys" $keys | toPrettyJson -}} +{{- $doc := dict "trust_domain" $broker.trustDomain "audience" $broker.audience "keys" $keys -}} +{{- with $broker.gateways -}} +{{- $entries := list -}} +{{- range . -}} +{{- $entries = append $entries (dict "kind" .kind "as2_issuer" .as2Issuer "token_endpoint" .tokenEndpoint "resource" .resource "servers" (.servers | default list)) -}} +{{- end -}} +{{- $_ := set $doc "gateways" $entries -}} +{{- end -}} +{{- $doc | toPrettyJson -}} +{{- end -}} +{{- /* mcpSigningKeyDir is where the embedded MCP gateway's signing key and its fallbacks are projected. */ -}} +{{- define "mecak8s.mcpSigningKeyDir" -}}/var/run/secrets/mcp-broker-signing-key{{- end -}} +{{- /* issuerKey normalizes an issuer URL as mecak8s compares issuers: scheme and host lowercased, a default port dropped, the path compared as written without a trailing slash. mecak8s's startup check is authoritative; this only avoids rendering a release that crash-loops. */ -}} +{{- define "mecak8s.issuerKey" -}} +{{- $u := urlParse . -}} +{{- $scheme := lower $u.scheme -}} +{{- $host := lower $u.host -}} +{{- if or (and (eq $scheme "https") (hasSuffix ":443" $host)) (and (eq $scheme "http") (hasSuffix ":80" $host)) -}}{{- $host = regexReplaceAll ":[0-9]+$" $host "" -}}{{- end -}} +{{- printf "%s://%s%s" $scheme $host (trimSuffix "/" $u.path) -}} +{{- end -}} +{{- define "mecak8s.validateGatewayEntries" -}} +{{- /* mecak8s refuses these combinations at startup; fail at render time instead of crash-looping. */ -}} +{{- $broker := .Values.identityBroker -}} +{{- $gateways := $broker.gateways | default list -}} +{{- $signingKey := .Values.mcp.broker.signingKey | default dict -}} +{{- $fallbacks := $signingKey.fallbacks | default list -}} +{{- if or $signingKey.secretName $signingKey.key -}} +{{- $_ := required "mcp.broker.signingKey.secretName is required when mcp.broker.signingKey.key is set" $signingKey.secretName -}} +{{- $_ := required "mcp.broker.signingKey.key is required when mcp.broker.signingKey.secretName is set" $signingKey.key -}} +{{- end -}} +{{- if and $fallbacks (not $signingKey.secretName) -}}{{ fail "mcp.broker.signingKey.fallbacks requires mcp.broker.signingKey" }}{{- end -}} +{{- /* Shortcut: the embedded gateway's signing key is allowed only with the identity broker on; removed by #2869. */ -}} +{{- if and $signingKey.secretName (not (and $broker.enabled $gateways)) -}}{{ fail "mcp.broker.signingKey requires identityBroker.enabled with an identityBroker.gateways entry" }}{{- end -}} +{{- if $gateways -}} +{{- if not $broker.enabled -}}{{ fail "identityBroker.gateways requires identityBroker.enabled=true" }}{{- end -}} +{{- /* Shortcut: one gateway entry, of kind embedded; removed by #2812. */ -}} +{{- if gt (len $gateways) 1 -}}{{ fail "identityBroker.gateways takes at most one entry" }}{{- end -}} +{{- $entry := first $gateways -}} +{{- if eq $entry.kind "external" -}}{{ fail "identityBroker.gateways[0].kind external: external gateways are not supported yet (#2812)" }}{{- end -}} +{{- $brokerClient := ($broker.keys | default dict).brokerClient | default dict -}} +{{- $_ := required "identityBroker.gateways requires identityBroker.keys.brokerClient, which the broker authenticates to the gateway's authorization server with" $brokerClient.secretName -}} +{{- $_ := required "identityBroker.gateways requires mcp.broker.signingKey: the embedded gateway's signing key" $signingKey.secretName -}} +{{- $oauth := list -}} +{{- range .Values.mcp.servers -}}{{- if eq .auth.mode "oauth" -}}{{- $oauth = append $oauth .name -}}{{- end -}}{{- end -}} +{{- if not (and $oauth .Values.mcp.broker.callbackURL) -}}{{ fail "identityBroker.gateways declares an embedded gateway, which needs mcp.broker.callbackURL and an mcp.servers entry with auth.mode oauth" }}{{- end -}} +{{- $issuer := printf "%s/v1/mcp/broker" (regexFind "^https://[^/?#]+" .Values.mcp.broker.callbackURL) -}} +{{- range $field, $want := dict "as2Issuer" $issuer "tokenEndpoint" (printf "%s/oauth/token" $issuer) "resource" (printf "%s/mcp" $issuer) -}} +{{- if ne (get $entry $field) $want -}}{{ fail (printf "identityBroker.gateways[0].%s must be %s, which the embedded gateway derives from mcp.broker.callbackURL" $field $want) }}{{- end -}} +{{- end -}} +{{- if and $broker.as1.issuer (eq (include "mecak8s.issuerKey" $broker.as1.issuer) (include "mecak8s.issuerKey" $issuer)) -}}{{ fail "identityBroker.gateways[0].as2Issuer must differ from identityBroker.as1.issuer: the broker client authenticates to both with one key" }}{{- end -}} +{{- range $entry.servers -}} +{{- if not (has . $oauth) -}}{{ fail (printf "identityBroker.gateways[0].servers entry %q is not an mcp.servers name with auth.mode oauth" .) }}{{- end -}} +{{- end -}} +{{- /* Shortcut: production's gateway entry routes no servers; removed by #2533 (AS-2 trusts AS-1). */ -}} +{{- if $entry.servers -}}{{ fail "identityBroker.gateways[0].servers must stay empty until the embedded gateway trusts AS-1's ID-JAGs (#2533)" }}{{- end -}} +{{- end -}} +{{- /* The same Secret key is the same key; mecak8s also compares the keys themselves. */ -}} +{{- if $signingKey.secretName -}} +{{- $keys := $broker.keys | default dict -}} +{{- range $name, $ref := dict "identityBroker.keys.agentIssuer" ($keys.agentIssuer | default dict) "identityBroker.keys.brokerClient" ($keys.brokerClient | default dict) "identityBroker.keys.as1Signing" ($keys.as1Signing | default dict) -}} +{{- range $own := prepend $fallbacks $signingKey -}} +{{- if and $ref.secretName (eq $ref.secretName $own.secretName) (eq $ref.key $own.key) -}}{{ fail (printf "mcp.broker.signingKey and %s name the same Secret key %s/%s; each role needs its own key" $name $ref.secretName $ref.key) }}{{- end -}} +{{- end -}} +{{- end -}} +{{- end -}} {{- end -}} {{- define "mecak8s.validateIdentityBroker" -}} {{- /* mecak8s refuses these combinations at startup; fail at render time instead of crash-looping. */ -}} @@ -383,6 +447,16 @@ mcp: mode: broker broker: callback_url: {{ .Values.mcp.broker.callbackURL | quote }} +{{- with .Values.mcp.broker.signingKey }}{{- if .secretName }} +{{- $dir := include "mecak8s.mcpSigningKeyDir" $ }} + signing_key_file: {{ printf "%s/signing-key/%s" $dir .key | quote }} +{{- with .fallbacks }} + fallback_key_files: +{{- range $i, $ref := . }} + - {{ printf "%s/fallback-%d/%s" $dir $i $ref.key | quote }} +{{- end }} +{{- end }} +{{- end }}{{- end }} {{- end }} servers: {{- range $server := .Values.mcp.servers }} diff --git a/deploy/helm/mecak8s/templates/deployment.yaml b/deploy/helm/mecak8s/templates/deployment.yaml index 58ec61a496..651f297cd3 100644 --- a/deploy/helm/mecak8s/templates/deployment.yaml +++ b/deploy/helm/mecak8s/templates/deployment.yaml @@ -10,6 +10,7 @@ {{- $learningStoreEnabled := ne .Values.learning.store.endpoint "" -}} {{- $learningStoreTokenConfigured := and .Values.learning.store.tokenSecret .Values.learning.store.tokenKey -}} {{- include "mecak8s.validateMCP" . -}} +{{- include "mecak8s.validateGatewayEntries" . -}} {{- $mcpOAuth := false -}} {{- range .Values.mcp.servers -}}{{- if eq .auth.mode "oauth" -}}{{- $mcpOAuth = true -}}{{- end -}}{{- end -}} {{- $mcpSettings := or $mcpOAuth (not .Values.mcp.servers) -}} @@ -374,6 +375,9 @@ spec: {{- if $mcpSettings }} - {name: mcp-profile, mountPath: /etc/mecatl-mcp, readOnly: true} {{- end }} + {{- if (.Values.mcp.broker.signingKey | default dict).secretName }} + - {name: mcp-broker-signing-key, mountPath: {{ include "mecak8s.mcpSigningKeyDir" . }}, readOnly: true} + {{- end }} {{- with .Values.extraVolumeMounts }} {{- toYaml . | nindent 12 }} {{- end }} @@ -489,6 +493,26 @@ spec: items: - {key: settings.yaml, path: settings.yaml} {{- end }} + {{- with .Values.mcp.broker.signingKey }} + {{- if .secretName }} + # The embedded MCP gateway's signing key and fallbacks, at the paths + # settings.yaml names. + - name: mcp-broker-signing-key + projected: + defaultMode: 0440 + sources: + - secret: + name: {{ .secretName }} + items: + - {key: {{ .key | quote }}, path: {{ printf "signing-key/%s" .key | quote }}} + {{- range $i, $ref := .fallbacks }} + - secret: + name: {{ $ref.secretName }} + items: + - {key: {{ $ref.key | quote }}, path: {{ printf "fallback-%d/%s" $i $ref.key | quote }}} + {{- end }} + {{- end }} + {{- end }} {{- with .Values.extraVolumes }} {{- toYaml . | nindent 8 }} {{- end }} diff --git a/deploy/helm/mecak8s/tests/broker_test.yaml b/deploy/helm/mecak8s/tests/broker_test.yaml index fc35fc5030..cbe256bdc3 100644 --- a/deploy/helm/mecak8s/tests/broker_test.yaml +++ b/deploy/helm/mecak8s/tests/broker_test.yaml @@ -43,6 +43,19 @@ tests: - failedTemplate: errorPattern: mcp.broker.callbackURL is required + - it: refuses the embedded gateway's signing key without the identity broker + set: + mcp.broker.signingKey.secretName: mcp-gateway-signing + mcp.broker.signingKey.key: key.pem + asserts: + - failedTemplate: + errorMessage: mcp.broker.signingKey requires identityBroker.enabled with an identityBroker.gateways entry + + - it: renders no signing key without one + asserts: + - notExists: + path: spec.template.spec.volumes[?(@.name == "mcp-broker-signing-key")] + - it: requires OIDC caller identity set: mockProvider: true diff --git a/deploy/helm/mecak8s/tests/identity_broker_test.yaml b/deploy/helm/mecak8s/tests/identity_broker_test.yaml index f2030e4a8c..4e0940472b 100644 --- a/deploy/helm/mecak8s/tests/identity_broker_test.yaml +++ b/deploy/helm/mecak8s/tests/identity_broker_test.yaml @@ -130,6 +130,30 @@ tests: path: spec.template.spec.containers[0].args content: --identity-broker-as1-upstream-ca-file=/var/run/secrets/as1-upstream-ca/ca.crt + - it: refuses a gateway entry without the embedded gateway + set: + identityBroker.gateways: + - kind: embedded + as2Issuer: https://mecatl.example.com/v1/mcp/broker + tokenEndpoint: https://mecatl.example.com/v1/mcp/broker/oauth/token + resource: https://mecatl.example.com/v1/mcp/broker/mcp + mcp.broker.signingKey.secretName: mcp-gateway-signing + mcp.broker.signingKey.key: key.pem + asserts: + - failedTemplate: + errorMessage: identityBroker.gateways declares an embedded gateway, which needs mcp.broker.callbackURL and an mcp.servers entry with auth.mode oauth + + - it: refuses an external gateway entry + set: + identityBroker.gateways: + - kind: external + as2Issuer: https://gateway.example.com + tokenEndpoint: https://gateway.example.com/oauth/token + resource: https://gateway.example.com/mcp + asserts: + - failedTemplate: + errorMessage: "identityBroker.gateways[0].kind external: external gateways are not supported yet (#2812)" + - it: rejects private upstream addresses without the upstream CA set: identityBroker.as1.upstream.allowPrivateAddresses: true diff --git a/deploy/helm/mecak8s/values.schema.json b/deploy/helm/mecak8s/values.schema.json index f5cbdbde11..45978aaee0 100644 --- a/deploy/helm/mecak8s/values.schema.json +++ b/deploy/helm/mecak8s/values.schema.json @@ -94,6 +94,21 @@ } }, "subjectClaim": {"type": "string", "pattern": "^\\S*$"}, + "gateways": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "as2Issuer", "tokenEndpoint", "resource"], + "properties": { + "kind": {"type": "string", "enum": ["embedded", "external"]}, + "as2Issuer": {"type": "string", "pattern": "^https://[^@/?#\\s]+(?:/[^?#\\s]*)?$"}, + "tokenEndpoint": {"type": "string", "pattern": "^https://[^@/?#\\s]+(?:/[^?#\\s]*)?$"}, + "resource": {"type": "string", "pattern": "^https://[^@/?#\\s]+(?:/[^?#\\s]*)?$"}, + "servers": {"type": "array", "uniqueItems": true, "items": {"type": "string", "pattern": "^[A-Za-z0-9_]+$"}} + } + } + }, "as1": { "type": "object", "additionalProperties": false, @@ -226,7 +241,28 @@ "additionalProperties": false, "required": ["callbackURL"], "properties": { - "callbackURL": {"type": "string", "anyOf": [{"const": ""}, {"pattern": "^https://[^@/\\s#]+(?:/[^\\s?#]*)?$"}]} + "callbackURL": {"type": "string", "anyOf": [{"const": ""}, {"pattern": "^https://[^@/\\s#]+(?:/[^\\s?#]*)?$"}]}, + "signingKey": { + "type": "object", + "additionalProperties": false, + "required": ["secretName", "key"], + "properties": { + "secretName": {"$ref": "#/definitions/optionalSecretKey/properties/secretName"}, + "key": {"$ref": "#/definitions/optionalSecretKey/properties/key"}, + "fallbacks": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["secretName", "key"], + "properties": { + "secretName": {"type": "string", "minLength": 1, "maxLength": 253, "pattern": "^[a-z0-9]([-.a-z0-9]*[a-z0-9])?$"}, + "key": {"type": "string", "minLength": 1, "maxLength": 253, "pattern": "^[-._a-zA-Z0-9]+$"} + } + } + } + } + } } }, "servers": { diff --git a/deploy/helm/mecak8s/values.yaml b/deploy/helm/mecak8s/values.yaml index ba85bbb670..93788e6ec1 100644 --- a/deploy/helm/mecak8s/values.yaml +++ b/deploy/helm/mecak8s/values.yaml @@ -60,6 +60,19 @@ mcp: # Public HTTPS URL where the browser returns after OAuth. This exact URL # must route to this service's HTTP listener through your ingress/gateway. callbackURL: "" + # The embedded MCP gateway's signing key (its authorization server, AS-2): + # an existing Secret key holding a PEM private key, projected read-only + # and rendered as mcp.broker.signing_key_file. Required with + # identityBroker.enabled and an identityBroker.gateways entry, and allowed + # only then; without it the embedded gateway generates its key at each + # start. It must differ from every identity broker key. fallbacks are + # earlier keys, also PEM private keys, whose tokens still verify during a + # rotation. mecak8s reads them at startup: after changing a Secret, run + # `kubectl rollout restart deployment/-mecak8s`. + signingKey: + secretName: "" + key: "" + fallbacks: [] servers: [] # Optional remote learning driver. A bearer token is optional; when both tokenSecret @@ -308,7 +321,8 @@ identityBroker: # its own keys at startup, so they stay the same across a restart and the # access tokens AS-1 issued before it keep verifying until they expire. The MCP # gateway's embedded authorization server generates its signing key at each - # start, so the tokens it issued stop verifying. Broker sessions, agent + # start, so the tokens it issued stop verifying, unless a gateway entry and + # mcp.broker.signingKey supply its key. Broker sessions, agent # registrations, and AS-1's refresh tokens are in memory and lost. The # broker reads its keys only at startup: a configuration change rolls the # pod, but after changing a key in a Secret, run @@ -348,6 +362,22 @@ identityBroker: # whose sub differs per application; sub for an IdP whose sub is the same # across applications. subjectClaim: "" + # Optional gateway entries, rendered into the identity broker's configuration + # file: at most one, of kind embedded, describing the embedded MCP gateway + # mecak8s runs for mcp.servers with auth.mode oauth. Its as2Issuer, + # tokenEndpoint, and resource must equal what the gateway derives from + # mcp.broker.callbackURL: /v1/mcp/broker, that plus + # /oauth/token, and that plus /mcp. as2Issuer must differ from as1.issuer. + # An entry requires keys.brokerClient and mcp.broker.signingKey. servers + # must stay empty until the embedded gateway trusts AS-1 (#2533); an entry + # without servers sets the gateway's authorization server up for the broker + # and routes no calls through it. + gateways: [] + # - kind: embedded + # as2Issuer: https://mecatl.example.com/v1/mcp/broker + # tokenEndpoint: https://mecatl.example.com/v1/mcp/broker/oauth/token + # resource: https://mecatl.example.com/v1/mcp/broker/mcp + # servers: [] # as1 hosts AS-1, Mecatl's sign-in authorization server in front of the company # identity provider, on mecak8s's HTTP listener under the issuer URL's path. A # non-empty issuer turns it on and requires oidc.enabled, oidc.audience, and diff --git a/internal/adapter/mcpauthority/authority.go b/internal/adapter/mcpauthority/authority.go index 8b7929f482..a935c612da 100644 --- a/internal/adapter/mcpauthority/authority.go +++ b/internal/adapter/mcpauthority/authority.go @@ -21,6 +21,18 @@ const ( type BrokerConfig struct { Routes []permconfig.MCPServerProfile CallbackURL string + // SigningKeyFile and FallbackKeyFiles are the absolute paths of the + // embedded authorization server's signing key and its fallbacks; empty + // lets it generate its key at each start. + SigningKeyFile string + FallbackKeyFiles []string +} + +func (c *BrokerConfig) clone() *BrokerConfig { + return &BrokerConfig{ + Routes: cloneRoutes(c.Routes), CallbackURL: c.CallbackURL, + SigningKeyFile: c.SigningKeyFile, FallbackKeyFiles: append([]string(nil), c.FallbackKeyFiles...), + } } // Result is the canonical authority tagged union. Unexported payloads prevent a @@ -43,7 +55,7 @@ func NewGlobal(servers []mcp.ServerConfig, lifecycle interface{ Close() error }) // NewBroker takes one deep defensive copy and creates a broker-only result. func NewBroker(config BrokerConfig) *Result { - return &Result{mode: Broker, broker: &BrokerConfig{Routes: cloneRoutes(config.Routes), CallbackURL: config.CallbackURL}} + return &Result{mode: Broker, broker: config.clone()} } // Mode returns the selected authority tag. Nil, zero, and malformed results fail @@ -80,7 +92,7 @@ func (r *Result) Broker() (BrokerConfig, bool) { if r.Mode() != Broker { return BrokerConfig{}, false } - return BrokerConfig{Routes: cloneRoutes(r.broker.Routes), CallbackURL: r.broker.CallbackURL}, true + return *r.broker.clone(), true } func cloneServers(in []mcp.ServerConfig) []mcp.ServerConfig { diff --git a/internal/adapter/mcpauthority/authority_test.go b/internal/adapter/mcpauthority/authority_test.go index 1bb2601477..ea918cc693 100644 --- a/internal/adapter/mcpauthority/authority_test.go +++ b/internal/adapter/mcpauthority/authority_test.go @@ -94,3 +94,17 @@ func TestResultOwnsImmutableCopies(t *testing.T) { t.Fatalf("broker aliases accessor result: %#v", again) } } + +func TestBrokerCarriesTheSigningKeyPaths(t *testing.T) { + fallbacks := []string{"/keys/as2-old/key.pem"} + broker := NewBroker(BrokerConfig{SigningKeyFile: "/keys/as2/key.pem", FallbackKeyFiles: fallbacks}) + fallbacks[0] = "/mutated.pem" + got, ok := broker.Broker() + if !ok || got.SigningKeyFile != "/keys/as2/key.pem" || len(got.FallbackKeyFiles) != 1 || got.FallbackKeyFiles[0] != "/keys/as2-old/key.pem" { + t.Fatalf("broker signing key = %q %v, want the declared paths", got.SigningKeyFile, got.FallbackKeyFiles) + } + got.FallbackKeyFiles[0] = "/returned-mutation.pem" + if again, _ := broker.Broker(); again.FallbackKeyFiles[0] != "/keys/as2-old/key.pem" { + t.Fatal("a returned fallback list aliases the result") + } +} diff --git a/internal/adapter/mcpbroker/as2.go b/internal/adapter/mcpbroker/as2.go index 8e6ceafa9e..88e60c67f9 100644 --- a/internal/adapter/mcpbroker/as2.go +++ b/internal/adapter/mcpbroker/as2.go @@ -27,7 +27,7 @@ const as2TokenPath = toolHiveBasePath + "/oauth/token" // embedded, the embedded authorization server's handler as mounted under // toolHiveBasePath. func newAS2(issuer, resource string, embedded http.Handler) *AS2 { - return &AS2{Issuer: issuer, TokenEndpoint: issuer + "/oauth/token", Resource: resource, handler: tokenEndpointOnly(embedded)} + return &AS2{Issuer: issuer, TokenEndpoint: as2TokenEndpoint(issuer), Resource: resource, handler: tokenEndpointOnly(embedded)} } // Handler serves AS-2's token endpoint, for composition to reach AS-2 in diff --git a/internal/adapter/mcpbroker/as2_signing_key_test.go b/internal/adapter/mcpbroker/as2_signing_key_test.go new file mode 100644 index 0000000000..d6e06071ed --- /dev/null +++ b/internal/adapter/mcpbroker/as2_signing_key_test.go @@ -0,0 +1,183 @@ +package mcpbroker + +import ( + "crypto/ecdsa" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/stacklok/toolhive/pkg/authserver" + "github.com/stacklok/toolhive/pkg/oauthproto" + + "github.com/stacklok/mecatl/internal/identitybroker/adapter/brokerconfig/brokerconfigtest" +) + +// The tests in this file are not parallel: AS-2's protected route reads an +// environment variable. + +// writeSigningKey writes a new P-256 signing key and returns it and its path. +func writeSigningKey(t *testing.T) (*ecdsa.PrivateKey, string) { + t.Helper() + key := brokerconfigtest.NewKey(t) + return key, brokerconfigtest.WriteKey(t, filepath.Join(t.TempDir(), "as2.pem"), key) +} + +// withSigningKey has AS-2 sign with keyFile and keep fallbacks. +func withSigningKey(keyFile string, fallbacks ...string) func(*ToolHiveConfig) { + return func(c *ToolHiveConfig) { c.SigningKeyFile, c.FallbackKeyFiles = keyFile, fallbacks } +} + +// gatewayToken redeems a fresh ID-JAG from as1 at process's AS-2 for a +// gateway token (V). +func gatewayToken(t *testing.T, as1 trustedAS1, broker as2BrokerClient, process *Process) string { + t.Helper() + as2 := process.AS2 + status, body := postAS2Token(t, as2, url.Values{ + "grant_type": {oauthproto.GrantTypeJWTBearer}, "assertion": {as1.idJAG(t, as2)}, "resource": {as2.Resource}, + "client_assertion_type": {clientAssertionTyp}, "client_assertion": {broker.assertion(t, as2.Issuer)}, + }) + token, _ := body["access_token"].(string) + if status != http.StatusOK || token == "" { + t.Fatalf("ID-JAG redemption: status %d, body %v", status, body) + } + return token +} + +// mountedProcess serves process's handlers. +func mountedProcess(t *testing.T, process *Process) *http.ServeMux { + t.Helper() + mux := http.NewServeMux() + if err := process.Handlers.Mount(mux, "/callback"); err != nil { + t.Fatalf("mount handlers: %v", err) + } + return mux +} + +// vmcpInitialize sends an MCP initialize with token to process's vMCP, which +// checks the token with the embedded server's KeyProvider, and returns the +// status. +func vmcpInitialize(t *testing.T, process *Process, token string) int { + t.Helper() + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, as2TestResource, strings.NewReader(mcpInitializeBody)) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + recorder := httptest.NewRecorder() + mountedProcess(t, process).ServeHTTP(recorder, req) + return recorder.Code +} + +// jwks returns process's published key set. +func jwks(t *testing.T, process *Process) string { + t.Helper() + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, as2TestIssuer+"/.well-known/jwks.json", nil) + recorder := httptest.NewRecorder() + mountedProcess(t, process).ServeHTTP(recorder, req) + body, _ := io.ReadAll(recorder.Body) + if recorder.Code != http.StatusOK || len(body) == 0 { + t.Fatalf("JWKS: status %d", recorder.Code) + } + return string(body) +} + +func TestToolHiveSigningKeyRunConfig(t *testing.T) { + got, err := ToolHiveConfig{}.signingKeyRunConfig() + if err != nil || got != nil { + t.Fatalf("without a key = %+v, %v; want none, so ToolHive generates one", got, err) + } + got, err = ToolHiveConfig{SigningKeyFile: "/keys/as2.pem", FallbackKeyFiles: []string{"/keys/as2-old.pem"}}.signingKeyRunConfig() + want := &authserver.SigningKeyRunConfig{SigningKeyFile: "/keys/as2.pem", FallbackKeyFiles: []string{"/keys/as2-old.pem"}} + if err != nil || !reflect.DeepEqual(got, want) { + t.Fatalf("with a key = %+v, %v; want %+v with no key directory", got, err, want) + } + for name, c := range map[string]ToolHiveConfig{ + "fallbacks without a key": {FallbackKeyFiles: []string{"/keys/as2-old.pem"}}, + "a relative key": {SigningKeyFile: "as2.pem"}, + "a relative fallback": {SigningKeyFile: "/keys/as2.pem", FallbackKeyFiles: []string{"as2-old.pem"}}, + } { + if _, err := c.signingKeyRunConfig(); !errors.Is(err, ErrInvalidCatalogue) { + t.Errorf("%s = %v, want ErrInvalidCatalogue", name, err) + } + c.CallbackURL, c.Profiles = as2TestCallbackURL, []ToolHiveProfile{staticProtectedProfile("private")} + if process, err := NewToolHiveProcess(t.Context(), c); !errors.Is(err, ErrInvalidCatalogue) { + if process != nil { + _ = process.Close() + } + t.Errorf("NewToolHiveProcess with %s = %v, want ErrInvalidCatalogue", name, err) + } + } +} + +func TestSigningPublicKeys(t *testing.T) { + key, keyFile := writeSigningKey(t) + old, oldFile := writeSigningKey(t) + got, err := SigningPublicKeys(keyFile, []string{oldFile}) + if err != nil || len(got) != 2 || !key.PublicKey.Equal(got[0]) || !old.PublicKey.Equal(got[1]) { + t.Fatalf("SigningPublicKeys = %d keys, %v; want the key's and the fallback's", len(got), err) + } + missing := filepath.Join(t.TempDir(), "absent.pem") + if _, err := SigningPublicKeys(keyFile, []string{missing}); err == nil || !strings.Contains(err.Error(), missing) { + t.Fatalf("SigningPublicKeys with a missing fallback = %v, want an error naming it", err) + } + // A fallback is a private key, as ToolHive loads it as a signing key. + public := brokerconfigtest.WritePublicKey(t, filepath.Join(t.TempDir(), "public.pem"), old) + if _, err := SigningPublicKeys(keyFile, []string{public}); err == nil { + t.Fatal("SigningPublicKeys accepted a public key as a fallback") + } +} + +// TestAS2SigningKeySurvivesARebuild: with an operator key, AS-2 publishes +// the same key set after a rebuild and the rebuilt vMCP accepts a gateway +// token signed before it; without one, each build generates its own key. +func TestAS2SigningKeySurvivesARebuild(t *testing.T) { + as1 := startTrustedAS1(t) + broker := newAS2BrokerClient(t) + _, keyFile := writeSigningKey(t) + first := startTrustingAS2With(t, as1, broker.config, withSigningKey(keyFile)) + token := gatewayToken(t, as1, broker, first) + rebuilt := startTrustingAS2With(t, as1, broker.config, withSigningKey(keyFile)) + if jwks(t, first) != jwks(t, rebuilt) { + t.Fatal("the rebuilt AS-2 publishes another key set") + } + if status := vmcpInitialize(t, rebuilt, token); status != http.StatusOK { + t.Fatalf("the rebuilt vMCP with a gateway token from before: status %d, want 200", status) + } + + generated := startTrustingAS2(t, as1, broker.config) + regenerated := startTrustingAS2(t, as1, broker.config) + if jwks(t, generated) == jwks(t, regenerated) { + t.Fatal("two builds without a signing key published one key set") + } + if status := vmcpInitialize(t, regenerated, gatewayToken(t, as1, broker, generated)); status != http.StatusUnauthorized { + t.Fatalf("a rebuilt vMCP without a signing key accepted an earlier gateway token: status %d, want 401", status) + } +} + +// TestAS2SigningKeyRotation: a gateway token signed with the previous key +// verifies at the vMCP while that key is a fallback, and not once it is +// dropped. +func TestAS2SigningKeyRotation(t *testing.T) { + as1 := startTrustedAS1(t) + broker := newAS2BrokerClient(t) + _, oldFile := writeSigningKey(t) + _, newFile := writeSigningKey(t) + token := gatewayToken(t, as1, broker, startTrustingAS2With(t, as1, broker.config, withSigningKey(oldFile))) + + during := startTrustingAS2With(t, as1, broker.config, withSigningKey(newFile, oldFile)) + if status := vmcpInitialize(t, during, token); status != http.StatusOK { + t.Fatalf("during the rotation, a gateway token signed with the fallback: status %d, want 200", status) + } + if status := vmcpInitialize(t, during, gatewayToken(t, as1, broker, during)); status != http.StatusOK { + t.Fatalf("during the rotation, a gateway token signed with the new key: status %d, want 200", status) + } + after := startTrustingAS2With(t, as1, broker.config, withSigningKey(newFile)) + if status := vmcpInitialize(t, after, token); status != http.StatusUnauthorized { + t.Fatalf("after the rotation, a gateway token signed with the dropped key: status %d, want 401", status) + } +} diff --git a/internal/adapter/mcpbroker/as2_test.go b/internal/adapter/mcpbroker/as2_test.go index 2cf19c1d2c..31df41a532 100644 --- a/internal/adapter/mcpbroker/as2_test.go +++ b/internal/adapter/mcpbroker/as2_test.go @@ -277,10 +277,10 @@ func TestAS2RegistersTheBrokerClientWithTheVMCPResource(t *testing.T) { t.Fatalf("AS-2 = %+v", as2) } // AS2Endpoints names the same AS-2 before construction. - if issuer, resource, err := AS2Endpoints(as2TestCallbackURL); err != nil || issuer != as2.Issuer || resource != as2.Resource { - t.Fatalf("AS2Endpoints = %q, %q, %v; want AS-2's %q and %q", issuer, resource, err, as2.Issuer, as2.Resource) + if issuer, token, resource, err := AS2Endpoints(as2TestCallbackURL); err != nil || issuer != as2.Issuer || token != as2.TokenEndpoint || resource != as2.Resource { + t.Fatalf("AS2Endpoints = %q, %q, %q, %v; want AS-2's %q, %q, and %q", issuer, token, resource, err, as2.Issuer, as2.TokenEndpoint, as2.Resource) } - if _, _, err := AS2Endpoints("http://broker.example/callback"); !errors.Is(err, ErrInvalidCatalogue) { + if _, _, _, err := AS2Endpoints("http://broker.example/callback"); !errors.Is(err, ErrInvalidCatalogue) { t.Fatalf("AS2Endpoints for an http callback = %v, want ErrInvalidCatalogue", err) } if got := []string(spy.client.GetAudience()); !reflect.DeepEqual(got, []string{as2TestResource}) { @@ -705,15 +705,26 @@ func newTrustingAS2(t *testing.T) (trustedAS1, as2BrokerClient, *Process) { // startTrustingAS2 sets AS-2 up trusting as1, with client as its broker // client. func startTrustingAS2(t *testing.T, as1 trustedAS1, client *ToolHiveBrokerClient) *Process { + t.Helper() + return startTrustingAS2With(t, as1, client, nil) +} + +// startTrustingAS2With is startTrustingAS2 with edit, when set, changing the +// configuration first. +func startTrustingAS2With(t *testing.T, as1 trustedAS1, client *ToolHiveBrokerClient, edit func(*ToolHiveConfig)) *Process { t.Helper() t.Setenv("MECATL_TEST_CLIENT_SECRET", "construction-only-secret") - process, err := NewToolHiveProcess(t.Context(), ToolHiveConfig{ + config := ToolHiveConfig{ CallbackURL: as2TestCallbackURL, Profiles: []ToolHiveProfile{staticProtectedProfile("private")}, BrokerClient: client, AS2Trust: NewAS2Trust(as2trust.Trust{ Issuer: as1.a.Issuer(), JWKSURL: as1.a.JWKSURL(), CAFile: as1.a.Harness.WriteCACert(t, t.TempDir()), Subjects: []string{as1servertest.Subject(t, as1.alice), as1servertest.Subject(t, as1.bob)}, }.WithDefaults()), - }) + } + if edit != nil { + edit(&config) + } + process, err := NewToolHiveProcess(t.Context(), config) if err != nil { t.Fatalf("NewToolHiveProcess: %v", err) } diff --git a/internal/adapter/mcpbroker/gateway.go b/internal/adapter/mcpbroker/gateway.go index 705bbd0123..dc3aa7f9ef 100644 --- a/internal/adapter/mcpbroker/gateway.go +++ b/internal/adapter/mcpbroker/gateway.go @@ -122,8 +122,8 @@ type GatewayCalls struct { SendOnce SendOnceRecord // ListLimits bound each listing of a server's tools through the gateway; // a zero field takes the mcp package's default. Production leaves it zero: - // it lets tests lower a limit until operator gateway entries (#2538) need - // their own. + // it lets tests lower a limit until external gateways (#2812) need their + // own. ListLimits mcpadapter.GatewayListLimits } diff --git a/internal/adapter/mcpbroker/toolhive_construction.go b/internal/adapter/mcpbroker/toolhive_construction.go index c9cb154f4b..153e8e2e0c 100644 --- a/internal/adapter/mcpbroker/toolhive_construction.go +++ b/internal/adapter/mcpbroker/toolhive_construction.go @@ -1,13 +1,16 @@ package mcpbroker import ( + "crypto" "encoding/json" "fmt" "net/http" + "path/filepath" "strings" "github.com/redis/go-redis/v9" "github.com/stacklok/toolhive/pkg/authserver" + servercrypto "github.com/stacklok/toolhive/pkg/authserver/server/crypto" "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" "github.com/stacklok/toolhive/pkg/authserver/storage" "github.com/stacklok/toolhive/pkg/oauthproto" @@ -79,6 +82,48 @@ type ToolHiveConfig struct { // EmbeddedGatewayClient builds the embedded gateway's HTTP client over // the vMCP handler for endpoint. EmbeddedGatewayClient func(vmcp http.Handler, endpoint string) (*http.Client, error) + // SigningKeyFile is the absolute path of the PEM private key the embedded + // authorization server signs its tokens with; empty generates a key at + // each start. FallbackKeyFiles are absolute paths of earlier keys, PEM + // private keys too, whose tokens still verify; they require + // SigningKeyFile. + SigningKeyFile string + FallbackKeyFiles []string +} + +// signingKeyRunConfig is ToolHive's configuration of the embedded +// authorization server's signing keys, nil without a key file. ToolHive +// joins each file name to an empty KeyDir, so the absolute paths stay as +// they are. +func (c ToolHiveConfig) signingKeyRunConfig() (*authserver.SigningKeyRunConfig, error) { + if c.SigningKeyFile == "" { + if len(c.FallbackKeyFiles) != 0 { + return nil, fmt.Errorf("%w: signing fallback keys need a signing key file", ErrInvalidCatalogue) + } + return nil, nil + } + for _, path := range append([]string{c.SigningKeyFile}, c.FallbackKeyFiles...) { + if !filepath.IsAbs(path) { + return nil, fmt.Errorf("%w: signing key file %q is not an absolute path", ErrInvalidCatalogue, path) + } + } + return &authserver.SigningKeyRunConfig{SigningKeyFile: c.SigningKeyFile, FallbackKeyFiles: append([]string(nil), c.FallbackKeyFiles...)}, nil +} + +// SigningPublicKeys reads the signing key at keyFile and its fallbacks as +// the embedded authorization server reads them, and returns their public +// keys, so composition can refuse a key another role uses. Errors name the +// file, never key material. +func SigningPublicKeys(keyFile string, fallbacks []string) ([]crypto.PublicKey, error) { + keys := make([]crypto.PublicKey, 0, 1+len(fallbacks)) + for _, path := range append([]string{keyFile}, fallbacks...) { + signer, err := servercrypto.LoadSigningKey(path) + if err != nil { + return nil, fmt.Errorf("signing key %s: %w", path, err) + } + keys = append(keys, signer.Public()) + } + return keys, nil } // AS2Trust is an ID-JAG issuer AS-2 trusts for the listed subjects only. @@ -92,6 +137,10 @@ type AS2Trust struct{ t *as2trust.Trust } // NewAS2Trust returns an AS2Trust trusting t. func NewAS2Trust(t as2trust.Trust) AS2Trust { return AS2Trust{t: &t} } +// TrustsAnIssuer reports whether t trusts an ID-JAG issuer; the zero value, +// production's, trusts none. +func (t AS2Trust) TrustsAnIssuer() bool { return t.t != nil } + // ToolHiveBrokerClient is the identity broker's client at AS-2. type ToolHiveBrokerClient struct { // ID is the client ID. @@ -125,16 +174,21 @@ func as2Resource(issuer string) string { return issuer + "/mcp" } -// AS2Endpoints returns the issuer and vMCP resource NewToolHiveProcess gives -// AS-2 when it sets AS-2 up for callbackURL, which it does only with a -// protected profile and a broker client. It fails when callbackURL is not the -// canonical HTTPS URL protected profiles require. -func AS2Endpoints(callbackURL string) (issuer, resource string, err error) { +// as2TokenEndpoint is the token endpoint of AS-2 at issuer. +func as2TokenEndpoint(issuer string) string { + return issuer + "/oauth/token" +} + +// AS2Endpoints returns the issuer, token endpoint, and vMCP resource +// NewToolHiveProcess gives AS-2 when it sets AS-2 up for callbackURL, which +// it does only with a protected profile and a broker client. It fails when +// callbackURL is not the canonical HTTPS URL protected profiles require. +func AS2Endpoints(callbackURL string) (issuer, tokenEndpoint, resource string, err error) { issuer, err = toolHiveIssuer(callbackURL, true) if err != nil { - return "", "", err + return "", "", "", err } - return issuer, as2Resource(issuer), nil + return issuer, as2TokenEndpoint(issuer), as2Resource(issuer), nil } // as2RunConfig returns AS-2's additions to the embedded authorization diff --git a/internal/adapter/mcpbroker/toolhive_process.go b/internal/adapter/mcpbroker/toolhive_process.go index e94d696560..4d87ebfcd5 100644 --- a/internal/adapter/mcpbroker/toolhive_process.go +++ b/internal/adapter/mcpbroker/toolhive_process.go @@ -135,6 +135,10 @@ func newToolHiveProcess(ctx context.Context, config ToolHiveConfig, options tool return nil, fmt.Errorf("%w: broker client: %w", ErrInvalidCatalogue, err) } } + signingKeys, err := config.signingKeyRunConfig() + if err != nil { + return nil, err + } diag := config.Diagnostics if diag == nil { diag = port.NopDiagnostics{} @@ -236,9 +240,10 @@ func newToolHiveProcess(ctx context.Context, config ToolHiveConfig, options tool if protectedTarget == nil { return rollback(fmt.Errorf("%w: protected ToolHive target is required", ErrInvalidCatalogue)) } - // Shortcut: the embedded authorization server sets no signing key and no HMAC secret, so ToolHive generates both at each start and the tokens, authorization codes, and refresh tokens they protect do not survive a restart; removed by #2538 (mecak8s supplies the signing key with the identity broker on) and #2869 (the HMAC secret). + // Shortcut: the embedded authorization server sets no HMAC secret, and no signing key unless config.SigningKeyFile names one, which mecak8s allows only with the identity broker on and an embedded gateway entry, so ToolHive generates them at each start and the authorization codes and refresh tokens, and without the key the tokens, they protect do not survive a restart; removed by #2869 (the HMAC secret, and the signing key with the identity broker off). runConfig := &authserver.RunConfig{ SchemaVersion: "v1", Issuer: issuer, AllowedAudiences: []string{resource}, Upstreams: construction.upstreams, + SigningKeyConfig: signingKeys, } if as2 { runConfig.InboundGrants, runConfig.TrustedIssuers = as2RunConfig(*config.BrokerClient, issuer, resource, config.AS2Trust) diff --git a/internal/adapter/permconfig/mcp_test.go b/internal/adapter/permconfig/mcp_test.go index 9f129fd9a6..3461d8a06e 100644 --- a/internal/adapter/permconfig/mcp_test.go +++ b/internal/adapter/permconfig/mcp_test.go @@ -5,9 +5,12 @@ import ( "context" "errors" "fmt" + "slices" "strings" "testing" + "github.com/goccy/go-yaml/parser" + "github.com/stacklok/mecatl/engine/adapter/memfs" "github.com/stacklok/mecatl/engine/port" "github.com/stacklok/mecatl/internal/adapter/slogdiag" @@ -512,3 +515,57 @@ func TestProjectMCPIgnoredWithValueFreeWarning(t *testing.T) { } } } + +func TestMCPBrokerSigningKeySettings(t *testing.T) { + cfg, err := parseYAML([]byte(`mcp: + mode: broker + broker: + signing_key_file: /keys/as2/key.pem + fallback_key_files: [/keys/as2-old/key.pem, /keys/as2-older/key.pem] +`)) + if err != nil { + t.Fatalf("parse signing key settings: %v", err) + } + if got := cfg.MCP.Broker; got.SigningKeyFile != "/keys/as2/key.pem" || !slices.Equal(got.FallbackKeyFiles, []string{"/keys/as2-old/key.pem", "/keys/as2-older/key.pem"}) { + t.Fatalf("broker signing key settings = %#v", got) + } + for name, tc := range map[string]struct{ body, want string }{ + "a relative key": {`signing_key_file: key.pem`, "mcp.broker.signing_key_file must be absolute"}, + "a blank key": {`signing_key_file: " "`, "mcp.broker.signing_key_file is required"}, + "fallbacks with an empty key": {"signing_key_file: \"\"\nfallback_key_files: [/keys/old.pem]", "requires mcp.broker.signing_key_file"}, + "a control character": {`signing_key_file: "/keys/a\tb.pem"`, "control characters"}, + "fallbacks without a key": {`fallback_key_files: [/keys/old.pem]`, "mcp.broker.fallback_key_files requires mcp.broker.signing_key_file"}, + "a relative fallback": {"signing_key_file: /keys/key.pem\nfallback_key_files: [old.pem]", "mcp.broker.fallback_key_files[0] must be absolute"}, + "an unknown signing key field": {`signing_key: /keys/key.pem`, "signing_key"}, + } { + // The settings parser reports a value-free schema error, so decode the + // section itself to see which rule refused it. + if _, err := parseYAML([]byte("mcp:\n mode: broker\n broker:\n " + strings.ReplaceAll(tc.body, "\n", "\n ") + "\n")); err == nil { + t.Errorf("%s: the settings parsed", name) + } + file, err := parser.ParseBytes([]byte(tc.body+"\n"), 0) + if err != nil { + t.Fatalf("%s: parse YAML: %v", name, err) + } + var profile MCPBrokerProfile + if err := profile.UnmarshalYAML(file.Docs[0].Body); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: decode = %v, want an error containing %q", name, err, tc.want) + } + } +} + +// TestProjectMCPBrokerSigningKeyIsIgnored: the embedded gateway's signing +// key is operator configuration; a project file cannot set it. +func TestProjectMCPBrokerSigningKeyIsIgnored(t *testing.T) { + var log bytes.Buffer + ws := &countingWS{Workspace: memfs.NewWorkspace("/repo")} + ws.seed(t, projectFileMecatl, "mcp:\n mode: broker\n broker:\n signing_key_file: /repo/key-canary.pem\n") + r := newWithEnv(Options{Conventional: true, TrustProject: true, Diagnostics: slogdiag.New(&log, false, port.LevelDebug)}, fakeEnv()) + _ = r.Resolve(context.Background(), ws) + if r.OperatorMCP() != nil { + t.Fatal("a project signing key became operator configuration") + } + if got := log.String(); !strings.Contains(got, "IGNORING a project-tier mcp") || strings.Contains(got, "key-canary") { + t.Fatalf("want a value-free warning, got: %s", got) + } +} diff --git a/internal/adapter/permconfig/schema.go b/internal/adapter/permconfig/schema.go index 3fffd29a84..0415124d0e 100644 --- a/internal/adapter/permconfig/schema.go +++ b/internal/adapter/permconfig/schema.go @@ -659,6 +659,10 @@ type MCPSection struct { type MCPBrokerProfile struct { // CallbackURL is required exactly when broker mode contains an OAuth route. It must be an absolute HTTPS URL without userinfo, query, or fragment; an omitted path or / is normalized to /. CallbackURL string `yaml:"callback_url"` + // SigningKeyFile is the absolute path of the PEM private key (RSA, ECDSA, or Ed25519; PKCS #1, SEC 1, or PKCS #8) the embedded MCP gateway's authorization server signs its tokens with, so they survive a restart. mecak8s requires it with the identity broker on and an embedded gateway entry in the identity broker's configuration file, and refuses it otherwise; it must differ from every identity broker key. It is read at startup, so a new key takes effect on restart. + SigningKeyFile string `yaml:"signing_key_file"` + // FallbackKeyFiles are absolute paths of earlier signing keys, PEM private keys like SigningKeyFile: tokens they signed still verify while they are listed, so the key can rotate. They require SigningKeyFile. + FallbackKeyFiles []string `yaml:"fallback_key_files"` } // MCPServerProfile is one named Streamable HTTP endpoint and its explicit auth mode. @@ -883,13 +887,43 @@ func (s *MCPSection) strictFields() map[string]any { } func (b *MCPBrokerProfile) strictFields() map[string]any { - return map[string]any{"callback_url": &b.CallbackURL} + return map[string]any{"callback_url": &b.CallbackURL, "signing_key_file": &b.SigningKeyFile, "fallback_key_files": &b.FallbackKeyFiles} } -// UnmarshalYAML strictly decodes broker-only metadata. Selection-specific -// validation belongs to the canonical authority resolver. +// UnmarshalYAML strictly decodes broker-only metadata and checks the signing +// key paths. Selection-specific validation belongs to the canonical authority +// resolver. func (b *MCPBrokerProfile) UnmarshalYAML(node ast.Node) error { - return decodeStrictMapping(node, "mcp.broker", b.strictFields()) + if err := decodeStrictMapping(node, "mcp.broker", b.strictFields()); err != nil { + return err + } + // An empty value is unset, as in the generated skeleton. + if b.SigningKeyFile != "" { + if err := validateMCPAbsolutePath("mcp.broker.signing_key_file", b.SigningKeyFile); err != nil { + return err + } + } + if len(b.FallbackKeyFiles) != 0 && b.SigningKeyFile == "" { + return errors.New("mcp.broker.fallback_key_files requires mcp.broker.signing_key_file") + } + for i, path := range b.FallbackKeyFiles { + if err := validateMCPAbsolutePath(fmt.Sprintf("mcp.broker.fallback_key_files[%d]", i), path); err != nil { + return err + } + } + return nil +} + +// validateMCPAbsolutePath refuses an empty, relative, or control-character +// path. +func validateMCPAbsolutePath(field, path string) error { + if err := validateMCPSafeValue(field, path); err != nil { + return err + } + if !filepath.IsAbs(path) { + return fmt.Errorf("%s must be absolute", field) + } + return nil } // UnmarshalYAML strictly decodes and validates an MCP operator section. diff --git a/internal/app/build.go b/internal/app/build.go index acf9938ec9..c8f4912579 100644 --- a/internal/app/build.go +++ b/internal/app/build.go @@ -999,17 +999,11 @@ type Config struct { // test-only and no production path sets it: it sees every ID-JAG // redeemed. identityBrokerAS2Transport func(http.RoundTripper) http.RoundTripper - // IdentityBrokerGatewayServers gives the real identity broker a gateway - // routing these servers, whose AS-2 Build binds once the MCP broker has - // started. It is test-only: production leaves it nil, which configures no - // gateway, so gateway calls are refused as not configured (#2533). - // Without IdentityBrokerAS2Trust, AS-2 refuses the gateway's ID-JAGs - // anyway. - IdentityBrokerGatewayServers []string // IdentityBrokerAS2Trust makes the bundled MCP broker's AS-2 trust an // ID-JAG issuer, such as a test's AS-1 from mcpbrokertest.TrustAS1. It is // test-only: production leaves it zero, and cannot build another, so - // AS-2 trusts no issuer. + // AS-2 trusts no issuer and Build refuses a gateway entry that routes + // servers. // Shortcut: AS-2 trusts AS-1 only in tests, and sends no reason codes until stacklok/toolhive#7030, so every invalid_grant at AS-2 takes the reasonless retry; removed by #2533 (AS-2 trusts AS-1 in production, with reason codes). IdentityBrokerAS2Trust as2Trust // IdentityBrokerAS1 connects the real identity broker's session open to an @@ -2341,10 +2335,10 @@ func Build(ctx context.Context, cfg Config) (*Built, error) { logMCPInventory(ctx, cfg.diag(), mcpInventory) // The identity broker is released after the MCP broker, on startup failure - // and on shutdown. A hosted AS-1 issues the gateway's ID-JAGs for the AS-2 - // the MCP broker will set up. - idjagTarget := deriveGatewayIDJAGTarget(cfg, brokerDeclaration, brokerSelected) - ib, err := buildIdentityBroker(ctx, cfg, idjagTarget) + // and on shutdown. Its embedded gateway entry must describe the embedded + // gateway the MCP broker will run. + ib, err := buildIdentityBroker(ctx, cfg, deriveEmbeddedGateway(cfg, brokerDeclaration, brokerSelected), + as2SigningKey{file: brokerDeclaration.SigningKeyFile, fallbacks: brokerDeclaration.FallbackKeyFiles}) if err != nil { childLiveness.Close() mcpClose() @@ -2374,12 +2368,11 @@ func Build(ctx context.Context, cfg Config) (*Built, error) { occupied = append(occupied, registered.Spec().Name) } } - identity := mcpBrokerIdentity{idjagTarget: idjagTarget, clientKeySetFile: ib.clientKeySetFile} - switch { - case ib.hosted != nil: - identity.as1Issuer = ib.hosted.Issuer - case cfg.IdentityBrokerAS1 != nil: - identity.as1Issuer = cfg.IdentityBrokerAS1.Issuer + // Without an embedded gateway entry the MCP broker is built as it is + // without the identity broker. + var identity mcpBrokerIdentity + if ib.gatewayEntry != nil { + identity = mcpBrokerIdentity{entry: ib.gatewayEntry, clientKeySetFile: ib.clientKeySetFile} } if ib.gateway && len(ib.gatewayServers) != 0 && agentCredentials != nil { identity.gatewayCalls = &mcpBrokerGatewayCalls{service: ib.service, credentials: agentCredentials, servers: ib.gatewayServers} @@ -2394,7 +2387,7 @@ func Build(ctx context.Context, cfg Config) (*Built, error) { return nil, err } } - // AS-2 is bound in process after the MCP broker starts (the #2560 + // AS-2 is bound in process after the MCP broker starts (the #2559 // shortcut on identitybroker.Broker.BindGatewayAS2). unbindAS2, err := ib.bindAS2(broker.as2) if err != nil { diff --git a/internal/app/identitybroker.go b/internal/app/identitybroker.go index b9b1fd8a45..667c232445 100644 --- a/internal/app/identitybroker.go +++ b/internal/app/identitybroker.go @@ -2,13 +2,12 @@ package app import ( "context" + "crypto" "errors" "fmt" "io" "net/http" - "net/url" "slices" - "strings" "time" "github.com/stacklok/mecatl/engine/port" @@ -131,54 +130,134 @@ type identityBrokerAS2 struct { HTTPClient *http.Client } -// gatewayIDJAGTarget is the AS-2 a hosted AS-1 issues the gateway's ID-JAGs -// for: the issuer and vMCP resource the bundled MCP broker gives AS-2, derived -// before either is built. -type gatewayIDJAGTarget struct { - Issuer, Resource string +// embeddedGateway is the embedded gateway the bundled MCP broker runs, as an +// embedded gateway entry must describe it: AS-2's issuer, token endpoint, and +// vMCP resource, derived from mcp.broker.callback_url before either broker is +// built, and the OAuth routes it can route. +type embeddedGateway struct { + Issuer, TokenEndpoint, Resource string + // Routes are the names of the MCP broker's OAuth routes. + Routes []string +} + +// as2SigningKey is the embedded gateway's signing key and its fallbacks +// (mcp.broker.signing_key_file and fallback_key_files). The identity broker +// never holds it; startup only checks it is not one of the broker's keys. +type as2SigningKey struct { + file string + fallbacks []string } -// errAS2IssuerIsAS1s refuses an AS-2 that would share AS-1's issuer. -var errAS2IssuerIsAS1s = errors.New("the MCP gateway's authorization server (AS-2) would have the same issuer as AS-1") +// errEmbeddedEntryWithoutEmbeddedGateway refuses an embedded gateway entry in +// a process that runs no embedded gateway. +var errEmbeddedEntryWithoutEmbeddedGateway = errors.New("the identity broker's configuration file declares an embedded gateway, but this process runs none: the embedded gateway needs the bundled MCP broker (mcp.mode: broker) with an OAuth server and an https mcp.broker.callback_url") + +// errEmbeddedEntryDisagrees refuses an embedded gateway entry whose AS-2 +// differs from the embedded gateway's. +var errEmbeddedEntryDisagrees = errors.New("the identity broker's embedded gateway entry disagrees with the embedded gateway this process runs") + +// errEmbeddedEntryServerIsNotARoute refuses an embedded gateway entry routing +// a server the MCP broker does not route through its embedded gateway. +var errEmbeddedEntryServerIsNotARoute = errors.New("the identity broker's embedded gateway entry routes a server that is not one of the MCP broker's OAuth servers (mcp.servers with auth.mode: oauth; names match exactly)") + +// errGatewayServersBeforeAS2TrustsAS1 refuses an entry routing servers while +// AS-2 trusts no ID-JAG issuer, which would refuse every call's ID-JAG. +// +// Shortcut: production's gateway entry routes no servers; removed by #2533 (AS-2 trusts AS-1). +var errGatewayServersBeforeAS2TrustsAS1 = errors.New("the identity broker's gateway entry routes servers, but the embedded gateway's authorization server (AS-2) does not trust AS-1's ID-JAGs yet (#2533); list no servers until it does") + +// errGatewayServersWithoutAS1 refuses an entry routing servers without the +// AS-1 that issues their calls' ID-JAGs. +var errGatewayServersWithoutAS1 = errors.New("the identity broker's gateway entry routes servers, which requires AS-1 (--identity-broker-as1-issuer) to issue their calls' ID-JAGs") -// errAS2IsNotIDJAGTarget refuses an AS-2 other than the one AS-1 issues the -// gateway's ID-JAGs for. -var errAS2IsNotIDJAGTarget = errors.New("the MCP gateway's authorization server (AS-2) is not the one AS-1 issues ID-JAGs for") +// errNoAS2SigningKey refuses an embedded gateway entry without the embedded +// gateway's signing key. +var errNoAS2SigningKey = errors.New("the identity broker's embedded gateway entry requires the embedded gateway's signing key (mcp.broker.signing_key_file)") + +// errAS2SigningKeyWithoutEntry refuses the embedded gateway's signing key +// without the identity broker and its embedded gateway entry. +// +// Shortcut: the key is allowed only with the identity broker on; removed by #2869 (the embedded gateway's keys survive a restart with the identity broker off). +var errAS2SigningKeyWithoutEntry = errors.New("mcp.broker.signing_key_file requires the identity broker (--enable-identity-broker) with an embedded gateway entry in its configuration file") + +// errAS2SigningKeyIsABrokerKey refuses an embedded gateway signing key that +// is also one of the identity broker's keys. +var errAS2SigningKeyIsABrokerKey = errors.New("the embedded gateway's signing key (mcp.broker.signing_key_file or a fallback) is also one of the identity broker's keys; each role needs its own key") + +// errAS2IsNotTheEntry refuses an AS-2 other than the one the identity +// broker's gateway entry names. +var errAS2IsNotTheEntry = errors.New("the MCP gateway's authorization server (AS-2) is not the one the identity broker's gateway entry names") // errGatewayIsNotAS2Resource refuses gateway calls sent to a gateway whose // resource is not the one AS-2 issues their tokens for. var errGatewayIsNotAS2Resource = errors.New("the MCP gateway's resource is not the one its authorization server (AS-2) issues tokens for") -// sameIssuer reports whether two issuer URLs name the same server: scheme and -// host compare case-insensitively, a default port equals none, and a trailing -// slash is ignored. Unparseable URLs compare byte for byte. -func sameIssuer(a, b string) bool { - if a == b { - return true - } - ua, errA := url.Parse(a) - ub, errB := url.Parse(b) - if errA != nil || errB != nil { - return false - } - return strings.EqualFold(ua.Scheme, ub.Scheme) && - strings.EqualFold(ua.Hostname(), ub.Hostname()) && - effectivePort(ua) == effectivePort(ub) && - strings.TrimSuffix(ua.EscapedPath(), "/") == strings.TrimSuffix(ub.EscapedPath(), "/") +// as1Issuer is the issuer of the AS-1 the identity broker uses, hosted or +// not; empty without one. +func as1Issuer(cfg Config) string { + switch { + case cfg.IdentityBrokerHostedAS1 != nil: + return cfg.IdentityBrokerHostedAS1.Issuer + case cfg.IdentityBrokerAS1 != nil: + return cfg.IdentityBrokerAS1.Issuer + } + return "" } -// effectivePort is u's port, or its scheme's default when it names none. -func effectivePort(u *url.URL) string { - if p := u.Port(); p != "" { - return p +// checkGatewayEntry returns the embedded gateway entry of file, after +// checking it against the embedded gateway this process runs and the +// embedded gateway's signing key against the broker's keys; nil when file +// has none, which then refuses a signing key. It runs before AS-1 is built. +func checkGatewayEntry(cfg Config, file brokerconfig.File, embedded *embeddedGateway, key as2SigningKey) (*identitybroker.GatewayEntry, error) { + if len(file.Gateways) == 0 { + if key.file != "" { + return nil, errAS2SigningKeyWithoutEntry + } + return nil, nil + } + // The broker accepts one embedded entry (identitybroker.ValidateGatewayEntries). + entry := file.Gateways[0] + entry.Servers = slices.Clone(entry.Servers) + if embedded == nil { + return nil, errEmbeddedEntryWithoutEmbeddedGateway + } + for _, f := range []struct{ name, entry, embedded string }{ + {"as2_issuer", entry.AS2Issuer, embedded.Issuer}, + {"token_endpoint", entry.TokenEndpoint, embedded.TokenEndpoint}, + {"resource", entry.Resource, embedded.Resource}, + } { + if f.entry != f.embedded { + return nil, fmt.Errorf("%w: its %s is %q, the embedded gateway's is %q", errEmbeddedEntryDisagrees, f.name, f.entry, f.embedded) + } } - switch strings.ToLower(u.Scheme) { - case "https": - return "443" - case "http": - return "80" + for _, server := range entry.Servers { + if !slices.Contains(embedded.Routes, server) { + return nil, fmt.Errorf("%w: %q", errEmbeddedEntryServerIsNotARoute, server) + } } - return "" + if len(entry.Servers) != 0 { + if !cfg.IdentityBrokerAS2Trust.TrustsAnIssuer() { + return nil, errGatewayServersBeforeAS2TrustsAS1 + } + if cfg.IdentityBrokerHostedAS1 == nil && cfg.IdentityBrokerAS1 == nil { + return nil, errGatewayServersWithoutAS1 + } + } + if key.file == "" { + return nil, errNoAS2SigningKey + } + as2Keys, err := as2SigningPublicKeys(key) + if err != nil { + return nil, fmt.Errorf("the embedded gateway's signing key: %w", err) + } + brokerKeys := file.Keys.PublicKeys() + for _, pub := range as2Keys { + eq, ok := pub.(interface{ Equal(crypto.PublicKey) bool }) + if ok && slices.ContainsFunc(brokerKeys, eq.Equal) { + return nil, errAS2SigningKeyIsABrokerKey + } + } + return &entry, nil } // hostedAS1IDJAGMaxLifetime caps the broker refresh tokens the hosted AS-1 @@ -210,8 +289,12 @@ type identityBrokerParts struct { // recorder holds the core's decision and ID-JAG records; nil for an // injected core. recorder *identitybroker.MemoryRecorder + // gatewayEntry is the configuration file's embedded gateway entry, which + // startup checked against the embedded gateway; nil without one, and then + // the MCP broker sets up no AS-2. + gatewayEntry *identitybroker.GatewayEntry // gateway reports whether the core has a gateway, whose AS-2 bindAS2 - // binds. + // binds: the entry routes servers. gateway bool // gatewayServers are the servers the gateway routes; set only with // gateway. @@ -248,18 +331,17 @@ func (p identityBrokerParts) bindAS2(as2 *identityBrokerAS2) (unbind func(), err // as does a configuration that gives sessions a shell. // // The real broker starts from its configuration file and the operator keys it -// names; no key is generated. With a hosted AS-1 and no test override, session -// open converts users' access tokens at that AS-1 in process: -// buildBrokerWithHostedAS1 registers the file's broker client key set there -// for the confidential delegate, which may obtain ID-JAGs for target when it -// is set. -func buildIdentityBroker(ctx context.Context, cfg Config, target *gatewayIDJAGTarget) (identityBrokerParts, error) { +// names; no key is generated. Its embedded gateway entry, if any, must agree +// with embedded, the embedded gateway this process runs, and needs the +// embedded gateway's signing key, as2Key, which is refused without one. With +// a hosted AS-1 and no test override, session open converts users' access +// tokens at that AS-1 in process: buildBrokerWithHostedAS1 registers the +// file's broker client key set there for the confidential delegate, which may +// obtain ID-JAGs for the entry when it routes servers. +func buildIdentityBroker(ctx context.Context, cfg Config, embedded *embeddedGateway, as2Key as2SigningKey) (identityBrokerParts, error) { if !cfg.IdentityBroker { - switch { - case cfg.IdentityBrokerHostedAS1 != nil: - return identityBrokerParts{}, errIdentityBrokerAS1WithoutBroker - case cfg.IdentityBrokerConfigFile != "": - return identityBrokerParts{}, errIdentityBrokerConfigFileWithoutBroker + if err := checkIdentityBrokerOff(cfg, as2Key); err != nil { + return identityBrokerParts{}, err } return identityBrokerParts{release: func() {}}, nil } @@ -273,24 +355,31 @@ func buildIdentityBroker(ctx context.Context, cfg Config, target *gatewayIDJAGTa // An injected test core needs no file; its hosted AS-1 generates its // signing key. var file brokerconfig.File + var entry *identitybroker.GatewayEntry if core == nil { if cfg.IdentityBrokerConfigFile == "" { return identityBrokerParts{}, errNoIdentityBrokerConfigFile } var err error - if file, err = brokerconfig.Load(cfg.IdentityBrokerConfigFile, brokerconfig.Host{AS1: cfg.IdentityBrokerHostedAS1 != nil}); err != nil { + if file, err = brokerconfig.Load(cfg.IdentityBrokerConfigFile, brokerconfig.Host{AS1: cfg.IdentityBrokerHostedAS1 != nil, AS1Issuer: as1Issuer(cfg)}); err != nil { return identityBrokerParts{}, err } + if entry, err = checkGatewayEntry(cfg, file, embedded, as2Key); err != nil { + return identityBrokerParts{}, err + } + } else if as2Key.file != "" { + // An injected test core has no configuration file, so no entry. + return identityBrokerParts{}, errAS2SigningKeyWithoutEntry } // Production wiring: host AS-1 with the broker client as the delegate, // then point the broker's session open at that AS-1. A test that replaces // the core or sets IdentityBrokerAS1 explicitly keeps the paths below. if core == nil && cfg.IdentityBrokerAS1 == nil && cfg.IdentityBrokerHostedAS1 != nil { - return buildBrokerWithHostedAS1(ctx, cfg, file, target) + return buildBrokerWithHostedAS1(ctx, cfg, file, entry) } var parts identityBrokerParts if core == nil { - broker, err := newIdentityBroker(ctx, cfg, file) + broker, err := newIdentityBroker(ctx, cfg, file, entry) if err != nil { return identityBrokerParts{}, fmt.Errorf("build identity broker: %w", err) } @@ -323,6 +412,20 @@ func buildIdentityBroker(ctx context.Context, cfg Config, target *gatewayIDJAGTa return parts, nil } +// checkIdentityBrokerOff refuses configuration that needs the identity +// broker when it is off. +func checkIdentityBrokerOff(cfg Config, as2Key as2SigningKey) error { + switch { + case cfg.IdentityBrokerHostedAS1 != nil: + return errIdentityBrokerAS1WithoutBroker + case cfg.IdentityBrokerConfigFile != "": + return errIdentityBrokerConfigFileWithoutBroker + case as2Key.file != "": + return errAS2SigningKeyWithoutEntry + } + return nil +} + // localWorkspace reports whether sessions' file tools can reach this // process's own filesystem: a workspace served by the local placement, alone // or as remote execution's local fallback. The Redis filesystem excludes a @@ -335,10 +438,11 @@ func localWorkspace(cfg Config) bool { // AS-1 are both enabled: it hosts AS-1 with the file's broker client key set // registered for the confidential delegate client // identitybroker.BrokerClientID, and builds the broker with its session open -// pointed at that AS-1 in process. With target, the delegate also obtains -// per-call ID-JAGs for it there, whose actor tokens AS-1 checks with the -// broker's CredentialVerifier. -func buildBrokerWithHostedAS1(ctx context.Context, cfg Config, file brokerconfig.File, target *gatewayIDJAGTarget) (identityBrokerParts, error) { +// pointed at that AS-1 in process. With an entry that routes servers, the +// delegate also obtains per-call ID-JAGs for its AS-2 there, whose actor +// tokens AS-1 checks with the broker's CredentialVerifier; AS-1 issues none +// for any other audience or resource. +func buildBrokerWithHostedAS1(ctx context.Context, cfg Config, file brokerconfig.File, entry *identitybroker.GatewayEntry) (identityBrokerParts, error) { as1 := cfg.IdentityBrokerHostedAS1 sources := make([]string, len(as1.PublicClients)) for i, c := range as1.PublicClients { @@ -350,12 +454,12 @@ func buildBrokerWithHostedAS1(ctx context.Context, cfg Config, file brokerconfig AllowedSourceClients: sources, IDJAGMaxLifetime: hostedAS1IDJAGMaxLifetime, } - if target != nil { - // Shortcut: AS-1 issues ID-JAGs only for the AS-2 the test-only gateway servers configure, so production configures no target and no actor profile; removed by #2533 and #2538. + if entry != nil && len(entry.Servers) != 0 { + // Shortcut: AS-1 issues ID-JAGs only for a gateway entry that routes servers, and production's routes none until AS-2 trusts AS-1, so production configures no target and no actor profile; removed by #2533. delegate.IDJAG = &as1server.IDJAGIssuance{ ActIssuer: identitybroker.ActorIssuer(identityBrokerConfig(cfg, file).TrustDomain), // Lifetime stays zero, ToolHive's default of a minute. - Targets: []as1server.IDJAGTarget{{Issuer: target.Issuer, ClientID: identitybroker.BrokerClientID, Resources: []string{target.Resource}}}, + Targets: []as1server.IDJAGTarget{{Issuer: entry.AS2Issuer, ClientID: identitybroker.BrokerClientID, Resources: []string{entry.Resource}}}, } } server, err := buildHostedAS1(ctx, as1, file, delegate) @@ -372,7 +476,7 @@ func buildBrokerWithHostedAS1(ctx context.Context, cfg Config, file brokerconfig if delegate.IDJAG != nil { cfg.IdentityBrokerAS1.ActorTokens = server } - broker, err := newIdentityBroker(ctx, cfg, file) + broker, err := newIdentityBroker(ctx, cfg, file, entry) if err != nil { _ = server.Close() return identityBrokerParts{}, fmt.Errorf("build identity broker: %w", err) @@ -440,7 +544,10 @@ type identityBroker struct { // clientKeySetFile is the broker client's public key set file. clientKeySetFile string recorder *identitybroker.MemoryRecorder - gateway bool + // gatewayEntry is the configuration file's checked embedded gateway + // entry; nil without one. + gatewayEntry *identitybroker.GatewayEntry + gateway bool // gatewayServers are the servers the gateway routes. gatewayServers []string } @@ -450,7 +557,7 @@ type identityBroker struct { func (b identityBroker) parts() identityBrokerParts { return identityBrokerParts{ client: b.client, clientKeySetFile: b.clientKeySetFile, core: b.core, definitions: b.definitions, - recorder: b.recorder, gateway: b.gateway, gatewayServers: b.gatewayServers, + recorder: b.recorder, gatewayEntry: b.gatewayEntry, gateway: b.gateway, gatewayServers: b.gatewayServers, } } @@ -497,9 +604,9 @@ var errNoBrokerClientKey = errors.New("the identity broker's configuration file // cannot be read fails startup, and each definition left out or adjusted is // logged. With cfg.IdentityBrokerAS1, session open converts access tokens at // that AS-1, authenticating with the broker client key, and calls get their -// ID-JAGs there; a gateway is configured only then, and only when a test sets -// cfg.IdentityBrokerGatewayServers. -func newIdentityBroker(ctx context.Context, cfg Config, file brokerconfig.File) (identityBroker, error) { +// ID-JAGs there; a gateway is configured only then, and only when entry, the +// checked gateway entry, routes servers. +func newIdentityBroker(ctx context.Context, cfg Config, file brokerconfig.File, entry *identitybroker.GatewayEntry) (identityBroker, error) { config := identityBrokerConfig(cfg, file) definitions, err := loadIdentityBrokerDefinitions(ctx, cfg) if err != nil { @@ -532,11 +639,11 @@ func newIdentityBroker(ctx context.Context, cfg Config, file brokerconfig.File) opts = append(opts, identitybroker.WithClock(as1.Now)) } // A gateway needs AS-1 to issue its ID-JAGs, so without an AS-1 there - // is none. - // Shortcut: production configures no gateway entry, so gateway calls are refused as not configured; removed by #2533 (AS-2 trusts AS-1 in production, gateway from configuration). - if cfg.IdentityBrokerGatewayServers != nil { - opts = append(opts, identitybroker.WithGateway(identitybroker.Gateway{Servers: cfg.IdentityBrokerGatewayServers})) - gateway, gatewayServers = true, append([]string(nil), cfg.IdentityBrokerGatewayServers...) + // is none; checkGatewayEntry refuses an entry routing servers then. + // Shortcut: production's gateway entry routes no servers, so gateway calls are refused as not configured; removed by #2533 (AS-2 trusts AS-1). + if entry != nil && len(entry.Servers) != 0 { + opts = append(opts, identitybroker.WithGateway(identitybroker.Gateway{Issuer: entry.AS2Issuer, Resource: entry.Resource, Servers: entry.Servers})) + gateway, gatewayServers = true, slices.Clone(entry.Servers) } } core, err := identitybroker.New(config, definitions, file.Keys.AgentIssuer, opts...) @@ -550,7 +657,7 @@ func newIdentityBroker(ctx context.Context, cfg Config, file brokerconfig.File) } return identityBroker{ core: core, definitions: definitions, client: client, clientKeySetFile: file.BrokerClientKeySetFile, - recorder: recorder, gateway: gateway, gatewayServers: gatewayServers, + recorder: recorder, gatewayEntry: entry, gateway: gateway, gatewayServers: gatewayServers, }, nil } diff --git a/internal/app/identitybroker_entry_test.go b/internal/app/identitybroker_entry_test.go new file mode 100644 index 0000000000..b11d3a9468 --- /dev/null +++ b/internal/app/identitybroker_entry_test.go @@ -0,0 +1,235 @@ +package app + +import ( + "crypto/ecdsa" + "errors" + "strings" + "testing" + + "github.com/stacklok/mecatl/internal/adapter/mcpauthority" + "github.com/stacklok/mecatl/internal/adapter/mcpbroker/mcpbrokertest" + "github.com/stacklok/mecatl/internal/adapter/permconfig" + "github.com/stacklok/mecatl/internal/identitybroker" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/brokerconfig/brokerconfigtest" + "github.com/stacklok/mecatl/internal/testutil/identityharness" +) + +// The tests in this file build with the identity broker's gateway entries and +// the embedded gateway's signing key. None is parallel: a protected route +// reads an environment variable. + +// entryBuild is a build configuration with the identity broker on, the +// protected calendar route with an embedded gateway signing key, and opts' +// configuration file. +func entryBuild(t *testing.T, opts brokerconfigtest.Options) Config { + t.Helper() + return Config{ + UseMock: true, NoSoul: true, NoShell: true, + IdentityBroker: true, MCPAuthority: protectedBrokerAuthorityWithKey(t), + IdentityBrokerConfigFile: brokerconfigtest.Write(t, opts).Path, + } +} + +// otherAS2Trust is an AS-2 trust in an issuer other than any AS-1 here, so a +// gateway entry may route servers. +func otherAS2Trust(t *testing.T) as2Trust { + t.Helper() + return mcpbrokertest.TrustAS1(mcpbrokertest.AS1Trust{ + Issuer: "https://untrusted-as1.mecatl.test", JWKSURL: "https://untrusted-as1.mecatl.test/jwks", + CAFile: identityharness.New(t, identityharness.Options{}).WriteCACert(t, t.TempDir()), Subjects: []string{"nobody"}, + }) +} + +// wantBuildRefused fails t unless Build refuses cfg with an error wrapping +// want, when set, and containing detail. +func wantBuildRefused(t *testing.T, cfg Config, want error, detail string) { + t.Helper() + built, err := buildIsolated(t, t.Context(), cfg) + if err == nil { + built.Close() + t.Fatalf("Build succeeded, want %v", want) + } + if (want != nil && !errors.Is(err, want)) || !strings.Contains(err.Error(), detail) { + t.Fatalf("Build error = %v, want %v containing %q", err, want, detail) + } +} + +// TestBuildRefusesADisagreeingGatewayEntry: an embedded gateway entry must +// name the AS-2 the embedded gateway derives from mcp.broker.callback_url, +// byte for byte, route only the MCP broker's OAuth servers, and have an +// embedded gateway to describe. +func TestBuildRefusesADisagreeingGatewayEntry(t *testing.T) { + entry := func(edit func(*identitybroker.GatewayEntry)) []identitybroker.GatewayEntry { + e := embeddedEntry() + edit(&e[0]) + return e + } + for name, tc := range map[string]struct { + gateways []identitybroker.GatewayEntry + edit func(*Config) + want error + detail string + }{ + "another issuer": { + gateways: entry(func(e *identitybroker.GatewayEntry) { e.AS2Issuer = "https://broker.example/v1/mcp/other" }), + want: errEmbeddedEntryDisagrees, detail: "as2_issuer", + }, + "an issuer with a trailing slash": { + gateways: entry(func(e *identitybroker.GatewayEntry) { e.AS2Issuer += "/" }), + want: errEmbeddedEntryDisagrees, detail: "as2_issuer", + }, + "another token endpoint": { + gateways: entry(func(e *identitybroker.GatewayEntry) { e.TokenEndpoint = as2TestIssuer + "/token" }), + want: errEmbeddedEntryDisagrees, detail: "token_endpoint", + }, + "another resource": { + gateways: entry(func(e *identitybroker.GatewayEntry) { e.Resource = as2TestIssuer }), + want: errEmbeddedEntryDisagrees, detail: "resource", + }, + "a server the MCP broker does not route": { + gateways: embeddedEntry("github"), want: errEmbeddedEntryServerIsNotARoute, detail: `"github"`, + }, + "a server in another case": { + gateways: embeddedEntry("Calendar"), want: errEmbeddedEntryServerIsNotARoute, detail: `"Calendar"`, + }, + "an anonymous server": { + gateways: embeddedEntry("docs"), want: errEmbeddedEntryServerIsNotARoute, detail: `"docs"`, + edit: func(cfg *Config) { + declaration, _ := cfg.MCPAuthority.Broker() + declaration.Routes = append(declaration.Routes, permconfig.MCPServerProfile{Name: "docs", URL: "https://docs.example/mcp", Auth: permconfig.MCPAuthProfile{Mode: "none"}}) + cfg.MCPAuthority = mcpauthority.NewBroker(declaration) + }, + }, + "no MCP broker": { + gateways: embeddedEntry(), want: errEmbeddedEntryWithoutEmbeddedGateway, + edit: func(cfg *Config) { cfg.MCPAuthority = nil }, + }, + "no OAuth route": { + gateways: embeddedEntry(), want: errEmbeddedEntryWithoutEmbeddedGateway, + edit: func(cfg *Config) { cfg.MCPAuthority = mcpauthority.NewBroker(mcpauthority.BrokerConfig{}) }, + }, + "a configured MCP broker": { + gateways: embeddedEntry(), want: errEmbeddedEntryWithoutEmbeddedGateway, + edit: func(cfg *Config) { + cfg.MCPAuthority = mcpauthority.NewBroker(mcpauthority.BrokerConfig{CallbackURL: brokerTestCallbackURL}) + cfg.MCPBrokerCaller = unusedBrokerCaller + }, + }, + "a non-https callback": { + gateways: embeddedEntry(), want: errEmbeddedEntryWithoutEmbeddedGateway, + edit: func(cfg *Config) { + declaration, _ := cfg.MCPAuthority.Broker() + declaration.CallbackURL = "http://broker.example/oauth/callback" + cfg.MCPAuthority = mcpauthority.NewBroker(declaration) + }, + }, + } { + t.Run(name, func(t *testing.T) { + cfg := entryBuild(t, brokerconfigtest.Options{Gateways: tc.gateways}) + cfg.IdentityBrokerAS1 = unusedAS1("https://as1.example") + cfg.IdentityBrokerAS2Trust = otherAS2Trust(t) + if tc.edit != nil { + tc.edit(&cfg) + } + wantBuildRefused(t, cfg, tc.want, tc.detail) + }) + } +} + +// TestBuildRefusesGatewayServersBeforeAS2TrustsAS1: production's AS-2 +// trusts no ID-JAG issuer, so an entry routing servers is refused, naming +// #2533; routing them also needs AS-1. +func TestBuildRefusesGatewayServersBeforeAS2TrustsAS1(t *testing.T) { + cfg := entryBuild(t, brokerconfigtest.Options{Gateways: embeddedEntry(gatewayTestServer)}) + cfg.IdentityBrokerAS1 = unusedAS1("https://as1.example") + wantBuildRefused(t, cfg, errGatewayServersBeforeAS2TrustsAS1, "#2533") + + cfg = entryBuild(t, brokerconfigtest.Options{Gateways: embeddedEntry(gatewayTestServer)}) + cfg.IdentityBrokerAS2Trust = otherAS2Trust(t) + wantBuildRefused(t, cfg, errGatewayServersWithoutAS1, "") +} + +// TestBuildGatewaySigningKeyRules: the embedded gateway's signing key is +// required with an embedded gateway entry and refused without one, including +// with the identity broker off. +func TestBuildGatewaySigningKeyRules(t *testing.T) { + t.Run("missing with an entry", func(t *testing.T) { + cfg := entryBuild(t, brokerconfigtest.Options{Gateways: embeddedEntry()}) + cfg.MCPAuthority = protectedBrokerAuthority() + wantBuildRefused(t, cfg, errNoAS2SigningKey, "") + }) + t.Run("without an entry", func(t *testing.T) { + wantBuildRefused(t, entryBuild(t, brokerconfigtest.Options{}), errAS2SigningKeyWithoutEntry, "") + }) + t.Run("with the identity broker off", func(t *testing.T) { + wantBuildRefused(t, Config{UseMock: true, NoSoul: true, NoShell: true, MCPAuthority: protectedBrokerAuthorityWithKey(t)}, errAS2SigningKeyWithoutEntry, "") + }) + t.Run("with an injected core", func(t *testing.T) { + cfg := Config{UseMock: true, NoSoul: true, NoShell: true, IdentityBroker: true, identityBrokerCore: newClosableCore(t), MCPAuthority: protectedBrokerAuthorityWithKey(t)} + wantBuildRefused(t, cfg, errAS2SigningKeyWithoutEntry, "") + }) + t.Run("unreadable", func(t *testing.T) { + cfg := entryBuild(t, brokerconfigtest.Options{Gateways: embeddedEntry()}) + declaration, _ := cfg.MCPAuthority.Broker() + declaration.SigningKeyFile = t.TempDir() + "/absent.pem" + cfg.MCPAuthority = mcpauthority.NewBroker(declaration) + wantBuildRefused(t, cfg, nil, "the embedded gateway's signing key") + }) +} + +// TestBuildRefusesAGatewaySigningKeyThatIsABrokerKey compares the public +// halves of the embedded gateway's signing key and its fallbacks with every +// identity broker key. +func TestBuildRefusesAGatewaySigningKeyThatIsABrokerKey(t *testing.T) { + h := identityharness.New(t, identityharness.Options{}) + agentFallback := brokerconfigtest.NewKey(t) + for name, tc := range map[string]struct { + hostedAS1 bool + // key and fallback pick the embedded gateway's signing key and a + // fallback from the written file; nil picks a new key. + key, fallback func(brokerconfigtest.Files) string + }{ + "the agent issuer key": {key: func(f brokerconfigtest.Files) string { return writeAS2Key(t, f.AgentIssuerKey) }}, + "an agent issuer fallback": {key: func(brokerconfigtest.Files) string { return writeAS2Key(t, agentFallback) }}, + "the broker client key": {key: func(f brokerconfigtest.Files) string { return writeAS2Key(t, f.BrokerClientKey) }}, + "a fallback that is the broker client key": { + fallback: func(f brokerconfigtest.Files) string { return writeAS2Key(t, f.BrokerClientKey) }, + }, + "AS-1's signing key": {hostedAS1: true, key: func(f brokerconfigtest.Files) string { return f.AS1SigningKeyFile }}, + "an AS-1 fallback key": {hostedAS1: true, fallback: func(f brokerconfigtest.Files) string { return f.AS1FallbackKeyFiles[0] }}, + } { + t.Run(name, func(t *testing.T) { + opts := brokerconfigtest.Options{Gateways: embeddedEntry(), AgentIssuerFallbackKeys: []*ecdsa.PrivateKey{agentFallback}, HostedAS1: tc.hostedAS1} + if tc.hostedAS1 { + opts.AS1Fallbacks = 1 + } + files := brokerconfigtest.Write(t, opts) + declaration, _ := protectedBrokerAuthority().Broker() + declaration.SigningKeyFile = writeAS2Key(t, brokerconfigtest.NewKey(t)) + if tc.key != nil { + declaration.SigningKeyFile = tc.key(files) + } + if tc.fallback != nil { + declaration.FallbackKeyFiles = []string{tc.fallback(files)} + } + cfg := Config{ + UseMock: true, NoSoul: true, NoShell: true, IdentityBroker: true, + MCPAuthority: mcpauthority.NewBroker(declaration), IdentityBrokerConfigFile: files.Path, + } + if tc.hostedAS1 { + cfg.IdentityBrokerHostedAS1 = hostedAS1Config(t, h, "https://as1.mecatl.test/as1") + } + wantBuildRefused(t, cfg, errAS2SigningKeyIsABrokerKey, "") + }) + } + // Positive control: a key of its own, with a fallback of its own, starts. + cfg := entryBuild(t, brokerconfigtest.Options{Gateways: embeddedEntry(), AgentIssuerFallbackKeys: []*ecdsa.PrivateKey{agentFallback}}) + declaration, _ := cfg.MCPAuthority.Broker() + declaration.FallbackKeyFiles = []string{writeAS2Key(t, brokerconfigtest.NewKey(t))} + cfg.MCPAuthority = mcpauthority.NewBroker(declaration) + built, err := buildIsolated(t, t.Context(), cfg) + if err != nil { + t.Fatalf("Build with the embedded gateway's own keys: %v", err) + } + built.Close() +} diff --git a/internal/app/identitybroker_gateway_test.go b/internal/app/identitybroker_gateway_test.go index 458fc18f6d..febf29b77f 100644 --- a/internal/app/identitybroker_gateway_test.go +++ b/internal/app/identitybroker_gateway_test.go @@ -24,9 +24,11 @@ import ( "github.com/stacklok/mecatl/internal/adapter/mcpauthority" "github.com/stacklok/mecatl/internal/adapter/mcpbroker" "github.com/stacklok/mecatl/internal/adapter/mcpbroker/mcpbrokertest" + "github.com/stacklok/mecatl/internal/adapter/permconfig" "github.com/stacklok/mecatl/internal/identitybroker" "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server" "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server/as1servertest" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/authserverclient" "github.com/stacklok/mecatl/internal/identitybroker/adapter/brokerconfig/brokerconfigtest" "github.com/stacklok/mecatl/internal/testutil/identityharness" ) @@ -57,10 +59,11 @@ func wantAct(agentID string) map[string]any { } // buildWithRealAS1 builds with the real AS-1, issuing ID-JAGs for AS-2 and -// checking actor tokens with the built broker's verifier, and a protected -// calendar route, after edit changes the configuration. trustAS1 makes AS-2 -// trust AS-1 for Alice. -func buildWithRealAS1(t *testing.T, trustAS1 bool, edit func(*Config)) *gatewayBuild { +// checking actor tokens with the built broker's verifier, a protected +// calendar route with the embedded gateway's signing key, and gateways, the +// broker's gateway entries, after edit changes the configuration. trustAS1 +// makes AS-2 trust AS-1 for Alice. +func buildWithRealAS1(t *testing.T, trustAS1 bool, gateways []identitybroker.GatewayEntry, edit func(*Config)) *gatewayBuild { t.Helper() h := identityharness.New(t, identityharness.Options{}) a := as1servertest.Start(t, h, as1servertest.IssueIDJAGs(brokerconfigtest.TrustDomain, as2TestIssuer, as2TestIssuer+"/mcp")) @@ -74,11 +77,14 @@ func buildWithRealAS1(t *testing.T, trustAS1 bool, edit func(*Config)) *gatewayB UseMock: true, NoSoul: true, NoShell: true, IdentityBroker: true, MCPAuthority: protectedBrokerAuthority(), // The file's broker client key is the one AS-1 registered. - IdentityBrokerConfigFile: brokerconfigtest.Write(t, brokerconfigtest.Options{BrokerClientKey: a.Key}).Path, + IdentityBrokerConfigFile: brokerconfigtest.Write(t, brokerconfigtest.Options{BrokerClientKey: a.Key, Gateways: gateways}).Path, IdentityBrokerAS1: &IdentityBrokerAS1{ Issuer: a.Issuer(), TokenEndpoint: a.Server.TokenEndpoint(), HTTPClient: as1HTTP, ActorTokens: a.Server, }, } + if len(gateways) != 0 { + cfg.MCPAuthority = protectedBrokerAuthorityWithKey(t) + } if trustAS1 { cfg.IdentityBrokerAS2Trust = mcpbrokertest.TrustAS1(mcpbrokertest.AS1Trust{ Issuer: a.Issuer(), JWKSURL: a.JWKSURL(), CAFile: h.WriteCACert(t, t.TempDir()), @@ -175,7 +181,10 @@ func jwtClaims(t *testing.T, token string) map[string]any { // AS-1 and a gateway token at the real AS-2 naming the agent as the actor and // the broker as the client. func TestBuildBindsAS2ToTheIdentityBrokerGateway(t *testing.T) { - g := buildWithRealAS1(t, true, func(cfg *Config) { cfg.IdentityBrokerGatewayServers = []string{gatewayTestServer} }) + g := buildWithRealAS1(t, true, embeddedEntry(gatewayTestServer), nil) + if got := g.built.identityBrokerAS2; got == nil || got.Issuer != as2TestIssuer || got.TokenEndpoint != as2TestIssuer+"/oauth/token" || got.Resource != as2TestIssuer+"/mcp" { + t.Fatalf("AS-2 = %+v, want the entry's", got) + } s, cred, _ := g.open(t) auth, err := g.built.IdentityBroker.AuthorizeCall(t.Context(), g.call(s, cred)) if err != nil { @@ -197,26 +206,12 @@ func TestBuildBindsAS2ToTheIdentityBrokerGateway(t *testing.T) { } // TestBuildIdentityBrokerUnboundGatewayIsUnavailable shows a gateway whose -// AS-2 is not bound, because startup set up no AS-2 or shutdown unbound it, -// refuses calls as unavailable before asking AS-1 for an ID-JAG. +// AS-2 shutdown unbound refuses calls as unavailable before asking AS-1 for +// an ID-JAG. Startup never leaves a gateway unbound: it refuses an entry +// without the embedded gateway (TestBuildRefusesADisagreeingGatewayEntry). func TestBuildIdentityBrokerUnboundGatewayIsUnavailable(t *testing.T) { - t.Run("no AS-2", func(t *testing.T) { - g := buildWithRealAS1(t, false, func(cfg *Config) { - cfg.IdentityBrokerGatewayServers = []string{gatewayTestServer} - cfg.MCPAuthority = nil - }) - if g.built.identityBrokerAS2 != nil { - t.Fatal("startup set up AS-2 without a protected route") - } - s, cred, _ := g.open(t) - _, err := g.built.IdentityBroker.AuthorizeCall(t.Context(), g.call(s, cred)) - wantBrokerError(t, err, identitybroker.CodeUnavailable, "") - if n := g.as1.Count(identityharness.KindIDJAG); n != 0 { - t.Fatalf("sent %d ID-JAG exchanges, want none", n) - } - }) t.Run("unbound at shutdown", func(t *testing.T) { - g := buildWithRealAS1(t, true, func(cfg *Config) { cfg.IdentityBrokerGatewayServers = []string{gatewayTestServer} }) + g := buildWithRealAS1(t, true, embeddedEntry(gatewayTestServer), nil) s, cred, _ := g.open(t) if _, err := g.built.IdentityBroker.AuthorizeCall(t.Context(), g.call(s, cred)); err != nil { t.Fatalf("AuthorizeCall before shutdown: %v", err) @@ -237,7 +232,7 @@ func TestBuildIdentityBrokerUnboundGatewayIsUnavailable(t *testing.T) { // that serves AS-2: the call held at its ID-JAG exchange while Close runs // still gets its gateway token. func TestBuildCloseFinishesACallInFlightBeforeTheMCPBroker(t *testing.T) { - g := buildWithRealAS1(t, true, func(cfg *Config) { cfg.IdentityBrokerGatewayServers = []string{gatewayTestServer} }) + g := buildWithRealAS1(t, true, embeddedEntry(gatewayTestServer), nil) s, cred, _ := g.open(t) entered, proceed := make(chan struct{}), make(chan struct{}) // A failed assertion still lets the call in flight finish. @@ -310,20 +305,35 @@ func TestBuildCloseFinishesACallInFlightBeforeTheMCPBroker(t *testing.T) { } } -// TestBuildConfiguresNoGatewayInProduction shows that without the test-only -// gateway servers, which production never sets, the identity broker has no -// gateway even with AS-2 set up: a session holding a grant is denied without -// an ID-JAG request. +// TestBuildConfiguresNoGatewayInProduction shows the configurations +// production can start with, an embedded gateway entry routing no servers or +// no entry, give the identity broker no gateway: a session holding a grant is +// denied without an ID-JAG request. The entry still sets AS-2 up, with the +// operator's signing key; without one there is no AS-2, as with the identity +// broker off. func TestBuildConfiguresNoGatewayInProduction(t *testing.T) { - g := buildWithRealAS1(t, false, nil) - if g.built.identityBrokerAS2 == nil { - t.Fatal("startup set up no AS-2") - } - s, cred, _ := g.open(t) - _, err := g.built.IdentityBroker.AuthorizeCall(t.Context(), g.call(s, cred)) - wantBrokerError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied) - if n := g.as1.Count(identityharness.KindIDJAG); n != 0 { - t.Fatalf("sent %d ID-JAG exchanges, want none", n) + for name, tc := range map[string]struct { + gateways []identitybroker.GatewayEntry + as2 bool + }{ + "an entry routing no servers": {embeddedEntry(), true}, + "no entry": {nil, false}, + } { + t.Run(name, func(t *testing.T) { + g := buildWithRealAS1(t, false, tc.gateways, nil) + if got := g.built.identityBrokerAS2 != nil; got != tc.as2 { + t.Fatalf("startup set up AS-2: %v, want %v", got, tc.as2) + } + if g.built.mcpBrokerGatewayServers != nil { + t.Fatalf("gateway servers = %v, want none", g.built.mcpBrokerGatewayServers) + } + s, cred, _ := g.open(t) + _, err := g.built.IdentityBroker.AuthorizeCall(t.Context(), g.call(s, cred)) + wantBrokerError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied) + if n := g.as1.Count(identityharness.KindIDJAG); n != 0 { + t.Fatalf("sent %d ID-JAG exchanges, want none", n) + } + }) } } @@ -337,8 +347,7 @@ func TestBuildConfiguresNoGatewayInProduction(t *testing.T) { // TestIdentityBrokerSessionToolCallThroughGateway. func TestIdentityBrokerTokensStayOutOfSessionsAndLogs(t *testing.T) { diag := &recordingDiag{} - g := buildWithRealAS1(t, true, func(cfg *Config) { - cfg.IdentityBrokerGatewayServers = []string{gatewayTestServer} + g := buildWithRealAS1(t, true, embeddedEntry(gatewayTestServer), func(cfg *Config) { cfg.Diagnostics = diag cfg.UseMock, cfg.MockProvider = false, mockllm.New(mockllm.TextTurn("done")) }) @@ -468,13 +477,13 @@ func TestIdentityBrokerTokensStayOutOfSessionsAndLogs(t *testing.T) { // gateway entry routes, and only with the identity broker on. func TestBuildInstallsGatewayCallsOnlyWithGatewayServers(t *testing.T) { t.Run("with gateway servers", func(t *testing.T) { - g := buildWithRealAS1(t, true, func(cfg *Config) { cfg.IdentityBrokerGatewayServers = []string{gatewayTestServer} }) + g := buildWithRealAS1(t, true, embeddedEntry(gatewayTestServer), nil) if got := g.built.mcpBrokerGatewayServers; !slices.Equal(got, []string{gatewayTestServer}) { t.Fatalf("gateway servers = %v, want [%s]", got, gatewayTestServer) } }) t.Run("without gateway servers", func(t *testing.T) { - g := buildWithRealAS1(t, true, nil) + g := buildWithRealAS1(t, true, embeddedEntry(), nil) if g.built.identityBrokerAS2 == nil { t.Fatal("startup set up no AS-2") } @@ -485,7 +494,7 @@ func TestBuildInstallsGatewayCallsOnlyWithGatewayServers(t *testing.T) { t.Run("without the identity broker", func(t *testing.T) { built, err := buildIsolated(t, t.Context(), Config{ Workspace: t.TempDir(), UseMock: true, NoSoul: true, NoShell: true, - MCPAuthority: protectedBrokerAuthority(), IdentityBrokerGatewayServers: []string{gatewayTestServer}, + MCPAuthority: protectedBrokerAuthority(), }) if err != nil { t.Fatal(err) @@ -529,33 +538,36 @@ func TestGatewayInProcessClientRefusesOtherURLs(t *testing.T) { } // TestHostedAS1IssuesTheGatewaysIDJAGs builds the production path, the -// identity broker beside a hosted AS-1, with the test-only gateway servers -// and a protected route: the hosted AS-1 issues a call's ID-JAG for the AS-2 -// the MCP broker set up, naming the agent in act with the broker's trust -// domain, and checks the agent's credential with the broker's verifier, which -// startup bound. AS-2 then refuses the ID-JAG: its test trust would have to -// list Alice's AS-1 subject, which the hosted AS-1 assigns only at a sign-in -// after the build, so it trusts no issuer, and the test reads the ID-JAG from -// the redemption. +// identity broker beside a hosted AS-1, with a gateway entry routing a +// protected route: the hosted AS-1 issues a call's ID-JAG for the entry's +// AS-2, naming the agent in act with the broker's trust domain, and checks +// the agent's credential with the broker's verifier, which startup bound. +// AS-2 then refuses the ID-JAG: its test trust would have to list Alice's +// AS-1 subject, which the hosted AS-1 assigns only at a sign-in after the +// build, so it trusts another issuer, and the test reads the ID-JAG from the +// redemption. func TestHostedAS1IssuesTheGatewaysIDJAGs(t *testing.T) { - hb := buildWithHostedAS1(t, []string{gatewayTestServer}) + hb := buildWithHostedAS1(t, embeddedEntry(gatewayTestServer)) // The hosted AS-1 issues ID-JAGs, and startup bound its actor-token check. wantBindRefused(t, hb.built, "already bound") g := hb.signIn(t) s, cred, _ := g.open(t) _, err := g.built.IdentityBroker.AuthorizeCall(t.Context(), g.call(s, cred)) - // An AS-2 trusting no issuer answers invalid_request, which the broker - // reports as a fault without a retry. - wantBrokerError(t, err, identitybroker.CodeInternal, "") + // An AS-2 trusting another issuer answers invalid_grant without a reason + // (the #2533 shortcut on Config.IdentityBrokerAS2Trust), which the broker + // retries once with a new ID-JAG before failing the call. + if err == nil { + t.Fatal("AS-2 redeemed an ID-JAG from an issuer it does not trust") + } jags := g.built.identityBrokerRecorder.IDJAGs() redeemed := hb.as2.Requests() - if len(jags) != 1 || len(redeemed) != 1 { - t.Fatalf("%d ID-JAG records and %d redemptions, want 1 of each", len(jags), len(redeemed)) + if len(jags) == 0 || len(redeemed) != len(jags) { + t.Fatalf("%d ID-JAG records and %d redemptions, want one redemption per ID-JAG", len(jags), len(redeemed)) } issuer := hb.issuer for i, r := range redeemed { - if r.Kind != identityharness.KindRedemption || r.Code != "invalid_request" || r.IssuedToken != "" { - t.Fatalf("redemption %d = %s answered %q, want an invalid_request refusal", i, r.Kind, r.Code) + if r.Kind != identityharness.KindRedemption || r.Code != "invalid_grant" || r.IssuedToken != "" { + t.Fatalf("redemption %d = %s answered %q, want an invalid_grant refusal", i, r.Kind, r.Code) } var header struct{ Typ string } if err := json.Unmarshal([]byte(jwtSegmentText(t, r.Assertion, 0)), &header); err != nil || header.Typ != "oauth-id-jag+jwt" { @@ -587,8 +599,11 @@ type hostedBuild struct { } // buildWithHostedAS1 builds the production path, the identity broker beside -// a hosted AS-1, with a protected calendar route and gatewayServers. -func buildWithHostedAS1(t *testing.T, gatewayServers []string) *hostedBuild { +// a hosted AS-1, with a protected calendar route and gateways, the broker's +// gateway entries. With an entry, the embedded gateway has a signing key; +// with one routing servers, AS-2 trusts an issuer other than AS-1, which an +// entry routing servers requires and which refuses AS-1's ID-JAGs. +func buildWithHostedAS1(t *testing.T, gateways []identitybroker.GatewayEntry) *hostedBuild { t.Helper() h := identityharness.New(t, identityharness.Options{}) // The issuer names the listener the hosted AS-1 is served on once built. @@ -600,20 +615,31 @@ func buildWithHostedAS1(t *testing.T, gatewayServers []string) *hostedBuild { hb := &hostedBuild{h: h, issuer: "https://" + ln.Addr().String() + "/as1"} hb.cfg = Config{ UseMock: true, NoSoul: true, NoShell: true, - IdentityBroker: true, IdentityBrokerConfigFile: testHostedAS1BrokerConfigFile(t), IdentityBrokerHostedAS1: hostedAS1Config(t, h, hb.issuer), - MCPAuthority: protectedBrokerAuthority(), IdentityBrokerGatewayServers: gatewayServers, + IdentityBroker: true, + IdentityBrokerConfigFile: brokerconfigtest.Write(t, brokerconfigtest.Options{HostedAS1: true, Gateways: gateways}).Path, + IdentityBrokerHostedAS1: hostedAS1Config(t, h, hb.issuer), + MCPAuthority: protectedBrokerAuthority(), identityBrokerAS2Transport: func(next http.RoundTripper) http.RoundTripper { hb.as2 = identityharness.NewFaultTransport(next, as2TestIssuer+"/oauth/token") return hb.as2 }, } + if len(gateways) != 0 { + hb.cfg.MCPAuthority = protectedBrokerAuthorityWithKey(t) + if len(gateways[0].Servers) != 0 { + hb.cfg.IdentityBrokerAS2Trust = mcpbrokertest.TrustAS1(mcpbrokertest.AS1Trust{ + Issuer: "https://untrusted-as1.mecatl.test", JWKSURL: "https://untrusted-as1.mecatl.test/jwks", + CAFile: h.WriteCACert(t, t.TempDir()), Subjects: []string{"nobody"}, + }) + } + } hb.built, err = buildIsolated(t, t.Context(), hb.cfg) if err != nil { t.Fatal(err) } t.Cleanup(hb.built.Close) - if hb.as2 == nil { - t.Fatal("startup set up no AS-2") + if (hb.as2 != nil) != (len(gateways) != 0) { + t.Fatalf("startup set up AS-2: %v, want it exactly with a gateway entry", hb.as2 != nil) } ts := &httptest.Server{Listener: ln, Config: &http.Server{Handler: hb.built.IdentityBrokerHostedAS1.Handler, ReadHeaderTimeout: 10 * time.Second}} ts.StartTLS() @@ -632,55 +658,102 @@ func (hb *hostedBuild) signIn(t *testing.T) *gatewayBuild { return &gatewayBuild{h: hb.h, built: hb.built, access: access} } -// TestHostedAS1IssuesNoIDJAGsInProduction builds the hosted AS-1 path -// without the test-only gateway servers, as production does: startup derives -// no ID-JAG target, the hosted AS-1 has no ID-JAG issuance (it refuses a -// verifier because no delegate client issues ID-JAGs, where one with issuance -// refuses only a second bind), and a call in a session holding a grant is -// denied without an ID-JAG or a redemption. +// TestHostedAS1IssuesNoIDJAGsInProduction builds the hosted AS-1 path as +// production can, with an embedded gateway entry routing no servers or with +// no entry: the hosted AS-1 has no ID-JAG issuance (it refuses a verifier +// because no delegate client issues ID-JAGs, where one with issuance refuses +// only a second bind), and a call in a session holding a grant is denied +// without an ID-JAG or a redemption. func TestHostedAS1IssuesNoIDJAGsInProduction(t *testing.T) { - hb := buildWithHostedAS1(t, nil) - declaration, selected := hb.cfg.MCPAuthority.Broker() - if target := deriveGatewayIDJAGTarget(hb.cfg, declaration, selected); target != nil { - t.Fatalf("production derives ID-JAG target %+v, want none", target) + for name, gateways := range map[string][]identitybroker.GatewayEntry{ + "an entry routing no servers": embeddedEntry(), + "no entry": nil, + } { + t.Run(name, func(t *testing.T) { + hb := buildWithHostedAS1(t, gateways) + wantBindRefused(t, hb.built, "no delegate client issues ID-JAGs") + g := hb.signIn(t) + s, cred, _ := g.open(t) + _, err := g.built.IdentityBroker.AuthorizeCall(t.Context(), g.call(s, cred)) + wantBrokerError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied) + if jags := g.built.identityBrokerRecorder.IDJAGs(); len(jags) != 0 { + t.Fatalf("ID-JAG records = %+v, want none", jags) + } + }) } - wantBindRefused(t, hb.built, "no delegate client issues ID-JAGs") - g := hb.signIn(t) - s, cred, _ := g.open(t) - _, err := g.built.IdentityBroker.AuthorizeCall(t.Context(), g.call(s, cred)) - wantBrokerError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied) - if jags := g.built.identityBrokerRecorder.IDJAGs(); len(jags) != 0 { - t.Fatalf("ID-JAG records = %+v, want none", jags) +} + +// TestHostedAS1IssuesIDJAGsOnlyForTheGatewayEntry asks the hosted AS-1, as +// the broker client, for ID-JAGs for an audience or resource the gateway +// entry does not name: AS-1 refuses each with invalid_target, and issues one +// for the entry's. +func TestHostedAS1IssuesIDJAGsOnlyForTheGatewayEntry(t *testing.T) { + hb := buildWithHostedAS1(t, embeddedEntry(gatewayTestServer)) + _, cred, _ := hb.signIn(t).open(t) + // A grant of Alice's own, from another sign-in, for the same agent. + access := hb.signIn(t).access + client, err := authserverclient.New(authserverclient.Config{ + Issuer: hb.issuer, TokenEndpoint: hb.built.identityBrokerHostedAS1Server.TokenEndpoint(), + Assertions: hb.built.identityBrokerClient, HTTPClient: hb.built.IdentityBrokerHostedAS1.HTTPClient, + }) + if err != nil { + t.Fatal(err) + } + grant, err := client.Exchange(t.Context(), identitybroker.TokenExchange{SubjectToken: access, Grant: identitybroker.ExchangeGrant{ + Type: identitybroker.ExchangeGrantType, IssuableTokenTypes: []string{identitybroker.TokenTypeIDJAG}, + }}) + if err != nil { + t.Fatalf("Exchange: %v", err) + } + issue := func(audience, resource string) error { + _, err := client.IssueIDJAG(t.Context(), identitybroker.IDJAGRequest{ + SubjectToken: grant.RefreshToken, ActorToken: cred, Audience: audience, Resource: resource, OperationID: "op-target", + }) + return err + } + for name, target := range map[string][2]string{ + "another audience": {"https://other.example/v1/mcp/broker", as2TestIssuer + "/mcp"}, + "another resource": {as2TestIssuer, as2TestIssuer + "/other-mcp"}, + } { + var refusal *identitybroker.ServerRefusal + if err := issue(target[0], target[1]); !errors.As(err, &refusal) || refusal.Code != "invalid_target" { + t.Errorf("%s: IssueIDJAG = %v, want invalid_target", name, err) + } + } + if err := issue(as2TestIssuer, as2TestIssuer+"/mcp"); err != nil { + t.Fatalf("IssueIDJAG for the entry's AS-2 and resource: %v", err) } } -// TestDeriveGatewayIDJAGTarget derives the AS-2 a hosted AS-1 issues the -// gateway's ID-JAGs for only with the test-only gateway servers and a bundled -// broker whose callback URL AS-2 can be set up for. -func TestDeriveGatewayIDJAGTarget(t *testing.T) { +// TestDeriveEmbeddedGateway derives the embedded gateway an embedded gateway +// entry must describe only for a bundled broker with an OAuth route and a +// callback URL AS-2 can be set up for. +func TestDeriveEmbeddedGateway(t *testing.T) { protected, _ := protectedBrokerAuthority().Broker() - gateway := []string{gatewayTestServer} - want := &gatewayIDJAGTarget{Issuer: as2TestIssuer, Resource: as2TestIssuer + "/mcp"} - if got := deriveGatewayIDJAGTarget(Config{IdentityBrokerGatewayServers: gateway}, protected, true); !reflect.DeepEqual(got, want) { - t.Fatalf("target = %+v, want %+v", got, want) + protected.Routes = append(protected.Routes, permconfig.MCPServerProfile{Name: "docs", URL: "https://docs.example/mcp", Auth: permconfig.MCPAuthProfile{Mode: "none"}}) + want := &embeddedGateway{Issuer: as2TestIssuer, TokenEndpoint: as2TestIssuer + "/oauth/token", Resource: as2TestIssuer + "/mcp", Routes: []string{"calendar"}} + if got := deriveEmbeddedGateway(Config{}, protected, true); !reflect.DeepEqual(got, want) { + t.Fatalf("embedded gateway = %+v, want %+v", got, want) } httpCallback := protected httpCallback.CallbackURL = "http://broker.example/oauth/callback" - configured := Config{IdentityBrokerGatewayServers: gateway} + anonymousOnly := protected + anonymousOnly.Routes = protected.Routes[1:] + configured := Config{} configured.MCPBrokerCaller = unusedBrokerCaller for name, tc := range map[string]struct { cfg Config declaration mcpauthority.BrokerConfig selected bool }{ - "no gateway servers": {Config{}, protected, true}, - "no broker": {Config{IdentityBrokerGatewayServers: gateway}, protected, false}, - "no routes": {Config{IdentityBrokerGatewayServers: gateway}, mcpauthority.BrokerConfig{CallbackURL: brokerTestCallbackURL}, true}, + "global authority": {Config{}, protected, false}, + "no routes": {Config{}, mcpauthority.BrokerConfig{CallbackURL: brokerTestCallbackURL}, true}, + "no OAuth route": {Config{}, anonymousOnly, true}, "configured broker": {configured, protected, true}, - "non-HTTPS callback": {Config{IdentityBrokerGatewayServers: gateway}, httpCallback, true}, + "non-HTTPS callback": {Config{}, httpCallback, true}, } { - if got := deriveGatewayIDJAGTarget(tc.cfg, tc.declaration, tc.selected); got != nil { - t.Errorf("%s: target = %+v, want none", name, got) + if got := deriveEmbeddedGateway(tc.cfg, tc.declaration, tc.selected); got != nil { + t.Errorf("%s: embedded gateway = %+v, want none", name, got) } } } @@ -744,31 +817,34 @@ func TestBuildFailsWhenAS1sActorTokenCheckCannotBind(t *testing.T) { }) } -// TestBuildMCPBrokerRefusesAS2OtherThanTheIDJAGTarget shows the bundled MCP -// broker refuses to start when the AS-2 it set up is not the one AS-1 issues -// the gateway's ID-JAGs for. -func TestBuildMCPBrokerRefusesAS2OtherThanTheIDJAGTarget(t *testing.T) { +// TestBuildMCPBrokerRefusesAS2OtherThanTheEntry shows the bundled MCP broker +// refuses to start when the AS-2 it set up is not the one the identity +// broker's gateway entry names, the check after startup's own. +func TestBuildMCPBrokerRefusesAS2OtherThanTheEntry(t *testing.T) { keySet := brokerconfigtest.WriteKeySet(t, filepath.Join(t.TempDir(), "jwks.json"), newBrokerClientKey(t)) - declaration, _ := protectedBrokerAuthority().Broker() - for name, target := range map[string]gatewayIDJAGTarget{ - "another issuer": {Issuer: "https://other.example/v1/mcp/broker", Resource: as2TestIssuer + "/mcp"}, - "another resource": {Issuer: as2TestIssuer, Resource: "https://other.example/mcp"}, + declaration, _ := protectedBrokerAuthorityWithKey(t).Broker() + for name, edit := range map[string]func(*identitybroker.GatewayEntry){ + "another issuer": func(e *identitybroker.GatewayEntry) { e.AS2Issuer = "https://other.example/v1/mcp/broker" }, + "another token endpoint": func(e *identitybroker.GatewayEntry) { e.TokenEndpoint = as2TestIssuer + "/token" }, + "another resource": func(e *identitybroker.GatewayEntry) { e.Resource = "https://other.example/mcp" }, } { t.Run(name, func(t *testing.T) { - parts, err := buildMCPBroker(t.Context(), Config{}, declaration, nil, mcpBrokerIdentity{clientKeySetFile: keySet, idjagTarget: &target}) + entry := embeddedEntry()[0] + edit(&entry) + parts, err := buildMCPBroker(t.Context(), Config{}, declaration, nil, mcpBrokerIdentity{clientKeySetFile: keySet, entry: &entry}) if err == nil { parts.close() - t.Fatal("buildMCPBroker set up an AS-2 AS-1 issues no ID-JAGs for") + t.Fatal("buildMCPBroker set up an AS-2 the gateway entry does not name") } - if !errors.Is(err, errAS2IsNotIDJAGTarget) { - t.Fatalf("buildMCPBroker error = %v, want %v", err, errAS2IsNotIDJAGTarget) + if !errors.Is(err, errAS2IsNotTheEntry) { + t.Fatalf("buildMCPBroker error = %v, want %v", err, errAS2IsNotTheEntry) } }) } - want := gatewayIDJAGTarget{Issuer: as2TestIssuer, Resource: as2TestIssuer + "/mcp"} - parts, err := buildMCPBroker(t.Context(), Config{}, declaration, nil, mcpBrokerIdentity{clientKeySetFile: keySet, idjagTarget: &want}) + entry := embeddedEntry()[0] + parts, err := buildMCPBroker(t.Context(), Config{}, declaration, nil, mcpBrokerIdentity{clientKeySetFile: keySet, entry: &entry}) if err != nil { - t.Fatalf("buildMCPBroker with the matching target: %v", err) + t.Fatalf("buildMCPBroker with the matching entry: %v", err) } parts.close() } diff --git a/internal/app/identitybroker_test.go b/internal/app/identitybroker_test.go index d491edd9f6..e5e14bb585 100644 --- a/internal/app/identitybroker_test.go +++ b/internal/app/identitybroker_test.go @@ -60,7 +60,7 @@ func (c *closableCore) FindSession(ctx context.Context, workload identitybroker. func newClosableCore(t *testing.T) *closableCore { t.Helper() - broker, err := newIdentityBroker(t.Context(), Config{}, testBrokerFile(t, brokerconfigtest.Options{})) + broker, err := newIdentityBroker(t.Context(), Config{}, testBrokerFile(t, brokerconfigtest.Options{}), nil) if err != nil { t.Fatal(err) } @@ -322,7 +322,7 @@ func TestIdentityBrokerUsesTheOperatorKeysPerRole(t *testing.T) { if err != nil { t.Fatal(err) } - broker, err := newIdentityBroker(t.Context(), Config{}, file) + broker, err := newIdentityBroker(t.Context(), Config{}, file, nil) if err != nil { t.Fatal(err) } @@ -360,7 +360,7 @@ func TestIdentityBrokerUsesTheOperatorKeysPerRole(t *testing.T) { if want := kidOf(t, files.BrokerClientKey); len(keys) != 1 || keys[0].KeyID != want { t.Fatalf("broker client JWKS %+v; want the file's broker client key %q", keys, want) } - restarted, err := newIdentityBroker(t.Context(), Config{}, file) + restarted, err := newIdentityBroker(t.Context(), Config{}, file, nil) if err != nil { t.Fatal(err) } @@ -463,7 +463,7 @@ func TestIdentityBrokerRefusesAnAS1WithoutTheBrokerClientKey(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := newIdentityBroker(t.Context(), Config{IdentityBrokerAS1: unusedAS1("https://as1.example")}, file); !errors.Is(err, errNoBrokerClientKey) { + if _, err := newIdentityBroker(t.Context(), Config{IdentityBrokerAS1: unusedAS1("https://as1.example")}, file, nil); !errors.Is(err, errNoBrokerClientKey) { t.Fatalf("newIdentityBroker = %v, want %v", err, errNoBrokerClientKey) } } @@ -581,7 +581,7 @@ func TestIdentityBrokerWiringConvertsAtAS1(t *testing.T) { a := as1servertest.Start(t, identityharness.New(t, identityharness.Options{}), nil) broker, err := newIdentityBroker(t.Context(), Config{IdentityBrokerAS1: &IdentityBrokerAS1{ Issuer: a.Issuer(), TokenEndpoint: a.Server.TokenEndpoint(), HTTPClient: a.HTTPClient(), - }}, testBrokerFile(t, brokerconfigtest.Options{BrokerClientKey: a.Key})) + }}, testBrokerFile(t, brokerconfigtest.Options{BrokerClientKey: a.Key}), nil) if err != nil { t.Fatal(err) } @@ -740,28 +740,6 @@ func TestIdentityBrokerHostsAS1(t *testing.T) { } } -func TestSameIssuer(t *testing.T) { - const issuer = "https://broker.example/v1/mcp/broker" - for other, want := range map[string]bool{ - issuer: true, - "HTTPS://Broker.Example/v1/mcp/broker": true, - "https://broker.example:443/v1/mcp/broker": true, - "https://broker.example/v1/mcp/broker/": true, - "http://broker.example/v1/mcp/broker": false, - "https://broker.example:8443/v1/mcp/broker": false, - "https://other.example/v1/mcp/broker": false, - "https://broker.example/v1/mcp/BROKER": false, - "https://broker.example/as1": false, - } { - if got := sameIssuer(issuer, other); got != want { - t.Errorf("sameIssuer(%q, %q) = %v, want %v", issuer, other, got, want) - } - if got := sameIssuer(other, issuer); got != want { - t.Errorf("sameIssuer(%q, %q) = %v, want %v", other, issuer, got, want) - } - } -} - func TestIdentityBrokerAS1RequiresTheBroker(t *testing.T) { built, err := buildIsolated(t, t.Context(), Config{Workspace: t.TempDir(), UseMock: true, NoSoul: true, IdentityBrokerHostedAS1: &IdentityBrokerAS1Config{Issuer: "https://mecatl.test/as1"}}) if err == nil { @@ -851,7 +829,7 @@ func TestScheduledFireClosesItsBrokerSessionWhenTheRunEnds(t *testing.T) { if err != nil { t.Fatal(err) } - ib, err := newIdentityBroker(t.Context(), Config{}, testBrokerFile(t, brokerconfigtest.Options{})) + ib, err := newIdentityBroker(t.Context(), Config{}, testBrokerFile(t, brokerconfigtest.Options{}), nil) if err != nil { t.Fatal(err) } @@ -912,7 +890,7 @@ func TestIdentityBrokerLoadsTheOperatorsDefinitions(t *testing.T) { const secret = "sk-test-do-not-log" bad := write("broken.md", "---\nname: broken\n---\n"+secret+"\n") // no description diag := &captureDiag{} - ib, err := newIdentityBroker(t.Context(), Config{AgentsDirs: []string{dir}, Diagnostics: diag}, testBrokerFile(t, brokerconfigtest.Options{})) + ib, err := newIdentityBroker(t.Context(), Config{AgentsDirs: []string{dir}, Diagnostics: diag}, testBrokerFile(t, brokerconfigtest.Options{}), nil) if err != nil { t.Fatalf("newIdentityBroker: %v", err) } @@ -950,7 +928,7 @@ func TestIdentityBrokerLoadsTheOperatorsDefinitions(t *testing.T) { func TestIdentityBrokerMissingAgentsDirFailsStartup(t *testing.T) { missing := filepath.Join(t.TempDir(), "missing") - if _, err := newIdentityBroker(t.Context(), Config{AgentsDirs: []string{missing}}, testBrokerFile(t, brokerconfigtest.Options{})); err == nil || !strings.Contains(err.Error(), "load identity broker definitions") { + if _, err := newIdentityBroker(t.Context(), Config{AgentsDirs: []string{missing}}, testBrokerFile(t, brokerconfigtest.Options{}), nil); err == nil || !strings.Contains(err.Error(), "load identity broker definitions") { t.Fatalf("newIdentityBroker with a missing agents directory = %v, want a load failure", err) } llm := mockllm.New(mockllm.TextTurn("done")) @@ -990,7 +968,7 @@ func TestIdentityDefinitionRefsUnderAHarnessPolicy(t *testing.T) { // even when a test injects the broker core, so it never starts without them // (the server refuses an identity broker with none). func TestIdentityBrokerWithAnInjectedCoreSendsTheConfiguredDefinitions(t *testing.T) { - parts, err := buildIdentityBroker(t.Context(), Config{IdentityBroker: true, NoShell: true, identityBrokerCore: newClosableCore(t)}, nil) + parts, err := buildIdentityBroker(t.Context(), Config{IdentityBroker: true, NoShell: true, identityBrokerCore: newClosableCore(t)}, nil, as2SigningKey{}) if err != nil { t.Fatalf("buildIdentityBroker: %v", err) } diff --git a/internal/app/mcp_broker_construction.go b/internal/app/mcp_broker_construction.go index 502992bd8d..30f6c6414b 100644 --- a/internal/app/mcp_broker_construction.go +++ b/internal/app/mcp_broker_construction.go @@ -2,6 +2,7 @@ package app import ( "context" + "crypto" "encoding/json" "fmt" "net/http" @@ -72,38 +73,51 @@ type mcpBrokerParts struct { } // mcpBrokerIdentity is what the identity broker gives the MCP broker; the -// zero value is no identity broker. +// zero value is no identity broker, or one without an embedded gateway +// entry, and leaves the MCP broker as it is without the identity broker. type mcpBrokerIdentity struct { // clientKeySetFile is the path of the broker client's public JWK Set, the - // identity broker's operator file. With a protected route, the bundled - // process registers the broker client with it at its authorization - // server, which becomes AS-2. Empty sets up no AS-2. + // identity broker's operator file. The bundled process registers the + // broker client with it at its authorization server, which becomes AS-2. + // It is set only with entry. clientKeySetFile string - // as1Issuer is AS-1's issuer, which AS-2's must differ from; empty when - // the identity broker has no AS-1. - as1Issuer string + // entry is the identity broker's embedded gateway entry, which the AS-2 + // set up must be; nil sets up no AS-2. + entry *identitybroker.GatewayEntry // gatewayCalls is nil when the identity broker has no gateway path. gatewayCalls *mcpBrokerGatewayCalls - // idjagTarget is the AS-2 AS-1 issues the gateway's ID-JAGs for, which - // the AS-2 set up must be; nil when none was derived. - idjagTarget *gatewayIDJAGTarget } -// deriveGatewayIDJAGTarget is the AS-2 the bundled MCP broker will set up for -// declaration, derived before the identity broker is built so a hosted AS-1 -// can issue the gateway's ID-JAGs for it. It is nil without the test-only -// gateway servers, without a bundled broker with routes, or for a callback URL -// AS-2 cannot derive its issuer from, which the bundled broker refuses anyway -// when a route is protected. -func deriveGatewayIDJAGTarget(cfg Config, declaration mcpauthority.BrokerConfig, selected bool) *gatewayIDJAGTarget { - if cfg.IdentityBrokerGatewayServers == nil || !selected || cfg.selectsConfiguredMCPBroker() || len(declaration.Routes) == 0 { +// deriveEmbeddedGateway is the embedded gateway the bundled MCP broker will +// run for declaration, derived before the identity broker is built so its +// gateway entry can be checked against it: AS-2's endpoints for the callback +// URL and the OAuth routes. It is nil without the bundled broker, without an +// OAuth route, or for a callback URL AS-2 cannot derive its issuer from, +// which the bundled broker refuses anyway. +func deriveEmbeddedGateway(cfg Config, declaration mcpauthority.BrokerConfig, selected bool) *embeddedGateway { + if !selected || cfg.selectsConfiguredMCPBroker() { return nil } - issuer, resource, err := mcpbroker.AS2Endpoints(declaration.CallbackURL) + var routes []string + for _, route := range declaration.Routes { + if route.Auth.Mode == "oauth" { + routes = append(routes, route.Name) + } + } + if len(routes) == 0 { + return nil + } + issuer, tokenEndpoint, resource, err := mcpbroker.AS2Endpoints(declaration.CallbackURL) if err != nil { return nil } - return &gatewayIDJAGTarget{Issuer: issuer, Resource: resource} + return &embeddedGateway{Issuer: issuer, TokenEndpoint: tokenEndpoint, Resource: resource, Routes: routes} +} + +// as2SigningPublicKeys reads the embedded gateway's signing key and its +// fallbacks as its authorization server does, and returns their public keys. +func as2SigningPublicKeys(key as2SigningKey) ([]crypto.PublicKey, error) { + return mcpbroker.SigningPublicKeys(key.file, key.fallbacks) } // mcpBrokerGatewayCalls is what the MCP broker needs to send gateway calls @@ -181,12 +195,15 @@ func buildBundledMCPBroker(ctx context.Context, cfg Config, declaration mcpautho return mcpBrokerParts{}, fmt.Errorf("build bundled MCP broker: %w", err) } config := toolHiveBrokerConfig(declaration.Routes, declaration.CallbackURL, occupied, authRedisClient, cfg.diag()) - if identity.clientKeySetFile != "" { + // Startup allows a signing key only with an embedded gateway entry + // (checkGatewayEntry). + config.SigningKeyFile, config.FallbackKeyFiles = declaration.SigningKeyFile, append([]string(nil), declaration.FallbackKeyFiles...) + if identity.entry != nil && identity.clientKeySetFile != "" { config.BrokerClient = &mcpbroker.ToolHiveBrokerClient{ID: identitybroker.BrokerClientID, KeySetFile: identity.clientKeySetFile} } config.AS2Trust = cfg.IdentityBrokerAS2Trust if calls := identity.gatewayCalls; calls != nil && config.BrokerClient != nil { - // Shortcut: only servers the identity broker's gateway entry routes use the gateway path, and production configures none until AS-2 trusts AS-1, so production is unchanged; removed by #2533 (production gateway) and #2538 (operator gateway entries). + // Shortcut: only servers the identity broker's gateway entry routes use the gateway path, and production's routes none until AS-2 trusts AS-1, so production is unchanged; removed by #2533. config.GatewayCalls = &mcpbroker.GatewayCalls{ Authorizer: calls.service, Credentials: calls.credentials, @@ -208,18 +225,16 @@ func buildBundledMCPBroker(ctx context.Context, cfg Config, declaration mcpautho if process.Gateway != nil { gatewayServers = config.GatewayCalls.Servers } + // Startup checked the entry against the AS-2 it derived; this checks the + // AS-2 the process set up is that one. + if entry := identity.entry; entry != nil && (process.AS2 == nil || process.AS2.Issuer != entry.AS2Issuer || + process.AS2.TokenEndpoint != entry.TokenEndpoint || process.AS2.Resource != entry.Resource) { + _ = process.Close() + authStorageClose() + return mcpBrokerParts{}, fmt.Errorf("build bundled MCP broker: %w", errAS2IsNotTheEntry) + } var as2 *identityBrokerAS2 if process.AS2 != nil { - if identity.as1Issuer != "" && sameIssuer(process.AS2.Issuer, identity.as1Issuer) { - _ = process.Close() - authStorageClose() - return mcpBrokerParts{}, fmt.Errorf("build bundled MCP broker: %w: %s", errAS2IssuerIsAS1s, identity.as1Issuer) - } - if target := identity.idjagTarget; target != nil && (process.AS2.Issuer != target.Issuer || process.AS2.Resource != target.Resource) { - _ = process.Close() - authStorageClose() - return mcpBrokerParts{}, fmt.Errorf("build bundled MCP broker: %w", errAS2IsNotIDJAGTarget) - } httpClient, err := as2InProcessClient(process.AS2) if err != nil { _ = process.Close() diff --git a/internal/app/mcp_broker_construction_test.go b/internal/app/mcp_broker_construction_test.go index a58e4deec4..861aceb474 100644 --- a/internal/app/mcp_broker_construction_test.go +++ b/internal/app/mcp_broker_construction_test.go @@ -6,10 +6,12 @@ import ( "crypto/elliptic" "crypto/rand" "encoding/json" - "errors" "net/http" + "net/http/httptest" "net/url" + "path/filepath" "reflect" + "slices" "strconv" "strings" "testing" @@ -23,6 +25,7 @@ import ( "github.com/stacklok/mecatl/internal/adapter/mcpbroker" "github.com/stacklok/mecatl/internal/adapter/permconfig" "github.com/stacklok/mecatl/internal/identitybroker" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/brokerconfig/brokerconfigtest" "github.com/stacklok/mecatl/internal/testutil/identityharness" ) @@ -129,6 +132,29 @@ func protectedBrokerAuthority() *mcpauthority.Result { return mcpauthority.NewBroker(mcpauthority.BrokerConfig{CallbackURL: brokerTestCallbackURL, Routes: []permconfig.MCPServerProfile{protectedToolHiveRoute("calendar")}}) } +// protectedBrokerAuthorityWithKey is protectedBrokerAuthority with a new +// signing key for the embedded gateway, which an embedded gateway entry +// requires. +func protectedBrokerAuthorityWithKey(t *testing.T) *mcpauthority.Result { + t.Helper() + declaration, _ := protectedBrokerAuthority().Broker() + declaration.SigningKeyFile = writeAS2Key(t, brokerconfigtest.NewKey(t)) + return mcpauthority.NewBroker(declaration) +} + +// writeAS2Key writes key as the embedded gateway's signing key and returns +// its path. +func writeAS2Key(t *testing.T, key *ecdsa.PrivateKey) string { + t.Helper() + return brokerconfigtest.WriteKey(t, filepath.Join(t.TempDir(), "as2.pem"), key) +} + +// embeddedEntry is the embedded gateway entry for protectedBrokerAuthority's +// embedded gateway, routing servers. +func embeddedEntry(servers ...string) []identitybroker.GatewayEntry { + return []identitybroker.GatewayEntry{brokerconfigtest.EmbeddedGateway(as2TestIssuer, servers...)} +} + // unusedAS1 points the identity broker's session open at an AS-1 startup // never calls. func unusedAS1(issuer string) *IdentityBrokerAS1 { @@ -144,21 +170,27 @@ func newBrokerClientKey(t *testing.T) *ecdsa.PrivateKey { return key } -// TestBuildRecordsAS2 sets AS-2 up with the identity broker on and a -// protected route, for each AS-1 the broker may have: startup records AS-2's -// issuer, token endpoint, resource, and an in-process client, and AS-2 knows -// the key the broker signs its client assertions with. +// TestBuildRecordsAS2 sets AS-2 up with the identity broker on, an embedded +// gateway entry routing no servers, and a protected route, for each AS-1 the +// broker may have: startup records AS-2's issuer, token endpoint, resource, +// and an in-process client, AS-2 knows the key the broker signs its client +// assertions with, and it publishes the operator's signing key. func TestBuildRecordsAS2(t *testing.T) { h := identityharness.New(t, identityharness.Options{}) for name, cfg := range map[string]Config{ "external AS-1": {IdentityBrokerAS1: unusedAS1("https://as1.example")}, "hosted AS-1": {IdentityBrokerHostedAS1: hostedAS1Config(t, h, "https://as1.mecatl.test/as1")}, - "no AS-1": {}, + // AS-1 on AS-2's host, under another path, has another issuer. + "hosted AS-1 on AS-2's host": {IdentityBrokerHostedAS1: hostedAS1Config(t, h, "https://broker.example/as1")}, + "no AS-1": {}, } { t.Run(name, func(t *testing.T) { cfg.UseMock, cfg.NoSoul = true, true - cfg.IdentityBroker, cfg.MCPAuthority = true, protectedBrokerAuthority() - cfg.IdentityBrokerConfigFile = testBrokerConfigFileFor(t, cfg) + as2Key := newBrokerClientKey(t) + declaration, _ := protectedBrokerAuthority().Broker() + declaration.SigningKeyFile = writeAS2Key(t, as2Key) + cfg.IdentityBroker, cfg.MCPAuthority = true, mcpauthority.NewBroker(declaration) + cfg.IdentityBrokerConfigFile = brokerconfigtest.Write(t, brokerconfigtest.Options{HostedAS1: cfg.IdentityBrokerHostedAS1 != nil, Gateways: embeddedEntry()}).Path built, err := buildIsolated(t, t.Context(), cfg) if err != nil { t.Fatal(err) @@ -221,10 +253,35 @@ func TestBuildRecordsAS2(t *testing.T) { if status, code := exchange(other); status != http.StatusUnauthorized || code != "invalid_client" { t.Fatalf("another key at AS-2: %d %q, want 401 invalid_client", status, code) } + if !as2PublishesKey(t, built, as2Key) { + t.Fatal("AS-2 does not publish the operator's signing key") + } }) } } +// as2PublishesKey reports whether built's embedded authorization server +// publishes key in its key set. +func as2PublishesKey(t *testing.T, built *Built, key *ecdsa.PrivateKey) bool { + t.Helper() + mux := http.NewServeMux() + if err := built.MountMCPBrokerHandlers(mux); err != nil { + t.Fatalf("MountMCPBrokerHandlers: %v", err) + } + recorder := httptest.NewRecorder() + mux.ServeHTTP(recorder, httptest.NewRequestWithContext(t.Context(), http.MethodGet, as2TestIssuer+"/.well-known/jwks.json", nil)) + var set identitybroker.JWKSet + if recorder.Code != http.StatusOK || json.Unmarshal(recorder.Body.Bytes(), &set) != nil { + t.Fatalf("AS-2 key set: status %d", recorder.Code) + } + signer, err := identitybroker.NewClientAssertionSigner(key, 0) + if err != nil { + t.Fatal(err) + } + want := signer.JWKS().Keys[0] + return slices.ContainsFunc(set.Keys, func(k identitybroker.JWK) bool { return k.X == want.X && k.Y == want.Y }) +} + // TestBuildMCPBrokerSetsNoAS2WithoutAKeySetFile pins that no broker client // key set file sets up no AS-2. func TestBuildMCPBrokerSetsNoAS2WithoutAKeySetFile(t *testing.T) { @@ -238,10 +295,13 @@ func TestBuildMCPBrokerSetsNoAS2WithoutAKeySetFile(t *testing.T) { } } +// TestBuildRecordsNoAS2: without an embedded gateway entry, the MCP broker +// sets no AS-2 up, as with the identity broker off. func TestBuildRecordsNoAS2(t *testing.T) { for name, cfg := range map[string]Config{ "identity broker off": {MCPAuthority: protectedBrokerAuthority()}, "injected core": {IdentityBroker: true, identityBrokerCore: newClosableCore(t), MCPAuthority: protectedBrokerAuthority()}, + "no gateway entry": {IdentityBroker: true, MCPAuthority: protectedBrokerAuthority()}, "no protected route": {IdentityBroker: true, MCPAuthority: mcpauthority.NewBroker(mcpauthority.BrokerConfig{CallbackURL: brokerTestCallbackURL})}, "identity broker alone": {IdentityBroker: true}, } { @@ -262,25 +322,27 @@ func TestBuildRecordsNoAS2(t *testing.T) { } } +// TestBuildRefusesAS2WithAS1sIssuer: the identity broker refuses a gateway +// entry whose AS-2 issuer is AS-1's. func TestBuildRefusesAS2WithAS1sIssuer(t *testing.T) { h := identityharness.New(t, identityharness.Options{}) for name, cfg := range map[string]Config{ "hosted AS-1": {IdentityBrokerHostedAS1: hostedAS1Config(t, h, as2TestIssuer)}, "external AS-1": {IdentityBrokerAS1: unusedAS1(as2TestIssuer)}, - // The same server spelled differently is still AS-2's issuer. + // The same issuer spelled differently is still AS-2's issuer. "external AS-1, other spelling": {IdentityBrokerAS1: unusedAS1("HTTPS://Broker.Example:443/v1/mcp/broker/")}, } { t.Run(name, func(t *testing.T) { cfg.UseMock, cfg.NoSoul = true, true - cfg.IdentityBroker, cfg.MCPAuthority = true, protectedBrokerAuthority() - cfg.IdentityBrokerConfigFile = testBrokerConfigFileFor(t, cfg) + cfg.IdentityBroker, cfg.MCPAuthority = true, protectedBrokerAuthorityWithKey(t) + cfg.IdentityBrokerConfigFile = brokerconfigtest.Write(t, brokerconfigtest.Options{HostedAS1: cfg.IdentityBrokerHostedAS1 != nil, Gateways: embeddedEntry()}).Path built, err := buildIsolated(t, t.Context(), cfg) if err == nil { built.Close() t.Fatal("Build gave AS-2 AS-1's issuer") } - if !errors.Is(err, errAS2IssuerIsAS1s) { - t.Fatalf("Build error = %v, want %v", err, errAS2IssuerIsAS1s) + if !strings.Contains(err.Error(), "gateways[0].as2_issuer") || !strings.Contains(err.Error(), "names AS-1's issuer") { + t.Fatalf("Build error = %v, want the entry's AS-2 issuer refused as AS-1's", err) } }) } diff --git a/internal/cliconfig/mcp_authority.go b/internal/cliconfig/mcp_authority.go index e9a1cb769d..a88f4b87bf 100644 --- a/internal/cliconfig/mcp_authority.go +++ b/internal/cliconfig/mcp_authority.go @@ -52,6 +52,9 @@ func resolveGlobalAuthority(opts MCPAuthorityOptions) (*mcpauthority.Result, err if opts.Operator != nil && opts.Operator.Broker.CallbackURL != "" { return nil, fmt.Errorf("%w: mcp.broker.callback_url is inert in global mode", ErrMCPProfileInvalid) } + if opts.Operator != nil && opts.Operator.Broker.SigningKeyFile != "" { + return nil, fmt.Errorf("%w: mcp.broker.signing_key_file is inert in global mode", ErrMCPProfileInvalid) + } if opts.Operator != nil { for _, route := range opts.Operator.Servers { if route.Auth.OAuth == nil { @@ -149,8 +152,13 @@ func resolveBrokerAuthority(section *permconfig.MCPSection) (*mcpauthority.Resul } } else if callback != "" { return nil, fmt.Errorf("%w: mcp.broker.callback_url requires a broker OAuth server", ErrMCPProfileInvalid) + } else if section.Broker.SigningKeyFile != "" { + return nil, fmt.Errorf("%w: mcp.broker.signing_key_file requires a broker OAuth server, whose embedded authorization server signs with it", ErrMCPProfileInvalid) } - return mcpauthority.NewBroker(mcpauthority.BrokerConfig{Routes: section.Servers, CallbackURL: callback}), nil + return mcpauthority.NewBroker(mcpauthority.BrokerConfig{ + Routes: section.Servers, CallbackURL: callback, + SigningKeyFile: section.Broker.SigningKeyFile, FallbackKeyFiles: section.Broker.FallbackKeyFiles, + }), nil } func validateBrokerOAuth(route permconfig.MCPServerProfile) error { diff --git a/internal/cliconfig/mcp_authority_test.go b/internal/cliconfig/mcp_authority_test.go index 5b31690cb4..10648efce1 100644 --- a/internal/cliconfig/mcp_authority_test.go +++ b/internal/cliconfig/mcp_authority_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "path/filepath" + "reflect" "strings" "testing" @@ -231,6 +232,27 @@ func TestMCPAuthorityBrokerCallbackRules(t *testing.T) { } } +// TestMCPAuthorityBrokerSigningKeyRules carries the embedded authorization +// server's signing key into the broker declaration, and refuses it where no +// embedded authorization server runs. +func TestMCPAuthorityBrokerSigningKeyRules(t *testing.T) { + key := permconfig.MCPBrokerProfile{CallbackURL: "https://agent.example/callback", SigningKeyFile: "/keys/as2/key.pem", FallbackKeyFiles: []string{"/keys/as2-old/key.pem"}} + got, err := ResolveMCPAuthority(MCPAuthorityOptions{Operator: &permconfig.MCPSection{Mode: "broker", Broker: key, Servers: []permconfig.MCPServerProfile{brokerOAuthRoute()}}, DefaultMode: mcpauthority.Global, BrokerSupported: true}) + if err != nil { + t.Fatalf("broker with a signing key: %v", err) + } + if broker, ok := got.Broker(); !ok || broker.SigningKeyFile != key.SigningKeyFile || !reflect.DeepEqual(broker.FallbackKeyFiles, key.FallbackKeyFiles) { + t.Fatalf("broker declaration = %#v, want the signing key paths", broker) + } + noOAuth := permconfig.MCPBrokerProfile{SigningKeyFile: key.SigningKeyFile} + if _, err := ResolveMCPAuthority(MCPAuthorityOptions{Operator: &permconfig.MCPSection{Mode: "broker", Broker: noOAuth}, DefaultMode: mcpauthority.Global, BrokerSupported: true}); !errors.Is(err, ErrMCPProfileInvalid) || !strings.Contains(err.Error(), "signing_key_file requires a broker OAuth server") { + t.Fatalf("signing key without an OAuth server error = %v", err) + } + if _, err := ResolveMCPAuthority(MCPAuthorityOptions{Operator: &permconfig.MCPSection{Mode: "global", Broker: noOAuth}, DefaultMode: mcpauthority.Global}); !errors.Is(err, ErrMCPProfileInvalid) || !strings.Contains(err.Error(), "signing_key_file is inert in global mode") { + t.Fatalf("global signing key error = %v", err) + } +} + func TestMCPAuthorityPreservesGlobalProfileResolution(t *testing.T) { oauth := environmentOAuth() oauth.Network.PrivateOrigins = []string{"https://issuer.example"} diff --git a/internal/configgen/configgen_test.go b/internal/configgen/configgen_test.go index 5bc5a4b199..ad911c4d60 100644 --- a/internal/configgen/configgen_test.go +++ b/internal/configgen/configgen_test.go @@ -246,6 +246,8 @@ func TestMCPArtifactsShowStrictUnionWithoutSecretValues(t *testing.T) { for _, want := range []string{ "`mcp.mode`", "`mcp.broker.callback_url`", + "`mcp.broker.signing_key_file`", + "`mcp.broker.fallback_key_files`", "`mcp.servers[].auth.mode`", "`mcp.servers[].auth.oauth.upstream.mode`", "`mcp.servers[].auth.oauth.upstream.oauth2.authorization_endpoint`", diff --git a/internal/configgen/settings.skeleton.yaml b/internal/configgen/settings.skeleton.yaml index c1ef2ad39d..de056e9279 100644 --- a/internal/configgen/settings.skeleton.yaml +++ b/internal/configgen/settings.skeleton.yaml @@ -582,6 +582,17 @@ # # be an absolute HTTPS URL without userinfo, query, or fragment; an omitted path or # # / is normalized to /. # callback_url: "" +# # SigningKeyFile is the absolute path of the PEM private key (RSA, ECDSA, or +# # Ed25519; PKCS #1, SEC 1, or PKCS #8) the embedded MCP gateway's authorization +# # server signs its tokens with, so they survive a restart. mecak8s requires it with +# # the identity broker on and an embedded gateway entry in the identity broker's +# # configuration file, and refuses it otherwise; it must differ from every identity +# # broker key. It is read at startup, so a new key takes effect on restart. +# signing_key_file: "" +# # FallbackKeyFiles are absolute paths of earlier signing keys, PEM private keys like +# # SigningKeyFile: tokens they signed still verify while they are listed, so the key +# # can rotate. They require SigningKeyFile. +# fallback_key_files: [] # # Servers is the ordered list of neutral Streamable HTTP route declarations. # servers: [] #| diff --git a/internal/identitybroker/adapter/authserverclient/redeem_test.go b/internal/identitybroker/adapter/authserverclient/redeem_test.go index 23732b69ed..6ee35849ba 100644 --- a/internal/identitybroker/adapter/authserverclient/redeem_test.go +++ b/internal/identitybroker/adapter/authserverclient/redeem_test.go @@ -28,7 +28,7 @@ const grantJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" // embedded AS-2, set up to trust that AS-1 through mcpbrokertest. Not // parallel: StartAS2 sets an environment variable. func TestRedeemAtRealAS2(t *testing.T) { - as2Issuer, as2Resource, err := mcpbroker.AS2Endpoints(mcpbrokertest.CallbackURL) + as2Issuer, _, as2Resource, err := mcpbroker.AS2Endpoints(mcpbrokertest.CallbackURL) if err != nil { t.Fatal(err) } diff --git a/internal/identitybroker/adapter/brokerconfig/brokerconfig.go b/internal/identitybroker/adapter/brokerconfig/brokerconfig.go index 4c18465246..55be06a616 100644 --- a/internal/identitybroker/adapter/brokerconfig/brokerconfig.go +++ b/internal/identitybroker/adapter/brokerconfig/brokerconfig.go @@ -16,7 +16,14 @@ // "agent_issuer": {"key_file": "/keys/agent-issuer/key.pem", "fallback_key_files": ["/keys/agent-issuer-old/public.pem"]}, // "broker_client": {"key_file": "/keys/broker-client/key.pem", "key_set_file": "/keys/broker-client-jwks/jwks.json"}, // "as1_signing": {"key_file": "/keys/as1/key.pem", "fallback_key_files": ["/keys/as1-old/key.pem"]} -// } +// }, +// "gateways": [{ +// "kind": "embedded", +// "as2_issuer": "https://mecatl.example.com/v1/mcp/broker", +// "token_endpoint": "https://mecatl.example.com/v1/mcp/broker/oauth/token", +// "resource": "https://mecatl.example.com/v1/mcp/broker/mcp", +// "servers": ["calendar"] +// }] // } // // Every path is absolute. Key files are PEM private keys: PKCS #1, SEC 1, or @@ -29,6 +36,15 @@ // broker client rotates through its key set file instead, which holds the old // and new public keys. AS-1's signing key is configured only with a hosted // AS-1. +// +// Gateways are optional. Each entry names its gateway's kind, its +// authorization server's (AS-2's) issuer and advertised token endpoint, each +// an absolute https URL, the vMCP resource, and the servers it routes. The +// broker validates the entries (identitybroker.ValidateGatewayEntries) and +// refuses one whose AS-2 issuer names AS-1's issuer: the broker client +// authenticates to both with one key. An entry requires the broker client +// key. The process that runs the gateway checks that it agrees with the +// entry. package brokerconfig import ( @@ -40,8 +56,10 @@ import ( "errors" "fmt" "io" + "net/url" "os" "path/filepath" + "strings" "time" "github.com/stacklok/mecatl/internal/identitybroker" @@ -70,6 +88,9 @@ type File struct { // signing key. AS1SigningKeyFile string AS1FallbackKeyFiles []string + // Gateways are the file's gateway entries, validated with + // identitybroker.ValidateGatewayEntries: none, or one embedded entry. + Gateways []identitybroker.GatewayEntry } // document is the file's JSON form. @@ -84,6 +105,16 @@ type document struct { } `json:"broker_client"` AS1Signing signingKey `json:"as1_signing"` } `json:"keys"` + Gateways []gatewayEntry `json:"gateways"` +} + +// gatewayEntry is a gateway entry's JSON form. +type gatewayEntry struct { + Kind string `json:"kind"` + AS2Issuer string `json:"as2_issuer"` + TokenEndpoint string `json:"token_endpoint"` + Resource string `json:"resource"` + Servers []string `json:"servers"` } // signingKey names a signing key and its fallbacks. @@ -131,6 +162,8 @@ func load(raw []byte, host Host) (File, error) { case !host.AS1 && doc.Keys.AS1Signing.KeyFile != "": // Refused before the unused private key is read. return File{}, errors.New("keys.as1_signing requires a hosted AS-1, which this process does not run") + case len(doc.Gateways) != 0 && doc.Keys.BrokerClient.KeyFile == "": + return File{}, errors.New("gateways requires keys.broker_client, which the broker authenticates to each gateway's AS-2 with") } if err := identitybroker.ValidateTrustDomain(doc.TrustDomain); err != nil { return File{}, fmt.Errorf("trust_domain: %w", err) @@ -145,6 +178,9 @@ func load(raw []byte, host Host) (File, error) { if err := file.Config.Validate(); err != nil { return File{}, err } + if file.Gateways, err = gateways(doc.Gateways, host); err != nil { + return File{}, err + } if file.Keys, err = readKeys(doc); err != nil { return File{}, err } @@ -154,6 +190,76 @@ func load(raw []byte, host Host) (File, error) { return file, nil } +// gateways converts and validates the file's gateway entries for a broker +// beside host: the broker's rules, each URL an absolute https URL, and no +// AS-2 issuer naming AS-1's. +func gateways(raw []gatewayEntry, host Host) ([]identitybroker.GatewayEntry, error) { + entries := make([]identitybroker.GatewayEntry, len(raw)) + for i, e := range raw { + entries[i] = identitybroker.GatewayEntry{ + Kind: identitybroker.GatewayKind(e.Kind), AS2Issuer: e.AS2Issuer, TokenEndpoint: e.TokenEndpoint, + Resource: e.Resource, Servers: append([]string(nil), e.Servers...), + } + } + if len(entries) == 0 { + return nil, nil + } + if err := identitybroker.ValidateGatewayEntries(entries); err != nil { + return nil, fmt.Errorf("gateways: %w", err) + } + for i, e := range raw { + for _, f := range []struct{ name, value string }{{"as2_issuer", e.AS2Issuer}, {"token_endpoint", e.TokenEndpoint}, {"resource", e.Resource}} { + if !httpsURL(f.value) { + return nil, fmt.Errorf("gateways[%d].%s: %q must be an absolute https URL with a host and no credentials, query, or fragment", i, f.name, f.value) + } + } + if host.AS1Issuer != "" && sameIssuer(e.AS2Issuer, host.AS1Issuer) { + return nil, fmt.Errorf("gateways[%d].as2_issuer: %q names AS-1's issuer %q; the broker client authenticates to both with one key, so a client assertion or ID-JAG meant for one would be accepted by the other", i, e.AS2Issuer, host.AS1Issuer) + } + } + return entries, nil +} + +// httpsURL reports whether raw is an absolute https URL with a host and no +// credentials, query, or fragment. +func httpsURL(raw string) bool { + u, err := url.Parse(raw) + return err == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.Contains(raw, "#") +} + +// sameIssuer reports whether two issuer URLs name the same issuer: scheme +// and host compare case-insensitively, a default port equals none, and the +// paths compare equal ignoring a trailing slash. The same host under another +// path is another issuer. Unparseable URLs compare byte for byte. +func sameIssuer(a, b string) bool { + if a == b { + return true + } + ua, errA := url.Parse(a) + ub, errB := url.Parse(b) + if errA != nil || errB != nil { + return false + } + return strings.EqualFold(ua.Scheme, ub.Scheme) && + strings.EqualFold(ua.Hostname(), ub.Hostname()) && + effectivePort(ua) == effectivePort(ub) && + strings.TrimSuffix(ua.EscapedPath(), "/") == strings.TrimSuffix(ub.EscapedPath(), "/") +} + +// effectivePort is u's port, or its scheme's default when it names none. +func effectivePort(u *url.URL) string { + if p := u.Port(); p != "" { + return p + } + switch strings.ToLower(u.Scheme) { + case "https": + return "443" + case "http": + return "80" + } + return "" +} + // readKeys reads the keys doc names, which load has checked are named // together where they must be. func readKeys(doc document) (identitybroker.Keys, error) { diff --git a/internal/identitybroker/adapter/brokerconfig/brokerconfig_test.go b/internal/identitybroker/adapter/brokerconfig/brokerconfig_test.go index 96f74e53d0..bd4495995e 100644 --- a/internal/identitybroker/adapter/brokerconfig/brokerconfig_test.go +++ b/internal/identitybroker/adapter/brokerconfig/brokerconfig_test.go @@ -14,6 +14,7 @@ import ( "io/fs" "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -442,6 +443,123 @@ func TestLoadedBrokerClientKeyMatchesItsKeySet(t *testing.T) { } } +// testAS2Issuer is the gateway entries' AS-2 issuer; testAS1Issuer is AS-1's +// on the same host under another path. +const ( + testAS2Issuer = "https://mecatl.example.com/v1/mcp/broker" + testAS1Issuer = "https://mecatl.example.com/as1" +) + +func TestLoadReadsAGatewayEntry(t *testing.T) { + t.Parallel() + for name, entry := range map[string]identitybroker.GatewayEntry{ + "routing servers": brokerconfigtest.EmbeddedGateway(testAS2Issuer, "calendar", "github"), + "routing none": brokerconfigtest.EmbeddedGateway(testAS2Issuer), + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + files := brokerconfigtest.Write(t, brokerconfigtest.Options{HostedAS1: true, Gateways: []identitybroker.GatewayEntry{entry}}) + got, err := brokerconfig.Load(files.Path, brokerconfig.Host{AS1: true, AS1Issuer: testAS1Issuer}) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(got.Gateways) != 1 { + t.Fatalf("Gateways = %+v, want the entry", got.Gateways) + } + g := got.Gateways[0] + if g.Kind != entry.Kind || g.AS2Issuer != entry.AS2Issuer || g.TokenEndpoint != entry.TokenEndpoint || g.Resource != entry.Resource || !slices.Equal(g.Servers, entry.Servers) { + t.Errorf("Gateways[0] = %+v, want %+v", g, entry) + } + }) + } + files := brokerconfigtest.Write(t, brokerconfigtest.Options{HostedAS1: true}) + got, err := brokerconfig.Load(files.Path, brokerconfig.Host{AS1: true, AS1Issuer: testAS1Issuer}) + if err != nil || got.Gateways != nil { + t.Fatalf("Load without gateways = %+v, %v; want no entries", got.Gateways, err) + } +} + +func TestLoadRefusesAGatewayEntry(t *testing.T) { + t.Parallel() + entry := func(edit func(map[string]any)) []map[string]any { + e := map[string]any{ + "kind": "embedded", "as2_issuer": testAS2Issuer, "token_endpoint": testAS2Issuer + "/oauth/token", + "resource": testAS2Issuer + "/mcp", "servers": []string{"calendar"}, + } + if edit != nil { + edit(e) + } + return []map[string]any{e} + } + set := func(field string, value any) []map[string]any { + return entry(func(e map[string]any) { e[field] = value }) + } + tests := map[string]struct { + gateways any + as1Issuer string + want string + }{ + "two entries": {gateways: append(entry(nil), entry(nil)...), want: "only one gateway entry"}, + "an external entry": {gateways: set("kind", "external"), want: "external gateways are not supported yet (#2812)"}, + "an unknown kind": {gateways: set("kind", "remote"), want: `kind "remote"`}, + "no kind": {gateways: entry(func(e map[string]any) { delete(e, "kind") }), want: `kind ""`}, + "no AS-2 issuer": {gateways: entry(func(e map[string]any) { delete(e, "as2_issuer") }), want: "AS-2 issuer"}, + "a blank resource": {gateways: set("resource", " "), want: "resource"}, + "no token endpoint": {gateways: entry(func(e map[string]any) { delete(e, "token_endpoint") }), want: "token endpoint"}, + "a repeated server": {gateways: set("servers", []string{"calendar", "calendar"}), want: "listed twice"}, + "an empty server": {gateways: set("servers", []string{""}), want: "gateway server"}, + "an unknown field": {gateways: set("dial_address", "https://10.0.0.1"), want: `unknown field "dial_address"`}, + "a relative issuer": {gateways: set("as2_issuer", "/v1/mcp/broker"), want: "gateways[0].as2_issuer"}, + "an http issuer": {gateways: set("as2_issuer", "http://mecatl.example.com/v1/mcp/broker"), want: "gateways[0].as2_issuer"}, + "an http endpoint": {gateways: set("token_endpoint", "http://mecatl.example.com/v1/mcp/broker/oauth/token"), want: "gateways[0].token_endpoint"}, + "a hostless resource": {gateways: set("resource", "https:///mcp"), want: "gateways[0].resource"}, + "a query": {gateways: set("resource", testAS2Issuer+"/mcp?x=1"), want: "gateways[0].resource"}, + "a fragment": {gateways: set("as2_issuer", testAS2Issuer+"#x"), want: "gateways[0].as2_issuer"}, + "credentials": {gateways: set("token_endpoint", "https://u:p@mecatl.example.com/oauth/token"), want: "gateways[0].token_endpoint"}, + "AS-1's issuer": {gateways: entry(nil), as1Issuer: testAS2Issuer, want: "names AS-1's issuer"}, + "AS-1's issuer, slash": {gateways: entry(nil), as1Issuer: testAS2Issuer + "/", want: "names AS-1's issuer"}, + "AS-1's issuer, case": {gateways: entry(nil), as1Issuer: "HTTPS://MECATL.example.com/v1/mcp/broker", want: "names AS-1's issuer"}, + "AS-1's issuer, port": {gateways: entry(nil), as1Issuer: "https://mecatl.example.com:443/v1/mcp/broker", want: "names AS-1's issuer"}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + files := brokerconfigtest.Write(t, brokerconfigtest.Options{HostedAS1: true}) + doc := readDoc(t, files.Path) + doc["gateways"] = tc.gateways + writeJSON(t, files.Path, doc) + as1 := tc.as1Issuer + if as1 == "" { + as1 = testAS1Issuer + } + _, err := brokerconfig.Load(files.Path, brokerconfig.Host{AS1: true, AS1Issuer: as1}) + if err == nil || !strings.Contains(err.Error(), tc.want) || !strings.Contains(err.Error(), files.Path) { + t.Fatalf("Load = %v, want an error naming the file and containing %q", err, tc.want) + } + }) + } + // The same host under another path, or another port, is another issuer. + for _, as1 := range []string{testAS1Issuer, "https://mecatl.example.com", "https://mecatl.example.com:8443/v1/mcp/broker"} { + files := brokerconfigtest.Write(t, brokerconfigtest.Options{HostedAS1: true, Gateways: []identitybroker.GatewayEntry{brokerconfigtest.EmbeddedGateway(testAS2Issuer, "calendar")}}) + if _, err := brokerconfig.Load(files.Path, brokerconfig.Host{AS1: true, AS1Issuer: as1}); err != nil { + t.Errorf("Load beside AS-1 at %s = %v, want the entry accepted", as1, err) + } + } +} + +// TestLoadRefusesAGatewayEntryWithoutTheBrokerClientKey: the broker +// authenticates to AS-2 with the broker client key. +func TestLoadRefusesAGatewayEntryWithoutTheBrokerClientKey(t *testing.T) { + t.Parallel() + files := brokerconfigtest.Write(t, brokerconfigtest.Options{Gateways: []identitybroker.GatewayEntry{brokerconfigtest.EmbeddedGateway(testAS2Issuer)}}) + doc := readDoc(t, files.Path) + delete(keys(doc), "broker_client") + writeJSON(t, files.Path, doc) + if _, err := brokerconfig.Load(files.Path, brokerconfig.Host{}); err == nil || !strings.Contains(err.Error(), "gateways requires keys.broker_client") { + t.Fatalf("Load = %v, want the entry refused without the broker client key", err) + } +} + func keys(doc map[string]any) map[string]any { return doc["keys"].(map[string]any) } func keyFile(doc map[string]any, role string) string { diff --git a/internal/identitybroker/adapter/brokerconfig/brokerconfigtest/brokerconfigtest.go b/internal/identitybroker/adapter/brokerconfig/brokerconfigtest/brokerconfigtest.go index 9209e0f671..eb74e9fbdf 100644 --- a/internal/identitybroker/adapter/brokerconfig/brokerconfigtest/brokerconfigtest.go +++ b/internal/identitybroker/adapter/brokerconfig/brokerconfigtest/brokerconfigtest.go @@ -42,6 +42,18 @@ type Options struct { // AS1Fallbacks generates that many AS-1 fallback keys; it requires // HostedAS1. AS1Fallbacks int + // Gateways are the gateway entries to write, such as EmbeddedGateway's. + Gateways []identitybroker.GatewayEntry +} + +// EmbeddedGateway is the embedded gateway entry for AS-2 at as2Issuer, +// with the token endpoint and vMCP resource mecak8s's embedded gateway +// derives from it, routing servers. +func EmbeddedGateway(as2Issuer string, servers ...string) identitybroker.GatewayEntry { + return identitybroker.GatewayEntry{ + Kind: identitybroker.GatewayEmbedded, AS2Issuer: as2Issuer, TokenEndpoint: as2Issuer + "/oauth/token", + Resource: as2Issuer + "/mcp", Servers: servers, + } } // Files are a written configuration file and its keys. @@ -101,6 +113,16 @@ func Write(t testing.TB, opts Options) Files { keys["as1_signing"] = signingKey{KeyFile: files.AS1SigningKeyFile, FallbackKeyFiles: files.AS1FallbackKeyFiles} } doc := map[string]any{"trust_domain": trustDomain, "audience": Audience, "keys": keys} + if opts.Gateways != nil { + entries := make([]map[string]any, len(opts.Gateways)) + for i, e := range opts.Gateways { + entries[i] = map[string]any{ + "kind": e.Kind, "as2_issuer": e.AS2Issuer, "token_endpoint": e.TokenEndpoint, + "resource": e.Resource, "servers": e.Servers, + } + } + doc["gateways"] = entries + } writeJSON(t, files.Path, doc) return files } diff --git a/internal/identitybroker/adapter/brokerconfig/sameissuer_test.go b/internal/identitybroker/adapter/brokerconfig/sameissuer_test.go new file mode 100644 index 0000000000..d75dad6da1 --- /dev/null +++ b/internal/identitybroker/adapter/brokerconfig/sameissuer_test.go @@ -0,0 +1,34 @@ +package brokerconfig + +import "testing" + +// TestSameIssuer compares issuers including their path: the same host under +// another path is another issuer. +func TestSameIssuer(t *testing.T) { + t.Parallel() + const issuer = "https://broker.example/v1/mcp/broker" + for other, want := range map[string]bool{ + issuer: true, + "HTTPS://Broker.Example/v1/mcp/broker": true, + "https://broker.example:443/v1/mcp/broker": true, + "https://broker.example/v1/mcp/broker/": true, + "http://broker.example/v1/mcp/broker": false, + "https://broker.example:8443/v1/mcp/broker": false, + "https://other.example/v1/mcp/broker": false, + "https://broker.example/v1/mcp/BROKER": false, + "https://broker.example/as1": false, + "https://broker.example": false, + "https://broker.example/v1/mcp": false, + } { + if got := sameIssuer(issuer, other); got != want { + t.Errorf("sameIssuer(%q, %q) = %v, want %v", issuer, other, got, want) + } + if got := sameIssuer(other, issuer); got != want { + t.Errorf("sameIssuer(%q, %q) = %v, want %v", other, issuer, got, want) + } + } + // A host-only issuer equals itself with a trailing slash. + if !sameIssuer("https://as1.example", "https://AS1.example:443/") { + t.Error("a host-only issuer differs from itself with a slash") + } +} diff --git a/internal/identitybroker/authorize.go b/internal/identitybroker/authorize.go index 8242a589ef..c2e417a688 100644 --- a/internal/identitybroker/authorize.go +++ b/internal/identitybroker/authorize.go @@ -47,13 +47,12 @@ func (b *Broker) AuthorizeCall(ctx context.Context, workload Workload, req Autho // Shortcut: step (6) checks 4 and 5 (run and owner) and 7 (ceiling) accept their inputs; removed by #2557 (checks 4 and 5) and the authority work (docs/drafts/agent-identity/README.md, "Order of work") for check 7. - // Check 6: the gateway routes the server. - // Shortcut: check 6 matches the call's server, not the tool's route; removed by #2538 (gateway entries carry their routed tools, or the design moves the tool check to the vMCP). + // Check 6: a configured gateway routes the server. if !b.gateway.routes(req.Server) { return Authorization{}, b.refuse(ctx, rec, ReasonError(ReasonDenied, "no gateway routes the server")) } - // AS-2 may not be bound yet (the #2560 shortcut on BindGatewayAS2). + // AS-2 may not be bound yet (the #2559 shortcut on BindGatewayAS2). as2, release, ok := b.acquireAS2() if !ok { return Authorization{}, b.refuse(ctx, rec, NewError(CodeUnavailable, "", "the gateway's authorization server is not bound yet")) diff --git a/internal/identitybroker/authorize_checks_test.go b/internal/identitybroker/authorize_checks_test.go index e82534a543..5096473436 100644 --- a/internal/identitybroker/authorize_checks_test.go +++ b/internal/identitybroker/authorize_checks_test.go @@ -73,21 +73,38 @@ func TestNewRefusesAnInvalidGateway(t *testing.T) { identitybroker.WithRecorder(identitybroker.NewMemoryRecorder()), identitybroker.WithIDJAGIssuer(&fakeIssuer{}), } as2 := identitybroker.GatewayAS2{Issuer: "https://as2.example.com", Resource: "https://vmcp.example.com/mcp", AuthServer: &fakeAS2{}} + entry := func(servers ...string) identitybroker.Gateway { + return identitybroker.Gateway{Issuer: as2.Issuer, Resource: as2.Resource, Servers: servers} + } + withAS2 := func(a identitybroker.GatewayAS2) identitybroker.Gateway { + g := entry("github") + g.AS2 = a + return g + } for name, g := range map[string]identitybroker.Gateway{ - "no servers": {}, - "an empty server": {Servers: []string{""}}, - "a spaced server": {Servers: []string{"git hub"}}, - "a repeat": {Servers: []string{"github", "calendar", "github"}}, - "an AS-2 issuer only": {Servers: []string{"github"}, AS2: identitybroker.GatewayAS2{Issuer: as2.Issuer}}, - "an AS-2 without a port": {Servers: []string{"github"}, AS2: identitybroker.GatewayAS2{Issuer: as2.Issuer, Resource: as2.Resource}}, - "a spaced AS-2 resource": {Servers: []string{"github"}, AS2: identitybroker.GatewayAS2{Issuer: as2.Issuer, Resource: "a b", AuthServer: as2.AuthServer}}, + "no issuer": {Resource: as2.Resource, Servers: []string{"github"}}, + "no resource": {Issuer: as2.Issuer, Servers: []string{"github"}}, + "a spaced issuer": {Issuer: "as 2", Resource: as2.Resource, Servers: []string{"github"}}, + "no servers": entry(), + "an empty server": entry(""), + "a spaced server": entry("git hub"), + "a repeat": entry("github", "calendar", "github"), + "an AS-2 issuer only": withAS2(identitybroker.GatewayAS2{Issuer: as2.Issuer}), + "an AS-2 without a port": withAS2(identitybroker.GatewayAS2{Issuer: as2.Issuer, Resource: as2.Resource}), + "a spaced AS-2 resource": withAS2(identitybroker.GatewayAS2{Issuer: as2.Issuer, Resource: "a b", AuthServer: as2.AuthServer}), + "another AS-2's issuer": withAS2(identitybroker.GatewayAS2{Issuer: "https://other.example.com", Resource: as2.Resource, AuthServer: as2.AuthServer}), + "another AS-2's resource": withAS2(identitybroker.GatewayAS2{Issuer: as2.Issuer, Resource: "https://other.example.com/mcp", AuthServer: as2.AuthServer}), + "the issuer and resource swapped": withAS2(identitybroker.GatewayAS2{Issuer: as2.Resource, Resource: as2.Issuer, AuthServer: as2.AuthServer}), } { _, err := identitybroker.New(config, nil, key, append(collaborators, identitybroker.WithGateway(g))...) if !errors.Is(err, identitybroker.ErrInvalidConfig) { t.Errorf("New with %s = %v, want ErrInvalidConfig", name, err) } } - gateway := identitybroker.WithGateway(identitybroker.Gateway{Servers: []string{"github"}}) + if _, err := identitybroker.New(config, nil, key, append(collaborators, identitybroker.WithGateway(withAS2(as2)))...); err != nil { + t.Errorf("New with the entry's AS-2 = %v", err) + } + gateway := identitybroker.WithGateway(entry("github")) for name, opts := range map[string][]identitybroker.Option{ "no recorder": {identitybroker.WithIDJAGIssuer(&fakeIssuer{}), gateway}, "no ID-JAG issuer": {identitybroker.WithRecorder(identitybroker.NewMemoryRecorder()), gateway}, @@ -101,7 +118,7 @@ func TestNewRefusesAnInvalidGateway(t *testing.T) { } _, err = identitybroker.New(config, nil, key, identitybroker.WithRecorder(identitybroker.NewMemoryRecorder()), identitybroker.WithIDJAGIssuer(&fakeIssuer{}), - gateway, identitybroker.WithGateway(identitybroker.Gateway{Servers: []string{"calendar"}})) + gateway, identitybroker.WithGateway(entry("calendar"))) if !errors.Is(err, identitybroker.ErrInvalidConfig) { t.Errorf("New with two gateways = %v, want ErrInvalidConfig", err) } diff --git a/internal/identitybroker/authorize_integration_test.go b/internal/identitybroker/authorize_integration_test.go index 4fe87daa82..61ed38442b 100644 --- a/internal/identitybroker/authorize_integration_test.go +++ b/internal/identitybroker/authorize_integration_test.go @@ -86,7 +86,7 @@ type harnessOptions struct { func newHarnessFixtureWith(t *testing.T, opts harnessOptions) *harnessFixture { t.Helper() // AS-1 is configured with the AS-2 StartAS2 sets up, before either runs. - as2Issuer, as2Resource, err := mcpbroker.AS2Endpoints(mcpbrokertest.CallbackURL) + as2Issuer, _, as2Resource, err := mcpbroker.AS2Endpoints(mcpbrokertest.CallbackURL) if err != nil { t.Fatal(err) } @@ -149,6 +149,7 @@ func newHarnessFixtureWith(t *testing.T, opts harnessOptions) *harnessFixture { identitybroker.WithIDJAGIssuer(as1), identitybroker.WithRecorder(rec), identitybroker.WithGateway(identitybroker.Gateway{ + Issuer: as2.Issuer, Resource: as2.Resource, Servers: []string{"github"}, AS2: identitybroker.GatewayAS2{Issuer: as2.Issuer, Resource: as2.Resource, AuthServer: as2Client}, })) diff --git a/internal/identitybroker/authorize_test.go b/internal/identitybroker/authorize_test.go index fd2abb3f04..a59abfe7ce 100644 --- a/internal/identitybroker/authorize_test.go +++ b/internal/identitybroker/authorize_test.go @@ -147,9 +147,11 @@ func (f *fakeAS2) tokens() []identitybroker.Token { return append([]identitybroker.Token(nil), f.issued...) } -// withGateway configures g with a recorder and an ID-JAG issuer, which a -// gateway requires; later options may replace them. +// withGateway configures g, as the entry of the test AS-2, with a recorder +// and an ID-JAG issuer, which a gateway requires; later options may replace +// them. func withGateway(g identitybroker.Gateway) identitybroker.Option { + g.Issuer, g.Resource = as2Issuer, as2Resource opts := []identitybroker.Option{ identitybroker.WithRecorder(identitybroker.NewMemoryRecorder()), identitybroker.WithIDJAGIssuer(&fakeIssuer{}), @@ -178,7 +180,7 @@ func newPerCall(t *testing.T, opts ...identitybroker.Option) perCallFixture { opts = append([]identitybroker.Option{ identitybroker.WithRecorder(rec), identitybroker.WithIDJAGIssuer(issuer), - identitybroker.WithGateway(identitybroker.Gateway{Servers: []string{"github", "calendar"}}), + identitybroker.WithGateway(identitybroker.Gateway{Issuer: as2Issuer, Resource: as2Resource, Servers: []string{"github", "calendar"}}), }, opts...) f := openGranted(t, opts...) unbind, err := f.b.BindGatewayAS2(boundAS2(as2)) @@ -211,7 +213,7 @@ func TestBindGatewayAS2(t *testing.T) { f := openGranted(t, identitybroker.WithRecorder(identitybroker.NewMemoryRecorder()), identitybroker.WithIDJAGIssuer(issuer), - identitybroker.WithGateway(identitybroker.Gateway{Servers: []string{"github"}})) + identitybroker.WithGateway(identitybroker.Gateway{Issuer: as2Issuer, Resource: as2Resource, Servers: []string{"github"}})) _, err := f.authorize(callRequest(f.s.ID, f.cred)) wantError(t, err, identitybroker.CodeUnavailable, "", f.cred) @@ -225,6 +227,9 @@ func TestBindGatewayAS2(t *testing.T) { "no resource": {Issuer: as2Issuer, AuthServer: as2}, "no port": {Issuer: as2Issuer, Resource: as2Resource}, "spaced issuer": {Issuer: "as 2", Resource: as2Resource, AuthServer: as2}, + // The gateway's entry names AS-2's issuer and resource. + "another issuer": {Issuer: "https://other.example.com", Resource: as2Resource, AuthServer: as2}, + "another resource": {Issuer: as2Issuer, Resource: "https://other.example.com/mcp", AuthServer: as2}, } { if _, err := f.b.BindGatewayAS2(bad); !errors.Is(err, identitybroker.ErrInvalidConfig) { t.Errorf("BindGatewayAS2 with %s = %v, want ErrInvalidConfig", name, err) @@ -268,7 +273,7 @@ func TestBindGatewayAS2(t *testing.T) { g := openGranted(t, identitybroker.WithRecorder(identitybroker.NewMemoryRecorder()), identitybroker.WithIDJAGIssuer(&fakeIssuer{}), - identitybroker.WithGateway(identitybroker.Gateway{Servers: []string{"github"}, AS2: boundAS2(&fakeAS2{})})) + identitybroker.WithGateway(identitybroker.Gateway{Issuer: as2Issuer, Resource: as2Resource, Servers: []string{"github"}, AS2: boundAS2(&fakeAS2{})})) if _, err := g.authorize(callRequest(g.s.ID, g.cred)); err != nil { t.Fatalf("AuthorizeCall with AS-2 configured at New: %v", err) } diff --git a/internal/identitybroker/broker.go b/internal/identitybroker/broker.go index f7f1a48f67..ada6bcffe4 100644 --- a/internal/identitybroker/broker.go +++ b/internal/identitybroker/broker.go @@ -67,7 +67,7 @@ type Broker struct { as1 AuthServer // gateway is the gateway calls are authorized through; nil when none is // configured, and every call is denied at the server check. There is at - // most one until #2538 (see WithGateway). + // most one until #2812 (see WithGateway). gateway *Gateway // gateways counts WithGateway options, so New refuses a second. gateways int diff --git a/internal/identitybroker/gateway.go b/internal/identitybroker/gateway.go index 663ffdafb6..b0105018ab 100644 --- a/internal/identitybroker/gateway.go +++ b/internal/identitybroker/gateway.go @@ -70,8 +70,12 @@ type GatewayTokenResult struct { ExpiresIn time.Duration } -// Gateway is the MCP gateway the broker authorizes calls through. +// Gateway is the MCP gateway the broker authorizes calls through, built from +// its gateway entry. type Gateway struct { + // Issuer and Resource are the AS-2 issuer and vMCP resource the gateway's + // entry names. The AS-2 bound for the gateway must name both. + Issuer, Resource string // Servers are the backend names the gateway routes. A call naming any // other server is denied. Servers []string @@ -80,6 +84,67 @@ type Gateway struct { AS2 GatewayAS2 } +// GatewayKind is a gateway entry's kind. +type GatewayKind string + +// The gateway kinds an entry may name. +const ( + // GatewayEmbedded is the gateway the process serving the broker's caller + // runs: mecak8s's embedded vMCP, whose authorization server is AS-2. + GatewayEmbedded GatewayKind = "embedded" + // GatewayExternal is a gateway run elsewhere, with its own AS-2. + GatewayExternal GatewayKind = "external" +) + +// GatewayEntry is a gateway the operator declares in the broker's +// configuration. Its AS-2 issuer and resource are the target AS-1 issues the +// gateway's ID-JAGs for, and its servers are the ones check 6 lets calls +// reach through it. +type GatewayEntry struct { + Kind GatewayKind + // AS2Issuer is the gateway's authorization server's issuer, an ID-JAG's + // audience. + AS2Issuer string + // TokenEndpoint is AS-2's token endpoint as AS-2 advertises it, never a + // dial address. + TokenEndpoint string + // Resource is the gateway's vMCP resource, an ID-JAG's resource. + Resource string + // Servers are the backend names the gateway routes. An entry may route + // none, which configures no gateway. + Servers []string +} + +// ValidateGatewayEntries checks entries as the broker accepts them: at most +// one entry, of kind GatewayEmbedded; its issuer, token endpoint, and +// resource non-empty printable text without spaces; and its servers the same, +// each listed once. The loader checks the URLs. Errors wrap ErrInvalidConfig. +// +// Shortcut: at most one gateway entry, of kind embedded; removed by #2812 (external gateways, and several gateways). +func ValidateGatewayEntries(entries []GatewayEntry) error { + if len(entries) > 1 { + return fmt.Errorf("%w: only one gateway entry can be configured", ErrInvalidConfig) + } + for i, e := range entries { + switch e.Kind { + case GatewayEmbedded: + case GatewayExternal: + return fmt.Errorf("%w: gateway entry %d: external gateways are not supported yet (#2812)", ErrInvalidConfig, i) + default: + return fmt.Errorf("%w: gateway entry %d: kind %q must be %q or %q", ErrInvalidConfig, i, e.Kind, GatewayEmbedded, GatewayExternal) + } + for _, f := range []struct{ name, value string }{{"AS-2 issuer", e.AS2Issuer}, {"token endpoint", e.TokenEndpoint}, {"resource", e.Resource}} { + if !isToken(f.value) { + return fmt.Errorf("%w: gateway entry %d: the %s must be non-empty printable text without spaces", ErrInvalidConfig, i, f.name) + } + } + if err := validateServers(e.Servers); err != nil { + return fmt.Errorf("%w: gateway entry %d: %v", ErrInvalidConfig, i, err) + } + } + return nil +} + // GatewayAS2 is the gateway's authorization server, AS-2, as the broker uses // it: the audience of the ID-JAGs it requests, the vMCP resource, and the // port that redeems ID-JAGs there. @@ -110,12 +175,13 @@ func (a GatewayAS2) validate() error { // WithGateway has AuthorizeCall authorize calls through g. Without it every // call that reaches the server check is denied. New refuses a second -// WithGateway, a gateway with no servers, with a server name that is not -// printable text without spaces or that appears twice, or with a partly set -// AS2, and a gateway without WithRecorder and WithIDJAGIssuer. New binds a -// non-zero AS2. +// WithGateway, a gateway without an issuer or resource, with no servers, with +// a server name that is not printable text without spaces or that appears +// twice, or with a partly set AS2 or one naming another issuer or resource, +// and a gateway without WithRecorder and WithIDJAGIssuer. New binds a non-zero +// AS2. // -// Shortcut: one gateway, the embedded one; removed by #2538 (operator-declared gateway entries, each with its own AS-2). +// Shortcut: one gateway; removed by #2812 (several gateways, each with its own AS-2). func WithGateway(g Gateway) Option { return func(b *Broker) { // Each broker gets its own copy: New clears the copy's AS2 once bound. @@ -136,19 +202,19 @@ func WithIDJAGIssuer(as1 IDJAGIssuer) Option { // needs to redeem ID-JAGs; until it is bound, a call that passes the checks // before a grant fails with CodeUnavailable. It returns an error wrapping // ErrInvalidConfig when no gateway is configured, AS-2 is already bound, or -// as2 is incomplete. +// as2 is incomplete or names another issuer or resource than the gateway's. // // The returned unbind is idempotent and leaves a later binding alone. It // returns once the calls using this binding have finished; calls after it // starts find AS-2 unbound. It must not be called from as2's AuthServer or // the broker's IDJAGIssuer, as it would wait for its own call. // -// Shortcut: AS-2 bound late, leaving an UNAVAILABLE window; removed by #2560 (AS-2 reached over the network as a configured gateway entry). +// Shortcut: AS-2 bound late, leaving an UNAVAILABLE window; removed by #2559 (AS-2 reached over the network as a configured gateway entry). func (b *Broker) BindGatewayAS2(as2 GatewayAS2) (unbind func(), err error) { if b.gateway == nil { return nil, fmt.Errorf("%w: no gateway is configured", ErrInvalidConfig) } - if err := as2.validate(); err != nil { + if err := b.gateway.checkAS2(as2); err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidConfig, err) } bound := &as2Binding{as2: as2} @@ -210,7 +276,7 @@ func (b *Broker) configureGateway() error { return errors.New("a gateway requires a recorder and an ID-JAG issuer") } if !g.AS2.isZero() { - if err := g.AS2.validate(); err != nil { + if err := g.checkAS2(g.AS2); err != nil { return err } b.as2.Store(&as2Binding{as2: g.AS2}) @@ -220,11 +286,33 @@ func (b *Broker) configureGateway() error { } func (g *Gateway) validate() error { - if len(g.Servers) == 0 { + switch { + case !isToken(g.Issuer): + return errors.New("the gateway's AS-2 issuer must be non-empty printable text without spaces") + case !isToken(g.Resource): + return errors.New("the gateway's resource must be non-empty printable text without spaces") + case len(g.Servers) == 0: return errors.New("the gateway routes no servers") } - seen := make(map[string]bool, len(g.Servers)) - for _, s := range g.Servers { + return validateServers(g.Servers) +} + +// checkAS2 checks that as2 is complete and is the AS-2 of g's entry. +func (g *Gateway) checkAS2(as2 GatewayAS2) error { + if err := as2.validate(); err != nil { + return err + } + if as2.Issuer != g.Issuer || as2.Resource != g.Resource { + return fmt.Errorf("the AS-2 at %q for %q is not the gateway's, at %q for %q", as2.Issuer, as2.Resource, g.Issuer, g.Resource) + } + return nil +} + +// validateServers refuses a server name that is not printable text without +// spaces or that appears twice. +func validateServers(servers []string) error { + seen := make(map[string]bool, len(servers)) + for _, s := range servers { if !isToken(s) { return fmt.Errorf("gateway server %q must be non-empty printable text without spaces", s) } diff --git a/internal/identitybroker/gateway_test.go b/internal/identitybroker/gateway_test.go new file mode 100644 index 0000000000..4684b8e6b8 --- /dev/null +++ b/internal/identitybroker/gateway_test.go @@ -0,0 +1,52 @@ +package identitybroker_test + +import ( + "errors" + "strings" + "testing" + + "github.com/stacklok/mecatl/internal/identitybroker" +) + +func TestValidateGatewayEntries(t *testing.T) { + embedded := func(edit func(*identitybroker.GatewayEntry)) identitybroker.GatewayEntry { + e := identitybroker.GatewayEntry{ + Kind: identitybroker.GatewayEmbedded, AS2Issuer: as2Issuer, TokenEndpoint: as2Issuer + "/oauth/token", + Resource: as2Resource, Servers: []string{"calendar", "github"}, + } + if edit != nil { + edit(&e) + } + return e + } + for name, entries := range map[string][]identitybroker.GatewayEntry{ + "none": nil, + "an embedded one": {embedded(nil)}, + "one routing none": {embedded(func(e *identitybroker.GatewayEntry) { e.Servers = nil })}, + } { + if err := identitybroker.ValidateGatewayEntries(entries); err != nil { + t.Errorf("%s: ValidateGatewayEntries = %v", name, err) + } + } + for name, tc := range map[string]struct { + entries []identitybroker.GatewayEntry + want string + }{ + "two entries": {[]identitybroker.GatewayEntry{embedded(nil), embedded(nil)}, "only one gateway entry"}, + "an external one": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.Kind = identitybroker.GatewayExternal })}, "external gateways are not supported yet (#2812)"}, + "an unknown kind": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.Kind = "remote" })}, `kind "remote"`}, + "no kind": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.Kind = "" })}, `kind ""`}, + "no issuer": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.AS2Issuer = "" })}, "AS-2 issuer"}, + "a spaced issuer": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.AS2Issuer = "https://as 2" })}, "AS-2 issuer"}, + "no token endpoint": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.TokenEndpoint = "" })}, "token endpoint"}, + "no resource": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.Resource = "" })}, "resource"}, + "a control character": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.Resource = as2Resource + "\x00" })}, "resource"}, + "an empty server": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.Servers = []string{""} })}, "gateway server"}, + "a repeated server": {[]identitybroker.GatewayEntry{embedded(func(e *identitybroker.GatewayEntry) { e.Servers = []string{"github", "github"} })}, "listed twice"}, + } { + err := identitybroker.ValidateGatewayEntries(tc.entries) + if !errors.Is(err, identitybroker.ErrInvalidConfig) || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: ValidateGatewayEntries = %v, want ErrInvalidConfig naming %q", name, err, tc.want) + } + } +} diff --git a/internal/identitybroker/keys.go b/internal/identitybroker/keys.go index 4ad7f3c0d2..ede8ccba08 100644 --- a/internal/identitybroker/keys.go +++ b/internal/identitybroker/keys.go @@ -43,6 +43,9 @@ type Host struct { // client key and AS-1's signing key; only a hosted AS-1 takes AS-1's // signing key. AS1 bool + // AS1Issuer is the issuer of the AS-1 the broker uses, hosted or not; + // empty without one. No gateway entry's AS-2 issuer may name it. + AS1Issuer string } // Validate checks k for a broker beside host. It refuses a missing required @@ -57,8 +60,7 @@ func (k Keys) Validate(host Host) error { if k.AgentIssuer == nil { return fmt.Errorf("%w: the agent issuer key is required", ErrInvalidConfig) } - _, issuerPub, err := checkSigner(k.AgentIssuer) - if err != nil { + if _, _, err := checkSigner(k.AgentIssuer); err != nil { return fmt.Errorf("%w: the agent issuer key: %v", ErrInvalidSigner, err) } switch { @@ -71,17 +73,11 @@ func (k Keys) Validate(host Host) error { case (k.BrokerClient == nil) != (len(k.BrokerClientKeySet) == 0): return fmt.Errorf("%w: the broker client key and the broker client's key set are required together", ErrInvalidConfig) } - type roleKey struct { - role string - pub crypto.PublicKey - } - keys := []roleKey{{"agent issuer", issuerPub}} for i, pub := range k.AgentIssuerFallbacks { // New refuses the same keys; checking here refuses them at load. if _, err := copyP256Public(pub); err != nil { return fmt.Errorf("%w: agent issuer fallback key %d: %v", ErrInvalidSigner, i, err) } - keys = append(keys, roleKey{"agent issuer", pub}) } if k.BrokerClient != nil { _, clientPub, err := checkSigner(k.BrokerClient) @@ -92,19 +88,11 @@ func (k Keys) Validate(host Host) error { if err != nil { return fmt.Errorf("%w: the broker client key: %v", ErrInvalidSigner, err) } - // AS-1 and AS-2 accept assertions signed by any key in the set, so - // each is a broker client key; the set holds clientPub. - set, err := checkClientKeySet(k.BrokerClientKeySet, jwk) - if err != nil { + if err := checkClientKeySet(k.BrokerClientKeySet, jwk); err != nil { return fmt.Errorf("%w: %v", ErrInvalidConfig, err) } - for _, pub := range set { - keys = append(keys, roleKey{"broker client", pub}) - } - } - for _, pub := range k.AS1Signing { - keys = append(keys, roleKey{"AS-1 signing", pub}) } + keys := k.roleKeys() for i, a := range keys { eq, ok := a.pub.(interface{ Equal(crypto.PublicKey) bool }) if !ok { @@ -117,34 +105,79 @@ func (k Keys) Validate(host Host) error { return nil } +// PublicKeys returns the public keys of every role in k: the agent issuer +// key and its fallbacks, the broker client's key set's ECDSA P-256 keys, +// which include the broker client key's, and AS-1's signing keys. A process +// holding a key for another role, such as the embedded gateway's signing key, +// refuses one of these. +func (k Keys) PublicKeys() []crypto.PublicKey { + keys := k.roleKeys() + pubs := make([]crypto.PublicKey, len(keys)) + for i, key := range keys { + pubs[i] = key.pub + } + return pubs +} + +// roleKey is a public key and the role it serves. +type roleKey struct { + role string + pub crypto.PublicKey +} + +// roleKeys returns k's public keys by role, as PublicKeys describes them. +// AS-1 and AS-2 accept assertions signed by any key in the broker client's +// key set, so each is a broker client key. +func (k Keys) roleKeys() []roleKey { + var keys []roleKey + if k.AgentIssuer != nil { + keys = append(keys, roleKey{"agent issuer", k.AgentIssuer.Public()}) + } + for _, pub := range k.AgentIssuerFallbacks { + keys = append(keys, roleKey{"agent issuer", pub}) + } + var set JWKSet + if json.Unmarshal(k.BrokerClientKeySet, &set) == nil { + for _, key := range set.Keys { + if pub, ok := p256JWKKey(key); ok { + keys = append(keys, roleKey{"broker client", pub}) + } + } + } + for _, pub := range k.AS1Signing { + keys = append(keys, roleKey{"AS-1 signing", pub}) + } + return keys +} + // checkClientKeySet checks that raw, the broker client's JWK Set, holds at -// least one key and client under client's kid, and returns the set's ECDSA -// P-256 keys. -func checkClientKeySet(raw []byte, client JWK) ([]crypto.PublicKey, error) { +// least one key and client under client's kid. +func checkClientKeySet(raw []byte, client JWK) error { var set JWKSet if err := json.Unmarshal(raw, &set); err != nil { - return nil, errors.New("the broker client's key set is not a JSON JWK Set") + return errors.New("the broker client's key set is not a JSON JWK Set") } if len(set.Keys) == 0 { - return nil, errors.New("the broker client's key set holds no key") + return errors.New("the broker client's key set holds no key") } found := false - var keys []crypto.PublicKey for _, key := range set.Keys { + // The broker client signs only with P-256, so any other key in the + // set could only let a server accept another role's key as mecatl's. + if _, ok := p256JWKKey(key); !ok { + return fmt.Errorf("the broker client's key set holds a key that is not an ECDSA P-256 key (kid %q); the broker client signs only with P-256", key.KeyID) + } if key.KeyID == client.KeyID { if key.KeyType != client.KeyType || key.Curve != client.Curve || key.X != client.X || key.Y != client.Y { - return nil, fmt.Errorf("the broker client's key set holds another key under the broker client key's kid %q", client.KeyID) + return fmt.Errorf("the broker client's key set holds another key under the broker client key's kid %q", client.KeyID) } found = true } - if pub, ok := p256JWKKey(key); ok { - keys = append(keys, pub) - } } if !found { - return nil, fmt.Errorf("the broker client's key set does not hold the broker client key's public key under its kid %q (its RFC 7638 thumbprint)", client.KeyID) + return fmt.Errorf("the broker client's key set does not hold the broker client key's public key under its kid %q (its RFC 7638 thumbprint)", client.KeyID) } - return keys, nil + return nil } // p256JWKKey is jwk's public key when jwk is a valid ECDSA P-256 key. diff --git a/internal/identitybroker/keys_test.go b/internal/identitybroker/keys_test.go index e1d9c8962c..4bebbbb20d 100644 --- a/internal/identitybroker/keys_test.go +++ b/internal/identitybroker/keys_test.go @@ -22,6 +22,17 @@ func keySetOf(t *testing.T, jwks ...JWK) []byte { return raw } +// keySetWithRaw is the JSON JWK Set of jwk followed by raw, a JWK that the +// JWK type cannot represent, such as an RSA or OKP key. +func keySetWithRaw(t *testing.T, jwk JWK, raw string) []byte { + t.Helper() + first, err := json.Marshal(jwk) + if err != nil { + t.Fatalf("marshal key: %v", err) + } + return []byte(`{"keys":[` + string(first) + `,` + raw + `]}`) +} + func jwkOf(t *testing.T, label string) JWK { t.Helper() jwk, err := publicJWK(&testKey(t, label).PublicKey) @@ -125,6 +136,24 @@ func TestKeysValidateRefuses(t *testing.T) { "a key set without the broker client's public key": { edit: func(k *Keys) { k.BrokerClientKeySet = keySetOf(t, jwkOf(t, "someone else")) }, want: "does not hold the broker client key's public key", }, + "a key set with an RSA key": { + edit: func(k *Keys) { + k.BrokerClientKeySet = keySetWithRaw(t, jwkOf(t, "broker client"), `{"kty":"RSA","kid":"rsa","n":"AQAB","e":"AQAB"}`) + }, + want: `not an ECDSA P-256 key (kid "rsa")`, + }, + "a key set with an Ed25519 key": { + edit: func(k *Keys) { + k.BrokerClientKeySet = keySetWithRaw(t, jwkOf(t, "broker client"), `{"kty":"OKP","crv":"Ed25519","kid":"okp","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}`) + }, + want: `not an ECDSA P-256 key (kid "okp")`, + }, + "a key set with a P-384 key": { + edit: func(k *Keys) { + k.BrokerClientKeySet = keySetWithRaw(t, jwkOf(t, "broker client"), `{"kty":"EC","crv":"P-384","kid":"p384","x":"AA","y":"AA"}`) + }, + want: `not an ECDSA P-256 key (kid "p384")`, + }, "a key set with another key under the broker client's kid": { edit: func(k *Keys) { other := jwkOf(t, "someone else") @@ -222,3 +251,18 @@ func TestWithAgentIssuerFallbacksRefusesANonP256Key(t *testing.T) { } } } + +func TestKeysPublicKeysListsEveryRole(t *testing.T) { + t.Parallel() + k := validKeys(t) + got := k.PublicKeys() + want := []string{"agent issuer", "old agent issuer", "next broker client", "broker client", "AS-1", "old AS-1"} + if len(got) != len(want) { + t.Fatalf("PublicKeys = %d keys, want %d", len(got), len(want)) + } + for i, label := range want { + if !testKey(t, label).PublicKey.Equal(got[i]) { + t.Errorf("PublicKeys[%d] is not the %s key", i, label) + } + } +} diff --git a/user-docs/operating/mecak8s/identity-and-client-access.md b/user-docs/operating/mecak8s/identity-and-client-access.md index 01d3eee5d8..6f1bbc45bf 100644 --- a/user-docs/operating/mecak8s/identity-and-client-access.md +++ b/user-docs/operating/mecak8s/identity-and-client-access.md @@ -381,6 +381,60 @@ AS-1's signing key is part of this file: `mecak8s` refuses to start with the removed `--identity-broker-as1-signing-key-file` flag, so set `keys.as1_signing.key_file` instead. +### Declare the embedded gateway + +The configuration file can list the MCP gateway the broker authorizes agent +calls through. The list is optional and takes at most one entry, which +describes the embedded gateway `mecak8s` runs for MCP servers with +`auth.mode: oauth`. With the chart, set `identityBroker.gateways`; without it, +add `gateways` to the file: + +```json +"gateways": [{ + "kind": "embedded", + "as2_issuer": "https://mecatl.example.com/v1/mcp/broker", + "token_endpoint": "https://mecatl.example.com/v1/mcp/broker/oauth/token", + "resource": "https://mecatl.example.com/v1/mcp/broker/mcp", + "servers": [] +}] +``` + +|Field|Meaning| +|-|-| +|`kind`|`embedded`. `mecak8s` refuses `external`: external gateways are not supported yet.| +|`as2_issuer`|The issuer of the gateway's authorization server: the scheme and host of `mcp.broker.callback_url` followed by `/v1/mcp/broker`. It must differ from AS-1's issuer, comparing the path too, because the broker authenticates to both with the same key.| +|`token_endpoint`|That issuer followed by `/oauth/token`, as the authorization server advertises it.| +|`resource`|That issuer followed by `/mcp`.| +|`servers`|MCP server names, matched exactly, each with `auth.mode: oauth`. Leave it empty for now.| + +`mecak8s` derives the embedded gateway's issuer, token endpoint, and resource +from `mcp.broker.callback_url` and refuses to start when the entry names +others, when it runs no embedded gateway, or when the file names no broker +client key. An entry also requires the gateway's own signing key, below. +Without an entry, the MCP broker runs as it does with the identity broker off. + +An entry that lists servers is refused until the gateway's authorization +server accepts AS-1's tokens, which is not available yet. An entry with no +servers routes no calls through the gateway: it registers the broker as a +client of the gateway's authorization server and keeps that server's signing +key across restarts. + +#### Set the gateway's signing key + +The embedded gateway's authorization server signs its tokens with the key in +the `mcp.broker.signing_key_file` setting. Earlier keys listed in +`mcp.broker.fallback_key_files` keep verifying the tokens they signed, so the +key can rotate the same way as the broker's keys. Both take absolute paths to +PEM private keys. `mecak8s` requires the key with the identity broker on and a +gateway entry, refuses it otherwise, and refuses a key, or a fallback, that is +also one of the broker's keys. With the chart, name an existing Secret key in +`mcp.broker.signingKey` and its fallbacks in `mcp.broker.signingKey.fallbacks`; +the chart projects them read-only and renders the setting. See the +[configuration reference](/reference/configuration.md) for the setting. + +`mecak8s` reads the key at startup, so restart the Deployment after changing it +in a Secret. + ### Keep the broker's keys out of sessions The broker reads its keys from files in the `mecak8s` pod, so it runs only @@ -438,9 +492,10 @@ comes from a Secret, so the access tokens AS-1 issued before a restart keep verifying until they expire. AS-1 accepts each access token for one session open, but it forgets which tokens it has accepted when the pod restarts. A token used before a restart can open one more session after it, until the token -expires. The MCP gateway's embedded authorization server generates its own -signing key at each start, so the tokens it issued stop verifying after a -restart. +expires. Without a gateway entry, the MCP gateway's embedded authorization +server generates its own signing key at each start, so the tokens it issued +stop verifying after a restart; with one, it signs with +[the key you supply](#set-the-gateways-signing-key). Turning on `oidc.ownerIdentity: sub_id` for a deployment with existing sessions leaves those sessions with their previous owners; see diff --git a/user-docs/reference/configuration.md b/user-docs/reference/configuration.md index 54e5cd5ce2..b9bb53866f 100644 --- a/user-docs/reference/configuration.md +++ b/user-docs/reference/configuration.md @@ -411,6 +411,8 @@ Strict OPERATOR-TIER Streamable HTTP MCP authority configuration. Mode selects o | `mcp.mode` | `string` | `(empty)` | Mode selects global or broker authority. Empty uses the command-root default. | | `mcp.broker` | `mcpbrokerprofile` | `(absent)` | Broker contains options meaningful only in broker mode. | | `mcp.broker.callback_url` | `string` | `(empty)` | CallbackURL is required exactly when broker mode contains an OAuth route. It must be an absolute HTTPS URL without userinfo, query, or fragment; an omitted path or / is normalized to /. | +| `mcp.broker.signing_key_file` | `string` | `(empty)` | SigningKeyFile is the absolute path of the PEM private key (RSA, ECDSA, or Ed25519; PKCS #1, SEC 1, or PKCS #8) the embedded MCP gateway's authorization server signs its tokens with, so they survive a restart. mecak8s requires it with the identity broker on and an embedded gateway entry in the identity broker's configuration file, and refuses it otherwise; it must differ from every identity broker key. It is read at startup, so a new key takes effect on restart. | +| `mcp.broker.fallback_key_files` | `[]string` | `(absent)` | FallbackKeyFiles are absolute paths of earlier signing keys, PEM private keys like SigningKeyFile: tokens they signed still verify while they are listed, so the key can rotate. They require SigningKeyFile. | | `mcp.servers` | `[]mcpserverprofile` | `(absent)` | Servers is the ordered list of neutral Streamable HTTP route declarations. | | `mcp.servers[].name` | `string` | `(empty)` | Name is an ASCII [A-Za-z0-9_]+ identifier, unique case-insensitively. | | `mcp.servers[].url` | `string` | `(empty)` | URL is an absolute HTTP(S) endpoint without userinfo or a fragment. |