Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
refactor: move hub and node logic to internal/ and keep CLI entrypoints under cmd/
Antonio Ojeae14a6083c7f4
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.goindex 15c93507..68a20530 100644--- a/cmd/sam-hub/main.go+++ b/cmd/sam-hub/main.go@@ -15,49 +15,23 @@package mainimport (- "io"-- "github.com/libp2p/go-libp2p/core/network"- "github.com/prometheus/client_golang/prometheus"- "github.com/prometheus/client_golang/prometheus/promhttp"-- "sync"-- "github.com/libp2p/go-msgio"-"context"- "crypto/ed25519""crypto/tls""crypto/x509"- "encoding/hex""fmt""net""net/http""os""strings"- "sync/atomic""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/google/sam/internal/hub"golog "github.com/ipfs/go-log/v2"- "github.com/libp2p/go-libp2p"- 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/connmgr"- "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay"- libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls"- "github.com/multiformats/go-multiaddr"madns "github.com/multiformats/go-multiaddr-dns"-- "golang.org/x/time/rate"-+ "github.com/prometheus/client_golang/prometheus"+ "github.com/prometheus/client_golang/prometheus/promhttp""github.com/spf13/cobra"- "google.golang.org/protobuf/proto")func init() {@@ -74,31 +48,6 @@ func init() {}}-const (- GracePeriod = 60 * time.Second-- // Rate limiting defaults- EnrollRateLimit = 10- EnrollBurst = 20-- // ConnManager limits- LowWaterMark = 100- HighWaterMark = 400- ConnGracePeriod = 1 * time.Minute-- // Timeouts- JWTVerificationTimeout = 10 * time.Second-- // Defaults- DefaultOIDCIssuer = "https://accounts.google.com"- DefaultMeshName = "public-mesh"- DefaultPolicyFile = "policies.yaml"- DefaultKeysDBPath = "keys.db"- DefaultBindAddress = ":9090"-)--var isHubReady atomic.Bool-var (oidcIssuer stringclientID string@@ -121,341 +70,7 @@ var (allowLoopbackFlag bool)-var logger = golog.Logger("sam-hub")--type relayACL struct {- hub *Hub-}--func (a *relayACL) AllowReserve(p peer.ID, addr multiaddr.Multiaddr) bool {- _, ok := a.hub.authenticatedPeers.Load(p)- if !ok {- logger.Errorf("[Relay] Rejecting reservation for %s: not authenticated", p)- } else {- logger.Infof("[Relay] Allowing reservation for %s", p)- }- return ok-}--func (a *relayACL) AllowConnect(src peer.ID, srcAddr multiaddr.Multiaddr, dest peer.ID) bool {- _, ok := a.hub.authenticatedPeers.Load(dest)- if !ok {- logger.Errorf("[Relay] Rejecting connect from %s to %s: dest not authenticated", src, dest)- } else {- logger.Infof("[Relay] Allowing connect from %s to %s", src, dest)- }- return ok-}--// Hub handles identity bridging and network discovery-type Hub struct {- Host host.Host- DHT *dht.IpfsDHT- Providers map[string]*oidc.Provider- KeyRing *KeyRing- MeshID string- PubSub *pubsub.PubSub- EventTopic *pubsub.Topic- Policy *api.PolicyConfig- limiter *rate.Limiter- ExternalAddrs []string- AllowedAudiences []string- AllowLoopback bool- BiscuitTimeout time.Duration- authenticatedPeers sync.Map-}--// NewHub starts a host supporting both QUIC and TCP (with TLS 1.3)-func NewHub(ctx context.Context, policy *api.PolicyConfig, allowLoopback bool) (*Hub, error) {- // Connection Manager for DoS protection- cm, err := connmgr.NewConnManager(LowWaterMark, HighWaterMark, connmgr.WithGracePeriod(ConnGracePeriod))- if err != nil {- return nil, fmt.Errorf("failed to create connection manager: %w", err)- }-- opts := []libp2p.Option{- libp2p.DefaultTransports,- libp2p.ListenAddrStrings(listenAddrs...),- // FIPS compliant Security- libp2p.Security(libp2ptls.ID, libp2ptls.New),- libp2p.ConnectionManager(cm),- libp2p.EnableAutoNATv2(),- libp2p.EnableNATService(),- libp2p.AddrsFactory(func(addrs []multiaddr.Multiaddr) []multiaddr.Multiaddr {- if allowLoopback {- return addrs- }- var filtered []multiaddr.Multiaddr- for _, addr := range addrs {- if !isLoopbackOrLinkLocal(addr) {- filtered = append(filtered, addr)- }- }- return filtered- }),- }-- h, err := libp2p.New(opts...)- if err != nil {- return nil, err- }-- kadDHT, err := dht.New(ctx, h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))- if err != nil {- return nil, err- }- if err = kadDHT.Bootstrap(ctx); err != nil {- return nil, err- }-- issuers := strings.Split(oidcIssuer, ",")- providers := make(map[string]*oidc.Provider)- for _, iss := range issuers {- iss = strings.TrimSpace(iss)- if iss == "" {- continue- }- var providerCtx = ctx- if insecureSkipTLSVerify {- tr := &http.Transport{- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},- }- client := &http.Client{- Timeout: 30 * time.Second,- Transport: tr,- }- providerCtx = oidc.ClientContext(ctx, client)- }- provider, err := oidc.NewProvider(providerCtx, iss)- if err != nil {- return nil, fmt.Errorf("failed to create provider for %s: %w", iss, err)- }- providers[iss] = provider- logger.Infof("[OIDC] Trusted issuer: %s", iss)- }-- var initialSeed []byte- if biscuitHex != "" {- var err error- initialSeed, err = hex.DecodeString(strings.TrimSpace(biscuitHex))- if err != nil {- return nil, fmt.Errorf("failed to decode key flag: %w", err)- }- }- kr, err := NewKeyRing(keysDBPath, keyGracePeriod, initialSeed)- if err != nil {- return nil, fmt.Errorf("failed to create keyring: %w", err)- }-- var auds []string- for _, aud := range strings.Split(allowedAudiencesFlag, ",") {- aud = strings.TrimSpace(aud)- if aud != "" {- auds = append(auds, aud)- }- }- if len(auds) == 0 {- auds = []string{api.DefaultAudience}- }-- var filteredExternal []string- for _, addr := range externalMultiaddrs {- if !strings.HasPrefix(addr, "http://") && !strings.HasPrefix(addr, "https://") {- filteredExternal = append(filteredExternal, addr)- }- }-- hub := &Hub{- Host: h,- DHT: kadDHT,- Providers: providers,- KeyRing: kr,- MeshID: meshName,- Policy: policy,- limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),- ExternalAddrs: filteredExternal,- AllowedAudiences: auds,- AllowLoopback: allowLoopback,- }- ps, err := pubsub.NewGossipSub(ctx, h)- if err != nil {- return nil, err- }- topic, err := ps.Join(api.GossipEvents)- if err != nil {- return nil, err- }-- hub.PubSub = ps- hub.EventTopic = topic-- _, err = relay.New(h, relay.WithACL(&relayACL{hub: hub}))- if err != nil {- return nil, err- }-- h.SetStreamHandler(api.AuthProtocolID, hub.HandleAuthHandshake)-- h.Network().Notify(&network.NotifyBundle{- DisconnectedF: func(n network.Network, c network.Conn) {- p := c.RemotePeer()- if len(h.Network().ConnsToPeer(p)) == 0 {- hub.authenticatedPeers.Delete(p)- }- },- })-- return hub, nil-}--func (h *Hub) parseAndVerifyJWT(ctx context.Context, jwtStr string, allowedAudiences []string) (jwt.MapClaims, *oidc.IDToken, error) {- jwtParser := jwt.Parser{}- jwtToken, _, err := jwtParser.ParseUnverified(jwtStr, jwt.MapClaims{})- if err != nil {- return nil, nil, fmt.Errorf("failed to parse JWT: %w", err)- }-- // 1. Defend against downgrade attacks immediately- alg, ok := jwtToken.Header["alg"].(string)- if !ok || alg == "" || strings.ToLower(alg) == "none" {- return nil, nil, fmt.Errorf("invalid or missing alg header")- }-- claims, ok := jwtToken.Claims.(jwt.MapClaims)- if !ok {- return nil, nil, fmt.Errorf("invalid JWT claims")- }- iss, _ := claims["iss"].(string)-- // 2. Extract the audience- var aud string- switch a := claims["aud"].(type) {- case string:- aud = a- case []any:- if len(a) > 0 {- aud, _ = a[0].(string)- }- }-- if aud == "" {- return nil, nil, fmt.Errorf("missing aud claim")- }-- // 3. Verify the audience matches one of your expected tenants/platforms- validAudience := false- for _, allowed := range allowedAudiences {- if aud == allowed {- validAudience = true- break- }- }- if !validAudience {- return nil, nil, fmt.Errorf("untrusted audience: %s", aud)- }-- // 4. Route to the correct provider- provider, ok := h.Providers[iss]- if !ok {- return nil, nil, fmt.Errorf("unknown issuer: %s", iss)- }-- // 5. Verify cryptographic signature, bypassing the strict single-clientID check- // because we already validated the audience against our allowed list above.- verifier := provider.Verifier(&oidc.Config{- SkipClientIDCheck: true,- })-- token, err := verifier.Verify(ctx, jwtStr)- if err != nil {- return nil, nil, fmt.Errorf("JWT validation failed: %w", err)- }-- return claims, token, nil-}--// startWatchdog periodically checks for peers that have connected but not completed OIDC-// authentication within the grace period, and evicts them from the network.--func (h *Hub) startRotation(ctx context.Context) {- if keyRotationInterval <= 0 {- return- }- go func() {- ticker := time.NewTicker(keyRotationInterval)- defer ticker.Stop()- for {- select {- case <-ticker.C:- logger.Infow("Rotating keys")- newPub, newPriv, oldPriv, err := h.KeyRing.PrepareRotation()- if err != nil {- logger.Errorw("Failed to prepare key rotation", "error", err)- continue- }- samHubKeyRotationsTotal.Inc()-- // Broadcast event- event := &api.MeshEvent{- Type: api.MeshEvent_KEY_ROTATION,- Timestamp: time.Now().UnixMilli(),- NewPublicKey: newPub,- }-- // Sign with the OLD key so nodes can verify it!- event.Signature = nil- data, err := proto.Marshal(event)- if err != nil {- logger.Errorw("Failed to marshal key rotation event", "error", err)- continue- }- event.Signature = ed25519.Sign(oldPriv, data)-- eventData, err := proto.Marshal(event)- if err != nil {- logger.Errorw("Failed to marshal key rotation event", "error", err)- continue- }- if err := h.EventTopic.Publish(ctx, eventData); err != nil {- logger.Errorw("Failed to publish key rotation event", "error", err)- } else {- logger.Infow("Broadcasted new public key", "public_key", hex.EncodeToString(newPub))- samHubMeshEventsTotal.WithLabelValues("KEY_ROTATION").Inc()-- // Promote the new key after successful broadcast- if err := h.KeyRing.CommitRotation(newPub, newPriv, keyGracePeriod); err != nil {- logger.Errorw("Failed to commit key rotation", "error", err)- } else {- logger.Infow("Committed new key to keyring")- }- }- case <-ctx.Done():- return- }- }- }()-}--func (h *Hub) signEvent(event *api.MeshEvent) error {- event.Signature = nil- data, err := proto.Marshal(event)- if err != nil {- return err- }- event.Signature = ed25519.Sign(h.KeyRing.GetCurrentKey(), data)- return nil-}--func (h *Hub) PublishEvent(ctx context.Context, event *api.MeshEvent) error {- if err := h.signEvent(event); err != nil {- return err- }- data, err := proto.Marshal(event)- if err != nil {- return err- }- return h.EventTopic.Publish(ctx, data)-}+var logger = golog.Logger("sam-hub-cli")func main() {rootCmd := &cobra.Command{@@ -478,7 +93,7 @@ func main() {_ = golog.SetLogLevel("dht", "fatal")_ = golog.SetLogLevel("dht/RtRefreshManager", "fatal")- policyConfig, err := LoadPolicyConfig(policyFile)+ policyConfig, err := hub.LoadPolicyConfig(policyFile)if err != nil {logger.Fatal(err)}@@ -494,22 +109,60 @@ func main() {}}- h, err := NewHub(ctx, policyConfig, allowLoopbackFlag)+ var auds []string+ for _, aud := range strings.Split(allowedAudiencesFlag, ",") {+ aud = strings.TrimSpace(aud)+ if aud != "" {+ auds = append(auds, aud)+ }+ }+ if len(auds) == 0 {+ auds = []string{api.DefaultAudience}+ }++ hOpts := hub.Options{+ OIDCIssuer: oidcIssuer,+ ClientID: clientID,+ BiscuitHex: biscuitHex,+ ListenAddrs: listenAddrs,+ MeshName: meshName,+ InsecureSkipTLSVerify: insecureSkipTLSVerify,+ PolicyFile: policyFile,+ KeyRotationInterval: keyRotationInterval,+ KeyGracePeriod: keyGracePeriod,+ KeysDBPath: keysDBPath,+ BindAddress: bindAddress,+ AdminToken: adminToken,+ TLSCertFile: tlsCertFile,+ TLSKeyFile: tlsKeyFile,+ TLSCAFile: tlsCAFile,+ ExternalMultiaddrs: externalMultiaddrs,+ AllowedAudiences: auds,+ AllowLoopback: allowLoopbackFlag,+ Policy: policyConfig,+ }++ h, err := hub.NewHub(ctx, hOpts)if err != nil {logger.Fatal(err)}+ defer func() {+ if err := h.Close(); err != nil {+ logger.Errorf("Failed to close hub: %v", err)+ }+ }()// Start key rotation if enabled- h.startRotation(ctx)+ h.StartRotation(ctx)if len(externalMultiaddrs) > 0 {- go startBootstrapFederation(ctx, h, externalMultiaddrs)+ go h.StartBootstrapFederation(ctx, externalMultiaddrs)}mux := http.NewServeMux()mux.Handle("/metrics", promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}))mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {- if isHubReady.Load() {+ if h.Ready() {w.WriteHeader(http.StatusOK)_, _ = w.Write([]byte("ok"))} else {@@ -518,8 +171,8 @@ func main() {}})- mux.HandleFunc("/register", h.handleRegisterHTTP)- mux.HandleFunc("/info", h.handleInfoHTTP)+ mux.HandleFunc("/register", h.HandleRegisterHTTP)+ mux.HandleFunc("/info", h.HandleInfoHTTP)mux.HandleFunc("/admin/ban", func(w http.ResponseWriter, r *http.Request) {if adminToken != "" {authHeader := r.Header.Get("Authorization")@@ -528,7 +181,7 @@ func main() {return}}- handleBan(h)(w, r)+ hub.HandleBan(h)(w, r)})server := &http.Server{@@ -554,7 +207,7 @@ func main() {}()logger.Infof("SAM Hub Online (HTTP on %s, P2P on %v)", bindAddress, listenAddrs)- isHubReady.Store(true)+ h.SetReady(true)logger.Infof("MeshID: %s", h.MeshID)logger.Infof("PeerID: %s", h.Host.ID())<-ctx.Done()@@ -567,22 +220,22 @@ func main() {defIssuer := os.Getenv("SAM_OIDC_ISSUER")if defIssuer == "" {- defIssuer = DefaultOIDCIssuer+ defIssuer = hub.DefaultOIDCIssuer}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(&biscuitHex, "key", os.Getenv("SAM_HUB_KEY"), "Hub Private Key (32-byte Hex)")rootCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{}, "libp2p Listen Addrs")rootCmd.Flags().StringSliceVar(&externalMultiaddrs, "external-multiaddr", []string{}, "External multiaddrs to announce")- rootCmd.Flags().StringVar(&meshName, "mesh", DefaultMeshName, "Mesh federation name")+ rootCmd.Flags().StringVar(&meshName, "mesh", hub.DefaultMeshName, "Mesh federation name")rootCmd.Flags().StringVar(&allowedAudiencesFlag, "allowed-audiences", api.DefaultAudience, "Comma-separated list of allowed OIDC audiences")rootCmd.Flags().BoolVar(&insecureSkipTLSVerify, "insecure-skip-tls-verify", false, "Skip TLS verification for OIDC issuers")rootCmd.Flags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error)")- rootCmd.Flags().StringVar(&policyFile, "policy-file", DefaultPolicyFile, "Path to policies.yaml")+ rootCmd.Flags().StringVar(&policyFile, "policy-file", hub.DefaultPolicyFile, "Path to policies.yaml")rootCmd.Flags().DurationVar(&keyRotationInterval, "key-rotation-interval", 0, "Key rotation interval (e.g. 12h). 0 disables rotation.")rootCmd.Flags().DurationVar(&keyGracePeriod, "key-grace-period", 24*time.Hour, "Key grace period for old keys (e.g. 24h).")- rootCmd.Flags().StringVar(&keysDBPath, "keys-db", DefaultKeysDBPath, "Path to BoltDB file for keys")- rootCmd.PersistentFlags().StringVar(&bindAddress, "bind-address", DefaultBindAddress, "Address to listen on for HTTP/HTTPS service")+ rootCmd.Flags().StringVar(&keysDBPath, "keys-db", hub.DefaultKeysDBPath, "Path to BoltDB file for keys")+ rootCmd.PersistentFlags().StringVar(&bindAddress, "bind-address", hub.DefaultBindAddress, "Address to listen on for HTTP/HTTPS service")rootCmd.PersistentFlags().StringVar(&adminToken, "admin-token", "", "Secret token for authorizing admin requests")rootCmd.PersistentFlags().StringVar(&tlsCertFile, "tls-cert-file", "", "Path to TLS certificate for the server")rootCmd.PersistentFlags().StringVar(&tlsKeyFile, "tls-key-file", "", "Path to TLS private key for the server")@@ -672,167 +325,3 @@ func main() {os.Exit(1)}}--func isLoopbackOrLinkLocal(addr multiaddr.Multiaddr) bool {- for _, proto := range addr.Protocols() {- if proto.Code == multiaddr.P_IP4 || proto.Code == multiaddr.P_IP6 {- value, err := addr.ValueForProtocol(proto.Code)- if err == nil {- ip := net.ParseIP(value)- if ip != nil {- if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {- return true- }- }- }- }- }- return false-}--func (h *Hub) HandleAuthHandshake(s network.Stream) {- defer func() {- if err := s.Close(); err != nil {- logger.Debugf("[AuthN] Failed to close auth stream: %v", err)- }- }()- remotePeer := s.Conn().RemotePeer()-- reader := msgio.NewVarintReaderSize(s, 1024*64)- msg, err := reader.ReadMsg()- if err != nil {- logger.Errorf("[AuthN] Failed to read handshake from %s: %v", remotePeer, err)- return- }- defer reader.ReleaseMsg(msg)-- var exchange api.AuthFrame- if err := proto.Unmarshal(msg, &exchange); err != nil {- logger.Warnf("[AuthN] Invalid protobuf from %s", remotePeer)- return- }-- b, err := h.verifyBiscuit(exchange.Biscuit, remotePeer)- if err != nil {- logger.Warnf("[AuthN] Authorization failed for %s: %v", remotePeer, err)- return- }-- // Enforce hardware binding- boundFact := biscuit.Fact{Predicate: biscuit.Predicate{- Name: "node",- IDs: []biscuit.Term{biscuit.String(remotePeer.String())},- }}- if _, err := b.GetBlockID(boundFact); err != nil {- logger.Warnf("[AuthN] Token is not bound to peer %s", remotePeer)- return- }-- h.authenticatedPeers.Store(remotePeer, true)- logger.Infof("[AuthN] Successfully authenticated peer %s", remotePeer)-- writer := msgio.NewVarintWriter(s)- resp := &api.AuthResponse{Success: true}- respBytes, _ := proto.Marshal(resp)- if err := writer.WriteMsg(respBytes); err != nil {- logger.Errorf("[AuthN] Failed to write ACK to %s: %v", remotePeer, err)- }-}--func startBootstrapFederation(ctx context.Context, h *Hub, peers []string) {- if len(peers) == 0 {- return- }- ticker := time.NewTicker(30 * time.Second)- defer ticker.Stop()-- connectBootstrap(ctx, h, peers)-- for {- select {- case <-ctx.Done():- return- case <-ticker.C:- connectBootstrap(ctx, h, peers)- }- }-}--func connectBootstrap(ctx context.Context, h *Hub, peers []string) {- for _, peerStr := range peers {- if strings.HasPrefix(peerStr, "http://") || strings.HasPrefix(peerStr, "https://") {- client := &http.Client{Timeout: 10 * time.Second}- resp, err := client.Get(peerStr + "/info")- if err != nil {- logger.Errorf("[Federation] HTTP Get error for %s: %v", peerStr, err)- continue- }- if resp.StatusCode != http.StatusOK {- logger.Errorf("[Federation] HTTP Get for %s returned status %d", peerStr, resp.StatusCode)- _ = resp.Body.Close()- continue- }- bodyBytes, err := io.ReadAll(resp.Body)- _ = resp.Body.Close()- if err != nil {- logger.Errorf("[Federation] ReadAll error: %v", err)- continue- }-- var info api.HubInfoResponse- if err := proto.Unmarshal(bodyBytes, &info); err != nil {- logger.Errorf("[Federation] Proto unmarshal error: %v", err)- continue- }-- for _, addrStr := range info.HubAddresses {- ma, err := multiaddr.NewMultiaddr(addrStr)- if err != nil {- logger.Errorf("[Federation] Multiaddr error: %v", err)- continue- }-- pi, err := peer.AddrInfoFromP2pAddr(ma)- if err != nil {- logger.Errorf("[Federation] AddrInfo error: %v", err)- continue- }-- if pi.ID == h.Host.ID() {- continue- }-- if len(h.Host.Network().ConnsToPeer(pi.ID)) > 0 {- continue- }-- if err := h.Host.Connect(ctx, *pi); err == nil {- logger.Infof("[Federation] Connected to bootstrap peer: %s via HTTP %s", pi.ID, peerStr)- } else {- logger.Errorf("[Federation] Failed to connect to %s: %v", pi.ID, err)- }- }- continue- }-- ma, err := multiaddr.NewMultiaddr(peerStr)- if err != nil {- continue- }- resolvedAddrs, err := madns.DefaultResolver.Resolve(ctx, ma)- if err != nil {- resolvedAddrs = []multiaddr.Multiaddr{ma}- }- for _, resolved := range resolvedAddrs {- pi, err := peer.AddrInfoFromP2pAddr(resolved)- if err != nil || pi.ID == h.Host.ID() {- continue- }- if len(h.Host.Network().ConnsToPeer(pi.ID)) == 0 {- if err := h.Host.Connect(ctx, *pi); err == nil {- logger.Infof("[Federation] Connected to bootstrap peer: %s via %s", pi.ID, peerStr)- }- }- }- }-}diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.goindex 68223fb4..d6053073 100644--- a/cmd/sam-node/main.go+++ b/cmd/sam-node/main.go@@ -16,14 +16,11 @@ package mainimport ("bufio"- "bytes""context""crypto/ed25519""encoding/hex""fmt"- "io""net"- "net/http""os""os/signal""strings"@@ -31,61 +28,61 @@ import ("time""github.com/google/sam/api"+ "github.com/google/sam/internal/node"golog "github.com/ipfs/go-log/v2"- "github.com/libp2p/go-libp2p/core/crypto""github.com/multiformats/go-multiaddr"+ madns "github.com/multiformats/go-multiaddr-dns""github.com/spf13/cobra"- "google.golang.org/protobuf/proto")-const (- DefaultMeshName = "public-mesh"- DefaultDiscoveryInterval = "30s"- DefaultHubURL = "http://localhost:8080"- DefaultConfigFile = "sam-node.yaml"-- // Renewal timing defaults- DefaultRenewalFallback = 50 * time.Minute- RenewalBuffer = 10 * time.Minute- RenewalThreshold = 15 * time.Minute-)+func init() {+ if dnsServer := os.Getenv("SAM_TEST_DNS_SERVER"); dnsServer != "" {+ customResolver := &net.Resolver{+ PreferGo: true,+ Dial: func(ctx context.Context, network, address string) (net.Conn, error) {+ d := net.Dialer{Timeout: 5 * time.Second}+ return d.DialContext(ctx, "udp", dnsServer)+ },+ }+ net.DefaultResolver = customResolver+ madns.DefaultResolver, _ = madns.NewResolver(madns.WithDefaultResolver(customResolver))+ }+}var (- hubAddr string- listenAddrs []string-+ hubAddr stringjwtFlag stringjwtPathFlag stringclientIDFlag stringclientSecretFlag string- oidcIssuerFlag string- deviceAuthURLFlag string- audienceFlag stringhubPublicKeyFlag stringbindAddrFlag stringmeshFlag stringdiscoveryIntervalFlag string- monitorBootstrapFlag time.Duration- monitorCheckIntervalFlag time.Duration+ listenAddrs []stringenableRelayFlag bool- logLevelFlag stringconfigFile string- keyGracePeriodFlag time.Duration+ oidcIssuerFlag string+ deviceAuthURLFlag string+ audienceFlag stringdataDirFlag string- allowLoopbackFlag boolheadlessFlag boolofflineAccessFlag bool+ logLevelFlag string+ keyGracePeriodFlag time.Duration+ allowLoopbackFlag bool+ monitorBootstrapFlag time.Duration+ monitorCheckIntervalFlag time.DurationautoRelayMinIntervalFlag time.DurationautoRelayBootDelayFlag time.DurationautoRelayBackoffFlag time.Duration-- apiTokenFlag string- tlsCertFlag string- tlsKeyFlag string- tlsCAFlag string+ apiTokenFlag string+ tlsCertFlag string+ tlsKeyFlag string+ tlsCAFlag string)-var logger = golog.Logger("sam-node")+var logger = golog.Logger("sam-node-cli")func main() {rootCmd := &cobra.Command{@@ -117,25 +114,25 @@ func main() {_ = golog.SetLogLevel("dht", "fatal")_ = golog.SetLogLevel("dht/RtRefreshManager", "fatal")- store, err := NewStore(resolveDataDir())+ store, err := node.NewStore(resolveDataDir())if err != nil {logger.Fatalf("Failed to open store: %v", err)}- nodeConfig, err := LoadNodeConfig(configFile)+ nodeConfig, err := node.LoadNodeConfig(configFile)if err != nil {logger.Fatalf("Failed to load node config: %v", err)}defer func() {if err := store.Close(); err != nil {- logger.Error("closing store: %v", err)+ logger.Errorf("closing store: %v", err)}}()var hubPubKey ed25519.PublicKeyvar hubAddrs []multiaddr.Multiaddr- storedPubKey, syncedAddrs, err := SyncHubConfig(context.Background(), store)+ storedPubKey, syncedAddrs, err := node.SyncHubConfig(context.Background(), store)if err != nil {logger.Warnf("Failed to sync hub config: %v", err)}@@ -152,7 +149,7 @@ func main() {hubPubKey = pubBytes}- var node *SamNode+ var meshNode *node.SamNodevar jwtStr string@@ -166,7 +163,7 @@ func main() {jwtStr = strings.TrimSpace(string(data))} else if oidcIssuerFlag != "" {logger.Info("Discovering OIDC endpoints...")- dummyNode := &SamNode{}+ dummyNode := &node.SamNode{}tokenURL, err := dummyNode.DiscoverTokenURL(context.Background(), oidcIssuerFlag)if err != nil {logger.Fatalf("Failed to discover OIDC endpoints: %v", err)@@ -190,7 +187,7 @@ func main() {}}logger.Infof("No identity found. Starting unauthenticated sidecar for enrollment over MCP...")- if err := startUnauthSidecarServer(displayHub, bindAddrFlag, tlsCertFlag, tlsKeyFlag); err != nil {+ if err := node.StartUnauthSidecarServer(displayHub, bindAddrFlag, tlsCertFlag, tlsKeyFlag); err != nil {logger.Fatalf("Failed to start unauthenticated sidecar: %v", err)}<-ctx.Done()@@ -201,8 +198,8 @@ func main() {if len(hubPubKey) == 0 {logger.Fatal("Hub public key not found in store and not provided. Cannot verify peers.")}- priv := getOrGenerateKey(store)- node, err = NewSamNode(context.Background(), SamNodeConfig{+ priv := node.GetOrGenerateKey(store)+ meshNode, err = node.NewSamNode(context.Background(), node.Options{PrivKey: priv,HubPubKey: hubPubKey,HubAddrs: hubAddrs,@@ -256,9 +253,9 @@ func main() {}}- priv := getOrGenerateKey(store)+ priv := node.GetOrGenerateKey(store)enrollCtx, enrollCancel := context.WithCancel(context.Background())- node, err = NewSamNode(enrollCtx, SamNodeConfig{+ meshNode, err = node.NewSamNode(enrollCtx, node.Options{PrivKey: priv,HubAddrs: initHubAddrs,Store: store,@@ -280,9 +277,9 @@ func main() {logger.Fatalf("Failed to initialize node for enrollment: %v", err)}- err = node.Enroll(enrollCtx, jwtStr)+ err = meshNode.Enroll(enrollCtx, hubAddr, jwtStr)if err != nil {- if teardownErr := node.Teardown(); teardownErr != nil {+ if teardownErr := meshNode.Teardown(); teardownErr != nil {logger.Errorf("Teardown failed during enrollment error cleanup: %v", teardownErr)}enrollCancel()@@ -292,19 +289,19 @@ func main() {logger.Warnf("Failed to save hub URL: %v", err)}- if teardownErr := node.Teardown(); teardownErr != nil {+ if teardownErr := meshNode.Teardown(); teardownErr != nil {logger.Errorf("Failed to teardown enrollment node: %v", teardownErr)}enrollCancel()- storedPubKey, newHubAddrs, err := SyncHubConfig(context.Background(), store)+ storedPubKey, newHubAddrs, err := node.SyncHubConfig(context.Background(), store)if err != nil {logger.Warnf("Failed to sync hub config post-enrollment: %v", err)}hubPubKey = storedPubKeylogger.Debugf("listenAddrs: %v, allowLoopback: %v", listenAddrs, allowLoopbackFlag)- node, err = NewSamNode(context.Background(), SamNodeConfig{+ meshNode, err = node.NewSamNode(context.Background(), node.Options{PrivKey: priv,HubPubKey: hubPubKey,HubAddrs: newHubAddrs,@@ -329,22 +326,22 @@ func main() {// Register static services from configif nodeConfig != nil && len(nodeConfig.Services) > 0 {- if err := node.RegisterStaticServices(context.Background(), nodeConfig.Services); err != nil {+ if err := meshNode.RegisterStaticServices(context.Background(), nodeConfig.Services); err != nil {logger.Fatalf("Failed to register static services: %v", err)}}// Start renewal loop- node.StartRenewalLoop(ctx, oidcIssuerFlag, clientIDFlag, clientSecretFlag, jwtPathFlag)+ meshNode.StartRenewalLoop(ctx, oidcIssuerFlag, clientIDFlag, clientSecretFlag, jwtPathFlag)- node.Host.SetStreamHandler(api.AuthProtocolID, node.HandleAuthHandshake)+ meshNode.Host.SetStreamHandler(api.AuthProtocolID, meshNode.HandleAuthHandshake)// Start Sidecar API Server (multiplexed with MCP)- if err := startSidecarServer(node, bindAddrFlag, apiTokenFlag, tlsCertFlag, tlsKeyFlag, tlsCAFlag); err != nil {+ if err := node.StartSidecarServer(meshNode, bindAddrFlag, apiTokenFlag, tlsCertFlag, tlsKeyFlag, tlsCAFlag); err != nil {logger.Fatalf("Failed to start sidecar server: %v", err)}- fmt.Printf("SAM Node Online.\nPeerID: %s\nListening on: %v\n", node.Host.ID(), node.Host.Addrs())+ fmt.Printf("SAM Node Online.\nPeerID: %s\nListening on: %v\n", meshNode.Host.ID(), meshNode.Host.Addrs())// Block forever<-ctx.Done()@@ -384,12 +381,12 @@ func main() {}targetHub = strings.TrimSuffix(targetHub, "/")- store, err := NewStore(resolveDataDir())+ store, err := node.NewStore(resolveDataDir())if err != nil {logger.Fatalf("Failed to open store: %v", err)}- nodeConfig, err := LoadNodeConfig(configFile)+ nodeConfig, err := node.LoadNodeConfig(configFile)if err != nil {logger.Fatalf("Failed to load node config: %v", err)}@@ -399,10 +396,10 @@ func main() {}}()- dummyNode := &SamNode{Store: store}+ dummyNode := &node.SamNode{Store: store}fmt.Printf("Discovering hub info from %s...\n", targetHub)- hubInfo, err := FetchHubInfo(ctx, targetHub)+ hubInfo, err := node.FetchHubInfo(ctx, targetHub)if err != nil {logger.Fatalf("Failed to discover hub info: %v", err)}@@ -416,7 +413,7 @@ func main() {logger.Fatalf("Failed to discover OIDC endpoints: %v", err)}- jwtStr, err := dummyNode.InteractiveLogin(ctx, authURL, tokenURL, hubInfo.ClientId, hubInfo.Audience, offlineAccessFlag)+ jwtStr, err := dummyNode.InteractiveLogin(ctx, authURL, tokenURL, hubInfo.ClientId, hubInfo.Audience, offlineAccessFlag, headlessFlag)if err != nil {logger.Fatalf("Failed to get token: %v", err)}@@ -451,8 +448,8 @@ func main() {}}- priv := getOrGenerateKey(store)- node, err := NewSamNode(context.Background(), SamNodeConfig{+ priv := node.GetOrGenerateKey(store)+ meshNode, err := node.NewSamNode(context.Background(), node.Options{PrivKey: priv,HubAddrs: initHubAddrs,Store: store,@@ -473,7 +470,7 @@ func main() {logger.Fatalf("Failed to initialize node for enrollment: %v", err)}- err = node.Enroll(context.Background(), jwtStr)+ err = meshNode.Enroll(context.Background(), targetHub, jwtStr)if err != nil {logger.Fatalf("Enrollment failed: %v", err)}@@ -496,8 +493,8 @@ func main() {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)")runCmd.Flags().StringVar(&bindAddrFlag, "bind-addr", "127.0.0.1:8080", "Local TCP address for the HTTP server (MCP and Sidecar API)")- runCmd.Flags().StringVar(&meshFlag, "mesh", DefaultMeshName, "Mesh federation name")- runCmd.Flags().StringVar(&discoveryIntervalFlag, "discovery-interval", DefaultDiscoveryInterval, "Polling interval for DHT discovery")+ runCmd.Flags().StringVar(&meshFlag, "mesh", node.DefaultMeshName, "Mesh federation name")+ runCmd.Flags().StringVar(&discoveryIntervalFlag, "discovery-interval", node.DefaultDiscoveryInterval, "Polling interval for DHT discovery")runCmd.Flags().DurationVar(&monitorBootstrapFlag, "monitor-bootstrap", 2*time.Minute, "Initial wait before monitoring hub connection")runCmd.Flags().DurationVar(&monitorCheckIntervalFlag, "monitor-interval", 1*time.Minute, "Interval for checking hub connection")runCmd.Flags().DurationVar(&autoRelayMinIntervalFlag, "autorelay-min-interval", 30*time.Second, "AutoRelay Min Interval")@@ -513,8 +510,8 @@ func main() {runCmd.Flags().StringVar(&tlsCertFlag, "tls-cert", "", "Path to TLS certificate for sidecar API")runCmd.Flags().StringVar(&tlsKeyFlag, "tls-key", "", "Path to TLS key for sidecar API")runCmd.Flags().StringVar(&tlsCAFlag, "tls-ca", "", "Path to TLS CA for sidecar API mTLS")- rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", DefaultHubURL, "Hub URL")- rootCmd.PersistentFlags().StringVar(&configFile, "config", DefaultConfigFile, "Path to sam-node.yaml configuration file")+ rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", node.DefaultHubURL, "Hub URL")+ rootCmd.PersistentFlags().StringVar(&configFile, "config", node.DefaultConfigFile, "Path to sam-node.yaml configuration file")rootCmd.PersistentFlags().StringVar(&oidcIssuerFlag, "oidc-issuer", "", "OIDC Issuer URL")rootCmd.PersistentFlags().StringVar(&deviceAuthURLFlag, "device-auth-url", "", "OIDC Device Authorization URL")rootCmd.PersistentFlags().StringVar(&audienceFlag, "audience", api.DefaultAudience, "OIDC Audience")@@ -541,140 +538,20 @@ func main() {}}-// resolveDataDir honors --data-dir / $SAM_DATA_DIR if set, else falls back to GetDataDir().+// resolveDataDir honors --data-dir / $SAM_DATA_DIR if set, else falls back to GetDefaultDataDir().func resolveDataDir() string {+ var dir stringif dataDirFlag != "" {- if err := os.MkdirAll(dataDirFlag, 0700); err != nil {- logger.Fatalf("Failed to create data directory: %v", err)- }- return dataDirFlag- }-- dir, err := GetDefaultDataDir()- if err != nil {- logger.Fatalf("Failed to get data dir: %v", err)- }- return dir-}--// getOrGenerateKey retrieves a persistent private key or creates one if it's the first run-func getOrGenerateKey(s *Store) crypto.PrivKey {- kb, _ := s.LoadKey()- if len(kb) == 0 {- logger.Info("[Store] Generating new Peer Identity...")- priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)- if err != nil {- logger.Fatalf("Failed to generate key: %v", err)- }- raw, _ := crypto.MarshalPrivateKey(priv)- if err := s.SaveKey(raw); err != nil {- logger.Fatalf("Failed to save key: %v", err)- }- return priv- }- priv, err := crypto.UnmarshalPrivateKey(kb)- if err != nil {- logger.Fatalf("Corrupt key in store: %v", err)- }- return priv-}-func (n *SamNode) Enroll(ctx context.Context, jwt string) error {- 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)- }-- if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {- return fmt.Errorf("hub address must be an HTTP or HTTPS URL for enrollment: %s", hubAddr)- }- url := hubAddr + "/register"- logger.Infof("Enrolling via HTTP at %s", url)-- httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))- if err != nil {- return fmt.Errorf("failed to create HTTP request: %v", err)- }- httpReq.Header.Set("Content-Type", "application/x-protobuf")-- client := &http.Client{- Timeout: 30 * time.Second,- }- resp, err := client.Do(httpReq)- if err != nil {- return fmt.Errorf("HTTP request failed: %v", err)- }- defer func() {- if err := resp.Body.Close(); err != nil {- logger.Errorf("failed to close response body: %v", err)- }- }()-- if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(resp.Body)- return fmt.Errorf("enrollment failed with status %s: %s", resp.Status, string(body))- }-- respData, err := io.ReadAll(resp.Body)- if err != nil {- return fmt.Errorf("failed to read response body: %v", err)- }-- var enrollResp api.EnrollResponse- if err := proto.Unmarshal(respData, &enrollResp); err != nil {- return fmt.Errorf("failed to unmarshal response: %v", err)- }-- if enrollResp.ErrorMessage != "" {- return fmt.Errorf("enrollment failed: %s", enrollResp.ErrorMessage)- }-- if len(enrollResp.BiscuitToken) == 0 {- return fmt.Errorf("received empty biscuit token")- }-- if err := n.Store.SaveIdentity(enrollResp.BiscuitToken); err != nil {- return fmt.Errorf("failed to save identity: %v", err)- }- n.SetIdentityCache(enrollResp.BiscuitToken)-- if err := n.Store.SaveIdentityExpiration(enrollResp.Expiration); err != nil {- return fmt.Errorf("failed to save identity expiration: %v", err)- }-- if err := n.Store.SaveHubConfig(enrollResp.HubPublicKey, enrollResp.HubAddresses); err != nil {- return fmt.Errorf("failed to save hub config: %v", err)- }-- n.keysMu.Lock()- n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(enrollResp.HubPublicKey), ReceivedAt: time.Now()})- n.keysMu.Unlock()-- // Connect and Auth to hub after enrollment to join the mesh- var lastAuthErr error- var authed bool- for _, addrStr := range enrollResp.HubAddresses {- addr, err := multiaddr.NewMultiaddr(addrStr)+ dir = dataDirFlag+ } else {+ d, err := node.GetDefaultDataDir()if err != nil {- logger.Warnf("Failed to parse hub address from response: %v", err)- continue- }- if err := n.ConnectAndAuthWithHub(ctx, addr); err != nil {- logger.Warnf("Failed to connect and auth with hub after enrollment: %v", err)- lastAuthErr = err- } else {- authed = true- break+ logger.Fatalf("Failed to get default data directory: %v", err)}+ dir = d}-- if !authed {- return fmt.Errorf("failed to connect and authenticate with any hub after HTTP enrollment (last error: %v)", lastAuthErr)+ if err := os.MkdirAll(dir, 0700); err != nil {+ logger.Fatalf("Failed to create data directory: %v", err)}-- logger.Info("Successfully enrolled via HTTP and stored identity and hub config.")- return nil+ return dir}diff --git a/cmd/sam-hub/admin.go b/internal/hub/admin.gosimilarity index 75%rename from cmd/sam-hub/admin.gorename to internal/hub/admin.goindex 5d149526..cead2e68 100644--- a/cmd/sam-hub/admin.go+++ b/internal/hub/admin.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("context"@@ -21,22 +21,25 @@ import ("time""github.com/google/sam/api"+ golog "github.com/ipfs/go-log/v2")+var adminLogger = golog.Logger("sam-hub-admin")+// HubAdmin defines the interface needed by admin handlers.type HubAdmin interface {PublishEvent(ctx context.Context, event *api.MeshEvent) error}-// handleBan returns a handler for the /admin/ban endpoint.-func handleBan(admin HubAdmin) http.HandlerFunc {+// HandleBan returns a handler for the /admin/ban endpoint.+func HandleBan(admin HubAdmin) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}peerID := r.URL.Query().Get("peer")- logger.Infof("[Admin API] Received ban request for peer: %s", peerID)+ adminLogger.Infof("[Admin API] Received ban request for peer: %s", peerID)if peerID == "" {http.Error(w, "Missing peer parameter", http.StatusBadRequest)@@ -50,14 +53,14 @@ func handleBan(admin HubAdmin) http.HandlerFunc {Timestamp: time.Now().UnixMilli(),}- logger.Infof("[Admin API] Publishing ban event for peer: %s", peerID)+ adminLogger.Infof("[Admin API] Publishing ban event for peer: %s", peerID)if err := admin.PublishEvent(r.Context(), event); err != nil {- logger.Errorf("[Admin API] Failed to publish event: %v", err)+ adminLogger.Errorf("[Admin API] Failed to publish event: %v", err)http.Error(w, fmt.Sprintf("Failed to publish event: %v", err), http.StatusInternalServerError)return}- logger.Infof("[Admin API] Successfully published ban event for peer: %s", peerID)+ adminLogger.Infof("[Admin API] Successfully published ban event for peer: %s", peerID)w.WriteHeader(http.StatusOK)_, _ = fmt.Fprintf(w, "Published BANNED event for peer %s", peerID)}diff --git a/cmd/sam-hub/admin_test.go b/internal/hub/admin_test.gosimilarity index 98%rename from cmd/sam-hub/admin_test.gorename to internal/hub/admin_test.goindex cc2fb1b1..325dc02b 100644--- a/cmd/sam-hub/admin_test.go+++ b/internal/hub/admin_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("context"@@ -38,7 +38,7 @@ func (m *mockHubAdmin) PublishEvent(ctx context.Context, event *api.MeshEvent) efunc TestHandleBan(t *testing.T) {mockAdmin := &mockHubAdmin{}- handler := handleBan(mockAdmin)+ handler := HandleBan(mockAdmin)// Test valid requestreq, err := http.NewRequest("POST", "/admin/ban?peer=test-peer-id", nil)diff --git a/cmd/sam-hub/biscuit.go b/internal/hub/biscuit.gosimilarity index 99%rename from cmd/sam-hub/biscuit.gorename to internal/hub/biscuit.goindex 3db57104..fc54161e 100644--- a/cmd/sam-hub/biscuit.go+++ b/internal/hub/biscuit.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("errors"diff --git a/cmd/sam-hub/biscuit_benchmark_test.go b/internal/hub/biscuit_benchmark_test.gosimilarity index 99%rename from cmd/sam-hub/biscuit_benchmark_test.gorename to internal/hub/biscuit_benchmark_test.goindex 22ad11f7..13cddc35 100644--- a/cmd/sam-hub/biscuit_benchmark_test.go+++ b/internal/hub/biscuit_benchmark_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("path/filepath"diff --git a/cmd/sam-hub/biscuit_test.go b/internal/hub/biscuit_test.gosimilarity index 99%rename from cmd/sam-hub/biscuit_test.gorename to internal/hub/biscuit_test.goindex d32d4de5..4b6ea74e 100644--- a/cmd/sam-hub/biscuit_test.go+++ b/internal/hub/biscuit_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("path/filepath"diff --git a/cmd/sam-hub/config.go b/internal/hub/config.gosimilarity index 81%rename from cmd/sam-hub/config.gorename to internal/hub/config.goindex 6f08b8ef..93ffb164 100644--- a/cmd/sam-hub/config.go+++ b/internal/hub/config.go@@ -1,4 +1,18 @@-package main+// 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 hubimport ("fmt"diff --git a/cmd/sam-hub/config_test.go b/internal/hub/config_test.gosimilarity index 99%rename from cmd/sam-hub/config_test.gorename to internal/hub/config_test.goindex 66e4fe08..4cd423aa 100644--- a/cmd/sam-hub/config_test.go+++ b/internal/hub/config_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("os"diff --git a/internal/hub/hub.go b/internal/hub/hub.gonew file mode 100644index 00000000..415c24a1--- /dev/null+++ b/internal/hub/hub.go@@ -0,0 +1,620 @@+// 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 hub++import (+ "context"+ "crypto/ed25519"+ "crypto/tls"+ "encoding/hex"+ "errors"+ "fmt"+ "io"+ "net"+ "net/http"+ "strings"+ "sync"+ "sync/atomic"+ "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"+ golog "github.com/ipfs/go-log/v2"+ "github.com/libp2p/go-libp2p"+ 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/network"+ "github.com/libp2p/go-libp2p/core/peer"+ "github.com/libp2p/go-libp2p/p2p/net/connmgr"+ "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay"+ libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls"+ "github.com/libp2p/go-msgio"+ "github.com/multiformats/go-multiaddr"+ madns "github.com/multiformats/go-multiaddr-dns"+ "golang.org/x/time/rate"+ "google.golang.org/protobuf/proto"+)++const (+ GracePeriod = 60 * time.Second++ // Rate limiting defaults+ EnrollRateLimit = 10+ EnrollBurst = 20++ // ConnManager limits+ LowWaterMark = 100+ HighWaterMark = 400+ ConnGracePeriod = 1 * time.Minute++ // Timeouts+ JWTVerificationTimeout = 10 * time.Second+)++type relayACL struct {+ hub *Hub+}++func (a *relayACL) AllowReserve(p peer.ID, addr multiaddr.Multiaddr) bool {+ _, ok := a.hub.authenticatedPeers.Load(p)+ if !ok {+ if a.hub.logger != nil {+ a.hub.logger.Errorf("[Relay] Rejecting reservation for %s: not authenticated", p)+ }+ } else {+ if a.hub.logger != nil {+ a.hub.logger.Infof("[Relay] Allowing reservation for %s", p)+ }+ }+ return ok+}++func (a *relayACL) AllowConnect(src peer.ID, srcAddr multiaddr.Multiaddr, dest peer.ID) bool {+ _, ok := a.hub.authenticatedPeers.Load(dest)+ if !ok {+ if a.hub.logger != nil {+ a.hub.logger.Errorf("[Relay] Rejecting connect from %s to %s: dest not authenticated", src, dest)+ }+ } else {+ if a.hub.logger != nil {+ a.hub.logger.Infof("[Relay] Allowing connect from %s to %s", src, dest)+ }+ }+ return ok+}++// Hub handles identity bridging and network discovery+type Hub struct {+ Host host.Host+ DHT *dht.IpfsDHT+ Providers map[string]*oidc.Provider+ KeyRing *KeyRing+ MeshID string+ PubSub *pubsub.PubSub+ EventTopic *pubsub.Topic+ Policy *api.PolicyConfig+ limiter *rate.Limiter+ ExternalAddrs []string+ AllowedAudiences []string+ AllowLoopback bool+ BiscuitTimeout time.Duration+ authenticatedPeers sync.Map+ logger *golog.ZapEventLogger+ oidcIssuer string+ keyRotationInterval time.Duration+ keyGracePeriod time.Duration+ insecureSkipTLSVerify bool+ isReady atomic.Bool+}++// NewHub starts a host supporting both QUIC and TCP (with TLS 1.3)+func NewHub(ctx context.Context, config Options) (*Hub, error) {+ config.Default()+ if err := config.Validate(); err != nil {+ return nil, err+ }++ // Connection Manager for DoS protection+ cm, err := connmgr.NewConnManager(LowWaterMark, HighWaterMark, connmgr.WithGracePeriod(ConnGracePeriod))+ if err != nil {+ return nil, fmt.Errorf("failed to create connection manager: %w", err)+ }++ p2pOpts := []libp2p.Option{+ libp2p.DefaultTransports,+ libp2p.ListenAddrStrings(config.ListenAddrs...),+ // FIPS compliant Security+ libp2p.Security(libp2ptls.ID, libp2ptls.New),+ libp2p.ConnectionManager(cm),+ libp2p.EnableAutoNATv2(),+ libp2p.EnableNATService(),+ libp2p.AddrsFactory(func(addrs []multiaddr.Multiaddr) []multiaddr.Multiaddr {+ if config.AllowLoopback {+ return addrs+ }+ var filtered []multiaddr.Multiaddr+ for _, addr := range addrs {+ if !isLoopbackOrLinkLocal(addr) {+ filtered = append(filtered, addr)+ }+ }+ return filtered+ }),+ }++ h, err := libp2p.New(p2pOpts...)+ if err != nil {+ return nil, err+ }++ kadDHT, err := dht.New(ctx, h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))+ if err != nil {+ _ = h.Close()+ return nil, err+ }+ if err = kadDHT.Bootstrap(ctx); err != nil {+ _ = h.Close()+ return nil, err+ }++ issuers := strings.Split(config.OIDCIssuer, ",")+ providers := make(map[string]*oidc.Provider)+ for _, iss := range issuers {+ iss = strings.TrimSpace(iss)+ if iss == "" {+ continue+ }+ var providerCtx = ctx+ if config.InsecureSkipTLSVerify {+ tr := &http.Transport{+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},+ }+ client := &http.Client{+ Timeout: 30 * time.Second,+ Transport: tr,+ }+ providerCtx = oidc.ClientContext(ctx, client)+ }+ provider, err := oidc.NewProvider(providerCtx, iss)+ if err != nil {+ _ = h.Close()+ return nil, fmt.Errorf("failed to create provider for %s: %w", iss, err)+ }+ providers[iss] = provider+ }++ var initialSeed []byte+ if config.BiscuitHex != "" {+ var err error+ initialSeed, err = hex.DecodeString(strings.TrimSpace(config.BiscuitHex))+ if err != nil {+ _ = h.Close()+ return nil, fmt.Errorf("failed to decode key flag: %w", err)+ }+ }+ kr, err := NewKeyRing(config.KeysDBPath, config.KeyGracePeriod, initialSeed)+ if err != nil {+ _ = h.Close()+ return nil, fmt.Errorf("failed to create keyring: %w", err)+ }++ var filteredExternal []string+ for _, addr := range config.ExternalMultiaddrs {+ if !strings.HasPrefix(addr, "http://") && !strings.HasPrefix(addr, "https://") {+ filteredExternal = append(filteredExternal, addr)+ }+ }++ hub := &Hub{+ Host: h,+ DHT: kadDHT,+ Providers: providers,+ KeyRing: kr,+ MeshID: config.MeshName,+ Policy: config.Policy,+ limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),+ ExternalAddrs: filteredExternal,+ AllowedAudiences: config.AllowedAudiences,+ AllowLoopback: config.AllowLoopback,+ logger: golog.Logger("sam-hub"),+ oidcIssuer: config.OIDCIssuer,+ keyRotationInterval: config.KeyRotationInterval,+ keyGracePeriod: config.KeyGracePeriod,+ insecureSkipTLSVerify: config.InsecureSkipTLSVerify,+ }++ ps, err := pubsub.NewGossipSub(ctx, h)+ if err != nil {+ _ = hub.Close()+ return nil, err+ }+ topic, err := ps.Join(api.GossipEvents)+ if err != nil {+ _ = hub.Close()+ return nil, err+ }++ hub.PubSub = ps+ hub.EventTopic = topic++ _, err = relay.New(h, relay.WithACL(&relayACL{hub: hub}))+ if err != nil {+ _ = hub.Close()+ return nil, err+ }++ h.SetStreamHandler(api.AuthProtocolID, hub.HandleAuthHandshake)++ h.Network().Notify(&network.NotifyBundle{+ DisconnectedF: func(n network.Network, c network.Conn) {+ p := c.RemotePeer()+ if len(h.Network().ConnsToPeer(p)) == 0 {+ hub.authenticatedPeers.Delete(p)+ }+ },+ })++ hub.logger.Infof("[OIDC] Trusted issuers: %s", config.OIDCIssuer)++ return hub, nil+}++// Ready returns the ready status of the Hub.+func (h *Hub) Ready() bool {+ return h.isReady.Load()+}++// SetReady sets the ready status of the Hub.+func (h *Hub) SetReady(ready bool) {+ h.isReady.Store(ready)+}++// Close closes the underlying p2p host and keyring db.+func (h *Hub) Close() error {+ var errs []error+ if h.Host != nil {+ if err := h.Host.Close(); err != nil {+ errs = append(errs, err)+ }+ }+ if h.KeyRing != nil {+ if err := h.KeyRing.Close(); err != nil {+ errs = append(errs, err)+ }+ }+ return errors.Join(errs...)+}++func (h *Hub) parseAndVerifyJWT(ctx context.Context, jwtStr string, allowedAudiences []string) (jwt.MapClaims, *oidc.IDToken, error) {+ jwtParser := jwt.Parser{}+ jwtToken, _, err := jwtParser.ParseUnverified(jwtStr, jwt.MapClaims{})+ if err != nil {+ return nil, nil, fmt.Errorf("failed to parse JWT: %w", err)+ }++ // 1. Defend against downgrade attacks immediately+ alg, ok := jwtToken.Header["alg"].(string)+ if !ok || alg == "" || strings.ToLower(alg) == "none" {+ return nil, nil, fmt.Errorf("invalid or missing alg header")+ }++ claims, ok := jwtToken.Claims.(jwt.MapClaims)+ if !ok {+ return nil, nil, fmt.Errorf("invalid JWT claims")+ }+ iss, _ := claims["iss"].(string)++ // 2. Extract the audience+ var aud string+ switch a := claims["aud"].(type) {+ case string:+ aud = a+ case []any:+ if len(a) > 0 {+ aud, _ = a[0].(string)+ }+ }++ if aud == "" {+ return nil, nil, fmt.Errorf("missing aud claim")+ }++ // 3. Verify the audience matches one of your expected tenants/platforms+ validAudience := false+ for _, allowed := range allowedAudiences {+ if aud == allowed {+ validAudience = true+ break+ }+ }+ if !validAudience {+ return nil, nil, fmt.Errorf("untrusted audience: %s", aud)+ }++ // 4. Route to the correct provider+ provider, ok := h.Providers[iss]+ if !ok {+ return nil, nil, fmt.Errorf("unknown issuer: %s", iss)+ }++ // 5. Verify cryptographic signature, bypassing the strict single-clientID check+ // because we already validated the audience against our allowed list above.+ verifier := provider.Verifier(&oidc.Config{+ SkipClientIDCheck: true,+ })++ token, err := verifier.Verify(ctx, jwtStr)+ if err != nil {+ return nil, nil, fmt.Errorf("JWT validation failed: %w", err)+ }++ return claims, token, nil+}++// StartRotation periodically checks for keys to rotate.+func (h *Hub) StartRotation(ctx context.Context) {+ if h.keyRotationInterval <= 0 {+ return+ }+ go func() {+ ticker := time.NewTicker(h.keyRotationInterval)+ defer ticker.Stop()+ for {+ select {+ case <-ticker.C:+ h.logger.Infow("Rotating keys")+ newPub, newPriv, oldPriv, err := h.KeyRing.PrepareRotation()+ if err != nil {+ h.logger.Errorw("Failed to prepare key rotation", "error", err)+ continue+ }+ samHubKeyRotationsTotal.Inc()++ // Broadcast event+ event := &api.MeshEvent{+ Type: api.MeshEvent_KEY_ROTATION,+ Timestamp: time.Now().UnixMilli(),+ NewPublicKey: newPub,+ }++ // Sign with the OLD key so nodes can verify it!+ event.Signature = nil+ data, err := proto.Marshal(event)+ if err != nil {+ h.logger.Errorw("Failed to marshal key rotation event", "error", err)+ continue+ }+ event.Signature = ed25519.Sign(oldPriv, data)++ eventData, err := proto.Marshal(event)+ if err != nil {+ h.logger.Errorw("Failed to marshal key rotation event", "error", err)+ continue+ }+ if err := h.EventTopic.Publish(ctx, eventData); err != nil {+ h.logger.Errorw("Failed to publish key rotation event", "error", err)+ } else {+ h.logger.Infow("Broadcasted new public key", "public_key", hex.EncodeToString(newPub))+ samHubMeshEventsTotal.WithLabelValues("KEY_ROTATION").Inc()++ // Promote the new key after successful broadcast+ if err := h.KeyRing.CommitRotation(newPub, newPriv, h.keyGracePeriod); err != nil {+ h.logger.Errorw("Failed to commit key rotation", "error", err)+ } else {+ h.logger.Infow("Committed new key to keyring")+ }+ }+ case <-ctx.Done():+ return+ }+ }+ }()+}++func (h *Hub) signEvent(event *api.MeshEvent) error {+ event.Signature = nil+ data, err := proto.Marshal(event)+ if err != nil {+ return err+ }+ event.Signature = ed25519.Sign(h.KeyRing.GetCurrentKey(), data)+ return nil+}++// PublishEvent signs and broadcasts a mesh event.+func (h *Hub) PublishEvent(ctx context.Context, event *api.MeshEvent) error {+ if err := h.signEvent(event); err != nil {+ return err+ }+ data, err := proto.Marshal(event)+ if err != nil {+ return err+ }+ return h.EventTopic.Publish(ctx, data)+}++func isLoopbackOrLinkLocal(addr multiaddr.Multiaddr) bool {+ for _, proto := range addr.Protocols() {+ if proto.Code == multiaddr.P_IP4 || proto.Code == multiaddr.P_IP6 {+ value, err := addr.ValueForProtocol(proto.Code)+ if err == nil {+ ip := net.ParseIP(value)+ if ip != nil {+ if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {+ return true+ }+ }+ }+ }+ }+ return false+}++// HandleAuthHandshake processes the inbound auth protocol handshake.+func (h *Hub) HandleAuthHandshake(s network.Stream) {+ defer func() {+ if err := s.Close(); err != nil {+ h.logger.Debugf("[AuthN] Failed to close auth stream: %v", err)+ }+ }()+ remotePeer := s.Conn().RemotePeer()++ reader := msgio.NewVarintReaderSize(s, 1024*64)+ msg, err := reader.ReadMsg()+ if err != nil {+ h.logger.Errorf("[AuthN] Failed to read handshake from %s: %v", remotePeer, err)+ return+ }+ defer reader.ReleaseMsg(msg)++ var exchange api.AuthFrame+ if err := proto.Unmarshal(msg, &exchange); err != nil {+ h.logger.Warnf("[AuthN] Invalid protobuf from %s", remotePeer)+ return+ }++ b, err := h.verifyBiscuit(exchange.Biscuit, remotePeer)+ if err != nil {+ h.logger.Warnf("[AuthN] Authorization failed for %s: %v", remotePeer, err)+ return+ }++ // Enforce hardware binding+ boundFact := biscuit.Fact{Predicate: biscuit.Predicate{+ Name: "node",+ IDs: []biscuit.Term{biscuit.String(remotePeer.String())},+ }}+ if _, err := b.GetBlockID(boundFact); err != nil {+ h.logger.Warnf("[AuthN] Token is not bound to peer %s", remotePeer)+ return+ }++ h.authenticatedPeers.Store(remotePeer, true)+ h.logger.Infof("[AuthN] Successfully authenticated peer %s", remotePeer)++ writer := msgio.NewVarintWriter(s)+ resp := &api.AuthResponse{Success: true}+ respBytes, _ := proto.Marshal(resp)+ if err := writer.WriteMsg(respBytes); err != nil {+ h.logger.Errorf("[AuthN] Failed to write ACK to %s: %v", remotePeer, err)+ }+}++// StartBootstrapFederation handles background bootstrap federation.+func (h *Hub) StartBootstrapFederation(ctx context.Context, peers []string) {+ if len(peers) == 0 {+ return+ }+ ticker := time.NewTicker(30 * time.Second)+ defer ticker.Stop()++ h.connectBootstrap(ctx, peers)++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ h.connectBootstrap(ctx, peers)+ }+ }+}++func (h *Hub) connectBootstrap(ctx context.Context, peers []string) {+ for _, peerStr := range peers {+ if strings.HasPrefix(peerStr, "http://") || strings.HasPrefix(peerStr, "https://") {+ client := &http.Client{Timeout: 10 * time.Second}+ resp, err := client.Get(peerStr + "/info")+ if err != nil {+ h.logger.Errorf("[Federation] HTTP Get error for %s: %v", peerStr, err)+ continue+ }+ if resp.StatusCode != http.StatusOK {+ h.logger.Errorf("[Federation] HTTP Get for %s returned status %d", peerStr, resp.StatusCode)+ _ = resp.Body.Close()+ continue+ }+ bodyBytes, err := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ if err != nil {+ h.logger.Errorf("[Federation] ReadAll error: %v", err)+ continue+ }++ var info api.HubInfoResponse+ if err := proto.Unmarshal(bodyBytes, &info); err != nil {+ h.logger.Errorf("[Federation] Proto unmarshal error: %v", err)+ continue+ }++ for _, addrStr := range info.HubAddresses {+ ma, err := multiaddr.NewMultiaddr(addrStr)+ if err != nil {+ h.logger.Errorf("[Federation] Multiaddr error: %v", err)+ continue+ }++ pi, err := peer.AddrInfoFromP2pAddr(ma)+ if err != nil {+ h.logger.Errorf("[Federation] AddrInfo error: %v", err)+ continue+ }++ if pi.ID == h.Host.ID() {+ continue+ }++ if len(h.Host.Network().ConnsToPeer(pi.ID)) > 0 {+ continue+ }++ if err := h.Host.Connect(ctx, *pi); err == nil {+ h.logger.Infof("[Federation] Connected to bootstrap peer: %s via HTTP %s", pi.ID, peerStr)+ } else {+ h.logger.Errorf("[Federation] Failed to connect to %s: %v", pi.ID, err)+ }+ }+ continue+ }++ ma, err := multiaddr.NewMultiaddr(peerStr)+ if err != nil {+ continue+ }+ resolvedAddrs, err := madns.DefaultResolver.Resolve(ctx, ma)+ if err != nil {+ resolvedAddrs = []multiaddr.Multiaddr{ma}+ }+ for _, resolved := range resolvedAddrs {+ pi, err := peer.AddrInfoFromP2pAddr(resolved)+ if err != nil || pi.ID == h.Host.ID() {+ continue+ }+ if len(h.Host.Network().ConnsToPeer(pi.ID)) == 0 {+ if err := h.Host.Connect(ctx, *pi); err == nil {+ h.logger.Infof("[Federation] Connected to bootstrap peer: %s via %s", pi.ID, peerStr)+ }+ }+ }+ }+}++// GetAuthenticatedPeers returns the underlying sync.Map containing authenticated peers.+func (h *Hub) GetAuthenticatedPeers() *sync.Map {+ return &h.authenticatedPeers+}diff --git a/cmd/sam-hub/main_test.go b/internal/hub/hub_test.gosimilarity index 96%rename from cmd/sam-hub/main_test.gorename to internal/hub/hub_test.goindex dcf48a7e..08fbbfc5 100644--- a/cmd/sam-hub/main_test.go+++ b/internal/hub/hub_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("io"@@ -38,8 +38,6 @@ func TestHandleInfoHTTP(t *testing.T) {}defer func() { _ = kr.Close() }()- oidcIssuer = "http://mock-issuer"-priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)if err != nil {t.Fatal(err)@@ -54,12 +52,13 @@ func TestHandleInfoHTTP(t *testing.T) {KeyRing: kr,AllowedAudiences: []string{"test-audience-1", "test-audience-2"},Host: h,+ oidcIssuer: "http://mock-issuer",}req := httptest.NewRequest("GET", "/info", nil)w := httptest.NewRecorder()- hub.handleInfoHTTP(w, req)+ hub.HandleInfoHTTP(w, req)resp := w.Result()if resp.StatusCode != http.StatusOK {diff --git a/cmd/sam-hub/keyring.go b/internal/hub/keyring.gosimilarity index 99%rename from cmd/sam-hub/keyring.gorename to internal/hub/keyring.goindex 13bc19f0..5b3f74eb 100644--- a/cmd/sam-hub/keyring.go+++ b/internal/hub/keyring.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("bytes"diff --git a/cmd/sam-hub/keyring_test.go b/internal/hub/keyring_test.gosimilarity index 99%rename from cmd/sam-hub/keyring_test.gorename to internal/hub/keyring_test.goindex 4c7b914a..fa9bfe76 100644--- a/cmd/sam-hub/keyring_test.go+++ b/internal/hub/keyring_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("bytes"diff --git a/cmd/sam-hub/metrics.go b/internal/hub/metrics.gosimilarity index 54%rename from cmd/sam-hub/metrics.gorename to internal/hub/metrics.goindex 7859f57b..03721aaf 100644--- a/cmd/sam-hub/metrics.go+++ b/internal/hub/metrics.go@@ -1,4 +1,18 @@-package main+// 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 hubimport ("github.com/prometheus/client_golang/prometheus"diff --git a/internal/hub/options.go b/internal/hub/options.gonew file mode 100644index 00000000..7deff958--- /dev/null+++ b/internal/hub/options.go@@ -0,0 +1,86 @@+// 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 hub++import (+ "fmt"+ "time"++ "github.com/google/sam/api"+)++const (+ DefaultOIDCIssuer = "https://accounts.google.com"+ DefaultMeshName = "public-mesh"+ DefaultPolicyFile = "policies.yaml"+ DefaultKeysDBPath = "keys.db"+ DefaultBindAddress = ":9090"+)++// Options holds configuration settings for the Hub.+type Options struct {+ OIDCIssuer string+ ClientID string+ BiscuitHex string+ ListenAddrs []string+ MeshName string+ InsecureSkipTLSVerify bool+ PolicyFile string+ KeyRotationInterval time.Duration+ KeyGracePeriod time.Duration+ KeysDBPath string+ BindAddress string+ AdminToken string+ TLSCertFile string+ TLSKeyFile string+ TLSCAFile string+ ExternalMultiaddrs []string+ AllowedAudiences []string+ AllowLoopback bool+ Policy *api.PolicyConfig+}++// Default sets non-zero default values for options.+func (o *Options) Default() {+ if o.OIDCIssuer == "" {+ o.OIDCIssuer = DefaultOIDCIssuer+ }+ if o.MeshName == "" {+ o.MeshName = DefaultMeshName+ }+ if o.PolicyFile == "" {+ o.PolicyFile = DefaultPolicyFile+ }+ if o.KeysDBPath == "" {+ o.KeysDBPath = DefaultKeysDBPath+ }+ if o.BindAddress == "" {+ o.BindAddress = DefaultBindAddress+ }+ if o.KeyGracePeriod == 0 {+ o.KeyGracePeriod = 24 * time.Hour+ }+}++// Validate checks that all required options are set and valid.+func (o *Options) Validate() error {+ if o.KeysDBPath == "" {+ return fmt.Errorf("keys database path is required")+ }+ if o.Policy == nil {+ return fmt.Errorf("policy configuration is required")+ }+ return nil+}diff --git a/cmd/sam-hub/relay_acl_test.go b/internal/hub/relay_acl_test.gosimilarity index 99%rename from cmd/sam-hub/relay_acl_test.gorename to internal/hub/relay_acl_test.goindex 69b4b387..172754c3 100644--- a/cmd/sam-hub/relay_acl_test.go+++ b/internal/hub/relay_acl_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("testing"diff --git a/cmd/sam-hub/server.go b/internal/hub/server.gosimilarity index 83%rename from cmd/sam-hub/server.gorename to internal/hub/server.goindex 79f4eb7e..30f3f25d 100644--- a/cmd/sam-hub/server.go+++ b/internal/hub/server.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package hubimport ("context"@@ -26,7 +26,8 @@ import ("google.golang.org/protobuf/proto")-func (h *Hub) handleRegisterHTTP(w http.ResponseWriter, r *http.Request) {+// HandleRegisterHTTP registers HTTP enrollment request.+func (h *Hub) HandleRegisterHTTP(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return@@ -43,7 +44,7 @@ func (h *Hub) handleRegisterHTTP(w http.ResponseWriter, r *http.Request) {}defer func() {if err := r.Body.Close(); err != nil {- logger.Errorf("failed to close request body: %v", err)+ h.logger.Errorf("failed to close request body: %v", err)}}()@@ -58,28 +59,28 @@ func (h *Hub) handleRegisterHTTP(w http.ResponseWriter, r *http.Request) {return}- logger.Infow("New HTTP enrollment request", "peer_id", req.PeerId)+ h.logger.Infow("New HTTP enrollment request", "peer_id", req.PeerId)ctx, cancel := context.WithTimeout(context.Background(), JWTVerificationTimeout)defer cancel()claims, token, err := h.parseAndVerifyJWT(ctx, req.Jwt, h.AllowedAudiences)if err != nil {- logger.Errorw("JWT verification failed", "peer_id", req.PeerId, "error", err)+ h.logger.Errorw("JWT verification failed", "peer_id", req.PeerId, "error", err)http.Error(w, "JWT validation failed: "+err.Error(), http.StatusUnauthorized)return}pID, err := peer.Decode(req.PeerId)if err != nil {- logger.Errorw("Invalid Peer ID", "peer_id", req.PeerId, "error", err)+ h.logger.Errorw("Invalid Peer ID", "peer_id", req.PeerId, "error", err)http.Error(w, "Invalid Peer ID", http.StatusBadRequest)return}biscuitData, err := h.mintBiscuitToken(claims, token, pID)if err != nil {- logger.Errorw("Biscuit minting failed", "peer_id", req.PeerId, "error", err)+ h.logger.Errorw("Biscuit minting failed", "peer_id", req.PeerId, "error", err)http.Error(w, "Failed to mint biscuit", http.StatusInternalServerError)return}@@ -94,7 +95,7 @@ func (h *Hub) handleRegisterHTTP(w http.ResponseWriter, r *http.Request) {respData, err := proto.Marshal(resp)if err != nil {- logger.Errorf("[Enroll] Failed to marshal response: %v", err)+ h.logger.Errorf("[Enroll] Failed to marshal response: %v", err)http.Error(w, "Failed to serialize response", http.StatusInternalServerError)return}@@ -103,11 +104,12 @@ func (h *Hub) handleRegisterHTTP(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)_, _ = w.Write(respData)- logger.Infow("Successfully enrolled peer via HTTP", "peer_id", req.PeerId)+ h.logger.Infow("Successfully enrolled peer via HTTP", "peer_id", req.PeerId)samHubEnrollmentTotal.WithLabelValues("success").Inc()}-func (h *Hub) handleInfoHTTP(w http.ResponseWriter, r *http.Request) {+// HandleInfoHTTP retrieves basic metadata info of the Hub.+func (h *Hub) HandleInfoHTTP(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return@@ -130,7 +132,7 @@ func (h *Hub) handleInfoHTTP(w http.ResponseWriter, r *http.Request) {// Fallback if Providers isn't fully populated (e.g. in unit tests)if issuer == "" {- issuer = oidcIssuer+ issuer = h.oidcIssuer}// If multiple issuers in fallback, pick the first one deterministicallyif strings.Contains(issuer, ",") {@@ -153,7 +155,7 @@ func (h *Hub) handleInfoHTTP(w http.ResponseWriter, r *http.Request) {respData, err := proto.Marshal(resp)if err != nil {- logger.Errorf("[Info] Failed to marshal info response: %v", err)+ h.logger.Errorf("[Info] Failed to marshal info response: %v", err)http.Error(w, "Failed to serialize response", http.StatusInternalServerError)return}diff --git a/cmd/sam-node/bridge_transport.go b/internal/node/bridge_transport.gosimilarity index 99%rename from cmd/sam-node/bridge_transport.gorename to internal/node/bridge_transport.goindex dca37a61..ad190353 100644--- a/cmd/sam-node/bridge_transport.go+++ b/internal/node/bridge_transport.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/bridge_transport_test.go b/internal/node/bridge_transport_test.gosimilarity index 99%rename from cmd/sam-node/bridge_transport_test.gorename to internal/node/bridge_transport_test.goindex 26abbf7d..5b082c0b 100644--- a/cmd/sam-node/bridge_transport_test.go+++ b/internal/node/bridge_transport_test.go@@ -5,7 +5,7 @@// You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0-package main+package nodeimport ("context"diff --git a/cmd/sam-node/config.go b/internal/node/config.gosimilarity index 99%rename from cmd/sam-node/config.gorename to internal/node/config.goindex 994baf2d..367cc1b8 100644--- a/cmd/sam-node/config.go+++ b/internal/node/config.go@@ -1,4 +1,4 @@-package main+package nodeimport ("fmt"diff --git a/cmd/sam-node/config_test.go b/internal/node/config_test.gosimilarity index 99%rename from cmd/sam-node/config_test.gorename to internal/node/config_test.goindex bb3e11be..e88825b3 100644--- a/cmd/sam-node/config_test.go+++ b/internal/node/config_test.go@@ -1,4 +1,4 @@-package main+package nodeimport ("os"diff --git a/cmd/sam-node/connection_monitor.go b/internal/node/connection_monitor.gosimilarity index 99%rename from cmd/sam-node/connection_monitor.gorename to internal/node/connection_monitor.goindex 42c9af47..4f9266f9 100644--- a/cmd/sam-node/connection_monitor.go+++ b/internal/node/connection_monitor.go@@ -1,4 +1,4 @@-package main+package nodeimport ("context"diff --git a/cmd/sam-node/connection_monitor_test.go b/internal/node/connection_monitor_test.gosimilarity index 99%rename from cmd/sam-node/connection_monitor_test.gorename to internal/node/connection_monitor_test.goindex 38e06358..aac250d3 100644--- a/cmd/sam-node/connection_monitor_test.go+++ b/internal/node/connection_monitor_test.go@@ -1,4 +1,4 @@-package main+package nodeimport ("context"diff --git a/internal/node/enroll.go b/internal/node/enroll.gonew file mode 100644index 00000000..6dfb6adc--- /dev/null+++ b/internal/node/enroll.go@@ -0,0 +1,157 @@+// 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 node++import (+ "bytes"+ "context"+ "crypto/ed25519"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"++ "github.com/google/sam/api"+ golog "github.com/ipfs/go-log/v2"+ "github.com/libp2p/go-libp2p/core/crypto"+ "github.com/multiformats/go-multiaddr"+ "google.golang.org/protobuf/proto"+)++var logger = golog.Logger("sam-node")++// GetOrGenerateKey retrieves a persistent private key or creates one if it's the first run+func GetOrGenerateKey(s *Store) crypto.PrivKey {+ kb, _ := s.LoadKey()+ if len(kb) == 0 {+ logger.Info("[Store] Generating new Peer Identity...")+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ logger.Fatalf("Failed to generate key: %v", err)+ }+ raw, _ := crypto.MarshalPrivateKey(priv)+ if err := s.SaveKey(raw); err != nil {+ logger.Fatalf("Failed to save key: %v", err)+ }+ return priv+ }+ priv, err := crypto.UnmarshalPrivateKey(kb)+ if err != nil {+ logger.Fatalf("Corrupt key in store: %v", err)+ }+ return priv+}++func (n *SamNode) Enroll(ctx context.Context, hubURL string, jwt string) error {+ 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)+ }++ if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {+ return fmt.Errorf("hub address must be an HTTP or HTTPS URL for enrollment: %s", hubURL)+ }+ url := hubURL + "/register"+ logger.Infof("Enrolling via HTTP at %s", url)++ httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))+ if err != nil {+ return fmt.Errorf("failed to create HTTP request: %v", err)+ }+ httpReq.Header.Set("Content-Type", "application/x-protobuf")++ client := &http.Client{+ Timeout: 30 * time.Second,+ }+ resp, err := client.Do(httpReq)+ if err != nil {+ return fmt.Errorf("HTTP request failed: %v", err)+ }+ defer func() {+ if err := resp.Body.Close(); err != nil {+ logger.Errorf("failed to close response body: %v", err)+ }+ }()++ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(resp.Body)+ return fmt.Errorf("enrollment failed with status %s: %s", resp.Status, string(body))+ }++ respData, err := io.ReadAll(resp.Body)+ if err != nil {+ return fmt.Errorf("failed to read response body: %v", err)+ }++ var enrollResp api.EnrollResponse+ if err := proto.Unmarshal(respData, &enrollResp); err != nil {+ return fmt.Errorf("failed to unmarshal response: %v", err)+ }++ if enrollResp.ErrorMessage != "" {+ return fmt.Errorf("enrollment failed: %s", enrollResp.ErrorMessage)+ }++ if len(enrollResp.BiscuitToken) == 0 {+ return fmt.Errorf("received empty biscuit token")+ }++ if err := n.Store.SaveIdentity(enrollResp.BiscuitToken); err != nil {+ return fmt.Errorf("failed to save identity: %v", err)+ }+ n.SetIdentityCache(enrollResp.BiscuitToken)++ if err := n.Store.SaveIdentityExpiration(enrollResp.Expiration); err != nil {+ return fmt.Errorf("failed to save identity expiration: %v", err)+ }++ if err := n.Store.SaveHubConfig(enrollResp.HubPublicKey, enrollResp.HubAddresses); err != nil {+ return fmt.Errorf("failed to save hub config: %v", err)+ }++ n.keysMu.Lock()+ n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(enrollResp.HubPublicKey), ReceivedAt: time.Now()})+ n.keysMu.Unlock()++ // Connect and Auth to hub after enrollment to join the mesh+ var lastAuthErr error+ var authed bool+ for _, addrStr := range enrollResp.HubAddresses {+ addr, err := multiaddr.NewMultiaddr(addrStr)+ if err != nil {+ logger.Warnf("Failed to parse hub address from response: %v", err)+ continue+ }+ if err := n.ConnectAndAuthWithHub(ctx, addr); err != nil {+ logger.Warnf("Failed to connect and auth with hub after enrollment: %v", err)+ lastAuthErr = err+ } else {+ authed = true+ break+ }+ }++ if !authed {+ return fmt.Errorf("failed to connect and authenticate with any hub after HTTP enrollment (last error: %v)", lastAuthErr)+ }++ logger.Info("Successfully enrolled via HTTP and stored identity and hub config.")+ return nil+}diff --git a/cmd/sam-node/main_test.go b/internal/node/enroll_test.gosimilarity index 94%rename from cmd/sam-node/main_test.gorename to internal/node/enroll_test.goindex ef4e9c2a..4f853e5f 100644--- a/cmd/sam-node/main_test.go+++ b/internal/node/enroll_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("bytes"@@ -30,13 +30,13 @@ func TestGetOrGenerateKey(t *testing.T) {defer func() { _ = store.Close() }()// First call should generate a key- key1 := getOrGenerateKey(store)+ key1 := GetOrGenerateKey(store)if key1 == nil {t.Fatal("Expected key to be generated")}// Second call should retrieve the same key- key2 := getOrGenerateKey(store)+ key2 := GetOrGenerateKey(store)if key2 == nil {t.Fatal("Expected key to be retrieved")}diff --git a/cmd/sam-node/gate.go b/internal/node/gate.gosimilarity index 99%rename from cmd/sam-node/gate.gorename to internal/node/gate.goindex 8b140604..475428f1 100644--- a/cmd/sam-node/gate.go+++ b/internal/node/gate.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/gate_test.go b/internal/node/gate_test.gosimilarity index 99%rename from cmd/sam-node/gate_test.gorename to internal/node/gate_test.goindex 7d1c541c..13ff255d 100644--- a/cmd/sam-node/gate_test.go+++ b/internal/node/gate_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"@@ -112,7 +112,7 @@ func startBareNode(t *testing.T, ctx context.Context) (*SamNode, func()) {if err != nil {t.Fatal(err)}- node, err := NewSamNode(ctx, SamNodeConfig{+ node, err := NewSamNode(ctx, Options{PrivKey: priv,HubAddrs: nil,Store: store,diff --git a/cmd/sam-node/hub_config.go b/internal/node/hub_config.gosimilarity index 99%rename from cmd/sam-node/hub_config.gorename to internal/node/hub_config.goindex 260ee6ba..9db3441c 100644--- a/cmd/sam-node/hub_config.go+++ b/internal/node/hub_config.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/hub_config_test.go b/internal/node/hub_config_test.gosimilarity index 99%rename from cmd/sam-node/hub_config_test.gorename to internal/node/hub_config_test.goindex 69315f06..d4a38cb9 100644--- a/cmd/sam-node/hub_config_test.go+++ b/internal/node/hub_config_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/inference_metrics.go b/internal/node/inference_metrics.gosimilarity index 99%rename from cmd/sam-node/inference_metrics.gorename to internal/node/inference_metrics.goindex 7a29977f..84d3af99 100644--- a/cmd/sam-node/inference_metrics.go+++ b/internal/node/inference_metrics.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("github.com/prometheus/client_golang/prometheus"diff --git a/cmd/sam-node/inference_service.go b/internal/node/inference_service.gosimilarity index 99%rename from cmd/sam-node/inference_service.gorename to internal/node/inference_service.goindex 96b2d213..6d0a359a 100644--- a/cmd/sam-node/inference_service.go+++ b/internal/node/inference_service.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("bufio"diff --git a/cmd/sam-node/inference_test.go b/internal/node/inference_test.gosimilarity index 99%rename from cmd/sam-node/inference_test.gorename to internal/node/inference_test.goindex 754e1fd7..5ef1fd50 100644--- a/cmd/sam-node/inference_test.go+++ b/internal/node/inference_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("bytes"diff --git a/cmd/sam-node/log_buffer.go b/internal/node/log_buffer.gosimilarity index 98%rename from cmd/sam-node/log_buffer.gorename to internal/node/log_buffer.goindex 38e9d239..a32c68a7 100644--- a/cmd/sam-node/log_buffer.go+++ b/internal/node/log_buffer.go@@ -1,4 +1,4 @@-package main+package nodeimport ("container/ring"diff --git a/cmd/sam-node/mcp.go b/internal/node/mcp.gosimilarity index 99%rename from cmd/sam-node/mcp.gorename to internal/node/mcp.goindex 99e23e9d..47522ac3 100644--- a/cmd/sam-node/mcp.go+++ b/internal/node/mcp.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/mcp_handlers.go b/internal/node/mcp_handlers.gosimilarity index 99%rename from cmd/sam-node/mcp_handlers.gorename to internal/node/mcp_handlers.goindex a2c3cf1a..4c11e128 100644--- a/cmd/sam-node/mcp_handlers.go+++ b/internal/node/mcp_handlers.go@@ -1,4 +1,4 @@-package main+package nodeimport ("context"diff --git a/cmd/sam-node/mcp_handlers_additional_test.go b/internal/node/mcp_handlers_additional_test.gosimilarity index 99%rename from cmd/sam-node/mcp_handlers_additional_test.gorename to internal/node/mcp_handlers_additional_test.goindex e21cd0ce..a02b230b 100644--- a/cmd/sam-node/mcp_handlers_additional_test.go+++ b/internal/node/mcp_handlers_additional_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/mcp_handlers_test.go b/internal/node/mcp_handlers_test.gosimilarity index 99%rename from cmd/sam-node/mcp_handlers_test.gorename to internal/node/mcp_handlers_test.goindex fbedeeaf..e9349c0b 100644--- a/cmd/sam-node/mcp_handlers_test.go+++ b/internal/node/mcp_handlers_test.go@@ -1,5 +1,5 @@// Copyright 2026 Google LLC-package main+package nodeimport ("context"diff --git a/cmd/sam-node/mcp_service.go b/internal/node/mcp_service.gosimilarity index 99%rename from cmd/sam-node/mcp_service.gorename to internal/node/mcp_service.goindex 4da8cf67..1d031567 100644--- a/cmd/sam-node/mcp_service.go+++ b/internal/node/mcp_service.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/mcp_test.go b/internal/node/mcp_test.gosimilarity index 99%rename from cmd/sam-node/mcp_test.gorename to internal/node/mcp_test.goindex 0220aaf7..56e063b0 100644--- a/cmd/sam-node/mcp_test.go+++ b/internal/node/mcp_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/middleware.go b/internal/node/middleware.gosimilarity index 99%rename from cmd/sam-node/middleware.gorename to internal/node/middleware.goindex ee84a1fb..c19079d3 100644--- a/cmd/sam-node/middleware.go+++ b/internal/node/middleware.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("crypto/ed25519"diff --git a/cmd/sam-node/middleware_test.go b/internal/node/middleware_test.gosimilarity index 99%rename from cmd/sam-node/middleware_test.gorename to internal/node/middleware_test.goindex e3f01c3a..08ce1a7b 100644--- a/cmd/sam-node/middleware_test.go+++ b/internal/node/middleware_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/node.go b/internal/node/node.gosimilarity index 98%rename from cmd/sam-node/node.gorename to internal/node/node.goindex 281f380e..cae918f1 100644--- a/cmd/sam-node/node.go+++ b/internal/node/node.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("math/rand"@@ -39,11 +39,11 @@ import ("github.com/google/sam/api"lru "github.com/hashicorp/golang-lru/v2""github.com/ipfs/go-cid"+ golog "github.com/ipfs/go-log/v2""github.com/libp2p/go-libp2p"gostream "github.com/libp2p/go-libp2p-gostream"dht "github.com/libp2p/go-libp2p-kad-dht"pubsub "github.com/libp2p/go-libp2p-pubsub"- "github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/discovery""github.com/libp2p/go-libp2p/core/event""github.com/libp2p/go-libp2p/core/host"@@ -86,6 +86,11 @@ const (// Reprovide intervalReprovideInterval = 5 * time.Minute++ // Renewal timing defaults+ DefaultRenewalFallback = 50 * time.Minute+ RenewalBuffer = 10 * time.Minute+ RenewalThreshold = 15 * time.Minute)var ErrFatalAuth = errors.New("fatal authentication error")@@ -136,6 +141,7 @@ type SamNode struct {reprovideTrigger chan struct{}BiscuitTimeout time.DurationcachedIdentity atomic.Value+ logger *golog.ZapEventLogger}// UpdateRelays updates the current relays used by AutoRelay.@@ -209,30 +215,13 @@ func resolveAddrIfNeeded(ctx context.Context, addr multiaddr.Multiaddr) ([]multireturn madns.DefaultResolver.Resolve(ctx, stripP2pFromDnsaddr(addr))}-// SamNodeConfig holds all configuration options for a SamNode.-type SamNodeConfig struct {- PrivKey crypto.PrivKey- HubPubKey ed25519.PublicKey- HubAddrs []multiaddr.Multiaddr- Store *Store- MeshID string- DiscoveryInterval string- ListenAddrs []string- EnableRelay bool- NodeConfig *NodeConfigComplete- KeyGracePeriod time.Duration- AllowLoopback bool- MonitorBootstrap time.Duration- MonitorInterval time.Duration- AutoRelayMinInterval time.Duration- AutoRelayBootDelay time.Duration- AutoRelayBackoff time.Duration-- BiscuitTimeout time.Duration-}-// NewSamNode creates a new Agent instance secured with the 4-layer pipeline.-func NewSamNode(ctx context.Context, cfg SamNodeConfig) (*SamNode, error) {+func NewSamNode(ctx context.Context, cfg Options) (*SamNode, error) {+ cfg.Default()+ if err := cfg.Validate(); err != nil {+ return nil, err+ }+var trustedKeys []TrustedKeyif len(cfg.HubPubKey) > 0 {trustedKeys = []TrustedKey{{Key: cfg.HubPubKey, ReceivedAt: time.Now()}}@@ -250,6 +239,7 @@ func NewSamNode(ctx context.Context, cfg SamNodeConfig) (*SamNode, error) {authSuccess: make(chan struct{}),reprovideTrigger: make(chan struct{}, 1),+ logger: golog.Logger("sam-node"),}node.BiscuitTimeout = cfg.BiscuitTimeout@@ -823,7 +813,12 @@ func (n *SamNode) StartRenewalLoop(ctx context.Context, issuerURL, clientID, cli}if fetchErr == nil {- fetchErr = n.Enroll(ctx, newJWT)+ hubURL, loadErr := n.Store.LoadHubURL()+ if loadErr != nil {+ fetchErr = fmt.Errorf("failed to load hub URL for renewal: %w", loadErr)+ } else {+ fetchErr = n.Enroll(ctx, hubURL, newJWT)+ }}if fetchErr != nil {diff --git a/cmd/sam-node/node_test.go b/internal/node/node_test.gosimilarity index 98%rename from cmd/sam-node/node_test.gorename to internal/node/node_test.goindex c60e79ea..2763eea4 100644--- a/cmd/sam-node/node_test.go+++ b/internal/node/node_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"@@ -100,7 +100,7 @@ func TestConnectionMonitor_CrashesAfterFailures(t *testing.T) {if os.Getenv("BE_CRASHER_MONITOR") == "1" {priv, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)store, _ := NewStore(t.TempDir())- node, err := NewSamNode(context.Background(), SamNodeConfig{+ node, err := NewSamNode(context.Background(), Options{PrivKey: priv,HubAddrs: nil,Store: store,diff --git a/cmd/sam-node/oidc.go b/internal/node/oidc.gosimilarity index 98%rename from cmd/sam-node/oidc.gorename to internal/node/oidc.goindex d8c41a7e..f9528bfd 100644--- a/cmd/sam-node/oidc.go+++ b/internal/node/oidc.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"@@ -61,7 +61,7 @@ func (n *SamNode) FetchJWT(ctx context.Context, tokenURL, clientID, clientSecret}// InteractiveLogin prompts the user to go to a URL and enter a code.-func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clientID, audience string, requestRefresh bool) (string, error) {+func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clientID, audience string, requestRefresh bool, headless bool) (string, error) {if authURL == "" {return "", fmt.Errorf("authorization URL is required")}@@ -83,7 +83,7 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clienreturn "", fmt.Errorf("failed to generate PKCE: %w", err)}- isHeadless := headlessFlag || os.Getenv("SSH_CLIENT") != "" || os.Getenv("SSH_TTY") != ""+ isHeadless := headless || os.Getenv("SSH_CLIENT") != "" || os.Getenv("SSH_TTY") != ""var redirectURI stringvar listener net.Listenerdiff --git a/cmd/sam-node/oidc_test.go b/internal/node/oidc_test.gosimilarity index 99%rename from cmd/sam-node/oidc_test.gorename to internal/node/oidc_test.goindex a72ad5a4..e8b3beb9 100644--- a/cmd/sam-node/oidc_test.go+++ b/internal/node/oidc_test.go@@ -1,4 +1,4 @@-package main+package nodeimport ("context"@@ -67,7 +67,7 @@ func TestInteractiveLogin(t *testing.T) {}defer func() { openBrowserFunc = originalOpenBrowser }()- token, err := node.InteractiveLogin(ctx, "http://auth.example.com/auth", server.URL+"/token", "client_id_test", "sam-e2e", false)+ token, err := node.InteractiveLogin(ctx, "http://auth.example.com/auth", server.URL+"/token", "client_id_test", "sam-e2e", false, false)if err != nil {t.Fatalf("InteractiveLogin failed: %v", err)}@@ -173,7 +173,7 @@ func TestInteractiveLoginWithRefresh(t *testing.T) {}defer func() { openBrowserFunc = originalOpenBrowser }()- token, err := node.InteractiveLogin(ctx, "http://auth.example.com/auth", server.URL+"/token", "client_id_test", "sam-e2e", true)+ token, err := node.InteractiveLogin(ctx, "http://auth.example.com/auth", server.URL+"/token", "client_id_test", "sam-e2e", true, false)if err != nil {t.Fatalf("InteractiveLogin failed: %v", err)}diff --git a/internal/node/options.go b/internal/node/options.gonew file mode 100644index 00000000..b3df4f8b--- /dev/null+++ b/internal/node/options.go@@ -0,0 +1,92 @@+// 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 node++import (+ "crypto/ed25519"+ "fmt"+ "time"++ "github.com/libp2p/go-libp2p/core/crypto"+ "github.com/multiformats/go-multiaddr"+)++const (+ DefaultMeshName = "public-mesh"+ DefaultDiscoveryInterval = "30s"+ DefaultHubURL = "http://localhost:8080"+ DefaultConfigFile = "sam-node.yaml"+)++// Options holds all configuration options for a SamNode.+type Options struct {+ PrivKey crypto.PrivKey+ HubPubKey ed25519.PublicKey+ HubAddrs []multiaddr.Multiaddr+ Store *Store+ MeshID string+ DiscoveryInterval string+ ListenAddrs []string+ EnableRelay bool+ NodeConfig *NodeConfigComplete+ KeyGracePeriod time.Duration+ AllowLoopback bool+ MonitorBootstrap time.Duration+ MonitorInterval time.Duration+ AutoRelayMinInterval time.Duration+ AutoRelayBootDelay time.Duration+ AutoRelayBackoff time.Duration++ BiscuitTimeout time.Duration+}++// Default applies default values to Options if they are not specified.+func (o *Options) Default() {+ if o.MeshID == "" {+ o.MeshID = "public-mesh"+ }+ if o.DiscoveryInterval == "" {+ o.DiscoveryInterval = "30s"+ }+ if o.MonitorBootstrap == 0 {+ o.MonitorBootstrap = 2 * time.Minute+ }+ if o.MonitorInterval == 0 {+ o.MonitorInterval = 1 * time.Minute+ }+ if o.AutoRelayMinInterval == 0 {+ o.AutoRelayMinInterval = 30 * time.Second+ }+ if o.AutoRelayBackoff == 0 {+ o.AutoRelayBackoff = 3 * time.Second+ }+ if o.KeyGracePeriod == 0 {+ o.KeyGracePeriod = 24 * time.Hour+ }+ if len(o.ListenAddrs) == 0 {+ o.ListenAddrs = []string{"/ip4/0.0.0.0/udp/5001/quic-v1", "/ip4/0.0.0.0/tcp/5002"}+ }+}++// Validate verifies that the required options are provided and valid.+func (o *Options) Validate() error {+ if o.PrivKey == nil {+ return fmt.Errorf("private key is required")+ }+ if o.Store == nil {+ return fmt.Errorf("store is required")+ }+ return nil+}diff --git a/cmd/sam-node/proxy_test.go b/internal/node/proxy_test.gosimilarity index 98%rename from cmd/sam-node/proxy_test.gorename to internal/node/proxy_test.goindex 9379a7b7..93afd26f 100644--- a/cmd/sam-node/proxy_test.go+++ b/internal/node/proxy_test.go@@ -1,4 +1,4 @@-package main+package nodeimport ("bufio"@@ -55,7 +55,7 @@ func TestDatapathIntegration(t *testing.T) {// Pre-populate stores with dummy keys to avoid enrollment failure if required// For this test, we assume we can run without full enrollment if we bypass AuthHandler- nodeA, err := NewSamNode(ctx, SamNodeConfig{+ nodeA, err := NewSamNode(ctx, Options{PrivKey: privA,HubAddrs: nil,Store: storeA,@@ -79,7 +79,7 @@ func TestDatapathIntegration(t *testing.T) {}}()- nodeB, err := NewSamNode(ctx, SamNodeConfig{+ nodeB, err := NewSamNode(ctx, Options{PrivKey: privB,HubAddrs: nil,Store: storeB,@@ -253,7 +253,7 @@ func TestDatapathIntegration_Unauthenticated(t *testing.T) {}defer func() { _ = storeB.Close() }()- nodeA, err := NewSamNode(ctx, SamNodeConfig{+ nodeA, err := NewSamNode(ctx, Options{PrivKey: privA,HubAddrs: nil,Store: storeA,@@ -277,7 +277,7 @@ func TestDatapathIntegration_Unauthenticated(t *testing.T) {}}()- nodeB, err := NewSamNode(ctx, SamNodeConfig{+ nodeB, err := NewSamNode(ctx, Options{PrivKey: privB,HubAddrs: nil,Store: storeB,@@ -396,7 +396,7 @@ func TestStdioDatapathIntegration(t *testing.T) {}defer func() { _ = storeB.Close() }()- nodeA, err := NewSamNode(ctx, SamNodeConfig{+ nodeA, err := NewSamNode(ctx, Options{PrivKey: privA,HubAddrs: nil,Store: storeA,@@ -416,7 +416,7 @@ func TestStdioDatapathIntegration(t *testing.T) {}defer func() { _ = nodeA.Host.Close() }()- nodeB, err := NewSamNode(ctx, SamNodeConfig{+ nodeB, err := NewSamNode(ctx, Options{PrivKey: privB,HubAddrs: nil,Store: storeB,@@ -580,7 +580,7 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {}defer func() { _ = storeB.Close() }()- nodeA, err := NewSamNode(ctx, SamNodeConfig{+ nodeA, err := NewSamNode(ctx, Options{PrivKey: privA,HubAddrs: nil,Store: storeA,@@ -604,7 +604,7 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {}}()- nodeB, err := NewSamNode(ctx, SamNodeConfig{+ nodeB, err := NewSamNode(ctx, Options{PrivKey: privB,HubAddrs: nil,Store: storeB,diff --git a/cmd/sam-node/rate_limiter.go b/internal/node/rate_limiter.gosimilarity index 99%rename from cmd/sam-node/rate_limiter.gorename to internal/node/rate_limiter.goindex 95c0bfb1..8689fe9f 100644--- a/cmd/sam-node/rate_limiter.go+++ b/internal/node/rate_limiter.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("sync"diff --git a/cmd/sam-node/rate_limiter_test.go b/internal/node/rate_limiter_test.gosimilarity index 99%rename from cmd/sam-node/rate_limiter_test.gorename to internal/node/rate_limiter_test.goindex 233809a2..a28fe91e 100644--- a/cmd/sam-node/rate_limiter_test.go+++ b/internal/node/rate_limiter_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("testing"diff --git a/cmd/sam-node/relay_acl_test.go b/internal/node/relay_acl_test.gosimilarity index 99%rename from cmd/sam-node/relay_acl_test.gorename to internal/node/relay_acl_test.goindex 0b33e55c..c9c31107 100644--- a/cmd/sam-node/relay_acl_test.go+++ b/internal/node/relay_acl_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("testing"diff --git a/cmd/sam-node/service.go b/internal/node/service.gosimilarity index 99%rename from cmd/sam-node/service.gorename to internal/node/service.goindex 126b3a3e..47406c83 100644--- a/cmd/sam-node/service.go+++ b/internal/node/service.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/service_registry.go b/internal/node/service_registry.gosimilarity index 99%rename from cmd/sam-node/service_registry.gorename to internal/node/service_registry.goindex f7685579..d79e7eca 100644--- a/cmd/sam-node/service_registry.go+++ b/internal/node/service_registry.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/service_registry_test.go b/internal/node/service_registry_test.gosimilarity index 99%rename from cmd/sam-node/service_registry_test.gorename to internal/node/service_registry_test.goindex 13ffbaca..63c986c6 100644--- a/cmd/sam-node/service_registry_test.go+++ b/internal/node/service_registry_test.go@@ -11,7 +11,7 @@// 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+package nodeimport ("context"diff --git a/cmd/sam-node/service_test.go b/internal/node/service_test.gosimilarity index 99%rename from cmd/sam-node/service_test.gorename to internal/node/service_test.goindex 6a26c1be..d45a6134 100644--- a/cmd/sam-node/service_test.go+++ b/internal/node/service_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"diff --git a/cmd/sam-node/sidecar.go b/internal/node/sidecar.gosimilarity index 98%rename from cmd/sam-node/sidecar.gorename to internal/node/sidecar.goindex 1246e0ed..dedbeaf8 100644--- a/cmd/sam-node/sidecar.go+++ b/internal/node/sidecar.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("context"@@ -36,7 +36,7 @@ import ("google.golang.org/protobuf/encoding/protojson")-func startSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile string) error {+func StartSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile string) error {mux := http.NewServeMux()// Public endpoints@@ -117,7 +117,7 @@ func startSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile streturn nil}-func startUnauthSidecarServer(hubURL, addr, certFile, keyFile string) error {+func StartUnauthSidecarServer(hubURL, addr, certFile, keyFile string) error {mux := http.NewServeMux()// Public endpoints@@ -191,7 +191,7 @@ func withAuth(token string, next http.Handler) http.Handler {logger.Debugf("[SidecarAuth] Incoming request: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)if token == "" {// If token is empty, we assume mTLS is handling authentication.- // startSidecarServer enforces that token is present if mTLS is not used.+ // StartSidecarServer enforces that token is present if mTLS is not used.next.ServeHTTP(w, r)return}diff --git a/cmd/sam-node/sidecar_test.go b/internal/node/sidecar_test.gosimilarity index 98%rename from cmd/sam-node/sidecar_test.gorename to internal/node/sidecar_test.goindex b84c87ff..92387e10 100644--- a/cmd/sam-node/sidecar_test.go+++ b/internal/node/sidecar_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("bytes"@@ -105,7 +105,7 @@ func TestSidecarServerAuthEnforcement(t *testing.T) {token := "test-token"// Start sidecar on an ephemeral port- err := startSidecarServer(node, "127.0.0.1:0", token, "", "", "")+ err := StartSidecarServer(node, "127.0.0.1:0", token, "", "", "")if err != nil {t.Fatalf("Failed to start sidecar server: %v", err)}@@ -524,16 +524,16 @@ func TestStartSidecarServer_TokenMandatory(t *testing.T) {node := &SamNode{BiscuitTimeout: 500 * time.Millisecond}// Test case: No token, no TLS- err := startSidecarServer(node, "127.0.0.1:0", "", "", "", "")+ err := StartSidecarServer(node, "127.0.0.1:0", "", "", "", "")if err == nil {- t.Fatal("Expected startSidecarServer to fail without token and TLS, but it succeeded")+ t.Fatal("Expected StartSidecarServer to fail without token and TLS, but it succeeded")}if !strings.Contains(err.Error(), "token is mandatory when not using mTLS") {t.Fatalf("Expected error to contain 'token is mandatory when not using mTLS', got: %v", err)}// Test case: Token provided, should not fail immediately- err = startSidecarServer(node, "127.0.0.1:0", "some-token", "", "", "")+ err = StartSidecarServer(node, "127.0.0.1:0", "some-token", "", "", "")if err != nil {if strings.Contains(err.Error(), "token is mandatory when not using mTLS") {t.Fatalf("Did not expect 'token is mandatory' error when token is provided, got: %v", err)diff --git a/cmd/sam-node/static_service_test.go b/internal/node/static_service_test.gosimilarity index 94%rename from cmd/sam-node/static_service_test.gorename to internal/node/static_service_test.goindex 28ad55b3..13872c4c 100644--- a/cmd/sam-node/static_service_test.go+++ b/internal/node/static_service_test.go@@ -1,4 +1,4 @@-package main+package nodeimport ("context"@@ -106,7 +106,7 @@ func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {}// 4. Create Node with empty hub addrs initially- node, err := NewSamNode(context.Background(), SamNodeConfig{+ node, err := NewSamNode(context.Background(), Options{PrivKey: priv,HubAddrs: []multiaddr.Multiaddr{},Store: store,@@ -153,11 +153,7 @@ func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {}// 6. Now enroll and connect to hub (which sets up DHT and hub connection)- oldHubAddr := hubAddr- hubAddr = hubURL- defer func() { hubAddr = oldHubAddr }()-- err = node.Enroll(ctx, "dummy-jwt")+ err = node.Enroll(ctx, hubURL, "dummy-jwt")if err != nil {t.Fatalf("failed to enroll: %v", err)}@@ -192,7 +188,7 @@ func TestStaticServiceRegistrationCommandFailure(t *testing.T) {}// 4. Create Node with empty hub addrs initially- node, err := NewSamNode(context.Background(), SamNodeConfig{+ node, err := NewSamNode(context.Background(), Options{PrivKey: priv,HubAddrs: []multiaddr.Multiaddr{},Store: store,@@ -216,12 +212,8 @@ func TestStaticServiceRegistrationCommandFailure(t *testing.T) {}()// 5. Enroll and connect to hub (which sets up DHT and hub connection)- oldHubAddr := hubAddr- hubAddr = hubURL- defer func() { hubAddr = oldHubAddr }()-ctx := context.Background()- err = node.Enroll(ctx, "dummy-jwt")+ err = node.Enroll(ctx, hubURL, "dummy-jwt")if err != nil {t.Fatalf("failed to enroll: %v", err)}diff --git a/cmd/sam-node/stdio_bridge.go b/internal/node/stdio_bridge.gosimilarity index 99%rename from cmd/sam-node/stdio_bridge.gorename to internal/node/stdio_bridge.goindex 4d07eb86..2c2b1337 100644--- a/cmd/sam-node/stdio_bridge.go+++ b/internal/node/stdio_bridge.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("bufio"diff --git a/cmd/sam-node/stdio_bridge_test.go b/internal/node/stdio_bridge_test.gosimilarity index 99%rename from cmd/sam-node/stdio_bridge_test.gorename to internal/node/stdio_bridge_test.goindex 5fca8289..67bcab03 100644--- a/cmd/sam-node/stdio_bridge_test.go+++ b/internal/node/stdio_bridge_test.go@@ -5,7 +5,7 @@// You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0-package main+package nodeimport ("bytes"diff --git a/cmd/sam-node/store.go b/internal/node/store.gosimilarity index 99%rename from cmd/sam-node/store.gorename to internal/node/store.goindex a5e631bc..0da700e1 100644--- a/cmd/sam-node/store.go+++ b/internal/node/store.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("encoding/json"diff --git a/cmd/sam-node/store_test.go b/internal/node/store_test.gosimilarity index 99%rename from cmd/sam-node/store_test.gorename to internal/node/store_test.goindex 16447c50..1c2ae213 100644--- a/cmd/sam-node/store_test.go+++ b/internal/node/store_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package main+package nodeimport ("bytes"