carlos / platform Public

db forward: T1 and T16 against MinIO with per-region credentials (plan 2, Task 12)

Not run locally (no MinIO on this machine; the plan says not to fetch
one). The same flow passed over shared DirStores in a scratch dry run;
CI's 30-minio-contract step is its first real run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 276d9e0efcd1e2431d4925daf576c77ef7993523 parent 7b8720a
3 files changed, +342 −0
  • .amadan/ci.d/30-minio-contract +50 −0
  • internal/console/dbforward_minio_test.go +280 −0
  • internal/console/server_test.go +12 −0

CI failed — run details

diff --git a/.amadan/ci.d/30-minio-contract b/.amadan/ci.d/30-minio-contract
index a0834406b..85e37e31a 100755
--- a/.amadan/ci.d/30-minio-contract
+++ b/.amadan/ci.d/30-minio-contract
@@ -388,4 +388,54 @@ if ! grep -q '^--- PASS: TestT4StorageProbeMinio (' "$out2"; then
exit 1
fi
+# The forwarded db read (db region forward plan 2: T1 and T16): one
+# deployment bucket, versioned, and a data bucket per region, on the one
+# server. The console user cannot read uk's data bucket; the uk box user
+# can. Neither may delete: the protocol deletes nothing (J4), so a delete
+# would fail at the server as well as in the tests' store wrappers.
+"$mc" --quiet mb local/dbf-deploy local/dbf-data-ie local/dbf-data-uk
+"$mc" --quiet version enable local/dbf-deploy
+cat >"$rundir/dbf-console.json" <<'EOF'
+{"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::dbf-deploy", "arn:aws:s3:::dbf-data-ie"]},
+ {"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": ["arn:aws:s3:::dbf-deploy/*"]},
+ {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::dbf-data-ie/*"]}
+]}
+EOF
+cat >"$rundir/dbf-ukbox.json" <<'EOF'
+{"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::dbf-deploy", "arn:aws:s3:::dbf-data-uk"]},
+ {"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": ["arn:aws:s3:::dbf-deploy/*"]},
+ {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::dbf-data-uk/*"]}
+]}
+EOF
+"$mc" --quiet admin policy create local dbf-console "$rundir/dbf-console.json"
+"$mc" --quiet admin policy create local dbf-ukbox "$rundir/dbf-ukbox.json"
+"$mc" --quiet admin user add local dbfconsole dbfconsolesecret1
+"$mc" --quiet admin user add local dbfukbox dbfukboxsecret1
+"$mc" --quiet admin policy attach local dbf-console --user dbfconsole
+"$mc" --quiet admin policy attach local dbf-ukbox --user dbfukbox
+
+out3=$rundir/test-dbf.log
+set +e
+CARLOS_MINIO_TEST=1 \
+ MINIO_ENDPOINT="http://127.0.0.1:$port" \
+ DBF_ROOT_KEY="$root_user" DBF_ROOT_SECRET="$root_pass" \
+ DBF_CONSOLE_KEY=dbfconsole DBF_CONSOLE_SECRET=dbfconsolesecret1 \
+ DBF_BOX_KEY=dbfukbox DBF_BOX_SECRET=dbfukboxsecret1 \
+ go test ./internal/console/ -run 'TestDBForwardMinio' -count=1 -v >"$out3" 2>&1
+test_status=$?
+set -e
+cat "$out3"
+if [ "$test_status" -ne 0 ]; then
+ exit "$test_status"
+fi
+if ! grep -q '^--- PASS: TestDBForwardMinio (' "$out3"; then
+ echo >&2
+ echo "the forwarded db read test did not PASS: it was skipped, filtered out, or renamed." >&2
+ echo "It skips unless CARLOS_MINIO_TEST=1. Check the env block above and that" >&2
+ echo "TestDBForwardMinio still exists in internal/console." >&2
+ exit 1
+fi
+
echo "minio contract: PASS"
diff --git a/internal/console/dbforward_minio_test.go b/internal/console/dbforward_minio_test.go
new file mode 100644
index 000000000..ce20a55dd
--- /dev/null
+++ b/internal/console/dbforward_minio_test.go
@@ -0,0 +1,280 @@
+package console
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ lss3 "github.com/benbjohnson/litestream/s3"
+
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+ "github.com/carlosframework/platform/internal/dbreads"
+ "github.com/carlosframework/platform/internal/dbreads/dbreadstest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// uploadReplica writes a file replica's LTX files into an S3 replica the way
+// a box's litestream does (WriteLTXFile), level by level.
+func uploadReplica(t *testing.T, from *lsfile.ReplicaClient, to *lss3.ReplicaClient) {
+ t.Helper()
+ ctx := context.Background()
+ for level := 0; level <= litestream.SnapshotLevel; level++ {
+ itr, err := from.LTXFiles(ctx, level, 0, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for itr.Next() {
+ f := itr.Item()
+ rc, err := from.OpenLTXFile(ctx, level, f.MinTXID, f.MaxTXID, 0, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := to.WriteLTXFile(ctx, level, f.MinTXID, f.MaxTXID, rc); err != nil {
+ t.Fatal(err)
+ }
+ rc.Close()
+ }
+ itr.Close()
+ }
+}
+
+// dbfGateStore holds the box's chunk and result creates, once armed, until
+// release closes, and records when each landed: T16 needs a box that
+// publishes only after the console has ended the request (plan review
+// finding 19).
+type dbfGateStore struct {
+ release.Store
+ mu sync.Mutex
+ open chan struct{}
+ reached chan struct{}
+ once *sync.Once
+ landed []time.Time
+}
+
+func (g *dbfGateStore) arm() {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.open, g.reached, g.once, g.landed = make(chan struct{}), make(chan struct{}), &sync.Once{}, nil
+}
+
+func (g *dbfGateStore) release() {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ close(g.open)
+}
+
+func (g *dbfGateStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ g.mu.Lock()
+ open, reached, once := g.open, g.reached, g.once
+ g.mu.Unlock()
+ if open == nil || !(strings.Contains(key, "/out/") || strings.HasSuffix(key, "/result.json")) {
+ return g.Store.Put(ctx, key, body, ifMatch)
+ }
+ once.Do(func() { close(reached) })
+ <-open
+ etag, err := g.Store.Put(ctx, key, body, ifMatch)
+ if err == nil {
+ g.mu.Lock()
+ g.landed = append(g.landed, time.Now())
+ g.mu.Unlock()
+ }
+ return etag, err
+}
+
+func (g *dbfGateStore) landedAfter(t time.Time) (n int, early bool) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ for _, at := range g.landed {
+ if !at.After(t) {
+ early = true
+ }
+ }
+ return len(g.landed), early
+}
+
+// TestDBForwardMinio is T1 and T16 against a real S3 server: a console in ie
+// and a box in uk sharing one deployment bucket (versioned), each with its
+// own data bucket and its own credentials, on one endpoint (spec §12). The
+// console's credentials cannot read uk's bucket (a MinIO policy), so a
+// console that read it would fail. Two tenants in uk each get their own
+// rows. Neither the console nor the box ever deletes or replaces anything
+// under db-reads/, and a box's writes after the request ended change
+// nothing. It runs only where .amadan/ci.d/30-minio-contract stands MinIO
+// up; the box is plan 1's real code joined in process (dbreadstest).
+func TestDBForwardMinio(t *testing.T) {
+ if os.Getenv("CARLOS_MINIO_TEST") != "1" {
+ t.Skip("set CARLOS_MINIO_TEST=1 (with a running MinIO and the DBF_* variables) to run; see .amadan/ci.d/30-minio-contract")
+ }
+ need := func(name string) string {
+ v := os.Getenv(name)
+ if v == "" {
+ t.Fatalf("%s is not set", name)
+ }
+ return v
+ }
+ endpoint := need("MINIO_ENDPOINT")
+ rootKey, rootSecret := need("DBF_ROOT_KEY"), need("DBF_ROOT_SECRET")
+ consoleKey, consoleSecret := need("DBF_CONSOLE_KEY"), need("DBF_CONSOLE_SECRET")
+ boxKey, boxSecret := need("DBF_BOX_KEY"), need("DBF_BOX_SECRET")
+ store := func(key, secret, bucket string) *release.S3Store {
+ return &release.S3Store{Bucket: bucket, Client: awss3.New(awss3.Options{
+ Region: "us-east-1", Credentials: credentials.NewStaticCredentialsProvider(key, secret, ""),
+ BaseEndpoint: aws.String(endpoint), UsePathStyle: true,
+ RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
+ ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
+ })}
+ }
+ replica := func(key, secret, bucket, prefix string) *lss3.ReplicaClient {
+ c := lss3.NewReplicaClient()
+ c.AccessKeyID, c.SecretAccessKey, c.Region, c.Bucket, c.Path, c.Endpoint, c.ForcePathStyle =
+ key, secret, "us-east-1", bucket, prefix, endpoint, true
+ return c
+ }
+ run := strconv.FormatInt(time.Now().UnixNano(), 36)
+ shop, other := "shop-"+run+".example.com", "other-"+run+".example.com"
+ for host, batches := range map[string]int{shop: 3, other: 1} {
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, batches)
+ uploadReplica(t, lsfile.NewReplicaClient(dir), replica(rootKey, rootSecret, "dbf-data-uk", "instances/"+host))
+ }
+
+ // The policy, shown: the console's credentials cannot list uk's bucket.
+ itr, err := replica(consoleKey, consoleSecret, "dbf-data-uk", "instances/"+shop).LTXFiles(context.Background(), 0, 0, false)
+ if err == nil {
+ for itr.Next() {
+ }
+ err = itr.Err()
+ itr.Close()
+ }
+ if err == nil {
+ t.Fatal("the console's credentials read uk's data bucket: the test proves nothing")
+ }
+
+ deploy := store(consoleKey, consoleSecret, "dbf-deploy")
+ fx := newConsoleFixtureOn(t, true, strictStore{Store: deploy, t: t})
+ fx.srv.cfg.DBForward, fx.srv.cfg.Region, fx.srv.cfg.HibernateBucket = true, "ie", "dbf-data-ie"
+ fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ return replica(consoleKey, consoleSecret, "dbf-data-ie", prefix), nil // the only data bucket this console has
+ }
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.AddMember(OpsAccountID, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ member := cliToken(t, fx, "member@example.com", "code-minio")
+ for _, host := range []string{shop, other} {
+ putShopRecord(t, fx, provision.Record{Host: host, Region: "uk", CreatedAt: time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)})
+ }
+ putEdgesFile(t, fx.rel, "uk-"+run, "uk", []string{dbreads.Capability}, false)
+ putBoxStatus(t, fx.rel, "uk-"+run, time.Now())
+ gate := &dbfGateStore{Store: store(boxKey, boxSecret, "dbf-deploy")}
+ box := dbreadstest.Start(t, dbreadstest.Options{
+ Store: strictStore{Store: gate, t: t}, Region: "uk", Box: "uk-" + run,
+ Pub: fx.pub, HibernatePrefix: "instances",
+ OpenReplica: func(_ context.Context, prefix string) (dbdoor.ReplicaReader, error) {
+ return replica(boxKey, boxSecret, "dbf-data-uk", prefix), nil
+ },
+ })
+ runBox(t, box)
+ dfx := &dbfFixture{consoleFixture: fx, member: member}
+
+ // T1: a forwarded query end to end, for each tenant, each its own rows.
+ for host, want := range map[string]string{shop: "n\n30\n", other: "n\n10\n"} {
+ body, key := queryBody(t, "SELECT count(*) AS n FROM t")
+ res := dfx.openRead(t, host, member, body)
+ lines := readLines(t, res.Body)
+ res.Body.Close()
+ if rows, _ := openAnswer(t, key, lines); string(rows) != want {
+ t.Fatalf("%s: %q, want %q", host, rows, want)
+ }
+ }
+
+ // T16 (plan review finding 19): the real box reaches publication and is
+ // held there; the console's request ends, by disconnect and then by its
+ // bound; only then does the box publish. Its late chunks and result land
+ // after the console ended, change nothing the console sends, and the
+ // strict stores see no delete and no replacing write from either side.
+ late := func(t *testing.T, end func(res *http.Response, br *bufio.Reader)) {
+ gate.arm()
+ body, _ := queryBody(t, "SELECT count(*) AS n FROM t")
+ res := dfx.openRead(t, shop, member, body)
+ br := bufio.NewReader(res.Body)
+ line, _ := br.ReadBytes('\n')
+ var adm dbreads.Line
+ json.Unmarshal(line, &adm)
+ end(res, br)
+ // The handler's last act is the cancel: once it is there, the
+ // console has ended the request.
+ waitKey := func(key string) {
+ deadline := time.Now().Add(60 * time.Second)
+ for {
+ if _, _, err := deploy.Get(context.Background(), key); err == nil {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("no %s", key)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ }
+ waitKey(dbreads.CancelKey(adm.Admitted))
+ consoleEnded := time.Now()
+ select {
+ case <-gate.reached:
+ case <-time.After(60 * time.Second):
+ t.Fatal("the box never reached publication")
+ }
+ if keys, _ := deploy.List(context.Background(), dbreads.OutPrefix(adm.Admitted)); len(keys) != 0 {
+ t.Fatalf("output published before the console ended: %v", keys)
+ }
+ gate.release()
+ waitKey(dbreads.ResultKey(adm.Admitted))
+ // At least the result lands late; a held chunk lands too unless the
+ // owner's cancel watch ended its create first (plan 1's watchCancel).
+ if n, early := gate.landedAfter(consoleEnded); n < 1 || early {
+ t.Fatalf("%d late writes, any before the console ended: %v", n, early)
+ }
+ }
+ t.Run("by disconnect", func(t *testing.T) {
+ late(t, func(res *http.Response, _ *bufio.Reader) {
+ select {
+ case <-gate.reached:
+ case <-time.After(60 * time.Second):
+ t.Fatal("the box never reached publication")
+ }
+ res.Body.Close()
+ })
+ })
+ t.Run("by timeout", func(t *testing.T) {
+ // The request's own bound, well past the box's restore and query of
+ // three batches, well short of the box's 20-minute owner deadline.
+ fx.srv.dbf.bound, fx.srv.dbf.grace = 20*time.Second, 0
+ late(t, func(res *http.Response, br *bufio.Reader) {
+ defer res.Body.Close()
+ lines := readLines(t, br)
+ if last := lines[len(lines)-1]; last.Ended != dbreads.EndedNoResult {
+ t.Fatalf("by timeout: %+v", last)
+ }
+ for _, l := range lines {
+ if l.Chunk != 0 || l.Result != nil {
+ t.Fatalf("a held box's output reached the console: %+v", l)
+ }
+ }
+ })
+ })
+}
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
index 1d43c7dc5..cfad24697 100644
--- a/internal/console/server_test.go
+++ b/internal/console/server_test.go
@@ -47,8 +47,20 @@ func newConsoleFixture(t *testing.T) *consoleFixture {
// newConsoleFixtureKeyed builds the fixture with or without the channel
// signing key (withKey=false is the read-only deployment shape).
func newConsoleFixtureKeyed(t *testing.T, withKey bool) *consoleFixture {
+ return newConsoleFixtureOn(t, withKey, nil)
+}
+
+// newConsoleFixtureOn is newConsoleFixtureKeyed over rel, when rel is not
+// nil, instead of the fixture's seeded DirStore.
+func newConsoleFixtureOn(t *testing.T, withKey bool, rel release.Store) *consoleFixture {
t.Helper()
regPath, relStore, priv, pub := buildFixtures(t)
+ // A test that needs a real S3 store (TestDBForwardMinio) passes its own;
+ // the fixture's seeded releases are then absent, which those tests do not
+ // read.
+ if rel != nil {
+ relStore = rel
+ }
st, err := Open(filepath.Join(t.TempDir(), "console.db"))
if err != nil {
t.Fatal(err)