fix(dolt): verify project identity on shared-server connect to an existing DB (Part A) (#5143)

GH#4637: the shared-server connect path (newServerMode) only ran the
project-identity verifier when CreateIfMissing was false. `bd init` always
sets CreateIfMissing:true, so it never verified identity at all — `bd init`
against a shared Dolt server could silently adopt a foreign project's
already-existing database instead of failing.

openServerConnection already computed dbExists internally (to decide
whether to CREATE DATABASE); it now returns that as a fourth value so the
caller can distinguish "connected to a database we just created" from
"connected to a database that was already there". It also corrects
dbExists to true when CREATE DATABASE IF NOT EXISTS itself reports
"database exists" (error 1007) — proof another process won a creation
race the initial SHOW DATABASES probe missed. newServerMode's identity
gate now runs verifyProjectIdentity/verifyGlobalProjectIdentity whenever
CreateIfMissing is false (unchanged) OR the database already existed
(new): a foreign existing database with a different _project_id than
local metadata.json now fails with PROJECT IDENTITY MISMATCH instead of
silently connecting. A genuinely new database (CreateIfMissing:true, did
not exist) still skips verification unchanged, and the existing soft-skip
behavior (missing local metadata.json, empty _project_id on either side)
is preserved. The gate also now runs before store.initSchema instead of
after, so a foreign existing database is rejected before bd's migrations
and Dolt commits are written into it — the old ordering predates this
change, but this change is what routes `bd init` into it for the first
time, so the exposure was new.

Gateway mode is excluded from the new check, but via the return value
rather than an extra condition at the gate: openServerConnection's
Gateway branch never probes existence (a successful ping is its only
existence signal), so it always reports dbAlreadyExisted == false and
the gate's `dbAlreadyExisted` clause never fires for Gateway. That is
intentional, not a leftover gap — cmd/bd/init.go's resolveInitProjectID
already implements the correct identity handling for gateway: reconciling
a stale or missing local project_id onto the server-authoritative one on
every init, including re-init, which depends on this open not
hard-failing first. Forcing verification here would break that adoption
flow instead of running it.

This is Part A only: the narrow fix for CreateIfMissing bypassing
verification against an existing database. It intentionally does not
address a foreign Dolt server that has no beads database at all (no
sentinel/UUID mechanism is added here) — that is a separate design
question tracked as mybd-y18b.

Tests are folded into internal/storage/dolt/cross_project_test.go, the
existing home for this "two projects share one Dolt server" scenario
family, rather than a new file: foreign-database rejection, a matching-id
positive control, genuinely-new-database success, both soft-skip paths
(no local metadata.json; database has no _project_id), and a dedicated
Gateway-skips-verification test documenting why that branch must stay
that way.

Agent-Signature: claude-code-sonnet-medium on behalf of matt wilkie
This commit is contained in:
matt wilkie 2026-07-31 01:40:54 -07:00 • committed by GitHub
commit 37de287127
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 386 additions and 40 deletions

View file

@ -113,12 +113,17 @@ func resolveInitIssuePrefix(gateway bool, existing, dbName, prefix string, readE
// Gateway: the hosted database's identity is server-authoritative, so an adopted
// server id always wins and is reconciled onto local even when localID is already
// set. A re-init or orchestrator-preseeded workspace must not keep a stale local
// id: init opens with CreateIfMissing, which skips the storage identity verifier
// (store.go verifyProjectIdentity), so a stale id would be saved as success and
// every later normal open would then hard-fail with PROJECT IDENTITY MISMATCH. A
// missing server id is a provisioning-contract violation bd will not mint over —
// even when a local id already exists — and a read error is surfaced as the
// transient failure it is, so a flaky connection is not misdiagnosed as an
// id: for Gateway specifically, init's CreateIfMissing:true open still skips the
// storage identity verifier (store.go verifyProjectIdentity/newServerMode — see
// its dbAlreadyExisted comment for why Gateway is exempt from the
// otherwise-CreateIfMissing:true check), so a stale id would be saved as success
// and every later normal open would then hard-fail with PROJECT IDENTITY
// MISMATCH. This CreateIfMissing skip is Gateway-only: a non-gateway
// CreateIfMissing:true init against an already-existing database now DOES run
// the verifier (GH#4637 Part A) and fails before reaching this reconciliation.
// A missing server id is a provisioning-contract violation bd will not mint
// over — even when a local id already exists — and a read error is surfaced as
// the transient failure it is, so a flaky connection is not misdiagnosed as an
// unprovisioned database.
//
// Non-gateway (legacy, unchanged): a non-empty localID is kept as-is (readErr
@ -1385,10 +1390,14 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
// at all (a missing identity is a provisioning-contract violation),
// and because the hosted server is authoritative it reconciles the
// identity on every init — even a re-init or preseeded workspace whose
// metadata.json already carries a stale project_id. Otherwise init
// (which opens with CreateIfMissing, skipping the storage identity
// verifier) would save the stale id as success and every later normal
// open would hard-fail with PROJECT IDENTITY MISMATCH.
// metadata.json already carries a stale project_id. This reconciliation
// depends on Gateway's CreateIfMissing:true open skipping the storage
// identity verifier (store.go newServerMode/verifyProjectIdentity) —
// Gateway-only, not init in general: a non-gateway CreateIfMissing:true
// init against an already-existing database now runs the verifier
// (GH#4637 Part A) and fails before this code runs at all. Without the
// Gateway skip, init would save the stale id as success and every later
// normal open would hard-fail with PROJECT IDENTITY MISMATCH.
adoptedFromDB := ""
var adoptReadErr error
if store != nil && shouldConsultInitProjectID(doltCfg.Gateway, cfg.ProjectID, database, bootstrappedFromRemote) {

View file

@ -11,6 +11,9 @@
// - Same issue prefix (worst case for collision detection)
// - Concurrent writes from both projects simultaneously
// - Read isolation (project A never sees project B's issues)
// - Project-identity verification on connect (GH#4637): a CreateIfMissing:true
// open reconnecting to an already-existing database with a mismatched local
// project_id must fail, not silently share the database
//
// Based on tests by @PabloLION (PR #2472).
package dolt
@ -19,11 +22,14 @@ import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/types"
)
@ -668,3 +674,264 @@ func TestCrossProject_ConcurrentReadWriteMix(t *testing.T) {
t.Errorf("TOTAL LEAKAGE EVENTS: %d", leakDetected.Load())
}
}
// =============================================================================
// Test 6: Project-Identity Verification on Connect (GH#4637 Part A)
// =============================================================================
//
// newServerMode's identity gate previously only ran when CreateIfMissing was
// false. `bd init` always sets CreateIfMissing:true, so it never verified
// identity at all — reconnecting to an already-existing database with a
// mismatched local project_id (the shape of `bd init` accidentally targeting
// another project's shared-server database) was silently accepted. These
// tests cover the fixed gate and the cases that must keep working unchanged:
// a genuinely new database, and each of verifyProjectIdentity's soft-skip
// paths (missing local metadata.json, empty project_id on either side).
// identityTestFixture holds a temp beadsDir wired up for identity-check tests:
// a Path for the Dolt client data dir, and a BeadsDir so verifyProjectIdentity
// can find metadata.json.
type identityTestFixture struct {
tmpDir string
beadsDir string
dbName string
}
func newIdentityTestFixture(t *testing.T, namePrefix string) *identityTestFixture {
t.Helper()
tmpDir, err := os.MkdirTemp("", "dolt-identity-"+namePrefix+"-*")
if err != nil {
t.Fatalf("mkdir temp: %v", err)
}
t.Cleanup(func() { os.RemoveAll(tmpDir) })
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("mkdir beadsDir: %v", err)
}
return &identityTestFixture{
tmpDir: tmpDir,
beadsDir: beadsDir,
dbName: uniqueTestDBName(t),
}
}
func (f *identityTestFixture) saveLocalProjectID(t *testing.T, projectID string) {
t.Helper()
if err := (&configfile.Config{ProjectID: projectID}).Save(f.beadsDir); err != nil {
t.Fatalf("save metadata.json: %v", err)
}
}
func (f *identityTestFixture) config() *Config {
return &Config{
Path: filepath.Join(f.tmpDir, "dolt"),
BeadsDir: f.beadsDir,
CommitterName: "test",
CommitterEmail: "test@test.com",
Database: f.dbName,
CreateIfMissing: true,
}
}
func TestCrossProject_IdentityCheck_ExistingDatabase_ForeignRejected(t *testing.T) {
skipIfNoDolt(t)
acquireTestSlot()
t.Cleanup(releaseTestSlot)
ctx, cancel := testContext(t)
defer cancel()
f := newIdentityTestFixture(t, "foreign")
ownerID := "11111111-1111-1111-1111-111111111111"
f.saveLocalProjectID(t, ownerID)
ownerStore, err := New(ctx, f.config())
if err != nil {
t.Fatalf("create owner store: %v", err)
}
if err := ownerStore.SetMetadata(ctx, "_project_id", ownerID); err != nil {
ownerStore.Close()
t.Fatalf("seed _project_id: %v", err)
}
ownerStore.Close()
// A different project's local metadata.json (foreign project id)
// reconnects to the SAME already-existing database with
// CreateIfMissing:true — the exact shape of `bd init` against a shared
// server. This must fail, not silently adopt the database.
foreignID := "22222222-2222-2222-2222-222222222222"
f.saveLocalProjectID(t, foreignID)
foreignStore, err := New(ctx, f.config())
if err == nil {
foreignStore.Close()
t.Fatalf("expected identity mismatch error, got nil (silently connected to foreign project's database)")
}
if !strings.Contains(err.Error(), "PROJECT IDENTITY MISMATCH") {
t.Fatalf("expected PROJECT IDENTITY MISMATCH error, got: %v", err)
}
}
// TestCrossProject_IdentityCheck_ExistingDatabase_MatchingSucceeds is the
// positive control for the rejection test above: the same
// already-existing-database + CreateIfMissing:true shape, but with local
// metadata.json carrying the SAME project id the database already records.
// This must keep succeeding — the fix must not turn ordinary reconnects
// (e.g. a second `bd` invocation against the same project) into failures.
func TestCrossProject_IdentityCheck_ExistingDatabase_MatchingSucceeds(t *testing.T) {
skipIfNoDolt(t)
acquireTestSlot()
t.Cleanup(releaseTestSlot)
ctx, cancel := testContext(t)
defer cancel()
f := newIdentityTestFixture(t, "matching")
projectID := "55555555-5555-5555-5555-555555555555"
f.saveLocalProjectID(t, projectID)
firstStore, err := New(ctx, f.config())
if err != nil {
t.Fatalf("create first store: %v", err)
}
if err := firstStore.SetMetadata(ctx, "_project_id", projectID); err != nil {
firstStore.Close()
t.Fatalf("seed _project_id: %v", err)
}
firstStore.Close()
secondStore, err := New(ctx, f.config())
if err != nil {
t.Fatalf("reconnect with matching project id must succeed, got: %v", err)
}
secondStore.Close()
}
func TestCrossProject_IdentityCheck_NewDatabase_Succeeds(t *testing.T) {
skipIfNoDolt(t)
acquireTestSlot()
t.Cleanup(releaseTestSlot)
ctx, cancel := testContext(t)
defer cancel()
f := newIdentityTestFixture(t, "new")
f.saveLocalProjectID(t, "33333333-3333-3333-3333-333333333333")
store, err := New(ctx, f.config())
if err != nil {
t.Fatalf("creating a brand-new database must still succeed: %v", err)
}
store.Close()
}
// TestCrossProject_IdentityCheck_SoftSkip_NoLocalMetadata covers
// verifyProjectIdentity's soft-skip when the reopening side has no local
// metadata.json at all (localID == ""): this must not be turned into a hard
// failure by the CreateIfMissing:true/dbAlreadyExisted gate.
func TestCrossProject_IdentityCheck_SoftSkip_NoLocalMetadata(t *testing.T) {
skipIfNoDolt(t)
acquireTestSlot()
t.Cleanup(releaseTestSlot)
ctx, cancel := testContext(t)
defer cancel()
f := newIdentityTestFixture(t, "nolocal")
ownerStore, err := New(ctx, f.config())
if err != nil {
t.Fatalf("create owner store: %v", err)
}
if err := ownerStore.SetMetadata(ctx, "_project_id", "44444444-4444-4444-4444-444444444444"); err != nil {
ownerStore.Close()
t.Fatalf("seed _project_id: %v", err)
}
ownerStore.Close()
// No metadata.json written for this reopen — configfile.Load returns nil.
reopenStore, err := New(ctx, f.config())
if err != nil {
t.Fatalf("expected soft-skip (no local metadata.json), got error: %v", err)
}
reopenStore.Close()
}
// TestCrossProject_IdentityCheck_SoftSkip_EmptyDBProjectID covers
// verifyProjectIdentity's other soft-skip: a local project_id is set, but the
// database itself has no _project_id recorded (an old-style database that
// predates the identity field). This must not be turned into a hard failure
// either — only a database that records a DIFFERENT non-empty _project_id is
// rejected.
func TestCrossProject_IdentityCheck_SoftSkip_EmptyDBProjectID(t *testing.T) {
skipIfNoDolt(t)
acquireTestSlot()
t.Cleanup(releaseTestSlot)
ctx, cancel := testContext(t)
defer cancel()
f := newIdentityTestFixture(t, "emptydb")
// Create the database but never seed _project_id — simulating an
// old-style database from before GH#2372.
ownerStore, err := New(ctx, f.config())
if err != nil {
t.Fatalf("create owner store: %v", err)
}
ownerStore.Close()
f.saveLocalProjectID(t, "66666666-6666-6666-6666-666666666666")
reopenStore, err := New(ctx, f.config())
if err != nil {
t.Fatalf("expected soft-skip (database has no _project_id), got error: %v", err)
}
reopenStore.Close()
}
// TestCrossProject_IdentityCheck_Gateway_SkipsVerification covers the one
// branch newServerMode's identity gate deliberately does NOT enforce:
// Gateway mode. openServerConnection never probes existence for a gateway
// database (see its Gateway branch), so it always reports dbAlreadyExisted
// == false and the CreateIfMissing:true/dbAlreadyExisted check never fires
// for Gateway — even though the database plainly does already exist
// server-side. This is intentional: cmd/bd/init.go's resolveInitProjectID
// reconciles a stale or mismatched local project_id onto the
// server-authoritative one on every gateway init instead of failing at open.
// A future cleanup that "closes" the Gateway exemption here would break that
// reconciliation flow — this test exists so that change has to update this
// assertion, not just delete a condition.
func TestCrossProject_IdentityCheck_Gateway_SkipsVerification(t *testing.T) {
skipIfNoDolt(t)
acquireTestSlot()
t.Cleanup(releaseTestSlot)
ctx, cancel := testContext(t)
defer cancel()
f := newIdentityTestFixture(t, "gateway")
ownerID := "77777777-7777-7777-7777-777777777777"
f.saveLocalProjectID(t, ownerID)
// Seed schema and _project_id with a normal (non-gateway) open first.
ownerStore, err := New(ctx, f.config())
if err != nil {
t.Fatalf("create owner store: %v", err)
}
if err := ownerStore.SetMetadata(ctx, "_project_id", ownerID); err != nil {
ownerStore.Close()
t.Fatalf("seed _project_id: %v", err)
}
ownerStore.Close()
// Reopen the SAME already-existing database in Gateway mode, with a
// mismatched local project_id. A non-gateway CreateIfMissing:true open in
// this shape is rejected (see the ForeignRejected test above) — Gateway
// must NOT be, because identity is reconciled by resolveInitProjectID,
// not enforced here.
mismatchedID := "88888888-8888-8888-8888-888888888888"
f.saveLocalProjectID(t, mismatchedID)
gatewayCfg := f.config()
gatewayCfg.Gateway = true
gatewayStore, err := New(ctx, gatewayCfg)
if err != nil {
t.Fatalf("gateway open must skip identity verification (reconciled by resolveInitProjectID instead), got error: %v", err)
}
gatewayStore.Close()
}

View file

@ -1708,7 +1708,7 @@ func newServerMode(ctx context.Context, cfg *Config) (*DoltStore, error) {
}
// Server mode: connect via MySQL protocol to dolt sql-server
db, connStr, createdDatabase, err := openServerConnection(ctx, cfg)
db, connStr, dbFacts, err := openServerConnection(ctx, cfg)
if err != nil {
return nil, err
}
@ -1759,17 +1759,38 @@ func newServerMode(ctx context.Context, cfg *Config) (*DoltStore, error) {
if err := schema.CheckForwardDrift(ctx, db); err != nil {
return nil, err
}
// A gateway server owns the schema: it provisions each project at its deployed bd
// version, so a client must never run migrations (DDL) against it. Treat it like
// ReadOnly for schema — the forward-drift guard above still protects a stale client
// binary.
if !cfg.ReadOnly && !cfg.Gateway {
if err := store.initSchema(ctx, createdDatabase); err != nil {
return nil, fmt.Errorf("failed to initialize schema: %w", err)
}
}
if !cfg.CreateIfMissing {
// Identity verification runs whenever we did not just create the database
// ourselves: the classic !CreateIfMissing "connect to an existing DB" path,
// and — critically — the CreateIfMissing:true "init" path when the target
// database turns out to already exist on the server. Without the latter,
// `bd init` against a shared server silently adopts a foreign project's
// existing database instead of failing, because CreateIfMissing:true used
// to skip the check unconditionally regardless of whether anything was
// actually created (GH#4637). A genuinely new database (dbAlreadyExisted
// == false) still skips verification: there is nothing to compare against
// yet, and the per-field soft-skips below already make this a no-op for a
// brand-new database in the !CreateIfMissing case too.
//
// This must run BEFORE store.initSchema below: initSchema runs migrations
// and Dolt commits against the database, so verifying first means a
// foreign existing database is rejected before bd writes anything into
// it, not after. On a database with no bd schema yet, GetMetadata errors
// and the verifier soft-skips, so this ordering does not change behavior
// for a genuinely fresh database.
//
// Gateway is effectively excluded from the alreadyExisted branch because
// openServerConnection never probes existence for it (see the Gateway
// branch below) and always returns alreadyExisted == false: gateway
// identity is not enforced here at all. That is deliberate, not an
// oversight — a hosted database's identity is server-authoritative, and
// cmd/bd/init.go already implements the correct reconciliation for it via
// resolveInitProjectID, adopting the server's _project_id onto a stale or
// missing local one on every init, including re-init, which relies on
// this open not hard-failing first. This gap is specific to Part A's
// server-existence check; it does not reopen the separate "foreign
// server, no bd database at all" gap tracked as Part B (mybd-y18b).
if !cfg.CreateIfMissing || dbFacts.alreadyExisted {
var verifyErr error
if cfg.Database == doltserver.GlobalDatabaseName {
verifyErr = store.verifyGlobalProjectIdentity(ctx, cfg.BeadsDir)
@ -1781,6 +1802,16 @@ func newServerMode(ctx context.Context, cfg *Config) (*DoltStore, error) {
}
}
// A gateway server owns the schema: it provisions each project at its deployed bd
// version, so a client must never run migrations (DDL) against it. Treat it like
// ReadOnly for schema — the forward-drift guard above still protects a stale client
// binary.
if !cfg.ReadOnly && !cfg.Gateway {
if err := store.initSchema(ctx, dbFacts.created); err != nil {
return nil, fmt.Errorf("failed to initialize schema: %w", err)
}
}
if isLocalHost(cfg.ServerHost) {
beadsDir := cfg.BeadsDir
if beadsDir == "" && cfg.Path != "" {
@ -2054,17 +2085,36 @@ func applyPoolLimits(db *sql.DB, cfg *Config) {
db.SetConnMaxIdleTime(idle)
}
// openServerConnection opens a connection to a dolt sql-server via MySQL
// protocol. The returned bool reports whether THIS call created the target
// database (see the bare-CREATE ownership arbitration below) — server-mode's
// analog of the uow path's `created` signal (#5042), threaded through to
// initSchema so only the proven creator arms schema.WithFreshBootstrapHeal.
func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bool, error) {
// serverConnFacts reports what openServerConnection established about the
// target database while connecting. The two fields are deliberately NOT
// inverses of each other: for a gateway database, existence is never probed,
// so both are false — neither "we created it" nor "it was already there" is
// proven, and each caller's gate must fail closed on its own terms.
type serverConnFacts struct {
// created reports whether THIS call's bare CREATE DATABASE won the
// ownership arbitration and actually created the database — server-mode's
// analog of the uow path's `created` signal (#5042). Threaded through to
// initSchema so only the proven creator arms schema.WithFreshBootstrapHeal.
created bool
// alreadyExisted reports whether the database was proven to exist on the
// server before this call: either the SHOW DATABASES probe found it, or
// our CREATE DATABASE was refused with "database exists" (1007). Callers
// use it to decide whether project-identity verification applies even
// when CreateIfMissing is true (see the newServerMode gate around
// verifyProjectIdentity, GH#4637).
alreadyExisted bool
}
// openServerConnection connects to (and if needed creates) the target database
// on a dolt sql-server via MySQL protocol. See serverConnFacts for what the
// returned facts mean and why they are not a single bool.
func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, serverConnFacts, error) {
connStr := buildServerDSN(cfg, cfg.Database)
db, err := sql.Open("mysql", connStr)
if err != nil {
return nil, "", false, fmt.Errorf("failed to open Dolt server connection: %w", err)
return nil, "", serverConnFacts{}, fmt.Errorf("failed to open Dolt server connection: %w", err)
}
// Configure the pool. *sql.DB is safe for concurrent use and manages its
@ -2089,11 +2139,21 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bo
// above would close the *sql.DB we just handed the caller.
if cfg.Gateway {
if err := db.PingContext(ctx); err != nil {
return nil, "", false, fmt.Errorf("failed to connect to gateway server %s:%d (database %q): %w",
return nil, "", serverConnFacts{}, fmt.Errorf("failed to connect to gateway server %s:%d (database %q): %w",
cfg.ServerHost, cfg.ServerPort, cfg.Database, err)
}
connReady = true
return db, connStr, false, nil
// Neither fact is established for a gateway database: we did not
// create it, and existence was never probed, so we cannot honestly
// report alreadyExisted either. The zero value is what the
// newServerMode caller relies on to skip its alreadyExisted-forced
// identity check for Gateway. That is intentional, not a leftover
// gap: gateway identity is reconciled (not enforced at open) by
// cmd/bd/init.go's resolveInitProjectID, which adopts the
// server-authoritative _project_id onto a stale or missing local one
// on every init, including re-init. It is also correct for `created`:
// an unproven creator must never arm fresh-bootstrap heal.
return db, connStr, serverConnFacts{}, nil
}
// Ensure database exists (may need to create it)
@ -2101,13 +2161,13 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bo
initConnStr := buildServerDSN(cfg, "")
initDB, err := sql.Open("mysql", initConnStr)
if err != nil {
return nil, "", false, fmt.Errorf("failed to open init connection: %w", err)
return nil, "", serverConnFacts{}, fmt.Errorf("failed to open init connection: %w", err)
}
defer func() { _ = initDB.Close() }()
// Validate database name to prevent SQL injection via backtick escaping
if err := ValidateDatabaseName(cfg.Database); err != nil {
return nil, "", false, fmt.Errorf("invalid database name %q: %w", cfg.Database, err)
return nil, "", serverConnFacts{}, fmt.Errorf("invalid database name %q: %w", cfg.Database, err)
}
// FIREWALL: Never create test databases on the production server.
@ -2116,7 +2176,7 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bo
// Production-port detection generalized via isProductionPort so non-3307
// production deployments are covered (AD-01).
if isTestDatabaseName(cfg.Database) && isProductionPort(cfg) {
return nil, "", false, fmt.Errorf(
return nil, "", serverConnFacts{}, fmt.Errorf(
"REFUSED: will not CREATE DATABASE %q on production port %d — "+
"this is a test database name on the production server (see DOLT-WAR-ROOM.md)",
cfg.Database, cfg.ServerPort)
@ -2125,6 +2185,10 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bo
// Check if the database already exists before deciding whether to create it.
// This prevents the shadow database bug: without CreateIfMissing, connecting
// to a server that lacks the expected database is an error (not silent creation).
// The result also feeds the caller's identity-verification gate: a
// CreateIfMissing:true init that lands on an already-existing database
// must still verify project identity (GH#4637) — only a database this
// call creates from scratch is exempt.
//
// Uses SHOW DATABASES + iterate for exact match instead of SHOW DATABASES LIKE,
// because LIKE treats _ and % as wildcards and Dolt does not support backslash
@ -2132,7 +2196,7 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bo
// match unrelated databases with LIKE.
dbExists, checkErr := databaseExistsOnServer(ctx, initDB, cfg.Database)
if checkErr != nil {
return nil, "", false, fmt.Errorf("failed to check if database %q exists on server %s:%d: %w",
return nil, "", serverConnFacts{}, fmt.Errorf("failed to check if database %q exists on server %s:%d: %w",
cfg.Database, cfg.ServerHost, cfg.ServerPort, checkErr)
}
@ -2147,7 +2211,7 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bo
created := false
if !dbExists {
if !cfg.CreateIfMissing {
return nil, "", false, databaseNotFoundError(cfg)
return nil, "", serverConnFacts{}, databaseNotFoundError(cfg)
}
// Bare CREATE DATABASE (no IF NOT EXISTS): the server arbitrates
@ -2165,13 +2229,19 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bo
if !strings.Contains(errLower, "database exists") && !strings.Contains(errLower, "1007") {
// Check for connection refused - server likely not running
if strings.Contains(errLower, "connection refused") || strings.Contains(errLower, "connect: connection refused") {
return nil, "", false, fmt.Errorf("failed to connect to Dolt server at %s:%d: %w\n\nThe Dolt server may not be running. Try:\n bd dolt start # Start a local server\n gt dolt start # If using an orchestrator",
return nil, "", serverConnFacts{}, fmt.Errorf("failed to connect to Dolt server at %s:%d: %w\n\nThe Dolt server may not be running. Try:\n bd dolt start # Start a local server\n gt dolt start # If using an orchestrator",
cfg.ServerHost, cfg.ServerPort, err)
}
return nil, "", false, fmt.Errorf("failed to create database: %w", err)
return nil, "", serverConnFacts{}, fmt.Errorf("failed to create database: %w", err)
}
// Lost the create race (or a benign TOCTOU with the dbExists
// check above): not ours, heal stays off.
// check above): not ours, heal stays off. The refusal IS proof of
// existence, though — another process won the CREATE DATABASE
// race between our SHOW DATABASES probe and this call — so
// correct dbExists even though the probe reported false. The
// caller's identity-verification gate depends on this being
// accurate, not just on the initial probe.
dbExists = true
}
}
@ -2193,11 +2263,11 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, bo
}
return nil
}, backoff.WithContext(bo, ctx)); err != nil {
return nil, "", false, fmt.Errorf("database %q not available after CREATE DATABASE: %w", cfg.Database, err)
return nil, "", serverConnFacts{}, fmt.Errorf("database %q not available after CREATE DATABASE: %w", cfg.Database, err)
}
connReady = true
return db, connStr, created, nil
return db, connStr, serverConnFacts{created: created, alreadyExisted: dbExists}, nil
}
// databaseExistsOnServer checks if a database with the exact given name exists