carlos / platform Public

edge: asset fill assertion and acknowledgement signatures

Task 1 of edge asset cache plan 3. signAssetFill/verifyAssetFill bind host,
path and query, account, app, generation and a timestamp under the mesh key in
the carlos-asset-fill-v1 domain, accepting current or next and returning the
key that matched. signAssetAck/verifyAssetAck bind the assertion and expiry in
carlos-asset-fill-ack-v1, so the home can answer under the key the far edge
signed with.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev cdb82069883f23a2caf65165ceb1ee01ed880300 parent 88db80a
2 files changed, +361 −0
  • internal/edge/assetfill.go +149 −0
  • internal/edge/assetfill_test.go +212 −0
diff --git a/internal/edge/assetfill.go b/internal/edge/assetfill.go
new file mode 100644
index 000000000..c2ab2dd4f
--- /dev/null
+++ b/internal/edge/assetfill.go
@@ -0,0 +1,149 @@
+package edge
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Asset fill signatures (edge asset cache design §5.3).
+//
+// A far edge asks a home box to fill or answer one cache entry by sending
+// X-Carlos-Asset-Fill, an assertion of exactly which entry it wants. The home
+// answers with X-Carlos-Asset-Fill-Ack, which says "I handled this as a fill
+// and did not meter it". Both are HMAC-SHA256 under the mesh key, each in its
+// own domain, so a hop signature (mesh.go) is never an assertion and an
+// assertion is never an acknowledgement.
+
+const (
+ // assetFillHeader carries the assertion on a far edge's fill request.
+ assetFillHeader = "X-Carlos-Asset-Fill"
+ // assetAckHeader carries the home's acknowledgement on the response.
+ assetAckHeader = "X-Carlos-Asset-Fill-Ack"
+ // assetExpiresHeader carries the entry's absolute expiry (unix seconds,
+ // 0 for "not storable") on the response, under the acknowledgement.
+ assetExpiresHeader = "X-Carlos-Asset-Expires"
+ // assetCacheHeader tells the client whether the cache answered:
+ // hit, miss or bypass.
+ assetCacheHeader = "Carlos-Cache"
+
+ assetFillDomain = "carlos-asset-fill-v1"
+ assetAckDomain = "carlos-asset-fill-ack-v1"
+)
+
+// assetFillClaims is what an assertion binds: the entry asked for and the
+// ownership and generation the far edge believes it has. PathQuery is the
+// request path and raw query as sent. None of the fields may contain a
+// newline, which separates them in the MAC input.
+type assetFillClaims struct {
+ Host, PathQuery, Account, App, Gen string
+}
+
+// assetFillMAC is the one place the assertion's signed bytes are built, so a
+// signer and a verifier cannot drift apart. The host goes through
+// canonicalizeHopHost like a hop's does. ok is false when a field carries a
+// newline, which would let one field's bytes pass for another's.
+func assetFillMAC(key []byte, c assetFillClaims, ts string) (mac []byte, ok bool) {
+ for _, f := range []string{c.Host, c.PathQuery, c.Account, c.App, c.Gen} {
+ if strings.Contains(f, "\n") {
+ return nil, false
+ }
+ }
+ h := hmac.New(sha256.New, key)
+ h.Write([]byte(strings.Join([]string{
+ assetFillDomain,
+ canonicalizeHopHost(c.Host),
+ c.PathQuery,
+ c.Account,
+ c.App,
+ c.Gen,
+ ts,
+ }, "\n")))
+ return h.Sum(nil), true
+}
+
+// signAssetFill produces the X-Carlos-Asset-Fill value, "<unix>:<hex>". It
+// returns "" when the claims cannot be signed (an empty key, or a newline in
+// a field); the caller then does not fill and forwards as today.
+func signAssetFill(key []byte, c assetFillClaims, now time.Time) string {
+ if len(key) == 0 {
+ return ""
+ }
+ ts := strconv.FormatInt(now.Unix(), 10)
+ mac, ok := assetFillMAC(key, c, ts)
+ if !ok {
+ return ""
+ }
+ return ts + ":" + hex.EncodeToString(mac)
+}
+
+// verifyAssetFill checks an assertion against both mirrored keys, with the
+// hop's +-hopSkew window and constant-time comparison. It returns the key
+// that verified: the home must sign its acknowledgement with that key, not
+// with signingKey, because a far edge that has not seen .next yet verifies
+// with the key it signed with.
+func verifyAssetFill(current, next []byte, c assetFillClaims, header string, now time.Time) (matched []byte, ok bool) {
+ ts, sig, found := strings.Cut(header, ":")
+ if !found || ts == "" || sig == "" {
+ return nil, false
+ }
+ sec, err := strconv.ParseInt(ts, 10, 64)
+ if err != nil {
+ return nil, false
+ }
+ skew := now.Sub(time.Unix(sec, 0))
+ if skew < 0 {
+ skew = -skew
+ }
+ if skew > hopSkew {
+ return nil, false
+ }
+ got, err := hex.DecodeString(sig)
+ if err != nil {
+ return nil, false
+ }
+ for _, key := range [][]byte{next, current} {
+ if len(key) == 0 {
+ continue
+ }
+ mac, signable := assetFillMAC(key, c, ts)
+ if signable && hmac.Equal(got, mac) {
+ return key, true
+ }
+ }
+ return nil, false
+}
+
+// assetAckMAC is the acknowledgement's MAC: the assertion exactly as the far
+// edge sent it and the decimal expiry, so neither can be swapped.
+func assetAckMAC(key []byte, assertion string, expires int64) []byte {
+ h := hmac.New(sha256.New, key)
+ h.Write([]byte(assetAckDomain))
+ h.Write([]byte("\n"))
+ h.Write([]byte(assertion))
+ h.Write([]byte("\n"))
+ h.Write([]byte(strconv.FormatInt(expires, 10)))
+ return h.Sum(nil)
+}
+
+// signAssetAck produces the X-Carlos-Asset-Fill-Ack value, hex only. expires
+// is the X-Carlos-Asset-Expires value sent beside it (0 for "not storable").
+func signAssetAck(key []byte, assertion string, expires int64) string {
+ return hex.EncodeToString(assetAckMAC(key, assertion, expires))
+}
+
+// verifyAssetAck is the far edge's check, with the key it signed the
+// assertion with. An empty key never verifies.
+func verifyAssetAck(key []byte, assertion string, expires int64, ack string) bool {
+ if len(key) == 0 {
+ return false
+ }
+ got, err := hex.DecodeString(ack)
+ if err != nil {
+ return false
+ }
+ return hmac.Equal(got, assetAckMAC(key, assertion, expires))
+}
diff --git a/internal/edge/assetfill_test.go b/internal/edge/assetfill_test.go
new file mode 100644
index 000000000..f377d949f
--- /dev/null
+++ b/internal/edge/assetfill_test.go
@@ -0,0 +1,212 @@
+package edge
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+// Not acceptance: these pin the signature primitives only. The wired fill
+// is exercised by the plan's acceptance tests.
+
+var (
+ fillKeyCurrent = []byte("0123456789abcdef0123456789abcdef")
+ fillKeyNext = []byte("fedcba9876543210fedcba9876543210")
+ fillNow = time.Unix(1_800_000_000, 0)
+)
+
+func testFillClaims() assetFillClaims {
+ return assetFillClaims{
+ Host: "shop.example.com",
+ PathQuery: "/assets/app.js?v=2",
+ Account: "acct-1",
+ App: "shop",
+ Gen: "g7",
+ }
+}
+
+func TestAssetFillRoundTrips(t *testing.T) {
+ c := testFillClaims()
+ h := signAssetFill(fillKeyCurrent, c, fillNow)
+ if h == "" {
+ t.Fatal("signAssetFill returned empty")
+ }
+ ts, sig, ok := strings.Cut(h, ":")
+ if !ok || ts == "" || sig == "" {
+ t.Fatalf("header %q is not <unix>:<hex>", h)
+ }
+ matched, ok := verifyAssetFill(fillKeyCurrent, nil, c, h, fillNow)
+ if !ok {
+ t.Fatal("a fresh assertion did not verify")
+ }
+ if string(matched) != string(fillKeyCurrent) {
+ t.Fatalf("matched key = %q, want the current key", matched)
+ }
+ // The host is canonicalized as a hop's is: case, port and a root dot do
+ // not change what is signed.
+ d := c
+ d.Host = "Shop.Example.com.:443"
+ if _, ok := verifyAssetFill(fillKeyCurrent, nil, d, h, fillNow); !ok {
+ t.Fatal("a differently spelled host did not canonicalize to the same assertion")
+ }
+ // Edges of the skew window still verify.
+ for _, off := range []time.Duration{-hopSkew, hopSkew} {
+ if _, ok := verifyAssetFill(fillKeyCurrent, nil, c, h, fillNow.Add(off)); !ok {
+ t.Fatalf("offset %v inside the skew window was refused", off)
+ }
+ }
+}
+
+func TestAssetFillRefusesEachChangedClaim(t *testing.T) {
+ base := testFillClaims()
+ h := signAssetFill(fillKeyCurrent, base, fillNow)
+ cases := []struct {
+ name string
+ mut func(c *assetFillClaims)
+ now time.Time
+ }{
+ {"host", func(c *assetFillClaims) { c.Host = "other.example.com" }, fillNow},
+ {"path-query", func(c *assetFillClaims) { c.PathQuery = "/assets/app.js?v=3" }, fillNow},
+ {"path", func(c *assetFillClaims) { c.PathQuery = "/assets/other.js?v=2" }, fillNow},
+ {"account", func(c *assetFillClaims) { c.Account = "acct-2" }, fillNow},
+ {"app", func(c *assetFillClaims) { c.App = "blog" }, fillNow},
+ {"gen", func(c *assetFillClaims) { c.Gen = "g8" }, fillNow},
+ {"empty gen", func(c *assetFillClaims) { c.Gen = "" }, fillNow},
+ {"field shift", func(c *assetFillClaims) { c.Account, c.App = "acct-1\nshop", "" }, fillNow},
+ {"timestamp past skew", func(c *assetFillClaims) {}, fillNow.Add(hopSkew + time.Second)},
+ {"timestamp before skew", func(c *assetFillClaims) {}, fillNow.Add(-hopSkew - time.Second)},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ c := base
+ tc.mut(&c)
+ if _, ok := verifyAssetFill(fillKeyCurrent, fillKeyNext, c, h, tc.now); ok {
+ t.Fatal("verified, want refused")
+ }
+ })
+ }
+ for _, bad := range []string{"", "nocolon", ":", "1800000000:", ":abcd", "x:abcd", "1800000000:zz", "1800000000:" + strings.Repeat("0", 64)} {
+ if _, ok := verifyAssetFill(fillKeyCurrent, fillKeyNext, base, bad, fillNow); ok {
+ t.Fatalf("malformed header %q verified", bad)
+ }
+ }
+ // A different key never verifies, and an empty key is never a key.
+ if _, ok := verifyAssetFill([]byte("wrong-wrong-wrong-wrong-wrong-xx"), nil, base, h, fillNow); ok {
+ t.Fatal("a different key verified")
+ }
+ if _, ok := verifyAssetFill(nil, nil, base, h, fillNow); ok {
+ t.Fatal("no keys verified")
+ }
+ // Claims that would break the newline framing are not signed at all.
+ nl := base
+ nl.App = "shop\nx"
+ if got := signAssetFill(fillKeyCurrent, nl, fillNow); got != "" {
+ t.Fatalf("signed claims carrying a newline: %q", got)
+ }
+}
+
+func TestHopSignatureIsNeverAnAssetFill(t *testing.T) {
+ c := testFillClaims()
+ hop := signHop(fillKeyCurrent, c.Host, fillNow)
+ if _, ok := verifyAssetFill(fillKeyCurrent, nil, c, hop, fillNow); ok {
+ t.Fatal("a hop signature verified as an asset fill")
+ }
+ if _, ok := verifyAssetFill(fillKeyCurrent, fillKeyNext, c, hop, fillNow); ok {
+ t.Fatal("a hop signature verified as an asset fill under two keys")
+ }
+ door := signHopDoor(fillKeyCurrent, c.Host, fillNow)
+ if _, ok := verifyAssetFill(fillKeyCurrent, nil, c, door, fillNow); ok {
+ t.Fatal("a door mark verified as an asset fill")
+ }
+ // And the converse: an assertion is not a hop.
+ fill := signAssetFill(fillKeyCurrent, c, fillNow)
+ if verifyHop(fillKeyCurrent, c.Host, fill, fillNow) {
+ t.Fatal("an asset fill verified as a hop")
+ }
+}
+
+func TestAssetFillAcceptsTheNextKey(t *testing.T) {
+ c := testFillClaims()
+ // Signed with .next (what signingKey picks the moment it exists).
+ hn := signAssetFill(signingKey(fillKeyCurrent, fillKeyNext), c, fillNow)
+ matched, ok := verifyAssetFill(fillKeyCurrent, fillKeyNext, c, hn, fillNow)
+ if !ok || string(matched) != string(fillKeyNext) {
+ t.Fatalf("next-signed assertion: ok=%v matched=%q, want next", ok, matched)
+ }
+ // Signed with current by a straggler while both are mirrored.
+ hc := signAssetFill(fillKeyCurrent, c, fillNow)
+ matched, ok = verifyAssetFill(fillKeyCurrent, fillKeyNext, c, hc, fillNow)
+ if !ok || string(matched) != string(fillKeyCurrent) {
+ t.Fatalf("current-signed assertion: ok=%v matched=%q, want current", ok, matched)
+ }
+ // With no .next mirrored, a next-signed assertion is refused.
+ if _, ok := verifyAssetFill(fillKeyCurrent, nil, c, hn, fillNow); ok {
+ t.Fatal("next-signed assertion verified with no next key")
+ }
+}
+
+func TestAssetAckBindsAssertionAndExpiry(t *testing.T) {
+ c := testFillClaims()
+ a := signAssetFill(fillKeyCurrent, c, fillNow)
+ const exp = int64(1_800_003_600)
+ ack := signAssetAck(fillKeyCurrent, a, exp)
+ if !verifyAssetAck(fillKeyCurrent, a, exp, ack) {
+ t.Fatal("a fresh acknowledgement did not verify")
+ }
+ if verifyAssetAck(fillKeyCurrent, a, exp+1, ack) {
+ t.Fatal("a changed expiry verified")
+ }
+ if verifyAssetAck(fillKeyCurrent, a, 0, ack) {
+ t.Fatal("a zero expiry verified against a non-zero acknowledgement")
+ }
+ other := signAssetFill(fillKeyCurrent, c, fillNow.Add(time.Second))
+ if verifyAssetAck(fillKeyCurrent, other, exp, ack) {
+ t.Fatal("a different assertion verified")
+ }
+ // A not-storable acknowledgement (expiry 0) is its own signed value.
+ zero := signAssetAck(fillKeyCurrent, a, 0)
+ if !verifyAssetAck(fillKeyCurrent, a, 0, zero) {
+ t.Fatal("an expiry-0 acknowledgement did not verify")
+ }
+ if verifyAssetAck(fillKeyCurrent, a, exp, zero) {
+ t.Fatal("an expiry-0 acknowledgement verified for a non-zero expiry")
+ }
+ if verifyAssetAck(fillKeyNext, a, exp, ack) {
+ t.Fatal("a different key verified")
+ }
+ for _, bad := range []string{"", "zz", ack[:len(ack)-2], ack + "00"} {
+ if verifyAssetAck(fillKeyCurrent, a, exp, bad) {
+ t.Fatalf("malformed acknowledgement %q verified", bad)
+ }
+ }
+ if verifyAssetAck(nil, a, exp, signAssetAck(nil, a, exp)) {
+ t.Fatal("an empty key verified")
+ }
+ // Neither a fill assertion's MAC nor a hop's is an acknowledgement.
+ _, hexSig, _ := strings.Cut(a, ":")
+ if verifyAssetAck(fillKeyCurrent, a, exp, hexSig) {
+ t.Fatal("the assertion's own MAC verified as its acknowledgement")
+ }
+}
+
+func TestAckUsesTheKeyTheAssertionMatched(t *testing.T) {
+ c := testFillClaims()
+ // The far edge has not yet seen .next and signs with current only.
+ assertion := signAssetFill(fillKeyCurrent, c, fillNow)
+ // The home holds both. signingKey would pick next; the ack must use the
+ // key the assertion matched instead.
+ matched, ok := verifyAssetFill(fillKeyCurrent, fillKeyNext, c, assertion, fillNow)
+ if !ok {
+ t.Fatal("assertion refused")
+ }
+ const exp = int64(1_800_003_600)
+ ack := signAssetAck(matched, assertion, exp)
+ if !verifyAssetAck(fillKeyCurrent, assertion, exp, ack) {
+ t.Fatal("the far edge could not verify an acknowledgement made with the matched key")
+ }
+ // The trap this guards: acknowledging with signingKey would not verify.
+ wrong := signAssetAck(signingKey(fillKeyCurrent, fillKeyNext), assertion, exp)
+ if verifyAssetAck(fillKeyCurrent, assertion, exp, wrong) {
+ t.Fatal("an acknowledgement under the other key verified at the far edge")
+ }
+}