Skip to content

Modern Docker Management, Designed for Everyone

feat: arcane-cli device code authentication (#1521)

Kyle Mendella38b8d67c994
diff --git a/backend/internal/huma/handlers/oidc.go b/backend/internal/huma/handlers/oidc.go
index b8e6b2d9b..70576fc81 100644
--- a/backend/internal/huma/handlers/oidc.go
+++ b/backend/internal/huma/handlers/oidc.go
@@ -69,6 +69,21 @@ type GetOidcConfigOutput struct {
Body auth.OidcConfigResponse
}
+type InitiateDeviceAuthInput struct{}
+
+type InitiateDeviceAuthOutput struct {
+ Body auth.OidcDeviceAuthResponse
+}
+
+type ExchangeDeviceTokenInput struct {
+ Body auth.OidcDeviceTokenRequest
+}
+
+type ExchangeDeviceTokenOutput struct {
+ SetCookie []string `header:"Set-Cookie" doc:"Session token cookie"`
+ Body auth.OidcDeviceTokenResponse
+}
+
// ============================================================================
// Registration
// ============================================================================
@@ -112,6 +127,24 @@ func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *
Description: "Process the OIDC callback and complete authentication",
Tags: []string{"OIDC"},
}, h.HandleOidcCallback)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "initiate-oidc-device-auth",
+ Method: http.MethodPost,
+ Path: "/oidc/device/code",
+ Summary: "Initiate OIDC device authorization",
+ Description: "Start the device authorization flow for CLI authentication",
+ Tags: []string{"OIDC"},
+ }, h.InitiateDeviceAuth)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "exchange-oidc-device-token",
+ Method: http.MethodPost,
+ Path: "/oidc/device/token",
+ Summary: "Exchange device code for tokens",
+ Description: "Exchange a device code for authentication tokens",
+ Tags: []string{"OIDC"},
+ }, h.ExchangeDeviceToken)
}
// ============================================================================
@@ -153,13 +186,14 @@ func (h *OidcHandler) GetOidcConfig(ctx context.Context, input *GetOidcConfigInp
return &GetOidcConfigOutput{
Body: auth.OidcConfigResponse{
- ClientID: config.ClientID,
- RedirectUri: h.oidcService.GetOidcRedirectURL(origin),
- IssuerUrl: config.IssuerURL,
- AuthorizationEndpoint: config.AuthorizationEndpoint,
- TokenEndpoint: config.TokenEndpoint,
- UserinfoEndpoint: config.UserinfoEndpoint,
- Scopes: config.Scopes,
+ ClientID: config.ClientID,
+ RedirectUri: h.oidcService.GetOidcRedirectURL(origin),
+ IssuerUrl: config.IssuerURL,
+ AuthorizationEndpoint: config.AuthorizationEndpoint,
+ TokenEndpoint: config.TokenEndpoint,
+ UserinfoEndpoint: config.UserinfoEndpoint,
+ DeviceAuthorizationEndpoint: config.DeviceAuthorizationEndpoint,
+ Scopes: config.Scopes,
},
}, nil
}
@@ -258,3 +292,88 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC
},
}, nil
}
+
+// InitiateDeviceAuth initiates the OIDC device authorization flow.
+func (h *OidcHandler) InitiateDeviceAuth(ctx context.Context, _ *InitiateDeviceAuthInput) (*InitiateDeviceAuthOutput, error) {
+ if h.authService == nil || h.oidcService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ enabled, err := h.authService.IsOidcEnabled(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.OidcStatusCheckError{}).Error())
+ }
+ if !enabled {
+ return nil, huma.Error400BadRequest((&common.OidcDisabledError{}).Error())
+ }
+
+ response, err := h.oidcService.InitiateDeviceAuth(ctx)
+ if err != nil {
+ slog.WarnContext(ctx, "Device authorization initiation failed", "error", err)
+ return nil, huma.Error500InternalServerError((&common.OidcAuthUrlGenerationError{Err: err}).Error())
+ }
+
+ return &InitiateDeviceAuthOutput{
+ Body: *response,
+ }, nil
+}
+
+// ExchangeDeviceToken exchanges a device code for authentication tokens.
+func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDeviceTokenInput) (*ExchangeDeviceTokenOutput, error) {
+ if h.authService == nil || h.oidcService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.Body.DeviceCode == "" {
+ return nil, huma.Error400BadRequest("device code is required")
+ }
+
+ userInfo, tokenResp, err := h.oidcService.ExchangeDeviceToken(ctx, input.Body.DeviceCode)
+ if err != nil {
+ errMsg := err.Error()
+ switch errMsg {
+ case "authorization_pending":
+ return nil, huma.Error400BadRequest("authorization_pending")
+ case "slow_down":
+ return nil, huma.Error400BadRequest("slow_down")
+ case "expired_token":
+ return nil, huma.Error400BadRequest("expired_token")
+ case "access_denied":
+ return nil, huma.Error403Forbidden("access_denied")
+ default:
+ slog.WarnContext(ctx, "Device token exchange failed", "error", err)
+ return nil, huma.Error400BadRequest((&common.OidcCallbackError{Err: err}).Error())
+ }
+ }
+
+ userModel, tokenPair, err := h.authService.OidcLogin(ctx, *userInfo, tokenResp)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.AuthFailedError{Err: err}).Error())
+ }
+
+ maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
+ if maxAge < 0 {
+ maxAge = 0
+ }
+ maxAge += 60
+
+ tokenCookie := cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken)
+
+ return &ExchangeDeviceTokenOutput{
+ SetCookie: []string{tokenCookie},
+ Body: auth.OidcDeviceTokenResponse{
+ Success: true,
+ Token: tokenPair.AccessToken,
+ RefreshToken: tokenPair.RefreshToken,
+ ExpiresAt: tokenPair.ExpiresAt,
+ User: user.User{
+ ID: userModel.ID,
+ Username: userModel.Username,
+ DisplayName: userModel.DisplayName,
+ Email: userModel.Email,
+ Roles: userModel.Roles,
+ OidcSubjectId: userModel.OidcSubjectId,
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.go
index 8e2330807..a244d00d8 100644
--- a/backend/internal/models/settings.go
+++ b/backend/internal/models/settings.go
@@ -72,23 +72,24 @@ type Settings struct {
DockerHost SettingVariable `key:"dockerHost,public,envOverride" meta:"label=Docker Host;type=text;keywords=docker,host,daemon,socket,unix,remote;category=internal;description=URI for Docker daemon"`
// Security category
- AuthLocalEnabled SettingVariable `key:"authLocalEnabled,public" meta:"label=Local Authentication;type=boolean;keywords=local,auth,authentication,username,password,login,credentials;category=security;description=Enable local username/password authentication" catmeta:"id=security;title=Security;icon=shield;url=/settings/security;description=Manage authentication and security settings"`
- AuthSessionTimeout SettingVariable `key:"authSessionTimeout" meta:"label=Session Timeout;type=number;keywords=session,timeout,expire,duration,lifetime,minutes,logout;category=security;description=How long user sessions remain active"`
- AuthPasswordPolicy SettingVariable `key:"authPasswordPolicy" meta:"label=Password Policy;type=select;keywords=password,policy,strength,complexity,requirements,security,rules;category=security;description=Set password strength requirements"`
- AuthOidcConfig SettingVariable `key:"authOidcConfig,sensitive,deprecated" meta:"label=OIDC Config;type=text;keywords=oidc,config,client,id,issuer,secret,oauth;category=security;description=OIDC provider configuration (deprecated - use individual fields)"`
- OidcEnabled SettingVariable `key:"oidcEnabled,public,envOverride" meta:"label=OIDC Authentication;type=boolean;keywords=oidc,openid,connect,sso,oauth,external,provider,federation;category=security;description=Enable OpenID Connect (OIDC) authentication"`
- OidcClientId SettingVariable `key:"oidcClientId,public,envOverride" meta:"label=OIDC Client ID;type=text;keywords=oidc,client,id,oauth,openid;category=security;description=OIDC provider client ID"`
- OidcClientSecret SettingVariable `key:"oidcClientSecret,sensitive,envOverride" meta:"label=OIDC Client Secret;type=password;keywords=oidc,client,secret,oauth,openid;category=security;description=OIDC provider client secret"`
- OidcIssuerUrl SettingVariable `key:"oidcIssuerUrl,public,envOverride" meta:"label=OIDC Issuer URL;type=text;keywords=oidc,issuer,url,oauth,openid,provider;category=security;description=OIDC provider issuer URL"`
- OidcAuthorizationEndpoint SettingVariable `key:"oidcAuthorizationEndpoint,envOverride" meta:"label=OIDC Authorization Endpoint;type=text;keywords=oidc,authorization,endpoint,oauth,openid;category=security;description=Override OIDC authorization endpoint"`
- OidcTokenEndpoint SettingVariable `key:"oidcTokenEndpoint,envOverride" meta:"label=OIDC Token Endpoint;type=text;keywords=oidc,token,endpoint,oauth,openid;category=security;description=Override OIDC token endpoint"`
- OidcUserinfoEndpoint SettingVariable `key:"oidcUserinfoEndpoint,envOverride" meta:"label=OIDC Userinfo Endpoint;type=text;keywords=oidc,userinfo,endpoint,oauth,openid;category=security;description=Override OIDC userinfo endpoint"`
- OidcJwksEndpoint SettingVariable `key:"oidcJwksEndpoint,envOverride" meta:"label=OIDC JWKS Endpoint;type=text;keywords=oidc,jwks,keys,endpoint,oauth,openid;category=security;description=Override OIDC JWKS endpoint"`
- OidcScopes SettingVariable `key:"oidcScopes,public,envOverride" meta:"label=OIDC Scopes;type=text;keywords=oidc,scopes,oauth,openid,permissions;category=security;description=OIDC scopes to request"`
- OidcAdminClaim SettingVariable `key:"oidcAdminClaim,public,envOverride" meta:"label=OIDC Admin Claim;type=text;keywords=oidc,admin,claim,role,group;category=security;description=Claim name for admin role mapping"`
- OidcAdminValue SettingVariable `key:"oidcAdminValue,public,envOverride" meta:"label=OIDC Admin Value;type=text;keywords=oidc,admin,value,role,group;category=security;description=Claim value that grants admin access"`
- OidcSkipTlsVerify SettingVariable `key:"oidcSkipTlsVerify,public,envOverride" meta:"label=OIDC Skip TLS Verify;type=boolean;keywords=oidc,tls,verify,skip,insecure;category=security;description=Skip TLS verification for OIDC provider"`
- OidcMergeAccounts SettingVariable `key:"oidcMergeAccounts,public,envOverride" meta:"label=OIDC Account Merging;type=boolean;keywords=oidc,merge,link,accounts,email,match,existing,users,combine;category=security;description=Allow OIDC logins to merge with existing accounts by email"`
+ AuthLocalEnabled SettingVariable `key:"authLocalEnabled,public" meta:"label=Local Authentication;type=boolean;keywords=local,auth,authentication,username,password,login,credentials;category=security;description=Enable local username/password authentication" catmeta:"id=security;title=Security;icon=shield;url=/settings/security;description=Manage authentication and security settings"`
+ AuthSessionTimeout SettingVariable `key:"authSessionTimeout" meta:"label=Session Timeout;type=number;keywords=session,timeout,expire,duration,lifetime,minutes,logout;category=security;description=How long user sessions remain active"`
+ AuthPasswordPolicy SettingVariable `key:"authPasswordPolicy" meta:"label=Password Policy;type=select;keywords=password,policy,strength,complexity,requirements,security,rules;category=security;description=Set password strength requirements"`
+ AuthOidcConfig SettingVariable `key:"authOidcConfig,sensitive,deprecated" meta:"label=OIDC Config;type=text;keywords=oidc,config,client,id,issuer,secret,oauth;category=security;description=OIDC provider configuration (deprecated - use individual fields)"`
+ OidcEnabled SettingVariable `key:"oidcEnabled,public,envOverride" meta:"label=OIDC Authentication;type=boolean;keywords=oidc,openid,connect,sso,oauth,external,provider,federation;category=security;description=Enable OpenID Connect (OIDC) authentication"`
+ OidcClientId SettingVariable `key:"oidcClientId,public,envOverride" meta:"label=OIDC Client ID;type=text;keywords=oidc,client,id,oauth,openid;category=security;description=OIDC provider client ID"`
+ OidcClientSecret SettingVariable `key:"oidcClientSecret,sensitive,envOverride" meta:"label=OIDC Client Secret;type=password;keywords=oidc,client,secret,oauth,openid;category=security;description=OIDC provider client secret"`
+ OidcIssuerUrl SettingVariable `key:"oidcIssuerUrl,public,envOverride" meta:"label=OIDC Issuer URL;type=text;keywords=oidc,issuer,url,oauth,openid,provider;category=security;description=OIDC provider issuer URL"`
+ OidcAuthorizationEndpoint SettingVariable `key:"oidcAuthorizationEndpoint,envOverride" meta:"label=OIDC Authorization Endpoint;type=text;keywords=oidc,authorization,endpoint,oauth,openid;category=security;description=Override OIDC authorization endpoint"`
+ OidcTokenEndpoint SettingVariable `key:"oidcTokenEndpoint,envOverride" meta:"label=OIDC Token Endpoint;type=text;keywords=oidc,token,endpoint,oauth,openid;category=security;description=Override OIDC token endpoint"`
+ OidcUserinfoEndpoint SettingVariable `key:"oidcUserinfoEndpoint,envOverride" meta:"label=OIDC Userinfo Endpoint;type=text;keywords=oidc,userinfo,endpoint,oauth,openid;category=security;description=Override OIDC userinfo endpoint"`
+ OidcJwksEndpoint SettingVariable `key:"oidcJwksEndpoint,envOverride" meta:"label=OIDC JWKS Endpoint;type=text;keywords=oidc,jwks,keys,endpoint,oauth,openid;category=security;description=Override OIDC JWKS endpoint"`
+ OidcDeviceAuthorizationEndpoint SettingVariable `key:"oidcDeviceAuthorizationEndpoint,envOverride" meta:"label=OIDC Device Authorization Endpoint;type=text;keywords=oidc,device,authorization,endpoint,oauth,openid,cli;category=security;description=Override OIDC device authorization endpoint for CLI authentication"`
+ OidcScopes SettingVariable `key:"oidcScopes,public,envOverride" meta:"label=OIDC Scopes;type=text;keywords=oidc,scopes,oauth,openid,permissions;category=security;description=OIDC scopes to request"`
+ OidcAdminClaim SettingVariable `key:"oidcAdminClaim,public,envOverride" meta:"label=OIDC Admin Claim;type=text;keywords=oidc,admin,claim,role,group;category=security;description=Claim name for admin role mapping"`
+ OidcAdminValue SettingVariable `key:"oidcAdminValue,public,envOverride" meta:"label=OIDC Admin Value;type=text;keywords=oidc,admin,value,role,group;category=security;description=Claim value that grants admin access"`
+ OidcSkipTlsVerify SettingVariable `key:"oidcSkipTlsVerify,public,envOverride" meta:"label=OIDC Skip TLS Verify;type=boolean;keywords=oidc,tls,verify,skip,insecure;category=security;description=Skip TLS verification for OIDC provider"`
+ OidcMergeAccounts SettingVariable `key:"oidcMergeAccounts,public,envOverride" meta:"label=OIDC Account Merging;type=boolean;keywords=oidc,merge,link,accounts,email,match,existing,users,combine;category=security;description=Allow OIDC logins to merge with existing accounts by email"`
// Appearance category
MobileNavigationMode SettingVariable `key:"mobileNavigationMode,public,local" meta:"label=Mobile Navigation Mode;type=select;keywords=mode,style,type,floating,docked,position,layout,design,appearance,bottom;category=appearance;description=Choose between floating or docked navigation on mobile" catmeta:"id=appearance;title=Appearance;icon=appearance;url=/settings/appearance;description=Customize navigation, theme, and interface behavior"`
@@ -267,10 +268,11 @@ type OidcConfig struct {
IssuerURL string `json:"issuerUrl"`
Scopes string `json:"scopes"`
- AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`
- TokenEndpoint string `json:"tokenEndpoint,omitempty"`
- UserinfoEndpoint string `json:"userinfoEndpoint,omitempty"`
- JwksURI string `json:"jwksUri,omitempty"`
+ AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`
+ TokenEndpoint string `json:"tokenEndpoint,omitempty"`
+ UserinfoEndpoint string `json:"userinfoEndpoint,omitempty"`
+ JwksURI string `json:"jwksUri,omitempty"`
+ DeviceAuthorizationEndpoint string `json:"deviceAuthorizationEndpoint,omitempty"`
// Admin mapping: evaluate this claim to grant admin.
// Examples:
diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.go
index 9475a241f..1b9b3c5cc 100644
--- a/backend/internal/services/auth_service.go
+++ b/backend/internal/services/auth_service.go
@@ -86,17 +86,18 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error
if authSettings.OidcEnabled {
oidcConfig := &models.OidcConfig{
- ClientID: settings.OidcClientId.Value,
- ClientSecret: settings.OidcClientSecret.Value,
- IssuerURL: settings.OidcIssuerUrl.Value,
- AuthorizationEndpoint: settings.OidcAuthorizationEndpoint.Value,
- TokenEndpoint: settings.OidcTokenEndpoint.Value,
- UserinfoEndpoint: settings.OidcUserinfoEndpoint.Value,
- JwksURI: settings.OidcJwksEndpoint.Value,
- Scopes: settings.OidcScopes.Value,
- AdminClaim: settings.OidcAdminClaim.Value,
- AdminValue: settings.OidcAdminValue.Value,
- SkipTlsVerify: settings.OidcSkipTlsVerify.IsTrue(),
+ ClientID: settings.OidcClientId.Value,
+ ClientSecret: settings.OidcClientSecret.Value,
+ IssuerURL: settings.OidcIssuerUrl.Value,
+ AuthorizationEndpoint: settings.OidcAuthorizationEndpoint.Value,
+ TokenEndpoint: settings.OidcTokenEndpoint.Value,
+ UserinfoEndpoint: settings.OidcUserinfoEndpoint.Value,
+ JwksURI: settings.OidcJwksEndpoint.Value,
+ DeviceAuthorizationEndpoint: settings.OidcDeviceAuthorizationEndpoint.Value,
+ Scopes: settings.OidcScopes.Value,
+ AdminClaim: settings.OidcAdminClaim.Value,
+ AdminValue: settings.OidcAdminValue.Value,
+ SkipTlsVerify: settings.OidcSkipTlsVerify.IsTrue(),
}
if oidcConfig.ClientID != "" || oidcConfig.IssuerURL != "" {
diff --git a/backend/internal/services/oidc_service.go b/backend/internal/services/oidc_service.go
index 4c0165aaa..006151e4e 100644
--- a/backend/internal/services/oidc_service.go
+++ b/backend/internal/services/oidc_service.go
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"net/http"
+ "net/url"
"strings"
"sync"
"time"
@@ -608,3 +609,251 @@ func (s *OidcService) decodeState(encodedState string) (*OidcState, error) {
return &stateData, nil
}
+
+// InitiateDeviceAuth initiates the OIDC device authorization flow.
+func (s *OidcService) InitiateDeviceAuth(ctx context.Context) (*auth.OidcDeviceAuthResponse, error) {
+ cfg, err := s.getEffectiveConfig(ctx)
+ if err != nil {
+ slog.Error("InitiateDeviceAuth: failed to get OIDC config", "error", err)
+ return nil, err
+ }
+
+ deviceEndpoint, err := s.getDeviceAuthorizationEndpoint(ctx, cfg)
+ if err != nil {
+ slog.Error("InitiateDeviceAuth: failed to get device endpoint", "error", err)
+ return nil, err
+ }
+
+ scopes := strings.Fields(cfg.Scopes)
+ if len(scopes) == 0 {
+ scopes = []string{"email", "profile"}
+ }
+ scopes = s.ensureOpenIDScope(scopes)
+
+ values := url.Values{}
+ values.Set("client_id", cfg.ClientID)
+ values.Set("scope", strings.Join(scopes, " "))
+ if cfg.ClientSecret != "" {
+ values.Set("client_secret", cfg.ClientSecret)
+ }
+
+ respData, err := s.makeDeviceAuthRequest(ctx, deviceEndpoint, values, cfg.SkipTlsVerify)
+ if err != nil {
+ return nil, err
+ }
+
+ deviceCode, ok := respData["device_code"].(string)
+ if !ok || deviceCode == "" {
+ return nil, errors.New("invalid device_code in response")
+ }
+ userCode, ok := respData["user_code"].(string)
+ if !ok || userCode == "" {
+ return nil, errors.New("invalid user_code in response")
+ }
+ verificationUri, ok := respData["verification_uri"].(string)
+ if !ok || verificationUri == "" {
+ return nil, errors.New("invalid verification_uri in response")
+ }
+ expiresIn, ok := respData["expires_in"].(float64)
+ if !ok {
+ return nil, errors.New("invalid expires_in in response")
+ }
+
+ response := &auth.OidcDeviceAuthResponse{
+ DeviceCode: deviceCode,
+ UserCode: userCode,
+ VerificationUri: verificationUri,
+ ExpiresIn: int(expiresIn),
+ }
+
+ if uri, ok := respData["verification_uri_complete"].(string); ok {
+ response.VerificationUriComplete = uri
+ }
+ if interval, ok := respData["interval"].(float64); ok {
+ response.Interval = int(interval)
+ } else {
+ response.Interval = 5
+ }
+
+ slog.Debug("InitiateDeviceAuth: device authorization initiated", "user_code", response.UserCode, "expires_in", response.ExpiresIn)
+ return response, nil
+}
+
+// getDeviceAuthorizationEndpoint discovers or returns the configured device authorization endpoint.
+func (s *OidcService) getDeviceAuthorizationEndpoint(ctx context.Context, cfg *models.OidcConfig) (string, error) {
+ if cfg.DeviceAuthorizationEndpoint != "" {
+ return cfg.DeviceAuthorizationEndpoint, nil
+ }
+
+ provider, err := s.getOrDiscoverProvider(ctx, cfg)
+ if err != nil {
+ return "", fmt.Errorf("failed to discover provider: %w", err)
+ }
+
+ var claims struct {
+ DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
+ }
+ if err := provider.Claims(&claims); err != nil {
+ return "", fmt.Errorf("failed to get device authorization endpoint from provider: %w", err)
+ }
+
+ if claims.DeviceAuthorizationEndpoint == "" {
+ return "", errors.New("device authorization endpoint not found in provider configuration")
+ }
+
+ return claims.DeviceAuthorizationEndpoint, nil
+}
+
+// makeDeviceAuthRequest makes a device authorization request.
+func (s *OidcService) makeDeviceAuthRequest(ctx context.Context, endpoint string, params url.Values, skipTls bool) (map[string]any, error) {
+ body := params.Encode()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(body))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+
+ client := s.getHttpClient(skipTls)
+ resp, err := client.Do(req)
+ if err != nil {
+ slog.Error("makeDeviceAuthRequest: request failed", "error", err)
+ return nil, fmt.Errorf("device authorization request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ var errorResp map[string]any
+ if err := json.NewDecoder(resp.Body).Decode(&errorResp); err == nil {
+ if errMsg, ok := errorResp["error"].(string); ok {
+ return nil, fmt.Errorf("device authorization failed: %s", errMsg)
+ }
+ }
+ return nil, fmt.Errorf("device authorization endpoint returned status %d", resp.StatusCode)
+ }
+
+ var respData map[string]any
+ if err := json.NewDecoder(resp.Body).Decode(&respData); err != nil {
+ return nil, fmt.Errorf("failed to decode device authorization response: %w", err)
+ }
+
+ return respData, nil
+}
+
+// ExchangeDeviceToken exchanges a device code for tokens.
+func (s *OidcService) ExchangeDeviceToken(ctx context.Context, deviceCode string) (*auth.OidcUserInfo, *auth.OidcTokenResponse, error) {
+ cfg, err := s.getEffectiveConfig(ctx)
+ if err != nil {
+ slog.Error("ExchangeDeviceToken: failed to get OIDC config", "error", err)
+ return nil, nil, err
+ }
+
+ var tokenEndpoint string
+ if cfg.TokenEndpoint != "" {
+ tokenEndpoint = cfg.TokenEndpoint
+ } else {
+ provider, err := s.getOrDiscoverProvider(ctx, cfg)
+ if err != nil {
+ return nil, nil, err
+ }
+ tokenEndpoint = provider.Endpoint().TokenURL
+ }
+
+ params := map[string]string{
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": deviceCode,
+ "client_id": cfg.ClientID,
+ }
+ if cfg.ClientSecret != "" {
+ params["client_secret"] = cfg.ClientSecret
+ }
+
+ tokenResp, err := s.makeTokenRequest(ctx, tokenEndpoint, params, cfg.SkipTlsVerify)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ var provider *oidc.Provider
+ if !s.hasManualEndpoints(cfg) {
+ provider, err = s.getOrDiscoverProvider(ctx, cfg)
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+
+ accessToken, ok := tokenResp["access_token"].(string)
+ if !ok || accessToken == "" {
+ return nil, nil, errors.New("invalid access_token in response")
+ }
+
+ token := &oauth2.Token{
+ AccessToken: accessToken,
+ TokenType: stringutils.GetStringOrDefault(tokenResp, "token_type", "Bearer"),
+ }
+ if refreshToken, ok := tokenResp["refresh_token"].(string); ok {
+ token.RefreshToken = refreshToken
+ }
+ if expiresIn, ok := tokenResp["expires_in"].(float64); ok {
+ token.Expiry = time.Now().Add(time.Duration(expiresIn) * time.Second)
+ }
+ if idToken, ok := tokenResp["id_token"].(string); ok {
+ token = token.WithExtra(map[string]any{"id_token": idToken})
+ }
+
+ idToken, rawIDToken, err := s.verifyIDToken(ctx, provider, cfg, token, "")
+ if err != nil {
+ return nil, nil, err
+ }
+
+ return s.buildUserInfo(ctx, provider, cfg, token, idToken, rawIDToken)
+}
+
+// makeTokenRequest makes a token exchange request.
+func (s *OidcService) makeTokenRequest(ctx context.Context, endpoint string, params map[string]string, skipTls bool) (map[string]any, error) {
+ values := url.Values{}
+ for k, v := range params {
+ values.Set(k, v)
+ }
+ body := values.Encode()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(body))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+
+ client := s.getHttpClient(skipTls)
+ resp, err := client.Do(req)
+ if err != nil {
+ slog.Error("makeTokenRequest: request failed", "error", err)
+ return nil, fmt.Errorf("token request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ var tokenResp map[string]any
+ if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
+ return nil, fmt.Errorf("failed to decode token response: %w", err)
+ }
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ if errMsg, ok := tokenResp["error"].(string); ok {
+ switch errMsg {
+ case "authorization_pending":
+ return nil, errors.New("authorization_pending")
+ case "slow_down":
+ return nil, errors.New("slow_down")
+ case "expired_token":
+ return nil, errors.New("expired_token")
+ case "access_denied":
+ return nil, errors.New("access_denied")
+ default:
+ return nil, fmt.Errorf("token exchange failed: %s", errMsg)
+ }
+ }
+ return nil, fmt.Errorf("token endpoint returned status %d", resp.StatusCode)
+ }
+
+ return tokenResp, nil
+}
diff --git a/backend/internal/utils/stringutils/stringutils.go b/backend/internal/utils/stringutils/stringutils.go
index ca384d248..934716b69 100644
--- a/backend/internal/utils/stringutils/stringutils.go
+++ b/backend/internal/utils/stringutils/stringutils.go
@@ -44,3 +44,12 @@ func TrimQuotes(s string) string {
}
return s
}
+
+func GetStringOrDefault(m map[string]any, key, defaultValue string) string {
+ if val, ok := m[key]; ok {
+ if str, ok := val.(string); ok {
+ return str
+ }
+ }
+ return defaultValue
+}
diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.go
index f7747006c..5a43ddb4f 100644
--- a/cli/internal/types/endpoints.go
+++ b/cli/internal/types/endpoints.go
@@ -18,10 +18,12 @@ type ArcaneApiEndpoints struct {
AuthRefreshEndpoint string
// OIDC
- OIDCStatusEndpoint string
- OIDCConfigEndpoint string
- OIDCUrlEndpoint string
- OIDCCallbackEndpoint string
+ OIDCStatusEndpoint string
+ OIDCConfigEndpoint string
+ OIDCUrlEndpoint string
+ OIDCCallbackEndpoint string
+ OIDCDeviceCodeEndpoint string
+ OIDCDeviceTokenEndpoint string
// API Keys
ApiKeysEndpoint string
@@ -176,10 +178,12 @@ var Endpoints = ArcaneApiEndpoints{
AuthRefreshEndpoint: "/api/auth/refresh",
// OIDC
- OIDCStatusEndpoint: "/api/oidc/status",
- OIDCConfigEndpoint: "/api/oidc/config",
- OIDCUrlEndpoint: "/api/oidc/url",
- OIDCCallbackEndpoint: "/api/oidc/callback",
+ OIDCStatusEndpoint: "/api/oidc/status",
+ OIDCConfigEndpoint: "/api/oidc/config",
+ OIDCUrlEndpoint: "/api/oidc/url",
+ OIDCCallbackEndpoint: "/api/oidc/callback",
+ OIDCDeviceCodeEndpoint: "/api/oidc/device/code",
+ OIDCDeviceTokenEndpoint: "/api/oidc/device/token",
// API Keys
ApiKeysEndpoint: "/api/api-keys",
@@ -327,10 +331,12 @@ func (e ArcaneApiEndpoints) AuthPassword() string { return e.AuthPasswordEndpoin
func (e ArcaneApiEndpoints) AuthRefresh() string { return e.AuthRefreshEndpoint }
// OIDC endpoints
-func (e ArcaneApiEndpoints) OIDCStatus() string { return e.OIDCStatusEndpoint }
-func (e ArcaneApiEndpoints) OIDCConfig() string { return e.OIDCConfigEndpoint }
-func (e ArcaneApiEndpoints) OIDCUrl() string { return e.OIDCUrlEndpoint }
-func (e ArcaneApiEndpoints) OIDCCallback() string { return e.OIDCCallbackEndpoint }
+func (e ArcaneApiEndpoints) OIDCStatus() string { return e.OIDCStatusEndpoint }
+func (e ArcaneApiEndpoints) OIDCConfig() string { return e.OIDCConfigEndpoint }
+func (e ArcaneApiEndpoints) OIDCUrl() string { return e.OIDCUrlEndpoint }
+func (e ArcaneApiEndpoints) OIDCCallback() string { return e.OIDCCallbackEndpoint }
+func (e ArcaneApiEndpoints) OIDCDeviceCode() string { return e.OIDCDeviceCodeEndpoint }
+func (e ArcaneApiEndpoints) OIDCDeviceToken() string { return e.OIDCDeviceTokenEndpoint }
// API Key endpoints
func (e ArcaneApiEndpoints) ApiKeys() string { return e.ApiKeysEndpoint }
diff --git a/types/auth/oidc.go b/types/auth/oidc.go
index b0adcd6bf..a42992adf 100644
--- a/types/auth/oidc.go
+++ b/types/auth/oidc.go
@@ -159,6 +159,11 @@ type OidcConfigResponse struct {
// Required: true
UserinfoEndpoint string `json:"userinfoEndpoint"`
+ // DeviceAuthorizationEndpoint is the URL of the device authorization endpoint.
+ //
+ // Required: false
+ DeviceAuthorizationEndpoint string `json:"deviceAuthorizationEndpoint,omitempty"`
+
// Scopes is the space-separated list of OAuth scopes requested.
//
// Required: true
@@ -205,3 +210,80 @@ type OidcCallbackResponse struct {
// Required: true
User user.User `json:"user"`
}
+
+// OidcDeviceAuthRequest is used to request a device authorization code.
+type OidcDeviceAuthRequest struct {
+ // RedirectUri is optional and kept for consistency with other auth flows.
+ //
+ // Required: false
+ RedirectUri string `json:"redirectUri,omitempty"`
+}
+
+// OidcDeviceAuthResponse contains the device authorization response.
+type OidcDeviceAuthResponse struct {
+ // DeviceCode is the device verification code.
+ //
+ // Required: true
+ DeviceCode string `json:"deviceCode"`
+
+ // UserCode is the end-user verification code.
+ //
+ // Required: true
+ UserCode string `json:"userCode"`
+
+ // VerificationUri is the end-user verification URI.
+ //
+ // Required: true
+ VerificationUri string `json:"verificationUri"`
+
+ // VerificationUriComplete is the end-user verification URI with user code included.
+ //
+ // Required: false
+ VerificationUriComplete string `json:"verificationUriComplete,omitempty"`
+
+ // ExpiresIn is the lifetime of the device_code and user_code in seconds.
+ //
+ // Required: true
+ ExpiresIn int `json:"expiresIn"`
+
+ // Interval is the minimum polling interval in seconds.
+ //
+ // Required: false
+ Interval int `json:"interval,omitempty"`
+}
+
+// OidcDeviceTokenRequest is used to exchange a device code for tokens.
+type OidcDeviceTokenRequest struct {
+ // DeviceCode is the device verification code from the authorization response.
+ //
+ // Required: true
+ DeviceCode string `json:"deviceCode"`
+}
+
+// OidcDeviceTokenResponse contains the response from device token exchange.
+type OidcDeviceTokenResponse struct {
+ // Success indicates if the authentication was successful.
+ //
+ // Required: true
+ Success bool `json:"success"`
+
+ // Token is the JWT access token.
+ //
+ // Required: true
+ Token string `json:"token"`
+
+ // RefreshToken is the refresh token for obtaining new access tokens.
+ //
+ // Required: true
+ RefreshToken string `json:"refreshToken"`
+
+ // ExpiresAt is the expiration time of the access token.
+ //
+ // Required: true
+ ExpiresAt time.Time `json:"expiresAt"`
+
+ // User contains the authenticated user information.
+ //
+ // Required: true
+ User user.User `json:"user"`
+}