db forward tasks 4 and 5: the root-signed request envelope, the queue entry check, reply keys, bound chunk and summary sealing, the result
Task 4's envelope needs Task 5's ParseReplyKey, so the plan's note applies: the two were built in one sitting. Task 4's tests failed first on the missing names, Task 5's likewise.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+657
−0
internal/dbreads/envelope.go+110 −0internal/dbreads/envelope_test.go+177 −0internal/dbreads/result.go+88 −0internal/dbreads/seal.go+184 −0internal/dbreads/seal_test.go+98 −0
diff --git a/internal/dbreads/envelope.go b/internal/dbreads/envelope.go| new file mode 100644 |
| index 000000000..3fc536284 |
| --- /dev/null |
| +++ b/internal/dbreads/envelope.go |
| @@ -0,0 +1,110 @@ |
| +package dbreads |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "errors" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// ErrEnvelope is a request this package will not sign or a box will not |
| +// accept: well signed, perhaps, but not for this id, region or moment. |
| +var ErrEnvelope = errors.New("dbreads: request refused") |
| + |
| +// Request is db-reads/<id>/request.json's payload (spec §5.5). The box |
| +// decodes it with release.VerifyRootEnvelope, which requires canonical JSON |
| +// for this exact type, so the field order here is the wire's. |
| +type Request struct { |
| + Purpose string `json:"purpose"` |
| + V int `json:"v"` |
| + ID string `json:"id"` |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| + Host string `json:"host"` |
| + Incarnation string `json:"incarnation"` |
| + Region string `json:"region"` |
| + Op string `json:"op"` |
| + SQL string `json:"sql"` |
| + At string `json:"at"` |
| + ReplyKey string `json:"reply_key"` |
| + By string `json:"by"` |
| + IssuedAt string `json:"issued_at"` |
| +} |
| + |
| +// Issued is IssuedAt as a time. |
| +func (r Request) Issued() (time.Time, error) { return time.Parse(time.RFC3339, r.IssuedAt) } |
| + |
| +// AtTime is At as a time; zero for the newest copy. |
| +func (r Request) AtTime() (time.Time, error) { |
| + if r.At == "" { |
| + return time.Time{}, nil |
| + } |
| + return time.Parse(time.RFC3339, r.At) |
| +} |
| + |
| +// ops are the operations this build serves. Plan 3 adds OpPull. |
| +var ops = map[string]bool{OpQuery: true} |
| + |
| +func (r Request) valid() bool { |
| + if r.Purpose != Purpose || r.V != 1 || !ValidID(r.ID) || !ValidRegion(r.Region) || |
| + !release.ValidAccount(r.Account) || !release.ValidApp(r.App) || !provision.ValidHostShape(r.Host) || |
| + r.Incarnation == "" || !ops[r.Op] || r.By == "" { |
| + return false |
| + } |
| + if r.Op == OpQuery && (r.SQL == "" || len(r.SQL) > MaxSQLBytes || !utf8.ValidString(r.SQL)) { |
| + return false |
| + } |
| + if _, err := r.AtTime(); err != nil { |
| + return false |
| + } |
| + if _, err := r.Issued(); err != nil { |
| + return false |
| + } |
| + _, err := ParseReplyKey(r.ReplyKey) |
| + return err == nil |
| +} |
| + |
| +// Sign is the console's half: it fills Purpose and V, refuses a request it |
| +// could not carry intact (invalid UTF-8 would be rewritten by encoding/json, |
| +// so the box would run SQL nobody typed), and signs with the root. |
| +// release.SignRootEnvelope refuses a scoped key. |
| +func Sign(sg release.Signer, req Request) ([]byte, error) { |
| + req.Purpose, req.V = Purpose, 1 |
| + if !req.valid() { |
| + return nil, ErrEnvelope |
| + } |
| + return release.SignRootEnvelope(sg, req) |
| +} |
| + |
| +// Verify is the box's half (spec §5.5): the root signature over canonical |
| +// JSON, this package's purpose, the id the object was read under, this box's |
| +// own region, and an issue time no more than PickupWindow old and Skew in the |
| +// future. The age bound is PickupWindow, not PickupWindow+Skew: InWindow |
| +// already widened the listing by Skew, and the envelope is checked against |
| +// this box's own clock. |
| +func Verify(pub ed25519.PublicKey, wire []byte, id, region string, now time.Time) (Request, error) { |
| + var req Request |
| + if err := release.VerifyRootEnvelope(pub, wire, &req); err != nil { |
| + return Request{}, err |
| + } |
| + if !req.valid() || req.ID != id || req.Region != region { |
| + return Request{}, ErrEnvelope |
| + } |
| + issued, _ := req.Issued() |
| + if issued.Before(now.Add(-PickupWindow)) || issued.After(now.Add(Skew)) { |
| + return Request{}, ErrEnvelope |
| + } |
| + return req, nil |
| +} |
| + |
| +// QueueMatches is the queue entry check (spec §5.9): the entry's region, |
| +// hour, time and id are all the envelope's, so a box's forged entry for a |
| +// real request names nothing the request does not. |
| +func QueueMatches(e QueueEntry, req Request) bool { |
| + issued, err := req.Issued() |
| + return err == nil && e.Region == req.Region && e.ID == req.ID && e.Issued.Equal(issued) && |
| + e.Hour == issued.UTC().Format(hourLayout) |
| +} |
diff --git a/internal/dbreads/envelope_test.go b/internal/dbreads/envelope_test.go| new file mode 100644 |
| index 000000000..379f1323d |
| --- /dev/null |
| +++ b/internal/dbreads/envelope_test.go |
| @@ -0,0 +1,177 @@ |
| +package dbreads |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +var testNow = time.Date(2026, 10, 22, 9, 0, 0, 0, time.UTC) |
| + |
| +func testRequest(t *testing.T) Request { |
| + t.Helper() |
| + priv, err := NewReplyKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return Request{ |
| + ID: "dbr_aaaaaaaaaaaaaaaaaaaaaaaaaa", Account: "bab", App: "shop", Host: "shop.example.com", |
| + Incarnation: "inc", Region: "uk", Op: OpQuery, SQL: "SELECT count(*) FROM orders", |
| + ReplyKey: EncodeReplyKey(priv.PublicKey()), By: "member@example.com", |
| + IssuedAt: testNow.Format(time.RFC3339), |
| + } |
| +} |
| + |
| +func rootKeys(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) { |
| + t.Helper() |
| + pub, priv, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return pub, priv |
| +} |
| + |
| +func TestEnvelopeVerifiesWhatTheRootSigned(t *testing.T) { |
| + t.Parallel() |
| + pub, priv := rootKeys(t) |
| + req := testRequest(t) |
| + wire, err := Sign(release.RootSigner(priv), req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := Verify(pub, wire, req.ID, "uk", testNow.Add(30*time.Second)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Purpose, req.V = Purpose, 1 |
| + if got != req { |
| + t.Fatalf("got %+v, want %+v", got, req) |
| + } |
| +} |
| + |
| +// T4 (spec §11.4), the envelope half: every forgery and replay the envelope |
| +// alone must stop. |
| +func TestEnvelopeRefusesForgeryAndReplay(t *testing.T) { |
| + t.Parallel() |
| + pub, priv := rootKeys(t) |
| + _, otherPriv := rootKeys(t) |
| + req := testRequest(t) |
| + good, err := Sign(release.RootSigner(priv), req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + unsigned, _ := json.Marshal(map[string]string{"payload": base64.StdEncoding.EncodeToString([]byte(`{}`)), "sig": ""}) |
| + wrongKey, err := Sign(release.RootSigner(otherPriv), req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cases := []struct { |
| + name string |
| + wire []byte |
| + id string |
| + region string |
| + now time.Time |
| + }{ |
| + {"unsigned", unsigned, req.ID, "uk", testNow}, |
| + {"wrong key", wrongKey, req.ID, "uk", testNow}, |
| + {"moved to another id", good, "dbr_bbbbbbbbbbbbbbbbbbbbbbbbbb", "uk", testNow}, |
| + {"moved to another region", good, req.ID, "ie", testNow}, |
| + {"older than the window", good, req.ID, "uk", testNow.Add(61 * time.Second)}, |
| + {"from the future", good, req.ID, "uk", testNow.Add(-61 * time.Second)}, |
| + } |
| + for _, c := range cases { |
| + if _, err := Verify(pub, c.wire, c.id, c.region, c.now); !errors.Is(err, ErrEnvelope) && !errors.Is(err, release.ErrRootEnvelope) { |
| + t.Errorf("%s: Verify = %v, want a refusal", c.name, err) |
| + } |
| + } |
| +} |
| + |
| +// A scoped release key cannot sign: the console that holds only one cannot |
| +// forward (spec §5.5). |
| +func TestEnvelopeScopedKeyCannotSign(t *testing.T) { |
| + t.Parallel() |
| + rootPub, rootPriv := rootKeys(t) |
| + seed, grant, err := release.MintKeyGrant(rootPriv, "ci", []string{"canary"}, time.Hour) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + key, err := release.ParseSigningKey(seed, "scoped") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sg, err := release.ScopedSigner(key, grant, rootPub) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := Sign(sg, testRequest(t)); !errors.Is(err, release.ErrRootEnvelope) { |
| + t.Fatalf("a scoped key signed: %v", err) |
| + } |
| +} |
| + |
| +func TestEnvelopeRefusesWhatItCannotCarry(t *testing.T) { |
| + t.Parallel() |
| + _, priv := rootKeys(t) |
| + for name, mut := range map[string]func(*Request){ |
| + "bad id": func(r *Request) { r.ID = "run_aaaaaaaaaaaaaaaaaaaaaaaaaa" }, |
| + "fleet region": func(r *Request) { r.Region = "fleet/acme" }, |
| + "bad host": func(r *Request) { r.Host = "../../etc" }, |
| + "bad op": func(r *Request) { r.Op = "shell" }, |
| + "empty sql": func(r *Request) { r.SQL = "" }, |
| + "huge sql": func(r *Request) { r.SQL = strings.Repeat("x", MaxSQLBytes+1) }, |
| + "invalid utf-8": func(r *Request) { r.SQL = "SELECT '\xff'" }, |
| + "bad at": func(r *Request) { r.At = "yesterday" }, |
| + "bad reply key": func(r *Request) { r.ReplyKey = "AAAA" }, |
| + "bad issued_at": func(r *Request) { r.IssuedAt = "now" }, |
| + } { |
| + req := testRequest(t) |
| + mut(&req) |
| + if _, err := Sign(release.RootSigner(priv), req); !errors.Is(err, ErrEnvelope) { |
| + t.Errorf("%s: Sign = %v", name, err) |
| + } |
| + } |
| +} |
| + |
| +// Review Focus 1: the SQL a person typed is the SQL the box runs. |
| +func TestEnvelopeSQLRoundTripsByteForByte(t *testing.T) { |
| + t.Parallel() |
| + pub, priv := rootKeys(t) |
| + req := testRequest(t) |
| + req.SQL = "SELECT '<a href=\"x\">&</a>' || char(10) || ' é' WHERE 1 < 2 AND 3 > 2" |
| + wire, err := Sign(release.RootSigner(priv), req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := Verify(pub, wire, req.ID, "uk", testNow) |
| + if err != nil || got.SQL != req.SQL { |
| + t.Fatalf("Verify = %q, %v", got.SQL, err) |
| + } |
| +} |
| + |
| +func TestQueueMatchesNeedsEveryPart(t *testing.T) { |
| + t.Parallel() |
| + req := testRequest(t) |
| + issued, _ := req.Issued() |
| + good, _ := ParseQueueKey(QueueKey("uk", issued, req.ID)) |
| + if !QueueMatches(good, req) { |
| + t.Fatal("the console's own entry does not match") |
| + } |
| + for name, key := range map[string]string{ |
| + "other region": QueueKey("ie", issued, req.ID), |
| + "other time": QueueKey("uk", issued.Add(time.Second), req.ID), |
| + "other hour": QueueHourPrefix("uk", issued.Add(time.Hour)) + strconv.FormatInt(issued.Unix(), 10) + "-" + req.ID, |
| + "other id": QueueKey("uk", issued, "dbr_bbbbbbbbbbbbbbbbbbbbbbbbbb"), |
| + } { |
| + e, ok := ParseQueueKey(key) |
| + if ok && QueueMatches(e, req) { |
| + t.Errorf("%s matched", name) |
| + } |
| + } |
| +} |
diff --git a/internal/dbreads/result.go b/internal/dbreads/result.go| new file mode 100644 |
| index 000000000..8bbfcde00 |
| --- /dev/null |
| +++ b/internal/dbreads/result.go |
| @@ -0,0 +1,88 @@ |
| +package dbreads |
| + |
| +import ( |
| + "fmt" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| +) |
| + |
| +// How a read ended (result.json's state, spec §5.6). |
| +const ( |
| + StateDone = "done" |
| + StateFailed = "failed" |
| + StateRefused = "refused" |
| + StateCancelled = "cancelled" |
| +) |
| + |
| +// The fixed code vocabulary the console may read. |
| +const ( |
| + CodeNothingReplicated = "nothing-replicated" |
| + CodeHistoryGone = "history-gone" |
| + CodeCheckFailed = "check-failed" |
| + CodeChangedTwice = "changed-twice" |
| + CodeTooLarge = "too-large" |
| + CodeNoRoom = "no-room" |
| + CodeSQLError = "sql-error" |
| + CodeTimeout = "timeout" |
| + CodeOutputCap = "output-cap" |
| + CodeRecordChanged = "record-changed" |
| + CodeMoving = "moving" |
| + CodeInterrupted = "interrupted" |
| +) |
| + |
| +var codesByState = map[string]map[string]bool{ |
| + StateDone: {"": true, CodeOutputCap: true}, |
| + StateFailed: {CodeNothingReplicated: true, CodeHistoryGone: true, CodeCheckFailed: true, CodeChangedTwice: true, CodeTooLarge: true, CodeNoRoom: true, CodeSQLError: true, CodeTimeout: true, CodeInterrupted: true}, |
| + StateRefused: {CodeRecordChanged: true, CodeMoving: true}, |
| + StateCancelled: {"": true}, |
| +} |
| + |
| +// Result is db-reads/<id>/result.json, written only after every chunk is |
| +// confirmed. LastSeq is the last chunk's sequence number; a done read has at |
| +// least one chunk, the last of which is sealed as last. |
| +type Result struct { |
| + State string `json:"state"` |
| + Code string `json:"code"` |
| + Box string `json:"box"` |
| + LastSeq int64 `json:"last_seq"` |
| + Started time.Time `json:"started"` |
| + Ended time.Time `json:"ended"` |
| + Sealed string `json:"sealed"` |
| +} |
| + |
| +// Valid is the shape the console checks before it relays a result. |
| +func (r Result) Valid() error { |
| + codes, ok := codesByState[r.State] |
| + switch { |
| + case !ok: |
| + return fmt.Errorf("dbreads: unknown state %q", r.State) |
| + case !codes[r.Code]: |
| + return fmt.Errorf("dbreads: code %q is not one of state %s's", r.Code, r.State) |
| + case r.LastSeq < 0, r.State == StateDone && r.LastSeq < 1: |
| + return fmt.Errorf("dbreads: last_seq %d for state %s", r.LastSeq, r.State) |
| + } |
| + return nil |
| +} |
| + |
| +// Picked is db-reads/<id>/picked: the owner (J3). |
| +type Picked struct { |
| + Box string `json:"box"` |
| + Boot string `json:"boot"` |
| + Nonce string `json:"nonce"` |
| + Deadline time.Time `json:"deadline"` |
| +} |
| + |
| +// Summary is the result's sealed half, which only the CLI can open (§5.6). |
| +type Summary struct { |
| + TXID uint64 `json:"txid"` // the copy's newest transaction |
| + At time.Time `json:"at"` // that transaction's time, from its LTX header |
| + Oldest time.Time `json:"oldest"` // history-gone: the earliest --at that works |
| + Restored int64 `json:"restored"` // too-large: the restored size |
| + Cap int64 `json:"cap"` // too-large: the box's cap |
| + Error string `json:"error"` // sql-error: SQLite's text; check-failed: the detail |
| + Bytes int64 `json:"bytes"` // the output's plaintext byte count |
| + SHA256 string `json:"sha256"` // the output's plaintext SHA-256, hex |
| + // Files is a pull's planned files in order (plan 3); empty for a query. |
| + Files []dbdoor.LTXFile `json:"files,omitempty"` |
| +} |
diff --git a/internal/dbreads/seal.go b/internal/dbreads/seal.go| new file mode 100644 |
| index 000000000..7d2d85215 |
| --- /dev/null |
| +++ b/internal/dbreads/seal.go |
| @@ -0,0 +1,184 @@ |
| +package dbreads |
| + |
| +import ( |
| + "crypto/aes" |
| + "crypto/cipher" |
| + "crypto/ecdh" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/binary" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "strconv" |
| + |
| + "golang.org/x/crypto/hkdf" |
| +) |
| + |
| +// Sealing is the appconfig v2 construction (spec §5.6): ECDH P-256 with a |
| +// fresh sender key per seal, HKDF-SHA256 with this package's own info string, |
| +// AES-256-GCM with bound associated data. The wire is raw bytes, never |
| +// base64, in the bucket: "DBR1" || sender key (65) || nonce (12) || ciphertext. |
| +const ( |
| + sealPrefix = "DBR1" |
| + sealEphLen = 65 |
| + sealNonceLen = 12 |
| + // SealOverhead is what sealing adds: under 100 bytes (spec §5.7). |
| + SealOverhead = len(sealPrefix) + sealEphLen + sealNonceLen + 16 |
| +) |
| + |
| +// The streams a chunk can carry, bound into its associated data. |
| +const ( |
| + StreamRows = "rows" // a query's output |
| + StreamLTX = "ltx" // a pull's planned files (plan 3) |
| +) |
| + |
| +// ErrSeal is any sealed object that does not open: wrong key, moved, |
| +// reordered, relabelled, truncated or corrupt. |
| +var ErrSeal = errors.New("dbreads: the sealed bytes do not open") |
| + |
| +var errBadReplyKey = errors.New("dbreads: reply_key is not an uncompressed P-256 point") |
| + |
| +// randReader is a var so a test can make sealing deterministic. |
| +var randReader io.Reader = rand.Reader |
| + |
| +// NewReplyKey is the CLI's ephemeral key pair for one read. The private half |
| +// never leaves the CLI's memory. |
| +func NewReplyKey() (*ecdh.PrivateKey, error) { return ecdh.P256().GenerateKey(randReader) } |
| + |
| +func EncodeReplyKey(pub *ecdh.PublicKey) string { |
| + return base64.StdEncoding.EncodeToString(pub.Bytes()) |
| +} |
| + |
| +func ParseReplyKey(s string) (*ecdh.PublicKey, error) { |
| + raw, err := base64.StdEncoding.Strict().DecodeString(s) |
| + if err != nil || len(raw) != sealEphLen { |
| + return nil, errBadReplyKey |
| + } |
| + pub, err := ecdh.P256().NewPublicKey(raw) |
| + if err != nil { |
| + return nil, errBadReplyKey |
| + } |
| + return pub, nil |
| +} |
| + |
| +// lengthPrefixed encodes fields so no choice of values makes two lists |
| +// encode the same. |
| +func lengthPrefixed(fields ...string) []byte { |
| + var out []byte |
| + for _, f := range fields { |
| + out = binary.BigEndian.AppendUint32(out, uint32(len(f))) |
| + out = append(out, f...) |
| + } |
| + return out |
| +} |
| + |
| +func chunkAAD(id string, seq int64, stream string, last bool) []byte { |
| + l := "0" |
| + if last { |
| + l = "1" |
| + } |
| + return lengthPrefixed(Purpose, "chunk", id, strconv.FormatInt(seq, 10), stream, l) |
| +} |
| + |
| +func summaryAAD(id string) []byte { return lengthPrefixed(Purpose, "summary", id) } |
| + |
| +func gcmFor(shared []byte) (cipher.AEAD, error) { |
| + key := make([]byte, 32) |
| + if _, err := io.ReadFull(hkdf.New(sha256.New, shared, nil, []byte(Purpose)), key); err != nil { |
| + return nil, err |
| + } |
| + block, err := aes.NewCipher(key) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return cipher.NewGCM(block) |
| +} |
| + |
| +func seal(pub *ecdh.PublicKey, aad, plain []byte) ([]byte, error) { |
| + eph, err := ecdh.P256().GenerateKey(randReader) |
| + if err != nil { |
| + return nil, err |
| + } |
| + nonce := make([]byte, sealNonceLen) |
| + if _, err := io.ReadFull(randReader, nonce); err != nil { |
| + return nil, err |
| + } |
| + shared, err := eph.ECDH(pub) |
| + if err != nil { |
| + return nil, err |
| + } |
| + gcm, err := gcmFor(shared) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out := make([]byte, 0, SealOverhead+len(plain)) |
| + out = append(out, sealPrefix...) |
| + out = append(out, eph.PublicKey().Bytes()...) |
| + out = append(out, nonce...) |
| + return gcm.Seal(out, nonce, plain, aad), nil |
| +} |
| + |
| +func open(priv *ecdh.PrivateKey, aad, sealed []byte) ([]byte, error) { |
| + if len(sealed) < SealOverhead || string(sealed[:len(sealPrefix)]) != sealPrefix { |
| + return nil, ErrSeal |
| + } |
| + body := sealed[len(sealPrefix):] |
| + ephPub, err := ecdh.P256().NewPublicKey(body[:sealEphLen]) |
| + if err != nil { |
| + return nil, ErrSeal |
| + } |
| + shared, err := priv.ECDH(ephPub) |
| + if err != nil { |
| + return nil, ErrSeal |
| + } |
| + gcm, err := gcmFor(shared) |
| + if err != nil { |
| + return nil, ErrSeal |
| + } |
| + plain, err := gcm.Open(nil, body[sealEphLen:sealEphLen+sealNonceLen], body[sealEphLen+sealNonceLen:], aad) |
| + if err != nil { |
| + return nil, ErrSeal |
| + } |
| + return plain, nil |
| +} |
| + |
| +// SealChunk seals one chunk of a read's output: bound to the read, its |
| +// sequence number, its stream and whether it is the last. |
| +func SealChunk(pub *ecdh.PublicKey, id string, seq int64, stream string, last bool, plain []byte) ([]byte, error) { |
| + return seal(pub, chunkAAD(id, seq, stream, last), plain) |
| +} |
| + |
| +func OpenChunk(priv *ecdh.PrivateKey, id string, seq int64, stream string, last bool, sealed []byte) ([]byte, error) { |
| + return open(priv, chunkAAD(id, seq, stream, last), sealed) |
| +} |
| + |
| +// SealSummary seals the result's summary (base64, it rides in result.json). |
| +func SealSummary(pub *ecdh.PublicKey, id string, s Summary) (string, error) { |
| + raw, err := json.Marshal(s) |
| + if err != nil { |
| + return "", err |
| + } |
| + sealed, err := seal(pub, summaryAAD(id), raw) |
| + if err != nil { |
| + return "", err |
| + } |
| + return base64.StdEncoding.EncodeToString(sealed), nil |
| +} |
| + |
| +func OpenSummary(priv *ecdh.PrivateKey, id, sealed string) (Summary, error) { |
| + raw, err := base64.StdEncoding.Strict().DecodeString(sealed) |
| + if err != nil { |
| + return Summary{}, ErrSeal |
| + } |
| + plain, err := open(priv, summaryAAD(id), raw) |
| + if err != nil { |
| + return Summary{}, err |
| + } |
| + var s Summary |
| + if err := json.Unmarshal(plain, &s); err != nil { |
| + return Summary{}, ErrSeal |
| + } |
| + return s, nil |
| +} |
diff --git a/internal/dbreads/seal_test.go b/internal/dbreads/seal_test.go| new file mode 100644 |
| index 000000000..97ab999cb |
| --- /dev/null |
| +++ b/internal/dbreads/seal_test.go |
| @@ -0,0 +1,98 @@ |
| +package dbreads |
| + |
| +import ( |
| + "bytes" |
| + "errors" |
| + "testing" |
| + "time" |
| +) |
| + |
| +const sealID = "dbr_aaaaaaaaaaaaaaaaaaaaaaaaaa" |
| + |
| +func TestChunkSealRoundTripsAndBindsEverything(t *testing.T) { |
| + t.Parallel() |
| + priv, err := NewReplyKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + plain := bytes.Repeat([]byte("row\n"), 1000) |
| + sealed, err := SealChunk(priv.PublicKey(), sealID, 3, StreamRows, false, plain) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(sealed)-len(plain) >= 100 || len(sealed)-len(plain) != SealOverhead { |
| + t.Fatalf("overhead %d, spec §5.7 says under 100 bytes", len(sealed)-len(plain)) |
| + } |
| + got, err := OpenChunk(priv, sealID, 3, StreamRows, false, sealed) |
| + if err != nil || !bytes.Equal(got, plain) { |
| + t.Fatalf("OpenChunk = %v", err) |
| + } |
| + other, _ := NewReplyKey() |
| + for name, open := range map[string]func() ([]byte, error){ |
| + "moved to another read": func() ([]byte, error) { |
| + return OpenChunk(priv, "dbr_bbbbbbbbbbbbbbbbbbbbbbbbbb", 3, StreamRows, false, sealed) |
| + }, |
| + "reordered": func() ([]byte, error) { return OpenChunk(priv, sealID, 4, StreamRows, false, sealed) }, |
| + "relabelled as last": func() ([]byte, error) { return OpenChunk(priv, sealID, 3, StreamRows, true, sealed) }, |
| + "another stream": func() ([]byte, error) { return OpenChunk(priv, sealID, 3, StreamLTX, false, sealed) }, |
| + "another key": func() ([]byte, error) { return OpenChunk(other, sealID, 3, StreamRows, false, sealed) }, |
| + "truncated": func() ([]byte, error) { return OpenChunk(priv, sealID, 3, StreamRows, false, sealed[:len(sealed)-1]) }, |
| + } { |
| + if _, err := open(); !errors.Is(err, ErrSeal) { |
| + t.Errorf("%s: %v", name, err) |
| + } |
| + } |
| +} |
| + |
| +func TestSummarySealRoundTrips(t *testing.T) { |
| + t.Parallel() |
| + priv, _ := NewReplyKey() |
| + want := Summary{TXID: 42, At: time.Date(2026, 10, 7, 14, 0, 0, 0, time.UTC), Bytes: 10, SHA256: "ab"} |
| + sealed, err := SealSummary(priv.PublicKey(), sealID, want) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := OpenSummary(priv, sealID, sealed) |
| + if err != nil || got.TXID != want.TXID || !got.At.Equal(want.At) || got.SHA256 != want.SHA256 { |
| + t.Fatalf("OpenSummary = %+v, %v", got, err) |
| + } |
| + if _, err := OpenSummary(priv, "dbr_bbbbbbbbbbbbbbbbbbbbbbbbbb", sealed); !errors.Is(err, ErrSeal) { |
| + t.Fatalf("a summary moved to another read opened: %v", err) |
| + } |
| +} |
| + |
| +func TestReplyKeyRefusesWhatIsNotAnUncompressedPoint(t *testing.T) { |
| + t.Parallel() |
| + for _, bad := range []string{"", "AAAA", "!!!!"} { |
| + if _, err := ParseReplyKey(bad); err == nil { |
| + t.Errorf("ParseReplyKey(%q) accepted", bad) |
| + } |
| + } |
| +} |
| + |
| +func TestResultValidKnowsTheVocabulary(t *testing.T) { |
| + t.Parallel() |
| + ok := []Result{ |
| + {State: StateDone, LastSeq: 1}, |
| + {State: StateDone, Code: CodeOutputCap, LastSeq: 3}, |
| + {State: StateFailed, Code: CodeSQLError}, |
| + {State: StateRefused, Code: CodeRecordChanged}, |
| + {State: StateCancelled}, |
| + } |
| + for _, r := range ok { |
| + if err := r.Valid(); err != nil { |
| + t.Errorf("%+v: %v", r, err) |
| + } |
| + } |
| + bad := []Result{ |
| + {State: StateDone, LastSeq: 0}, |
| + {State: "maybe"}, |
| + {State: StateFailed, Code: "nope"}, |
| + {State: StateDone, LastSeq: -1}, |
| + } |
| + for _, r := range bad { |
| + if err := r.Valid(); err == nil { |
| + t.Errorf("%+v accepted", r) |
| + } |
| + } |
| +} |