Skip to content

Agent Mesh

node: address review feedback on device auth flow

Antonio Ojea230a21ac43c2
diff --git a/internal/node/oidc.go b/internal/node/oidc.go
index 26644314..b06deab6 100644
--- a/internal/node/oidc.go
+++ b/internal/node/oidc.go
@@ -32,6 +32,7 @@ import (
"time"
"github.com/coreos/go-oidc/v3/oidc"
+ "github.com/mattn/go-isatty"
"golang.org/x/oauth2/clientcredentials"
)
@@ -378,11 +379,8 @@ func (n *SamNode) InteractiveLoginWithMode(ctx context.Context, authURL, tokenUR
}
func stdinIsInteractive() bool {
- fi, err := os.Stdin.Stat()
- if err != nil {
- return false
- }
- return (fi.Mode() & os.ModeCharDevice) != 0
+ fd := os.Stdin.Fd()
+ return isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd)
}
// DeviceLogin performs OAuth 2.0 Device Authorization Grant (RFC 8628).
@@ -505,7 +503,15 @@ func (n *SamNode) DeviceLogin(ctx context.Context, deviceAuthURL, tokenURL, clie
tokenResp, err := client.Do(tokenReq)
if err != nil {
- return "", fmt.Errorf("token polling request failed: %w", err)
+ // Transient network errors shouldn't abort the whole device flow: log
+ // and keep polling until the context is cancelled or the code expires.
+ logger.Warnf("Token polling request failed: %v. Retrying in %v...", err, pollInterval)
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ case <-time.After(pollInterval):
+ }
+ continue
}
body, readErr := io.ReadAll(tokenResp.Body)
diff --git a/internal/node/oidc_test.go b/internal/node/oidc_test.go
index 6037a54e..14a07650 100644
--- a/internal/node/oidc_test.go
+++ b/internal/node/oidc_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"net/url"
"strings"
+ "sync/atomic"
"testing"
"time"
)
@@ -453,6 +454,62 @@ func TestInteractiveLoginBrowserFailFallsBackToDevice(t *testing.T) {
}
}
+// TestDeviceLoginRetriesOnTransientTokenError verifies that a transient
+// network error while polling the token endpoint doesn't abort the device
+// flow: DeviceLogin should log a warning, wait for the next poll interval,
+// and keep polling until it succeeds (or the context/expiry ends it).
+func TestDeviceLoginRetriesOnTransientTokenError(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/device", func(w http.ResponseWriter, r *http.Request) {
+ 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,
+ })
+ })
+
+ var pollCount int32
+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
+ if atomic.AddInt32(&pollCount, 1) == 1 {
+ // Simulate a transient network error on the first poll by closing
+ // the connection without writing a response.
+ hj, ok := w.(http.Hijacker)
+ if !ok {
+ t.Fatal("ResponseWriter does not support hijacking")
+ }
+ conn, _, err := hj.Hijack()
+ if err != nil {
+ t.Fatalf("failed to hijack connection: %v", err)
+ }
+ _ = conn.Close()
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]string{"id_token": "token_after_retry"})
+ })
+
+ server := httptest.NewServer(mux)
+ defer server.Close()
+
+ node := &SamNode{}
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ token, err := node.DeviceLogin(ctx, server.URL+"/device", server.URL+"/token", "client_id_test", "sam-e2e", false)
+ if err != nil {
+ t.Fatalf("DeviceLogin failed: %v", err)
+ }
+ if token != "token_after_retry" {
+ t.Fatalf("Expected token_after_retry, got %q", token)
+ }
+ if got := atomic.LoadInt32(&pollCount); got < 2 {
+ t.Fatalf("expected at least 2 poll attempts, got %d", got)
+ }
+}
+
func TestParseAuthMode(t *testing.T) {
cases := []struct {
in string
diff --git a/tests/e2e/auth_flows.bats b/tests/e2e/auth_flows.bats
index d0fd6fa3..266fa019 100644
--- a/tests/e2e/auth_flows.bats
+++ b/tests/e2e/auth_flows.bats
@@ -37,7 +37,10 @@ teardown() {
[[ -n "${token}" ]]
- # 2. Run sam-node join to enroll and store identity
+ # 2. Run sam-node join to enroll and store identity. The sam-node image has
+ # no browser to open, so the loopback flow can't complete; join falls back
+ # to the OAuth 2.0 Device Authorization Grant (RFC 8628), which the mock
+ # OIDC provider advertises and auto-approves on the first poll.
local node_name="${MESH_PREFIX}-node-login"
local router_peer_id
router_peer_id=$(cat "/tmp/${MESH_PREFIX}-router-peer-id")
@@ -45,49 +48,26 @@ teardown() {
local data_vol="${MESH_PREFIX}-data"
docker volume create "${data_vol}"
CLEANUP_VOLUMES+=("${data_vol}")
-
- docker run --name "${node_name}-join" \
+
+ docker run -d --name "${node_name}-join" \
--network "${MESH_NETWORK}" \
$(mesh_get_add_hosts) \
-v "${data_vol}:/data" \
"sam-node:local" \
- join --data-dir /data "http://sam-control-plane:8080" > "/tmp/${node_name}-join.out" 2>&1 &
- local join_pid=$!
+ join --data-dir /data "http://sam-control-plane:8080"
MESH_CONTAINERS+=("${node_name}-join")
- # Wait for redirect_uri and state in the output
- local redirect_uri=""
- local state=""
- local port=""
- for i in {1..20}; do
- if grep -q "redirect_uri=" "/tmp/${node_name}-join.out"; then
- # Output format: http://mock-oidc...redirect_uri=http%3A%2F%2F127.0.0.1%3A<PORT>%2Fcallback&...&state=<STATE>
- local line
- line=$(grep "redirect_uri=" "/tmp/${node_name}-join.out" | head -n 1)
- redirect_uri=$(echo "$line" | grep -o 'redirect_uri=[^&]*' | cut -d= -f2 | tr -d '\r\n')
- state=$(echo "$line" | grep -o 'state=[^&]*' | cut -d= -f2 | tr -d '\r\n')
-
- # URL decode redirect_uri
- # e.g. http%3A%2F%2F127.0.0.1%3A41353%2Fcallback -> http://127.0.0.1:41353/callback
- redirect_uri=$(echo "$redirect_uri" | sed -e 's/%3A/:/g' -e 's/%2F/\//g')
-
- port=$(echo "$redirect_uri" | grep -o ':[0-9]*' | tr -d ':\r\n')
- if [[ -n "$port" && -n "$state" ]]; then
- break
- fi
- fi
- sleep 1
- done
-
- [[ -n "$port" ]] && [[ -n "$state" ]]
-
- # Trigger the callback in the sam-node container's network namespace
- docker run --rm --network "container:${node_name}-join" python:3.12 python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:${port}/callback?code=dev_code_123&state=${state}')"
-
- # Wait for the join process to finish
- wait $join_pid
+ run mesh_wait_for_log "${node_name}-join" "OAuth Device Authorization Flow" 20
+ [[ "$status" -eq 0 ]]
+ run mesh_wait_for_log "${node_name}-join" "Enter code: ABCD-1234" 20
+ [[ "$status" -eq 0 ]]
+
+ # Wait for the join process to finish and check it succeeded.
+ run mesh_wait_for_log "${node_name}-join" "Successfully joined the Sovereign Agent Mesh!" 20
+ [[ "$status" -eq 0 ]]
+ [[ "$(docker inspect -f '{{.State.ExitCode}}' "${node_name}-join")" -eq 0 ]]
docker rm -f "${node_name}-join" >/dev/null 2>&1 || true
-
+
# Now run the node with the stored identity
docker run -d \
--name "${node_name}" \