From 9bd537c72e5f4a322a32f776c0436181f1367e44 Mon Sep 17 00:00:00 2001 From: Roy QIU Date: Thu, 6 Aug 2026 20:27:21 +0800 Subject: [PATCH] fix(api): authenticate requests via SSH key for non-token logins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- cmd/api.go | 23 +++++++- cmd/api_test.go | 10 ++++ modules/api/client.go | 107 +++++++++++++++++++++++++++++++++++-- modules/api/client_test.go | 99 ++++++++++++++++++++++++++++++++++ 4 files changed, 233 insertions(+), 6 deletions(-) create mode 100644 modules/api/client_test.go diff --git a/cmd/api.go b/cmd/api.go index 6c5c22a5..c068ca64 100644 --- a/cmd/api.go +++ b/cmd/api.go @@ -120,7 +120,10 @@ func runApi(requestCtx stdctx.Context, cmd *cli.Command) error { } // Create API client and make request - client := api.NewClient(ctx.Login) + client, err := api.NewClient(ctx.Login) + if err != nil { + return fmt.Errorf("failed to create API client: %w", err) + } resp, err := client.Do(request.Method, request.Endpoint, body, request.Headers) if err != nil { return fmt.Errorf("request failed: %w", err) @@ -191,6 +194,16 @@ func prepareAPIRequest(cmd *cli.Command, ctx *context.TeaContext) (*preparedAPIR } endpoint := cmd.Args().First() + // Detect a Windows drive-letter path, which means an MSYS2/Git-Bash shell + // converted the endpoint (e.g. "/repos/..." -> "C:/Program Files/Git/repos/...") + // before tea ever saw it. tea cannot recover the original path, so surface a + // clear error instead of a confusing "404 page not found". + if looksLikeWindowsPath(endpoint) { + return nil, fmt.Errorf("endpoint %q looks like a Windows filesystem path, not a URL path\n"+ + "your shell (MSYS2 / Git Bash) likely converted it; re-run with MSYS_NO_PATHCONV=1\n"+ + "set, or run tea from cmd / PowerShell", endpoint) + } + // Expand placeholders in endpoint endpoint = expandPlaceholders(endpoint, ctx) @@ -391,6 +404,14 @@ func isTextContentType(contentType string) bool { strings.Contains(contentType, "toml") } +// looksLikeWindowsPath reports whether s begins with a Windows drive letter +// (e.g. "C:/..." or "C:\..."), which signals MSYS2/Git-Bash path conversion of +// what should have been a URL path. +func looksLikeWindowsPath(s string) bool { + return len(s) >= 3 && ((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z')) && + s[1] == ':' && (s[2] == '/' || s[2] == '\\') +} + // expandPlaceholders replaces {owner}, {repo}, and {branch} in the endpoint func expandPlaceholders(endpoint string, ctx *context.TeaContext) string { endpoint = strings.ReplaceAll(endpoint, "{owner}", ctx.Owner) diff --git a/cmd/api_test.go b/cmd/api_test.go index 8e92b5e0..3f0e92b6 100644 --- a/cmd/api_test.go +++ b/cmd/api_test.go @@ -310,6 +310,16 @@ func TestApiCommaInFieldValue(t *testing.T) { assert.Equal(t, "hello, world", parsed["body"]) } +func TestApiRejectsWindowsPathEndpoint(t *testing.T) { + // MSYS2/Git-Bash converts "/repos/..." into a Windows path like + // "C:/Program Files/Git/repos/...". tea cannot undo that, so it must reject + // it with a clear, actionable error rather than a confusing 404. + _, _, err := runApiWithArgs(t, []string{"C:/Program Files/Git/repos/owner/repo/issues"}) + require.Error(t, err) + assert.Contains(t, err.Error(), "Windows filesystem path") + assert.Contains(t, err.Error(), "MSYS_NO_PATHCONV") +} + func TestApiRawDataFlag(t *testing.T) { _, body, err := runApiWithArgs(t, []string{"-d", `{"title":"test","body":"hello"}`, "/test"}) require.NoError(t, err) diff --git a/modules/api/client.go b/modules/api/client.go index 2892dd7c..9cfe5996 100644 --- a/modules/api/client.go +++ b/modules/api/client.go @@ -5,6 +5,7 @@ package api import ( "crypto/tls" + "encoding/base64" "fmt" "io" "log" @@ -12,19 +13,32 @@ import ( "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 } -// NewClient creates a new API client from a Login config -func NewClient(login *config.Login) *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) @@ -34,14 +48,40 @@ func NewClient(login *config.Login) *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 } -// Do executes an HTTP request with authentication headers +// 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) @@ -54,7 +94,7 @@ func (c *Client) Do(method, endpoint string, body io.Reader, headers map[string] return nil, fmt.Errorf("failed to create request: %w", err) } - // Set authentication header + // Set authentication header for bearer-token logins. if c.token != "" { req.Header.Set("Authorization", "token "+c.token) } @@ -69,9 +109,66 @@ func (c *Client) Do(method, endpoint string, body io.Reader, headers map[string] 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 diff --git a/modules/api/client_test.go b/modules/api/client_test.go new file mode 100644 index 00000000..ac8b7d8d --- /dev/null +++ b/modules/api/client_test.go @@ -0,0 +1,99 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package api + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "gitea.dev/tea/modules/config" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" +) + +// captureRequest starts an httptest server that records the last request it +// received and returns the server plus a pointer to the captured request. +func captureRequest(t *testing.T) (*httptest.Server, **http.Request) { + t.Helper() + var captured *http.Request + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + captured = r + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, "{}") + })) + t.Cleanup(ts.Close) + return ts, &captured +} + +// generateSSHKey writes an ed25519 OpenSSH private key to a temp file and +// returns the file path and the SHA256 fingerprint of its public key. +func generateSSHKey(t *testing.T) (keyPath, fingerprint string) { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + + block, err := ssh.MarshalPrivateKey(priv, "") + require.NoError(t, err) + + keyPath = filepath.Join(t.TempDir(), "id_ed25519") + require.NoError(t, os.WriteFile(keyPath, pem.EncodeToMemory(block), 0o600)) + + pubKey, err := ssh.NewPublicKey(pub) + require.NoError(t, err) + return keyPath, ssh.FingerprintSHA256(pubKey) +} + +// doGet issues a single GET against the server using a client built from login. +func doGet(t *testing.T, login *config.Login) { + t.Helper() + c, err := NewClient(login) + require.NoError(t, err) + resp, err := c.Do(http.MethodGet, "/anything", nil, nil) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) +} + +func TestClient_TokenLoginSetsAuthorization(t *testing.T) { + ts, captured := captureRequest(t) + login := &config.Login{ + URL: ts.URL, + Token: "abc123", + } + + doGet(t, login) + + assert.Equal(t, "token abc123", (*captured).Header.Get("Authorization")) + // No SSH signature for a plain token login. + assert.Empty(t, (*captured).Header.Get("Signature")) +} + +func TestClient_SSHKeyLoginSignsRequest(t *testing.T) { + ts, captured := captureRequest(t) + keyPath, fingerprint := generateSSHKey(t) + + login := &config.Login{ + URL: ts.URL, + SSHKey: keyPath, + SSHKeyFingerprint: fingerprint, + } + + doGet(t, login) + + // An SSH-key login has no bearer token, so it must authenticate via an + // HTTP Signature header instead. This is the bug: the custom client used + // to send neither. + assert.Empty(t, (*captured).Header.Get("Authorization"), + "SSH-key login must not rely on a bearer token") + assert.NotEmpty(t, (*captured).Header.Get("Signature"), + "SSH-key login must sign the request") +}