193 lines
5.1 KiB
Go
193 lines
5.1 KiB
Go
package oidc
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
DefaultAuthURL = "https://auth.site.latha.org"
|
|
DefaultK3sClientID = "400047321930268787"
|
|
DefaultK3sScope = "openid profile email groups"
|
|
)
|
|
|
|
type DeviceAuthResponse 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"`
|
|
Error string `json:"error,omitempty"`
|
|
ErrorDescription string `json:"error_description,omitempty"`
|
|
}
|
|
|
|
type TokenResponse struct {
|
|
AccessToken string `json:"access_token"`
|
|
TokenType string `json:"token_type"`
|
|
ExpiresIn int `json:"expires_in"`
|
|
RefreshToken string `json:"refresh_token,omitempty"`
|
|
IDToken string `json:"id_token,omitempty"`
|
|
Scope string `json:"scope,omitempty"`
|
|
ObtainedAt string `json:"obtained_at,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
ErrorDescription string `json:"error_description,omitempty"`
|
|
}
|
|
|
|
func RequestDeviceCode(ctx context.Context, client *http.Client, authURL, clientID, scope string) (*DeviceAuthResponse, error) {
|
|
if client == nil {
|
|
client = &http.Client{Timeout: 15 * time.Second}
|
|
}
|
|
endpoint := strings.TrimRight(authURL, "/") + "/oauth/v2/device_authorization"
|
|
form := url.Values{}
|
|
form.Set("client_id", clientID)
|
|
if scope != "" {
|
|
form.Set("scope", scope)
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
req.Header.Set("Accept", "application/json")
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var out DeviceAuthResponse
|
|
if err := json.Unmarshal(body, &out); err != nil {
|
|
return nil, fmt.Errorf("decode device_authorization (%d): %w", resp.StatusCode, err)
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 || out.Error != "" {
|
|
msg := out.ErrorDescription
|
|
if msg == "" {
|
|
msg = out.Error
|
|
}
|
|
if msg == "" {
|
|
msg = string(body)
|
|
}
|
|
return nil, fmt.Errorf("device authorization failed (%d): %s", resp.StatusCode, msg)
|
|
}
|
|
if out.DeviceCode == "" {
|
|
return nil, fmt.Errorf("device authorization returned empty device_code")
|
|
}
|
|
return &out, nil
|
|
}
|
|
|
|
func PollDeviceToken(ctx context.Context, client *http.Client, authURL, clientID, deviceCode string, interval time.Duration) (*TokenResponse, error) {
|
|
if client == nil {
|
|
client = &http.Client{Timeout: 15 * time.Second}
|
|
}
|
|
if interval <= 0 {
|
|
interval = 5 * time.Second
|
|
}
|
|
endpoint := strings.TrimRight(authURL, "/") + "/oauth/v2/token"
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
case <-time.After(interval):
|
|
}
|
|
|
|
form := url.Values{}
|
|
form.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
|
|
form.Set("device_code", deviceCode)
|
|
form.Set("client_id", clientID)
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
req.Header.Set("Accept", "application/json")
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
resp.Body.Close()
|
|
if readErr != nil {
|
|
return nil, readErr
|
|
}
|
|
|
|
var tok TokenResponse
|
|
if err := json.Unmarshal(body, &tok); err != nil {
|
|
return nil, fmt.Errorf("decode token response (%d): %w", resp.StatusCode, err)
|
|
}
|
|
|
|
if resp.StatusCode >= 200 && resp.StatusCode < 300 && tok.Error == "" {
|
|
tok.ObtainedAt = time.Now().UTC().Format(time.RFC3339)
|
|
return &tok, nil
|
|
}
|
|
|
|
switch tok.Error {
|
|
case "authorization_pending":
|
|
continue
|
|
case "slow_down":
|
|
interval += 5 * time.Second
|
|
continue
|
|
default:
|
|
msg := tok.ErrorDescription
|
|
if msg == "" {
|
|
msg = tok.Error
|
|
}
|
|
if msg == "" {
|
|
msg = string(body)
|
|
}
|
|
return nil, fmt.Errorf("device token polling failed (%d): %s", resp.StatusCode, msg)
|
|
}
|
|
}
|
|
}
|
|
|
|
func ExpandPath(p string) (string, error) {
|
|
if strings.HasPrefix(p, "~/") {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return filepath.Join(home, p[2:]), nil
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func SaveTokenFile(path string, tok *TokenResponse) error {
|
|
resolved, err := ExpandPath(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(resolved), 0o700); err != nil {
|
|
return fmt.Errorf("create config dir: %w", err)
|
|
}
|
|
data, err := json.MarshalIndent(tok, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
data = append(data, '\n')
|
|
if err := os.WriteFile(resolved, data, 0o600); err != nil {
|
|
return fmt.Errorf("write token file: %w", err)
|
|
}
|
|
if err := os.Chmod(resolved, 0o600); err != nil {
|
|
return fmt.Errorf("chmod token file: %w", err)
|
|
}
|
|
return nil
|
|
}
|