Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
refactor and make fetch config more robust
Antonio Ojea434620f29b46
diff --git a/cmd/sam-node/connection_monitor.go b/cmd/sam-node/connection_monitor.goindex 9f81ee81..a44ca8a0 100644--- a/cmd/sam-node/connection_monitor.go+++ b/cmd/sam-node/connection_monitor.go@@ -3,7 +3,6 @@ package mainimport ("context"- "github.com/google/sam/api""github.com/multiformats/go-multiaddr")@@ -13,7 +12,7 @@ type hubConnectionManager interface {LoadHubConfig() ([]byte, []string, error)ConnectAndAuthWithHub(ctx context.Context, addr multiaddr.Multiaddr) errorLoadHubURL() (string, error)- DiscoverHubInfo(ctx context.Context, url string) (*api.HubInfoResponse, error)+SaveHubConfig(pubKey []byte, addrs []string) error}@@ -57,7 +56,7 @@ func checkHubConnection(ctx context.Context, mgr hubConnectionManager) (stable b}logger.Infof("[Monitor] Reconnect P2P failed. Discovering hub info from %s...", hubURL)- info, err := mgr.DiscoverHubInfo(ctx, hubURL)+ info, err := FetchHubInfo(ctx, hubURL)if err != nil || len(info.HubAddresses) == 0 {return false, false}@@ -74,7 +73,9 @@ func checkHubConnection(ctx context.Context, mgr hubConnectionManager) (stable b}if pubKeyBytes, _, err := mgr.LoadHubConfig(); err == nil {- _ = mgr.SaveHubConfig(pubKeyBytes, info.HubAddresses)+ if saveErr := mgr.SaveHubConfig(pubKeyBytes, info.HubAddresses); saveErr != nil {+ logger.Errorf("[Monitor] Failed to save updated hub config: %v", saveErr)+ }}for _, addr := range newHubAddrs {diff --git a/cmd/sam-node/hub_config.go b/cmd/sam-node/hub_config.gonew file mode 100644index 00000000..33dc8a2a--- /dev/null+++ b/cmd/sam-node/hub_config.go@@ -0,0 +1,140 @@+// 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 main++import (+ "context"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"++ "github.com/google/sam/api"+ "github.com/multiformats/go-multiaddr"+ "google.golang.org/protobuf/proto"+)++// FetchHubInfo retrieves the latest configuration from the Hub's /info endpoint.+func FetchHubInfo(ctx context.Context, hubURL string) (*api.HubInfoResponse, error) {+ if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {+ hubURL = "https://" + hubURL+ }+ hubURL = strings.TrimSuffix(hubURL, "/")++ urlStr := hubURL + "/info"+ req, err := http.NewRequestWithContext(ctx, "GET", urlStr, nil)+ if err != nil {+ return nil, fmt.Errorf("failed to create HTTP request: %w", err)+ }++ client := &http.Client{+ Timeout: 10 * time.Second,+ }+ resp, err := client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("HTTP request failed: %w", err)+ }+ defer resp.Body.Close()++ body, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))+ if err != nil {+ return nil, fmt.Errorf("failed to read response body: %w", err)+ }++ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("hub returned status %s: %s", resp.Status, string(body))+ }++ var info api.HubInfoResponse+ if err := proto.Unmarshal(body, &info); err != nil {+ return nil, fmt.Errorf("failed to decode /info response: %w", err)+ }++ return &info, nil+}++// SyncHubConfig loads the hub configuration from the store, attempts to refresh it+// via HTTP from the hub, and updates the store if successful.+// It returns the hub public key and the latest multiaddresses.+func SyncHubConfig(ctx context.Context, s *Store) ([]byte, []multiaddr.Multiaddr, error) {+ pubKey, storedAddrsStr, err := s.LoadHubConfig()+ if err != nil {+ return nil, nil, fmt.Errorf("failed to load hub config from store: %w", err)+ }++ hubURL, err := s.LoadHubURL()+ if err != nil {+ return nil, nil, fmt.Errorf("failed to load hub URL from store: %w", err)+ }+ var hubAddrs []multiaddr.Multiaddr++ // Parse stored addresses+ for _, addrStr := range storedAddrsStr {+ ma, err := multiaddr.NewMultiaddr(addrStr)+ if err != nil {+ logger.Warnf("Failed to parse stored hub address %q: %v", addrStr, err)+ continue+ }+ hubAddrs = append(hubAddrs, ma)+ }++ // Fallback for legacy databases: extract URL from multiaddr+ if hubURL == "" && len(hubAddrs) > 0 {+ for _, addr := range hubAddrs {+ if val, err := addr.ValueForProtocol(multiaddr.P_DNS4); err == nil {+ hubURL = "https://" + val+ break+ }+ if val, err := addr.ValueForProtocol(multiaddr.P_DNSADDR); err == nil {+ hubURL = "https://" + val+ break+ }+ }+ if hubURL != "" {+ logger.Infof("Extracted legacy hub URL from multiaddrs: %s", hubURL)+ }+ }++ // If we have a URL, fetch the latest info+ if hubURL != "" {+ logger.Infof("Fetching latest hub addresses via HTTP from %s...", hubURL)+ info, err := FetchHubInfo(ctx, hubURL)+ if err != nil {+ logger.Warnf("Failed to fetch updated addresses via HTTP (using cached): %v", err)+ } else if len(info.HubAddresses) > 0 {+ logger.Infof("Discovered latest hub addresses: %v", info.HubAddresses)+ var newHubAddrs []multiaddr.Multiaddr+ for _, addrStr := range info.HubAddresses {+ ma, parseErr := multiaddr.NewMultiaddr(addrStr)+ if parseErr != nil {+ logger.Warnf("Failed to parse discovered hub address %q: %v", addrStr, parseErr)+ continue+ }+ newHubAddrs = append(newHubAddrs, ma)+ }+ if len(newHubAddrs) > 0 {+ hubAddrs = newHubAddrs+ if len(pubKey) > 0 {+ if saveErr := s.SaveHubConfig(pubKey, info.HubAddresses); saveErr != nil {+ logger.Errorf("Failed to save updated hub config to store: %v", saveErr)+ }+ }+ }+ }+ }++ return pubKey, hubAddrs, nil+}diff --git a/cmd/sam-node/hub_config_test.go b/cmd/sam-node/hub_config_test.gonew file mode 100644index 00000000..6065d298--- /dev/null+++ b/cmd/sam-node/hub_config_test.go@@ -0,0 +1,165 @@+// 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 main++import (+ "context"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "testing"++ "github.com/google/sam/api"+ "google.golang.org/protobuf/proto"+)++func TestFetchHubInfo(t *testing.T) {+ expectedInfo := &api.HubInfoResponse{+ HubAddresses: []string{"/ip4/127.0.0.1/tcp/4001"},+ OidcIssuer: "https://issuer.example.com",+ ClientId: "client-id",+ }++ body, err := proto.Marshal(expectedInfo)+ if err != nil {+ t.Fatalf("Failed to marshal info: %v", err)+ }++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/info" {+ t.Errorf("Expected path /info, got %s", r.URL.Path)+ }+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(body)+ }))+ defer server.Close()++ info, err := FetchHubInfo(context.Background(), server.URL)+ if err != nil {+ t.Fatalf("FetchHubInfo failed: %v", err)+ }++ if !reflect.DeepEqual(info.HubAddresses, expectedInfo.HubAddresses) {+ t.Errorf("Expected HubAddresses %v, got %v", expectedInfo.HubAddresses, info.HubAddresses)+ }+ if info.OidcIssuer != expectedInfo.OidcIssuer {+ t.Errorf("Expected OidcIssuer %s, got %s", expectedInfo.OidcIssuer, info.OidcIssuer)+ }+ if info.ClientId != expectedInfo.ClientId {+ t.Errorf("Expected ClientId %s, got %s", expectedInfo.ClientId, info.ClientId)+ }+}++func TestFetchHubInfo_HTTPError(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ }))+ defer server.Close()++ _, err := FetchHubInfo(context.Background(), server.URL)+ if err == nil {+ t.Fatal("Expected error, got nil")+ }+ if !strings.Contains(err.Error(), "hub returned status 500 Internal Server Error") {+ t.Errorf("Expected error to contain '500 Internal Server Error', got %v", err)+ }+}++func TestFetchHubInfo_InvalidProto(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("invalid data"))+ }))+ defer server.Close()++ _, err := FetchHubInfo(context.Background(), server.URL)+ if err == nil {+ t.Fatal("Expected error, got nil")+ }+ if !strings.Contains(err.Error(), "failed to decode /info response") {+ t.Errorf("Expected error to contain 'failed to decode /info response', got %v", err)+ }+}++func TestSyncHubConfig(t *testing.T) {+ expectedInfo := &api.HubInfoResponse{+ HubAddresses: []string{"/ip4/127.0.0.1/tcp/4001"},+ OidcIssuer: "https://issuer.example.com",+ ClientId: "client-id",+ }++ body, err := proto.Marshal(expectedInfo)+ if err != nil {+ t.Fatalf("Failed to marshal info: %v", err)+ }++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(body)+ }))+ defer server.Close()++ tempDir := t.TempDir()+ store, err := NewStore(tempDir)+ if err != nil {+ t.Fatalf("Failed to create store: %v", err)+ }+ defer store.Close()++ // Initial store is empty, so SyncHubConfig should just return empty+ pubKey, addrs, err := SyncHubConfig(context.Background(), store)+ if err != nil {+ t.Fatalf("SyncHubConfig failed: %v", err)+ }+ if len(pubKey) != 0 || len(addrs) != 0 {+ t.Errorf("Expected empty result for empty store, got pubKey=%v, addrs=%v", pubKey, addrs)+ }++ // Save initial config with explicit hub URL+ testPubKey := []byte("test-pub-key")+ if err := store.SaveHubConfig(testPubKey, []string{"/ip4/1.2.3.4/tcp/1234"}); err != nil {+ t.Fatalf("Failed to save hub config: %v", err)+ }+ if err := store.SaveHubURL(server.URL); err != nil {+ t.Fatalf("Failed to save hub url: %v", err)+ }++ // Call SyncHubConfig, it should fetch new addrs from server+ pubKey, addrs, err = SyncHubConfig(context.Background(), store)+ if err != nil {+ t.Fatalf("SyncHubConfig failed: %v", err)+ }++ if string(pubKey) != string(testPubKey) {+ t.Errorf("Expected pubKey %s, got %s", testPubKey, pubKey)+ }++ if len(addrs) != 1 || addrs[0].String() != expectedInfo.HubAddresses[0] {+ t.Errorf("Expected addrs %v, got %v", expectedInfo.HubAddresses, addrs)+ }++ // Verify the new addrs were saved to the store+ savedPubKey, savedAddrsStr, err := store.LoadHubConfig()+ if err != nil {+ t.Fatalf("Failed to load hub config: %v", err)+ }+ if string(savedPubKey) != string(testPubKey) {+ t.Errorf("Expected saved pubKey %s, got %s", testPubKey, savedPubKey)+ }+ if len(savedAddrsStr) != 1 || savedAddrsStr[0] != expectedInfo.HubAddresses[0] {+ t.Errorf("Expected saved addrs %v, got %v", expectedInfo.HubAddresses, savedAddrsStr)+ }+}diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.goindex 48e672d5..fe18a9e9 100644--- a/cmd/sam-node/main.go+++ b/cmd/sam-node/main.go@@ -123,17 +123,13 @@ func main() {var hubPubKey ed25519.PublicKeyvar hubAddrs []multiaddr.Multiaddr- storedPubKey, storedAddrs, _ := store.LoadHubConfig()+ storedPubKey, syncedAddrs, err := SyncHubConfig(context.Background(), store)+ if err != nil {+ logger.Warnf("Failed to sync hub config: %v", err)+ }if len(storedPubKey) > 0 {hubPubKey = storedPubKey- for _, addrStr := range storedAddrs {- ma, err := multiaddr.NewMultiaddr(addrStr)- if err != nil {- logger.Warnf("Failed to parse stored hub address %q: %v", addrStr, err)- continue- }- hubAddrs = append(hubAddrs, ma)- }+ hubAddrs = syncedAddrs}if hubPublicKeyFlag != "" {@@ -240,17 +236,11 @@ func main() {}enrollCancel()- storedPubKey, storedAddrs, _ := store.LoadHubConfig()- hubPubKey = storedPubKey- var newHubAddrs []multiaddr.Multiaddr- for _, addrStr := range storedAddrs {- ma, err := multiaddr.NewMultiaddr(addrStr)- if err != nil {- logger.Warnf("Failed to parse stored hub address %q: %v", addrStr, err)- continue- }- newHubAddrs = append(newHubAddrs, ma)+ storedPubKey, newHubAddrs, err := SyncHubConfig(context.Background(), store)+ if err != nil {+ logger.Warnf("Failed to sync hub config post-enrollment: %v", err)}+ hubPubKey = storedPubKeylogger.Debugf("listenAddrs: %v, allowLoopback: %v", listenAddrs, allowLoopbackFlag)node, err = NewSamNode(context.Background(), priv, hubPubKey, newHubAddrs, store, meshFlag, discoveryIntervalFlag, listenAddrs, enableRelayFlag, nodeConfig, keyGracePeriodFlag, allowLoopbackFlag)@@ -334,7 +324,7 @@ func main() {dummyNode := &SamNode{Store: store}fmt.Printf("Discovering hub info from %s...\n", targetHub)- hubInfo, err := dummyNode.DiscoverHubInfo(ctx, targetHub)+ hubInfo, err := FetchHubInfo(ctx, targetHub)if err != nil {logger.Fatalf("Failed to discover hub info: %v", err)}diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.goindex 5aaf35e9..85c1d6c8 100644--- a/cmd/sam-node/node.go+++ b/cmd/sam-node/node.go@@ -262,7 +262,6 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.Pnode.services = NewServiceRegistry(node.DHT)- // Bootstrap: Connect and Auth to the Hubvar authenticated boolvar fatalAuthErr error@@ -282,43 +281,7 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.Pif fatalAuthErr != nil {return nil, fmt.Errorf("fatal auth failure: %w", fatalAuthErr)}-- // Self-healing fallback: try to fetch updated addresses via HTTP if hub_url is known- hubURL, err := node.Store.LoadHubURL()- if err == nil && hubURL != "" {- logger.Infof("[AuthN] All P2P dials failed. Attempting to fetch updated hub addresses via HTTP from %s...", hubURL)- info, err := node.DiscoverHubInfo(ctx, hubURL)- if err == nil && len(info.HubAddresses) > 0 {- logger.Infof("[AuthN] Discovered updated hub addresses: %v", info.HubAddresses)- var newHubAddrs []multiaddr.Multiaddr- for _, addrStr := range info.HubAddresses {- ma, err := multiaddr.NewMultiaddr(addrStr)- if err == nil {- newHubAddrs = append(newHubAddrs, ma)- }- }- if len(newHubAddrs) > 0 {- if pubKeyBytes, _, err := node.Store.LoadHubConfig(); err == nil {- _ = node.Store.SaveHubConfig(pubKeyBytes, info.HubAddresses)- }- for _, addr := range newHubAddrs {- if err := node.ConnectAndAuthWithHub(ctx, addr); err != nil {- logger.Warnf("[AuthN] Fallback auth failed with %s: %v", addr, err)- } else {- logger.Infof("[AuthN] Fallback connection successful!")- authenticated = true- break- }- }- }- } else {- logger.Warnf("[AuthN] Failed to fetch updated addresses via HTTP: %v", err)- }- }-- if !authenticated {- return nil, fmt.Errorf("failed to authenticate with any hub: all connection attempts failed")- }+ return nil, fmt.Errorf("failed to authenticate with any hub: all connection attempts failed")}// Initialize Gossipsub for Hub Eventsdiff --git a/cmd/sam-node/oidc.go b/cmd/sam-node/oidc.goindex ffd9f6e7..a65eec71 100644--- a/cmd/sam-node/oidc.go+++ b/cmd/sam-node/oidc.go@@ -21,7 +21,6 @@ import ("encoding/base64""encoding/json""fmt"- "io""net""net/http""net/url"@@ -32,9 +31,7 @@ import ("time""github.com/coreos/go-oidc/v3/oidc"- "github.com/google/sam/api""golang.org/x/oauth2/clientcredentials"- "google.golang.org/protobuf/proto")// generatePKCE generates a PKCE code verifier and challenge.@@ -314,50 +311,6 @@ func (n *SamNode) DiscoverEndpoints(ctx context.Context, issuerURL string) (tokereturn claims.TokenURL, claims.AuthURL, nil}-// DiscoverHubInfo queries the hub's /info endpoint to fetch OIDC configurations.-func (n *SamNode) DiscoverHubInfo(ctx context.Context, hubURL string) (*api.HubInfoResponse, error) {- if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {- hubURL = "https://" + hubURL- }- hubURL = strings.TrimSuffix(hubURL, "/")-- urlStr := hubURL + "/info"- req, err := http.NewRequestWithContext(ctx, "GET", urlStr, nil)- if err != nil {- return nil, fmt.Errorf("failed to create HTTP request: %w", err)- }-- client := &http.Client{- Timeout: 10 * time.Second,- }- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("HTTP request failed: %w", err)- }- defer func() {- if err := resp.Body.Close(); err != nil {- logger.Errorf("Failed to close response body: %v", err)- }- }()-- if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))- return nil, fmt.Errorf("hub returned status %s: %s", resp.Status, string(body))- }-- body, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))- if err != nil {- return nil, fmt.Errorf("failed to read response body: %w", err)- }-- var hubInfo api.HubInfoResponse- if err := proto.Unmarshal(body, &hubInfo); err != nil {- return nil, fmt.Errorf("failed to unmarshal hub info: %w", err)- }-- return &hubInfo, nil-}-var openBrowserFunc = openBrowserfunc openBrowser(targetURL string) {diff --git a/cmd/sam-node/sidecar.go b/cmd/sam-node/sidecar.goindex 02945bc4..184e3cd8 100644--- a/cmd/sam-node/sidecar.go+++ b/cmd/sam-node/sidecar.go@@ -41,22 +41,22 @@ func startSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile stmux.HandleFunc("/readyz", handleReadyz)// Protected endpoints- mux.Handle("/sam/service/register", withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mux.Handle("/sam/service/register", withMeshConnection(node, withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {handleRegisterService(node, w, r)- })))- mux.Handle("/sam/service/unregister", withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ }))))+ mux.Handle("/sam/service/unregister", withMeshConnection(node, withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {handleUnregisterService(node, w, r)- })))- mux.Handle("/sam/service/discover", withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ }))))+ mux.Handle("/sam/service/discover", withMeshConnection(node, withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {handleDiscoverService(node, w, r)- })))+ }))))// Mount Egress Proxy- mux.Handle("/sam/", withAuth(token, createEgressProxy(node)))+ mux.Handle("/sam/", withMeshConnection(node, withAuth(token, createEgressProxy(node))))// Mount MCP handlermcpHandler := NewMCPHandler(node)- mux.Handle("/", mcpHandler)+ mux.Handle("/", withMeshConnection(node, mcpHandler))server := &http.Server{Handler: mux,@@ -128,6 +128,16 @@ func handleReadyz(w http.ResponseWriter, r *http.Request) {}}+func withMeshConnection(node *SamNode, next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if node != nil && !node.IsConnected() {+ http.Error(w, "Service Unavailable: Not connected to the mesh", http.StatusServiceUnavailable)+ return+ }+ next.ServeHTTP(w, r)+ })+}+func withAuth(token string, next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if token == "" {diff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.goindex 42692562..c60c2285 100644--- a/tests/integration/fallback_test.go+++ b/tests/integration/fallback_test.go@@ -497,8 +497,8 @@ func TestSelfHealingHTTPFallback(t *testing.T) {success := falsefor i := 0; i < 50; i++ {out = stdout.String()- if strings.Contains(out, "Attempting to fetch updated hub addresses via HTTP") &&- strings.Contains(out, "Fallback connection successful!") {+ if strings.Contains(out, "Fetching latest hub addresses via HTTP") &&+ strings.Contains(out, "Successfully authenticated with hub via libp2p") {success = truebreak}