beads/cmd/bd/resolve_dolt_server_connection_test.go
Jim Wordelman 349e4b029f
fix(dolt): explicit ServerPort must outrank ambient BEADS_DOLT_SERVER_PORT env var (#5835)
* test(feat): red — Fix: explicit Config.ServerPort must outrank ambient BEADS_DOLT_SERVER_PORT env var (refs be-wf9a.1)

* feat: green — Fix: explicit Config.ServerPort must outrank ambient BEADS_DOLT_SERVER_PORT env var (refs be-wf9a.1)

* test(dolt): red — applyResolvedConfig must propagate ServerPortSource (refs be-9tju)

Four new subtests on TestApplyResolvedConfig pin down the reviewer's
security blocker: applyResolvedConfig (open.go:250-255) copies only
doltserver.DefaultConfig(beadsDir).Port into cfg.ServerPort, never
.PortSource/.PortSharedServer. Chained through applyConfigDefaults,
this mislabels any port-file-resolved port as PortSourceCallerExplicit
(the PortSourceUnset guard at store.go:1429 can't tell the difference),
which in turn makes the legacy BEADS_DOLT_PORT env-var override at
store.go:1439 a no-op — a regression of the hq-27t bug class.

Currently failing (RED), for the traced reasons:
- "propagates ServerPortSource...": ServerPortSource stays "" instead
  of "port_file".
- "chained through applyConfigDefaults...never mislabeled": comes out
  "caller_explicit" instead of "port_file".
- "legacy BEADS_DOLT_PORT redirects...": ServerPort stays the
  port-file value (14567) instead of following the env override
  (43211).

A fourth subtest ("genuinely caller-explicit ServerPort still
outranks ambient env") already passes today — it chains through the
same real applyResolvedConfig -> applyConfigDefaults integration path
that the reviewer flagged as uncovered (the existing
TestApplyConfigDefaults_* tests bypass applyResolvedConfig entirely
via a bare &Config{}), locking in that be-wf9a.1's original
caller-explicit-wins intent survives the upcoming fix.

* fix(dolt): green — propagate ServerPortSource so legacy port-env override isn't silently skipped (refs be-9tju)

Two-part fix for the request-changes security blocker on this branch:

1. internal/storage/dolt/open.go applyResolvedConfig: when ServerPort
   resolves via doltserver.DefaultConfig(beadsDir)'s fallback chain
   (env > port file > config.yaml > metadata), propagate the resolved
   .PortSource and .PortSharedServer alongside .Port — mirroring the
   pattern store.go's own fallback block already uses. Previously only
   .Port was copied, leaving ServerPortSource at its zero value
   (PortSourceUnset) even when the port came from an ambient/stored
   resolution like the port file.

2. internal/storage/dolt/store.go applyConfigDefaults: widen the legacy
   BEADS_DOLT_PORT / BEADS_DOLT_SERVER_PORT env-override gate from
   `cfg.ServerPort == 0` to `cfg.ServerPort == 0 ||
   !cfg.ServerPortSource.IsAuthoritative()`. Part 1 alone isn't
   sufficient: the gate only ever checked whether ServerPort was zero,
   independent of whether its source was actually caller-authoritative.

Without both parts, applyConfigDefaults's PortSourceUnset check
(`if cfg.ServerPort != 0 && cfg.ServerPortSource == PortSourceUnset {
cfg.ServerPortSource = PortSourceCallerExplicit }`) mislabeled a
port-file-resolved port as caller-explicit, which then made the legacy
env override a silent no-op for any normal (non-init) bd command
against an already-initialized project — a regression of the hq-27t
bug class, exactly as reported in be-9tju's rejection notes.

A genuinely caller-explicit ServerPort (e.g. bd init --server-port)
still outranks the ambient env var: applyResolvedConfig only stamps
PortSourceCallerExplicit when the caller preset ServerPort before the
call, and IsAuthoritative() is true for that source — covered by the
new "genuinely caller-explicit ... still outranks ambient env" subtest
committed in the RED step (4f4de51618).

Targeted test: go test ./internal/storage/dolt/... -run
TestApplyResolvedConfig -v — all 10 subtests (6 original + 4 new) pass.

Full suite: bash scripts/ci/pr-core.sh succeeded in 345s, zero FAILs,
including both packages that timed out on the prior rejected run
(cmd/bd 288.243s ok, internal/storage/embeddeddolt 255.521s ok) and
both packages this diff touches (internal/doltserver 5.045s ok,
internal/storage/dolt 9.520s ok). Log: /tmp/tdd-green-pr-core.log.

* docs(release-gates): record be-gd3v gate PASS (ServerPort precedence fix)

All 7 criteria clear: review PASS, tests green (-race, 0 skips),
lint clean, no blocking findings, clean tree, clean fast-forward off
origin/main, single theme. PR gastownhall/beads#5835 opened.

* fix(doltserver): stamp a PortSource on the shared-server default port

Review point 1 (blocking), part 1 of 2.

DefaultConfig filled in DefaultSharedServerPort (3308) when shared-server
mode is on and no source resolved a port, but left PortSource unset. That
made a bd-chosen port indistinguishable from a caller assertion: any site
copying DefaultConfig(...).Port into dolt.Config.ServerPort hands
applyConfigDefaults a nonzero port with PortSourceUnset, and the
"nonzero + unset => caller_explicit" inference (be-wf9a.1) stamps it
authoritative.

Add PortSourceSharedServerDefault -- deliberately NOT authoritative, since
bd picked it on the user's behalf exactly like the port file -- and record
it on that fill. TestDefaultConfig_NonzeroPortAlwaysHasSource pins the
invariant the inference depends on: DefaultConfig never returns a nonzero
Port with PortSourceUnset. Verified red before the fix (Port=3308 with
PortSourceUnset), green after.

Propagation at the remaining unthreaded call sites follows in part 2.

* fix(cmd/bd): propagate PortSource at the remaining unthreaded config sites

Review point 1 (blocking), part 2 of 2.

applyConfigDefaults infers "the caller explicitly asserted this port" from
"ServerPort nonzero, ServerPortSource unset" (be-wf9a.1). Round 2 closed
that gap in applyResolvedConfig, but four twin sites still copied
doltserver.DefaultConfig(dir).Port into a hand-built dolt.Config without
the source, so every port bd resolved for itself arrived labeled
authoritative:

  - cmd/bd/main.go resolveDoltServerConnection -- the primary CLI
    store-open path, and the connection `bd serve` builds
    (cmd/bd/uow_factory.go). Its own comment said it mirrors
    applyResolvedConfig; the mirror had gone out of sync.
  - cmd/bd/init.go initPort -- resolves from the env var, the port file,
    or the shared-server default 3308. None of the three is a caller
    assertion.
  - cmd/bd/init.go initGlobalDatabaseConfig -- copied ServerPort forward
    without its source.
  - cmd/bd/doctor/federation.go doltServerConfig.

Consequences, both user-visible: the legacy BEADS_DOLT_PORT override
became a silent no-op on the main CLI path while still working on the
library open path -- the two open paths disagreed on precedence -- and a
stale .beads/dolt-server.port after a crashed server made auto-start
hard-fail with "bd will not silently use a different port than the one you
configured" when the user had configured nothing (GH#4052).

Centralize rather than repeat the three-line copy a fifth time:
dolt.ApplyResolvedServerPort(beadsDir, cfg) resolves port, source and
shared-server flag together, and applyResolvedConfig now uses it too.
init.go keeps its own hand-rolled chain (it deliberately consults only
project-local sources, GH#2336) and tracks the source alongside; `bd init
--server-port` stamps PortSourceCallerExplicit itself, replacing rather
than inheriting the resolved source.

The shared-server default also sets ServerPortSharedServer, mirroring
DefaultConfig: if the shared server is down and auto-start brings up a
repo-local one, that is a different database, so newServerMode still fails
closed -- now with the accurate message instead of one blaming the user's
config.

Tests: TestApplyResolvedServerPort (+ chained through applyConfigDefaults)
and TestResolveDoltServerConnectionPropagatesPortSource assert the source
travels and, directly, that IsAuthoritative() is false for both port-file
and shared-default ports -- that predicate is what both consumers branch
on. Verified red before the fix (ServerPortSource = "" on the CLI path),
green after.

* docs(changelog): record the ServerPort precedence changes

Review point 2. Two deliberate user-visible precedence flips shipped
without a CHANGELOG entry: caller-explicit ServerPort now beats the ambient
port env vars, and the legacy BEADS_DOLT_PORT spelling no longer overrides
a port resolved from config.yaml, Dolt's listener.port, or metadata.json.
Both are intentional, so both are documented, with the migration for the
one workspace shape that changes behavior.

Also notes the GH#4052 failure that goes away with them -- a stale
.beads/dolt-server.port no longer makes auto-start refuse to start over a
port the user never configured -- since that is user-visible too.

Placed at the top of Unreleased/Changed rather than the end: main has been
appending after the existing entry, so inserting before it leaves that
block as common context and the two hunks merge without conflict.

* docs(release-gates): note the be-gd3v gate describes 2dbcbd7f2, not the head

Review point 3 (nit). The gate recorded headRefOid = 2dbcbd7f2 with "no
drift", but the commit adding the gate document was itself the first to
move the head past that SHA, so the claim contradicted itself the moment it
landed. Qualify the line as a snapshot and add a Post-gate history section
listing what has landed since -- including this review round, whose code
changes the criteria walk does not cover.

Corrected by annotation rather than by editing the verdict: the PASS is
still accurate about the SHA it examined.
2026-08-20 05:43:57 -07:00

74 lines
3.3 KiB
Go

//go:build cgo
package main
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/doltserver"
"github.com/steveyegge/beads/internal/storage/dolt"
)
// TestResolveDoltServerConnectionPropagatesPortSource guards the primary CLI
// store-open path (and, through the same function, the unit-of-work provider
// `bd serve` builds).
//
// resolveDoltServerConnection hand-builds a dolt.Config that is handed straight
// to dolt.New → applyConfigDefaults, which infers "the caller explicitly
// asserted this port" from "ServerPort nonzero, ServerPortSource unset". While
// this site copied doltserver.DefaultConfig(dir).Port alone, every port bd
// resolved for itself arrived here labeled authoritative — so the CLI path and
// the library open path (dolt.NewFromConfig) disagreed on precedence: the
// legacy BEADS_DOLT_PORT override was honored by one and silently dropped by
// the other.
func TestResolveDoltServerConnectionPropagatesPortSource(t *testing.T) {
t.Run("port-file port is not a caller assertion (be-9tju)", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
t.Setenv("BEADS_DOLT_PORT", "")
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("HOME", t.TempDir())
beadsDir := t.TempDir()
if err := doltserver.EnsurePortFile(beadsDir, 14567); err != nil {
t.Fatalf("EnsurePortFile: %v", err)
}
doltCfg := &dolt.Config{BeadsDir: beadsDir}
if err := resolveDoltServerConnection(context.Background(), beadsDir, &configfile.Config{Backend: configfile.BackendDolt}, doltCfg); err != nil {
t.Fatalf("resolveDoltServerConnection: %v", err)
}
if doltCfg.ServerPort != 14567 {
t.Fatalf("ServerPort = %d, want 14567", doltCfg.ServerPort)
}
if doltCfg.ServerPortSource != doltserver.PortSourcePortFile {
t.Fatalf("ServerPortSource = %q, want %q: the source must travel with the port, or applyConfigDefaults promotes bd's own port-file bookkeeping to caller_explicit", doltCfg.ServerPortSource, doltserver.PortSourcePortFile)
}
if doltCfg.ServerPortSource.IsAuthoritative() {
t.Fatal("port-file port reported authoritative on the CLI path: BEADS_DOLT_PORT becomes a silent no-op here while still working on the library open path, and a stale port file turns auto-start's benign retarget into a hard error (GH#4052)")
}
})
t.Run("shared-server default is not a caller assertion (GH#4052)", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
t.Setenv("BEADS_DOLT_PORT", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("HOME", t.TempDir())
t.Setenv("BEADS_DOLT_SHARED_SERVER", "1")
beadsDir := t.TempDir()
doltCfg := &dolt.Config{BeadsDir: beadsDir}
if err := resolveDoltServerConnection(context.Background(), beadsDir, &configfile.Config{Backend: configfile.BackendDolt}, doltCfg); err != nil {
t.Fatalf("resolveDoltServerConnection: %v", err)
}
if doltCfg.ServerPort != doltserver.DefaultSharedServerPort {
t.Fatalf("ServerPort = %d, want %d", doltCfg.ServerPort, doltserver.DefaultSharedServerPort)
}
if doltCfg.ServerPortSource.IsAuthoritative() {
t.Fatalf("ServerPortSource = %q reported authoritative: bd chose the shared default 3308 itself, so it must not be defended as a user-configured port", doltCfg.ServerPortSource)
}
})
}