Skip to content

Agent Mesh

router, node, standalone: address PR #838 review and harden external ingress

Antonio Ojea74099010074d
diff --git a/.github/k8s/agentmesh-router-template.yaml b/.github/k8s/agentmesh-router-template.yaml
index 5a2a35a5..793e8926 100644
--- a/.github/k8s/agentmesh-router-template.yaml
+++ b/.github/k8s/agentmesh-router-template.yaml
@@ -95,6 +95,7 @@ spec:
- "--metrics-addr=0.0.0.0:9090"
- "--ingress-addr=0.0.0.0:8080"
- "--ingress-url=https://${ENV_NAME}.sam-mesh.dev/ingress"
+ - "--public-control-plane=https://${ENV_NAME}.sam-mesh.dev"
- "--allow-insecure-ingress-http"
# Profiles on loopback only: `kubectl port-forward <pod> 6060` then
# `go tool pprof http://127.0.0.1:6060/debug/pprof/heap`.
diff --git a/api/agentmesh.pb.go b/api/agentmesh.pb.go
index 7731063d..ecd9221a 100644
--- a/api/agentmesh.pb.go
+++ b/api/agentmesh.pb.go
@@ -153,7 +153,7 @@ type IngressAuthMode int32
const (
// Defaults to INGRESS_AUTH_MODE_EDGE.
IngressAuthMode_INGRESS_AUTH_MODE_UNSPECIFIED IngressAuthMode = 0
- // Router verifies Mesh Biscuit or trusted OIDC JWT + mesh policy at the edge.
+ // Router and provider node verify a delegated Mesh Biscuit + mesh policy.
IngressAuthMode_INGRESS_AUTH_MODE_EDGE IngressAuthMode = 1
// Backend authenticates its own requests; requires an explicit PASSTHROUGH
// grant on the serving node's PolicyRole.allowed_ingress.
diff --git a/api/agentmesh.proto b/api/agentmesh.proto
index be559300..b265be2a 100644
--- a/api/agentmesh.proto
+++ b/api/agentmesh.proto
@@ -153,7 +153,7 @@ enum ServiceType {
enum IngressAuthMode {
// Defaults to INGRESS_AUTH_MODE_EDGE.
INGRESS_AUTH_MODE_UNSPECIFIED = 0;
- // Router verifies Mesh Biscuit or trusted OIDC JWT + mesh policy at the edge.
+ // Router and provider node verify a delegated Mesh Biscuit + mesh policy.
INGRESS_AUTH_MODE_EDGE = 1;
// Backend authenticates its own requests; requires an explicit PASSTHROUGH
// grant on the serving node's PolicyRole.allowed_ingress.
diff --git a/api/ingress.go b/api/ingress.go
index 75358ca3..58b20ac4 100644
--- a/api/ingress.go
+++ b/api/ingress.go
@@ -16,6 +16,7 @@ package api
import (
"fmt"
+ "net/http"
"net/url"
"slices"
"strings"
@@ -110,6 +111,16 @@ func ValidateServiceIngress(svcType ServiceType, ing *ServiceIngress) error {
if !IsInboundServiceType(svcType) {
return fmt.Errorf("ingress is only supported for inbound service types (a2a, mcp, inference), got %v", svcType)
}
+ return ValidatePeerRecordIngress(ing)
+}
+
+// ValidatePeerRecordIngress validates the mode and allow-list contents of a
+// ServiceIngress message independent of service type (for example when a
+// router validates a PeerRecord received during directory lookup).
+func ValidatePeerRecordIngress(ing *ServiceIngress) error {
+ if ing == nil {
+ return nil
+ }
mode := EffectiveIngressAuthMode(ing)
if _, err := IngressAuthModeToString(mode); err != nil {
return err
@@ -133,6 +144,22 @@ func ValidateServiceIngress(svcType ServiceType, ing *ServiceIngress) error {
return nil
}
+// SanitizeExternalIngressHeaders removes ambient cookies, spoofable X-Mesh-*
+// and X-Peer-Id attribution headers, and (when stripAuthorization is true) the
+// external caller's Authorization header before forwarding an external ingress
+// request across the router-to-node hop or into a local backend service.
+func SanitizeExternalIngressHeaders(h http.Header, stripAuthorization bool) {
+ for name := range h {
+ lower := strings.ToLower(name)
+ if lower == "cookie" ||
+ (stripAuthorization && lower == "authorization") ||
+ strings.HasPrefix(lower, "x-mesh-") ||
+ strings.EqualFold(name, HeaderPeerID) {
+ delete(h, name)
+ }
+ }
+}
+
// ValidateIngressGrant checks one PolicyRole.allowed_ingress entry.
func ValidateIngressGrant(g *IngressGrant, roleName string) error {
if g == nil || len(g.Services) == 0 {
diff --git a/api/mcp.go b/api/mcp.go
new file mode 100644
index 00000000..504de608
--- /dev/null
+++ b/api/mcp.go
@@ -0,0 +1,96 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+)
+
+// DefaultMaxMCPBodyInspectBytes is the default maximum HTTP request body size
+// buffered when inspecting an MCP JSON-RPC 2.0 payload for tool-level policy
+// evaluation (4 MiB).
+const DefaultMaxMCPBodyInspectBytes int64 = 4 << 20
+
+// InspectJSONRPCMCPBody inspects a JSON-RPC 2.0 request body for MCP methods
+// and extracts the bare tool name when present, or sets allowStreamInit for
+// session handshake, capability discovery, and protocol notification methods
+// that precede a tool call.
+func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) {
+ if len(bytes.TrimSpace(body)) == 0 {
+ return "", false
+ }
+ var rpc struct {
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params"`
+ }
+ if err := json.Unmarshal(body, &rpc); err != nil {
+ return "", false
+ }
+ switch rpc.Method {
+ case "initialize", "notifications/initialized", "server/discover", "ping",
+ "tools/list", "resources/list", "prompts/list", "notifications/cancelled":
+ return "", true
+ case "tools/call":
+ var params struct {
+ Name string `json:"name"`
+ }
+ if err := json.Unmarshal(rpc.Params, &params); err != nil {
+ return "", false
+ }
+ rawTool := strings.TrimSpace(params.Name)
+ if rawTool == "" {
+ return "", false
+ }
+ if _, stripped, err := SplitToolName(rawTool); err == nil {
+ return stripped, false
+ }
+ return rawTool, false
+ default:
+ return "", false
+ }
+}
+
+// InspectMCPHTTPRequestBody buffers and restores r.Body up to maxBytes
+// (defaulting to DefaultMaxMCPBodyInspectBytes when maxBytes <= 0) and extracts
+// the MCP tool name and stream initialization flag.
+func InspectMCPHTTPRequestBody(r *http.Request, maxBytes int64) (mcpTool string, allowStreamInit bool, err error) {
+ if r == nil {
+ return "", false, nil
+ }
+ if strings.EqualFold(r.Method, http.MethodGet) || strings.EqualFold(r.Method, http.MethodDelete) {
+ return "", true, nil
+ }
+ if r.Body == nil || !strings.EqualFold(r.Method, http.MethodPost) {
+ return "", false, nil
+ }
+ if maxBytes <= 0 {
+ maxBytes = DefaultMaxMCPBodyInspectBytes
+ }
+ bodyBytes, err := io.ReadAll(io.LimitReader(r.Body, maxBytes+1))
+ if err != nil {
+ return "", false, fmt.Errorf("failed to read MCP request body: %w", err)
+ }
+ r.Body = io.NopCloser(bytes.NewReader(bodyBytes))
+ if int64(len(bodyBytes)) > maxBytes {
+ return "", false, fmt.Errorf("MCP request body exceeds maximum inspection size (%d bytes)", maxBytes)
+ }
+ tool, allowInit := InspectJSONRPCMCPBody(bodyBytes)
+ return tool, allowInit, nil
+}
diff --git a/api/mcp_test.go b/api/mcp_test.go
new file mode 100644
index 00000000..d9fad8e3
--- /dev/null
+++ b/api/mcp_test.go
@@ -0,0 +1,159 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package api
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestInspectJSONRPCMCPBody(t *testing.T) {
+ cases := []struct {
+ name string
+ body string
+ wantTool string
+ wantAllow bool
+ }{
+ {
+ name: "tools/call bare tool",
+ body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_file"}}`,
+ wantTool: "read_file",
+ wantAllow: false,
+ },
+ {
+ name: "tools/call namespaced tool",
+ body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"mcp://github/get_pr"}}`,
+ wantTool: "get_pr",
+ wantAllow: false,
+ },
+ {
+ name: "initialize",
+ body: `{"jsonrpc":"2.0","id":1,"method":"initialize"}`,
+ wantTool: "",
+ wantAllow: true,
+ },
+ {
+ name: "notifications/initialized",
+ body: `{"jsonrpc":"2.0","method":"notifications/initialized"}`,
+ wantTool: "",
+ wantAllow: true,
+ },
+ {
+ name: "server/discover",
+ body: `{"jsonrpc":"2.0","id":1,"method":"server/discover"}`,
+ wantTool: "",
+ wantAllow: true,
+ },
+ {
+ name: "tools/list",
+ body: `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`,
+ wantTool: "",
+ wantAllow: true,
+ },
+ {
+ name: "resources/read is not auth-free",
+ body: `{"jsonrpc":"2.0","id":1,"method":"resources/read","params":{"uri":"file:///secret"}}`,
+ wantTool: "",
+ wantAllow: false,
+ },
+ {
+ name: "empty body",
+ body: " ",
+ wantTool: "",
+ wantAllow: false,
+ },
+ {
+ name: "invalid json",
+ body: "{not-json",
+ wantTool: "",
+ wantAllow: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ gotTool, gotAllow := InspectJSONRPCMCPBody([]byte(tc.body))
+ if gotTool != tc.wantTool || gotAllow != tc.wantAllow {
+ t.Fatalf("InspectJSONRPCMCPBody(%q) = (%q, %v), want (%q, %v)", tc.body, gotTool, gotAllow, tc.wantTool, tc.wantAllow)
+ }
+ })
+ }
+}
+
+func TestInspectMCPHTTPRequestBody(t *testing.T) {
+ body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"mcp://git/status"}}`
+ req := httptest.NewRequest(http.MethodPost, "/mcp/git", strings.NewReader(body))
+ tool, allowInit, err := InspectMCPHTTPRequestBody(req, 1024)
+ if err != nil {
+ t.Fatalf("InspectMCPHTTPRequestBody: %v", err)
+ }
+ if tool != "status" || allowInit {
+ t.Fatalf("got (%q, %v), want (\"status\", false)", tool, allowInit)
+ }
+ restored, err := io.ReadAll(req.Body)
+ if err != nil || string(restored) != body {
+ t.Fatalf("restored body = %q (err=%v), want %q", string(restored), err, body)
+ }
+
+ getReq := httptest.NewRequest(http.MethodGet, "/mcp/git", nil)
+ if tool, allowInit, err := InspectMCPHTTPRequestBody(getReq, 1024); err != nil || tool != "" || !allowInit {
+ t.Fatalf("GET SSE stream: got (%q, %v, %v), want (\"\", true, nil)", tool, allowInit, err)
+ }
+
+ oversized := httptest.NewRequest(http.MethodPost, "/mcp/git", strings.NewReader(strings.Repeat("a", 65)))
+ if _, _, err := InspectMCPHTTPRequestBody(oversized, 64); err == nil {
+ t.Fatal("oversized MCP body succeeded, want error")
+ }
+}
+
+func TestSanitizeExternalIngressHeaders(t *testing.T) {
+ edgeHdr := http.Header{
+ "Authorization": {"Bearer caller-token"},
+ "Cookie": {"sid=123"},
+ "X-Mesh-Principal": {"[email protected]"},
+ "X-Mesh-Custom": {"evil"},
+ "X-Peer-Id": {"spoofed-peer"},
+ "Content-Type": {"application/json"},
+ "X-Hub-Signature": {"sha256=ok"},
+ }
+ SanitizeExternalIngressHeaders(edgeHdr, true)
+ for _, mustDrop := range []string{"Authorization", "Cookie", "X-Mesh-Principal", "X-Mesh-Custom", "X-Peer-Id"} {
+ if got := edgeHdr.Get(mustDrop); got != "" {
+ t.Errorf("stripAuth=true kept %s=%q", mustDrop, got)
+ }
+ }
+ if edgeHdr.Get("Content-Type") != "application/json" || edgeHdr.Get("X-Hub-Signature") != "sha256=ok" {
+ t.Errorf("stripAuth=true dropped benign headers: %v", edgeHdr)
+ }
+
+ passHdr := http.Header{
+ "Authorization": {"Bearer pair-token"},
+ "Cookie": {"sid=123"},
+ "X-Mesh-Principal": {"[email protected]"},
+ "X-Peer-Id": {"spoofed-peer"},
+ }
+ SanitizeExternalIngressHeaders(passHdr, false)
+ if got := passHdr.Get("Authorization"); got != "Bearer pair-token" {
+ t.Errorf("stripAuth=false Authorization = %q, want Bearer pair-token", got)
+ }
+ for _, mustDrop := range []string{"Cookie", "X-Mesh-Principal", "X-Peer-Id"} {
+ if got := passHdr.Get(mustDrop); got != "" {
+ t.Errorf("stripAuth=false kept %s=%q", mustDrop, got)
+ }
+ }
+}
diff --git a/api/network.go b/api/network.go
index 762b228b..40177dd4 100644
--- a/api/network.go
+++ b/api/network.go
@@ -318,12 +318,6 @@ const (
// node can re-verify Datalog policy, local attenuation, TAR, and allow-lists
// end to end. Stripped before forwarding to the backend service.
HeaderMeshIngressCallerBiscuit = "X-Mesh-Ingress-Caller-Biscuit"
-
- // HeaderMeshIngressClaims carries base64url-encoded JSON OIDC fact claims
- // verified at the router edge over IngressProtocolID when the external caller
- // authenticated with a trusted OIDC JWT rather than a Mesh Biscuit. Stripped
- // before forwarding to the backend service.
- HeaderMeshIngressClaims = "X-Mesh-Ingress-Claims"
)
// ============================================================================
diff --git a/charts/agentmesh/values.yaml b/charts/agentmesh/values.yaml
index fd0414b2..12ecd864 100644
--- a/charts/agentmesh/values.yaml
+++ b/charts/agentmesh/values.yaml
@@ -13,6 +13,9 @@ gateway:
adminRoute: false
# Routes /ingress and /ingress/ directly to the router Service so external HTTP
# callers reach opted-in node services without traversing the control plane.
+ # Because routers behind an L7 Gateway see the Gateway's internal proxy IP on
+ # TCP RemoteAddr, attach per-client source-IP rate limiting (e.g. Cloud Armor)
+ # at the Gateway for unauthenticated routes (AgentCard discovery and passthrough).
ingressRoute: true
# External prefix the console is served under. Empty leaves the console unrouted.
consolePath: /console
diff --git a/cmd/agentmesh-router/main.go b/cmd/agentmesh-router/main.go
index 263854d7..5f880e55 100644
--- a/cmd/agentmesh-router/main.go
+++ b/cmd/agentmesh-router/main.go
@@ -81,8 +81,6 @@ var (
ingressTLSCertPath string
ingressTLSKeyPath string
allowInsecureIngressHTTP bool
- oidcIssuer string
- audience string
publicControlPlaneURL string
)
@@ -123,8 +121,6 @@ func main() {
IngressTLSCertPath: ingressTLSCertPath,
IngressTLSKeyPath: ingressTLSKeyPath,
AllowInsecureIngressHTTP: allowInsecureIngressHTTP,
- OIDCIssuer: oidcIssuer,
- Audience: audience,
PublicControlPlaneURL: publicControlPlaneURL,
}
labels, err := api.ParseLabelFlags(labelFlags)
@@ -190,8 +186,6 @@ func main() {
rootCmd.Flags().StringVar(&ingressTLSCertPath, "ingress-tls-cert-path", "", "Path to TLS certificate file for --ingress-addr")
rootCmd.Flags().StringVar(&ingressTLSKeyPath, "ingress-tls-key-path", "", "Path to TLS private key file for --ingress-addr")
rootCmd.Flags().BoolVar(&allowInsecureIngressHTTP, "allow-insecure-ingress-http", false, "Allow --ingress-addr on a non-loopback interface without TLS (only when behind a TLS-terminating L7 load balancer) and allow http:// in --ingress-url")
- rootCmd.Flags().StringVar(&oidcIssuer, "oidc-issuer", "", "Optional OIDC issuer URL override for verifying OIDC JWTs on edge ingress (defaults to the control plane's /info oidc_issuer)")
- rootCmd.Flags().StringVar(&audience, "audience", "", "Optional OIDC audience override for verifying OIDC JWTs on edge ingress (defaults to the control plane's /info audience)")
rootCmd.Flags().StringVar(&publicControlPlaneURL, "public-control-plane", "", "Optional public URL of the control plane advertised in RFC 9728 and A2A OAuth metadata when --control-plane uses a cluster-internal address")
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
diff --git a/internal/envoy/server.go b/internal/envoy/server.go
index 989602e6..e7e394d1 100644
--- a/internal/envoy/server.go
+++ b/internal/envoy/server.go
@@ -18,11 +18,8 @@
package envoy
import (
- "bytes"
"context"
- "encoding/json"
"errors"
- "fmt"
"io"
"net/http"
"strings"
@@ -485,53 +482,11 @@ func (s *GatewayServer) evaluateExtProcDecision(ctx context.Context, method, pat
// and extracts the bare tool name when present, or sets allowStreamInit for
// session handshake, capability discovery, and protocol notification methods.
func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) {
- var rpc struct {
- Method string `json:"method"`
- Params struct {
- Name string `json:"name"`
- } `json:"params"`
- }
- if err := json.Unmarshal(body, &rpc); err != nil {
- return "", false
- }
- switch rpc.Method {
- case "initialize", "notifications/initialized", "server/discover", "ping",
- "tools/list", "resources/list", "prompts/list", "notifications/cancelled":
- return "", true
- case "tools/call":
- rawTool := strings.TrimSpace(rpc.Params.Name)
- if rawTool == "" {
- return "", false
- }
- if _, stripped, err := api.SplitToolName(rawTool); err == nil {
- return stripped, false
- }
- return rawTool, false
- default:
- return "", false
- }
+ return api.InspectJSONRPCMCPBody(body)
}
// InspectMCPHTTPRequestBody buffers and restores r.Body up to MaxGRPCMessageBytes
// and extracts the MCP tool name and stream initialization flag.
func InspectMCPHTTPRequestBody(r *http.Request) (string, bool, error) {
- if r == nil {
- return "", false, nil
- }
- if strings.EqualFold(r.Method, http.MethodGet) || strings.EqualFold(r.Method, http.MethodDelete) {
- return "", true, nil
- }
- if r.Body == nil || !strings.EqualFold(r.Method, http.MethodPost) {
- return "", false, nil
- }
- bodyBytes, err := io.ReadAll(io.LimitReader(r.Body, MaxGRPCMessageBytes+1))
- if err != nil {
- return "", false, err
- }
- if int64(len(bodyBytes)) > MaxGRPCMessageBytes {
- return "", false, fmt.Errorf("MCP request body exceeds maximum inspection size (%d bytes)", MaxGRPCMessageBytes)
- }
- r.Body = io.NopCloser(bytes.NewReader(bodyBytes))
- tool, allowInit := InspectJSONRPCMCPBody(bodyBytes)
- return tool, allowInit, nil
+ return api.InspectMCPHTTPRequestBody(r, MaxGRPCMessageBytes)
}
diff --git a/internal/identity/ingress.go b/internal/identity/ingress.go
index adc8baa6..f3e939af 100644
--- a/internal/identity/ingress.go
+++ b/internal/identity/ingress.go
@@ -16,37 +16,17 @@ package identity
import (
"crypto/ed25519"
- "crypto/rand"
"encoding/base64"
- "encoding/json"
"fmt"
"slices"
"sort"
"strings"
- "sync"
"time"
"github.com/eclipse-biscuit/biscuit-go/v2"
"github.com/google/agentmesh/api"
)
-var (
- ephemeralOnce sync.Once
- ephemeralPub ed25519.PublicKey
- ephemeralPriv ed25519.PrivateKey
-)
-
-func ephemeralEvalKeys() (ed25519.PublicKey, ed25519.PrivateKey) {
- ephemeralOnce.Do(func() {
- var err error
- ephemeralPub, ephemeralPriv, err = ed25519.GenerateKey(rand.Reader)
- if err != nil {
- panic(fmt.Sprintf("failed to generate ephemeral evaluation key: %v", err))
- }
- })
- return ephemeralPub, ephemeralPriv
-}
-
// DecodeBase64Biscuit decodes a base64 or unpadded base64url encoded Biscuit.
func DecodeBase64Biscuit(encoded string) ([]byte, error) {
encoded = strings.TrimSpace(encoded)
@@ -59,90 +39,6 @@ func DecodeBase64Biscuit(encoded string) ([]byte, error) {
return base64.RawURLEncoding.DecodeString(encoded)
}
-// OIDCFactsFromJWTClaims extracts standard Agent Mesh OIDC identity facts
-// ("user", "email", "group", "idp_role") from verified JWT claims. FactRole and
-// FactNode are never derived from OIDC claims.
-func OIDCFactsFromJWTClaims(claims map[string]any) map[string][]string {
- out := make(map[string][]string)
- if len(claims) == 0 {
- return out
- }
- claimMap := api.OIDCClaimToFact()
- for claimKey, factName := range claimMap {
- raw, ok := claims[claimKey]
- if !ok || raw == nil {
- continue
- }
- seen := make(map[string]bool)
- for _, item := range toStringSlice(raw) {
- if item == "" || seen[item] {
- continue
- }
- seen[item] = true
- out[factName] = append(out[factName], item)
- }
- sort.Strings(out[factName])
- }
- return out
-}
-
-func allowedOIDCFactNames() map[string]bool {
- allowed := make(map[string]bool)
- for _, factName := range api.OIDCClaimToFact() {
- allowed[factName] = true
- }
- return allowed
-}
-
-// SanitizeOIDCFacts returns a copy containing only permitted OIDC fact names
-// ("user", "email", "group", "idp_role") and non-empty deduplicated values.
-func SanitizeOIDCFacts(facts map[string][]string) map[string][]string {
- allowed := allowedOIDCFactNames()
- clean := make(map[string][]string)
- for k, vals := range facts {
- if !allowed[k] {
- continue
- }
- seen := make(map[string]bool)
- for _, v := range vals {
- if v == "" || seen[v] {
- continue
- }
- seen[v] = true
- clean[k] = append(clean[k], v)
- }
- if len(clean[k]) > 0 {
- sort.Strings(clean[k])
- }
- }
- return clean
-}
-
-// MarshalIngressClaimsHeader encodes verified OIDC fact claims for transport
-// over IngressProtocolID from an authenticated router to the serving node.
-func MarshalIngressClaimsHeader(facts map[string][]string) (string, error) {
- clean := SanitizeOIDCFacts(facts)
- raw, err := json.Marshal(clean)
- if err != nil {
- return "", err
- }
- return base64.RawURLEncoding.EncodeToString(raw), nil
-}
-
-// UnmarshalIngressClaimsHeader decodes and sanitizes verified OIDC fact claims
-// received over IngressProtocolID from an authenticated router.
-func UnmarshalIngressClaimsHeader(encoded string) (map[string][]string, error) {
- raw, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(encoded))
- if err != nil {
- return nil, fmt.Errorf("invalid base64url ingress claims header: %w", err)
- }
- var parsed map[string][]string
- if err := json.Unmarshal(raw, &parsed); err != nil {
- return nil, fmt.Errorf("invalid json ingress claims header: %w", err)
- }
- return SanitizeOIDCFacts(parsed), nil
-}
-
// TargetFactsFromBiscuit queries api.TargetFactRules on a provider's own
// verified Biscuit to produce the target_fact(type, val) facts injected when
// evaluating BaselineTargetCheck against a caller.
@@ -269,12 +165,10 @@ func runIngressAuthorizer(authorizer biscuit.Authorizer, p IngressEvalParams) ([
return roles, nil
}
-// AuthorizeIngressDelegatedBiscuit authorizes a verified Delegated Session
-// Biscuit or task-attenuated Task Biscuit (minted via RFC 8693 /oauth/token or
-// SDK task attenuation) against mesh Datalog policy, local node attenuation,
-// TAR blocks, and ServiceIngress.allow. Unattenuated standing member/router
-// transport Biscuits are rejected.
-func AuthorizeIngressDelegatedBiscuit(claims *VerifiedBiscuitClaims, p IngressEvalParams) (*IngressCallerResult, error) {
+// ValidateIngressCallerPreDial checks the caller's verified Biscuit claims,
+// TAR attenuation chain, and ServiceIngress.allow ACL locally before opening a
+// network connection or /mesh/auth handshake to the serving provider.
+func ValidateIngressCallerPreDial(claims *VerifiedBiscuitClaims, p IngressEvalParams) (map[string][]string, error) {
if claims == nil || claims.Biscuit == nil {
return nil, fmt.Errorf("missing verified biscuit claims")
}
@@ -284,16 +178,6 @@ func AuthorizeIngressDelegatedBiscuit(claims *VerifiedBiscuitClaims, p IngressEv
if claims.NodePeerID != "" && len(claims.TaskRules) == 0 {
return nil, fmt.Errorf("unattenuated transport member biscuits cannot be used as HTTP edge bearer tokens; exchange at /oauth/token")
}
-
- authorizer, err := newAuthorizer(claims.Biscuit, claims.VerifyingKey, p.Timeout)
- if err != nil {
- return nil, fmt.Errorf("failed to create biscuit authorizer: %w", err)
- }
- roles, err := runIngressAuthorizer(authorizer, p)
- if err != nil {
- return nil, err
- }
-
if len(claims.TaskRules) > 0 {
taskReq := api.TaskRequestContext{
ServiceType: p.ServiceType,
@@ -308,85 +192,43 @@ func AuthorizeIngressDelegatedBiscuit(claims *VerifiedBiscuitClaims, p IngressEv
return nil, err
}
}
-
idMap := claims.IdentityClaimsMap()
if !api.MatchIngressAllow(p.Allow, idMap) {
return nil, fmt.Errorf("caller does not satisfy service ingress allow list")
}
-
- actorNodeID := claims.ActorNodePeerID
- if actorNodeID == "" {
- actorNodeID = claims.NodePeerID
- }
-
- return &IngressCallerResult{
- Principal: claims.Principal(),
- Roles: roles,
- TaskName: claims.InnermostTaskName(),
- ActorNodeID: actorNodeID,
- IdentityFacts: idMap,
- }, nil
+ return idMap, nil
}
-// AuthorizeIngressOIDCFacts authorizes verified OIDC JWT fact claims against
-// mesh Datalog policy, local node attenuation, and ServiceIngress.allow using
-// the exact same Biscuit Datalog authorizer as Delegated Session Biscuits.
-func AuthorizeIngressOIDCFacts(oidcFacts map[string][]string, p IngressEvalParams) (*IngressCallerResult, error) {
- clean := SanitizeOIDCFacts(oidcFacts)
- if len(clean) == 0 {
- return nil, fmt.Errorf("verified OIDC token carries no identity claims")
- }
-
- pub, priv := ephemeralEvalKeys()
- builder := biscuit.NewBuilder(priv)
- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactExpiration,
- IDs: []biscuit.Term{biscuit.Date(time.Now().Add(5 * time.Minute))},
- }}); err != nil {
- return nil, err
- }
- keys := make([]string, 0, len(clean))
- for k := range clean {
- keys = append(keys, k)
- }
- sort.Strings(keys)
- for _, k := range keys {
- for _, v := range clean[k] {
- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: k,
- IDs: []biscuit.Term{biscuit.String(v)},
- }}); err != nil {
- return nil, err
- }
- }
- }
- tok, err := builder.Build()
+// AuthorizeIngressDelegatedBiscuit authorizes a verified Delegated Session
+// Biscuit or task-attenuated Task Biscuit (minted via RFC 8693 /oauth/token,
+// POST /token/exchange, or SDK task attenuation) against mesh Datalog policy,
+// local node attenuation, TAR blocks, and ServiceIngress.allow. Unattenuated
+// standing member/router transport Biscuits are rejected.
+func AuthorizeIngressDelegatedBiscuit(claims *VerifiedBiscuitClaims, p IngressEvalParams) (*IngressCallerResult, error) {
+ idMap, err := ValidateIngressCallerPreDial(claims, p)
if err != nil {
return nil, err
}
- authorizer, err := tok.Authorizer(pub, AuthorizerOptions(p.Timeout)...)
+
+ authorizer, err := newAuthorizer(claims.Biscuit, claims.VerifyingKey, p.Timeout)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("failed to create biscuit authorizer: %w", err)
}
roles, err := runIngressAuthorizer(authorizer, p)
if err != nil {
return nil, err
}
- if !api.MatchIngressAllow(p.Allow, clean) {
- return nil, fmt.Errorf("caller does not satisfy service ingress allow list")
- }
-
- var principal string
- if emails := clean[api.FactEmail]; len(emails) > 0 {
- principal = emails[0]
- } else if users := clean[api.FactUser]; len(users) > 0 {
- principal = users[0]
+ actorNodeID := claims.ActorNodePeerID
+ if actorNodeID == "" {
+ actorNodeID = claims.NodePeerID
}
return &IngressCallerResult{
- Principal: principal,
+ Principal: claims.Principal(),
Roles: roles,
- IdentityFacts: clean,
+ TaskName: claims.InnermostTaskName(),
+ ActorNodeID: actorNodeID,
+ IdentityFacts: idMap,
}, nil
}
diff --git a/internal/identity/ingress_test.go b/internal/identity/ingress_test.go
index 40f27aff..058b922e 100644
--- a/internal/identity/ingress_test.go
+++ b/internal/identity/ingress_test.go
@@ -273,42 +273,28 @@ func TestAuthorizeIngressCallers(t *testing.T) {
t.Fatal("expected allow list mismatch to deny")
}
- // 3. Verified OIDC JWT claims round-trip through X-Mesh-Ingress-Claims and evaluate identically.
- oidcFacts := OIDCFactsFromJWTClaims(map[string]any{
- "sub": "uid-2",
- "email": "[email protected]",
- "groups": []any{"a2a"},
- "roles": []string{"mesh:role:router"}, // mapped to idp_role, NEVER role!
- })
- hdr, err := MarshalIngressClaimsHeader(oidcFacts)
+ // 3. Router Biscuits (even if attenuated with a TAR block) MUST be rejected as HTTP edge bearer tokens.
+ routerRaw, err := MintBootstrapBiscuitToken(priv, actorPeer, api.RoleRouter, time.Now().Add(time.Hour), []*api.PolicyRole{
+ {Name: api.RoleRouter, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}},
+ }, nil)
if err != nil {
- t.Fatalf("MarshalIngressClaimsHeader: %v", err)
+ t.Fatalf("MintBootstrapBiscuitToken(router): %v", err)
}
- unmarshaled, err := UnmarshalIngressClaimsHeader(hdr)
+ attRouterRaw, err := AttenuateBiscuit(routerRaw, tarRule)
if err != nil {
- t.Fatalf("UnmarshalIngressClaimsHeader: %v", err)
+ t.Fatalf("AttenuateBiscuit(router): %v", err)
}
- oidcRes, err := AuthorizeIngressOIDCFacts(unmarshaled, IngressEvalParams{
- ServiceType: "a2a",
- ServiceName: "assistant",
- Method: "POST",
- Path: "/message:send",
- TargetFacts: targetFacts,
- EnforceTargetCheck: true,
- MeshPolicyRules: meshRules,
- Allow: []string{"email:*@google.com"},
- Timeout: time.Second,
- })
+ routerClaims, err := InspectVerifiedBiscuit(attRouterRaw, []ed25519.PublicKey{pub}, time.Second)
if err != nil {
- t.Fatalf("AuthorizeIngressOIDCFacts: %v", err)
- }
- if oidcRes.Principal != "[email protected]" {
- t.Fatalf("got principal %q, want [email protected]", oidcRes.Principal)
+ t.Fatalf("InspectVerifiedBiscuit(router): %v", err)
}
- for _, r := range oidcRes.Roles {
- if r == api.RoleRouter {
- t.Fatal("OIDC roles claim must never become mesh role")
- }
+ if _, err := ValidateIngressCallerPreDial(routerClaims, IngressEvalParams{
+ ServiceType: "a2a",
+ ServiceName: "assistant",
+ Method: "POST",
+ Path: "/message:send",
+ }); err == nil {
+ t.Fatal("expected router biscuit to be rejected at HTTP edge")
}
}
diff --git a/internal/node/config.go b/internal/node/config.go
index 77a72a09..f0be11c9 100644
--- a/internal/node/config.go
+++ b/internal/node/config.go
@@ -118,9 +118,20 @@ func CompleteNodeConfig(config api.NodeConfig) (*NodeConfigComplete, error) {
if typeErr != nil {
return nil, fmt.Errorf("service %q: %w", svc.Name, typeErr)
}
- if _, err := api.ServiceIngressFromConfig(sType, svc.Ingress); err != nil {
+ ing, err := api.ServiceIngressFromConfig(sType, svc.Ingress)
+ if err != nil {
return nil, fmt.Errorf("service %q: %w", svc.Name, err)
}
+ if api.EffectiveIngressAuthMode(ing) == api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH {
+ if svc.TargetAuthPath != "" {
+ return nil, fmt.Errorf("service %q: ingress auth_mode %q cannot be combined with target_auth_path (would expose backend credential without caller authentication)", svc.Name, api.IngressAuthModeStringPassthrough)
+ }
+ if svc.TargetURL != "" {
+ if bt, pErr := parseBackendTarget(svc.TargetURL); pErr == nil && bt.auth != "" {
+ return nil, fmt.Errorf("service %q: ingress auth_mode %q cannot be combined with an inline target_url credential (would expose backend credential without caller authentication)", svc.Name, api.IngressAuthModeStringPassthrough)
+ }
+ }
+ }
}
if svc.TargetAuthPath != "" && svc.TargetURL == "" {
return nil, fmt.Errorf("service %q: target_auth_path needs a target_url", svc.Name)
diff --git a/internal/node/ingress.go b/internal/node/ingress.go
index 28a6e735..dffe2bc4 100644
--- a/internal/node/ingress.go
+++ b/internal/node/ingress.go
@@ -260,6 +260,8 @@ func (n *AgentMeshNode) externalIngressHandler() http.Handler {
}
if n.services == nil {
+ externalIngressRequestsTotal.WithLabelValues(modeMetric, externalIngressOutcomeInvalid).Inc()
+ logger.Error("[ExternalIngress] Service registry not initialized")
http.Error(w, "Service registry not initialized", http.StatusServiceUnavailable)
return
}
@@ -297,7 +299,7 @@ func (n *AgentMeshNode) externalIngressHandler() http.Handler {
backendPath := "/" + upstreamPath
if effectiveMode == api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH {
- stripExternalIngressHeaders(r.Header, false)
+ api.SanitizeExternalIngressHeaders(r.Header, false)
r.Header.Set(api.HeaderPeerID, remotePeer.String())
r.Header.Set(api.HeaderMeshIngress, api.IngressAuthModeStringPassthrough)
@@ -320,13 +322,11 @@ func (n *AgentMeshNode) externalIngressHandler() http.Handler {
// AgentCard without caller credentials so external A2A clients can
// discover SecuritySchemes before authenticating.
callerBiscuitHeader := strings.TrimSpace(r.Header.Get(api.HeaderMeshIngressCallerBiscuit))
- callerClaimsHeader := strings.TrimSpace(r.Header.Get(api.HeaderMeshIngressClaims))
if serviceType == api.ServiceType_SERVICE_TYPE_A2A &&
r.Method == http.MethodGet &&
upstreamPath == a2aAgentCardPath &&
- callerBiscuitHeader == "" &&
- callerClaimsHeader == "" {
- stripExternalIngressHeaders(r.Header, true)
+ callerBiscuitHeader == "" {
+ api.SanitizeExternalIngressHeaders(r.Header, true)
r.Header.Set(api.HeaderPeerID, remotePeer.String())
r.Header.Set(api.HeaderMeshIngress, api.IngressAuthModeStringEdge)
@@ -346,14 +346,25 @@ func (n *AgentMeshNode) externalIngressHandler() http.Handler {
return
}
- if callerBiscuitHeader == "" && callerClaimsHeader == "" {
+ if callerBiscuitHeader == "" {
externalIngressRequestsTotal.WithLabelValues(modeMetric, externalIngressOutcomeUnauthenticated).Inc()
+ logger.Warnf("[ExternalIngress] Missing caller biscuit on edge ingress request from router %s for %s", remotePeer, target)
http.Error(w, "Missing caller credentials on edge ingress request", http.StatusUnauthorized)
return
}
- if callerBiscuitHeader != "" && callerClaimsHeader != "" {
+
+ callerBiscuitBytes, err := identity.DecodeBase64Biscuit(callerBiscuitHeader)
+ if err != nil {
externalIngressRequestsTotal.WithLabelValues(modeMetric, externalIngressOutcomeInvalid).Inc()
- http.Error(w, "Ambiguous caller credentials on edge ingress request", http.StatusBadRequest)
+ logger.Warnf("[ExternalIngress] Invalid caller biscuit encoding via router %s for %s: %v", remotePeer, target, err)
+ http.Error(w, "Invalid caller biscuit encoding", http.StatusBadRequest)
+ return
+ }
+ verifiedCaller, err := n.VerifyLocalBiscuit(callerBiscuitBytes)
+ if err != nil {
+ externalIngressRequestsTotal.WithLabelValues(modeMetric, externalIngressOutcomeDeny).Inc()
+ logger.Warnf("[ExternalIngress] Caller biscuit verification failed via router %s for %s: %v", remotePeer, target, err)
+ refuse(w, http.StatusForbidden, "Authorization failed", proxyStatusDenied)
return
}
@@ -365,53 +376,19 @@ func (n *AgentMeshNode) externalIngressHandler() http.Handler {
return
}
- authorizeCaller := func(params identity.IngressEvalParams) (*identity.IngressCallerResult, []byte, int, string) {
- if callerBiscuitHeader != "" {
- rawCaller, decErr := identity.DecodeBase64Biscuit(callerBiscuitHeader)
- if decErr != nil {
- return nil, nil, http.StatusBadRequest, "Invalid caller biscuit encoding"
- }
- verifiedCaller, verErr := n.VerifyLocalBiscuit(rawCaller)
- if verErr != nil {
- return nil, nil, http.StatusForbidden, fmt.Sprintf("Authorization failed: %v", verErr)
- }
- res, authErr := identity.AuthorizeIngressDelegatedBiscuit(verifiedCaller, params)
- if authErr != nil {
- return nil, nil, http.StatusForbidden, "Authorization failed"
- }
- return res, rawCaller, http.StatusOK, ""
- }
- oidcFacts, decErr := identity.UnmarshalIngressClaimsHeader(callerClaimsHeader)
- if decErr != nil {
- return nil, nil, http.StatusBadRequest, "Invalid caller claims header"
- }
- res, authErr := identity.AuthorizeIngressOIDCFacts(oidcFacts, params)
- if authErr != nil {
- return nil, nil, http.StatusForbidden, "Authorization failed"
- }
- return res, nil, http.StatusOK, ""
- }
-
if serviceType == api.ServiceType_SERVICE_TYPE_MCP {
preParams := evalParams
preParams.AllowMCPStreamInit = true
- if _, _, status, msg := authorizeCaller(preParams); status != http.StatusOK {
- outcome := externalIngressOutcomeDeny
- if status == http.StatusBadRequest {
- outcome = externalIngressOutcomeInvalid
- }
- externalIngressRequestsTotal.WithLabelValues(modeMetric, outcome).Inc()
- logger.Warnf("[ExternalIngress] Pre-body MCP AuthZ failed via router %s for %s: %s", remotePeer, target, msg)
- if status == http.StatusBadRequest {
- http.Error(w, msg, status)
- } else {
- refuse(w, status, "Authorization failed", proxyStatusDenied)
- }
+ if _, authErr := identity.AuthorizeIngressDelegatedBiscuit(verifiedCaller, preParams); authErr != nil {
+ externalIngressRequestsTotal.WithLabelValues(modeMetric, externalIngressOutcomeDeny).Inc()
+ logger.Warnf("[ExternalIngress] Pre-body MCP AuthZ failed via router %s for %s: %v", remotePeer, target, authErr)
+ refuse(w, http.StatusForbidden, "Authorization failed", proxyStatusDenied)
return
}
- mcpTool, allowInit, bodyErr := inspectMCPHTTPRequestBody(r)
+ mcpTool, allowInit, bodyErr := api.InspectMCPHTTPRequestBody(r, api.DefaultMaxMCPBodyInspectBytes)
if bodyErr != nil {
externalIngressRequestsTotal.WithLabelValues(modeMetric, externalIngressOutcomeDeny).Inc()
+ logger.Warnf("[ExternalIngress] MCP body inspection failed via router %s for %s: %v", remotePeer, target, bodyErr)
refuse(w, http.StatusRequestEntityTooLarge, bodyErr.Error(), proxyStatusDenied)
return
}
@@ -419,23 +396,15 @@ func (n *AgentMeshNode) externalIngressHandler() http.Handler {
evalParams.AllowMCPStreamInit = allowInit
}
- callerRes, callerBiscuitBytes, status, errMsg := authorizeCaller(evalParams)
- if status != http.StatusOK {
- outcome := externalIngressOutcomeDeny
- if status == http.StatusBadRequest {
- outcome = externalIngressOutcomeInvalid
- }
- externalIngressRequestsTotal.WithLabelValues(modeMetric, outcome).Inc()
- logger.Warnf("[ExternalIngress] AuthZ denied via router %s for %s: %s", remotePeer, target, errMsg)
- if status == http.StatusBadRequest {
- http.Error(w, errMsg, status)
- } else {
- refuse(w, status, "Authorization failed", proxyStatusDenied)
- }
+ callerRes, err := identity.AuthorizeIngressDelegatedBiscuit(verifiedCaller, evalParams)
+ if err != nil {
+ externalIngressRequestsTotal.WithLabelValues(modeMetric, externalIngressOutcomeDeny).Inc()
+ logger.Warnf("[ExternalIngress] AuthZ denied via router %s for %s: %v", remotePeer, target, err)
+ refuse(w, http.StatusForbidden, "Authorization failed", proxyStatusDenied)
return
}
- stripExternalIngressHeaders(r.Header, true)
+ api.SanitizeExternalIngressHeaders(r.Header, true)
r.Header.Set(api.HeaderPeerID, remotePeer.String())
r.Header.Set(api.HeaderMeshIngress, api.IngressAuthModeStringEdge)
if callerRes.Principal != "" {
@@ -510,18 +479,6 @@ func (n *AgentMeshNode) buildExternalIngressEvalParams(serviceType, serviceName,
return p, nil
}
-func stripExternalIngressHeaders(h http.Header, stripAuthorization bool) {
- for name := range h {
- lower := strings.ToLower(name)
- if lower == "cookie" ||
- (stripAuthorization && lower == "authorization") ||
- strings.HasPrefix(lower, "x-mesh-") ||
- strings.EqualFold(name, api.HeaderPeerID) {
- delete(h, name)
- }
- }
-}
-
func rewriteExternalIngressRequestPath(r *http.Request, parts []string, upstreamPath string) {
if upstreamPath == "" {
r.URL.Path = "/"
diff --git a/internal/node/ingress_test.go b/internal/node/ingress_test.go
index 252c6180..3de2c6ff 100644
--- a/internal/node/ingress_test.go
+++ b/internal/node/ingress_test.go
@@ -20,8 +20,11 @@ import (
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
+ "errors"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -50,7 +53,8 @@ func mustTestPeerID(t *testing.T) (peer.ID, libp2pcrypto.PrivKey) {
type fakeIngressDHT struct {
fakeDHT
- ingressCalls []ingressProvideCall
+ ingressCalls []ingressProvideCall
+ failIngressErr error
}
type ingressProvideCall struct {
@@ -65,7 +69,7 @@ func (f *fakeIngressDHT) ProvideWithIngress(_ context.Context, key []byte, servi
service: service,
ingress: ing,
})
- return nil
+ return f.failIngressErr
}
func TestServiceRegistry_ProvideWithIngressOnlyOnNamedKey(t *testing.T) {
@@ -135,6 +139,156 @@ func TestCompleteNodeConfig_ValidatesServiceIngress(t *testing.T) {
}
}
+func TestServiceRegistry_RefusedIngressFallsBackToInternalProvide(t *testing.T) {
+ dht := &fakeIngressDHT{
+ failIngressErr: errors.New("router refused ingress role ceiling"),
+ }
+ reg := newServiceRegistryForTest(dht)
+
+ var callbackInfo *api.ServiceInfo
+ reg.onIngressRegistered = func(info *api.ServiceInfo) {
+ callbackInfo = info
+ }
+
+ svc := &fakeService{
+ info: &api.ServiceInfo{
+ Name: "ungranted",
+ Type: api.ServiceType_SERVICE_TYPE_A2A,
+ Ingress: &api.ServiceIngress{
+ AuthMode: api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH,
+ },
+ },
+ handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {}),
+ }
+
+ beforeIngressFail := counterValue(t, serviceProvideFailuresTotal.WithLabelValues(provideFailureScopeIngress))
+ if err := reg.Register(context.Background(), svc); err != nil {
+ t.Fatalf("Register: %v", err)
+ }
+ afterIngressFail := counterValue(t, serviceProvideFailuresTotal.WithLabelValues(provideFailureScopeIngress))
+ if afterIngressFail != beforeIngressFail+1 {
+ t.Errorf("ingress failure counter = %v, want %v", afterIngressFail, beforeIngressFail+1)
+ }
+ if callbackInfo != nil {
+ t.Errorf("onIngressRegistered called with %v when ingress announcement failed, want nil", callbackInfo)
+ }
+ if len(dht.ingressCalls) != 1 {
+ t.Fatalf("ProvideWithIngress calls = %d, want 1", len(dht.ingressCalls))
+ }
+ nameKey, _ := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, "ungranted")
+ typeKey, _ := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, "")
+ if len(dht.calls) != 2 || !bytes.Equal(dht.calls[0], nameKey) || !bytes.Equal(dht.calls[1], typeKey) {
+ t.Fatalf("plain Provide calls = %d, want 2 (fallback nameKey + typeKey)", len(dht.calls))
+ }
+
+ // ReprovideAll also falls back while ingress remains refused, then succeeds without fallback once granted.
+ if withheld := reg.ReprovideAll(context.Background()); withheld != 0 {
+ t.Fatalf("ReprovideAll withheld = %d, want 0", withheld)
+ }
+ if len(dht.ingressCalls) != 2 || len(dht.calls) != 4 {
+ t.Fatalf("after refused ReprovideAll: ingressCalls=%d calls=%d, want 2 and 4", len(dht.ingressCalls), len(dht.calls))
+ }
+
+ dht.failIngressErr = nil
+ if withheld := reg.ReprovideAll(context.Background()); withheld != 0 {
+ t.Fatalf("ReprovideAll after policy fix withheld = %d, want 0", withheld)
+ }
+ if len(dht.ingressCalls) != 3 || len(dht.calls) != 5 {
+ t.Fatalf("after policy fix ReprovideAll: ingressCalls=%d calls=%d, want 3 and 5 (typeKey only)", len(dht.ingressCalls), len(dht.calls))
+ }
+}
+
+func TestPassthroughWithBackendCredentialRejected(t *testing.T) {
+ authFile := filepath.Join(t.TempDir(), "token")
+ if err := os.WriteFile(authFile, []byte("secret-token\n"), 0o600); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+
+ t.Run("CompleteNodeConfig rejects passthrough with target_auth_path", func(t *testing.T) {
+ cfg := api.NodeConfig{
+ Services: []api.ServiceConfig{
+ {
+ Name: "webhook",
+ Type: "a2a",
+ TargetURL: "http://127.0.0.1:8081",
+ TargetAuthPath: authFile,
+ Ingress: &api.IngressConfig{AuthMode: "passthrough"},
+ },
+ },
+ }
+ if _, err := CompleteNodeConfig(cfg); err == nil {
+ t.Fatal("expected error for passthrough + target_auth_path, got nil")
+ }
+ })
+
+ t.Run("CompleteNodeConfig rejects passthrough with inline target_url credential", func(t *testing.T) {
+ cfg := api.NodeConfig{
+ Services: []api.ServiceConfig{
+ {
+ Name: "webhook",
+ Type: "a2a",
+ TargetURL: "http://bearer:[email protected]:8081",
+ Ingress: &api.IngressConfig{AuthMode: "passthrough"},
+ },
+ },
+ }
+ if _, err := CompleteNodeConfig(cfg); err == nil {
+ t.Fatal("expected error for passthrough + inline target_url credential, got nil")
+ }
+ })
+
+ t.Run("CompleteNodeConfig allows edge with target_auth_path", func(t *testing.T) {
+ cfg := api.NodeConfig{
+ Services: []api.ServiceConfig{
+ {
+ Name: "assistant",
+ Type: "a2a",
+ TargetURL: "http://127.0.0.1:8081",
+ TargetAuthPath: authFile,
+ Ingress: &api.IngressConfig{AuthMode: "edge"},
+ },
+ },
+ }
+ if _, err := CompleteNodeConfig(cfg); err != nil {
+ t.Fatalf("expected edge + target_auth_path to succeed, got: %v", err)
+ }
+ })
+
+ t.Run("buildRegisterRequest and NewServiceFromRequest reject passthrough with credential", func(t *testing.T) {
+ if _, err := buildRegisterRequest(api.ServiceConfig{
+ Name: "webhook",
+ Type: "a2a",
+ TargetURL: "http://127.0.0.1:8081",
+ TargetAuthPath: authFile,
+ Ingress: &api.IngressConfig{AuthMode: "passthrough"},
+ }); err == nil {
+ t.Fatal("buildRegisterRequest accepted passthrough + target_auth_path")
+ }
+ if _, err := buildRegisterRequest(api.ServiceConfig{
+ Name: "webhook",
+ Type: "a2a",
+ TargetURL: "http://bearer:[email protected]:8081",
+ Ingress: &api.IngressConfig{AuthMode: "passthrough"},
+ }); err == nil {
+ t.Fatal("buildRegisterRequest accepted passthrough + inline target_url credential")
+ }
+ if _, err := NewServiceFromRequest(&api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{
+ Name: "webhook",
+ Type: api.ServiceType_SERVICE_TYPE_A2A,
+ Ingress: &api.ServiceIngress{
+ AuthMode: api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH,
+ },
+ },
+ Backend: &api.RegisterServiceRequest_TargetUrl{
+ TargetUrl: "http://bearer:[email protected]:8081",
+ },
+ }); err == nil {
+ t.Fatal("NewServiceFromRequest accepted passthrough + inline backend credential")
+ }
+ })
+}
+
func TestExternalIngressHandler(t *testing.T) {
cpPub, cpPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
@@ -454,33 +608,11 @@ func TestExternalIngressHandler(t *testing.T) {
}
})
- t.Run("edge OIDC claims header evaluated identically against Datalog + local policy", func(t *testing.T) {
- claimsHdr, err := identity.MarshalIngressClaimsHeader(map[string][]string{
- api.FactUser: {"uid-alice"},
- api.FactEmail: {"[email protected]"},
- })
- if err != nil {
- t.Fatalf("MarshalIngressClaimsHeader: %v", err)
- }
-
- okReq := httptest.NewRequest(http.MethodPost, "http://mesh/a2a/assistant/", strings.NewReader(`{}`))
- okReq.RemoteAddr = routerPID.String()
- okReq.Header.Set(api.HeaderMeshBiscuit, routerB64)
- okReq.Header.Set(api.HeaderMeshIngressClaims, claimsHdr)
- okRec := httptest.NewRecorder()
- h.ServeHTTP(okRec, okReq)
- if okRec.Code != http.StatusOK {
- t.Fatalf("OIDC claims status = %d, want 200: %s", okRec.Code, okRec.Body.String())
- }
- if got := capturedHeaders.Get(api.HeaderMeshPrincipal); got != "[email protected]" {
- t.Errorf("X-Mesh-Principal = %q, want [email protected]", got)
- }
-
- // Local nodeConfig policy denies /admin
+ t.Run("local nodeConfig policy denies /admin on edge delegated biscuit", func(t *testing.T) {
adminReq := httptest.NewRequest(http.MethodPost, "http://mesh/a2a/assistant/admin", strings.NewReader(`{}`))
adminReq.RemoteAddr = routerPID.String()
adminReq.Header.Set(api.HeaderMeshBiscuit, routerB64)
- adminReq.Header.Set(api.HeaderMeshIngressClaims, claimsHdr)
+ adminReq.Header.Set(api.HeaderMeshIngressCallerBiscuit, delegatedAliceB64)
adminRec := httptest.NewRecorder()
h.ServeHTTP(adminRec, adminReq)
if adminRec.Code != http.StatusForbidden {
@@ -488,6 +620,27 @@ func TestExternalIngressHandler(t *testing.T) {
}
})
+ t.Run("uninitialized service registry returns 503 and increments invalid counter", func(t *testing.T) {
+ uninitNode := &AgentMeshNode{
+ config: Options{PrivKey: servingPriv},
+ trustedKeys: []TrustedKey{{Key: cpPub, ReceivedAt: time.Now()}},
+ BiscuitTimeout: time.Second,
+ }
+ before := counterValue(t, externalIngressRequestsTotal.WithLabelValues("unknown", externalIngressOutcomeInvalid))
+ req := httptest.NewRequest(http.MethodPost, "http://mesh/a2a/assistant/", strings.NewReader(`{}`))
+ req.RemoteAddr = routerPID.String()
+ req.Header.Set(api.HeaderMeshBiscuit, routerB64)
+ rec := httptest.NewRecorder()
+ uninitNode.externalIngressHandler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want 503: %s", rec.Code, rec.Body.String())
+ }
+ after := counterValue(t, externalIngressRequestsTotal.WithLabelValues("unknown", externalIngressOutcomeInvalid))
+ if after != before+1 {
+ t.Errorf("invalid counter = %v, want %v", after, before+1)
+ }
+ })
+
t.Run("MCP tool-level TAR enforced on external edge ingress", func(t *testing.T) {
allowBody := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_file"}}`
allowReq := httptest.NewRequest(http.MethodPost, "http://mesh/mcp/files/", bytes.NewBufferString(allowBody))
diff --git a/internal/node/oidc.go b/internal/node/oidc.go
index 455e97c9..d485ec5d 100644
--- a/internal/node/oidc.go
+++ b/internal/node/oidc.go
@@ -178,18 +178,12 @@ func (n *AgentMeshNode) InteractiveLoginWithMode(ctx context.Context, authURL, t
break
}
}
- if listener == nil && deviceAuthURL == "" {
- // When no device flow fallback is available (or AuthModeBrowser
- // explicitly disabled it), try an RFC 8252 ephemeral loopback port
- // before degrading to deprecated out-of-band paste.
- listener, err = net.Listen("tcp", "127.0.0.1:0")
- }
if listener == nil {
if deviceAuthURL != "" {
- logger.Warnf("Could not bind local OIDC listener (ports 13000-13002 busy: %v); falling back to device authorization flow.", err)
+ logger.Warn("Could not bind local OIDC listener (ports 13000-13002 busy); falling back to device authorization flow.")
return n.DeviceLogin(ctx, deviceAuthURL, tokenURL, clientID, audience, requestRefresh)
}
- logger.Warnf("Could not bind local OIDC listener (ports 13000-13002 busy: %v). Falling back to headless (OOB) authorization.", err)
+ logger.Warn("Could not bind local OIDC listener (ports 13000-13002 busy). Falling back to headless (OOB) authorization.")
isHeadless = true
redirectURI = "urn:ietf:wg:oauth:2.0:oob"
} else {
@@ -232,9 +226,6 @@ func (n *AgentMeshNode) InteractiveLoginWithMode(ctx context.Context, authURL, t
if !isHeadless {
if err := openBrowserFunc(targetURL); err != nil {
if deviceAuthURL != "" {
- if listener != nil {
- _ = listener.Close()
- }
logger.Warnf("Could not open a browser (%v); falling back to device authorization flow.", err)
return n.DeviceLogin(ctx, deviceAuthURL, tokenURL, clientID, audience, requestRefresh)
}
@@ -298,7 +289,6 @@ func (n *AgentMeshNode) InteractiveLoginWithMode(ctx context.Context, authURL, t
}
w.Header().Set("Content-Type", "text/html")
- w.Header().Set("Connection", "close")
_, _ = w.Write([]byte("<html><body><h1>Authorization successful!</h1><p>You can close this window and return to the CLI.</p></body></html>"))
select {
diff --git a/internal/node/service.go b/internal/node/service.go
index 205518ac..0600c02b 100644
--- a/internal/node/service.go
+++ b/internal/node/service.go
@@ -135,6 +135,17 @@ func NewServiceFromRequest(req *api.RegisterServiceRequest) (Service, error) {
if err := api.ValidateServiceIngress(info.GetType(), info.GetIngress()); err != nil {
return nil, fmt.Errorf("service %q: %w", info.GetName(), err)
}
+ if info.GetIngress() != nil && api.EffectiveIngressAuthMode(info.GetIngress()) == api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH {
+ if t, ok := req.Backend.(*api.RegisterServiceRequest_TargetUrl); ok {
+ bt, err := parseBackendTarget(t.TargetUrl)
+ if err != nil {
+ return nil, fmt.Errorf("service %q: %w", info.GetName(), err)
+ }
+ if bt.auth != "" {
+ return nil, fmt.Errorf("service %q: ingress auth_mode %q cannot be combined with a backend credential (would expose backend credential without caller authentication)", info.GetName(), api.IngressAuthModeStringPassthrough)
+ }
+ }
+ }
switch info.Type {
case api.ServiceType_SERVICE_TYPE_MCP:
return &MCPService{baseService: baseService{info: info, backend: req.Backend}}, nil
@@ -160,6 +171,16 @@ func buildRegisterRequest(sCfg api.ServiceConfig) (*api.RegisterServiceRequest,
if err != nil {
return nil, fmt.Errorf("service %s: %w", sCfg.Name, err)
}
+ if ing != nil && api.EffectiveIngressAuthMode(ing) == api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH {
+ if sCfg.TargetAuthPath != "" {
+ return nil, fmt.Errorf("service %s: ingress auth_mode %q cannot be combined with target_auth_path (would expose backend credential without caller authentication)", sCfg.Name, api.IngressAuthModeStringPassthrough)
+ }
+ if sCfg.TargetURL != "" {
+ if bt, pErr := parseBackendTarget(sCfg.TargetURL); pErr == nil && bt.auth != "" {
+ return nil, fmt.Errorf("service %s: ingress auth_mode %q cannot be combined with an inline target_url credential (would expose backend credential without caller authentication)", sCfg.Name, api.IngressAuthModeStringPassthrough)
+ }
+ }
+ }
req := &api.RegisterServiceRequest{
Service: &api.ServiceInfo{
Type: sType,
diff --git a/internal/node/service_registry.go b/internal/node/service_registry.go
index 8f0d984d..2f8064a8 100644
--- a/internal/node/service_registry.go
+++ b/internal/node/service_registry.go
@@ -23,8 +23,30 @@ import (
"time"
"github.com/google/agentmesh/api"
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promauto"
)
+const (
+ provideFailureScopeIngress = "ingress"
+ provideFailureScopeName = "name"
+ provideFailureScopeType = "type"
+)
+
+var serviceProvideFailuresTotal = promauto.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "agentmesh_node_service_provide_failures_total",
+ Help: "Failed directory announcements for local services, by announcement scope",
+ },
+ []string{"scope"},
+)
+
+func init() {
+ for _, scope := range []string{provideFailureScopeIngress, provideFailureScopeName, provideFailureScopeType} {
+ serviceProvideFailuresTotal.WithLabelValues(scope)
+ }
+}
+
// directoryProvider is what ServiceRegistry asks of the directory: to
// announce a key and to withdraw it. Production wires this to the node's
// Directory; tests use a fake.
@@ -162,20 +184,11 @@ func (r *ServiceRegistry) Register(ctx context.Context, svc Service) error {
}
probeErr := advertisable(ctx, svc, r.backendProbeTimeout)
+ ingressAnnounced := false
if probeErr != nil {
logger.Warnf("[ServiceRegistry] Registered %s/%s but not advertising it: backend did not answer: %v", info.Type, info.Name, probeErr)
} else {
- nameCtx, nameCancel := context.WithTimeout(ctx, 5*time.Second)
- defer nameCancel()
- if err := r.provide(nameCtx, nameKey, serviceTarget(info), info.GetIngress()); err != nil {
- logger.Warnf("[ServiceRegistry] Announcing %s by name: %v", info.Name, err)
- }
-
- typeCtx, typeCancel := context.WithTimeout(ctx, 5*time.Second)
- defer typeCancel()
- if err := r.provide(typeCtx, typeKey, serviceTarget(info), nil); err != nil {
- logger.Warnf("[ServiceRegistry] Announcing %s by type: %v", info.Name, err)
- }
+ ingressAnnounced = r.announceServiceKeys(ctx, info, nameKey, typeKey)
}
r.mu.Lock()
@@ -191,7 +204,7 @@ func (r *ServiceRegistry) Register(ctx context.Context, svc Service) error {
if probeErr == nil {
logger.Infof("[ServiceRegistry] Registered and announced %s/%s", info.Type, info.Name)
- if info.GetIngress() != nil && r.onIngressRegistered != nil {
+ if ingressAnnounced && r.onIngressRegistered != nil {
r.onIngressRegistered(info)
}
} else if r.reprovideNow != nil {
@@ -232,13 +245,67 @@ func (r *ServiceRegistry) Unregister(ctx context.Context, name string) error {
return nil
}
-func (r *ServiceRegistry) provide(ctx context.Context, key []byte, service string, ingress *api.ServiceIngress) error {
- if ingress != nil {
+// announceServiceKeys publishes the service's name and type directory keys.
+// When an external ingress announcement is refused or fails, it logs an error,
+// increments agentmesh_node_service_provide_failures_total{scope="ingress"},
+// and immediately falls back to an internal-only announcement without ingress
+// metadata so in-mesh discovery continues working. It returns true iff the
+// service declared ingress and its ingress directory announcement succeeded.
+func (r *ServiceRegistry) announceServiceKeys(ctx context.Context, info *api.ServiceInfo, nameKey, typeKey []byte) bool {
+ target := serviceTarget(info)
+ ing := info.GetIngress()
+ ingressAnnounced := false
+
+ if ing != nil {
if ip, ok := r.dht.(ingressDirectoryProvider); ok {
- return ip.ProvideWithIngress(ctx, key, service, ingress)
+ ingCtx, ingCancel := context.WithTimeout(ctx, 5*time.Second)
+ err := ip.ProvideWithIngress(ingCtx, nameKey, target, ing)
+ ingCancel()
+ if err == nil {
+ ingressAnnounced = true
+ } else {
+ if ctx.Err() == nil {
+ serviceProvideFailuresTotal.WithLabelValues(provideFailureScopeIngress).Inc()
+ logger.Errorf("[ServiceRegistry] External ingress announcement for %s/%s failed; falling back to internal-only directory announcement: %v", info.Type, info.Name, err)
+ }
+ nameCtx, nameCancel := context.WithTimeout(ctx, 5*time.Second)
+ fallbackErr := r.dht.Provide(nameCtx, nameKey, target)
+ nameCancel()
+ if fallbackErr != nil && ctx.Err() == nil {
+ serviceProvideFailuresTotal.WithLabelValues(provideFailureScopeName).Inc()
+ logger.Errorf("[ServiceRegistry] Announcing %s/%s by name (internal fallback): %v", info.Type, info.Name, fallbackErr)
+ }
+ }
+ } else {
+ nameCtx, nameCancel := context.WithTimeout(ctx, 5*time.Second)
+ err := r.dht.Provide(nameCtx, nameKey, target)
+ nameCancel()
+ if err == nil {
+ ingressAnnounced = true
+ } else if ctx.Err() == nil {
+ serviceProvideFailuresTotal.WithLabelValues(provideFailureScopeName).Inc()
+ logger.Errorf("[ServiceRegistry] Announcing %s/%s by name: %v", info.Type, info.Name, err)
+ }
}
+ } else {
+ nameCtx, nameCancel := context.WithTimeout(ctx, 5*time.Second)
+ err := r.dht.Provide(nameCtx, nameKey, target)
+ nameCancel()
+ if err != nil && ctx.Err() == nil {
+ serviceProvideFailuresTotal.WithLabelValues(provideFailureScopeName).Inc()
+ logger.Errorf("[ServiceRegistry] Announcing %s/%s by name: %v", info.Type, info.Name, err)
+ }
+ }
+
+ typeCtx, typeCancel := context.WithTimeout(ctx, 5*time.Second)
+ typeErr := r.dht.Provide(typeCtx, typeKey, target)
+ typeCancel()
+ if typeErr != nil && ctx.Err() == nil {
+ serviceProvideFailuresTotal.WithLabelValues(provideFailureScopeType).Inc()
+ logger.Errorf("[ServiceRegistry] Announcing %s/%s by type: %v", info.Type, info.Name, typeErr)
}
- return r.dht.Provide(ctx, key, service)
+
+ return ingressAnnounced
}
// serviceTarget is a service as a record names it, "<type>://<name>".
@@ -385,21 +452,15 @@ Loop:
return
}
- for _, name := range []string{info.Name, ""} {
- key, err := api.ServiceKey(info.Type, name)
- if err != nil {
- continue
- }
- var ing *api.ServiceIngress
- if name != "" {
- ing = info.GetIngress()
- }
- provideCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- if err := r.provide(provideCtx, key, serviceTarget(info), ing); err != nil && ctx.Err() == nil {
- logger.Warnf("[ServiceRegistry] Announcing %s/%s again: %v", info.Type, info.Name, err)
- }
- cancel()
+ nameKey, err := api.ServiceKey(info.Type, info.Name)
+ if err != nil {
+ return
+ }
+ typeKey, err := api.ServiceKey(info.Type, "")
+ if err != nil {
+ return
}
+ r.announceServiceKeys(ctx, info, nameKey, typeKey)
}()
}
wg.Wait()
diff --git a/internal/router/config.go b/internal/router/config.go
index d9ca3f6d..dceb38de 100644
--- a/internal/router/config.go
+++ b/internal/router/config.go
@@ -134,11 +134,6 @@ type Options struct {
// non-loopback interface (for example behind a TLS-terminating L7 Gateway)
// and permits http:// in IngressURL on non-loopback hosts.
AllowInsecureIngressHTTP bool
- // OIDCIssuer and Audience optionally override the OIDC issuer and audience
- // learned from the control plane's GET /info when verifying OIDC JWTs on
- // INGRESS_AUTH_MODE_EDGE requests.
- OIDCIssuer string
- Audience string
// PublicControlPlaneURL optionally overrides ControlPlaneURL in external
// RFC 9728 and A2A OAuth discovery metadata when ControlPlaneURL is a
// cluster-internal or loopback address.
diff --git a/internal/router/directory.go b/internal/router/directory.go
index 2483f6a0..d50307c6 100644
--- a/internal/router/directory.go
+++ b/internal/router/directory.go
@@ -571,9 +571,12 @@ func (r *Router) findProviders(ctx context.Context, key []byte, limit int) []pro
directoryLookupsTotal.WithLabelValues(directoryResultOK).Inc()
var entries []providerEntry
for _, rec := range resp.GetProviders() {
- if entry, err := providerEntryOfRecord(rec); err == nil {
- entries = append(entries, entry)
+ entry, err := providerEntryOfRecord(rec)
+ if err != nil {
+ logger.Warnf("[Directory] Dropping invalid provider record %q from router %s: %v", rec.GetPeerId(), target, err)
+ continue
}
+ entries = append(entries, entry)
}
answers <- entries
}(target)
@@ -638,6 +641,9 @@ func providerEntryOfRecord(rec *api.PeerRecord) (providerEntry, error) {
if err != nil {
return providerEntry{}, err
}
+ if err := api.ValidatePeerRecordIngress(rec.GetIngress()); err != nil {
+ return providerEntry{}, err
+ }
return providerEntry{
info: peer.AddrInfo{ID: p, Addrs: addrs},
ingress: cloneServiceIngress(rec.GetIngress()),
@@ -671,7 +677,7 @@ func (r *Router) directoryFindPeer(ctx context.Context, remote peer.ID, q *api.D
return nil, err
}
for _, rec := range records {
- if rec.GetPeerId() == p.String() {
+ if recPID, decErr := peer.Decode(rec.GetPeerId()); decErr == nil && recPID == p {
return &api.DirectoryResponse{Peer: rec}, nil
}
}
diff --git a/internal/router/ingress.go b/internal/router/ingress.go
index d764a599..d4f369d8 100644
--- a/internal/router/ingress.go
+++ b/internal/router/ingress.go
@@ -15,7 +15,6 @@
package router
import (
- "bytes"
"context"
"crypto/sha256"
"encoding/base64"
@@ -33,7 +32,7 @@ import (
"time"
"github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/coreos/go-oidc/v3/oidc"
+ "github.com/eclipse-biscuit/biscuit-go/v2"
"github.com/google/agentmesh/api"
"github.com/google/agentmesh/internal/identity"
gostream "github.com/libp2p/go-libp2p-gostream"
@@ -57,9 +56,9 @@ const (
ingressOutcomeRateLimited = "rate_limited"
ingressOutcomeBadGateway = "bad_gateway"
ingressOutcomeInvalid = "invalid"
+ ingressOutcomeUnavailable = "unavailable"
maxIngressBodyBytes = 32 << 20
- maxIngressMCPBodyBytes = 4 << 20
maxIngressCardBodyBytes = 1 << 20
a2aAgentCardSubpath = ".well-known/agent-card.json"
ingressDialTimeout = 10 * time.Second
@@ -83,6 +82,7 @@ func init() {
ingressOutcomeRateLimited,
ingressOutcomeBadGateway,
ingressOutcomeInvalid,
+ ingressOutcomeUnavailable,
} {
routerIngressRequestsTotal.WithLabelValues(mode, outcome)
}
@@ -150,7 +150,7 @@ func (r *Router) IngressHandler() http.Handler {
},
MaxIdleConnsPerHost: 16,
IdleConnTimeout: 60 * time.Second,
- ResponseHeaderTimeout: 60 * time.Second,
+ ResponseHeaderTimeout: 5 * time.Minute,
}
mux := http.NewServeMux()
@@ -167,125 +167,91 @@ func (r *Router) IngressHandler() http.Handler {
return mux
}
+func isUnspecifiedBindHost(host string) bool {
+ h := strings.Trim(strings.TrimSpace(host), "[]")
+ if h == "" {
+ return true
+ }
+ ip := net.ParseIP(h)
+ return ip != nil && ip.IsUnspecified()
+}
+
+func (r *Router) singlePortWSPort() string {
+ if r.Host == nil || r.Host.Network() == nil {
+ return ""
+ }
+ for _, a := range r.Host.Network().ListenAddresses() {
+ if _, err := a.ValueForProtocol(multiaddr.P_WS); err != nil {
+ continue
+ }
+ if port, err := a.ValueForProtocol(multiaddr.P_TCP); err == nil {
+ return port
+ }
+ }
+ return ""
+}
+
func (r *Router) leasedIngressURL() string {
if configured := strings.TrimSuffix(strings.TrimSpace(r.config.IngressURL), "/"); configured != "" {
return configured
}
if r.ingressAddr != nil {
- scheme := "http"
- if r.config.IngressTLSCertPath != "" {
- scheme = "https"
+ addrStr := r.ingressAddr.String()
+ host, _, err := net.SplitHostPort(addrStr)
+ if err == nil && !isUnspecifiedBindHost(host) {
+ scheme := "http"
+ if r.config.IngressTLSCertPath != "" {
+ scheme = "https"
+ }
+ return scheme + "://" + addrStr + "/ingress"
}
- return scheme + "://" + r.ingressAddr.String() + "/ingress"
+ return ""
}
- if r.config.AdvertiseSinglePortIngress && r.Host != nil && r.Host.Network() != nil {
+ if r.config.AdvertiseSinglePortIngress {
host := strings.TrimSpace(r.config.SinglePortBindHost)
- if host == "" {
- host = "0.0.0.0"
- }
- for _, a := range r.Host.Network().ListenAddresses() {
- if _, err := a.ValueForProtocol(multiaddr.P_WS); err != nil {
- continue
- }
- port, err := a.ValueForProtocol(multiaddr.P_TCP)
- if err != nil {
- continue
+ if !isUnspecifiedBindHost(host) {
+ if port := r.singlePortWSPort(); port != "" {
+ return "http://" + net.JoinHostPort(host, port) + "/ingress"
}
- return "http://" + net.JoinHostPort(host, port) + "/ingress"
}
}
return ""
}
-func (r *Router) effectiveIngressBaseURL(req *http.Request) string {
+// effectiveIngressBaseURL resolves the canonical external /ingress base URL
+// from operator configuration or a non-unspecified bound listener, never from
+// the untrusted HTTP Host header.
+func (r *Router) effectiveIngressBaseURL() string {
if leased := r.leasedIngressURL(); leased != "" {
return leased
}
- scheme := "http"
- if r.config.IngressTLSCertPath != "" || (req != nil && req.TLS != nil) {
- scheme = "https"
+ if pub := strings.TrimSuffix(strings.TrimSpace(r.config.PublicControlPlaneURL), "/"); pub != "" {
+ return pub + "/ingress"
}
- if req != nil && req.Host != "" {
- return scheme + "://" + req.Host + "/ingress"
+ if r.config.AdvertiseSinglePortIngress {
+ if port := r.singlePortWSPort(); port != "" {
+ return "http://" + net.JoinHostPort("127.0.0.1", port) + "/ingress"
+ }
}
- return strings.TrimSuffix(r.config.ControlPlaneURL, "/") + "/ingress"
+ return strings.TrimSuffix(strings.TrimSpace(r.config.ControlPlaneURL), "/") + "/ingress"
}
-func (r *Router) effectivePublicControlPlaneURL(req *http.Request) string {
+func (r *Router) effectivePublicControlPlaneURL() string {
if pub := strings.TrimSuffix(strings.TrimSpace(r.config.PublicControlPlaneURL), "/"); pub != "" {
return pub
}
if r.config.AdvertiseSinglePortIngress || (r.config.IngressURL != "" && r.config.AllowInsecureControlPlane) {
- return strings.TrimSuffix(r.effectiveIngressBaseURL(req), "/ingress")
+ return strings.TrimSuffix(r.effectiveIngressBaseURL(), "/ingress")
}
return strings.TrimSuffix(strings.TrimSpace(r.config.ControlPlaneURL), "/")
}
-func (r *Router) effectiveOIDCIssuer() string {
- if configured := strings.TrimSpace(r.config.OIDCIssuer); configured != "" {
- return strings.TrimSuffix(configured, "/")
- }
- if synced := r.syncedOIDCIssuer.Load(); synced != nil && *synced != "" {
- return strings.TrimSuffix(*synced, "/")
- }
- return ""
-}
-
-func (r *Router) allowedAudiences() []string {
- var out []string
- add := func(s string) {
- s = strings.TrimSpace(s)
- if s == "" {
- return
- }
- for _, existing := range out {
- if existing == s {
- return
- }
- }
- out = append(out, s)
- }
- add(r.config.Audience)
- if synced := r.syncedAudience.Load(); synced != nil {
- add(*synced)
- }
- add(api.DefaultAudience)
- return out
-}
-
-func (r *Router) resolveOIDCProviders(ctx context.Context) map[string]*oidc.Provider {
- iss := r.effectiveOIDCIssuer()
- if iss == "" {
- return nil
- }
- r.oidcMu.Lock()
- defer r.oidcMu.Unlock()
- if r.oidcProviders == nil {
- r.oidcProviders = make(map[string]*oidc.Provider)
- }
- if p, ok := r.oidcProviders[iss]; ok {
- return map[string]*oidc.Provider{iss: p}
- }
- discCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
- p, err := oidc.NewProvider(discCtx, iss)
- if err != nil {
- logger.Warnf("[Ingress] OIDC discovery for %s failed: %v", iss, err)
- return nil
- }
- r.oidcProviders[iss] = p
- return map[string]*oidc.Provider{iss: p}
-}
-
-func (r *Router) handleIngressProtectedResourceMetadata(w http.ResponseWriter, req *http.Request) {
- base := r.effectiveIngressBaseURL(req)
+func (r *Router) handleIngressProtectedResourceMetadata(w http.ResponseWriter, _ *http.Request) {
+ base := r.effectiveIngressBaseURL()
var servers []string
- if cp := r.effectivePublicControlPlaneURL(req); cp != "" {
+ if cp := r.effectivePublicControlPlaneURL(); cp != "" {
servers = append(servers, cp)
}
- if iss := r.effectiveOIDCIssuer(); iss != "" && (len(servers) == 0 || servers[0] != iss) {
- servers = append(servers, iss)
- }
doc := api.OAuthProtectedResourceMetadata{
Resource: base,
AuthorizationServers: servers,
@@ -294,6 +260,8 @@ func (r *Router) handleIngressProtectedResourceMetadata(w http.ResponseWriter, r
}
out, err := json.Marshal(doc)
if err != nil {
+ routerIngressRequestsTotal.WithLabelValues(ingressModeMetadata, ingressOutcomeBadGateway).Inc()
+ logger.Errorf("[Ingress] Failed to marshal protected resource metadata: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
@@ -303,31 +271,37 @@ func (r *Router) handleIngressProtectedResourceMetadata(w http.ResponseWriter, r
_, _ = w.Write(out)
}
-func (r *Router) writeIngressUnauthorized(w http.ResponseWriter, req *http.Request, modeMetric, message string) {
+func (r *Router) writeIngressUnauthorized(w http.ResponseWriter, modeMetric, message string) {
routerIngressRequestsTotal.WithLabelValues(modeMetric, ingressOutcomeUnauthenticated).Inc()
- metaURL := r.effectiveIngressBaseURL(req) + "/.well-known/oauth-protected-resource"
+ metaURL := r.effectiveIngressBaseURL() + "/.well-known/oauth-protected-resource"
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer resource_metadata=%q`, metaURL))
http.Error(w, message, http.StatusUnauthorized)
}
+func biscuitRateLimitKey(b *biscuit.Biscuit, raw []byte) string {
+ if b != nil {
+ if ids := b.RevocationIds(); len(ids) > 0 && len(ids[0]) > 0 {
+ return "biscuit:" + base64.RawURLEncoding.EncodeToString(ids[0])
+ }
+ }
+ sum := sha256.Sum256(raw)
+ return "biscuit:" + hex.EncodeToString(sum[:16])
+}
+
func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request, transport http.RoundTripper) {
if !r.isReady.Load() || r.shutdown.Load() {
+ routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeUnavailable).Inc()
+ logger.Warn("[Ingress] Router is not ready or is shutting down")
http.Error(w, "Router is not ready", http.StatusServiceUnavailable)
return
}
clientIP := clientIPFromRemoteAddr(req.RemoteAddr)
- if r.ingressLimiter != nil && !r.ingressLimiter.Allow(clientIP) {
- routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeRateLimited).Inc()
- logger.Warnf("[Ingress] Rate limit exceeded for client %s", clientIP)
- http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
- return
- }
-
req.Body = http.MaxBytesReader(w, req.Body, maxIngressBodyBytes)
if hasDotSegment(req.URL.Path) {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeInvalid).Inc()
+ logger.Debugf("[Ingress] Rejecting dot-segment path from %s", clientIP)
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
@@ -336,6 +310,7 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request,
parts := strings.SplitN(trimmed, "/", 4)
if len(parts) < 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeInvalid).Inc()
+ logger.Debugf("[Ingress] Rejecting malformed ingress path from %s", clientIP)
http.Error(w, "Invalid ingress path: expected /ingress/<peer_id>/<service_type>/<service_name>", http.StatusBadRequest)
return
}
@@ -351,22 +326,26 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request,
targetPeer, err := peer.Decode(peerIDStr)
if err != nil {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeInvalid).Inc()
+ logger.Debugf("[Ingress] Rejecting invalid peer ID from %s: %v", clientIP, err)
http.Error(w, "Invalid peer ID", http.StatusBadRequest)
return
}
svcType, err := api.ParseServiceType(serviceTypeStr)
if err != nil {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeInvalid).Inc()
+ logger.Debugf("[Ingress] Rejecting invalid service type %q from %s", serviceTypeStr, clientIP)
http.Error(w, "Invalid service type", http.StatusBadRequest)
return
}
if !api.IsInboundServiceType(svcType) {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeNotFound).Inc()
+ logger.Debugf("[Ingress] Rejecting non-inbound service type %q from %s", serviceTypeStr, clientIP)
http.Error(w, "Service not found", http.StatusNotFound)
return
}
if err := api.ValidateServiceFormat(serviceTypeStr + "://" + serviceName); err != nil {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeInvalid).Inc()
+ logger.Debugf("[Ingress] Rejecting invalid service name from %s: %v", clientIP, err)
http.Error(w, "Invalid service name", http.StatusBadRequest)
return
}
@@ -380,6 +359,7 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request,
key, err := api.ServiceKey(svcType, serviceName)
if err != nil {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeInvalid).Inc()
+ logger.Debugf("[Ingress] Invalid service key for %s://%s: %v", serviceTypeStr, serviceName, err)
http.Error(w, "Invalid service key", http.StatusBadRequest)
return
}
@@ -392,13 +372,19 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request,
}
var providerRec *api.PeerRecord
for _, rec := range providers {
- if rec.GetPeerId() == targetPeer.String() {
+ recPID, decErr := peer.Decode(rec.GetPeerId())
+ if decErr != nil {
+ logger.Warnf("[Ingress] Ignoring provider record with invalid peer ID %q: %v", rec.GetPeerId(), decErr)
+ continue
+ }
+ if recPID == targetPeer {
providerRec = rec
break
}
}
if providerRec == nil || providerRec.GetIngress() == nil {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeNotFound).Inc()
+ logger.Debugf("[Ingress] No ingress record found for %s (%s://%s)", targetPeer, serviceTypeStr, serviceName)
http.Error(w, "Service not found", http.StatusNotFound)
return
}
@@ -408,32 +394,17 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request,
modeStr, err := api.IngressAuthModeToString(effectiveMode)
if err != nil {
routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeDeny).Inc()
+ logger.Warnf("[Ingress] Unsupported ingress auth mode %v for %s", effectiveMode, targetPeer)
http.Error(w, "Unsupported ingress auth mode", http.StatusForbidden)
return
}
- cred, err := r.ensureProviderAuthenticated(req.Context(), targetPeer, providerRec.GetAddrs())
- if err != nil {
- routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
- logger.Warnf("[Ingress] Could not reach or authenticate provider %s for %s://%s: %v", targetPeer, serviceTypeStr, serviceName, err)
- http.Error(w, "Bad Gateway: provider unreachable", http.StatusBadGateway)
- return
- }
-
- // Re-check the provider's role ceiling against current mesh policy so a
- // revoked role grant takes effect at the next sync without waiting for TTL.
- if err := r.requireIngress(targetPeer, svcType, serviceName, effectiveMode); err != nil {
- routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeDeny).Inc()
- logger.Warnf("[Ingress] Provider %s no longer authorized to expose %s://%s (%s): %v", targetPeer, serviceTypeStr, serviceName, modeStr, err)
- http.Error(w, "Forbidden", http.StatusForbidden)
- return
- }
-
r.keysMu.RLock()
routerBiscuit := r.credential.biscuit
r.keysMu.RUnlock()
if len(routerBiscuit) == 0 {
- routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeUnavailable).Inc()
+ logger.Warn("[Ingress] Router credential unavailable")
http.Error(w, "Router credential unavailable", http.StatusServiceUnavailable)
return
}
@@ -441,114 +412,74 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request,
targetURI := serviceTypeStr + "://" + serviceName
backendPath := "/" + subpath
-
- // Unauthenticated GET discovery of A2A AgentCard (both well-known path and
- // bare service root GET for resolvers such as a2a-go).
- if svcType == api.ServiceType_SERVICE_TYPE_A2A &&
+ isAgentCardGet := svcType == api.ServiceType_SERVICE_TYPE_A2A &&
req.Method == http.MethodGet &&
- (subpath == "" || subpath == a2aAgentCardSubpath) {
- r.serveIngressAgentCard(w, req, transport, targetPeer, serviceName, effectiveMode, modeStr, routerBiscuitHeader)
- return
- }
-
- if effectiveMode == api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH {
- routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeAllow).Inc()
- logger.Infow("Border Crossing",
- "direction", "inbound",
- "protocol", string(api.IngressProtocolID),
- "mode", api.IngressAuthModeStringPassthrough,
- "client_ip", clientIP,
- "target_peer_id", targetPeer.String(),
- "target", targetURI,
- "method", req.Method,
- "path", backendPath,
- )
- r.forwardIngressHTTP(w, req, transport, targetPeer, serviceTypeStr, serviceName, subpath, hasTrailingOrSubpath, routerBiscuitHeader, api.IngressAuthModeStringPassthrough, "", "")
- return
- }
-
- // INGRESS_AUTH_MODE_EDGE: authenticate Bearer token and evaluate policy.
- bearerToken, ok := extractBearerToken(req.Header.Get("Authorization"))
- if !ok {
- r.writeIngressUnauthorized(w, req, modeStr, "Missing or invalid Authorization: Bearer header")
- return
- }
-
- targetFacts, err := identity.TargetFactsFromBiscuit(cred.biscuit, r.getTrustedPublicKeys(), r.config.BiscuitTimeout)
- if err != nil {
- routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
- logger.Warnf("[Ingress] Failed to extract target facts for %s: %v", targetPeer, err)
- http.Error(w, "Bad Gateway", http.StatusBadGateway)
- return
- }
-
- evalParams := identity.IngressEvalParams{
- ServiceType: serviceTypeStr,
- ServiceName: serviceName,
- Method: req.Method,
- Path: backendPath,
- TargetFacts: targetFacts,
- EnforceTargetCheck: true,
- MeshPolicyRules: r.meshPolicyRules(),
- Allow: ing.GetAllow(),
- Timeout: r.config.BiscuitTimeout,
- }
-
- if svcType == api.ServiceType_SERVICE_TYPE_MCP {
- mcpTool, allowInit, bodyErr := inspectRouterMCPBody(req)
- if bodyErr != nil {
- routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeInvalid).Inc()
- http.Error(w, bodyErr.Error(), http.StatusRequestEntityTooLarge)
- return
- }
- evalParams.MCPTool = mcpTool
- evalParams.AllowMCPStreamInit = allowInit
- }
+ (subpath == "" || subpath == a2aAgentCardSubpath)
- var callerRes *identity.IngressCallerResult
- var callerBiscuitHdr, callerClaimsHdr string
+ var (
+ verifiedCaller *identity.VerifiedBiscuitClaims
+ callerBiscuitHdr string
+ evalParams identity.IngressEvalParams
+ )
- if isCompactJWT(bearerToken) {
- providersMap := r.resolveOIDCProviders(req.Context())
- if len(providersMap) == 0 {
- r.writeIngressUnauthorized(w, req, modeStr, "No OIDC provider configured for JWT verification")
- return
- }
- jwtClaims, _, err := identity.VerifyJWT(req.Context(), bearerToken, r.allowedAudiences(), providersMap)
- if err != nil {
- logger.Warnf("[Ingress] OIDC JWT verification failed from %s for %s: %v", clientIP, targetURI, err)
- r.writeIngressUnauthorized(w, req, modeStr, "Invalid Bearer token")
- return
- }
- oidcFacts := identity.OIDCFactsFromJWTClaims(map[string]any(jwtClaims))
- callerRes, err = identity.AuthorizeIngressOIDCFacts(oidcFacts, evalParams)
- if err != nil {
- routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeDeny).Inc()
- logger.Warnf("[Ingress] Edge AuthZ denied OIDC caller from %s for %s: %v", clientIP, targetURI, err)
- http.Error(w, "Forbidden", http.StatusForbidden)
+ // On EDGE ingress (except unauthenticated A2A AgentCard GET), verify the
+ // caller's Biscuit, revocation state, actor bans, rate limit, TAR rules, and
+ // ServiceIngress.allow locally BEFORE dialing or authenticating the provider.
+ if effectiveMode == api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE && !isAgentCardGet {
+ bearerToken, ok := extractBearerToken(req.Header.Get("Authorization"))
+ if !ok {
+ if r.ingressLimiter != nil && !r.ingressLimiter.Allow("unauth:"+clientIP) {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeRateLimited).Inc()
+ logger.Warnf("[Ingress] Rate limit exceeded for unauthenticated client %s", clientIP)
+ http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
+ return
+ }
+ r.writeIngressUnauthorized(w, modeStr, "Missing or invalid Authorization: Bearer header")
return
}
- callerClaimsHdr, err = identity.MarshalIngressClaimsHeader(oidcFacts)
- if err != nil {
- routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
- http.Error(w, "Internal Server Error", http.StatusInternalServerError)
+ if isCompactJWT(bearerToken) {
+ if r.ingressLimiter != nil && !r.ingressLimiter.Allow("unauth:"+clientIP) {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeRateLimited).Inc()
+ logger.Warnf("[Ingress] Rate limit exceeded for JWT client %s", clientIP)
+ http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
+ return
+ }
+ logger.Debugf("[Ingress] Rejecting raw JWT on edge ingress from %s for %s; exchange at /oauth/token required", clientIP, targetURI)
+ r.writeIngressUnauthorized(w, modeStr, "Mesh Biscuit required; exchange platform JWT at /oauth/token")
return
}
- } else {
rawCaller, err := identity.DecodeBase64Biscuit(bearerToken)
if err != nil {
- r.writeIngressUnauthorized(w, req, modeStr, "Invalid Bearer token encoding")
+ if r.ingressLimiter != nil && !r.ingressLimiter.Allow("unauth:"+clientIP) {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeRateLimited).Inc()
+ logger.Warnf("[Ingress] Rate limit exceeded for invalid token encoding from %s", clientIP)
+ http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
+ return
+ }
+ r.writeIngressUnauthorized(w, modeStr, "Invalid Bearer token encoding")
return
}
verified, err := identity.InspectVerifiedBiscuit(rawCaller, r.getTrustedPublicKeys(), r.config.BiscuitTimeout)
if err != nil {
+ if r.ingressLimiter != nil && !r.ingressLimiter.Allow("unauth:"+clientIP) {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeRateLimited).Inc()
+ logger.Warnf("[Ingress] Rate limit exceeded for failed biscuit verification from %s", clientIP)
+ http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
+ return
+ }
logger.Warnf("[Ingress] Biscuit verification failed from %s for %s: %v", clientIP, targetURI, err)
- r.writeIngressUnauthorized(w, req, modeStr, "Invalid Bearer token")
+ r.writeIngressUnauthorized(w, modeStr, "Invalid Bearer token")
+ return
+ }
+ if r.ingressLimiter != nil && !r.ingressLimiter.Allow(biscuitRateLimitKey(verified.Biscuit, rawCaller)) {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeRateLimited).Inc()
+ logger.Warnf("[Ingress] Rate limit exceeded for caller %s from %s", verified.Principal(), clientIP)
+ http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
return
}
if r.isBiscuitRevoked(verified.Biscuit) {
logger.Warnf("[Ingress] Refusing revoked Biscuit from %s for %s", clientIP, targetURI)
- r.writeIngressUnauthorized(w, req, modeStr, "Token has been revoked")
+ r.writeIngressUnauthorized(w, modeStr, "Token has been revoked")
return
}
for _, pidStr := range []string{verified.NodePeerID, verified.ActorNodePeerID, verified.ClientPeerID} {
@@ -564,14 +495,101 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request,
}
}
}
- callerRes, err = identity.AuthorizeIngressDelegatedBiscuit(verified, evalParams)
- if err != nil {
+
+ evalParams = identity.IngressEvalParams{
+ ServiceType: serviceTypeStr,
+ ServiceName: serviceName,
+ Method: req.Method,
+ Path: backendPath,
+ EnforceTargetCheck: true,
+ MeshPolicyRules: r.meshPolicyRules(),
+ Allow: ing.GetAllow(),
+ Timeout: r.config.BiscuitTimeout,
+ }
+ if svcType == api.ServiceType_SERVICE_TYPE_MCP {
+ mcpTool, allowInit, bodyErr := api.InspectMCPHTTPRequestBody(req, api.DefaultMaxMCPBodyInspectBytes)
+ if bodyErr != nil {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeInvalid).Inc()
+ logger.Warnf("[Ingress] Oversized or unreadable MCP body from %s for %s: %v", clientIP, targetURI, bodyErr)
+ http.Error(w, bodyErr.Error(), http.StatusRequestEntityTooLarge)
+ return
+ }
+ evalParams.MCPTool = mcpTool
+ evalParams.AllowMCPStreamInit = allowInit
+ }
+ if _, err := identity.ValidateIngressCallerPreDial(verified, evalParams); err != nil {
routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeDeny).Inc()
- logger.Warnf("[Ingress] Edge AuthZ denied Biscuit caller (%s) from %s for %s: %v", verified.Principal(), clientIP, targetURI, err)
+ logger.Warnf("[Ingress] Pre-dial AuthZ denied caller (%s) from %s for %s: %v", verified.Principal(), clientIP, targetURI, err)
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
+ verifiedCaller = verified
callerBiscuitHdr = base64.StdEncoding.EncodeToString(rawCaller)
+ } else if r.ingressLimiter != nil {
+ anonKey := "anon:" + clientIP + ":" + targetPeer.String()
+ if !r.ingressLimiter.Allow(anonKey) {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeRateLimited).Inc()
+ logger.Warnf("[Ingress] Rate limit exceeded for client %s to target %s", clientIP, targetPeer)
+ http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
+ return
+ }
+ }
+
+ cred, err := r.ensureProviderAuthenticated(req.Context(), targetPeer, providerRec.GetAddrs())
+ if err != nil {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
+ logger.Warnf("[Ingress] Could not reach or authenticate provider %s for %s://%s: %v", targetPeer, serviceTypeStr, serviceName, err)
+ http.Error(w, "Bad Gateway: provider unreachable", http.StatusBadGateway)
+ return
+ }
+
+ // Re-check the provider's role ceiling against current mesh policy so a
+ // revoked role grant takes effect at the next sync without waiting for TTL.
+ if err := r.requireIngress(targetPeer, svcType, serviceName, effectiveMode); err != nil {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeDeny).Inc()
+ logger.Warnf("[Ingress] Provider %s no longer authorized to expose %s://%s (%s): %v", targetPeer, serviceTypeStr, serviceName, modeStr, err)
+ http.Error(w, "Forbidden", http.StatusForbidden)
+ return
+ }
+
+ // Unauthenticated GET discovery of A2A AgentCard (both well-known path and
+ // bare service root GET for resolvers such as a2a-go).
+ if isAgentCardGet {
+ r.serveIngressAgentCard(w, req, transport, targetPeer, serviceName, effectiveMode, modeStr, routerBiscuitHeader)
+ return
+ }
+
+ if effectiveMode == api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeAllow).Inc()
+ logger.Infow("Border Crossing",
+ "direction", "inbound",
+ "protocol", string(api.IngressProtocolID),
+ "mode", api.IngressAuthModeStringPassthrough,
+ "client_ip", clientIP,
+ "target_peer_id", targetPeer.String(),
+ "target", targetURI,
+ "method", req.Method,
+ "path", backendPath,
+ )
+ r.forwardIngressHTTP(w, req, transport, targetPeer, serviceTypeStr, serviceName, subpath, hasTrailingOrSubpath, routerBiscuitHeader, api.IngressAuthModeStringPassthrough, "")
+ return
+ }
+
+ targetFacts, err := identity.TargetFactsFromBiscuit(cred.biscuit, r.getTrustedPublicKeys(), r.config.BiscuitTimeout)
+ if err != nil {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
+ logger.Warnf("[Ingress] Failed to extract target facts for %s: %v", targetPeer, err)
+ http.Error(w, "Bad Gateway", http.StatusBadGateway)
+ return
+ }
+ evalParams.TargetFacts = targetFacts
+
+ callerRes, err := identity.AuthorizeIngressDelegatedBiscuit(verifiedCaller, evalParams)
+ if err != nil {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeDeny).Inc()
+ logger.Warnf("[Ingress] Edge AuthZ denied Biscuit caller (%s) from %s for %s: %v", verifiedCaller.Principal(), clientIP, targetURI, err)
+ http.Error(w, "Forbidden", http.StatusForbidden)
+ return
}
routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeAllow).Inc()
@@ -589,7 +607,7 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request,
"path", backendPath,
)
- r.forwardIngressHTTP(w, req, transport, targetPeer, serviceTypeStr, serviceName, subpath, hasTrailingOrSubpath, routerBiscuitHeader, api.IngressAuthModeStringEdge, callerBiscuitHdr, callerClaimsHdr)
+ r.forwardIngressHTTP(w, req, transport, targetPeer, serviceTypeStr, serviceName, subpath, hasTrailingOrSubpath, routerBiscuitHeader, api.IngressAuthModeStringEdge, callerBiscuitHdr)
}
func (r *Router) forwardIngressHTTP(
@@ -599,7 +617,7 @@ func (r *Router) forwardIngressHTTP(
targetPeer peer.ID,
serviceTypeStr, serviceName, subpath string,
hasTrailingOrSubpath bool,
- routerBiscuitHeader, modeStr, callerBiscuitHdr, callerClaimsHdr string,
+ routerBiscuitHeader, modeStr, callerBiscuitHdr string,
) {
upstreamPath := "/" + serviceTypeStr + "/" + serviceName
if hasTrailingOrSubpath {
@@ -618,20 +636,18 @@ func (r *Router) forwardIngressHTTP(
pr.Out.URL.RawQuery = pr.In.URL.RawQuery
pr.Out.Host = targetPeer.String()
- sanitizeRouterOutboundHeaders(pr.Out.Header, stripAuth)
+ api.SanitizeExternalIngressHeaders(pr.Out.Header, stripAuth)
pr.Out.Header.Set(api.HeaderMeshBiscuit, routerBiscuitHeader)
pr.Out.Header.Set(api.HeaderMeshIngress, modeStr)
if callerBiscuitHdr != "" {
pr.Out.Header.Set(api.HeaderMeshIngressCallerBiscuit, callerBiscuitHdr)
}
- if callerClaimsHdr != "" {
- pr.Out.Header.Set(api.HeaderMeshIngressClaims, callerClaimsHdr)
- }
},
ErrorHandler: func(rw http.ResponseWriter, _ *http.Request, err error) {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeInvalid).Inc()
+ logger.Warnf("[Ingress] Request body to %s (%s://%s) exceeded size limit", targetPeer, serviceTypeStr, serviceName)
http.Error(rw, "Request Entity Too Large", http.StatusRequestEntityTooLarge)
return
}
@@ -657,6 +673,7 @@ func (r *Router) serveIngressAgentCard(
outReq, err := http.NewRequestWithContext(req.Context(), http.MethodGet, cardURL, nil)
if err != nil {
routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
+ logger.Errorf("[Ingress] Failed to build A2A agent card request for %s/%s: %v", targetPeer, serviceName, err)
http.Error(w, "Bad Gateway", http.StatusBadGateway)
return
}
@@ -679,6 +696,8 @@ func (r *Router) serveIngressAgentCard(
body := io.LimitReader(resp.Body, maxIngressCardBodyBytes)
if resp.StatusCode != http.StatusOK {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
+ logger.Warnf("[Ingress] Backend returned status %d for A2A agent card %s/%s", resp.StatusCode, targetPeer, serviceName)
if ct := resp.Header.Get("Content-Type"); ct != "" {
w.Header().Set("Content-Type", ct)
}
@@ -695,8 +714,8 @@ func (r *Router) serveIngressAgentCard(
return
}
- serviceBase := fmt.Sprintf("%s/%s/%s/%s", r.effectiveIngressBaseURL(req), targetPeer.String(), api.ServiceTypeStringA2A, serviceName)
- if err := r.rewriteAgentCardForIngress(&card, serviceBase, r.effectivePublicControlPlaneURL(req), effectiveMode); err != nil {
+ serviceBase := fmt.Sprintf("%s/%s/%s/%s", r.effectiveIngressBaseURL(), targetPeer.String(), api.ServiceTypeStringA2A, serviceName)
+ if err := r.rewriteAgentCardForIngress(&card, serviceBase, r.effectivePublicControlPlaneURL(), effectiveMode); err != nil {
routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
logger.Warnf("[Ingress] A2A agent card from %s/%s unusable on ingress: %v", targetPeer, serviceName, err)
http.Error(w, fmt.Sprintf("Bad Gateway: %v", err), http.StatusBadGateway)
@@ -705,6 +724,8 @@ func (r *Router) serveIngressAgentCard(
out, err := json.Marshal(&card)
if err != nil {
+ routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeBadGateway).Inc()
+ logger.Errorf("[Ingress] Failed to marshal AgentCard for %s/%s: %v", targetPeer, serviceName, err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
@@ -757,8 +778,8 @@ func (r *Router) rewriteAgentCardForIngress(card *a2a.AgentCard, serviceBase, pu
schemes := a2a.NamedSecuritySchemes{
"bearer": a2a.HTTPAuthSecurityScheme{
Scheme: "bearer",
- BearerFormat: "Biscuit or OIDC JWT",
- Description: "Agent Mesh delegated session Biscuit or trusted OIDC JWT",
+ BearerFormat: "Biscuit",
+ Description: "Agent Mesh delegated session or task Biscuit",
},
}
reqs := a2a.SecurityRequirementsOptions{
@@ -781,13 +802,6 @@ func (r *Router) rewriteAgentCardForIngress(card *a2a.AgentCard, serviceBase, pu
}
reqs = append(reqs, a2a.SecurityRequirements{"agentmesh_oauth2": {}})
}
- if iss := r.effectiveOIDCIssuer(); iss != "" {
- schemes["oidc"] = a2a.OpenIDConnectSecurityScheme{
- Description: "Mesh OIDC Identity Provider",
- OpenIDConnectURL: iss + "/.well-known/openid-configuration",
- }
- reqs = append(reqs, a2a.SecurityRequirements{"oidc": {}})
- }
card.SecuritySchemes = schemes
card.SecurityRequirements = reqs
}
@@ -875,6 +889,9 @@ func (r *Router) authenticateIngressMember(ctx context.Context, targetPeer peer.
if err != nil {
return memberCredential{}, fmt.Errorf("verify provider biscuit: %w", err)
}
+ if r.isBiscuitRevoked(b) {
+ return memberCredential{}, fmt.Errorf("provider %s biscuit is revoked", targetPeer)
+ }
cred := memberCredential{biscuit: b, key: verifyingKey}
r.admitPeer(targetPeer, expiry)
r.credentials.Store(targetPeer, cred)
@@ -887,10 +904,12 @@ func splitProviderAddrs(targetPeer peer.ID, rawAddrs []string) ([]multiaddr.Mult
for _, s := range rawAddrs {
ma, err := multiaddr.NewMultiaddr(s)
if err != nil {
+ logger.Debugf("[Ingress] Ignoring invalid provider multiaddr %q for %s: %v", s, targetPeer, err)
continue
}
tAddr, pid := peer.SplitAddr(ma)
if pid != "" && pid != targetPeer {
+ logger.Debugf("[Ingress] Ignoring provider multiaddr %q naming %s instead of %s", s, pid, targetPeer)
continue
}
if tAddr == nil {
@@ -908,18 +927,6 @@ func splitProviderAddrs(targetPeer peer.ID, rawAddrs []string) ([]multiaddr.Mult
return transport, relays
}
-func sanitizeRouterOutboundHeaders(h http.Header, stripAuthorization bool) {
- for name := range h {
- lower := strings.ToLower(name)
- if lower == "cookie" ||
- (stripAuthorization && lower == "authorization") ||
- strings.HasPrefix(lower, "x-mesh-") ||
- strings.EqualFold(name, api.HeaderPeerID) {
- delete(h, name)
- }
- }
-}
-
func extractBearerToken(header string) (string, bool) {
parts := strings.SplitN(strings.TrimSpace(header), " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
@@ -985,56 +992,3 @@ func ingressETagMatches(header, etag string) bool {
}
return false
}
-
-func inspectRouterMCPBody(r *http.Request) (mcpTool string, allowStreamInit bool, err error) {
- if r == nil {
- return "", false, nil
- }
- if strings.EqualFold(r.Method, http.MethodGet) || strings.EqualFold(r.Method, http.MethodDelete) {
- return "", true, nil
- }
- if r.Body == nil || !strings.EqualFold(r.Method, http.MethodPost) {
- return "", false, nil
- }
- bodyBytes, err := io.ReadAll(io.LimitReader(r.Body, maxIngressMCPBodyBytes+1))
- if err != nil {
- return "", false, fmt.Errorf("failed to read MCP request body: %w", err)
- }
- r.Body = io.NopCloser(bytes.NewReader(bodyBytes))
- if len(bodyBytes) > maxIngressMCPBodyBytes {
- return "", false, fmt.Errorf("MCP request body exceeds %d byte inspection limit", maxIngressMCPBodyBytes)
- }
- if len(bytes.TrimSpace(bodyBytes)) == 0 {
- return "", false, nil
- }
-
- var envelope struct {
- Method string `json:"method"`
- Params json.RawMessage `json:"params"`
- }
- if err := json.Unmarshal(bodyBytes, &envelope); err != nil {
- return "", false, nil
- }
- switch envelope.Method {
- case "tools/call":
- var params struct {
- Name string `json:"name"`
- }
- if err := json.Unmarshal(envelope.Params, &params); err == nil {
- rawTool := strings.TrimSpace(params.Name)
- if rawTool == "" {
- return "", false, nil
- }
- if _, stripped, splitErr := api.SplitToolName(rawTool); splitErr == nil {
- return stripped, false, nil
- }
- return rawTool, false, nil
- }
- return "", false, nil
- case "initialize", "notifications/initialized", "server/discover", "ping",
- "tools/list", "resources/list", "prompts/list", "notifications/cancelled":
- return "", true, nil
- default:
- return "", false, nil
- }
-}
diff --git a/internal/router/ingress_test.go b/internal/router/ingress_test.go
index 8853422c..fa5a942a 100644
--- a/internal/router/ingress_test.go
+++ b/internal/router/ingress_test.go
@@ -18,12 +18,11 @@ import (
"bytes"
"crypto/ed25519"
"crypto/rand"
- "crypto/rsa"
"encoding/base64"
"encoding/hex"
"encoding/json"
"io"
- "math/big"
+ "net"
"net/http"
"net/http/httptest"
"path/filepath"
@@ -37,10 +36,12 @@ import (
"github.com/google/agentmesh/api"
"github.com/google/agentmesh/internal/identity"
"github.com/google/agentmesh/internal/ratelimit"
- lru "github.com/hashicorp/golang-lru/v2"
gostream "github.com/libp2p/go-libp2p-gostream"
kb "github.com/libp2p/go-libp2p-kbucket"
+ libp2pcrypto "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
+ "github.com/libp2p/go-libp2p/core/peer"
+ "github.com/multiformats/go-multiaddr"
)
func TestIngressOptionsValidate(t *testing.T) {
@@ -228,6 +229,20 @@ func TestDirectoryIngressEnforcementAndPropagation(t *testing.T) {
}
})
+ t.Run("providerEntryOfRecord rejects invalid ingress metadata from peer router", func(t *testing.T) {
+ badRec := &api.PeerRecord{
+ PeerId: edgeMember.ID().String(),
+ Addrs: []string{memberAddr},
+ Ingress: &api.ServiceIngress{
+ AuthMode: api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH,
+ Allow: []string{"email:[email protected]"},
+ },
+ }
+ if _, err := providerEntryOfRecord(badRec); err == nil {
+ t.Fatal("providerEntryOfRecord accepted PASSTHROUGH with allow list, want error")
+ }
+ })
+
t.Run("EDGE announcement accepted and propagated across federated routers", func(t *testing.T) {
ing := &api.ServiceIngress{
AuthMode: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,
@@ -263,74 +278,20 @@ func TestDirectoryIngressEnforcementAndPropagation(t *testing.T) {
})
}
-func newTestOIDCServer(t *testing.T) (string, *rsa.PrivateKey) {
- t.Helper()
- privKey, err := rsa.GenerateKey(rand.Reader, 2048)
- if err != nil {
- t.Fatalf("rsa.GenerateKey: %v", err)
- }
- mux := http.NewServeMux()
- srv := httptest.NewServer(mux)
- t.Cleanup(srv.Close)
-
- mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(map[string]any{
- "issuer": srv.URL,
- "jwks_uri": srv.URL + "/keys",
- })
- })
- mux.HandleFunc("/keys", func(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(map[string]any{
- "keys": []map[string]any{
- {
- "kty": "RSA",
- "alg": "RS256",
- "use": "sig",
- "kid": "test-kid",
- "n": base64.RawURLEncoding.EncodeToString(privKey.N.Bytes()),
- "e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(privKey.E)).Bytes()),
- },
- },
- })
- })
- return srv.URL, privKey
-}
-
-func signTestOIDCJWT(t *testing.T, key *rsa.PrivateKey, claims jwt.MapClaims) string {
- t.Helper()
- tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
- tok.Header["kid"] = "test-kid"
- signed, err := tok.SignedString(key)
- if err != nil {
- t.Fatalf("SignedString: %v", err)
- }
- return signed
-}
-
func TestRouterIngressHandlerEndToEnd(t *testing.T) {
cpPub, cpPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("GenerateKey: %v", err)
}
- oidcIssuer, oidcKey := newTestOIDCServer(t)
r := newDirectoryRouter(t)
r.config.ControlPlaneURL = "https://hub.example.com"
- r.config.OIDCIssuer = oidcIssuer
- r.config.Audience = api.DefaultAudience
r.config.BiscuitTimeout = 2 * time.Second
limiter, err := ratelimit.NewPeerRateLimiterWithRate(128, ingressRateLimitPerIP, ingressRateBurstPerIP)
if err != nil {
t.Fatalf("NewPeerRateLimiterWithRate: %v", err)
}
r.ingressLimiter = limiter
- revoked, err := lru.New[string, time.Time](128)
- if err != nil {
- t.Fatalf("lru.New: %v", err)
- }
- r.revokedTokens = revoked
routerBiscuitRaw, err := identity.MintBootstrapBiscuitToken(cpPriv, r.Host.ID(), api.RoleRouter, time.Now().Add(time.Hour), []*api.PolicyRole{
{Name: api.RoleRouter, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}},
@@ -385,7 +346,6 @@ func TestRouterIngressHandlerEndToEnd(t *testing.T) {
MeshIngress string `json:"mesh_ingress"`
MeshBiscuit bool `json:"mesh_biscuit"`
CallerBiscuit bool `json:"caller_biscuit"`
- CallerClaims string `json:"caller_claims"`
SpoofedHeader string `json:"spoofed_header"`
}
ingListener, err := gostream.Listen(provider, api.IngressProtocolID)
@@ -431,7 +391,6 @@ func TestRouterIngressHandlerEndToEnd(t *testing.T) {
MeshIngress: req.Header.Get(api.HeaderMeshIngress),
MeshBiscuit: req.Header.Get(api.HeaderMeshBiscuit) != "",
CallerBiscuit: req.Header.Get(api.HeaderMeshIngressCallerBiscuit) != "",
- CallerClaims: req.Header.Get(api.HeaderMeshIngressClaims),
SpoofedHeader: req.Header.Get("X-Mesh-Spoofed"),
})
})
@@ -509,8 +468,8 @@ func TestRouterIngressHandlerEndToEnd(t *testing.T) {
if doc.Resource != baseURL {
t.Fatalf("Resource = %q, want %q", doc.Resource, baseURL)
}
- if len(doc.AuthorizationServers) < 2 || doc.AuthorizationServers[0] != "https://hub.example.com" || doc.AuthorizationServers[1] != oidcIssuer {
- t.Fatalf("AuthorizationServers = %v, want [https://hub.example.com %s]", doc.AuthorizationServers, oidcIssuer)
+ if len(doc.AuthorizationServers) != 1 || doc.AuthorizationServers[0] != "https://hub.example.com" {
+ t.Fatalf("AuthorizationServers = %v, want [https://hub.example.com]", doc.AuthorizationServers)
}
})
@@ -541,7 +500,25 @@ func TestRouterIngressHandlerEndToEnd(t *testing.T) {
}
})
- t.Run("EDGE AgentCard discovery rewrites URL, injects SecuritySchemes, and honors ETag", func(t *testing.T) {
+ t.Run("EDGE rejects raw compact JWT with 401 pointing callers to /oauth/token exchange", func(t *testing.T) {
+ req, _ := http.NewRequest(http.MethodPost, baseURL+"/"+provider.ID().String()+"/a2a/echo", strings.NewReader(`{}`))
+ req.Header.Set("Authorization", "Bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhbGljZSJ9.sig")
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("POST with compact JWT: %v", err)
+ }
+ _ = resp.Body.Close()
+ if resp.StatusCode != http.StatusUnauthorized {
+ t.Fatalf("compact JWT status = %d, want 401", resp.StatusCode)
+ }
+ www := resp.Header.Get("WWW-Authenticate")
+ wantSub := baseURL + "/.well-known/oauth-protected-resource"
+ if !strings.Contains(www, wantSub) {
+ t.Fatalf("WWW-Authenticate = %q, want substring %q", www, wantSub)
+ }
+ })
+
+ t.Run("EDGE AgentCard discovery rewrites URL, injects Biscuit + OAuth2 SecuritySchemes, and honors ETag", func(t *testing.T) {
cardEndpoint := baseURL + "/" + provider.ID().String() + "/a2a/echo"
resp, err := client.Get(cardEndpoint)
if err != nil {
@@ -566,11 +543,14 @@ func TestRouterIngressHandlerEndToEnd(t *testing.T) {
if len(card.Signatures) != 0 {
t.Fatalf("Signatures = %v, want cleared after URL rewrite", card.Signatures)
}
- for _, schemeName := range []a2a.SecuritySchemeName{"bearer", "agentmesh_oauth2", "oidc"} {
+ for _, schemeName := range []a2a.SecuritySchemeName{"bearer", "agentmesh_oauth2"} {
if _, ok := card.SecuritySchemes[schemeName]; !ok {
t.Fatalf("SecuritySchemes missing %q: %+v", schemeName, card.SecuritySchemes)
}
}
+ if _, hasOIDC := card.SecuritySchemes["oidc"]; hasOIDC {
+ t.Fatalf("SecuritySchemes unexpectedly advertised raw oidc scheme: %+v", card.SecuritySchemes)
+ }
// Conditional GET with If-None-Match returns 304 Not Modified.
condReq, _ := http.NewRequest(http.MethodGet, cardEndpoint+"/.well-known/agent-card.json", nil)
@@ -666,7 +646,7 @@ func TestRouterIngressHandlerEndToEnd(t *testing.T) {
t.Fatalf("MCP drop_db status = %d, want 403", dropResp.StatusCode)
}
- // Revoked Biscuit -> 401.
+ // Revoked Biscuit -> 401 (both hex and base64url revocation IDs work).
aliceB, _ := biscuit.Unmarshal(aliceRaw)
for _, revID := range aliceB.RevocationIds() {
r.recordRevokedBiscuitID(hex.EncodeToString(revID), time.Now().Add(time.Hour))
@@ -683,42 +663,6 @@ func TestRouterIngressHandlerEndToEnd(t *testing.T) {
}
})
- t.Run("EDGE OIDC JWT verification forwards attested claims", func(t *testing.T) {
- jwtStr := signTestOIDCJWT(t, oidcKey, jwt.MapClaims{
- "iss": oidcIssuer,
- "sub": "oidc-alice",
- "aud": api.DefaultAudience,
- "email": "[email protected]",
- "email_verified": true,
- "exp": time.Now().Add(time.Hour).Unix(),
- "iat": time.Now().Add(-time.Minute).Unix(),
- })
- req, _ := http.NewRequest(http.MethodPost, baseURL+"/"+provider.ID().String()+"/a2a/echo", strings.NewReader(`{}`))
- req.Header.Set("Authorization", "Bearer "+jwtStr)
- resp, err := client.Do(req)
- if err != nil {
- t.Fatalf("POST with OIDC JWT: %v", err)
- }
- var got capturedReq
- if err := json.NewDecoder(resp.Body).Decode(&got); err != nil {
- t.Fatalf("decode OIDC upstream: %v", err)
- }
- _ = resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- t.Fatalf("OIDC JWT status = %d, want 200", resp.StatusCode)
- }
- if got.CallerClaims == "" || got.Auth != "" {
- t.Fatalf("expected CallerClaims set and Authorization stripped, got %+v", got)
- }
- claimsMap, err := identity.UnmarshalIngressClaimsHeader(got.CallerClaims)
- if err != nil {
- t.Fatalf("UnmarshalIngressClaimsHeader: %v", err)
- }
- if len(claimsMap[api.FactEmail]) != 1 || claimsMap[api.FactEmail][0] != "[email protected]" {
- t.Fatalf("forwarded email claims = %v, want [[email protected]]", claimsMap[api.FactEmail])
- }
- })
-
t.Run("PASSTHROUGH preserves backend Authorization and SecuritySchemes while stripping X-Mesh-*", func(t *testing.T) {
cardEndpoint := baseURL + "/" + provider.ID().String() + "/a2a/paired"
cardResp, err := client.Get(cardEndpoint + "/.well-known/agent-card.json")
@@ -770,3 +714,308 @@ func TestRouterIngressHandlerEndToEnd(t *testing.T) {
}
})
}
+
+func TestLeasedIngressURLAndHostHeaderHardening(t *testing.T) {
+ r := &Router{
+ config: Options{
+ ControlPlaneURL: "https://internal-cp.cluster.local:8443",
+ PublicControlPlaneURL: "https://bananas.sam-mesh.dev",
+ },
+ }
+
+ for _, addr := range []*net.TCPAddr{
+ {IP: net.IPv4zero, Port: 8090},
+ {IP: net.IPv6zero, Port: 8090},
+ } {
+ r.ingressAddr = addr
+ if got := r.leasedIngressURL(); got != "" {
+ t.Fatalf("leasedIngressURL() for unspecified %s = %q, want empty string", addr, got)
+ }
+ if got := r.effectiveIngressBaseURL(); got != "https://bananas.sam-mesh.dev/ingress" {
+ t.Fatalf("effectiveIngressBaseURL() for unspecified %s = %q, want https://bananas.sam-mesh.dev/ingress", addr, got)
+ }
+ }
+
+ // Unbound IngressHandler must never reflect a spoofed Host header into
+ // RFC 9728 metadata or WWW-Authenticate headers.
+ r.ingressAddr = nil
+ h := r.IngressHandler()
+ req := httptest.NewRequest(http.MethodGet, "http://evil.attacker.example/ingress/.well-known/oauth-protected-resource", nil)
+ req.Host = "evil.attacker.example"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("metadata status = %d, want 200", rec.Code)
+ }
+ if strings.Contains(rec.Body.String(), "evil.attacker.example") {
+ t.Fatalf("metadata leaked spoofed Host header: %s", rec.Body.String())
+ }
+ var doc api.OAuthProtectedResourceMetadata
+ if err := json.Unmarshal(rec.Body.Bytes(), &doc); err != nil {
+ t.Fatalf("Unmarshal metadata: %v", err)
+ }
+ if doc.Resource != "https://bananas.sam-mesh.dev/ingress" {
+ t.Fatalf("Resource = %q, want https://bananas.sam-mesh.dev/ingress", doc.Resource)
+ }
+}
+
+func TestEdgeIngressPreDialRejectsBeforeDialingProvider(t *testing.T) {
+ cpPub, cpPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("GenerateKey: %v", err)
+ }
+ r := newDirectoryRouter(t)
+ r.config.ControlPlaneURL = "https://hub.example.com"
+ r.config.BiscuitTimeout = 2 * time.Second
+ r.isReady.Store(true)
+
+ routerBiscuitRaw, err := identity.MintBootstrapBiscuitToken(cpPriv, r.Host.ID(), api.RoleRouter, time.Now().Add(time.Hour), []*api.PolicyRole{
+ {Name: api.RoleRouter, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}},
+ }, nil)
+ if err != nil {
+ t.Fatalf("MintBootstrapBiscuitToken: %v", err)
+ }
+ r.keysMu.Lock()
+ r.trustedPublicKeys = []ed25519.PublicKey{cpPub}
+ r.credential = credential{biscuit: routerBiscuitRaw, expiration: time.Now().Add(time.Hour)}
+ r.keysMu.Unlock()
+
+ // Create a synthetic unreachable provider PeerID with a closed loopback port.
+ // If handleIngressRequest dialed the provider before checking the caller's
+ // Biscuit, it would fail with 502 Bad Gateway instead of 401/403.
+ priv, _, err := libp2pcrypto.GenerateEd25519Key(rand.Reader)
+ if err != nil {
+ t.Fatalf("GenerateEd25519Key: %v", err)
+ }
+ unreachablePeer, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ t.Fatalf("IDFromPrivateKey: %v", err)
+ }
+ key, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, "echo")
+ if err != nil {
+ t.Fatalf("ServiceKey: %v", err)
+ }
+ r.records.putWithIngress(
+ key,
+ unreachablePeer,
+ []multiaddr.Multiaddr{multiaddr.StringCast("/ip4/127.0.0.1/tcp/1")},
+ &api.ServiceIngress{
+ AuthMode: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,
+ Allow: []string{"email:[email protected]"},
+ },
+ time.Now(),
+ )
+
+ callerRole := &api.PolicyRole{
+ Name: "caller",
+ AllowedServices: []string{"a2a://echo"},
+ AllowedTargets: []string{"*"},
+ }
+ bobRaw, err := identity.MintDelegatedBiscuitToken(cpPriv, jwt.MapClaims{
+ "sub": "bob",
+ "email": "[email protected]",
+ }, unreachablePeer, time.Now().Add(time.Hour), []string{"caller"}, []*api.PolicyRole{callerRole}, nil, false)
+ if err != nil {
+ t.Fatalf("MintDelegatedBiscuitToken(bob): %v", err)
+ }
+ standingNodeRaw, _, err := identity.MintBiscuitToken(cpPriv, jwt.MapClaims{
+ "sub": "alice",
+ "email": "[email protected]",
+ }, nil, unreachablePeer, time.Now().Add(time.Hour), []string{"caller"}, []*api.PolicyRole{callerRole}, nil)
+ if err != nil {
+ t.Fatalf("MintBiscuitToken(standing): %v", err)
+ }
+
+ h := r.IngressHandler()
+ targetPath := "/ingress/" + unreachablePeer.String() + "/a2a/echo/message:send"
+
+ cases := []struct {
+ name string
+ authHeader string
+ wantStatus int
+ }{
+ {
+ name: "unauthenticated rejected 401 before dial",
+ authHeader: "",
+ wantStatus: http.StatusUnauthorized,
+ },
+ {
+ name: "compact JWT rejected 401 before dial",
+ authHeader: "Bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhbGljZSJ9.sig",
+ wantStatus: http.StatusUnauthorized,
+ },
+ {
+ name: "ServiceIngress.allow mismatch rejected 403 before dial",
+ authHeader: "Bearer " + base64.StdEncoding.EncodeToString(bobRaw),
+ wantStatus: http.StatusForbidden,
+ },
+ {
+ name: "unattenuated standing node Biscuit rejected 403 before dial",
+ authHeader: "Bearer " + base64.StdEncoding.EncodeToString(standingNodeRaw),
+ wantStatus: http.StatusForbidden,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, targetPath, strings.NewReader(`{}`))
+ if tc.authHeader != "" {
+ req.Header.Set("Authorization", tc.authHeader)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != tc.wantStatus {
+ t.Fatalf("status = %d (%s), want %d (must not dial unreachable provider)", rec.Code, strings.TrimSpace(rec.Body.String()), tc.wantStatus)
+ }
+ })
+ }
+}
+
+func TestRevocationSetDoesNotEvictLiveEntries(t *testing.T) {
+ _, cpPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("GenerateKey: %v", err)
+ }
+ priv, _, err := libp2pcrypto.GenerateEd25519Key(rand.Reader)
+ if err != nil {
+ t.Fatalf("GenerateEd25519Key: %v", err)
+ }
+ pid, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ t.Fatalf("IDFromPrivateKey: %v", err)
+ }
+ firstRaw, err := identity.MintDelegatedBiscuitToken(cpPriv, jwt.MapClaims{"sub": "first"}, pid, time.Now().Add(time.Hour), nil, nil, nil, false)
+ if err != nil {
+ t.Fatalf("MintDelegatedBiscuitToken: %v", err)
+ }
+ firstB, err := biscuit.Unmarshal(firstRaw)
+ if err != nil {
+ t.Fatalf("biscuit.Unmarshal: %v", err)
+ }
+
+ var set revocationSet
+ now := time.Now()
+ // Record the first Biscuit's root revocation ID in hex format.
+ set.add(hex.EncodeToString(firstB.RevocationIds()[0]), now.Add(time.Hour))
+
+ // Add 5,000 more live revocations (> old 4096 LRU capacity) plus expired entries.
+ for i := 0; i < 5000; i++ {
+ var id [32]byte
+ id[0] = byte(i >> 8)
+ id[1] = byte(i)
+ id[2] = 1
+ set.add(base64.RawURLEncoding.EncodeToString(id[:]), now.Add(time.Hour))
+ }
+ set.mu.Lock()
+ set.entries["already-expired"] = now.Add(-time.Minute)
+ set.mu.Unlock()
+
+ if !set.isRevoked(firstB, now) {
+ t.Fatal("first revoked Biscuit was evicted after 5000 inserts; deny list must never evict live entries")
+ }
+ if got := set.activeCount(now); got != 5001 {
+ t.Fatalf("activeCount = %d, want 5001", got)
+ }
+}
+
+func TestGatewaySafeIngressRateLimiting(t *testing.T) {
+ cpPub, cpPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("GenerateKey: %v", err)
+ }
+ r := newDirectoryRouter(t)
+ r.config.ControlPlaneURL = "https://hub.example.com"
+ r.config.BiscuitTimeout = 2 * time.Second
+ limiter, err := ratelimit.NewPeerRateLimiterWithRate(128, 1, 2)
+ if err != nil {
+ t.Fatalf("NewPeerRateLimiterWithRate: %v", err)
+ }
+ r.ingressLimiter = limiter
+ r.isReady.Store(true)
+
+ routerBiscuitRaw, err := identity.MintBootstrapBiscuitToken(cpPriv, r.Host.ID(), api.RoleRouter, time.Now().Add(time.Hour), []*api.PolicyRole{
+ {Name: api.RoleRouter, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}},
+ }, nil)
+ if err != nil {
+ t.Fatalf("MintBootstrapBiscuitToken: %v", err)
+ }
+ r.keysMu.Lock()
+ r.trustedPublicKeys = []ed25519.PublicKey{cpPub}
+ r.credential = credential{biscuit: routerBiscuitRaw, expiration: time.Now().Add(time.Hour)}
+ r.keysMu.Unlock()
+
+ providerRole := &api.PolicyRole{
+ Name: "agent-host",
+ AllowedPublish: []string{"a2a://*"},
+ AllowedIngress: []*api.IngressGrant{{Services: []string{"a2a://echo"}}},
+ }
+ callerRole := &api.PolicyRole{
+ Name: "caller",
+ AllowedServices: []string{"a2a://echo"},
+ AllowedTargets: []string{"*"},
+ }
+ roles := []*api.PolicyRole{providerRole, callerRole}
+ provider := attachWithRole(t, r, cpPub, cpPriv, providerRole)
+ providerAddr := provider.Addrs()[0].String() + "/p2p/" + provider.ID().String()
+
+ ingListener, err := gostream.Listen(provider, api.IngressProtocolID)
+ if err != nil {
+ t.Fatalf("gostream.Listen: %v", err)
+ }
+ t.Cleanup(func() { _ = ingListener.Close() })
+ upstreamSrv := &http.Server{
+ Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }),
+ ReadHeaderTimeout: 5 * time.Second,
+ }
+ go func() { _ = upstreamSrv.Serve(ingListener) }()
+ t.Cleanup(func() { _ = upstreamSrv.Close() })
+
+ key, _ := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, "echo")
+ resp := ask(t, provider, r.Host.ID(), provideWithIngress(key, "a2a://echo", &api.ServiceIngress{
+ AuthMode: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,
+ }, providerAddr))
+ if resp.GetError() != "" {
+ t.Fatalf("provide failed: %s", resp.GetError())
+ }
+
+ mintCaller := func(sub string) string {
+ raw, err := identity.MintDelegatedBiscuitToken(cpPriv, jwt.MapClaims{"sub": sub}, provider.ID(), time.Now().Add(time.Hour), []string{"caller"}, roles, nil, false)
+ if err != nil {
+ t.Fatalf("MintDelegatedBiscuitToken(%s): %v", sub, err)
+ }
+ return base64.StdEncoding.EncodeToString(raw)
+ }
+ tokA := mintCaller("alice")
+ tokB := mintCaller("bob")
+
+ h := r.IngressHandler()
+ sharedGatewayRemoteAddr := "10.128.0.5:44321"
+ targetPath := "/ingress/" + provider.ID().String() + "/a2a/echo"
+
+ send := func(tok string) int {
+ req := httptest.NewRequest(http.MethodPost, targetPath, strings.NewReader(`{}`))
+ req.RemoteAddr = sharedGatewayRemoteAddr
+ req.Header.Set("Authorization", "Bearer "+tok)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec.Code
+ }
+
+ // Exhaust Caller A's burst of 2 through the shared Gateway IP.
+ if code := send(tokA); code != http.StatusOK {
+ t.Fatalf("Caller A req 1 = %d, want 200", code)
+ }
+ if code := send(tokA); code != http.StatusOK {
+ t.Fatalf("Caller A req 2 = %d, want 200", code)
+ }
+ if code := send(tokA); code != http.StatusTooManyRequests {
+ t.Fatalf("Caller A req 3 = %d, want 429", code)
+ }
+
+ // Caller B sharing the exact same Gateway RemoteAddr must NOT be starved.
+ if code := send(tokB); code != http.StatusOK {
+ t.Fatalf("Caller B behind same Gateway IP = %d, want 200", code)
+ }
+}
diff --git a/internal/router/metrics.go b/internal/router/metrics.go
index fef7a1db..1ba8d75c 100644
--- a/internal/router/metrics.go
+++ b/internal/router/metrics.go
@@ -119,6 +119,7 @@ type routerStateCollector struct {
watermarkDesc *prometheus.Desc
relayLimitDesc *prometheus.Desc
bannedDesc *prometheus.Desc
+ revokedDesc *prometheus.Desc
dhtDesc *prometheus.Desc
recordsDesc *prometheus.Desc
biscuitExpiryDesc *prometheus.Desc
@@ -167,6 +168,10 @@ func newRouterStateCollector(r *Router) *routerStateCollector {
"agentmesh_router_banned_peers",
"Peers on the ban list synced from the control plane",
nil, nil),
+ revokedDesc: prometheus.NewDesc(
+ "agentmesh_router_revoked_tokens",
+ "Active revoked Biscuit tokens held in this router's deny list",
+ nil, nil),
dhtDesc: prometheus.NewDesc(
"agentmesh_router_dht_routing_table_size",
"Peers in the Kademlia routing table",
@@ -185,7 +190,7 @@ func newRouterStateCollector(r *Router) *routerStateCollector {
func (c *routerStateCollector) Describe(ch chan<- *prometheus.Desc) {
for _, d := range []*prometheus.Desc{
c.infoDesc, c.readyDesc, c.drainingDesc, c.authenticatedDesc, c.peerRoutersDesc, c.connectedDesc, c.connectionsDesc, c.watermarkDesc, c.relayLimitDesc,
- c.bannedDesc, c.dhtDesc, c.recordsDesc, c.biscuitExpiryDesc, connsPerSourceIPDesc,
+ c.bannedDesc, c.revokedDesc, c.dhtDesc, c.recordsDesc, c.biscuitExpiryDesc, connsPerSourceIPDesc,
} {
ch <- d
}
@@ -228,6 +233,7 @@ func (c *routerStateCollector) Collect(ch chan<- prometheus.Metric) {
ch <- prometheus.MustNewConstMetric(c.connectionsDesc, prometheus.GaugeValue, float64(inbound), "inbound")
ch <- prometheus.MustNewConstMetric(c.connectionsDesc, prometheus.GaugeValue, float64(outbound), "outbound")
ch <- prometheus.MustNewConstMetric(c.bannedDesc, prometheus.GaugeValue, float64(syncMapLen(&r.bannedPeers)))
+ ch <- prometheus.MustNewConstMetric(c.revokedDesc, prometheus.GaugeValue, float64(r.revokedTokens.activeCount(time.Now())))
ch <- prometheus.MustNewConstMetric(c.dhtDesc, prometheus.GaugeValue, float64(r.DHT.RoutingTable().Size()))
ch <- prometheus.MustNewConstMetric(c.recordsDesc, prometheus.GaugeValue, float64(r.records.size()))
diff --git a/internal/router/metrics_test.go b/internal/router/metrics_test.go
index 7eeab451..3a902691 100644
--- a/internal/router/metrics_test.go
+++ b/internal/router/metrics_test.go
@@ -89,6 +89,7 @@ func TestRouterMetricsListener(t *testing.T) {
r.authenticatedPeers.Store(peer.ID("peer-a"), true)
r.authenticatedPeers.Store(peer.ID("peer-b"), true)
r.bannedPeers.Store(peer.ID("peer-x"), true)
+ r.recordRevokedBiscuitID("revoked-token-1", time.Now().Add(time.Hour))
// Two peer routers listed, of which one is authenticated.
r.peerRouters.Store(peer.ID("peer-a"), true)
r.peerRouters.Store(peer.ID("peer-r"), true)
@@ -119,6 +120,7 @@ func TestRouterMetricsListener(t *testing.T) {
`agentmesh_router_peer_routers{state="listed"} 2`,
`agentmesh_router_peer_routers{state="authenticated"} 1`,
"agentmesh_router_banned_peers 1",
+ "agentmesh_router_revoked_tokens 1",
"agentmesh_router_connected_peers 0",
"agentmesh_router_dht_routing_table_size 0",
"agentmesh_router_directory_records 1",
diff --git a/internal/router/router.go b/internal/router/router.go
index ce7b3dc8..4bc34d84 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -35,14 +35,12 @@ import (
"sync/atomic"
"time"
- "github.com/coreos/go-oidc/v3/oidc"
"github.com/eclipse-biscuit/biscuit-go/v2"
"github.com/google/agentmesh/api"
cpclient "github.com/google/agentmesh/internal/controlplane/client"
"github.com/google/agentmesh/internal/identity"
"github.com/google/agentmesh/internal/p2plimits"
"github.com/google/agentmesh/internal/ratelimit"
- lru "github.com/hashicorp/golang-lru/v2"
golog "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
@@ -401,12 +399,7 @@ type Router struct {
ingressAddr net.Addr
ingressLimiter *ratelimit.PeerRateLimiter
- revokedTokens *lru.Cache[string, time.Time]
-
- oidcMu sync.Mutex
- oidcProviders map[string]*oidc.Provider
- syncedOIDCIssuer atomic.Pointer[string]
- syncedAudience atomic.Pointer[string]
+ revokedTokens revocationSet
// identityLoggedAt is when the "Router Online" line was last written.
identityLoggedAt atomic.Pointer[time.Time]
@@ -434,11 +427,6 @@ func NewRouter(ctx context.Context, config Options) (*Router, error) {
cancel()
return nil, fmt.Errorf("failed to create ingress rate limiter: %w", err)
}
- revokedTokens, err := lru.New[string, time.Time](handshakeLimiterSize)
- if err != nil {
- cancel()
- return nil, fmt.Errorf("failed to create revocation cache: %w", err)
- }
return &Router{
config: config,
@@ -446,8 +434,6 @@ func NewRouter(ctx context.Context, config Options) (*Router, error) {
cancel: cancel,
handshakeLimiter: handshakeLimiter,
ingressLimiter: ingressLimiter,
- revokedTokens: revokedTokens,
- oidcProviders: make(map[string]*oidc.Provider),
syncTrigger: make(chan struct{}, 1),
}, nil
}
@@ -1188,40 +1174,148 @@ func (r *Router) syncRevocations() error {
for _, revID := range resp.GetRevocationIds() {
r.recordRevokedBiscuitID(revID, expiry)
}
+ r.credentials.Range(func(k, v any) bool {
+ pid, ok := k.(peer.ID)
+ cred, credOK := v.(memberCredential)
+ if ok && credOK && r.isBiscuitRevoked(cred.biscuit) {
+ logger.Infof("[Revocations] Evicting peer %s with revoked biscuit", pid)
+ r.forgetPeer(pid)
+ if r.records != nil {
+ r.records.removePeer(pid)
+ }
+ if r.Host != nil {
+ _ = r.Host.Network().ClosePeer(pid)
+ }
+ }
+ return true
+ })
if len(resp.GetBannedPeerIds()) > 0 {
r.reconcileBannedPeers(resp.GetBannedPeerIds(), fetchedAt)
}
return nil
}
-func (r *Router) recordRevokedBiscuitID(revID string, expiry time.Time) {
- if revID == "" || r.revokedTokens == nil {
+const revokedPruneMin = 64
+
+// revocationSet holds active revoked Biscuit authority revocation IDs synced
+// from the control plane. Entries expire by timestamp and are never evicted by
+// capacity, so high-churn revocation cannot push live revocations out of the
+// deny list. Zero-value safe for test routers constructed as &Router{}.
+type revocationSet struct {
+ mu sync.Mutex
+ entries map[string]time.Time
+ pruneAt int
+}
+
+func normalizeRevocationKey(revID string) string {
+ revID = strings.TrimSpace(revID)
+ if revID == "" {
+ return ""
+ }
+ if (len(revID) == 64 || len(revID) == 128) && isHexDigits(revID) {
+ if raw, err := hex.DecodeString(revID); err == nil && len(raw) > 0 {
+ return base64.RawURLEncoding.EncodeToString(raw)
+ }
+ }
+ return revID
+}
+
+func isHexByte(c byte) bool {
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
+}
+
+func isHexDigits(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if !isHexByte(s[i]) {
+ return false
+ }
+ }
+ return len(s) > 0
+}
+
+func (s *revocationSet) add(revID string, expiry time.Time) {
+ key := normalizeRevocationKey(revID)
+ if key == "" {
return
}
- r.revokedTokens.Add(revID, expiry)
- if raw, err := hex.DecodeString(revID); err == nil && len(raw) > 0 {
- r.revokedTokens.Add(base64.RawURLEncoding.EncodeToString(raw), expiry)
+ now := time.Now()
+ if !now.Before(expiry) {
+ return
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.entries == nil {
+ s.entries = make(map[string]time.Time)
+ }
+ if len(s.entries) >= max(revokedPruneMin, s.pruneAt) {
+ for k, exp := range s.entries {
+ if !now.Before(exp) {
+ delete(s.entries, k)
+ }
+ }
+ s.pruneAt = max(revokedPruneMin, 2*len(s.entries))
+ }
+ if existing, ok := s.entries[key]; !ok || expiry.After(existing) {
+ s.entries[key] = expiry
}
}
-func (r *Router) isBiscuitRevoked(b *biscuit.Biscuit) bool {
- if r == nil || r.revokedTokens == nil || b == nil {
+func (s *revocationSet) isRevoked(b *biscuit.Biscuit, now time.Time) bool {
+ if s == nil || b == nil {
return false
}
- now := time.Now()
- for _, id := range b.RevocationIds() {
- for _, key := range []string{hex.EncodeToString(id), base64.RawURLEncoding.EncodeToString(id)} {
- if exp, ok := r.revokedTokens.Get(key); ok {
- if now.Before(exp) {
- return true
- }
- r.revokedTokens.Remove(key)
+ ids := b.RevocationIds()
+ if len(ids) == 0 {
+ return false
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if len(s.entries) == 0 {
+ return false
+ }
+ for _, id := range ids {
+ key := base64.RawURLEncoding.EncodeToString(id)
+ if exp, ok := s.entries[key]; ok {
+ if now.Before(exp) {
+ return true
}
+ delete(s.entries, key)
}
}
return false
}
+func (s *revocationSet) activeCount(now time.Time) int {
+ if s == nil {
+ return 0
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ n := 0
+ for k, exp := range s.entries {
+ if now.Before(exp) {
+ n++
+ } else {
+ delete(s.entries, k)
+ }
+ }
+ return n
+}
+
+func (r *Router) recordRevokedBiscuitID(revID string, expiry time.Time) {
+ if r == nil {
+ return
+ }
+ r.revokedTokens.add(revID, expiry)
+}
+
+func (r *Router) isBiscuitRevoked(b *biscuit.Biscuit) bool {
+ if r == nil || b == nil {
+ return false
+ }
+ return r.revokedTokens.isRevoked(b, time.Now())
+}
+
// refreshExpiringCredential refreshes the router's own credential once less
// than a fifth of its lifetime is left, so a credential is never presented
// close to its expiry.
@@ -1543,13 +1637,6 @@ func (r *Router) connectBootstrapRouters() {
return
}
- if iss := strings.TrimSpace(info.GetOidcIssuer()); iss != "" {
- r.syncedOIDCIssuer.Store(&iss)
- }
- if aud := strings.TrimSpace(info.GetAudience()); aud != "" {
- r.syncedAudience.Store(&aud)
- }
-
// /info carries the whole ban set, so this is also where a router that
// restarted or missed a MeshEvent_BANNED catches up.
r.reconcileBannedPeers(info.GetBannedPeerIds(), fetchedAt)
@@ -1812,6 +1899,14 @@ func (r *Router) HandleAuthHandshake(s network.Stream) {
_ = s.Reset()
return
}
+ if r.isBiscuitRevoked(b) {
+ if r.authFailureLog.allow(remotePeer, time.Now()) {
+ logger.Warnf("[AuthN] Rejecting revoked biscuit for peer %s", remotePeer)
+ }
+ authHandshakesTotal.WithLabelValues(handshakeUnauthorized).Inc()
+ _ = s.Reset()
+ return
+ }
r.admitPeer(remotePeer, expiry)
r.credentials.Store(remotePeer, memberCredential{biscuit: b, key: verifyingKey})
@@ -1885,6 +1980,9 @@ func (r *Router) performMutualAuth(s network.Stream) error {
if err != nil {
return fmt.Errorf("failed to verify peer router biscuit: %w", err)
}
+ if r.isBiscuitRevoked(b) {
+ return fmt.Errorf("peer router %s biscuit is revoked", remotePeer)
+ }
// Enforce required role inside the biscuit
if err := identity.RequireRole(b, verifyingKey, r.config.RequiredRole, r.config.BiscuitTimeout); err != nil {
diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.go
index 797c7371..302543fd 100644
--- a/internal/standalone/standalone.go
+++ b/internal/standalone/standalone.go
@@ -389,6 +389,7 @@ func (s *Server) Start(ctx context.Context) (retErr error) {
}
var externalAddrs []string
var ingressURL string
+ var publicControlPlaneURL string
allowInsecureIngress := true
if s.opts.ExternalURL != "" {
ext, err := externalMultiaddr(s.opts.ExternalURL)
@@ -396,7 +397,8 @@ func (s *Server) Start(ctx context.Context) (retErr error) {
return err
}
externalAddrs = []string{ext}
- ingressURL = strings.TrimRight(s.opts.ExternalURL, "/") + "/ingress"
+ publicControlPlaneURL = strings.TrimRight(s.opts.ExternalURL, "/")
+ ingressURL = publicControlPlaneURL + "/ingress"
allowInsecureIngress = strings.HasPrefix(s.opts.ExternalURL, "http://")
}
@@ -407,6 +409,7 @@ func (s *Server) Start(ctx context.Context) (retErr error) {
rtr, err := router.NewRouter(ctx, router.Options{
ControlPlaneURL: "http://" + cp.Addr(),
+ PublicControlPlaneURL: publicControlPlaneURL,
ListenAddrs: append([]string{wsAddr}, s.opts.P2PListen...),
ExternalAddrs: externalAddrs,
AllowLoopback: !s.opts.Router.DisallowLoopback,
@@ -585,19 +588,21 @@ func (s *Server) seedPolicyOnFirstBoot(ctx context.Context) error {
}
// defaultDevPolicyRoles mirrors the Helm bootstrap job's role set with the
-// node role opened up for zero-config development use.
+// node role opened up for zero-config development use while keeping external
+// HTTP ingress restricted to zero-trust INGRESS_AUTH_MODE_EDGE unless an
+// operator explicitly grants INGRESS_AUTH_MODE_PASSTHROUGH via --policy-file
+// or POST /policies.
func defaultDevPolicyRoles() []*api.PolicyRole {
devIngress := []*api.IngressGrant{{
Services: []string{"*"},
AllowedAuthModes: []api.IngressAuthMode{
api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE,
- api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH,
},
}}
return []*api.PolicyRole{
{Name: "mesh-admin", AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}, AllowedIngress: devIngress},
{Name: api.RoleRouter, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}},
- {Name: api.RoleNode, AllowedServices: []string{"*"}, AllowedPublish: []string{"*"}, AllowedTargets: []string{"*"}, AllowedLabels: []string{"*"}, AllowedIngress: devIngress},
+ {Name: api.RoleNode, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}, AllowedPublish: []string{"*"}, AllowedLabels: []string{"*"}, AllowedIngress: devIngress},
}
}
diff --git a/internal/standalone/standalone_test.go b/internal/standalone/standalone_test.go
index 2ecaddf7..c2a48082 100644
--- a/internal/standalone/standalone_test.go
+++ b/internal/standalone/standalone_test.go
@@ -22,6 +22,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "slices"
"testing"
"time"
@@ -206,8 +207,44 @@ func TestWrapPublicHTTPHandlerCountsProxiedRequestsWithoutExternalURL(t *testing
}
}
+func roleGrantsIngressMode(r *api.PolicyRole, mode api.IngressAuthMode) bool {
+ for _, g := range r.GetAllowedIngress() {
+ modes := g.GetAllowedAuthModes()
+ if len(modes) == 0 {
+ if mode == api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE {
+ return true
+ }
+ continue
+ }
+ if slices.Contains(modes, mode) {
+ return true
+ }
+ }
+ return false
+}
+
+func TestDefaultDevPolicyRolesSafeIngressCeiling(t *testing.T) {
+ roles := defaultDevPolicyRoles()
+ var nodeRole *api.PolicyRole
+ for _, r := range roles {
+ if r.GetName() == api.RoleNode {
+ nodeRole = r
+ break
+ }
+ }
+ if nodeRole == nil {
+ t.Fatalf("defaultDevPolicyRoles missing %s", api.RoleNode)
+ }
+ if !roleGrantsIngressMode(nodeRole, api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE) {
+ t.Errorf("default %s role denied INGRESS_AUTH_MODE_EDGE, want allowed", api.RoleNode)
+ }
+ if roleGrantsIngressMode(nodeRole, api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH) {
+ t.Errorf("default %s role allowed INGRESS_AUTH_MODE_PASSTHROUGH, want denied by safe default", api.RoleNode)
+ }
+}
+
func TestStandaloneSinglePortIngressAndSeededPolicy(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv, err := New(Options{
@@ -295,14 +332,20 @@ func TestStandaloneSinglePortIngressAndSeededPolicy(t *testing.T) {
if err := protojson.Unmarshal(polBody, &pol); err != nil {
t.Fatalf("unmarshal PolicyConfig: %v", err)
}
- foundNodeIngress := false
+ var nodeRole *api.PolicyRole
for _, role := range pol.GetRoles() {
- if role.GetName() == api.RoleNode && len(role.GetAllowedIngress()) > 0 {
- foundNodeIngress = true
+ if role.GetName() == api.RoleNode {
+ nodeRole = role
break
}
}
- if !foundNodeIngress {
+ if nodeRole == nil || len(nodeRole.GetAllowedIngress()) == 0 {
t.Fatalf("seeded PolicyConfig for %s lacks allowed_ingress: %+v", api.RoleNode, pol.GetRoles())
}
+ if !roleGrantsIngressMode(nodeRole, api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE) {
+ t.Errorf("seeded %s role denied INGRESS_AUTH_MODE_EDGE, want allowed", api.RoleNode)
+ }
+ if roleGrantsIngressMode(nodeRole, api.IngressAuthMode_INGRESS_AUTH_MODE_PASSTHROUGH) {
+ t.Errorf("seeded %s role allowed INGRESS_AUTH_MODE_PASSTHROUGH, want denied without explicit --policy-file", api.RoleNode)
+ }
}
diff --git a/sdk/js/src/gen/agentmesh_pb.ts b/sdk/js/src/gen/agentmesh_pb.ts
index baa12d69..5cda8a51 100644
--- a/sdk/js/src/gen/agentmesh_pb.ts
+++ b/sdk/js/src/gen/agentmesh_pb.ts
@@ -3312,7 +3312,7 @@ export enum IngressAuthMode {
UNSPECIFIED = 0,
/**
- * Router verifies Mesh Biscuit or trusted OIDC JWT + mesh policy at the edge.
+ * Router and provider node verify a delegated Mesh Biscuit + mesh policy.
*
* @generated from enum value: INGRESS_AUTH_MODE_EDGE = 1;
*/
diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.md
index 1b5fe9d5..7409c011 100644
--- a/site/content/docs/contributing/security-architecture.md
+++ b/site/content/docs/contributing/security-architecture.md
@@ -317,7 +317,12 @@ minted statelessly on the control plane with zero database writes:
- `user(...)`, `email(...)`, `group(...)`, `idp_role(...)`, and `role(...)` are
resolved strictly from the caller's `subject_token`.
- No `node()` fact is minted, which prevents `node:<peer_id>` policy bindings on
- the origin node from leaking to the delegated caller.
+ the origin node from leaking to the delegated caller. On router external HTTP
+ ingress (`/ingress/*` in `edge` mode), `ValidateIngressCallerPreDial` and
+ `AuthorizeIngressDelegatedBiscuit` reject `mesh:role:router` Biscuits and
+ unattenuated standing Member Biscuits (`node(...)` with zero `tar_block`
+ blocks), accepting only Delegated Session Biscuits or task-attenuated
+ Biscuits.
Before handing a task token to an untrusted leaf process or sandbox, the holder
calls `Seal()`, discarding the ephemeral next-block key so no further blocks can
@@ -326,7 +331,8 @@ be appended.
Revocation operates at two levels. Root-prefix revocation (`GET /revocations`)
uses `b.RevocationIds()[0]` to identify the authority block, so revoking a root
token or banning a peer or user at the control plane invalidates both the root
-Biscuit and every offline-attenuated child derived from it across the mesh.
+Biscuit and every offline-attenuated child derived from it across the mesh
+(enforced by both `agentmesh-node` and `agentmesh-router`).
Local task revocation (`POST /oauth/revoke`) lets an orchestrator revoke a
specific child Task Biscuit at the local `agentmesh-node` as soon as a task finishes,
caching `RevocationIds()[last]` in the node's revocation LRU until the token's
@@ -358,7 +364,7 @@ as a standard OIDC issuer:
| **libp2p data path** (node-to-node, node-to-router) | Channel binding: Block 0 `client_peer_id` must equal the `connection_peer_id` authenticated by the libp2p Noise or TLS handshake. | The transport private key | None needed; the token is unusable on any other connection. |
| **Control plane mesh protocol** (`/enroll`, `/enroll/status`, `/register`, `/refresh`, `/routers/lease`, `/token/exchange`, `/sts/token`) | Ed25519 signature over `mesh:<endpoint>:<peer_id>:<challenge_unix_ms>`, carried in protobuf fields (`challenge_unix_ms`, `challenge_signature`) or `X-Mesh-Challenge-Ts` / `X-Mesh-Challenge-Sig` on `GET /enroll/status`. | Endpoint name, peer ID, timestamp | 5-minute freshness window (`challengeMaxAge`) with one-shot `Date`-header clock-skew recovery on `401`; `/refresh` additionally redeems only the last Biscuit issued to the peer. |
| **Control plane read & report endpoints** (`GET /policies`, `GET /egress`, `GET /revocations`, `POST /nodes/catalog`) | Bearer Member Biscuit of an admitted node (`admittedNodeWithChallenge`) plus `X-Mesh-Challenge-Ts` / `X-Mesh-Challenge-Sig` signed over `mesh:<endpoint>:<peer_id>:<ts>` (`policies`, `egress`, `revocations`, `nodes-catalog`), verified against the node's stored Ed25519 public key via `verifyFreshChallenge`. | Enrolled node credential, endpoint name, peer ID, timestamp | 5-minute freshness window (`challengeMaxAge`) with one-shot `Date`-header clock-skew recovery on `401`, bounded by Biscuit TTL and ban/revocation list. |
-| **OAuth 2.1 external client surface** (`/oauth/authorize`, `/oauth/token`, `/mcp` over HTTPS) | Authorization Code + PKCE (`S256`) on the code grant. The `client_peer_id` of the minted Biscuit is the calling node's when a node calls, otherwise the `actor_peer_id` form parameter or the control plane's own peer ID (`resolveDefaultActorPeer`). | A claimed peer ID (the Biscuit is a bearer token on the HTTPS `/mcp` hop unless sender-constrained with DPoP; see §5.2) | Single-use authorization codes with PKCE verifier check on the code exchange; none on the resulting bearer Biscuit. |
+| **OAuth 2.1 & external HTTP ingress surface** (`/oauth/authorize`, `/oauth/token`, node `/mcp` and router `/ingress/*` over HTTPS) | Authorization Code + PKCE (`S256`) on the code grant, or RFC 8693 token exchange (`POST /oauth/token`). External HTTPS callers have no libp2p connection, so `BaselineReplayCheck` (`client_peer_id == connection_peer_id`) is omitted on `/mcp` and `/ingress/*`; instead `/ingress/*` (`edge` mode) rejects `mesh:role:router` and unattenuated standing Member Biscuits, verifies signature, revocations, `tar_block`, and `ServiceIngress.allow` at the router before dialing any provider, and re-verifies end-to-end at the serving node over `/mesh/ingress/1.0.0`. | A claimed peer ID (the Biscuit is a bearer token on the HTTPS `/mcp` or `/ingress/*` hop unless sender-constrained with DPoP on `/mcp`; see §5.2) | Single-use authorization codes with PKCE verifier check on the code exchange; authority-block revocation (`GET /revocations`) and short TTL on the resulting bearer Biscuit. |
---
@@ -526,10 +532,13 @@ redemption of the last Biscuit issued to the peer.
### 5.2 Optional DPoP (RFC 9449) at the OAuth 2.1 border
Inside the mesh, libp2p channel binding (`client_peer_id == connection_peer_id`)
-provides per-connection proof of possession between nodes. An external MCP
-client, however, reaches a node's `/mcp` ingress over HTTPS with no libp2p
-channel, so the Biscuit minted for it at `/oauth/token` carries a claimed
-`client_peer_id` and is a bearer token on that HTTPS hop.
+provides per-connection proof of possession between nodes. An external HTTP
+client, however, reaches a node's `/mcp` ingress or a router's `/ingress/*`
+(`edge` mode) over HTTPS with no libp2p channel, so `BaselineReplayCheck`
+cannot bind the request to a libp2p stream; the Biscuit minted at
+`/oauth/token` carries a claimed `client_peer_id` and acts as a bearer token on
+that HTTPS hop (with `mesh:role:router` and unattenuated standing Member
+Biscuits explicitly refused on `/ingress/*`).
DPoP (RFC 9449) is the standard mechanism to sender-constrain that external
OAuth hop: when a client sends a `DPoP` header at `/oauth/token`, the control
@@ -538,10 +547,10 @@ as `client_key_thumbprint("<jkt>")` in the Biscuit authority block, and returns
`token_type: DPoP`, and the node's `/mcp` ingress verifies the `DPoP` proof with
`ath` over the Biscuit and checks
`client_key_thumbprint($t), connection_key_thumbprint($t)`. Because the MCP
-authorization specification does not require DPoP and off-the-shelf MCP clients
-(Claude Code, Gemini CLI, Cursor, VS Code) only send Authorization Code + PKCE
-today, DPoP is optional (`dpop_bound_access_tokens_required: false`) and a
-Biscuit minted without a `DPoP` proof remains a bearer token at `/mcp`.
+and A2A specifications do not require DPoP and off-the-shelf MCP and A2A clients
+(Claude Code, Gemini CLI, Cursor, VS Code, `a2aclient`) only send bearer tokens
+over TLS today, DPoP is optional (`dpop_bound_access_tokens_required: false`) on
+`/mcp` and omitted on `/ingress/*`.
### 5.3 No built-in Azure or AWS IMDS node enrollment `TokenSource`
diff --git a/site/content/docs/guides/external-ingress.md b/site/content/docs/guides/external-ingress.md
index 86d83882..83eb4344 100644
--- a/site/content/docs/guides/external-ingress.md
+++ b/site/content/docs/guides/external-ingress.md
@@ -44,8 +44,10 @@ administrator and the node owner opt in:
## What the admin writes
In `agentmesh-one` development mode (no `--policy-file`), `mesh:role:node`
-includes `allowed_ingress` out of the box so local relays and Cloud Run sandboxes
-work with zero configuration.
+grants `INGRESS_AUTH_MODE_EDGE` on `*` out of the box so zero-trust external
+ingress works with zero configuration. `INGRESS_AUTH_MODE_PASSTHROUGH` is never
+granted by default, even in `agentmesh-one`: pass `--policy-file` or update the
+policy via `POST /policies` to enable `passthrough` for a role.
On a production mesh, grant `allowed_ingress` on the serving node's role and
bind external callers to a role whose `allowed_services` and `allowed_targets`
@@ -94,8 +96,8 @@ Add `ingress:` to any `a2a`, `mcp`, or `inference` entry in `agentmesh-node.yaml
```yaml
version: "v1alpha1"
services:
- # Zero-trust default (auth_mode: edge): router + node verify OAuth/OIDC/Biscuit
- # identity and evaluate Datalog RBAC, TAR attenuation, and optional allow list.
+ # Zero-trust default (auth_mode: edge): router + node verify a Delegated
+ # Session Biscuit and evaluate Datalog RBAC, TAR attenuation, and allow list.
- type: a2a
name: coder
target_url: "http://127.0.0.1:9001"
@@ -121,31 +123,41 @@ from the mesh's router lease and exposes it in `agentmesh-node debug services`:
[Ingress] Published a2a://coder at https://bananas.sam-mesh.dev/ingress/12D3KooW.../a2a/coder (auth_mode=edge)
```
+If the node's mesh role does not grant external exposure for that service or
+auth mode, `agentmesh-node` logs an error, increments
+`agentmesh_node_service_provide_failures_total{scope="ingress"}`, and falls back
+to announcing the service internally so mesh peers can still reach it.
+
## How `edge` and `passthrough` behave
### `auth_mode: edge` (default)
-1. Unauthenticated requests receive `401 Unauthorized` with an RFC 9728 header:
+1. Unauthenticated requests (and requests carrying a raw platform JWT) receive
+ `401 Unauthorized` with an RFC 9728 header:
`WWW-Authenticate: Bearer resource_metadata="<public-url>/ingress/.well-known/oauth-protected-resource"`.
-2. External callers present `Authorization: Bearer <token>`, where `<token>` is
- either:
- - a **Delegated Session Biscuit** minted by the control plane's OAuth 2.1
- Authorization Server (`/oauth/authorize` + `/oauth/token`) or
- `POST /token/exchange` (optionally attenuated with a
- `TaskAuthorizationRule`), or
- - a **trusted OIDC JWT** issued by the mesh's `oidc_issuer`.
-3. Both the router (at the network edge) and the serving node (defense in depth
- over `/mesh/ingress/1.0.0`) verify the caller's identity and enforce the
- intersection of mesh Datalog RBAC, any appended `TaskAuthorizationRule`
- (including MCP `tools/call` tool names), `ServiceIngress.allow`, and local
+2. External callers present `Authorization: Bearer <biscuit>`, where `<biscuit>`
+ is a **Delegated Session Biscuit** minted by the control plane's OAuth 2.1
+ Authorization Server (`/oauth/authorize` + `/oauth/token`) or RFC 8693 token
+ exchange (`POST /oauth/token` or `POST /token/exchange`), optionally
+ attenuated with a `TaskAuthorizationRule`. Callers holding an OIDC JWT
+ exchange it once at `POST /oauth/token` into a Delegated Session Biscuit so
+ `agentmesh-router` stays purely on Ed25519 Biscuit verification with zero
+ IdP JWKS network dependencies. `mesh:role:router` Biscuits and unattenuated
+ standing node Biscuits (`node(...)` without a `tar_block`) are rejected.
+3. The router verifies the Biscuit signature, authority revocation ID, banned
+ peer status, `TaskAuthorizationRule` chain (including MCP `tools/call` tool
+ names), and `ServiceIngress.allow` locally **before** dialing any provider
+ node. Once admitted, both the router and the serving node (defense in depth
+ over `/mesh/ingress/1.0.0`) enforce the full intersection of mesh Datalog
+ RBAC, `TaskAuthorizationRule`, `ServiceIngress.allow`, and local
`agentmesh-node.yaml` `attenuation`.
4. The external `Authorization` header is stripped before reaching the local
backend (replaced only if `target_auth_path` is configured on the node).
5. For `a2a` services, unauthenticated `GET` requests to the service root or
`/.well-known/agent-card.json` return the backend's A2A `AgentCard` with
`supportedInterfaces[].url` rewritten to the public `/ingress/...` URL,
- `signatures` cleared, and `securitySchemes` populated with `bearer`,
- `agentmesh_oauth2`, and `oidc`.
+ `signatures` cleared, and `securitySchemes` populated with `bearer`
+ (`bearerFormat: "Biscuit"`) and `agentmesh_oauth2`.
### `auth_mode: passthrough` (opt-in)
@@ -155,6 +167,11 @@ header untouched over `/mesh/ingress/1.0.0` while stripping `Cookie` and
`X-Mesh-*` headers and preserving the backend's own `AgentCard`
`securitySchemes`.
+Combining `auth_mode: passthrough` with `target_auth_path` or inline credentials
+in `target_url` (`http://user:pass@host`) is rejected at config validation and
+service registration so node-local static backend credentials can never be
+injected on unauthenticated external passthrough routes.
+
## Operator deployment
### `agentmesh-one` (local, VM, or Cloud Run)
@@ -173,6 +190,7 @@ agentmesh-one --external-url https://my-hub.run.app --data-dir /data
```text
--ingress-addr=0.0.0.0:8080
--ingress-url=https://hub.example.com/ingress
+ --public-control-plane=https://hub.example.com
--allow-insecure-ingress-http
```
(Or terminate TLS directly on the router with `--ingress-tls-cert-path` and
@@ -183,7 +201,12 @@ agentmesh-one --external-url https://my-hub.run.app --data-dir /data
Because routers federate their directory and circuit relays, any router pod
can serve `/ingress/<peer_id>/...` regardless of which router pod holds the
node's relay reservation.
-3. With the Helm chart (`charts/agentmesh`), `router.ingressPort` (`8090` by
+3. Authenticated `edge` requests are rate-limited per verified Biscuit identity
+ at the router. Because routers behind an L7 `Gateway` see the proxy's
+ internal source IP on TCP `RemoteAddr`, configure per-client source-IP rate
+ limiting at your L7 `Gateway` (for example Cloud Armor on GKE) to protect
+ unauthenticated `AgentCard` discovery and `passthrough` routes.
+4. With the Helm chart (`charts/agentmesh`), `router.ingressPort` (`8090` by
default) and `gateway.ingressRoute: true` configure both the router listener
and the `HTTPRoute` automatically when `gateway.enabled: true`. Set
`router.ingressUrl` (e.g. `https://hub.example.com/ingress`),
diff --git a/site/content/docs/reference/router.md b/site/content/docs/reference/router.md
index 8b9c180b..93034bb2 100644
--- a/site/content/docs/reference/router.md
+++ b/site/content/docs/reference/router.md
@@ -52,7 +52,6 @@ replica count.
| `--ingress-url` | none | Public base URL advertised in the router's lease and rewritten into A2A `AgentCard` and RFC 9728 metadata (for example `https://hub.example.com/ingress`). |
| `--ingress-tls-cert-path`, `--ingress-tls-key-path` | none | TLS certificate and private key for `--ingress-addr`. |
| `--allow-insecure-ingress-http` | `false` | Permit plaintext HTTP on a non-loopback `--ingress-addr` (behind a TLS-terminating L7 proxy) and `http://` in `--ingress-url`. |
-| `--oidc-issuer`, `--audience` | from `/info` | Optional overrides for OIDC JWT verification on `edge` ingress requests. |
| `--public-control-plane` | derived | Optional public control-plane URL advertised in RFC 9728 and A2A OAuth metadata when `--control-plane` is an internal address. |
| `--pprof-addr` | off | Serve Go runtime profiles under `/debug/pprof/` on this address, for attributing memory or goroutines the metrics show as held. Unauthenticated, and a heap profile is a dump of process memory, which holds the router's key: bind it to loopback and reach it with `kubectl port-forward`. |
| `--log-level` | `info` | `debug`, `info`, `warn`, `error`. |
@@ -150,7 +149,7 @@ The metrics address exposes, next to the Go runtime metrics:
| `agentmesh_router_connection_watermark{level}` | The `low` and `high` watermarks in force. The gap between `inbound` connections and the `high` watermark is the free capacity. |
| `agentmesh_router_conns_per_source_ip_limit` | The per-address cap in force. |
| `agentmesh_router_relay_limit{limit}` | The relay budget in force: `reservations`, `reservations_per_ip` and `circuits_per_peer`. |
-| `agentmesh_router_connected_peers`, `agentmesh_router_authenticated_peers`, `agentmesh_router_banned_peers` | Peers in each state. |
+| `agentmesh_router_connected_peers`, `agentmesh_router_authenticated_peers`, `agentmesh_router_banned_peers`, `agentmesh_router_revoked_tokens` | Peers in each state and non-expired authority revocation IDs currently enforced by the router. |
| `agentmesh_router_peer_routers{state}` | Other routers this one knows, from the control plane's list or a handshake that proved the router role: `listed`, and `authenticated` for those it currently holds a mutual authentication with. The two differ while a federation pass is pending or a peer router is down. |
| `agentmesh_router_dht_routing_table_size` | Peer routers in the DHT's routing table: the authenticated peer routers, since nothing else enters it. |
| `agentmesh_router_directory_requests_total{op,result}`, `agentmesh_router_directory_request_seconds{op}` | Directory requests served, by operation (`provide`, `withdraw`, `find_providers`, `find_peer`; `place` is a record or withdrawal another router put here, `lookup` a find another router ran here) and result (`ok`, `empty`, `invalid`, `denied` for a record naming a service the member's credential does not grant serving, `error`), with the time each took. |
@@ -164,6 +163,7 @@ The metrics address exposes, next to the Go runtime metrics:
| `agentmesh_router_inbound_connections_refused_total{reason}` | Inbound connections the router refused before the handshake, by reason. `per_ip_limit` is the per-address cap. `rate_limit` is the per-address rate limit on new connections. `scope_limit` is libp2p's connection cap. `scope_limit` also counts a connection refused while more than half that cap are still in TLS or Noise setup. `other` is any other refusal. |
| `agentmesh_router_streams_refused_total{scope,protocol}` | Streams refused, by scope and protocol or service. `scope="unauthenticated"` is a stream from a peer that never passed the handshake, reset when its connection closed; a steady rate is a scanner, or a member whose handshake fails. The other scopes are the resource manager's: a count on `/mesh/kad/1.0.0` or a `/meshsub/*` protocol there is members the router keeps out of discovery; see the scalability guide. |
| `agentmesh_router_busiest_connection_streams{transport}` | The most streams any one connection carries. The connection to a service the router relays for holds one stream per relayed caller, and QUIC admits 256 per connection; see the scalability guide. |
+| `agentmesh_router_ingress_requests_total{auth_mode,outcome}`, `agentmesh_router_ingress_request_duration_seconds{auth_mode}` | External HTTP ingress requests served under `/ingress/` (`auth_mode` in `edge`, `passthrough`, `metadata`, `unknown`; `outcome` in `allow`, `unauthenticated`, `forbidden`, `not_found`, `rate_limited`, `unavailable`, `bad_gateway`) and their duration. |
| `libp2p_relaysvc_*` | The relay service's own counters: `reservations_total{type}` and `connections_total{type}` (`opened`, `closed`, `renewed`), requests by response status, rejections and bytes relayed. The difference between `opened` and `closed` is the number in use; read it against `agentmesh_router_relay_limit` to see how close the relay is to its budget. |
A fleet is at capacity when `agentmesh_router_connections{direction="inbound"}`
diff --git a/tests/integration/ingress_test.go b/tests/integration/ingress_test.go
index bf57ba4a..faf22f17 100644
--- a/tests/integration/ingress_test.go
+++ b/tests/integration/ingress_test.go
@@ -82,6 +82,37 @@ func postOperatorPolicy(t *testing.T, ctx context.Context, baseURL, adminToken s
}
}
+func exchangeJWTForBiscuit(t *testing.T, cpURL, jwtStr, optionsJSON string, seal bool) string {
+ t.Helper()
+ form := url.Values{
+ "grant_type": {api.GrantTypeTokenExchange},
+ "subject_token": {jwtStr},
+ "subject_token_type": {"urn:ietf:params:oauth:token-type:id_token"},
+ }
+ if optionsJSON != "" {
+ form.Set("options", optionsJSON)
+ }
+ if seal {
+ form.Set("seal", "true")
+ }
+ resp, err := (&http.Client{Timeout: 5 * time.Second}).PostForm(cpURL+"/oauth/token", form)
+ if err != nil {
+ t.Fatalf("POST /oauth/token: %v", err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("POST /oauth/token = %s: %s", resp.Status, body)
+ }
+ var out struct {
+ AccessToken string `json:"access_token"`
+ }
+ if err := json.Unmarshal(body, &out); err != nil || out.AccessToken == "" {
+ t.Fatalf("decode /oauth/token response: %v (%s)", err, body)
+ }
+ return out.AccessToken
+}
+
func enrollAndStartRuntimeNode(
t *testing.T,
ctx context.Context,
@@ -186,13 +217,13 @@ func enrollAndStartRuntimeNode(
// - RFC 9728 OAuth Protected Resource metadata at /ingress/.well-known/oauth-protected-resource
// - Internal-only services remain 404 on /ingress/...
// - Default EDGE mode: unauthenticated A2A AgentCard discovery with public URL & SecuritySchemes rewrite,
-// OIDC JWT + ServiceIngress.allow ACL enforcement, stock A2A SendMessage & SSE SendStreamingMessage,
-// signed X-AgentMesh-Identity-Evidence delivery to the backend, and RFC 8693 /oauth/token Delegated
-// Session Biscuit with TAR MCP tool attenuation
-// - Opt-in PASSTHROUGH mode: upstream Bearer pair token preserved end-to-end while spoofed X-AgentMesh-*
+// raw JWT rejection (401 + RFC 9728 WWW-Authenticate), RFC 8693 /oauth/token Delegated Session Biscuit
+// - ServiceIngress.allow ACL enforcement, stock A2A SendMessage & SSE SendStreamingMessage,
+// X-Mesh-Principal delivery to the backend, and TAR MCP tool attenuation
+// - Opt-in PASSTHROUGH mode: upstream Bearer pair token preserved end-to-end while spoofed X-Mesh-*
// headers are stripped.
func TestStandaloneExternalIngressCUJ(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
oidcURL, mintJWT := startCustomMockOIDC(t)
@@ -389,8 +420,8 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) {
if prm.Resource != srv.IngressURL() {
t.Errorf("PRM resource = %q, want %q", prm.Resource, srv.IngressURL())
}
- if len(prm.AuthorizationServers) < 2 || prm.AuthorizationServers[0] != srv.PublicURL() || prm.AuthorizationServers[1] != oidcURL {
- t.Errorf("PRM authorization_servers = %v, want [%s %s]", prm.AuthorizationServers, srv.PublicURL(), oidcURL)
+ if len(prm.AuthorizationServers) != 1 || prm.AuthorizationServers[0] != srv.PublicURL() {
+ t.Errorf("PRM authorization_servers = %v, want [%s]", prm.AuthorizationServers, srv.PublicURL())
}
// Internal-only service (ingress == nil) is never exposed on /ingress/...
@@ -443,9 +474,25 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) {
t.Fatalf("unauthenticated POST = %d WWW-Authenticate=%q, want 401 with resource_metadata", unauthResp.StatusCode, unauthResp.Header.Get("WWW-Authenticate"))
}
- // OIDC caller permitted by mesh role ("external-caller") but excluded by ServiceIngress.allow gets 403.
+ // Raw OIDC JWT presented directly to /ingress/ is rejected with 401 + RFC 9728 WWW-Authenticate
+ // (external callers exchange JWTs at POST /oauth/token into Delegated Session Biscuits).
+ yaroslavJWT := mintJWT(map[string]any{"sub": "yaroslav-sub", "email": "[email protected]"})
+ rawJWTReq, _ := http.NewRequestWithContext(ctx, http.MethodPost, wantInvokeURL, strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"message/send"}`))
+ rawJWTReq.Header.Set("Content-Type", "application/json")
+ rawJWTReq.Header.Set("Authorization", "Bearer "+yaroslavJWT)
+ rawJWTResp, err := httpClient.Do(rawJWTReq)
+ if err != nil {
+ t.Fatalf("raw JWT POST: %v", err)
+ }
+ _ = rawJWTResp.Body.Close()
+ if rawJWTResp.StatusCode != http.StatusUnauthorized || !strings.Contains(rawJWTResp.Header.Get("WWW-Authenticate"), "/.well-known/oauth-protected-resource") {
+ t.Fatalf("raw JWT POST = %d WWW-Authenticate=%q, want 401 with resource_metadata", rawJWTResp.StatusCode, rawJWTResp.Header.Get("WWW-Authenticate"))
+ }
+
+ // Delegated Session Biscuit permitted by mesh role ("external-caller") but excluded by ServiceIngress.allow gets 403.
otherJWT := mintJWT(map[string]any{"sub": "other-sub", "email": "[email protected]"})
- deniedClient, err := a2aclient.NewFromCard(ctx, publicCoderCard, a2aclient.WithJSONRPCTransport(bearerClient(otherJWT, nil)))
+ otherBiscuit := exchangeJWTForBiscuit(t, srv.PublicURL(), otherJWT, "", false)
+ deniedClient, err := a2aclient.NewFromCard(ctx, publicCoderCard, a2aclient.WithJSONRPCTransport(bearerClient(otherBiscuit, nil)))
if err != nil {
t.Fatalf("NewFromCard(other): %v", err)
}
@@ -453,9 +500,9 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) {
t.Fatal("SendMessage with caller excluded by ServiceIngress.allow succeeded, want error")
}
- // Authorized OIDC caller succeeds on both SendMessage and SSE SendStreamingMessage.
- yaroslavJWT := mintJWT(map[string]any{"sub": "yaroslav-sub", "email": "[email protected]"})
- allowedClient, err := a2aclient.NewFromCard(ctx, publicCoderCard, a2aclient.WithJSONRPCTransport(bearerClient(yaroslavJWT, nil)))
+ // Authorized Delegated Session Biscuit succeeds on both SendMessage and SSE SendStreamingMessage.
+ yaroslavBiscuit := exchangeJWTForBiscuit(t, srv.PublicURL(), yaroslavJWT, "", false)
+ allowedClient, err := a2aclient.NewFromCard(ctx, publicCoderCard, a2aclient.WithJSONRPCTransport(bearerClient(yaroslavBiscuit, nil)))
if err != nil {
t.Fatalf("NewFromCard(yaroslav): %v", err)
}
@@ -489,28 +536,7 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) {
// Exchange OIDC JWT at POST /oauth/token into a TAR-attenuated, sealed Session Biscuit
// scoped exclusively to mcp://tools tool "read_file".
tarJSON := `{"name":"read-only","rules":[{"allowed_services":["mcp://tools"],"operation":{"allowed_tools":["read_file"]}}]}`
- form := url.Values{
- "grant_type": {api.GrantTypeTokenExchange},
- "subject_token": {yaroslavJWT},
- "subject_token_type": {"urn:ietf:params:oauth:token-type:id_token"},
- "options": {tarJSON},
- "seal": {"true"},
- }
- tokResp, err := httpClient.PostForm(srv.PublicURL()+"/oauth/token", form)
- if err != nil {
- t.Fatalf("POST /oauth/token: %v", err)
- }
- tokBody, _ := io.ReadAll(tokResp.Body)
- _ = tokResp.Body.Close()
- if tokResp.StatusCode != http.StatusOK {
- t.Fatalf("POST /oauth/token = %s: %s", tokResp.Status, tokBody)
- }
- var oauthOut struct {
- AccessToken string `json:"access_token"`
- }
- if err := json.Unmarshal(tokBody, &oauthOut); err != nil || oauthOut.AccessToken == "" {
- t.Fatalf("decode /oauth/token response: %v (%s)", err, tokBody)
- }
+ tarBiscuit := exchangeJWTForBiscuit(t, srv.PublicURL(), yaroslavJWT, tarJSON, true)
mcpURL := fmt.Sprintf("%s/%s/mcp/tools", srv.IngressURL(), peerID)
mcpCli := mcp.NewClient(&mcp.Implementation{Name: "external-mcp-caller", Version: "1.0.0"}, nil)
@@ -519,7 +545,7 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) {
for {
mcpSess, err = mcpCli.Connect(ctx, &mcp.StreamableClientTransport{
Endpoint: mcpURL,
- HTTPClient: bearerClient(oauthOut.AccessToken, nil),
+ HTTPClient: bearerClient(tarBiscuit, nil),
}, nil)
if err == nil {
break
@@ -589,10 +615,12 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) {
// Router A (tier=relay), is reachable through Router B's standalone --ingress-addr HTTP gateway
// over Router A's circuit relay (/p2p/<routerA>/p2p-circuit/p2p/<node>).
// - PolicyRole.allowed_ingress ceiling: when mesh:role:node grants EDGE only on a2a://coder,
-// attempting to expose a2a://ungranted (PASSTHROUGH) is refused by the router directory.
+// attempting to expose a2a://ungranted (PASSTHROUGH) is refused on external ingress (404 on Router B)
+// while automatically falling back to plain internal directory announcement so mesh peers can still
+// discover a2a://ungranted internally.
// - Banning the provider node via POST /admin/revoke immediately causes Router B to return 404.
func TestFederatedMultiRouterIngressRoleCeilingAndBan(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
oidcURL, mintJWT := startCustomMockOIDC(t)
@@ -782,7 +810,8 @@ func TestFederatedMultiRouterIngressRoleCeilingAndBan(t *testing.T) {
time.Sleep(100 * time.Millisecond)
}
- // Ungranted PASSTHROUGH service was rejected by Router A's directory ceiling check -> 404 on Router B.
+ // Ungranted PASSTHROUGH service was rejected on external ingress -> 404 on Router B,
+ // while announceServiceKeys fell back to plain Provide so internal mesh discovery still finds it.
ungrantedResp, err := httpClient.Get(fmt.Sprintf("%s/%s/a2a/ungranted/.well-known/agent-card.json", ingressBaseB, peerID))
if err != nil {
t.Fatalf("GET ungranted passthrough service: %v", err)
@@ -791,10 +820,29 @@ func TestFederatedMultiRouterIngressRoleCeilingAndBan(t *testing.T) {
if ungrantedResp.StatusCode != http.StatusNotFound {
t.Fatalf("ungranted passthrough service status = %d, want 404", ungrantedResp.StatusCode)
}
+ ungrantedKey, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_A2A, "ungranted")
+ if err != nil {
+ t.Fatalf("ServiceKey(a2a, ungranted): %v", err)
+ }
+ internalProviders, err := provider.Directory.FindProviders(ctx, ungrantedKey, 10)
+ if err != nil {
+ t.Fatalf("FindProviders(a2a://ungranted): %v", err)
+ }
+ foundInternal := false
+ for _, pi := range internalProviders {
+ if pi.ID == peerID {
+ foundInternal = true
+ break
+ }
+ }
+ if !foundInternal {
+ t.Fatalf("a2a://ungranted missing from internal directory after ingress ceiling refusal; got providers %v", internalProviders)
+ }
- // External caller invokes a2a://coder through Router B -> Router A circuit relay -> private node.
+ // External caller exchanges OIDC JWT at POST /oauth/token and invokes a2a://coder through Router B -> Router A circuit relay -> private node.
alanJWT := mintJWT(map[string]any{"sub": "alan-sub", "email": "[email protected]"})
- a2aCli, err := a2aclient.NewFromCard(ctx, resolvedCard, a2aclient.WithJSONRPCTransport(bearerClient(alanJWT, nil)))
+ alanBiscuit := exchangeJWTForBiscuit(t, cpURL, alanJWT, "", false)
+ a2aCli, err := a2aclient.NewFromCard(ctx, resolvedCard, a2aclient.WithJSONRPCTransport(bearerClient(alanBiscuit, nil)))
if err != nil {
t.Fatalf("NewFromCard(alan): %v", err)
}