Skip to content

Agent Mesh

refactor to use oidc different modes

Antonio Ojea6fdfbc0e8fa0
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..61a07fcf
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,27 @@
+# SAM Repository AI Agent Guidelines
+
+You are an expert software engineering assistant helping to develop, maintain, and test the **SAM** repository.
+
+## 1. Architecture & Component Independence
+* **Decoupled Architecture:** The `sam-hub` and `sam-node` components are strictly independent. They must not share internal state or tightly couple their logic.
+* **API Communication:** All data communication between `sam-hub` and `sam-node` must happen exclusively via the common API defined in `api/sam.proto`.
+* **Zero Trust:** Enforce a Zero Trust architecture. Assume no implicit trust between nodes, hubs, or external actors. All data passing through the API must be authenticated, authorized, and validated.
+* **Simple UX:** Maintain a very simple User Experience. Configuration, CLI usage, and error messages must be intuitive, minimal, and explicitly clear.
+
+## 2. Dependency Management (Strict Constraint)
+* **You are forbidden from suggesting any code that requires a new entry in `go.mod` unless you explicitly ask for my permission first.**
+* If a task can be solved using the existing dependencies or the Go standard library, you must choose that path even if it requires more lines of code.
+
+## 3. Testing Best Practices
+Enforce strict modularity in testing. The repository uses a defined testing pyramid (Unit, Integration, and E2E via Bats). You must adhere to the following testing philosophy:
+* **Optimize for Test Speed:** E2E tests are slow and strictly based on existing Critical User Journeys (CUJs).
+* **Push Coverage Down:** If test coverage for a specific edge case or feature can be added at a lower level (Unit or Integration), it is strictly preferred over E2E for speed.
+* **No Redundancy:** Do not replicate a test in the slower E2E path if it is already sufficiently covered in the Integration path.
+* **Test Domains:**
+ * **Unit Tests:** Focus on isolated, internal functions.
+ * **Integration Tests (`tests/integration/`):** Verify module interactions and API compliance in Go.
+ * **E2E Tests (`tests/e2e/*.bats`):** Use Bats (Bash Automated Testing System) exclusively for high-level, black-box testing of core CUJs.
+
+## 4. Code Quality & Modularity
+* Ensure all new code is highly modular, prioritizing small, single-responsibility functions that are easy to unit test.
+* Respect the existing repository structure (`cmd/`, `api/`, `internal/`, `tests/`).
diff --git a/api/constants.go b/api/constants.go
new file mode 100644
index 00000000..f666aa05
--- /dev/null
+++ b/api/constants.go
@@ -0,0 +1,6 @@
+package api
+
+import "github.com/libp2p/go-libp2p/core/protocol"
+
+const EnrollProtocolID protocol.ID = "/sam/enroll/1.0.0"
+const GossipEvents = "/sam/mesh/events/v1"
diff --git a/api/sam.pb.go b/api/sam.pb.go
index 994bd3bd..00279233 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -471,6 +471,134 @@ func (x *RevocationMsg) GetSignature() []byte {
return nil
}
+type EnrollRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Jwt string `protobuf:"bytes,1,opt,name=jwt,proto3" json:"jwt,omitempty"`
+ PeerId string `protobuf:"bytes,2,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *EnrollRequest) Reset() {
+ *x = EnrollRequest{}
+ mi := &file_api_sam_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *EnrollRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*EnrollRequest) ProtoMessage() {}
+
+func (x *EnrollRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[7]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use EnrollRequest.ProtoReflect.Descriptor instead.
+func (*EnrollRequest) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *EnrollRequest) GetJwt() string {
+ if x != nil {
+ return x.Jwt
+ }
+ return ""
+}
+
+func (x *EnrollRequest) GetPeerId() string {
+ if x != nil {
+ return x.PeerId
+ }
+ return ""
+}
+
+type EnrollResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ BiscuitToken []byte `protobuf:"bytes,1,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"`
+ ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`
+ HubPublicKey []byte `protobuf:"bytes,3,opt,name=hub_public_key,json=hubPublicKey,proto3" json:"hub_public_key,omitempty"`
+ HubAddresses []string `protobuf:"bytes,4,rep,name=hub_addresses,json=hubAddresses,proto3" json:"hub_addresses,omitempty"`
+ Expiration int64 `protobuf:"varint,5,opt,name=expiration,proto3" json:"expiration,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *EnrollResponse) Reset() {
+ *x = EnrollResponse{}
+ mi := &file_api_sam_proto_msgTypes[8]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *EnrollResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*EnrollResponse) ProtoMessage() {}
+
+func (x *EnrollResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[8]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use EnrollResponse.ProtoReflect.Descriptor instead.
+func (*EnrollResponse) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{8}
+}
+
+func (x *EnrollResponse) GetBiscuitToken() []byte {
+ if x != nil {
+ return x.BiscuitToken
+ }
+ return nil
+}
+
+func (x *EnrollResponse) GetErrorMessage() string {
+ if x != nil {
+ return x.ErrorMessage
+ }
+ return ""
+}
+
+func (x *EnrollResponse) GetHubPublicKey() []byte {
+ if x != nil {
+ return x.HubPublicKey
+ }
+ return nil
+}
+
+func (x *EnrollResponse) GetHubAddresses() []string {
+ if x != nil {
+ return x.HubAddresses
+ }
+ return nil
+}
+
+func (x *EnrollResponse) GetExpiration() int64 {
+ if x != nil {
+ return x.Expiration
+ }
+ return 0
+}
+
var File_api_sam_proto protoreflect.FileDescriptor
const file_api_sam_proto_rawDesc = "" +
@@ -512,7 +640,18 @@ const file_api_sam_proto_rawDesc = "" +
"\x0etarget_peer_id\x18\x01 \x01(\tR\ftargetPeerId\x12\x16\n" +
"\x06reason\x18\x02 \x01(\tR\x06reason\x12\x1c\n" +
"\ttimestamp\x18\x03 \x01(\x03R\ttimestamp\x12\x1c\n" +
- "\tsignature\x18\x04 \x01(\fR\tsignatureB\x1bZ\x19github.com/google/sam/apib\x06proto3"
+ "\tsignature\x18\x04 \x01(\fR\tsignature\":\n" +
+ "\rEnrollRequest\x12\x10\n" +
+ "\x03jwt\x18\x01 \x01(\tR\x03jwt\x12\x17\n" +
+ "\apeer_id\x18\x02 \x01(\tR\x06peerId\"\xc5\x01\n" +
+ "\x0eEnrollResponse\x12#\n" +
+ "\rbiscuit_token\x18\x01 \x01(\fR\fbiscuitToken\x12#\n" +
+ "\rerror_message\x18\x02 \x01(\tR\ferrorMessage\x12$\n" +
+ "\x0ehub_public_key\x18\x03 \x01(\fR\fhubPublicKey\x12#\n" +
+ "\rhub_addresses\x18\x04 \x03(\tR\fhubAddresses\x12\x1e\n" +
+ "\n" +
+ "expiration\x18\x05 \x01(\x03R\n" +
+ "expirationB\x1bZ\x19github.com/google/sam/apib\x06proto3"
var (
file_api_sam_proto_rawDescOnce sync.Once
@@ -526,28 +665,30 @@ func file_api_sam_proto_rawDescGZIP() []byte {
return file_api_sam_proto_rawDescData
}
-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 9)
+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 11)
var file_api_sam_proto_goTypes = []any{
- (*AuthEnvelope)(nil), // 0: sam.v1.AuthEnvelope
- (*HubConfig)(nil), // 1: sam.v1.HubConfig
- (*PeerProfile)(nil), // 2: sam.v1.PeerProfile
- (*PeerRegistry)(nil), // 3: sam.v1.PeerRegistry
- (*ModelProperty)(nil), // 4: sam.v1.ModelProperty
- (*AgentCard)(nil), // 5: sam.v1.AgentCard
- (*RevocationMsg)(nil), // 6: sam.v1.RevocationMsg
- nil, // 7: sam.v1.PeerRegistry.PeersEntry
- nil, // 8: sam.v1.AgentCard.MetadataEntry
+ (*AuthEnvelope)(nil), // 0: sam.v1.AuthEnvelope
+ (*HubConfig)(nil), // 1: sam.v1.HubConfig
+ (*PeerProfile)(nil), // 2: sam.v1.PeerProfile
+ (*PeerRegistry)(nil), // 3: sam.v1.PeerRegistry
+ (*ModelProperty)(nil), // 4: sam.v1.ModelProperty
+ (*AgentCard)(nil), // 5: sam.v1.AgentCard
+ (*RevocationMsg)(nil), // 6: sam.v1.RevocationMsg
+ (*EnrollRequest)(nil), // 7: sam.v1.EnrollRequest
+ (*EnrollResponse)(nil), // 8: sam.v1.EnrollResponse
+ nil, // 9: sam.v1.PeerRegistry.PeersEntry
+ nil, // 10: sam.v1.AgentCard.MetadataEntry
}
var file_api_sam_proto_depIdxs = []int32{
- 7, // 0: sam.v1.PeerRegistry.peers:type_name -> sam.v1.PeerRegistry.PeersEntry
- 4, // 1: sam.v1.AgentCard.models:type_name -> sam.v1.ModelProperty
- 8, // 2: sam.v1.AgentCard.metadata:type_name -> sam.v1.AgentCard.MetadataEntry
- 2, // 3: sam.v1.PeerRegistry.PeersEntry.value:type_name -> sam.v1.PeerProfile
- 4, // [4:4] is the sub-list for method output_type
- 4, // [4:4] is the sub-list for method input_type
- 4, // [4:4] is the sub-list for extension type_name
- 4, // [4:4] is the sub-list for extension extendee
- 0, // [0:4] is the sub-list for field type_name
+ 9, // 0: sam.v1.PeerRegistry.peers:type_name -> sam.v1.PeerRegistry.PeersEntry
+ 4, // 1: sam.v1.AgentCard.models:type_name -> sam.v1.ModelProperty
+ 10, // 2: sam.v1.AgentCard.metadata:type_name -> sam.v1.AgentCard.MetadataEntry
+ 2, // 3: sam.v1.PeerRegistry.PeersEntry.value:type_name -> sam.v1.PeerProfile
+ 4, // [4:4] is the sub-list for method output_type
+ 4, // [4:4] is the sub-list for method input_type
+ 4, // [4:4] is the sub-list for extension type_name
+ 4, // [4:4] is the sub-list for extension extendee
+ 0, // [0:4] is the sub-list for field type_name
}
func init() { file_api_sam_proto_init() }
@@ -561,7 +702,7 @@ func file_api_sam_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),
NumEnums: 0,
- NumMessages: 9,
+ NumMessages: 11,
NumExtensions: 0,
NumServices: 0,
},
diff --git a/api/sam.proto b/api/sam.proto
index f91c2cd9..0612e47d 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -59,3 +59,16 @@ message RevocationMsg {
int64 timestamp = 3;
bytes signature = 4;
}
+
+message EnrollRequest {
+ string jwt = 1;
+ string peer_id = 2;
+}
+
+message EnrollResponse {
+ bytes biscuit_token = 1;
+ string error_message = 2;
+ bytes hub_public_key = 3;
+ repeated string hub_addresses = 4;
+ int64 expiration = 5;
+}
diff --git a/cmd/sam-hub/hooks.go b/cmd/sam-hub/hooks.go
index bcbc6ff5..5e44d707 100644
--- a/cmd/sam-hub/hooks.go
+++ b/cmd/sam-hub/hooks.go
@@ -21,12 +21,10 @@ import (
"sync"
"time"
- p2phttp "github.com/libp2p/go-libp2p-http"
"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/libp2p/go-libp2p/p2p/protocol/identify"
"github.com/multiformats/go-multiaddr"
)
@@ -61,18 +59,9 @@ func (g *hubConnGate) InterceptSecured(dir network.Direction, p peer.ID, mas net
}
func (g *hubConnGate) InterceptUpgraded(c network.Conn) (bool, control.DisconnectReason) {
- protocolID := c.ConnState().StreamMultiplexer
-
- // Always allow the OIDC bridge protocol and basic identify
- if protocolID == p2phttp.DefaultP2PProtocol || protocolID == identify.ID {
- return true, 0
- }
-
- g.mu.RLock()
- defer g.mu.RUnlock()
-
- // REJECT BY DEFAULT: If not authenticated via OIDC, block any other protocol
- return g.authenticated[c.RemotePeer()], control.DisconnectReason(0)
+ // We allow all connections to be upgraded. Protocol-level authorization
+ // is handled at the stream level or by the watchdog.
+ return true, 0
}
var _ network.Notifiee = (*notifier)(nil)
diff --git a/cmd/sam-hub/http.go b/cmd/sam-hub/http.go
deleted file mode 100644
index 2c0e7320..00000000
--- a/cmd/sam-hub/http.go
+++ /dev/null
@@ -1,224 +0,0 @@
-// 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/google/sam/api"
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/peer"
- "google.golang.org/protobuf/encoding/protojson"
-)
-
-// 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
- }
-
- var claims struct {
- Subject string `json:"sub"`
- Email string `json:"email"`
- Groups []string `json:"groups"`
- }
-
- if h.AuthProvider == "oauth2" {
- req, _ := http.NewRequest("GET", h.OAuth2UserURL, nil)
- req.Header.Set("Authorization", "Bearer "+token.AccessToken)
- resp, err := http.DefaultClient.Do(req)
- if err != nil || resp.StatusCode != 200 {
- http.Error(w, "Failed to fetch user info from OAuth2 provider", 500)
- return
- }
- defer func() { _ = resp.Body.Close() }()
-
- var userData map[string]interface{}
- if err := json.NewDecoder(resp.Body).Decode(&userData); err != nil {
- http.Error(w, "Failed to parse user info JSON", 500)
- return
- }
-
- if sub, ok := userData[h.OAuth2UserField]; ok {
- claims.Subject = fmt.Sprintf("%v", sub)
- } else {
- http.Error(w, "User ID field not found in response", 500)
- return
- }
-
- if email, ok := userData[h.OAuth2EmailField]; ok {
- claims.Email = fmt.Sprintf("%v", email)
- }
- } else {
- 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
- }
- 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 := &api.HubConfig{
- PublicKeyHex: hex.EncodeToString(pubKey),
- MeshId: h.MeshID,
- BootstrapNodes: addrStrs,
- }
- b, err := protojson.Marshal(config)
- if err != nil {
- http.Error(w, "Failed to marshal config", http.StatusInternalServerError)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- if _, err := w.Write(b); err != nil {
- log.Printf("writing 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())
- }
-
- registry := &api.PeerRegistry{
- Peers: make(map[string]*api.PeerProfile),
- }
- for _, pID := range peers {
- registry.Peers[pID] = &api.PeerProfile{}
- }
- b, err := protojson.Marshal(registry)
- if err != nil {
- http.Error(w, "Failed to marshal peers", http.StatusInternalServerError)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- if _, err := w.Write(b); err != nil {
- log.Printf("writing peers response: %v", err)
- }
-}
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.go
index ebd8fb57..5a7c33ec 100644
--- a/cmd/sam-hub/main.go
+++ b/cmd/sam-hub/main.go
@@ -17,30 +17,32 @@ package main
import (
"context"
"crypto/ed25519"
- "encoding/base64"
+ "crypto/tls"
"encoding/hex"
"fmt"
"log"
"net/http"
"os"
+ "strings"
"time"
"github.com/biscuit-auth/biscuit-go/v2"
"github.com/coreos/go-oidc/v3/oidc"
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
- p2phttp "github.com/libp2p/go-libp2p-http"
dht "github.com/libp2p/go-libp2p-kad-dht"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/libp2p/go-libp2p/p2p/net/gostream"
+ "github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay"
libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls"
libp2pquic "github.com/libp2p/go-libp2p/p2p/transport/quic"
+ "github.com/libp2p/go-msgio"
"github.com/libp2p/go-libp2p/p2p/transport/tcp"
"github.com/spf13/cobra"
- "golang.org/x/oauth2"
+ "google.golang.org/protobuf/proto"
)
const (
@@ -48,37 +50,24 @@ const (
)
var (
- authProvider string
- oidcIssuer string
- clientID string
- clientSecret string
- biscuitHex string
- listenAddrs []string
- meshName string
- publicAddr string
- httpAddr string // Mandatory HTTP listener flag
- oauth2AuthURL string
- oauth2TokenURL string
- oauth2UserURL string
- oauth2UserField string
- oauth2EmailField string
+ oidcIssuer string
+ clientID string
+ biscuitHex string
+ listenAddrs []string
+ meshName string
+ insecureSkipTLSVerify bool
)
// Hub handles identity bridging and network discovery
type Hub struct {
Host host.Host
DHT *dht.IpfsDHT
- OIDCConfig *oauth2.Config
- Verifier *oidc.IDTokenVerifier
+ Providers map[string]*oidc.Provider
BiscuitKey ed25519.PrivateKey
MeshID string
PubSub *pubsub.PubSub
EventTopic *pubsub.Topic
- gater *hubConnGate
- AuthProvider string
- OAuth2UserURL string
- OAuth2UserField string
- OAuth2EmailField string
+ gater *hubConnGate
}
// NewHub starts a host supporting both QUIC and TCP (with TLS 1.3)
@@ -112,33 +101,27 @@ func NewHub(ctx context.Context) (*Hub, error) {
return nil, err
}
- var oidcConfig *oauth2.Config
- var verifier *oidc.IDTokenVerifier
-
- if authProvider == "oauth2" {
- oidcConfig = &oauth2.Config{
- ClientID: clientID,
- ClientSecret: clientSecret,
- Endpoint: oauth2.Endpoint{
- AuthURL: oauth2AuthURL,
- TokenURL: oauth2TokenURL,
- },
- RedirectURL: fmt.Sprintf("%s/callback", publicAddr),
- Scopes: []string{"user:email"},
+ issuers := strings.Split(oidcIssuer, ",")
+ providers := make(map[string]*oidc.Provider)
+ for _, iss := range issuers {
+ iss = strings.TrimSpace(iss)
+ if iss == "" {
+ continue
}
- } else {
- provider, err := oidc.NewProvider(ctx, oidcIssuer)
- if err != nil {
- return nil, err
+ var providerCtx = ctx
+ if insecureSkipTLSVerify {
+ tr := &http.Transport{
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ }
+ client := &http.Client{Transport: tr}
+ providerCtx = oidc.ClientContext(ctx, client)
}
- oidcConfig = &oauth2.Config{
- ClientID: clientID,
- ClientSecret: clientSecret,
- Endpoint: provider.Endpoint(),
- RedirectURL: fmt.Sprintf("%s/callback", publicAddr),
- Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
+ provider, err := oidc.NewProvider(providerCtx, iss)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create provider for %s: %w", iss, err)
}
- verifier = provider.Verifier(&oidc.Config{ClientID: clientID})
+ providers[iss] = provider
+ fmt.Printf("[OIDC] Trusted issuer: %s\n", iss)
}
// SAM_HUB_KEY stores an ed25519 seed as a 32-byte hex value.
@@ -149,17 +132,12 @@ func NewHub(ctx context.Context) (*Hub, error) {
bKey := ed25519.NewKeyFromSeed(keyBytes)
hub := &Hub{
- Host: h,
- DHT: kadDHT,
- gater: gater,
- OIDCConfig: oidcConfig,
- Verifier: verifier,
- BiscuitKey: bKey,
- MeshID: meshName,
- AuthProvider: authProvider,
- OAuth2UserURL: oauth2UserURL,
- OAuth2UserField: oauth2UserField,
- OAuth2EmailField: oauth2EmailField,
+ Host: h,
+ DHT: kadDHT,
+ gater: gater,
+ Providers: providers,
+ BiscuitKey: bKey,
+ MeshID: meshName,
}
h.Network().Notify(&notifier{hub: hub})
@@ -167,7 +145,7 @@ func NewHub(ctx context.Context) (*Hub, error) {
if err != nil {
return nil, err
}
- topic, err := ps.Join("sam/mesh/events/v1")
+ topic, err := ps.Join(api.GossipEvents)
if err != nil {
return nil, err
}
@@ -176,61 +154,164 @@ func NewHub(ctx context.Context) (*Hub, error) {
return hub, nil
}
-// 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) {
+func (h *Hub) handleEnroll(s network.Stream) {
+ defer func() {
+ _ = s.Close()
+ }()
+ remotePeer := s.Conn().RemotePeer()
+ fmt.Printf("[Enroll] New enrollment request from %s\n", remotePeer)
+
+ reader := msgio.NewVarintReaderSize(s, 1024*64)
+ msg, err := reader.ReadMsg()
+ if err != nil {
+ fmt.Printf("[Enroll] Failed to read message: %v\n", err)
+ return
+ }
+ defer reader.ReleaseMsg(msg)
+
+ var req api.EnrollRequest
+ if err := proto.Unmarshal(msg, &req); err != nil {
+ fmt.Printf("[Enroll] Failed to unmarshal request: %v\n", err)
+ return
+ }
+
+ if req.PeerId != remotePeer.String() {
+ fmt.Printf("[Enroll] Peer ID mismatch: %s != %s\n", req.PeerId, remotePeer)
+ h.sendEnrollResponse(s, nil, "Peer ID mismatch", 0)
+ return
+ }
+
+ // Parse JWT unverified to get issuer and audience
+ parser := jwt.Parser{}
+ jwtToken, _, err := parser.ParseUnverified(req.Jwt, jwt.MapClaims{})
+ if err != nil {
+ fmt.Printf("[Enroll] Failed to parse JWT: %v\n", err)
+ h.sendEnrollResponse(s, nil, "Failed to parse JWT", 0)
+ return
+ }
+ claims, ok := jwtToken.Claims.(jwt.MapClaims)
+ if !ok {
+ fmt.Printf("[Enroll] Invalid JWT claims\n")
+ h.sendEnrollResponse(s, nil, "Invalid JWT claims", 0)
+ return
+ }
+ iss, _ := claims["iss"].(string)
+
+ var aud string
+ switch a := claims["aud"].(type) {
+ case string:
+ aud = a
+ case []any:
+ if len(a) > 0 {
+ aud, _ = a[0].(string)
+ }
+ }
+
+ provider, ok := h.Providers[iss]
+ if !ok {
+ fmt.Printf("[Enroll] Unknown issuer: %s\n", iss)
+ h.sendEnrollResponse(s, nil, fmt.Sprintf("Unknown issuer: %s", iss), 0)
+ return
+ }
+
+ // TODO: Revisit client check later (enforce specific audience)
+ // For now we accept whatever audience is in the token by passing it as expected ClientID
+ verifier := provider.Verifier(&oidc.Config{ClientID: aud})
+
+ token, err := verifier.Verify(context.Background(), req.Jwt)
+ if err != nil {
+ fmt.Printf("[Enroll] JWT validation failed: %v\n", err)
+ h.sendEnrollResponse(s, nil, fmt.Sprintf("JWT validation failed: %v", err), 0)
+ return
+ }
+
+ var roles []string
+ if rolesAny, ok := claims["roles"].([]any); ok {
+ for _, r := range rolesAny {
+ if str, ok := r.(string); ok {
+ roles = append(roles, str)
+ }
+ }
+ }
+
builder := biscuit.NewBuilder(h.BiscuitKey)
- // user mapping (sub)
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "user",
- IDs: []biscuit.Term{biscuit.String(sub)},
+ Name: "expiration",
+ IDs: []biscuit.Term{biscuit.Date(token.Expiry)},
}}); err != nil {
- return "", err
+ fmt.Printf("[Enroll] Failed to add expiration fact: %v\n", err)
+ h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0)
+ return
}
- // email mapping (email)
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "email",
- IDs: []biscuit.Term{biscuit.String(email)},
+ Name: "node",
+ IDs: []biscuit.Term{biscuit.String(remotePeer.String())},
}}); err != nil {
- return "", err
+ fmt.Printf("[Enroll] Failed to add node fact: %v\n", err)
+ h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0)
+ return
}
- // group mapping (groups)
- for _, g := range groups {
+ for _, role := range roles {
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: "group",
- IDs: []biscuit.Term{biscuit.String(g)},
+ IDs: []biscuit.Term{biscuit.String(role)},
}}); err != nil {
- return "", err
+ fmt.Printf("[Enroll] Failed to add group fact: %v\n", err)
+ h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0)
+ return
}
}
- // peer_id mapping (hardware binding)
- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "node",
- IDs: []biscuit.Term{biscuit.String(p.String())},
- }}); err != nil {
- return "", err
+ t, err := builder.Build()
+ if err != nil {
+ fmt.Printf("[Enroll] Failed to build biscuit: %v\n", err)
+ h.sendEnrollResponse(s, nil, "Failed to build biscuit", 0)
+ return
}
- // mesh_id mapping (namespace)
- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "namespace",
- IDs: []biscuit.Term{biscuit.String(h.MeshID)},
- }}); err != nil {
- return "", err
+ biscuitData, err := t.Serialize()
+ if err != nil {
+ fmt.Printf("[Enroll] Failed to serialize biscuit: %v\n", err)
+ h.sendEnrollResponse(s, nil, "Failed to serialize biscuit", 0)
+ return
}
- t, err := builder.Build()
- if err != nil {
- return "", err
+ h.gater.mu.Lock()
+ h.gater.authenticated[remotePeer] = true
+ delete(h.gater.pending, remotePeer)
+ h.gater.mu.Unlock()
+
+ h.sendEnrollResponse(s, biscuitData, "", token.Expiry.Unix())
+ fmt.Printf("[Enroll] Successfully enrolled peer %s\n", remotePeer)
+}
+
+func (h *Hub) sendEnrollResponse(s network.Stream, biscuitToken []byte, errMsg string, expiration int64) {
+ var hubAddrs []string
+ for _, addr := range h.Host.Addrs() {
+ hubAddrs = append(hubAddrs, addr.String()+"/p2p/"+h.Host.ID().String())
+ }
+
+ pubKey := h.BiscuitKey.Public().(ed25519.PublicKey)
+
+ resp := &api.EnrollResponse{
+ BiscuitToken: biscuitToken,
+ ErrorMessage: errMsg,
+ HubPublicKey: pubKey,
+ HubAddresses: hubAddrs,
+ Expiration: expiration,
}
- data, err := t.Serialize()
+ data, err := proto.Marshal(resp)
if err != nil {
- return "", err
+ fmt.Printf("[Enroll] Failed to marshal response: %v\n", err)
+ return
+ }
+ writer := msgio.NewVarintWriter(s)
+ if err := writer.WriteMsg(data); err != nil {
+ fmt.Printf("[Enroll] Failed to write response: %v\n", err)
}
- return base64.StdEncoding.EncodeToString(data), nil
}
// startWatchdog periodically checks for peers that have connected but not completed OIDC
@@ -265,63 +346,30 @@ func main() {
if err != nil {
log.Fatal(err)
}
+ h.Host.SetStreamHandler(api.EnrollProtocolID, h.handleEnroll)
- // Watchdog: Expel peers that connect but never finish OIDC
+ // Watchdog: Expel peers that connect but never finish authentication
h.startWatchdog()
- mux := http.NewServeMux()
- // OIDC Endpoints
- mux.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
- listener, err := gostream.Listen(h.Host, p2phttp.DefaultP2PProtocol)
- if err != nil {
- log.Fatal(err)
- }
- defer func() {
- if err := listener.Close(); err != nil {
- log.Printf("closing p2p listener: %v", err)
- }
- }()
- // Serve the HTTP handler over libp2p streams
- go func() {
- server := &http.Server{
- Handler: mux,
- }
- if err := server.Serve(listener); err != nil {
- log.Printf("p2p http server exited: %v", err)
- }
- }()
-
fmt.Printf("SAM Hub Online (QUIC + TCP)\n")
fmt.Printf("MeshID: %s\n", h.MeshID)
fmt.Printf("PeerID: %s\n", h.Host.ID())
- // 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))
+ fmt.Printf("Hub running on P2P transports only.\n")
+ select {}
},
}
- rootCmd.Flags().StringVar(&authProvider, "auth-provider", "oidc", "Authentication provider (oidc or oauth2)")
- rootCmd.Flags().StringVar(&oidcIssuer, "issuer", os.Getenv("SAM_OIDC_ISSUER"), "OIDC Issuer URL")
- rootCmd.Flags().StringVar(&oauth2AuthURL, "oauth2-auth-url", "", "OAuth2 Authorization URL")
- rootCmd.Flags().StringVar(&oauth2TokenURL, "oauth2-token-url", "", "OAuth2 Token URL")
- rootCmd.Flags().StringVar(&oauth2UserURL, "oauth2-user-url", "", "OAuth2 User Info URL")
- rootCmd.Flags().StringVar(&oauth2UserField, "oauth2-user-field", "id", "JSON field for User ID")
- rootCmd.Flags().StringVar(&oauth2EmailField, "oauth2-email-field", "email", "JSON field for Email")
+ defIssuer := os.Getenv("SAM_OIDC_ISSUER")
+ if defIssuer == "" {
+ defIssuer = "https://accounts.google.com"
+ }
+ rootCmd.Flags().StringVar(&oidcIssuer, "issuer", defIssuer, "OIDC Issuer URL")
rootCmd.Flags().StringVar(&clientID, "client-id", os.Getenv("SAM_OIDC_ID"), "OIDC Client ID")
- rootCmd.Flags().StringVar(&clientSecret, "client-secret", os.Getenv("SAM_OIDC_SECRET"), "OIDC Client Secret")
rootCmd.Flags().StringVar(&biscuitHex, "key", os.Getenv("SAM_HUB_KEY"), "Hub Private Key (32-byte Hex)")
- 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().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/8080/quic-v1", "/ip4/0.0.0.0/tcp/8080"}, "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")
+ rootCmd.Flags().BoolVar(&insecureSkipTLSVerify, "insecure-skip-tls-verify", false, "Skip TLS verification for OIDC issuers")
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index bfdf02fa..244d835f 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -15,22 +15,37 @@
package main
import (
- "bufio"
"context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/hex"
"fmt"
"log"
+ "net"
"os"
+ "os/signal"
"strings"
+ "syscall"
+ "time"
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p/core/crypto"
+ "github.com/libp2p/go-msgio"
+ "github.com/multiformats/go-multiaddr"
"github.com/spf13/cobra"
+ "google.golang.org/protobuf/proto"
)
var (
hubAddr string
listenAddrs []string
- tokenFlag string
+
+ jwtFlag string
+ jwtPathFlag string
+ clientIDFlag string
+ clientSecretFlag string
+ tokenURLFlag string
+ hubPublicKeyFlag string
)
func main() {
@@ -39,19 +54,19 @@ func main() {
Short: "Sovereign Agent Mesh Node",
}
- // LOGIN COMMAND: For Headless Environments
- loginCmd := &cobra.Command{
- Use: "login",
- Short: "Establish sovereign identity with the Hub",
+ // RUN COMMAND: Start the Mesh
+ runCmd := &cobra.Command{
+ Use: "run",
+ Short: "Start the sovereign mesh node",
Run: func(cmd *cobra.Command, args []string) {
+ ctx := cmd.Context()
dataDir, err := GetDataDir()
if err != nil {
- log.Fatalf("Critical: %v", err)
+ log.Fatalf("Failed to get data dir: %v", err)
}
-
store, err := NewStore(dataDir)
if err != nil {
- log.Fatalf("Critical: %v", err)
+ log.Fatalf("Failed to open store: %v", err)
}
defer func() {
if err := store.Close(); err != nil {
@@ -59,59 +74,182 @@ func main() {
}
}()
- hubPubKey, hubAddrs, err := api.FetchConfig(context.Background(), hubAddr)
- if err != nil {
- log.Printf("Failed to fetch hub config from %s: %v", hubAddr, err)
- fmt.Println("\n💡 Tip: If you don't have a private hub running, you can try the public community mesh:")
- fmt.Printf(" sam-node login --hub https://community.sam-mesh.dev\n\n")
- log.Fatalf("Critical: Cannot proceed without a valid hub.")
- }
+ var hubPubKey ed25519.PublicKey
+ var hubAddrs []multiaddr.Multiaddr
- priv := getOrGenerateKey(store)
- // Temporary host to determine PeerID
- tempNode, err := NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store)
- if err != nil {
- log.Fatalf("Failed to initialize identity: %v", err)
+ storedPubKey, storedAddrs, _ := store.LoadHubConfig()
+ if len(storedPubKey) > 0 {
+ hubPubKey = storedPubKey
+ for _, addrStr := range storedAddrs {
+ ma, _ := multiaddr.NewMultiaddr(addrStr)
+ hubAddrs = append(hubAddrs, ma)
+ }
}
- defer func() {
- if err := tempNode.Host.Close(); err != nil {
- log.Printf("closing temporary node host: %v", err)
+
+ if hubPublicKeyFlag != "" {
+ pubBytes, err := hex.DecodeString(hubPublicKeyFlag)
+ if err != nil {
+ log.Fatalf("Invalid hub public key: %v", err)
}
- }()
+ hubPubKey = pubBytes
+ }
- loginURL := fmt.Sprintf("%s/login?peer_id=%s", hubAddr, tempNode.Host.ID())
+ var node *SamNode
- fmt.Println("--- Sovereign Identity Login ---")
- fmt.Printf("1. Please open the following URL in your browser:\n\n %s\n\n", loginURL)
- fmt.Println("2. Authenticate via your OIDC provider.")
- fmt.Println("3. Copy the 'Identity Biscuit' provided at the end of the flow.")
- fmt.Print("\nPaste your Identity Biscuit here: ")
+ var jwtStr string
- reader := bufio.NewReader(os.Stdin)
- token, err := reader.ReadString('\n')
- if err != nil {
- log.Fatalf("Failed to read input: %v", err)
+ if jwtFlag != "" {
+ jwtStr = jwtFlag
+ } else if jwtPathFlag != "" {
+ data, err := os.ReadFile(jwtPathFlag)
+ if err != nil {
+ log.Fatalf("Failed to read JWT file: %v", err)
+ }
+ jwtStr = strings.TrimSpace(string(data))
+ } else if tokenURLFlag != "" {
+ fmt.Println("Fetching JWT via OIDC Client Credentials...")
+ dummyNode := &SamNode{}
+ var err error
+ jwtStr, err = dummyNode.FetchJWT(context.Background(), tokenURLFlag, clientIDFlag, clientSecretFlag)
+ if err != nil {
+ log.Fatalf("Failed to fetch JWT: %v", err)
+ }
}
- token = strings.TrimSpace(token)
- if token == "" {
- log.Fatal("Error: No token provided.")
- }
+ if jwtStr == "" {
+ token, _ := store.LoadIdentity()
+ if token == "" {
+ log.Fatal("No JWT or stored identity found. Cannot authenticate.")
+ }
+ fmt.Println("Using stored identity.")
- if err := store.SaveIdentity(token); err != nil {
- log.Fatalf("Failed to save identity: %v", err)
+ if len(hubPubKey) == 0 {
+ log.Fatal("Hub public key not found in store and not provided. Cannot verify peers.")
+ }
+ priv := getOrGenerateKey(store)
+ node, err = NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store)
+ if err != nil {
+ log.Fatalf("Failed to start mesh node: %v", err)
+ }
+ } else {
+ var initHubAddrs []multiaddr.Multiaddr
+ ma, err := multiaddr.NewMultiaddr(hubAddr)
+ if err == nil {
+ initHubAddrs = []multiaddr.Multiaddr{ma}
+ } else {
+ // Try parsing as host:port
+ host, port, err := net.SplitHostPort(hubAddr)
+ if err == nil {
+ ip := net.ParseIP(host)
+ var maddr multiaddr.Multiaddr
+ if ip != nil {
+ maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s", host, port))
+ } else {
+ maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/dns4/%s/tcp/%s", host, port))
+ }
+ initHubAddrs = []multiaddr.Multiaddr{maddr}
+ } else {
+ if len(hubAddrs) > 0 {
+ initHubAddrs = hubAddrs
+ } else {
+ log.Fatalf("Invalid hub address and no stored config: %v", err)
+ }
+ }
+ }
+
+ priv := getOrGenerateKey(store)
+ node, err = NewSamNode(context.Background(), priv, nil, initHubAddrs, store)
+ if err != nil {
+ log.Fatalf("Failed to initialize node for enrollment: %v", err)
+ }
+
+ err = node.Enroll(context.Background(), jwtStr)
+ if err != nil {
+ log.Fatalf("Enrollment failed: %v", err)
+ }
+
+ storedPubKey, _, _ = store.LoadHubConfig()
+ hubPubKey = storedPubKey
+
+ node.HubPublicKey = hubPubKey
}
- fmt.Printf("\nSuccess! Identity stored for PeerID: %s\n", tempNode.Host.ID())
+ // Start renewal loop
+ go func() {
+ for {
+ var renewAfter = 50 * time.Minute // Default fallback
+
+ exp, err := node.Store.LoadIdentityExpiration()
+ if err == nil && exp > 0 {
+ expTime := time.Unix(exp, 0)
+ duration := time.Until(expTime)
+ // Renew 10 minutes before expiration if duration permits
+ if duration > 15*time.Minute {
+ renewAfter = duration - 10*time.Minute
+ } else if duration > 0 {
+ renewAfter = duration / 2 // half of remaining time
+ } else {
+ renewAfter = 1 * time.Minute // already expired or immediate
+ }
+ }
+
+ fmt.Printf("[Auth] Next renewal in %v\n", renewAfter)
+ timer := time.NewTimer(renewAfter)
+
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ return
+ case <-timer.C:
+ fmt.Println("Renewing enrollment...")
+ var newJWT string
+ if tokenURLFlag != "" {
+ var err error
+ newJWT, err = node.FetchJWT(ctx, tokenURLFlag, clientIDFlag, clientSecretFlag)
+ if err != nil {
+ fmt.Printf("Failed to fetch JWT for renewal: %v\n", err)
+ continue
+ }
+ } else if jwtPathFlag != "" {
+ data, err := os.ReadFile(jwtPathFlag)
+ if err != nil {
+ fmt.Printf("Failed to read JWT file for renewal: %v\n", err)
+ continue
+ }
+ newJWT = strings.TrimSpace(string(data))
+ } else {
+ fmt.Println("No credentials available for renewal.")
+ continue
+ }
+
+ if err := node.Enroll(ctx, newJWT); err != nil {
+ fmt.Printf("Renewal enrollment failed: %v\n", err)
+ } else {
+ fmt.Println("Enrollment renewed successfully.")
+ }
+ }
+ }
+ }()
+
+ node.Host.SetStreamHandler(AuthProtocolID, node.HandleAuthHandshake)
+
+ fmt.Printf("SAM Node Online.\nPeerID: %s\nListening on: %v\n", node.Host.ID(), listenAddrs)
+
+ // Block forever
+ <-ctx.Done()
+ fmt.Println("Shutting down...")
},
}
- // RUN COMMAND: Start the Mesh
- runCmd := &cobra.Command{
- Use: "run",
- Short: "Start the sovereign mesh node",
+ loginCmd := &cobra.Command{
+ Use: "login",
+ Short: "Log in to the mesh via interactive OIDC flow",
Run: func(cmd *cobra.Command, args []string) {
- dataDir, _ := GetDataDir()
+ ctx := cmd.Context()
+ dataDir, err := GetDataDir()
+ if err != nil {
+ log.Fatalf("Failed to get data dir: %v", err)
+ }
store, err := NewStore(dataDir)
if err != nil {
log.Fatalf("Failed to open store: %v", err)
@@ -122,49 +260,77 @@ func main() {
}
}()
- token := tokenFlag
- if token == "" {
- 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
+ if tokenURLFlag == "" {
+ log.Fatal("--token-url is required for login")
}
- hubPubKey, hubAddrs, err := api.FetchConfig(context.Background(), hubAddr)
+ dummyNode := &SamNode{Store: store}
+ jwtStr, err := dummyNode.InteractiveLogin(ctx, tokenURLFlag)
if err != nil {
- log.Printf("Failed to fetch hub config from %s: %v", hubAddr, err)
- fmt.Println("\n💡 Tip: If you don't have a private hub running, you can try the public community mesh:")
- fmt.Printf(" sam-node run --hub https://community.sam-mesh.dev\n\n")
- log.Fatalf("Critical: Cannot proceed without a valid hub.")
+ log.Fatalf("Failed to get token: %v", err)
+ }
+
+ // Connect to Hub and Enroll
+ var initHubAddrs []multiaddr.Multiaddr
+ ma, err := multiaddr.NewMultiaddr(hubAddr)
+ if err == nil {
+ initHubAddrs = []multiaddr.Multiaddr{ma}
+ } else {
+ host, port, err := net.SplitHostPort(hubAddr)
+ if err == nil {
+ ip := net.ParseIP(host)
+ var maddr multiaddr.Multiaddr
+ if ip != nil {
+ maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s", host, port))
+ } else {
+ maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/dns4/%s/tcp/%s", host, port))
+ }
+ initHubAddrs = []multiaddr.Multiaddr{maddr}
+ } else {
+ log.Fatalf("Invalid hub address: %v", err)
+ }
}
priv := getOrGenerateKey(store)
- node, err := NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store)
+ node, err := NewSamNode(context.Background(), priv, nil, initHubAddrs, store)
if err != nil {
- log.Fatalf("Failed to start mesh node: %v", err)
+ log.Fatalf("Failed to initialize node for enrollment: %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)
+ err = node.Enroll(context.Background(), jwtStr)
+ if err != nil {
+ log.Fatalf("Enrollment failed: %v", err)
+ }
- // Block forever
- select {}
+ fmt.Println("Login successful and identity stored.")
},
}
// Configure Flags
- runCmd.Flags().StringVar(&tokenFlag, "token", os.Getenv("SAM_NODE_TOKEN"), "Manual Identity Biscuit (overrides store)")
runCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/5001/quic-v1", "/ip4/0.0.0.0/tcp/5002"}, "libp2p Listen Addrs")
+ runCmd.Flags().StringVar(&jwtFlag, "jwt", "", "Pre-fetched JWT token")
+ runCmd.Flags().StringVar(&jwtPathFlag, "jwt-path", "", "Path to file containing JWT token")
+ runCmd.Flags().StringVar(&clientIDFlag, "client-id", os.Getenv("SAM_OIDC_ID"), "OIDC Client ID for M2M")
+ runCmd.Flags().StringVar(&clientSecretFlag, "client-secret", os.Getenv("SAM_OIDC_SECRET"), "OIDC Client Secret for M2M")
+ runCmd.Flags().StringVar(&hubPublicKeyFlag, "hub-public-key", "", "Hub Public Key (32-byte Hex)")
rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", "http://localhost:8080", "Hub URL")
+ rootCmd.PersistentFlags().StringVar(&tokenURLFlag, "token-url", "", "OIDC Token URL")
- rootCmd.AddCommand(loginCmd, runCmd)
- if err := rootCmd.Execute(); err != nil {
+ rootCmd.AddCommand(runCmd)
+ rootCmd.AddCommand(loginCmd)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ sigChan := make(chan os.Signal, 1)
+ signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
+ go func() {
+ <-sigChan
+ fmt.Println("\n[Signal] Received interrupt, shutting down...")
+ cancel()
+ }()
+
+ if err := rootCmd.ExecuteContext(ctx); err != nil {
os.Exit(1)
}
}
@@ -190,3 +356,65 @@ func getOrGenerateKey(s *Store) crypto.PrivKey {
}
return priv
}
+
+func (n *SamNode) Enroll(ctx context.Context, jwt string) error {
+ if n.HubPeerID == "" {
+ return fmt.Errorf("not connected to any hub")
+ }
+
+ s, err := n.Host.NewStream(ctx, n.HubPeerID, "/sam/enroll/1.0.0")
+ if err != nil {
+ return fmt.Errorf("failed to open enroll stream: %v", err)
+ }
+ defer func() { _ = s.Close() }()
+
+ req := &api.EnrollRequest{
+ Jwt: jwt,
+ PeerId: n.Host.ID().String(),
+ }
+ data, err := proto.Marshal(req)
+ if err != nil {
+ return fmt.Errorf("failed to marshal enroll request: %v", err)
+ }
+
+ writer := msgio.NewVarintWriter(s)
+ if err := writer.WriteMsg(data); err != nil {
+ return fmt.Errorf("failed to write enroll request: %v", err)
+ }
+
+ reader := msgio.NewVarintReaderSize(s, 1024*64)
+ respMsg, err := reader.ReadMsg()
+ if err != nil {
+ return fmt.Errorf("failed to read enroll response: %v", err)
+ }
+ defer reader.ReleaseMsg(respMsg)
+
+ var resp api.EnrollResponse
+ if err := proto.Unmarshal(respMsg, &resp); err != nil {
+ return fmt.Errorf("failed to unmarshal enroll response: %v", err)
+ }
+
+ if resp.ErrorMessage != "" {
+ return fmt.Errorf("enrollment failed: %s", resp.ErrorMessage)
+ }
+
+ if len(resp.BiscuitToken) == 0 {
+ return fmt.Errorf("received empty biscuit token")
+ }
+
+ tokenStr := base64.StdEncoding.EncodeToString(resp.BiscuitToken)
+ if err := n.Store.SaveIdentity(tokenStr); err != nil {
+ return fmt.Errorf("failed to save identity: %v", err)
+ }
+
+ if err := n.Store.SaveIdentityExpiration(resp.Expiration); err != nil {
+ return fmt.Errorf("failed to save identity expiration: %v", err)
+ }
+
+ if err := n.Store.SaveHubConfig(resp.HubPublicKey, resp.HubAddresses); err != nil {
+ return fmt.Errorf("failed to save hub config: %v", err)
+ }
+
+ fmt.Println("Successfully enrolled and stored identity and hub config.")
+ return nil
+}
diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.go
index 90ecaa21..6fc9a860 100644
--- a/cmd/sam-node/middleware.go
+++ b/cmd/sam-node/middleware.go
@@ -18,6 +18,9 @@ import (
"fmt"
"github.com/biscuit-auth/biscuit-go/v2"
+
+ "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/protocol"
@@ -33,8 +36,8 @@ type RequestContext struct {
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 {
+ // Allow the auth protocol and enroll protocol to proceed without checks
+ if pid == AuthProtocolID || pid == api.EnrollProtocolID {
handler(s)
return
}
@@ -79,6 +82,15 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext) error {
return err
}
+ // Verify that the token is bound to the connecting peer's ID
+ boundFact := biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "node",
+ IDs: []biscuit.Term{biscuit.String(req.PeerID.String())},
+ }}
+ if _, err := b.GetBlockID(boundFact); err != nil {
+ return fmt.Errorf("token is not bound to peer %s", req.PeerID)
+ }
+
// Inject the current action context (Standard Vocabulary)
authorizer.AddFact(biscuit.Fact{
Predicate: biscuit.Predicate{
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index bb808f78..5c8d1c55 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -22,7 +22,6 @@ import (
"github.com/biscuit-auth/biscuit-go/v2"
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
- "google.golang.org/protobuf/proto"
dht "github.com/libp2p/go-libp2p-kad-dht"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/crypto"
@@ -35,18 +34,18 @@ import (
"github.com/libp2p/go-libp2p/p2p/transport/tcp"
"github.com/libp2p/go-msgio"
"github.com/multiformats/go-multiaddr"
+ "google.golang.org/protobuf/proto"
)
const AuthProtocolID = protocol.ID("/sam/auth/1.0.0")
-
-
type SamNode struct {
Host host.Host
DHT *dht.IpfsDHT
PubSub *pubsub.PubSub
Store *Store
HubPublicKey ed25519.PublicKey
+ HubPeerID peer.ID
}
// NewSamNode creates a new Agent instance secured with the 4-layer pipeline.
@@ -81,11 +80,31 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.P
// 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)
+ addrInfo, err := peer.AddrInfoFromP2pAddr(addr)
+ if err != nil || addrInfo == nil {
+ // Try to connect without Peer ID in address
+ addrInfo = &peer.AddrInfo{
+ Addrs: []multiaddr.Multiaddr{addr},
}
+ fmt.Println("[Warning] Connecting to hub without Peer ID verification in address.")
+ }
+ if err := h.Connect(ctx, *addrInfo); err != nil {
+ fmt.Printf("Warning: Failed to bootstrap to hub %s: %v\n", addr, err)
+ } else {
+ if addrInfo.ID == "" {
+ // Discover Peer ID from connection
+ for _, c := range h.Network().Conns() {
+ if c.RemoteMultiaddr().Equal(addr) {
+ node.HubPeerID = c.RemotePeer()
+ fmt.Printf("Connected to hub (discovered PeerID): %s\n", node.HubPeerID)
+ break
+ }
+ }
+ } else {
+ node.HubPeerID = addrInfo.ID
+ fmt.Printf("Connected to hub: %s\n", addrInfo.ID)
+ }
+ break
}
}
@@ -107,7 +126,7 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.P
// 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")
+ topic, err := n.PubSub.Join(api.GossipEvents)
if err != nil {
return
}
@@ -204,3 +223,5 @@ func (n *SamNode) HandleAuthHandshake(s network.Stream) {
fmt.Printf("[AuthN] Successfully authenticated peer %s (%s)\n", remotePeer, identity.UserEmail)
}
+
+
diff --git a/cmd/sam-node/oidc.go b/cmd/sam-node/oidc.go
new file mode 100644
index 00000000..54a79476
--- /dev/null
+++ b/cmd/sam-node/oidc.go
@@ -0,0 +1,64 @@
+// 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 (
+ "bufio"
+ "context"
+ "fmt"
+ "os"
+ "strings"
+
+ "golang.org/x/oauth2/clientcredentials"
+)
+
+// FetchJWT fetches a JWT token using the Client Credentials flow.
+func (n *SamNode) FetchJWT(ctx context.Context, tokenURL, clientID, clientSecret string) (string, error) {
+ config := &clientcredentials.Config{
+ ClientID: clientID,
+ ClientSecret: clientSecret,
+ TokenURL: tokenURL,
+ }
+ token, err := config.Token(ctx)
+ if err != nil {
+ return "", err
+ }
+ return token.AccessToken, nil
+}
+
+// InteractiveLogin prompts the user to go to a URL and paste the token back.
+func (n *SamNode) InteractiveLogin(ctx context.Context, tokenURL string) (string, error) {
+ fmt.Println("------------------------------------------------------------")
+ fmt.Println("Device Authorization Flow")
+ fmt.Println("------------------------------------------------------------")
+ fmt.Printf("To authenticate, please go to the following URL in your browser:\n\n")
+ fmt.Printf(" %s\n\n", tokenURL)
+ fmt.Println("After successful login, copy the token and paste it below.")
+ fmt.Println("------------------------------------------------------------")
+ fmt.Print("Enter JWT Token: ")
+
+ reader := bufio.NewReader(os.Stdin)
+ token, err := reader.ReadString('\n')
+ if err != nil {
+ return "", fmt.Errorf("failed to read token: %v", err)
+ }
+
+ token = strings.TrimSpace(token)
+ if token == "" {
+ return "", fmt.Errorf("empty token provided")
+ }
+
+ return token, nil
+}
diff --git a/cmd/sam-node/store.go b/cmd/sam-node/store.go
index 694f0ccd..06606322 100644
--- a/cmd/sam-node/store.go
+++ b/cmd/sam-node/store.go
@@ -28,6 +28,7 @@ const (
bucketIdentity = "identity"
keyBiscuit = "identity_biscuit"
keyPrivKey = "node_private_key"
+ keyIdentityExp = "identity_expiration"
)
type Store struct {
@@ -89,6 +90,31 @@ func (s *Store) LoadIdentity() (string, error) {
return string(val), nil
}
+func (s *Store) SaveIdentityExpiration(exp int64) error {
+ return s.db.Update(func(tx *bbolt.Tx) error {
+ b := tx.Bucket([]byte(bucketIdentity))
+ return b.Put([]byte(keyIdentityExp), []byte(fmt.Sprintf("%d", exp)))
+ })
+}
+
+func (s *Store) LoadIdentityExpiration() (int64, error) {
+ var val []byte
+ _ = s.db.View(func(tx *bbolt.Tx) error {
+ b := tx.Bucket([]byte(bucketIdentity))
+ val = b.Get([]byte(keyIdentityExp))
+ return nil
+ })
+ if len(val) == 0 {
+ return 0, fmt.Errorf("no identity expiration found")
+ }
+ var exp int64
+ _, err := fmt.Sscanf(string(val), "%d", &exp)
+ if err != nil {
+ return 0, err
+ }
+ return exp, nil
+}
+
func (s *Store) SaveKey(key []byte) error {
return s.db.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(bucketIdentity))
@@ -106,6 +132,32 @@ func (s *Store) LoadKey() ([]byte, error) {
return val, nil
}
+func (s *Store) SaveHubConfig(pubKey []byte, addrs []string) error {
+ return s.db.Update(func(tx *bbolt.Tx) error {
+ b := tx.Bucket([]byte(bucketIdentity))
+ if err := b.Put([]byte("hub_public_key"), pubKey); err != nil {
+ return err
+ }
+ data, _ := json.Marshal(addrs)
+ return b.Put([]byte("hub_addresses"), data)
+ })
+}
+
+func (s *Store) LoadHubConfig() ([]byte, []string, error) {
+ var pubKey []byte
+ var addrs []string
+ err := s.db.View(func(tx *bbolt.Tx) error {
+ b := tx.Bucket([]byte(bucketIdentity))
+ pubKey = b.Get([]byte("hub_public_key"))
+ addrsBytes := b.Get([]byte("hub_addresses"))
+ if len(addrsBytes) > 0 {
+ return json.Unmarshal(addrsBytes, &addrs)
+ }
+ return nil
+ })
+ return pubKey, addrs, err
+}
+
func (s *Store) Close() error {
return s.db.Close()
}
diff --git a/docs/kubernetes-deployment.md b/docs/kubernetes-deployment.md
new file mode 100644
index 00000000..3f776878
--- /dev/null
+++ b/docs/kubernetes-deployment.md
@@ -0,0 +1,283 @@
+# Kubernetes Deployment and Local Testing Guide
+
+This guide explains how to deploy the `sam-hub` in a Kubernetes cluster and how to test it locally using `kind` and `cloud-provider-kind`.
+
+This guide supports using either **Google OIDC** or a **Mock OIDC Provider** for authentication. The mock provider is recommended for quick local testing as it does not require creating external credentials.
+
+---
+
+## 1. Mock OIDC Provider Manifests (Optional)
+
+The manifests for the mock OIDC provider are available in [mock-oidc.yaml](manifests/mock-oidc.yaml).
+
+[mock-oidc.yaml](manifests/mock-oidc.yaml ':include')
+
+---
+
+## 2. SAM Hub Manifests
+
+The manifests for the SAM Hub are available in [sam-hub.yaml](manifests/sam-hub.yaml).
+
+[sam-hub.yaml](manifests/sam-hub.yaml ':include')
+
+---
+
+## 3. Configuring Google OIDC (Optional)
+
+To use Google as the OIDC provider instead of the mock provider:
+
+1. **Create OAuth Client ID:** Create a OAuth 2.0 Client ID in the Google Cloud Console.
+2. **Set Redirect URI:** Set the authorized redirect URI to `http://<your-hub-public-ip>:8080/callback` (replace `<your-hub-public-ip>` with your actual public IP or domain).
+3. **Update Secret:** Update the `sam-hub-secret` in `sam-hub.yaml` with your Google credentials:
+ ```yaml
+ SAM_OIDC_ISSUER: "https://accounts.google.com"
+ SAM_OIDC_ID: "<your-client-id>.apps.googleusercontent.com"
+ SAM_OIDC_SECRET: "<your-client-secret>"
+ ```
+
+---
+
+## 4. Local Testing with Kind
+
+### Step 1: Create a Kind Cluster
+```bash
+kind create cluster --name sam-test
+```
+
+### Step 2: Run cloud-provider-kind
+Run it in a separate terminal:
+```bash
+cloud-provider-kind
+```
+
+### Step 3: Load Images into Kind
+```bash
+kind load docker-image sam-hub:local --name sam-test
+kind load docker-image sam-node:local --name sam-test
+```
+
+### Step 4: Apply Manifests
+
+If using the **Mock OIDC Provider**:
+```bash
+kubectl apply -f mock-oidc.yaml
+kubectl apply -f sam-hub.yaml
+```
+
+If using **Google OIDC**:
+```bash
+kubectl apply -f sam-hub.yaml
+```
+
+### Step 5: Get the External IP
+You can use the following command to extract the allocated IP into an environment variable:
+
+```bash
+HUB_IP=$(kubectl get svc sam-hub -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
+```
+
+---
+
+## 5. Connecting an Agent
+
+To connect a `sam-node` to the hub, you just need the hub's external IP and port.
+
+### Enrolling the Agent
+
+To connect a `sam-node` to the hub for the first time, you need to enroll it. The node needs to authenticate with the hub using a JWT token.
+
+If you are using the **Mock OIDC Provider**, the node can fetch the token automatically from the mock provider's token endpoint.
+
+1. **Get the Mock OIDC Service IP:**
+ ```bash
+ MOCK_IP=$(kubectl get svc mock-oidc -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
+ ```
+
+2. **Run the Node with Token URL:**
+ ```bash
+ sam-node run \
+ --hub "$HUB_IP:4002" \
+ --token-url "http://$MOCK_IP:18080/token"
+ ```
+
+If you are using **Google OIDC**, you must obtain a valid Google ID token for your user and pass it via the `--jwt` flag:
+```bash
+sam-node run \
+ --hub "$HUB_IP:4002" \
+ --jwt "<your-google-id-token>"
+```
+
+Once enrolled, identity is stored in the local database, and you can run without authentication flags:
+```bash
+sam-node run \
+ --hub "$HUB_IP:4002"
+```
+
+---
+
+## 6. Automating Node Deployment
+
+To automate the deployment of `sam-nodes` in Kubernetes and have them fetch the JWT token automatically, you can use a standard Kubernetes `Deployment` or `StatefulSet`.
+
+### Example Deployment
+
+Here is a sample manifest that uses the in-cluster DNS to fetch the token from the mock provider:
+
+```yaml
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: sam-node
+spec:
+ replicas: 3
+ selector:
+ matchLabels:
+ app: sam-node
+ template:
+ metadata:
+ labels:
+ app: sam-node
+ spec:
+ containers:
+ - name: sam-node
+ image: sam-node:local
+ command: ["sam-node", "run"]
+ args:
+ - "--hub"
+ - "sam-hub:4002"
+ - "--token-url"
+ - "http://mock-oidc:18080/token"
+ env:
+ - name: HOME
+ value: /data
+ volumeMounts:
+ - name: data-volume
+ mountPath: /data
+ volumes:
+ - name: data-volume
+ emptyDir: {}
+```
+
+### Supported Authentication Flows
+
+The SAM project supports three primary flows for acquiring a JWT token to enroll nodes, depending on the environment and security requirements:
+
+#### 1. Client Credentials Flow (Machine-to-Machine)
+* **Description:** Defined in OAuth 2.0 RFC 6749, section 4.4. An application exchanges its application credentials (such as Client ID and Client Secret) for an access token.
+* **Use Case:** For unattended services or deployments connecting to a production OIDC provider.
+* **How to use:** Pass the `--token-url`, `--client-id`, and `--client-secret` flags to `sam-node run`.
+* **Example:**
+```bash
+sam-node run \
+ --hub "hub.example.com:4002" \
+ --token-url "https://oauth2.googleapis.com/token" \
+ --client-id "$SAM_OIDC_ID" \
+ --client-secret "$SAM_OIDC_SECRET"
+```
+
+#### 2. Device Authorization Flow (Human Intervention)
+* **Description:** For input-constrained devices or CLI tools used by humans. The device asks the user to go to a link on their computer or smartphone to authorize the device, avoiding the need to enter complex passwords in the CLI.
+* **Use Case:** When a human operator is enrolling a node manually.
+* **How to use:** The user obtains a token via the OIDC provider's device flow (or browser flow) and passes it directly via the `--jwt` flag.
+* **Example:**
+```bash
+sam-node run \
+ --hub "hub.example.com:4002" \
+ --jwt "eyJhbGciOiJSUzI1NiIs..."
+```
+
+#### 3. Workload Identity Federation (Secretless Kubernetes)
+* **Description:** The current best practice in Kubernetes. It removes the need for static secrets entirely. The machine proves its identity based on where it is running by presenting a ServiceAccount token (a signed JWT issued by the K8s API).
+* **Use Case:** Production Kubernetes deployments.
+* **How it works:** The Pod has a ServiceAccount token mounted. The Pod presents this token to the `sam-hub`. The hub verifies it by calling back to the Kubernetes OIDC discovery endpoint.
+* **How to use:** Pass the path to the mounted ServiceAccount token to the `--jwt-path` flag.
+* **Example:**
+```bash
+sam-node run \
+ --hub "hub.example.com:4002" \
+ --jwt-path "/var/run/secrets/kubernetes.io/serviceaccount/token"
+```
+> [!NOTE]
+> The `sam-hub` must be configured to trust the Kubernetes API server as an OIDC issuer for this flow to work.
+
+---
+
+## 7. Configuring Workload Identity in Kubernetes
+
+Workload Identity allows `sam-node` pods to authenticate with the `sam-hub` using their Kubernetes ServiceAccount token, removing the need for static credentials.
+
+Here are the exact steps to configure this:
+
+### Step 1: Ensure OIDC Discovery is enabled on your Cluster
+Most managed Kubernetes services (GKE, EKS, AKS) and local tools like `kind` support ServiceAccount Issuer Discovery.
+In `kind`, this is enabled by default. You can find the issuer URL by running:
+```bash
+kubectl get --raw /.well-known/openid-configuration | jq -r .issuer
+```
+(Or check your cloud provider's documentation for the public issuer URL).
+
+### Step 2: Configure the Hub to trust the Kubernetes Issuer
+Update the `sam-hub` deployment to include the Kubernetes issuer URL in the `--issuer` flag.
+
+If you are using `kind`, the issuer URL is usually `https://kubernetes.default.svc.cluster.local` (internal) or the external URL mapped by kind.
+
+Update `sam-hub.yaml`:
+```yaml
+ spec:
+ containers:
+ - name: sam-hub
+ args:
+ - "--issuer"
+ - "https://accounts.google.com,https://kubernetes.default.svc.cluster.local"
+```
+
+### Step 3: Create a ServiceAccount for the Node
+Create a ServiceAccount that the `sam-node` pods will use.
+```yaml
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: sam-node-sa
+```
+
+### Step 4: Deploy the Node with a Projected Volume
+Deploy the `sam-node` and configure it to use the ServiceAccount. We use a **Projected Volume** to request a token with the specific audience expected by the hub (e.g., the mesh name or a specific client ID).
+
+```yaml
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: sam-node
+spec:
+ replicas: 3
+ 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"
+ - "sam-hub:4002"
+ - "--jwt-path"
+ - "/var/run/secrets/tokens/sam-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-hub-audience" # Match this with what the hub expects
+```
diff --git a/docs/manifests/mock-oidc.yaml b/docs/manifests/mock-oidc.yaml
new file mode 100644
index 00000000..fb0b9ac8
--- /dev/null
+++ b/docs/manifests/mock-oidc.yaml
@@ -0,0 +1,146 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: mock-oidc-script
+data:
+ server.py: |
+ import json
+ import time
+ import jwt
+ from http.server import BaseHTTPRequestHandler, HTTPServer
+
+ PRIVATE_KEY = """-----BEGIN PRIVATE KEY-----
+ MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDGtPD85uaT342Y
+ yqGAiWQ6OV2BxvpXQRMzsb7VpdLa146xf5/1b9lIR4dFvhvGUqnyzFLV0EdIzTqo
+ xyKGHbQY68DIUjH3iwt6rzU0Vkw/3g/R/TBEmGwdqNDLCBItsLOnF4HfsxAWtjaU
+ R96S4oXaCUcXOD/3yHs0ha4tu8YgwGwMHa/CQRgcTX5FshR6uHow5G7NiOVYUcAP
+ c1HXmwmf0FeSY9r0QudmIjkJSeIH1I/BufpEqbcjrSyjYd4eldbhjlCvuIR93Sva
+ 8jZBzdCW+xxyU+8dz2tEgRjm9G7CpoCpAwhcEQQW7XRUb8DP9+bid9VfT+3C1Te6
+ u8eowndXAgMBAAECggEAGF6ZjZKt5aXNolb7jp2K/r8JUkC6dBgFiFn8uwwOu4sj
+ M26hCgNRJRWsp+eEVYLO1/mqERHtpCaTUp61g7hB3aqQJqE6Ao95dW7megg5ar3L
+ t+ey0z7UR6DsFnJjdFoO9meiJHK7/uUS9YWI7P++BbsMjnL2GWfrgEoCzhYQ2vQ2
+ 8t9lGmJfaEeicTcPs4/Jtz9nX+KQ1CqKb5uHP6IyVQjV/nIjWh1WZJV5wsmLM1ZF
+ YT7NPEhXkgH5JjwzEI3QR9ZMs4FUgbduImmS280YCMNMUNVsSBbbV/1hh7Sxlp6B
+ bRaK12sPPRwW0sHw3odZKjGzKIFlu9I5TieNJ5w2AQKBgQDy3cxDXxj+bcSYuWDp
+ p4EVNTwg+IY9eT0x1x+tWXaOjGTscD4GrdUYhspWuoUn5NxZ0ub0apiTMQfoM9a0
+ Qr3CKngkL5JTi6OwdnEaTPNvQiSJdgXXzYdCXeucK5soeHCZTPAb3bV27LtpxyMI
+ QSx9rnKcSyoRSavLWP0hr8QNVwKBgQDRc84q3I5tZX/whoUmeTj6aNJoIa1KAACM
+ 0Fnr9ecjLS50kXIiTSCiNE8pcBcsSxYgo+PG5W9oQaZcdd7r2nJOqaizpjnHbF+9
+ S/Ts9vj+dJlCUcjjROghzYrI5mdb8Dq2Ngd93IcBt5H+W6bm8wWUgLy0IJmJDKHE
+ Z7SS22imAQKBgAETHi5GI3QsxCvw1g7yoM2ZOLTkpKNs/+pSi19XAAFNebzaGkwp
+ RMIhBpAvrxsoFhmHp2H5fsdX9jL+17pgeTp8uZ9fXoRkH8tOGt4E7SbW4haBoTD9
+ RdXzWHGOd9dMASOMhZt59a2bCpFDQlJtB2de+D7czkjZTJtPv38AqhttAoGAE8X2
+ Aa/etk8tu9xHN7GcAm/g5TnArUrAwops4szNLFH4n8KXXsufOBDuJEBTv7e6+Avg
+ 1gcU9Ge2N+ZczDFMN0bnCUa5D62YgDtqfPB34zXIvi0QZPw9WeuYnYy610AfmtIQ
+ 9P3btPrKipPGdukcbr+UkQC+3eRWZT9RGcgi4gECgYApA3J0jlD+JFtYKFOuJWxS
+ aFEhYPe2dVW78bJoMMhxPtD9hWw/zWVUdyhdXMHoP8/igwNiUqXaYacPbxTFu5ft
+ w/+UummqB6KpqPFnpbqP826Udr4SEHH0iwvs4MDqSlXcOC5CXbIoMLB/zMjE+u/J
+ IqNKTt9jbR4zISCpyOCsQw==
+ -----END PRIVATE KEY-----"""
+
+ JWKS = {
+ "keys": [
+ {
+ "kty": "RSA",
+ "alg": "RS256",
+ "use": "sig",
+ "kid": "test-key-id",
+ "n": "xrTw_Obmk9-NmMqhgIlkOjldgcb6V0ETM7G-1aXS2teOsX-f9W_ZSEeHRb4bxlKp8sxS1dBHSM06qMcihh20GOvAyFIx94sLeq81NFZMP94P0f0wRJhsHajQywgSLbCzpxeB37MQFrY2lEfekuKF2glHFzg_98h7NIWuLbvGIMBsDB2vwkEYHE1-RbIUerh6MORuzYjlWFHAD3NR15sJn9BXkmPa9ELnZiI5CUniB9SPwbn6RKm3I60so2HeHpXW4Y5Qr7iEfd0r2vI2Qc3QlvscclPvHc9rRIEY5vRuwqaAqQMIXBEEFu10VG_Az_fm4nfVX0_twtU3urvHqMJ3Vw",
+ "e": "AQAB"
+ }
+ ]
+ }
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.path == '/.well-known/openid-configuration':
+ body = {
+ 'issuer': 'http://mock-oidc:18080',
+ 'authorization_endpoint': 'http://mock-oidc:18080/auth',
+ 'token_endpoint': 'http://mock-oidc:18080/token',
+ 'jwks_uri': 'http://mock-oidc:18080/keys'
+ }
+ data = json.dumps(body).encode('utf-8')
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ if self.path == '/keys':
+ data = json.dumps(JWKS).encode('utf-8')
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(b'ok')
+
+ def do_POST(self):
+ if self.path == '/token':
+ payload = {
+ 'iss': 'http://mock-oidc:18080',
+ 'aud': 'sam-e2e',
+ 'sub': 'test-user',
+ 'exp': int(time.time()) + 3600,
+ 'roles': ['admin', 'user']
+ }
+ token = jwt.encode(payload, PRIVATE_KEY, algorithm='RS256', headers={'kid': 'test-key-id'})
+ body = {
+ 'access_token': token,
+ 'token_type': 'Bearer',
+ 'expires_in': 3600
+ }
+ data = json.dumps(body).encode('utf-8')
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ self.send_response(404)
+ self.end_headers()
+
+ print("Mock OIDC server ready", flush=True)
+ HTTPServer(('0.0.0.0', 18080), Handler).serve_forever()
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: mock-oidc
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: mock-oidc
+ template:
+ metadata:
+ labels:
+ app: mock-oidc
+ spec:
+ containers:
+ - name: mock-oidc
+ image: python:3.12
+ command: ["sh", "-c", "pip install pyjwt cryptography && python /app/server.py"]
+ volumeMounts:
+ - name: script-volume
+ mountPath: /app
+ volumes:
+ - name: script-volume
+ configMap:
+ name: mock-oidc-script
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: mock-oidc
+spec:
+ type: LoadBalancer
+ ports:
+ - port: 18080
+ targetPort: 18080
+ selector:
+ app: mock-oidc
diff --git a/docs/manifests/sam-hub.yaml b/docs/manifests/sam-hub.yaml
new file mode 100644
index 00000000..aac50609
--- /dev/null
+++ b/docs/manifests/sam-hub.yaml
@@ -0,0 +1,73 @@
+apiVersion: v1
+kind: Secret
+metadata:
+ name: sam-hub-secret
+type: Opaque
+stringData:
+ SAM_HUB_KEY: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # 32-byte hex
+ SAM_OIDC_ISSUER: "http://mock-oidc:18080"
+ SAM_OIDC_ID: "sam-e2e"
+ SAM_OIDC_SECRET: "sam-e2e-secret"
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: sam-hub
+ labels:
+ app: 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
+ imagePullPolicy: IfNotPresent
+ args:
+ - "--mesh=public-mesh"
+ - "--issuer=$(SAM_OIDC_ISSUER)"
+ ports:
+ - containerPort: 8080
+ name: public-port
+ env:
+ - name: SAM_HUB_KEY
+ valueFrom:
+ secretKeyRef:
+ name: sam-hub-secret
+ key: SAM_HUB_KEY
+ - name: SAM_OIDC_ISSUER
+ valueFrom:
+ secretKeyRef:
+ name: sam-hub-secret
+ key: SAM_OIDC_ISSUER
+ - name: SAM_OIDC_ID
+ valueFrom:
+ secretKeyRef:
+ name: sam-hub-secret
+ key: SAM_OIDC_ID
+ - name: SAM_OIDC_SECRET
+ valueFrom:
+ secretKeyRef:
+ name: sam-hub-secret
+ key: SAM_OIDC_SECRET
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: sam-hub
+spec:
+ type: LoadBalancer
+ selector:
+ app: sam-hub
+ ports:
+ - protocol: TCP
+ port: 8080
+ targetPort: 8080
+ name: public-port
+
diff --git a/go.mod b/go.mod
index ed24a9b1..bd199a1b 100644
--- a/go.mod
+++ b/go.mod
@@ -5,8 +5,8 @@ go 1.25.7
require (
github.com/biscuit-auth/biscuit-go/v2 v2.2.0
github.com/coreos/go-oidc/v3 v3.18.0
+ github.com/golang-jwt/jwt/v5 v5.3.1
github.com/libp2p/go-libp2p v0.48.0
- github.com/libp2p/go-libp2p-http v0.5.0
github.com/libp2p/go-libp2p-kad-dht v0.39.0
github.com/libp2p/go-libp2p-pubsub v0.15.0
github.com/libp2p/go-msgio v0.3.0
@@ -14,6 +14,7 @@ require (
github.com/spf13/cobra v1.10.2
go.etcd.io/bbolt v1.4.3
golang.org/x/oauth2 v0.36.0
+ google.golang.org/protobuf v1.36.11
)
require (
@@ -51,7 +52,6 @@ require (
github.com/libp2p/go-cidranger v1.1.0 // indirect
github.com/libp2p/go-flow-metrics v0.3.0 // indirect
github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect
- github.com/libp2p/go-libp2p-gostream v0.6.0 // indirect
github.com/libp2p/go-libp2p-kbucket v0.8.0 // indirect
github.com/libp2p/go-libp2p-record v0.3.1 // indirect
github.com/libp2p/go-libp2p-routing-helpers v0.7.5 // indirect
@@ -124,6 +124,5 @@ require (
golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.44.0 // indirect
gonum.org/v1/gonum v0.17.0 // indirect
- google.golang.org/protobuf v1.36.11 // indirect
lukechampine.com/blake3 v1.4.1 // indirect
)
diff --git a/go.sum b/go.sum
index 9f0aa689..52b6e569 100644
--- a/go.sum
+++ b/go.sum
@@ -117,6 +117,8 @@ github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaL
github.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=
@@ -272,10 +274,6 @@ github.com/libp2p/go-libp2p v0.48.0 h1:h2BrLAgrj7X8bEN05K7qmrjpNHYA+6tnsGRdprjTn
github.com/libp2p/go-libp2p v0.48.0/go.mod h1:Q1fBZNdmC2Hf82husCTfkKJVfHm2we5zk+NWmOGEmWk=
github.com/libp2p/go-libp2p-asn-util v0.4.1 h1:xqL7++IKD9TBFMgnLPZR6/6iYhawHKHl950SO9L6n94=
github.com/libp2p/go-libp2p-asn-util v0.4.1/go.mod h1:d/NI6XZ9qxw67b4e+NgpQexCIiFYJjErASrYW4PFDN8=
-github.com/libp2p/go-libp2p-gostream v0.6.0 h1:QfAiWeQRce6pqnYfmIVWJFXNdDyfiR/qkCnjyaZUPYU=
-github.com/libp2p/go-libp2p-gostream v0.6.0/go.mod h1:Nywu0gYZwfj7Jc91PQvbGU8dIpqbQQkjWgDuOrFaRdA=
-github.com/libp2p/go-libp2p-http v0.5.0 h1:+x0AbLaUuLBArHubbbNRTsgWz0RjNTy6DJLOxQ3/QBc=
-github.com/libp2p/go-libp2p-http v0.5.0/go.mod h1:glh87nZ35XCQyFsdzZps6+F4HYI6DctVFY5u1fehwSg=
github.com/libp2p/go-libp2p-kad-dht v0.39.0 h1:mww38eBYiUvdsu+Xl/GLlBC0Aa8M+5HAwvafkFOygAM=
github.com/libp2p/go-libp2p-kad-dht v0.39.0/go.mod h1:Po2JugFEkDq9Vig/JXtc153ntOi0q58o4j7IuITCOVs=
github.com/libp2p/go-libp2p-kbucket v0.8.0 h1:QAK7RzKJpYe+EuSEATAaaHYMYLkPDGC18m9jxPLnU8s=
diff --git a/tests/e2e/auth_flows.bats b/tests/e2e/auth_flows.bats
new file mode 100644
index 00000000..42d4b2a3
--- /dev/null
+++ b/tests/e2e/auth_flows.bats
@@ -0,0 +1,120 @@
+#!/usr/bin/env bats
+
+load "lib/container_mesh.bash"
+
+setup() {
+ if ! mesh_require_docker; then
+ skip "docker not available or daemon not running"
+ fi
+
+ if [[ ! -x "./bin/sam-node" || ! -x "./bin/sam-hub" ]]; then
+ skip "missing binaries; run: make build"
+ fi
+
+ mesh_setup_env
+}
+
+teardown() {
+ mesh_cleanup_env
+}
+
+@test "Authentication Flow 1: Client Credentials Flow" {
+ run mesh_start_mock_oidc
+ [[ "$status" -eq 0 ]]
+
+ run mesh_start_hub
+ [[ "$status" -eq 0 ]]
+
+ # mesh_start_node uses --token-url by default, which implements Client Credentials flow
+ run mesh_start_node 1
+ [[ "$status" -eq 0 ]]
+
+ run mesh_assert_container_running "${MESH_PREFIX}-node-1"
+ [[ "$status" -eq 0 ]]
+}
+
+@test "Authentication Flow 2: Device Authorization Flow (Interactive)" {
+ run mesh_start_mock_oidc
+ [[ "$status" -eq 0 ]]
+
+ run mesh_start_hub
+ [[ "$status" -eq 0 ]]
+
+ # 1. Get a token from mock provider using Python helper
+ local token
+ token=$(docker run --rm --network "${MESH_NETWORK}" python:3.12 python3 -c "import urllib.request; import json; req = urllib.request.Request('http://mock-oidc:18080/token', data=b''); resp = urllib.request.urlopen(req); print(json.loads(resp.read().decode())['access_token'])")
+
+ [[ -n "${token}" ]]
+
+ # 2. Run sam-node login and pipe the token
+ local node_name="${MESH_PREFIX}-node-login"
+ local hub_peer_id
+ hub_peer_id=$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")
+
+ local data_vol="${MESH_PREFIX}-data"
+ docker volume create "${data_vol}"
+
+ # We run it interactively to pipe stdin
+ echo "${token}" | docker run --rm \
+ --network "${MESH_NETWORK}" \
+ -v "${data_vol}:/root/.config/sam-mesh" \
+ -i \
+ "sam-node:local" \
+ login --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" --token-url "http://mock-oidc:18080/token"
+
+ # Now run the node with the stored identity
+ docker run -d \
+ --name "${node_name}" \
+ --network "${MESH_NETWORK}" \
+ -v "${data_vol}:/root/.config/sam-mesh" \
+ "sam-node:local" \
+ run \
+ --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}"
+
+ mesh_wait_for_log "${node_name}" "Using stored identity." 20
+
+ # Cleanup volume
+ docker volume rm "${data_vol}" >/dev/null 2>&1 || true
+}
+
+@test "Authentication Flow 3: Workload Identity Federation (JWT Path)" {
+ run mesh_start_mock_oidc
+ [[ "$status" -eq 0 ]]
+
+ run mesh_start_hub
+ [[ "$status" -eq 0 ]]
+
+ # 1. Get a token from mock provider
+ local token
+ token=$(docker run --rm --network "${MESH_NETWORK}" python:3.12 python3 -c "import urllib.request; import json; req = urllib.request.Request('http://mock-oidc:18080/token', data=b''); resp = urllib.request.urlopen(req); print(json.loads(resp.read().decode())['access_token'])")
+
+ [[ -n "${token}" ]]
+
+ # 2. Save it to a file in a volume
+ local token_vol="${MESH_PREFIX}-token"
+ docker volume create "${token_vol}"
+
+ docker run --rm \
+ -v "${token_vol}:/tokens" \
+ busybox \
+ sh -c "echo \"${token}\" > /tokens/sa-token"
+
+ # 3. Run sam-node with --jwt-path
+ local node_name="${MESH_PREFIX}-node-wi"
+ local hub_peer_id
+ hub_peer_id=$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")
+
+ docker run -d \
+ --name "${node_name}" \
+ --network "${MESH_NETWORK}" \
+ -v "${token_vol}:/var/run/secrets/tokens" \
+ "sam-node:local" \
+ run \
+ --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" \
+ --jwt-path "/var/run/secrets/tokens/sa-token"
+
+ mesh_wait_for_log "${node_name}" "SAM Node Online" 20
+
+ # Cleanup volume
+ docker volume rm "${token_vol}" >/dev/null 2>&1 || true
+}
diff --git a/tests/e2e/gen_db.go b/tests/e2e/gen_db.go
new file mode 100644
index 00000000..06c67081
--- /dev/null
+++ b/tests/e2e/gen_db.go
@@ -0,0 +1,66 @@
+// 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 (
+ "encoding/json"
+ "log"
+ "os"
+ "path/filepath"
+
+ "go.etcd.io/bbolt"
+)
+
+func main() {
+ if len(os.Args) < 2 {
+ log.Fatal("Usage: gen_db <db_path>")
+ }
+ dbPath := os.Args[1]
+
+ err := os.MkdirAll(filepath.Dir(dbPath), 0700)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ db, err := bbolt.Open(dbPath, 0600, nil)
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer func() { _ = db.Close() }()
+
+ err = db.Update(func(tx *bbolt.Tx) error {
+ b, err := tx.CreateBucketIfNotExists([]byte("identity"))
+ if err != nil {
+ return err
+ }
+ // The following constants are mock values used for testing.
+ // 'mock-biscuit-token' is a dummy token string.
+ // The hub public key is a dummy 32-byte hex string (all zeros).
+ if err := b.Put([]byte("identity_biscuit"), []byte("mock-biscuit-token")); err != nil {
+ return err
+ }
+ if err := b.Put([]byte("hub_public_key"), []byte("0000000000000000000000000000000000000000000000000000000000000000")); err != nil {
+ return err
+ }
+ addrsData, _ := json.Marshal([]string{"/ip4/127.0.0.1/tcp/4002/p2p/QmYyQSo1sn1GjUuQwca9AdvV8Zeyvmxrww8dDnewPrfJs9"})
+ if err := b.Put([]byte("hub_addresses"), addrsData); err != nil {
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/tests/e2e/kind_wi.bats b/tests/e2e/kind_wi.bats
new file mode 100644
index 00000000..7dfa3d51
--- /dev/null
+++ b/tests/e2e/kind_wi.bats
@@ -0,0 +1,210 @@
+#!/usr/bin/env bats
+
+setup() {
+ if ! command -v kind >/dev/null 2>&1; then
+ skip "kind not available"
+ fi
+ if ! command -v kubectl >/dev/null 2>&1; then
+ skip "kubectl not available"
+ fi
+ if ! command -v jq >/dev/null 2>&1; then
+ skip "jq not available"
+ fi
+
+ # We use a unique cluster name to avoid conflicts
+ CLUSTER_NAME="sam-wi-test-$RANDOM"
+
+ # Create Kind cluster
+ kind create cluster --name "${CLUSTER_NAME}"
+
+ # Build images
+ make docker-build
+
+ # 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-hub-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"
+ - "--listen"
+ - "/ip4/0.0.0.0/tcp/4002"
+ - "--insecure-skip-tls-verify"
+ envFrom:
+ - configMapRef:
+ name: sam-hub-config
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: sam-hub
+spec:
+ type: ClusterIP
+ ports:
+ - port: 4002
+ targetPort: 4002
+ 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 "PeerID:" | awk '{print $2}' | tr -d '\r')
+
+ [[ -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"
+ - "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}"
+ - "--jwt-path"
+ - "/var/run/secrets/tokens/sam-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-hub-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/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index f47b70d2..9c059642 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -96,8 +96,58 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
read -r -d '' cmd <<'EOF' || true
python3 - <<'PY'
import json
+import time
+import jwt
from http.server import BaseHTTPRequestHandler, HTTPServer
+# The following RSA private key and JWKS were generated for testing purposes.
+# They are used by the mock OIDC server to sign JWTs.
+# To generate a new key pair:
+# openssl genpkey -algorithm RSA -out private.pem -pkeyopt rsa_keygen_bits:2048
+# openssl rsa -pubout -in private.pem -out public.pem
+# Parameters: RSA 2048 bits, Algorithm: RS256, kid: test-key-id
+PRIVATE_KEY = """-----BEGIN PRIVATE KEY-----
+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDGtPD85uaT342Y
+yqGAiWQ6OV2BxvpXQRMzsb7VpdLa146xf5/1b9lIR4dFvhvGUqnyzFLV0EdIzTqo
+xyKGHbQY68DIUjH3iwt6rzU0Vkw/3g/R/TBEmGwdqNDLCBItsLOnF4HfsxAWtjaU
+R96S4oXaCUcXOD/3yHs0ha4tu8YgwGwMHa/CQRgcTX5FshR6uHow5G7NiOVYUcAP
+c1HXmwmf0FeSY9r0QudmIjkJSeIH1I/BufpEqbcjrSyjYd4eldbhjlCvuIR93Sva
+8jZBzdCW+xxyU+8dz2tEgRjm9G7CpoCpAwhcEQQW7XRUb8DP9+bid9VfT+3C1Te6
+u8eowndXAgMBAAECggEAGF6ZjZKt5aXNolb7jp2K/r8JUkC6dBgFiFn8uwwOu4sj
+M26hCgNRJRWsp+eEVYLO1/mqERHtpCaTUp61g7hB3aqQJqE6Ao95dW7megg5ar3L
+t+ey0z7UR6DsFnJjdFoO9meiJHK7/uUS9YWI7P++BbsMjnL2GWfrgEoCzhYQ2vQ2
+8t9lGmJfaEeicTcPs4/Jtz9nX+KQ1CqKb5uHP6IyVQjV/nIjWh1WZJV5wsmLM1ZF
+YT7NPEhXkgH5JjwzEI3QR9ZMs4FUgbduImmS280YCMNMUNVsSBbbV/1hh7Sxlp6B
+bRaK12sPPRwW0sHw3odZKjGzKIFlu9I5TieNJ5w2AQKBgQDy3cxDXxj+bcSYuWDp
+p4EVNTwg+IY9eT0x1x+tWXaOjGTscD4GrdUYhspWuoUn5NxZ0ub0apiTMQfoM9a0
+Qr3CKngkL5JTi6OwdnEaTPNvQiSJdgXXzYdCXeucK5soeHCZTPAb3bV27LtpxyMI
+QSx9rnKcSyoRSavLWP0hr8QNVwKBgQDRc84q3I5tZX/whoUmeTj6aNJoIa1KAACM
+0Fnr9ecjLS50kXIiTSCiNE8pcBcsSxYgo+PG5W9oQaZcdd7r2nJOqaizpjnHbF+9
+S/Ts9vj+dJlCUcjjROghzYrI5mdb8Dq2Ngd93IcBt5H+W6bm8wWUgLy0IJmJDKHE
+Z7SS22imAQKBgAETHi5GI3QsxCvw1g7yoM2ZOLTkpKNs/+pSi19XAAFNebzaGkwp
+RMIhBpAvrxsoFhmHp2H5fsdX9jL+17pgeTp8uZ9fXoRkH8tOGt4E7SbW4haBoTD9
+RdXzWHGOd9dMASOMhZt59a2bCpFDQlJtB2de+D7czkjZTJtPv38AqhttAoGAE8X2
+Aa/etk8tu9xHN7GcAm/g5TnArUrAwops4szNLFH4n8KXXsufOBDuJEBTv7e6+Avg
+1gcU9Ge2N+ZczDFMN0bnCUa5D62YgDtqfPB34zXIvi0QZPw9WeuYnYy610AfmtIQ
+9P3btPrKipPGdukcbr+UkQC+3eRWZT9RGcgi4gECgYApA3J0jlD+JFtYKFOuJWxS
+aFEhYPe2dVW78bJoMMhxPtD9hWw/zWVUdyhdXMHoP8/igwNiUqXaYacPbxTFu5ft
+w/+UummqB6KpqPFnpbqP826Udr4SEHH0iwvs4MDqSlXcOC5CXbIoMLB/zMjE+u/J
+IqNKTt9jbR4zISCpyOCsQw==
+-----END PRIVATE KEY-----"""
+
+JWKS = {
+ "keys": [
+ {
+ "kty": "RSA",
+ "alg": "RS256",
+ "use": "sig",
+ "kid": "test-key-id",
+ "n": "xrTw_Obmk9-NmMqhgIlkOjldgcb6V0ETM7G-1aXS2teOsX-f9W_ZSEeHRb4bxlKp8sxS1dBHSM06qMcihh20GOvAyFIx94sLeq81NFZMP94P0f0wRJhsHajQywgSLbCzpxeB37MQFrY2lEfekuKF2glHFzg_98h7NIWuLbvGIMBsDB2vwkEYHE1-RbIUerh6MORuzYjlWFHAD3NR15sJn9BXkmPa9ELnZiI5CUniB9SPwbn6RKm3I60so2HeHpXW4Y5Qr7iEfd0r2vI2Qc3QlvscclPvHc9rRIEY5vRuwqaAqQMIXBEEFu10VG_Az_fm4nfVX0_twtU3urvHqMJ3Vw",
+ "e": "AQAB"
+ }
+ ]
+}
+
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/.well-known/openid-configuration':
@@ -115,7 +165,7 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(data)
return
if self.path == '/keys':
- data = b'{"keys":[]}'
+ data = json.dumps(JWKS).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(data)))
@@ -126,6 +176,32 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(b'ok')
+ def do_POST(self):
+ if self.path == '/token':
+ payload = {
+ 'iss': 'http://mock-oidc:18080',
+ 'aud': 'sam-e2e',
+ 'sub': 'test-user',
+ 'exp': int(time.time()) + 3600,
+ 'roles': ['admin', 'user']
+ }
+ token = jwt.encode(payload, PRIVATE_KEY, algorithm='RS256', headers={'kid': 'test-key-id'})
+ body = {
+ 'access_token': token,
+ 'token_type': 'Bearer',
+ 'expires_in': 3600
+ }
+ data = json.dumps(body).encode('utf-8')
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ self.send_response(404)
+ self.end_headers()
+
+print("Mock OIDC server ready", flush=True)
HTTPServer(('0.0.0.0', 18080), Handler).serve_forever()
PY
EOF
@@ -134,11 +210,11 @@ EOF
--name "${name}" \
--network "${MESH_NETWORK}" \
--network-alias mock-oidc \
- python:3.12-alpine \
- sh -lc "${cmd}" >/dev/null
+ python:3.12 \
+ sh -lc "pip install pyjwt cryptography && ${cmd}" >/dev/null
MESH_CONTAINERS+=("${name}")
- mesh_wait_for_log "${name}" "" 3 || true
+ mesh_wait_for_log "${name}" "Mock OIDC server ready" 30
}
mesh_start_hub() {
@@ -153,29 +229,38 @@ EOF
"sam-hub:local" \
--issuer "http://mock-oidc:18080" \
--client-id "sam-e2e" \
- --client-secret "sam-e2e-secret" \
--key "${key}" \
--listen "/ip4/0.0.0.0/udp/4001/quic-v1" \
--listen "/ip4/0.0.0.0/tcp/4002" \
- --mesh "e2e-mesh" \
- --public-url "http://sam-hub:8080" >/dev/null
+ --mesh "e2e-mesh" >/dev/null
MESH_CONTAINERS+=("${name}")
mesh_wait_for_log "${name}" "SAM Hub Online" 20
+
+ # Extract Peer ID for nodes to use
+ local peer_id
+ peer_id=$(docker logs "${name}" | grep "PeerID:" | awk '{print $2}' | tr -d '\r')
+ echo "${peer_id}" > "/tmp/${MESH_PREFIX}-hub-peer-id"
+ echo "Extracted Hub PeerID: ${peer_id}"
}
mesh_start_node() {
local idx="$1"
local name="${MESH_PREFIX}-node-${idx}"
+ local hub_peer_id
+ hub_peer_id=$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")
+
docker run -d \
--name "${name}" \
--network "${MESH_NETWORK}" \
--network-alias "sam-node-${idx}" \
"sam-node:local" \
run \
- --hub "http://sam-hub:8080" \
- --token "token-${idx}" \
+ --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" \
+ --client-id "sam-e2e" \
+ --client-secret "sam-e2e-secret" \
+ --token-url "http://mock-oidc:18080/token" \
--listen "/ip4/0.0.0.0/udp/5001/quic-v1" \
--listen "/ip4/0.0.0.0/tcp/5002" >/dev/null
diff --git a/tests/e2e/sam.bats b/tests/e2e/sam.bats
index fb700e3b..f519b49c 100644
--- a/tests/e2e/sam.bats
+++ b/tests/e2e/sam.bats
@@ -18,37 +18,11 @@ setup() {
export XDG_CONFIG_HOME="$HOME/.config"
mkdir -p "$XDG_CONFIG_HOME"
- # Start mock hub config server
- python3 -c '
-import http.server
-import socketserver
-import sys
-PORT = 8080
-
-class Handler(http.server.SimpleHTTPRequestHandler):
- def do_GET(self):
- if self.path == "/api/v1/config":
- self.send_response(200)
- self.send_header("Content-type", "application/json")
- self.end_headers()
- self.wfile.write(b"{\"public_key_hex\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"mesh_id\":\"test-mesh\",\"bootstrap_nodes\":[\"/ip4/127.0.0.1/tcp/4002/p2p/QmYyQSo1sn1GjUuQwca9AdvV8Zeyvmxrww8dDnewPrfJs9\"]}")
- else:
- self.send_response(404)
- self.end_headers()
-
-socketserver.TCPServer.allow_reuse_address = True
-with socketserver.TCPServer(("", PORT), Handler) as httpd:
- httpd.serve_forever()
-' &
- MOCK_HUB_PID=$!
- export MOCK_HUB_PID
- sleep 0.5
}
teardown() {
- kill "$MOCK_HUB_PID" || true
- wait "$MOCK_HUB_PID" 2>/dev/null || true
+
rm -rf "$TEST_TMPDIR"
}
@@ -58,23 +32,15 @@ teardown() {
[[ "$output" == *"Sovereign Agent Mesh Node"* ]]
}
-@test "sam-node login --help returns success" {
- run "$SAM_NODE_BINARY" login --help
- [[ "$status" -eq 0 ]]
- [[ "$output" == *"Establish sovereign identity with the Hub"* ]]
-}
-@test "sam-node run without identity prints guidance" {
+
+@test "sam-node run without identity fails" {
run "$SAM_NODE_BINARY" run
- [[ "$status" -eq 0 ]]
- [[ "$output" == *"No identity found"* ]]
+ [[ "$status" -ne 0 ]]
+ [[ "$output" == *"No JWT or stored identity found"* ]]
}
-@test "sam-node login stores identity from stdin" {
- run bash -c "printf 'sample-token\n' | '$SAM_NODE_BINARY' login"
- [[ "$status" -eq 0 ]]
- [[ "$output" == *"Success! Identity stored"* ]]
-}
+
@test "sam-hub --help returns success" {
run "$SAM_HUB_BINARY" --help
diff --git a/tests/e2e/watch.bats b/tests/e2e/watch.bats
index 60fc37f0..dd4d761b 100644
--- a/tests/e2e/watch.bats
+++ b/tests/e2e/watch.bats
@@ -12,43 +12,18 @@ setup() {
export XDG_CONFIG_HOME="$HOME/.config"
mkdir -p "$XDG_CONFIG_HOME"
- # Start mock hub config server
- python3 -c '
-import http.server
-import socketserver
-import sys
-
-PORT = 8080
-
-class Handler(http.server.SimpleHTTPRequestHandler):
- def do_GET(self):
- if self.path == "/api/v1/config":
- self.send_response(200)
- self.send_header("Content-type", "application/json")
- self.end_headers()
- self.wfile.write(b"{\"public_key_hex\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"mesh_id\":\"test-mesh\",\"bootstrap_nodes\":[\"/ip4/127.0.0.1/tcp/4002/p2p/QmYyQSo1sn1GjUuQwca9AdvV8Zeyvmxrww8dDnewPrfJs9\"]}")
- else:
- self.send_response(404)
- self.end_headers()
-
-socketserver.TCPServer.allow_reuse_address = True
-with socketserver.TCPServer(("", PORT), Handler) as httpd:
- httpd.serve_forever()
-' &
- MOCK_HUB_PID=$!
- export MOCK_HUB_PID
- sleep 0.5
+ # Generate mock DB
+ go run tests/e2e/gen_db.go "$XDG_CONFIG_HOME/sam-mesh/agent.db"
}
teardown() {
- kill "$MOCK_HUB_PID" || true
- wait "$MOCK_HUB_PID" 2>/dev/null || true
+ chmod -R +w "$TEST_TMPDIR" || true
rm -rf "$TEST_TMPDIR"
}
-@test "sam-node run with token reaches online state" {
+@test "sam-node run with stored identity reaches online state" {
log_file="$TEST_TMPDIR/run.log"
- "$SAM_NODE_BINARY" run --token test-token --listen /ip4/127.0.0.1/udp/0/quic-v1 --listen /ip4/127.0.0.1/tcp/0 >"$log_file" 2>&1 &
+ "$SAM_NODE_BINARY" run --listen /ip4/127.0.0.1/udp/0/quic-v1 --listen /ip4/127.0.0.1/tcp/0 >"$log_file" 2>&1 &
pid=$!
online=""
@@ -66,25 +41,4 @@ teardown() {
[[ "$online" == "yes" ]]
}
-@test "sam-node login enables run without --token" {
- run bash -c "printf 'persisted-token\n' | '$SAM_NODE_BINARY' login"
- [[ "$status" -eq 0 ]]
- log_file="$TEST_TMPDIR/run-stored.log"
- "$SAM_NODE_BINARY" run --listen /ip4/127.0.0.1/udp/0/quic-v1 --listen /ip4/127.0.0.1/tcp/0 >"$log_file" 2>&1 &
- pid=$!
-
- online=""
- for _ in {1..40}; do
- if grep -q "SAM Node Online" "$log_file"; then
- online="yes"
- break
- fi
- sleep 0.1
- done
-
- kill "$pid" >/dev/null 2>&1 || true
- wait "$pid" >/dev/null 2>&1 || true
-
- [[ "$online" == "yes" ]]
-}
diff --git a/tests/integration/call_test.go b/tests/integration/call_test.go
index 1660d747..a8f0c317 100644
--- a/tests/integration/call_test.go
+++ b/tests/integration/call_test.go
@@ -20,14 +20,14 @@ import (
"time"
)
-func TestSamNodeLoginHelp(t *testing.T) {
+func TestSamNodeRunHelp(t *testing.T) {
nodeBin := buildBinary(t, "./cmd/sam-node")
- stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, nil, "", nodeBin, "login", "--help")
+ stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, nil, "", nodeBin, "run", "--help")
if err != nil {
- t.Fatalf("sam-node login --help failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
+ t.Fatalf("sam-node run --help failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
out := stdout + stderr
- if !strings.Contains(out, "Establish sovereign identity with the Hub") {
+ if !strings.Contains(out, "Start the sovereign mesh node") {
t.Fatalf("unexpected help output:\n%s", out)
}
}
diff --git a/tests/integration/cuj_test.go b/tests/integration/cuj_test.go
index 6b1822d9..10b88a4d 100644
--- a/tests/integration/cuj_test.go
+++ b/tests/integration/cuj_test.go
@@ -25,7 +25,7 @@ import (
func TestSamNodeRunWithManualTokenStarts(t *testing.T) {
nodeBin := buildBinary(t, "./cmd/sam-node")
- hubURL := startMockHubConfigServer(t)
+ _, hubAddr := startMockLibp2pHub(t)
tmpHome := t.TempDir()
env := append(os.Environ(),
"HOME="+tmpHome,
@@ -40,8 +40,8 @@ func TestSamNodeRunWithManualTokenStarts(t *testing.T) {
"",
nodeBin,
"run",
- "--hub", hubURL,
- "--token", "test-token",
+ "--hub", hubAddr,
+ "--jwt", "test-jwt",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
)
diff --git a/tests/integration/login_test.go b/tests/integration/login_test.go
new file mode 100644
index 00000000..c9869df7
--- /dev/null
+++ b/tests/integration/login_test.go
@@ -0,0 +1,79 @@
+// 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 integration_test
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestSamNodeLogin(t *testing.T) {
+ nodeBin := buildBinary(t, "./cmd/sam-node")
+ _, hubAddr := startMockLibp2pHub(t)
+ tmpHome := t.TempDir()
+ env := append(os.Environ(),
+ "HOME="+tmpHome,
+ "XDG_CONFIG_HOME="+filepath.Join(tmpHome, ".config"),
+ )
+
+ // We simulate the user pasting the token followed by a newline.
+ stdin := "test-jwt-token\n"
+
+ stdout, stderr, err := runCommand(
+ t,
+ repoRoot(t),
+ 5*time.Second,
+ env,
+ stdin,
+ nodeBin,
+ "login",
+ "--hub", hubAddr,
+ "--token-url", "http://example.com/token",
+ )
+ if err != nil {
+ t.Fatalf("login command failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
+ }
+
+ out := stdout + stderr
+ if !strings.Contains(out, "Login successful and identity stored.") {
+ t.Fatalf("login did not succeed:\n%s", out)
+ }
+
+ // Verify that the identity is actually stored.
+ // We can try to run the node without flags now!
+ stdout, stderr, err = runCommand(
+ t,
+ repoRoot(t),
+ 3*time.Second,
+ env,
+ "",
+ nodeBin,
+ "run",
+ "--hub", hubAddr,
+ )
+ // We expect it to keep running because it uses stored identity.
+ if err != context.DeadlineExceeded {
+ t.Fatalf("expected run command to keep running, got: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
+ }
+
+ out = stdout + stderr
+ if !strings.Contains(out, "Using stored identity.") {
+ t.Fatalf("node did not use stored identity:\n%s", out)
+ }
+}
diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.go
index e37556c9..fc29fc4f 100644
--- a/tests/integration/minimal_helpers_test.go
+++ b/tests/integration/minimal_helpers_test.go
@@ -17,21 +17,21 @@ package integration_test
import (
"bytes"
"context"
- "crypto/ed25519"
- "crypto/rand"
- "encoding/hex"
- "encoding/json"
"errors"
- "net/http"
- "net/http/httptest"
+ "fmt"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
- corecrypto "github.com/libp2p/go-libp2p/core/crypto"
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p"
+ "github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
+ "github.com/libp2p/go-libp2p/core/protocol"
+ "github.com/libp2p/go-msgio"
+ "google.golang.org/protobuf/proto"
)
func repoRoot(t *testing.T) string {
@@ -90,37 +90,37 @@ func runCommand(
return stdout.String(), stderr.String(), err
}
-func startMockHubConfigServer(t *testing.T) string {
+func startMockLibp2pHub(t *testing.T) (peer.ID, string) {
t.Helper()
- pubKey, _, err := ed25519.GenerateKey(rand.Reader)
+ h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))
if err != nil {
- t.Fatalf("generating hub public key: %v", err)
+ t.Fatalf("failed to create mock libp2p host: %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": hex.EncodeToString(pubKey),
- "mesh_id": "test-mesh",
- "bootstrap_nodes": []string{bootstrapAddr},
- })
- default:
- http.NotFound(w, r)
+ h.SetStreamHandler(protocol.ID("/sam/enroll/1.0.0"), func(s network.Stream) {
+ defer func() { _ = s.Close() }()
+
+ // The following constants are mock values used for testing.
+ // 'mock-biscuit-token' is a dummy token string.
+ // 'mock-hub-pub-key' is a dummy public key string.
+ resp := &api.EnrollResponse{
+ BiscuitToken: []byte("mock-biscuit-token"),
+ HubPublicKey: []byte("mock-hub-pub-key"),
+ HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},
}
- }))
- t.Cleanup(ts.Close)
- return ts.URL
+ data, err := proto.Marshal(resp)
+ if err != nil {
+ fmt.Printf("Failed to marshal mock response: %v\n", err)
+ return
+ }
+ writer := msgio.NewVarintWriter(s)
+ if err := writer.WriteMsg(data); err != nil {
+ fmt.Printf("Failed to write mock response: %v\n", err)
+ }
+ })
+
+ t.Cleanup(func() { _ = h.Close() })
+
+ return h.ID(), h.Addrs()[0].String() + "/p2p/" + h.ID().String()
}
diff --git a/tests/integration/p2p_test.go b/tests/integration/p2p_test.go
index fd410873..b667dfc1 100644
--- a/tests/integration/p2p_test.go
+++ b/tests/integration/p2p_test.go
@@ -30,11 +30,11 @@ func TestSamNodeRunWithoutIdentity(t *testing.T) {
"XDG_CONFIG_HOME=" + filepath.Join(tmpHome, ".config"),
}
stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, append(os.Environ(), env...), "", nodeBin, "run")
- if err != nil {
- t.Fatalf("sam-node run without identity failed unexpectedly: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
+ if err == nil {
+ t.Fatalf("expected sam-node run without identity to fail, but it succeeded\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
}
out := stdout + stderr
- if !strings.Contains(out, "No identity found") {
+ if !strings.Contains(out, "No JWT or stored identity found") {
t.Fatalf("expected missing identity message, got:\n%s", out)
}
}
diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.go
index f4bb3545..8dc5920f 100644
--- a/tests/integration/proxy_test.go
+++ b/tests/integration/proxy_test.go
@@ -16,38 +16,61 @@ package integration_test
import (
"context"
+ "encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
+
+ "go.etcd.io/bbolt"
)
-func TestSamNodeLoginThenRunWithStoredIdentity(t *testing.T) {
+func TestSamNodeRunWithStoredIdentity(t *testing.T) {
nodeBin := buildBinary(t, "./cmd/sam-node")
- hubURL := startMockHubConfigServer(t)
tmpHome := t.TempDir()
- env := append(os.Environ(),
- "HOME="+tmpHome,
- "XDG_CONFIG_HOME="+filepath.Join(tmpHome, ".config"),
- )
- loginOut, loginErrOut, err := runCommand(
- t,
- repoRoot(t),
- 10*time.Second,
- env,
- "test-biscuit-token\n",
- nodeBin,
- "login",
- "--hub", hubURL,
- )
+ // Pre-populate store
+ configDir := filepath.Join(tmpHome, ".config", "sam-mesh")
+ err := os.MkdirAll(configDir, 0700)
if err != nil {
- t.Fatalf("sam-node login failed: %v\nstdout:\n%s\nstderr:\n%s", err, loginOut, loginErrOut)
+ t.Fatalf("failed to create config dir: %v", err)
}
- if !strings.Contains(loginOut+loginErrOut, "Success! Identity stored") {
- t.Fatalf("unexpected login output:\n%s\n%s", loginOut, loginErrOut)
+
+ dbPath := filepath.Join(configDir, "agent.db")
+ db, err := bbolt.Open(dbPath, 0600, nil)
+ if err != nil {
+ t.Fatalf("failed to open db: %v", err)
}
+ err = db.Update(func(tx *bbolt.Tx) error {
+ b, err := tx.CreateBucketIfNotExists([]byte("identity"))
+ if err != nil {
+ return err
+ }
+ // The following constants are mock values used for testing.
+ // 'mock-biscuit-token' is a dummy token string.
+ // 'mock-hub-pub-key' is a dummy public key string.
+ if err := b.Put([]byte("identity_biscuit"), []byte("mock-biscuit-token")); err != nil {
+ return err
+ }
+ if err := b.Put([]byte("hub_public_key"), []byte("mock-hub-pub-key")); err != nil {
+ return err
+ }
+ addrsData, _ := json.Marshal([]string{"/ip4/127.0.0.1/tcp/4002/p2p/Qm..."})
+ if err := b.Put([]byte("hub_addresses"), addrsData); err != nil {
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("failed to update db: %v", err)
+ }
+ _ = db.Close()
+
+ env := append(os.Environ(),
+ "HOME="+tmpHome,
+ "XDG_CONFIG_HOME="+filepath.Join(tmpHome, ".config"),
+ )
runOut, runErrOut, err := runCommand(
t,
@@ -57,17 +80,18 @@ 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",
)
if err != context.DeadlineExceeded {
t.Fatalf("expected run command to keep running until timeout, got: %v\nstdout:\n%s\nstderr:\n%s", err, runOut, runErrOut)
}
- if strings.Contains(runOut+runErrOut, "No identity found") {
- t.Fatalf("run command did not use stored identity:\n%s\n%s", runOut, runErrOut)
+
+ out := runOut + runErrOut
+ if !strings.Contains(out, "Using stored identity.") {
+ t.Fatalf("run command did not use stored identity:\n%s", out)
}
- if !strings.Contains(runOut+runErrOut, "SAM Node Online") {
- t.Fatalf("node did not reach online state:\n%s\n%s", runOut, runErrOut)
+ if !strings.Contains(out, "SAM Node Online") {
+ t.Fatalf("node did not reach online state:\n%s", out)
}
}