#7192 · Lifecycle hooks lose authenticated CLI routing
Verdict: PARTIALLY REPRODUCED · Root-cause confidence: high · reproduction label: partial-repro
1. TL;DR
Repository lifecycle scripts cannot inherit the authenticated server endpoint that works for agent processes. Both real lifecycle runners erase that endpoint before launching Bash, and the actual CLI configuration loader then falls back to its production loopback default. In isolated tests, the built CLI also fails authentication when explicitly pointed at an upstream that requires a machine header, even when the matching header is present in an environment variable. The same CLI succeeds when the hook explicitly uses the real machine-auth proxy instead. These mechanisms reproduce in two clean trusted main checkouts; native Windows, a real hosted Connect enrollment/server move, and the remote terminal-creation workflow were not exercised, so the overall verdict is partial rather than a claim of full end-to-end reproduction.
2. Claims vs findings
| Claim | Status | Evidence |
|---|---|---|
| Setup and teardown remove inherited server context. | Verified | Both real Bash hooks record an empty server endpoint despite a valid proxy URL in their parent environment. Thread identity is also removed as intended. |
| The CLI without an endpoint chooses the local production server. | Verified | The production CLI config loader resolves the captured hook environment to http://127.0.0.1:38886. No request is made to that port. |
| A direct endpoint alone does not supply machine authentication. | Verified with a fixture upstream | The actual built CLI, run by each hook, exits 1 with HTTP 401. The local upstream observes no machine header even after the hook explicitly exports a matching header variable. |
| The loopback machine-auth proxy makes the CLI work. | Verified | The actual proxy injects the synthetic header. Both hook kinds then run the CLI successfully, exit 0, and print []. |
| Moving a native Windows server produces the reported HTTP 410 and remote terminal failure. | Unverified end to end | No native Windows machine or hosted account was used. The old production endpoint was deliberately never contacted. The 410 response and terminal creation are not simulated as proof. |
| There is no supported automatic hook discovery of the proxy endpoint. | Verified for this call path only | The hook handler provides runtime shell context, but the lifecycle runner sanitizes it; the CLI config path supplies a loopback default instead of runtime discovery. This is not an exhaustive claim about every plugin or private runtime file. |
3. Environment
- Public repository
get-bb/bb, fetchedorigin/mainatbcfdf1ca3c3a6ff60385ab323c5a551f943a0bff; both checkouts use exactly that commit. - Linux 4.19.0-gvisor; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.12. No provider or agent session required.
- Two detached clean temporary worktrees, called
$WORK/base-aand$WORK/base-bbelow. Fresh isolated home/workspace directories are created and deleted by each test suite. - All listeners bind
127.0.0.1on fresh ephemeral ports; actual values are in the output excerpts. No development core, production runtime, real credentials, default production port, or hosted Connect instance was used. - Only the synthetic header value
fixture-machineis used. The upstream is an HTTP fixture requiring that header; lifecycle execution, CLI command/configuration, and machine-auth proxy are real repository code.
4. Minimal reproduction
- Prepare the trusted base and build the CLI using the commands below.
- Save the complete inline test in the specified package path.
- Run the focused Turbo test. On the unchanged base it intentionally fails the two proposed endpoint-preservation expectations; the two authentication controls pass.
git clone --branch main https://github.com/get-bb/bb.git bb-7192-a cd bb-7192-a git checkout --detach bcfdf1ca3c3a6ff60385ab323c5a551f943a0bff pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk pnpm exec turbo run build --filter=@bb/cli # Save the inline test below as apps/host-daemon/src/issue-7192.repro.test.ts pnpm exec turbo run test --filter=@bb/host-daemon -- issue-7192.repro.test.ts --silent=false # Expected on this unfixed base: exit 1, two endpoint failures and two passing authentication controls pnpm exec turbo run test --filter=@bb/host-daemon -- environment-lifecycle-script.test.ts operation-environment.test.ts machine-auth-proxy.test.ts
Expected versus actual
The proposed regression expectation is that a hook can resolve a usable machine-auth endpoint while still losing thread identity. It is not a claim that the currently documented sanitizer promises endpoint preservation. Actual behavior is an empty hook endpoint and a loopback default; explicit direct routing fails, while explicit proxy routing succeeds.
@bb/host-daemon:test: {"upstreamUrl":"http://127.0.0.1:31073","proxyUrl":"http://127.0.0.1:40817"}
@bb/host-daemon:test: {"kind":"setup","hookEndpoint":"","resolvedCliUrl":"http://127.0.0.1:38886"}
@bb/host-daemon:test: {"kind":"teardown","hookEndpoint":"","resolvedCliUrl":"http://127.0.0.1:38886"}
@bb/host-daemon:test: {"kind":"setup","route":"direct","exit":"1","output":"Error: HTTP 401: machine_auth_required\n{\n \"ok\": false,\n \"error\": {\n \"code\": \"http_401\",\n \"message\": \"HTTP 401: machine_auth_required\"\n }\n}","requests":[{"authenticated":false,"path":"/api/v1/hosts?includeCreating=true&type=persistent"}]}
@bb/host-daemon:test: {"kind":"setup","route":"proxy","exit":"0","output":"[]","requests":[{"authenticated":true,"path":"/api/v1/hosts?includeCreating=true&type=persistent"}]}
@bb/host-daemon:test: {"kind":"teardown","route":"direct","exit":"1","output":"Error: HTTP 401: machine_auth_required\n{\n \"ok\": false,\n \"error\": {\n \"code\": \"http_401\",\n \"message\": \"HTTP 401: machine_auth_required\"\n }\n}","requests":[{"authenticated":false,"path":"/api/v1/hosts?includeCreating=true&type=persistent"}]}
@bb/host-daemon:test: {"kind":"teardown","route":"proxy","exit":"0","output":"[]","requests":[{"authenticated":true,"path":"/api/v1/hosts?includeCreating=true&type=persistent"}]}
@bb/host-daemon:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
@bb/host-daemon:test: AssertionError: expected 'http://127.0.0.1:38886' to be 'http://127.0.0.1:40817' // Object.is equality
@bb/host-daemon:test: Test Files 1 failed (1)
@bb/host-daemon:test: Tests 2 failed | 2 passed (4)
Complete reproducible test
This test exercises actual lifecycle subprocesses and the built CLI. It never sends a request to the fallback production endpoint. The test is inline rather than published as a separate script, following the reports repository’s artifact policy.
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { createServer, type Server } from "node:http";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { loadCliConfig } from "@bb/config/cli";
import { runSetupScript, runTeardownScript } from "./environment-lifecycle-script.js";
import { startMachineAuthProxy, type MachineAuthProxy } from "./machine-auth-proxy.js";
function shellQuote(value: string): string {
return `'${value.replaceAll("'", "'\\''")}'`;
}
describe.skipIf(process.platform === "win32")("issue 7192 lifecycle CLI access", () => {
let directory: string;
let upstream: Server;
let upstreamUrl: string;
let proxy: MachineAuthProxy;
const requests: { authenticated: boolean; path: string }[] = [];
const cliPath = fileURLToPath(new URL("../../cli/dist/index.js", import.meta.url));
beforeAll(async () => {
directory = await mkdtemp(join(tmpdir(), "bb-7192-repro-"));
upstream = createServer((request, response) => {
const authenticated = request.headers["x-bb-connect-machine"] === "fixture-machine";
requests.push({ authenticated, path: request.url ?? "" });
response.setHeader("content-type", "application/json");
if (!authenticated) {
response.writeHead(401);
response.end(JSON.stringify({ error: "machine_auth_required" }));
return;
}
response.end("[]");
});
await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
const address = upstream.address();
if (address === null || typeof address === "string") throw new Error("No TCP listener");
upstreamUrl = `http://127.0.0.1:${address.port}`;
proxy = await startMachineAuthProxy({
serverUrl: upstreamUrl,
serverHeaders: { "x-bb-connect-machine": "fixture-machine" },
});
console.log(JSON.stringify({ upstreamUrl, proxyUrl: proxy.serverUrl }));
});
afterAll(async () => {
await proxy?.close();
upstream?.closeAllConnections();
if (upstream) await new Promise<void>((resolve) => upstream.close(() => resolve()));
if (directory) await rm(directory, { recursive: true, force: true });
});
function inheritedEnv(): NodeJS.ProcessEnv {
return {
PATH: `${dirname(process.execPath)}:/usr/bin:/bin`,
HOME: directory,
USERPROFILE: directory,
NODE_ENV: "production",
BB_SERVER_URL: proxy.serverUrl,
BB_SERVER_HEADERS: JSON.stringify({ "x-bb-connect-machine": "fixture-machine" }),
BB_THREAD_ID: "fixture-thread",
};
}
it.each(["setup", "teardown"] as const)(
"%s retains a usable machine endpoint while removing thread identity",
async (kind) => {
const endpointFile = join(directory, `${kind}-endpoint`);
const identityFile = join(directory, `${kind}-identity`);
await writeFile(join(directory, `.bb-env-${kind}.sh`),
`printf '%s' "\${BB_SERVER_URL-}" > ${shellQuote(endpointFile)}\nprintf '%s' "\${BB_THREAD_ID-}" > ${shellQuote(identityFile)}\n`);
const run = kind === "setup" ? runSetupScript : runTeardownScript;
await run({ workspacePath: directory, timeoutMs: 5000, env: inheritedEnv() });
const endpoint = await readFile(endpointFile, "utf8");
const config = loadCliConfig({ env: endpoint ? { BB_SERVER_URL: endpoint } : {}, homeDir: directory, mode: "prod" });
console.log(JSON.stringify({ kind, hookEndpoint: endpoint, resolvedCliUrl: config.BB_SERVER_URL }));
expect(await readFile(identityFile, "utf8")).toBe("");
expect(config.BB_SERVER_URL).toBe(proxy.serverUrl);
},
);
it.each(["setup", "teardown"] as const)(
"%s CLI rejects a direct URL with BB_SERVER_HEADERS but succeeds through the actual proxy",
async (kind) => {
const run = kind === "setup" ? runSetupScript : runTeardownScript;
for (const [route, url] of [["direct", upstreamUrl], ["proxy", proxy.serverUrl]] as const) {
const outputFile = join(directory, `${kind}-${route}-output`);
const exitFile = join(directory, `${kind}-${route}-exit`);
await writeFile(join(directory, `.bb-env-${kind}.sh`),
`export BB_SERVER_URL=${shellQuote(url)}\nexport BB_SERVER_HEADERS='{"x-bb-connect-machine":"fixture-machine"}'\n${shellQuote(process.execPath)} ${shellQuote(cliPath)} machine list --json > ${shellQuote(outputFile)} 2>&1\nprintf '%s' "$?" > ${shellQuote(exitFile)}\n`);
const requestCount = requests.length;
await run({ workspacePath: directory, timeoutMs: 10000, env: inheritedEnv() });
const exit = await readFile(exitFile, "utf8");
const output = await readFile(outputFile, "utf8");
const observed = requests.slice(requestCount);
console.log(JSON.stringify({ kind, route, exit, output: output.trim(), requests: observed }));
expect(observed.length).toBeGreaterThan(0);
expect(observed.every((request) => request.path.startsWith("/api/v1/hosts"))).toBe(true);
if (route === "direct") {
expect(exit).toBe("1");
expect(output).toContain("401");
expect(observed.every((request) => !request.authenticated)).toBe(true);
} else {
expect(exit).toBe("0");
expect(JSON.parse(output)).toEqual([]);
expect(observed.every((request) => request.authenticated)).toBe(true);
}
}
},
);
});
5. Root cause
- The daemon creates the machine-auth proxy and places its loopback URL in runtime shell context: apps/host-daemon/src/start-host-daemon.ts:134.
- The hook command handler merges runtime shell environment into the inherited environment: apps/host-daemon/src/command-handlers/environment-hook.ts:64.
- The lifecycle runner explicitly requests inherited-environment sanitization: apps/host-daemon/src/environment-lifecycle-script.ts:173. apps/host-daemon/src/operation-environment.ts:4 sanitizes first, then adds explicitly contributed values. With no overriding contribution, there is no restoration of the machine endpoint.
- The shared sanitizer intentionally removes all
BB_variables andNODE_ENV: packages/process-utils/src/environment.ts:6. This strips machine routing together with thread-local context before either platform’s Bash launcher is selected. - The CLI config loader selects the production loopback URL when no explicit endpoint is supplied: packages/config/src/cli.ts:19. Its URL resolver reads an explicit value, an environment value, or development defaults—not persisted machine headers: packages/config/src/server-url.ts:16.
- The CLI SDK factory supplies a URL and a fetch implementation, not machine headers: apps/cli/src/client.ts:6. Restoring only a direct remote URL therefore does not reproduce the proxy’s authentication behavior.
The deeper mismatch is that sanitization intentionally removes daemon/thread-specific context, while there is no replacement machine-scoped CLI routing contract at the lifecycle boundary. The proxy itself works: the positive controls reach the same fixture upstream with the correct synthetic header.
6. Proposed fix and safety decision
Define an explicit machine-scoped CLI endpoint contract for lifecycle subprocesses, then inject only the approved loopback proxy endpoint after sanitization. Keep thread identifiers and raw credentials out of inherited hook context; do not weaken the shared sanitizer globally. Cover setup, teardown, local-server mode, moved-server mode, proxy lifetime, and native Windows casing/launch behavior. Document the contract through the CLI guide and environment hook documentation.
No automatic fix PR: propagating machine-authenticated routing into repository hooks changes authentication-context behavior and requires a security/product decision. That fails the caller’s simple-fix eligibility rule regardless of patch size. No production patch, fix branch, commit, or code push was made.
7. Verification
The same investigator repeated the reproduction in a second clean detached checkout at the recorded base commit, installed with the frozen lockfile, rebuilt the required packages, and copied only the newly authored reproduction test. This is a second clean run, not independent verification. New temporary workspaces and new upstream/proxy ports were allocated. The test SHA-256 in both checkouts was fe2250e643fa86be26aa9fe23f748a1b66c8923f9496de1ae2a43bdc4f2c8cc6.
git worktree add --detach ../bb-7192-b bcfdf1ca3c3a6ff60385ab323c5a551f943a0bff cd ../bb-7192-b git status --short pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk pnpm exec turbo run build --filter=@bb/cli # Save the identical inline test in the same package-relative path pnpm exec turbo run test --filter=@bb/host-daemon -- issue-7192.repro.test.ts --silent=false
@bb/host-daemon:test: {"upstreamUrl":"http://127.0.0.1:43623","proxyUrl":"http://127.0.0.1:43949"}
@bb/host-daemon:test: {"kind":"setup","hookEndpoint":"","resolvedCliUrl":"http://127.0.0.1:38886"}
@bb/host-daemon:test: {"kind":"teardown","hookEndpoint":"","resolvedCliUrl":"http://127.0.0.1:38886"}
@bb/host-daemon:test: {"kind":"setup","route":"direct","exit":"1","output":"Error: HTTP 401: machine_auth_required\n{\n \"ok\": false,\n \"error\": {\n \"code\": \"http_401\",\n \"message\": \"HTTP 401: machine_auth_required\"\n }\n}","requests":[{"authenticated":false,"path":"/api/v1/hosts?includeCreating=true&type=persistent"}]}
@bb/host-daemon:test: {"kind":"setup","route":"proxy","exit":"0","output":"[]","requests":[{"authenticated":true,"path":"/api/v1/hosts?includeCreating=true&type=persistent"}]}
@bb/host-daemon:test: {"kind":"teardown","route":"direct","exit":"1","output":"Error: HTTP 401: machine_auth_required\n{\n \"ok\": false,\n \"error\": {\n \"code\": \"http_401\",\n \"message\": \"HTTP 401: machine_auth_required\"\n }\n}","requests":[{"authenticated":false,"path":"/api/v1/hosts?includeCreating=true&type=persistent"}]}
@bb/host-daemon:test: {"kind":"teardown","route":"proxy","exit":"0","output":"[]","requests":[{"authenticated":true,"path":"/api/v1/hosts?includeCreating=true&type=persistent"}]}
@bb/host-daemon:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
@bb/host-daemon:test: AssertionError: expected 'http://127.0.0.1:38886' to be 'http://127.0.0.1:43949' // Object.is equality
@bb/host-daemon:test: Test Files 1 failed (1)
@bb/host-daemon:test: Tests 2 failed | 2 passed (4)
Both runs: two endpoint-preservation failures for the intended reason, plus two passing direct-vs-proxy controls. Existing lifecycle, operation-environment, and proxy suites passed: 29 passed, 1 skipped, 3 files passed. The skipped test is an existing Windows-specific case on this Linux host. No production fix was applied, so there is no post-fix result.
Report correction after the second run: none to the portable mechanism. The verdict remains partial because neither run exercises the reported native Windows/hosted-move/terminal-creation sequence.
8. Related issues and pull requests
No linked open pull request was present in the issue timeline or repository search at investigation time. Historical agent-launcher behavior mentioned in the issue was not treated as proof that lifecycle hooks inherit the same routing; the shared sanitizer and actual subprocess tests are the evidence here.
9. Appendix
Classification applied: Bug, Medium priority, Medium effort; workspaces, cli, connect. There were no existing classifications or labels to preserve. The Type was read again after mutation.
Preparation note: an initial unfiltered pnpm exec turbo run build failed in plugin SDK resolution because SDK runtime outputs were not yet present. Explicit SDK type generation and the targeted CLI build succeeded; the test task built the required SDK runtime. This investigation does not claim the whole monorepo build passes.
The untrusted issue body was used only as claims to test. No issue-provided script, patch, branch, or external URL was executed or fetched. All executed application code came from the recorded trusted main commit; the reproduction fixture was written from repository evidence. Raw logs, the test copy, and the investigation brief remain in private local scratch storage rather than the public reports repository. All temporary test listeners and workspaces are closed/removed by suite teardown.
Evidence commands: git fetch origin main, git rev-parse origin/main, clean-worktree creation at the recorded SHA, frozen installs, the build and test commands shown above, git diff --check, sha256sum on the two test copies, GitHub read-only metadata/label/PR queries, and the authorized classification writes. This non-visual report needs no screenshot.