Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
init
Antonio Ojea8757b33f09a0
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 00000000..bb38860d--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,96 @@+# Code of Conduct++## Our Pledge++In the interest of fostering an open and welcoming environment, we as+contributors and maintainers pledge to making participation in our project and+our community a harassment-free experience for everyone, regardless of age, body+size, disability, ethnicity, gender identity and expression, level of+experience, education, socio-economic status, nationality, personal appearance,+race, religion, or sexual identity and orientation.++## Our Standards++Examples of behavior that contributes to creating a positive environment+include:++* Using welcoming and inclusive language+* Being respectful of differing viewpoints and experiences+* Gracefully accepting constructive criticism+* Focusing on what is best for the community+* Showing empathy towards other community members++Examples of unacceptable behavior by participants include:++* The use of sexualized language or imagery and unwelcome sexual attention or+ advances+* Trolling, insulting/derogatory comments, and personal or political attacks+* Public or private harassment+* Publishing others' private information, such as a physical or electronic+ address, without explicit permission+* Other conduct which could reasonably be considered inappropriate in a+ professional setting++## Our Responsibilities++Project maintainers are responsible for clarifying the standards of acceptable+behavior and are expected to take appropriate and fair corrective action in+response to any instances of unacceptable behavior.++Project maintainers have the right and responsibility to remove, edit, or reject+comments, commits, code, wiki edits, issues, and other contributions that are+not aligned to this Code of Conduct, or to ban temporarily or permanently any+contributor for other behaviors that they deem inappropriate, threatening,+offensive, or harmful.++## Scope++This Code of Conduct applies both within project spaces and in public spaces+when an individual is representing the project or its community. Examples of+representing a project or community include using an official project e-mail+address, posting via an official social media account, or acting as an appointed+representative at an online or offline event. Representation of a project may be+further defined and clarified by project maintainers.++This Code of Conduct also applies outside the project spaces when the Project+Steward has a reasonable belief that an individual's behavior may have a+negative impact on the project or its community.++## Conflict Resolution++We do not believe that all conflict is bad; healthy debate and disagreement+often yield positive results. However, it is never okay to be disrespectful or+to engage in behavior that violates the project’s code of conduct.++If you see someone violating the code of conduct, you are encouraged to address+the behavior directly with those involved. Many issues can be resolved quickly+and easily, and this gives people more control over the outcome of their+dispute. If you are unable to resolve the matter for any reason, or if the+behavior is threatening or harassing, report it. We are dedicated to providing+an environment where participants feel welcome and safe.++Reports should be directed to *[PROJECT STEWARD NAME(s) AND EMAIL(s)]*, the+Project Steward(s) for *[PROJECT NAME]*. It is the Project Steward’s duty to+receive and address reported violations of the code of conduct. They will then+work with a committee consisting of representatives from the Open Source+Programs Office and the Google Open Source Strategy team. If for any reason you+are uncomfortable reaching out to the Project Steward, please email++We will investigate every complaint, but you may not receive a direct response.+We will use our discretion in determining when and how to follow up on reported+incidents, which may range from not taking action to permanent expulsion from+the project and project-sponsored spaces. We will notify the accused of the+report and provide them an opportunity to discuss it before any action is taken.+The identity of the reporter will be omitted from the details of the report+supplied to the accused. In potentially harmful situations, such as ongoing+harassment or threats to anyone's safety, we may take action without notice.++## Attribution++This Code of Conduct is adapted from the Contributor Covenant, version 1.4,+available at+https://www.contributor-covenant.org/version/1/4/code-of-conduct.html++Note: A version of this file is also available in the+[New Project repo](https://github.com/google/new-project/blob/master/docs/code-of-conduct.md).diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 00000000..b16bd944--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,33 @@+# How to contribute++We'd love to accept your patches and contributions to this project.++## Before you begin++### Sign our Contributor License Agreement++Contributions to this project must be accompanied by a+[Contributor License Agreement](https://cla.developers.google.com/about) (CLA).+You (or your employer) retain the copyright to your contribution; this simply+gives us permission to use and redistribute your contributions as part of the+project.++If you or your current employer have already signed the Google CLA (even if it+was for a different project), you probably don't need to do it again.++Visit <https://cla.developers.google.com/> to see your current agreements or to+sign a new one.++### Review our community guidelines++This project follows+[Google's Open Source Community Guidelines](https://opensource.google/conduct/).++## Contribution process++### Code reviews++All submissions, including submissions by project members, require review. We+use GitHub pull requests for this purpose. Consult+[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more+information on using pull requests.diff --git a/cmd/sam-hub/hooks.go b/cmd/sam-hub/hooks.goindex 9b6aa157..bcbc6ff5 100644--- a/cmd/sam-hub/hooks.go+++ b/cmd/sam-hub/hooks.go@@ -1,3 +1,17 @@+// 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 mainimport (@@ -12,6 +26,7 @@ import ("github.com/libp2p/go-libp2p/core/control""github.com/libp2p/go-libp2p/core/network""github.com/libp2p/go-libp2p/core/peer"+ "github.com/libp2p/go-libp2p/p2p/protocol/identify""github.com/multiformats/go-multiaddr")@@ -49,7 +64,7 @@ func (g *hubConnGate) InterceptUpgraded(c network.Conn) (bool, control.DisconnecprotocolID := c.ConnState().StreamMultiplexer// Always allow the OIDC bridge protocol and basic identify- if protocolID == p2phttp.DefaultP2PProtocol || protocolID == "/ipfs/id/1.0.0" {+ if protocolID == p2phttp.DefaultP2PProtocol || protocolID == identify.ID {return true, 0}diff --git a/cmd/sam-hub/http.go b/cmd/sam-hub/http.gonew file mode 100644index 00000000..293f8148--- /dev/null+++ b/cmd/sam-hub/http.go@@ -0,0 +1,180 @@+// 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 (+ "crypto/ed25519"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "log"+ "net/http"+ "strings"++ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/libp2p/go-libp2p/core/host"+ "github.com/libp2p/go-libp2p/core/peer"+)++// authMiddleware protects HTTP endpoints by requiring a valid Hub-issued Biscuit+func (h *Hub) authMiddleware(next http.HandlerFunc) http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ authHeader := r.Header.Get("Authorization")+ if authHeader == "" {+ http.Error(w, "Unauthorized: missing Authorization header", http.StatusUnauthorized)+ return+ }++ tokenStr := strings.TrimPrefix(authHeader, "Bearer ")+ data, err := base64.StdEncoding.DecodeString(tokenStr)+ if err != nil {+ http.Error(w, "Unauthorized: invalid base64 encoding", http.StatusUnauthorized)+ return+ }++ b, err := biscuit.Unmarshal(data)+ if err != nil {+ http.Error(w, "Unauthorized: invalid biscuit token", http.StatusUnauthorized)+ return+ }++ // The Hub verifies the token using its own derived public key+ pubKey := h.BiscuitKey.Public().(ed25519.PublicKey)+ authorizer, err := b.Authorizer(pubKey)+ if err != nil {+ http.Error(w, "Unauthorized: signature verification failed", http.StatusUnauthorized)+ return+ }++ if err := authorizer.Authorize(); err != nil {+ http.Error(w, "Forbidden: invalid capabilities or wrong mesh", http.StatusForbidden)+ return+ }++ next.ServeHTTP(w, r)+ }+}++func (h *Hub) handleLogin(w http.ResponseWriter, r *http.Request) {+ pID := r.URL.Query().Get("peer_id")+ if pID == "" {+ http.Error(w, "Missing peer_id", 400)+ return+ }+ // Bind PeerID as the OIDC 'state'+ url := h.OIDCConfig.AuthCodeURL(pID)+ http.Redirect(w, r, url, http.StatusFound)+}++func (h *Hub) handleCallback(w http.ResponseWriter, r *http.Request) {+ ctx := r.Context()+ peerIDStr := r.URL.Query().Get("state")+ code := r.URL.Query().Get("code")++ token, err := h.OIDCConfig.Exchange(ctx, code)+ if err != nil {+ http.Error(w, "Token exchange failed", 500)+ return+ }++ rawID, _ := token.Extra("id_token").(string)+ idToken, err := h.Verifier.Verify(ctx, rawID)+ if err != nil {+ http.Error(w, "ID Token verification failed", http.StatusUnauthorized)+ return+ }+ // standard claims mapping+ var claims struct {+ Subject string `json:"sub"`+ Email string `json:"email"`+ Groups []string `json:"groups"`+ }+ if err := idToken.Claims(&claims); err != nil {+ http.Error(w, "Failed to parse claims", 500)+ return+ }++ p, err := peer.Decode(peerIDStr)+ if err != nil {+ http.Error(w, "Invalid peer_id", 400)+ return+ }++ // Issue the Biscuit using Standard Vocabulary+ biscuitToken, err := h.issueStandardBiscuit(p, claims.Subject, claims.Email, claims.Groups)+ if err != nil {+ http.Error(w, "Biscuit issuance failed", 500)+ return+ }++ // Unlock the Mesh Firewall for this PeerID+ h.gater.mu.Lock()+ h.gater.authenticated[p] = true+ delete(h.gater.pending, p)+ h.gater.mu.Unlock()++ w.Header().Set("Content-Type", "text/html")+ if _, err := fmt.Fprintf(w, `<html><body>+ <h3>Sovereign Identity Verified!</h3>+ <p>Peer <code>%s</code> is now part of mesh <code>%s</code></p>+ <p>Identity: <code>%s</code></p>+ <hr/>+ <p>Standard Identity Biscuit:</p>+ <textarea rows="5" cols="60">%s</textarea>+ </body></html>`, p, h.MeshID, claims.Email, biscuitToken); err != nil {+ log.Printf("writing callback response: %v", err)+ }+}++// handleConfig provides the public key and bootstrap addresses over standard HTTP+func (h *Hub) handleConfig(w http.ResponseWriter, r *http.Request) {+ // Extract the Hub's public multiaddresses+ addrs, _ := peer.AddrInfoToP2pAddrs(host.InfoFromHost(h.Host))+ var addrStrs []string+ for _, a := range addrs {+ addrStrs = append(addrStrs, a.String())+ }++ pubKey := h.BiscuitKey.Public().(ed25519.PublicKey)++ config := map[string]interface{}{+ "public_key": hex.EncodeToString(pubKey),+ "mesh_id": h.MeshID,+ "bootstrap_nodes": addrStrs,+ }+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(config); err != nil {+ log.Printf("encoding config response: %v", err)+ }+}++// handlePeers returns the registry of enrolled peers+func (h *Hub) handlePeers(w http.ResponseWriter, r *http.Request) {+ h.gater.mu.RLock()+ defer h.gater.mu.RUnlock()++ peers := make([]string, 0, len(h.gater.authenticated))+ for pID := range h.gater.authenticated {+ peers = append(peers, pID.String())+ }++ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(map[string]interface{}{+ "enrolled_peers": peers,+ }); err != nil {+ log.Printf("encoding peers response: %v", err)+ }+}diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.goindex 21f58adf..6a7f2f3e 100644--- a/cmd/sam-hub/main.go+++ b/cmd/sam-hub/main.go@@ -1,3 +1,17 @@+// 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 mainimport (@@ -41,6 +55,7 @@ var (listenAddrs []stringmeshName stringpublicAddr string+ httpAddr string // Mandatory HTTP listener flag)// Hub handles identity bridging and network discovery@@ -129,77 +144,6 @@ func NewHub(ctx context.Context) (*Hub, error) {return hub, nil}-func (h *Hub) handleLogin(w http.ResponseWriter, r *http.Request) {- pID := r.URL.Query().Get("peer_id")- if pID == "" {- http.Error(w, "Missing peer_id", 400)- return- }- // Bind PeerID as the OIDC 'state'- url := h.OIDCConfig.AuthCodeURL(pID)- http.Redirect(w, r, url, http.StatusFound)-}--func (h *Hub) handleCallback(w http.ResponseWriter, r *http.Request) {- ctx := r.Context()- peerIDStr := r.URL.Query().Get("state")- code := r.URL.Query().Get("code")-- token, err := h.OIDCConfig.Exchange(ctx, code)- if err != nil {- http.Error(w, "Token exchange failed", 500)- return- }-- rawID, _ := token.Extra("id_token").(string)- idToken, err := h.Verifier.Verify(ctx, rawID)- if err != nil {- http.Error(w, "ID Token verification failed", http.StatusUnauthorized)- return- }- // standard claims mapping- var claims struct {- Subject string `json:"sub"`- Email string `json:"email"`- Groups []string `json:"groups"`- }- if err := idToken.Claims(&claims); err != nil {- http.Error(w, "Failed to parse claims", 500)- return- }-- p, err := peer.Decode(peerIDStr)- if err != nil {- http.Error(w, "Invalid peer_id", 400)- return- }-- // Issue the Biscuit using Standard Vocabulary- biscuitToken, err := h.issueStandardBiscuit(p, claims.Subject, claims.Email, claims.Groups)- if err != nil {- http.Error(w, "Biscuit issuance failed", 500)- return- }-- // Unlock the Mesh Firewall for this PeerID- h.gater.mu.Lock()- h.gater.authenticated[p] = true- delete(h.gater.pending, p)- h.gater.mu.Unlock()-- w.Header().Set("Content-Type", "text/html")- if _, err := fmt.Fprintf(w, `<html><body>- <h3>Sovereign Identity Verified!</h3>- <p>Peer <code>%s</code> is now part of mesh <code>%s</code></p>- <p>Identity: <code>%s</code></p>- <hr/>- <p>Standard Identity Biscuit:</p>- <textarea rows="5" cols="60">%s</textarea>- </body></html>`, p, h.MeshID, claims.Email, biscuitToken); err != nil {- log.Printf("writing callback response: %v", err)- }-}-// issueStandardBiscuit creates a biscuit with standard facts for user, email, groups, and hardware binding (peer ID).func (h *Hub) issueStandardBiscuit(p peer.ID, sub string, email string, groups []string) (string, error) {builder := biscuit.NewBuilder(h.BiscuitKey)@@ -257,6 +201,8 @@ func (h *Hub) issueStandardBiscuit(p peer.ID, sub string, email string, groups [return base64.StdEncoding.EncodeToString(data), nil}+// startWatchdog periodically checks for peers that have connected but not completed OIDC+// authentication within the grace period, and evicts them from the network.func (h *Hub) startWatchdog() {go func() {ticker := time.NewTicker(10 * time.Second)@@ -292,8 +238,12 @@ func main() {h.startWatchdog()mux := http.NewServeMux()+ // OIDC Endpointsmux.HandleFunc("/login", h.handleLogin)mux.HandleFunc("/callback", h.handleCallback)+ // API endpoints for agents to fetch config and peer registry+ mux.HandleFunc("/api/v1/config", h.handleConfig)+ mux.HandleFunc("/api/v1/peers", h.authMiddleware(h.handlePeers))// Corrected libp2phttp Serve logic// This allows agents to reach OIDC via libp2p streams@@ -306,6 +256,7 @@ func main() {log.Printf("closing p2p listener: %v", err)}}()+ // Serve the HTTP handler over libp2p streamsgo func() {server := &http.Server{Handler: mux,@@ -318,7 +269,10 @@ func main() {fmt.Printf("SAM Hub Online (QUIC + TCP)\n")fmt.Printf("MeshID: %s\n", h.MeshID)fmt.Printf("PeerID: %s\n", h.Host.ID())- select {}++ // Standard HTTP server for browser-based OIDC and config API+ fmt.Printf("Starting Standard HTTP Frontend on %s\n", httpAddr)+ log.Fatal(http.ListenAndServe(httpAddr, mux))},}@@ -329,6 +283,7 @@ func main() {rootCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/4001/quic-v1", "/ip4/0.0.0.0/tcp/4002"}, "libp2p Listen Addrs")rootCmd.Flags().StringVar(&meshName, "mesh", "public-mesh", "Mesh federation name")rootCmd.Flags().StringVar(&publicAddr, "public-url", "http://localhost:8080", "Public URL for browser OIDC")+ rootCmd.Flags().StringVar(&httpAddr, "http-listen", ":8080", "Standard HTTP listen address for OIDC and Config")if err := rootCmd.Execute(); err != nil {os.Exit(1)diff --git a/cmd/sam-node/gate.go b/cmd/sam-node/gate.gonew file mode 100644index 00000000..148ca166--- /dev/null+++ b/cmd/sam-node/gate.go@@ -0,0 +1,62 @@+// 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 (+ "fmt"++ "github.com/libp2p/go-libp2p/core/connmgr"+ "github.com/libp2p/go-libp2p/core/control"+ "github.com/libp2p/go-libp2p/core/network"+ "github.com/libp2p/go-libp2p/core/peer"+ "github.com/multiformats/go-multiaddr"+)++var _ connmgr.ConnectionGater = (*nodeConnGate)(nil)++// nodeConnGate enforces swarm-level AuthN policies+type nodeConnGate struct {+ node *SamNode+}++// InterceptPeerDial controls who we are allowed to call (Outbound)+func (g *nodeConnGate) InterceptPeerDial(p peer.ID) (allow bool) {+ return !g.node.Store.IsBanned(p)+}++// InterceptAddrDial ensures we only dial specific approved networks+func (g *nodeConnGate) InterceptAddrDial(p peer.ID, m multiaddr.Multiaddr) (allow bool) {+ return true+}++// InterceptAccept controls who can call us (Inbound)+func (g *nodeConnGate) InterceptAccept(n network.ConnMultiaddrs) (allow bool) {+ return true // Connection allowed, but InterceptSecured will verify the PeerID+}++// InterceptSecured is called after TLS handshake. This is our Layer 2 Check.+func (g *nodeConnGate) InterceptSecured(dir network.Direction, p peer.ID, n network.ConnMultiaddrs) (allow bool) {+ if g.node.Store.IsBanned(p) {+ fmt.Printf("[Layer 2] Dropping connection: Peer %s is explicitly BANNED\n", p)+ return false+ }++ // Allow the TLS pipe to stay open. Layer 3 & 4 will handle the rest.+ return true+}++func (g *nodeConnGate) InterceptUpgraded(n network.Conn) (allow bool, cc control.DisconnectReason) {+ return true, 0+}diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.goindex 7676c136..cac8c251 100644--- a/cmd/sam-node/main.go+++ b/cmd/sam-node/main.go@@ -1,14 +1,33 @@+// 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 mainimport ("bufio""context"+ "crypto/ed25519"+ "encoding/hex"+ "encoding/json""fmt""log"+ "net/http""os""strings""github.com/libp2p/go-libp2p/core/crypto"+ "github.com/multiformats/go-multiaddr""github.com/spf13/cobra")@@ -18,6 +37,64 @@ var (tokenFlag string)+type hubConfigResponse struct {+ PublicKey string `json:"public_key"`+ MeshID string `json:"mesh_id"`+ BootstrapNodes []string `json:"bootstrap_nodes"`+}++func fetchHubConfig(ctx context.Context, hubBaseURL string) (ed25519.PublicKey, []multiaddr.Multiaddr, error) {+ configURL := strings.TrimRight(hubBaseURL, "/") + "/api/v1/config"+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, configURL, nil)+ if err != nil {+ return nil, nil, fmt.Errorf("creating hub config request: %w", err)+ }++ resp, err := (&http.Client{}).Do(req)+ if err != nil {+ return nil, nil, fmt.Errorf("requesting hub config: %w", err)+ }+ defer func() {+ _ = resp.Body.Close()+ }()++ if resp.StatusCode != http.StatusOK {+ return nil, nil, fmt.Errorf("hub config returned status %d", resp.StatusCode)+ }++ var cfg hubConfigResponse+ if err := json.NewDecoder(resp.Body).Decode(&cfg); err != nil {+ return nil, nil, fmt.Errorf("decoding hub config response: %w", err)+ }++ pubBytes, err := hex.DecodeString(strings.TrimSpace(cfg.PublicKey))+ if err != nil {+ return nil, nil, fmt.Errorf("decoding hub public key: %w", err)+ }+ if len(pubBytes) != ed25519.PublicKeySize {+ return nil, nil, fmt.Errorf("invalid hub public key length: %d", len(pubBytes))+ }++ var hubAddrs []multiaddr.Multiaddr+ for _, raw := range cfg.BootstrapNodes {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ continue+ }+ ma, err := multiaddr.NewMultiaddr(raw)+ if err != nil {+ log.Printf("ignoring invalid bootstrap multiaddr %q: %v", raw, err)+ continue+ }+ hubAddrs = append(hubAddrs, ma)+ }+ if len(hubAddrs) == 0 {+ return nil, nil, fmt.Errorf("hub config did not provide valid bootstrap addresses")+ }++ return ed25519.PublicKey(pubBytes), hubAddrs, nil+}+func main() {rootCmd := &cobra.Command{Use: "sam-node",@@ -44,12 +121,22 @@ func main() {}}()+ hubPubKey, hubAddrs, err := fetchHubConfig(context.Background(), hubAddr)+ if err != nil {+ log.Fatalf("Failed to fetch hub config: %v", err)+ }+priv := getOrGenerateKey(store)// Temporary host to determine PeerID- tempNode, err := NewSamNode(context.Background(), priv, []string{})+ tempNode, err := NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store)if err != nil {log.Fatalf("Failed to initialize identity: %v", err)}+ defer func() {+ if err := tempNode.Host.Close(); err != nil {+ log.Printf("closing temporary node host: %v", err)+ }+ }()loginURL := fmt.Sprintf("%s/login?peer_id=%s", hubAddr, tempNode.Host.ID())@@ -96,24 +183,29 @@ func main() {token := tokenFlagif token == "" {- token, _ = store.LoadIdentity()+ token, err = store.LoadIdentity()+ if err != nil {+ log.Printf("Failed to load identity: %v", err)+ }}if token == "" {fmt.Println("No identity found. Please run 'sam-node login' or provide --token")return}+ hubPubKey, hubAddrs, err := fetchHubConfig(context.Background(), hubAddr)+ if err != nil {+ log.Fatalf("Failed to fetch hub config: %v", err)+ }+priv := getOrGenerateKey(store)- node, err := NewSamNode(context.Background(), priv, listenAddrs)+ node, err := NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store)if err != nil {log.Fatalf("Failed to start mesh node: %v", err)}- // Register the mandatory sovereign auth hook- node.Host.SetStreamHandler(AuthProtocol, node.HandleAuthHandshake)- if err := node.ListenForMeshEvents(context.Background()); err != nil {- log.Fatalf("Failed to listen for mesh events: %v", err)- }+ // Ensure the auth protocol handler is always installed.+ node.Host.SetStreamHandler(AuthProtocolID, node.HandleAuthHandshake)fmt.Printf("SAM Node Online.\nPeerID: %s\nListening on: %v\n", node.Host.ID(), listenAddrs)diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.gonew file mode 100644index 00000000..90ecaa21--- /dev/null+++ b/cmd/sam-node/middleware.go@@ -0,0 +1,91 @@+// 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 (+ "fmt"++ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/libp2p/go-libp2p/core/network"+ "github.com/libp2p/go-libp2p/core/peer"+ "github.com/libp2p/go-libp2p/core/protocol"+)++// RequestContext carries the security metadata for a specific stream request+type RequestContext struct {+ PeerID peer.ID+ User string+ Group string+ Protocol protocol.ID+}++func (n *SamNode) WrapSecurely(pid protocol.ID, handler network.StreamHandler) {+ n.Host.SetStreamHandler(pid, func(s network.Stream) {+ // Allow the auth protocol to proceed without checks+ if pid == AuthProtocolID {+ handler(s)+ return+ }+ // Before handling any other stream, we must ensure the peer is authenticated and authorized.+ remotePeer := s.Conn().RemotePeer()++ identity, err := n.Store.GetVerifiedIdentity(remotePeer)+ if err != nil {+ if resetErr := s.Reset(); resetErr != nil {+ fmt.Printf("failed to reset unauthenticated stream: %v\n", resetErr)+ }+ return+ }++ reqCtx := RequestContext{+ PeerID: remotePeer,+ User: identity.UserID,+ Protocol: pid,+ }++ // AuthZ Check+ if err := n.Authorize(identity.RawBiscuit, reqCtx); err != nil {+ fmt.Printf("[AuthZ] Denied %s to %s: %v\n", pid, identity.UserID, err)+ if resetErr := s.Reset(); resetErr != nil {+ fmt.Printf("failed to reset unauthorized stream: %v\n", resetErr)+ }+ return+ }++ handler(s)+ })+}++func (n *SamNode) Authorize(rawToken []byte, req RequestContext) error {+ b, err := biscuit.Unmarshal(rawToken)+ if err != nil {+ return fmt.Errorf("invalid biscuit: %w", err)+ }++ authorizer, err := b.Authorizer(n.HubPublicKey)+ if err != nil {+ return err+ }++ // Inject the current action context (Standard Vocabulary)+ authorizer.AddFact(biscuit.Fact{+ Predicate: biscuit.Predicate{+ Name: "operation",+ IDs: []biscuit.Term{biscuit.String(req.Protocol)},+ },+ })++ return authorizer.Authorize()+}diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.goindex 9044c513..2d069a39 100644--- a/cmd/sam-node/node.go+++ b/cmd/sam-node/node.go@@ -1,11 +1,26 @@+// 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 mainimport ("context"+ "crypto/ed25519""encoding/json""fmt"- "sync"+ "github.com/biscuit-auth/biscuit-go/v2""github.com/libp2p/go-libp2p"dht "github.com/libp2p/go-libp2p-kad-dht"pubsub "github.com/libp2p/go-libp2p-pubsub"@@ -17,110 +32,175 @@ import (libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls"libp2pquic "github.com/libp2p/go-libp2p/p2p/transport/quic""github.com/libp2p/go-libp2p/p2p/transport/tcp"+ "github.com/libp2p/go-msgio"+ "github.com/multiformats/go-multiaddr")-const AuthProtocol = protocol.ID("/sam/auth/1.0.0")+const AuthProtocolID = protocol.ID("/sam/auth/1.0.0")++// IdentityExchange is the "Auth Envelope"+type IdentityExchange struct {+ Biscuit []byte `json:"biscuit"`+ Version string `json:"version"`+}type SamNode struct {Host host.HostDHT *dht.IpfsDHTPubSub *pubsub.PubSubStore *Store- TrustedPeers map[peer.ID]bool- mu sync.RWMutex+ HubPublicKey ed25519.PublicKey}-// NewSamNode initializes a FIPS-compliant libp2p host-func NewSamNode(ctx context.Context, priv crypto.PrivKey, listenAddrs []string) (*SamNode, error) {+// NewSamNode creates a new Agent instance secured with the 4-layer pipeline.+func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.PublicKey, hubAddrs []multiaddr.Multiaddr, store *Store) (*SamNode, error) {+ node := &SamNode{+ Store: store,+ HubPublicKey: hubPubKey,+ }++ // Layer 2: Attach the Bouncer (Gater)+ gater := &nodeConnGate{node: node}++ // Layer 1: Establish FIPS-compliant Transportsh, err := libp2p.New(- libp2p.Identity(priv),- libp2p.ListenAddrStrings(listenAddrs...),- libp2p.Transport(libp2pquic.NewTransport), // Preferred (UDP/QUIC)- libp2p.Transport(tcp.NewTCPTransport), // Fallback (TCP)- libp2p.Security(libp2ptls.ID, libp2ptls.New), // FIPS Compliant TLS 1.3+ libp2p.Identity(privKey),+ libp2p.Transport(libp2pquic.NewTransport),+ libp2p.Transport(tcp.NewTCPTransport),+ libp2p.Security(libp2ptls.ID, libp2ptls.New),+ libp2p.ConnectionGater(gater),)if err != nil {- return nil, fmt.Errorf("failed to create libp2p host: %w", err)+ return nil, err}+ node.Host = h- return &SamNode{- Host: h,- TrustedPeers: make(map[peer.ID]bool),- }, nil-}+ // Initialize Rendezvous (DHT Client)+ kdht, err := dht.New(ctx, h, dht.Mode(dht.ModeClient))+ if err != nil {+ return nil, err+ }+ node.DHT = kdht-// SecureStreamHandler implements the "Reject by Default" middleware-func (n *SamNode) SecureStreamHandler(pid protocol.ID, handler network.StreamHandler) {- n.Host.SetStreamHandler(pid, func(s network.Stream) {- n.mu.RLock()- isTrusted := n.TrustedPeers[s.Conn().RemotePeer()]- n.mu.RUnlock()-- if !isTrusted {- // DROP: Peer has not completed the /sam/auth/1.0.0 handshake- fmt.Printf("Blocked unauthorized stream request for %s from %s\n", pid, s.Conn().RemotePeer())- if err := s.Reset(); err != nil {- fmt.Printf("Failed to reset unauthorized stream: %v\n", err)+ // Bootstrap: Connect to the Hub+ for _, addr := range hubAddrs {+ addrInfo, _ := peer.AddrInfoFromP2pAddr(addr)+ if addrInfo != nil {+ if err := h.Connect(ctx, *addrInfo); err != nil {+ fmt.Printf("Warning: Failed to bootstrap to hub %s: %v\n", addr, err)}- return}+ }- handler(s)- })-}--func (n *SamNode) ListenForMeshEvents(ctx context.Context) error {- ps, err := pubsub.NewGossipSub(ctx, n.Host)+ // Initialize Gossipsub for Hub Events+ ps, err := pubsub.NewGossipSub(ctx, h)if err != nil {- return err+ return nil, err}- topic, err := ps.Join("sam/mesh/events/v1")+ node.PubSub = ps++ // Listen for Network Evictions/Revocations from the Hub+ go node.listenForHubEvents(ctx)++ // Layer 3: Open the Lobby Door (Auth Protocol is bypassed by Layer 4)+ node.WrapSecurely(AuthProtocolID, node.HandleAuthHandshake)++ return node, nil+}++// listenForHubEvents listens to the topic established by the Hub+func (n *SamNode) listenForHubEvents(ctx context.Context) {+ topic, err := n.PubSub.Join("sam/mesh/events/v1")if err != nil {- return err+ return}- n.PubSub = pssub, err := topic.Subscribe()if err != nil {- return err+ return}- go func() {- for {- msg, err := sub.Next(ctx)- if err != nil {- return- }- var ev struct {- PeerID peer.ID `json:"peer_id"`- Action string `json:"action"` // "LEFT", "BANNED"- }- if err := json.Unmarshal(msg.Data, &ev); err == nil {- if ev.Action == "LEFT" || ev.Action == "BANNED" {- n.mu.Lock()- delete(n.TrustedPeers, ev.PeerID)- n.mu.Unlock()- fmt.Printf("[Mesh] Evicting peer %s based on Hub gossip\n", ev.PeerID)- }- }+ for {+ msg, err := sub.Next(ctx)+ if err != nil {+ return}- }()- return nil+ // In a full implementation, parse the event (e.g. {"action": "LEFT", "peer": "Qm..."})+ // and verify the Hub's signature on the payload to prevent forged kicks.+ fmt.Printf("[Mesh Event] Received Hub update from %s\n", msg.ReceivedFrom)+ }}-// HandleAuthHandshake handles incoming Identity Biscuits+// HandleAuthHandshake is the core libp2p stream handler for /sam/auth/1.0.0.+// This is the "Admission Office" of the mesh node.func (n *SamNode) HandleAuthHandshake(s network.Stream) {defer func() {if err := s.Close(); err != nil {fmt.Printf("Failed to close auth stream: %v\n", err)}}()+ remotePeer := s.Conn().RemotePeer()++ reader := msgio.NewVarintReaderSize(s, 1024*64)+ msg, err := reader.ReadMsg()+ if err != nil {+ fmt.Printf("[AuthN] Failed to read handshake from %s: %v\n", remotePeer, err)+ return+ }+ defer reader.ReleaseMsg(msg)++ var exchange IdentityExchange+ if err := json.Unmarshal(msg, &exchange); err != nil {+ fmt.Printf("[AuthN] Invalid JSON from %s\n", remotePeer)+ return+ }++ // 2. Unmarshal and verify token format+ b, err := biscuit.Unmarshal(exchange.Biscuit)+ if err != nil {+ fmt.Printf("[AuthN] Malformed biscuit from %s\n", remotePeer)+ return+ }++ // 3. Verify signature chain against the trusted Hub key.+ authorizer, err := b.Authorizer(n.HubPublicKey)+ if err != nil {+ fmt.Printf("[AuthN] Signature verification setup failed for %s: %v\n", remotePeer, err)+ return+ }+ if err := authorizer.Authorize(); err != nil {+ fmt.Printf("[AuthN] Authorization failed for %s: %v\n", remotePeer, err)+ return+ }- // MVP: Logic to read Biscuit from stream, verify against Hub Public Key,- // and ensure it is bound to the connecting PeerID.+ // 4. Enforce hardware binding: token must include node(<remotePeerID>)+ boundFact := biscuit.Fact{Predicate: biscuit.Predicate{+ Name: "node",+ IDs: []biscuit.Term{biscuit.String(remotePeer.String())},+ }}+ if _, err := b.GetBlockID(boundFact); err != nil {+ fmt.Printf("[AuthN] Token is not bound to peer %s\n", remotePeer)+ return+ }- n.mu.Lock()- n.TrustedPeers[s.Conn().RemotePeer()] = true- n.mu.Unlock()+ // Query for the standard facts we mapped in the Hub+ // user_id, user_email, group, mesh_id+ // Note: We use the authorizer to extract these values from the Datalog state+ identity := VerifiedIdentity{+ RawBiscuit: exchange.Biscuit,+ // In a full implementation, you would use authorizer.Query()+ // to extract specific strings like user_id and group.+ NodeID: remotePeer.String(), // Placeholder for Datalog query result+ UserID: "extracted_id", // Placeholder for Datalog query result+ UserEmail: "extracted_email", // Placeholder for Datalog query result+ MeshID: "extracted_mesh", // Placeholder for Datalog query result+ }++ // 5. Save to the persistent session cache (BoltDB)+ // Once saved here, the ConnectionGater and Middleware will "recognize" this peer.+ if err := n.Store.SaveVerifiedIdentity(remotePeer, identity); err != nil {+ fmt.Printf("[AuthN] Store error for %s: %v\n", remotePeer, err)+ return+ }- fmt.Printf("Peer %s authenticated successfully via Biscuit\n", s.Conn().RemotePeer())+ fmt.Printf("[AuthN] Successfully authenticated peer %s (%s)\n", remotePeer, identity.UserEmail)}diff --git a/cmd/sam-node/store.go b/cmd/sam-node/store.goindex 393b43e6..694f0ccd 100644--- a/cmd/sam-node/store.go+++ b/cmd/sam-node/store.go@@ -1,10 +1,26 @@+// 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 mainimport (+ "encoding/json""fmt""os""path/filepath"+ "github.com/libp2p/go-libp2p/core/peer""go.etcd.io/bbolt")@@ -38,7 +54,15 @@ func NewStore(dir string) (*Store, error) {}err = db.Update(func(tx *bbolt.Tx) error {- _, _ = tx.CreateBucketIfNotExists([]byte(bucketIdentity))+ if _, err := tx.CreateBucketIfNotExists([]byte(bucketIdentity)); err != nil {+ return err+ }+ if _, err := tx.CreateBucketIfNotExists([]byte(bucketVerifiedPeers)); err != nil {+ return err+ }+ if _, err := tx.CreateBucketIfNotExists([]byte(bucketBannedPeers)); err != nil {+ return err+ }return nil})@@ -85,3 +109,64 @@ func (s *Store) LoadKey() ([]byte, error) {func (s *Store) Close() error {return s.db.Close()}++const (+ bucketVerifiedPeers = "verified_peers"+ bucketBannedPeers = "banned_peers"+)++// VerifiedIdentity is the "Visitor Badge" saved after Layer 3+type VerifiedIdentity struct {+ NodeID string `json:"node"`+ UserID string `json:"user"`+ UserEmail string `json:"email"`+ MeshID string `json:"namespace"`+ RawBiscuit []byte `json:"raw_biscuit"`+}++// IsBanned checks local store to see if this peer is banned.+func (s *Store) IsBanned(p peer.ID) bool {+ var banned bool+ _ = s.db.View(func(tx *bbolt.Tx) error {+ b := tx.Bucket([]byte(bucketBannedPeers))+ if b == nil {+ return nil+ }+ if b.Get([]byte(p.String())) != nil {+ banned = true+ }+ return nil+ })+ return banned+}++func (s *Store) SaveVerifiedIdentity(p peer.ID, identity VerifiedIdentity) error {+ return s.db.Update(func(tx *bbolt.Tx) error {+ b := tx.Bucket([]byte(bucketVerifiedPeers))+ if b == nil {+ var err error+ b, err = tx.CreateBucketIfNotExists([]byte(bucketVerifiedPeers))+ if err != nil {+ return err+ }+ }+ data, _ := json.Marshal(identity)+ return b.Put([]byte(p.String()), data)+ })+}++func (s *Store) GetVerifiedIdentity(p peer.ID) (*VerifiedIdentity, error) {+ var identity VerifiedIdentity+ err := s.db.View(func(tx *bbolt.Tx) error {+ b := tx.Bucket([]byte(bucketVerifiedPeers))+ if b == nil {+ return fmt.Errorf("peer auth store is not initialized")+ }+ data := b.Get([]byte(p.String()))+ if data == nil {+ return fmt.Errorf("peer not authenticated")+ }+ return json.Unmarshal(data, &identity)+ })+ return &identity, err+}diff --git a/go.mod b/go.modindex a6ff4d9d..ed24a9b1 100644--- a/go.mod+++ b/go.mod@@ -1,4 +1,4 @@-module sam+module github.com/google/samgo 1.25.7@@ -9,11 +9,9 @@ require (github.com/libp2p/go-libp2p-http v0.5.0github.com/libp2p/go-libp2p-kad-dht v0.39.0github.com/libp2p/go-libp2p-pubsub v0.15.0- github.com/modelcontextprotocol/go-sdk v1.5.0+ github.com/libp2p/go-msgio v0.3.0github.com/multiformats/go-multiaddr v0.16.1github.com/spf13/cobra v1.10.2- github.com/vishvananda/netlink v1.3.1- github.com/vishvananda/netns v0.0.5go.etcd.io/bbolt v1.4.3golang.org/x/oauth2 v0.36.0)@@ -34,7 +32,6 @@ require (github.com/go-logr/stdr v1.2.2 // indirectgithub.com/gogo/protobuf v1.3.2 // indirectgithub.com/google/gopacket v1.1.19 // indirect- github.com/google/jsonschema-go v0.4.2 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/gorilla/websocket v1.5.3 // indirectgithub.com/hashicorp/golang-lru v1.0.2 // indirect@@ -58,7 +55,6 @@ require (github.com/libp2p/go-libp2p-kbucket v0.8.0 // indirectgithub.com/libp2p/go-libp2p-record v0.3.1 // indirectgithub.com/libp2p/go-libp2p-routing-helpers v0.7.5 // indirect- github.com/libp2p/go-msgio v0.3.0 // indirectgithub.com/libp2p/go-netroute v0.4.0 // indirectgithub.com/libp2p/go-reuseport v0.4.0 // indirectgithub.com/libp2p/go-yamux/v5 v5.1.0 // indirect@@ -103,13 +99,10 @@ require (github.com/quic-go/qpack v0.6.0 // indirectgithub.com/quic-go/quic-go v0.59.0 // indirectgithub.com/quic-go/webtransport-go v0.10.0 // indirect- github.com/segmentio/asm v1.1.3 // indirect- github.com/segmentio/encoding v0.5.4 // indirectgithub.com/spaolacci/murmur3 v1.1.0 // indirectgithub.com/spf13/pflag v1.0.9 // indirectgithub.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 // indirectgithub.com/wlynxg/anet v0.0.5 // indirect- github.com/yosida95/uritemplate/v3 v3.0.2 // indirectgo.opentelemetry.io/auto/sdk v1.2.1 // indirectgo.opentelemetry.io/otel v1.43.0 // indirectgo.opentelemetry.io/otel/metric v1.43.0 // indirectdiff --git a/go.sum b/go.sumindex 5a1fe3ae..9f0aa689 100644--- a/go.sum+++ b/go.sum@@ -117,8 +117,6 @@ github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLgithub.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=-github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=-github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=@@ -167,8 +165,6 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjXgithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=-github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=-github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=@@ -328,8 +324,6 @@ github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0Qugithub.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=-github.com/modelcontextprotocol/go-sdk v1.5.0 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU=-github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=@@ -430,10 +424,6 @@ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDgithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=-github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=-github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=-github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=-github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=github.com/shurcooL/go v0.0.0-20200502201357-93f07166e636/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg=github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=@@ -468,18 +458,12 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKugithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=github.com/urfave/cli v1.22.10/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=-github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=-github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=-github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=-github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0 h1:GDDkbFiaK8jsSDJfjId/PEGEShv6ugrt4kYsC5UIDaQ=github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0/go.mod h1:x6AKhvSSexNrVSrViXSHUEbICjmGXhtgABaHIySUSGw=github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 h1:EKhdznlJHPMoKr0XTrX+IlJs1LH3lyx2nfr1dOlZ79k=github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1/go.mod h1:8UvriyWtv5Q5EOgjHaSseUEdkQfvwFv1I/In/O2M9gc=github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=-github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=-github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=@@ -697,10 +681,8 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBcgolang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=golang.org/x/telemetry v0.0.0-20260414141209-fac6e1c83189 h1:7p/97HVUhjLxq0iDCOrbBrAK6mXKEx9i0HzThbOM4L0=diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bashindex f7a412f1..55717ea3 100644--- a/tests/e2e/lib/container_mesh.bash+++ b/tests/e2e/lib/container_mesh.bash@@ -6,10 +6,30 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenMESH_HELPERS_LOADED=1MESH_RUNTIME_IMAGE="${MESH_RUNTIME_IMAGE:-sam-e2e-runtime:local}"+ MESH_NETWORK_SUBNET_BASE="${MESH_NETWORK_SUBNET_BASE:-172.31}"MESH_NETWORK=""MESH_CONTAINERS=()MESH_PREFIX=""+ # Best-effort cleanup of leaked resources from prior failed runs.+ mesh_cleanup_stale_resources() {+ local ids+ ids="$(docker ps -aq --filter "name=mesh-")"+ if [[ -n "${ids}" ]]; then+ # shellcheck disable=SC2086+ docker rm -f ${ids} >/dev/null 2>&1 || true+ fi++ local nets+ nets="$(docker network ls --format '{{.Name}}' | grep '^mesh-.*-net$' || true)"+ if [[ -n "${nets}" ]]; then+ while IFS= read -r net; do+ [[ -z "${net}" ]] && continue+ docker network rm "${net}" >/dev/null 2>&1 || true+ done <<< "${nets}"+ fi+ }+mesh_require_docker() {command -v docker >/dev/null 2>&1 || return 1docker info >/dev/null 2>&1 || return 1@@ -24,9 +44,20 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then}mesh_setup_env() {- MESH_PREFIX="mesh-${BATS_TEST_NUMBER}-$(date +%s)"+ mesh_cleanup_stale_resources++ MESH_PREFIX="mesh-${BATS_TEST_NUMBER}-$$-$(date +%s)"MESH_NETWORK="${MESH_PREFIX}-net"- docker network create "${MESH_NETWORK}" >/dev/null++ # Use a deterministic subnet slice to reduce chance of Docker IPAM exhaustion.+ local subnet+ local octet+ octet=$(( (BATS_TEST_NUMBER % 200) + 20 ))+ subnet="${MESH_NETWORK_SUBNET_BASE}.${octet}.0/24"++ if ! docker network create --subnet "${subnet}" "${MESH_NETWORK}" >/dev/null 2>&1; then+ docker network create "${MESH_NETWORK}" >/dev/null+ fi}mesh_cleanup_env() {diff --git a/tests/integration/cuj_test.go b/tests/integration/cuj_test.goindex 3a83d20f..6b1822d9 100644--- a/tests/integration/cuj_test.go+++ b/tests/integration/cuj_test.go@@ -25,6 +25,7 @@ import (func TestSamNodeRunWithManualTokenStarts(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")+ hubURL := startMockHubConfigServer(t)tmpHome := t.TempDir()env := append(os.Environ(),"HOME="+tmpHome,@@ -39,6 +40,7 @@ func TestSamNodeRunWithManualTokenStarts(t *testing.T) {"",nodeBin,"run",+ "--hub", hubURL,"--token", "test-token","--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0",diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex ae2f8476..d8e5d87b 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -17,12 +17,21 @@ package integration_testimport ("bytes""context"+ "crypto/ed25519"+ "crypto/rand"+ "encoding/hex"+ "encoding/json""errors"+ "net/http"+ "net/http/httptest""os/exec""path/filepath""runtime""testing""time"++ corecrypto "github.com/libp2p/go-libp2p/core/crypto"+ "github.com/libp2p/go-libp2p/core/peer")func repoRoot(t *testing.T) string {@@ -80,3 +89,38 @@ func runCommand(}return stdout.String(), stderr.String(), err}++func startMockHubConfigServer(t *testing.T) string {+ t.Helper()++ pubKey, _, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatalf("generating hub public key: %v", err)+ }++ bootstrapPriv, _, err := corecrypto.GenerateEd25519Key(rand.Reader)+ if err != nil {+ t.Fatalf("generating bootstrap key: %v", err)+ }+ bootstrapPeerID, err := peer.IDFromPrivateKey(bootstrapPriv)+ if err != nil {+ t.Fatalf("deriving bootstrap peer id: %v", err)+ }+ bootstrapAddr := "/ip4/127.0.0.1/tcp/4002/p2p/" + bootstrapPeerID.String()++ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/v1/config":+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "public_key": hex.EncodeToString(pubKey),+ "mesh_id": "test-mesh",+ "bootstrap_nodes": []string{bootstrapAddr},+ })+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(ts.Close)+ return ts.URL+}diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.goindex 9a7db421..f4bb3545 100644--- a/tests/integration/proxy_test.go+++ b/tests/integration/proxy_test.go@@ -25,6 +25,7 @@ import (func TestSamNodeLoginThenRunWithStoredIdentity(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")+ hubURL := startMockHubConfigServer(t)tmpHome := t.TempDir()env := append(os.Environ(),"HOME="+tmpHome,@@ -39,6 +40,7 @@ func TestSamNodeLoginThenRunWithStoredIdentity(t *testing.T) {"test-biscuit-token\n",nodeBin,"login",+ "--hub", hubURL,)if err != nil {t.Fatalf("sam-node login failed: %v\nstdout:\n%s\nstderr:\n%s", err, loginOut, loginErrOut)@@ -55,6 +57,7 @@ func TestSamNodeLoginThenRunWithStoredIdentity(t *testing.T) {"",nodeBin,"run",+ "--hub", hubURL,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0",)