238 lines
6.6 KiB
Go
238 lines
6.6 KiB
Go
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")
|
|
}
|