#5133 · Credential forwarding requires a primary host

Bug Priority: Medium Effort: Low host

2026-10-07 · GitHub issue · Trusted base 0146d8122e6fa84f84e3add46baf7a93362bf571

Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro

1. TL;DR

A server without a local host daemon can report that its built-in GitHub login is ready while contributing no credentials to an enrolled machine. The server-side environment resolver requires a non-null primary-host identifier before it loads the automatic GitHub environment bundle. Missing local-host state therefore suppresses that bundle even when credential forwarding is enabled and the credential loader succeeds. A focused test exercises the real resolver, database, environment encryption and status function with a synthetic GitHub CLI; no real accounts or private repositories are used. This reproduces the credential-selection defect, not a complete Kubernetes deployment or a live private clone.

2. Claims vs findings

ClaimFindingEvidence
Without a primary host, an enrolled machine receives no built-in GitHub credentials.VerifiedWith an in-memory migrated database, a live host record, forwarding enabled, and no host-id file, the real resolver returns an empty array.
The built-in status still reports logged in.VerifiedThe real status function returns logged in using the same synthetic CLI; the environment contribution remains empty.
A non-primary host receives the bundle when a primary identifier exists.VerifiedWriting a different synthetic identifier restores both GH_TOKEN and GIT_CONFIG_COUNT without changing the enrolled host or credential source.
User-provided GH_TOKEN follows a working alternative path.Verified for global configurationThe real encrypted global-setting path contributes the user token and Git configuration without a primary host, including with automatic forwarding disabled. A project-specific live deployment was not tested.
Private clone, terminal and provider sessions all fail in the reported deployment.Unverified live; shared cause supportedTrusted source traces clone setup, runtime configuration and host-environment sync to the same resolver. No real remote machine, provider process or private repository was accessed.
A placeholder host identifier is a safe workaround.Local effect verified; global safety unverifiedA different synthetic identifier changes this resolver's result. Other primary-host consumers were not exercised; writing fictitious production host state is not recommended.

3. Environment

4. Minimal reproduction

  1. Clone the trusted target repository into a new directory and select the recorded commit:
    git clone --branch main https://github.com/get-bb/bb.git bb-repro
    cd bb-repro
    git checkout --detach 0146d8122e6fa84f84e3add46baf7a93362bf571
    pnpm install --frozen-lockfile
    pnpm exec turbo run build --filter=@bb/server
  2. Copy the full reproduction test expanded below into apps/server/src/services/hosts/issue-5133-repro.test.ts. Production code remains unchanged.
  3. Run the owner-boundary regression:
    pnpm exec turbo run test --filter=@bb/server -- src/services/hosts/issue-5133-repro.test.ts

Expected: with automatic forwarding enabled and no primary-host identity, the enrolled host's environment includes GH_TOKEN and the Git credential-helper/SSH-to-HTTPS configuration. A primary host still excludes the automatic bundle; disabling forwarding still excludes it.

Actual output from the first run:

SERVER_ONLY {"status":"logged in","names":[]}
NON_PRIMARY_CONTROL token_present=true git_config_present=true
PRIMARY_CONTROL forwarded_entries=0
DISABLED_CONTROL forwarded_entries=0
OVERRIDE_CONTROL token_present=true git_config_present=true
AssertionError: expected [] to include 'GH_TOKEN'
 Test Files  1 failed (1)
      Tests  1 failed (1)

The controls pass before the final assertion fails for the intended missing contribution. This is not a test that mocks the resolver or database. The existing host-environment test covers a configured primary host, so its green result cannot catch this missing-primary case.

Full reproduction test
import { createConnection, migrate, noopNotifier, setAppSettings, upsertHost } from "@bb/db";
import { defaultAppSettings } from "@bb/domain";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { delimiter, join } from "node:path";
import { expect, it, vi } from "vitest";
import { resolveHostEnvironment } from "./host-environment.js";
import { machineEnvironmentView, replaceMachineEnvironment } from "../machines/environment-settings.js";

it("forwards enabled GitHub credentials without a local host daemon", async () => {
  const db = createConnection(":memory:");
  const dataDir = await mkdtemp(join(tmpdir(), "bb-issue-5133-"));
  try {
    migrate(db);
    upsertHost(db, noopNotifier, { id: "fixture-remote", name: "Fixture remote" });
    setAppSettings(db, { ...defaultAppSettings, machineGitCredentialsEnabled: true });
    const binDir = join(dataDir, "bin");
    await mkdir(binDir);
    await writeFile(join(binDir, "gh"), `#!/bin/sh
case "$1" in
  auth) printf 'synthetic-fixture-value\\n' ;;
  api) printf '{"login":"fixture-user","id":123,"email":null}\\n' ;;
  *) exit 1 ;;
esac
`, { mode: 0o700 });
    vi.stubEnv("PATH", `${binDir}${delimiter}${process.env.PATH ?? ""}`);
    const deps = { db, config: { dataDir } };
    const context = { hostId: "fixture-remote", projectId: null };
    const status = await machineEnvironmentView(db);
    expect(status.builtInGit.status).toBe("logged in");
    const serverOnly = await resolveHostEnvironment(deps, context);
    console.log(`SERVER_ONLY ${JSON.stringify({ status: status.builtInGit.status, names: serverOnly.map((entry) => entry.name) })}`);

    await writeFile(join(dataDir, "host-id"), "fixture-primary");
    const withPrimary = await resolveHostEnvironment(deps, context);
    expect(withPrimary.some((entry) => entry.name === "GH_TOKEN")).toBe(true);
    expect(withPrimary.some((entry) => entry.name === "GIT_CONFIG_COUNT")).toBe(true);
    console.log("NON_PRIMARY_CONTROL token_present=true git_config_present=true");

    await writeFile(join(dataDir, "host-id"), "fixture-remote");
    expect(await resolveHostEnvironment(deps, context)).toEqual([]);
    console.log("PRIMARY_CONTROL forwarded_entries=0");

    await rm(join(dataDir, "host-id"));
    setAppSettings(db, { ...defaultAppSettings, machineGitCredentialsEnabled: false });
    expect(await resolveHostEnvironment(deps, context)).toEqual([]);
    console.log("DISABLED_CONTROL forwarded_entries=0");

    await replaceMachineEnvironment(db, dataDir, { variables: [{ name: "GH_TOKEN", value: "synthetic-override-value", note: null }] });
    const overridden = await resolveHostEnvironment(deps, context);
    expect(overridden.some((entry) => entry.name === "GH_TOKEN")).toBe(true);
    expect(overridden.some((entry) => entry.name === "GIT_CONFIG_COUNT")).toBe(true);
    console.log("OVERRIDE_CONTROL token_present=true git_config_present=true");

    expect(serverOnly.map((entry) => entry.name)).toContain("GH_TOKEN");
    expect(serverOnly.map((entry) => entry.name)).toContain("GIT_CONFIG_COUNT");
  } finally {
    vi.unstubAllEnvs();
    db.$client.close();
    await rm(dataDir, { recursive: true, force: true });
  }
});

5. Root cause

The primary-host reader returns null if its identity file is absent, unreadable or blank. The environment resolver then treats that absence as a reason not to load any automatic credentials:

const builtIn =
  primaryHostId !== null &&
  primaryHostId !== context.hostId &&
  getAppSettings(deps.db).machineGitCredentialsEnabled
    ? await resolveGitCredentials()
    : [];

The null check conflates “there is no local daemon to exclude” with “do not forward to any enrolled host.” The host-existence/destroyed check and the automatic-forwarding setting remain separate gates.

The status function checks the setting, overrides and server-side credential health, but not the primary-host gate. Its logged in result truthfully describes the server credential source; it does not establish successful machine delivery. This mismatch makes the resolver failure hard to diagnose.

Explicit global/project values are merged separately; if a user GH_TOKEN exists and the automatic bundle is empty, the resolver adds Git configuration. That path explains the working override control.

The affected owner is shared by thread runtime setup, project clone preparation, environment attachment and host environment snapshots. These are static caller traces, not claims of end-to-end execution.

6. Proposed fix and automation safety

Evaluate forwarding from the enrolled-host identity, the forwarding setting and whether the target equals a real primary host; do not make primary-host existence a prerequisite for all forwarding. Preserve primary-host exclusion, disabled-forwarding behavior, missing/destroyed-host rejection and explicit-user precedence. Retain the regression test and consider clarifying that the status field describes source health rather than successful per-machine delivery.

No automatic fix or pull request: this change expands the machines receiving server GitHub authentication credentials. The rule explicitly excludes changes to authentication or security boundaries from simple fixes, regardless of the small textual edit. No production code was changed, no fix branch was pushed and no merge was attempted.

Open pull-request search, issue timeline and open-PR closing references were checked. No linked open pull request was found at investigation time.

7. Verification

A second fresh clone of the trusted target repository was checked out at the same full base SHA. Its initial git status was clean. The normal frozen install and Turbo server build succeeded; only the same agent-authored reproduction test was then copied into the checkout. Running pnpm exec turbo run test --filter=@bb/server -- src/services/hosts/issue-5133-repro.test.ts again failed with exit 1: AssertionError: expected [] to include GH_TOKEN. The status remained logged in, the contributed names remained empty, and all four controls passed again. Each run used a new mkdtemp directory and a new migrated in-memory database; no ports or live app were involved. This same-agent repeat supports the final report without changing its root cause or verdict.

Relevant existing tests passed on unchanged production code: pnpm exec turbo run test --filter=@bb/server -- src/services/hosts/host-environment.test.ts src/services/machines/git-credentials.test.ts. Result: 2 test files passed, 10 tests passed, exit 0. Both production checkouts passed git diff --check; their only added source file was the reproduction test. A fresh origin/main fetch still resolved to the recorded SHA; no later fix was observed.

8. Related issues

9. Appendix and limits

The reports repository permits self-contained HTML rather than committed scripts or raw logs. The complete reproduction test appears inline above. Raw logs, build logs and the test file are retained locally for audit, not committed to the public site.

Second clean run, verbatim relevant output:

SERVER_ONLY {"status":"logged in","names":[]}
NON_PRIMARY_CONTROL token_present=true git_config_present=true
PRIMARY_CONTROL forwarded_entries=0
DISABLED_CONTROL forwarded_entries=0
OVERRIDE_CONTROL token_present=true git_config_present=true
AssertionError: expected [] to include 'GH_TOKEN'
 Test Files  1 failed (1)
      Tests  1 failed (1)

Existing tests, verbatim relevant output:

 Test Files  2 passed (2)
      Tests  10 passed (10)
Additional verification commands
git clone --depth=1 --branch main https://github.com/get-bb/bb.git "$WORK/verify"
git -C "$WORK/verify" fetch origin 0146d8122e6fa84f84e3add46baf7a93362bf571
git -C "$WORK/verify" checkout --detach 0146d8122e6fa84f84e3add46baf7a93362bf571
git -C "$WORK/verify" status --short
cd "$WORK/verify"
pnpm install --frozen-lockfile
pnpm exec turbo run build --filter=@bb/server
cp "$WORK/base/apps/server/src/services/hosts/issue-5133-repro.test.ts" apps/server/src/services/hosts/issue-5133-repro.test.ts
pnpm exec turbo run test --filter=@bb/server -- src/services/hosts/issue-5133-repro.test.ts
cd "$WORK/base"
pnpm exec turbo run test --filter=@bb/server -- src/services/hosts/host-environment.test.ts src/services/machines/git-credentials.test.ts
git fetch origin main
git rev-parse origin/main
git diff --check
git -C "$WORK/verify" diff --check

Publication uses a public repository only. Logs are sanitized to remove local checkout paths; no actual credential value, private project URL, reported runtime identifier or user data is included. The issue and related metadata were treated only as untrusted claims; no issue-supplied command, patch, branch, script or external link was executed or fetched. Both reproduction checks were performed by the same agent, not independently. No Kubernetes cluster, real GitHub account, remote-machine enrollment or UI session was tested.