carlos / platform Public

config: receipts describe the whole request; one-read env list --json

A receipt reports the version the completed request left (round 1, P2-3):
after exec_delivery, or the credentials minted into a team's new
environment, the door reads the bundle once more and reports that version,
with changed from it. A failed or out-of-scope read drops the receipt.

A default bundle the door could not read either side of a write keeps
others.default with the half it read and unavailable: true (P2-4); the
CLI prints one line saying it could not be compared.

carlos env list --json carries every var, secrets as digests only, under
one version (P2-5). A given but empty --if-version is refused, and the
effective 404 names --host and an older console.

Witnesses (P2-7): stale team create with minting on writes and mints
nothing; ownership change during the 412 re-read is the canonical 404; a
real second account with the same names is 404; an overlay secret shows
as its digest alone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 5e766b38b79178c0d53e36633f7f02827b25f60f parent 21e4aa5
6 files changed, +633 −43
  • apimode.go +19 −7
  • apimode_test.go +32 −0
  • appconfig_cli.go +58 −9
  • appconfig_cli_test.go +89 −4
  • internal/console/apiconfig.go +85 −21
  • internal/console/apiconfig_witness_test.go +350 −2
diff --git a/apimode.go b/apimode.go
index 36b9ec018..b98525408 100644
--- a/apimode.go
+++ b/apimode.go
@@ -3111,19 +3111,26 @@ type apiConfigReceipt struct {
Digests map[string]string `json:"digests"`
// Others is present for a write to a named environment that folds the
// default bundle in: the default's version just before and just after.
- // They differ when somebody else wrote the default during this write.
+ // They differ when somebody else wrote the default during this write,
+ // and the pair is marked unavailable when the console could not read
+ // the default on one side of it.
Others map[string]apiConfigVersionPair `json:"others,omitempty"`
}
+// apiConfigVersionPair is one of a receipt's others. Unavailable is set
+// when the console could not read that layer on one side of the write or
+// both; the half it did read is kept, the other is "".
type apiConfigVersionPair struct {
- Before string `json:"before"`
- After string `json:"after"`
+ Before string `json:"before"`
+ After string `json:"after"`
+ Unavailable bool `json:"unavailable"`
}
// apiConfigEffective is GET .../config/effective?host=: what one route's
// stored config resolves to, layer by layer (#522 §4.4). The json tags are
-// the wire's, so `carlos env effective --json` re-encodes the console's
-// answer unchanged.
+// the wire's, so `carlos env effective --json` re-encodes the fields this
+// CLI knows under the console's own names. A field a newer console adds is
+// dropped, not passed through: the output is typed, by choice.
type apiConfigEffective struct {
Host string `json:"host"`
Environment string `json:"environment"`
@@ -3159,13 +3166,18 @@ type apiEffectiveVar struct {
}
// configEffective reads one route's effective config. host must be a route
-// of app; anything else is the gate's 404, which reads as the usual
-// membership message.
+// of app; anything else is the gate's 404. That 404 is the same bytes an
+// unknown account or app, a non-member and a console with no effective door
+// at all get, so the message names --host and an older console as well as
+// the membership riddle, as restart's 404 does.
func (s *apiSession) configEffective(ctx context.Context, a apiAcct, app, host string) (apiConfigEffective, error) {
status, body, err := s.getJSON(ctx, withQuery(apiPath(a, app, "/config/effective"), "host", host))
if err != nil {
return apiConfigEffective{}, err
}
+ if status == http.StatusNotFound && !hasJSONError(body) {
+ return apiConfigEffective{}, fmt.Errorf("%w. or %s is not one of this app's routes (check --host), or this console predates carlos env effective and needs updating", notFoundErr(), host)
+ }
if status != http.StatusOK {
return apiConfigEffective{}, apiErrorFromBody(status, body)
}
diff --git a/apimode_test.go b/apimode_test.go
index 9928b7088..1894a7cd6 100644
--- a/apimode_test.go
+++ b/apimode_test.go
@@ -4356,3 +4356,35 @@ func TestConfigEffectiveParses(t *testing.T) {
t.Fatal("shadows decoded nil; want [] so --json never prints null")
}
}
+
+// The effective door's 404 is the gate's byte-identical one, so the message
+// names the host and an older console as well as the membership riddle, as
+// restart's does; a JSON error body is still shown as sent.
+func TestConfigEffectiveNotFoundNamesHostAndOlderConsole(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Query().Get("host") == "json.example.com" {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusNotFound)
+ io.WriteString(w, `{"error":"a door's own words"}`)
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ defer ts.Close()
+ _, err := newTestSession(ts.URL).configEffective(context.Background(), apiAcct{Seg: "acct"}, "app", "shop.example.com")
+ if err == nil || !errors.Is(err, errMembershipNotFound) {
+ t.Fatalf("err = %v, want the membership 404", err)
+ }
+ for _, want := range []string{"shop.example.com", "--host", "predates carlos env effective"} {
+ if !strings.Contains(err.Error(), want) {
+ t.Errorf("err = %q, want it to mention %q", err, want)
+ }
+ }
+ if strings.ContainsAny(err.Error(), "—–") {
+ t.Errorf("err = %q carries a dash", err)
+ }
+ _, err = newTestSession(ts.URL).configEffective(context.Background(), apiAcct{Seg: "acct"}, "app", "json.example.com")
+ if err == nil || err.Error() != "a door's own words" {
+ t.Fatalf("err = %v, want the door's own message", err)
+ }
+}
diff --git a/appconfig_cli.go b/appconfig_cli.go
index 85baecd7f..909dbd46c 100644
--- a/appconfig_cli.go
+++ b/appconfig_cli.go
@@ -366,6 +366,32 @@ func ifVersionFlag(fs *flag.FlagSet) *string {
return fs.String("if-version", "", `write only if the bundle is at this version ("none": only if it does not exist yet). needs a console`)
}
+// checkIfVersionGiven refuses an --if-version that was passed but names no
+// version, as in --if-version "$V" with V unset. Read as absent it would turn
+// a conditional write into an unconditional one, which is the one thing the
+// flag exists to prevent. Called before anything is read or written.
+func checkIfVersionGiven(fs *flag.FlagSet, ifVersion *string) {
+ if err := ifVersionGiven(fs, ifVersion); err != nil {
+ log.Fatal(err)
+ }
+}
+
+// ifVersionGiven is checkIfVersionGiven without the exit, and trims the
+// version it keeps.
+func ifVersionGiven(fs *flag.FlagSet, ifVersion *string) error {
+ given := false
+ fs.Visit(func(f *flag.Flag) {
+ if f.Name == "if-version" {
+ given = true
+ }
+ })
+ *ifVersion = strings.TrimSpace(*ifVersion)
+ if given && *ifVersion == "" {
+ return errors.New(ifVersionCopyEmpty)
+ }
+ return nil
+}
+
// checkIfVersionDirect refuses --if-version in direct bucket mode. The
// guarantee rests on the store refusing a write whose etag moved, whoever
// wrote in between, and a directory store only checks that inside one
@@ -386,6 +412,8 @@ const (
receiptCopyVersion = "version %s, was %s"
receiptCopyUnchanged = "nothing changed. the bundle is still at version %s"
receiptCopyOtherMoved = "the default bundle changed while this was written. it is now at version %s, was %s"
+ receiptCopyOtherGone = "the default bundle could not be read either side of this write, so whether it changed meanwhile is not known"
+ ifVersionCopyEmpty = "--if-version is empty, so nothing was written. pass the version to write against, or leave the flag out"
effectiveCopyDirect = "carlos env effective works through a console only. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR and run carlos auth login"
)
@@ -413,8 +441,15 @@ func printReceipt(w io.Writer, rc *apiConfigReceipt) {
}
// The two layers share no transaction, so the console can only report
// that the default moved during the write; what that means is the
- // caller's call, and the line says no more than the receipt does.
- if p, ok := rc.Others["default"]; ok && p.Before != p.After {
+ // caller's call, and the line says no more than the receipt does. A
+ // pair the console could not complete says so: silence there would read
+ // as "the default did not move".
+ p, ok := rc.Others["default"]
+ switch {
+ case !ok:
+ case p.Unavailable:
+ fmt.Fprintf(w, "%s %s\n", c.warn("note:"), receiptCopyOtherGone)
+ case p.Before != p.After:
fmt.Fprintf(w, "%s %s\n", c.warn("note:"), fmt.Sprintf(receiptCopyOtherMoved, p.After, p.Before))
}
}
@@ -488,6 +523,7 @@ func runEnvSet(args []string) {
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
+ checkIfVersionGiven(fs, ifVersion)
usage := "usage: carlos env set --app <a> [--environment <name>] [--if-version <v>] [--console <origin>] KEY=value [KEY2=value2 ...]"
checkEnvironmentFlag(*environment)
kv, err := parseKV(fs.Args())
@@ -559,6 +595,7 @@ func runEnvUnset(args []string) {
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
+ checkIfVersionGiven(fs, ifVersion)
usage := "usage: carlos env unset --app <a> [--environment <name>] [--if-version <v>] [--console <origin>] KEY [KEY2 ...]"
if fs.NArg() == 0 {
log.Fatal(usage)
@@ -620,7 +657,13 @@ func runEnvList(args []string) {
fs.Parse(args)
usage := "usage: carlos env list --app <a> [--environment <name>] [--digests] [--json] [--console <origin>]"
checkEnvironmentFlag(*environment)
- l := loadListing(*app, *environment, acctRaw, acctIDRaw, acctOf, *consoleFlag, usage, "env", !*asJSON)
+ // --json is the whole bundle, secrets included as digests: one read a
+ // script can take its baseline from. The table stays plain vars only.
+ kind := "env"
+ if *asJSON {
+ kind = ""
+ }
+ l := loadListing(*app, *environment, acctRaw, acctIDRaw, acctOf, *consoleFlag, usage, kind, !*asJSON)
if *asJSON {
printListingJSON(os.Stdout, l)
return
@@ -650,9 +693,13 @@ type listedVar struct {
}
// loadListing fetches one bundle's vars of one kind, through the console
-// or straight from the bucket, sorted by key. printUsing is skipped for
-// --json, whose stdout must be one JSON document. exec_delivery belongs to
-// the env listing only, as it always has.
+// or straight from the bucket, sorted by key. kind "" keeps every var, of
+// every kind: that is `env list --json`, the one read a script can take a
+// whole bundle from, plain vars and secrets under one version (round 1,
+// P2-5), where two listings could describe two different bundles. A secret
+// row still carries no value and no envelope (listedVarOf). printUsing is
+// skipped for --json, whose stdout must be one JSON document. exec_delivery
+// belongs to the env listing only, as it always has.
func loadListing(app, environment string, acctRaw, acctIDRaw *string, acctOf func() string, consoleFlag, usage, kind string, announce bool) bundleListing {
sess, err := resolveMode(consoleFlag)
if err != nil {
@@ -671,7 +718,7 @@ func loadListing(app, environment string, acctRaw, acctIDRaw *string, acctOf fun
}
l = bundleListing{App: app2, Version: cfg.Version, ExecDelivery: cfg.ExecDelivery}
for _, v := range cfg.Vars {
- if v.Kind == kind {
+ if kind == "" || v.Kind == kind {
l.Vars = append(l.Vars, listedVarOf(v.Key, v.Kind, v.Value, v.Digest))
}
}
@@ -685,13 +732,13 @@ func loadListing(app, environment string, acctRaw, acctIDRaw *string, acctOf fun
}
l = bundleListing{App: app, Version: layer.Version, ExecDelivery: layer.Manifest.ExecDelivery}
for k, v := range layer.Manifest.Vars {
- if v.Kind == kind {
+ if kind == "" || v.Kind == kind {
l.Vars = append(l.Vars, listedVarOf(k, v.Kind, v.Value, appconfig.Digest(v)))
}
}
}
l.Bundle = bundleLabel(environment)
- if kind != "env" {
+ if kind == "secret" {
l.ExecDelivery = ""
}
if l.Vars == nil {
@@ -1131,6 +1178,7 @@ func runSecretsSet(args []string) {
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
+ checkIfVersionGiven(fs, ifVersion)
usage := "usage: carlos secrets set --app <a> [--environment <name>] [--if-version <v>] [--console <origin>] KEY=value [KEY2=value2 ...]"
checkEnvironmentFlag(*environment)
kv, err := parseKV(fs.Args())
@@ -1337,6 +1385,7 @@ func runSecretsUnset(args []string) {
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
+ checkIfVersionGiven(fs, ifVersion)
usage := "usage: carlos secrets unset --app <a> [--environment <name>] [--if-version <v>] [--console <origin>] KEY [KEY2 ...]"
if fs.NArg() == 0 {
log.Fatal(usage)
diff --git a/appconfig_cli_test.go b/appconfig_cli_test.go
index 64b8b50f9..4c59ed837 100644
--- a/appconfig_cli_test.go
+++ b/appconfig_cli_test.go
@@ -6,6 +6,7 @@ package main
import (
"context"
"encoding/json"
+ "flag"
"io"
"net/http"
"net/http/httptest"
@@ -89,6 +90,9 @@ func TestEnvListDigestsColumn(t *testing.T) {
}
}
+// env list --json is the whole bundle under one version: plain vars with
+// their values and secrets as digests alone, so one read is a baseline for
+// both kinds (round 1, P2-5).
func TestEnvListJSON(t *testing.T) {
listConsole(t, listBody, "")
out := runCapturingRealStdout(t, func() {
@@ -96,14 +100,25 @@ func TestEnvListJSON(t *testing.T) {
})
var got struct {
App, Bundle, Version string
- Vars []struct{ Key, Kind, Value, Digest string }
+ Vars []map[string]any
}
if err := json.Unmarshal([]byte(out), &got); err != nil {
t.Fatalf("stdout %q is not one JSON document: %v", out, err)
}
- if got.App != "titogo" || got.Bundle != "default" || got.Version != "cv1:aaaa" || len(got.Vars) != 1 ||
- got.Vars[0].Key != "LOG_LEVEL" || got.Vars[0].Value != "info" || got.Vars[0].Digest != "vd1:1111" {
- t.Fatalf("json = %+v", got)
+ if got.App != "titogo" || got.Bundle != "default" || got.Version != "cv1:aaaa" || len(got.Vars) != 2 {
+ t.Fatalf("json = %+v, want both vars under one version", got)
+ }
+ bank, logLevel := got.Vars[0], got.Vars[1]
+ if bank["key"] != "BANK_KEY" || bank["kind"] != "secret" || bank["digest"] != "vd1:2222" {
+ t.Fatalf("secret row = %v", bank)
+ }
+ for _, field := range []string{"value", "envelope"} {
+ if _, has := bank[field]; has {
+ t.Fatalf("the secret row carries %q: %v", field, bank)
+ }
+ }
+ if logLevel["key"] != "LOG_LEVEL" || logLevel["value"] != "info" || logLevel["digest"] != "vd1:1111" {
+ t.Fatalf("plain row = %v", logLevel)
}
out = runCapturingRealStdout(t, func() {
runSecretsList([]string{"-app", "titogo", "-account", apiTestAccount, "--json"})
@@ -150,6 +165,76 @@ func TestEnvListBucketModeVersion(t *testing.T) {
if !strings.Contains(out, "version none") {
t.Fatalf("absent environment: stdout = %q, want version none", out)
}
+
+ // --json in bucket mode is the whole bundle too, the secret as its
+ // digest alone.
+ secret := appconfig.Var{Kind: "secret", Envelope: "sealed-canary", SealedTo: "fp"}
+ if _, err := appconfig.ApplyIf(context.Background(), st, "bab", "titogo", "", "",
+ map[string]appconfig.Var{"BANK_KEY": secret}, nil); err != nil {
+ t.Fatal(err)
+ }
+ layer, err = appconfig.LoadLayer(context.Background(), st, appconfig.Key("bab", "titogo"), "titogo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ out = runCapturingRealStdout(t, func() {
+ runEnvList([]string{"-app", "titogo", "-account", "bab", "--json"})
+ })
+ if strings.Contains(out, "sealed-canary") {
+ t.Fatalf("env list --json carries the envelope: %s", out)
+ }
+ var got bundleListing
+ if err := json.Unmarshal([]byte(out), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Version != layer.Version || len(got.Vars) != 2 || got.Vars[0].Key != "BANK_KEY" ||
+ got.Vars[0].Digest != appconfig.Digest(secret) || got.Vars[0].Value != nil {
+ t.Fatalf("bucket-mode json = %+v, want both vars at %s", got, layer.Version)
+ }
+}
+
+// A pair the console could not complete prints one line saying so, and no
+// "changed" claim either way.
+func TestPrintReceiptOthersUnavailable(t *testing.T) {
+ var b strings.Builder
+ printReceipt(&b, &apiConfigReceipt{Bundle: "prod", VersionBefore: "cv1:a", VersionAfter: "cv1:b", Changed: true,
+ Set: []string{"S"}, Others: map[string]apiConfigVersionPair{"default": {Before: "cv1:d1", Unavailable: true}}})
+ out := b.String()
+ if !strings.Contains(out, receiptCopyOtherGone) || strings.Contains(out, "the default bundle changed") {
+ t.Fatalf("receipt = %q, want the unavailable line alone", out)
+ }
+ if strings.Count(out, "default bundle") != 1 {
+ t.Fatalf("receipt = %q, want one line about the default bundle", out)
+ }
+}
+
+// --if-version given but empty, as with an unset shell variable, is refused
+// rather than read as no precondition; absent, it is no precondition.
+func TestIfVersionGivenEmptyRefused(t *testing.T) {
+ for _, c := range []struct {
+ args []string
+ want string
+ err bool
+ }{
+ {nil, "", false},
+ {[]string{"--if-version", "cv1:aa"}, "cv1:aa", false},
+ {[]string{"--if-version", " none "}, "none", false},
+ {[]string{"--if-version", ""}, "", true},
+ {[]string{"--if-version= "}, "", true},
+ } {
+ fs := flag.NewFlagSet("t", flag.ContinueOnError)
+ v := ifVersionFlag(fs)
+ if err := fs.Parse(c.args); err != nil {
+ t.Fatal(err)
+ }
+ err := ifVersionGiven(fs, v)
+ if (err != nil) != c.err || *v != c.want {
+ t.Errorf("%q: err %v, version %q; want err %v, version %q", c.args, err, *v, c.err, c.want)
+ }
+ if err != nil && err.Error() != ifVersionCopyEmpty {
+ t.Errorf("%q: err %q", c.args, err)
+ }
+ }
}
func TestIfVersionRefusedInBucketMode(t *testing.T) {
diff --git a/internal/console/apiconfig.go b/internal/console/apiconfig.go
index ae8648449..76b4472c9 100644
--- a/internal/console/apiconfig.go
+++ b/internal/console/apiconfig.go
@@ -331,7 +331,8 @@ func (s *Server) handleAPIConfigGet(w http.ResponseWriter, r *http.Request) {
// 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
+// saying exactly what it did, and the version the whole request left the
+// bundle at (configReceiptReread). 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).
@@ -568,6 +569,10 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
bundle := configBundleName(envName)
removed := 0
var receipt *apiConfigReceipt
+ // rereadReceipt is set when the request writes the bundle again after
+ // the set/unset write: exec_delivery, or the credentials a team's new
+ // environment is minted.
+ rereadReceipt := req.ExecDelivery != nil
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
@@ -620,11 +625,15 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
var (
rc appconfig.Receipt
err error
+ created bool
defBefore string
defReadErr error
)
if team {
- rc, err = s.teamApplyEnvironment(ctx, tv, envName, ifVersion, sets, req.Unset)
+ rc, created, err = s.teamApplyEnvironment(ctx, tv, envName, ifVersion, sets, req.Unset)
+ if created {
+ rereadReceipt = true
+ }
if errors.Is(err, errTeamOutOfScope) {
http.NotFound(w, r)
return
@@ -651,14 +660,15 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
// 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.
+ // team sees nothing of the default. Either read failing costs the
+ // write nothing and is reported as such (round 1, P2-4): the pair is
+ // marked unavailable and keeps the read that worked, because a
+ // receipt with no pair would read as one where the default does not
+ // matter.
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},
- }
+ defAfter, defAfterErr := s.configDefaultVersion(ctx, acct.Sqid, app)
+ receipt.Others = map[string]apiConfigVersionPair{
+ appconfig.DefaultBundle: configVersionPair(defBefore, defReadErr, defAfter, defAfterErr),
}
}
unlockAcct()
@@ -698,6 +708,14 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
s.audit(acct, app, addr, "exec-delivery", "exec-delivery "+*req.ExecDelivery+" ("+bundle+") (cli)")
s.bumpSerial(ctx)
}
+ // The receipt describes the completed request (round 1, P2-3). When
+ // the request wrote the bundle again after its set/unset write, the
+ // version that write reported is already history, so the bundle is read
+ // once more and the receipt reports that version: the one a caller can
+ // pass as its next if_version.
+ if receipt != nil && rereadReceipt {
+ receipt = s.configReceiptReread(ctx, acct.Sqid, app, envName, tv, receipt)
+ }
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
@@ -947,38 +965,42 @@ var errTeamOutOfScope = errors.New("console: environment is out of the team's sc
// 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, ifVersion string, sets map[string]appconfig.Var, unsets []string) (appconfig.Receipt, error) {
+//
+// created reports that this write brought the bundle into being, and so
+// that the credentials minted into it after the write have moved its
+// version on.
+func (s *Server) teamApplyEnvironment(ctx context.Context, tv *teamView, envName, ifVersion string, sets map[string]appconfig.Var, unsets []string) (rc appconfig.Receipt, created bool, err 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 appconfig.Receipt{}, err
+ return appconfig.Receipt{}, false, err
}
if found {
if m.OwnerScope != tv.scope {
- return appconfig.Receipt{}, errTeamOutOfScope
+ return appconfig.Receipt{}, false, errTeamOutOfScope
}
} else {
recs, truncated, err := s.listRecords(ctx, tv.acct.Sqid, tv.app, instanceListMax)
if err != nil {
- return appconfig.Receipt{}, err
+ return appconfig.Receipt{}, false, 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 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)
+ return appconfig.Receipt{}, false, 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 appconfig.Receipt{}, errTeamOutOfScope
+ return appconfig.Receipt{}, false, errTeamOutOfScope
}
}
}
// 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)
+ 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 appconfig.Receipt{}, errTeamOutOfScope
+ return appconfig.Receipt{}, false, errTeamOutOfScope
}
if err == nil && !found {
// A bundle this scope just brought into being: the walks mint its
@@ -987,8 +1009,9 @@ func (s *Server) teamApplyEnvironment(ctx context.Context, tv *teamView, envName
// 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 rc, true, nil
}
- return rc, err
+ return rc, false, err
}
// configIfVersion is the PUT's precondition, from the body's if_version or
@@ -1071,7 +1094,8 @@ func configSetAndUnset(keys, unsets []string) string {
}
// configDefaultVersion is the default bundle's version, for a receipt's
-// others. A failure is logged and handed back; the caller drops the pair.
+// others. A failure is logged and handed back; the caller marks the pair
+// unavailable.
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 {
@@ -1081,6 +1105,42 @@ func (s *Server) configDefaultVersion(ctx context.Context, acct, app string) (st
return l.Version, nil
}
+// configVersionPair is a receipt's pair for another layer, from the two
+// reads either side of the write. A read that failed leaves its half out
+// and marks the pair unavailable, so "could not compare" never reads as
+// "compared, and nothing moved".
+func configVersionPair(before string, beforeErr error, after string, afterErr error) apiConfigVersionPair {
+ var p apiConfigVersionPair
+ if beforeErr == nil {
+ p.Before = before
+ }
+ if afterErr == nil {
+ p.After = after
+ }
+ p.Unavailable = beforeErr != nil || afterErr != nil
+ return p
+}
+
+// configReceiptReread is rc with its version_after and changed taken from a
+// fresh read of the bundle, for a request that wrote it again after the
+// set/unset write. It answers nil, and the request answers with no receipt
+// (as an older console's does), when that read fails, or when, for a team,
+// the bundle read is no longer its scope's: a version the request cannot
+// vouch for, or one that is another scope's, is not reported.
+func (s *Server) configReceiptReread(ctx context.Context, acct, app, envName string, tv *teamView, rc *apiConfigReceipt) *apiConfigReceipt {
+ l, err := appconfig.LoadLayer(ctx, s.cfg.Releases, appconfig.BundleKey(acct, app, envName), app)
+ if err != nil {
+ log.Printf("console: api config apply %s/%s (%s): receipt version: %v", acct, app, configBundleName(envName), err)
+ return nil
+ }
+ if tv != nil && (!l.Found || l.Manifest.OwnerScope != tv.scope) {
+ return nil
+ }
+ rc.VersionAfter = l.Version
+ rc.Changed = rc.VersionBefore != l.Version
+ return rc
+}
+
// 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
@@ -1123,9 +1183,13 @@ type apiConfigReceipt struct {
Others map[string]apiConfigVersionPair `json:"others,omitempty"`
}
+// apiConfigVersionPair is another layer's version either side of a write.
+// Unavailable marks a pair where a read failed: the half that was read is
+// kept and the other left out.
type apiConfigVersionPair struct {
- Before string `json:"before"`
- After string `json:"after"`
+ Before string `json:"before,omitempty"`
+ After string `json:"after,omitempty"`
+ Unavailable bool `json:"unavailable,omitempty"`
}
// configReceiptWire copies a Receipt onto the wire field by field, so a
diff --git a/internal/console/apiconfig_witness_test.go b/internal/console/apiconfig_witness_test.go
index 6f150ee80..72efe4498 100644
--- a/internal/console/apiconfig_witness_test.go
+++ b/internal/console/apiconfig_witness_test.go
@@ -1,23 +1,83 @@
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.
+// a supplied precondition never vanishes, a team is authorised on the
+// snapshot it is shown, a receipt describes the completed request, a
+// default bundle that could not be compared says so, and the door's
+// refusals, ownership checks, account isolation and secret handling hold
+// end to end.
import (
"bytes"
"context"
"encoding/json"
+ "errors"
"io"
"net/http"
"strings"
+ "sync"
"sync/atomic"
"testing"
+ "time"
"github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/mail"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
+// keyHookStore counts the Gets of one key and, when at is reached, runs
+// hook just before that Get, or fails it when fail is set. It claims an
+// atomic conditional Put, as atomicDirStore does, so a conditional write is
+// accepted.
+type keyHookStore struct {
+ release.Store
+ key string
+
+ mu sync.Mutex
+ gets int
+ at map[int]bool
+ fail bool
+ hook func(ctx context.Context)
+}
+
+func (k *keyHookStore) AtomicConditionalPut() {}
+
+func (k *keyHookStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == k.key {
+ k.mu.Lock()
+ k.gets++
+ hit := k.at[k.gets]
+ hook, fail := k.hook, k.fail
+ k.mu.Unlock()
+ if hit {
+ if fail {
+ return nil, "", errors.New("test: injected read failure")
+ }
+ if hook != nil {
+ hook(ctx)
+ }
+ }
+ }
+ return k.Store.Get(ctx, key)
+}
+
+func (k *keyHookStore) reset(at ...int) {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+ k.gets = 0
+ k.at = map[int]bool{}
+ for _, n := range at {
+ k.at[n] = true
+ }
+}
+
+func (k *keyHookStore) count() int {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+ return k.gets
+}
+
// 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()
@@ -155,3 +215,291 @@ func TestAPIConfigTeamGetOwnershipRace(t *testing.T) {
})
}
}
+
+// TestAPIConfigPutReceiptCoversExecDelivery: an unconditional request that
+// sets vars and exec_delivery reports the version the whole request left,
+// and a var set that changed nothing still reads as changed when
+// exec_delivery moved the bundle.
+func TestAPIConfigPutReceiptCoversExecDelivery(t *testing.T) {
+ fx, token := configFixture(t, "code-config-receipt-exec")
+ seedDefault(t, fx, token, envSet("A", "1"))
+ useCfgCountStore(fx, true)
+ key := appconfig.Key(release.OpsAccount, "titogo")
+ before := storedVersion(t, fx, key)
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "set": envSet("A", "1"), "exec_delivery": "file",
+ }, token)
+ if status != http.StatusOK {
+ t.Fatalf("PUT = %d %v", status, out)
+ }
+ r := receiptOf(t, out)
+ 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 || got == before {
+ t.Errorf("version_after = %q, want the stored %q after both writes", got, want)
+ }
+ if r["changed"] != true {
+ t.Errorf("changed = %v, want true: exec_delivery moved the bundle", r["changed"])
+ }
+ // The version is the one to reuse: a conditional write at it lands.
+ if status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "if_version": str(t, r, "version_after"), "set": envSet("B", "2"),
+ }, token); status != http.StatusOK {
+ t.Fatalf("a write at the receipt's version = %d %v", status, out)
+ }
+}
+
+// TestAPIConfigTeamCreateReceiptCoversMinting: a team write that creates
+// its environment mints the environment's platform credentials into it in
+// further writes. The receipt reports the version after those, so the
+// version it gives is the one a following conditional write can use, as
+// the "none" refusal advises.
+func TestAPIConfigTeamCreateReceiptCoversMinting(t *testing.T) {
+ w := newPlatformWorld(t, "code-team-create-receipt")
+ useCfgCountStore(w.fx, true)
+ team := teamToken(t, w.fx.st, OpsAccountID, "alta-titogo", "titogo", "alta")
+ key := appconfig.EnvironmentKey(release.OpsAccount, "titogo", "fresh")
+
+ status, out := putJSON(t, w.fx.ts.URL+"/api/cli/apps/bab/titogo/config", map[string]any{
+ "environment": "fresh", "set": envSet("K", "v"),
+ }, team)
+ if status != http.StatusOK {
+ t.Fatalf("team create = %d %v", status, out)
+ }
+ if _, ok := w.vars(t, "fresh")["TITO_SMTP_USER"]; !ok {
+ t.Fatal("the created environment got no mail credential: the witness needs minting on")
+ }
+ r := receiptOf(t, out)
+ if str(t, r, "version_before") != appconfig.VersionNone {
+ t.Errorf("version_before = %v, want none", r["version_before"])
+ }
+ if got, want := str(t, r, "version_after"), storedVersion(t, w.fx, key); got != want {
+ t.Fatalf("version_after = %q, want the stored %q after minting", got, want)
+ }
+ if r["changed"] != true {
+ t.Errorf("changed = %v", r["changed"])
+ }
+ if status, out := putJSON(t, w.fx.ts.URL+"/api/cli/apps/bab/titogo/config", map[string]any{
+ "environment": "fresh", "if_version": str(t, r, "version_after"), "set": envSet("K2", "v"),
+ }, team); status != http.StatusOK {
+ t.Fatalf("a write at the creation receipt's version = %d %v", status, out)
+ }
+}
+
+// TestAPIConfigPutOthersUnavailable: when either read of the default
+// bundle fails, the write still lands and the receipt says the comparison
+// was unavailable, keeping the read that worked.
+func TestAPIConfigPutOthersUnavailable(t *testing.T) {
+ for _, c := range []struct {
+ what string
+ failGet int
+ wantBefore bool
+ }{{"before", 1, false}, {"after", 2, true}} {
+ t.Run(c.what, func(t *testing.T) {
+ fx, token := configFixture(t, "code-config-others-unavailable-"+c.what)
+ seedDefault(t, fx, token, envSet("BASE", "1"))
+ defKey := appconfig.Key(release.OpsAccount, "titogo")
+ def := storedVersion(t, fx, defKey)
+ ks := &keyHookStore{Store: fx.rel, key: defKey, fail: true}
+ ks.reset(c.failGet)
+ fx.srv.cfg.Releases = ks
+
+ status, out := putJSON(t, configURL(fx, "titogo"), map[string]any{
+ "environment": "staging", "set": envSet("S", "1"),
+ }, token)
+ if status != http.StatusOK {
+ t.Fatalf("PUT = %d %v, want the write to stand", status, out)
+ }
+ if ks.count() < 2 {
+ t.Fatalf("the door read the default %d times, want 2", ks.count())
+ }
+ envKey := appconfig.EnvironmentKey(release.OpsAccount, "titogo", "staging")
+ r := receiptOf(t, out)
+ if str(t, r, "version_after") != storedVersion(t, fx, envKey) {
+ t.Errorf("receipt = %v", r)
+ }
+ others, _ := r["others"].(map[string]any)
+ pair, _ := others["default"].(map[string]any)
+ if pair == nil || pair["unavailable"] != true {
+ t.Fatalf("others = %v, want default marked unavailable", r["others"])
+ }
+ if c.wantBefore {
+ if pair["before"] != def {
+ t.Errorf("before = %v, want %q", pair["before"], def)
+ }
+ if _, ok := pair["after"]; ok {
+ t.Errorf("after = %v from a failed read", pair["after"])
+ }
+ } else {
+ if pair["after"] != def {
+ t.Errorf("after = %v, want %q", pair["after"], def)
+ }
+ if _, ok := pair["before"]; ok {
+ t.Errorf("before = %v from a failed read", pair["before"])
+ }
+ }
+ })
+ }
+}
+
+// TestAPIConfigTeamStaleCreateNoMint: a team's conditional write to an
+// absent environment it could create, at any version but "none", is a 412
+// naming "none". Nothing is written and nothing is minted, with minting on.
+func TestAPIConfigTeamStaleCreateNoMint(t *testing.T) {
+ w := newPlatformWorld(t, "code-team-stale-create")
+ useCfgCountStore(w.fx, true)
+ team := teamToken(t, w.fx.st, OpsAccountID, "alta-titogo", "titogo", "alta")
+ ctx := context.Background()
+ gen := genEtag(t, w.fx, "titogo")
+ events := configEventCount(t, w.fx)
+
+ status, out := putJSON(t, w.fx.ts.URL+"/api/cli/apps/bab/titogo/config", map[string]any{
+ "environment": "fresh", "if_version": "cv1:" + strings.Repeat("0", 64), "set": envSet("K", "v"),
+ }, team)
+ if status != http.StatusPreconditionFailed || str(t, out, "version") != appconfig.VersionNone {
+ t.Fatalf("stale team create = %d %v, want 412 naming none", status, out)
+ }
+ if _, _, found, err := appconfig.GetEnvironment(ctx, w.fx.rel, "bab", "titogo", "fresh"); err != nil || found {
+ t.Fatalf("the refused create landed (found %v, %v)", found, err)
+ }
+ mrec, _, err := mail.Get(ctx, w.fx.rel, "bab", "titogo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if mrec.Environments["fresh"] != nil {
+ t.Fatalf("a mail credential was minted for a refused create: %+v", mrec.Environments)
+ }
+ if rr := relayRecord(t, w.fx, "titogo"); rr.Environments["fresh"] != nil {
+ t.Fatalf("a relay identity was minted for a refused create: %+v", rr.Environments)
+ }
+ if genEtag(t, w.fx, "titogo") != gen || configEventCount(t, w.fx) != events {
+ t.Fatal("the refused create bumped the generation or left an audit row")
+ }
+}
+
+// TestAPIConfigTeam412OwnershipRace: the bundle changing hands between a
+// team's refused write and the read that names the current version is the
+// canonical 404, not a 412 carrying another scope's version.
+func TestAPIConfigTeam412OwnershipRace(t *testing.T) {
+ w := newTeamWorld(t, "code-team-412-race")
+ ctx := context.Background()
+ key := appconfig.EnvironmentKey(release.OpsAccount, "titogo", "team")
+ ks := &keyHookStore{Store: w.fx.rel, key: key}
+ w.fx.srv.cfg.Releases = ks
+ stale := putBody(t, map[string]any{"environment": "team", "if_version": "cv1:" + strings.Repeat("0", 64), "set": envSet("K", "v")})
+
+ // The yardstick: the same stale write, untouched, is a 412, and its
+ // last read of the bundle is the one that names the version.
+ ks.reset()
+ status, _, out := rawReq(t, http.MethodPut, w.url("/config"), w.team, stale)
+ if status != http.StatusPreconditionFailed {
+ t.Fatalf("yardstick = %d %s, want 412", status, out)
+ }
+ last := ks.count()
+
+ ks.reset(last)
+ ks.hook = func(ctx context.Context) {
+ if err := appconfig.SetEnvironmentOwner(ctx, w.fx.rel, "bab", "titogo", "team", "", nil); err != nil {
+ t.Error(err)
+ }
+ if err := appconfig.SetEnvironmentOwner(ctx, w.fx.rel, "bab", "titogo", "team", "beta", nil); err != nil {
+ t.Error(err)
+ }
+ }
+ status, hdr, out := rawReq(t, http.MethodPut, w.url("/config"), w.team, stale)
+ assertNotFound(t, "412 re-read after the bundle changed hands", canonicalNotFound(t), status, hdr, out)
+ if m, _, _, _ := appconfig.GetEnvironment(ctx, w.fx.rel, "bab", "titogo", "team"); m.OwnerScope != "beta" || m.Vars["K"].Kind != "" {
+ t.Fatalf("after the race: owner %q, K %+v", m.OwnerScope, m.Vars["K"])
+ }
+ if strings.Contains(out, storedVersion(t, w.fx, key)) {
+ t.Fatalf("the 404 names the new owner's version: %s", out)
+ }
+}
+
+// TestAPIConfigSecondAccountSameNames: a real second account holding an app
+// and a host of the same names is the canonical 404 on every config door,
+// for a member of the first, and its bytes do not move.
+func TestAPIConfigSecondAccountSameNames(t *testing.T) {
+ fx, token := effectiveWorld(t, "code-config-second-account")
+ ctx := context.Background()
+ now := time.Now()
+ if err := fx.st.CreateAccount(2, "bac", "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(2, "titogo", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := appconfig.SetEnv(ctx, fx.rel, "bac", "titogo", map[string]string{"THEIRS": "bac-canary"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := appconfig.SaveEnvironment(ctx, fx.rel, "bac", "titogo", "prod",
+ map[string]appconfig.Var{"THEIRS_ENV": {Kind: "env", Value: "bac-env-canary"}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ rec := provision.Record{Schema: 1, Host: effectiveHost, Slug: "a", App: "titogo", Account: "bac",
+ Pool: "tito", Region: "ie", Channel: "stable", Environment: "prod",
+ CreatedAt: now.UTC(), CreatedBy: "bob@keymail.dev"}
+ if err := provision.CreateRecord(ctx, fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ defKey, envKey := appconfig.Key("bac", "titogo"), appconfig.EnvironmentKey("bac", "titogo", "prod")
+ defBytes, envBytes := rawAtKey(t, fx, defKey), rawAtKey(t, fx, envKey)
+ defVersion := appconfig.Version(defBytes, true)
+
+ base := fx.ts.URL + "/api/cli/apps/bac/titogo"
+ want := canonicalNotFound(t)
+ for _, c := range []struct{ what, method, u, body string }{
+ {"GET default", http.MethodGet, base + "/config", ""},
+ {"GET environment", http.MethodGet, base + "/config?environment=prod", ""},
+ {"effective", http.MethodGet, base + "/config/effective?host=" + effectiveHost, ""},
+ {"PUT", http.MethodPut, base + "/config", putBody(t, map[string]any{"set": envSet("MINE", "1")})},
+ {"conditional PUT", http.MethodPut, base + "/config", putBody(t, map[string]any{"if_version": defVersion, "set": envSet("MINE", "1")})},
+ } {
+ status, h, body := rawReq(t, c.method, c.u, token, c.body)
+ assertNotFound(t, c.what, want, status, h, body)
+ for _, leak := range []string{"bac-canary", "bac-env-canary", defVersion} {
+ if strings.Contains(body, leak) {
+ t.Errorf("%s carries %q", c.what, leak)
+ }
+ }
+ }
+ if !bytes.Equal(rawAtKey(t, fx, defKey), defBytes) || !bytes.Equal(rawAtKey(t, fx, envKey), envBytes) {
+ t.Fatal("the second account's config moved")
+ }
+}
+
+// TestAPIConfigEffectiveOverlaySecret: a secret the platform's overlay
+// supplies shows in the effective view as its digest alone, with no value
+// and no envelope.
+func TestAPIConfigEffectiveOverlaySecret(t *testing.T) {
+ fx, token := effectiveWorld(t, "code-config-effective-overlay-secret")
+ _, _, envelope := sealedFor(t, "overlay-secret-canary")
+ if _, _, err := appconfig.ApplyInstance(context.Background(), fx.rel, release.OpsAccount, "titogo", effectiveHost,
+ map[string]appconfig.Var{"OS": {Kind: "secret", Envelope: envelope}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ raw := rawAtKey(t, fx, appconfig.InstanceConfigKey(release.OpsAccount, "titogo", effectiveHost))
+ var overlay appconfig.Manifest
+ if err := json.Unmarshal(raw, &overlay); err != nil {
+ t.Fatal(err)
+ }
+ status, body := getRaw(t, effectiveURL(fx, "titogo", effectiveHost), token)
+ if status != http.StatusOK {
+ t.Fatalf("effective = %d %s", status, body)
+ }
+ if strings.Contains(body, envelope) || strings.Contains(body, "overlay-secret-canary") {
+ t.Fatalf("the effective view carries the overlay secret: %s", body)
+ }
+ _, out := getJSON(t, effectiveURL(fx, "titogo", effectiveHost), token)
+ row := varsByKey(t, out)["OS"]
+ if str(t, row, "from") != appconfig.FromOverlay || str(t, row, "kind") != "secret" || str(t, row, "digest") != appconfig.Digest(overlay.Vars["OS"]) {
+ t.Fatalf("OS = %v", row)
+ }
+ for _, field := range []string{"value", "envelope", "sealed_to"} {
+ if _, ok := row[field]; ok {
+ t.Errorf("overlay secret row carries %q: %v", field, row)
+ }
+ }
+}