diff --git a/cmd/bd/context_cmd.go b/cmd/bd/context_cmd.go index e4fae354d..edca12748 100644 --- a/cmd/bd/context_cmd.go +++ b/cmd/bd/context_cmd.go @@ -8,6 +8,7 @@ import ( "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/doltserver" "github.com/steveyegge/beads/internal/metrics" + "github.com/steveyegge/beads/internal/storage/domain" ) // ContextInfo contains the effective backend identity and repository context. @@ -59,7 +60,14 @@ Examples: return runContextProxiedServer(cmd, rootCtx) } - info := ContextInfo{ + // The direct route reads config files itself rather than through the + // contextinfo provider — it must answer in degraded states where no + // database can be opened — but it assembles the SAME snapshot the + // proxied route gets from the provider, and hands it to the same + // view. That is what keeps `bd context` one answer across two routes, + // and what puts both of them on the projection GET /v0/beads/context + // serves. + snapshot := domain.ContextInfo{ Backend: configfile.BackendDolt, BdVersion: Version, } @@ -79,14 +87,14 @@ Examples: return HandleError("cannot resolve repo context: %v", err) } - info.BeadsDir = rc.BeadsDir - info.RepoRoot = rc.RepoRoot - info.CWDRepoRoot = rc.CWDRepoRoot - info.IsRedirected = rc.IsRedirected - info.IsWorktree = rc.IsWorktree + snapshot.BeadsDir = rc.BeadsDir + snapshot.RepoRoot = rc.RepoRoot + snapshot.CWDRepoRoot = rc.CWDRepoRoot + snapshot.IsRedirected = rc.IsRedirected + snapshot.IsWorktree = rc.IsWorktree if role, ok := rc.Role(); ok { - info.Role = string(role) + snapshot.Role = string(role) } cfg, err := configfile.Load(rc.BeadsDir) @@ -97,32 +105,30 @@ Examples: cfg = configfile.DefaultConfig() } - info.DoltMode = cfg.GetDoltMode() - info.Database = cfg.GetDoltDatabase() - info.ProjectID = cfg.ProjectID + snapshot.DoltMode = cfg.GetDoltMode() + snapshot.Database = cfg.GetDoltDatabase() + snapshot.ProjectID = cfg.ProjectID if cfg.IsDoltServerMode() { - info.ServerHost = cfg.GetDoltServerHost() + snapshot.ServerHost = cfg.GetDoltServerHost() dsCfg := doltserver.DefaultConfig(rc.BeadsDir) - info.ServerPort = dsCfg.Port + snapshot.ServerPort = dsCfg.Port } if cfg.IsDoltProxiedServerMode() { p, err := resolveProxiedServerRootPath(rc.BeadsDir) if err != nil { return HandleError("resolve proxied server root: %v", err) } - info.ProxiedDir = p + snapshot.ProxiedDir = p } if dataDir := cfg.GetDoltDataDir(); dataDir != "" { - info.DataDir = dataDir + snapshot.DataDir = dataDir } - if remote := resolveSyncRemoteFromDir(rc.BeadsDir); remote != "" { - info.SyncRemote = remote - info.SyncGitRemote = remote - } + snapshot.SyncRemote = resolveSyncRemoteFromDir(rc.BeadsDir) + info := contextInfoView(snapshot) if jsonOutput { return outputJSON(info) } diff --git a/cmd/bd/context_proxied_server.go b/cmd/bd/context_proxied_server.go index e5373b58d..5bf1bf1c8 100644 --- a/cmd/bd/context_proxied_server.go +++ b/cmd/bd/context_proxied_server.go @@ -44,24 +44,42 @@ func contextProxiedError(format string, args ...any) error { return HandleError(format, args...) } +// contextInfoView projects a workspace snapshot onto what `bd context` prints +// and marshals. BOTH routes reach it — the proxied one above and the direct +// one in context_cmd.go — so there is one answer to "what does bd context +// say", assembled once. +// +// The workspace identity half comes from domain.PublishedContext, the same +// projection GET /v0/beads/context serves, so the two surfaces cannot name the +// same workspace differently. +// +// Everything below that call is LOCAL-ONLY and deliberately so, which is why +// it is written out here rather than added to the shared projection. These are +// operator diagnostics printed to the terminal of whoever owns the workspace: +// the redirect and worktree flags, the absolute host paths, the database bind +// endpoint, the role, and the sync remote — which is exactly the member the +// shared projection has no room for, because a remote URL routinely embeds a +// credential and an HTTP client is not the person who configured it. func contextInfoView(d domain.ContextInfo) ContextInfo { + published := domain.PublishedContext(d) return ContextInfo{ - BeadsDir: d.BeadsDir, - RepoRoot: d.RepoRoot, + BdVersion: published.BdVersion, + Backend: published.Backend, + DoltMode: published.DoltMode, + Database: published.Database, + BeadsDir: published.BeadsDir, + RepoRoot: published.RepoRoot, + ProjectID: published.ProjectID, + CWDRepoRoot: d.CWDRepoRoot, IsRedirected: d.IsRedirected, IsWorktree: d.IsWorktree, - Backend: d.Backend, - DoltMode: d.DoltMode, ServerHost: d.ServerHost, ServerPort: d.ServerPort, ProxiedDir: d.ProxiedDir, - Database: d.Database, DataDir: d.DataDir, - ProjectID: d.ProjectID, + Role: d.Role, SyncRemote: d.SyncRemote, SyncGitRemote: d.SyncRemote, - Role: d.Role, - BdVersion: d.BdVersion, } } diff --git a/internal/httpapi/handlers.go b/internal/httpapi/handlers.go index 5aef7c327..0423a4032 100644 --- a/internal/httpapi/handlers.go +++ b/internal/httpapi/handlers.go @@ -63,43 +63,44 @@ func (s *Server) requireNoQuery(w http.ResponseWriter, r *http.Request) bool { // contextResponse projects the workspace snapshot onto the wire. // -// This is an ALLOWLIST, written out field by field, and that is the whole -// point: the source struct is the server's own configuration, which is exactly -// the kind of struct that grows a member nobody meant to publish. Marshaling -// it directly — or copying it field-for-field "to keep them in sync" — would -// turn every future addition into a silent disclosure. +// The snapshot's own fields come from domain.PublishedContext, which is the +// projection `bd context` publishes too — so the identity this server hands an +// automation client and the identity the CLI prints beside it are the same +// seven values read the same way, not two field-by-field copies kept in sync +// by hand. // -// Three exclusions are load-bearing: +// That projection is also where the EXCLUSIONS live, and living there is what +// makes them structural rather than remembered. domain.PublishedContextFields +// has no SyncRemote member at all — it is populated unconditionally from the +// workspace's sync.remote config and remote URLs routinely embed credentials +// — so this handler cannot publish one by forgetting to leave it out. Nor can +// it publish the database bind endpoint (advertising it invites clients to +// bypass this API and dial a server whose trust model is "root with an empty +// password on loopback") or the absolute host paths. BeadsDir and RepoRoot ARE +// published, deliberately: they are the single-workspace server's only +// workspace-identity handshake, and the document says so. // -// SyncRemote, above all. It is populated unconditionally from the workspace's -// sync.remote config, and remote URLs routinely embed credentials -// (https://x-access-token:TOKEN@host/...). It is excluded in this and every -// future version. -// -// ServerHost/ServerPort, the database bind endpoint: advertising it invites -// clients to bypass this API and dial the database directly, on a server whose -// trust model is "root with an empty password on loopback". -// -// DataDir, ProxiedDir and CWDRepoRoot, absolute host paths that identify -// nothing a client needs. BeadsDir and RepoRoot ARE published, deliberately: -// they are the single-workspace server's only workspace-identity handshake, and -// the document says so. +// The three members that are NOT the workspace's are named here, because they +// are this surface's own: the API version, the schema version, and the +// capability set derived from the implemented handlers. func contextResponse(info domain.ContextInfo, schemaVersion int, capabilities []string) apigen.ContextResponse { if capabilities == nil { // The document types this as an array; a client must never have to // tell null from empty to learn that nothing is implemented. capabilities = []string{} } + published := domain.PublishedContext(info) return apigen.ContextResponse{ ApiVersion: APIVersion, - BdVersion: info.BdVersion, SchemaVersion: schemaVersion, - Backend: info.Backend, - DoltMode: info.DoltMode, - Database: info.Database, - BeadsDir: info.BeadsDir, - RepoRoot: info.RepoRoot, - ProjectId: info.ProjectID, Capabilities: capabilities, + + BdVersion: published.BdVersion, + Backend: published.Backend, + DoltMode: published.DoltMode, + Database: published.Database, + BeadsDir: published.BeadsDir, + RepoRoot: published.RepoRoot, + ProjectId: published.ProjectID, } } diff --git a/internal/storage/domain/context.go b/internal/storage/domain/context.go index fd3c00418..d139e6280 100644 --- a/internal/storage/domain/context.go +++ b/internal/storage/domain/context.go @@ -52,6 +52,54 @@ type ContextInfo struct { BdVersion string } +// PublishedContextFields is the workspace identity every context surface +// answers with, projected off the snapshot exactly once. `bd context` prints +// it, `bd context --json` marshals it, and GET /v0/beads/context serves it — +// and because the projection below is the only way any of them gets these +// values, the three cannot drift into naming the same workspace differently. +// +// WHAT IS ABSENT IS THE POINT, and its absence is structural rather than +// remembered. +// +// SyncRemote above all. It is populated unconditionally from the workspace's +// sync.remote config and remote URLs routinely embed credentials +// (https://x-access-token:TOKEN@host/...), so it has no member here: a surface +// that reaches identity through this type cannot publish it by forgetting to +// exclude it, and adding one is an edit to this file with the review that +// implies. +// +// The database bind endpoint (ServerHost, ServerPort) and the absolute host +// paths (CWDRepoRoot, ProxiedDir, DataDir) are absent for the same reason: +// advertising the endpoint invites a client to bypass the API and dial a +// server whose trust model is "root with an empty password on loopback", and +// the paths identify nothing a consumer needs. A surface that is entitled to +// them — the local CLI, printing a diagnostic to the operator's own terminal +// — reads them off the snapshot itself, beside this projection and visibly +// so. +type PublishedContextFields struct { + BdVersion string + Backend string + DoltMode string + Database string + BeadsDir string + RepoRoot string + ProjectID string +} + +// PublishedContext projects a workspace snapshot onto the fields every context +// surface publishes. +func PublishedContext(info ContextInfo) PublishedContextFields { + return PublishedContextFields{ + BdVersion: info.BdVersion, + Backend: info.Backend, + DoltMode: info.DoltMode, + Database: info.Database, + BeadsDir: info.BeadsDir, + RepoRoot: info.RepoRoot, + ProjectID: info.ProjectID, + } +} + type ContextUseCase interface { GetContextInfo(ctx context.Context) (ContextInfo, error) } diff --git a/internal/storage/domain/context_published_test.go b/internal/storage/domain/context_published_test.go new file mode 100644 index 000000000..a594c7479 --- /dev/null +++ b/internal/storage/domain/context_published_test.go @@ -0,0 +1,113 @@ +package domain + +import ( + "reflect" + "strings" + "testing" +) + +// The sync remote is written the way every token-authenticated git remote is +// written: the credential lives in the URL's userinfo. +const ( + publishedFakeToken = "ghs_NOTAREALTOKENabcdefghijklmnop" + publishedFakeRemote = "https://x-access-token:" + publishedFakeToken + "@github.com/example/private.git" +) + +// populatedSnapshot fills EVERY member with its own sentinel, so a leak shows +// up as the name of the field that leaked rather than as a failed count. +func populatedSnapshot() ContextInfo { + return ContextInfo{ + BeadsDir: "/host/workspace/.beads", + RepoRoot: "/host/workspace", + CWDRepoRoot: "/host/elsewhere", + IsRedirected: true, + IsWorktree: true, + Backend: "dolt", + DoltMode: "proxied-server", + ServerHost: "10.4.2.9", + ServerPort: 3307, + ProxiedDir: "/host/workspace/.beads/dolt", + Database: "beads", + DataDir: "/host/workspace/.beads/embeddeddolt", + ProjectID: "proj-1", + SyncRemote: publishedFakeRemote, + Role: "maintainer", + BdVersion: "9.9.9", + } +} + +// TestPublishedContextCarriesNothingExcluded is the enforcement half of the +// context exclusions, and it sits HERE — one level below both surfaces — +// because that is what makes them structural. The HTTP allowlist test pins +// what the handler writes; this pins that the values it is written from never +// contained the excluded members in the first place, so neither surface can +// republish one by adding a field to its own response struct. +func TestPublishedContextCarriesNothingExcluded(t *testing.T) { + snapshot := populatedSnapshot() + published := PublishedContext(snapshot) + + excluded := map[string]string{ + "SyncRemote": snapshot.SyncRemote, + "CWDRepoRoot": snapshot.CWDRepoRoot, + "ServerHost": snapshot.ServerHost, + "ProxiedDir": snapshot.ProxiedDir, + "DataDir": snapshot.DataDir, + "Role": snapshot.Role, + } + + v := reflect.ValueOf(published) + for i := range v.NumField() { + field := v.Type().Field(i) + got, ok := v.Field(i).Interface().(string) + if !ok { + continue + } + for name, sentinel := range excluded { + if sentinel != "" && strings.Contains(got, sentinel) { + t.Errorf("published field %s carries the excluded %s: %q", field.Name, name, got) + } + } + } + + // Named separately from the value sweep above: a credential could also + // arrive embedded in some other field, and the sweep alone would not see a + // member that grew the wrong name. + if _, found := reflect.TypeOf(published).FieldByName("SyncRemote"); found { + t.Error("PublishedContextFields grew a SyncRemote member; remote URLs routinely embed credentials " + + "and this type is the reason no surface has to remember that") + } + if _, found := reflect.TypeOf(published).FieldByName("ServerPort"); found { + t.Error("PublishedContextFields grew a ServerPort member; the database bind endpoint is excluded " + + "so that no consumer is invited to dial the database directly") + } +} + +// TestPublishedContextCarriesTheIdentity is the other direction: every member +// it does have has to be the snapshot's own value, because two surfaces read +// their workspace identity from exactly this and a transposed pair would name +// the same workspace two different ways on each of them. +func TestPublishedContextCarriesTheIdentity(t *testing.T) { + snapshot := populatedSnapshot() + published := PublishedContext(snapshot) + + for _, tc := range []struct{ name, got, want string }{ + {"BdVersion", published.BdVersion, snapshot.BdVersion}, + {"Backend", published.Backend, snapshot.Backend}, + {"DoltMode", published.DoltMode, snapshot.DoltMode}, + {"Database", published.Database, snapshot.Database}, + {"BeadsDir", published.BeadsDir, snapshot.BeadsDir}, + {"RepoRoot", published.RepoRoot, snapshot.RepoRoot}, + {"ProjectID", published.ProjectID, snapshot.ProjectID}, + } { + if tc.got != tc.want { + t.Errorf("%s = %q, want %q", tc.name, tc.got, tc.want) + } + } + + // The count is part of the claim: a new member is a new disclosure on + // every surface that consumes this at once, which is a review, not a + // refactor. + if n := reflect.TypeOf(published).NumField(); n != 7 { + t.Errorf("PublishedContextFields has %d members, want 7 — adding one publishes it on every context surface", n) + } +}