carlos / platform Public

console: config PUT reads its body once and refuses trailing data

Round 3 P1: a second JSON object after the first carried an if_version
that neither the decoder nor the precondition scan looked at, so the
write landed unconditionally. Per Paul's ruling, on this door only (the
shared decodeJSONBody is untouched), readConfigPutBody reads the whole
body once within configPutMaxBytes, decodes the request from that slice
and requires nothing but whitespace after the one value; anything else
is a 400 before any store read. configIfVersion decides from the same
bytes. The guard table gains trailing-object (also in one-byte reads),
trailing-garbage and trailing-literal rows, and whitespace still passes.

Copy: "this request takes if_version in the body, not an If-Match
header"; new "the body must be one JSON object with nothing after it".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 5a2defb62b6fe860af8af7c14ffbf5c66101a8a3 parent cc24126
2 files changed, +107 −33
  • internal/console/apiconfig.go +51 −12
  • internal/console/apiconfig_witness_test.go +56 −21

CI cancelled — superseded by a newer push — run details

Intent

diff --git a/internal/console/apiconfig.go b/internal/console/apiconfig.go
index 52579c4df..8b6345cf3 100644
--- a/internal/console/apiconfig.go
+++ b/internal/console/apiconfig.go
@@ -391,14 +391,10 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
// from the raw body: a struct field cannot tell an absent member
// from a null one, and keeps only the last of a repeated one.
}
- // The bytes the decoder reads are kept for configIfVersion. The tee
- // sits under readJSONLimit's own byte cap, so it holds at most that.
- var rawBody bytes.Buffer
- r.Body = struct {
- io.Reader
- io.Closer
- }{io.TeeReader(r.Body, &rawBody), r.Body}
- if !readJSONLimit(w, r, &req, configPutMaxBytes) {
+ // One read of the whole body, and everything below works from it: the
+ // struct and the precondition come from the same bytes (round 3).
+ rawBody, ok := readConfigPutBody(w, r, &req)
+ if !ok {
return
}
message, ok := checkedActivityMessage(w, req.Message)
@@ -534,7 +530,7 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
// The precondition's refusals come last among the body checks and,
// like them, before the first store call: a request refused here has
// read nothing, so it cannot have learnt a version either.
- ifVersion, ok := configIfVersion(w, r, rawBody.Bytes())
+ ifVersion, ok := configIfVersion(w, r, rawBody)
if !ok {
return
}
@@ -1022,11 +1018,53 @@ func (s *Server) teamApplyEnvironment(ctx context.Context, tv *teamView, envName
return rc, false, err
}
+// readConfigPutBody reads the PUT's whole body once, within
+// configPutMaxBytes, decodes it into out and hands the same bytes back for
+// configIfVersion. The body must be exactly one JSON value with nothing but
+// whitespace after it (round 3 ruling): a second object, a literal or
+// garbage after the first is a 400 before any store read. A decoder that
+// stops at the end of the first value never looks at what follows, so a
+// precondition placed there would vanish, and a write meant to be
+// conditional would land unconditionally.
+//
+// Its own reader rather than the shared decodeJSONBody, which other doors
+// use and which this ruling leaves alone; the refusals for content type,
+// size and malformed JSON keep that function's words.
+func readConfigPutBody(w http.ResponseWriter, r *http.Request, out any) ([]byte, bool) {
+ ct, _, _ := strings.Cut(r.Header.Get("Content-Type"), ";")
+ if strings.TrimSpace(strings.ToLower(ct)) != "application/json" {
+ jsonError(w, http.StatusUnsupportedMediaType, "send a JSON body with Content-Type: application/json")
+ return nil, false
+ }
+ raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, configPutMaxBytes))
+ if err != nil {
+ var tooLarge *http.MaxBytesError
+ if errors.As(err, &tooLarge) {
+ jsonError(w, http.StatusRequestEntityTooLarge, "request body too large")
+ return nil, false
+ }
+ jsonError(w, http.StatusBadRequest, "could not read the request body")
+ return nil, false
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ if err := dec.Decode(out); err != nil {
+ jsonError(w, http.StatusBadRequest, "malformed JSON body")
+ return nil, false
+ }
+ var rest json.RawMessage
+ if err := dec.Decode(&rest); err != io.EOF {
+ jsonError(w, http.StatusBadRequest, configCopyTrailingBody)
+ return nil, false
+ }
+ return raw, true
+}
+
// configIfVersion is the PUT's precondition, and the ONE place that decides
// whether the request supplied one (round 2 ruling, after the same fault
// recurred in rounds 1 and 2): a supplied precondition must never become
-// none on the way in. It reads the raw body, which readJSONLimit has
-// already decoded as a JSON object, and answers the 400 itself.
+// none on the way in. It reads the raw body, the same bytes
+// readConfigPutBody decoded the request from (one JSON object, nothing
+// after it), and answers the 400 itself.
//
// Absent means an unconditional write, as it always did. Otherwise
// if_version must be exactly one top-level member holding a non-empty JSON
@@ -1095,7 +1133,8 @@ const (
configCopyIfVersionNotString = "if_version must be a version string. send the version to write against, or leave the field out"
configCopyIfVersionTwice = "if_version is in the body more than once. send it once"
configCopyIfVersionUnreadable = "if_version could not be read from the body. send the body as one JSON object"
- configCopyIfMatch = "this door takes if_version in the body, not an If-Match header"
+ configCopyIfMatch = "this request takes if_version in the body, not an If-Match header"
+ configCopyTrailingBody = "the body must be one JSON object with nothing after it"
)
// configSetAndUnset is the first of keys (sorted) that unsets also names,
diff --git a/internal/console/apiconfig_witness_test.go b/internal/console/apiconfig_witness_test.go
index 789fee92b..c26fd1c68 100644
--- a/internal/console/apiconfig_witness_test.go
+++ b/internal/console/apiconfig_witness_test.go
@@ -18,6 +18,7 @@ import (
"sync"
"sync/atomic"
"testing"
+ "testing/iotest"
"time"
"github.com/carlosframework/platform/internal/appconfig"
@@ -81,7 +82,14 @@ func (k *keyHookStore) count() int {
// reqWithHeaders is rawReq with any number of values per header.
func reqWithHeaders(t *testing.T, method, u, bearer, body string, hdr http.Header) (int, string) {
t.Helper()
- req, err := http.NewRequest(method, u, strings.NewReader(body))
+ return reqWithBody(t, method, u, bearer, strings.NewReader(body), hdr)
+}
+
+// reqWithBody is reqWithHeaders over any reader. A reader of unknown length
+// goes out chunked, so the door receives the body in pieces.
+func reqWithBody(t *testing.T, method, u, bearer string, body io.Reader, hdr http.Header) (int, string) {
+ t.Helper()
+ req, err := http.NewRequest(method, u, body)
if err != nil {
t.Fatal(err)
}
@@ -124,29 +132,46 @@ func TestAPIConfigPutRefusesUnusablePrecondition(t *testing.T) {
stale := `"cv1:` + strings.Repeat("0", 64) + `"`
for _, c := range []struct {
- what string
- body string
- hdr http.Header
+ what string
+ body string
+ hdr http.Header
+ chunked bool // delivered one byte per read, as a chunked body
}{
- {"null", `{"if_version":null,` + set + `}`, nil},
- {"empty string", `{"if_version":"",` + set + `}`, nil},
- {"blank string", `{"if_version":" ",` + set + `}`, nil},
- {"number", `{"if_version":0,` + set + `}`, nil},
- {"boolean", `{"if_version":true,` + set + `}`, nil},
- {"object", `{"if_version":{},` + set + `}`, nil},
- {"array", `{"if_version":[],` + set + `}`, nil},
- {"a version then null", `{"if_version":` + stale + `,"if_version":null,` + set + `}`, nil},
- {"null then a version", `{"if_version":null,"if_version":"` + cur + `",` + set + `}`, nil},
- {"two versions", `{"if_version":` + stale + `,"if_version":"` + cur + `",` + set + `}`, nil},
- {"the same version twice", `{"if_version":"` + cur + `","if_version":"` + cur + `",` + set + `}`, nil},
- {"null under another case", `{"IF_VERSION":null,` + set + `}`, nil},
- {"two cases of the member", `{"if_version":"` + cur + `","If_Version":null,` + set + `}`, nil},
- {"an If-Match header", plain, http.Header{"If-Match": {`"` + cur + `"`}}},
- {"an If-Match header beside the field", `{"if_version":"` + cur + `",` + set + `}`, http.Header{"If-Match": {cur}}},
- {"an empty If-Match header", plain, http.Header{"If-Match": {""}}},
+ {"null", `{"if_version":null,` + set + `}`, nil, false},
+ {"empty string", `{"if_version":"",` + set + `}`, nil, false},
+ {"blank string", `{"if_version":" ",` + set + `}`, nil, false},
+ {"number", `{"if_version":0,` + set + `}`, nil, false},
+ {"boolean", `{"if_version":true,` + set + `}`, nil, false},
+ {"object", `{"if_version":{},` + set + `}`, nil, false},
+ {"array", `{"if_version":[],` + set + `}`, nil, false},
+ {"a version then null", `{"if_version":` + stale + `,"if_version":null,` + set + `}`, nil, false},
+ {"null then a version", `{"if_version":null,"if_version":"` + cur + `",` + set + `}`, nil, false},
+ {"two versions", `{"if_version":` + stale + `,"if_version":"` + cur + `",` + set + `}`, nil, false},
+ {"the same version twice", `{"if_version":"` + cur + `","if_version":"` + cur + `",` + set + `}`, nil, false},
+ {"null under another case", `{"IF_VERSION":null,` + set + `}`, nil, false},
+ {"two cases of the member", `{"if_version":"` + cur + `","If_Version":null,` + set + `}`, nil, false},
+ {"an If-Match header", plain, http.Header{"If-Match": {`"` + cur + `"`}}, false},
+ {"an If-Match header beside the field", `{"if_version":"` + cur + `",` + set + `}`, http.Header{"If-Match": {cur}}, false},
+ {"an empty If-Match header", plain, http.Header{"If-Match": {""}}, false},
+ // Round 3: the body is one JSON object and nothing after it, so no
+ // precondition can sit where the decoder never looks.
+ {"a trailing object with if_version", plain + "\n" + `{"if_version":` + stale + `}`, nil, false},
+ {"a trailing object with if_version, in one-byte reads", plain + "\n" + `{"if_version":` + stale + `}`, nil, true},
+ {"a trailing object without it", plain + `{"unset":["A"]}`, nil, false},
+ {"trailing x", plain + "x", nil, false},
+ {"a trailing ]", plain + "]", nil, false},
+ {"a trailing {", plain + " {", nil, false},
+ {"a trailing null", plain + " null", nil, false},
+ {"a trailing 1", plain + "\n1", nil, false},
} {
before := cs.getCount()
- status, out := reqWithHeaders(t, http.MethodPut, u, token, c.body, c.hdr)
+ var status int
+ var out string
+ if c.chunked {
+ status, out = reqWithBody(t, http.MethodPut, u, token, iotest.OneByteReader(strings.NewReader(c.body)), c.hdr)
+ } else {
+ status, out = reqWithHeaders(t, http.MethodPut, u, token, c.body, c.hdr)
+ }
if status != http.StatusBadRequest {
t.Errorf("%s = %d %s, want 400", c.what, status, out)
}
@@ -186,6 +211,16 @@ func TestAPIConfigPutRefusesUnusablePrecondition(t *testing.T) {
if status, out := reqWithHeaders(t, http.MethodPut, u, token, plain, nil); status != http.StatusOK {
t.Fatalf("no precondition = %d %s", status, out)
}
+ // Whitespace after the object is not trailing data, in one read or in
+ // one-byte reads.
+ now := `"` + storedVersion(t, fx, key) + `"`
+ if status, out := reqWithHeaders(t, http.MethodPut, u, token, `{"if_version":`+now+`,`+set+"}\n\t \r\n", nil); status != http.StatusOK {
+ t.Fatalf("a body ending in whitespace = %d %s", status, out)
+ }
+ now = `"` + storedVersion(t, fx, key) + `"`
+ if status, out := reqWithBody(t, http.MethodPut, u, token, iotest.OneByteReader(strings.NewReader(`{"if_version":`+now+`,`+set+"}\n")), nil); status != http.StatusOK {
+ t.Fatalf("a chunked body ending in a newline = %d %s", status, out)
+ }
}
// TestAPIConfigTeamGetOwnershipRace: a team GET is authorised on the bytes