diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 19ea255a3..f87a0add2 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -639,6 +639,15 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fromJSONL: fromJSONL, nonInteractive: nonInteractive, }); err != nil { + // runInitProxiedServer runs the same checkExistingBeadsData + // the route below does, but it runs it inside itself — so + // --init-if-missing used to end here as a plain exit-1 + // "Aborting.", and its mismatch guards never ran at all. The + // check happens before any .beads/ write, so nothing has been + // touched by the time we get this error. + if initIfMissing && !reinitLocal && errors.Is(err, errWorkspaceAlreadyInitialized) { + return resolveInitIfMissingAlreadyInitialized(cmd, database, prefix, quiet) + } return err } return nil @@ -771,26 +780,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // directory) must still abort rather than be masked as a // successful skip. if initIfMissing && errors.Is(err, errWorkspaceAlreadyInitialized) { - // Guard against masking a genuine mismatch: an explicit - // --prefix or --database that does not match the existing - // workspace must abort, since silently skipping would ignore - // the request and reuse a different database. --database is - // the authoritative selector, so it is checked even when - // --prefix is also set. - existing := existingWorkspaceDBName() - if cmd.Flags().Changed("database") { - if initIfMissingDatabaseMismatch(existing, database) { - return fmt.Errorf("workspace already initialized as database %q, but --database %q was requested.\nRemove --database (or pass a matching value) to reuse the existing workspace", existing, database) - } - } else if cmd.Flags().Changed("prefix") { - if initIfMissingPrefixMismatch(existing, prefix) { - return fmt.Errorf("workspace already initialized as database %q, but --prefix %q was requested.\nRemove --prefix (or pass a matching value) to reuse the existing workspace", existing, prefix) - } - } - if !quiet { - fmt.Fprintln(os.Stderr, "Skipping init: workspace already initialized.") - } - return nil + return resolveInitIfMissingAlreadyInitialized(cmd, database, prefix, quiet) } return fmt.Errorf("%v", err) } @@ -2762,6 +2752,40 @@ func initIfMissingPrefixMismatch(existingDBName, requestedPrefix string) bool { return requested != "" && !strings.EqualFold(existingDBName, requested) } +// resolveInitIfMissingAlreadyInitialized decides what --init-if-missing does +// once the workspace is known to be initialized already: nil for the benign +// skip (message printed here), or the abort for a request that would be +// silently ignored by skipping. +// +// Guard against masking a genuine mismatch: an explicit --prefix or --database +// that does not match the existing workspace must abort, since silently +// skipping would ignore the request and reuse a different database. --database +// is the authoritative selector, so it is checked even when --prefix is also +// set. +// +// Both init routes share this: the embedded/server route reaches it from its +// own checkExistingBeadsData, the proxied-server route from the identical check +// inside runInitProxiedServer. Before that wiring existed, --init-if-missing was +// simply inert on the proxied route — an already-initialized workspace exited 1 +// with the "Aborting." banner, and the two mismatch guards this delegates to had +// never once run. +func resolveInitIfMissingAlreadyInitialized(cmd *cobra.Command, database, prefix string, quiet bool) error { + existing := existingWorkspaceDBName() + if cmd.Flags().Changed("database") { + if initIfMissingDatabaseMismatch(existing, database) { + return fmt.Errorf("workspace already initialized as database %q, but --database %q was requested.\nRemove --database (or pass a matching value) to reuse the existing workspace", existing, database) + } + } else if cmd.Flags().Changed("prefix") { + if initIfMissingPrefixMismatch(existing, prefix) { + return fmt.Errorf("workspace already initialized as database %q, but --prefix %q was requested.\nRemove --prefix (or pass a matching value) to reuse the existing workspace", existing, prefix) + } + } + if !quiet { + fmt.Fprintln(os.Stderr, "Skipping init: workspace already initialized.") + } + return nil +} + // initIfMissingDatabaseMismatch reports whether an explicit --database request // conflicts with the existing workspace. --database is the authoritative database // selector (it overrides prefix-based naming later in init), so an explicit diff --git a/cmd/bd/init_proxied_if_missing_test.go b/cmd/bd/init_proxied_if_missing_test.go new file mode 100644 index 000000000..fa183e880 --- /dev/null +++ b/cmd/bd/init_proxied_if_missing_test.go @@ -0,0 +1,96 @@ +//go:build cgo + +package main + +import ( + "strings" + "testing" +) + +// TestProxiedServerInitIfMissing covers --init-if-missing on the proxied-server +// route, where it used to be inert: runInitProxiedServer runs its own +// already-initialized check and returns before init.go's --init-if-missing +// block, so a scaffold script re-running init got exit 1 and the "Aborting." +// banner, and the mismatch guards that protect the flag had never run at all. +func TestProxiedServerInitIfMissing(t *testing.T) { + requireProxiedServerEnv(t) + + bd := buildEmbeddedBD(t) + p := bdProxiedInit(t, bd, "pim") + + initArgs := func(extra ...string) []string { + return append([]string{ + "init", "--proxied-server", "--non-interactive", "--skip-agents", "--skip-hooks", + }, extra...) + } + + t.Run("re-init skips benignly", func(t *testing.T) { + _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, initArgs("--init-if-missing")...) + if err != nil { + t.Fatalf("init --init-if-missing should exit 0 on an initialized workspace: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(stderr, "Skipping init: workspace already initialized") { + t.Errorf("expected the benign skip message, got stderr:\n%s", stderr) + } + }) + + t.Run("matching prefix skips benignly", func(t *testing.T) { + _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, initArgs("--init-if-missing", "--prefix", p.prefix)...) + if err != nil { + t.Fatalf("matching --prefix should still skip: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(stderr, "Skipping init: workspace already initialized") { + t.Errorf("expected the benign skip message, got stderr:\n%s", stderr) + } + }) + + // The multi-project ask. Skipping here would silently ignore --database and + // keep using the existing one, so it must refuse — and say which database + // the workspace is actually on. + t.Run("different database is refused, not skipped", func(t *testing.T) { + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, initArgs("--init-if-missing", "--database", "some_other_db")...) + if err == nil { + t.Fatalf("mismatched --database must abort; got success\nstdout:\n%s\nstderr:\n%s", stdout, stderr) + } + out := stdout + stderr + for _, want := range []string{ + "workspace already initialized as database " + `"` + p.database + `"`, + `--database "some_other_db" was requested`, + } { + if !strings.Contains(out, want) { + t.Errorf("abort message missing %q, got:\n%s", want, out) + } + } + if strings.Contains(out, "Skipping init") { + t.Errorf("a mismatched --database must not be skipped, got:\n%s", out) + } + }) + + t.Run("different prefix is refused, not skipped", func(t *testing.T) { + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, initArgs("--init-if-missing", "--prefix", "somethingelse")...) + if err == nil { + t.Fatalf("mismatched --prefix must abort; got success\nstdout:\n%s\nstderr:\n%s", stdout, stderr) + } + out := stdout + stderr + for _, want := range []string{ + "workspace already initialized as database " + `"` + p.database + `"`, + `--prefix "somethingelse" was requested`, + } { + if !strings.Contains(out, want) { + t.Errorf("abort message missing %q, got:\n%s", want, out) + } + } + }) + + // Without the flag, the existing refusal is unchanged: --init-if-missing is + // what makes re-init benign, not this change. + t.Run("without the flag re-init still aborts", func(t *testing.T) { + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, initArgs()...) + if err == nil { + t.Fatalf("re-init without --init-if-missing must abort; got success\nstdout:\n%s\nstderr:\n%s", stdout, stderr) + } + if out := stdout + stderr; !strings.Contains(out, "already initialized") { + t.Errorf("expected the existing already-initialized refusal, got:\n%s", out) + } + }) +} diff --git a/internal/storage/dolt/gateway_session_test.go b/internal/storage/dolt/gateway_session_test.go new file mode 100644 index 000000000..53b41b8db --- /dev/null +++ b/internal/storage/dolt/gateway_session_test.go @@ -0,0 +1,92 @@ +package dolt + +import ( + "context" + "database/sql" + "errors" + "regexp" + "strings" + "testing" + + "github.com/DATA-DOG/go-sqlmock" +) + +// gatewaySessionMock stands in for a gateway that answers SELECT DATABASE() +// with the database it actually put the session on — which need not be the one +// named in the handshake. +func gatewaySessionMock(t *testing.T, answer any) *sql.DB { + t.Helper() + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New(): %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + mock.ExpectQuery(regexp.QuoteMeta("SELECT DATABASE()")). + WillReturnRows(sqlmock.NewRows([]string{"DATABASE()"}).AddRow(answer)) + return db +} + +func TestAssertGatewaySessionDatabase(t *testing.T) { + ctx := context.Background() + + t.Run("session on the requested database passes", func(t *testing.T) { + if err := assertGatewaySessionDatabase(ctx, gatewaySessionMock(t, "team_b"), "team_b"); err != nil { + t.Fatalf("assertGatewaySessionDatabase() = %v, want nil", err) + } + }) + + t.Run("case-folded match passes", func(t *testing.T) { + if err := assertGatewaySessionDatabase(ctx, gatewaySessionMock(t, "Team_B"), "team_b"); err != nil { + t.Fatalf("assertGatewaySessionDatabase() = %v, want nil", err) + } + }) + + // Before this assertion the direct gateway open accepted the mismatch in + // silence: bd went on to read team_a's identity and adopt it as the + // workspace's own, on a `bd init --database=team_b` that never reached + // team_b at all. + t.Run("credential-scoped gateway is caught and both databases are named", func(t *testing.T) { + err := assertGatewaySessionDatabase(ctx, gatewaySessionMock(t, "team_a"), "team_b") + if err == nil { + t.Fatal("assertGatewaySessionDatabase() = nil, want a mismatch error") + } + for _, want := range []string{ + `connected this session to database "team_a"`, + `not the requested "team_b"`, + "ask the server administrator", + "re-run init without --database", + } { + if !strings.Contains(err.Error(), want) { + t.Fatalf("mismatch message %q missing %q", err.Error(), want) + } + } + }) + + t.Run("no session database is reported as not provisioned or not granted", func(t *testing.T) { + for _, answer := range []any{nil, ""} { + err := assertGatewaySessionDatabase(ctx, gatewaySessionMock(t, answer), "team_b") + if err == nil { + t.Fatalf("assertGatewaySessionDatabase(%v) = nil, want an error", answer) + } + for _, want := range []string{"no database", "not provisioned", "has not been granted access"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("message %q missing %q", err.Error(), want) + } + } + } + }) + + t.Run("query failure surfaces the driver error", func(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New(): %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + cause := errors.New("connection reset by peer") + mock.ExpectQuery(regexp.QuoteMeta("SELECT DATABASE()")).WillReturnError(cause) + + if got := assertGatewaySessionDatabase(ctx, db, "team_b"); !errors.Is(got, cause) { + t.Fatalf("assertGatewaySessionDatabase() = %v, want it to wrap %v", got, cause) + } + }) +} diff --git a/internal/storage/dolt/store.go b/internal/storage/dolt/store.go index 093eb114d..79c0c19ac 100644 --- a/internal/storage/dolt/store.go +++ b/internal/storage/dolt/store.go @@ -2420,6 +2420,40 @@ type serverConnFacts struct { alreadyExisted bool } +// assertGatewaySessionDatabase verifies the gateway actually placed this +// session on the database bd asked for, comparing case-insensitively as MySQL +// does for schema names. A NULL or empty answer means the session is on no +// database at all, which for a gateway means the same thing as a refusal: the +// name bd asked for is not provisioned for this credential. +// +// The uow provider makes the same assertion for the proxied-server open +// (uow.assertSessionDatabase); this is the direct-open sibling, kept here +// rather than shared because internal/storage/dolt does not depend on uow. +func assertGatewaySessionDatabase(ctx context.Context, db *sql.DB, want string) error { + conn, err := db.Conn(ctx) + if err != nil { + return fmt.Errorf("failed to pin gateway connection (database %q): %w", want, err) + } + defer func() { _ = conn.Close() }() + + var current sql.NullString + if err := conn.QueryRowContext(ctx, "SELECT DATABASE()").Scan(¤t); err != nil { + return fmt.Errorf("failed to read the session database after connecting to gateway server for database %q: %w", want, err) + } + switch { + case !current.Valid || current.String == "": + return fmt.Errorf( + "the gateway server left this session on no database after requesting %q — either the database is not provisioned on the server or this credential has not been granted access to it; ask the server administrator to provision the database and grant access", + want) + case strings.EqualFold(current.String, want): + return nil + default: + return fmt.Errorf( + "the gateway server connected this session to database %q, not the requested %q — this credential appears to be scoped to %q. The requested database is not provisioned for this credential; ask the server administrator to provision it on the server (and grant this credential access), or re-run init without --database to use the provisioned one", + current.String, want, current.String) + } +} + // 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. @@ -2448,14 +2482,26 @@ func openServerConnection(ctx context.Context, cfg *Config) (*sql.DB, string, se // A gateway server owns database routing and existence, so bd does not probe or create // it: skip the no-database admin connection (and the SHOW DATABASES / CREATE DATABASE - // it would run) and verify the project connection directly — a successful connect IS - // the existence proof. connReady must be set before returning the pool, or the defer - // above would close the *sql.DB we just handed the caller. + // it would run) and verify the project connection directly — a successful connect that + // lands on the requested database IS the existence proof. connReady must be set before + // returning the pool, or the defer above would close the *sql.DB we just handed the + // caller. if cfg.Gateway { if err := db.PingContext(ctx); err != nil { return nil, "", serverConnFacts{}, fmt.Errorf("failed to connect to gateway server %s:%d (database %q): %w", cfg.ServerHost, cfg.ServerPort, cfg.Database, err) } + // A connect proves the gateway accepted the credential, NOT that it + // honored the database name. A gateway scopes connections by + // credential, so it can take a foreign name in the handshake and serve + // its own database anyway — and every read below is unqualified, so bd + // would read one project's data while believing it was in another's. + // On `bd init --database=` that adoption is completely silent: + // resolveInitIssuePrefix adopts whatever prefix comes back. One query + // closes it. + if err := assertGatewaySessionDatabase(ctx, db, cfg.Database); err != nil { + return nil, "", serverConnFacts{}, err + } connReady = true // Neither fact is established for a gateway database: we did not // create it, and existence was never probed, so we cannot honestly diff --git a/internal/storage/uow/dolt_sql_provider.go b/internal/storage/uow/dolt_sql_provider.go index c1170031d..ad957fa44 100644 --- a/internal/storage/uow/dolt_sql_provider.go +++ b/internal/storage/uow/dolt_sql_provider.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "fmt" + "strings" "sync/atomic" "time" @@ -247,9 +248,15 @@ func (p *doltSQLProvider) verifyTeamServerSchema(ctx context.Context, conn *sql. if isSerializationError(err) { return fmt.Errorf("uow: switching to database: %w", err) } - return backoff.Permanent(fmt.Errorf( - "uow: database %q not found — the schema is managed by beads-team-server; ask your operator to run 'bts init' first: %w", - database, err)) + return backoff.Permanent(classifyUseDatabaseError(err, database, teamServerUseDatabaseRemedy)) + } + // A USE that returns no error is not proof the session moved: see + // assertSessionDatabase. + if err := assertSessionDatabase(ctx, conn, database); err != nil { + if isSerializationError(err) { + return err + } + return backoff.Permanent(err) } if err := checkTeamServerSchema(ctx, conn, database); err != nil { if isSerializationError(err) { @@ -276,13 +283,104 @@ func (p *doltSQLProvider) attachPreviewDatabase(ctx context.Context, conn *sql.C if isSerializationError(err) { return fmt.Errorf("uow: switching to database: %w", err) } - return backoff.Permanent(fmt.Errorf( - "uow: database %q not found — preview commands (--dry-run, --inspect) never create or migrate a database; run the command without the preview flag first: %w", - database, err)) + return backoff.Permanent(classifyUseDatabaseError(err, database, previewUseDatabaseRemedy)) } return nil } +// useDatabaseRemedy carries the advice classifyUseDatabaseError appends to the +// two failure shapes whose remedy depends on which open path asked: a database +// the server says is absent, and a failure it could not classify at all. Denial +// needs no variant — a refused credential is refused the same way everywhere, +// and only the server administrator can change that. +type useDatabaseRemedy struct { + // missing is appended when the server reports the database does not exist. + missing string + // unclassified is appended when the driver error is neither a denial nor an + // absence, so the message must not claim to know which. + unclassified string +} + +var ( + // teamServerUseDatabaseRemedy: the schema on this path is owned by the team + // server, so bd never creates the database — an absent one is a + // provisioning request, not something a retry can fix. + teamServerUseDatabaseRemedy = useDatabaseRemedy{ + missing: "it must be provisioned on the server; ask the server administrator to create it, then re-run init", + unclassified: "the schema is managed by beads-team-server; ask your operator to run 'bts init' first", + } + // previewUseDatabaseRemedy: a preview open promised not to mutate anything, + // so it neither creates nor migrates where the ordinary open would. That + // answers both shapes, so both fields carry it. + previewUseDatabaseRemedy = useDatabaseRemedy{ + missing: previewRemedyText, + unclassified: previewRemedyText, + } +) + +const previewRemedyText = "preview commands (--dry-run, --inspect) never create or migrate a database; run the command without the preview flag first" + +// classifyUseDatabaseError describes a failed USE using only what the server +// actually said. The old wording called every failure "database %q not found", +// including the access-denied errors a scoped credential gets — which sent +// operators off to provision a database that already existed and only needed a +// grant. A server hides existence from a credential it has not granted the +// database (see isDatabaseNotFoundError), so on a denial bd must name both +// possibilities instead of picking one. +func classifyUseDatabaseError(err error, database string, remedy useDatabaseRemedy) error { + switch { + case isAccessDeniedError(err): + return fmt.Errorf( + "uow: access to database %q was denied for this credential — either the database is not provisioned on the server or this credential has not been granted access to it; ask the server administrator to provision the database and grant access: %w", + database, err) + case isDatabaseNotFoundError(err): + return fmt.Errorf("uow: database %q does not exist on the server — %s: %w", database, remedy.missing, err) + default: + return fmt.Errorf("uow: could not switch to database %q — %s: %w", database, remedy.unclassified, err) + } +} + +// rowQuerier is the subset of *sql.Conn, *sql.DB, and *sql.Tx that +// assertSessionDatabase needs, so the assertion can be tested against a stub. +type rowQuerier interface { + QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row +} + +// assertSessionDatabase verifies the server actually placed this session on the +// database bd asked for. +// +// A front door that scopes connections by credential — a gateway, a proxy that +// rewrites routing — can accept a foreign database name in the handshake or a +// USE for it and serve its own database anyway. Nothing later on the open path +// notices: bd's identity reads are unqualified, so they return the SESSION's +// database while bd attributes them to the REQUESTED one. That is how +// `bd init --database=` ends up reporting a prefix conflict against a +// database it never reached, and — with no --prefix to disagree — how a +// workspace silently adopts another project's identity and then reads and +// writes that project's data. +// +// Schema names compare case-insensitively, matching MySQL. A NULL or empty +// answer means the session is on no database at all, which is the same +// not-provisioned-or-not-granted situation classifyUseDatabaseError describes. +func assertSessionDatabase(ctx context.Context, q rowQuerier, want string) error { + var current sql.NullString + if err := q.QueryRowContext(ctx, "SELECT DATABASE()").Scan(¤t); err != nil { + return fmt.Errorf("uow: reading the session database after selecting %q: %w", want, err) + } + switch { + case !current.Valid || current.String == "": + return fmt.Errorf( + "uow: the server left this session on no database after selecting %q — either the database is not provisioned on the server or this credential has not been granted access to it; ask the server administrator to provision the database and grant access", + want) + case strings.EqualFold(current.String, want): + return nil + default: + return fmt.Errorf( + "uow: the server connected this session to database %q, not the requested %q — this credential appears to be scoped to %q. The requested database is not provisioned for this credential; ask the server administrator to provision it on the server (and grant this credential access), or re-run init without --database to use the provisioned one", + current.String, want, current.String) + } +} + // bootstrapPreparer carries the sticky fresh-bootstrap state across the backoff // retry attempts of a single initSchema call and runs as MigrateUpWithLock's // locked-preparation callback (see prepare). @@ -343,6 +441,14 @@ func (b *bootstrapPreparer) prepare(ctx context.Context, conn *sql.Conn) (*schem err: fmt.Errorf("uow: creating database: %w", err), retryable: true, } + case isAccessDeniedError(err): + // A server that provisions databases itself denies CREATE to the + // credentials it hands out. Say so instead of surfacing the raw + // driver error, and do not retry or fall back: bd must not go + // looking for another way to create a database it was refused. + return nil, &bootstrapPreparationError{err: fmt.Errorf( + "uow: creating database %q was denied for this credential — this server provisions databases server-side; ask the server administrator to provision it, then re-run init: %w", + b.database, err)} default: return nil, &bootstrapPreparationError{err: fmt.Errorf("uow: creating database: %w", err)} } @@ -378,6 +484,18 @@ func buildDSN(ep proxy.Endpoint, database, user, password, tlsConfigName string) }.String() } +// assertSessionDatabaseOnPool runs assertSessionDatabase on a connection pinned +// out of pool. A pool hands out a different connection per call, so the +// assertion has to name the connection it is asserting about. +func assertSessionDatabaseOnPool(ctx context.Context, pool *sql.DB, want string) error { + conn, err := pool.Conn(ctx) + if err != nil { + return fmt.Errorf("uow: pin connection: %w", err) + } + defer func() { _ = conn.Close() }() + return assertSessionDatabase(ctx, conn, want) +} + func openDB(ctx context.Context, dsn string) (*sql.DB, error) { conn, err := sql.Open("mysql", dsn) if err != nil { @@ -418,6 +536,15 @@ func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUse return nil, err } + // This pool names the database in the MySQL handshake and never issues a + // USE, so nothing has yet checked that the server honored the name. Every + // unqualified read the caller makes — project identity above all — belongs + // to whatever database this session actually landed on, so assert it once + // here, on a pinned connection, before handing the pool out. + if err := assertSessionDatabaseOnPool(ctx, dbConn, database); err != nil { + return nil, errors.Join(err, dbConn.Close()) + } + return &doltSQLProvider{ defaultBranch: defaultBranch, db: dbConn, diff --git a/internal/storage/uow/errors.go b/internal/storage/uow/errors.go index a7c0fee61..217d5904e 100644 --- a/internal/storage/uow/errors.go +++ b/internal/storage/uow/errors.go @@ -50,3 +50,41 @@ func isDatabaseExistsError(err error) bool { errLower := strings.ToLower(err.Error()) return strings.Contains(errLower, "database exists") || strings.Contains(errLower, "1007") } + +// isAccessDeniedError reports whether err is the server refusing an operation +// because the connected credential is not allowed to perform it. MySQL numbers +// these 1044 (ER_DBACCESS_DENIED_ERROR) and 1045 (ER_ACCESS_DENIED_ERROR); Dolt +// reports the same refusals under the generic 1105 with the wording intact, so +// the text fallback is what classifies them there. +func isAccessDeniedError(err error) bool { + if err == nil { + return false + } + var mysqlErr *mysql.MySQLError + if errors.As(err, &mysqlErr) && (mysqlErr.Number == 1044 || mysqlErr.Number == 1045) { + return true + } + errLower := strings.ToLower(err.Error()) + return strings.Contains(errLower, "access denied") || strings.Contains(errLower, "command denied") +} + +// isDatabaseNotFoundError reports whether the server said the database does not +// exist: MySQL 1049 (ER_BAD_DB_ERROR, "Unknown database"), or Dolt's "database +// not found: ". +// +// A false answer is NOT evidence the database exists. A server deliberately +// hides existence from a credential that has not been granted the database, +// answering access-denied for present and absent names alike, so only a +// privileged credential can tell the two apart. Callers must report the denial +// as a denial rather than guessing absence from it. +func isDatabaseNotFoundError(err error) bool { + if err == nil { + return false + } + var mysqlErr *mysql.MySQLError + if errors.As(err, &mysqlErr) && mysqlErr.Number == 1049 { + return true + } + errLower := strings.ToLower(err.Error()) + return strings.Contains(errLower, "database not found") || strings.Contains(errLower, "unknown database") +} diff --git a/internal/storage/uow/errors_test.go b/internal/storage/uow/errors_test.go new file mode 100644 index 000000000..0796af0ac --- /dev/null +++ b/internal/storage/uow/errors_test.go @@ -0,0 +1,143 @@ +package uow + +import ( + "errors" + "fmt" + "strings" + "testing" + + mysql "github.com/go-sql-driver/mysql" +) + +func TestIsAccessDeniedError(t *testing.T) { + for _, tt := range []struct { + name string + err error + want bool + }{ + {name: "nil", err: nil, want: false}, + {name: "mysql 1044 db access denied", err: &mysql.MySQLError{Number: 1044, Message: "Access denied for user"}, want: true}, + {name: "mysql 1045 access denied", err: &mysql.MySQLError{Number: 1045, Message: "Access denied for user"}, want: true}, + // Dolt reports both refusals under the generic 1105, so only the text + // classifies them. + {name: "dolt 1105 access denied", err: &mysql.MySQLError{Number: 1105, Message: "Access denied for user 'scoped'@'%' to database 'team_b'"}, want: true}, + {name: "dolt 1105 command denied", err: &mysql.MySQLError{Number: 1105, Message: "command denied to user 'scoped'@'%'"}, want: true}, + {name: "dolt 1105 unrelated", err: &mysql.MySQLError{Number: 1105, Message: "unexpected internal error"}, want: false}, + {name: "not found is not a denial", err: &mysql.MySQLError{Number: 1049, Message: "database not found: team_b"}, want: false}, + {name: "plain error with the wording", err: errors.New("db: UseDatabase: Access denied for user"), want: true}, + {name: "plain unrelated error", err: errors.New("connection reset by peer"), want: false}, + {name: "wrapped", err: fmt.Errorf("db: UseDatabase: %w", &mysql.MySQLError{Number: 1044}), want: true}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := isAccessDeniedError(tt.err); got != tt.want { + t.Fatalf("isAccessDeniedError(%v) = %t, want %t", tt.err, got, tt.want) + } + }) + } +} + +func TestIsDatabaseNotFoundError(t *testing.T) { + for _, tt := range []struct { + name string + err error + want bool + }{ + {name: "nil", err: nil, want: false}, + {name: "mysql 1049", err: &mysql.MySQLError{Number: 1049, Message: "Unknown database 'team_b'"}, want: true}, + {name: "dolt text", err: errors.New("db: UseDatabase: database not found: team_b"), want: true}, + {name: "mysql text", err: errors.New("Error 1049 (42000): Unknown database 'team_b'"), want: true}, + // The load-bearing negative: a denial must never be reported as absence. + {name: "access denied is not absence", err: &mysql.MySQLError{Number: 1105, Message: "Access denied for user 'scoped'@'%' to database 'team_b'"}, want: false}, + {name: "plain unrelated error", err: errors.New("connection reset by peer"), want: false}, + {name: "wrapped", err: fmt.Errorf("db: UseDatabase: %w", &mysql.MySQLError{Number: 1049}), want: true}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := isDatabaseNotFoundError(tt.err); got != tt.want { + t.Fatalf("isDatabaseNotFoundError(%v) = %t, want %t", tt.err, got, tt.want) + } + }) + } +} + +func TestClassifyUseDatabaseError(t *testing.T) { + // The exact server errors observed from dolt 2.1.8 against a credential + // granted only one database. + denied := fmt.Errorf("db: UseDatabase: %w", + &mysql.MySQLError{Number: 1105, Message: "Access denied for user 'scoped'@'%' to database 'team_b'"}) + missing := fmt.Errorf("db: UseDatabase: %w", + &mysql.MySQLError{Number: 1049, Message: "database not found: team_b"}) + other := fmt.Errorf("db: UseDatabase: %w", errors.New("connection reset by peer")) + + t.Run("denied reports a denial, never absence", func(t *testing.T) { + err := classifyUseDatabaseError(denied, "team_b", teamServerUseDatabaseRemedy) + assertContainsAll(t, err.Error(), + `access to database "team_b" was denied`, + "not provisioned on the server", + "has not been granted access", + "ask the server administrator", + // The wrapped driver error must survive for diagnosis. + "Access denied for user 'scoped'", + ) + if strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "does not exist") { + t.Fatalf("denial must not claim the database is absent: %v", err) + } + if !errors.Is(err, denied) { + t.Fatalf("classifyUseDatabaseError() dropped the cause: %v", err) + } + }) + + t.Run("missing reports absence with the caller's remedy", func(t *testing.T) { + err := classifyUseDatabaseError(missing, "team_b", teamServerUseDatabaseRemedy) + assertContainsAll(t, err.Error(), + `database "team_b" does not exist on the server`, + "ask the server administrator to create it", + "database not found: team_b", + ) + }) + + t.Run("missing under preview keeps the preview remedy", func(t *testing.T) { + err := classifyUseDatabaseError(missing, "team_b", previewUseDatabaseRemedy) + assertContainsAll(t, err.Error(), + `database "team_b" does not exist on the server`, + "--dry-run", + "without the preview flag first", + ) + }) + + t.Run("unclassified claims neither absence nor denial", func(t *testing.T) { + err := classifyUseDatabaseError(other, "team_b", teamServerUseDatabaseRemedy) + assertContainsAll(t, err.Error(), + `could not switch to database "team_b"`, + "connection reset by peer", + ) + if strings.Contains(err.Error(), "does not exist") || strings.Contains(err.Error(), "was denied") { + t.Fatalf("unclassified failure must not guess a cause: %v", err) + } + }) + + // Vendor neutrality: the classified branches speak of "the server + // administrator", never a product. Only the untouched unclassified remedy + // still carries the historical product wording (tracked as a separate + // naming sweep). + t.Run("classified messages name no product", func(t *testing.T) { + for _, err := range []error{ + classifyUseDatabaseError(denied, "team_b", teamServerUseDatabaseRemedy), + classifyUseDatabaseError(missing, "team_b", teamServerUseDatabaseRemedy), + } { + for _, banned := range []string{"beads-team-server", "bts "} { + if strings.Contains(err.Error(), banned) { + t.Fatalf("message must not name a product (%q): %v", banned, err) + } + } + } + }) +} + +func assertContainsAll(t *testing.T, got string, wants ...string) { + t.Helper() + for _, want := range wants { + if !strings.Contains(got, want) { + t.Fatalf("message %q missing %q", got, want) + } + } +} diff --git a/internal/storage/uow/session_database_test.go b/internal/storage/uow/session_database_test.go new file mode 100644 index 000000000..37e17dbe5 --- /dev/null +++ b/internal/storage/uow/session_database_test.go @@ -0,0 +1,113 @@ +package uow + +import ( + "context" + "database/sql" + "errors" + "regexp" + "strings" + "testing" + + "github.com/DATA-DOG/go-sqlmock" +) + +// sessionDatabaseMock stands in for a front door that answers SELECT DATABASE() +// with whatever it actually put the session on, which may not be what bd asked +// for. +func sessionDatabaseMock(t *testing.T, answer any) (*sql.DB, sqlmock.Sqlmock) { + t.Helper() + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New(): %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + mock.ExpectQuery(regexp.QuoteMeta("SELECT DATABASE()")). + WillReturnRows(sqlmock.NewRows([]string{"DATABASE()"}).AddRow(answer)) + return db, mock +} + +func TestAssertSessionDatabase(t *testing.T) { + ctx := context.Background() + + t.Run("session on the requested database passes", func(t *testing.T) { + db, mock := sessionDatabaseMock(t, "team_b") + if err := assertSessionDatabase(ctx, db, "team_b"); err != nil { + t.Fatalf("assertSessionDatabase() = %v, want nil", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } + }) + + // MySQL schema names are case-insensitive, so a server that normalizes the + // name is not a mismatch. + t.Run("case-folded match passes", func(t *testing.T) { + db, _ := sessionDatabaseMock(t, "TEAM_B") + if err := assertSessionDatabase(ctx, db, "team_b"); err != nil { + t.Fatalf("assertSessionDatabase() = %v, want nil", err) + } + }) + + // The field bug: a credential scoped to team_a asks for team_b, the front + // door accepts the name and serves team_a. Before the assertion, every + // later unqualified read was attributed to team_b. + t.Run("scoped front door is caught and both databases are named", func(t *testing.T) { + db, _ := sessionDatabaseMock(t, "team_a") + err := assertSessionDatabase(ctx, db, "team_b") + if err == nil { + t.Fatal("assertSessionDatabase() = nil, want a mismatch error") + } + for _, want := range []string{ + `connected this session to database "team_a"`, + `not the requested "team_b"`, + "scoped", + "ask the server administrator", + "re-run init without --database", + } { + if !strings.Contains(err.Error(), want) { + t.Fatalf("mismatch message %q missing %q", err.Error(), want) + } + } + }) + + t.Run("no session database is reported as not provisioned or not granted", func(t *testing.T) { + for _, answer := range []any{nil, ""} { + db, _ := sessionDatabaseMock(t, answer) + err := assertSessionDatabase(ctx, db, "team_b") + if err == nil { + t.Fatalf("assertSessionDatabase(%v) = nil, want an error", answer) + } + for _, want := range []string{"no database", "not provisioned", "has not been granted access"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("message %q missing %q", err.Error(), want) + } + } + } + }) + + t.Run("query failure surfaces the driver error", func(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New(): %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + cause := errors.New("connection reset by peer") + mock.ExpectQuery(regexp.QuoteMeta("SELECT DATABASE()")).WillReturnError(cause) + + got := assertSessionDatabase(ctx, db, "team_b") + if !errors.Is(got, cause) { + t.Fatalf("assertSessionDatabase() = %v, want it to wrap %v", got, cause) + } + }) + + // Vendor neutrality for the new strings. + t.Run("messages name no product", func(t *testing.T) { + db, _ := sessionDatabaseMock(t, "team_a") + err := assertSessionDatabase(ctx, db, "team_b") + for _, banned := range []string{"beads-team-server", "bts "} { + if strings.Contains(err.Error(), banned) { + t.Fatalf("message must not name a product (%q): %v", banned, err) + } + } + }) +} diff --git a/internal/storage/uow/team_server_integration_test.go b/internal/storage/uow/team_server_integration_test.go index a660f4230..5ce079653 100644 --- a/internal/storage/uow/team_server_integration_test.go +++ b/internal/storage/uow/team_server_integration_test.go @@ -53,14 +53,18 @@ func newTeamServerHarness(t *testing.T) *teamServerHarness { } func (h *teamServerHarness) openProvider(ctx context.Context, database string, teamServer bool, expectedProjectID string) (UnitOfWorkProvider, error) { + return h.openProviderAs(ctx, database, "root", "", teamServer, expectedProjectID) +} + +func (h *teamServerHarness) openProviderAs(ctx context.Context, database, user, password string, teamServer bool, expectedProjectID string) (UnitOfWorkProvider, error) { return NewExternalDoltServerUOWProvider( ctx, h.storeRootDir, database, h.logPath, configfile.ExternalDoltConfig{Host: "127.0.0.1", Port: h.port}, - "root", - "", + user, + password, 0, 0, teamServer, @@ -98,11 +102,15 @@ func TestTeamServerMode_Integration(t *testing.T) { const database = "beads_ts" - t.Run("missing database refused with bts init", func(t *testing.T) { + // A privileged credential CAN see that the database is absent, so the + // refusal says exactly that and asks for provisioning. It must not repeat + // the old blanket "not found" for failures it did not classify. + t.Run("missing database refused as absent, with provisioning guidance", func(t *testing.T) { p, err := h.openProvider(ctx, "beads_ts_missing", true, "") require.Error(t, err) assert.Nil(t, p) - assert.Contains(t, err.Error(), "bts init") + assert.Contains(t, err.Error(), `database "beads_ts_missing" does not exist on the server`) + assert.Contains(t, err.Error(), "ask the server administrator to create it") }) t.Run("existing empty database refused with bts init", func(t *testing.T) { @@ -136,6 +144,51 @@ func TestTeamServerMode_Integration(t *testing.T) { "team-server open must not modify schema_migrations") }) + // A credential granted only its own database is what a gateway front door + // hands out, and the server deliberately answers "access denied" for both + // absent and merely ungranted names — so bd cannot tell them apart and must + // stop claiming it can. + t.Run("scoped credential", func(t *testing.T) { + admin := h.directDB(t, "") + _, err := admin.ExecContext(ctx, "CREATE USER IF NOT EXISTS 'scoped'@'%' IDENTIFIED BY 'pw'") + require.NoError(t, err) + t.Cleanup(func() { + _, err := admin.ExecContext(ctx, "DROP USER IF EXISTS 'scoped'@'%'") + assert.NoError(t, err) + }) + _, err = admin.ExecContext(ctx, "GRANT ALL ON `"+database+"`.* TO 'scoped'@'%'") + require.NoError(t, err) + + t.Run("granted database still opens", func(t *testing.T) { + p, err := h.openProviderAs(ctx, database, "scoped", "pw", true, "") + require.NoError(t, err) + t.Cleanup(func() { _ = p.Close(ctx) }) + }) + + // beads_test exists on the server; the scoped credential has no grant + // for it. Both this and the absent name below must produce the SAME + // honest message, because the server gives bd the same error. + for _, tc := range []struct { + name string + database string + }{ + {name: "ungranted existing database", database: "beads_test"}, + {name: "absent database", database: "beads_ts_absent"}, + } { + t.Run(tc.name+" is reported as denied, not as absent", func(t *testing.T) { + p, err := h.openProviderAs(ctx, tc.database, "scoped", "pw", true, "") + require.Error(t, err) + assert.Nil(t, p) + assert.Contains(t, err.Error(), "access to database "+strconv.Quote(tc.database)+" was denied") + assert.Contains(t, err.Error(), "ask the server administrator to provision the database and grant access") + assert.NotContains(t, err.Error(), "does not exist on the server", + "a denial hides existence — bd must not claim the database is absent") + assert.NotContains(t, err.Error(), "bts init", + "the remedy for a denial is a grant, not provisioning by a named product") + }) + } + }) + t.Run("project identity is verified on every open, not just at init", func(t *testing.T) { // bts provisions the shared database with a project identity; bd // adopts it at init and, before this guard existed, never looked at