fix(httpclient): repair CI-red tests and apply review fixes (adopt-pr #7210)

Three defects on the contributor head, none of them present on the base:

- test/docsync's TestEngdocsAndRootMarkdownLinks fails: the generated
  divergence-ledger doc links http-client-backend.md, an architecture
  spec this repository does not carry. Name it in a code span instead,
  in ledgerDocPreamble, and regenerate the doc (-update-ledger-doc).

- TestCAFileHygieneRefusesGroupWritableFile fails under umask 022:
  os.WriteFile's 0o660 passes through the umask, so the file lands 0640,
  is never group-writable, and TransportForFile accepts it. Chmod it
  explicitly. Its acceptance twin had the same gap on its file (only the
  explicitly chmodded directory reached the user-private-group
  exception), so chmod that file too: a mutant that drops the exception
  for files alone passed the old test under umask 022 and fails the new
  one.

- That acceptance twin calls the unix-only isUserPrivateGroup from
  ca_test.go, which carries no build constraint, so the package's tests
  do not compile for GOOS=windows. Move it, otherwise verbatim, into
  ca_permissions_unix_test.go beside the other isUserPrivateGroup tests.

Review fixes (iteration 1):

- Encode dispatched through nine case arms of op/shape conjunctions
  (cyclomatic 24). Switch on an (op, shape) struct key instead, and move
  the getIssue and search-bridge arms into encodeGetIssue and
  encodeSearch. The arms are disjoint, so dispatch and every error string
  are unchanged. Cyclomatic 24 -> 10.

- EventStream.Next kept four accumulators and the per-field switch in
  one loop (cognitive 27). Gather the accumulators into sseEvent and
  fold each field line, per-event cap included, in applyField. Next
  cognitive 27 -> 12; applyField is 11/11.

- The CA hygiene walk joined a relative symlink target onto the textual
  containing directory, so with a/link -> ../b/c and b/c/x -> ../y it
  resolved a/y where the kernel opens b/y: a valid CA was refused, or a
  hygienic file at a/y was checked and read instead. readLinkTarget joins
  onto the directory's EvalSymlinks path, taken after that directory's
  own ancestors passed the hop-by-hop check. The regression test plants
  a decoy at a/y; a lexical-join mutant reads it and fails.

- SaveTarget wrote a relative CAFile that every later LoadTarget
  refuses. Both now go through checkCAFileAbsolute, so SaveTarget refuses
  first, with LoadTarget's own message, and writes nothing.

- Document the cached transport TransportFor and TransportForFile return
  as shared and read-only.

Review fixes (iteration 2):

- The walk still dropped a ".." inside a symlink target textually:
  filepath.Join cleans a relative target, and an absolute target's
  ancestors come from filepath.Dir, while the kernel takes that ".."
  from wherever the component before it really leads. Both reviews
  rated the relative leaf as a wrong-file read, and it is one: with
  x/d -> ../e/s, x/L -> d/../y read a decoy at x/y where the kernel
  opens e/y. The other three shapes are hygiene bypasses: an absolute
  leaf target x/d/../y, and an ancestor link to d/../dir or x/d/../dir
  with the CA at x/L/y, each read a file in a world-writable e that the
  walk never checked. readLinkTarget now refuses a target with a ".."
  after any other component, relative or absolute; a leading run of
  ".." is still taken from the directory's physical path. The test pins
  all four shapes behind a control that refuses e/y named directly, and
  a table pins hasInteriorDotDot's boundary. Mutants that drop the
  refusal, limit it to relative targets, refuse every "..", or count
  "." as a component each fail.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Eddie the Engineer 2026-10-05 01:12:49 +00:00 • committed by Eddie the Engineer
commit 12b29cb1b3
10 changed files with 388 additions and 112 deletions

View file

@ -23,8 +23,8 @@ the encoder's reflection **bijection gate** pins the ledger to the wire (a
request field added upstream lands here or fails CI), and the golden test
`TestDivergenceLedgerDocMatchesLedger` pins this doc to the ledger. The prose
rationale, the decision numbers (D-rows) each entry cites, and the full test-lane
map live in the architecture spec,
[http-client-backend.md](http-client-backend.md).
map live in the architecture spec, `http-client-backend.md`, which is not
included in this repository.
A handful of rows still carry a `TODO` pin: these are the read-display and
pre-run residuals (wisp-in-list, the pretty `bd ready` parent-epic map, the

View file

@ -366,6 +366,12 @@ func resolveCAFile(target Target) (resolvedCA, error) {
// to it — with no window where some processes trust only the old certificate
// and others only the new one.
//
// Because it is cached, the returned transport is SHARED: every caller in
// this process asking for the same file holds the same *http.Transport. Treat
// it as read-only — wrap it rather than type-asserting and reconfiguring it —
// since setting its TLSClientConfig, Proxy or DialContext would silently
// change trust for every other holder.
//
// # HTTPS proxies
//
// When a CA is configured, the returned transport refuses to reach a target
@ -402,7 +408,8 @@ func TransportFor(target Target) (http.RoundTripper, error) {
// silently renarrowed by a variable it may not even know exists.
//
// Like TransportFor, this participates in the (absolute path, content hash)
// transport cache and refuses loudly (missing file, hygiene, malformed PEM)
// transport cache — so what it returns is the same shared, read-only
// transport — and refuses loudly (missing file, hygiene, malformed PEM)
// rather than falling back to system roots.
func TransportForFile(path string) (http.RoundTripper, error) {
return transportForFile(path, "ca_file")

View file

@ -235,12 +235,9 @@ func checkCAFilePermissionsHop(path string, hops int) (string, os.FileInfo, erro
if err := checkAncestors(dir); err != nil {
return "", nil, err
}
target, err := os.Readlink(path)
target, err := readLinkTarget(path, dir)
if err != nil {
return "", nil, fmt.Errorf("readlink %s: %w", path, err)
}
if !filepath.IsAbs(target) {
target = filepath.Join(dir, target)
return "", nil, err
}
return checkCAFilePermissionsHop(target, hops+1)
}
@ -284,12 +281,9 @@ func checkAncestorsHop(dir string, hops int) error {
if err := checkAncestorsHop(parentOfLink, hops+1); err != nil {
return err
}
target, err := os.Readlink(dir)
target, err := readLinkTarget(dir, parentOfLink)
if err != nil {
return fmt.Errorf("readlink %s: %w", dir, err)
}
if !filepath.IsAbs(target) {
target = filepath.Join(parentOfLink, target)
return err
}
return checkAncestorsHop(target, hops+1)
}
@ -304,6 +298,65 @@ func checkAncestorsHop(dir string, hops int) error {
return checkAncestorsHop(parent, hops+1)
}
// readLinkTarget reads the symlink at link, whose containing directory dir
// has already passed checkAncestors, and returns the path it points to. A
// relative target is joined onto dir's PHYSICAL path, not its text: the
// kernel resolves the target from the directory the link really lives in, so
// when dir itself runs through a symlinked directory, a lexical
// filepath.Join(dir, target) collapses any ".." in the target against the
// wrong parent (a/link -> b/c with b/c/x -> ../y names b/y, never a/y).
// Resolving dir in one EvalSymlinks call is safe here because every symlink
// along it was already checked hop by hop on the way in.
//
// A target with a ".." after any other component is refused outright,
// relative or absolute. The kernel takes that ".." from wherever the
// component before it really leads, through that component's own symlinks,
// while filepath.Join and the walk's own filepath.Dir drop the pair
// textually, so the directories the kernel actually passes through are never
// checked: with x/d -> ../e/s, x/L -> d/../y names e/y, not x/y, and an
// absolute x/L -> /r/x/d/../y is even opened at /r/e/y while only /r/x and
// its ancestors are checked, never /r/e. A leading run of ".." is kept: it is
// taken from dir's physical path, which has no symlinks left to take it
// through.
func readLinkTarget(link, dir string) (string, error) {
target, err := os.Readlink(link)
if err != nil {
return "", fmt.Errorf("readlink %s: %w", link, err)
}
if hasInteriorDotDot(target) {
return "", fmt.Errorf(
`symlink %s points at %q, whose ".." follows another component; the kernel resolves that ".." through the earlier component's own symlinks, which this check would skip, so rewrite the link without the inner ".."`,
link, target)
}
if filepath.IsAbs(target) {
return target, nil
}
physical, err := filepath.EvalSymlinks(dir)
if err != nil {
return "", fmt.Errorf("resolve %s: %w", dir, err)
}
return filepath.Join(physical, target), nil
}
// hasInteriorDotDot reports whether target has a ".." component after some
// other component, setting aside "." and the empty components a leading or
// doubled "/" leaves: the shape readLinkTarget refuses.
func hasInteriorDotDot(target string) bool {
named := false
for _, elem := range strings.Split(target, "/") {
switch elem {
case "", ".":
case "..":
if named {
return true
}
default:
named = true
}
}
return false
}
// checkOwnerAndMode applies the ownership and writability rules to one path
// (the leaf file, or one ancestor directory) already stat'd into fi.
//

View file

@ -76,6 +76,137 @@ func TestCheckCAFilePermissionsRefusesSymlinkItselfInWorldWritableDir(t *testing
}
}
// TestCheckCAFilePermissionsResolvesRelativeLinkAgainstPhysicalDir pins the
// walk to the kernel's reading of a relative symlink target: with a/link ->
// ../b/c and b/c/x -> ../y, the path a/link/x names b/y, because ".." is taken
// from the directory x really lives in. A lexical join collapses it against
// a/link instead and lands on a/y; the hygienic decoy planted there makes that
// mistake a wrong-file read rather than just a refusal.
func TestCheckCAFilePermissionsResolvesRelativeLinkAgainstPhysicalDir(t *testing.T) {
root := secureTempDir(t)
for _, d := range []string{"a", "b", filepath.Join("b", "c")} {
if err := os.Mkdir(filepath.Join(root, d), 0o700); err != nil {
t.Fatalf("mkdir %s: %v", d, err)
}
}
realPath := filepath.Join(root, "b", "y")
if err := os.WriteFile(realPath, []byte("real"), 0o600); err != nil {
t.Fatalf("write real file: %v", err)
}
if err := os.WriteFile(filepath.Join(root, "a", "y"), []byte("decoy"), 0o600); err != nil {
t.Fatalf("write decoy file: %v", err)
}
if err := os.Symlink(filepath.Join("..", "b", "c"), filepath.Join(root, "a", "link")); err != nil {
t.Fatalf("symlink a/link: %v", err)
}
if err := os.Symlink(filepath.Join("..", "y"), filepath.Join(root, "b", "c", "x")); err != nil {
t.Fatalf("symlink b/c/x: %v", err)
}
path := filepath.Join(root, "a", "link", "x")
got, _, err := checkCAFilePermissions(path)
if err != nil {
t.Fatalf("checkCAFilePermissions(%s): %v", path, err)
}
want, err := filepath.EvalSymlinks(realPath)
if err != nil {
t.Fatalf("EvalSymlinks(%s): %v", realPath, err)
}
if got != want {
t.Errorf("checkCAFilePermissions resolved %s to %s, want %s", path, got, want)
}
data, err := readCAFile(path, "ca_file")
if err != nil {
t.Fatalf("readCAFile(%s): %v", path, err)
}
if string(data) != "real" {
t.Errorf("readCAFile(%s) read %q, want the file the kernel names (%q)", path, data, "real")
}
}
// TestReadCAFileRefusesLinkTargetWithInteriorDotDot pins readLinkTarget's
// refusal of a target whose ".." follows another component. With x/d ->
// ../evil/sub, the kernel resolves d/.. to evil, a world-writable directory
// the walk refuses when it is named directly, but a textual collapse never
// looks at d: the relative leaf link then reads the hygienic decoy at x/y, and
// the other three shapes read the file inside evil without evil ever being
// checked. The targets are spelled as strings because filepath.Join would
// clean the ".." away.
func TestReadCAFileRefusesLinkTargetWithInteriorDotDot(t *testing.T) {
root := secureTempDir(t)
evil := filepath.Join(root, "evil")
x := filepath.Join(root, "x")
for _, d := range []string{evil, filepath.Join(evil, "sub"), filepath.Join(evil, "dir"), x, filepath.Join(x, "dir")} {
if err := os.Mkdir(d, 0o700); err != nil {
t.Fatalf("mkdir %s: %v", d, err)
}
}
if err := os.Chmod(evil, 0o777); err != nil {
t.Fatalf("chmod evil 0777: %v", err)
}
for path, content := range map[string]string{
filepath.Join(evil, "y"): "evil",
filepath.Join(evil, "dir", "y"): "evil",
filepath.Join(x, "y"): "decoy",
filepath.Join(x, "dir", "y"): "decoy",
} {
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatalf("write %s: %v", path, err)
}
}
if err := os.Symlink(filepath.Join("..", "evil", "sub"), filepath.Join(x, "d")); err != nil {
t.Fatalf("symlink x/d: %v", err)
}
if _, err := readCAFile(filepath.Join(evil, "y"), "ca_file"); err == nil {
t.Fatal("readCAFile accepted a file in a world-writable directory named directly, so the cases below prove nothing")
}
for _, tc := range []struct{ name, link, target, path string }{
{"relative leaf", "L1", "d/../y", "L1"},
{"absolute leaf", "L2", x + "/d/../y", "L2"},
{"relative ancestor", "L3", "d/../dir", "L3/y"},
{"absolute ancestor", "L4", x + "/d/../dir", "L4/y"},
} {
t.Run(tc.name, func(t *testing.T) {
if err := os.Symlink(tc.target, filepath.Join(x, tc.link)); err != nil {
t.Fatalf("symlink %s: %v", tc.link, err)
}
path := filepath.Join(x, tc.path)
data, err := readCAFile(path, "ca_file")
if err == nil {
t.Fatalf("readCAFile(%s) through %q read %q, want a refusal", path, tc.target, data)
}
if !strings.Contains(err.Error(), `whose ".." follows another component`) {
t.Errorf("readCAFile(%s) through %q: %v, want the interior \"..\" refusal", path, tc.target, err)
}
})
}
}
// TestHasInteriorDotDot pins the boundary of that refusal: a ".." after
// another component is refused, but a leading run of them is not, since
// readLinkTarget takes it from a physical directory.
func TestHasInteriorDotDot(t *testing.T) {
for target, want := range map[string]bool{
"y": false,
"../y": false,
"../../b/c": false,
"./../y": false,
"/r/b/y": false,
"/../y": false,
"d/../y": true,
"d/./../y": true,
"d/..": true,
"../d/../y": true,
"/r/d/../y": true,
"//r/d/../y": true,
} {
if got := hasInteriorDotDot(target); got != want {
t.Errorf("hasInteriorDotDot(%q) = %v, want %v", target, got, want)
}
}
}
// TestCheckCAFilePermissionsRefusesWorldWritableGrandparent is finding 3: a
// world-writable GRANDparent (not just the immediate parent) must be
// refused — an attacker who can write the grandparent can rename the parent
@ -390,3 +521,34 @@ func TestIsUserPrivateGroupFalseForUnknownIDs(t *testing.T) {
t.Error("isUserPrivateGroup reported true for ids that cannot possibly resolve to a real account")
}
}
// TestCAFileHygieneAcceptsGroupWritableFileUnderUserPrivateGroup is finding
// 4's availability half: a umask-002 layout (Ubuntu's default
// user-private-groups scheme) produces 0775 directories and 0664 files owned
// by the running user's own primary group, which is no more shared than a
// umask-022 layout — group-write only reaches a group whose sole member, by
// convention, is the file's own owner. This must be ACCEPTED, not refused.
func TestCAFileHygieneAcceptsGroupWritableFileUnderUserPrivateGroup(t *testing.T) {
if !isUserPrivateGroup(uint32(os.Getuid()), uint32(os.Getgid())) { //nolint:gosec // uid/gid are always non-negative
t.Skip("this host's running user does not use the Debian/OpenSSH user-private-group convention")
}
clearCAEnvironment(t)
ca := newTestCA(t)
dir := t.TempDir()
if err := os.Chmod(dir, 0o775); err != nil {
t.Fatalf("chmod dir 0775: %v", err)
}
path := filepath.Join(dir, "ca.pem")
if err := os.WriteFile(path, ca.pem, 0o664); err != nil {
t.Fatalf("write ca file: %v", err)
}
// WriteFile's mode passes through the umask (see the refusal case in
// ca_test.go): under umask 022 the file would land 0644, leaving only the
// directory to exercise the user-private-group exception.
if err := os.Chmod(path, 0o664); err != nil {
t.Fatalf("chmod ca file 0664: %v", err)
}
if _, err := TransportForFile(path); err != nil {
t.Fatalf("TransportForFile refused a umask-002 (0775/0664) layout under the owner's own user-private group: %v", err)
}
}

View file

@ -1192,6 +1192,12 @@ func TestCAFileHygieneRefusesGroupWritableFile(t *testing.T) {
if err := os.WriteFile(path, ca.pem, 0o660); err != nil {
t.Fatalf("write group-writable ca file: %v", err)
}
// WriteFile's mode passes through the process umask: under umask 022 the
// file lands 0640, not group-writable at all, and the refusal under test
// is never reached. Set the mode explicitly.
if err := os.Chmod(path, 0o660); err != nil {
t.Fatalf("chmod ca file 0660: %v", err)
}
chownToNonPrivateGroup(t, path)
_, err := TransportForFile(path)
if err == nil {
@ -1202,31 +1208,6 @@ func TestCAFileHygieneRefusesGroupWritableFile(t *testing.T) {
}
}
// TestCAFileHygieneAcceptsGroupWritableFileUnderUserPrivateGroup is finding
// 4's availability half: a umask-002 layout (Ubuntu's default
// user-private-groups scheme) produces 0775 directories and 0664 files owned
// by the running user's own primary group, which is no more shared than a
// umask-022 layout — group-write only reaches a group whose sole member, by
// convention, is the file's own owner. This must be ACCEPTED, not refused.
func TestCAFileHygieneAcceptsGroupWritableFileUnderUserPrivateGroup(t *testing.T) {
if !isUserPrivateGroup(uint32(os.Getuid()), uint32(os.Getgid())) { //nolint:gosec // uid/gid are always non-negative
t.Skip("this host's running user does not use the Debian/OpenSSH user-private-group convention")
}
clearCAEnvironment(t)
ca := newTestCA(t)
dir := t.TempDir()
if err := os.Chmod(dir, 0o775); err != nil {
t.Fatalf("chmod dir 0775: %v", err)
}
path := filepath.Join(dir, "ca.pem")
if err := os.WriteFile(path, ca.pem, 0o664); err != nil {
t.Fatalf("write ca file: %v", err)
}
if _, err := TransportForFile(path); err != nil {
t.Fatalf("TransportForFile refused a umask-002 (0775/0664) layout under the owner's own user-private group: %v", err)
}
}
// TestCAFileHygieneRefusesWorldWritableParentDir refuses a CA file whose
// parent directory anyone can write to — SSH's known_hosts / authorized_keys
// hygiene rule — since replacing the file entirely bypasses the file's own

View file

@ -94,51 +94,66 @@ type Encoded struct {
// It exists so the gates can drive every table uniformly. Ordinary callers know
// which request they hold and use the typed functions below.
func Encode(op Op, shape string, source any) (Encoded, error) {
switch {
case op == OpListReadyWork && shape == "":
switch (opShape{op, shape}) {
case opShape{OpListReadyWork, ""}:
return encodeAs(op, shape, source, ReadyParams)
case op == OpCountReadyWork && shape == "":
case opShape{OpCountReadyWork, ""}:
return encodeAs(op, shape, source, ReadyCountParams)
case op == OpListIssues && shape == "":
case opShape{OpListIssues, ""}:
return encodeAs(op, shape, source, ListParams)
case op == OpQueryIssues && shape == "":
case opShape{OpQueryIssues, ""}:
return encodeAs(op, shape, source, QueryParams)
case op == OpCountIssues && shape == "":
case opShape{OpCountIssues, ""}:
return encodeAs(op, shape, source, CountParams)
case op == OpCountIssues && shape == "byGroup":
case opShape{OpCountIssues, "byGroup"}:
return encodeAs(op, shape, source, CountByGroupParams)
case op == OpListReadyWork && shape == "workFilterBridge":
case opShape{OpListReadyWork, "workFilterBridge"}:
return encodeAs(op, shape, source, ReadyBridgeParams)
case op == OpGetIssue && shape == "":
req, err := sourceAs[issueops.GetRequest](op, shape, source)
if err != nil {
return Encoded{}, err
}
id, v := GetTarget(req)
return Encoded{Params: v, PathIDs: []string{id}}, nil
case op == OpGetIssue && shape == "searchExactIDs",
op == OpListIssues && shape == "searchParentWalk":
filter, err := sourceAs[types.IssueFilter](op, shape, source)
if err != nil {
return Encoded{}, err
}
// The zero vocabulary, which is what a gate driving the table has: it
// falls back to the built-in statuses and the default infra types, the
// same reading BuildListFilter gives an unconfigured workspace.
plan, err := PlanSearch(filter, ZeroVocabulary)
if err != nil {
return Encoded{}, err
}
if string(plan.Shape) != shape {
return Encoded{}, fmt.Errorf("encode: the filter is the %q shape, not %q", plan.Shape, shape)
}
return Encoded{Params: plan.Params, PathIDs: plan.IDs}, nil
case opShape{OpGetIssue, ""}:
return encodeGetIssue(op, shape, source)
case opShape{OpGetIssue, "searchExactIDs"}, opShape{OpListIssues, "searchParentWalk"}:
return encodeSearch(op, shape, source)
}
return Encoded{}, fmt.Errorf("encode: no encoder for operation %q shape %q", op, shape)
}
// opShape is the (operation, shape) pair Encode dispatches on.
type opShape struct {
op Op
shape string
}
// encodeGetIssue is Encode's arm for getIssue: GetTarget's id is the one path
// id the request dials.
func encodeGetIssue(op Op, shape string, source any) (Encoded, error) {
req, err := sourceAs[issueops.GetRequest](op, shape, source)
if err != nil {
return Encoded{}, err
}
id, v := GetTarget(req)
return Encoded{Params: v, PathIDs: []string{id}}, nil
}
// encodeSearch is Encode's arm for the two SearchIssues bridge shapes: it plans
// the filter and refuses one that plans to the other shape.
func encodeSearch(op Op, shape string, source any) (Encoded, error) {
filter, err := sourceAs[types.IssueFilter](op, shape, source)
if err != nil {
return Encoded{}, err
}
// The zero vocabulary, which is what a gate driving the table has: it
// falls back to the built-in statuses and the default infra types, the
// same reading BuildListFilter gives an unconfigured workspace.
plan, err := PlanSearch(filter, ZeroVocabulary)
if err != nil {
return Encoded{}, err
}
if string(plan.Shape) != shape {
return Encoded{}, fmt.Errorf("encode: the filter is the %q shape, not %q", plan.Shape, shape)
}
return Encoded{Params: plan.Params, PathIDs: plan.IDs}, nil
}
func encodeAs[T any](op Op, shape string, source any, encoder func(T) (url.Values, error)) (Encoded, error) {
req, err := sourceAs[T](op, shape, source)
if err != nil {

View file

@ -191,8 +191,8 @@ the encoder's reflection **bijection gate** pins the ledger to the wire (a
request field added upstream lands here or fails CI), and the golden test
` + "`TestDivergenceLedgerDocMatchesLedger`" + ` pins this doc to the ledger. The prose
rationale, the decision numbers (D-rows) each entry cites, and the full test-lane
map live in the architecture spec,
[http-client-backend.md](http-client-backend.md).
map live in the architecture spec, ` + "`http-client-backend.md`" + `, which is not
included in this repository.
A handful of rows still carry a ` + "`TODO`" + ` pin: these are the read-display and
pre-run residuals (wisp-in-list, the pretty ` + "`bd ready`" + ` parent-epic map, the

View file

@ -34,9 +34,9 @@ type Target struct {
// this target — not an addition to the system store — set by
// `bd connect --ca-file <path>`. "" leaves this target on the system
// roots. MUST BE ABSOLUTE: `bd connect` resolves the flag's path with
// filepath.Abs before writing it, and LoadTarget refuses a relative one
// rather than resolving it against whatever directory bd happens to run
// in. BEADS_HTTP_CA_FILE (see TransportFor / CAFileEnv), when its
// filepath.Abs before writing it, and SaveTarget and LoadTarget both
// refuse a relative one rather than resolving it against whatever
// directory bd happens to run in. BEADS_HTTP_CA_FILE (see TransportFor / CAFileEnv), when its
// host-scoped pattern matches this target, overrides this per the
// documented precedence — env beats sidecar, the same rung order the
// bearer ladder uses, but the two disagreeing is a refusal, not a silent
@ -101,18 +101,32 @@ func LoadTarget(beadsDir string) (Target, error) {
if u.Scheme != "http" && u.Scheme != "https" {
return Target{}, fmt.Errorf("url in %s has scheme %q; want http or https", TargetFileName, u.Scheme)
}
if f.CAFile != "" && !filepath.IsAbs(f.CAFile) {
return Target{}, fmt.Errorf(
"ca_file in %s is %q, a relative path; it must be absolute, because resolving it against the current directory would pick a different file depending on where bd was run — re-run `bd connect --ca-file` to record an absolute path",
TargetFileName, f.CAFile)
if err := checkCAFileAbsolute(f.CAFile); err != nil {
return Target{}, err
}
return Target{BaseURL: u, ExpectProjectID: f.ExpectProjectID, CAFile: f.CAFile}, nil
}
// checkCAFileAbsolute refuses a relative ca_file (see Target.CAFile). LoadTarget
// and SaveTarget share it, so a sidecar can never be written holding a value
// every later load would refuse.
func checkCAFileAbsolute(caFile string) error {
if caFile != "" && !filepath.IsAbs(caFile) {
return fmt.Errorf(
"ca_file in %s is %q, a relative path; it must be absolute, because resolving it against the current directory would pick a different file depending on where bd was run — re-run `bd connect --ca-file` to record an absolute path",
TargetFileName, caFile)
}
return nil
}
// SaveTarget writes the sidecar 0600, beside metadata.json. It exists so tests
// and the connect command share one encoder; the connect UX itself (gitignore
// coverage, identity verification, conversion consent) is not here.
// coverage, identity verification, conversion consent) is not here. It refuses
// a relative CAFile before writing anything, with LoadTarget's own message.
func SaveTarget(beadsDir string, t Target) error {
if err := checkCAFileAbsolute(t.CAFile); err != nil {
return err
}
f := targetFile{ExpectProjectID: t.ExpectProjectID, API: "v0", CAFile: t.CAFile}
if t.BaseURL != nil {
f.URL = t.BaseURL.String()

View file

@ -3,6 +3,7 @@
package httpclient
import (
"errors"
"os"
"path/filepath"
"strings"
@ -91,6 +92,32 @@ func TestLoadTargetRejectsRelativeCAFile(t *testing.T) {
}
}
// TestSaveTargetRejectsRelativeCAFile is LoadTarget's refusal on the write
// side: a relative ca_file must never reach the sidecar, where every later
// LoadTarget would refuse it and leave the workspace unopenable. The refusal is
// LoadTarget's own message, and it writes nothing, so the workspace stays
// unconnected rather than holding a sidecar it cannot load.
func TestSaveTargetRejectsRelativeCAFile(t *testing.T) {
dir := t.TempDir()
saveErr := SaveTarget(dir, Target{BaseURL: mustParseURL(t, "https://example.com"), CAFile: "relative/ca.pem"})
if saveErr == nil {
t.Fatal("SaveTarget accepted a relative ca_file")
}
if _, err := LoadTarget(dir); !errors.Is(err, ErrNotConnected) {
t.Errorf("LoadTarget after the refused save = %v, want ErrNotConnected: nothing may be written", err)
}
seeded := t.TempDir()
sidecar := `{"url":"https://example.com","ca_file":"relative/ca.pem"}`
if err := os.WriteFile(TargetPath(seeded), []byte(sidecar), 0o600); err != nil {
t.Fatalf("seed sidecar: %v", err)
}
_, loadErr := LoadTarget(seeded)
if loadErr == nil || saveErr.Error() != loadErr.Error() {
t.Errorf("SaveTarget refused with %q; want LoadTarget's own refusal %q", saveErr, loadErr)
}
}
// TestLoadTargetAcceptsAbsoluteCAFile is the control for the above: an
// absolute ca_file round-trips through LoadTarget unchanged.
func TestLoadTargetAcceptsAbsoluteCAFile(t *testing.T) {

View file

@ -263,12 +263,7 @@ func (s *EventStream) Close() {
// deadline, that the caller cancels, or that the connection drops surfaces as an
// error; a per-event size cap refuses a frame larger than the client's bound.
func (s *EventStream) Next() (StreamEvent, error) {
var (
data []byte
name string
seq int64
eventBytes int64
)
var ev sseEvent
for {
line, err := s.readLine()
if err != nil {
@ -280,11 +275,11 @@ func (s *EventStream) Next() (StreamEvent, error) {
// The blank line dispatches. A frame with no data carries only a retry
// advisory or an id and fires no message in SSE, so it is folded into
// the next event rather than returned.
if len(data) == 0 {
data, name, seq, eventBytes = nil, "", 0, 0
if len(ev.data) == 0 {
ev = sseEvent{}
continue
}
return StreamEvent{Seq: seq, Name: name, Data: data, Retry: s.retry}, nil
return StreamEvent{Seq: ev.seq, Name: ev.name, Data: ev.data, Retry: s.retry}, nil
}
if line[0] == ':' {
@ -294,33 +289,55 @@ func (s *EventStream) Next() (StreamEvent, error) {
}
field, value := splitSSEField(line)
eventBytes += int64(len(value))
if eventBytes > s.maxBytes {
return StreamEvent{}, s.tooLarge()
}
switch field {
case "event":
name = value
case "data":
if len(data) > 0 {
data = append(data, '\n')
}
data = append(data, value...)
if int64(len(data)) > s.maxBytes {
return StreamEvent{}, s.tooLarge()
}
case "id":
if n, perr := strconv.ParseInt(value, 10, 64); perr == nil {
seq = n
}
case "retry":
if ms, perr := strconv.ParseInt(value, 10, 64); perr == nil && ms >= 0 {
s.retry = time.Duration(ms) * time.Millisecond
}
if err := s.applyField(&ev, field, value); err != nil {
return StreamEvent{}, err
}
}
}
// sseEvent is one event's fields, accumulated by Next until a blank line
// dispatches them.
type sseEvent struct {
data []byte
name string
seq int64
// size is every field value read for this event, which is what the
// per-event cap measures.
size int64
}
// applyField folds one SSE field line into ev, refusing the event once its
// values pass the per-event cap. Every field's value counts against the cap,
// not just data's. retry is the one field that is not the event's: it is a
// stream-wide advisory, so it lands on s.
func (s *EventStream) applyField(ev *sseEvent, field, value string) error {
ev.size += int64(len(value))
if ev.size > s.maxBytes {
return s.tooLarge()
}
switch field {
case "event":
ev.name = value
case "data":
if len(ev.data) > 0 {
ev.data = append(ev.data, '\n')
}
ev.data = append(ev.data, value...)
if int64(len(ev.data)) > s.maxBytes {
return s.tooLarge()
}
case "id":
if n, perr := strconv.ParseInt(value, 10, 64); perr == nil {
ev.seq = n
}
case "retry":
if ms, perr := strconv.ParseInt(value, 10, 64); perr == nil && ms >= 0 {
s.retry = time.Duration(ms) * time.Millisecond
}
}
return nil
}
// readLine reads one SSE line, bounded by the per-event cap and armed with the
// idle deadline.
//