Skip to content

Agent Mesh

node: add OAuth device flow for headless enrollment with browser-fail fallback

Antonio Ojea0251770c97ac
diff --git a/agents/skills/sam-mesh/SKILL.md b/agents/skills/sam-mesh/SKILL.md
index 03dfde04..3df0dccc 100644
--- a/agents/skills/sam-mesh/SKILL.md
+++ b/agents/skills/sam-mesh/SKILL.md
@@ -34,9 +34,13 @@ approve it before running anything.
log file, and how to stop it. It is idempotent, so run it again whenever you
need to confirm a node is up.
3. If step 2 reports that the node is not enrolled, run the command it prints,
- `sam-node join --headless <control-plane-url>`. That prints a URL and a
- code: show both to the user and wait while they complete the login, then
- repeat step 2. Enrollment is a one-time step per machine.
+ `sam-node join --headless <control-plane-url>`. In headless mode SAM now
+ prefers OAuth device flow automatically when the OIDC provider supports it,
+ 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.
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 10dc1680..92df7635 100644
--- a/cmd/sam-box/main.go
+++ b/cmd/sam-box/main.go
@@ -424,12 +424,16 @@ func main() {
fmt.Printf("Client ID discovered: %s\n", controlPlaneInfo.ClientId)
logger.Info("Discovering OIDC endpoints...")
- tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, controlPlaneInfo.OidcIssuer)
+ endpoints, err := dummyNode.DiscoverEndpointsWithDevice(ctx, controlPlaneInfo.OidcIssuer)
if err != nil {
logger.Fatalf("Failed to discover OIDC endpoints: %v", err)
}
+ deviceAuthURL := endpoints.DeviceAuthURL
+ if deviceAuthURLFlag != "" {
+ deviceAuthURL = deviceAuthURLFlag
+ }
- jwtStr, err = dummyNode.InteractiveLogin(ctx, authURL, tokenURL, controlPlaneInfo.ClientId, controlPlaneInfo.Audience, offlineAccessFlag, headlessFlag)
+ jwtStr, err = dummyNode.InteractiveLoginWithDeviceAuth(ctx, endpoints.AuthURL, endpoints.TokenURL, deviceAuthURL, controlPlaneInfo.ClientId, controlPlaneInfo.Audience, offlineAccessFlag, headlessFlag)
if err != nil {
logger.Fatalf("Failed to get token: %v", err)
}
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index bf164e0e..7a000972 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -276,12 +276,16 @@ func interactiveJoin(ctx context.Context, store *node.Store, targetControlPlane
fmt.Printf("Client ID discovered: %s\n", info.ClientId)
logger.Info("Discovering OIDC endpoints...")
- tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, info.OidcIssuer)
+ endpoints, err := dummyNode.DiscoverEndpointsWithDevice(ctx, info.OidcIssuer)
if err != nil {
return "", nil, fmt.Errorf("failed to discover OIDC endpoints: %w", err)
}
+ deviceAuthURL := endpoints.DeviceAuthURL
+ if deviceAuthURLFlag != "" {
+ deviceAuthURL = deviceAuthURLFlag
+ }
- jwtStr, err := dummyNode.InteractiveLogin(ctx, authURL, tokenURL, info.ClientId, info.Audience, offlineAccessFlag, headlessFlag)
+ jwtStr, err := dummyNode.InteractiveLoginWithDeviceAuth(ctx, endpoints.AuthURL, endpoints.TokenURL, deviceAuthURL, info.ClientId, info.Audience, offlineAccessFlag, headlessFlag)
if err != nil {
return "", nil, fmt.Errorf("failed to get token: %w", err)
}
diff --git a/internal/node/oidc.go b/internal/node/oidc.go
index f7dcdf14..de5ab2bd 100644
--- a/internal/node/oidc.go
+++ b/internal/node/oidc.go
@@ -21,6 +21,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
+ "io"
"net"
"net/http"
"net/url"
@@ -62,6 +63,13 @@ 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, 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.
+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")
}
@@ -85,10 +93,18 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clien
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
if isHeadless {
+ if !stdinIsInteractive() {
+ logger.Warn("Headless OOB flow requires pasting a code, but stdin is non-interactive and no device endpoint is configured; auth may block")
+ }
redirectURI = "urn:ietf:wg:oauth:2.0:oob"
} else {
var err error
@@ -102,6 +118,10 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clien
}
}
if listener == nil {
+ if deviceAuthURL != "" {
+ logger.Warn("Could not bind local OIDC listener (ports 13000-13002 busy); falling back to device authorization flow.")
+ return n.DeviceLogin(ctx, deviceAuthURL, tokenURL, clientID, audience, requestRefresh)
+ }
logger.Warn("Could not bind local OIDC listener (ports 13000-13002 busy). Falling back to headless (OOB) authorization.")
isHeadless = true
redirectURI = "urn:ietf:wg:oauth:2.0:oob"
@@ -136,6 +156,22 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clien
authReq.URL.RawQuery = q.Encode()
targetURL := authReq.URL.String()
+ // In an interactive (loopback) flow, try to open the browser up front. If it
+ // can't be opened, nothing will complete the redirect, so when the provider
+ // advertises a device authorization endpoint we fall back to device flow
+ // rather than forcing the user (or a CUJ harness) to paste a callback code
+ // back. Headless flows open the browser only best-effort (after the banner),
+ // since they already print a URL to complete elsewhere.
+ if !isHeadless {
+ if err := openBrowserFunc(targetURL); err != nil {
+ if deviceAuthURL != "" {
+ logger.Warnf("Could not open a browser (%v); falling back to device authorization flow.", err)
+ return n.DeviceLogin(ctx, deviceAuthURL, tokenURL, clientID, audience, requestRefresh)
+ }
+ logger.Warnf("Could not open a browser (%v); open the URL below manually or paste the callback code.", err)
+ }
+ }
+
fmt.Println("------------------------------------------------------------")
fmt.Println("OAuth Authorization Flow")
fmt.Println("------------------------------------------------------------")
@@ -148,8 +184,10 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clien
}
fmt.Println("------------------------------------------------------------")
- // Try to open browser automatically
- openBrowserFunc(targetURL)
+ if isHeadless {
+ // Best-effort: some headless setups still have a usable browser.
+ _ = openBrowserFunc(targetURL)
+ }
loginCtx, loginCancel := context.WithCancel(ctx)
defer loginCancel()
@@ -266,6 +304,61 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clien
if err != nil {
return "", err
}
+
+ jwt, refreshToken, err := parseTokenResponse(resp)
+ if err != nil {
+ return "", err
+ }
+ if refreshToken != "" && n.Store != nil {
+ if err := n.Store.SaveRefreshToken(refreshToken); err != nil {
+ logger.Warnf("Failed to save refresh token: %v", err)
+ }
+ }
+ return jwt, nil
+}
+
+func stdinIsInteractive() bool {
+ fi, err := os.Stdin.Stat()
+ if err != nil {
+ return false
+ }
+ return (fi.Mode() & os.ModeCharDevice) != 0
+}
+
+// DeviceLogin performs OAuth 2.0 Device Authorization Grant (RFC 8628).
+func (n *SamNode) DeviceLogin(ctx context.Context, deviceAuthURL, tokenURL, clientID, audience string, requestRefresh bool) (string, error) {
+ if deviceAuthURL == "" {
+ return "", fmt.Errorf("device authorization URL is required")
+ }
+ if tokenURL == "" {
+ return "", fmt.Errorf("token URL is required")
+ }
+ if clientID == "" {
+ return "", fmt.Errorf("client ID is required")
+ }
+
+ deviceData := url.Values{}
+ deviceData.Set("client_id", clientID)
+ scope := "openid email profile"
+ if requestRefresh {
+ scope += " offline_access"
+ }
+ deviceData.Set("scope", scope)
+ if audience != "" {
+ deviceData.Set("audience", audience)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "POST", deviceAuthURL, strings.NewReader(deviceData.Encode()))
+ if err != nil {
+ return "", fmt.Errorf("failed to create device authorization request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ client := &http.Client{Timeout: 10 * time.Second}
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("device authorization request failed: %w", err)
+ }
defer func() {
if err := resp.Body.Close(); err != nil {
logger.Errorf("Failed to close response body: %v", err)
@@ -278,7 +371,169 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clien
ErrorDescription string `json:"error_description"`
}
_ = json.NewDecoder(resp.Body).Decode(&errResp)
- return "", fmt.Errorf("token request failed: %s - %s", errResp.Error, errResp.ErrorDescription)
+ return "", fmt.Errorf("device authorization failed: %s - %s", errResp.Error, errResp.ErrorDescription)
+ }
+
+ var deviceResp struct {
+ DeviceCode string `json:"device_code"`
+ UserCode string `json:"user_code"`
+ VerificationURI string `json:"verification_uri"`
+ VerificationURIComplete string `json:"verification_uri_complete"`
+ ExpiresIn int `json:"expires_in"`
+ Interval int `json:"interval"`
+ Message string `json:"message"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&deviceResp); err != nil {
+ return "", fmt.Errorf("failed to decode device authorization response: %w", err)
+ }
+ if deviceResp.DeviceCode == "" {
+ return "", fmt.Errorf("device authorization response missing device_code")
+ }
+
+ verificationURL := deviceResp.VerificationURI
+ if deviceResp.VerificationURIComplete != "" {
+ verificationURL = deviceResp.VerificationURIComplete
+ }
+
+ fmt.Println("------------------------------------------------------------")
+ fmt.Println("OAuth Device Authorization Flow")
+ fmt.Println("------------------------------------------------------------")
+ if deviceResp.Message != "" {
+ fmt.Println(deviceResp.Message)
+ fmt.Println()
+ } else {
+ if verificationURL != "" {
+ fmt.Printf("Open this URL in a browser:\n\n %s\n\n", verificationURL)
+ }
+ if deviceResp.UserCode != "" {
+ fmt.Printf("Enter code: %s\n\n", deviceResp.UserCode)
+ }
+ }
+ fmt.Println("Waiting for authorization...")
+ fmt.Println("------------------------------------------------------------")
+
+ pollInterval := 5 * time.Second
+ if deviceResp.Interval > 0 {
+ pollInterval = time.Duration(deviceResp.Interval) * time.Second
+ }
+ var expiresAt time.Time
+ if deviceResp.ExpiresIn > 0 {
+ expiresAt = time.Now().Add(time.Duration(deviceResp.ExpiresIn) * time.Second)
+ }
+
+ for {
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ default:
+ }
+
+ if !expiresAt.IsZero() && time.Now().After(expiresAt) {
+ return "", fmt.Errorf("device authorization expired before completion")
+ }
+
+ tokenData := url.Values{}
+ tokenData.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
+ tokenData.Set("device_code", deviceResp.DeviceCode)
+ tokenData.Set("client_id", clientID)
+
+ tokenReq, err := http.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(tokenData.Encode()))
+ if err != nil {
+ return "", fmt.Errorf("failed to create token polling request: %w", err)
+ }
+ tokenReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ tokenResp, err := client.Do(tokenReq)
+ if err != nil {
+ return "", fmt.Errorf("token polling request failed: %w", err)
+ }
+
+ body, readErr := io.ReadAll(tokenResp.Body)
+ if closeErr := tokenResp.Body.Close(); closeErr != nil {
+ logger.Errorf("Failed to close response body: %v", closeErr)
+ }
+ if readErr != nil {
+ return "", fmt.Errorf("failed to read token polling response: %w", readErr)
+ }
+
+ if tokenResp.StatusCode == http.StatusOK {
+ var tokenData struct {
+ AccessToken string `json:"access_token"`
+ IdToken string `json:"id_token"`
+ RefreshToken string `json:"refresh_token"`
+ }
+ if err := json.Unmarshal(body, &tokenData); err != nil {
+ return "", fmt.Errorf("failed to decode token response: %w", err)
+ }
+ jwt := tokenData.AccessToken
+ if tokenData.IdToken != "" {
+ jwt = tokenData.IdToken
+ }
+ if jwt == "" {
+ return "", fmt.Errorf("token response did not contain an access_token or id_token")
+ }
+ if tokenData.RefreshToken != "" && n.Store != nil {
+ if saveErr := n.Store.SaveRefreshToken(tokenData.RefreshToken); saveErr != nil {
+ logger.Warnf("Failed to save refresh token: %v", saveErr)
+ }
+ }
+ return jwt, nil
+ }
+
+ if tokenResp.StatusCode != http.StatusBadRequest {
+ return "", fmt.Errorf("token request failed with status: %s", tokenResp.Status)
+ }
+
+ var errResp struct {
+ Error string `json:"error"`
+ ErrorDescription string `json:"error_description"`
+ }
+ if err := json.Unmarshal(body, &errResp); err != nil {
+ return "", fmt.Errorf("failed to decode token polling error response: %w", err)
+ }
+
+ switch errResp.Error {
+ case "authorization_pending":
+ // keep polling
+ case "slow_down":
+ pollInterval += 5 * time.Second
+ case "access_denied":
+ return "", fmt.Errorf("device authorization denied by user")
+ case "expired_token":
+ return "", fmt.Errorf("device authorization expired")
+ default:
+ return "", fmt.Errorf("device token polling failed: %s - %s", errResp.Error, errResp.ErrorDescription)
+ }
+
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ case <-time.After(pollInterval):
+ }
+ }
+}
+
+func parseTokenResponse(resp *http.Response) (jwt string, refreshToken string, err error) {
+ defer func() {
+ if closeErr := resp.Body.Close(); closeErr != nil {
+ logger.Errorf("Failed to close response body: %v", closeErr)
+ }
+ }()
+
+ body, readErr := io.ReadAll(resp.Body)
+ if readErr != nil {
+ return "", "", readErr
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ var errResp struct {
+ Error string `json:"error"`
+ ErrorDescription string `json:"error_description"`
+ }
+ if unmarshalErr := json.Unmarshal(body, &errResp); unmarshalErr == nil && errResp.Error != "" {
+ return "", "", fmt.Errorf("token request failed: %s - %s", errResp.Error, errResp.ErrorDescription)
+ }
+ return "", "", fmt.Errorf("token request failed with status: %s", resp.Status)
}
var tokenResp struct {
@@ -286,20 +541,18 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, authURL, tokenURL, clien
IdToken string `json:"id_token"`
RefreshToken string `json:"refresh_token"`
}
- if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
- return "", err
- }
-
- if tokenResp.RefreshToken != "" && n.Store != nil {
- if err := n.Store.SaveRefreshToken(tokenResp.RefreshToken); err != nil {
- logger.Warnf("Failed to save refresh token: %v", err)
- }
+ if err := json.Unmarshal(body, &tokenResp); err != nil {
+ return "", "", err
}
+ jwt = tokenResp.AccessToken
if tokenResp.IdToken != "" {
- return tokenResp.IdToken, nil
+ jwt = tokenResp.IdToken
+ }
+ if jwt == "" {
+ return "", "", fmt.Errorf("token response did not contain an access_token or id_token")
}
- return tokenResp.AccessToken, nil
+ return jwt, tokenResp.RefreshToken, nil
}
// oidcDiscoveryTimeout bounds a single OIDC discovery HTTP call so an
@@ -328,28 +581,48 @@ func (n *SamNode) DiscoverTokenURL(ctx context.Context, issuerURL string) (strin
// DiscoverEndpoints discovers both token and authorization endpoints.
func (n *SamNode) DiscoverEndpoints(ctx context.Context, issuerURL string) (tokenURL, authURL string, err error) {
+ endpoints, err := n.DiscoverEndpointsWithDevice(ctx, issuerURL)
+ if err != nil {
+ return "", "", err
+ }
+ return endpoints.TokenURL, endpoints.AuthURL, nil
+}
+
+// OIDCEndpoints contains discovered OIDC endpoint URLs.
+type OIDCEndpoints struct {
+ TokenURL string
+ AuthURL string
+ DeviceAuthURL string
+}
+
+// DiscoverEndpointsWithDevice discovers token, authorization and device authorization endpoints.
+func (n *SamNode) DiscoverEndpointsWithDevice(ctx context.Context, issuerURL string) (*OIDCEndpoints, error) {
client := &http.Client{Timeout: oidcDiscoveryTimeout}
provider, err := oidc.NewProvider(oidc.ClientContext(ctx, client), issuerURL)
if err != nil {
- return "", "", fmt.Errorf("failed to create OIDC provider: %w", err)
+ return nil, fmt.Errorf("failed to create OIDC provider: %w", err)
}
var claims struct {
- TokenURL string `json:"token_endpoint"`
- AuthURL string `json:"authorization_endpoint"`
+ TokenURL string `json:"token_endpoint"`
+ AuthURL string `json:"authorization_endpoint"`
+ DeviceAuthURL string `json:"device_authorization_endpoint"`
}
if err := provider.Claims(&claims); err != nil {
- return "", "", fmt.Errorf("failed to extract claims: %w", err)
+ return nil, fmt.Errorf("failed to extract claims: %w", err)
}
- return claims.TokenURL, claims.AuthURL, nil
+ return &OIDCEndpoints{
+ TokenURL: claims.TokenURL,
+ AuthURL: claims.AuthURL,
+ DeviceAuthURL: claims.DeviceAuthURL,
+ }, nil
}
var openBrowserFunc = openBrowser
-func openBrowser(targetURL string) {
+func openBrowser(targetURL string) error {
parsedURL, err := url.Parse(targetURL)
if err != nil || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
- logger.Debugf("Failed to open browser: invalid or unsafe URL scheme %q", targetURL)
- return
+ return fmt.Errorf("invalid or unsafe URL scheme %q", targetURL)
}
var cmdErr error
switch runtime.GOOS {
@@ -364,7 +637,9 @@ func openBrowser(targetURL string) {
}
if cmdErr != nil {
logger.Debugf("Failed to open browser: %v", cmdErr)
+ return cmdErr
}
+ return nil
}
// RefreshJWT refreshes the OIDC token using the stored refresh token.
diff --git a/internal/node/oidc_test.go b/internal/node/oidc_test.go
index 3a35ca37..e2ec924e 100644
--- a/internal/node/oidc_test.go
+++ b/internal/node/oidc_test.go
@@ -3,6 +3,7 @@ package node
import (
"context"
"encoding/json"
+ "fmt"
"net"
"net/http"
"net/http/httptest"
@@ -56,7 +57,7 @@ func TestInteractiveLogin(t *testing.T) {
// Mock openBrowser to simulate the user authorizing in the browser
originalOpenBrowser := openBrowserFunc
- openBrowserFunc = func(urlStr string) {
+ openBrowserFunc = func(urlStr string) error {
u, _ := url.Parse(urlStr)
redirectURI := u.Query().Get("redirect_uri")
state := u.Query().Get("state")
@@ -65,6 +66,7 @@ func TestInteractiveLogin(t *testing.T) {
time.Sleep(100 * time.Millisecond)
_, _ = http.Get(redirectURI + "?code=dev_code_123&state=" + state)
}()
+ return nil
}
defer func() { openBrowserFunc = originalOpenBrowser }()
@@ -110,6 +112,42 @@ func TestDiscoverEndpoints(t *testing.T) {
}
}
+func TestDiscoverEndpointsWithDevice(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(map[string]interface{}{
+ "issuer": "http://" + r.Host,
+ "token_endpoint": "http://" + r.Host + "/token",
+ "authorization_endpoint": "http://" + r.Host + "/auth",
+ "device_authorization_endpoint": "http://" + r.Host + "/device",
+ }); err != nil {
+ t.Errorf("Failed to encode response: %v", err)
+ }
+ })
+
+ server := httptest.NewServer(mux)
+ defer server.Close()
+
+ node := &SamNode{BiscuitTimeout: 500 * time.Millisecond}
+ ctx := context.Background()
+
+ endpoints, err := node.DiscoverEndpointsWithDevice(ctx, server.URL)
+ if err != nil {
+ t.Fatalf("DiscoverEndpointsWithDevice failed: %v", err)
+ }
+
+ if endpoints.TokenURL != server.URL+"/token" {
+ t.Errorf("Expected tokenURL %s, got %s", server.URL+"/token", endpoints.TokenURL)
+ }
+ if endpoints.AuthURL != server.URL+"/auth" {
+ t.Errorf("Expected authURL %s, got %s", server.URL+"/auth", endpoints.AuthURL)
+ }
+ if endpoints.DeviceAuthURL != server.URL+"/device" {
+ t.Errorf("Expected deviceAuthURL %s, got %s", server.URL+"/device", endpoints.DeviceAuthURL)
+ }
+}
+
// TestDiscoverEndpointsDoesNotHangOnUnresponsiveIssuer guards against an
// unbounded hang: DiscoverEndpoints/DiscoverTokenURL used to call
// oidc.NewProvider with no client timeout, so an issuer that accepts a
@@ -193,7 +231,7 @@ func TestInteractiveLoginWithRefresh(t *testing.T) {
defer cancel()
originalOpenBrowser := openBrowserFunc
- openBrowserFunc = func(urlStr string) {
+ openBrowserFunc = func(urlStr string) error {
u, _ := url.Parse(urlStr)
redirectURI := u.Query().Get("redirect_uri")
state := u.Query().Get("state")
@@ -211,6 +249,7 @@ func TestInteractiveLoginWithRefresh(t *testing.T) {
time.Sleep(100 * time.Millisecond)
_, _ = http.Get(redirectURI + "?code=dev_code_123&state=" + state)
}()
+ return nil
}
defer func() { openBrowserFunc = originalOpenBrowser }()
@@ -233,6 +272,187 @@ func TestInteractiveLoginWithRefresh(t *testing.T) {
}
}
+func TestInteractiveLoginWithDeviceAuth_Headless(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) {
+ if r.Method != "POST" {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ _ = r.ParseForm()
+ if r.FormValue("client_id") != "client_id_test" {
+ http.Error(w, "Invalid client_id", http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
+ "device_code": "dev_code_1",
+ "user_code": "ABCD-EFGH",
+ "verification_uri": "https://example.com/device",
+ "verification_uri_complete": "https://example.com/device?user_code=ABCD-EFGH",
+ "expires_in": 60,
+ "interval": 1,
+ })
+ })
+
+ pollCount := 0
+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "POST" {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ _ = r.ParseForm()
+ if r.FormValue("grant_type") != "urn:ietf:params:oauth:grant-type:device_code" {
+ http.Error(w, "Invalid grant_type", http.StatusBadRequest)
+ return
+ }
+ pollCount++
+ w.Header().Set("Content-Type", "application/json")
+ if pollCount < 2 {
+ w.WriteHeader(http.StatusBadRequest)
+ _ = json.NewEncoder(w).Encode(map[string]string{
+ "error": "authorization_pending",
+ "error_description": "waiting",
+ })
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]string{
+ "id_token": "id_token_from_device",
+ "refresh_token": "refresh_from_device",
+ })
+ })
+
+ server := httptest.NewServer(mux)
+ defer server.Close()
+
+ store, err := NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("Failed to create store: %v", err)
+ }
+ defer func() {
+ if err := store.Close(); err != nil {
+ t.Errorf("failed to close store: %v", err)
+ }
+ }()
+
+ node := &SamNode{Store: store}
+ 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 device flow is used")
+ return nil
+ }
+ defer func() { openBrowserFunc = originalOpenBrowser }()
+
+ token, err := node.InteractiveLoginWithDeviceAuth(
+ ctx,
+ "http://auth.example.com/auth",
+ server.URL+"/token",
+ server.URL+"/device",
+ "client_id_test",
+ "sam-e2e",
+ true,
+ true,
+ )
+ if err != nil {
+ t.Fatalf("InteractiveLoginWithDeviceAuth failed: %v", err)
+ }
+ if token != "id_token_from_device" {
+ t.Fatalf("Expected id_token_from_device, got %q", token)
+ }
+
+ savedRefresh, err := store.LoadRefreshToken()
+ if err != nil {
+ t.Fatalf("Failed to load refresh token: %v", err)
+ }
+ if savedRefresh != "refresh_from_device" {
+ t.Fatalf("Expected refresh_from_device, got %q", savedRefresh)
+ }
+}
+
+// TestInteractiveLoginBrowserFailFallsBackToDevice verifies that in an
+// interactive (non-headless) flow, if the browser cannot be opened, SAM falls
+// back to the device authorization flow when the provider advertises one,
+// instead of leaving the user to paste a callback code.
+func TestInteractiveLoginBrowserFailFallsBackToDevice(t *testing.T) {
+ t.Setenv("SSH_CLIENT", "")
+ t.Setenv("SSH_TTY", "")
+
+ mux := http.NewServeMux()
+
+ mux.HandleFunc("/device", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "POST" {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ _ = r.ParseForm()
+ if r.FormValue("client_id") != "client_id_test" {
+ http.Error(w, "Invalid client_id", http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
+ "device_code": "dev_code_1",
+ "user_code": "WXYZ-1234",
+ "verification_uri": "https://example.com/device",
+ "expires_in": 60,
+ "interval": 1,
+ })
+ })
+
+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "POST" {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ _ = 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": "id_token_after_browser_fail",
+ })
+ })
+
+ 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 {
+ return fmt.Errorf("no browser available")
+ }
+ defer func() { openBrowserFunc = originalOpenBrowser }()
+
+ token, err := node.InteractiveLoginWithDeviceAuth(
+ ctx,
+ "http://auth.example.com/auth",
+ server.URL+"/token",
+ server.URL+"/device",
+ "client_id_test",
+ "sam-e2e",
+ false,
+ false, // interactive: browser flow attempted first, then device fallback
+ )
+ if err != nil {
+ t.Fatalf("InteractiveLoginWithDeviceAuth failed: %v", err)
+ }
+ if token != "id_token_after_browser_fail" {
+ t.Fatalf("Expected id_token_after_browser_fail, 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/quickstart.md b/site/content/docs/quickstart.md
index 32de6395..d6e8ace1 100644
--- a/site/content/docs/quickstart.md
+++ b/site/content/docs/quickstart.md
@@ -91,7 +91,7 @@ sam-node is running in the background.
Stop kill 48213
```
-If no API token is configured (`SAM_API_TOKEN` or `--api-token-path`), `--daemonize` generates one under the data directory and reuses it on later starts. The command is idempotent: re-run it to confirm a node is up. Enrollment still needs a one-time login, so on a node with no identity it tells you to run `sam-node join --headless <control-plane-url>` first.
+If no API token is configured (`SAM_API_TOKEN` or `--api-token-path`), `--daemonize` generates one under the data directory and reuses it on later starts. The command is idempotent: re-run it to confirm a node is up. Enrollment still needs a one-time login, so on a node with no identity it tells you to run `sam-node join --headless <control-plane-url>` first. In headless mode, SAM prefers OAuth device flow automatically when the provider supports it, and falls back to OOB code-paste only when needed.
#### Starting Over
diff --git a/site/content/docs/user/agent-usage.md b/site/content/docs/user/agent-usage.md
index 11ab0c4c..b2003956 100644
--- a/site/content/docs/user/agent-usage.md
+++ b/site/content/docs/user/agent-usage.md
@@ -56,7 +56,7 @@ If you are running the node on a remote server via SSH (without a web browser),
```bash
sam-node join https://bananas.sam-mesh.dev --headless
```
-The CLI will print a verification URL and code (e.g. `https://google.com/device` and `ABCD-EFGH`). Open this URL on your local laptop, enter the code, complete the login, and the remote terminal session will activate automatically.
+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.
### Automatic Token Renewal
To allow long-lived nodes to automatically renew their tokens in the background, request offline access (refreshes the OIDC session):