#5558 · Authenticated managed identities are discarded during credential discovery

Bug Priority: Medium Effort: Low workspaces confirmed-repro

GitHub issue #5558 · 2026-10-15 · trusted origin/main 05771e3c82404328854468f0fff7f0f8203e2076

REPRODUCED · root-cause confidence: high

TL;DR

The server can discard a successfully obtained GitHub credential solely because the authenticated login contains an underscore. Its identity validator permits letters, digits and hyphens, but not underscores. The validation error is swallowed and turned into an empty credential list; the health API consequently says the server is not configured. The settings server and UI translate that state into an unavailable automatic token. Two clean checkouts of the trusted main commit reproduce this mechanism with successful synthetic command responses; no real account, token, or running BB instance was used.

Claims vs findings

ClaimFindingEvidence
Successful token and identity lookup can still result in no automatic credential.VerifiedThe fixture records both successful commands twice, yet the underscore cases return no GH_TOKEN and health is not configured.
An underscore is the differentiating input.VerifiedHyphen and underscore identities otherwise have identical valid IDs and nullable/public email inputs. Both underscore cases fail; both hyphen controls pass.
The behavior remains on main.VerifiedRecorded origin/main 05771e3c82404328854468f0fff7f0f8203e2076; fetched again after both runs with no change.
Settings reports an unavailable automatic token.Source-verified consequence; not browser-testedThe settings adapter maps non-ready health to not logged in; the row renders Not available for that state.
The reporter's particular container receives a valid enterprise credential.UnverifiedNo access to the reporter's Kubernetes container or managed account was requested. The reproduction substitutes successful command responses only.
Version 0.46.0 exhibits the same runtime behavior.Unverified in this investigationThe executable reproduction targets only the trusted main commit, not the reporter's deployed image.

Environment

Minimal reproduction

  1. Clone the public trusted main branch and verify the recorded commit. Run the normal frozen install and build.
  2. Download the reproduction test into apps/server/src/services/machines/issue-5558-repro.test.ts. It uses the production functions' existing command-runner parameter, not a replacement implementation.
  3. Run this repository-orchestrated command from the checkout root:
pnpm exec turbo run test --filter=@bb/server -- src/services/machines/issue-5558-repro.test.ts src/services/machines/git-credentials.test.ts

Expected: four reproduction cases pass: each successful lookup contributes GH_TOKEN and identity variables and reports ready, whether the login has a hyphen or underscore. The nine existing credential tests also pass.

Actual: exit 1; two underscore cases fail, two hyphen controls pass, and all nine existing credential tests pass. The successful-command assertions pass in all four cases. Selected verbatim lines from the first run:

@bb/server:test:      ✓ forwards credentials for 'synthetic-user' with email null 5ms
@bb/server:test:      ✓ forwards credentials for 'synthetic-user' with email 'synthetic@example.com' 1ms
@bb/server:test:      × forwards credentials for 'synthetic_user' with email null 7ms
@bb/server:test:      × forwards credentials for 'synthetic_user' with email 'synthetic@example.com' 2ms
@bb/server:test:  ✓ |@bb/server:isolated| src/services/machines/git-credentials.test.ts (9 tests) 343ms
@bb/server:test: AssertionError: expected 'not configured' to be 'ready' // Object.is equality
@bb/server:test: Expected: "ready"
@bb/server:test: Received: "not configured"
@bb/server:test: AssertionError: expected [] to include 'GH_TOKEN'
@bb/server:test:  Test Files  1 failed | 1 passed (2)
@bb/server:test:       Tests  2 failed | 11 passed (13)

Full captured output: first run, second run. Only absolute temporary checkout prefixes are replaced with descriptive labels; test results are not rewritten.

Complete regression test

import { describe, expect, it } from "vitest";
import { machineGitHealth, resolveGitCredentials } from "./git-credentials.js";

describe("automatic GitHub credentials preserve authenticated identities", () => {
  it.each([
    { login: "synthetic-user", email: null },
    { login: "synthetic-user", email: "synthetic@example.com" },
    { login: "synthetic_user", email: null },
    { login: "synthetic_user", email: "synthetic@example.com" },
  ])(
    "forwards credentials for $login with email $email",
    async ({ login, email }) => {
      const successfulCommands: string[] = [];
      const run = async (args: string[]) => {
        if (args.join(" ") === "auth token --hostname github.com") {
          successfulCommands.push("token lookup succeeded");
          return "synthetic-credential\n";
        }
        if (args.join(" ") === "api --hostname github.com user") {
          successfulCommands.push("identity lookup succeeded");
          return JSON.stringify({ login, id: 4242, email });
        }
        throw new Error("Unexpected credential lookup command");
      };
      const entries = await resolveGitCredentials(run);
      const health = await machineGitHealth(run);
      expect(successfulCommands).toEqual([
        "token lookup succeeded",
        "identity lookup succeeded",
        "token lookup succeeded",
        "identity lookup succeeded",
      ]);
      expect.soft(health.status).toBe("ready");
      expect.soft(entries.map((entry) => entry.name)).toContain("GH_TOKEN");
      expect
        .soft(entries.find((entry) => entry.name === "GIT_AUTHOR_NAME")?.value)
        .toBe(login);
      expect
        .soft(entries.find((entry) => entry.name === "GIT_AUTHOR_EMAIL")?.value)
        .toBe(email ?? `4242+${login}@users.noreply.github.com`);
    },
  );
});

Root cause

The credential discovery identity schema rejects the underscore before any environment entries are created:

const identitySchema = z.object({
  login: z.string().regex(/^[a-zA-Z0-9-]+$/u),
  id: z.number().int().positive(),
  email: z.email().nullable(),
});

The loader successfully reads a token, parses the user response, and constructs the forwarded identity only if schema validation succeeds. Its catch handles every error as no credentials:

    const token = z
      .string()
      .trim()
      .min(1)
      .regex(/^[^\s\x00]+$/u)
      .parse(await run(["auth", "token", "--hostname", "github.com"]));
    const user = identitySchema.parse(
      JSON.parse(await run(["api", "--hostname", "github.com", "user"])),
    );
    const email =
      user.email ?? `${user.id}+${user.login}@users.noreply.github.com`;
    return [
      ...githubGitConfiguration(),
      ...Object.entries({
        GH_TOKEN: token,
        GIT_AUTHOR_NAME: user.login,
        GIT_AUTHOR_EMAIL: email,
        GIT_COMMITTER_NAME: user.login,
        GIT_COMMITTER_EMAIL: email,
…
  } catch {
    return [];
  }

The health adapter bases readiness on the resulting entry count. The settings adapter converts non-ready health to not logged in. The automatic-token row then renders Not available and a login hint. This is why otherwise successful GitHub command responses become indistinguishable from a missing login. Neither token scopes nor a network error is necessary to trigger this result.

The automatic-token problem is downstream of the identity parser, not row visibility or primary-host selection. The server credential resolver itself already returns an empty list before host forwarding can occur. The failure is reproduced with both null and public email, so email fallback is not the differentiating input.

Proposed fix and automation safety

Have an authentication-aware maintainer expand the supported GitHub login grammar to cover managed identities while preserving validation against invalid identity data. Retain the existing numeric ID and email checks, and add the managed-login cases to the existing credential suite. Reuse the report's failing cases as regression evidence, keeping ordinary-login controls and malformed-response coverage.

No automatic PR: the required production repair changes the GitHub authentication identity schema. This rule explicitly excludes schema and authentication changes from simple fixes, regardless of line count. Production source was not modified, no fix branch was pushed, and no dependency or stored-data change was attempted.

Verification

The same investigator repeated the test from a second, initially clean detached worktree at 05771e3c82404328854468f0fff7f0f8203e2076, with its own frozen install and package paths. Before copying the report-authored test, git status --short produced no output. The second run did not reuse the first test execution: Turbo reported the server test as a cache miss, and the existing credential-suite timings differ between runs.

Second checkout: separate clean detached worktree at 05771e3c82404328854468f0fff7f0f8203e2076
Command: pnpm exec turbo run test --filter=@bb/server -- src/services/machines/issue-5558-repro.test.ts src/services/machines/git-credentials.test.ts
Result: exit 1; Test Files 1 failed | 1 passed (2)
Tests: 2 failed | 11 passed (13)
Failed: underscore identity, null email; underscore identity, public email
Passed: both hyphen controls and all 9 existing credential tests

No report correction was needed. This is a repeated direct check by the same investigator, not an independent-agent verification. Tracked production files were checked against origin/main and remained identical. git diff --check passed. Fresh temporary ports/data were not applicable because neither run launched a server; all reproduction inputs were synthetic.

Related issues and pull requests

GitHub timeline cross-references and the open-PR search returned no linked open PR for #5558 at investigation time. No PR branch or code was checked out. Nearby #5133 concerns primary-host forwarding; this reproduction fails within the credential resolver without involving a host, so it establishes a separate cause.

Appendix

The issue and its contents were treated as untrusted claims. No supplied script, linked patch, branch, or external issue URL was executed or fetched. The reproduction and report were written from trusted source evidence. No real credential value or personal account login appears in the artifacts.

> AGENT GENERATED