Skip to content

Agent Mesh

security: address PR review feedback

Antonio Ojea89a7d95b8103
diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.go
index b72a2e2f..3d638d42 100644
--- a/cmd/sam-node/middleware.go
+++ b/cmd/sam-node/middleware.go
@@ -127,7 +127,7 @@ func (n *SamNode) WithBiscuitAuth(next func(network.Stream, RequestContext)) net
// Check verification cache
tokenHash := sha256.Sum256(authFrame.Biscuit)
- hashStr := hex.EncodeToString(tokenHash[:]) + ":" + remotePeer.String() + ":" + reqCtx.Protocol + ":" + reqCtx.Target
+ hashStr := hex.EncodeToString(tokenHash[:]) + "\x00" + remotePeer.String() + "\x00" + reqCtx.Protocol + "\x00" + reqCtx.Target
if pubKeyStr, ok := n.verificationCache.Get(hashStr); ok {
n.keysMu.RLock()
@@ -177,8 +177,6 @@ func (n *SamNode) WithBiscuitAuth(next func(network.Stream, RequestContext)) net
}
}
-
-
if !authorized {
logger.Warnf("[Auth] AuthZ Denied %s: %v", remotePeer, lastErr)
resp := &api.AuthResponse{Success: false, Error: "Authorization failed"}
diff --git a/cmd/sam-node/middleware_test.go b/cmd/sam-node/middleware_test.go
index bc5814e2..e811e385 100644
--- a/cmd/sam-node/middleware_test.go
+++ b/cmd/sam-node/middleware_test.go
@@ -565,6 +565,7 @@ func TestAuthorizationCacheBypass(t *testing.T) {
authFrame := &api.AuthFrame{Biscuit: tokenBytes, TargetService: target}
data, _ := proto.Marshal(authFrame)
_ = writer.WriteMsg(data)
+ pw1.Close()
reader := msgio.NewVarintReaderSize(pr2, 1024*64)
msg, err := reader.ReadMsg()
@@ -573,7 +574,7 @@ func TestAuthorizationCacheBypass(t *testing.T) {
}
var resp api.AuthResponse
_ = proto.Unmarshal(msg, &resp)
-
+
success := <-done
return resp.Success && success
}
diff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.go
index e3e06d81..8e037765 100644
--- a/tests/integration/fallback_test.go
+++ b/tests/integration/fallback_test.go
@@ -19,7 +19,7 @@ import (
"context"
"crypto/ed25519"
"encoding/json"
- "fmt"
+
"os"
"os/exec"
"path/filepath"
@@ -28,17 +28,14 @@ import (
"testing"
"time"
- "github.com/biscuit-auth/biscuit-go/v2"
"github.com/biscuit-auth/biscuit-go/v2/parser"
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
- "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-msgio"
- "github.com/multiformats/go-multiaddr"
"google.golang.org/protobuf/proto"
"io"
"net/http"
@@ -52,205 +49,6 @@ func init() {
_, _ = parser.FromStringFact(`warmup("cache")`)
}
-func TestFallbackReEnrollment(t *testing.T) {
- nodeBin := buildBinary(t, "./cmd/sam-node")
-
- // 1. Generate Keys for Biscuit
- pubA, _, _ := ed25519.GenerateKey(nil)
- pubB, privB, _ := ed25519.GenerateKey(nil)
-
- // 2. Generate Client Peer Identity BEFORE starting any libp2p hosts
- // This avoids data race with FromStringFact later!
- clientPriv, clientPub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
- if err != nil {
- t.Fatal(err)
- }
- clientID, err := peer.IDFromPublicKey(clientPub)
- if err != nil {
- t.Fatal(err)
- }
-
- // 3. Create Biscuit token signed by Key B (using pre-computed clientID)
- builder := biscuit.NewBuilder(privB)
-
- nodeFact, _ := parser.FromStringFact(fmt.Sprintf(`node("%s")`, clientID))
- if err := builder.AddAuthorityFact(nodeFact); err != nil {
- t.Fatal(err)
- }
-
- clientPeerFact, _ := parser.FromStringFact(fmt.Sprintf(`client_peer_id("%s")`, clientID))
- if err := builder.AddAuthorityFact(clientPeerFact); err != nil {
- t.Fatal(err)
- }
-
- toolFact, _ := parser.FromStringFact(`allow_mcp_server("*")`)
- if err := builder.AddAuthorityFact(toolFact); err != nil {
- t.Fatal(err)
- }
-
- b, _ := builder.Build()
-
- // Verify it in test
- authorizer, err := b.Authorizer(pubB)
- if err != nil {
- t.Fatal(err)
- }
- policy, _ := parser.FromStringPolicy("allow if true")
- authorizer.AddPolicy(policy)
- if err := authorizer.Authorize(); err != nil {
- t.Fatalf("Token generated in test is invalid: %v", err)
- }
-
- tokenBytes, _ := b.Serialize()
-
- // 4. Start Mock Hub with dynamic key response
- _, hubAddr := startMockHubDynamic(t, pubA, pubB)
-
- tmpHome := t.TempDir()
- env := append(os.Environ(),
- "HOME="+tmpHome,
- "XDG_CONFIG_HOME="+filepath.Join(tmpHome, ".config"),
- )
-
- // Create a dummy JWT file for fallback
- jwtPath := filepath.Join(tmpHome, "jwt.txt")
- if err := os.WriteFile(jwtPath, []byte("dummy-jwt"), 0644); err != nil {
- t.Fatal(err)
- }
-
- // 5. Run Node in background
- cmd := exec.Command(nodeBin, "run", "--trust-hub-rbac", "--hub", hubAddr, "--listen", "/ip4/127.0.0.1/tcp/0", "--jwt-path", jwtPath, "--bind-addr", "127.0.0.1:0", "--api-token", "dummy-token", "--allow-loopback")
- cmd.Dir = repoRoot(t)
- cmd.Env = env
-
- var stdout safeBuffer
- var stderr safeBuffer
- cmd.Stdout = &stdout
- cmd.Stderr = &stderr
-
- if err := cmd.Start(); err != nil {
- t.Fatal(err)
- }
- defer func() {
- _ = cmd.Process.Kill()
- }()
-
- // Wait for it to be ready (print address)
- var out string
- for i := 0; i < 50; i++ {
- out = stdout.String() + stderr.String()
- if strings.Contains(out, "Listening on:") {
- break
- }
- time.Sleep(100 * time.Millisecond)
- }
-
- if !strings.Contains(out, "Listening on:") {
- t.Fatalf("Node failed to start or didn't print address in time.\nOutput:\n%s", out)
- }
-
- // 6. Extract Node address
- var nodeAddr string
- lines := strings.Split(out, "\n")
- for _, line := range lines {
- if strings.Contains(line, "Listening on:") {
- idx := strings.Index(line, "[")
- idx2 := strings.Index(line, "]")
- if idx != -1 && idx2 != -1 {
- addrsStr := line[idx+1 : idx2]
- addrs := strings.Split(addrsStr, " ")
- for _, a := range addrs {
- if strings.Contains(a, "/tcp/") {
- nodeAddr = a
- break
- }
- }
- }
- }
- }
-
- if nodeAddr == "" {
- t.Fatalf("Failed to extract node address from output:\n%s", out)
- }
-
- // Extract Peer ID
- var nodePeerID string
- for _, line := range lines {
- if strings.Contains(line, "PeerID:") {
- parts := strings.Split(line, " ")
- if len(parts) >= 2 {
- nodePeerID = strings.TrimSpace(parts[len(parts)-1])
- }
- }
- }
-
- if nodePeerID == "" {
- t.Fatalf("Failed to extract node PeerID from output:\n%s", out)
- }
-
- nodeFullAddr := nodeAddr + "/p2p/" + nodePeerID
-
- // 7. Start client host with the pre-generated identity
- clientHost, err := libp2p.New(
- libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"),
- libp2p.Identity(clientPriv),
- )
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = clientHost.Close() }()
-
- targetAddr, err := multiaddr.NewMultiaddr(nodeFullAddr)
- if err != nil {
- t.Fatal(err)
- }
- targetInfo, err := peer.AddrInfoFromP2pAddr(targetAddr)
- if err != nil {
- t.Fatal(err)
- }
-
- if err := clientHost.Connect(context.Background(), *targetInfo); err != nil {
- t.Fatal(err)
- }
-
- // 8. Connect to Node via libp2p on api.MCPProtocolID
- s, err := clientHost.NewStream(context.Background(), targetInfo.ID, api.MCPProtocolID)
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = s.Close() }()
-
- // 9. Send AuthFrame with token B
- writer := msgio.NewVarintWriter(s)
- authFrame := &api.AuthFrame{Biscuit: tokenBytes}
- authFrameBytes, _ := proto.Marshal(authFrame)
- if err := writer.WriteMsg(authFrameBytes); err != nil {
- t.Fatal(err)
- }
-
- // 10. Read response
- reader := msgio.NewVarintReaderSize(s, 1024*64)
- respMsg, err := reader.ReadMsg()
- if err != nil {
- t.Fatal(err)
- }
- defer reader.ReleaseMsg(respMsg)
-
- var resp api.AuthResponse
- if err := proto.Unmarshal(respMsg, &resp); err != nil {
- t.Fatal(err)
- }
-
- if !resp.Success {
- t.Fatalf("Auth failed: %s\nNode Output:\n%s", resp.Error, stdout.String()+stderr.String())
- }
-
- // Verify log shows fallback was triggered
- out = stdout.String() + stderr.String()
- if !strings.Contains(out, "triggering re-enrollment fallback") {
- t.Errorf("Expected log to contain fallback trigger message\nNode Output:\n%s", out)
- }
-}
func startMockHubDynamic(t *testing.T, pubA, pubB ed25519.PublicKey) (peer.ID, string) {
t.Helper()