fix(init): gate server-conn promotion on server mode and make it restorable
Three blockers from the #5178 review: 1. Lint: the os.Setenv/os.Unsetenv return values are checked. The restore path discards them deliberately, with the reason in a comment. 2. Embedded mode: the promotion moved out of the top of RunE to just after every source of server mode has been consulted (--server, BEADS_DOLT_SERVER_MODE, --shared-server, workspace inheritance, and config.yaml dolt.mode), and is skipped when embedded mode wins. Running it unconditionally exported BEADS_DOLT_SERVER_* during an embedded init, which tripped init's own remote-host guard and broke TestEmbeddedInit/server_flags_ignored. Gating reproduces today's contract: embedded init still records the flags in metadata.json without acting on them. Gating on the resolved mode rather than on the literal --server flag also covers inherited and configured server workspaces. 3. Env leak across in-process invocations: promoteExplicitServerConnFlags returns a restore func that puts every touched variable back, including ones that were absent, and init defers it. One CLI process runs one init, but the test binary runs many, which is what the macos-latest failures showed. Validation is also separated from application, so a later invalid flag can no longer leave an earlier valid one already written to the environment. Adds five regressions for the restore contract, including two sequential in-process promotions that must not accumulate. Refs: gastownhall/beads#5178 (review)
This commit is contained in:
parent
fd524aa479
commit
9960f14a6e
2 changed files with 255 additions and 35 deletions
181
cmd/bd/init.go
181
cmd/bd/init.go
|
|
@ -386,9 +386,6 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
serverUser, _ := cmd.Flags().GetString("server-user")
|
||||
database, _ := cmd.Flags().GetString("database")
|
||||
destroyToken, _ := cmd.Flags().GetString("destroy-token")
|
||||
if err := promoteExplicitServerConnFlags(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// --force is a deprecated alias for --reinit-local. They share
|
||||
// semantics for the local data-safety guard; both refuse remote
|
||||
|
|
@ -705,6 +702,20 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
}
|
||||
}
|
||||
|
||||
// Explicit connection flags outrank stale BEADS_DOLT_SERVER_* values
|
||||
// (GH#5177). This must run AFTER every source of server mode has been
|
||||
// consulted above: --server, BEADS_DOLT_SERVER_MODE, --shared-server,
|
||||
// workspace inheritance, and config.yaml dolt.mode. In embedded mode
|
||||
// the flags are still recorded in metadata.json, but promoting them
|
||||
// into the environment would trip init's own remote-host guard below.
|
||||
if initServerMode {
|
||||
restoreServerConnEnv, err := promoteExplicitServerConnFlags(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer restoreServerConnEnv()
|
||||
}
|
||||
|
||||
// Reject hyphens in --database for embedded mode. Must run AFTER
|
||||
// serverMode is set above — otherwise !usesSQLServer() always returns
|
||||
// true and incorrectly rejects server-mode names (GH#3231).
|
||||
|
|
@ -3053,6 +3064,72 @@ func initRemoteCloneMode(initServerMode, externalServer bool) remoteCloneMode {
|
|||
return remoteCloneCLI
|
||||
}
|
||||
|
||||
// serverConnEnvMutation is one pending change to the process environment.
|
||||
// unset records the "remove this variable" case, which is distinct from
|
||||
// setting it to the empty string for every downstream resolver.
|
||||
type serverConnEnvMutation struct {
|
||||
key string
|
||||
value string
|
||||
unset bool
|
||||
}
|
||||
|
||||
// resolveExplicitServerConnEnv turns the explicit --server-* flags into the
|
||||
// set of environment changes promoteExplicitServerConnFlags will apply. It
|
||||
// validates every flag before returning, so a later invalid flag cannot leave
|
||||
// an earlier valid one already applied to the process environment.
|
||||
//
|
||||
// Because a socket outranks host/port everywhere downstream, selecting TCP
|
||||
// explicitly (--server-host or --server-port) also clears an ambient
|
||||
// BEADS_DOLT_SERVER_SOCKET unless --server-socket was itself given. An
|
||||
// explicitly empty --server-socket clears the ambient socket too: empty is
|
||||
// the documented "use TCP" value (see configfile.GetDoltServerSocket).
|
||||
// Changed-but-empty host/user and out-of-range port values fail explicitly
|
||||
// rather than being silently ignored.
|
||||
func resolveExplicitServerConnEnv(cmd *cobra.Command) ([]serverConnEnvMutation, error) {
|
||||
var muts []serverConnEnvMutation
|
||||
if cmd.Flags().Changed("server-host") {
|
||||
v, _ := cmd.Flags().GetString("server-host")
|
||||
if v == "" {
|
||||
return nil, fmt.Errorf("--server-host cannot be empty; omit the flag to use BEADS_DOLT_SERVER_HOST or the default (%s)", configfile.DefaultDoltServerHost)
|
||||
}
|
||||
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_HOST", value: v})
|
||||
}
|
||||
if cmd.Flags().Changed("server-port") {
|
||||
v, _ := cmd.Flags().GetInt("server-port")
|
||||
if v < 1 || v > 65535 {
|
||||
return nil, fmt.Errorf("--server-port must be between 1 and 65535, got %d; omit the flag to use BEADS_DOLT_SERVER_PORT or the default (%d)", v, configfile.DefaultDoltServerPort)
|
||||
}
|
||||
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_PORT", value: strconv.Itoa(v)})
|
||||
}
|
||||
if cmd.Flags().Changed("server-user") {
|
||||
v, _ := cmd.Flags().GetString("server-user")
|
||||
if v == "" {
|
||||
return nil, fmt.Errorf("--server-user cannot be empty; omit the flag to use BEADS_DOLT_SERVER_USER or the default (%s)", configfile.DefaultDoltServerUser)
|
||||
}
|
||||
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_USER", value: v})
|
||||
}
|
||||
switch {
|
||||
case cmd.Flags().Changed("server-socket"):
|
||||
v, _ := cmd.Flags().GetString("server-socket")
|
||||
if v == "" {
|
||||
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_SOCKET", unset: true})
|
||||
} else {
|
||||
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_SOCKET", value: v})
|
||||
}
|
||||
case cmd.Flags().Changed("server-host") || cmd.Flags().Changed("server-port"):
|
||||
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_SOCKET", unset: true})
|
||||
}
|
||||
if cmd.Flags().Changed("server-tls") {
|
||||
v, _ := cmd.Flags().GetBool("server-tls")
|
||||
tls := "0"
|
||||
if v {
|
||||
tls = "1"
|
||||
}
|
||||
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_TLS", value: tls})
|
||||
}
|
||||
return muts, nil
|
||||
}
|
||||
|
||||
// promoteExplicitServerConnFlags makes an explicit --server-host/--server-port/
|
||||
// --server-user/--server-socket/--server-tls flag outrank the corresponding
|
||||
// BEADS_DOLT_SERVER_* environment variable. Every downstream resolver
|
||||
|
|
@ -3060,63 +3137,63 @@ func initRemoteCloneMode(initServerMode, externalServer bool) remoteCloneMode {
|
|||
// first, so without promotion a stale shell-profile value silently redirects
|
||||
// init to a different server than the one named on the command line.
|
||||
//
|
||||
// Because a socket outranks host/port everywhere downstream, selecting TCP
|
||||
// explicitly (--server-host or --server-port) also clears an ambient
|
||||
// BEADS_DOLT_SERVER_SOCKET unless --server-socket was itself given. An
|
||||
// explicitly empty --server-socket clears the ambient socket too: empty is
|
||||
// the documented "use TCP" value. Changed-but-empty host/user and
|
||||
// out-of-range port values fail explicitly rather than being silently
|
||||
// ignored.
|
||||
// Callers must invoke this only once server mode is resolved: in embedded
|
||||
// mode the connection flags are recorded in metadata.json but must not reach
|
||||
// the environment, or init trips its own "embedded mode has no host/port"
|
||||
// guard.
|
||||
//
|
||||
// The promotion is scoped to this process's environment only; nothing here
|
||||
// is persisted to metadata.json (TLS in particular stays env/credentials-file
|
||||
// configured, per bd dolt help).
|
||||
func promoteExplicitServerConnFlags(cmd *cobra.Command) error {
|
||||
if cmd.Flags().Changed("server-host") {
|
||||
v, _ := cmd.Flags().GetString("server-host")
|
||||
if v == "" {
|
||||
return fmt.Errorf("--server-host cannot be empty; omit the flag to use BEADS_DOLT_SERVER_HOST or the default (%s)", configfile.DefaultDoltServerHost)
|
||||
}
|
||||
os.Setenv("BEADS_DOLT_SERVER_HOST", v)
|
||||
// The returned restore function puts the environment back exactly as it was,
|
||||
// including variables that were absent. One CLI process runs one init, so the
|
||||
// mutation is invisible there, but any in-process caller (the test binary, an
|
||||
// embedding host) would otherwise inherit this invocation's overrides.
|
||||
// Callers should defer it on every return path.
|
||||
//
|
||||
// Nothing here is persisted to metadata.json (TLS in particular stays
|
||||
// env/credentials-file configured, per bd dolt help).
|
||||
func promoteExplicitServerConnFlags(cmd *cobra.Command) (func(), error) {
|
||||
noop := func() {}
|
||||
muts, err := resolveExplicitServerConnEnv(cmd)
|
||||
if err != nil {
|
||||
return noop, err
|
||||
}
|
||||
if cmd.Flags().Changed("server-port") {
|
||||
v, _ := cmd.Flags().GetInt("server-port")
|
||||
if v < 1 || v > 65535 {
|
||||
return fmt.Errorf("--server-port must be between 1 and 65535, got %d; omit the flag to use BEADS_DOLT_SERVER_PORT or the default (%d)", v, configfile.DefaultDoltServerPort)
|
||||
}
|
||||
os.Setenv("BEADS_DOLT_SERVER_PORT", strconv.Itoa(v))
|
||||
if len(muts) == 0 {
|
||||
return noop, nil
|
||||
}
|
||||
if cmd.Flags().Changed("server-user") {
|
||||
v, _ := cmd.Flags().GetString("server-user")
|
||||
if v == "" {
|
||||
return fmt.Errorf("--server-user cannot be empty; omit the flag to use BEADS_DOLT_SERVER_USER or the default (%s)", configfile.DefaultDoltServerUser)
|
||||
}
|
||||
os.Setenv("BEADS_DOLT_SERVER_USER", v)
|
||||
|
||||
type savedEnv struct {
|
||||
value string
|
||||
present bool
|
||||
}
|
||||
switch {
|
||||
case cmd.Flags().Changed("server-socket"):
|
||||
v, _ := cmd.Flags().GetString("server-socket")
|
||||
if v == "" {
|
||||
// Empty means TCP (see configfile.GetDoltServerSocket); an
|
||||
// explicit empty flag clears stale socket environment state.
|
||||
os.Unsetenv("BEADS_DOLT_SERVER_SOCKET")
|
||||
saved := make(map[string]savedEnv, len(muts))
|
||||
restore := func() {
|
||||
for key, prev := range saved {
|
||||
// Nothing actionable remains if the restore itself fails: the
|
||||
// process is either exiting or already past the init it scoped.
|
||||
if prev.present {
|
||||
_ = os.Setenv(key, prev.value)
|
||||
continue
|
||||
}
|
||||
_ = os.Unsetenv(key)
|
||||
}
|
||||
}
|
||||
|
||||
for _, mut := range muts {
|
||||
if _, seen := saved[mut.key]; !seen {
|
||||
value, present := os.LookupEnv(mut.key)
|
||||
saved[mut.key] = savedEnv{value: value, present: present}
|
||||
}
|
||||
var applyErr error
|
||||
if mut.unset {
|
||||
applyErr = os.Unsetenv(mut.key)
|
||||
} else {
|
||||
os.Setenv("BEADS_DOLT_SERVER_SOCKET", v)
|
||||
applyErr = os.Setenv(mut.key, mut.value)
|
||||
}
|
||||
case cmd.Flags().Changed("server-host") || cmd.Flags().Changed("server-port"):
|
||||
// Explicit TCP selection: an ambient socket would silently outrank
|
||||
// the host/port named on the command line.
|
||||
os.Unsetenv("BEADS_DOLT_SERVER_SOCKET")
|
||||
}
|
||||
if cmd.Flags().Changed("server-tls") {
|
||||
v, _ := cmd.Flags().GetBool("server-tls")
|
||||
if v {
|
||||
os.Setenv("BEADS_DOLT_SERVER_TLS", "1")
|
||||
} else {
|
||||
os.Setenv("BEADS_DOLT_SERVER_TLS", "0")
|
||||
if applyErr != nil {
|
||||
restore()
|
||||
return noop, fmt.Errorf("applying %s: %w", mut.key, applyErr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return restore, nil
|
||||
}
|
||||
|
||||
func initDoltServerTLSFromEnv() bool {
|
||||
|
|
|
|||
|
|
@ -25,11 +25,21 @@ func mustSetFlag(t *testing.T, c *cobra.Command, name, value string) {
|
|||
}
|
||||
}
|
||||
|
||||
// mustPromote applies the promotion and registers its restore for the end of
|
||||
// the subtest, so the cases below assert promoted state without leaking it.
|
||||
func mustPromote(t *testing.T, c *cobra.Command) {
|
||||
t.Helper()
|
||||
if err := promoteExplicitServerConnFlags(c); err != nil {
|
||||
restore := mustPromoteWithRestore(t, c)
|
||||
t.Cleanup(restore)
|
||||
}
|
||||
|
||||
func mustPromoteWithRestore(t *testing.T, c *cobra.Command) func() {
|
||||
t.Helper()
|
||||
restore, err := promoteExplicitServerConnFlags(c)
|
||||
if err != nil {
|
||||
t.Fatalf("promoteExplicitServerConnFlags: %v", err)
|
||||
}
|
||||
return restore
|
||||
}
|
||||
|
||||
func TestPromoteExplicitServerConnFlags(t *testing.T) {
|
||||
|
|
@ -192,10 +202,14 @@ func TestPromoteExplicitServerConnFlags(t *testing.T) {
|
|||
c := newServerFlagsCmd()
|
||||
mustSetFlag(t, c, tc.flag, tc.value)
|
||||
|
||||
err := promoteExplicitServerConnFlags(c)
|
||||
restore, err := promoteExplicitServerConnFlags(c)
|
||||
if err == nil {
|
||||
t.Fatalf("promoteExplicitServerConnFlags = nil, want error containing %q", tc.wantSub)
|
||||
}
|
||||
if restore == nil {
|
||||
t.Fatal("restore func is nil on error; callers defer it unconditionally")
|
||||
}
|
||||
restore()
|
||||
if !strings.Contains(err.Error(), tc.wantSub) {
|
||||
t.Errorf("error = %q, want substring %q", err, tc.wantSub)
|
||||
}
|
||||
|
|
@ -212,3 +226,132 @@ func TestPromoteExplicitServerConnFlags(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The promotion mutates process-global state. One CLI process runs one init,
|
||||
// but the test binary (and any embedding host) runs many in the same process,
|
||||
// so every override must be reversible. These cases pin the restore contract
|
||||
// that keeps main's suites passing unmodified.
|
||||
func TestPromoteExplicitServerConnFlagsRestoresEnv(t *testing.T) {
|
||||
t.Run("restores previous values after a successful promotion", func(t *testing.T) {
|
||||
t.Setenv("BEADS_DOLT_SERVER_HOST", "profile-host")
|
||||
t.Setenv("BEADS_DOLT_SERVER_PORT", "3307")
|
||||
t.Setenv("BEADS_DOLT_SERVER_USER", "profile-user")
|
||||
t.Setenv("BEADS_DOLT_SERVER_TLS", "1")
|
||||
|
||||
c := newServerFlagsCmd()
|
||||
mustSetFlag(t, c, "server-host", "db.example.com")
|
||||
mustSetFlag(t, c, "server-port", "3306")
|
||||
mustSetFlag(t, c, "server-user", "app_rw")
|
||||
mustSetFlag(t, c, "server-tls", "false")
|
||||
|
||||
restore := mustPromoteWithRestore(t, c)
|
||||
|
||||
if got := os.Getenv("BEADS_DOLT_SERVER_HOST"); got != "db.example.com" {
|
||||
t.Fatalf("BEADS_DOLT_SERVER_HOST = %q, want db.example.com while promoted", got)
|
||||
}
|
||||
|
||||
restore()
|
||||
|
||||
for key, want := range map[string]string{
|
||||
"BEADS_DOLT_SERVER_HOST": "profile-host",
|
||||
"BEADS_DOLT_SERVER_PORT": "3307",
|
||||
"BEADS_DOLT_SERVER_USER": "profile-user",
|
||||
"BEADS_DOLT_SERVER_TLS": "1",
|
||||
} {
|
||||
if got := os.Getenv(key); got != want {
|
||||
t.Errorf("after restore %s = %q, want %q", key, got, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("restores absent variables to absent", func(t *testing.T) {
|
||||
for _, key := range []string{"BEADS_DOLT_SERVER_HOST", "BEADS_DOLT_SERVER_PORT", "BEADS_DOLT_SERVER_SOCKET"} {
|
||||
t.Setenv(key, "")
|
||||
if err := os.Unsetenv(key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
c := newServerFlagsCmd()
|
||||
mustSetFlag(t, c, "server-host", "db.example.com")
|
||||
mustSetFlag(t, c, "server-port", "3306")
|
||||
|
||||
restore := mustPromoteWithRestore(t, c)
|
||||
if got := os.Getenv("BEADS_DOLT_SERVER_PORT"); got != "3306" {
|
||||
t.Fatalf("BEADS_DOLT_SERVER_PORT = %q, want 3306 while promoted", got)
|
||||
}
|
||||
|
||||
restore()
|
||||
|
||||
for _, key := range []string{"BEADS_DOLT_SERVER_HOST", "BEADS_DOLT_SERVER_PORT"} {
|
||||
if got, ok := os.LookupEnv(key); ok {
|
||||
t.Errorf("after restore %s = %q, want absent", key, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("restores a socket cleared by explicit TCP selection", func(t *testing.T) {
|
||||
t.Setenv("BEADS_DOLT_SERVER_SOCKET", "/tmp/profile.sock")
|
||||
|
||||
c := newServerFlagsCmd()
|
||||
mustSetFlag(t, c, "server-host", "db.example.com")
|
||||
|
||||
restore := mustPromoteWithRestore(t, c)
|
||||
if got, ok := os.LookupEnv("BEADS_DOLT_SERVER_SOCKET"); ok {
|
||||
t.Fatalf("BEADS_DOLT_SERVER_SOCKET = %q, want absent while promoted", got)
|
||||
}
|
||||
|
||||
restore()
|
||||
|
||||
if got := os.Getenv("BEADS_DOLT_SERVER_SOCKET"); got != "/tmp/profile.sock" {
|
||||
t.Errorf("after restore BEADS_DOLT_SERVER_SOCKET = %q, want /tmp/profile.sock", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a rejected flag leaves earlier valid flags unapplied", func(t *testing.T) {
|
||||
t.Setenv("BEADS_DOLT_SERVER_HOST", "profile-host")
|
||||
t.Setenv("BEADS_DOLT_SERVER_PORT", "3307")
|
||||
|
||||
// Host is valid and resolves first; the port is not. Validation runs
|
||||
// to completion before any variable is written, so the host must not
|
||||
// survive the rejection.
|
||||
c := newServerFlagsCmd()
|
||||
mustSetFlag(t, c, "server-host", "db.example.com")
|
||||
mustSetFlag(t, c, "server-port", "0")
|
||||
|
||||
restore, err := promoteExplicitServerConnFlags(c)
|
||||
if err == nil {
|
||||
t.Fatal("promoteExplicitServerConnFlags = nil, want an out-of-range port error")
|
||||
}
|
||||
restore()
|
||||
|
||||
if got := os.Getenv("BEADS_DOLT_SERVER_HOST"); got != "profile-host" {
|
||||
t.Errorf("BEADS_DOLT_SERVER_HOST = %q, want profile-host (unapplied)", got)
|
||||
}
|
||||
if got := os.Getenv("BEADS_DOLT_SERVER_PORT"); got != "3307" {
|
||||
t.Errorf("BEADS_DOLT_SERVER_PORT = %q, want 3307 (unapplied)", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("sequential in-process promotions do not accumulate", func(t *testing.T) {
|
||||
t.Setenv("BEADS_DOLT_SERVER_HOST", "profile-host")
|
||||
t.Setenv("BEADS_DOLT_SERVER_SOCKET", "/tmp/profile.sock")
|
||||
|
||||
// First invocation promotes, as a server-mode init would.
|
||||
first := newServerFlagsCmd()
|
||||
mustSetFlag(t, first, "server-host", "db.example.com")
|
||||
mustPromoteWithRestore(t, first)()
|
||||
|
||||
// Second invocation passes no connection flags, as an embedded-mode
|
||||
// init would. It must see the ambient environment, not the first
|
||||
// invocation's overrides.
|
||||
mustPromoteWithRestore(t, newServerFlagsCmd())()
|
||||
|
||||
if got := os.Getenv("BEADS_DOLT_SERVER_HOST"); got != "profile-host" {
|
||||
t.Errorf("BEADS_DOLT_SERVER_HOST = %q, want profile-host (first promotion leaked)", got)
|
||||
}
|
||||
if got := os.Getenv("BEADS_DOLT_SERVER_SOCKET"); got != "/tmp/profile.sock" {
|
||||
t.Errorf("BEADS_DOLT_SERVER_SOCKET = %q, want /tmp/profile.sock (first promotion leaked)", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue