← reports

#5838 · CLI transport lacks managed-run write protection

BugHighEffort: LowcliGitHub issueOctober 20, 2026

Verdict: REPRODUCED · Root-cause confidence: high
Trusted base: b0bb68655adcc6cd79e495d3484f4011a0640e2e

1. TL;DR

The CLI can attempt a plugin settings write against its default local production address even when a managed-job marker is present. The real built CLI selected port 38886, fetched a synthetic setting schema, dispatched a PUT to the intercepted transport, and exited successfully. The same result occurred with an explicit default URL and with localhost. Configuration chooses a production fallback and the shared HTTP transport performs no managed-job check. Two clean trusted checkouts produced identical results; this establishes the routing defect, not the cause of a historical credential incident.

2. Claims vs findings

ClaimStatusEvidence
A marked process can write through the default CLI target.VerifiedAll three managed default-target cases dispatched GET, PUT and exited 0 in both checkouts.
Specifying the default URL explicitly does not prevent the write.VerifiedExplicit 127.0.0.1 and localhost cases match the implicit-default result.
The managed-job marker is sufficient to reproduce the missing guard.Verified within scopeThe child received a synthetic nonempty marker; no actual job scheduler or host-care runtime was started.
The reported incident overwrote a credential.UnverifiedNo account, credential, production database, incident attachment, or external investigation link was accessed.
A guard would have prevented that exact incident.UnverifiedThe original invocation and job ancestry were not established. This report makes no such causal claim.
The entire requested acceptance matrix is proven.UnverifiedThis direct repro covers plugin configuration routing, an alias and two controls, not every method, SDK operation, override, re-exec or plugin-proxy case.

3. Environment

4. Minimal reproduction

  1. Check out the trusted recorded base and build its CLI:
    ROOT=$(mktemp -d)
    git clone --single-branch --branch main https://github.com/get-bb/bb.git "$ROOT/source-one"
    git -C "$ROOT/source-one" checkout --detach b0bb68655adcc6cd79e495d3484f4011a0640e2e
    cd "$ROOT/source-one"
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/cli
  2. Save the two self-contained files below next to each other, outside the checkout. The recorder never delegates to a real HTTP transport.
  3. Run the regression assertion:
    node issue-5838-reproduce.mjs "$ROOT/source-one"
    Expected protected behavior: the three marked default-target invocations return nonzero and dispatch no write. Both controls succeed. Actual baseline behavior: every invocation exits 0 and dispatches GET followed by PUT; the regression assertion then exits 1.

issue-5838-fetch-recorder.mjs

import { appendFileSync } from "node:fs";

globalThis.fetch = async function recordOnly(resource, options = {}) {
  const address = resource instanceof Request ? resource.url : String(resource);
  const method = options.method ?? (resource instanceof Request ? resource.method : "GET");
  appendFileSync(process.env.REPRO_REQUESTS, `${JSON.stringify({ address, method })}\n`);
  const destination = new URL(address);
  if (!destination.pathname.endsWith("/settings")) {
    throw new Error("Unexpected synthetic endpoint");
  }
  return Response.json({
    ok: true,
    schema: { ceiling: { type: "number", label: "Ceiling", default: 2 } },
    values: { ceiling: 2 },
  });
};

issue-5838-reproduce.mjs

import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const checkout = resolve(process.argv[2]);
const fixture = join(dirname(fileURLToPath(import.meta.url)), "issue-5838-fetch-recorder.mjs");
const sandbox = mkdtempSync(join(tmpdir(), "transport-reproduction-"));
const cases = [
  { name: "managed implicit default", marked: true, target: null, blocked: true },
  { name: "managed explicit default", marked: true, target: "http://127.0.0.1:38886", blocked: true },
  { name: "managed localhost default", marked: true, target: "http://localhost:38886", blocked: true },
  { name: "managed alternate port control", marked: true, target: "http://127.0.0.1:49873", blocked: false },
  { name: "unmanaged default control", marked: false, target: null, blocked: false },
];
const observations = [];

try {
  for (const [index, scenario] of cases.entries()) {
    const home = join(sandbox, `case-${index}`);
    mkdirSync(home);
    const record = join(home, "requests.ndjson");
    const env = {
      PATH: process.env.PATH,
      HOME: home,
      TMPDIR: home,
      NODE_ENV: "production",
      BB_CLI_ERROR_LOG: "0",
      REPRO_REQUESTS: record,
    };
    if (scenario.marked) env.HOST_CARE_JOB_ID = "synthetic-managed-run";
    if (scenario.target !== null) env.BB_SERVER_URL = scenario.target;
    const child = spawnSync(process.execPath, [
      "--import", fixture,
      join(checkout, "apps/cli/dist/index.js"),
      "plugin", "config", "synthetic-limits", "set", "ceiling", "7", "--json",
    ], { cwd: checkout, env, encoding: "utf8", timeout: 20000 });
    assert.ifError(child.error);
    const requests = existsSync(record)
      ? readFileSync(record, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line))
      : [];
    const observation = {
      scenario: scenario.name,
      expected: scenario.blocked ? "nonzero exit and no write dispatched" : "successful write",
      exit: child.status,
      requests,
      stdout: child.stdout.trim(),
      stderr: child.stderr.trim(),
    };
    console.log(JSON.stringify(observation));
    observations.push({ scenario, observation });
  }
  for (const { scenario, observation } of observations.filter(({ scenario }) => !scenario.blocked)) {
    assert.equal(observation.exit, 0, `${scenario.name}: control must succeed`);
    assert.equal(observation.requests.filter(({ method }) => method === "PUT").length, 1);
  }
  const unexpectedWrites = observations.filter(({ scenario, observation }) => scenario.blocked &&
    (observation.exit === 0 || observation.requests.some(({ method }) => !["GET", "HEAD", "OPTIONS"].includes(method))));
  assert.equal(unexpectedWrites.length, 0, "Managed requests reached the default-port write transport");
} finally {
  rmSync(sandbox, { recursive: true, force: true });
}

Observed results in both checkouts

managed implicit default: exit=0; methods=GET,PUT; stderr=""
managed explicit default: exit=0; methods=GET,PUT; stderr=""
managed localhost default: exit=0; methods=GET,PUT; stderr=""
managed alternate port control: exit=0; methods=GET,PUT; stderr=""
unmanaged default control: exit=0; methods=GET,PUT; stderr=""

AssertionError [ERR_ASSERTION]: Managed requests reached the default-port write transport
3 !== 0
Regression process exit: 1

Each settings URL was http://HOST:PORT/api/v1/plugins/synthetic-limits/settings. HOST was 127.0.0.1 except for the localhost case. The runner prints every complete synthetic request record and CLI output. The settings response intentionally describes a fixed fake state; it is not evidence of persisted data.

5. Root cause

  1. Production constants select port 38886 and loopback 127.0.0.1.
  2. CLI configuration fallback selects that address when no server URL is configured. An explicit URL is passed through the configured-value branch.
  3. Runtime context resolution loads this configuration and returns its server URL without rewriting it from project or thread context.
  4. Plugin configuration mutation fetches the schema and then calls the PUT path. Plugin HTTP helper sends both requests through the shared transport.
  5. Shared CLI HTTP transport unconditionally calls fetch and also supplies that fetch function to the Node SDK:
    export function cliFetch(
      input: RequestInfo | URL,
      init?: CliRequestInit,
    ): Promise<Response> {
      return fetch(input, init);
    }
    There is no target-, method-, or managed-job-dependent rejection here. This missing policy explains the observed dispatch and successful synthetic response.

High priority reflects accidental configuration corruption risk, not a demonstrated privilege escalation. Low effort reflects a contained CLI transport change using existing URL/error plumbing. The test detects a real request reaching that transport; no production-only test seam was added.

6. Proposed fix

Put accidental-routing protection at the existing shared CLI fetch boundary, before transport dispatch, and make the effective Request/init method and normalized destination explicit. Keep intentional reads and isolated targets working; preserve ordinary invocations. Propagate a structured error through both core and plugin CLI entry paths and document any override. This is defense against accidental targeting, not authentication or a security boundary. Extend the primary boundary test with read methods, aliases, Request precedence, overrides, SDK mutations and re-exec.

No new fix branch or PR was created: the open linked PR below already addresses this issue.

7. Linked PR review

PR #5839 — static review only

GitHub's closing-issue metadata confirms the open PR links #5838. The reviewed diff at head b1a3eadf7f20da98d76c227046a02704e864740d adds a managed-process method/loopback-port check to apps/cli/src/client.ts, a specific error, JSON error propagation, documentation and regression cases. This targets the verified root cause rather than patching only one plugin command.

Verdict: directionally aligned, runtime behavior not verified. No branch, script, patch or test from the PR was executed. No merge-readiness or complete acceptance claim follows from this static review. The tests executed for this report are the trusted-base reproduction and existing plugin configuration tests only.

8. Related issues

A bounded review of open CLI-labeled issues did not identify another issue with this same routing mechanism. This is not an exhaustive duplicate search. The linked open PR is the reason no duplicate implementation was attempted.

9. Verification

The same agent repeated the reproduction in a second clean checkout at the identical trusted commit. Both checkouts were clean before execution; installation/build generated only ignored outputs. A separate set of temporary child homes and request logs was created on the second run. No ports or data directories were shared because no server was needed. This was a repeat by the same agent, not independent verification.

git clone --shared --no-checkout "$ROOT/source-one" "$ROOT/source-two"
git -C "$ROOT/source-two" remote set-url origin https://github.com/get-bb/bb.git
git -C "$ROOT/source-two" checkout --detach b0bb68655adcc6cd79e495d3484f4011a0640e2e
cd "$ROOT/source-two"
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@bb/cli
node /path/to/issue-5838-reproduce.mjs "$ROOT/source-two"

First run: regression exit 1; 3 marked default-target writes dispatched.
Second run: regression exit 1; 3 marked default-target writes dispatched.
Complete captured reproduction outputs: byte-identical.
Both controls: exit 0, exactly one PUT in each run.
Both checkout HEADs: b0bb68655adcc6cd79e495d3484f4011a0640e2e
Both tracked working trees: clean.

No report correction was necessary after the second run. Root-cause links were checked against numbered source at the recorded commit.

10. Appendix

Existing trusted-base coverage was checked through Turbo:

pnpm exec turbo run test --filter=@bb/cli -- src/__tests__/command-output/plugin-config.test.ts

Test Files  1 passed (1)
Tests       6 passed (6)
Tasks       6 successful, 6 total

Both frozen installations succeeded; each targeted CLI build completed five successful tasks. The existing suite confirms the normal plugin config path but does not assert a managed-process routing guard. The new external repro fails for that missing behavior, after successful controls; no production fix was applied.

Untrusted-data handling: issue/PR text was treated only as claims. No external issue links, attached scripts, investigation threads, production settings, credentials or runtime data were opened. Reproduction code was authored from trusted repository evidence. Raw local logs and scripts stay outside this public repository; their necessary reproducible content is included inline. No visual evidence is needed for this nonvisual CLI defect.