carlos / platform Public

console: one config write check for every door

The config PUT door's validation and write path move into
configwrite.go: checkConfigEnvironment, checkConfigSets and writeConfig
return configRefusal values (closed code, the JSON door's exact status
and text) instead of writing responses, so a later form door shares the
same rules. handleAPIConfigPut keeps its team path, audit and serial
bump, and renders refusals byte-identically. The appconfig writer pin
now lists configwrite.go and watches ApplyAtVersion too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e5c8cdab806ecc9ed17e07114437c673f36f8621 parent 5e5d3b5
4 files changed, +635 −211
  • internal/console/apiconfig.go +41 −210
  • internal/console/configwrite.go +346 −0
  • internal/console/configwrite_test.go +246 −0
  • internal/console/teamcreds_test.go +2 −1

Intent

Human

<task-notification> <task-id>ae73859cee8eb4b00</task-id> <tool-use-id>toolu_01Dw8PjFKSMQo2btARZUX2eh</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/abe35d56-e4c2-40df-9005-6e66b76b1f50/tasks/ae73859cee8eb4b00.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3 classifier" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>All three of Astra's P2 fixes are in, committed as 5e5d3b55 (internal/appconfig files only): - **P2-1:** a route on an owned environment is Unresolved when the default bundle won't read, since both passes need it. Pending() is unchanged for stamped routes. - **P2-2:** the classifier and SyncExec now share the `&lt;host&gt;.config` collision check, and colliding exec routes are Unresolved. A real-pass test on the existing fixture confirms no bounce and no delivery report. - **P2-3:** Pending() is computed from the old notice's own rules, so sidecar rows carrying Addr/Addrs project as before. It is checked against the old AwaitingRestart over 2000 generated cases, plus Addr/Addrs regressions. `go test ./internal/appconfig -run 'Classify|AwaitingRestart|BlockedStamps|SyncExec' -count=1` passes, and the tests caught all 4 deliberate breaks. Fix note is appended to task-3-report.md.</result> <usage><subagent_tokens>181563</subagent_tokens><tool_uses>19</tool_uses><duration_ms>555689</duration_ms></usage> </task-notification>

diff --git a/internal/console/apiconfig.go b/internal/console/apiconfig.go
index db12b0916..41f5b10cd 100644
--- a/internal/console/apiconfig.go
+++ b/internal/console/apiconfig.go
@@ -36,7 +36,6 @@ import (
"time"
"github.com/carlosframework/platform/internal/appconfig"
- "github.com/carlosframework/platform/internal/release"
)
// configStoreTimeout bounds every store round trip these handlers make — the
@@ -88,31 +87,12 @@ func configBundleName(envName string) string {
// validAPIEnvironment refuses a bad environment name — from the GET door's
// query parameter or the PUT door's body — before it can reach the store,
-// answering 400 itself and reporting whether the caller may proceed.
-//
-// "" is not a refusal: it is how both doors say "the default bundle". But
-// "default" IS refused, and with its own sentence, because it already NAMES
-// that bundle (config.json) — accepting it would either error confusingly
-// deep in appconfig or, worse, read and write a second bundle that merely
-// looks like the default one. Same rule the CLI enforces client-side
-// (checkEnvironmentFlag, appconfig_cli.go); enforced here too, because a
-// door must not depend on its client's manners.
-//
-// The name is NOT echoed back. There is exactly one of them per request, so
-// naming it buys a caller nothing they don't already know, and the shape
-// rule is the actionable half.
+// answering 400 itself and reporting whether the caller may proceed. The
+// rules are checkConfigEnvironment's (configwrite.go), shared with every
+// door that writes config.
func validAPIEnvironment(w http.ResponseWriter, name string) bool {
- if name == "" {
- return true
- }
- if name == appconfig.DefaultBundle {
- jsonError(w, http.StatusBadRequest,
- `"default" already names the base bundle (config.json) that every route gets when no `+
- `environment is bound — omit the environment to work on it directly, don't name it`)
- return false
- }
- if !appconfig.ValidEnvironmentName(name) {
- jsonError(w, http.StatusBadRequest, "invalid environment name — want [a-z0-9-]{1,32}")
+ if ref := checkConfigEnvironment(name); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
return false
}
return true
@@ -140,28 +120,11 @@ func configNothingToRemove(err error) bool {
return strings.Contains(msg, "nothing to unset") || strings.Contains(msg, "nothing to turn off")
}
-// configStoreError answers a config write that failed, mapping the three
-// outcomes a caller can act on differently and describing none of them in
-// bucket terms — the store's own error text (bucket names, key paths, AWS
-// request ids) goes to the log, where the operator who can act on it will
-// see it, and never to the client.
+// configStoreError answers a config write that failed: configStoreRefusal's
+// mapping (configwrite.go), written as a JSON error.
func (s *Server) configStoreError(w http.ResponseWriter, what string, err error) {
- log.Printf("console: %s: %v", what, err)
- if errors.Is(err, release.ErrCASConflict) {
- // Someone else wrote this bundle between our read and our write.
- // Retry-worthy, and the operator has to re-read first — appconfig
- // deliberately has no automatic retry (see apply's doc comment).
- jsonError(w, http.StatusConflict, "config changed concurrently — try again")
- return
- }
- if configNothingToRemove(err) {
- // appconfig's own sentence, verbatim: it names the app and the
- // bundle, which is exactly what the operator needs and carries
- // nothing they didn't send.
- jsonError(w, http.StatusConflict, err.Error())
- return
- }
- jsonError(w, http.StatusBadGateway, "could not store the config — try again")
+ ref := configStoreRefusal(what, err)
+ jsonError(w, ref.Status, ref.Msg)
}
// handleAPIConfigGet answers `carlos env list` / `carlos secrets list` /
@@ -391,63 +354,17 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
return
}
}
- // Sorted, so a request with several defects always refuses on the same
- // one — a map's own iteration order would make the error a caller sees
- // depend on nothing they can reason about.
- keys := make([]string, 0, len(req.Set))
- for k := range req.Set {
- keys = append(keys, k)
+ // The var rules are checkConfigSets' (configwrite.go), shared with
+ // every door that writes config: sorted names, each name before its
+ // kind, nothing written on a refusal.
+ in := make(map[string]configVarIn, len(req.Set))
+ for k, v := range req.Set {
+ in[k] = configVarIn{Kind: v.Kind, Value: v.Value, Envelope: v.Envelope, SealedTo: v.SealedTo}
}
- sort.Strings(keys)
- sets := make(map[string]appconfig.Var, len(req.Set))
- for _, k := range keys {
- v := req.Set[k]
- if !appconfig.ValidVarName(k) {
- jsonError(w, http.StatusBadRequest,
- fmt.Sprintf("invalid var name %q — want a letter or underscore, then letters, digits or underscores", k))
- return
- }
- switch v.Kind {
- case "env":
- // The same check applyAt makes, made earlier: here the operator
- // can still see the plaintext and fix it.
- if err := appconfig.ValidVarValue(v.Value); err != nil {
- jsonError(w, http.StatusBadRequest, fmt.Sprintf("var %s: %v", k, err))
- return
- }
- if v.Envelope != "" {
- jsonError(w, http.StatusBadRequest,
- fmt.Sprintf(`var %s is kind "env" but carries an envelope — send it as kind "secret", or drop the envelope`, k))
- return
- }
- // Built field by field, never copied wholesale from the wire
- // shape: an "env" var cannot smuggle an envelope into the bucket
- // even if the check above were ever loosened.
- sets[k] = appconfig.Var{Kind: "env", Value: v.Value}
- case "secret":
- if err := appconfig.CheckEnvelope(v.Envelope); err != nil {
- // CheckEnvelope's errors name the defect and never echo the
- // envelope — deliberately, because they end up here.
- jsonError(w, http.StatusBadRequest, fmt.Sprintf("var %s: %v", k, err))
- return
- }
- if v.Value != "" {
- // Refused, not silently dropped: a caller who sent plaintext
- // to a door that stores ciphertext has to LEARN that their
- // secret crossed the wire in the clear, so they can rotate
- // it. The refusal never echoes the value it is refusing.
- jsonError(w, http.StatusBadRequest,
- fmt.Sprintf(`var %s is kind "secret" but carries a plaintext value — seal it client-side and send only the envelope`, k))
- return
- }
- // SealedTo is checked against the app's key below, under the
- // account lock, before anything is written.
- sets[k] = appconfig.Var{Kind: "secret", Envelope: v.Envelope, SealedTo: v.SealedTo}
- default:
- jsonError(w, http.StatusBadRequest,
- fmt.Sprintf(`var %s: invalid kind %q — want "env" or "secret"`, k, v.Kind))
- return
- }
+ keys, sets, ref := checkConfigSets(in)
+ if ref != nil {
+ ref.writeJSONDoor(w, r)
+ return
}
// Unset keys are deliberately NOT name-checked: a name that could never
// be SET can never be present to remove, so refusing one would only turn
@@ -501,32 +418,17 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
bundle := configBundleName(envName)
removed := 0
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
- // replacement cannot land between them: the key door takes the same
- // lock and then sees this value. Taken here, at the door, before any
- // app lock (teamApplyEnvironment's comes after: account, then app).
- // Nothing below takes the account lock again: planLock is only on the
- // create doors. A team write into an environment holds it too, sealed
- // value or not: one that brings the environment into being mints its
- // platform credentials (mintOwnedEnvironment) under it, sealed to the
- // key chosen there (Task 6). Any other plain env write takes no lock.
- unlockAcct := func() {}
- if configSetsSecret(sets) || (team && envName != "") {
- unlock := s.lockAccount(acct.Sqid)
- held := true
- unlockAcct = func() {
- if held {
- held = false
- unlock()
- }
- }
- defer unlockAcct()
- }
- if configSetsSecret(sets) {
- if !s.configCheckSealedTo(w, r, ctx, acct, app, keys, sets) {
- return
- }
+ // The account lock and the seal check under it are configWriteBegin's
+ // (configwrite.go), the same first half writeConfig runs. A team write
+ // into an environment holds the lock sealed value or not (lockAlways):
+ // one that brings the environment into being mints its platform
+ // credentials (mintOwnedEnvironment) under it, sealed to the key chosen
+ // there (Task 6). Any other plain env write takes no lock.
+ unlockAcct, ref := s.configWriteBegin(ctx, acct, app, keys, sets, team && envName != "")
+ defer unlockAcct()
+ if ref != nil {
+ ref.writeJSONDoor(w, r)
+ return
}
if team {
managed, err := s.platformManagedKeys(ctx, acct.Sqid, app, envName)
@@ -546,27 +448,20 @@ func (s *Server) handleAPIConfigPut(w http.ResponseWriter, r *http.Request) {
// unset-only refusal (applyAt), and asking to set a flag is not asking
// to remove anything.
if len(sets) > 0 || len(req.Unset) > 0 {
- if configPutBeforeApply != nil {
- configPutBeforeApply()
+ // configWriteStore runs the test hook, the write, the unlock and
+ // the store error's mapping: writeConfig's second half. The team
+ // path is this door's alone.
+ if team {
+ removed, ref = s.configWriteStore(ctx, unlockAcct, acct, app, envName, func(ctx context.Context) (int, error) {
+ return s.teamApplyEnvironment(ctx, tv, envName, sets, req.Unset)
+ })
+ } else {
+ removed, ref = s.configWriteBundle(ctx, unlockAcct, acct, app, envName, nil, sets, req.Unset)
}
- 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)
- 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)
- }
- if err != nil {
- s.configStoreError(w, fmt.Sprintf("api config apply %s/%s (%s)", acct.Sqid, app, bundle), err)
+ if ref != nil {
+ ref.writeJSONDoor(w, r)
return
}
- 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
// store in a database with different reach. The unset count is what
@@ -630,70 +525,6 @@ func configSetsSecret(sets map[string]appconfig.Var) bool {
return false
}
-// configCheckSealedTo checks each sealed var of a PUT against the key the
-// app's boxes hold (fleet secrets key spec §5.3), answering the refusal
-// itself and reporting whether the PUT may go on. keys is the sorted var
-// names, so a request with several defects always refuses on the same one.
-// The caller holds the account lock.
-//
-// For an app on a fleet, each value must say it is sealed to the fleet's key
-// (an older CLI says nothing and is told to upgrade) and be v2. For an app
-// placed nowhere, an absent sealed_to is today's behaviour and accepted; a
-// present one must be the deployment key. A console without a usable
-// deployment key has nothing to compare, and accepts as it always has.
-//
-// It reads chooseSealKey, not sealKeyFor: the PUT never seals, and it needs
-// the fleet's name for its refusals. sealKeyFor is chooseSealKey plus the
-// sealer, so the key checked here is the key the GET served.
-func (s *Server) configCheckSealedTo(w http.ResponseWriter, r *http.Request, ctx context.Context, acct *Account, app string, keys []string, sets map[string]appconfig.Var) bool {
- c, err := s.chooseSealKey(ctx, acct.Sqid, app)
- var keyless errFleetNoSecretsKey
- var unknown errUnknownApp
- switch {
- case err == nil:
- case errors.As(err, &keyless):
- jsonError(w, http.StatusConflict, keyless.Error())
- return false
- case errors.Is(err, errNoDeploymentKey), errors.Is(err, errDeploymentKeyUnreadable):
- return true
- case errors.As(err, &unknown):
- // The gate saw the app a moment ago; it went since. The gate's own
- // answer.
- http.NotFound(w, r)
- return false
- default:
- log.Printf("console: api config apply %s/%s: seal key: %v", acct.Sqid, app, err)
- jsonError(w, http.StatusBadGateway, "could not read the config — try again")
- return false
- }
- fp := appconfig.KeyFingerprint(c.pub)
- for _, k := range keys {
- v, ok := sets[k]
- if !ok || v.Kind != "secret" {
- continue
- }
- if c.fleet == "" {
- if v.SealedTo != "" && v.SealedTo != fp {
- jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s was sealed to a key that this app's boxes do not hold. unset CARLOS_SECRETS_PUBKEY in your terminal and set %s again", k, k))
- return false
- }
- continue
- }
- switch {
- case v.SealedTo == "":
- jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s cannot be checked, because the carlos CLI that sealed it did not say which key it used, and %s is placed on %s. upgrade the carlos CLI and set %s again", k, app, c.fleet, k))
- return false
- case v.SealedTo != fp:
- jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s was sealed to a key that %s's boxes do not hold. unset CARLOS_SECRETS_PUBKEY in your terminal and set %s again", k, c.fleet, k))
- return false
- case !appconfig.EnvelopeBound(v.Envelope):
- jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s was sealed in an older format that %s's boxes do not accept. upgrade the carlos CLI and set %s again", k, c.fleet, k))
- return false
- }
- }
- return true
-}
-
// apiConfigRestart is the config door's answer to "did that reach
// anything?" — the wire half of appconfig.AwaitingRestart.
//
diff --git a/internal/console/configwrite.go b/internal/console/configwrite.go
new file mode 100644
index 000000000..e2dedb887
--- /dev/null
+++ b/internal/console/configwrite.go
@@ -0,0 +1,346 @@
+// One config write check for every door (console secrets, Task 4). The
+// JSON door (handleAPIConfigPut, the CLI's) and the console's own settings
+// form both write an app's config bundle; if each carried its own copy of
+// the rules, the two would drift, and the door that drifted looser would
+// be the one an attacker used. So the rules live here, once, and each
+// door only renders what they decide.
+//
+// A refusal is a value, not a written response: configRefusal carries the
+// JSON door's exact status and sentence (byte-identical to what that door
+// has always answered) and a closed code another door can render in its
+// own words. Every refusal still comes back before the first store call;
+// the only store-shaped refusals (conflict, nothing-to-remove, store) are
+// the write's own outcome.
+//
+// NOTHING IN A REFUSAL OR A LOG LINE CARRIES CONTENT. Var names appear
+// (the caller has to learn which var was refused, and names are not
+// secret); values and envelopes never do.
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "sort"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// configVarIn is one var a write asks to set, in the PUT's wire shape but
+// door-neutral: the JSON door decodes into it, a form door fills it in.
+type configVarIn struct{ Kind, Value, Envelope, SealedTo string }
+
+// configRefusalCode names why a config write was refused. The set is
+// closed: a door renders each one, and a new code is a new rule every door
+// has to learn.
+type configRefusalCode string
+
+const (
+ configRefusalEnvName configRefusalCode = "env-name"
+ configRefusalEnvDefault configRefusalCode = "env-default"
+ configRefusalVarName configRefusalCode = "var-name"
+ configRefusalVarValue configRefusalCode = "var-value"
+ configRefusalEnvEnvelope configRefusalCode = "env-envelope"
+ configRefusalSecretEnvelope configRefusalCode = "secret-envelope"
+ configRefusalSecretPlaintext configRefusalCode = "secret-plaintext"
+ configRefusalVarKind configRefusalCode = "var-kind"
+ configRefusalKeylessFleet configRefusalCode = "keyless-fleet"
+ configRefusalSealedWrongKey configRefusalCode = "sealed-wrong-key"
+ configRefusalSealedUnchecked configRefusalCode = "sealed-unchecked"
+ configRefusalSealedOld configRefusalCode = "sealed-old"
+ configRefusalNotFound configRefusalCode = "not-found"
+ configRefusalConflict configRefusalCode = "conflict"
+ configRefusalNothingToRemove configRefusalCode = "nothing-to-remove"
+ configRefusalStore configRefusalCode = "store"
+ configRefusalSealKey configRefusalCode = "seal-key"
+)
+
+// configRefusal is one refused config write: a code every door can render,
+// and the JSON door's own status and sentence for it.
+type configRefusal struct {
+ Code configRefusalCode
+ Status int // the JSON door's status
+ Msg string // the JSON door's exact current text
+ Var string // the offending name, "" if none
+}
+
+// writeJSONDoor answers ref the way the JSON door always has: not-found is
+// http.NotFound's own body (the gate's byte-identical 404), everything else
+// a JSON error.
+func (ref *configRefusal) writeJSONDoor(w http.ResponseWriter, r *http.Request) {
+ if ref.Code == configRefusalNotFound {
+ http.NotFound(w, r)
+ return
+ }
+ jsonError(w, ref.Status, ref.Msg)
+}
+
+func badConfig(code configRefusalCode, name, msg string) *configRefusal {
+ return &configRefusal{Code: code, Status: http.StatusBadRequest, Msg: msg, Var: name}
+}
+
+// checkConfigEnvironment refuses a bad environment name, or returns nil.
+//
+// "" is not a refusal: it is how every door says "the default bundle". But
+// "default" IS refused, and with its own sentence, because it already NAMES
+// that bundle (config.json) — accepting it would either error confusingly
+// deep in appconfig or, worse, read and write a second bundle that merely
+// looks like the default one. Same rule the CLI enforces client-side
+// (checkEnvironmentFlag, appconfig_cli.go); enforced here too, because a
+// door must not depend on its client's manners.
+//
+// The name is NOT echoed back. There is exactly one of them per request, so
+// naming it buys a caller nothing they don't already know, and the shape
+// rule is the actionable half.
+func checkConfigEnvironment(name string) *configRefusal {
+ if name == "" {
+ return nil
+ }
+ if name == appconfig.DefaultBundle {
+ return badConfig(configRefusalEnvDefault, "",
+ `"default" already names the base bundle (config.json) that every route gets when no `+
+ `environment is bound — omit the environment to work on it directly, don't name it`)
+ }
+ if !appconfig.ValidEnvironmentName(name) {
+ return badConfig(configRefusalEnvName, "", "invalid environment name — want [a-z0-9-]{1,32}")
+ }
+ return nil
+}
+
+// checkConfigSets checks every var a write asks to set and builds the vars
+// it will store, returning the names sorted.
+//
+// Sorted, so a request with several defects always refuses on the same
+// one — a map's own iteration order would make the error a caller sees
+// depend on nothing they can reason about. Each name is checked before its
+// kind, and each kind's rules in a fixed order.
+//
+// A garbage envelope is caught HERE, while the person who pasted it is
+// still looking at it — accepted now, it would stall the app's whole config
+// at render time, hours later, on every host, out of sight
+// (appconfig.CheckEnvelope's doc comment).
+func checkConfigSets(in map[string]configVarIn) ([]string, map[string]appconfig.Var, *configRefusal) {
+ keys := make([]string, 0, len(in))
+ for k := range in {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ sets := make(map[string]appconfig.Var, len(in))
+ for _, k := range keys {
+ v := in[k]
+ if !appconfig.ValidVarName(k) {
+ return nil, nil, badConfig(configRefusalVarName, k,
+ fmt.Sprintf("invalid var name %q — want a letter or underscore, then letters, digits or underscores", k))
+ }
+ switch v.Kind {
+ case "env":
+ // The same check applyAt makes, made earlier: here the operator
+ // can still see the plaintext and fix it.
+ if err := appconfig.ValidVarValue(v.Value); err != nil {
+ return nil, nil, badConfig(configRefusalVarValue, k, fmt.Sprintf("var %s: %v", k, err))
+ }
+ if v.Envelope != "" {
+ return nil, nil, badConfig(configRefusalEnvEnvelope, k,
+ fmt.Sprintf(`var %s is kind "env" but carries an envelope — send it as kind "secret", or drop the envelope`, k))
+ }
+ // Built field by field, never copied wholesale from the wire
+ // shape: an "env" var cannot smuggle an envelope into the bucket
+ // even if the check above were ever loosened.
+ sets[k] = appconfig.Var{Kind: "env", Value: v.Value}
+ case "secret":
+ if err := appconfig.CheckEnvelope(v.Envelope); err != nil {
+ // CheckEnvelope's errors name the defect and never echo the
+ // envelope — deliberately, because they end up here.
+ return nil, nil, badConfig(configRefusalSecretEnvelope, k, fmt.Sprintf("var %s: %v", k, err))
+ }
+ if v.Value != "" {
+ // Refused, not silently dropped: a caller who sent plaintext
+ // to a door that stores ciphertext has to LEARN that their
+ // secret crossed the wire in the clear, so they can rotate
+ // it. The refusal never echoes the value it is refusing.
+ return nil, nil, badConfig(configRefusalSecretPlaintext, k,
+ fmt.Sprintf(`var %s is kind "secret" but carries a plaintext value — seal it client-side and send only the envelope`, k))
+ }
+ // SealedTo is checked against the app's key by writeConfig,
+ // under the account lock, before anything is written.
+ sets[k] = appconfig.Var{Kind: "secret", Envelope: v.Envelope, SealedTo: v.SealedTo}
+ default:
+ return nil, nil, badConfig(configRefusalVarKind, k,
+ fmt.Sprintf(`var %s: invalid kind %q — want "env" or "secret"`, k, v.Kind))
+ }
+ }
+ return keys, sets, nil
+}
+
+// writeConfig writes one bundle's sets and unsets: the account lock when a
+// secret is set, the seal check under it, the store write (Apply or
+// ApplyEnvironment when want is nil, ApplyAtVersion at want otherwise), and
+// the unlock after it. keys and sets are checkConfigSets' answer. Audit and
+// bumpSerial are the door's: each names itself in the trail.
+//
+// A write with nothing to set or unset writes nothing and is not refused.
+func (s *Server) writeConfig(ctx context.Context, acct *Account, app, envName string, want *appconfig.BundleVersion, keys []string, sets map[string]appconfig.Var, unset []string) (removed int, ref *configRefusal) {
+ unlock, ref := s.configWriteBegin(ctx, acct, app, keys, sets, false)
+ defer unlock()
+ if ref != nil {
+ return 0, ref
+ }
+ if len(sets) == 0 && len(unset) == 0 {
+ return 0, nil
+ }
+ return s.configWriteBundle(ctx, unlock, acct, app, envName, want, sets, unset)
+}
+
+// configWriteBundle is configWriteStore over the bundle's own write: Apply
+// or ApplyEnvironment when want is nil, ApplyAtVersion at want otherwise.
+func (s *Server) configWriteBundle(ctx context.Context, unlock func(), acct *Account, app, envName string, want *appconfig.BundleVersion, sets map[string]appconfig.Var, unset []string) (int, *configRefusal) {
+ return s.configWriteStore(ctx, unlock, acct, app, envName, func(ctx context.Context) (int, error) {
+ switch {
+ case want != nil:
+ return appconfig.ApplyAtVersion(ctx, s.cfg.Releases, acct.Sqid, app, envName, *want, sets, unset)
+ case envName == "":
+ return appconfig.Apply(ctx, s.cfg.Releases, acct.Sqid, app, sets, unset)
+ default:
+ return appconfig.ApplyEnvironment(ctx, s.cfg.Releases, acct.Sqid, app, envName, sets, unset)
+ }
+ })
+}
+
+// configWriteBegin is a write's first half: the account lock, then the
+// seal check under it. It returns the unlock (idempotent; a no-op when no
+// lock was taken), which the caller must defer even on a refusal.
+//
+// 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
+// replacement cannot land between them: the key door takes the same lock
+// and then sees this value. Taken here, before any app lock
+// (teamApplyEnvironment's comes after: account, then app). Nothing in the
+// write takes the account lock again: planLock is only on the create
+// doors. lockAlways is the JSON door's team write into an environment,
+// which holds it sealed value or not: one that brings the environment into
+// being mints its platform credentials (mintOwnedEnvironment) under it.
+// Any other plain env write takes no lock.
+func (s *Server) configWriteBegin(ctx context.Context, acct *Account, app string, keys []string, sets map[string]appconfig.Var, lockAlways bool) (func(), *configRefusal) {
+ unlockAcct := func() {}
+ secret := configSetsSecret(sets)
+ if secret || lockAlways {
+ unlock := s.lockAccount(acct.Sqid)
+ held := true
+ unlockAcct = func() {
+ if held {
+ held = false
+ unlock()
+ }
+ }
+ }
+ if secret {
+ if ref := s.configCheckSealedTo(ctx, acct, app, keys, sets); ref != nil {
+ return unlockAcct, ref
+ }
+ }
+ return unlockAcct, nil
+}
+
+// configWriteStore is a write's second half: the test hook, the store write
+// apply makes, the unlock, and the store error's refusal.
+func (s *Server) configWriteStore(ctx context.Context, unlock func(), acct *Account, app, envName string, apply func(context.Context) (int, error)) (int, *configRefusal) {
+ if configPutBeforeApply != nil {
+ configPutBeforeApply()
+ }
+ removed, err := apply(ctx)
+ unlock()
+ if errors.Is(err, errTeamOutOfScope) {
+ // Only teamApplyEnvironment says this: the not-found an unknown
+ // environment gets (§3, §4), with no log line.
+ return 0, &configRefusal{Code: configRefusalNotFound, Status: http.StatusNotFound, Msg: notFoundBody}
+ }
+ if err != nil {
+ return 0, configStoreRefusal(fmt.Sprintf("api config apply %s/%s (%s)", acct.Sqid, app, configBundleName(envName)), err)
+ }
+ return removed, nil
+}
+
+// notFoundBody is http.NotFound's text, without its newline: the Msg of a
+// not-found refusal, which the JSON door renders with http.NotFound itself.
+const notFoundBody = "404 page not found"
+
+// configStoreRefusal is a config write that failed, mapping the three
+// outcomes a caller can act on differently and describing none of them in
+// bucket terms — the store's own error text (bucket names, key paths, AWS
+// request ids) goes to the log, where the operator who can act on it will
+// see it, and never to the client.
+func configStoreRefusal(what string, err error) *configRefusal {
+ log.Printf("console: %s: %v", what, err)
+ if errors.Is(err, release.ErrCASConflict) {
+ // Someone else wrote this bundle between our read and our write.
+ // Retry-worthy, and the operator has to re-read first — appconfig
+ // deliberately has no automatic retry (see apply's doc comment).
+ return &configRefusal{Code: configRefusalConflict, Status: http.StatusConflict, Msg: "config changed concurrently — try again"}
+ }
+ if configNothingToRemove(err) {
+ // appconfig's own sentence, verbatim: it names the app and the
+ // bundle, which is exactly what the operator needs and carries
+ // nothing they didn't send.
+ return &configRefusal{Code: configRefusalNothingToRemove, Status: http.StatusConflict, Msg: err.Error()}
+ }
+ return &configRefusal{Code: configRefusalStore, Status: http.StatusBadGateway, Msg: "could not store the config — try again"}
+}
+
+// configCheckSealedTo checks each sealed var of a write against the key the
+// app's boxes hold (fleet secrets key spec §5.3), returning the refusal or
+// nil. keys is the sorted var names, so a request with several defects
+// always refuses on the same one. The caller holds the account lock.
+//
+// For an app on a fleet, each value must say it is sealed to the fleet's key
+// (an older CLI says nothing and is told to upgrade) and be v2. For an app
+// placed nowhere, an absent sealed_to is today's behaviour and accepted; a
+// present one must be the deployment key. A console without a usable
+// deployment key has nothing to compare, and accepts as it always has.
+//
+// It reads chooseSealKey, not sealKeyFor: the write never seals, and it
+// needs the fleet's name for its refusals. sealKeyFor is chooseSealKey plus
+// the sealer, so the key checked here is the key the GET served.
+func (s *Server) configCheckSealedTo(ctx context.Context, acct *Account, app string, keys []string, sets map[string]appconfig.Var) *configRefusal {
+ c, err := s.chooseSealKey(ctx, acct.Sqid, app)
+ var keyless errFleetNoSecretsKey
+ var unknown errUnknownApp
+ switch {
+ case err == nil:
+ case errors.As(err, &keyless):
+ return &configRefusal{Code: configRefusalKeylessFleet, Status: http.StatusConflict, Msg: keyless.Error()}
+ case errors.Is(err, errNoDeploymentKey), errors.Is(err, errDeploymentKeyUnreadable):
+ return nil
+ case errors.As(err, &unknown):
+ // The gate saw the app a moment ago; it went since. The gate's own
+ // answer.
+ return &configRefusal{Code: configRefusalNotFound, Status: http.StatusNotFound, Msg: notFoundBody}
+ default:
+ log.Printf("console: api config apply %s/%s: seal key: %v", acct.Sqid, app, err)
+ return &configRefusal{Code: configRefusalSealKey, Status: http.StatusBadGateway, Msg: "could not read the config — try again"}
+ }
+ fp := appconfig.KeyFingerprint(c.pub)
+ for _, k := range keys {
+ v, ok := sets[k]
+ if !ok || v.Kind != "secret" {
+ continue
+ }
+ if c.fleet == "" {
+ if v.SealedTo != "" && v.SealedTo != fp {
+ return badConfig(configRefusalSealedWrongKey, k, fmt.Sprintf("%s was sealed to a key that this app's boxes do not hold. unset CARLOS_SECRETS_PUBKEY in your terminal and set %s again", k, k))
+ }
+ continue
+ }
+ switch {
+ case v.SealedTo == "":
+ return badConfig(configRefusalSealedUnchecked, k, fmt.Sprintf("%s cannot be checked, because the carlos CLI that sealed it did not say which key it used, and %s is placed on %s. upgrade the carlos CLI and set %s again", k, app, c.fleet, k))
+ case v.SealedTo != fp:
+ return badConfig(configRefusalSealedWrongKey, k, fmt.Sprintf("%s was sealed to a key that %s's boxes do not hold. unset CARLOS_SECRETS_PUBKEY in your terminal and set %s again", k, c.fleet, k))
+ case !appconfig.EnvelopeBound(v.Envelope):
+ return badConfig(configRefusalSealedOld, k, fmt.Sprintf("%s was sealed in an older format that %s's boxes do not accept. upgrade the carlos CLI and set %s again", k, c.fleet, k))
+ }
+ }
+ return nil
+}
diff --git a/internal/console/configwrite_test.go b/internal/console/configwrite_test.go
new file mode 100644
index 000000000..7788760f6
--- /dev/null
+++ b/internal/console/configwrite_test.go
@@ -0,0 +1,246 @@
+package console
+
+// The shared config write check (configwrite.go): every refusal it can make
+// carries the JSON door's exact answer, and none carries content.
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// cwMarker is the content every refusal below must never echo.
+const cwMarker = "cw-content-marker-7f3a"
+
+// cwJSONBody is the body the JSON door writes for ref.
+func cwJSONBody(ref *configRefusal) string {
+ rec := httptest.NewRecorder()
+ ref.writeJSONDoor(rec, httptest.NewRequest(http.MethodPut, "/", nil))
+ return rec.Body.String()
+}
+
+func TestCheckConfigSetsCodes(t *testing.T) {
+ fx, token := configFixture(t, "code-cw-codes")
+ _, _, envelope := sealedFor(t, "irrelevant")
+
+ type set = map[string]configVarIn
+ cases := []struct {
+ name string
+ env string
+ set set
+ code configRefusalCode
+ v string
+ }{
+ {"environment default", "default", set{"A": {Kind: "env", Value: "1"}}, configRefusalEnvDefault, ""},
+ {"environment name", "Staging Prod", set{"A": {Kind: "env", Value: "1"}}, configRefusalEnvName, ""},
+ {"var name", "", set{"9BAD": {Kind: "env", Value: "1"}}, configRefusalVarName, "9BAD"},
+ {"var value", "", set{"A": {Kind: "env", Value: "one\ntwo"}}, configRefusalVarValue, "A"},
+ {"env envelope", "", set{"A": {Kind: "env", Value: "1", Envelope: envelope}}, configRefusalEnvEnvelope, "A"},
+ {"secret envelope", "", set{"A": {Kind: "secret", Envelope: "not base64 at all!!"}}, configRefusalSecretEnvelope, "A"},
+ {"secret plaintext", "", set{"A": {Kind: "secret", Envelope: envelope, Value: "hunter2"}}, configRefusalSecretPlaintext, "A"},
+ {"var kind", "", set{"A": {Kind: "sekret", Value: "1"}}, configRefusalVarKind, "A"},
+ // Order: sorted names, the name before the kind.
+ {"sorted: first name refuses", "", set{"Z": {Kind: "sekret"}, "A": {Kind: "env", Envelope: envelope}}, configRefusalEnvEnvelope, "A"},
+ {"name before kind", "", set{"9X": {Kind: "sekret"}}, configRefusalVarName, "9X"},
+ // The environment is checked before any var.
+ {"environment before vars", "default", set{"9X": {Kind: "sekret"}}, configRefusalEnvDefault, ""},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ ref := checkConfigEnvironment(c.env)
+ if ref == nil {
+ _, _, ref = checkConfigSets(c.set)
+ }
+ if ref == nil {
+ t.Fatal("not refused")
+ }
+ if ref.Code != c.code || ref.Status != http.StatusBadRequest || ref.Var != c.v {
+ t.Fatalf("refusal = %+v, want code %s, 400, var %q", ref, c.code, c.v)
+ }
+ wire := map[string]any{}
+ for k, v := range c.set {
+ wire[k] = map[string]string{"kind": v.Kind, "value": v.Value, "envelope": v.Envelope}
+ }
+ body := map[string]any{"set": wire}
+ if c.env != "" {
+ body["environment"] = c.env
+ }
+ status, got := putRaw(t, configURL(fx, "titogo"), body, token)
+ if status != ref.Status || got != cwJSONBody(ref) {
+ t.Fatalf("door = %d %q, shared check = %d %q", status, got, ref.Status, cwJSONBody(ref))
+ }
+ })
+ }
+ if _, found := storedManifest(t, fx, "titogo"); found {
+ t.Fatal("a refused write stored a manifest")
+ }
+}
+
+func TestCheckConfigSetsBuildsFieldByField(t *testing.T) {
+ _, _, envelope := sealedFor(t, "irrelevant")
+ keys, sets, ref := checkConfigSets(map[string]configVarIn{
+ "B": {Kind: "env", Value: "1", SealedTo: "fp"},
+ "A": {Kind: "secret", Envelope: envelope, SealedTo: "fp"},
+ })
+ if ref != nil {
+ t.Fatal(ref.Msg)
+ }
+ if strings.Join(keys, ",") != "A,B" {
+ t.Fatalf("keys = %v, want sorted", keys)
+ }
+ if sets["B"] != (appconfig.Var{Kind: "env", Value: "1"}) || sets["A"] != (appconfig.Var{Kind: "secret", Envelope: envelope, SealedTo: "fp"}) {
+ t.Fatalf("sets = %+v", sets)
+ }
+}
+
+// cwFailStore fails every write.
+type cwFailStore struct{ release.Store }
+
+func (cwFailStore) Put(context.Context, string, []byte, string) (string, error) {
+ return "", errors.New("store down")
+}
+
+func TestWriteConfigNeverEchoesContent(t *testing.T) {
+ var logs bytes.Buffer
+ prev := log.Writer()
+ log.SetOutput(&logs)
+ t.Cleanup(func() { log.SetOutput(prev) })
+
+ type outcome struct {
+ name string
+ ref *configRefusal
+ code configRefusalCode
+ content []string
+ }
+ var got []outcome
+
+ // The shared checks, each fed content it must not repeat.
+ _, _, envelope := sealedFor(t, cwMarker)
+ for _, c := range []struct {
+ name string
+ v configVarIn
+ code configRefusalCode
+ }{
+ {"var value", configVarIn{Kind: "env", Value: cwMarker + "\nx"}, configRefusalVarValue},
+ {"env envelope", configVarIn{Kind: "env", Value: cwMarker, Envelope: envelope}, configRefusalEnvEnvelope},
+ {"secret envelope", configVarIn{Kind: "secret", Envelope: cwMarker + "!!"}, configRefusalSecretEnvelope},
+ {"secret plaintext", configVarIn{Kind: "secret", Envelope: envelope, Value: cwMarker}, configRefusalSecretPlaintext},
+ {"var kind", configVarIn{Kind: "sekret", Value: cwMarker, Envelope: envelope}, configRefusalVarKind},
+ } {
+ _, _, ref := checkConfigSets(map[string]configVarIn{"A": c.v})
+ got = append(got, outcome{c.name, ref, c.code, []string{cwMarker, envelope}})
+ }
+
+ // writeConfig's own refusals: a fleet app.
+ fx, _, k := skFleetShop(t, "code-cw-fleet", true)
+ acct, err := fx.st.AccountBySqid(fx.sqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account: %v %v", acct, err)
+ }
+ ctx := context.Background()
+ write := func(app, envName string, want *appconfig.BundleVersion, sets map[string]appconfig.Var, unset []string) *configRefusal {
+ t.Helper()
+ keys := make([]string, 0, len(sets))
+ for n := range sets {
+ keys = append(keys, n)
+ }
+ _, ref := fx.srv.writeConfig(ctx, acct, app, envName, want, keys, sets, unset)
+ if n := acctLockHolders(fx.srv, acct.Sqid); n != 0 {
+ t.Fatalf("account lock held by %d after writeConfig", n)
+ }
+ return ref
+ }
+ v2 := skSeal(t, fx, k.pub, true)
+ v1 := skSeal(t, fx, k.pub, false)
+ depPub, depFP := mustTestSecretsKey()
+ wrong := skSeal(t, fx, depPub, true)
+ secret := func(env, fp string) map[string]appconfig.Var {
+ return map[string]appconfig.Var{"API_KEY": {Kind: "secret", Envelope: env, SealedTo: fp}}
+ }
+ got = append(got,
+ outcome{"sealed unchecked", write("shop", "", nil, secret(v2, ""), nil), configRefusalSealedUnchecked, []string{v2}},
+ outcome{"sealed wrong key (fleet)", write("shop", "", nil, secret(wrong, depFP), nil), configRefusalSealedWrongKey, []string{wrong}},
+ outcome{"sealed old", write("shop", "", nil, secret(v1, k.fp), nil), configRefusalSealedOld, []string{v1}},
+ outcome{"not found", write("ghost", "", nil, secret(v2, k.fp), nil), configRefusalNotFound, []string{v2}},
+ outcome{"seal key", func() *configRefusal {
+ _, ref := fx.srv.writeConfig(ctx, &Account{Sqid: "zzzz"}, "shop", "", nil, []string{"API_KEY"}, secret(v2, k.fp), nil)
+ return ref
+ }(), configRefusalSealKey, []string{v2}},
+ outcome{"nothing to remove", write("shop", "", nil, nil, []string{"GONE"}), configRefusalNothingToRemove, nil},
+ )
+ // A landed write, then one at a version the bundle has left.
+ if ref := write("shop", "", nil, secret(v2, k.fp), nil); ref != nil {
+ t.Fatalf("good write refused: %+v", ref)
+ }
+ _, ver, err := appconfig.GetBundle(ctx, fx.rel, fx.sqid, "shop", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ stale := appconfig.BundleVersion{}
+ plain := map[string]appconfig.Var{"PORT": {Kind: "env", Value: cwMarker}}
+ got = append(got, outcome{"conflict", write("shop", "", &stale, plain, nil), configRefusalConflict, []string{cwMarker}})
+ if ref := write("shop", "", &ver, plain, nil); ref != nil {
+ t.Fatalf("write at the current version refused: %+v", ref)
+ }
+ if m := skStored(t, fx); m.Vars["PORT"].Value != cwMarker || m.Vars["API_KEY"].Envelope != v2 {
+ t.Fatalf("stored = %+v", m.Vars)
+ }
+ // A store that will not write.
+ fx.srv.cfg.Releases = cwFailStore{fx.srv.cfg.Releases}
+ got = append(got, outcome{"store", write("shop", "", nil, plain, nil), configRefusalStore, []string{cwMarker}})
+
+ // A keyless fleet, and a platform app's wrong key.
+ fx2, _, _ := skFleetShop(t, "code-cw-keyless", false)
+ acct2, err := fx2.st.AccountBySqid(fx2.sqid)
+ if err != nil || acct2 == nil {
+ t.Fatalf("account: %v %v", acct2, err)
+ }
+ if _, err := fx2.st.CreateAppIn(OpsAccountID, "plat", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ wrong2 := skSeal(t, fx2, skNewKey(t).pub, true)
+ _, ref := fx2.srv.writeConfig(ctx, acct2, "shop", "", nil, []string{"API_KEY"}, secret(wrong2, depFP), nil)
+ got = append(got, outcome{"keyless fleet", ref, configRefusalKeylessFleet, []string{wrong2}})
+ _, ref = fx2.srv.writeConfig(ctx, acct2, "plat", "", nil, []string{"API_KEY"}, secret(wrong2, "not-the-deployment-key"), nil)
+ got = append(got, outcome{"sealed wrong key (platform)", ref, configRefusalSealedWrongKey, []string{wrong2}})
+
+ seen := map[configRefusalCode]bool{}
+ for _, o := range got {
+ if o.ref == nil {
+ t.Fatalf("%s: not refused", o.name)
+ }
+ if o.ref.Code != o.code {
+ t.Fatalf("%s: code = %s (%q), want %s", o.name, o.ref.Code, o.ref.Msg, o.code)
+ }
+ seen[o.code] = true
+ for _, c := range o.content {
+ if strings.Contains(o.ref.Msg, c) {
+ t.Errorf("%s: Msg %q echoes content", o.name, o.ref.Msg)
+ }
+ if strings.Contains(logs.String(), c) {
+ t.Errorf("%s: the log echoes content: %s", o.name, logs.String())
+ }
+ }
+ }
+ // Every code but the environment's (no content to echo) was exercised.
+ for _, c := range []configRefusalCode{
+ configRefusalVarValue, configRefusalEnvEnvelope, configRefusalSecretEnvelope,
+ configRefusalSecretPlaintext, configRefusalVarKind, configRefusalKeylessFleet,
+ configRefusalSealedWrongKey, configRefusalSealedUnchecked, configRefusalSealedOld,
+ configRefusalNotFound, configRefusalConflict, configRefusalNothingToRemove,
+ configRefusalStore, configRefusalSealKey,
+ } {
+ if !seen[c] {
+ t.Errorf("code %s not exercised", c)
+ }
+ }
+}
diff --git a/internal/console/teamcreds_test.go b/internal/console/teamcreds_test.go
index 5b2841307..ec7b6a13f 100644
--- a/internal/console/teamcreds_test.go
+++ b/internal/console/teamcreds_test.go
@@ -377,7 +377,7 @@ func TestApplyCallersAreTheKnownWalks(t *testing.T) {
return true
}
switch sel.Sel.Name {
- case "Apply", "ApplyEnvironment", "ApplyEnvironmentOwned", "SetEnv", "SetSecret", "SaveEnvironment", "SetEnvironmentOwner", "ForkEnvironment", "ApplyInstance":
+ case "Apply", "ApplyEnvironment", "ApplyAtVersion", "ApplyEnvironmentOwned", "SetEnv", "SetSecret", "SaveEnvironment", "SetEnvironmentOwner", "ForkEnvironment", "ApplyInstance":
if callers[rel] == nil {
callers[rel] = map[string]bool{}
}
@@ -418,6 +418,7 @@ func TestApplyCallersAreTheKnownWalks(t *testing.T) {
"internal/console/apienv.go", // adopt, release and fork
"internal/console/apimail.go", // CARLOS_MAIL_EVENTS_KEY, default bundle only
"internal/console/apiscan.go", // the scan callback secret's removal, default bundle only
+ "internal/console/configwrite.go", // writeConfig, the config write every config door shares
"internal/console/relayenv.go", // CARLOS_RELAY per owned environment
"internal/console/relayops.go", // CARLOS_RELAY for the app
"internal/console/scankeysync.go", // the scan callback secret, default bundle only