Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
fix relay issues
Antonio Ojeae45dd7636c63
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.goindex e7eb49b1..ecbb6cee 100644--- a/cmd/sam-hub/main.go+++ b/cmd/sam-hub/main.go@@ -15,6 +15,8 @@package mainimport (+ "io"+"github.com/libp2p/go-libp2p/core/network""github.com/prometheus/client_golang/prometheus""github.com/prometheus/client_golang/prometheus/promhttp"@@ -256,6 +258,13 @@ func NewHub(ctx context.Context, policy *api.PolicyConfig, allowLoopback bool) (auds = []string{api.DefaultAudience}}+ var filteredExternal []string+ for _, addr := range externalMultiaddrs {+ if !strings.HasPrefix(addr, "http://") && !strings.HasPrefix(addr, "https://") {+ filteredExternal = append(filteredExternal, addr)+ }+ }+hub := &Hub{Host: h,DHT: kadDHT,@@ -264,7 +273,7 @@ func NewHub(ctx context.Context, policy *api.PolicyConfig, allowLoopback bool) (MeshID: meshName,Policy: policy,limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),- ExternalAddrs: externalMultiaddrs,+ ExternalAddrs: filteredExternal,AllowedAudiences: auds,AllowLoopback: allowLoopback,}@@ -943,6 +952,57 @@ func startBootstrapFederation(ctx context.Context, h *Hub, peers []string) {func connectBootstrap(ctx context.Context, h *Hub, peers []string) {for _, peerStr := range peers {+ if strings.HasPrefix(peerStr, "http://") || strings.HasPrefix(peerStr, "https://") {+ client := &http.Client{Timeout: 10 * time.Second}+ resp, err := client.Get(peerStr + "/info")+ if err != nil {+ logger.Errorf("[Federation] HTTP Get error for %s: %v", peerStr, err)+ continue+ }++ bodyBytes, err := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ if err != nil {+ logger.Errorf("[Federation] ReadAll error: %v", err)+ continue+ }++ var info api.HubInfoResponse+ if err := proto.Unmarshal(bodyBytes, &info); err != nil {+ logger.Errorf("[Federation] Proto unmarshal error: %v", err)+ continue+ }++ for _, addrStr := range info.HubAddresses {+ ma, err := multiaddr.NewMultiaddr(addrStr)+ if err != nil {+ logger.Errorf("[Federation] Multiaddr error: %v", err)+ continue+ }++ pi, err := peer.AddrInfoFromP2pAddr(ma)+ if err != nil {+ logger.Errorf("[Federation] AddrInfo error: %v", err)+ continue+ }++ if pi.ID == h.Host.ID() {+ continue+ }++ if len(h.Host.Network().ConnsToPeer(pi.ID)) > 0 {+ continue+ }++ if err := h.Host.Connect(ctx, *pi); err == nil {+ logger.Infof("[Federation] Connected to bootstrap peer: %s via HTTP %s", pi.ID, peerStr)+ } else {+ logger.Errorf("[Federation] Failed to connect to %s: %v", pi.ID, err)+ }+ }+ continue+ }+ma, err := multiaddr.NewMultiaddr(peerStr)if err != nil {continuediff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.goindex 9f62d77b..d2dbaeee 100644--- a/cmd/sam-node/mcp.go+++ b/cmd/sam-node/mcp.go@@ -17,11 +17,14 @@ package mainimport ("context""encoding/json"+ "errors""fmt""net/http"+ "strings""time""github.com/google/sam/api"+ "github.com/libp2p/go-libp2p/core/network""github.com/libp2p/go-libp2p/core/peer""github.com/libp2p/go-libp2p/core/peerstore""github.com/libp2p/go-msgio"@@ -151,6 +154,10 @@ func (n *SamNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, toolNameif err == nil {return res, nil}+ if errors.Is(err, context.DeadlineExceeded) || strings.Contains(err.Error(), "context deadline exceeded") {+ logger.Warnf("[MCP] Tool call failed with timeout, not retrying: %v", err)+ return nil, err+ }logger.Warnf("[MCP] Tool call failed, retrying in %v: %v", backoff, err)timer := time.NewTimer(backoff)select {@@ -167,7 +174,10 @@ func (n *SamNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, toolNamefunc (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolName string, params any) (*mcp.CallToolResult, error) {// Open streamlogger.Debugf("Dialing %s for MCP...\n", targetPeer)- dialCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ dialCtx, cancel := context.WithTimeout(ctx, 15*time.Second)+ // Allow limited connections (like circuit relays) to be used for this stream.+ // Otherwise libp2p will hang waiting for a direct connection!+ dialCtx = network.WithAllowLimitedConn(dialCtx, "mcp")defer cancel()s, err := n.Host.NewStream(dialCtx, targetPeer, api.MCPProtocolID)if err != nil {@@ -274,9 +284,14 @@ func (n *SamNode) fetchRemoteServiceCatalog(ctx context.Context, peerID peer.ID,// This prevents dial backoff errors when the relay is behind a load-balanced DNS address.func (n *SamNode) resolveRelayAddresses(ctx context.Context, targetPeer peer.ID) {if n.Host == nil || n.DHT == nil {+ logger.Debugf("[Discovery] Host or DHT is nil")return}addrs := n.Host.Peerstore().Addrs(targetPeer)+ logger.Debugf("[Discovery] resolveRelayAddresses for %s: found %d addrs in peerstore", targetPeer, len(addrs))++ var validCircuitAddrs []multiaddr.Multiaddr+for _, ma := range addrs {parts := multiaddr.Split(ma)if len(parts) < 2 {@@ -287,6 +302,9 @@ func (n *SamNode) resolveRelayAddresses(ctx context.Context, targetPeer peer.ID)continue}+ // Keep the advertised circuit address+ validCircuitAddrs = append(validCircuitAddrs, ma)+p2pPart := parts[len(parts)-2]if p2pPart.Protocol().Code != multiaddr.P_P2P {continue@@ -294,27 +312,25 @@ func (n *SamNode) resolveRelayAddresses(ctx context.Context, targetPeer peer.ID)relayID, err := peer.Decode(p2pPart.Value())if err != nil {+ logger.Debugf("[Discovery] Failed to decode relayID: %v", err)continue}- // Found a relay. Let's find its direct IPs via DHT.- pi, err := n.DHT.FindPeer(ctx, relayID)- if err != nil || len(pi.Addrs) == 0 {- continue- }+ logger.Debugf("[Discovery] Found relay %s for target %s", relayID, targetPeer)- for _, relayAddr := range pi.Addrs {- // Check if it's a direct IP (not dns)- protocols := relayAddr.Protocols()- if len(protocols) == 0 {- continue- }- code := protocols[0].Code- if code == multiaddr.P_IP4 || code == multiaddr.P_IP6 {- circuitPart, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s/p2p-circuit", relayID.String()))- newMa := relayAddr.Encapsulate(circuitPart)- n.Host.Peerstore().AddAddr(targetPeer, newMa, peerstore.TempAddrTTL)- }+ circuitAddr, err := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s/p2p-circuit", relayID.String()))+ if err == nil {+ logger.Debugf("[Discovery] Added generic relay circuit address for %s: %s", targetPeer, circuitAddr.String())+ validCircuitAddrs = append(validCircuitAddrs, circuitAddr)+ } else {+ logger.Errorf("[Discovery] Failed to create circuit addr: %v", err)}}++ if len(validCircuitAddrs) > 0 {+ // Clear existing addresses to prevent libp2p from hanging on dead private IPs+ n.Host.Peerstore().ClearAddrs(targetPeer)+ n.Host.Peerstore().AddAddrs(targetPeer, validCircuitAddrs, peerstore.TempAddrTTL)+ logger.Infof("[Discovery] Replaced addrs for %s with %d circuit addrs", targetPeer, len(validCircuitAddrs))+ }}diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.goindex 7fcde2ff..0e3eeda3 100644--- a/cmd/sam-node/node.go+++ b/cmd/sam-node/node.go@@ -995,7 +995,7 @@ func (n *SamNode) IsServiceRegistered(serviceName string) bool {// reachable mesh can't wedge a discovery call indefinitely.const (dhtLookupTimeout = 5 * time.Second- discoveryFanoutTimeout = 15 * time.Second+ discoveryFanoutTimeout = 40 * time.Second)// findProvidersByCID is the shared DHT-lookup primitive; bounds the@@ -1236,6 +1236,7 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ logger.Infof("[Ingress] Received request: %s %s", r.Method, r.URL.Path)path := r.URL.Pathparts := strings.SplitN(strings.TrimPrefix(path, "/"), "/", 3)if len(parts) < 2 {@@ -1256,12 +1257,24 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {}svc, ok := n.services.Get(serviceName)- if !ok || svc.Handler() == nil {+ if !ok {+ logger.Errorf("[Ingress] Service not found: %s", serviceName)http.Error(w, "Service not found", http.StatusNotFound)return}+ if svc.Handler() == nil {+ logger.Errorf("[Ingress] Service %s has nil handler", serviceName)+ http.Error(w, "Service not found", http.StatusNotFound)+ return+ }+ logger.Infof("[Ingress] Forwarding to service %s, upstreamPath: %q", serviceName, upstreamPath)- r.URL.Path = "/" + upstreamPath+ if upstreamPath == "" {+ r.URL.Path = ""+ } else {+ r.URL.Path = "/" + upstreamPath+ }+ r.URL.RawPath = ""svc.Handler().ServeHTTP(w, r)}),}diff --git a/cmd/sam-node/service.go b/cmd/sam-node/service.goindex 16126e0f..fca3265d 100644--- a/cmd/sam-node/service.go+++ b/cmd/sam-node/service.go@@ -55,7 +55,21 @@ func newReverseProxyHandler(targetURL string) (http.Handler, error) {if err != nil {return nil, fmt.Errorf("invalid target URL: %w", err)}- return httputil.NewSingleHostReverseProxy(u), nil+ proxy := httputil.NewSingleHostReverseProxy(u)+ originalDirector := proxy.Director+ proxy.Director = func(req *http.Request) {+ originalPath := req.URL.Path+ originalDirector(req)++ // httputil.NewSingleHostReverseProxy automatically appends a trailing slash+ // when joining an empty request path with a target URL. If the client requested+ // the exact base path (empty) and the target doesn't natively end in a slash, strip it.+ if originalPath == "" && !strings.HasSuffix(u.Path, "/") && strings.HasSuffix(req.URL.Path, "/") {+ req.URL.Path = strings.TrimSuffix(req.URL.Path, "/")+ }+ logger.Debugf("[ReverseProxy] Forwarding to: %q", req.URL.String())+ }+ return proxy, nil}func (b *baseService) Info() *api.ServiceInfo { return b.info }diff --git a/cmd/sam-node/sidecar.go b/cmd/sam-node/sidecar.goindex 3be941b7..2092e931 100644--- a/cmd/sam-node/sidecar.go+++ b/cmd/sam-node/sidecar.go@@ -348,12 +348,18 @@ func createEgressProxy(node *SamNode) http.Handler {if len(parts) > 5 {upstreamPath = parts[5]}+ logger.Debugf("[Egress] Routing to peer: %s, svcType: %s, svcName: %s, upstream: %q", peerID, serviceType, serviceName, upstreamPath)req.URL.Scheme = "libp2p"req.URL.Host = peerIDreq.Host = peerID- req.URL.Path = fmt.Sprintf("/%s/%s/%s", serviceType, serviceName, upstreamPath)- logger.Infof("[Proxy] Rewriting URL to libp2p://%s%s", req.URL.Host, req.URL.Path)+ if upstreamPath == "" {+ req.URL.Path = fmt.Sprintf("/%s/%s", serviceType, serviceName)+ } else {+ req.URL.Path = fmt.Sprintf("/%s/%s/%s", serviceType, serviceName, upstreamPath)+ }+ req.URL.RawPath = ""+ logger.Debugf("[Proxy] Rewriting URL to libp2p://%s%s", req.URL.Host, req.URL.Path)},Transport: transport,}diff --git a/tests/e2e/fixtures/allow-anonymous-oidc.yaml b/tests/e2e/fixtures/allow-anonymous-oidc.yamlnew file mode 100644index 00000000..3b2b2734--- /dev/null+++ b/tests/e2e/fixtures/allow-anonymous-oidc.yaml@@ -0,0 +1,23 @@+apiVersion: rbac.authorization.k8s.io/v1+kind: ClusterRole+metadata:+ name: oidc-reader+rules:+- nonResourceURLs:+ - /.well-known/openid-configuration+ - /openid/v1/jwks+ verbs:+ - get+---+apiVersion: rbac.authorization.k8s.io/v1+kind: ClusterRoleBinding+metadata:+ name: allow-anonymous-oidc+roleRef:+ apiGroup: rbac.authorization.k8s.io+ kind: ClusterRole+ name: oidc-reader+subjects:+- kind: User+ name: system:anonymous+ apiGroup: rbac.authorization.k8s.iodiff --git a/tests/e2e/fixtures/sam-hub.yaml b/tests/e2e/fixtures/sam-hub.yamlnew file mode 100644index 00000000..70ee5787--- /dev/null+++ b/tests/e2e/fixtures/sam-hub.yaml@@ -0,0 +1,74 @@+apiVersion: v1+kind: ConfigMap+metadata:+ name: sam-hub-config+data:+ SAM_OIDC_ISSUER: "${ISSUER}"+ SAM_OIDC_ID: "sam-mesh-audience"+ SAM_HUB_KEY: "0000000000000000000000000000000000000000000000000000000000000000"+---+apiVersion: v1+kind: Service+metadata:+ name: sam-hub+spec:+ clusterIP: None+ ports:+ - name: http+ port: 9090+ targetPort: 9090+ - port: 4501+ targetPort: 4501+ protocol: TCP+ name: p2p-tcp+ - port: 4501+ targetPort: 4501+ protocol: UDP+ name: p2p-udp+ selector:+ app: sam-hub+---+apiVersion: apps/v1+kind: StatefulSet+metadata:+ name: sam-hub+spec:+ serviceName: "sam-hub"+ replicas: 2+ selector:+ matchLabels:+ app: sam-hub+ template:+ metadata:+ labels:+ app: sam-hub+ spec:+ containers:+ - name: sam-hub+ image: sam-hub:local+ args:+ - "--issuer"+ - "${ISSUER}"+ - "--key"+ - "0000000000000000000000000000000000000000000000000000000000000000"+ - "--insecure-skip-tls-verify"+ - "--listen=/ip4/0.0.0.0/tcp/4501"+ - "--listen=/ip4/0.0.0.0/udp/4501/quic-v1"+ - "--external-multiaddr=/dns4/sam-hub.default.svc.cluster.local/tcp/4501"+ - "--external-multiaddr=/dns4/sam-hub.default.svc.cluster.local/udp/4501/quic-v1"+ - "--external-multiaddr=http://sam-hub-0.sam-hub.default.svc.cluster.local:9090"+ - "--external-multiaddr=http://sam-hub-1.sam-hub.default.svc.cluster.local:9090"+ - "--allow-loopback"+ envFrom:+ - configMapRef:+ name: sam-hub-config+ ports:+ - containerPort: 9090+ hostPort: 9090+ protocol: TCP+ - containerPort: 4501+ hostPort: 4501+ protocol: TCP+ - containerPort: 4501+ hostPort: 4501+ protocol: UDPdiff --git a/tests/e2e/fixtures/sam-node.yaml b/tests/e2e/fixtures/sam-node.yamlnew file mode 100644index 00000000..2a099b3b--- /dev/null+++ b/tests/e2e/fixtures/sam-node.yaml@@ -0,0 +1,39 @@+apiVersion: apps/v1+kind: Deployment+metadata:+ name: sam-node+spec:+ replicas: 2+ selector:+ matchLabels:+ app: sam-node+ template:+ metadata:+ labels:+ app: sam-node+ spec:+ serviceAccountName: sam-node-sa+ containers:+ - name: sam-node+ image: sam-node:local+ command: ["/sam-node", "run"]+ args:+ - "--hub"+ - "http://sam-hub.default.svc.cluster.local:9090"+ - "--jwt-path"+ - "/var/run/secrets/tokens/sam-token"+ - "--api-token"+ - "secret-token"+ - "--allow-loopback"+ volumeMounts:+ - name: sam-token+ mountPath: /var/run/secrets/tokens+ readOnly: true+ volumes:+ - name: sam-token+ projected:+ sources:+ - serviceAccountToken:+ path: sam-token+ expirationSeconds: 3600+ audience: "sam-mesh-audience"diff --git a/tests/e2e/kind_wi.bats b/tests/e2e/kind_wi.batsdeleted file mode 100644index b167c241..00000000--- a/tests/e2e/kind_wi.bats+++ /dev/null@@ -1,198 +0,0 @@-#!/usr/bin/env bats--setup() {- # We use a unique cluster name to avoid conflicts- CLUSTER_NAME="sam-wi-test-$RANDOM"-- # Create Kind cluster- kind create cluster --name "${CLUSTER_NAME}"-- # Load images into Kind- kind load docker-image sam-hub:local --name "${CLUSTER_NAME}"- kind load docker-image sam-node:local --name "${CLUSTER_NAME}"-}--teardown() {- echo "=== Hub Logs ==="- kubectl logs -l app=sam-hub --tail=-1 || true- echo "=== Node Logs ==="- kubectl logs -l app=sam-node --tail=-1 || true- kind delete cluster --name "${CLUSTER_NAME}"-}--k8s_wait_for_log() {- local pod="$1"- local needle="$2"- local timeout_s="${3:-20}"- local i- for ((i=0; i<timeout_s*10; i++)); do- if kubectl logs "${pod}" 2>&1 | grep -q "${needle}"; then- return 0- fi- sleep 0.1- done- return 1-}--@test "Workload Identity Federation in Kind" {- # 1. Get the issuer URL- local issuer- issuer=$(kubectl get --raw /.well-known/openid-configuration | jq -r .issuer)- [[ -n "${issuer}" ]]-- # 1.5. Grant anonymous access to OIDC discovery- cat <<EOF | kubectl apply -f --apiVersion: rbac.authorization.k8s.io/v1-kind: ClusterRole-metadata:- name: oidc-reader-rules:-- nonResourceURLs:- - /.well-known/openid-configuration- - /openid/v1/jwks- verbs:- - get-----apiVersion: rbac.authorization.k8s.io/v1-kind: ClusterRoleBinding-metadata:- name: allow-anonymous-oidc-roleRef:- apiGroup: rbac.authorization.k8s.io- kind: ClusterRole- name: oidc-reader-subjects:-- kind: User- name: system:anonymous- apiGroup: rbac.authorization.k8s.io-EOF-- # 2. Deploy Hub- cat <<EOF | kubectl apply -f --apiVersion: v1-kind: ConfigMap-metadata:- name: sam-hub-config-data:- SAM_OIDC_ISSUER: "${issuer}"- SAM_OIDC_ID: "sam-mesh-audience"- SAM_HUB_KEY: "0000000000000000000000000000000000000000000000000000000000000000"-----apiVersion: apps/v1-kind: Deployment-metadata:- name: sam-hub-spec:- replicas: 1- selector:- matchLabels:- app: sam-hub- template:- metadata:- labels:- app: sam-hub- spec:- containers:- - name: sam-hub- image: sam-hub:local- args:- - "--issuer"- - "${issuer}"- - "--key"- - "0000000000000000000000000000000000000000000000000000000000000000"- - "--insecure-skip-tls-verify"- envFrom:- - configMapRef:- name: sam-hub-config-----apiVersion: v1-kind: Service-metadata:- name: sam-hub-spec:- type: ClusterIP- ports:- - name: http- port: 9090- targetPort: 9090- selector:- app: sam-hub-EOF-- # Wait for Hub to be ready- kubectl wait --for=condition=available deployment/sam-hub --timeout=60s-- # Get Hub Pod Name- local hub_pod_name- hub_pod_name=$(kubectl get pods -l app=sam-hub -o jsonpath='{.items[0].metadata.name}')-- # Wait for PeerID to appear in logs- k8s_wait_for_log "${hub_pod_name}" "PeerID:" 20-- # Get Hub PeerID- local hub_peer_id- hub_peer_id=$(kubectl logs "${hub_pod_name}" | grep -oE '12D3Koo[a-zA-Z0-9]+' | head -n 1)-- [[ -n "${hub_peer_id}" ]]-- # 3. Deploy Node- # Create ServiceAccount- kubectl create serviceaccount sam-node-sa-- # Deploy Node with projected volume- cat <<EOF | kubectl apply -f --apiVersion: apps/v1-kind: Deployment-metadata:- name: sam-node-spec:- replicas: 1- selector:- matchLabels:- app: sam-node- template:- metadata:- labels:- app: sam-node- spec:- serviceAccountName: sam-node-sa- containers:- - name: sam-node- image: sam-node:local- command: ["/sam-node", "run"]- args:- - "--hub"- - "http://sam-hub:9090"- - "--jwt-path"- - "/var/run/secrets/tokens/sam-token"- - "--api-token"- - "secret-token"- volumeMounts:- - name: sam-token- mountPath: /var/run/secrets/tokens- readOnly: true- volumes:- - name: sam-token- projected:- sources:- - serviceAccountToken:- path: sam-token- expirationSeconds: 3600- audience: "sam-mesh-audience"-EOF-- # Wait for Node to be ready- kubectl wait --for=condition=available deployment/sam-node --timeout=60s-- # 4. Verify enrollment by checking logs- local pod_name- pod_name=$(kubectl get pods -l app=sam-node -o jsonpath='{.items[0].metadata.name}')-- # Wait a bit for enrollment to happen- sleep 10-- local logs- logs=$(kubectl logs "${pod_name}")-- [[ "$logs" == *"SAM Node Online"* ]] || [[ "$logs" == *"Successfully enrolled"* ]]-}diff --git a/tests/e2e/kubernetes.bats b/tests/e2e/kubernetes.batsnew file mode 100644index 00000000..646558d7--- /dev/null+++ b/tests/e2e/kubernetes.bats@@ -0,0 +1,198 @@+#!/usr/bin/env bats++setup() {+ CLUSTER_NAME="sam-wi-test-$RANDOM"+ KUBECONTEXT="kind-${CLUSTER_NAME}"++ # Create Kind cluster with 2 worker nodes so we can use hostPort+ cat <<KIND | kind create cluster --name "${CLUSTER_NAME}" --config=-+kind: Cluster+apiVersion: kind.x-k8s.io/v1alpha4+nodes:+- role: control-plane+- role: worker+- role: worker+KIND++ # Load images into Kind+ kind load docker-image sam-hub:local --name "${CLUSTER_NAME}"+ kind load docker-image sam-node:local --name "${CLUSTER_NAME}"+}++teardown() {+ echo "=== Hub Logs ==="+ kubectl --context="${KUBECONTEXT}" logs -l app=sam-hub --tail=-1 || true+ echo "=== Node Logs ==="+ kubectl --context="${KUBECONTEXT}" logs -l app=sam-node --tail=-1 || true+ kind delete cluster --name "${CLUSTER_NAME}"+ docker rm -f external-sam-node >/dev/null 2>&1 || true+}++k8s_wait_for_log() {+ local pod="$1"+ local needle="$2"+ local timeout_s="${3:-20}"+ local i+ for ((i=0; i<timeout_s*10; i++)); do+ if kubectl --context="${KUBECONTEXT}" logs "${pod}" 2>&1 | grep -E -q "${needle}"; then+ return 0+ fi+ sleep 0.1+ done+ return 1+}++docker_wait_for_log() {+ local container="$1"+ local needle="$2"+ local timeout_s="${3:-20}"+ local i+ for ((i=0; i<timeout_s*10; i++)); do+ if docker logs "${container}" 2>&1 | grep -E -q "${needle}"; then+ return 0+ fi+ sleep 0.1+ done+ return 1+}++deploy_mesh() {+ # 1. Get the issuer URL+ local issuer+ issuer=$(kubectl --context="${KUBECONTEXT}" get --raw /.well-known/openid-configuration | jq -r .issuer)+ [[ -n "${issuer}" ]]++ # 1.5. Grant anonymous access to OIDC discovery+ kubectl --context="${KUBECONTEXT}" apply -f tests/e2e/fixtures/allow-anonymous-oidc.yaml++ # 2. Deploy Hub+ export ISSUER="${issuer}"+ envsubst < tests/e2e/fixtures/sam-hub.yaml | kubectl --context="${KUBECONTEXT}" apply -f -++ # Wait for Hub to be ready+ kubectl --context="${KUBECONTEXT}" rollout status statefulset/sam-hub --timeout=60s++ # Get Hub PeerID+ k8s_wait_for_log "sam-hub-0" "PeerID:" 20+ local hub_peer_id+ hub_peer_id=$(kubectl --context="${KUBECONTEXT}" logs "sam-hub-0" | grep -oE '12D3Koo[a-zA-Z0-9]+' | head -n 1 || true)+ [[ -n "${hub_peer_id}" ]]++ # 3. Deploy Node+ kubectl --context="${KUBECONTEXT}" create serviceaccount sam-node-sa || true++ kubectl --context="${KUBECONTEXT}" apply -f tests/e2e/fixtures/sam-node.yaml++ # Wait for Node to be ready+ kubectl --context="${KUBECONTEXT}" wait --for=condition=available deployment/sam-node --timeout=60s+}++@test "Workload Identity Federation in Kind" {+ deploy_mesh++ # Verify enrollment+ local pod_name+ pod_name=$(kubectl --context="${KUBECONTEXT}" get pods -l app=sam-node -o jsonpath='{.items[0].metadata.name}')++ k8s_wait_for_log "${pod_name}" "SAM Node Online|Successfully enrolled" 30+}++@test "Local SAM agent connects to cluster hub and uses relay" {+ deploy_mesh++ # Get IP of nodes running sam-hub pods+ NODE0_IP=$(kubectl --context="${KUBECONTEXT}" get pod sam-hub-0 -o jsonpath='{.status.hostIP}')+ NODE1_IP=$(kubectl --context="${KUBECONTEXT}" get pod sam-hub-1 -o jsonpath='{.status.hostIP}')++ # Start external node in a docker container attached to kind network+ # We use the sam-node:local image and mount the token+ kubectl --context="${KUBECONTEXT}" create token sam-node-sa --duration=1h --audience="sam-mesh-audience" > /tmp/sam-token++ # Run the node using docker+ # We add /etc/hosts entries for sam-hub.default.svc.cluster.local+ docker run -d --name external-sam-node --network kind \+ --add-host "sam-hub.default.svc.cluster.local:$NODE0_IP" \+ --add-host "sam-hub.default.svc.cluster.local:$NODE1_IP" \+ -v /tmp/sam-token:/var/run/secrets/tokens/sam-token \+ sam-node:local run \+ --hub "http://sam-hub.default.svc.cluster.local:9090" \+ --jwt-path "/var/run/secrets/tokens/sam-token" \+ --api-token "secret-token" \+ --bind-addr "0.0.0.0:8080" \+ --allow-loopback++ # Wait for external node to be ready+ if ! docker_wait_for_log external-sam-node "SAM Node Online|Successfully enrolled" 30; then+ echo "external-sam-node failed to start or connect. Logs:"+ docker logs external-sam-node+ return 1+ fi++ # Register a service on the first cluster node+ local pod_name+ pod_name=$(kubectl --context="${KUBECONTEXT}" get pods -l app=sam-node -o jsonpath='{.items[0].metadata.name}')++ # Wait for the cluster node to log its PeerID+ k8s_wait_for_log "${pod_name}" "PeerID:" 20+ local cluster_node_peer_id+ cluster_node_peer_id=$(kubectl --context="${KUBECONTEXT}" logs "${pod_name}" | grep "PeerID:" | head -n 1 | awk '{print $2}' | tr -d '\r' || true)++ # Port forward cluster node to register a service from the host+ kubectl --context="${KUBECONTEXT}" port-forward "${pod_name}" 8081:8080 &+ PF_NODE_PID=$!++ local i+ for ((i=0; i<50; i++)); do+ if nc -z 127.0.0.1 8081 2>/dev/null; then+ break+ fi+ sleep 0.1+ done++ # Register a service on the cluster node that points to its own /healthz endpoint+ python3 -c "+import urllib.request+import json+data = {+ 'service': {+ 'type': 3,+ 'name': 'echo-tool',+ 'description': 'test'+ },+ 'target_url': 'http://127.0.0.1:8080/healthz'+}+req = urllib.request.Request(+ 'http://127.0.0.1:8081/sam/service/register',+ data=json.dumps(data).encode('utf-8'),+ headers={+ 'Authorization': 'Bearer secret-token',+ 'Content-Type': 'application/json'+ }+)+with urllib.request.urlopen(req) as response:+ print(response.read().decode('utf-8'))+"++ # The external node will use its sidecar egress proxy to talk to the cluster node over the mesh.+ echo "Testing mesh datapath..."+ local output+ local i+ for ((i=0; i<60; i++)); do+ output=$(docker run --rm --network container:external-sam-node alpine wget -q -O- --timeout=2 --header="Authorization: Bearer secret-token" "http://127.0.0.1:8080/sam/${cluster_node_peer_id}/a2a/echo-tool" || true)+ if [ "$output" == "OK" ]; then+ break+ fi+ sleep 1+ done++ if [ "$output" != "OK" ]; then+ echo "Expected 'OK', got '$output'"+ echo "=== External Node Logs ==="+ docker logs external-sam-node || true+ return 1+ fi++ # Cleanup+ kill $PF_NODE_PID || true+ docker rm -f external-sam-node || true+}