Skip to content

Modern Docker Management, Designed for Everyone

feat(cli): switch username and password login to OIDC device code (#1682)

Kyle Mendellc84132ddd5ba
diff --git a/.gitignore b/.gitignore
index f3b080751..e45ff33e5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,4 +47,6 @@ arcane-devcli
# btca
-.btca
\ No newline at end of file
+.btca
+
+cli/arcane-cli
\ No newline at end of file
diff --git a/cli/README.md b/cli/README.md
index b89c8bce6..a12fdd546 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -33,7 +33,7 @@ Set the Arcane server URL:
### Authenticate (choose one)
-#### Option A: JWT login
+#### Option A: Device code (OIDC)
- `arcane auth login`
diff --git a/cli/go.mod b/cli/go.mod
index 6e6180874..592957185 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -4,6 +4,7 @@ go 1.25.6
require (
github.com/charmbracelet/fang v0.4.4
+ github.com/charmbracelet/x/term v0.2.2
github.com/fatih/color v1.18.0
github.com/getarcaneapp/arcane/types v0.0.0-20260110011808-8759100aa57c
github.com/mattn/go-runewidth v0.0.19
@@ -11,7 +12,6 @@ require (
github.com/sirupsen/logrus v1.9.4
github.com/spf13/cobra v1.10.2
go.withmatt.com/size v0.0.0-20250220224316-11aee5773e67
- golang.org/x/term v0.39.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -21,7 +21,6 @@ require (
github.com/charmbracelet/ultraviolet v0.0.0-20251106190538-99ea45596692 // indirect
github.com/charmbracelet/x/ansi v0.11.0 // indirect
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 // indirect
- github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.4.1 // indirect
@@ -57,6 +56,7 @@ require (
golang.org/x/exp v0.0.0-20250911091902-df9299821621 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.40.0 // indirect
+ golang.org/x/term v0.39.0 // indirect
golang.org/x/text v0.33.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
)
diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.go
index ffb291183..0fd916ec1 100644
--- a/cli/pkg/auth/cmd.go
+++ b/cli/pkg/auth/cmd.go
@@ -4,9 +4,11 @@ import (
"encoding/json"
"fmt"
"io"
+ "os"
"strings"
- "syscall"
+ "time"
+ "github.com/charmbracelet/x/term"
"github.com/getarcaneapp/arcane/cli/internal/client"
"github.com/getarcaneapp/arcane/cli/internal/config"
"github.com/getarcaneapp/arcane/cli/internal/output"
@@ -14,7 +16,6 @@ import (
"github.com/getarcaneapp/arcane/types/auth"
"github.com/getarcaneapp/arcane/types/base"
"github.com/spf13/cobra"
- "golang.org/x/term"
)
var jsonOutput bool
@@ -28,51 +29,22 @@ var AuthCmd = &cobra.Command{
var loginCmd = &cobra.Command{
Use: "login",
- Short: "Login to Arcane",
+ Short: "Login to Arcane using OIDC device authorization",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- username, _ := cmd.Flags().GetString("username")
- password, _ := cmd.Flags().GetString("password")
-
- if username == "" {
- fmt.Print("Username: ")
- if _, err := fmt.Scanln(&username); err != nil {
- return fmt.Errorf("failed to read username: %w", err)
- }
- }
-
- if password == "" {
- fmt.Print("Password: ")
- bytePassword, err := term.ReadPassword(int(syscall.Stdin))
- if err != nil {
- return fmt.Errorf("failed to read password: %w", err)
- }
- password = string(bytePassword)
- fmt.Println() // Add newline after hidden password input
- }
-
- c, err := client.NewFromConfig()
+ c, err := client.NewFromConfigUnauthenticated()
if err != nil {
- // Login should work even when no auth has been configured yet.
- c, err = client.NewFromConfigUnauthenticated()
- if err != nil {
- return err
- }
- }
-
- loginReq := auth.Login{
- Username: username,
- Password: password,
+ return err
}
- reqBody, err := json.Marshal(loginReq)
+ reqBody, err := json.Marshal(auth.OidcDeviceAuthRequest{})
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}
- resp, err := c.Post(cmd.Context(), types.Endpoints.AuthLogin(), reqBody)
+ resp, err := c.Post(cmd.Context(), types.Endpoints.OIDCDeviceCode(), reqBody)
if err != nil {
- return fmt.Errorf("login failed: %w", err)
+ return fmt.Errorf("device authorization failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
@@ -82,40 +54,104 @@ var loginCmd = &cobra.Command{
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return fmt.Errorf("login failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
+ return fmt.Errorf("device authorization failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
}
- var result base.ApiResponse[auth.LoginResponse]
- if err := json.Unmarshal(bodyBytes, &result); err != nil {
+ var deviceAuth auth.OidcDeviceAuthResponse
+ if err := json.Unmarshal(bodyBytes, &deviceAuth); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
- if !result.Success || result.Data.Token == "" {
- return fmt.Errorf("login failed: unexpected response from server")
+
+ output.Header("Device Login")
+ output.KeyValue("Verification URL", deviceAuth.VerificationUri)
+ if deviceAuth.VerificationUriComplete != "" {
+ output.KeyValue("Verification URL (complete)", deviceAuth.VerificationUriComplete)
+ }
+ output.KeyValue("User code", deviceAuth.UserCode)
+ output.Info("Complete authorization in your browser to finish login.")
+
+ pollInterval := time.Duration(deviceAuth.Interval) * time.Second
+ if pollInterval <= 0 {
+ pollInterval = 5 * time.Second
}
+ expiresAt := time.Now().Add(time.Duration(deviceAuth.ExpiresIn) * time.Second)
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
+ for {
+ if time.Now().After(expiresAt) {
+ return fmt.Errorf("device authorization expired; run login again")
+ }
+
+ select {
+ case <-time.After(pollInterval):
+ case <-cmd.Context().Done():
+ return cmd.Context().Err()
+ }
+
+ tokenReqBody, err := json.Marshal(auth.OidcDeviceTokenRequest{DeviceCode: deviceAuth.DeviceCode})
if err != nil {
- return fmt.Errorf("failed to marshal JSON: %w", err)
+ return fmt.Errorf("failed to marshal token request: %w", err)
}
- fmt.Println(string(resultBytes))
- return nil
- }
- // Save JWT token to config
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
- cfg.JWTToken = result.Data.Token
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to save token: %w", err)
- }
+ tokenResp, err := c.Post(cmd.Context(), types.Endpoints.OIDCDeviceToken(), tokenReqBody)
+ if err != nil {
+ return fmt.Errorf("device token exchange failed: %w", err)
+ }
- output.Success("Login successful")
- path, _ := config.ConfigPath()
- output.KeyValue("JWT token saved to config", path)
- return nil
+ tokenBody, err := io.ReadAll(tokenResp.Body)
+ _ = tokenResp.Body.Close()
+ if err != nil {
+ return fmt.Errorf("failed to read token response: %w", err)
+ }
+
+ if tokenResp.StatusCode < 200 || tokenResp.StatusCode >= 300 {
+ errCode := extractDeviceAuthErrorCode(string(tokenBody))
+ switch errCode {
+ case "authorization_pending":
+ continue
+ case "slow_down":
+ pollInterval += 5 * time.Second
+ continue
+ case "expired_token":
+ return fmt.Errorf("device authorization expired; run login again")
+ case "access_denied":
+ return fmt.Errorf("device authorization denied")
+ default:
+ return fmt.Errorf("device token exchange failed (status %d): %s", tokenResp.StatusCode, strings.TrimSpace(string(tokenBody)))
+ }
+ }
+
+ var tokenResult auth.OidcDeviceTokenResponse
+ if err := json.Unmarshal(tokenBody, &tokenResult); err != nil {
+ return fmt.Errorf("failed to parse token response: %w", err)
+ }
+ if !tokenResult.Success || tokenResult.Token == "" {
+ return fmt.Errorf("device token exchange failed: unexpected response from server")
+ }
+
+ if jsonOutput {
+ resultBytes, err := json.MarshalIndent(tokenResult, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
+ cfg.JWTToken = tokenResult.Token
+ cfg.APIKey = ""
+ if err := config.Save(cfg); err != nil {
+ return fmt.Errorf("failed to save token: %w", err)
+ }
+
+ output.Success("Login successful")
+ path, _ := config.ConfigPath()
+ output.KeyValue("JWT token saved to config", path)
+ return nil
+ }
},
}
@@ -211,7 +247,7 @@ var passwordCmd = &cobra.Command{
if currentPassword == "" {
fmt.Print("Current password: ")
- bytePassword, err := term.ReadPassword(int(syscall.Stdin))
+ bytePassword, err := term.ReadPassword(os.Stdin.Fd())
if err != nil {
return fmt.Errorf("failed to read current password: %w", err)
}
@@ -221,7 +257,7 @@ var passwordCmd = &cobra.Command{
if newPassword == "" {
fmt.Print("New password: ")
- bytePassword, err := term.ReadPassword(int(syscall.Stdin))
+ bytePassword, err := term.ReadPassword(os.Stdin.Fd())
if err != nil {
return fmt.Errorf("failed to read new password: %w", err)
}
@@ -338,8 +374,6 @@ func init() {
AuthCmd.AddCommand(refreshCmd)
// Login command flags
- loginCmd.Flags().StringP("username", "u", "", "Username")
- loginCmd.Flags().StringP("password", "p", "", "Password")
loginCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
// Password command flags
@@ -355,3 +389,36 @@ func init() {
logoutCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
meCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
+
+func extractDeviceAuthErrorCode(body string) string {
+ trimmed := strings.TrimSpace(body)
+ if trimmed == "" {
+ return ""
+ }
+
+ var detail struct {
+ Detail string `json:"detail"`
+ Error string `json:"error"`
+ }
+ if err := json.Unmarshal([]byte(trimmed), &detail); err == nil {
+ if detail.Detail != "" {
+ trimmed = detail.Detail
+ } else if detail.Error != "" {
+ trimmed = detail.Error
+ }
+ }
+
+ lower := strings.ToLower(trimmed)
+ switch {
+ case strings.Contains(lower, "authorization_pending"):
+ return "authorization_pending"
+ case strings.Contains(lower, "slow_down"):
+ return "slow_down"
+ case strings.Contains(lower, "expired_token"):
+ return "expired_token"
+ case strings.Contains(lower, "access_denied"):
+ return "access_denied"
+ default:
+ return ""
+ }
+}
diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.go
index 51d177029..bc01969a4 100644
--- a/cli/pkg/config/cmd.go
+++ b/cli/pkg/config/cmd.go
@@ -59,7 +59,7 @@ var configSetCmd = &cobra.Command{
Examples:
arcane config set --server-url http://localhost:3553
arcane config set --api-key arc_xxxxxxxxxxxxx
- arcane auth login --username admin
+ arcane auth login
arcane config set --jwt-token eyJhbGciOi...`,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()