carlos / platform Public

console: the reads route's gate and admission (DBF-9, DBF-10, DBF-21, DBF-22 wired, pending copy) (plan 2, Task 6)

The route joins claim-routes.txt, and the claim invariant census gets a
refused fixture: a host-claim console never signs a forwarded read, so it
answers main's residency sentence after the record read and writes
nothing (spec §6, §9.1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 67e39c0182af4907a2cf29159dbdef53be222441 parent 23ae5c8
7 files changed, +701 −1
  • approved_db_forward_copy_test.go +1 −1
  • internal/console/apidbforward.go +300 −0
  • internal/console/apidbforward_test.go +363 −0
  • internal/console/authcli.go +3 −0
  • internal/console/claim_invariant_fixtures_test.go +16 −0
  • internal/console/claim_invariant_test.go +17 −0
  • internal/console/testdata/claim-routes.txt +1 −0
diff --git a/approved_db_forward_copy_test.go b/approved_db_forward_copy_test.go
index 3d0a3b0b9..b552abd37 100644
--- a/approved_db_forward_copy_test.go
+++ b/approved_db_forward_copy_test.go
@@ -49,7 +49,7 @@ var dbForwardCopyBuilt = []string{}
// that has not turned forwarding on. The copy review moves each id from here
// to dbForwardCopyBuilt, applying Paul's edits in the same commit. Docs rows
// are public the moment the site syncs, so they are never wired.
-var dbForwardCopyWired = []string{"DBF-1", "DBF-2", "DBF-14"}
+var dbForwardCopyWired = []string{"DBF-1", "DBF-2", "DBF-14", "DBF-9", "DBF-10", "DBF-21", "DBF-22"}
func mustParseDBForwardRecord(t *testing.T) []copyRow {
t.Helper()
diff --git a/internal/console/apidbforward.go b/internal/console/apidbforward.go
index c2b0094ab..cd8d834f1 100644
--- a/internal/console/apidbforward.go
+++ b/internal/console/apidbforward.go
@@ -6,14 +6,25 @@
package console
import (
+ "context"
"crypto/ed25519"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
"fmt"
+ "log"
"net/http"
+ "os"
"slices"
+ "strings"
"time"
+ "unicode/utf8"
"github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbquery"
"github.com/carlosframework/platform/internal/dbreads"
+ "github.com/carlosframework/platform/internal/hostclaim"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -136,3 +147,292 @@ func (s *Server) dbResidency(w http.ResponseWriter, r *http.Request, rec provisi
Region: rec.Region, ForwardOps: []string{dbreads.OpQuery},
})
}
+
+// The forwarded read's other console sentences (copy record DBF-9, DBF-10,
+// DBF-21, DBF-22). PENDING copy review, wired behind CARLOS_DB_FORWARD as
+// the three above are.
+const (
+ dbfTooMany = "too many database reads are open. wait a minute and try again."
+ dbfMoving = "%s is moving between regions. read its database once the move has finished."
+ dbfAudit = "forwarded a database query to region %s. the query was %d bytes, sha256 %s (cli)"
+ dbfAuditAt = "forwarded a database query to region %s, as of %s. the query was %d bytes, sha256 %s (cli)"
+)
+
+const dbReadRetryAfter = "30"
+
+// dbForwardAuditDetail is the db-read row's detail (spec §9.3): the SQL's
+// length and the first 16 hex digits of its SHA-256, never its text.
+func dbForwardAuditDetail(region, sqlText string, at time.Time) string {
+ sum := sha256.Sum256([]byte(sqlText))
+ sha := hex.EncodeToString(sum[:])[:16]
+ if at.IsZero() {
+ return fmt.Sprintf(dbfAudit, region, len(sqlText), sha)
+ }
+ return fmt.Sprintf(dbfAuditAt, region, at.UTC().Format(time.RFC3339), len(sqlText), sha)
+}
+
+// dbReadAdmitted is a read this console has admitted, signed and queued.
+type dbReadAdmitted struct {
+ id, region string
+ issued time.Time
+}
+
+// handleAPIDBRead is POST /api/cli/apps/{account}/{app}/db/{host}/reads
+// (spec §9.1): one forwarded read, which exists only inside this request
+// (§5.2, J1). The admission counts are released by this handler's return and
+// nowhere else (J5).
+func (s *Server) handleAPIDBRead(w http.ResponseWriter, r *http.Request) {
+ rc := http.NewResponseController(w)
+ // Everything before the 200, the body included, gets s.dbf.preHeader:
+ // a body delivered slowly must not hold the request past backhaul's
+ // 30 s header wait (plan review finding 13).
+ if err := rc.SetReadDeadline(time.Now().Add(s.dbf.preHeader)); err != nil && !errors.Is(err, http.ErrNotSupported) {
+ log.Printf("console: db read: set the admission read deadline: %v", err)
+ }
+ a, actor, ok := s.admitDBRead(w, r)
+ if !ok {
+ return
+ }
+ defer s.dbReads.release(actor)
+ // Then the server's ReadTimeout would end this connection under a read
+ // that lasts longer; the read's own bound holds it instead, as the
+ // import door's read deadline does (apiinstanceimport.go).
+ if err := rc.SetReadDeadline(time.Now().Add(s.dbf.bound + time.Minute)); err != nil && !errors.Is(err, http.ErrNotSupported) {
+ log.Printf("console: db read: extend the read deadline: %v", err)
+ }
+ s.streamDBRead(w, r, rc, a)
+}
+
+// cancelDBRead is the one write J1 allows after a read's request ends
+// without a result: best effort, so the owner stops early and a box that
+// has not picked it skips it.
+func (s *Server) cancelDBRead(id string) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if _, err := s.cfg.Releases.Put(ctx, dbreads.CancelKey(id), nil, ""); err != nil && !errors.Is(err, release.ErrCASConflict) {
+ log.Printf("console: db read %s: cancel: %v", id, err)
+ }
+}
+
+// announceDBRead bumps the serial on the request's own context, so a
+// request that has already ended announces nothing (J1; plan review finding
+// 11). bumpSerial detaches on purpose, for callers whose writes outlive
+// them; this read does not outlive its request.
+func (s *Server) announceDBRead(ctx context.Context) {
+ ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+ if err := release.BumpSerial(ctx, s.cfg.Releases, time.Now()); err != nil && ctx.Err() == nil {
+ log.Printf("console: db read: serial bump: %v (boxes list every 30 s anyway)", err)
+ }
+}
+
+// admitDBRead is spec §5.5 step 3, all of it bounded by s.dbf.preHeader so
+// the 200 leaves well inside backhaul's 30 s header wait: dbGate's order
+// (person, membership with the byte-identical 404, the db budget,
+// configuration, the record, the class rail, pooled, fleet), then a moving
+// record, the SQL guard, capability on complete evidence, the admission
+// counts, and the audit row, the signed request, its queue entry and the
+// serial. Any refusal is an ordinary status and JSON error.
+func (s *Server) admitDBRead(w http.ResponseWriter, r *http.Request) (dbReadAdmitted, string, bool) {
+ none := dbReadAdmitted{}
+ ctx, cancel := context.WithTimeout(r.Context(), s.dbf.preHeader)
+ defer cancel()
+ if p, ok := principalFrom(r.Context()); !ok || p.Kind != PrincipalUser {
+ http.NotFound(w, r)
+ return none, "", false
+ }
+ actor, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok {
+ return none, "", false
+ }
+ if !s.cli.db.allow(hashToken(bearer(r)), time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, "too many database requests. Wait a minute and try again.")
+ return none, "", false
+ }
+ if s.cfg.Releases == nil || s.cfg.HibernateBucket == "" {
+ jsonError(w, http.StatusServiceUnavailable, "this console has no data bucket set up, so it cannot read databases.")
+ return none, "", false
+ }
+ var body dbreads.ReadBody
+ if !readJSONLimit(w, r, &body, dbreads.MaxSQLBytes+8<<10) {
+ return none, "", false
+ }
+ host := r.PathValue("host")
+ src, err := s.resolveDBSource(ctx, acct, actor, app, host)
+ switch {
+ case errors.Is(err, os.ErrNotExist), errors.Is(err, ErrBadHost):
+ http.NotFound(w, r)
+ return none, "", false
+ case errors.Is(err, errSourceClass):
+ jsonError(w, http.StatusConflict, dbClassRefusal(src.rec))
+ return none, "", false
+ case errors.Is(err, ErrPooled):
+ jsonError(w, http.StatusConflict, fmt.Sprintf(
+ "%s runs in the pool %s, so its data is on the pool's own server. carlos db cannot read it.", host, src.rec.Pool))
+ return none, "", false
+ case errors.Is(err, ErrResidency):
+ // The case this route exists for.
+ case err == nil:
+ // In region: the db door serves it directly. There is no forwarded
+ // read for it until in-region reads move to the box path (plan 4).
+ http.NotFound(w, r)
+ return none, "", false
+ case errors.Is(err, errSourceResolve):
+ log.Printf("console: db read %s/%s/%s: resolve: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, "could not read the replica. Try again.")
+ return none, "", false
+ default:
+ log.Printf("console: db read %s/%s/%s: read record: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, "could not read the instance. Try again.")
+ return none, "", false
+ }
+ rec := src.rec
+ signer, ok := s.dbForwardSigner()
+ if !ok || !s.forwardable(rec) {
+ jsonError(w, http.StatusConflict, s.dbResidencyRefusal(rec))
+ return none, "", false
+ }
+ if rec.Move != nil {
+ jsonError(w, http.StatusConflict, fmt.Sprintf(dbfMoving, host))
+ return none, "", false
+ }
+ if body.Op != dbreads.OpQuery {
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return none, "", false
+ }
+ // encoding/json turns bytes that are not UTF-8, and a lone surrogate
+ // escape, into U+FFFD without a word, so the SQL decoded here may not be
+ // the SQL sent. The box must run exactly the bytes typed or be told no
+ // (plan 1's Review Focus 1), so any U+FFFD is refused; a query that
+ // meant one literally is refused too, and says so the same way (plan
+ // review finding 36). The CLI refuses first, with DBF-32.
+ if strings.ContainsRune(body.SQL, utf8.RuneError) {
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return none, "", false
+ }
+ if err := dbquery.CheckSQL(body.SQL); err != nil || body.SQL == "" {
+ msg := http.StatusText(http.StatusBadRequest)
+ if err != nil {
+ msg = err.Error()
+ }
+ jsonError(w, http.StatusBadRequest, msg)
+ return none, "", false
+ }
+ var at time.Time
+ if body.At != "" {
+ if at, err = time.Parse(time.RFC3339, body.At); err != nil || at.After(time.Now().Add(dbreads.Skew)) {
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return none, "", false
+ }
+ }
+ if _, err := dbreads.ParseReplyKey(body.ReplyKey); err != nil {
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return none, "", false
+ }
+ snap, serr := s.liveEdges(ctx)
+ switch dbForwardEvidence(snap, serr, rec.Region) {
+ case dbForwardNone:
+ jsonError(w, http.StatusConflict, fmt.Sprintf(dbfNoCapable, host, rec.Region))
+ return none, "", false
+ case dbForwardDead:
+ jsonError(w, http.StatusConflict, fmt.Sprintf(dbfNoneLive, host, rec.Region))
+ return none, "", false
+ }
+ if !s.dbReads.acquire(actor) {
+ w.Header().Set("Retry-After", dbReadRetryAfter)
+ jsonError(w, http.StatusTooManyRequests, dbfTooMany)
+ return none, "", false
+ }
+ admitted := false
+ defer func() {
+ if !admitted {
+ s.dbReads.release(actor)
+ }
+ }()
+ fail := func(what string, err error) (dbReadAdmitted, string, bool) {
+ log.Printf("console: db read %s/%s/%s: %s: %v", acct.Sqid, app, host, what, err)
+ jsonError(w, http.StatusBadGateway, "could not read the instance. Try again.")
+ return none, "", false
+ }
+ id, err := dbreads.MintID()
+ if err != nil {
+ return fail("mint id", err)
+ }
+ inc, err := hostclaim.Incarnation(acct.Sqid, app, host, rec.CreatedAt)
+ if err != nil {
+ return fail("incarnation", err)
+ }
+ issued := time.Now().UTC().Truncate(time.Second)
+ atRaw := ""
+ if !at.IsZero() {
+ atRaw = at.UTC().Format(time.RFC3339Nano)
+ }
+ wire, err := dbreads.Sign(signer, dbreads.Request{ID: id, Account: acct.Sqid, App: app, Host: host, Incarnation: inc,
+ Region: rec.Region, Op: body.Op, SQL: body.SQL, At: atRaw, ReplyKey: body.ReplyKey, By: actor,
+ IssuedAt: issued.Format(time.RFC3339)})
+ if err != nil {
+ // SQL the envelope cannot carry intact (invalid UTF-8).
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return none, "", false
+ }
+ // J1 at every write (plan review finding 28): the request's context is
+ // checked immediately before each one, because the stores do not stop a
+ // write for it (DirStore.Put ignores its context). The audit row comes
+ // first, while the request is open and before any box can see the read,
+ // so a read a box runs always has its row (spec §9.3 rev 6). A request
+ // that ends before request.json is written leaves at most that row; one
+ // that ends after leaves request.json, perhaps the queue entry, and the
+ // cancel, never a serial bump. A row the store cannot write refuses the
+ // read rather than run it unaudited.
+ ended := func(step string, published bool) bool {
+ if s.dbf.beforeWrite != nil {
+ s.dbf.beforeWrite(step)
+ }
+ if ctx.Err() == nil {
+ return false
+ }
+ if published {
+ s.cancelDBRead(id)
+ }
+ return true
+ }
+ if ended("audit", false) {
+ return none, "", false
+ }
+ if err := s.store.RecordActivityContext(ctx, acct.ID, app, actor, Activity{Action: dbAuditAction,
+ TargetType: "instance", Target: host, Detail: dbForwardAuditDetail(rec.Region, body.SQL, at)}, time.Now()); err != nil {
+ return fail("audit", err)
+ }
+ if ended("request", false) {
+ return none, "", false
+ }
+ if _, err := s.cfg.Releases.Put(ctx, dbreads.RequestKey(id), wire, ""); err != nil {
+ // An ambiguous create may have landed: cancel, as for the queue.
+ s.cancelDBRead(id)
+ return fail("write the request", err)
+ }
+ if ended("queue", true) {
+ return none, "", false
+ }
+ if _, err := s.cfg.Releases.Put(ctx, dbreads.QueueKey(rec.Region, issued, id), nil, ""); err != nil {
+ // The queue entry may have landed on an ambiguous answer: cancel, so
+ // a box that lists it skips it (J1's one write).
+ s.cancelDBRead(id)
+ return fail("write the queue entry", err)
+ }
+ if ended("serial", true) {
+ return none, "", false
+ }
+ // The bump runs on the request's context, not bumpSerial's detached one,
+ // so a request that ends while it runs does not announce (finding 33).
+ s.announceDBRead(ctx)
+ admitted = true
+ return dbReadAdmitted{id: id, region: rec.Region, issued: issued}, actor, true
+}
+
+// streamDBRead is Task 7's.
+func (s *Server) streamDBRead(w http.ResponseWriter, _ *http.Request, _ *http.ResponseController, a dbReadAdmitted) {
+ w.Header().Set("Content-Type", "application/x-ndjson")
+ w.WriteHeader(http.StatusOK)
+ json.NewEncoder(w).Encode(dbreads.Line{Admitted: a.id})
+}
diff --git a/internal/console/apidbforward_test.go b/internal/console/apidbforward_test.go
index c375948a0..bcc159a76 100644
--- a/internal/console/apidbforward_test.go
+++ b/internal/console/apidbforward_test.go
@@ -1,18 +1,26 @@
package console
import (
+ "bufio"
+ "bytes"
"context"
+ "crypto/ecdh"
"crypto/ed25519"
"crypto/rand"
"encoding/json"
"fmt"
+ "io"
+ "net"
"net/http"
+ "net/http/httptest"
"slices"
"strings"
+ "sync"
"testing"
"time"
"github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbquery"
"github.com/carlosframework/platform/internal/dbreads"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
@@ -222,3 +230,358 @@ func TestListDoorKeepsMainsSentenceForTheHomeRegion(t *testing.T) {
t.Fatalf("%d %s", status, body)
}
}
+
+func (fx *dbfFixture) readURL(host string) string {
+ return fx.ts.URL + "/api/cli/apps/" + release.OpsAccount + "/shop/db/" + host + "/reads"
+}
+
+func queryBody(t *testing.T, sqlText string) (dbreads.ReadBody, *ecdh.PrivateKey) {
+ t.Helper()
+ key, err := dbreads.NewReplyKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return dbreads.ReadBody{Op: dbreads.OpQuery, SQL: sqlText, ReplyKey: dbreads.EncodeReplyKey(key.PublicKey())}, key
+}
+
+// openRead posts a read and returns the open response; the caller reads its
+// lines or closes it.
+func (fx *dbfFixture) openRead(t *testing.T, host, bearer string, body dbreads.ReadBody) *http.Response {
+ t.Helper()
+ raw, _ := json.Marshal(body)
+ req, _ := http.NewRequest(http.MethodPost, fx.readURL(host), bytes.NewReader(raw))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return res
+}
+
+func readLines(t *testing.T, r io.Reader) []dbreads.Line {
+ t.Helper()
+ sc := bufio.NewScanner(r)
+ sc.Buffer(make([]byte, 64<<10), dbreads.MaxLineBytes)
+ var out []dbreads.Line
+ for sc.Scan() {
+ var l dbreads.Line
+ if err := json.Unmarshal(sc.Bytes(), &l); err != nil {
+ t.Fatalf("not a line: %s", sc.Bytes())
+ }
+ out = append(out, l)
+ }
+ return out
+}
+
+func refusal(t *testing.T, res *http.Response) (int, string) {
+ t.Helper()
+ defer res.Body.Close()
+ b, _ := io.ReadAll(res.Body)
+ return res.StatusCode, string(b)
+}
+
+func TestDBReadRouteRefusesBeforeAdmitting(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ good, _ := queryBody(t, "SELECT 1")
+ putShopRecord(t, fx.consoleFixture, provision.Record{Host: "here.example.com", Region: "ie", CreatedAt: time.Now().UTC()})
+ putShopRecord(t, fx.consoleFixture, provision.Record{Host: "moving.example.com", Region: "uk", CreatedAt: time.Now().UTC(),
+ Move: &provision.MoveState{ID: "mv_x", To: "ie", State: "requested"}})
+ two := good
+ two.SQL = "SELECT 1; SELECT 2"
+ pull := good
+ pull.Op, pull.SQL = dbreads.OpPull, ""
+ badKey := good
+ badKey.ReplyKey = "AAAA"
+ future := good
+ future.At = time.Now().Add(time.Hour).UTC().Format(time.RFC3339)
+ for name, c := range map[string]struct {
+ host string
+ body dbreads.ReadBody
+ status int
+ want string
+ }{
+ "an in-region instance": {"here.example.com", good, http.StatusNotFound, ""},
+ "no such instance": {"nope.example.com", good, http.StatusNotFound, ""},
+ "moving": {"moving.example.com", good, http.StatusConflict, fmt.Sprintf(dbfMoving, "moving.example.com")},
+ "two statements": {dbfHost, two, http.StatusBadRequest, dbquery.ErrOneStatement.Error()},
+ "an op this console does not forward": {dbfHost, pull, http.StatusBadRequest, ""},
+ "a reply key that is not a key": {dbfHost, badKey, http.StatusBadRequest, ""},
+ "a time in the future": {dbfHost, future, http.StatusBadRequest, ""},
+ } {
+ status, body := refusal(t, fx.openRead(t, c.host, fx.member, c.body))
+ if status != c.status || !strings.Contains(body, c.want) {
+ t.Errorf("%s: %d %s", name, status, body)
+ }
+ }
+ // SQL that JSON decoding would have rewritten (plan review finding 36):
+ // a byte that is not UTF-8, and a lone surrogate escape.
+ for name, sqlJSON := range map[string]string{
+ "a byte that is not UTF-8": "\"SELECT '\xff'\"",
+ "a lone surrogate": `"SELECT '\ud800'"`,
+ } {
+ raw := `{"op":"query","sql":` + sqlJSON + `,"reply_key":"` + good.ReplyKey + `"}`
+ req, _ := http.NewRequest(http.MethodPost, fx.readURL(dbfHost), strings.NewReader(raw))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+fx.member)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if status, body := refusal(t, res); status != http.StatusBadRequest {
+ t.Errorf("%s: %d %s", name, status, body)
+ }
+ }
+ if keys, _ := fx.rel.List(context.Background(), dbreads.Prefix); len(keys) != 0 {
+ t.Fatalf("a refused read wrote %v", keys)
+ }
+ fx.srv.cfg.DBForward = false
+ status, body := refusal(t, fx.openRead(t, dbfHost, fx.member, good))
+ if status != http.StatusConflict || !strings.Contains(body, "This console can only read data kept in region ie.") {
+ t.Fatalf("forwarding off: %d %s", status, body)
+ }
+ fx.srv.cfg.DBForward, fx.srv.cfg.HostClaim = true, true
+ status, body = refusal(t, fx.openRead(t, dbfHost, fx.member, good))
+ if status != http.StatusConflict || !strings.Contains(body, "This console can only read data kept in") {
+ t.Fatalf("a host-claim console: %d %s", status, body)
+ }
+}
+
+func TestDBReadRouteRefusesOnCompleteEvidence(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ putEdgesFile(t, fx.rel, "uk-1", "uk", nil, false)
+ good, _ := queryBody(t, "SELECT 1")
+ status, body := refusal(t, fx.openRead(t, dbfHost, fx.member, good))
+ if status != http.StatusConflict || !strings.Contains(body, fmt.Sprintf(dbfNoCapable, dbfHost, "uk")) {
+ t.Fatalf("%d %s", status, body)
+ }
+}
+
+// Admission, then the request, the queue entry, the serial and the audit
+// row, all before the 200.
+func TestDBReadQueuesASignedRequestAndAudits(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.pickup = 200 * time.Millisecond
+ body, _ := queryBody(t, "SELECT count(*) FROM orders")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ lines := readLines(t, res.Body)
+ res.Body.Close()
+ if res.StatusCode != http.StatusOK || len(lines) == 0 || lines[0].Admitted == "" {
+ t.Fatalf("%d %+v", res.StatusCode, lines)
+ }
+ id := lines[0].Admitted
+ raw, _, err := fx.rel.Get(context.Background(), dbreads.RequestKey(id))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req, err := dbreads.Verify(fx.pub, raw, id, "uk", time.Now())
+ if err != nil || req.SQL != body.SQL || req.Host != dbfHost || req.By != "member@example.com" || req.Account != release.OpsAccount {
+ t.Fatalf("request %+v: %v", req, err)
+ }
+ issued, _ := req.Issued()
+ if _, _, err := fx.rel.Get(context.Background(), dbreads.QueueKey("uk", issued, id)); err != nil {
+ t.Fatalf("no queue entry: %v", err)
+ }
+ if _, _, err := fx.rel.Get(context.Background(), release.SerialKey); err != nil {
+ t.Fatalf("the serial was not bumped: %v", err)
+ }
+ evs, _ := fx.st.Events(OpsAccountID, "shop", 10)
+ want := dbForwardAuditDetail("uk", body.SQL, time.Time{})
+ found := false
+ for _, e := range evs {
+ found = found || (e.Action == "db-read" && e.Target == dbfHost && e.Detail == want)
+ }
+ if !found || strings.Contains(want, "orders") {
+ t.Fatalf("audit %q in %+v", want, evs)
+ }
+}
+
+// dbfPutHook runs hook after each create of a key with suffix, once the
+// create has landed.
+type dbfPutHook struct {
+ release.Store
+ suffix string
+ hook func()
+}
+
+func (h *dbfPutHook) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ etag, err := h.Store.Put(ctx, key, body, ifMatch)
+ if strings.HasSuffix(key, h.suffix) || (h.suffix == "queue" && strings.HasPrefix(key, dbreads.Prefix+"queue/")) {
+ h.hook()
+ }
+ return etag, err
+}
+
+// dbReadAudited is safe from a handler's goroutine: it never calls t.Fatal.
+func dbReadAudited(t *testing.T, st *Store) bool {
+ t.Helper()
+ evs, err := st.Events(OpsAccountID, "shop", 10)
+ if err != nil {
+ t.Error(err)
+ return false
+ }
+ for _, e := range evs {
+ if e.Action == "db-read" && e.Target == dbfHost {
+ return true
+ }
+ }
+ return false
+}
+
+// dbfServe drives the handler in process with ctx as the request's own
+// context, so a test can end the request at an exact step.
+func (fx *dbfFixture) dbfServe(t *testing.T, ctx context.Context, sqlText string) *httptest.ResponseRecorder {
+ t.Helper()
+ body, _ := queryBody(t, sqlText)
+ raw, _ := json.Marshal(body)
+ req := httptest.NewRequest(http.MethodPost, fx.readURL(dbfHost), bytes.NewReader(raw)).WithContext(ctx)
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+fx.member)
+ rec := httptest.NewRecorder()
+ fx.srv.ServeHTTP(rec, req)
+ return rec
+}
+
+// dbfBucket is what a read left under db-reads/: request objects, queue
+// entries and cancels, by count.
+func dbfBucket(t *testing.T, s release.Store) (requests, queued, cancels int) {
+ t.Helper()
+ keys, _ := s.List(context.Background(), dbreads.Prefix)
+ for _, k := range keys {
+ switch {
+ case strings.HasPrefix(k, dbreads.Prefix+"queue/"):
+ queued++
+ case strings.HasSuffix(k, "/request.json"):
+ requests++
+ case strings.HasSuffix(k, "/cancel"):
+ cancels++
+ }
+ }
+ return
+}
+
+// dbfCtxStore refuses a write whose context has ended, as the S3 store
+// does and DirStore does not, and runs onGet once on a read of key.
+type dbfCtxStore struct {
+ release.Store
+ key string
+ onGet func()
+ once sync.Once
+}
+
+func (c *dbfCtxStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == c.key {
+ c.once.Do(c.onGet)
+ }
+ return c.Store.Get(ctx, key)
+}
+
+func (c *dbfCtxStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
+ return c.Store.Put(ctx, key, body, ifMatch)
+}
+
+// Plan review findings 11, 28 and 33 (J1, spec §5.5 step 3 and §9.3 rev 6):
+// the request's context is checked immediately before every write of
+// admission. Ended before the audit row: nothing at all. Before
+// request.json: the row only. Before the queue entry: the row, request.json
+// and the cancel. Before the serial: the row, both objects and the cancel.
+// Never a serial bump, never a 200. And the bump itself runs on the
+// request's context, so a request that ends while it reads the serial does
+// not write it.
+// Mutations, each red in its own case: drop any one of the four ended()
+// checks; drop the cancel on a published step; write the audit row after
+// the creates ("the audit row is down before the request"); call
+// s.bumpSerial instead of announceDBRead ("ended during the serial read":
+// the detached write lands).
+func TestDBReadEndedDuringAdmissionWritesOnlyTheCancel(t *testing.T) {
+ t.Run("the audit row is down before the request", func(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ auditedFirst := false
+ fx.srv.cfg.Releases = &dbfPutHook{Store: fx.rel, suffix: "/request.json", hook: func() {
+ auditedFirst = dbReadAudited(t, fx.st)
+ }}
+ fx.srv.dbf.pickup = 100 * time.Millisecond
+ body, _ := queryBody(t, "SELECT 1")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+ if !auditedFirst {
+ t.Fatal("request.json was written before the audit row")
+ }
+ })
+ for _, c := range []struct {
+ step string
+ audited bool
+ requests, queued, cancels int
+ }{
+ {"audit", false, 0, 0, 0},
+ {"request", true, 0, 0, 0},
+ {"queue", true, 1, 0, 1},
+ {"serial", true, 1, 1, 1},
+ } {
+ t.Run("ended before "+c.step, func(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ _, serialBefore, _ := fx.rel.Get(context.Background(), release.SerialKey)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ fx.srv.dbf.beforeWrite = func(step string) {
+ if step == c.step {
+ cancel()
+ }
+ }
+ rec := fx.dbfServe(t, ctx, "SELECT 1")
+ // The ended path writes no response (nobody is there to read
+ // it), and a recorder never written reports 200: read the body.
+ if strings.Contains(rec.Body.String(), "admitted") {
+ t.Fatalf("an ended request was admitted: %s", rec.Body)
+ }
+ if _, serialAfter, _ := fx.rel.Get(context.Background(), release.SerialKey); serialAfter != serialBefore {
+ t.Fatal("the serial was bumped after the request ended")
+ }
+ requests, queued, cancels := dbfBucket(t, fx.rel)
+ if got := dbReadAudited(t, fx.st); got != c.audited || requests != c.requests || queued != c.queued || cancels != c.cancels {
+ t.Fatalf("audited %v, requests %d, queue entries %d, cancels %d", got, requests, queued, cancels)
+ }
+ })
+ }
+ t.Run("ended during the serial read", func(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ _, serialBefore, _ := fx.rel.Get(context.Background(), release.SerialKey)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ fx.srv.cfg.Releases = &dbfCtxStore{Store: fx.rel, key: release.SerialKey, onGet: cancel}
+ fx.dbfServe(t, ctx, "SELECT 1")
+ if _, serialAfter, _ := fx.rel.Get(context.Background(), release.SerialKey); serialAfter != serialBefore {
+ t.Fatal("the serial was written after the request ended during the bump")
+ }
+ })
+}
+
+// Plan review finding 13: a body delivered slowly is cut at s.dbf.preHeader,
+// well inside backhaul's 30 s header wait, and admits nothing.
+// Mutation: drop the preHeader read deadline, keeping only the bound's (red:
+// the connection is still open at 3 s).
+func TestDBReadStalledBodyIsCutAtThePreHeaderBound(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.preHeader = 300 * time.Millisecond
+ conn, err := net.Dial("tcp", strings.TrimPrefix(fx.ts.URL, "http://"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ path := strings.TrimPrefix(fx.readURL(dbfHost), fx.ts.URL)
+ fmt.Fprintf(conn, "POST %s HTTP/1.1\r\nHost: console\r\nAuthorization: Bearer %s\r\n"+
+ "Content-Type: application/json\r\nContent-Length: 4096\r\n\r\n{\"op\":", path, fx.member)
+ conn.SetReadDeadline(time.Now().Add(3 * time.Second))
+ start := time.Now()
+ _, err = io.ReadAll(conn) // a refusal, then the close; or the close alone
+ if ne, ok := err.(net.Error); ok && ne.Timeout() {
+ t.Fatalf("the stalled body still held the request after %s", time.Since(start))
+ }
+ if keys, _ := fx.rel.List(context.Background(), dbreads.Prefix); len(keys) != 0 {
+ t.Fatalf("a stalled body wrote %v", keys)
+ }
+}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 90c76a5b6..c55633abb 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -749,6 +749,9 @@ func (s *Server) registerCLIRoutes() {
// production data). admin is refused with the rest.
s.cliRoute("GET /api/cli/apps/{account}/{app}/db/{host}/ltx/{level}", svcrole.Set{}, s.handleAPIDBList)
s.cliRoute("GET /api/cli/apps/{account}/{app}/db/{host}/ltx/{level}/{span}", svcrole.Set{}, s.handleAPIDBGet)
+ // The forwarded read (db region forward spec §9.1): people only, the db
+ // door's whole gate once, then the read inside the same request.
+ s.cliRoute("POST /api/cli/apps/{account}/{app}/db/{host}/reads", svcrole.Set{}, s.handleAPIDBRead)
// The zero Set, deliberately: a credential may never mint a credential,
// including itself. This is the escalation cut (spec §3). It takes no
// authority away — handleAPIInstanceToken gates on apiAccountApp, which
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index f409dfd1e..20b1b8dab 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1467,6 +1467,22 @@ var claimFixtures = map[string]claimFixture{
status: http.StatusConflict,
msg: seedClaimConsoleRefusal().Msg,
}},
+ // The forwarded db read (db region forward spec §6, §9.1) never signs
+ // on a host-claim console (dbForwardSigner): an instance homed outside
+ // the console's region gets main's residency sentence, after the record
+ // read and before anything is written. The console stays in the home
+ // region and the instance is in ie, so the sentence is the residency one.
+ "route POST /api/cli/apps/{account}/{app}/db/{host}/reads": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ setup: func(t *testing.T, cx *claimCase) {
+ cx.movableInstance(t)
+ cx.srv.cfg.HibernateBucket = claimDBBucket
+ cx.srv.cfg.DBForward = true
+ },
+ do: claimRefusedAPI(http.MethodPost, "/api/cli/apps/bab/titogo/db/"+claimDBHost+"/reads", claimDBReadBody),
+ status: http.StatusConflict,
+ msg: claimDBReadResidencyMsg,
+ }},
// carlos run waits for the claim's reservation protocol (#250): every
// run route refuses on a host-claim console (claimUnsupported).
"route POST /api/cli/apps/{account}/{app}/instances/{host}/runs": {refused: &claimRefusalFixture{
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index 5e438dd64..e8f6e40ff 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -58,6 +58,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/dbreads"
"github.com/carlosframework/platform/internal/dnsrec"
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/mail"
@@ -114,10 +115,26 @@ var claimUnsupported = map[string]string{
"no operation gates both, so every transfer is refused",
claimMoveResolveUnavailableMsg: "the operator's door out of a stuck move (CARLOS_MOVES_PHASE1) has only its gate until " +
"the Moves resolution body lands; it answers this sentence and writes nothing",
+ claimDBReadResidencyMsg: "a forwarded db read needs the root signer, which a host-claim console never uses for it " +
+ "(db region forward spec §6): the reads route reads the record and answers main's residency sentence, writing nothing",
seedClaimConsoleRefusal().Msg: "seeded instances need nested boxes, and the claim-armed path waits for #250 (seeded-instances spec §3.4); " +
"every import door refuses before it reads the record, and the legacy route assignment before it reads anything",
}
+// claimDBReadResidencyMsg is main's residency sentence for the claim world's
+// instance (in ie) on a console in the home region: what the forwarded db
+// read answers on a host-claim console. claimDBReadBody is a valid read.
+var (
+ claimDBReadResidencyMsg = claimDBHost + " keeps its data in region ie. This console can only read data kept in the home region."
+ claimDBReadBody = func() string {
+ key, err := dbreads.NewReplyKey()
+ if err != nil {
+ panic(err)
+ }
+ return `{"op":"query","sql":"SELECT 1","reply_key":"` + dbreads.EncodeReplyKey(key.PublicKey()) + `"}`
+ }()
+)
+
// claimLifecycleRoot is the classifier's NonApp reason for a lifecycle CAS
// root (hostops.ClassifyMutation): a host claim moved, which a refusal must
// never do.
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index bb81d7f5f..92a03ad37 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -168,6 +168,7 @@ route POST /api/cli/apps/{account}/new-temporary
route POST /api/cli/apps/{account}/{app}/build-probe
route POST /api/cli/apps/{account}/{app}/channels/resign
route POST /api/cli/apps/{account}/{app}/config/sync
+route POST /api/cli/apps/{account}/{app}/db/{host}/reads
route POST /api/cli/apps/{account}/{app}/delete
route POST /api/cli/apps/{account}/{app}/domains
route POST /api/cli/apps/{account}/{app}/door-keys