carlos / platform Public

cli: config receipts, --if-version, env effective, digest (#522 plan 1 task 5)

env/secrets list print the bundle's version in the header (from the
console's GET, or one LoadLayer read in bucket mode); --digests adds a
digest column and --json carries both. The four writing verbs take
--if-version, print the receipt's names and the version after (or that
nothing changed), and exit 4 on a 412 with the current version printed.
Before a conditional write the client checks the console reports a
version: an older console would ignore if_version and write anyway.
Bucket mode refuses --if-version.

New: carlos env effective --app --host [--json] (console only) and
carlos env digest --kind env|secret, local, matching appconfig.Digest;
--sealed-to supplies the fingerprint a secret's digest also covers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e83235ab170bc2aca9e6ffb346ff4a662fd880fa parent a8230be
4 files changed, +1,175 −129
  • apimode.go +183 −18
  • apimode_test.go +204 −0
  • appconfig_cli.go +453 −111
  • appconfig_cli_test.go +335 −0

CI failed — run details

diff --git a/apimode.go b/apimode.go
index f65f9d99c..36b9ec018 100644
--- a/apimode.go
+++ b/apimode.go
@@ -2871,9 +2871,11 @@ func (s *apiSession) patchJSON(ctx context.Context, path string, in any) (int, [
// ever populated for Kind=="env": a secret row's value is structurally
// absent on the wire (the console couldn't read it if it wanted to), so
// Value simply decodes to "" for those rows, same as an env var's own empty
-// string would.
+// string would. Digest is appconfig.Digest of the stored var, so a script
+// can tell whether a key moved without seeing a secret; "" from a console
+// that predates #522.
type apiConfigVar struct {
- Key, Kind, Value string
+ Key, Kind, Value, Digest string
}
// apiConfig is one bundle's config read back through the console, mirroring
@@ -2884,7 +2886,12 @@ type apiConfigVar struct {
// (see secretsPubKey's API-mode resolution order in appconfig_cli.go).
// Environments is always present (possibly empty).
type apiConfig struct {
- Bundle string
+ Bundle string
+ // Version names the bundle's stored bytes ("none" when it has no
+ // object), the value --if-version takes; "" from a console that
+ // predates #522, which is also how configApply tells such a console
+ // apart before trusting it with a precondition.
+ Version string
ExecDelivery string
SecretsPubkey string
// SecretsAccount is the account sqid secrets for this app are sealed
@@ -2906,18 +2913,9 @@ type apiConfig struct {
// non-empty: the server's own zero value for "no ?environment=" is an
// absent parameter, not one carrying "".
func (s *apiSession) configGet(ctx context.Context, a apiAcct, app, environment string) (apiConfig, error) {
- // The one caller-side query append in this package: apiPath's own
- // invariant ("no tail carries a query string") still holds — the tail
- // here is a bare "/config" — but apiPath itself may have added
- // ?exact=sqid for an --account-id call, so this append has to pick its
- // separator instead of assuming "?".
path := apiPath(a, app, "/config")
if environment != "" {
- sep := "?"
- if strings.Contains(path, "?") {
- sep = "&"
- }
- path += sep + "environment=" + url.QueryEscape(environment)
+ path = withQuery(path, "environment", environment)
}
status, body, err := s.getJSON(ctx, path)
if err != nil {
@@ -2928,15 +2926,17 @@ func (s *apiSession) configGet(ctx context.Context, a apiAcct, app, environment
}
var res struct {
Bundle string `json:"bundle"`
+ Version string `json:"version"`
ExecDelivery string `json:"exec_delivery"`
SecretsPubkey string `json:"secrets_pubkey"`
SecretsAccount string `json:"secrets_account"`
KeylessFleet string `json:"secrets_keyless_fleet"`
Environments []string `json:"environments"`
Vars []struct {
- Key string `json:"key"`
- Kind string `json:"kind"`
- Value string `json:"value"`
+ Key string `json:"key"`
+ Kind string `json:"kind"`
+ Value string `json:"value"`
+ Digest string `json:"digest"`
} `json:"vars"`
}
if err := json.Unmarshal(body, &res); err != nil {
@@ -2944,6 +2944,7 @@ func (s *apiSession) configGet(ctx context.Context, a apiAcct, app, environment
}
out := apiConfig{
Bundle: res.Bundle,
+ Version: res.Version,
ExecDelivery: res.ExecDelivery,
SecretsPubkey: res.SecretsPubkey,
SecretsAccount: res.SecretsAccount,
@@ -2952,11 +2953,23 @@ func (s *apiSession) configGet(ctx context.Context, a apiAcct, app, environment
Vars: make([]apiConfigVar, len(res.Vars)),
}
for i, v := range res.Vars {
- out.Vars[i] = apiConfigVar{Key: v.Key, Kind: v.Kind, Value: v.Value}
+ out.Vars[i] = apiConfigVar{Key: v.Key, Kind: v.Kind, Value: v.Value, Digest: v.Digest}
}
return out, nil
}
+// withQuery appends one query parameter to an apiPath result. apiPath's own
+// invariant ("no tail carries a query string") still holds, but apiPath
+// itself may have added ?exact=sqid for an --account-id call, so the
+// separator has to be picked rather than assumed.
+func withQuery(path, key, value string) string {
+ sep := "?"
+ if strings.Contains(path, "?") {
+ sep = "&"
+ }
+ return path + sep + key + "=" + url.QueryEscape(value)
+}
+
// apiConfigApply is one config write through the console's config door,
// mirroring PUT /api/cli/apps/{account}/{app}/config's body exactly. Set's
// values marshal through appconfig.Var's OWN json tags
@@ -2973,6 +2986,11 @@ type apiConfigApply struct {
Unset []string `json:"unset,omitempty"`
ExecDelivery *string `json:"exec_delivery,omitempty"`
Message string `json:"message,omitempty"`
+ // IfVersion makes the set/unset write conditional on the bundle being
+ // at this version (#522 §4.5): "none" for "only if it does not exist
+ // yet", "" for no precondition. Last, and omitempty, so every request
+ // without one is byte for byte what it was.
+ IfVersion string `json:"if_version,omitempty"`
}
// configApply sends one PUT to the console's config door — a set, an unset,
@@ -2982,11 +3000,28 @@ type apiConfigApply struct {
// the server's count of unsets ACTUALLY present, never the argument count —
// the same rule unsetVars already follows for direct mode (a count of
// arguments reads as success for a typo'd key).
+//
+// With IfVersion set it first reads the bundle: a console that predates
+// #522 ignores a body field it does not know, so the precondition would be
+// dropped and the write made unconditionally. Such a console sends no
+// version on its GET, and is refused here before anything is written.
func (s *apiSession) configApply(ctx context.Context, a apiAcct, app string, req apiConfigApply) (apiConfigApplyResult, error) {
+ if req.IfVersion != "" {
+ cfg, err := s.configGet(ctx, a, app, req.Environment)
+ if err != nil {
+ return apiConfigApplyResult{}, err
+ }
+ if cfg.Version == "" {
+ return apiConfigApplyResult{}, errors.New(ifVersionCopyOldConsole)
+ }
+ }
status, body, err := s.putJSON(ctx, apiPath(a, app, "/config"), req)
if err != nil {
return apiConfigApplyResult{}, err
}
+ if status == http.StatusPreconditionFailed {
+ return apiConfigApplyResult{}, versionMismatchFromBody(status, body)
+ }
if status != http.StatusOK {
return apiConfigApplyResult{}, apiErrorFromBody(status, body)
}
@@ -2994,11 +3029,46 @@ func (s *apiSession) configApply(ctx context.Context, a apiAcct, app string, req
Result string `json:"result"`
Removed int `json:"removed"`
Restart *apiConfigRestart `json:"restart"`
+ Receipt *apiConfigReceipt `json:"receipt"`
}
if err := json.Unmarshal(body, &res); err != nil {
return apiConfigApplyResult{}, fmt.Errorf("config: unreadable response: %w", err)
}
- return apiConfigApplyResult{Removed: res.Removed, Restart: res.Restart}, nil
+ return apiConfigApplyResult{Removed: res.Removed, Restart: res.Restart, Receipt: res.Receipt}, nil
+}
+
+// ifVersionCopyOldConsole refuses --if-version against a console that
+// cannot check it.
+const ifVersionCopyOldConsole = "this console cannot check --if-version yet, so nothing was written. run the command without --if-version, or wait for the console to be updated"
+
+// apiVersionMismatch is a conditional write the console refused with 412:
+// the bundle was not at the version sent, and nothing was written. It is a
+// type of its own so the verbs can exit with exitVersionMismatch, which a
+// script tells apart from every other failure. Version is the version the
+// console read after refusing, "" when it could not read one.
+type apiVersionMismatch struct {
+ Message, Version string
+}
+
+func (e *apiVersionMismatch) Error() string {
+ if e.Version == "" {
+ return e.Message
+ }
+ return e.Message + "\ncurrent version: " + e.Version
+}
+
+// versionMismatchFromBody decodes the 412 body {"error","version"}. A body
+// without a message still means the same thing, so it gets the CLI's own.
+func versionMismatchFromBody(status int, body []byte) error {
+ var e struct {
+ Error string `json:"error"`
+ Version string `json:"version"`
+ }
+ _ = json.Unmarshal(body, &e)
+ if e.Error == "" {
+ e.Error = fmt.Sprintf("the config is not at the version you sent, so nothing was written (status %d)", status)
+ }
+ return &apiVersionMismatch{Message: e.Error, Version: e.Version}
}
// apiConfigApplyResult is one config write's answer — a struct rather than
@@ -3019,6 +3089,101 @@ type apiConfigApplyResult struct {
// means these are the routes, and an empty Hosts there really does mean
// none.
Restart *apiConfigRestart
+ // Receipt is what the set/unset write did to the bundle (#522 §4.6).
+ // Nil from a console that predates receipts, and for an
+ // exec_delivery-only write, which has none; either way the verbs print
+ // nothing for it rather than a guess.
+ Receipt *apiConfigReceipt
+}
+
+// apiConfigReceipt mirrors the console's receipt (internal/console
+// apiconfig.go). Lists are sorted by the console; Unset is what was present
+// and removed, UnsetAbsent what was asked for and not there, and Digests
+// covers the keys just set so a caller can check what it sent.
+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 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.
+ Others map[string]apiConfigVersionPair `json:"others,omitempty"`
+}
+
+type apiConfigVersionPair struct {
+ Before string `json:"before"`
+ After string `json:"after"`
+}
+
+// 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.
+type apiConfigEffective struct {
+ Host string `json:"host"`
+ Environment string `json:"environment"`
+ Owned bool `json:"owned"`
+ Layers apiEffectiveLayers `json:"layers"`
+ Vars []apiEffectiveVar `json:"vars"`
+}
+
+// apiEffectiveLayers: a layer that is no part of the route's merge is absent
+// rather than empty (the default for an owned environment, the environment
+// for a route bound to none), hence the pointers.
+type apiEffectiveLayers struct {
+ Default *apiLayerVersion `json:"default,omitempty"`
+ Environment *apiLayerVersion `json:"environment,omitempty"`
+ Overlay *apiLayerVersion `json:"overlay,omitempty"`
+}
+
+type apiLayerVersion struct {
+ Name string `json:"name,omitempty"`
+ Version string `json:"version"`
+}
+
+// apiEffectiveVar is one key as the route gets it. Value is a pointer
+// because an empty plain value and no value at all (a secret, or an
+// overlay's plain var) are different answers.
+type apiEffectiveVar struct {
+ Key string `json:"key"`
+ Kind string `json:"kind"`
+ Digest string `json:"digest"`
+ From string `json:"from"`
+ Value *string `json:"value,omitempty"`
+ Shadows []string `json:"shadows"`
+}
+
+// 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.
+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.StatusOK {
+ return apiConfigEffective{}, apiErrorFromBody(status, body)
+ }
+ var out apiConfigEffective
+ if err := json.Unmarshal(body, &out); err != nil {
+ return apiConfigEffective{}, fmt.Errorf("config: unreadable response: %w", err)
+ }
+ // [] rather than null, so --json never prints a null where the console
+ // meant "shadows nothing".
+ if out.Vars == nil {
+ out.Vars = []apiEffectiveVar{}
+ }
+ for i := range out.Vars {
+ if out.Vars[i].Shadows == nil {
+ out.Vars[i].Shadows = []string{}
+ }
+ }
+ return out, nil
}
// apiConfigRestart mirrors the console's own restart notice across the wire
diff --git a/apimode_test.go b/apimode_test.go
index 74aa45bda..9928b7088 100644
--- a/apimode_test.go
+++ b/apimode_test.go
@@ -17,6 +17,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "slices"
"strings"
"sync"
"sync/atomic"
@@ -4152,3 +4153,206 @@ func testSecretsPubkey(t *testing.T) string {
}
return pub
}
+
+// ---- #522 plan 1 task 5: versions, digests, receipts, if_version ----------
+
+// configWireStub is a console that answers the config GET with version and
+// digests and the PUT with whatever put says, recording the PUT body.
+func configWireStub(t *testing.T, version string, put func(w http.ResponseWriter, body []byte)) (*httptest.Server, *[]string) {
+ t.Helper()
+ var bodies []string
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet {
+ out := map[string]any{"bundle": "default", "environments": []string{}, "vars": []any{}}
+ if version != "" {
+ out["version"] = version
+ }
+ json.NewEncoder(w).Encode(out)
+ return
+ }
+ b, _ := io.ReadAll(r.Body)
+ bodies = append(bodies, string(b))
+ put(w, b)
+ }))
+ t.Cleanup(ts.Close)
+ return ts, &bodies
+}
+
+func TestConfigGetParsesVersionAndDigest(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{
+ "bundle": "default",
+ "version": "cv1:aaaa",
+ "environments": []string{},
+ "vars": []map[string]any{
+ {"key": "LOG_LEVEL", "kind": "env", "value": "info", "digest": "vd1:1111"},
+ {"key": "BANK_KEY", "kind": "secret", "digest": "vd1:2222"},
+ },
+ })
+ }))
+ defer ts.Close()
+ cfg, err := newTestSession(ts.URL).configGet(context.Background(), apiAcct{Seg: "acct"}, "app", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cfg.Version != "cv1:aaaa" {
+ t.Fatalf("Version = %q", cfg.Version)
+ }
+ if cfg.Vars[0] != (apiConfigVar{Key: "LOG_LEVEL", Kind: "env", Value: "info", Digest: "vd1:1111"}) ||
+ cfg.Vars[1] != (apiConfigVar{Key: "BANK_KEY", Kind: "secret", Digest: "vd1:2222"}) {
+ t.Fatalf("vars = %+v", cfg.Vars)
+ }
+}
+
+func TestConfigApplySendsIfVersion(t *testing.T) {
+ ts, bodies := configWireStub(t, "cv1:aaaa", func(w http.ResponseWriter, _ []byte) {
+ json.NewEncoder(w).Encode(map[string]any{"result": "ok", "removed": 0})
+ })
+ _, err := newTestSession(ts.URL).configApply(context.Background(), apiAcct{Seg: "acct"}, "app", apiConfigApply{
+ Set: map[string]appconfig.Var{"PORT": {Kind: "env", Value: "8080"}},
+ IfVersion: "cv1:aaaa",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := `{"environment":"","set":{"PORT":{"kind":"env","value":"8080"}},"if_version":"cv1:aaaa"}`; len(*bodies) != 1 || (*bodies)[0] != want {
+ t.Fatalf("PUT bodies = %q, want [%q]", *bodies, want)
+ }
+}
+
+// An older console ignores a body field it does not know, so if_version sent
+// to one would make an unconditional write. configApply asks first and
+// refuses before writing anything.
+func TestConfigApplyIfVersionOlderConsoleRefused(t *testing.T) {
+ ts, bodies := configWireStub(t, "", func(w http.ResponseWriter, _ []byte) {
+ json.NewEncoder(w).Encode(map[string]any{"result": "ok", "removed": 0})
+ })
+ _, err := newTestSession(ts.URL).configApply(context.Background(), apiAcct{Seg: "acct"}, "app", apiConfigApply{
+ Set: map[string]appconfig.Var{"PORT": {Kind: "env", Value: "8080"}},
+ IfVersion: "cv1:aaaa",
+ })
+ if err == nil || !strings.Contains(err.Error(), "--if-version") {
+ t.Fatalf("err = %v, want the older-console refusal", err)
+ }
+ if len(*bodies) != 0 {
+ t.Fatalf("PUT sent to a console that cannot check if_version: %q", *bodies)
+ }
+}
+
+func TestConfigApplyParsesReceipt(t *testing.T) {
+ ts, _ := configWireStub(t, "cv1:aaaa", func(w http.ResponseWriter, _ []byte) {
+ io.WriteString(w, `{"result":"ok","removed":1,"receipt":{"bundle":"prod","version_before":"cv1:aaaa","version_after":"cv1:bbbb",
+ "changed":true,"set":["A"],"unset":["OLD"],"unset_absent":["NEVER"],"digests":{"A":"vd1:1111"},
+ "others":{"default":{"before":"cv1:d1","after":"cv1:d2"}}}}`)
+ })
+ res, err := newTestSession(ts.URL).configApply(context.Background(), apiAcct{Seg: "acct"}, "app", apiConfigApply{
+ Environment: "prod", Set: map[string]appconfig.Var{"A": {Kind: "env", Value: "1"}}, Unset: []string{"OLD", "NEVER"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ rc := res.Receipt
+ if rc == nil {
+ t.Fatal("Receipt = nil")
+ }
+ if rc.Bundle != "prod" || rc.VersionBefore != "cv1:aaaa" || rc.VersionAfter != "cv1:bbbb" || !rc.Changed ||
+ !slices.Equal(rc.Set, []string{"A"}) || !slices.Equal(rc.Unset, []string{"OLD"}) || !slices.Equal(rc.UnsetAbsent, []string{"NEVER"}) ||
+ rc.Digests["A"] != "vd1:1111" || rc.Others["default"] != (apiConfigVersionPair{Before: "cv1:d1", After: "cv1:d2"}) {
+ t.Fatalf("receipt = %+v", rc)
+ }
+ if res.Removed != 1 {
+ t.Fatalf("Removed = %d", res.Removed)
+ }
+}
+
+func TestConfigApplyOlderConsoleNoReceipt(t *testing.T) {
+ ts, _ := configWireStub(t, "", func(w http.ResponseWriter, _ []byte) {
+ json.NewEncoder(w).Encode(map[string]any{"result": "ok", "removed": 0})
+ })
+ res, err := newTestSession(ts.URL).configApply(context.Background(), apiAcct{Seg: "acct"}, "app", apiConfigApply{
+ Set: map[string]appconfig.Var{"PORT": {Kind: "env", Value: "8080"}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.Receipt != nil {
+ t.Fatalf("Receipt = %+v, want nil from a console that sends none", res.Receipt)
+ }
+ var buf bytes.Buffer
+ printReceipt(&buf, res.Receipt) // must not panic, must say nothing
+ if buf.Len() != 0 {
+ t.Fatalf("printReceipt(nil) wrote %q", buf.String())
+ }
+}
+
+// TestEnvSet412ExitsWithVersionMismatch: the CLI verbs exit through
+// exitCodeFor (Ruling 3: no subprocess harness), so the mapping and the
+// printed version are what is pinned here.
+func TestEnvSet412ExitsWithVersionMismatch(t *testing.T) {
+ for _, tc := range []struct {
+ name, body, wantVersion string
+ }{
+ {"with version", `{"error":"the config is not at the version you sent, so nothing was written. read it again before you retry","version":"cv1:cccc"}`, "cv1:cccc"},
+ {"read failed, no version", `{"error":"the config is not at the version you sent, so nothing was written. read it again before you retry"}`, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ts, _ := configWireStub(t, "cv1:aaaa", func(w http.ResponseWriter, _ []byte) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusPreconditionFailed)
+ io.WriteString(w, tc.body)
+ })
+ _, err := newTestSession(ts.URL).configApply(context.Background(), apiAcct{Seg: "acct"}, "app", apiConfigApply{
+ Set: map[string]appconfig.Var{"PORT": {Kind: "env", Value: "8080"}}, IfVersion: "cv1:aaaa",
+ })
+ if err == nil {
+ t.Fatal("configApply on 412 returned no error")
+ }
+ if got := exitCodeFor(err); got != exitVersionMismatch || exitVersionMismatch != 4 {
+ t.Fatalf("exitCodeFor = %d, want 4", got)
+ }
+ if !strings.Contains(err.Error(), "nothing was written") {
+ t.Fatalf("err = %q, want the console's message", err)
+ }
+ if tc.wantVersion != "" && !strings.Contains(err.Error(), "current version: "+tc.wantVersion) {
+ t.Fatalf("err = %q, want the current version printed", err)
+ }
+ if tc.wantVersion == "" && strings.Contains(err.Error(), "current version") {
+ t.Fatalf("err = %q names a version the console did not send", err)
+ }
+ })
+ }
+ if got := exitCodeFor(errors.New("anything else")); got != 1 {
+ t.Fatalf("exitCodeFor(other) = %d, want 1", got)
+ }
+}
+
+func TestConfigEffectiveParses(t *testing.T) {
+ var gotURI string
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotURI = r.URL.RequestURI()
+ io.WriteString(w, `{"host":"shop.example.com","environment":"prod","owned":false,
+ "layers":{"default":{"version":"cv1:d"},"environment":{"name":"prod","version":"cv1:e"},"overlay":{"version":"none"}},
+ "vars":[{"key":"A","kind":"env","digest":"vd1:a","from":"environment","value":"","shadows":["default"]},
+ {"key":"S","kind":"secret","digest":"vd1:s","from":"default","shadows":null}]}`)
+ }))
+ defer ts.Close()
+ e, err := newTestSession(ts.URL).configEffective(context.Background(), apiAcct{Seg: "acct"}, "app", "shop.example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if gotURI != "/api/cli/apps/acct/app/config/effective?host=shop.example.com" {
+ t.Fatalf("uri = %q", gotURI)
+ }
+ if e.Host != "shop.example.com" || e.Environment != "prod" || e.Owned ||
+ e.Layers.Default == nil || e.Layers.Default.Version != "cv1:d" ||
+ e.Layers.Environment == nil || e.Layers.Environment.Name != "prod" || e.Layers.Environment.Version != "cv1:e" ||
+ e.Layers.Overlay == nil || e.Layers.Overlay.Version != "none" {
+ t.Fatalf("effective = %+v", e)
+ }
+ if len(e.Vars) != 2 || e.Vars[0].Value == nil || *e.Vars[0].Value != "" || e.Vars[1].Value != nil {
+ t.Fatalf("vars = %+v: an empty plain value must stay distinct from no value", e.Vars)
+ }
+ if e.Vars[1].Shadows == nil {
+ t.Fatal("shadows decoded nil; want [] so --json never prints null")
+ }
+}
diff --git a/appconfig_cli.go b/appconfig_cli.go
index 6b4683225..85baecd7f 100644
--- a/appconfig_cli.go
+++ b/appconfig_cli.go
@@ -176,9 +176,12 @@ const (
const envUsage = `usage: carlos env <command>
commands:
- set --app <a> [--environment <name>] KEY=value [KEY2=value2 ...] set one or more plain config vars
- unset --app <a> [--environment <name>] KEY [KEY2 ...] remove config vars
- list --app <a> [--environment <name>] list an app's config vars
+ set --app <a> [--environment <name>] [--if-version <v>] KEY=value [KEY2=value2 ...] set one or more plain config vars
+ unset --app <a> [--environment <name>] [--if-version <v>] KEY [KEY2 ...] remove config vars
+ list --app <a> [--environment <name>] [--digests] [--json] list an app's config vars and the bundle's version
+ effective --app <a> --host <h> [--json] show what one route gets from each config layer
+ digest --kind env --value <v> print a plain var's digest, to check a receipt
+ digest --kind secret --envelope-file <path> [--sealed-to <fp>] print a secret's digest from the envelope that was sent
environments --app <a> list an app's named environment bundles
exec-delivery --app <a> [--environment <name>] file|off|inherit opt one bundle's TCP-addr exec routes into config delivery
sync --app <a> request immediate config convergence (issue #44)
@@ -218,6 +221,22 @@ the agent can only request that pass, not write /etc or restart units
itself. It never restarts a box's shared edge service, only the one app's
own delivery.
+every bundle has a version, which changes whenever its stored contents do,
+and every var has a digest, which changes whenever that var does. list
+shows the version, and --digests adds the digests. set and unset print
+what they changed and the version after. --if-version <v> writes only if
+the bundle is still at version v ("none" if it must not exist yet);
+otherwise nothing is written, the current version is printed and carlos
+exits with code 4. --if-version needs a console.
+
+effective shows, for one route, each key, the layer it comes from (default,
+environment or overlay) and the lower layers it hides. it works through a
+console only.
+
+digest computes a digest locally. for a secret, pass the envelope that was
+sent and, with --sealed-to, the fingerprint it was sealed to: both are part
+of the stored var, and secrets set fills in sealed_to.
+
adopt, release and fork are an account owner's acts, through a logged-in
console only: an environment a team scope owns is standalone (it never
inherits the default bundle) and receives platform credentials minted for
@@ -245,6 +264,10 @@ func RunEnv(args []string) {
runEnvUnset(args[1:])
case "list":
runEnvList(args[1:])
+ case "effective":
+ runEnvEffective(args[1:])
+ case "digest":
+ runEnvDigest(args[1:])
case "environments":
runEnvEnvironments(args[1:])
case "exec-delivery":
@@ -296,16 +319,104 @@ func checkEnvironmentFlag(environment string) {
}
}
-// loadBundle fetches the manifest a `list` command shows: the default
+// loadBundleLayer fetches the bundle a `list` command shows: the default
// bundle when environment=="", or the named environment's own bundle
// otherwise — never merged. LoadMerged is what a bound route actually gets
// at materialization time; `list` shows exactly one bundle, matching what
-// `set`/`unset` write to for the same --environment value.
-func loadBundle(ctx context.Context, s release.Store, acct, app, environment string) (*appconfig.Manifest, error) {
- if environment == "" {
- return appconfig.Get(ctx, s, acct, app)
+// `set`/`unset` write to for the same --environment value. One read gives
+// both the manifest and its version, so the version printed is the version
+// of exactly the vars printed.
+func loadBundleLayer(ctx context.Context, s release.Store, acct, app, environment string) (appconfig.Layer, error) {
+ if !release.ValidAccount(acct) {
+ return appconfig.Layer{}, fmt.Errorf("config: invalid account %q", acct)
+ }
+ if !release.ValidApp(app) {
+ return appconfig.Layer{}, fmt.Errorf("config: invalid app %q", app)
+ }
+ if environment != "" && !appconfig.ValidEnvironmentName(environment) {
+ return appconfig.Layer{}, fmt.Errorf("config: invalid environment name %q", environment)
+ }
+ return appconfig.LoadLayer(ctx, s, appconfig.BundleKey(acct, app, environment), app)
+}
+
+// exitVersionMismatch is the process exit code when a set or unset is
+// refused because the bundle is not at --if-version. A code of its own so a
+// script can tell "re-read and decide" from every other failure, which
+// exits 1.
+const exitVersionMismatch = 4
+
+// exitCodeFor maps a config write's error to the process exit code.
+func exitCodeFor(err error) int {
+ var vm *apiVersionMismatch
+ if errors.As(err, &vm) {
+ return exitVersionMismatch
+ }
+ return 1
+}
+
+// fatalConfigWrite is log.Fatal for a config write's error, with the exit
+// code exitCodeFor picks.
+func fatalConfigWrite(err error) {
+ log.Print(err)
+ os.Exit(exitCodeFor(err))
+}
+
+// ifVersionFlag registers --if-version on the four writing verbs.
+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`)
+}
+
+// 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
+// process (#522 §4.5); a console's store does it for every writer.
+func checkIfVersionDirect(ifVersion string) error {
+ if ifVersion == "" {
+ return nil
+ }
+ return errors.New(ifVersionCopyDirect)
+}
+
+// The receipt and version lines, one block so they read as one voice.
+const (
+ ifVersionCopyDirect = "--if-version works through a console only, so nothing was written. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR and run carlos auth login"
+ receiptCopySet = "set: %s"
+ receiptCopyUnset = "removed: %s"
+ receiptCopyAbsent = "not there: %s"
+ 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"
+ effectiveCopyDirect = "carlos env effective works through a console only. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR and run carlos auth login"
+)
+
+// printReceipt writes what a set or unset did, from the console's receipt:
+// the exact names, and the version after (or that nothing changed). A nil
+// receipt, from an older console, prints nothing: silence makes no claim,
+// where a guess from the arguments would.
+func printReceipt(w io.Writer, rc *apiConfigReceipt) {
+ if rc == nil {
+ return
+ }
+ c := colorFor(w)
+ for _, l := range []struct {
+ format string
+ names []string
+ }{{receiptCopySet, rc.Set}, {receiptCopyUnset, rc.Unset}, {receiptCopyAbsent, rc.UnsetAbsent}} {
+ if len(l.names) > 0 {
+ fmt.Fprintf(w, " %s\n", fmt.Sprintf(l.format, strings.Join(l.names, ", ")))
+ }
+ }
+ if rc.Changed {
+ fmt.Fprintf(w, " %s\n", c.muted(fmt.Sprintf(receiptCopyVersion, rc.VersionAfter, rc.VersionBefore)))
+ } else {
+ fmt.Fprintf(w, " %s\n", fmt.Sprintf(receiptCopyUnchanged, rc.VersionAfter))
+ }
+ // 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 {
+ fmt.Fprintf(w, "%s %s\n", c.warn("note:"), fmt.Sprintf(receiptCopyOtherMoved, p.After, p.Before))
}
- return appconfig.LoadEnvironment(ctx, s, acct, app, environment)
}
// saveEnvVars writes plain config vars to the default bundle when
@@ -372,11 +483,12 @@ func runEnvSet(args []string) {
messageFlags := addMutationMessageFlags(fs)
app := appFlag(fs, "")
environment := environmentFlag(fs, "named environment bundle to set in (omit for the default bundle)")
+ ifVersion := ifVersionFlag(fs)
acctRaw, acctIDRaw, regPath, acctOf := accountFlagsWithRegistry(fs)
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
- usage := "usage: carlos env set --app <a> [--environment <name>] [--console <origin>] KEY=value [KEY2=value2 ...]"
+ 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())
if err != nil {
@@ -400,11 +512,12 @@ func runEnvSet(args []string) {
log.Fatalf("env set: %v", merr)
}
res, err := sess.configApply(context.Background(), acct, app2,
- apiConfigApply{Environment: *environment, Set: set, Message: message})
+ apiConfigApply{Environment: *environment, Set: set, Message: message, IfVersion: *ifVersion})
if err != nil {
- log.Fatal(err)
+ fatalConfigWrite(err)
}
fmt.Printf("%s %d env var(s) for %s (%s)\n", colorFor(os.Stdout).ok("set"), len(kv), app2, bundleLabel(*environment))
+ printReceipt(os.Stdout, res.Receipt)
printRestartNotice(os.Stdout, app2, restartFromAPI(res.Restart))
return
}
@@ -412,6 +525,9 @@ func runEnvSet(args []string) {
if *app == "" {
log.Fatal(usage)
}
+ if err := checkIfVersionDirect(*ifVersion); err != nil {
+ log.Fatal(err)
+ }
store := openStore()
if err := saveEnvVars(context.Background(), store, acctOf(), *app, *environment, kv); err != nil {
log.Fatal(err)
@@ -438,11 +554,12 @@ func runEnvUnset(args []string) {
messageFlags := addMutationMessageFlags(fs)
app := appFlag(fs, "")
environment := environmentFlag(fs, "named environment bundle to remove from (omit for the default bundle)")
+ ifVersion := ifVersionFlag(fs)
acctRaw, acctIDRaw, regPath, acctOf := accountFlagsWithRegistry(fs)
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
- usage := "usage: carlos env unset --app <a> [--environment <name>] [--console <origin>] KEY [KEY2 ...]"
+ usage := "usage: carlos env unset --app <a> [--environment <name>] [--if-version <v>] [--console <origin>] KEY [KEY2 ...]"
if fs.NArg() == 0 {
log.Fatal(usage)
}
@@ -461,11 +578,12 @@ func runEnvUnset(args []string) {
log.Fatalf("env unset: %v", merr)
}
res, err := sess.configApply(context.Background(), acct, app2,
- apiConfigApply{Environment: *environment, Unset: fs.Args(), Message: message})
+ apiConfigApply{Environment: *environment, Unset: fs.Args(), Message: message, IfVersion: *ifVersion})
if err != nil {
- log.Fatal(err)
+ fatalConfigWrite(err)
}
fmt.Printf("%s %d of %d var(s) for %s (%s)\n", colorFor(os.Stdout).ok("unset"), res.Removed, fs.NArg(), app2, bundleLabel(*environment))
+ printReceipt(os.Stdout, res.Receipt)
printRestartNotice(os.Stdout, app2, restartFromAPI(res.Restart))
return
}
@@ -473,6 +591,9 @@ func runEnvUnset(args []string) {
if *app == "" {
log.Fatal(usage)
}
+ if err := checkIfVersionDirect(*ifVersion); err != nil {
+ log.Fatal(err)
+ }
store := openStore()
removed, err := unsetVars(context.Background(), store, acctOf(), *app, *environment, fs.Args())
if err != nil {
@@ -491,86 +612,150 @@ func runEnvList(args []string) {
fs := flag.NewFlagSet("env list", flag.ExitOnError)
app := appFlag(fs, "")
environment := environmentFlag(fs, "named environment bundle to list (omit for the default bundle)")
+ digests := fs.Bool("digests", false, "add each var's digest")
+ asJSON := fs.Bool("json", false, "print the bundle as JSON, with its version and every digest")
acctRaw, acctIDRaw, acctOf := accountFlags(fs)
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
- usage := "usage: carlos env list --app <a> [--environment <name>] [--console <origin>]"
+ 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)
+ if *asJSON {
+ printListingJSON(os.Stdout, l)
+ return
+ }
+ printEnvList(os.Stdout, l, *digests)
+}
- sess, err := resolveMode(*consoleFlag)
+// bundleListing is one bundle as `env list` and `secrets list` show it,
+// the same whichever mode fetched it, and the shape of their --json.
+// Version is "" from a console that predates #522, and the header then
+// reads as it always did.
+type bundleListing struct {
+ App string `json:"app"`
+ Bundle string `json:"bundle"`
+ Version string `json:"version"`
+ ExecDelivery string `json:"exec_delivery,omitempty"`
+ Vars []listedVar `json:"vars"`
+}
+
+// listedVar is one row. Value is a pointer so a secret row has no value
+// field at all, while a plain var's empty value still shows as "".
+type listedVar struct {
+ Key string `json:"key"`
+ Kind string `json:"kind"`
+ Value *string `json:"value,omitempty"`
+ Digest string `json:"digest"`
+}
+
+// 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.
+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 {
log.Fatal(err)
}
+ var l bundleListing
if sess != nil {
- printUsing(os.Stdout, sess)
+ if announce {
+ printUsing(os.Stdout, sess)
+ }
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
- app2 := resolvedApp(sess, acct, *app, usage)
- cfg, err := sess.configGet(context.Background(), acct, app2, *environment)
+ app2 := resolvedApp(sess, acct, app, usage)
+ cfg, err := sess.configGet(context.Background(), acct, app2, environment)
if err != nil {
log.Fatal(err)
}
- printEnvList(app2, *environment, cfg.ExecDelivery, envVarsFromAPI(cfg.Vars))
- return
+ l = bundleListing{App: app2, Version: cfg.Version, ExecDelivery: cfg.ExecDelivery}
+ for _, v := range cfg.Vars {
+ if v.Kind == kind {
+ l.Vars = append(l.Vars, listedVarOf(v.Key, v.Kind, v.Value, v.Digest))
+ }
+ }
+ } else {
+ if app == "" {
+ log.Fatal(usage)
+ }
+ layer, err := loadBundleLayer(context.Background(), openStore(), acctOf(), app, environment)
+ if err != nil {
+ log.Fatal(err)
+ }
+ l = bundleListing{App: app, Version: layer.Version, ExecDelivery: layer.Manifest.ExecDelivery}
+ for k, v := range layer.Manifest.Vars {
+ if v.Kind == kind {
+ l.Vars = append(l.Vars, listedVarOf(k, v.Kind, v.Value, appconfig.Digest(v)))
+ }
+ }
}
-
- if *app == "" {
- log.Fatal(usage)
+ l.Bundle = bundleLabel(environment)
+ if kind != "env" {
+ l.ExecDelivery = ""
}
- m, err := loadBundle(context.Background(), openStore(), acctOf(), *app, *environment)
- if err != nil {
- log.Fatal(err)
+ if l.Vars == nil {
+ l.Vars = []listedVar{}
}
- envVars := map[string]string{}
- for k, v := range m.Vars {
- if v.Kind == "env" {
- envVars[k] = v.Value
- }
+ sort.Slice(l.Vars, func(i, j int) bool { return l.Vars[i].Key < l.Vars[j].Key })
+ return l
+}
+
+func listedVarOf(key, kind, value, digest string) listedVar {
+ r := listedVar{Key: key, Kind: kind, Digest: digest}
+ if kind == "env" {
+ r.Value = &value
}
- printEnvList(*app, *environment, m.ExecDelivery, envVars)
+ return r
}
-// envVarsFromAPI narrows an apiConfig's Vars to the kind=="env" rows, keyed
-// by name — configGet's response shape for the API branch of runEnvList,
-// matching the direct branch's own map[key]value shape so printEnvList
-// prints identically regardless of mode.
-func envVarsFromAPI(vars []apiConfigVar) map[string]string {
- out := map[string]string{}
- for _, v := range vars {
- if v.Kind == "env" {
- out[v.Key] = v.Value
- }
+// listHeader is the line above a listing. The version sits in it (spec
+// §4.9) so a copy of the listing always says which state it shows.
+func listHeader(l bundleListing) string {
+ if l.Version == "" {
+ return fmt.Sprintf("%s (%s):", l.App, l.Bundle)
+ }
+ return fmt.Sprintf("%s (%s, version %s):", l.App, l.Bundle, l.Version)
+}
+
+func printListingJSON(w io.Writer, l bundleListing) {
+ enc := json.NewEncoder(w)
+ enc.SetIndent("", " ")
+ if err := enc.Encode(l); err != nil {
+ log.Fatal(err)
}
- return out
}
// printEnvList renders `env list`'s output — header line, an exec-delivery
// line when the listed bundle sets one (see appconfig.Manifest.ExecDelivery),
-// then a sorted KEY/VALUE tabwriter —
+// then a sorted KEY/VALUE table, with a DIGEST column for --digests —
// byte-identical between the direct and API branches of runEnvList, which
-// differ only in HOW they fetch execDelivery/vars.
-func printEnvList(app, environment, execDelivery string, vars map[string]string) {
- fmt.Printf("%s\n", colorFor(os.Stdout).head(fmt.Sprintf("%s (%s):", app, bundleLabel(environment))))
+// differ only in HOW they fetch the listing.
+func printEnvList(w io.Writer, l bundleListing, digests bool) {
+ fmt.Fprintf(w, "%s\n", colorFor(w).head(listHeader(l)))
// exec_delivery is printed for whichever bundle is being listed — since
// issue #195 it can be set in a named one, where it means "routes bound
// to this environment get files". A bundle SILENT on it prints nothing
// rather than the value it inherits: the listing shows what this bundle
// holds, and rendering an inherited value would make the bundle look
// like it states something it does not.
- if execDelivery != "" {
- fmt.Printf("exec-delivery: %s\n", execDelivery)
+ if l.ExecDelivery != "" {
+ fmt.Fprintf(w, "exec-delivery: %s\n", l.ExecDelivery)
}
- var keys []string
- for k := range vars {
- keys = append(keys, k)
+ t := newTable(w)
+ if digests {
+ fmt.Fprintln(t, "KEY\tVALUE\tDIGEST")
+ } else {
+ fmt.Fprintln(t, "KEY\tVALUE")
}
- sort.Strings(keys)
- w := newTable(os.Stdout)
- fmt.Fprintln(w, "KEY\tVALUE")
- for _, k := range keys {
- fmt.Fprintf(w, "%s\t%s\n", k, vars[k])
+ for _, v := range l.Vars {
+ if digests {
+ fmt.Fprintf(t, "%s\t%s\t%s\n", v.Key, *v.Value, v.Digest)
+ } else {
+ fmt.Fprintf(t, "%s\t%s\n", v.Key, *v.Value)
+ }
}
- w.Flush()
+ t.Flush()
}
// runEnvExecDelivery is `carlos env exec-delivery` — issue #18's opt-in
@@ -792,9 +977,9 @@ func runEnvSync(args []string) {
const secretsUsage = `usage: carlos secrets <command>
commands:
- set --app <a> [--environment <name>] KEY=value [KEY2=value2 ...] seal and set one or more secrets
- unset --app <a> [--environment <name>] KEY [KEY2 ...] remove secrets
- list --app <a> [--environment <name>] list a secret's key names only — never values
+ set --app <a> [--environment <name>] [--if-version <v>] KEY=value [KEY2=value2 ...] seal and set one or more secrets
+ unset --app <a> [--environment <name>] [--if-version <v>] KEY [KEY2 ...] remove secrets
+ list --app <a> [--environment <name>] [--digests] [--json] list a secret's key names only — never values
genkey mint a CARLOS_SECRETS_KEY/PUBKEY pair
fingerprint [--file <path>] print the fingerprint of the key in a host.env, never the key
@@ -812,6 +997,9 @@ it's set in this terminal's own environment, otherwise the console's own
served public key (Config.SecretsPub) if it has one — CARLOS_SECRETS_KEY
(the PRIVATE half) never leaves the box holding it either way.
genkey and fingerprint are always local, in both modes.
+versions, digests and --if-version work as for "carlos env". a secret's
+digest is taken over its sealed envelope, so it says nothing about the value
+and changes every time the secret is set, even to the same value.
for an app placed on a fleet the console serves the fleet's own key, so leave
CARLOS_SECRETS_PUBKEY unset. register that key with "carlos fleets secrets-key".
`
@@ -938,11 +1126,12 @@ func runSecretsSet(args []string) {
fs := flag.NewFlagSet("secrets set", flag.ExitOnError)
app := appFlag(fs, "")
environment := environmentFlag(fs, "named environment bundle to set in (omit for the default bundle)")
+ ifVersion := ifVersionFlag(fs)
acctRaw, acctIDRaw, regPath, acctOf := accountFlagsWithRegistry(fs)
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
- usage := "usage: carlos secrets set --app <a> [--environment <name>] [--console <origin>] KEY=value [KEY2=value2 ...]"
+ 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())
if err != nil {
@@ -1006,11 +1195,12 @@ func runSecretsSet(args []string) {
set[k] = appconfig.Var{Kind: "secret", Envelope: env, SealedTo: sealedTo}
}
res, err := sess.configApply(context.Background(), acct, app2,
- apiConfigApply{Environment: *environment, Set: set})
+ apiConfigApply{Environment: *environment, Set: set, IfVersion: *ifVersion})
if err != nil {
- log.Fatal(err)
+ fatalConfigWrite(err)
}
fmt.Printf("%s %d secret(s) for %s (%s)\n", colorFor(os.Stdout).ok("set"), len(kv), app2, bundleLabel(*environment))
+ printReceipt(os.Stdout, res.Receipt)
printRestartNotice(os.Stdout, app2, restartFromAPI(res.Restart))
return
}
@@ -1018,6 +1208,9 @@ func runSecretsSet(args []string) {
if *app == "" {
log.Fatal(usage)
}
+ if err := checkIfVersionDirect(*ifVersion); err != nil {
+ log.Fatal(err)
+ }
pub := secretsPubKey()
acct := acctOf()
store := openStore()
@@ -1139,11 +1332,12 @@ func runSecretsUnset(args []string) {
fs := flag.NewFlagSet("secrets unset", flag.ExitOnError)
app := appFlag(fs, "")
environment := environmentFlag(fs, "named environment bundle to remove from (omit for the default bundle)")
+ ifVersion := ifVersionFlag(fs)
acctRaw, acctIDRaw, regPath, acctOf := accountFlagsWithRegistry(fs)
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
- usage := "usage: carlos secrets unset --app <a> [--environment <name>] [--console <origin>] KEY [KEY2 ...]"
+ usage := "usage: carlos secrets unset --app <a> [--environment <name>] [--if-version <v>] [--console <origin>] KEY [KEY2 ...]"
if fs.NArg() == 0 {
log.Fatal(usage)
}
@@ -1158,11 +1352,12 @@ func runSecretsUnset(args []string) {
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
app2 := resolvedApp(sess, acct, *app, usage)
res, err := sess.configApply(context.Background(), acct, app2,
- apiConfigApply{Environment: *environment, Unset: fs.Args()})
+ apiConfigApply{Environment: *environment, Unset: fs.Args(), IfVersion: *ifVersion})
if err != nil {
- log.Fatal(err)
+ fatalConfigWrite(err)
}
fmt.Printf("%s %d of %d secret(s) for %s (%s)\n", colorFor(os.Stdout).ok("unset"), res.Removed, fs.NArg(), app2, bundleLabel(*environment))
+ printReceipt(os.Stdout, res.Receipt)
printRestartNotice(os.Stdout, app2, restartFromAPI(res.Restart))
return
}
@@ -1170,6 +1365,9 @@ func runSecretsUnset(args []string) {
if *app == "" {
log.Fatal(usage)
}
+ if err := checkIfVersionDirect(*ifVersion); err != nil {
+ log.Fatal(err)
+ }
store := openStore()
removed, err := unsetVars(context.Background(), store, acctOf(), *app, *environment, fs.Args())
if err != nil {
@@ -1185,62 +1383,42 @@ func runSecretsUnset(args []string) {
// printSecretsList renders `secrets list`'s output — header line, then
// sorted key names only, never values — byte-identical between the direct
// and API branches of runSecretsList, which differ only in HOW they fetch
-// the key set.
-func printSecretsList(app, environment string, keys []string) {
- fmt.Printf("%s\n", colorFor(os.Stdout).head(fmt.Sprintf("%s (%s):", app, bundleLabel(environment))))
- sort.Strings(keys)
- for _, k := range keys {
- fmt.Println(k)
+// the listing. --digests turns the names into a KEY/DIGEST table: a
+// secret's digest is over its envelope, so it says only "changed since".
+func printSecretsList(w io.Writer, l bundleListing, digests bool) {
+ fmt.Fprintf(w, "%s\n", colorFor(w).head(listHeader(l)))
+ if !digests {
+ for _, v := range l.Vars {
+ fmt.Fprintln(w, v.Key)
+ }
+ return
+ }
+ t := newTable(w)
+ fmt.Fprintln(t, "KEY\tDIGEST")
+ for _, v := range l.Vars {
+ fmt.Fprintf(t, "%s\t%s\n", v.Key, v.Digest)
}
+ t.Flush()
}
func runSecretsList(args []string) {
fs := flag.NewFlagSet("secrets list", flag.ExitOnError)
app := appFlag(fs, "")
environment := environmentFlag(fs, "named environment bundle to list (omit for the default bundle)")
+ digests := fs.Bool("digests", false, "add each secret's digest")
+ asJSON := fs.Bool("json", false, "print the bundle's secrets as JSON, with its version and every digest")
acctRaw, acctIDRaw, acctOf := accountFlags(fs)
consoleFlag := consoleOption(fs, "console origin to work through (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
- usage := "usage: carlos secrets list --app <a> [--environment <name>] [--console <origin>]"
+ usage := "usage: carlos secrets list --app <a> [--environment <name>] [--digests] [--json] [--console <origin>]"
checkEnvironmentFlag(*environment)
-
- sess, err := resolveMode(*consoleFlag)
- if err != nil {
- log.Fatal(err)
- }
- if sess != nil {
- printUsing(os.Stdout, sess)
- acct := resolvedAccount(sess, acctRaw, acctIDRaw)
- app2 := resolvedApp(sess, acct, *app, usage)
- cfg, err := sess.configGet(context.Background(), acct, app2, *environment)
- if err != nil {
- log.Fatal(err)
- }
- var keys []string
- for _, v := range cfg.Vars {
- if v.Kind == "secret" {
- keys = append(keys, v.Key)
- }
- }
- printSecretsList(app2, *environment, keys)
+ l := loadListing(*app, *environment, acctRaw, acctIDRaw, acctOf, *consoleFlag, usage, "secret", !*asJSON)
+ if *asJSON {
+ printListingJSON(os.Stdout, l)
return
}
-
- if *app == "" {
- log.Fatal(usage)
- }
- m, err := loadBundle(context.Background(), openStore(), acctOf(), *app, *environment)
- if err != nil {
- log.Fatal(err)
- }
- var keys []string
- for k, v := range m.Vars {
- if v.Kind == "secret" {
- keys = append(keys, k)
- }
- }
- printSecretsList(*app, *environment, keys)
+ printSecretsList(os.Stdout, l, *digests)
}
func runSecretsGenkey(args []string) {
@@ -1405,3 +1583,167 @@ func requireEnvConsoleSession(verb, consoleFlag string) *apiSession {
}
return sess
}
+
+// runEnvEffective is `carlos env effective`: for one route, every key it
+// gets from the stored layers, which layer it comes from and which lower
+// layers it hides (#522 §4.4). Console only: the route's environment comes
+// from its instance record, which the console reads with the gate in front
+// of it. Values set on the box itself (an exec route's own <host>.env, the
+// agent's control vars) are not in the bucket and are not shown.
+func runEnvEffective(args []string) {
+ fs := flag.NewFlagSet("env effective", flag.ExitOnError)
+ app := appFlag(fs, "")
+ host := fs.String("host", "", "the route to show (one of the app's hosts)")
+ asJSON := fs.Bool("json", false, "print the console's answer as JSON")
+ acctRaw, acctIDRaw, _ := accountFlags(fs)
+ consoleFlag := consoleOption(fs, "console origin to work through (default: the only logged-in one)")
+ fs.Usage = flagUsage(fs, "")
+ fs.Parse(args)
+ usage := "usage: carlos env effective --app <a> --host <h> [--json] [--console <origin>]"
+ if *host == "" || fs.NArg() != 0 {
+ log.Fatal(usage)
+ }
+ sess, err := resolveMode(*consoleFlag)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if sess == nil {
+ log.Fatal(effectiveCopyDirect)
+ }
+ if !*asJSON {
+ printUsing(os.Stdout, sess)
+ }
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ app2 := resolvedApp(sess, acct, *app, usage)
+ e, err := sess.configEffective(context.Background(), acct, app2, *host)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if *asJSON {
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetIndent("", " ")
+ if err := enc.Encode(e); err != nil {
+ log.Fatal(err)
+ }
+ return
+ }
+ printEffective(os.Stdout, e)
+}
+
+// printEffective renders the effective view: a header naming the route and
+// its environment, each layer's version, then one row per key. A layer that
+// is no part of the merge is left out, as the console leaves it out.
+func printEffective(w io.Writer, e apiConfigEffective) {
+ c := colorFor(w)
+ env := e.Environment
+ if env == "" {
+ env = "no environment"
+ }
+ if e.Owned {
+ env += ", owned by a team"
+ }
+ fmt.Fprintf(w, "%s\n", c.head(fmt.Sprintf("%s (%s):", e.Host, env)))
+ t := newTable(w)
+ fmt.Fprintln(t, "LAYER\tVERSION")
+ for _, l := range []struct {
+ name string
+ v *apiLayerVersion
+ }{{appconfig.FromDefault, e.Layers.Default}, {appconfig.FromEnvironment, e.Layers.Environment}, {appconfig.FromOverlay, e.Layers.Overlay}} {
+ if l.v != nil {
+ fmt.Fprintf(t, "%s\t%s\n", l.name, l.v.Version)
+ }
+ }
+ t.Flush()
+ fmt.Fprintln(w)
+ t = newTable(w)
+ fmt.Fprintln(t, "KEY\tKIND\tFROM\tHIDES\tVALUE")
+ for _, v := range e.Vars {
+ value := ""
+ if v.Value != nil {
+ value = *v.Value
+ }
+ fmt.Fprintf(t, "%s\t%s\t%s\t%s\t%s\n", v.Key, v.Kind, v.From, strings.Join(v.Shadows, ", "), value)
+ }
+ t.Flush()
+}
+
+// digestInput is `carlos env digest`'s flags, split out so the checks can be
+// tested without a process exit.
+type digestInput struct {
+ kind, value string
+ valueSet bool // --value given, so "" is a value rather than a missing flag
+ envelopeFile string
+ sealedTo string
+}
+
+// The digest verb's refusals.
+const (
+ digestCopyKind = `--kind must be "env" or "secret"`
+ digestCopyNeedValue = "--kind env needs --value"
+ digestCopyEnvOnly = "--envelope-file and --sealed-to are for --kind secret"
+ digestCopyNeedEnvelope = "--kind secret needs --envelope-file"
+ digestCopySecretNoValue = "--value is for --kind env. for a secret, pass the sealed envelope with --envelope-file"
+ digestCopyEmptyEnvelope = "%s is empty. it should hold the envelope that was sent"
+)
+
+// envDigest is appconfig.Digest of the var the flags describe: exactly the
+// fields the console stores, so the answer matches the digest in a receipt
+// or a listing for the same var (#522 §4.7 step 3). The envelope file is
+// trimmed because a saved envelope usually ends in a newline that was never
+// part of it.
+func envDigest(in digestInput) (string, error) {
+ switch in.kind {
+ case "env":
+ if in.envelopeFile != "" || in.sealedTo != "" {
+ return "", errors.New(digestCopyEnvOnly)
+ }
+ if !in.valueSet {
+ return "", errors.New(digestCopyNeedValue)
+ }
+ return appconfig.Digest(appconfig.Var{Kind: "env", Value: in.value}), nil
+ case "secret":
+ if in.valueSet {
+ return "", errors.New(digestCopySecretNoValue)
+ }
+ if in.envelopeFile == "" {
+ return "", errors.New(digestCopyNeedEnvelope)
+ }
+ raw, err := os.ReadFile(in.envelopeFile)
+ if err != nil {
+ return "", err
+ }
+ envelope := strings.TrimSpace(string(raw))
+ if envelope == "" {
+ return "", fmt.Errorf(digestCopyEmptyEnvelope, in.envelopeFile)
+ }
+ return appconfig.Digest(appconfig.Var{Kind: "secret", Envelope: envelope, SealedTo: in.sealedTo}), nil
+ }
+ return "", errors.New(digestCopyKind)
+}
+
+// runEnvDigest is `carlos env digest`. Local in both modes: it reads nothing
+// but its own flags and the envelope file.
+func runEnvDigest(args []string) {
+ fs := flag.NewFlagSet("env digest", flag.ExitOnError)
+ kind := fs.String("kind", "", `"env" for a plain var, "secret" for a sealed one`)
+ value := fs.String("value", "", "the plain var's value (--kind env)")
+ envelopeFile := fs.String("envelope-file", "", "a file holding the sealed envelope that was sent (--kind secret)")
+ sealedTo := fs.String("sealed-to", "", "the fingerprint the secret was sealed to, as sent in sealed_to (--kind secret). carlos secrets set always sends one")
+ fs.Usage = flagUsage(fs, "usage: carlos env digest --kind env --value <v>\n or: carlos env digest --kind secret --envelope-file <path> [--sealed-to <fp>]")
+ fs.Parse(args)
+ if fs.NArg() != 0 {
+ fs.Usage()
+ os.Exit(2)
+ }
+ in := digestInput{kind: *kind, value: *value, envelopeFile: *envelopeFile, sealedTo: *sealedTo}
+ fs.Visit(func(f *flag.Flag) {
+ if f.Name == "value" {
+ in.valueSet = true
+ }
+ })
+ d, err := envDigest(in)
+ if err != nil {
+ log.Fatalf("env digest: %v", err)
+ }
+ fmt.Println(d)
+}
diff --git a/appconfig_cli_test.go b/appconfig_cli_test.go
new file mode 100644
index 000000000..64b8b50f9
--- /dev/null
+++ b/appconfig_cli_test.go
@@ -0,0 +1,335 @@
+// The CLI side of config versions, digests and receipts (#522 plan 1, spec
+// §4.9): what env/secrets list, set and unset print, and the effective and
+// digest verbs.
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// listConsole is a logged-in console whose config GET answers body, and
+// whose PUT answers put; it returns nothing because the verbs print.
+func listConsole(t *testing.T, body map[string]any, put string) {
+ t.Helper()
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPut {
+ io.WriteString(w, put)
+ return
+ }
+ json.NewEncoder(w).Encode(body)
+ }))
+ t.Cleanup(ts.Close)
+ loginTo(t, ts.URL, "vicky@keymail.dev")
+}
+
+var listBody = map[string]any{
+ "bundle": "default",
+ "version": "cv1:aaaa",
+ "environments": []string{},
+ "vars": []map[string]any{
+ {"key": "LOG_LEVEL", "kind": "env", "value": "info", "digest": "vd1:1111"},
+ {"key": "BANK_KEY", "kind": "secret", "digest": "vd1:2222"},
+ },
+}
+
+func TestEnvListPrintsVersion(t *testing.T) {
+ listConsole(t, listBody, "")
+ out := runCapturingRealStdout(t, func() {
+ runEnvList([]string{"-app", "titogo", "-account", apiTestAccount})
+ })
+ if !strings.Contains(out, "titogo (default, version cv1:aaaa):") {
+ t.Fatalf("stdout = %q, want the version in the header line", out)
+ }
+ if strings.Contains(out, "vd1:1111") {
+ t.Fatalf("stdout = %q, digests shown without --digests", out)
+ }
+}
+
+// An older console sends no version: the header is today's, not one with an
+// empty version in it.
+func TestEnvListOlderConsoleHeader(t *testing.T) {
+ old := map[string]any{"bundle": "default", "environments": []string{}, "vars": []any{}}
+ listConsole(t, old, "")
+ out := runCapturingRealStdout(t, func() {
+ runEnvList([]string{"-app", "titogo", "-account", apiTestAccount})
+ })
+ if !strings.Contains(out, "titogo (default):") || strings.Contains(out, "version") {
+ t.Fatalf("stdout = %q, want the old header", out)
+ }
+}
+
+func TestEnvListDigestsColumn(t *testing.T) {
+ listConsole(t, listBody, "")
+ out := runCapturingRealStdout(t, func() {
+ runEnvList([]string{"-app", "titogo", "-account", apiTestAccount, "--digests"})
+ })
+ if !strings.Contains(out, "DIGEST") || !strings.Contains(out, "vd1:1111") {
+ t.Fatalf("stdout = %q, want a digest column", out)
+ }
+ if strings.Contains(out, "vd1:2222") || strings.Contains(out, "BANK_KEY") {
+ t.Fatalf("stdout = %q, env list shows a secret", out)
+ }
+ out = runCapturingRealStdout(t, func() {
+ runSecretsList([]string{"-app", "titogo", "-account", apiTestAccount, "--digests"})
+ })
+ if !strings.Contains(out, "version cv1:aaaa") || !strings.Contains(out, "BANK_KEY") || !strings.Contains(out, "vd1:2222") || strings.Contains(out, "LOG_LEVEL") {
+ t.Fatalf("secrets list --digests = %q", out)
+ }
+}
+
+func TestEnvListJSON(t *testing.T) {
+ listConsole(t, listBody, "")
+ out := runCapturingRealStdout(t, func() {
+ runEnvList([]string{"-app", "titogo", "-account", apiTestAccount, "--json"})
+ })
+ var got struct {
+ App, Bundle, Version string
+ Vars []struct{ Key, Kind, Value, Digest string }
+ }
+ 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)
+ }
+ out = runCapturingRealStdout(t, func() {
+ runSecretsList([]string{"-app", "titogo", "-account", apiTestAccount, "--json"})
+ })
+ var sec map[string]any
+ if err := json.Unmarshal([]byte(out), &sec); err != nil {
+ t.Fatalf("secrets list --json %q: %v", out, err)
+ }
+ vars := sec["vars"].([]any)
+ row := vars[0].(map[string]any)
+ if sec["version"] != "cv1:aaaa" || len(vars) != 1 || row["key"] != "BANK_KEY" || row["digest"] != "vd1:2222" {
+ t.Fatalf("secrets json = %v", sec)
+ }
+ if _, has := row["value"]; has {
+ t.Fatalf("a secret row carries a value field: %v", row)
+ }
+}
+
+// Bucket mode reads the layer once and prints its version from those bytes,
+// and its digests are appconfig.Digest of the stored vars.
+func TestEnvListBucketModeVersion(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ dir := t.TempDir()
+ t.Setenv("CARLOS_DEPLOYMENT_DIR", dir)
+ st := release.NewDirStore(dir)
+ if err := appconfig.SetEnv(context.Background(), st, "bab", "titogo", map[string]string{"LOG_LEVEL": "info"}); 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", "--digests"})
+ })
+ want := appconfig.Digest(appconfig.Var{Kind: "env", Value: "info"})
+ if !strings.Contains(out, "version "+layer.Version) || !strings.Contains(out, want) {
+ t.Fatalf("stdout = %q, want version %s and digest %s", out, layer.Version, want)
+ }
+ out = runCapturingRealStdout(t, func() {
+ runEnvList([]string{"-app", "titogo", "-account", "bab", "-environment", "nothing-here"})
+ })
+ if !strings.Contains(out, "version none") {
+ t.Fatalf("absent environment: stdout = %q, want version none", out)
+ }
+}
+
+func TestIfVersionRefusedInBucketMode(t *testing.T) {
+ if err := checkIfVersionDirect(""); err != nil {
+ t.Fatalf("no --if-version refused: %v", err)
+ }
+ err := checkIfVersionDirect("cv1:aaaa")
+ if err == nil || !strings.Contains(err.Error(), "--if-version") || strings.Contains(err.Error(), "\n") {
+ t.Fatalf("err = %v, want a one-line refusal naming --if-version", err)
+ }
+}
+
+const receiptChanged = `{"result":"ok","removed":0,"receipt":{"bundle":"default","version_before":"cv1:aaaa","version_after":"cv1:bbbb",
+ "changed":true,"set":["A","B"],"unset":[],"unset_absent":[],"digests":{"A":"vd1:a","B":"vd1:b"}}}`
+
+func TestEnvSetPrintsReceipt(t *testing.T) {
+ listConsole(t, listBody, receiptChanged)
+ out := runCapturingRealStdout(t, func() {
+ runEnvSet([]string{"-app", "titogo", "-account", apiTestAccount, "--if-version", "cv1:aaaa", "A=1", "B=2"})
+ })
+ for _, want := range []string{"set: A, B", "version cv1:bbbb, was cv1:aaaa"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("stdout = %q, want %q", out, want)
+ }
+ }
+ if strings.Contains(out, "nothing changed") {
+ t.Fatalf("stdout = %q says nothing changed", out)
+ }
+}
+
+func TestEnvSetUnchangedSaysSo(t *testing.T) {
+ listConsole(t, listBody, `{"result":"ok","removed":0,"receipt":{"bundle":"default","version_before":"cv1:aaaa","version_after":"cv1:aaaa",
+ "changed":false,"set":["LOG_LEVEL"],"unset":[],"unset_absent":[],"digests":{"LOG_LEVEL":"vd1:1111"}}}`)
+ out := runCapturingRealStdout(t, func() {
+ runEnvSet([]string{"-app", "titogo", "-account", apiTestAccount, "LOG_LEVEL=info"})
+ })
+ if !strings.Contains(out, "nothing changed") || !strings.Contains(out, "cv1:aaaa") {
+ t.Fatalf("stdout = %q, want it to say nothing changed", out)
+ }
+}
+
+func TestEnvUnsetPrintsReceiptNames(t *testing.T) {
+ listConsole(t, listBody, `{"result":"ok","removed":1,"receipt":{"bundle":"prod","version_before":"cv1:aaaa","version_after":"cv1:bbbb",
+ "changed":true,"set":[],"unset":["OLD"],"unset_absent":["NEVER"],"digests":{},
+ "others":{"default":{"before":"cv1:d1","after":"cv1:d2"}}}}`)
+ out := runCapturingRealStdout(t, func() {
+ runEnvUnset([]string{"-app", "titogo", "-account", apiTestAccount, "-environment", "prod", "OLD", "NEVER"})
+ })
+ for _, want := range []string{"removed: OLD", "not there: NEVER", "the default bundle changed while this was written"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("stdout = %q, want %q", out, want)
+ }
+ }
+}
+
+const effectiveBody = `{"host":"shop.example.com","environment":"prod","owned":false,
+ "layers":{"default":{"version":"cv1:dddd"},"environment":{"name":"prod","version":"cv1:eeee"},"overlay":{"version":"none"}},
+ "vars":[{"key":"DATABASE_URL","kind":"secret","digest":"vd1:s","from":"environment","shadows":["default"]},
+ {"key":"LOG_LEVEL","kind":"env","digest":"vd1:l","from":"default","value":"info","shadows":[]}]}`
+
+func effectiveConsole(t *testing.T) *string {
+ t.Helper()
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ var gotURI string
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotURI = r.URL.RequestURI()
+ io.WriteString(w, effectiveBody)
+ }))
+ t.Cleanup(ts.Close)
+ loginTo(t, ts.URL, "vicky@keymail.dev")
+ return &gotURI
+}
+
+func TestEnvEffectiveTable(t *testing.T) {
+ uri := effectiveConsole(t)
+ out := runCapturingRealStdout(t, func() {
+ runEnvEffective([]string{"-app", "titogo", "-account", apiTestAccount, "--host", "shop.example.com"})
+ })
+ if *uri != "/api/cli/apps/"+apiTestAccount+"/titogo/config/effective?host=shop.example.com" {
+ t.Fatalf("uri = %q", *uri)
+ }
+ for _, want := range []string{"shop.example.com (prod):", "cv1:dddd", "cv1:eeee", "none", "FROM", "HIDES"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("stdout = %q, want %q", out, want)
+ }
+ }
+ var dbLine, logLine string
+ for _, l := range strings.Split(out, "\n") {
+ switch {
+ case strings.HasPrefix(l, "DATABASE_URL"):
+ dbLine = l
+ case strings.HasPrefix(l, "LOG_LEVEL"):
+ logLine = l
+ }
+ }
+ if !strings.Contains(dbLine, "environment") || !strings.Contains(dbLine, "default") || !strings.Contains(logLine, "info") {
+ t.Fatalf("rows = %q / %q", dbLine, logLine)
+ }
+}
+
+func TestEnvEffectiveJSON(t *testing.T) {
+ effectiveConsole(t)
+ out := runCapturingRealStdout(t, func() {
+ runEnvEffective([]string{"-app", "titogo", "-account", apiTestAccount, "--host", "shop.example.com", "--json"})
+ })
+ var got, want any
+ if err := json.Unmarshal([]byte(out), &got); err != nil {
+ t.Fatalf("stdout %q: %v", out, err)
+ }
+ if err := json.Unmarshal([]byte(effectiveBody), &want); err != nil {
+ t.Fatal(err)
+ }
+ g, _ := json.Marshal(got)
+ w, _ := json.Marshal(want)
+ if string(g) != string(w) {
+ t.Fatalf("--json = %s\nwant the console's answer %s", g, w)
+ }
+}
+
+func TestEnvDigestMatchesAppconfig(t *testing.T) {
+ out := runCapturingRealStdout(t, func() {
+ runEnvDigest([]string{"--kind", "env", "--value", "info"})
+ })
+ if want := appconfig.Digest(appconfig.Var{Kind: "env", Value: "info"}) + "\n"; out != want {
+ t.Fatalf("stdout = %q, want %q", out, want)
+ }
+}
+
+// A secret's digest is over the envelope and the fingerprint it was sealed
+// to, so --sealed-to is what makes it match what secrets set stored.
+func TestEnvDigestSecretMatchesStored(t *testing.T) {
+ _, pubB64, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := appconfig.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ stored, err := appconfig.NewSealer(pub, appconfig.Binding{Account: "bab", App: "titogo"}, false).
+ Seal(appconfig.Binding{Account: "bab", App: "titogo"}, []byte("hunter2"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := t.TempDir() + "/envelope"
+ if err := os.WriteFile(path, []byte("\n"+stored.Envelope+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ got, err := envDigest(digestInput{kind: "secret", envelopeFile: path, sealedTo: stored.SealedTo})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != appconfig.Digest(stored) {
+ t.Fatalf("digest = %s, want the stored var's %s", got, appconfig.Digest(stored))
+ }
+}
+
+func TestEnvDigestRefusals(t *testing.T) {
+ path := t.TempDir() + "/empty"
+ if err := os.WriteFile(path, []byte(" \n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ for _, in := range []digestInput{
+ {},
+ {kind: "plain", value: "x", valueSet: true},
+ {kind: "env"},
+ {kind: "env", value: "x", valueSet: true, envelopeFile: path},
+ {kind: "env", value: "x", valueSet: true, sealedTo: "fp"},
+ {kind: "secret"},
+ {kind: "secret", envelopeFile: path, value: "x", valueSet: true},
+ {kind: "secret", envelopeFile: path},
+ {kind: "secret", envelopeFile: path + "-missing"},
+ } {
+ if d, err := envDigest(in); err == nil {
+ t.Errorf("envDigest(%+v) = %s, want a refusal", in, d)
+ }
+ }
+ // An empty plain value is a value.
+ if d, err := envDigest(digestInput{kind: "env", valueSet: true}); err != nil || d != appconfig.Digest(appconfig.Var{Kind: "env"}) {
+ t.Fatalf("empty value: %s, %v", d, err)
+ }
+}