gitea.tea/modules/api/client.go
Roy QIU 9bd537c72e fix(api): authenticate requests via SSH key for non-token logins
The custom api client only sent a bearer token, so a login that
authenticates with an SSH key (HTTP Signature) sent no credentials at
all — `tea api` failed with 401/404 on every endpoint. The SDK signs
such requests; the custom client did not.

Authenticate via token or SSH key/cert, reusing the SDK's exported
HTTPSign signer construction plus the same httpsig signing path. Also
detect MSYS2/Git-Bash path mangling of the endpoint argument and surface
a clear, actionable error instead of a confusing "404 page not found".

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 20:27:21 +08:00

202 lines
5.9 KiB
Go

// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package api
import (
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
gitea "gitea.dev/sdk"
"gitea.dev/tea/modules/config"
"gitea.dev/tea/modules/httputil"
"github.com/42wim/httpsig"
"golang.org/x/crypto/ssh"
)
// Client provides direct HTTP access to Gitea API
type Client struct {
baseURL string
token string
signer *requestSigner // nil when the login uses a bearer token instead of an SSH key
httpClient *http.Client
}
// requestSigner signs requests via an SSH key (HTTP Signature), the auth method
// the Gitea SDK applies for SSH-key/cert logins. The custom api client must do
// the same or it sends no credentials at all (token logins carry no SSH key).
type requestSigner struct {
signer *gitea.HTTPSign
cert bool
}
// NewClient creates a new API client from a Login config. It returns an error
// if the login authenticates with an SSH key but the key cannot be loaded.
func NewClient(login *config.Login) (*Client, error) {
// Refresh OAuth token if expired or near expiry
if err := login.RefreshOAuthTokenIfNeeded(); err != nil {
log.Printf("Warning: failed to refresh OAuth token: %v", err)
}
httpClient := &http.Client{
Transport: httputil.WrapTransport(&tls.Config{InsecureSkipVerify: login.Insecure}),
}
signer, err := newRequestSigner(login)
if err != nil {
return nil, err
}
return &Client{
baseURL: strings.TrimSuffix(login.URL, "/"),
token: login.GetAccessToken(),
signer: signer,
httpClient: httpClient,
}, nil
}
// newRequestSigner builds an SSH-key signer matching the login's auth method,
// or nil for a bearer-token login.
func newRequestSigner(login *config.Login) (*requestSigner, error) {
switch {
case login.SSHCertPrincipal != "":
s, err := gitea.NewHTTPSignWithCert(login.SSHCertPrincipal, login.SSHKey, login.SSHPassphrase)
if err != nil {
return nil, fmt.Errorf("failed to load SSH certificate: %w", err)
}
return &requestSigner{signer: s, cert: true}, nil
case login.SSHKeyFingerprint != "":
s, err := gitea.NewHTTPSignWithPubkey(login.SSHKeyFingerprint, login.SSHKey, login.SSHPassphrase)
if err != nil {
return nil, fmt.Errorf("failed to load SSH key: %w", err)
}
return &requestSigner{signer: s, cert: false}, nil
}
return nil, nil
}
// Do executes an HTTP request with the login's authentication.
func (c *Client) Do(method, endpoint string, body io.Reader, headers map[string]string) (*http.Response, error) {
// Build the full URL
reqURL, err := c.buildURL(endpoint)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, reqURL, body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// Set authentication header for bearer-token logins.
if c.token != "" {
req.Header.Set("Authorization", "token "+c.token)
}
// Set default content type for requests with body
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
// Apply custom headers (can override defaults)
for key, value := range headers {
req.Header.Set(key, value)
}
// Authenticate SSH-key/cert logins via HTTP Signature.
if c.signer != nil {
if err := c.signer.sign(req); err != nil {
return nil, fmt.Errorf("failed to sign request: %w", err)
}
}
return c.httpClient.Do(req)
}
// sign adds an HTTP Signature header using the SSH key. This mirrors the
// Gitea SDK's private Client.signRequest; the SDK exposes no public way to make
// a raw authenticated request, so the signing orchestration is replicated here
// while reusing the SDK's exported signer construction (the hard part).
// ponytail: duplicates ~30 lines of SDK signing; remove if the SDK ever exposes
// a public raw-request method.
func (s *requestSigner) sign(r *http.Request) error {
headersToSign := []string{httpsig.RequestTarget, "(created)", "(expires)"}
if s.cert {
pubkey, err := ssh.ParsePublicKey(s.signer.PublicKey().Marshal())
if err != nil {
return err
}
cert, ok := pubkey.(*ssh.Certificate)
if !ok {
return fmt.Errorf("no ssh certificate found")
}
r.Header.Add("x-ssh-certificate", base64.RawStdEncoding.EncodeToString(cert.Marshal()))
headersToSign = append(headersToSign, "x-ssh-certificate")
}
var contents []byte
// If we have a body, the Digest header is added and included in the signature.
if r.Body != nil {
body, err := r.GetBody()
if err != nil {
return fmt.Errorf("getBody() failed: %w", err)
}
contents, err = io.ReadAll(body)
if err != nil {
return fmt.Errorf("failed reading body: %w", err)
}
headersToSign = append(headersToSign, "Digest")
}
// The signature is valid for 10 seconds.
modernSigner, _, err := httpsig.NewSSHSigner(s.signer, httpsig.DigestSha512, headersToSign, httpsig.Signature, 10)
if err != nil {
return fmt.Errorf("httpsig.NewSSHSigner failed: %w", err)
}
keyID := "gitea"
if !s.cert {
keyID = ssh.FingerprintSHA256(s.signer.PublicKey())
}
return modernSigner.SignRequest(keyID, r, contents)
}
// buildURL constructs the full URL from an endpoint
func (c *Client) buildURL(endpoint string) (string, error) {
// If endpoint is already a full URL, validate it matches the login's host
if strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://") {
endpointURL, err := url.Parse(endpoint)
if err != nil {
return "", fmt.Errorf("invalid URL: %w", err)
}
baseURL, err := url.Parse(c.baseURL)
if err != nil {
return "", fmt.Errorf("invalid base URL: %w", err)
}
if endpointURL.Host != baseURL.Host {
return "", fmt.Errorf("URL host %q does not match login host %q (token would be sent to wrong server)", endpointURL.Host, baseURL.Host)
}
return endpoint, nil
}
// Ensure endpoint starts with /
if !strings.HasPrefix(endpoint, "/") {
endpoint = "/" + endpoint
}
// Auto-prefix /api/v1/ if not present
if !strings.HasPrefix(endpoint, "/api/") {
endpoint = "/api/v1" + endpoint
}
return c.baseURL + endpoint, nil
}