beads/cmd/bd/dolt_clean_databases_quote_test.go
Vishnu J 29bd4eeacd
fix(doctor,doltserver): escape SHOW DATABASES identifiers at raw-interpolation sites (#6434) (#6638)
* fix(doctor,doltserver): escape SHOW DATABASES identifiers at raw-interpolation sites

Three call sites interpolated a SHOW DATABASES-derived name into SQL without
doubling backticks, so a database name containing a backtick could break out
of the identifier quoting:

- cmd/bd/doctor/dolt.go probeForCorrectDatabase (issues probe)
- internal/doltserver/doltserver.go flush routine (dolt_status probe and USE)

Extract each query into a small helper (issuesProbeQuery, doltStatusQuery,
useDatabaseStatement) that applies the same escape already used by
inspectServerMetadataDatabases, and unit-test them without a live Dolt server.

Fixes #6434

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(doctor): escape the bd doctor --fix probe via a shared doltutil helper

Maintainer review fixes for PR #6638 (review iterations 1 and 2).

The review's one major (Change Impact / Blast Radius) is that the PR
escapes three of four identical SHOW DATABASES interpolation sites.
probeForCorrectDoltDatabase (cmd/bd/doctor/fix/metadata.go) is a
near-line-for-line clone of the probeForCorrectDatabase this PR fixed --
same enumeration, same system-DB skip map, same testdb_/doctest_/
doctortest_ prefix filter, byte-identical query string -- and the two are
the check and fix halves of one GH#2160 wrong-database repair. So after
this PR "bd doctor" detects a backticked database and emits
"Fix: Run 'bd doctor --fix' to set dolt_database=X", while "bd doctor
--fix" reaches the still-raw twin, whose SELECT errors, yielding
correctDB == "" and a bare return nil: no fix, no error, no output. The
PR turned a consistent double failure into a repair tool that tells the
user to run a command that silently does nothing.

Take the review's preferred single remedy, which also closes the
Architectural Consistency minor: land one exported
doltutil.QuoteIdentifier and route every site through it.
internal/storage/doltutil was already imported by the affected packages
(cmd/bd/doctor, cmd/bd/doctor/fix, internal/doltserver), so only cmd/bd
gains an import edge.

- new doltutil.QuoteIdentifier, returning the backtick-quoted form so
  quoting and escaping cannot be applied separately; unit-tested for
  plain, empty, embedded/leading backtick, and backtick-only names
- route all five hand-inlined backtick-doubling copies through it: the
  three builders this PR added, the pre-existing DROP DATABASE in
  cmd/bd/dolt_clean_databases.go, and inspectServerMetadataDatabases.
  Non-test inline copies go from five to one -- the helper itself
- drop the surviving //nolint:gosec rationale "dbName from SHOW
  DATABASES, not user input" at fix/metadata.go, which documented as
  safe exactly the premise this PR exists to refute
- pin the call site, not only the builder: a sqlmock test asserts
  probeForCorrectDoltDatabase issues the escaped query. Reverting the
  escape fails it with probeForCorrectDoltDatabase() = "", the silent
  no-op described above, while the plain-name case stays green

Left raw deliberately, as both review lanes concluded: doltserver.go's
CREATE DATABASE takes the constant GlobalDatabaseName, and the raw USE in
internal/testutil takes test-controlled names.

Review iteration 2 found no blocker or major. Its one minor is that the
consolidation re-created the ambiguity it removed, one level up: the repo
already exported a QuoteIdentifier in internal/storage/domain/db with the
opposite contract -- allowlist-based, returns an error, rejects anything
outside validIdentifier -- whose docstring claimed to be "the one place
this repository's identifiers are quoted", a sentence the new helper
falsified while staking a competing near-universal claim of its own.

- rename doltutil.QuoteIdentifier to QuoteIdentifierUnvalidated, and have
  both docstrings state their input class and cross-reference the other:
  db.QuoteIdentifier for bd-minted names that must satisfy the allowlist
  before the database or table is addressed, the doltutil helper for
  server-reported names bd does not control. The escape-over-reject
  behavior does not change -- rejecting a SHOW DATABASES name would skip
  the candidate, which is the defect this PR exists to fix. The new name
  also keeps Quote, so callers do not re-wrap an already-quoted result
- scope the helper's "every identifier that is not a compile-time constant
  or already validated" rule to non-test code: internal/testutil still
  interpolates raw, on test-controlled names, and has no non-test importer
- pin dropStaleDatabases (cmd/bd/dolt_clean_databases.go), the one
  destructive statement in the set. versioncontrolops.DBConn is already a
  parameter there, so a recording fake needs no server and no sqlmock, and
  the test is tagless where the sibling file is cgo-gated. Reverting that
  call site to raw interpolation fails it with
  "DROP DATABASE `evil`; DROP TABLE x`" -- the injected statement escaping
  the identifier -- while the plain-name statement stays byte-identical

The remaining unpinned site, inspectServerMetadataDatabases, opens its own
*sql.DB inside openServerCatalogDB, so pinning it needs a production seam
rather than a test. It was already correctly escaped before this PR and is
unchanged by it; left as reviewer-noted follow-up, as is nolintlint, which
.golangci.yml still disables.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
2026-09-26 14:26:04 -07:00

71 lines
2.5 KiB
Go

package main
import (
"context"
"database/sql"
"testing"
"github.com/steveyegge/beads/internal/storage/versioncontrolops"
)
// recordingDropConn records the statements dropStaleDatabases issues. Only
// ExecContext is reachable from that function; the other two methods exist to
// satisfy versioncontrolops.DBConn and fail loudly if that ever changes.
type recordingDropConn struct {
t *testing.T
queries []string
}
var _ versioncontrolops.DBConn = (*recordingDropConn)(nil)
func (c *recordingDropConn) ExecContext(_ context.Context, query string, _ ...any) (sql.Result, error) {
c.queries = append(c.queries, query)
return nil, nil
}
func (c *recordingDropConn) QueryContext(_ context.Context, query string, _ ...any) (*sql.Rows, error) {
c.t.Fatalf("unexpected QueryContext(%q)", query)
return nil, nil
}
func (c *recordingDropConn) QueryRowContext(_ context.Context, query string, _ ...any) *sql.Row {
c.t.Fatalf("unexpected QueryRowContext(%q)", query)
return nil
}
// TestDropStaleDatabasesQuotesIdentifiers pins the one destructive statement in
// the SHOW DATABASES set to the escaping helper. `bd dolt clean-databases`
// enumerates server database names and DROPs the stale ones, so the name it
// interpolates is whatever created the database, never a bd-minted value. The
// PR this test ships with fixed a sibling probe that had been left on raw
// interpolation precisely because nothing tied its call site to a builder;
// DROP DATABASE is where that mistake would cost the most, and the seam is
// free — dropStaleDatabases already takes versioncontrolops.DBConn as a
// parameter, so no server and no sqlmock are needed. Expectations are exact
// strings, so reverting the call site to raw `%s` interpolation fails the
// backtick case here rather than silently regressing.
func TestDropStaleDatabasesQuotesIdentifiers(t *testing.T) {
conn := &recordingDropConn{t: t}
stale := []string{"beads_x", "evil`; DROP TABLE x"}
dropped, err := dropStaleDatabases(t.Context(), conn, stale)
if err != nil {
t.Fatalf("dropStaleDatabases: %v", err)
}
if dropped != len(stale) {
t.Fatalf("dropped = %d, want %d", dropped, len(stale))
}
want := []string{
"DROP DATABASE `beads_x`",
"DROP DATABASE `evil``; DROP TABLE x`",
}
if len(conn.queries) != len(want) {
t.Fatalf("issued %d statements (%q), want %d", len(conn.queries), conn.queries, len(want))
}
for i, wantQuery := range want {
if conn.queries[i] != wantQuery {
t.Errorf("statement %d = %q, want %q", i, conn.queries[i], wantQuery)
}
}
}