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 '&' || 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) } } } // A pull is an op this build signs and serves (plan 3), and carries no SQL. func TestEnvelopeCarriesAPull(t *testing.T) { t.Parallel() pub, priv := rootKeys(t) req := testRequest(t) req.Op, req.SQL = OpPull, "" wire, err := Sign(release.RootSigner(priv), req) if err != nil { t.Fatal(err) } if got, err := Verify(pub, wire, req.ID, "uk", testNow); err != nil || got.Op != OpPull { t.Fatalf("%+v %v", got, err) } req.SQL = "SELECT 1" if _, err := Sign(release.RootSigner(priv), req); !errors.Is(err, ErrEnvelope) { t.Fatalf("a pull carrying SQL signed: %v", err) } }