feat: initial latha-auth CLI for Gitea PKCE relay and Zitadel Device Code
This commit is contained in:
commit
82d6862a0e
9 files changed
+682
No files matched your search
@@ -0,0 +1,3 @@
|
||||
latha-auth
|
||||
*.test
|
||||
.DS_Store
|
||||
@@ -0,0 +1,15 @@
|
||||
# latha-auth
|
||||
|
||||
Zero-localhost OAuth CLI for remote VMs authenticating against Gitea (`git.site.latha.org`) and Zitadel (`auth.site.latha.org`).
|
||||
|
||||
## Commands
|
||||
|
||||
- `latha-auth gitea`: Authenticates with Gitea via PKCE + the `https://deploy.site.latha.org/oauth/callback` relay, configures `tea login` (`latha`), and sets up git credentials.
|
||||
- `latha-auth k3s`: Runs Zitadel OAuth 2.0 Device Code flow for K3s Headlamp (`dash.latha.org`, `client_id=400047321930268787`) and saves the token to `~/.config/latha-auth/k3s-token.json` (`0600`).
|
||||
- `latha-auth oidc --client-id <id> [--scope "..."] [--out <path>]`: Generic Zitadel Device Code flow for any `auth.site.latha.org` service.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
go build -o ~/.local/bin/latha-auth ./cmd/latha-auth
|
||||
```
|
||||
@@ -0,0 +1,207 @@
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultGiteaURL = "https://git.site.latha.org"
|
||||
DefaultRelayURL = "https://deploy.site.latha.org"
|
||||
DefaultClientID = "98c0bb53-4019-4295-bed8-122ecbf9c31f"
|
||||
DefaultTeaName = "latha"
|
||||
)
|
||||
|
||||
type TokenResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ErrorDesc string `json:"error_description,omitempty"`
|
||||
}
|
||||
|
||||
type pollResponse struct {
|
||||
Status string `json:"status"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func RedirectURI(relayURL string) string {
|
||||
return strings.TrimRight(relayURL, "/") + "/oauth/callback"
|
||||
}
|
||||
|
||||
func BuildAuthorizeURL(giteaURL, clientID, redirectURI, state, challenge string) string {
|
||||
u, _ := url.Parse(strings.TrimRight(giteaURL, "/") + "/login/oauth/authorize")
|
||||
q := u.Query()
|
||||
q.Set("client_id", clientID)
|
||||
q.Set("redirect_uri", redirectURI)
|
||||
q.Set("response_type", "code")
|
||||
q.Set("state", state)
|
||||
q.Set("code_challenge", challenge)
|
||||
q.Set("code_challenge_method", "S256")
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func PollRelay(ctx context.Context, client *http.Client, relayURL, state string, interval time.Duration) (string, error) {
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
if interval <= 0 {
|
||||
interval = 2 * time.Second
|
||||
}
|
||||
pollURL := strings.TrimRight(relayURL, "/") + "/api/oauth/poll?state=" + url.QueryEscape(state)
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
code, ready, err := pollOnce(ctx, client, pollURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ready {
|
||||
return code, nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pollOnce(ctx context.Context, client *http.Client, pollURL string) (string, bool, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, pollURL, nil)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
var out pollResponse
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return "", false, fmt.Errorf("invalid poll response (%d): %w", resp.StatusCode, err)
|
||||
}
|
||||
|
||||
switch resp.StatusCode {
|
||||
case http.StatusAccepted:
|
||||
return "", false, nil
|
||||
case http.StatusOK:
|
||||
if out.Status == "ready" && out.Code != "" {
|
||||
return out.Code, true, nil
|
||||
}
|
||||
return "", false, fmt.Errorf("unexpected ready payload: %s", string(body))
|
||||
default:
|
||||
return "", false, fmt.Errorf("relay poll failed (%d): %s", resp.StatusCode, string(body))
|
||||
}
|
||||
}
|
||||
|
||||
func ExchangeCode(ctx context.Context, client *http.Client, giteaURL, clientID, redirectURI, code, verifier string) (*TokenResponse, error) {
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
tokenURL := strings.TrimRight(giteaURL, "/") + "/login/oauth/access_token"
|
||||
form := url.Values{}
|
||||
form.Set("grant_type", "authorization_code")
|
||||
form.Set("client_id", clientID)
|
||||
form.Set("code", code)
|
||||
form.Set("redirect_uri", redirectURI)
|
||||
form.Set("code_verifier", verifier)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, 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 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 != "" {
|
||||
msg := tok.ErrorDesc
|
||||
if msg == "" {
|
||||
msg = tok.Error
|
||||
}
|
||||
if msg == "" {
|
||||
msg = string(body)
|
||||
}
|
||||
return nil, fmt.Errorf("token exchange failed (%d): %s", resp.StatusCode, msg)
|
||||
}
|
||||
if tok.AccessToken == "" {
|
||||
return nil, fmt.Errorf("token exchange returned empty access_token")
|
||||
}
|
||||
return &tok, nil
|
||||
}
|
||||
|
||||
func FindTeaBinary(override string) (string, error) {
|
||||
if override != "" {
|
||||
return override, nil
|
||||
}
|
||||
if p, err := exec.LookPath("tea"); err == nil {
|
||||
return p, nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err == nil {
|
||||
candidate := filepath.Join(home, ".local", "bin", "tea")
|
||||
if info, statErr := os.Stat(candidate); statErr == nil && !info.IsDir() {
|
||||
return candidate, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("tea binary not found in PATH or ~/.local/bin/tea")
|
||||
}
|
||||
|
||||
func ConfigureTeaAndGit(ctx context.Context, teaBin, name, giteaURL, token string) error {
|
||||
bin, err := FindTeaBinary(teaBin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Remove existing login with the same name if present so we can cleanly update it.
|
||||
delCmd := exec.CommandContext(ctx, bin, "login", "delete", name)
|
||||
_ = delCmd.Run()
|
||||
|
||||
addCmd := exec.CommandContext(ctx, bin,
|
||||
"login", "add",
|
||||
"--name", name,
|
||||
"--url", strings.TrimRight(giteaURL, "/"),
|
||||
"--token", token,
|
||||
"--git-credentials",
|
||||
)
|
||||
out, err := addCmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("tea login add failed: %w: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestBuildAuthorizeURL(t *testing.T) {
|
||||
uStr := BuildAuthorizeURL(
|
||||
"https://git.site.latha.org",
|
||||
"cid-123",
|
||||
"https://deploy.site.latha.org/oauth/callback",
|
||||
"st-456",
|
||||
"chal-789",
|
||||
)
|
||||
u, err := url.Parse(uStr)
|
||||
if err != nil {
|
||||
t.Fatalf("parse url: %v", err)
|
||||
}
|
||||
if u.Path != "/login/oauth/authorize" {
|
||||
t.Fatalf("unexpected path: %s", u.Path)
|
||||
}
|
||||
q := u.Query()
|
||||
if q.Get("client_id") != "cid-123" ||
|
||||
q.Get("redirect_uri") != "https://deploy.site.latha.org/oauth/callback" ||
|
||||
q.Get("response_type") != "code" ||
|
||||
q.Get("state") != "st-456" ||
|
||||
q.Get("code_challenge") != "chal-789" ||
|
||||
q.Get("code_challenge_method") != "S256" {
|
||||
t.Fatalf("unexpected query params: %v", q)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollRelayAndExchangeCode(t *testing.T) {
|
||||
var polls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/oauth/poll":
|
||||
if r.URL.Query().Get("state") != "st-1" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
n := polls.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if n < 2 {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"status": "pending"})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ready", "code": "code-abc"})
|
||||
|
||||
case "/login/oauth/access_token":
|
||||
if err := r.ParseForm(); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if r.Form.Get("grant_type") != "authorization_code" ||
|
||||
r.Form.Get("client_id") != "cid-1" ||
|
||||
r.Form.Get("code") != "code-abc" ||
|
||||
r.Form.Get("code_verifier") != "ver-xyz" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(TokenResponse{
|
||||
AccessToken: "tok-999",
|
||||
TokenType: "bearer",
|
||||
ExpiresIn: 3600,
|
||||
})
|
||||
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
code, err := PollRelay(ctx, srv.Client(), srv.URL, "st-1", 10*time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatalf("PollRelay: %v", err)
|
||||
}
|
||||
if code != "code-abc" {
|
||||
t.Fatalf("code = %q, want %q", code, "code-abc")
|
||||
}
|
||||
|
||||
tok, err := ExchangeCode(ctx, srv.Client(), srv.URL, "cid-1", RedirectURI(srv.URL), code, "ver-xyz")
|
||||
if err != nil {
|
||||
t.Fatalf("ExchangeCode: %v", err)
|
||||
}
|
||||
if tok.AccessToken != "tok-999" {
|
||||
t.Fatalf("AccessToken = %q, want %q", tok.AccessToken, "tok-999")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDeviceCodeFlowAndSave(t *testing.T) {
|
||||
var attempts atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/oauth/v2/device_authorization":
|
||||
if r.Form.Get("client_id") != "400047321930268787" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(DeviceAuthResponse{
|
||||
DeviceCode: "dev-123",
|
||||
UserCode: "ABCD-EFGH",
|
||||
VerificationURI: "https://auth.site.latha.org/device",
|
||||
VerificationURIComplete: "https://auth.site.latha.org/device?user_code=ABCD-EFGH",
|
||||
ExpiresIn: 300,
|
||||
Interval: 1,
|
||||
})
|
||||
case "/oauth/v2/token":
|
||||
n := attempts.Add(1)
|
||||
if n == 1 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"error": "authorization_pending"})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(TokenResponse{
|
||||
AccessToken: "access-1",
|
||||
IDToken: "id-1",
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: 3600,
|
||||
})
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
da, err := RequestDeviceCode(ctx, srv.Client(), srv.URL, DefaultK3sClientID, DefaultK3sScope)
|
||||
if err != nil {
|
||||
t.Fatalf("RequestDeviceCode: %v", err)
|
||||
}
|
||||
if da.UserCode != "ABCD-EFGH" {
|
||||
t.Fatalf("UserCode = %q, want ABCD-EFGH", da.UserCode)
|
||||
}
|
||||
|
||||
tok, err := PollDeviceToken(ctx, srv.Client(), srv.URL, DefaultK3sClientID, da.DeviceCode, 10*time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatalf("PollDeviceToken: %v", err)
|
||||
}
|
||||
if tok.IDToken != "id-1" {
|
||||
t.Fatalf("IDToken = %q, want id-1", tok.IDToken)
|
||||
}
|
||||
|
||||
outPath := filepath.Join(t.TempDir(), "nested", "k3s-token.json")
|
||||
if err := SaveTokenFile(outPath, tok); err != nil {
|
||||
t.Fatalf("SaveTokenFile: %v", err)
|
||||
}
|
||||
info, err := os.Stat(outPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Stat: %v", err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("file perm = %o, want 0600", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package pkce
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// GenerateVerifier returns a 43-character URL-safe PKCE code verifier.
|
||||
func GenerateVerifier() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate verifier: %w", err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// ChallengeS256 computes the S256 PKCE code challenge for verifier.
|
||||
func ChallengeS256(verifier string) string {
|
||||
sum := sha256.Sum256([]byte(verifier))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// GenerateState returns a random hex-encoded OAuth state token.
|
||||
func GenerateState() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate state: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package pkce
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPKCE(t *testing.T) {
|
||||
v, err := GenerateVerifier()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateVerifier: %v", err)
|
||||
}
|
||||
if len(v) < 43 {
|
||||
t.Fatalf("expected verifier length >= 43, got %d", len(v))
|
||||
}
|
||||
if strings.ContainsAny(v, "+/=") {
|
||||
t.Fatalf("verifier should be base64url without padding: %q", v)
|
||||
}
|
||||
|
||||
c := ChallengeS256(v)
|
||||
sum := sha256.Sum256([]byte(v))
|
||||
want := base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
if c != want {
|
||||
t.Fatalf("ChallengeS256 = %q, want %q", c, want)
|
||||
}
|
||||
|
||||
s1, err := GenerateState()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateState: %v", err)
|
||||
}
|
||||
s2, err := GenerateState()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateState: %v", err)
|
||||
}
|
||||
if len(s1) != 32 || s1 == s2 {
|
||||
t.Fatalf("unexpected state values: %q, %q", s1, s2)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user