Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sam-one: fleet knobs, file/env-only secrets, shared token wire type
Antonio Ojea4e03a339494a
diff --git a/.gemini/styleguide.md b/.gemini/styleguide.mdindex 10549df9..371dc5ca 100644--- a/.gemini/styleguide.md+++ b/.gemini/styleguide.md@@ -179,11 +179,48 @@ explicitly agreed to. If the dependency only runs inside a sandbox image, itbelongs in that command's own module (`cmd/nano-init/go.mod` pattern). Flagany new root dependency that lacks this justification.-## 5. Review output+## 5. API surfaces and secrets++### Why++SAM has two API surfaces with different encodings (`AGENTS.md` §1, "Two API+surfaces"): the mesh protocol between components is protobuf from+`api/sam.proto`; the operator plane (`/admin/*`, `/users/*`) is JSON whose+shapes are Go structs in `api/`. Shapes defined ad hoc inside a handler, or+borrowed from `internal/storage`, have no single owner: the console, the CLI+and the tests each re-spell the field names, and a rename breaks one of them+silently. Secrets passed as flag values leak through `ps` and shell history+regardless of how carefully the rest of the system handles them.++### Rules++1. **Flag wire shapes defined outside `api/`.** In a handler, `var req struct+ { ... json:"..." }`, `json.NewEncoder(w).Encode(map[string]any{...})`, or a+ client building `map[string]any{"ttl_hours": ...}` is a request for+ change: name the `api.*Request` / `api.*Response` type that should exist+ (or the proto message, if a mesh component consumes it).+2. **Flag internal types on the wire.** `json.NewEncoder(w).Encode(list)`+ where `list` is `[]*storage.X`, or a `cmd/` / `internal/console` package+ importing `internal/storage` to decode a response, serializes storage+ details (hashes, timestamps, column-shaped names) as an API. Propose an+ `api.XInfo` type and quote the fields that must not cross.+3. **Flag the wrong encoding for the surface.** A new mesh-protocol message+ as JSON, or a new operator endpoint that only the console will call as+ protobuf, needs a stated reason. The tell for "mesh protocol" is a+ consumer in `internal/node`, `internal/router`, `internal/sambox` or the+ FFI.+4. **Flag secrets as flag values.** Any `Flags().StringVar(&x, "...token"|+ "...secret"|"...password", ...)` whose value is the credential itself,+ rather than a `--*-path` or an env var name, is a finding; so is a+ banner or log line that prints a credential the operator supplied.+ `sam-control-plane --admin-token-path` and `sam-node+ --bootstrap-token-path` are the reference shape.++## 6. Review output- Group findings by the section numbers above so the author can see whichrule applies.-- For rule 1 and rule 2 findings, always propose the corrected code, not+- For rule 1, rule 2 and rule 5 findings, always propose the corrected code, notjust the diagnosis.- Do not raise generic Go style nits (naming, comment punctuation, importordering) that `gofmt` and `golangci-lint` already enforce via `make lint`.diff --git a/AGENTS.md b/AGENTS.mdindex 14492bd9..685397c6 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -5,6 +5,8 @@ You are an expert software engineering assistant helping to develop, maintain, a## 1. Architecture & Component Independence* **Decoupled Architecture:** The `sam-control-plane`, `sam-router` and `sam-node` components are strictly independent. They must not share internal state or tightly couple their logic.* **API Communication:** All data communication between `sam-control-plane`, `sam-router` and `sam-node` must happen exclusively via the common API defined in `api/sam.proto`.+* **Two API surfaces, two encodings:** the *mesh protocol* — anything a mesh component speaks (node, router, `sam-box`, the agent connector): enrollment, refresh, keys, leases, auth streams, policy sync — is protobuf from `api/sam.proto` (`application/x-protobuf`). The *operator plane* — what humans, the web console and admin CLIs call (`/admin/*`, `/users/*`) — is JSON, with its request and response types declared as Go structs in `api/` (e.g. `api.BootstrapTokenRequest`). Never define a wire shape as an anonymous struct or `map[string]any` inside a handler, and never serialize an `internal/storage` (or any other internal) type onto either surface; clients in `cmd/` and `internal/console` import `api/` only. A message that a mesh component consumes goes in the proto even if a console also reads it.+* **Secrets never travel as flag values:** binaries read credentials from a file (`--*-path`) or the environment, never from a command-line argument that would sit in `ps` output and shell history. Banners and logs name the source of an operator-supplied secret instead of echoing it.* **Sandbox Dataplane:** `sam-box` (one per sandbox) is the single egress policy enforcement point. It holds no libp2p host, no enrollment and no mesh identity, and reaches the mesh exclusively as a client of the local `sam-node` sidecar socket. `nano-init` (PID 1 inside the guest, its own Go module) owns the guest side; its datapath is the `tun2connect` library. The sandbox boundary is a Unix socket speaking named HTTP tunnels: CONNECT (TCP) and connect-udp (UDP) out, `CONNECT <port>` back in. The authoritative design is `site/content/docs/agent-architecture.md`; do not contradict it.* **Enforcement over Convention:** never gate sandbox traffic on the agent's cooperation — no proxy environment variables, no `LD_PRELOAD` shims, no DNS spoofing. The agent harness stays unmodified and mesh-unaware; confinement is a route and a socket, built by the userspace launcher (`nano-init`) and judged in `sam-box`. An agent that must cooperate with its own confinement is not confined.* **Policy on Names:** egress policy, secret injection and routing decisions are made on the destination *name*, never on an IP. Deny by default.diff --git a/api/bootstrap_token.go b/api/bootstrap_token.gonew file mode 100644index 00000000..03b05a87--- /dev/null+++ b/api/bootstrap_token.go@@ -0,0 +1,55 @@+// 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 api++// BootstrapTokenRequest is the JSON body that mints a bootstrap token, on+// POST /admin/bootstrap-tokens (admin bearer) and POST /users/me/tokens+// (OIDC user). It is the one definition both the control plane and its+// clients (sam-one's CLI, the console) marshal, so a field name exists in+// exactly one place.+type BootstrapTokenRequest struct {+ // Role the token enrolls into, e.g. RoleNode. Required on the admin+ // endpoint; the user endpoint defaults it to RoleNode.+ Role string `json:"role"`+ // OwnerID is the user the token is issued on behalf of. Honored by the+ // user endpoint only, and only for admins; defaults to the caller.+ OwnerID string `json:"owner_id,omitempty"`+ // TTLHours bounds the token's validity; the control plane defaults a+ // non-positive value to 24.+ TTLHours int `json:"ttl_hours"`+ // MaxUsages is how many enrollments the token admits; the control plane+ // defaults a non-positive value to 1.+ MaxUsages int `json:"max_usages"`+ // Description is a free-form operator note stored with the token.+ Description string `json:"description,omitempty"`+ // AutonomousRecovery is copied onto every node the token enrolls: such a+ // node may still refresh its credential after the control plane's+ // signing key rotated past its grace period, on proof of possession of+ // its own key alone. Admin-only, because a node that can always recover+ // holds a credential that never expires (see+ // storage.EnrolledNode.AutonomousRecovery).+ AutonomousRecovery bool `json:"autonomous_recovery"`+}++// BootstrapTokenResponse is returned (201) when a bootstrap token is minted.+// Token is the plaintext and is shown exactly once; the control plane keeps+// only its hash, which is also the ID.+type BootstrapTokenResponse struct {+ ID string `json:"id"`+ Token string `json:"token"`+ Role string `json:"role"`+ OwnerID string `json:"owner_id,omitempty"`+ ExpiresAt string `json:"expires_at"`+}diff --git a/cmd/sam-one/admin.go b/cmd/sam-one/admin.goindex bd112c90..b1f13ed5 100644--- a/cmd/sam-one/admin.go+++ b/cmd/sam-one/admin.go@@ -20,7 +20,6 @@ import ("fmt""io""net/http"- "os""strings""text/tabwriter""time"@@ -40,18 +39,18 @@ type adminClient struct {token string}-// resolveAdminToken picks the admin credential: explicit flag, then the-// SAM_ADMIN_TOKEN env, then the token persisted in data-dir by a previous run.-func resolveAdminToken(flagVal, dataDir string) (string, error) {- if flagVal != "" {- return flagVal, nil- }- if env := os.Getenv("SAM_ADMIN_TOKEN"); env != "" {- return env, nil+// resolveAdminToken picks the admin credential: a file named by the flag,+// then the SAM_ADMIN_TOKEN env, then the token persisted in data-dir by a+// previous run. The value itself is never a flag argument.+func resolveAdminToken(tokenPath, dataDir string) (string, error) {+ if tok, err := secretFromPathOrEnv(tokenPath, "SAM_ADMIN_TOKEN"); err != nil {+ return "", fmt.Errorf("invalid --admin-token-path: %w", err)+ } else if tok != "" {+ return tok, nil}tok, err := standalone.AdminTokenFromDataDir(dataDir)if err != nil {- return "", fmt.Errorf("no admin token: pass --admin-token, set SAM_ADMIN_TOKEN, or point --data-dir at a sam-one data directory (%v)", err)+ return "", fmt.Errorf("no admin token: pass --admin-token-path, set SAM_ADMIN_TOKEN, or point --data-dir at a sam-one data directory (%v)", err)}return tok, nil}@@ -80,19 +79,18 @@ func (c *adminClient) do(method, path, contentType string, body []byte) ([]byte,return respBody, nil}-type createdToken struct {- ID string `json:"id"`- Token string `json:"token"`- Role string `json:"role"`- ExpiresAt string `json:"expires_at"`-}--func (c *adminClient) createToken(role string, ttlHours, maxUsages int, description string) (*createdToken, error) {- payload, err := json.Marshal(map[string]any{- "role": role,- "ttl_hours": ttlHours,- "max_usages": maxUsages,- "description": description,+// createToken mints a bootstrap token. autonomousRecovery is copied onto+// every node the token enrolls: such a node may still /refresh after the+// control plane's signing key rotated past its grace period, which is what+// a device that spends days offline needs and what a stolen device should+// not get.+func (c *adminClient) createToken(role string, ttlHours, maxUsages int, description string, autonomousRecovery bool) (*api.BootstrapTokenResponse, error) {+ payload, err := json.Marshal(api.BootstrapTokenRequest{+ Role: role,+ TTLHours: ttlHours,+ MaxUsages: maxUsages,+ Description: description,+ AutonomousRecovery: autonomousRecovery,})if err != nil {return nil, err@@ -101,7 +99,7 @@ func (c *adminClient) createToken(role string, ttlHours, maxUsages int, descriptif err != nil {return nil, err}- var created createdToken+ var created api.BootstrapTokenResponseif err := json.Unmarshal(body, &created); err != nil {return nil, fmt.Errorf("failed to decode response %q: %w", body, err)}@@ -167,11 +165,11 @@ func (c *adminClient) resolveTokenID(idOrPrefix string) (string, error) {// newAdminSubcommands wires the token and admin command trees onto root.func newAdminSubcommands() []*cobra.Command {var (- server string- adminToken string- dataDir string- clientFactory = func() (*adminClient, error) {- tok, err := resolveAdminToken(adminToken, dataDir)+ server string+ adminTokenPath string+ dataDir string+ clientFactory = func() (*adminClient, error) {+ tok, err := resolveAdminToken(adminTokenPath, dataDir)if err != nil {return nil, err}@@ -185,15 +183,16 @@ func newAdminSubcommands() []*cobra.Command {addSharedFlags := func(cmd *cobra.Command) {cmd.PersistentFlags().StringVar(&server, "server", "http://127.0.0.1:8080", "Base URL of the running sam-one server")- cmd.PersistentFlags().StringVar(&adminToken, "admin-token", "", "Admin API bearer token (or env SAM_ADMIN_TOKEN, or read from --data-dir)")+ cmd.PersistentFlags().StringVar(&adminTokenPath, "admin-token-path", "", "File containing the admin API bearer token (or env SAM_ADMIN_TOKEN, or read from --data-dir)")cmd.PersistentFlags().StringVar(&dataDir, "data-dir", ".", "sam-one data directory holding the persisted admin token")}var (- role string- ttlHours int- maxUsages int- description string+ role string+ ttlHours int+ maxUsages int+ description string+ autonomousRecovery bool)tokenCreate := &cobra.Command{Use: "create",@@ -203,7 +202,7 @@ func newAdminSubcommands() []*cobra.Command {if err != nil {return err}- created, err := c.createToken(role, ttlHours, maxUsages, description)+ created, err := c.createToken(role, ttlHours, maxUsages, description, autonomousRecovery)if err != nil {return err}@@ -218,6 +217,7 @@ func newAdminSubcommands() []*cobra.Command {tokenCreate.Flags().IntVar(&ttlHours, "ttl-hours", 24, "Token validity in hours")tokenCreate.Flags().IntVar(&maxUsages, "max-usages", 1, "How many enrollments the token allows")tokenCreate.Flags().StringVar(&description, "description", "", "Free-form note stored with the token")+ tokenCreate.Flags().BoolVar(&autonomousRecovery, "autonomous-recovery", false, autonomousRecoveryHelp)tokenList := &cobra.Command{Use: "list",@@ -311,15 +311,19 @@ func tokenStatus(tok *storage.BootstrapToken, now time.Time) string {}}+// autonomousRecoveryHelp is shared by every command that mints tokens.+const autonomousRecoveryHelp = "Let enrolled devices renew even after the signing key rotated past its grace period (devices that stay offline for days); a lost device then keeps renewing until banned"+// newTokenQRCommand mints a node token and renders it, with the URL devices// must enroll against, as a terminal QR code. server points at the shared// --server flag so the QR defaults to the URL the admin used.func newTokenQRCommand(clientFactory func() (*adminClient, error), server *string) *cobra.Command {var (- enrollURL string- ttlHours int- maxUsages int- description string+ enrollURL string+ ttlHours int+ maxUsages int+ description string+ autonomousRecovery bool)cmd := &cobra.Command{Use: "qr",@@ -350,7 +354,7 @@ func newTokenQRCommand(clientFactory func() (*adminClient, error), server *strinif description == "" {description = "device enrollment via " + target}- created, err := c.createToken(api.RoleNode, ttlHours, maxUsages, description)+ created, err := c.createToken(api.RoleNode, ttlHours, maxUsages, description, autonomousRecovery)if err != nil {return err}@@ -361,5 +365,6 @@ func newTokenQRCommand(clientFactory func() (*adminClient, error), server *strincmd.Flags().IntVar(&ttlHours, "ttl-hours", 1, "Token validity in hours")cmd.Flags().IntVar(&maxUsages, "max-usages", 1, "How many devices may enroll with this code")cmd.Flags().StringVar(&description, "description", "", "Free-form note stored with the token")+ cmd.Flags().BoolVar(&autonomousRecovery, "autonomous-recovery", false, autonomousRecoveryHelp)return cmd}diff --git a/cmd/sam-one/admin_test.go b/cmd/sam-one/admin_test.goindex 51262baf..09229a51 100644--- a/cmd/sam-one/admin_test.go+++ b/cmd/sam-one/admin_test.go@@ -16,6 +16,7 @@ package mainimport ("encoding/json"+ "fmt""io""net/http""net/http/httptest"@@ -40,17 +41,23 @@ func newFakeAdminAPI(t *testing.T) *httptest.Server {}switch r.Method {case http.MethodPost:- var req map[string]any+ // Decode into the shared wire type, as the control plane does, so a+ // client that drifts from it fails here.+ var req api.BootstrapTokenRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {http.Error(w, "bad body", http.StatusBadRequest)return}+ if !req.AutonomousRecovery || req.MaxUsages != 1 || req.TTLHours != 24 || req.Description != "note" {+ http.Error(w, fmt.Sprintf("unexpected request %+v", req), http.StatusBadRequest)+ return+ }w.WriteHeader(http.StatusCreated)- _ = json.NewEncoder(w).Encode(map[string]any{- "id": "abcdef123456",- "token": "sam-bt-fresh",- "role": req["role"],- "expires_at": "2026-12-31T00:00:00Z",+ _ = json.NewEncoder(w).Encode(api.BootstrapTokenResponse{+ ID: "abcdef123456",+ Token: "sam-bt-fresh",+ Role: req.Role,+ ExpiresAt: "2026-12-31T00:00:00Z",})case http.MethodGet:_ = json.NewEncoder(w).Encode([]storage.BootstrapToken{{@@ -98,7 +105,7 @@ func TestAdminClient(t *testing.T) {ts := newFakeAdminAPI(t)c := &adminClient{client: ts.Client(), server: ts.URL, token: "adm-tok"}- created, err := c.createToken(api.RoleNode, 24, 1, "note")+ created, err := c.createToken(api.RoleNode, 24, 1, "note", true)if err != nil {t.Fatalf("createToken failed: %v", err)}@@ -138,6 +145,10 @@ func TestResolveAdminToken(t *testing.T) {if err := os.WriteFile(filepath.Join(dir, "admin-token"), []byte("sam_adm_file\n"), 0o600); err != nil {t.Fatalf("failed to write token file: %v", err)}+ explicit := filepath.Join(t.TempDir(), "my-admin-token")+ if err := os.WriteFile(explicit, []byte(" sam_adm_explicit\n"), 0o600); err != nil {+ t.Fatalf("failed to write explicit token file: %v", err)+ }t.Setenv("SAM_ADMIN_TOKEN", "")if got, err := resolveAdminToken("", dir); err != nil || got != "sam_adm_file" {@@ -148,8 +159,18 @@ func TestResolveAdminToken(t *testing.T) {if got, err := resolveAdminToken("", dir); err != nil || got != "sam_adm_env" {t.Errorf("env precedence = %q, %v; want sam_adm_env", got, err)}- if got, err := resolveAdminToken("sam_adm_flag", dir); err != nil || got != "sam_adm_flag" {- t.Errorf("flag precedence = %q, %v; want sam_adm_flag", got, err)+ if got, err := resolveAdminToken(explicit, dir); err != nil || got != "sam_adm_explicit" {+ t.Errorf("--admin-token-path precedence = %q, %v; want sam_adm_explicit (trimmed)", got, err)+ }++ // A path that is set but unusable must not fall through to env or data-dir.+ if _, err := resolveAdminToken(filepath.Join(t.TempDir(), "missing"), dir); err == nil {+ t.Error("expected an error for a missing --admin-token-path")+ }+ empty := filepath.Join(t.TempDir(), "empty")+ _ = os.WriteFile(empty, []byte("\n"), 0o600)+ if _, err := resolveAdminToken(empty, dir); err == nil {+ t.Error("expected an error for an empty --admin-token-path")}t.Setenv("SAM_ADMIN_TOKEN", "")diff --git a/cmd/sam-one/main.go b/cmd/sam-one/main.goindex ee56163d..40e742b0 100644--- a/cmd/sam-one/main.go+++ b/cmd/sam-one/main.go@@ -46,8 +46,9 @@ func main() {dataDir stringdbDriver stringdbDSN string- joinToken string- adminToken string+ joinTokenPath string+ noJoinToken bool+ adminTokenPath stringpolicyFile stringoidcIssuer stringoidcClientID string@@ -77,13 +78,16 @@ func main() {}}- // Env fallbacks keep single-container platforms (Cloud Run)- // configurable without flags.- if joinToken == "" {- joinToken = os.Getenv("SAM_TOKEN")+ // Secrets arrive through a file or the environment, never as a+ // flag value that would sit in `ps` and shell history. Env keeps+ // single-container platforms (Cloud Run) configurable.+ joinToken, err := secretFromPathOrEnv(joinTokenPath, "SAM_TOKEN")+ if err != nil {+ logger.Fatalf("Invalid --token-path: %v", err)}- if adminToken == "" {- adminToken = os.Getenv("SAM_ADMIN_TOKEN")+ adminToken, err := secretFromPathOrEnv(adminTokenPath, "SAM_ADMIN_TOKEN")+ if err != nil {+ logger.Fatalf("Invalid --admin-token-path: %v", err)}if externalURL == "" {externalURL = os.Getenv("SAM_EXTERNAL_URL")@@ -134,6 +138,7 @@ func main() {DBDriver: dbDriver,DBDSN: dbDSN,JoinToken: joinToken,+ DisableJoinToken: noJoinToken,AdminToken: adminToken,PolicyFile: policyFile,OIDCIssuer: oidcIssuer,@@ -154,7 +159,7 @@ func main() {}}()- printBanner(srv, tun)+ printBanner(srv, tun, bannerSecrets{adminSupplied: adminToken != "", joinSupplied: joinToken != ""})if enrollQR {if err := printBootEnrollQR(cmd.Context(), srv, enrollQRMaxUsages); err != nil {logger.Errorf("Device enrollment QR: %v", err)@@ -179,8 +184,9 @@ func main() {rootCmd.Flags().StringVar(&dataDir, "data-dir", ".", "Directory for the database, router key and generated tokens")rootCmd.Flags().StringVar(&dbDriver, "db-driver", "sqlite", "Database driver (sqlite or postgres)")rootCmd.Flags().StringVar(&dbDSN, "db-dsn", "", "Database DSN (default <data-dir>/sam.db for sqlite)")- rootCmd.Flags().StringVar(&joinToken, "token", "", "Cluster join token (or env SAM_TOKEN; auto-generated if empty)")- rootCmd.Flags().StringVar(&adminToken, "admin-token", "", "Admin API bearer token (or env SAM_ADMIN_TOKEN; auto-generated if empty)")+ rootCmd.Flags().StringVar(&joinTokenPath, "token-path", "", "File containing the cluster join token (or env SAM_TOKEN; auto-generated and persisted in --data-dir if neither is set)")+ rootCmd.Flags().BoolVar(&noJoinToken, "no-join-token", false, "Run without a standing join token; devices enroll only with minted bootstrap tokens (token create/qr) or OIDC")+ rootCmd.Flags().StringVar(&adminTokenPath, "admin-token-path", "", "File containing the admin API bearer token (or env SAM_ADMIN_TOKEN; auto-generated and persisted in --data-dir if neither is set)")rootCmd.Flags().StringVar(&policyFile, "policy-file", "", "Path to a protojson PolicyConfigUpdateRequest seeding the mesh policy on first boot only")rootCmd.Flags().StringVar(&oidcIssuer, "issuer", "", "Optional external OIDC issuer URL (comma-separated)")rootCmd.Flags().StringVar(&oidcClientID, "oidc-client-id", "", "OAuth client id advertised via /info (defaults to the first allowed audience)")@@ -219,8 +225,21 @@ func main() {}}-func printBanner(srv *standalone.Server, tun tunnel.Tunnel) {+// bannerSecrets records which credentials the operator supplied (flag or+// env). Those are theirs already and stdout is often a log pipeline, so the+// banner names the source instead of echoing the value; tokens sam-one+// generated itself are shown, since this is where the operator learns them.+type bannerSecrets struct {+ adminSupplied bool+ joinSupplied bool+}++func printBanner(srv *standalone.Server, tun tunnel.Tunnel, secrets bannerSecrets) {base := srv.PublicURL()+ adminShown := srv.AdminToken()+ if secrets.adminSupplied {+ adminShown = "(supplied via --admin-token-path / SAM_ADMIN_TOKEN)"+ }fmt.Println("══════════════════════════════════════════════════════════════════")fmt.Println("SAM standalone mesh is ready!")fmt.Println()@@ -230,11 +249,23 @@ func printBanner(srv *standalone.Server, tun tunnel.Tunnel) {}fmt.Printf("Web Console: %s/console\n", base)fmt.Printf("Router Peer: %s\n", srv.PeerID())- fmt.Printf("Admin Token: %s\n", srv.AdminToken())- fmt.Printf("Join Token: %s\n", srv.JoinToken())- fmt.Println()- fmt.Println("To enroll a node:")- fmt.Printf(" sam-node join %s --bootstrap-token %s\n", base, srv.JoinToken())+ fmt.Printf("Admin Token: %s\n", adminShown)+ switch {+ case srv.JoinToken() == "":+ fmt.Println("Join Token: disabled (--no-join-token); enroll devices with `sam-one token qr` / `token create` or OIDC")+ case secrets.joinSupplied:+ fmt.Println("Join Token: (supplied via --token-path / SAM_TOKEN)")+ fmt.Println()+ fmt.Println("To enroll a node:")+ fmt.Printf(" sam-node join %s --bootstrap-token-path <file with the join token>\n", base)+ default:+ fmt.Printf("Join Token: %s\n", srv.JoinToken())+ fmt.Println()+ fmt.Println("To enroll a node:")+ // The token is persisted next to the database; a file beats a value+ // in the shell history, like sam-node's own help recommends.+ fmt.Printf(" sam-node join %s --bootstrap-token-path %s\n", base, srv.JoinTokenPath())+ }fmt.Println("══════════════════════════════════════════════════════════════════")}@@ -327,3 +358,21 @@ func freePort(host string) (int, error) {defer func() { _ = l.Close() }()return l.Addr().(*net.TCPAddr).Port, nil}++// secretFromPathOrEnv reads a credential from path when given, else from+// the named environment variable; "" means neither was set. A path that is+// set but unreadable or empty is an error, not a silent fallback.+func secretFromPathOrEnv(path, env string) (string, error) {+ if path != "" {+ data, err := os.ReadFile(path)+ if err != nil {+ return "", err+ }+ secret := strings.TrimSpace(string(data))+ if secret == "" {+ return "", fmt.Errorf("%s is empty", path)+ }+ return secret, nil+ }+ return strings.TrimSpace(os.Getenv(env)), nil+}diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex b136959d..6f7dd9e3 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -1828,16 +1828,7 @@ func (s *Server) HandleAdminBootstrapTokens(w http.ResponseWriter, r *http.Requereturn}- var req struct {- Role string `json:"role"`- TTLHours int `json:"ttl_hours"`- MaxUsages int `json:"max_usages"`- Description string `json:"description"`- // Copied onto every node this token enrolls; see- // storage.EnrolledNode.AutonomousRecovery.- AutonomousRecovery bool `json:"autonomous_recovery"`- }-+ var req api.BootstrapTokenRequestr.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)if err := json.NewDecoder(r.Body).Decode(&req); err != nil {http.Error(w, "Invalid JSON body", http.StatusBadRequest)@@ -1886,11 +1877,11 @@ func (s *Server) HandleAdminBootstrapTokens(w http.ResponseWriter, r *http.Requew.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusCreated)- _ = json.NewEncoder(w).Encode(map[string]any{- "id": tokenRecord.ID,- "token": tokenVal,- "role": tokenRecord.Role,- "expires_at": tokenRecord.ExpiresAt.Format(time.RFC3339),+ _ = json.NewEncoder(w).Encode(api.BootstrapTokenResponse{+ ID: tokenRecord.ID,+ Token: tokenVal,+ Role: tokenRecord.Role,+ ExpiresAt: tokenRecord.ExpiresAt.Format(time.RFC3339),})}@@ -2540,18 +2531,9 @@ func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.Requesreturn}- var req struct {- Role string `json:"role"`- OwnerID string `json:"owner_id"`- TTLHours int `json:"ttl_hours"`- MaxUsages int `json:"max_usages"`- Description string `json:"description"`- // Copied onto every node this token enrolls; see- // storage.EnrolledNode.AutonomousRecovery. Admin-only: it decides- // whether a lost device can rejoin the mesh on its own.- AutonomousRecovery bool `json:"autonomous_recovery"`- }-+ // AutonomousRecovery is admin-only here: it decides whether a lost device+ // can rejoin the mesh on its own.+ var req api.BootstrapTokenRequestr.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)if err := json.NewDecoder(r.Body).Decode(&req); err != nil {http.Error(w, "Invalid JSON body", http.StatusBadRequest)@@ -2624,12 +2606,12 @@ func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.Requesw.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusCreated)- _ = json.NewEncoder(w).Encode(map[string]any{- "id": tokenRecord.ID,- "token": tokenVal,- "role": tokenRecord.Role,- "owner_id": tokenRecord.OwnerID,- "expires_at": tokenRecord.ExpiresAt.Format(time.RFC3339),+ _ = json.NewEncoder(w).Encode(api.BootstrapTokenResponse{+ ID: tokenRecord.ID,+ Token: tokenVal,+ Role: tokenRecord.Role,+ OwnerID: tokenRecord.OwnerID,+ ExpiresAt: tokenRecord.ExpiresAt.Format(time.RFC3339),})}diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.goindex 07c729b9..aeb51e04 100644--- a/internal/standalone/standalone.go+++ b/internal/standalone/standalone.go@@ -93,6 +93,11 @@ type Options struct {// JoinToken is the cluster join token; auto-generated and persisted in// DataDir when empty.JoinToken string+ // DisableJoinToken runs without any standing join token: devices then+ // enroll only with explicitly minted bootstrap tokens or through OIDC.+ // The right setting for a fleet; the default keeps `sam-node join` on a+ // laptop zero-config.+ DisableJoinToken bool// AdminToken protects the admin REST API; auto-generated and persisted in// DataDir when empty.AdminToken string@@ -179,6 +184,9 @@ func (o *Options) Validate() error {if _, err := wsListenMultiaddr(o.BindAddress); err != nil {return fmt.Errorf("invalid bind address %q: %w", o.BindAddress, err)}+ if o.DisableJoinToken && o.JoinToken != "" {+ return fmt.Errorf("a join token was supplied together with DisableJoinToken")+ }if o.ExternalURL != "" {if _, err := externalMultiaddr(o.ExternalURL); err != nil {return fmt.Errorf("invalid external URL %q: %w", o.ExternalURL, err)@@ -268,14 +276,16 @@ func (s *Server) Start(ctx context.Context) error {return err}- s.joinToken = s.opts.JoinToken- if s.joinToken == "" {- if s.joinToken, err = loadOrCreateTokenFile(filepath.Join(s.opts.DataDir, joinTokenFile), joinTokenPrefix); err != nil {- return fmt.Errorf("failed to provision join token: %w", err)+ if !s.opts.DisableJoinToken {+ s.joinToken = s.opts.JoinToken+ if s.joinToken == "" {+ if s.joinToken, err = loadOrCreateTokenFile(filepath.Join(s.opts.DataDir, joinTokenFile), joinTokenPrefix); err != nil {+ return fmt.Errorf("failed to provision join token: %w", err)+ }+ }+ if err := s.ensureBootstrapToken(ctx, s.joinToken, api.RoleNode, joinTokenMaxUsages, joinTokenTTL, "sam-one join token"); err != nil {+ return fmt.Errorf("failed to register join token: %w", err)}- }- if err := s.ensureBootstrapToken(ctx, s.joinToken, api.RoleNode, joinTokenMaxUsages, joinTokenTTL, "sam-one join token"); err != nil {- return fmt.Errorf("failed to register join token: %w", err)}// Per-boot single-use credential for the embedded router's stock@@ -393,9 +403,14 @@ func (s *Server) PublicURL() string {// AdminToken returns the resolved admin API token.func (s *Server) AdminToken() string { return s.adminToken }-// JoinToken returns the resolved cluster join token.+// JoinToken returns the resolved cluster join token, or "" when the server+// runs with DisableJoinToken.func (s *Server) JoinToken() string { return s.joinToken }+// JoinTokenPath is where an auto-generated join token is persisted, for+// `sam-node join --bootstrap-token-path`.+func (s *Server) JoinTokenPath() string { return filepath.Join(s.opts.DataDir, joinTokenFile) }+// PeerID returns the embedded router's peer ID.func (s *Server) PeerID() string { return s.router.Host.ID().String() }diff --git a/site/content/docs/user/cloud-run-deployment.md b/site/content/docs/user/cloud-run-deployment.mdindex 3c041298..cb7b20ee 100644--- a/site/content/docs/user/cloud-run-deployment.md+++ b/site/content/docs/user/cloud-run-deployment.md@@ -151,7 +151,9 @@ provider starts for propagation on first call.## 6. Operate with the CLI-The `sam-one` binary doubles as an admin client for the running service:+The `sam-one` binary doubles as an admin client for the running service.+It reads the admin credential from `SAM_ADMIN_TOKEN` or a file named by+`--admin-token-path`, never from a flag value:```bashexport SAM_ADMIN_TOKEN="$ADMIN_TOKEN"diff --git a/site/content/docs/user/device-enrollment.md b/site/content/docs/user/device-enrollment.mdindex ebaa91d8..3e994c9f 100644--- a/site/content/docs/user/device-enrollment.md+++ b/site/content/docs/user/device-enrollment.md@@ -90,6 +90,7 @@ For more devices, or on a non-interactive deployment, mint a code on demandwith the admin CLI:```bash+# Admin credential: env, or --admin-token-path <file>; never a flag value.export SAM_ADMIN_TOKEN=... # from the banner, or <data-dir>/admin-tokensam-one token qr --server https://brave-otter-quick-1234.trycloudflare.com```@@ -171,3 +172,58 @@ and changing labels means unenrolling and scanning a new code.pin a token to a hostname: a token is valid at whatever URL the samecontrol plane answers on. Treat the printed line like the join token —it is a credential until it is spent or expires.++## From demo to fleet++`sam-one` is the same control plane, router and store as the split+deployment in one process, so a device enrolled through a QR code gets the+production credential lifecycle: a Biscuit bound to its own key, renewed+through `POST /refresh` with a signed challenge well before its 24 h+expiry, verified against rotating signing keys, revocable with+`sam-one admin ban`. The mobile app runs the same renewal loop as+`sam-node`. What separates a demo from a fleet is configuration:++* **Drop the standing join token.** The auto-generated join token is a+ ten-year, unlimited-use secret meant for `sam-node join` on a laptop.+ Run with `--no-join-token`; devices then enroll only with tokens you+ mint (`token qr`, `token create`) or through OIDC.+* **Seed a real policy.** Without `--policy-file` the first boot installs+ an open development policy (any enrolled node may declare any label and+ register any service) and says so in the log. Use+ `--control-plane-manual-enrollment` if each device should be approved in+ the console before it gets a credential.+* **Pass secrets, don't read them off the screen.** Secrets are only ever+ read from a file (`--admin-token-path`, `--token-path`) or the environment+ (`SAM_ADMIN_TOKEN`, `SAM_TOKEN`); there is deliberately no flag that takes+ the value, so it never lands in `ps` output or shell history. When you+ supply them, the banner names the source instead of echoing the value into+ your logs. `--enroll-qr=false` keeps startup codes out of non-interactive+ logs.+* **Give the mesh a stable https name.** A quick tunnel changes hostname on+ every start, and enrolled devices remember the URL they enrolled at —+ fine for an afternoon, fatal for a fleet. Use Cloud Run, a named tunnel+ on your own domain, or a reverse proxy with `--external-url`.+* **Decide what happens to devices that go dark.** The signing key rotates+ every 24 h and stays valid for verification for a 1 h grace period. A+ device that renews inside that window is fine indefinitely; one that+ comes back later holds a Biscuit no current key can verify, and+ `/refresh` refuses it — the node exits rather than run unverified. Two+ knobs, and they are a trade-off:+ * Mint its token with `--autonomous-recovery`. The device may then+ recover on proof of possession of its key alone, whenever it returns.+ The cost is that a lost device keeps renewing until you ban it.+ * Or widen the window for everyone with+ `--control-plane-key-grace-period` (e.g. `168h` for a weekly check-in+ cadence). The cost is that a stolen credential also lives that long.+ Toggle recovery per device later from the console+ (`POST /admin/nodes/{peer-id}/autonomous-recovery`).+* **Keep the data directory.** `router.key` is the mesh's identity;+ `sam.db` holds enrollments, tokens and policy. Back it up, or point+ `--db-driver postgres` at a managed database. `sam-one` is a singleton by+ design; when you need more than one control plane, move to the split+ components with the Helm chart.++Want OIDC instead of tokens? Give `sam-one` an issuer (`--issuer`,+`--allowed-audiences`, `--oidc-client-id`) and the app's **Login & Enroll**+and **Device Login** flows work unchanged, as does signing in to the+console as an OIDC admin.diff --git a/tests/integration/standalone_test.go b/tests/integration/standalone_test.goindex e6b8f676..c859bff0 100644--- a/tests/integration/standalone_test.go+++ b/tests/integration/standalone_test.go@@ -161,6 +161,61 @@ func TestStandaloneNodeJoin(t *testing.T) {})}+// TestStandaloneNoJoinToken pins the fleet configuration: no standing join+// token exists anywhere (not in the store, not on disk), the embedded+// router still enrolls with its per-boot token, and devices join only with+// explicitly minted tokens.+func TestStandaloneNoJoinToken(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ if _, err := standalone.New(standalone.Options{BindAddress: "127.0.0.1:0", DataDir: t.TempDir(), DisableJoinToken: true, JoinToken: "sam_tok_x"}); err == nil {+ t.Fatal("DisableJoinToken together with an explicit JoinToken must be rejected")+ }++ dataDir := t.TempDir()+ srv, err := standalone.New(standalone.Options{BindAddress: "127.0.0.1:0", DataDir: dataDir, DisableJoinToken: true})+ if err != nil {+ t.Fatalf("failed to create standalone server: %v", err)+ }+ if err := srv.Start(ctx); err != nil {+ t.Fatalf("failed to start standalone server: %v", err)+ }+ t.Cleanup(func() { _ = srv.Close() })+ if srv.JoinToken() != "" {+ t.Fatalf("JoinToken() = %q, want empty", srv.JoinToken())+ }+ if _, err := os.Stat(filepath.Join(dataDir, "join-token")); !os.IsNotExist(err) {+ t.Fatalf("join-token file must not be written: %v", err)+ }++ client := &http.Client{Timeout: 5 * time.Second}+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+srv.Addr()+"/admin/bootstrap-tokens", nil)+ req.Header.Set("Authorization", "Bearer "+srv.AdminToken())+ resp, err := client.Do(req)+ if err != nil {+ t.Fatalf("GET /admin/bootstrap-tokens: %v", err)+ }+ body, _ := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ if resp.StatusCode != http.StatusOK || strings.Contains(string(body), "sam-one join token") {+ t.Fatalf("token list = %s %s; want 200 without a join token", resp.Status, body)+ }++ // The embedded router self-enrolled without it, and a minted token still+ // admits a device through the single port.+ _, portStr, _ := net.SplitHostPort(srv.Addr())+ port, _ := strconv.Atoi(portStr)+ waitForActiveRouters(t, port, 1, 10*time.Second)+ devTok, err := srv.MintDeviceEnrollmentToken(ctx, 0, 1)+ if err != nil {+ t.Fatalf("failed to mint device token: %v", err)+ }+ if err := newStandaloneTestNode(t, ctx).EnrollBootstrap(ctx, srv.PublicURL(), devTok); err != nil {+ t.Fatalf("device enrollment without a join token failed: %v", err)+ }+}+// newStandaloneTestNode returns a started, unenrolled loopback node.func newStandaloneTestNode(t *testing.T, ctx context.Context) *node.SamNode {t.Helper()