Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/envd/internal/api/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,13 @@ const thawHeader = "X-Envd-Thaw"
// clock.
const clockCorrectionHeader = "X-Envd-Init-Clock-Correction"

// maxInitBodyBytes caps the /init request body. The largest legitimate payload carries env
// vars and a CA bundle, both far below this. The body is read before auth (auth needs the
// parsed token), and the server sets no ReadTimeout, so an unbounded io.ReadAll would let
// any guest process that can reach the port allocate heap until envd — the sandbox's
// control plane — is OOM-killed.
const maxInitBodyBytes = 1 << 20 // 1 MiB

func (a *API) PostInit(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()

Expand Down Expand Up @@ -237,11 +244,24 @@ func (a *API) PostInit(w http.ResponseWriter, r *http.Request) {
freezeGen := a.workloadFreezer.FreezeGeneration(ctx)

if r.Body != nil {
// Cap the body before reading it: the read runs before auth, so this is
// the only thing standing between an unauthenticated oversized request
// and an OOM. MaxBytesError also makes the server close the connection
// after the response instead of draining the oversized remainder.
r.Body = http.MaxBytesReader(w, r.Body, maxInitBodyBytes)

// Read raw body so we can wipe it after parsing
body, err := io.ReadAll(r.Body)
// Ensure body is wiped after we're done
defer memguard.WipeBytes(body)
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
logger.Warn().Msg("Request body exceeds the /init size limit")
w.WriteHeader(http.StatusRequestEntityTooLarge)

return
}
logger.Error().Msgf("Failed to read request body: %v", err)
w.WriteHeader(http.StatusBadRequest)

Expand Down
49 changes: 49 additions & 0 deletions packages/envd/internal/api/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1225,3 +1225,52 @@ func TestPostInit_UnauthorizedDoesNotUnfreeze(t *testing.T) {
assert.Equal(t, http.StatusUnauthorized, rec.Code)
assert.Empty(t, mgr.unfreezeAttempts, "unauthorized /init must not attempt unfreeze")
}

// An oversized /init body must be rejected before it can be parsed or applied:
// the body is read before auth, so the size cap is the only thing standing
// between an unauthenticated oversized request and an envd OOM.
func TestPostInit_RejectsOversizedBody(t *testing.T) {
t.Parallel()

mgr := &fakeCgroupManager{}
api := newAPIWithCgroupManager(mgr)
api.isNotFC = true

// One byte past the cap. Well-formed JSON is irrelevant: the read itself
// must fail first.
body := bytes.Repeat([]byte{'a'}, maxInitBodyBytes+1)

req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/init", bytes.NewReader(body))
require.NoError(t, err)
rec := httptest.NewRecorder()
api.PostInit(rec, req)

assert.Equal(t, http.StatusRequestEntityTooLarge, rec.Code)
assert.Empty(t, mgr.unfreezeAttempts, "rejected /init must not attempt unfreeze")
}

// A body at the cap is still accepted.
func TestPostInit_AcceptsBodyAtSizeCap(t *testing.T) {
t.Parallel()

mgr := &fakeCgroupManager{}
api := newAPIWithCgroupManager(mgr)
api.isNotFC = true

// Padding inside the cap, via an env var value.
value := strings.Repeat("x", maxInitBodyBytes-64)
body, err := json.Marshal(PostInitJSONBody{
EnvVars: &EnvVars{"PADDING": value},
})
require.NoError(t, err)
require.Less(t, len(body), maxInitBodyBytes)

req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/init", bytes.NewReader(body))
require.NoError(t, err)
rec := httptest.NewRecorder()
api.PostInit(rec, req)

require.Equal(t, http.StatusNoContent, rec.Code)
_, ok := api.defaults.EnvVars.Load("PADDING")
assert.True(t, ok, "body at the cap should still be applied")
}