From e40b94ce9cba9b42bf9a10ff66be13472cab3630 Mon Sep 17 00:00:00 2001 From: Hostodo Hermes Operations Date: Tue, 3 Nov 2026 08:58:48 +0000 Subject: [PATCH] [verified] fix(api): bound authentication error bodies --- pkg/api/client.go | 16 +++++- pkg/api/client_test.go | 117 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 1 deletion(-) diff --git a/pkg/api/client.go b/pkg/api/client.go index d936d72..3206c40 100644 --- a/pkg/api/client.go +++ b/pkg/api/client.go @@ -30,6 +30,12 @@ var ErrTokenExpired = fmt.Errorf("session expired - run 'hostodo login'") // ErrSessionRevoked indicates session was revoked and user needs to re-login var ErrSessionRevoked = fmt.Errorf("session revoked - run 'hostodo login' to authenticate again") +// ErrAuthenticationResponseTooLarge prevents an untrusted authentication error +// response from consuming unbounded client memory. +var ErrAuthenticationResponseTooLarge = fmt.Errorf("authentication error response is too large") + +const maxAuthenticationErrorResponseBytes = 2 << 20 + // NewClient creates a new API client func NewClient(cfg *config.Config) (*Client, error) { // Create cookie jar for session management @@ -105,8 +111,16 @@ func (c *Client) doRequest(method, path string, body interface{}) (*http.Respons // Check for invalid/expired/revoked token (401 Unauthorized) if resp.StatusCode == 401 { // Try to parse error detail for distinct revoked vs expired messages - body, _ := io.ReadAll(resp.Body) + body, readErr := io.ReadAll( + io.LimitReader(resp.Body, maxAuthenticationErrorResponseBytes+1), + ) resp.Body.Close() + if len(body) > maxAuthenticationErrorResponseBytes { + return nil, ErrAuthenticationResponseTooLarge + } + if readErr != nil { + return nil, fmt.Errorf("failed to read authentication error response: %w", readErr) + } var errResp struct { Detail string `json:"detail"` } diff --git a/pkg/api/client_test.go b/pkg/api/client_test.go index 2130aef..5843e89 100644 --- a/pkg/api/client_test.go +++ b/pkg/api/client_test.go @@ -2,6 +2,8 @@ package api import ( "encoding/json" + "errors" + "io" "net/http" "net/http/httptest" "os" @@ -13,6 +15,58 @@ import ( "github.com/hostodo/odo-cli/v2/pkg/config" ) +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (fn roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { + return fn(request) +} + +type boundedErrorReadCloser struct { + remaining int + finalErr error + closed bool +} + +func (reader *boundedErrorReadCloser) Read(buffer []byte) (int, error) { + if reader.remaining == 0 { + return 0, io.EOF + } + count := len(buffer) + if count > reader.remaining { + count = reader.remaining + } + for index := 0; index < count; index++ { + buffer[index] = 'x' + } + reader.remaining -= count + if reader.remaining == 0 { + if reader.finalErr != nil { + return count, reader.finalErr + } + return count, io.EOF + } + return count, nil +} + +func (reader *boundedErrorReadCloser) Close() error { + reader.closed = true + return nil +} + +func clientWith401Body(body io.ReadCloser) *Client { + return &Client{ + BaseURL: "https://api.example.test", + HTTPClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: body, + Header: make(http.Header), + }, nil + })}, + config: &config.Config{}, + } +} + // newTestClient creates a Client pointed at a test server. func newTestClient(t *testing.T, serverURL string) *Client { t.Helper() @@ -430,6 +484,69 @@ func TestClient_401_Revoked_ReturnsSessionRevokedError(t *testing.T) { } } +func TestClient_401_OversizedBodyIsRejectedAtBound(t *testing.T) { + injectToken(t) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(strings.Repeat("x", maxAuthenticationErrorResponseBytes+1))) + })) + defer srv.Close() + + client := newTestClient(t, srv.URL) + _, err := client.Get("/oversized-auth-response") + if !errors.Is(err, ErrAuthenticationResponseTooLarge) { + t.Fatalf("expected ErrAuthenticationResponseTooLarge, got: %v", err) + } +} + +func TestClient_401_OversizedBodyWinsOverFinalReadErrorAndCloses(t *testing.T) { + injectToken(t) + readFailure := errors.New("synthetic final read failure") + body := &boundedErrorReadCloser{ + remaining: maxAuthenticationErrorResponseBytes + 1, + finalErr: readFailure, + } + + _, err := clientWith401Body(body).Get("/oversized-auth-response") + if !errors.Is(err, ErrAuthenticationResponseTooLarge) { + t.Fatalf("expected oversized sentinel, got: %v", err) + } + if !body.closed { + t.Fatal("401 response body was not closed") + } +} + +func TestClient_401_ExactBoundaryIsAcceptedAndCloses(t *testing.T) { + injectToken(t) + body := &boundedErrorReadCloser{remaining: maxAuthenticationErrorResponseBytes} + + _, err := clientWith401Body(body).Get("/exact-boundary-auth-response") + if !errors.Is(err, ErrTokenExpired) { + t.Fatalf("expected ordinary expired-token classification, got: %v", err) + } + if !body.closed { + t.Fatal("401 response body was not closed") + } +} + +func TestClient_401_ShortReadErrorIsReturnedAndCloses(t *testing.T) { + injectToken(t) + readFailure := errors.New("synthetic short read failure") + body := &boundedErrorReadCloser{remaining: 128, finalErr: readFailure} + + _, err := clientWith401Body(body).Get("/short-auth-response") + if !errors.Is(err, readFailure) { + t.Fatalf("expected wrapped read failure, got: %v", err) + } + if errors.Is(err, ErrAuthenticationResponseTooLarge) { + t.Fatalf("short response was misclassified as oversized: %v", err) + } + if !body.closed { + t.Fatal("401 response body was not closed") + } +} + // ------------------------------------------------------------------- // GetDefaultPaymentMethod // -------------------------------------------------------------------