carlos / platform Public

console: refuse unusable If-Match; check team GET on its own read

A supplied precondition never vanishes (round 1, P1-1): an If-Match that
is empty, "", *, a weak W/ tag, a list or a second header, and a body
if_version that is present but empty or blank, are a 400 before anything
is read. Before, an empty quoted tag became an unconditional write.

A team GET is authorised on the bytes it answers with (P1-2): the layer
read must be found and owned by the team's scope, else the canonical 404,
so a bundle released or transferred after the scope step shows nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 21e4aa58ba92d0b5dd4a251e33f3abcfac46c156 parent 08eed55
2 files changed, +221 −12
  • internal/console/apiconfig.go +64 −12
  • internal/console/apiconfig_witness_test.go +157 −0
diff --git a/internal/console/apiconfig.go b/internal/console/apiconfig.go
index ef930a92e..ae8648449 100644
--- a/internal/console/apiconfig.go
+++ b/internal/console/apiconfig.go
@@ -213,6 +213,15 @@ func (s *Server) handleAPIConfigGet(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusBadGateway, "could not read the config — try again")
return
}
+ // A team is authorised on the bytes it is about to be shown, not only
+ // on the scope step's earlier read (round 1, P1-2): the bundle can be
+ // released or handed to another scope in between, and its new vars,
+ // digests and version are then not this caller's. The scope step's
+ // answer for a bundle it does not own, byte for byte.
+ if team && (!layer.Found || layer.Manifest.OwnerScope != tv.scope) {
+ http.NotFound(w, r)
+ return
+ }
// Always present, possibly empty: it powers `carlos env environments`
// without a fourth door, and a client should read the key rather than
// test for its absence.
@@ -374,9 +383,11 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
// turn the flag OFF.
ExecDelivery *string `json:"exec_delivery"`
// IfVersion makes the set/unset half conditional on the bundle's
- // version (#522 §4.5); "" is today's unconditional write. The
- // If-Match header says the same thing (configIfVersion).
- IfVersion string `json:"if_version"`
+ // version (#522 §4.5). A POINTER, like ExecDelivery: an absent field
+ // is today's unconditional write, and a present empty one is a
+ // precondition that must not quietly become none (configIfVersion).
+ // The If-Match header says the same thing.
+ IfVersion *string `json:"if_version"`
}
if !readJSONLimit(w, r, &req, configPutMaxBytes) {
return
@@ -986,22 +997,63 @@ func (s *Server) teamApplyEnvironment(ctx context.Context, tv *teamView, envName
// speak it; an entity tag arrives quoted, so one pair of quotes is dropped.
// The body wins nothing on a disagreement: a caller who said two things has
// to say which one it meant.
-func configIfVersion(w http.ResponseWriter, r *http.Request, body string) (string, bool) {
- body = strings.TrimSpace(body)
- header := strings.TrimSpace(r.Header.Get("If-Match"))
- if len(header) >= 2 && header[0] == '"' && header[len(header)-1] == '"' {
- header = header[1 : len(header)-1]
+//
+// A precondition that is SUPPLIED never becomes none (round 1, P1-1): only
+// an absent field and an absent header mean an unconditional write. A
+// present one that names no version (empty, blank or `""`), or names one in
+// a form this door does not take (`*`, a weak `W/` tag, a list, a second
+// header, a stray quote), is a 400 before anything is read. Falling back to
+// an unconditional write would overwrite exactly the concurrent change the
+// caller asked to be protected from, and a 412 would claim a comparison
+// that was never made.
+func configIfVersion(w http.ResponseWriter, r *http.Request, bodyField *string) (string, bool) {
+ body := ""
+ if bodyField != nil {
+ body = strings.TrimSpace(*bodyField)
+ if body == "" {
+ jsonError(w, http.StatusBadRequest, configCopyEmptyIfVersion)
+ return "", false
+ }
}
- switch {
- case header == "":
+ values := r.Header.Values("If-Match")
+ if len(values) == 0 {
return body, true
- case body == "" || body == header:
+ }
+ header, ok := configIfMatchTag(values)
+ if !ok {
+ jsonError(w, http.StatusBadRequest, configCopyBadIfMatch)
+ return "", false
+ }
+ if body == "" || body == header {
return header, true
}
- jsonError(w, http.StatusBadRequest, "if_version and the If-Match header name different versions. send one of them, or the same version in both")
+ jsonError(w, http.StatusBadRequest, configCopyIfVersionDisagree)
return "", false
}
+// configIfMatchTag is the one version an If-Match header names, quoted or
+// not, and false for any other form.
+func configIfMatchTag(values []string) (string, bool) {
+ if len(values) != 1 {
+ return "", false
+ }
+ tag := strings.TrimSpace(values[0])
+ if len(tag) >= 2 && tag[0] == '"' && tag[len(tag)-1] == '"' {
+ tag = tag[1 : len(tag)-1]
+ }
+ if tag == "" || tag == "*" || strings.HasPrefix(tag, "W/") || strings.ContainsAny(tag, "\", \t") {
+ return "", false
+ }
+ return tag, true
+}
+
+// The precondition's 400s.
+const (
+ configCopyEmptyIfVersion = "if_version is empty. send the version to write against, or leave if_version out"
+ configCopyBadIfMatch = "If-Match must name one version, quoted or not. an empty tag, \"*\", a weak tag and a list are not accepted"
+ configCopyIfVersionDisagree = "if_version and the If-Match header name different versions. send one, or send the same version in both"
+)
+
// configSetAndUnset is the first of keys (sorted) that unsets also names,
// "" when none: a request with several such names always refuses on the
// same one.
diff --git a/internal/console/apiconfig_witness_test.go b/internal/console/apiconfig_witness_test.go
new file mode 100644
index 000000000..6f150ee80
--- /dev/null
+++ b/internal/console/apiconfig_witness_test.go
@@ -0,0 +1,157 @@
+package console
+
+// Witnesses from the config receipts branch review (#522 plan 1, round 1):
+// a supplied precondition never vanishes, and a team is authorised on the
+// snapshot it is shown.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// 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))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ for k, vs := range hdr {
+ for _, v := range vs {
+ req.Header.Add(k, v)
+ }
+ }
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ out, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return res.StatusCode, string(out)
+}
+
+// TestAPIConfigPutRefusesUnusablePrecondition: an If-Match or if_version
+// that is present but empty, a wildcard, a weak tag or a list is refused
+// with 400 before anything is read. None of them may fall back to an
+// unconditional write, and none is a 412: they are not versions at all.
+func TestAPIConfigPutRefusesUnusablePrecondition(t *testing.T) {
+ fx, token := configFixture(t, "code-config-precondition-forms")
+ seedDefault(t, fx, token, envSet("A", "1"))
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ cur := storedVersion(t, fx, key)
+ stored := rawAtKey(t, fx, key)
+ gen := genEtag(t, fx, "titogo")
+ cs := useCfgCountStore(fx, true)
+ u := configURL(fx, "titogo")
+ plain := putBody(t, map[string]any{"set": envSet("B", "2")})
+
+ for _, c := range []struct {
+ what string
+ body string
+ hdr http.Header
+ }{
+ {"an empty quoted If-Match", plain, http.Header{"If-Match": {`""`}}},
+ {"an empty If-Match", plain, http.Header{"If-Match": {""}}},
+ {"a blank If-Match", plain, http.Header{"If-Match": {" "}}},
+ {"a wildcard If-Match", plain, http.Header{"If-Match": {"*"}}},
+ {"a weak If-Match of the current version", plain, http.Header{"If-Match": {`W/"` + cur + `"`}}},
+ {"an If-Match list", plain, http.Header{"If-Match": {`"` + cur + `", "cv1:00"`}}},
+ {"two If-Match headers", plain, http.Header{"If-Match": {`"` + cur + `"`, `"` + cur + `"`}}},
+ {"an unbalanced quote", plain, http.Header{"If-Match": {`"` + cur}}},
+ {"an empty if_version", `{"if_version":"","set":{"B":{"kind":"env","value":"2"}}}`, nil},
+ {"a blank if_version", `{"if_version":" ","set":{"B":{"kind":"env","value":"2"}}}`, nil},
+ {"an empty if_version beside a good header", `{"if_version":"","set":{"B":{"kind":"env","value":"2"}}}`, http.Header{"If-Match": {cur}}},
+ } {
+ before := cs.getCount()
+ 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)
+ }
+ var e map[string]any
+ if json.Unmarshal([]byte(out), &e) != nil || e["error"] == "" || strings.Contains(out, cur) {
+ t.Errorf("%s: body %s, want an error naming no version", c.what, out)
+ }
+ if n := cs.getCount() - before; n != 0 {
+ t.Errorf("%s read the store %d times, want 0", c.what, n)
+ }
+ if !bytes.Equal(rawAtKey(t, fx, key), stored) {
+ t.Fatalf("%s changed the stored bytes", c.what)
+ }
+ if genEtag(t, fx, "titogo") != gen {
+ t.Fatalf("%s bumped the generation", c.what)
+ }
+ }
+
+ // An absent precondition is today's unconditional write, and a present
+ // usable one still works, quoted or not.
+ if status, out := reqWithHeaders(t, http.MethodPut, u, token, putBody(t, map[string]any{"if_version": cur, "set": envSet("B", "2")}), nil); status != http.StatusOK {
+ t.Fatalf("a usable if_version = %d %s", status, out)
+ }
+ if status, out := reqWithHeaders(t, http.MethodPut, u, token, plain, nil); status != http.StatusOK {
+ t.Fatalf("no precondition = %d %s", status, out)
+ }
+}
+
+// TestAPIConfigTeamGetOwnershipRace: a team GET is authorised on the bytes
+// it answers with. A bundle that changes hands after the scope step, and
+// gains a var and a version on the way, is the canonical 404, carrying
+// nothing of the new bytes.
+func TestAPIConfigTeamGetOwnershipRace(t *testing.T) {
+ for _, c := range []struct {
+ what string
+ owner string
+ }{{"released", ""}, {"transferred", "beta"}} {
+ t.Run(c.what, func(t *testing.T) {
+ w := newTeamWorld(t, "code-team-get-race-"+c.what)
+ ctx := context.Background()
+ key := appconfig.EnvironmentKey(release.OpsAccount, "titogo", "team")
+ var fired atomic.Bool
+ var hookErr error
+ h := func(r *http.Request) {
+ if r.URL.Path != "/api/cli/apps/bab/titogo/config" || fired.Swap(true) {
+ return
+ }
+ if _, err := appconfig.ApplyEnvironmentOwned(ctx, w.fx.rel, "bab", "titogo", "team", "alta",
+ map[string]appconfig.Var{"LATER": {Kind: "env", Value: "later-canary"}}, nil); err != nil {
+ hookErr = err
+ return
+ }
+ if err := appconfig.SetEnvironmentOwner(ctx, w.fx.rel, "bab", "titogo", "team", "", nil); err != nil {
+ hookErr = err
+ return
+ }
+ if c.owner != "" {
+ hookErr = appconfig.SetEnvironmentOwner(ctx, w.fx.rel, "bab", "titogo", "team", c.owner, nil)
+ }
+ }
+ teamScopedHook.Store(&h)
+ t.Cleanup(func() { teamScopedHook.Store(nil) })
+ status, hdr, body := rawReq(t, http.MethodGet, w.url("/config?environment=team"), w.team, "")
+ teamScopedHook.Store(nil)
+ if !fired.Load() || hookErr != nil {
+ t.Fatalf("the bundle did not change hands after the scope step (fired %v): %v", fired.Load(), hookErr)
+ }
+ assertNotFound(t, "team GET after the bundle changed hands", canonicalNotFound(t), status, hdr, body)
+ now := storedVersion(t, w.fx, key)
+ for _, leak := range []string{now, "LATER", "later-canary", "TEAM_ONLY"} {
+ if strings.Contains(body, leak) {
+ t.Errorf("the 404 carries %q: %s", leak, body)
+ }
+ }
+ })
+ }
+}