The first slice that runs a server. Proxied-server workspaces go live; the read and claim operations are registered as transitional 501 stubs so route and spec parity can be proved all at once instead of growing a hole per slice. `bd serve --addr 127.0.0.1:0 [--allow-non-loopback]`, and no other flags in v0. The bound address is stdout's first line, because under the ephemeral default it is the only way to find the port. Shutdown rides the signal context the root command already installs. No lock file, pid file or discovery file: serve is operator-invoked and the TCP bind IS the mutual exclusion — dbproxy needs that machinery only because clients race to auto-spawn it. The mode gate says two different things, deliberately. Embedded is a PERMANENT typed storage.ErrUnsupported: there is no unit-of-work provider for that backend. Dolt server mode is STAGED — the provider construction exists and is tested, it just is not wired in yet — so the text names what works today and says this does not, rather than reading as an architectural limit that would send an operator off to change their topology for nothing. One unit of work per request, closed through a DETACHED context. The transaction layer poisons the pinned connection when a ROLLBACK send fails (doltserver_tx.go), so closing with the request's own canceled context would burn a session on every client disconnect. Front-tier hardening lands here, not later, because without it a hung Dolt becomes a silently growing black hole: slots fill with immortal queries, /healthz stays green because it never touches the database, and recovery produces a thundering herd. So: a Host-header allowlist (DNS-rebinding defense for an unauthenticated, browser-reachable loopback service), a netutil.LimitListener connection cap (Go spawns a goroutine per connection, so the database semaphore alone does not bound what is accepted), a database semaphore with a BOUNDED 10s wait mapping to the already-documented 503 busy, a 60s per-request deadline, and explicit pool limits on the provider's *sql.DB via a new uow.PoolTuner knob — openDB set none, and database/sql's default is unlimited. /v0/beads/context serializes an explicit ten-field allowlist and nothing else. SyncRemote is hard-excluded in this and every future version: it is populated unconditionally from config sync.remote, and remote URLs routinely embed credentials. The database bind endpoint and the remaining absolute host paths are excluded too. `capabilities` is derived from IMPLEMENTED handlers only, so a release cut between this slice and the endpoint slices advertises only what actually works. The observability floor is an acceptance criterion, not a convention: one structured stderr line per request (method, path, status, problem code, duration, semaphore wait, unit-of-work acquire), startup and shutdown lines, a semaphore-saturation event, and a request_id on every problem response. That last one required documenting request_id on the spec's Problem schema — the only spec edit here, additive, with types regenerated. Decisions implemented as given: hooks do not fire (a user-controlled subprocess per mutation is an unbounded latency multiplier and an orphaned child at shutdown); the per-command auto-commit globals are never touched (nothing to exclude — proxied PersistentPostRunE only closes the provider); and actor on an HTTP request stays caller-asserted provenance, which the context and capabilities wording does not contradict. Tests: TestSpecRouteParity asserts set equality between the route table and the document's paths, and builds the real mux so a pattern ServeMux would refuse fails here rather than on the first request. TestSpecStatusCodesMatchHandlerTable carries a commented, enumerated 501 exemption that is self-deleting — it fails if the route table and the list disagree, and fails again if the list outlives the last stub. The context allowlist is enforced from the handler out, over a body built from a snapshot with every field populated and a credential-bearing sync remote. TestWithUOWClosesWithADetachedContext records the close context's state AT close time, which is the only moment it says anything. Verified: build, vet and golangci-lint clean (the two gosec findings in cmd/bd/main.go pre-date this change); internal/httpapi green under -race; protocol corpus byte-identical with BEADS_PROTOCOL_REQUIRE_DOLT=1; and a real server started against a proxied workspace, answered both endpoints, refused a foreign Host, an unknown query key and a second bind, and drained to exit 0 on SIGTERM. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
119 lines
4.1 KiB
Go
119 lines
4.1 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
)
|
|
|
|
// fakeCredential is a realistic sync remote: a token in the userinfo of an
|
|
// HTTPS URL, which is how every token-authenticated git remote is written.
|
|
const (
|
|
fakeToken = "ghs_NOTAREALTOKENabcdefghijklmnop"
|
|
fakeSyncRemote = "https://x-access-token:" + fakeToken + "@github.com/example/private.git"
|
|
fakeDoltAddress = "10.4.2.9"
|
|
)
|
|
|
|
// populatedContextInfo fills EVERY field of the snapshot with a distinct
|
|
// sentinel. A field that leaks shows up as its own sentinel in the body, so the
|
|
// assertions below name the leak instead of just failing a count.
|
|
func populatedContextInfo() domain.ContextInfo {
|
|
return domain.ContextInfo{
|
|
BeadsDir: "/host/workspace/.beads",
|
|
RepoRoot: "/host/workspace",
|
|
CWDRepoRoot: "/host/elsewhere",
|
|
IsRedirected: true,
|
|
IsWorktree: true,
|
|
Backend: "dolt",
|
|
DoltMode: "proxied-server",
|
|
ServerHost: fakeDoltAddress,
|
|
ServerPort: 3307,
|
|
ProxiedDir: "/host/workspace/.beads/dolt",
|
|
Database: "beads",
|
|
DataDir: "/host/workspace/.beads/embeddeddolt",
|
|
ProjectID: "proj-1",
|
|
SyncRemote: fakeSyncRemote,
|
|
Role: "maintainer",
|
|
BdVersion: "9.9.9",
|
|
}
|
|
}
|
|
|
|
// TestContextHandlerServesOnlyTheAllowlist is the enforcement half of the
|
|
// context field allowlist: TestContextResponseAllowlist pins what the document
|
|
// and the generated struct agree to, this pins what the handler actually
|
|
// writes.
|
|
//
|
|
// It matters because the source of this response is the server's own
|
|
// configuration — exactly the kind of struct that grows a member nobody meant
|
|
// to publish. A future field on domain.ContextInfo, or a refactor that
|
|
// "simplifies" the projection into marshalling the struct, fails here.
|
|
func TestContextHandlerServesOnlyTheAllowlist(t *testing.T) {
|
|
ts := newTestServer(t, Config{
|
|
Workspace: populatedContextInfo(),
|
|
SchemaVersion: 1,
|
|
})
|
|
|
|
resp := ts.get(t, "/v0/beads/context")
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200", resp.StatusCode)
|
|
}
|
|
|
|
raw, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
t.Fatalf("read body: %v", err)
|
|
}
|
|
var body map[string]any
|
|
if err := json.Unmarshal(raw, &body); err != nil {
|
|
t.Fatalf("decode %q: %v", raw, err)
|
|
}
|
|
|
|
want := map[string]bool{}
|
|
for _, name := range contextResponseAllowlist {
|
|
want[name] = true
|
|
}
|
|
got := map[string]bool{}
|
|
for name := range body {
|
|
got[name] = true
|
|
}
|
|
if extra := diff(got, want); len(extra) > 0 {
|
|
t.Errorf("response carries fields outside the allowlist: %v\n"+
|
|
"every member of this body is a permanent, deliberate disclosure", extra)
|
|
}
|
|
if missing := diff(want, got); len(missing) > 0 {
|
|
t.Errorf("allowlisted fields absent from the response: %v", missing)
|
|
}
|
|
|
|
// The credential check is separate from the key check on purpose: a sync
|
|
// remote could also arrive embedded in some other field's value, and the
|
|
// key set alone would not notice.
|
|
if strings.Contains(string(raw), fakeToken) {
|
|
t.Errorf("the sync remote's credential appears in the response body:\n%s", raw)
|
|
}
|
|
if strings.Contains(string(raw), fakeSyncRemote) {
|
|
t.Errorf("the sync remote URL appears in the response body:\n%s", raw)
|
|
}
|
|
// Advertising the database endpoint invites clients to bypass this API and
|
|
// dial a server whose trust model is "root, empty password, loopback".
|
|
if strings.Contains(string(raw), fakeDoltAddress) || strings.Contains(string(raw), "3307") {
|
|
t.Errorf("the database bind endpoint appears in the response body:\n%s", raw)
|
|
}
|
|
|
|
if body["api_version"] != APIVersion {
|
|
t.Errorf("api_version = %v, want %q", body["api_version"], APIVersion)
|
|
}
|
|
if body["bd_version"] != "9.9.9" {
|
|
t.Errorf("bd_version = %v", body["bd_version"])
|
|
}
|
|
if body["beads_dir"] != "/host/workspace/.beads" {
|
|
t.Errorf("beads_dir = %v", body["beads_dir"])
|
|
}
|
|
// The document types capabilities as an array; a client must never have to
|
|
// tell null from empty to learn that nothing is implemented yet.
|
|
if _, ok := body["capabilities"].([]any); !ok {
|
|
t.Errorf("capabilities = %#v, want a JSON array", body["capabilities"])
|
|
}
|
|
}
|