carlos / platform Public

console: conditional config writes and receipts (#522 plan 1 task 4)

The config PUT door takes if_version (If-Match as a synonym) and makes
the set/unset write conditional on the bundle's version through ApplyIf
and ApplyEnvironmentOwnedIf. A bundle not at that version, at read or by
a racing writer, answers 412 with the version now stored; nothing is
written. Refusals run before any store call: header and body disagree,
if_version with exec_delivery, a store without an atomic conditional
put, a team's "none", and a name in both set and unset (only with a
precondition).

Every set/unset write answers with a receipt: versions either side,
exact set/unset/unset_absent names, digests of what was set, and for a
non-owned named environment the default bundle's version either side.
removed and the audit row are unchanged. Receipt gains Owned so the door
can tell an owned environment from the one read that guarded the write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a8230beac6832bde559a873dee00cb397313a068 parent f234419
4 files changed, +886 −22
  • internal/appconfig/observe.go +7 −1
  • internal/appconfig/observe_apply_test.go +22 −0
  • internal/console/apiconfig.go +224 −21
  • internal/console/apiconfig_conditional_test.go +633 −0

CI failed — run details

diff --git a/internal/appconfig/observe.go b/internal/appconfig/observe.go
index 2d558d506..e0b7813bd 100644
--- a/internal/appconfig/observe.go
+++ b/internal/appconfig/observe.go
@@ -143,9 +143,15 @@ var ErrConditionalCreateOwned = errors.New("config: a conditional write cannot c
// Changed compares versions, not intent: rewriting a var to the value it
// already holds still writes, but leaves the bytes and so the version as
// they were.
+//
+// Owned is whether the layer as written belongs to a team scope. An owned
+// environment's merge never reads the default bundle, so a caller reporting
+// the default's version alongside a write needs to know, and this is the
+// one read that can say without a second one.
type Receipt struct {
VersionBefore, VersionAfter string
Changed bool
+ Owned bool
Set, Unset, UnsetAbsent []string
Digests map[string]string
}
@@ -161,7 +167,7 @@ func applyToManifest(m *Manifest, sets map[string]Var, unsets []string) Receipt
if m.Vars == nil {
m.Vars = map[string]Var{}
}
- r := Receipt{Set: []string{}, Unset: []string{}, UnsetAbsent: []string{}, Digests: map[string]string{}}
+ r := Receipt{Owned: m.OwnerScope != "", Set: []string{}, Unset: []string{}, UnsetAbsent: []string{}, Digests: map[string]string{}}
seen := make(map[string]bool, len(unsets))
for _, k := range unsets {
if seen[k] {
diff --git a/internal/appconfig/observe_apply_test.go b/internal/appconfig/observe_apply_test.go
index 6810c5549..c79f88de2 100644
--- a/internal/appconfig/observe_apply_test.go
+++ b/internal/appconfig/observe_apply_test.go
@@ -336,6 +336,28 @@ func TestApplyEnvironmentOwnedIfNoneRefused(t *testing.T) {
}
}
+// Owned says whether the layer as written is an owned environment, on every
+// write path: the door decides from it whether the default bundle's version
+// belongs in the receipt.
+func TestReceiptOwned(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ set := envVars(map[string]string{"A": "1"})
+ r, err := ApplyEnvironmentOwnedIf(ctx, s, "bab", "keymail", "team", "alta", "", set, nil)
+ if err != nil || !r.Owned {
+ t.Fatalf("owned write: Owned = %v, err %v; want true", r.Owned, err)
+ }
+ // The account's own write into that owned bundle, through ApplyIf.
+ if r, err = ApplyIf(ctx, s, "bab", "keymail", "team", "", set, nil); err != nil || !r.Owned {
+ t.Fatalf("ApplyIf into an owned bundle: Owned = %v, err %v; want true", r.Owned, err)
+ }
+ for _, env := range []string{"", "plain"} {
+ if r, err = ApplyIf(ctx, s, "bab", "keymail", env, "", set, nil); err != nil || r.Owned {
+ t.Fatalf("ApplyIf %q: Owned = %v, err %v; want false", env, r.Owned, err)
+ }
+ }
+}
+
// The unconditional callers keep today's contract: a lost race is
// release.ErrCASConflict (the door's 409), never the conditional 412.
func TestApplyUnchangedSignatures(t *testing.T) {
diff --git a/internal/console/apiconfig.go b/internal/console/apiconfig.go
index 5a449d22a..ef930a92e 100644
--- a/internal/console/apiconfig.go
+++ b/internal/console/apiconfig.go
@@ -316,9 +316,17 @@ func (s *Server) handleAPIConfigGet(w http.ResponseWriter, r *http.Request) {
// handleAPIConfigPut answers `carlos env set/unset`, `carlos secrets
// set/unset` and `carlos env exec-delivery`: one bundle, one request, one CAS
-// write for the set/unset half (appconfig.Apply) — two would mean a
+// write for the set/unset half (appconfig.ApplyIf) — two would mean a
// half-applied request whenever the second lost a race.
//
+// With if_version (or If-Match) that write is conditional on the bundle's
+// version (#522 §4.5): a bundle not at it is a 412 naming the version it is
+// at, nothing written. Every set/unset write answers with a receipt (§4.6)
+// saying exactly what it did to which version. Versions and digests go to
+// this caller only, never to a log line or an audit row: a version of plain
+// vars is a hash of plaintext, and an audit reader could test guesses
+// against it (R1-1).
+//
// EVERY REFUSAL RUNS BEFORE THE FIRST STORE CALL. That is not tidiness: a
// request carrying one good var and one malformed one must leave the bundle
// exactly as it found it, or an operator retrying a corrected request would
@@ -365,6 +373,10 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
// the field would otherwise be indistinguishable from one asking to
// 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"`
}
if !readJSONLimit(w, r, &req, configPutMaxBytes) {
return
@@ -499,11 +511,52 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
return
}
}
+ // 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, req.IfVersion)
+ if !ok {
+ return
+ }
+ if ifVersion != "" {
+ if req.ExecDelivery != nil {
+ // exec_delivery is a second CAS write (below), and one
+ // precondition cannot guard two writes.
+ jsonError(w, http.StatusBadRequest,
+ "if_version cannot cover exec_delivery, which is a separate write. send exec_delivery in a request of its own")
+ return
+ }
+ if !release.HasAtomicConditionalPut(s.cfg.Releases) {
+ // The guarantee is the store's to keep (R2-2): a DirStore checks
+ // the etag under a mutex one process holds, so a conditional
+ // write there would promise what it cannot keep.
+ jsonError(w, http.StatusBadRequest, "conditional writes need a store that supports them")
+ return
+ }
+ if team && ifVersion == appconfig.VersionNone {
+ // Creating an owned environment mints its platform credentials
+ // in further writes (mintOwnedEnvironment), which one
+ // precondition cannot cover (R1-3).
+ teamRefuse(w, `cannot create an environment with if_version "none". create it without if_version, then send the version in its receipt`)
+ return
+ }
+ // A name in both halves: applyToManifest unsets then sets, so the
+ // write is well defined, but a receipt listing the name as both set
+ // and removed answers a question the caller should not have asked
+ // while promising exactness. Refused only here, so an unconditional
+ // write behaves exactly as it always has.
+ if k := configSetAndUnset(keys, req.Unset); k != "" {
+ jsonError(w, http.StatusBadRequest,
+ fmt.Sprintf("%s is in both set and unset, which a write with if_version does not accept. send it in one of them", k))
+ return
+ }
+ }
ctx, cancel := context.WithTimeout(r.Context(), configStoreTimeout)
defer cancel()
bundle := configBundleName(envName)
removed := 0
+ var receipt *apiConfigReceipt
audit := ""
// A request carrying a sealed value holds the account lock from the
// key check through the write (fleet secrets key spec §5.2.1), so a key
@@ -553,23 +606,50 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
if configPutBeforeApply != nil {
configPutBeforeApply()
}
- var err error
- switch {
- case envName == "":
- removed, err = appconfig.Apply(ctx, s.cfg.Releases, acct.Sqid, app, sets, req.Unset)
- case team:
- removed, err = s.teamApplyEnvironment(ctx, tv, envName, sets, req.Unset)
+ var (
+ rc appconfig.Receipt
+ err error
+ defBefore string
+ defReadErr error
+ )
+ if team {
+ rc, err = s.teamApplyEnvironment(ctx, tv, envName, ifVersion, sets, req.Unset)
if errors.Is(err, errTeamOutOfScope) {
http.NotFound(w, r)
return
}
- default:
- removed, err = appconfig.ApplyEnvironment(ctx, s.cfg.Releases, acct.Sqid, app, envName, sets, req.Unset)
+ } else {
+ if envName != "" {
+ defBefore, defReadErr = s.configDefaultVersion(ctx, acct.Sqid, app)
+ }
+ rc, err = appconfig.ApplyIf(ctx, s.cfg.Releases, acct.Sqid, app, envName, ifVersion, sets, req.Unset)
+ }
+ what := fmt.Sprintf("api config apply %s/%s (%s)", acct.Sqid, app, bundle)
+ if errors.Is(err, appconfig.ErrVersionMismatch) {
+ s.configPreconditionFailed(w, r, ctx, what, acct.Sqid, app, envName, tv, err)
+ return
}
if err != nil {
- s.configStoreError(w, fmt.Sprintf("api config apply %s/%s (%s)", acct.Sqid, app, bundle), err)
+ s.configStoreError(w, what, err)
return
}
+ removed = len(rc.Unset)
+ receipt = configReceiptWire(bundle, rc)
+ // For a named environment that folds the default in, the default's
+ // version either side of the write (§4.6). The two are separate
+ // objects with no shared transaction, so this reports, it does not
+ // guard: a before and after that differ mean someone wrote the
+ // default during this request. A team's environment is owned, and a
+ // team sees nothing of the default. Either read failing leaves the
+ // pair out rather than half of it, and costs the write nothing.
+ if envName != "" && !team && !rc.Owned {
+ defAfter, err := s.configDefaultVersion(ctx, acct.Sqid, app)
+ if defReadErr == nil && err == nil {
+ receipt.Others = map[string]apiConfigVersionPair{
+ appconfig.DefaultBundle: {Before: defBefore, After: defAfter},
+ }
+ }
+ }
unlockAcct()
// Counts and the bundle, never keys and never values — an audit trail
// that recorded a secret's envelope would be a copy of the secret
@@ -608,6 +688,12 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
s.bumpSerial(ctx)
}
out := map[string]any{"result": "ok", "removed": removed}
+ // Only the set/unset half has a receipt: an exec_delivery-only request
+ // wrote through a setter that reports no versions, and an answer
+ // claiming one would describe a write this door did not make.
+ if receipt != nil {
+ out["receipt"] = receipt
+ }
// Whether this write landed on a process that will never read it
// (discussion #16). Computed AFTER both writes, because it describes
// what they left behind, and only when something actually changed: an
@@ -847,44 +933,161 @@ var errTeamOutOfScope = errors.New("console: environment is out of the team's sc
// or that any bundle already holds, is not the scope's to create; the
// scope's own bundle is written, and a bundle another scope holds is out
// of scope. The ownership is re-checked on the CAS bytes inside
-// appconfig.ApplyEnvironmentOwned, so a release or adopt that lands between
+// appconfig.ApplyEnvironmentOwnedIf, so a release or adopt that lands between
// the check here and the write is a refusal, not a write into a bundle the
// scope no longer holds.
-func (s *Server) teamApplyEnvironment(ctx context.Context, tv *teamView, envName string, sets map[string]appconfig.Var, unsets []string) (int, error) {
+func (s *Server) teamApplyEnvironment(ctx context.Context, tv *teamView, envName, ifVersion string, sets map[string]appconfig.Var, unsets []string) (appconfig.Receipt, error) {
defer s.lockApp(tv.acct.Sqid, tv.app)()
m, _, found, err := appconfig.GetEnvironment(ctx, s.cfg.Releases, tv.acct.Sqid, tv.app, envName)
if err != nil {
- return 0, err
+ return appconfig.Receipt{}, err
}
if found {
if m.OwnerScope != tv.scope {
- return 0, errTeamOutOfScope
+ return appconfig.Receipt{}, errTeamOutOfScope
}
} else {
recs, truncated, err := s.listRecords(ctx, tv.acct.Sqid, tv.app, instanceListMax)
if err != nil {
- return 0, err
+ return appconfig.Receipt{}, err
}
if truncated {
// More records than the listing holds: whether one references
// the name is not known, so the name is not the scope's.
- return 0, fmt.Errorf("config: %s/%s has more than %d instance records, so a new environment's name cannot be checked against them", tv.acct.Sqid, tv.app, instanceListMax)
+ return appconfig.Receipt{}, fmt.Errorf("config: %s/%s has more than %d instance records, so a new environment's name cannot be checked against them", tv.acct.Sqid, tv.app, instanceListMax)
}
for _, rec := range recs {
if rec.Environment == envName {
- return 0, errTeamOutOfScope
+ return appconfig.Receipt{}, errTeamOutOfScope
}
}
}
- removed, err := appconfig.ApplyEnvironmentOwned(ctx, s.cfg.Releases, tv.acct.Sqid, tv.app, envName, tv.scope, sets, unsets)
+ // The version is compared inside, on the read whose etag guards the
+ // write, after the ownership check there: the check above is not the
+ // one the write rests on (§4.5, R1-3).
+ rc, err := appconfig.ApplyEnvironmentOwnedIf(ctx, s.cfg.Releases, tv.acct.Sqid, tv.app, envName, tv.scope, ifVersion, sets, unsets)
if errors.Is(err, appconfig.ErrNotOwnedBy) {
- return 0, errTeamOutOfScope
+ return appconfig.Receipt{}, errTeamOutOfScope
}
if err == nil && !found {
// A bundle this scope just brought into being: the walks mint its
// own platform credentials (§3a), under the lock, best-effort — a
- // re-enable repairs anything that did not land.
+ // re-enable repairs anything that did not land. Never after a
+ // conditional write: the door refuses "none" for a team, and any
+ // other version of an absent bundle is a mismatch.
s.mintOwnedEnvironment(ctx, tv.acct, tv.app, envName)
}
- return removed, err
+ return rc, err
+}
+
+// configIfVersion is the PUT's precondition, from the body's if_version or
+// the If-Match header, answering the 400 itself when the two disagree. ""
+// means none. The header is the HTTP spelling for clients that already
+// 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]
+ }
+ switch {
+ case header == "":
+ return body, true
+ case 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")
+ return "", false
+}
+
+// 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.
+func configSetAndUnset(keys, unsets []string) string {
+ unset := make(map[string]bool, len(unsets))
+ for _, k := range unsets {
+ unset[k] = true
+ }
+ for _, k := range keys {
+ if unset[k] {
+ return k
+ }
+ }
+ return ""
+}
+
+// configDefaultVersion is the default bundle's version, for a receipt's
+// others. A failure is logged and handed back; the caller drops the pair.
+func (s *Server) configDefaultVersion(ctx context.Context, acct, app string) (string, error) {
+ l, err := appconfig.LoadLayer(ctx, s.cfg.Releases, appconfig.Key(acct, app), app)
+ if err != nil {
+ log.Printf("console: api config apply %s/%s: default version: %v", acct, app, err)
+ return "", err
+ }
+ return l.Version, nil
+}
+
+// configPreconditionFailed answers a conditional write refused because the
+// bundle was not at the caller's version, at read or by the write. The
+// answer names the version now stored, read once more, so the caller can
+// re-read and decide without a second round trip to learn it. A team hears
+// it only for a bundle its scope still owns (or one still absent, which it
+// could create): the bundle can change hands between the refused write and
+// this read, and another scope's version is not this caller's to see. If
+// the read fails the 412 still stands, without a version: nothing was
+// written either way.
+func (s *Server) configPreconditionFailed(w http.ResponseWriter, r *http.Request, ctx context.Context, what, acct, app, envName string, tv *teamView, err error) {
+ log.Printf("console: %s: %v", what, err)
+ out := map[string]any{"error": "the config is not at the version you sent, so nothing was written. read it again before you retry"}
+ l, rerr := appconfig.LoadLayer(ctx, s.cfg.Releases, appconfig.BundleKey(acct, app, envName), app)
+ switch {
+ case rerr != nil:
+ log.Printf("console: %s: current version: %v", what, rerr)
+ case tv != nil && l.Found && l.Manifest.OwnerScope != tv.scope:
+ http.NotFound(w, r)
+ return
+ default:
+ out["version"] = l.Version
+ }
+ writeJSON(w, http.StatusPreconditionFailed, out)
+}
+
+// apiConfigReceipt is the wire shape of one write's receipt (§4.6). Names
+// and digests only: a secret's envelope has no field here, as on the GET.
+type apiConfigReceipt struct {
+ Bundle string `json:"bundle"`
+ VersionBefore string `json:"version_before"`
+ VersionAfter string `json:"version_after"`
+ Changed bool `json:"changed"`
+ Set []string `json:"set"`
+ Unset []string `json:"unset"`
+ UnsetAbsent []string `json:"unset_absent"`
+ Digests map[string]string `json:"digests"`
+ // Others names other layers' versions either side of the write, keyed
+ // by bundle: today only the default, for a named environment that folds
+ // it in.
+ Others map[string]apiConfigVersionPair `json:"others,omitempty"`
+}
+
+type apiConfigVersionPair struct {
+ Before string `json:"before"`
+ After string `json:"after"`
+}
+
+// configReceiptWire copies a Receipt onto the wire field by field, so a
+// field added to appconfig.Receipt reaches callers only when chosen here
+// (Owned, for one, is the door's to act on, not to report).
+func configReceiptWire(bundle string, rc appconfig.Receipt) *apiConfigReceipt {
+ return &apiConfigReceipt{
+ Bundle: bundle,
+ VersionBefore: rc.VersionBefore,
+ VersionAfter: rc.VersionAfter,
+ Changed: rc.Changed,
+ Set: rc.Set,
+ Unset: rc.Unset,
+ UnsetAbsent: rc.UnsetAbsent,
+ Digests: rc.Digests,
+ }
}
diff --git a/internal/console/apiconfig_conditional_test.go b/internal/console/apiconfig_conditional_test.go
new file mode 100644
index 000000000..a997397ca
--- /dev/null
+++ b/internal/console/apiconfig_conditional_test.go
@@ -0,0 +1,633 @@
+package console
+
+// Conditional config writes and receipts on the PUT door (#522 plan 1, spec
+// §4.5-4.6): if_version and its If-Match synonym, the 412, the refusals that
+// answer before anything is read, and the receipt every write now carries.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// cfgCountStore counts the Gets made under one app's prefix, so a refusal can
+// be shown to have read nothing, and runs beforePut once ahead of the first
+// Put to putKey: another writer landing between the door's read and its
+// write. It makes no promise about conditional writes.
+type cfgCountStore struct {
+ release.Store
+ prefix string
+
+ mu sync.Mutex
+ gets int
+ putKey string
+ beforePut func(ctx context.Context)
+}
+
+func (c *cfgCountStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if strings.HasPrefix(key, c.prefix) {
+ c.mu.Lock()
+ c.gets++
+ c.mu.Unlock()
+ }
+ return c.Store.Get(ctx, key)
+}
+
+func (c *cfgCountStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ c.mu.Lock()
+ hook := c.beforePut
+ if key != c.putKey {
+ hook = nil
+ }
+ if hook != nil {
+ c.beforePut = nil
+ }
+ c.mu.Unlock()
+ if hook != nil {
+ hook(ctx)
+ }
+ return c.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (c *cfgCountStore) getCount() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.gets
+}
+
+// atomicDirStore is cfgCountStore claiming an atomic conditional Put. In one
+// test process DirStore's mutex makes its check and replace one step, which
+// is the promise; production consoles get it from S3.
+type atomicDirStore struct{ *cfgCountStore }
+
+func (atomicDirStore) AtomicConditionalPut() {}
+
+// useCfgCountStore puts the console on a cfgCountStore over the fixture's bucket,
+// atomic or not. fx.rel stays the plain store, so the test's own reads are
+// not counted.
+func useCfgCountStore(fx *consoleFixture, atomic bool) *cfgCountStore {
+ c := &cfgCountStore{Store: fx.rel, prefix: release.AppPrefix(release.OpsAccount, "titogo")}
+ if atomic {
+ fx.srv.cfg.Releases = atomicDirStore{c}
+ } else {
+ fx.srv.cfg.Releases = c
+ }
+ return c
+}
+
+// rawAtKey is the stored bytes at key, nil when absent.
+func rawAtKey(t *testing.T, fx *consoleFixture, key string) []byte {
+ t.Helper()
+ raw, _, err := fx.rel.Get(context.Background(), key)
+ if err != nil {
+ return nil
+ }
+ return raw
+}
+
+// receiptOf is the receipt object of a PUT's answer.
+func receiptOf(t *testing.T, out map[string]any) map[string]any {
+ t.Helper()
+ r, ok := out["receipt"].(map[string]any)
+ if !ok {
+ t.Fatalf("answer has no receipt: %v", out)
+ }
+ return r
+}
+
+// receiptList decodes a JSON array of strings, failing on null: the receipt's
+// lists are always present.
+func receiptList(t *testing.T, m map[string]any, k string) []string {
+ t.Helper()
+ raw, ok := m[k].([]any)
+ if !ok {
+ t.Fatalf("%s = %#v, want an array", k, m[k])
+ }
+ out := make([]string, 0, len(raw))
+ for _, v := range raw {
+ out = append(out, v.(string))
+ }
+ return out
+}
+
+func putBody(t *testing.T, body map[string]any) string {
+ t.Helper()
+ raw, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+func seedDefault(t *testing.T, fx *consoleFixture, token string, set map[string]any) {
+ t.Helper()
+ if status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{"set": set}, token); status != http.StatusOK {
+ t.Fatalf("seed PUT = %d %v", status, out)
+ }
+}
+
+func envSet(kv ...string) map[string]any {
+ out := map[string]any{}
+ for i := 0; i+1 < len(kv); i += 2 {
+ out[kv[i]] = map[string]any{"kind": "env", "value": kv[i+1]}
+ }
+ return out
+}
+
+func configEventCount(t *testing.T, fx *consoleFixture) int {
+ t.Helper()
+ events, err := fx.st.Events(OpsAccountID, "titogo", 200)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n := 0
+ for _, e := range events {
+ if e.Action == "config" {
+ n++
+ }
+ }
+ return n
+}
+
+// TestAPIConfigPutReceipt: an unconditional write answers with a receipt
+// whose versions name the stored bytes either side and whose lists are
+// exact, and keeps today's removed.
+func TestAPIConfigPutReceipt(t *testing.T) {
+ fx, token := configFixture(t, "code-config-receipt")
+ seedDefault(t, fx, token, envSet("OLD", "1", "KEEP", "2"))
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ before := storedVersion(t, fx, key)
+ _, _, envelope := sealedFor(t, "receipt-secret")
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "set": map[string]any{
+ "PORT": map[string]any{"kind": "env", "value": "8080"},
+ "BANK_KEY": map[string]any{"kind": "secret", "envelope": envelope},
+ },
+ "unset": []string{"OLD", "NEVER_THERE", "OLD"},
+ }, token)
+ if status != http.StatusOK {
+ t.Fatalf("PUT = %d %v", status, out)
+ }
+ if out["removed"] != 1.0 {
+ t.Errorf("removed = %v, want 1", out["removed"])
+ }
+ r := receiptOf(t, out)
+ if str(t, r, "bundle") != appconfig.DefaultBundle {
+ t.Errorf("bundle = %v", r["bundle"])
+ }
+ if got := str(t, r, "version_before"); got != before {
+ t.Errorf("version_before = %q, want %q", got, before)
+ }
+ if got, want := str(t, r, "version_after"), storedVersion(t, fx, key); got != want {
+ t.Errorf("version_after = %q, want %q (the stored bytes')", got, want)
+ }
+ if r["changed"] != true {
+ t.Errorf("changed = %v, want true", r["changed"])
+ }
+ if got := receiptList(t, r, "set"); !reflect.DeepEqual(got, []string{"BANK_KEY", "PORT"}) {
+ t.Errorf("set = %v", got)
+ }
+ if got := receiptList(t, r, "unset"); !reflect.DeepEqual(got, []string{"OLD"}) {
+ t.Errorf("unset = %v", got)
+ }
+ if got := receiptList(t, r, "unset_absent"); !reflect.DeepEqual(got, []string{"NEVER_THERE"}) {
+ t.Errorf("unset_absent = %v", got)
+ }
+ stored, _ := storedManifest(t, fx, "titogo")
+ digests, _ := r["digests"].(map[string]any)
+ if len(digests) != 2 {
+ t.Errorf("digests = %v, want the two keys just set", digests)
+ }
+ for _, k := range []string{"PORT", "BANK_KEY"} {
+ if digests[k] != appconfig.Digest(stored.Vars[k]) {
+ t.Errorf("digest %s = %v, want %q", k, digests[k], appconfig.Digest(stored.Vars[k]))
+ }
+ }
+ if _, ok := r["others"]; ok {
+ t.Errorf("a default-bundle write carries others: %v", r["others"])
+ }
+ if strings.Contains(fmt.Sprint(out), envelope) {
+ t.Fatal("the answer carries the envelope")
+ }
+}
+
+// TestAPIConfigPutIfVersionStale: a stale if_version is 412 naming the
+// current version, with nothing written and no generation bump.
+func TestAPIConfigPutIfVersionStale(t *testing.T) {
+ fx, token := configFixture(t, "code-config-stale")
+ useCfgCountStore(fx, true)
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ seedDefault(t, fx, token, envSet("A", "1"))
+ old := storedVersion(t, fx, key)
+ seedDefault(t, fx, token, envSet("A", "2"))
+ cur := storedVersion(t, fx, key)
+ stored := rawAtKey(t, fx, key)
+ gen := genEtag(t, fx, "titogo")
+ events := configEventCount(t, fx)
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "if_version": old, "set": envSet("B", "3"),
+ }, token)
+ if status != http.StatusPreconditionFailed {
+ t.Fatalf("stale PUT = %d %v, want 412", status, out)
+ }
+ if str(t, out, "version") != cur {
+ t.Errorf("412 version = %v, want %q", out["version"], cur)
+ }
+ if str(t, out, "error") == "" {
+ t.Error("412 carries no error sentence")
+ }
+ if !bytes.Equal(rawAtKey(t, fx, key), stored) {
+ t.Fatal("a stale write changed the stored bytes")
+ }
+ if genEtag(t, fx, "titogo") != gen {
+ t.Fatal("a stale write bumped the generation")
+ }
+ if configEventCount(t, fx) != events {
+ t.Fatal("a stale write left an audit row")
+ }
+
+ // At the current version it lands, and the receipt starts there.
+ status, out = putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "if_version": cur, "set": envSet("B", "3"),
+ }, token)
+ if status != http.StatusOK {
+ t.Fatalf("PUT at the current version = %d %v", status, out)
+ }
+ if r := receiptOf(t, out); str(t, r, "version_before") != cur || str(t, r, "version_after") != storedVersion(t, fx, key) {
+ t.Errorf("receipt versions = %v -> %v", r["version_before"], r["version_after"])
+ }
+
+ // "none" creates a named environment once, and is 412 after that.
+ body := map[string]any{"environment": "staging", "if_version": appconfig.VersionNone, "set": envSet("S", "1")}
+ if status, out := putJSON(t, configURL(fx, "titogo"), body, token); status != http.StatusOK {
+ t.Fatalf("create with none = %d %v", status, out)
+ }
+ status, out = putJSON(t, configURL(fx, "titogo"), body, token)
+ envKey := appconfig.EnvironmentKey(release.OpsAccount, "titogo", "staging")
+ if status != http.StatusPreconditionFailed || str(t, out, "version") != storedVersion(t, fx, envKey) {
+ t.Fatalf("second create with none = %d %v, want 412 naming the stored version", status, out)
+ }
+}
+
+// TestAPIConfigPutIfVersionRace: another writer landing between the door's
+// read and its write is a 412 too, and its bytes stay (R2-4).
+func TestAPIConfigPutIfVersionRace(t *testing.T) {
+ fx, token := configFixture(t, "code-config-race")
+ cs := useCfgCountStore(fx, true)
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ seedDefault(t, fx, token, envSet("A", "1"))
+ cur := storedVersion(t, fx, key)
+ competing := []byte(`{"schema":1,"app":"titogo","vars":{"A":{"kind":"env","value":"theirs"}}}`)
+ cs.putKey = key
+ cs.beforePut = func(ctx context.Context) {
+ _, etag, err := fx.rel.Get(ctx, key)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if _, err := fx.rel.Put(ctx, key, competing, etag); err != nil {
+ t.Error(err)
+ }
+ }
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "if_version": cur, "set": envSet("B", "2"),
+ }, token)
+ if status != http.StatusPreconditionFailed {
+ t.Fatalf("raced PUT = %d %v, want 412", status, out)
+ }
+ if !bytes.Equal(rawAtKey(t, fx, key), competing) {
+ t.Fatal("the competing write was overwritten")
+ }
+ if got, want := str(t, out, "version"), appconfig.Version(competing, true); got != want {
+ t.Errorf("412 version = %q, want the competing bytes' %q", got, want)
+ }
+}
+
+// TestAPIConfigPutIfVersionWithExecDelivery: one precondition cannot cover
+// two writes, so the pair is refused before anything is read.
+func TestAPIConfigPutIfVersionWithExecDelivery(t *testing.T) {
+ fx, token := configFixture(t, "code-config-exec-if")
+ seedDefault(t, fx, token, envSet("A", "1"))
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ cur := storedVersion(t, fx, key)
+ stored := rawAtKey(t, fx, key)
+ cs := useCfgCountStore(fx, true)
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "if_version": cur, "set": envSet("B", "2"), "exec_delivery": "file",
+ }, token)
+ if status != http.StatusBadRequest {
+ t.Fatalf("if_version with exec_delivery = %d %v, want 400", status, out)
+ }
+ if n := cs.getCount(); n != 0 {
+ t.Errorf("the refusal read the store %d times, want 0", n)
+ }
+ if !bytes.Equal(rawAtKey(t, fx, key), stored) {
+ t.Fatal("the refusal changed the stored bytes")
+ }
+}
+
+// TestAPIConfigPutIfMatchHeaderConflict: If-Match is the body field's
+// synonym; the two disagreeing is a 400 before any read.
+func TestAPIConfigPutIfMatchHeaderConflict(t *testing.T) {
+ fx, token := configFixture(t, "code-config-ifmatch")
+ seedDefault(t, fx, token, envSet("A", "1"))
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ cur := storedVersion(t, fx, key)
+ cs := useCfgCountStore(fx, true)
+ u := configURL(fx, "titogo")
+
+ body := putBody(t, map[string]any{"if_version": cur, "set": envSet("B", "2")})
+ status, _, out := rawReqHeader(t, http.MethodPut, u, token, body, map[string]string{"If-Match": `"cv1:00"`})
+ if status != http.StatusBadRequest {
+ t.Fatalf("header and body differ = %d %s, want 400", status, out)
+ }
+ if n := cs.getCount(); n != 0 {
+ t.Errorf("the refusal read the store %d times, want 0", n)
+ }
+
+ // The header alone, stale: 412, as the body field would be.
+ body = putBody(t, map[string]any{"set": envSet("B", "2")})
+ if status, _, out := rawReqHeader(t, http.MethodPut, u, token, body, map[string]string{"If-Match": "cv1:00"}); status != http.StatusPreconditionFailed {
+ t.Fatalf("stale header = %d %s, want 412", status, out)
+ }
+ // The header alone, current and quoted as an HTTP entity tag: it lands.
+ status, _, out = rawReqHeader(t, http.MethodPut, u, token, body, map[string]string{"If-Match": `"` + cur + `"`})
+ if status != http.StatusOK {
+ t.Fatalf("current header = %d %s, want 200", status, out)
+ }
+ var res map[string]any
+ if err := json.Unmarshal([]byte(out), &res); err != nil {
+ t.Fatal(err)
+ }
+ if r := receiptOf(t, res); str(t, r, "version_before") != cur {
+ t.Errorf("version_before = %v, want %q", r["version_before"], cur)
+ }
+ // Header and body agreeing is the same as either.
+ now := storedVersion(t, fx, key)
+ body = putBody(t, map[string]any{"if_version": now, "set": envSet("C", "3")})
+ if status, _, out := rawReqHeader(t, http.MethodPut, u, token, body, map[string]string{"If-Match": now}); status != http.StatusOK {
+ t.Fatalf("agreeing header and body = %d %s, want 200", status, out)
+ }
+}
+
+// TestAPIConfigPutIfVersionOnDirStore: a store that cannot promise an
+// atomic conditional write refuses if_version before any read (R2-2), and
+// keeps unconditional writes as they were.
+func TestAPIConfigPutIfVersionOnDirStore(t *testing.T) {
+ fx, token := configFixture(t, "code-config-dirstore")
+ seedDefault(t, fx, token, envSet("A", "1"))
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ cur := storedVersion(t, fx, key)
+ stored := rawAtKey(t, fx, key)
+ cs := useCfgCountStore(fx, false)
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "if_version": cur, "set": envSet("B", "2"),
+ }, token)
+ if status != http.StatusBadRequest {
+ t.Fatalf("if_version on a DirStore = %d %v, want 400", status, out)
+ }
+ if n := cs.getCount(); n != 0 {
+ t.Errorf("the refusal read the store %d times, want 0", n)
+ }
+ if !bytes.Equal(rawAtKey(t, fx, key), stored) {
+ t.Fatal("the refusal changed the stored bytes")
+ }
+ if status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{"set": envSet("B", "2")}, token); status != http.StatusOK {
+ t.Fatalf("unconditional PUT on a DirStore = %d %v", status, out)
+ }
+}
+
+// TestAPIConfigPutIfVersionSetAndUnsetSameName: with a precondition, a name
+// both set and unset is refused before any read; without one it is today's
+// write.
+func TestAPIConfigPutIfVersionSetAndUnsetSameName(t *testing.T) {
+ fx, token := configFixture(t, "code-config-both")
+ seedDefault(t, fx, token, envSet("A", "1"))
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ cur := storedVersion(t, fx, key)
+ stored := rawAtKey(t, fx, key)
+ cs := useCfgCountStore(fx, true)
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "if_version": cur, "set": envSet("A", "2"), "unset": []string{"A"},
+ }, token)
+ if status != http.StatusBadRequest {
+ t.Fatalf("set and unset of one name with if_version = %d %v, want 400", status, out)
+ }
+ if n := cs.getCount(); n != 0 {
+ t.Errorf("the refusal read the store %d times, want 0", n)
+ }
+ if !bytes.Equal(rawAtKey(t, fx, key), stored) {
+ t.Fatal("the refusal changed the stored bytes")
+ }
+ if status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "set": envSet("A", "2"), "unset": []string{"A"},
+ }, token); status != http.StatusOK {
+ t.Fatalf("the same write without if_version = %d %v, want today's 200", status, out)
+ }
+}
+
+// TestAPIConfigPutOthersForNamedEnv: a write to a named environment that is
+// not owned names the default bundle's version either side of it; a write
+// to an owned one, whose merge never reads the default, does not.
+func TestAPIConfigPutOthersForNamedEnv(t *testing.T) {
+ fx, token := configFixture(t, "code-config-others")
+ seedDefault(t, fx, token, envSet("BASE", "1"))
+ defKey := appconfig.Key(release.OpsAccount, "titogo")
+ def := storedVersion(t, fx, defKey)
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "environment": "staging", "set": envSet("S", "1"),
+ }, token)
+ if status != http.StatusOK {
+ t.Fatalf("PUT staging = %d %v", status, out)
+ }
+ r := receiptOf(t, out)
+ if str(t, r, "bundle") != "staging" {
+ t.Errorf("bundle = %v", r["bundle"])
+ }
+ envKey := appconfig.EnvironmentKey(release.OpsAccount, "titogo", "staging")
+ if str(t, r, "version_before") != appconfig.VersionNone || str(t, r, "version_after") != storedVersion(t, fx, envKey) {
+ t.Errorf("versions = %v -> %v", r["version_before"], r["version_after"])
+ }
+ others, _ := r["others"].(map[string]any)
+ pair, _ := others["default"].(map[string]any)
+ if pair == nil || str(t, pair, "before") != def || str(t, pair, "after") != def {
+ t.Fatalf("others = %v, want default before and after both %q", r["others"], def)
+ }
+
+ // The default bundle written during the request: before and after differ.
+ cs := useCfgCountStore(fx, false)
+ cs.putKey = envKey
+ cs.beforePut = func(ctx context.Context) {
+ if err := appconfig.SetEnv(ctx, fx.rel, release.OpsAccount, "titogo", map[string]string{"BASE": "2"}); err != nil {
+ t.Error(err)
+ }
+ }
+ status, out = putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "environment": "staging", "set": envSet("S", "2"),
+ }, token)
+ if status != http.StatusOK {
+ t.Fatalf("second PUT staging = %d %v", status, out)
+ }
+ pair, _ = receiptOf(t, out)["others"].(map[string]any)["default"].(map[string]any)
+ if str(t, pair, "before") != def || str(t, pair, "after") != storedVersion(t, fx, defKey) || str(t, pair, "after") == def {
+ t.Fatalf("others.default = %v, want %q then the moved version", pair, def)
+ }
+
+ // An owned environment, written by the account itself: no others.
+ if _, err := appconfig.ApplyEnvironmentOwned(context.Background(), fx.rel, release.OpsAccount, "titogo", "team", "alta",
+ map[string]appconfig.Var{"T": {Kind: "env", Value: "1"}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ status, out = putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "environment": "team", "set": envSet("T", "2"),
+ }, token)
+ if status != http.StatusOK {
+ t.Fatalf("PUT owned = %d %v", status, out)
+ }
+ if o, ok := receiptOf(t, out)["others"]; ok {
+ t.Errorf("an owned environment's receipt carries others: %v", o)
+ }
+}
+
+// TestAPIConfigTeamPutIfVersion: a team's conditional write is checked on
+// the owned path, ownership first; "none" (create) is refused before any
+// read (R1-3).
+func TestAPIConfigTeamPutIfVersion(t *testing.T) {
+ w := newTeamWorld(t, "code-team-ifversion")
+ cs := useCfgCountStore(w.fx, true)
+ ctx := context.Background()
+ key := appconfig.EnvironmentKey(release.OpsAccount, "titogo", "team")
+ old := storedVersion(t, w.fx, key)
+ if _, err := appconfig.ApplyEnvironmentOwned(ctx, w.fx.rel, "bab", "titogo", "team", "alta",
+ map[string]appconfig.Var{"MOVED": {Kind: "env", Value: "1"}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ cur := storedVersion(t, w.fx, key)
+ stored := rawAtKey(t, w.fx, key)
+
+ status, out := putJSON(t, w.url("/config"), map[string]any{
+ "environment": "team", "if_version": old, "set": envSet("K", "v"),
+ }, w.team)
+ if status != http.StatusPreconditionFailed || str(t, out, "version") != cur {
+ t.Fatalf("stale team PUT = %d %v, want 412 naming %q", status, out, cur)
+ }
+ if !bytes.Equal(rawAtKey(t, w.fx, key), stored) {
+ t.Fatal("a stale team write changed the stored bytes")
+ }
+
+ // Another scope's bundle is the not-found it always was, whatever the
+ // version: a 412 would say it exists.
+ other := storedVersion(t, w.fx, appconfig.EnvironmentKey(release.OpsAccount, "titogo", "other"))
+ w.notFound(t, "conditional PUT other", http.MethodPut, "/config",
+ putBody(t, map[string]any{"environment": "other", "if_version": other, "set": envSet("K", "v")}))
+
+ // The scope gate reads the named bundle's owner before any team
+ // handler runs. A request refused by the handler's own body checks
+ // costs exactly that read and no more, so it is the yardstick.
+ before := cs.getCount()
+ if status, out := putJSON(t, w.url("/config"), map[string]any{
+ "environment": "fresh", "set": envSet("bad-name", "v"),
+ }, w.team); status != http.StatusBadRequest {
+ t.Fatalf("yardstick PUT = %d %v, want 400", status, out)
+ }
+ gate := cs.getCount() - before
+ before = cs.getCount()
+ status, out = putJSON(t, w.url("/config"), map[string]any{
+ "environment": "fresh", "if_version": appconfig.VersionNone, "set": envSet("K", "v"),
+ }, w.team)
+ if status != http.StatusBadRequest {
+ t.Fatalf("team PUT with none = %d %v, want 400", status, out)
+ }
+ if n := cs.getCount() - before; n != gate {
+ t.Errorf("the refusal read the store %d times, want the scope gate's %d alone", n, gate)
+ }
+ if _, _, found, _ := appconfig.GetEnvironment(ctx, w.fx.rel, "bab", "titogo", "fresh"); found {
+ t.Fatal("a refused create landed")
+ }
+
+ status, out = putJSON(t, w.url("/config"), map[string]any{
+ "environment": "team", "if_version": cur, "set": envSet("K", "v"), "unset": []string{"TEAM_ONLY"},
+ }, w.team)
+ if status != http.StatusOK || out["removed"] != 1.0 {
+ t.Fatalf("team PUT at the current version = %d %v", status, out)
+ }
+ r := receiptOf(t, out)
+ if str(t, r, "version_before") != cur || str(t, r, "version_after") != storedVersion(t, w.fx, key) {
+ t.Errorf("receipt versions = %v -> %v", r["version_before"], r["version_after"])
+ }
+ if _, ok := r["others"]; ok {
+ t.Errorf("a team receipt names the default bundle: %v", r["others"])
+ }
+}
+
+// TestAPIConfigPutNoContentInLogsOrAudit: versions and digests go to the
+// caller only; the log and the audit row carry what they carried before.
+func TestAPIConfigPutNoContentInLogsOrAudit(t *testing.T) {
+ fx, token := configFixture(t, "code-config-nocontent")
+ useCfgCountStore(fx, true)
+ buf := captureLog(t)
+ _, _, envelope := sealedFor(t, "audit-secret")
+ const plain = "plain-value-canary"
+ set := map[string]any{
+ "PORT": map[string]any{"kind": "env", "value": plain},
+ "BANK_KEY": map[string]any{"kind": "secret", "envelope": envelope},
+ }
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{"set": set}, token)
+ if status != http.StatusOK {
+ t.Fatalf("PUT = %d %v", status, out)
+ }
+ stale := str(t, receiptOf(t, out), "version_before")
+ // A refused conditional write logs too; it must say no more.
+ if status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{"if_version": stale, "set": set}, token); status != http.StatusPreconditionFailed {
+ t.Fatalf("stale PUT = %d %v", status, out)
+ }
+ cur := storedVersion(t, fx, appconfig.Key(release.OpsAccount, "titogo"))
+ if status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{"if_version": cur, "set": set}, token); status != http.StatusOK {
+ t.Fatalf("conditional PUT = %d %v", status, out)
+ }
+
+ logged := buf.String()
+ for _, bad := range []string{envelope, plain, "cv1:", "vd1:"} {
+ if strings.Contains(logged, bad) {
+ t.Errorf("the log carries %q:\n%s", bad, logged)
+ }
+ }
+ events, err := fx.st.Events(OpsAccountID, "titogo", 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var details []string
+ for _, e := range events {
+ row := fmt.Sprintf("%+v", e)
+ for _, bad := range []string{envelope, plain, "cv1:", "vd1:"} {
+ if strings.Contains(row, bad) {
+ t.Errorf("audit row carries %q: %s", bad, row)
+ }
+ }
+ if e.Action == "config" {
+ details = append(details, e.Detail)
+ }
+ }
+ sort.Strings(details)
+ want := []string{"config: 2 set, 0 unset (default) (cli)", "config: 2 set, 0 unset (default) (cli)"}
+ if !reflect.DeepEqual(details, want) {
+ t.Errorf("config audit details = %q, want %q", details, want)
+ }
+}