carlos / platform Public

appconfig: config versions and digests (#522 plan 1 task 1)

Version names a layer by the SHA-256 of its stored bytes ("none" when the
object is absent), Digest names one var over its four stored fields, and
LoadLayer reads a bundle once and returns the manifest with the version of
those exact bytes, refusing a newer schema as getIfExistsAtETag does.
BundleKey picks the default or named-environment key.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d730277e5ceb55b21ca31aded7197dd3c5571a57 parent ea02b30
2 files changed, +270 −0
  • internal/appconfig/observe.go +118 −0
  • internal/appconfig/observe_test.go +152 −0

CI failed — run details

diff --git a/internal/appconfig/observe.go b/internal/appconfig/observe.go
new file mode 100644
index 000000000..c377d1f94
--- /dev/null
+++ b/internal/appconfig/observe.go
@@ -0,0 +1,118 @@
+// Versions and digests: how a config layer and a single var are named for
+// the console's receipts (#522). Both are computed from bytes this binary
+// read, never from the store's etag, so two reads of unchanged bytes agree
+// on every backend (a store is free to hand back a different etag for the
+// same content, or none).
+package appconfig
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// VersionNone is the version of a layer that has no object at all. It is
+// distinct from every real version, including that of an existing empty
+// manifest: "never configured" and "configured, then fully unset" are
+// different states (see getIfExists).
+const VersionNone = "none"
+
+// Version names a layer by the bytes of its stored object. found==false is an
+// absent object and gives VersionNone; found with zero bytes still hashes, so
+// an existing-but-empty object never reads as absent. The "cv1:" prefix
+// versions the scheme so a later change of hash cannot be mistaken for a
+// content change.
+func Version(raw []byte, found bool) string {
+ if !found {
+ return VersionNone
+ }
+ sum := sha256.Sum256(raw)
+ return "cv1:" + hex.EncodeToString(sum[:])
+}
+
+// digestDomain separates var digests from every other SHA-256 this package
+// computes, and is the "v1" in the scheme.
+const digestDomain = "carlos.config.var.v1"
+
+// Digest names one var's stored state: a hash over its four stored fields,
+// NUL-separated so no field can bleed into its neighbour. For a secret the
+// input is the envelope, which sealing randomises, so the digest says
+// nothing about the plaintext and re-sealing the same plaintext reads as a
+// change (accurately: somebody wrote it). For a plain var it includes the
+// value, which whoever holds the digest can already read.
+func Digest(v Var) string {
+ h := sha256.New()
+ for i, f := range []string{digestDomain, v.Kind, v.Value, v.Envelope, v.SealedTo} {
+ if i > 0 {
+ h.Write([]byte{0})
+ }
+ h.Write([]byte(f))
+ }
+ return "vd1:" + hex.EncodeToString(h.Sum(nil))
+}
+
+// Digests is Digest over every var in m, keyed by var name. A nil manifest
+// gives an empty, non-nil map so callers can range and encode it without a
+// check.
+func Digests(m *Manifest) map[string]string {
+ out := map[string]string{}
+ if m == nil {
+ return out
+ }
+ for name, v := range m.Vars {
+ out[name] = Digest(v)
+ }
+ return out
+}
+
+// Layer is one config bundle as read from the bucket: the manifest, whether
+// an object existed, and the Version of the exact bytes the manifest was
+// parsed from. Version and Manifest come from a single read so they cannot
+// disagree.
+type Layer struct {
+ Version string
+ Found bool
+ Manifest *Manifest // empty but non-nil when the layer is absent
+}
+
+// LoadLayer reads key once and returns it with the version of those raw
+// bytes. An absent object is a valid layer (VersionNone, an empty manifest),
+// not an error. It refuses a newer-schema manifest exactly as
+// getIfExistsAtETag does: unmarshalling has already dropped fields this
+// binary does not know, so a version taken over them would describe a layer
+// the caller cannot see.
+func LoadLayer(ctx context.Context, s release.Store, key, app string) (Layer, error) {
+ raw, _, err := s.Get(ctx, key)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return Layer{
+ Version: VersionNone,
+ Manifest: &Manifest{Schema: 1, App: app, Vars: map[string]Var{}},
+ }, nil
+ }
+ return Layer{}, err
+ }
+ var m Manifest
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return Layer{}, fmt.Errorf("config %s: %w", key, err)
+ }
+ if m.Schema > MaxSchema {
+ return Layer{}, fmt.Errorf("config %s: schema %d is newer than this binary understands — upgrade carlos", key, m.Schema)
+ }
+ return Layer{Version: Version(raw, true), Found: true, Manifest: &m}, nil
+}
+
+// BundleKey is the bucket key of a config bundle: the default bundle for
+// envName "", the named environment otherwise.
+func BundleKey(acct, app, envName string) string {
+ if envName == "" {
+ return Key(acct, app)
+ }
+ return EnvironmentKey(acct, app, envName)
+}
diff --git a/internal/appconfig/observe_test.go b/internal/appconfig/observe_test.go
new file mode 100644
index 000000000..ba50bb582
--- /dev/null
+++ b/internal/appconfig/observe_test.go
@@ -0,0 +1,152 @@
+package appconfig
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestVersionAbsentIsNone(t *testing.T) {
+ if got := Version(nil, false); got != "none" {
+ t.Fatalf("Version(nil, false) = %q, want none", got)
+ }
+}
+
+func TestVersionIsHashOfBytes(t *testing.T) {
+ want := "cv1:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
+ if got := Version([]byte("abc"), true); got != want {
+ t.Fatalf("Version(abc) = %q, want %q", got, want)
+ }
+}
+
+func TestVersionEmptyObjectIsNotNone(t *testing.T) {
+ got := Version([]byte{}, true)
+ if got == VersionNone || !strings.HasPrefix(got, "cv1:") {
+ t.Fatalf("Version(empty, true) = %q, want a cv1: version", got)
+ }
+}
+
+func TestDigestPinned(t *testing.T) {
+ sum := sha256.Sum256([]byte("carlos.config.var.v1\x00env\x00info\x00\x00"))
+ want := "vd1:" + hex.EncodeToString(sum[:])
+ if got := Digest(Var{Kind: "env", Value: "info"}); got != want {
+ t.Fatalf("Digest = %q, want %q", got, want)
+ }
+}
+
+func TestDigestSecretUsesEnvelope(t *testing.T) {
+ _, pubB64, err := GenerateKey()
+ if err != nil {
+ t.Fatalf("GenerateKey: %v", err)
+ }
+ pub, err := ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatalf("ParsePublicKey: %v", err)
+ }
+ b := Binding{Account: "acct", App: "shop"}
+ e1, err := Seal(pub, b, []byte("hunter2"))
+ if err != nil {
+ t.Fatalf("Seal: %v", err)
+ }
+ e2, err := Seal(pub, b, []byte("hunter2"))
+ if err != nil {
+ t.Fatalf("Seal: %v", err)
+ }
+ d1 := Digest(Var{Kind: "secret", Envelope: e1})
+ d2 := Digest(Var{Kind: "secret", Envelope: e2})
+ if d1 == d2 {
+ t.Fatalf("two seals of one plaintext share a digest %q", d1)
+ }
+ if plain := Digest(Var{Kind: "secret", Value: "hunter2"}); d1 == plain || d2 == plain {
+ t.Fatalf("secret digest equals a digest built from the plaintext")
+ }
+}
+
+func TestDigestKindMatters(t *testing.T) {
+ if a, b := Digest(Var{Kind: "env", Value: "x"}), Digest(Var{Kind: "secret", Envelope: "x"}); a == b {
+ t.Fatalf("env value and secret envelope with the same string share digest %q", a)
+ }
+}
+
+func TestDigestsNilSafe(t *testing.T) {
+ got := Digests(nil)
+ if got == nil || len(got) != 0 {
+ t.Fatalf("Digests(nil) = %#v, want empty non-nil map", got)
+ }
+ m := &Manifest{Vars: map[string]Var{"A": {Kind: "env", Value: "1"}}}
+ if got := Digests(m); len(got) != 1 || got["A"] != Digest(m.Vars["A"]) {
+ t.Fatalf("Digests = %#v", got)
+ }
+}
+
+func TestBundleKey(t *testing.T) {
+ if got := BundleKey("acct", "shop", ""); got != Key("acct", "shop") {
+ t.Fatalf("default bundle key = %q", got)
+ }
+ if got := BundleKey("acct", "shop", "staging"); got != EnvironmentKey("acct", "shop", "staging") {
+ t.Fatalf("named bundle key = %q", got)
+ }
+}
+
+func TestLoadLayerStableAcrossReads(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ if _, err := Apply(ctx, s, "acct", "shop", map[string]Var{"A": {Kind: "env", Value: "1"}}, nil); err != nil {
+ t.Fatalf("Apply: %v", err)
+ }
+ key := Key("acct", "shop")
+ l1, err := LoadLayer(ctx, s, key, "shop")
+ if err != nil {
+ t.Fatalf("LoadLayer: %v", err)
+ }
+ l2, err := LoadLayer(ctx, s, key, "shop")
+ if err != nil {
+ t.Fatalf("LoadLayer: %v", err)
+ }
+ if !l1.Found || l1.Version == VersionNone || l1.Version != l2.Version {
+ t.Fatalf("versions not stable: %+v vs %+v", l1, l2)
+ }
+ if l1.Manifest.Vars["A"].Value != "1" {
+ t.Fatalf("manifest not loaded: %+v", l1.Manifest)
+ }
+ if _, err := Apply(ctx, s, "acct", "shop", map[string]Var{"B": {Kind: "env", Value: "2"}}, nil); err != nil {
+ t.Fatalf("Apply: %v", err)
+ }
+ l3, err := LoadLayer(ctx, s, key, "shop")
+ if err != nil {
+ t.Fatalf("LoadLayer: %v", err)
+ }
+ if l3.Version == l1.Version {
+ t.Fatalf("version did not move after a write: %q", l3.Version)
+ }
+}
+
+func TestLoadLayerAbsent(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ l, err := LoadLayer(context.Background(), s, Key("acct", "shop"), "shop")
+ if err != nil {
+ t.Fatalf("LoadLayer: %v", err)
+ }
+ if l.Version != "none" || l.Found {
+ t.Fatalf("absent layer = %+v", l)
+ }
+ if l.Manifest == nil || len(l.Manifest.Vars) != 0 {
+ t.Fatalf("absent layer manifest = %+v, want empty non-nil", l.Manifest)
+ }
+}
+
+func TestLoadLayerRefusesNewerSchema(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := Key("acct", "shop")
+ if _, err := s.Put(ctx, key, []byte(`{"schema":99,"app":"shop","vars":{}}`), ""); err != nil {
+ t.Fatalf("Put: %v", err)
+ }
+ if _, err := LoadLayer(ctx, s, key, "shop"); err == nil || !strings.Contains(err.Error(), "newer") {
+ t.Fatalf("LoadLayer on schema 99: err = %v, want newer-schema refusal", err)
+ }
+}