Skip to content

Agent Mesh

node: add --auth-mode to force a deterministic enrollment flow

Antonio Ojea1515abc22f02
diff --git a/agents/skills/sam-mesh/SKILL.md b/agents/skills/sam-mesh/SKILL.md
index 3df0dccc..d4bc7755 100644
--- a/agents/skills/sam-mesh/SKILL.md
+++ b/agents/skills/sam-mesh/SKILL.md
@@ -39,8 +39,10 @@ approve it before running anything.
so no pasted callback code is required: it prints a verification URL/code
and polls until login completes. If the provider does not expose a device
endpoint, SAM falls back to OOB code-paste flow; show the URL/code to the
- user, wait for completion, then repeat step 2. Enrollment is a one-time step
- per machine.
+ user, wait for completion, then repeat step 2. For deterministic automation,
+ force the flow with `--auth-mode device` (also `oob`, `browser`, or the
+ default `auto`); `--auth-mode device` fails fast if the provider has no
+ device endpoint. Enrollment is a one-time step per machine.
4. Read the node API token from the file named in step 2, then register the MCP
endpoint `http://127.0.0.1:8080/mcp` with the header
`X-Sam-Authentication: Bearer <token>`. Claude Code:
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.go
index 92df7635..d87e811b 100644
--- a/cmd/sam-box/main.go
+++ b/cmd/sam-box/main.go
@@ -71,6 +71,7 @@ var (
audienceFlag string
dataDirFlag string
headlessFlag bool
+ authModeFlag string
offlineAccessFlag bool
logLevelFlag string
keyGracePeriodFlag time.Duration
@@ -433,7 +434,12 @@ func main() {
deviceAuthURL = deviceAuthURLFlag
}
- jwtStr, err = dummyNode.InteractiveLoginWithDeviceAuth(ctx, endpoints.AuthURL, endpoints.TokenURL, deviceAuthURL, controlPlaneInfo.ClientId, controlPlaneInfo.Audience, offlineAccessFlag, headlessFlag)
+ mode, err := node.ParseAuthMode(authModeFlag)
+ if err != nil {
+ logger.Fatalf("Invalid --auth-mode: %v", err)
+ }
+
+ jwtStr, err = dummyNode.InteractiveLoginWithMode(ctx, endpoints.AuthURL, endpoints.TokenURL, deviceAuthURL, controlPlaneInfo.ClientId, controlPlaneInfo.Audience, offlineAccessFlag, headlessFlag, mode)
if err != nil {
logger.Fatalf("Failed to get token: %v", err)
}
@@ -554,6 +560,7 @@ func main() {
rootCmd.PersistentFlags().StringVar(&audienceFlag, "audience", api.DefaultAudience, "OIDC Audience")
rootCmd.PersistentFlags().StringVar(&dataDirFlag, "data-dir", "", "Override directory for the agent store (defaults to OS user config dir)")
rootCmd.PersistentFlags().BoolVar(&headlessFlag, "headless", false, "Force headless out-of-band (OOB) authentication flow")
+ rootCmd.PersistentFlags().StringVar(&authModeFlag, "auth-mode", "auto", "Interactive enrollment auth mode: auto, device, oob, or browser")
rootCmd.AddCommand(runCmd)
rootCmd.AddCommand(joinCmd)
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 7a000972..8b6cb71b 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -73,6 +73,7 @@ var (
audienceFlag string
dataDirFlag string
headlessFlag bool
+ authModeFlag string
daemonizeFlag bool
resetAllFlag bool
assumeYesFlag bool
@@ -285,7 +286,12 @@ func interactiveJoin(ctx context.Context, store *node.Store, targetControlPlane
deviceAuthURL = deviceAuthURLFlag
}
- jwtStr, err := dummyNode.InteractiveLoginWithDeviceAuth(ctx, endpoints.AuthURL, endpoints.TokenURL, deviceAuthURL, info.ClientId, info.Audience, offlineAccessFlag, headlessFlag)
+ mode, err := node.ParseAuthMode(authModeFlag)
+ if err != nil {
+ return "", nil, fmt.Errorf("invalid --auth-mode: %w", err)
+ }
+
+ jwtStr, err := dummyNode.InteractiveLoginWithMode(ctx, endpoints.AuthURL, endpoints.TokenURL, deviceAuthURL, info.ClientId, info.Audience, offlineAccessFlag, headlessFlag, mode)
if err != nil {
return "", nil, fmt.Errorf("failed to get token: %w", err)
}
@@ -939,6 +945,7 @@ func main() {
rootCmd.PersistentFlags().StringVar(&audienceFlag, "audience", api.DefaultAudience, "OIDC Audience")
rootCmd.PersistentFlags().StringVar(&dataDirFlag, "data-dir", "", "Override directory for the agent store (defaults to OS user config dir)")
rootCmd.PersistentFlags().BoolVar(&headlessFlag, "headless", false, "Force headless out-of-band (OOB) authentication flow")
+ rootCmd.PersistentFlags().StringVar(&authModeFlag, "auth-mode", "auto", "Interactive enrollment auth mode: auto, device, oob, or browser")
rootCmd.AddCommand(runCmd)
rootCmd.AddCommand(joinCmd)
diff --git a/internal/node/oidc.go b/internal/node/oidc.go
index de5ab2bd..26644314 100644
--- a/internal/node/oidc.go
+++ b/internal/node/oidc.go
@@ -61,18 +61,56 @@ func (n *SamNode) FetchJWT(ctx context.Context, tokenURL, clientID, clientSecret
return token.AccessToken, nil
}
+// AuthMode selects how interactive enrollment authenticates the user.
+type AuthMode string
+
+const (
+ // AuthModeAuto prefers device flow in headless environments (when the
+ // provider advertises one) and the loopback browser flow otherwise, with an
+ // automatic device fallback when the browser can't be opened.
+ AuthModeAuto AuthMode = "auto"
+ // AuthModeDevice forces the OAuth 2.0 Device Authorization Grant (RFC 8628).
+ AuthModeDevice AuthMode = "device"
+ // AuthModeOOB forces the out-of-band code-paste flow.
+ AuthModeOOB AuthMode = "oob"
+ // AuthModeBrowser forces the loopback browser (authorization code) flow.
+ AuthModeBrowser AuthMode = "browser"
+)
+
+// ParseAuthMode validates a user-provided --auth-mode value. An empty string
+// maps to AuthModeAuto.
+func ParseAuthMode(s string) (AuthMode, error) {
+ switch AuthMode(strings.ToLower(strings.TrimSpace(s))) {
+ case "", AuthModeAuto:
+ return AuthModeAuto, nil
+ case AuthModeDevice:
+ return AuthModeDevice, nil
+ case AuthModeOOB:
+ return AuthModeOOB, nil
+ case AuthModeBrowser:
+ return AuthModeBrowser, nil
+ default:
+ return "", fmt.Errorf("invalid auth mode %q (want auto, device, oob, or browser)", s)
+ }
+}
+
// 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, headless bool) (string, error) {
return n.InteractiveLoginWithDeviceAuth(ctx, authURL, tokenURL, "", clientID, audience, requestRefresh, headless)
}
-// InteractiveLoginWithDeviceAuth prompts the user to authenticate, preferring
-// OAuth Device Authorization Grant in headless mode when the provider exposes
-// a device authorization endpoint.
+// InteractiveLoginWithDeviceAuth authenticates using AuthModeAuto: it prefers
+// the OAuth Device Authorization Grant in headless mode when the provider
+// exposes a device authorization endpoint, and otherwise uses the loopback
+// browser flow with a device fallback.
func (n *SamNode) InteractiveLoginWithDeviceAuth(ctx context.Context, authURL, tokenURL, deviceAuthURL, clientID, audience string, requestRefresh bool, headless bool) (string, error) {
- if authURL == "" {
- return "", fmt.Errorf("authorization URL is required")
- }
+ return n.InteractiveLoginWithMode(ctx, authURL, tokenURL, deviceAuthURL, clientID, audience, requestRefresh, headless, AuthModeAuto)
+}
+
+// InteractiveLoginWithMode authenticates the user using an explicit AuthMode,
+// letting callers (e.g. CUJ harnesses) force a deterministic flow instead of
+// relying on headless environment detection.
+func (n *SamNode) InteractiveLoginWithMode(ctx context.Context, authURL, tokenURL, deviceAuthURL, clientID, audience string, requestRefresh bool, headless bool, mode AuthMode) (string, error) {
if tokenURL == "" {
return "", fmt.Errorf("token URL is required")
}
@@ -80,6 +118,35 @@ func (n *SamNode) InteractiveLoginWithDeviceAuth(ctx context.Context, authURL, t
return "", fmt.Errorf("client ID is required")
}
+ isHeadless := headless || os.Getenv("SSH_CLIENT") != "" || os.Getenv("SSH_TTY") != ""
+
+ switch mode {
+ case AuthModeDevice:
+ if deviceAuthURL == "" {
+ return "", fmt.Errorf("auth-mode=device requested but the OIDC provider does not advertise a device_authorization_endpoint")
+ }
+ return n.DeviceLogin(ctx, deviceAuthURL, tokenURL, clientID, audience, requestRefresh)
+ case AuthModeOOB:
+ // Force out-of-band paste; disable any device fallback.
+ isHeadless = true
+ deviceAuthURL = ""
+ case AuthModeBrowser:
+ // Force the loopback browser flow; disable device fallback.
+ isHeadless = false
+ deviceAuthURL = ""
+ case AuthModeAuto:
+ if isHeadless && deviceAuthURL != "" {
+ logger.Info("Headless mode detected and device authorization endpoint available; using device flow")
+ return n.DeviceLogin(ctx, deviceAuthURL, tokenURL, clientID, audience, requestRefresh)
+ }
+ default:
+ return "", fmt.Errorf("invalid auth mode %q", mode)
+ }
+
+ if authURL == "" {
+ return "", fmt.Errorf("authorization URL is required")
+ }
+
stateBytes := make([]byte, 16)
if _, err := rand.Read(stateBytes); err != nil {
return "", fmt.Errorf("failed to generate state: %w", err)
@@ -91,13 +158,6 @@ func (n *SamNode) InteractiveLoginWithDeviceAuth(ctx context.Context, authURL, t
return "", fmt.Errorf("failed to generate PKCE: %w", err)
}
- isHeadless := headless || os.Getenv("SSH_CLIENT") != "" || os.Getenv("SSH_TTY") != ""
-
- if isHeadless && deviceAuthURL != "" {
- logger.Info("Headless mode detected and device authorization endpoint available; using device flow")
- return n.DeviceLogin(ctx, deviceAuthURL, tokenURL, clientID, audience, requestRefresh)
- }
-
var redirectURI string
var listener net.Listener
diff --git a/internal/node/oidc_test.go b/internal/node/oidc_test.go
index e2ec924e..6037a54e 100644
--- a/internal/node/oidc_test.go
+++ b/internal/node/oidc_test.go
@@ -453,6 +453,187 @@ func TestInteractiveLoginBrowserFailFallsBackToDevice(t *testing.T) {
}
}
+func TestParseAuthMode(t *testing.T) {
+ cases := []struct {
+ in string
+ want AuthMode
+ wantErr bool
+ }{
+ {"", AuthModeAuto, false},
+ {"auto", AuthModeAuto, false},
+ {"AUTO", AuthModeAuto, false},
+ {" device ", AuthModeDevice, false},
+ {"oob", AuthModeOOB, false},
+ {"browser", AuthModeBrowser, false},
+ {"nonsense", "", true},
+ }
+ for _, tc := range cases {
+ got, err := ParseAuthMode(tc.in)
+ if tc.wantErr {
+ if err == nil {
+ t.Errorf("ParseAuthMode(%q): expected error, got %q", tc.in, got)
+ }
+ continue
+ }
+ if err != nil {
+ t.Errorf("ParseAuthMode(%q): unexpected error: %v", tc.in, err)
+ continue
+ }
+ if got != tc.want {
+ t.Errorf("ParseAuthMode(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ }
+}
+
+// TestAuthModeDeviceForcedWhenInteractive verifies that auth-mode=device uses
+// the device flow even in a non-headless environment, and never touches the
+// browser.
+func TestAuthModeDeviceForcedWhenInteractive(t *testing.T) {
+ t.Setenv("SSH_CLIENT", "")
+ t.Setenv("SSH_TTY", "")
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/device", func(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
+ "device_code": "dev_code_1",
+ "user_code": "AAAA-BBBB",
+ "verification_uri": "https://example.com/device",
+ "expires_in": 60,
+ "interval": 1,
+ })
+ })
+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ if r.FormValue("grant_type") != "urn:ietf:params:oauth:grant-type:device_code" {
+ http.Error(w, "Invalid grant_type", http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]string{"id_token": "forced_device_token"})
+ })
+
+ server := httptest.NewServer(mux)
+ defer server.Close()
+
+ node := &SamNode{}
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ originalOpenBrowser := openBrowserFunc
+ openBrowserFunc = func(_ string) error {
+ t.Error("openBrowser should not be called when auth-mode=device")
+ return nil
+ }
+ defer func() { openBrowserFunc = originalOpenBrowser }()
+
+ token, err := node.InteractiveLoginWithMode(
+ ctx,
+ "http://auth.example.com/auth",
+ server.URL+"/token",
+ server.URL+"/device",
+ "client_id_test",
+ "sam-e2e",
+ false,
+ false,
+ AuthModeDevice,
+ )
+ if err != nil {
+ t.Fatalf("InteractiveLoginWithMode failed: %v", err)
+ }
+ if token != "forced_device_token" {
+ t.Fatalf("Expected forced_device_token, got %q", token)
+ }
+}
+
+// TestAuthModeDeviceWithoutEndpointErrors verifies that auth-mode=device fails
+// fast when the provider advertises no device endpoint.
+func TestAuthModeDeviceWithoutEndpointErrors(t *testing.T) {
+ node := &SamNode{}
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+
+ _, err := node.InteractiveLoginWithMode(
+ ctx,
+ "http://auth.example.com/auth",
+ "http://token.example.com/token",
+ "", // no device endpoint
+ "client_id_test",
+ "sam-e2e",
+ false,
+ true,
+ AuthModeDevice,
+ )
+ if err == nil {
+ t.Fatal("expected an error when auth-mode=device but no device endpoint is available")
+ }
+ if !strings.Contains(err.Error(), "device_authorization_endpoint") {
+ t.Fatalf("expected device endpoint error, got: %v", err)
+ }
+}
+
+// TestAuthModeBrowserIgnoresDevice verifies that auth-mode=browser uses the
+// loopback flow even under a headless (SSH) environment with a device
+// endpoint available, and never falls back to device flow.
+func TestAuthModeBrowserIgnoresDevice(t *testing.T) {
+ t.Setenv("SSH_CLIENT", "1")
+ t.Setenv("SSH_TTY", "")
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/device", func(w http.ResponseWriter, r *http.Request) {
+ t.Error("device endpoint should not be used when auth-mode=browser")
+ http.Error(w, "unexpected", http.StatusBadRequest)
+ })
+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ if r.FormValue("grant_type") != "authorization_code" {
+ http.Error(w, "Invalid grant_type", http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]string{"id_token": "browser_mode_token"})
+ })
+
+ server := httptest.NewServer(mux)
+ defer server.Close()
+
+ node := &SamNode{}
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ originalOpenBrowser := openBrowserFunc
+ openBrowserFunc = func(urlStr string) error {
+ u, _ := url.Parse(urlStr)
+ redirectURI := u.Query().Get("redirect_uri")
+ state := u.Query().Get("state")
+ go func() {
+ time.Sleep(50 * time.Millisecond)
+ _, _ = http.Get(redirectURI + "?code=dev_code_123&state=" + state)
+ }()
+ return nil
+ }
+ defer func() { openBrowserFunc = originalOpenBrowser }()
+
+ token, err := node.InteractiveLoginWithMode(
+ ctx,
+ "http://auth.example.com/auth",
+ server.URL+"/token",
+ server.URL+"/device",
+ "client_id_test",
+ "sam-e2e",
+ false,
+ true, // headless requested, but browser mode overrides it
+ AuthModeBrowser,
+ )
+ if err != nil {
+ t.Fatalf("InteractiveLoginWithMode failed: %v", err)
+ }
+ if token != "browser_mode_token" {
+ t.Fatalf("Expected browser_mode_token, got %q", token)
+ }
+}
+
func TestRenewWithRefreshToken(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
diff --git a/site/content/docs/user/agent-usage.md b/site/content/docs/user/agent-usage.md
index b2003956..1a8aef51 100644
--- a/site/content/docs/user/agent-usage.md
+++ b/site/content/docs/user/agent-usage.md
@@ -58,6 +58,14 @@ sam-node join https://bananas.sam-mesh.dev --headless
```
When the OIDC provider supports device authorization, SAM automatically uses device flow (no pasted callback code required): it prints a verification URL/code and polls until approval. If device authorization is unavailable, SAM falls back to OOB code-paste flow.
+### Choosing the Auth Flow Explicitly
+By default (`--auth-mode auto`) SAM picks the flow for you: device flow in headless environments when available, the loopback browser flow otherwise (with an automatic device fallback if the browser can't be opened). For deterministic automation (e.g. CI/CUJ harnesses), force a specific flow instead of relying on environment detection:
+```bash
+# Force RFC 8628 device flow (no code to paste back)
+sam-node join https://bananas.sam-mesh.dev --auth-mode device
+```
+Supported values: `auto` (default), `device`, `oob`, `browser`. `--auth-mode device` fails fast if the provider does not advertise a `device_authorization_endpoint`.
+
### Automatic Token Renewal
To allow long-lived nodes to automatically renew their tokens in the background, request offline access (refreshes the OIDC session):
```bash