From fda2a123c719564545f1ee32295f3dba27bce81e Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Wed, 4 Nov 2026 13:48:57 +0000 Subject: [PATCH] hscontrol: answer 413 only for an oversized c2n response Updates #3629 --- hscontrol/noise.go | 9 ++++++++- hscontrol/noise_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/hscontrol/noise.go b/hscontrol/noise.go index 2048d11eb..0bb897f5e 100644 --- a/hscontrol/noise.go +++ b/hscontrol/noise.go @@ -356,7 +356,14 @@ func (ns *noiseServer) C2NResponseHandler( body, err := io.ReadAll(http.MaxBytesReader(writer, req.Body, maxC2NResponseBytes)) if err != nil { - httpError(writer, NewHTTPError(http.StatusRequestEntityTooLarge, "reading c2n response", err)) + status := http.StatusBadRequest + + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + status = http.StatusRequestEntityTooLarge + } + + httpError(writer, NewHTTPError(status, "reading c2n response", err)) + return } diff --git a/hscontrol/noise_test.go b/hscontrol/noise_test.go index ccecb4963..a94d9ce65 100644 --- a/hscontrol/noise_test.go +++ b/hscontrol/noise_test.go @@ -21,6 +21,7 @@ import ( "strings" "sync" "testing" + "testing/iotest" "time" "github.com/go-chi/chi/v5" @@ -2599,3 +2600,26 @@ func TestC2NResponseHandler_OversizedBody(t *testing.T) { _, pending := app.state.C2NTarget(c2nID) assert.True(t, pending) } + +// TestC2NResponseHandler_BrokenBody verifies that a body that fails to read +// for another reason than its size is a 400, not a 413. +func TestC2NResponseHandler_BrokenBody(t *testing.T) { + t.Parallel() + + app := createTestApp(t) + user := app.state.CreateUserForTest("c2n-broken-user") + node := putTestNodeInStore(t, app, user, "c2n-node") + + c2nID, _ := app.state.RegisterC2N(node.ID) + defer app.state.CancelC2N(c2nID) + + ns := &noiseServer{headscale: app, machineKey: node.MachineKey} + + req := newC2NResponseRequest(c2nID, nil) + req.Body = io.NopCloser(iotest.ErrReader(io.ErrUnexpectedEOF)) + + rec := httptest.NewRecorder() + ns.C2NResponseHandler(rec, req) + + assert.Equal(t, http.StatusBadRequest, rec.Code) +}