fix(uow): verify project identity on every team-server open, not just at init (#5183)
The proxied/team-server path short-circuits in cmd/bd/main.go before validateWorkspaceIdentity and never constructs a DoltStore, so DoltStore.verifyProjectIdentity — which guards every non-CreateIfMissing gateway open — is unreachable there. `bd init --team-server` ADOPTS whatever identity the shared database carries, and before this change nothing re-asserted it on any later open. This predates #5159; what #5159 changed is exposure. Proxied-server used to mean a per-workspace database bd created itself, so "the server is serving a DIFFERENT project's database" barely applied. --team-server deliberately points bd at a long-lived, operator-managed (bts) database, selectable per invocation via --database — exactly the case the gateway guard exists to catch. This is the proxied-path sibling of the shared-server gap #5143 closes; that PR does not cover this path. Scope: this closes the TEAM-SERVER half. Plain proxied-server mode also never reaches verifyProjectIdentity, but asserting there would break `bd sql --database <arbitrary db>`, which the proxied multistatement tests establish as intentional. Follow-up tracked separately. checkTeamServerIdentity runs immediately after checkTeamServerSchema, so the metadata table is known to exist at this binary's version. A mismatch is wrapped in backoff.Permanent; isSerializationError only matches typed MySQL 1213/1205, so a plain mismatch can never be misclassified as retryable, while a genuine deadlock during the metadata read still retries. Identity is required on BOTH sides in team-server mode rather than soft-skipped as verifyProjectIdentity does for legacy databases: adoptTeamServerIdentity already refuses to attach to a bts database with no metadata._project_id, so an absent identity is an invalid state, not a legacy one — and tolerating it would mean deleting one row from the shared database silently disables this guard for every client. A team-server workspace with no local ProjectID is likewise refused, since an empty expectation is indistinguishable from the adoption path. --team-server is unreleased, so neither tightening costs compatibility. The two callers that legitimately have nothing to assert — `bd init`, which adopts, and server-wide database maintenance — go through newProxiedServerUOWProviderAdopting. Asserting the locally-minted placeholder at init would reject every correct init. identityPosture's zero value is the asserting one, so a missed posture fails safe. Tests: unit coverage of match/mismatch/adoption/absent-identity/read-error, plus an integration negative control that provisions a real identity and confirms a foreign workspace is refused. The mismatch test was mutation-checked — it fails when the comparison is disabled. Agent-Signature: claude-opus-5-medium on behalf of maphew
This commit is contained in:
parent
6d81e1c73a
commit
f8c84d510a
14 changed files with 306 additions and 20 deletions
|
|
@ -8,7 +8,7 @@ import (
|
|||
)
|
||||
|
||||
func runDoltCleanDatabasesProxied(ctx context.Context, beadsDir string, opts cleanDatabasesOptions) error {
|
||||
provider, err := newProxiedServerUOWProvider(ctx, beadsDir, "")
|
||||
provider, err := newProxiedServerUOWProviderAdopting(ctx, beadsDir, "")
|
||||
if err != nil {
|
||||
return HandleError("failed to open uow provider: %v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -156,7 +156,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
|
|||
fmt.Fprintf(os.Stderr, "Warning: failed to initialize version tracking: %v\n", fsResult.LocalVersionErr)
|
||||
}
|
||||
|
||||
initUOWProvider, err := newProxiedServerUOWProvider(ctx, beadsDir, "")
|
||||
initUOWProvider, err := newProxiedServerUOWProviderAdopting(ctx, beadsDir, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open uow provider: %v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,17 +14,62 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
)
|
||||
|
||||
// newProxiedServerUOWProvider opens the proxied-server provider and, in
|
||||
// team-server mode, asserts that the shared bts-managed database is serving
|
||||
// THIS workspace's project (gastownhall/beads: the proxied-path sibling of the
|
||||
// gateway's DoltStore.verifyProjectIdentity guard).
|
||||
func newProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverride string) (uow.UnitOfWorkProvider, error) {
|
||||
return openProxiedServerUOWProvider(ctx, beadsDir, databaseOverride, assertWorkspaceIdentity)
|
||||
}
|
||||
|
||||
// newProxiedServerUOWProviderAdopting skips that assertion. Only two callers
|
||||
// legitimately have no workspace identity to assert: `bd init --team-server`,
|
||||
// which ADOPTS the identity the shared database already carries (asserting the
|
||||
// locally-minted placeholder would reject every correct init), and server-wide
|
||||
// database maintenance, which is not scoped to one project's database.
|
||||
func newProxiedServerUOWProviderAdopting(ctx context.Context, beadsDir, databaseOverride string) (uow.UnitOfWorkProvider, error) {
|
||||
return openProxiedServerUOWProvider(ctx, beadsDir, databaseOverride, adoptWorkspaceIdentity)
|
||||
}
|
||||
|
||||
// identityPosture selects whether a proxied open asserts the workspace's
|
||||
// project identity against the database or adopts whatever it finds.
|
||||
type identityPosture bool
|
||||
|
||||
const (
|
||||
assertWorkspaceIdentity identityPosture = false
|
||||
adoptWorkspaceIdentity identityPosture = true
|
||||
)
|
||||
|
||||
func openProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverride string, posture identityPosture) (uow.UnitOfWorkProvider, error) {
|
||||
if beadsDir == "" {
|
||||
return nil, fmt.Errorf("newProxiedServerUOWProvider: beadsDir must be set")
|
||||
}
|
||||
|
||||
// NOTE: a load error is swallowed here (pre-existing behavior), which
|
||||
// leaves persisted == nil and therefore silently falls back to the default
|
||||
// database with teamServer=false. The identity assertion below inherits
|
||||
// that: an unreadable metadata.json degrades to no assertion rather than a
|
||||
// refusal. Tracked separately with the wider silent-fallback smell.
|
||||
persisted, _ := configfile.Load(beadsDir)
|
||||
database := configfile.DefaultDoltDatabase
|
||||
var teamServer bool
|
||||
var expectedProjectID string
|
||||
if persisted != nil {
|
||||
database = persisted.GetDoltDatabase()
|
||||
teamServer = persisted.IsTeamServerManaged()
|
||||
if posture == assertWorkspaceIdentity {
|
||||
expectedProjectID = persisted.ProjectID
|
||||
// An empty local identity would reach checkTeamServerIdentity as
|
||||
// "nothing to assert" — indistinguishable from the adoption path,
|
||||
// which would silently disable the guard. A team-server workspace
|
||||
// always has an adopted ProjectID after a successful init, so an
|
||||
// empty one here is a broken workspace, not a legacy one.
|
||||
if teamServer && expectedProjectID == "" {
|
||||
return nil, fmt.Errorf(
|
||||
"newProxiedServerUOWProvider: this team-server workspace has no project identity in %s; re-run 'bd init --team-server' to adopt the identity provisioned in the shared database (it never writes to that database)",
|
||||
configfile.ConfigFileName)
|
||||
}
|
||||
}
|
||||
}
|
||||
if databaseOverride != "" {
|
||||
database = databaseOverride
|
||||
|
|
@ -38,10 +83,10 @@ func newProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverride
|
|||
proxyIdleTimeout = info.IdleTimeout
|
||||
}
|
||||
if info != nil && info.External != nil {
|
||||
return newExternalProxiedServerUOWProvider(ctx, beadsDir, database, info.External, proxyPort, proxyIdleTimeout, teamServer)
|
||||
return newExternalProxiedServerUOWProvider(ctx, beadsDir, database, info.External, proxyPort, proxyIdleTimeout, teamServer, expectedProjectID)
|
||||
}
|
||||
|
||||
return newManagedProxiedServerUOWProvider(ctx, beadsDir, database, proxyPort, proxyIdleTimeout, teamServer)
|
||||
return newManagedProxiedServerUOWProvider(ctx, beadsDir, database, proxyPort, proxyIdleTimeout, teamServer, expectedProjectID)
|
||||
}
|
||||
|
||||
func newExternalProxiedServerUOWProvider(
|
||||
|
|
@ -51,6 +96,7 @@ func newExternalProxiedServerUOWProvider(
|
|||
proxyPort int,
|
||||
proxyIdleTimeout time.Duration,
|
||||
teamServer bool,
|
||||
expectedProjectID string,
|
||||
) (uow.UnitOfWorkProvider, error) {
|
||||
rootPath, err := resolveProxiedServerRootPath(beadsDir)
|
||||
if err != nil {
|
||||
|
|
@ -85,6 +131,7 @@ func newExternalProxiedServerUOWProvider(
|
|||
proxyPort,
|
||||
proxyIdleTimeout,
|
||||
teamServer,
|
||||
expectedProjectID,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -94,6 +141,7 @@ func newManagedProxiedServerUOWProvider(
|
|||
proxyPort int,
|
||||
proxyIdleTimeout time.Duration,
|
||||
teamServer bool,
|
||||
expectedProjectID string,
|
||||
) (uow.UnitOfWorkProvider, error) {
|
||||
doltBin, err := exec.LookPath("dolt")
|
||||
if err != nil {
|
||||
|
|
@ -142,5 +190,6 @@ func newManagedProxiedServerUOWProvider(
|
|||
proxyPort,
|
||||
proxyIdleTimeout,
|
||||
teamServer,
|
||||
expectedProjectID,
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ func TestNewExternalProxiedServerUOWProvider_CreatesRootDir(t *testing.T) {
|
|||
beadsDir := t.TempDir()
|
||||
external := &configfile.ExternalDoltConfig{Host: "db.invalid"}
|
||||
|
||||
_, err := newExternalProxiedServerUOWProvider(context.Background(), beadsDir, "beads_test", external, 0, 0, false)
|
||||
_, err := newExternalProxiedServerUOWProvider(context.Background(), beadsDir, "beads_test", external, 0, 0, false, "")
|
||||
require.Error(t, err, "invalid external config must surface a validation error")
|
||||
|
||||
wantRoot := proxiedServerRoot(beadsDir)
|
||||
|
|
|
|||
|
|
@ -27,6 +27,11 @@ type doltSQLProvider struct {
|
|||
// teamServer: schema is owned by beads-team-server (bts) — bd never
|
||||
// creates the database or migrates, only verifies the schema version.
|
||||
teamServer bool
|
||||
// expectedProjectID is the calling workspace's project identity, asserted
|
||||
// against the team-server database on open. Empty means "no assertion
|
||||
// available" (bd init, which adopts; server-wide maintenance; a workspace
|
||||
// predating project identity) and skips the check.
|
||||
expectedProjectID string
|
||||
}
|
||||
|
||||
var (
|
||||
|
|
@ -113,6 +118,14 @@ func (p *doltSQLProvider) initSchema(ctx context.Context, database string) error
|
|||
}
|
||||
return backoff.Permanent(err)
|
||||
}
|
||||
// Identity is checked only after the schema check proves the
|
||||
// metadata table exists at this binary's version.
|
||||
if err := checkTeamServerIdentity(ctx, conn, database, p.expectedProjectID); err != nil {
|
||||
if isSerializationError(err) {
|
||||
return fmt.Errorf("uow: team-server identity check: %w", err)
|
||||
}
|
||||
return backoff.Permanent(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if created {
|
||||
|
|
@ -176,16 +189,17 @@ func openDB(ctx context.Context, dsn string) (*sql.DB, error) {
|
|||
return conn, nil
|
||||
}
|
||||
|
||||
func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUser, rootPassword, tlsConfigName string, teamServer bool) (UnitOfWorkProvider, error) {
|
||||
func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUser, rootPassword, tlsConfigName string, teamServer bool, expectedProjectID string) (UnitOfWorkProvider, error) {
|
||||
initDB, err := openDB(ctx, buildDSN(ep, "", rootUser, rootPassword, tlsConfigName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
initProvider := &doltSQLProvider{
|
||||
defaultBranch: defaultBranch,
|
||||
db: initDB,
|
||||
teamServer: teamServer,
|
||||
defaultBranch: defaultBranch,
|
||||
db: initDB,
|
||||
teamServer: teamServer,
|
||||
expectedProjectID: expectedProjectID,
|
||||
}
|
||||
|
||||
if err := initProvider.initSchema(ctx, database); err != nil {
|
||||
|
|
@ -203,8 +217,9 @@ func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUse
|
|||
}
|
||||
|
||||
return &doltSQLProvider{
|
||||
defaultBranch: defaultBranch,
|
||||
db: dbConn,
|
||||
teamServer: teamServer,
|
||||
defaultBranch: defaultBranch,
|
||||
db: dbConn,
|
||||
teamServer: teamServer,
|
||||
expectedProjectID: expectedProjectID,
|
||||
}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ func NewDoltServerUOWProvider(
|
|||
proxyPort int,
|
||||
idleTimeout time.Duration,
|
||||
teamServer bool,
|
||||
expectedProjectID string,
|
||||
) (UnitOfWorkProvider, error) {
|
||||
if idleTimeout == 0 {
|
||||
idleTimeout = defaultProxyIdleTimeout
|
||||
|
|
@ -69,5 +70,5 @@ func NewDoltServerUOWProvider(
|
|||
return nil, fmt.Errorf("uow: get proxy endpoint: %w", err)
|
||||
}
|
||||
|
||||
return openAndInitSchema(ctx, ep, database, rootUser, rootPassword, "", teamServer)
|
||||
return openAndInitSchema(ctx, ep, database, rootUser, rootPassword, "", teamServer, expectedProjectID)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ func TestNewDoltServerUOWProvider_ValidationErrors(t *testing.T) {
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
assert.Nil(t, p)
|
||||
require.Error(t, err)
|
||||
|
|
@ -109,6 +110,7 @@ func TestNewDoltServerUOWProvider_HappyPath(t *testing.T) {
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
|
|
@ -166,6 +168,7 @@ func TestNewDoltServerUOWProvider_ConcurrentInstantiation(t *testing.T) {
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
results[i] = result{provider: p, err: err}
|
||||
}()
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ func NewExternalDoltServerUOWProvider(
|
|||
proxyPort int,
|
||||
idleTimeout time.Duration,
|
||||
teamServer bool,
|
||||
expectedProjectID string,
|
||||
) (UnitOfWorkProvider, error) {
|
||||
if idleTimeout == 0 {
|
||||
idleTimeout = defaultProxyIdleTimeout
|
||||
|
|
@ -65,7 +66,7 @@ func NewExternalDoltServerUOWProvider(
|
|||
return nil, fmt.Errorf("uow: get proxy endpoint: %w", err)
|
||||
}
|
||||
|
||||
return openAndInitSchema(ctx, ep, database, rootUser, rootPassword, tlsConfigName, teamServer)
|
||||
return openAndInitSchema(ctx, ep, database, rootUser, rootPassword, tlsConfigName, teamServer, expectedProjectID)
|
||||
}
|
||||
|
||||
func registerExternalTLSConfig(external configfile.ExternalDoltConfig) (string, error) {
|
||||
|
|
|
|||
|
|
@ -51,6 +51,7 @@ func TestNewExternalDoltServerUOWProvider_ValidationErrors(t *testing.T) {
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
assert.Nil(t, p)
|
||||
require.Error(t, err)
|
||||
|
|
@ -94,6 +95,7 @@ func TestNewExternalDoltServerUOWProvider_EndToEnd(t *testing.T) {
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, provider)
|
||||
|
|
@ -170,6 +172,7 @@ func TestNewExternalDoltServerUOWProvider_ConcurrentInstantiation(t *testing.T)
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
results[i] = result{provider: p, err: err}
|
||||
}()
|
||||
|
|
@ -264,6 +267,7 @@ func TestNewExternalDoltServerUOWProvider_FreshInitSelfHealsAfterMidPassFailure(
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
require.NoError(t, err, "fresh init must converge after a mid-pass transient failure, not trip the #4566 guard on its own bootstrap debris")
|
||||
require.NotNil(t, provider)
|
||||
|
|
@ -347,6 +351,7 @@ func TestNewExternalDoltServerUOWProvider_PreexistingDirtyDatabaseIsNotHealed(t
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
if provider != nil {
|
||||
t.Cleanup(func() { _ = provider.Close(context.Background()) })
|
||||
|
|
|
|||
|
|
@ -92,6 +92,7 @@ func TestUOW_ConcurrentMergeOps_NoLostUpdate(t *testing.T) {
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, provider)
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ func newTeamServerHarness(t *testing.T) *teamServerHarness {
|
|||
}
|
||||
}
|
||||
|
||||
func (h *teamServerHarness) openProvider(ctx context.Context, database string, teamServer bool) (UnitOfWorkProvider, error) {
|
||||
func (h *teamServerHarness) openProvider(ctx context.Context, database string, teamServer bool, expectedProjectID string) (UnitOfWorkProvider, error) {
|
||||
return NewExternalDoltServerUOWProvider(
|
||||
ctx,
|
||||
h.storeRootDir,
|
||||
|
|
@ -64,6 +64,7 @@ func (h *teamServerHarness) openProvider(ctx context.Context, database string, t
|
|||
0,
|
||||
0,
|
||||
teamServer,
|
||||
expectedProjectID,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -98,7 +99,7 @@ func TestTeamServerMode_Integration(t *testing.T) {
|
|||
const database = "beads_ts"
|
||||
|
||||
t.Run("missing database refused with bts init", func(t *testing.T) {
|
||||
p, err := h.openProvider(ctx, "beads_ts_missing", true)
|
||||
p, err := h.openProvider(ctx, "beads_ts_missing", true, "")
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, p)
|
||||
assert.Contains(t, err.Error(), "bts init")
|
||||
|
|
@ -106,14 +107,14 @@ func TestTeamServerMode_Integration(t *testing.T) {
|
|||
|
||||
t.Run("existing empty database refused with bts init", func(t *testing.T) {
|
||||
// The container pre-creates beads_test with no beads schema in it.
|
||||
p, err := h.openProvider(ctx, "beads_test", true)
|
||||
p, err := h.openProvider(ctx, "beads_test", true, "")
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, p)
|
||||
assert.Contains(t, err.Error(), "bts init")
|
||||
})
|
||||
|
||||
// Provision the database the way bts would (a normal, migrating open).
|
||||
provisioner, err := h.openProvider(ctx, database, false)
|
||||
provisioner, err := h.openProvider(ctx, database, false, "")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, provisioner.Close(ctx))
|
||||
|
||||
|
|
@ -122,7 +123,7 @@ func TestTeamServerMode_Integration(t *testing.T) {
|
|||
require.Positive(t, before.maxVersion, "provisioning must have applied migrations")
|
||||
|
||||
t.Run("matching version opens and leaves schema_migrations untouched", func(t *testing.T) {
|
||||
p, err := h.openProvider(ctx, database, true)
|
||||
p, err := h.openProvider(ctx, database, true, "")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = p.Close(ctx) })
|
||||
|
||||
|
|
@ -135,6 +136,43 @@ func TestTeamServerMode_Integration(t *testing.T) {
|
|||
"team-server open must not modify schema_migrations")
|
||||
})
|
||||
|
||||
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
|
||||
// it again on the proxied path.
|
||||
_, err := direct.ExecContext(ctx,
|
||||
"REPLACE INTO metadata (`key`, value) VALUES (?, ?)", "_project_id", "project-owning-this-db")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
_, err := direct.ExecContext(ctx, "DELETE FROM metadata WHERE `key` = ?", "_project_id")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("matching workspace identity opens", func(t *testing.T) {
|
||||
p, err := h.openProvider(ctx, database, true, "project-owning-this-db")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = p.Close(ctx) })
|
||||
})
|
||||
|
||||
// The negative control: a workspace belonging to another project must
|
||||
// be refused rather than silently served this database.
|
||||
t.Run("foreign workspace identity is refused", func(t *testing.T) {
|
||||
p, err := h.openProvider(ctx, database, true, "project-somewhere-else")
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, p)
|
||||
assert.Contains(t, err.Error(), "PROJECT IDENTITY MISMATCH")
|
||||
assert.Contains(t, err.Error(), "project-somewhere-else")
|
||||
assert.Contains(t, err.Error(), "project-owning-this-db")
|
||||
})
|
||||
|
||||
// The adoption path (bd init --team-server) asserts nothing.
|
||||
t.Run("adoption path still opens", func(t *testing.T) {
|
||||
p, err := h.openProvider(ctx, database, true, "")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = p.Close(ctx) })
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("behind database refused with bts migrate", func(t *testing.T) {
|
||||
// Roll the migration cursor back one version to simulate a behind DB.
|
||||
var savedHash sql.NullString
|
||||
|
|
@ -150,7 +188,7 @@ func TestTeamServerMode_Integration(t *testing.T) {
|
|||
rolledBack := snapshotMigrations(t, ctx, direct)
|
||||
require.Less(t, rolledBack.maxVersion, before.maxVersion)
|
||||
|
||||
p, err := h.openProvider(ctx, database, true)
|
||||
p, err := h.openProvider(ctx, database, true, "")
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, p)
|
||||
assert.Contains(t, err.Error(), "bts migrate")
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
)
|
||||
|
||||
|
|
@ -32,3 +33,65 @@ func checkTeamServerSchema(ctx context.Context, conn schema.DBConn, database str
|
|||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkTeamServerIdentity verifies that the bts-managed database this
|
||||
// invocation is about to open really belongs to the calling workspace's
|
||||
// project. The connection must already have the database selected.
|
||||
//
|
||||
// The proxied/team-server path never constructs a DoltStore, so
|
||||
// DoltStore.verifyProjectIdentity — which guards every non-CreateIfMissing
|
||||
// gateway open — is unreachable here. `bd init --team-server` ADOPTS whatever
|
||||
// identity the shared database carries (it has no expected value to assert
|
||||
// against), and before this check nothing re-asserted it on any later open.
|
||||
// That was tolerable while proxied-server meant a per-workspace database bd
|
||||
// created itself; --team-server points bd at a long-lived operator-managed
|
||||
// database selectable per invocation via --database, which is exactly the
|
||||
// "serving a DIFFERENT project" case the gateway guard exists to catch.
|
||||
//
|
||||
// expectedProjectID is empty for the paths that legitimately have no
|
||||
// assertion to make (`bd init`, which adopts, and server-wide database
|
||||
// maintenance); those skip the check.
|
||||
func checkTeamServerIdentity(ctx context.Context, conn schema.DBConn, database, expectedProjectID string) error {
|
||||
// Soft-skip semantics deliberately mirror DoltStore.verifyProjectIdentity:
|
||||
// an empty id on EITHER side means "no assertion available", not
|
||||
// "mismatch", so workspaces and databases that predate project identity
|
||||
// keep working.
|
||||
if expectedProjectID == "" {
|
||||
return nil
|
||||
}
|
||||
// A read error is surfaced rather than skipped: checkTeamServerSchema has
|
||||
// already proven the beads schema is present at this binary's version, so
|
||||
// the metadata table exists and a failure here is a real fault, not the
|
||||
// legacy-database case verifyProjectIdentity tolerates.
|
||||
dbProjectID, err := issueops.GetMetadataInTx(ctx, conn, "_project_id")
|
||||
if err != nil {
|
||||
return fmt.Errorf("uow: team-server identity check on database %q: %w", database, err)
|
||||
}
|
||||
// Unlike verifyProjectIdentity, an absent stored identity is NOT tolerated
|
||||
// here. adoptTeamServerIdentity refuses to attach to a bts database that
|
||||
// has no metadata._project_id at all, so for a team-server database this
|
||||
// is an already-invalid state rather than a legacy one — and soft-skipping
|
||||
// it would mean deleting one row from the shared database silently
|
||||
// disables this guard for every client.
|
||||
if dbProjectID == "" {
|
||||
return fmt.Errorf(
|
||||
"uow: database %q has no project identity (metadata._project_id) — the schema is managed by beads-team-server; ask your operator to provision it with 'bts init' (or heal an older bts database with 'bts migrate')",
|
||||
database)
|
||||
}
|
||||
if dbProjectID != expectedProjectID {
|
||||
return fmt.Errorf(
|
||||
"PROJECT IDENTITY MISMATCH — refusing to connect\n\n"+
|
||||
" Local project ID (metadata.json): %s\n"+
|
||||
" Database %q project ID: %s\n\n"+
|
||||
"The team server is serving a DIFFERENT project's database.\n"+
|
||||
"This can happen when:\n"+
|
||||
" - --database (or a --db name override) points at another project\n"+
|
||||
" - the configured dolt_database was repointed after 'bd init'\n"+
|
||||
" - the operator re-provisioned this database for another project\n\n"+
|
||||
"Check dolt_database in .beads/metadata.json and any --database/--db\n"+
|
||||
"override. 'bd init --team-server' re-adopts the provisioned identity\n"+
|
||||
"and never writes to the shared database, so it is safe to re-run.",
|
||||
expectedProjectID, database, dbProjectID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -154,3 +154,112 @@ func TestCheckTeamServerSchema_Ahead_EscapeHatchWarnsInsteadOfRefusing(t *testin
|
|||
t.Errorf("stderr = %q, want a schema-skew warning", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func expectProjectIDQuery(mock sqlmock.Sqlmock, projectID string) {
|
||||
mock.ExpectQuery("SELECT value FROM metadata WHERE .key. = \\?").
|
||||
WithArgs("_project_id").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"value"}).AddRow(projectID))
|
||||
}
|
||||
|
||||
// The negative control: a database provisioned for a different project must be
|
||||
// refused, not adopted. This is the whole point of the guard — on the proxied
|
||||
// path nothing else re-checks identity after init.
|
||||
func TestCheckTeamServerIdentity_ForeignProjectID_Refuses(t *testing.T) {
|
||||
mock, db, closeDB := newVersionMockDB(t)
|
||||
defer closeDB()
|
||||
expectProjectIDQuery(mock, "project-BBBB")
|
||||
|
||||
err := checkTeamServerIdentity(context.Background(), db, "beads_team", "project-AAAA")
|
||||
if err == nil {
|
||||
t.Fatal("checkTeamServerIdentity = nil, want refusal when the database serves a different project")
|
||||
}
|
||||
for _, want := range []string{"PROJECT IDENTITY MISMATCH", "project-AAAA", "project-BBBB", "beads_team"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("error %q should contain %q", err, want)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(err.Error(), "bd init --team-server") {
|
||||
t.Errorf("error %q should tell the user re-running init is safe", err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckTeamServerIdentity_MatchingProjectID_OK(t *testing.T) {
|
||||
mock, db, closeDB := newVersionMockDB(t)
|
||||
defer closeDB()
|
||||
expectProjectIDQuery(mock, "project-AAAA")
|
||||
|
||||
if err := checkTeamServerIdentity(context.Background(), db, "beads_team", "project-AAAA"); err != nil {
|
||||
t.Fatalf("checkTeamServerIdentity = %v, want nil when identities match", err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// `bd init --team-server` adopts the provisioned identity, so it passes an
|
||||
// empty expectation. The check must then not query at all — asserting the
|
||||
// locally-minted placeholder would reject every correct init.
|
||||
func TestCheckTeamServerIdentity_AdoptionPath_SkipsWithoutQuerying(t *testing.T) {
|
||||
mock, db, closeDB := newVersionMockDB(t)
|
||||
defer closeDB()
|
||||
|
||||
if err := checkTeamServerIdentity(context.Background(), db, "beads_team", ""); err != nil {
|
||||
t.Fatalf("checkTeamServerIdentity = %v, want nil on the adoption path", err)
|
||||
}
|
||||
// No ExpectQuery was registered; any query would be an unexpected call.
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("adoption path must not query the database: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A bts-managed database with no _project_id row is an invalid state, not a
|
||||
// legacy one: adoptTeamServerIdentity refuses to attach to such a database in
|
||||
// the first place. Soft-skipping it would let one deleted row disable the
|
||||
// guard for every client.
|
||||
func TestCheckTeamServerIdentity_DatabaseWithoutIdentity_Refuses(t *testing.T) {
|
||||
mock, db, closeDB := newVersionMockDB(t)
|
||||
defer closeDB()
|
||||
mock.ExpectQuery("SELECT value FROM metadata WHERE .key. = \\?").
|
||||
WithArgs("_project_id").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"value"}))
|
||||
|
||||
err := checkTeamServerIdentity(context.Background(), db, "beads_team", "project-AAAA")
|
||||
if err == nil {
|
||||
t.Fatal("checkTeamServerIdentity = nil, want refusal for a database with no _project_id")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "bts init") {
|
||||
t.Errorf("error %q should point the operator at 'bts init'", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckTeamServerIdentity_EmptyStoredIdentity_Refuses(t *testing.T) {
|
||||
mock, db, closeDB := newVersionMockDB(t)
|
||||
defer closeDB()
|
||||
expectProjectIDQuery(mock, "")
|
||||
|
||||
if err := checkTeamServerIdentity(context.Background(), db, "beads_team", "project-AAAA"); err == nil {
|
||||
t.Fatal("checkTeamServerIdentity = nil, want refusal for an empty stored identity")
|
||||
}
|
||||
}
|
||||
|
||||
// Unlike the legacy-database cases above, a genuine read failure is surfaced:
|
||||
// checkTeamServerSchema has already proven the schema is present, so the
|
||||
// metadata table exists and an error here is a real fault.
|
||||
func TestCheckTeamServerIdentity_ReadError_Surfaces(t *testing.T) {
|
||||
mock, db, closeDB := newVersionMockDB(t)
|
||||
defer closeDB()
|
||||
mock.ExpectQuery("SELECT value FROM metadata WHERE .key. = \\?").
|
||||
WithArgs("_project_id").
|
||||
WillReturnError(errors.New("Error 1105 (HY000): connection reset"))
|
||||
|
||||
err := checkTeamServerIdentity(context.Background(), db, "beads_team", "project-AAAA")
|
||||
if err == nil {
|
||||
t.Fatal("checkTeamServerIdentity = nil, want the read error surfaced")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "beads_team") {
|
||||
t.Errorf("error %q should name the database", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ func newTestUOWProvider(t *testing.T) UnitOfWorkProvider {
|
|||
0,
|
||||
0,
|
||||
false,
|
||||
"",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, provider)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue