#5852 · Stored credential selection and legacy fallback
PARTIALLY REPRODUCED · Root-cause confidence: medium
1. TL;DR
The usage collector ignores a SQLite credential whose active flag is NULL, even when it is the only stored key. With an older auth file present, the collector sends the file credential; without that file, it reports unauthenticated and sends no request. Both outcomes repeat in two clean trusted checkouts using a real temporary SQLite database and an intercepted network boundary. The existing suite passes because it explicitly treats NULL as inactive. This verifies the collector mechanism, not the full OpenCode upgrade: no external installer, binary, upstream source link, or issue-provided script was used, so the provider's actual migration and version-specific selection rules remain unverified.
2. Claims vs findings
| Claim | Status | Evidence |
|---|---|---|
| NULL-active stored credentials are skipped. | Verified | Real SQLite fixture, both runs; the selection predicate requires active = 1. |
| A leftover file can be used instead; removing it produces unauthenticated. | Verified for synthesized state | Both failing regression cases show the claimed collector outcomes; all fetch calls are intercepted. |
| Explicitly active database keys already work. | Verified | Positive control passes and selects the database rather than the file. |
| An upgrade creates this state, and the current provider treats NULL rows as selectable. | Unverified | No upstream installation or migration execution. The fixture reproduces the reported state, not its origin. |
| A migration record reliably distinguishes provider major versions. | Unverified | Not established by trusted bb source; needs trusted provider-version evidence before a production fix. |
| A leftover Console account wins over the stored-credential path. | Static finding only | Account resolution precedes the credential query; this secondary scenario was not run. |
3. Environment
- Public repository: get-bb/bb; recorded origin/main:
e0f6fda5a02332bd4eb44183542a57f34f3263d7. A final fetch still returned this commit. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.1.
- Two distinct detached checkouts: first checkout
base/, second checkoutverify/. Both use the recorded trusted commit; production files remain unchanged. - Normal
pnpm install --frozen-lockfilein both checkouts; Turbo ran upstream generation/native-verification prerequisites. No dependency added. - No live bb instance, user credentials, provider installation, listening port, or subscription. Each test creates and removes its own temporary HOME/XDG data directory. Fetch returns a synthetic HTTP 500 and never reaches the network.
4. Minimal reproduction
- Create a trusted checkout and install the existing lockfile:
git clone https://github.com/get-bb/bb.git bb-5852 cd bb-5852 git checkout --detach e0f6fda5a02332bd4eb44183542a57f34f3263d7 pnpm install --frozen-lockfile
- Save the authored reproduction test as
packages/provider-bridge-acp/src/bridge/issue-5852.repro.test.ts. - Run the focused test:
pnpm exec turbo run test --filter=@bb/provider-bridge-acp -- src/bridge/issue-5852.repro.test.ts
The two regression assertions express the expected result if the NULL-active row is authoritative: select the database credential, independent of a legacy file. They fail on unchanged production code; the explicitly-active positive control passes.
Expected: selectedDatabase = true in both NULL-active cases.
Actual (verbatim sanitized observations):
{"legacyFile":true,"selectedDatabase":false,"selectedLegacy":true,"requests":1,"status":"error"}
{"legacyFile":false,"selectedDatabase":false,"selectedLegacy":false,"requests":0,"status":"unauthenticated"}
First run: 2 failed | 1 passed (3), exit 1.
Second run: same observations and assertion failures, exit 1.
The error status is the intentional HTTP 500 stub, not a real usage-service failure.
Full reproduction source
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { readOpenCodeGoUsage } from "./opencode-usage.js";
let directory: string;
const fetchUsage = vi.fn<typeof fetch>();
const databaseKey = "fixture-database-only";
const obsoleteKey = "fixture-obsolete-file";
beforeEach(async () => {
directory = await fs.mkdtemp(path.join(os.tmpdir(), "bb-5852-"));
await fs.mkdir(path.join(directory, "opencode"));
fetchUsage.mockReset();
fetchUsage.mockImplementation(
async () => new Response("{}", { status: 500 }),
);
vi.stubGlobal("fetch", fetchUsage);
});
afterEach(async () => {
vi.unstubAllGlobals();
await fs.rm(directory, { recursive: true, force: true });
});
async function seedCredential(active: number | null, legacyFile: boolean) {
const database = new DatabaseSync(
path.join(directory, "opencode", "opencode.db"),
);
try {
database.exec(
"CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, label TEXT NOT NULL, value TEXT NOT NULL, connector_id TEXT, method_id TEXT, active INTEGER, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL)",
);
database
.prepare(
"INSERT INTO credential (id, integration_id, label, value, active, time_created, time_updated) VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.run(
"fixture-row",
"opencode",
"fixture",
JSON.stringify({ type: "key", key: databaseKey }),
active,
10,
10,
);
} finally {
database.close();
}
if (legacyFile) {
await fs.writeFile(
path.join(directory, "opencode", "auth.json"),
JSON.stringify({ "opencode-go": { type: "api", key: obsoleteKey } }),
);
}
}
it("control: an explicitly active database credential overrides the legacy file", async () => {
await seedCredential(1, true);
const result = await readOpenCodeGoUsage({
HOME: directory,
XDG_DATA_HOME: directory,
});
const headers = new Headers(fetchUsage.mock.calls[0]?.[1]?.headers);
expect(headers.get("authorization") === "Bearer " + databaseKey).toBe(true);
expect(result.usage.status).toBe("error");
});
it.each([true, false])(
"regression: a selectable unflagged database credential remains usable (legacy file: %s)",
async (legacyFile) => {
await seedCredential(null, legacyFile);
const result = await readOpenCodeGoUsage({
HOME: directory,
XDG_DATA_HOME: directory,
});
const headers = new Headers(fetchUsage.mock.calls[0]?.[1]?.headers);
const selectedDatabase =
headers.get("authorization") === "Bearer " + databaseKey;
const selectedLegacy =
headers.get("authorization") === "Bearer " + obsoleteKey;
console.log(
JSON.stringify({
legacyFile,
selectedDatabase,
selectedLegacy,
requests: fetchUsage.mock.calls.length,
status: result.usage.status,
}),
);
expect(selectedDatabase).toBe(true);
},
);
5. Root cause
readStoredCredential, line 105 requires active = 1. In SQLite, a NULL active value does not satisfy this predicate, so no key is returned. readOpenCodeGoUsage, line 197 then falls back to legacy credentials without distinguishing database generations. If no legacy key exists, lines 202–203 returns unauthenticated. This completely explains the observed fixture outcomes.
SELECT value FROM credential WHERE integration_id = ? AND active = 1 ORDER BY time_created DESC, id DESC LIMIT 1 apiKey ??= await readLegacyApiKey(env);
Line 185 also resolves a Console account before querying stored credentials. The entry point is getAcpProviderUsage, line 384. No public API or server path needs to be invented to reach this reader.
The stronger underlying issue is the collector's storage-authority assumption. Existing test, lines 285 onward explicitly groups NULL with inactive rows, so the baseline suite enforces the behavior being reported. Git history attributes the stored-credential implementation to a312ed2d6 (#4696). Whether that assumption is wrong for a particular provider version requires upstream evidence outside this run.
6. Proposed fix and safety gate
First establish a reliable, read-only provider-version discriminator from trusted provider evidence, including fresh and upgraded databases. Then match that version's selected credential and authoritative store while preserving older-version behavior. Cover imported NULL rows, empty current stores with leftover files, Console leftovers, explicit active rows, and ordering ties. Do not broaden the predicate for every database merely because this fixture fails.
No automatic production fix or PR: changing which credential is selected changes authentication behavior, which this autopilot rule explicitly excludes from simple fixes. Provider-version semantics are also unverified. Only the authored reproduction file is added locally; no production code, schema, migration, dependency, or stored user data changes.
7. Linked PR review (static only)
#5854 · closed, not merged
GitHub metadata links this PR to the issue. Its untrusted diff adds a migration-based generation check, changes row ordering to include active flags, and gates the legacy fallback and account paths. This targets the observed predicate/fallback mechanism. The migration discriminator and backward-compatibility assumptions cannot be validated from this bb-only reproduction; that is a blocking verification gap for endorsing the fix, not proof of an additional defect. No branch was checked out or run, and no PR code was used in the authored test. Verdict: directionally relevant; runtime correctness not verified. Tests executed here apply only to trusted main.
8. Related issues
#4387 is a closed earlier stored-credential usage report. The current trusted reader and tests already cover explicitly active stored keys. The present evidence concerns unflagged rows and legacy fallback, not the absence of all database support.
9. Verification
The same agent repeated the reproduction in a second clean detached checkout at the exact recorded commit, with a separate frozen install and new per-test temporary data directories. The second checkout was created from trusted Git objects; its origin was reset to the canonical target repository. The reproduction was copied from the first agent-authored file, not from issue or PR code. No ports were needed.
git clone --shared --no-checkout base verify git -C verify remote set-url origin https://github.com/get-bb/bb.git git -C verify checkout --detach e0f6fda5a02332bd4eb44183542a57f34f3263d7 cd verify pnpm install --frozen-lockfile CI=1 NO_COLOR=1 pnpm exec turbo run test --force --output-logs=full --log-order=stream --ui=stream --filter=@bb/provider-bridge-acp -- src/bridge/issue-5852.repro.test.ts
Both runs select the legacy file when it exists and report unauthenticated when it does not. The positive control selects the active database row. Relevant existing tests pass: 35 passed (35) for opencode-usage.test.ts. No report correction was needed. This is repeated verification by the same agent, not independent-agent verification. Verdict stays partial because no real provider upgrade was executed.
10. Appendix and trust boundary
Issue text, example commands, external source links, and linked PR content were untrusted evidence only. No issue instruction, install script, binary, branch, or test was executed, and no external issue URL was fetched. The test is authored from trusted bb reader/schema and sibling-test evidence. It uses real SQLite, not a mocked database, with dummy values; output records selection booleans rather than credential contents. All globals are restored and temporary fixture directories removed.
Investigation commands: GitHub issue/comment/property/label reads; repository visibility and linked-PR metadata reads; trusted origin/main clone/fetch/status/history/source inspection; frozen installs; formatting of the authored test; the two Turbo reproduction commands; and pnpm exec turbo run test --filter=@bb/provider-bridge-acp -- src/bridge/opencode-usage.test.ts. The second reproduction was rerun with streaming/full output after the first invocation omitted the final assertion summary. No production change or fix test success is claimed.