feat!: remove gitea command in favor of gt
Gitea login is handled by gt directly. The OAuth relay polling that atproto shares moves to internal/relay.
This commit is contained in:
1 parent
a1cfcc1de7
commit
8bc017ca72
6 files changed
+143
-541
No files matched your search
@@ -1,10 +1,11 @@
|
||||
# latha-auth
|
||||
|
||||
Zero-localhost OAuth CLI for remote VMs authenticating against Gitea (`git.site.latha.org`), Zitadel (`auth.site.latha.org`), and AT Protocol (any PDS).
|
||||
Zero-localhost OAuth CLI for remote VMs authenticating against Zitadel (`auth.site.latha.org`), and AT Protocol (any PDS).
|
||||
|
||||
For Gitea (`git.site.latha.org`), use [`gt`](https://gitea.com/gitea/cli) directly: `gt auth login --host https://git.site.latha.org`, then `gt auth setup-git`.
|
||||
|
||||
## Commands
|
||||
|
||||
- `latha-auth gitea`: Authenticates with Gitea via PKCE + the `https://deploy.site.latha.org/oauth/callback` relay, logs in with `gt` ([gitea/cli](https://gitea.com/gitea/cli)), and runs `gt auth setup-git` to configure 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.
|
||||
- `latha-auth atproto --identifier <handle|did> [--scope "..."] [--out <path>]`: AT Protocol OAuth (PAR + PKCE + DPoP) as a public client, collecting the code via the same deploy relay. Saves the session — tokens plus the DPoP private key they are bound to — to `~/.config/latha-auth/atproto-session.json` (`0600`). The client_id defaults to the metadata JSON served by gitea-k3s-deployer at `https://deploy.site.latha.org/oauth/atproto-client-metadata.json` (source copy versioned in this repo at `oauth/atproto-client-metadata.json`; regenerate with `latha-auth atproto --print-client-metadata` after scope/redirect changes, or override with `--client-id` / `LATHA_ATPROTO_CLIENT_ID`).
|
||||
|
||||
+5
-70
@@ -12,12 +12,12 @@ import (
|
||||
"time"
|
||||
|
||||
"git.site.latha.org/experiments/latha-auth/internal/atproto"
|
||||
"git.site.latha.org/experiments/latha-auth/internal/gitea"
|
||||
"git.site.latha.org/experiments/latha-auth/internal/oidc"
|
||||
"git.site.latha.org/experiments/latha-auth/internal/pkce"
|
||||
"git.site.latha.org/experiments/latha-auth/internal/relay"
|
||||
)
|
||||
|
||||
const version = "0.2.0"
|
||||
const version = "0.3.0"
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
@@ -30,8 +30,6 @@ func main() {
|
||||
|
||||
var err error
|
||||
switch os.Args[1] {
|
||||
case "gitea":
|
||||
err = runGitea(ctx, os.Args[2:])
|
||||
case "k3s":
|
||||
err = runK3s(ctx, os.Args[2:])
|
||||
case "oidc":
|
||||
@@ -65,7 +63,6 @@ Usage:
|
||||
latha-auth <command> [flags]
|
||||
|
||||
Commands:
|
||||
gitea Authenticate with Gitea (git.site.latha.org) via PKCE + relay
|
||||
k3s Authenticate with K3s Headlamp (dash.latha.org) via Zitadel Device Code
|
||||
oidc Authenticate with any Zitadel service (auth.site.latha.org) via Device Code
|
||||
atproto Authenticate with AT Protocol via OAuth (PAR + PKCE + DPoP) + relay
|
||||
@@ -76,68 +73,6 @@ Run 'latha-auth <command> --help' for command-specific flags.
|
||||
`)
|
||||
}
|
||||
|
||||
func runGitea(ctx context.Context, args []string) error {
|
||||
defaultClientID := os.Getenv("LATHA_GITEA_CLIENT_ID")
|
||||
if defaultClientID == "" {
|
||||
defaultClientID = gitea.DefaultClientID
|
||||
}
|
||||
|
||||
fs := flag.NewFlagSet("gitea", flag.ContinueOnError)
|
||||
clientID := fs.String("client-id", defaultClientID, "Gitea OAuth2 client ID (or LATHA_GITEA_CLIENT_ID)")
|
||||
giteaURL := fs.String("gitea-url", gitea.DefaultGiteaURL, "Gitea base URL")
|
||||
relayURL := fs.String("relay-url", gitea.DefaultRelayURL, "OAuth callback relay base URL")
|
||||
gtBin := fs.String("gt-bin", "", "Path to gt binary (optional)")
|
||||
credentialStore := fs.String("credential-store", "auto", "Credential store for gt: auto, keyring, or file")
|
||||
timeout := fs.Duration("timeout", 5*time.Minute, "Authorization timeout")
|
||||
noGT := fs.Bool("no-gt", false, "Skip configuring gt/git credentials and print access token")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
verifier, err := pkce.GenerateVerifier()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
state, err := pkce.GenerateState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
challenge := pkce.ChallengeS256(verifier)
|
||||
redirectURI := gitea.RedirectURI(*relayURL)
|
||||
authURL := gitea.BuildAuthorizeURL(*giteaURL, *clientID, redirectURI, state, challenge)
|
||||
|
||||
fmt.Println("Open this URL in your browser to authorize Gitea:")
|
||||
fmt.Println()
|
||||
fmt.Printf(" %s\n\n", authURL)
|
||||
fmt.Println("Waiting for authorization callback...")
|
||||
|
||||
pollCtx, cancel := context.WithTimeout(ctx, *timeout)
|
||||
defer cancel()
|
||||
|
||||
httpClient := &http.Client{Timeout: 15 * time.Second}
|
||||
code, err := gitea.PollRelay(pollCtx, httpClient, *relayURL, state, 2*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tok, err := gitea.ExchangeCode(pollCtx, httpClient, *giteaURL, *clientID, redirectURI, code, verifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if *noGT {
|
||||
fmt.Println(tok.AccessToken)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := gitea.ConfigureGTAndGit(ctx, *gtBin, *giteaURL, tok.AccessToken, *credentialStore); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("Configured gt login (%s) and git credentials.\n", *giteaURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
func runK3s(ctx context.Context, args []string) error {
|
||||
fs := flag.NewFlagSet("k3s", flag.ContinueOnError)
|
||||
clientID := fs.String("client-id", oidc.DefaultK3sClientID, "Zitadel OAuth2 client ID")
|
||||
@@ -225,7 +160,7 @@ func runAtproto(ctx context.Context, args []string) error {
|
||||
identifier := fs.String("identifier", "", "Account handle or DID (required unless --print-client-metadata)")
|
||||
clientID := fs.String("client-id", defaultClientID, "OAuth client_id URL serving the client metadata JSON (or LATHA_ATPROTO_CLIENT_ID)")
|
||||
scope := fs.String("scope", atproto.DefaultScope, "OAuth scope")
|
||||
relayURL := fs.String("relay-url", gitea.DefaultRelayURL, "OAuth callback relay base URL")
|
||||
relayURL := fs.String("relay-url", relay.DefaultURL, "OAuth callback relay base URL")
|
||||
redirectURI := fs.String("redirect-uri", "", "OAuth redirect URI (defaults to <relay-url>/oauth/callback)")
|
||||
outPath := fs.String("out", atproto.DefaultSessionPath, "Output session JSON path")
|
||||
plcURL := fs.String("plc-url", atproto.DefaultPLCURL, "PLC directory base URL")
|
||||
@@ -236,7 +171,7 @@ func runAtproto(ctx context.Context, args []string) error {
|
||||
}
|
||||
|
||||
if *redirectURI == "" {
|
||||
*redirectURI = gitea.RedirectURI(*relayURL)
|
||||
*redirectURI = relay.RedirectURI(*relayURL)
|
||||
}
|
||||
|
||||
if *printMetadata {
|
||||
@@ -298,7 +233,7 @@ func runAtproto(ctx context.Context, args []string) error {
|
||||
pollCtx, cancel := context.WithTimeout(ctx, *timeout)
|
||||
defer cancel()
|
||||
|
||||
code, err := gitea.PollRelay(pollCtx, httpClient, *relayURL, state, 2*time.Second)
|
||||
code, err := relay.Poll(pollCtx, httpClient, *relayURL, state, 2*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
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"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// FindGTBinary locates the Gitea CLI (`gt`) executable from an explicit override, PATH, or ~/.local/bin/gt.
|
||||
func FindGTBinary(override string) (string, error) {
|
||||
if override != "" {
|
||||
return override, nil
|
||||
}
|
||||
if p, err := exec.LookPath("gt"); err == nil {
|
||||
return p, nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err == nil {
|
||||
candidate := filepath.Join(home, ".local", "bin", "gt")
|
||||
if info, statErr := os.Stat(candidate); statErr == nil && !info.IsDir() {
|
||||
return candidate, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("gt binary not found in PATH or ~/.local/bin/gt (install from https://gitea.com/gitea/cli)")
|
||||
}
|
||||
|
||||
// ConfigureGTAndGit logs gt into giteaURL using token and configures Git's credential helper via gt.
|
||||
// credentialStore may be "", "auto", "keyring", or "file".
|
||||
func ConfigureGTAndGit(ctx context.Context, gtBin, giteaURL, token, credentialStore string) error {
|
||||
switch credentialStore {
|
||||
case "", "auto", "keyring", "file":
|
||||
default:
|
||||
return fmt.Errorf("invalid credential store %q (expected auto, keyring, or file)", credentialStore)
|
||||
}
|
||||
|
||||
bin, err := FindGTBinary(gtBin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
baseURL := strings.TrimRight(giteaURL, "/")
|
||||
login := func(store string) ([]byte, error) {
|
||||
args := []string{"auth", "login", "--host", baseURL, "--with-token", "--yes", "--no-input"}
|
||||
if store != "" {
|
||||
args = append(args, "--credential-store", store)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, bin, args...)
|
||||
cmd.Stdin = strings.NewReader(token + "\n")
|
||||
return cmd.CombinedOutput()
|
||||
}
|
||||
|
||||
if credentialStore == "" || credentialStore == "auto" {
|
||||
out, err := login("")
|
||||
if err != nil {
|
||||
msg := strings.TrimSpace(string(out))
|
||||
if isKeyringUnavailable(msg) {
|
||||
out, err = login("file")
|
||||
msg = strings.TrimSpace(string(out))
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("gt auth login failed: %w: %s", err, msg)
|
||||
}
|
||||
}
|
||||
} else if out, err := login(credentialStore); err != nil {
|
||||
return fmt.Errorf("gt auth login failed: %w: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
|
||||
setupCmd := exec.CommandContext(ctx, bin, "auth", "setup-git", "--host", baseURL, "--no-input")
|
||||
if out, err := setupCmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("gt auth setup-git failed: %w: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isKeyringUnavailable(msg string) bool {
|
||||
return strings.Contains(msg, "secure credential storage unavailable") ||
|
||||
strings.Contains(msg, "keyring storage unavailable")
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindGTBinary(t *testing.T) {
|
||||
if got, err := FindGTBinary("/custom/gt"); err != nil || got != "/custom/gt" {
|
||||
t.Fatalf("override = (%q, %v), want (/custom/gt, nil)", got, err)
|
||||
}
|
||||
|
||||
tmp := t.TempDir()
|
||||
binDir := filepath.Join(tmp, "bin")
|
||||
if err := os.MkdirAll(binDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gtPath := filepath.Join(binDir, "gt")
|
||||
if err := os.WriteFile(gtPath, []byte("#!/bin/sh\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Setenv("PATH", binDir)
|
||||
t.Setenv("HOME", tmp)
|
||||
if got, err := FindGTBinary(""); err != nil || got != gtPath {
|
||||
t.Fatalf("PATH lookup = (%q, %v), want (%q, nil)", got, err, gtPath)
|
||||
}
|
||||
|
||||
t.Setenv("PATH", filepath.Join(tmp, "empty"))
|
||||
localBin := filepath.Join(tmp, ".local", "bin")
|
||||
if err := os.MkdirAll(localBin, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
localGT := filepath.Join(localBin, "gt")
|
||||
if err := os.WriteFile(localGT, []byte("#!/bin/sh\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := FindGTBinary(""); err != nil || got != localGT {
|
||||
t.Fatalf("~/.local/bin fallback = (%q, %v), want (%q, nil)", got, err, localGT)
|
||||
}
|
||||
}
|
||||
|
||||
func writeFakeGT(t *testing.T, logPath, scriptBody string) string {
|
||||
t.Helper()
|
||||
gtPath := filepath.Join(t.TempDir(), "gt")
|
||||
script := "#!/bin/sh\nset -eu\nLOG_FILE=" + logPath + "\n" + scriptBody
|
||||
if err := os.WriteFile(gtPath, []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return gtPath
|
||||
}
|
||||
|
||||
func TestConfigureGTAndGit(t *testing.T) {
|
||||
t.Run("default auto succeeds with keyring", func(t *testing.T) {
|
||||
logPath := filepath.Join(t.TempDir(), "calls.log")
|
||||
gtPath := writeFakeGT(t, logPath, `
|
||||
if [ "$1" = "auth" ] && [ "$2" = "login" ]; then
|
||||
token=$(cat)
|
||||
printf "login|%s|%s\n" "$*" "$token" >> "$LOG_FILE"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$1" = "auth" ] && [ "$2" = "setup-git" ]; then
|
||||
printf "setup-git|%s\n" "$*" >> "$LOG_FILE"
|
||||
exit 0
|
||||
fi
|
||||
exit 1
|
||||
`)
|
||||
if err := ConfigureGTAndGit(context.Background(), gtPath, "https://git.site.latha.org/", "secret-tok", "auto"); err != nil {
|
||||
t.Fatalf("ConfigureGTAndGit: %v", err)
|
||||
}
|
||||
got, err := os.ReadFile(logPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "login|auth login --host https://git.site.latha.org --with-token --yes --no-input|secret-tok\n" +
|
||||
"setup-git|auth setup-git --host https://git.site.latha.org --no-input\n"
|
||||
if string(got) != want {
|
||||
t.Fatalf("calls:\n%s\nwant:\n%s", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("auto falls back to file store when keyring unavailable", func(t *testing.T) {
|
||||
logPath := filepath.Join(t.TempDir(), "calls.log")
|
||||
gtPath := writeFakeGT(t, logPath, `
|
||||
if [ "$1" = "auth" ] && [ "$2" = "login" ]; then
|
||||
token=$(cat)
|
||||
printf "login|%s|%s\n" "$*" "$token" >> "$LOG_FILE"
|
||||
case "$*" in
|
||||
*"--credential-store file"*) exit 0 ;;
|
||||
*) echo "error: secure credential storage unavailable; use --credential-store file" >&2; exit 1 ;;
|
||||
esac
|
||||
fi
|
||||
if [ "$1" = "auth" ] && [ "$2" = "setup-git" ]; then
|
||||
printf "setup-git|%s\n" "$*" >> "$LOG_FILE"
|
||||
exit 0
|
||||
fi
|
||||
exit 1
|
||||
`)
|
||||
if err := ConfigureGTAndGit(context.Background(), gtPath, "https://git.site.latha.org", "secret-tok", ""); err != nil {
|
||||
t.Fatalf("ConfigureGTAndGit fallback: %v", err)
|
||||
}
|
||||
got, err := os.ReadFile(logPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "login|auth login --host https://git.site.latha.org --with-token --yes --no-input|secret-tok\n" +
|
||||
"login|auth login --host https://git.site.latha.org --with-token --yes --no-input --credential-store file|secret-tok\n" +
|
||||
"setup-git|auth setup-git --host https://git.site.latha.org --no-input\n"
|
||||
if string(got) != want {
|
||||
t.Fatalf("calls:\n%s\nwant:\n%s", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit keyring does not fall back to file", func(t *testing.T) {
|
||||
logPath := filepath.Join(t.TempDir(), "calls.log")
|
||||
gtPath := writeFakeGT(t, logPath, `
|
||||
echo "error: secure credential storage unavailable" >&2
|
||||
exit 1
|
||||
`)
|
||||
err := ConfigureGTAndGit(context.Background(), gtPath, "https://git.site.latha.org", "secret-tok", "keyring")
|
||||
if err == nil || !strings.Contains(err.Error(), "gt auth login failed") {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid credential store", func(t *testing.T) {
|
||||
err := ConfigureGTAndGit(context.Background(), "/nonexistent/gt", "https://git.site.latha.org", "secret-tok", "bogus")
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid credential store") {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DefaultURL is the OAuth callback relay that collects authorization codes.
|
||||
const DefaultURL = "https://deploy.site.latha.org"
|
||||
|
||||
type pollResponse struct {
|
||||
Status string `json:"status"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// RedirectURI is the redirect URI registered for the relay.
|
||||
func RedirectURI(relayURL string) string {
|
||||
return strings.TrimRight(relayURL, "/") + "/oauth/callback"
|
||||
}
|
||||
|
||||
// Poll waits for the relay to receive the authorization code for state.
|
||||
func Poll(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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPoll(t *testing.T) {
|
||||
var polls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/oauth/poll" || r.URL.Query().Get("state") != "st-1" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if polls.Add(1) < 2 {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"status": "pending"})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ready", "code": "code-abc"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
code, err := Poll(ctx, srv.Client(), srv.URL, "st-1", 10*time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatalf("Poll: %v", err)
|
||||
}
|
||||
if code != "code-abc" {
|
||||
t.Fatalf("code = %q", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectURI(t *testing.T) {
|
||||
if got := RedirectURI("https://x.example/"); got != "https://x.example/oauth/callback" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user