Skip to content

Commit 27851d1

Browse files
committed
fix(reasoning): hash the resolved wire credential for refusal scoping
The catalog path carries the configured apiKey expression while the request path carries the resolved secret, so a refusal learned under the resolved-secret hash was looked up under the reference-string hash and never applied for keychain/env users. credentialIdentity now resolves the configured expression (_apiKeyAttempt.reference on the request path, apiKey on the catalog path) before hashing, so both sides bind learned refusals to the same wire credential. The read-path resolver moves to the leaf module api-key-resolve so reasoning-metadata can import it without the ../config barrel cycle.
1 parent 421909a commit 27851d1

4 files changed

Lines changed: 248 additions & 112 deletions

File tree

‎src/providers/api-key-resolve.ts‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/**
2+
* Read-path for provider key material: env references, keychain references, or the literal
3+
* value.
4+
*
5+
* Leaf module on purpose: reasoning-metadata.ts imports resolveProviderApiKey() here so a
6+
* learned-refusal identity can hash the same credential the wire sends. key-store.ts needs
7+
* the ../config barrel for the write path (saveConfigPreservingClaudeCode), and importing it
8+
* from reasoning-metadata would close the cycle the reasoning-metadata header warns about.
9+
* resolveEnvValue comes from ../config/proxy-env for the same reason.
10+
*
11+
* `config.json` keeps only a reference (`keychain:<provider>` for the active key,
12+
* `keychain:<provider>/<pool id>` for pool entries); the secret lives in the OS credential store
13+
* under one service name. Reads are synchronous on purpose: `routedProviderConfig` and the
14+
* quota/compaction/catalog callers are all sync, and `@napi-rs/keyring` ships a sync `Entry`.
15+
*
16+
* Policy: a reference that cannot be resolved fails closed (no key) and is warned once per
17+
* account; nothing ever rewrites plaintext into config or its backups.
18+
*/
19+
import { createRequire } from "node:module";
20+
import { resolveEnvValue } from "../config/proxy-env";
21+
import type { OcxProviderConfig } from "../types";
22+
23+
export const KEYCHAIN_REFERENCE_PREFIX = "keychain:";
24+
export const PROVIDER_KEYCHAIN_SERVICE = "opencodex.provider-api-key.v1";
25+
26+
export interface ProviderKeychainEntry {
27+
getPassword(): string | null;
28+
setPassword(password: string): void;
29+
deletePassword(): boolean;
30+
}
31+
32+
export type ProviderKeychainEntryFactory = (service: string, account: string) => ProviderKeychainEntry;
33+
34+
const nodeRequire = createRequire(import.meta.url);
35+
36+
function defaultEntryFactory(service: string, account: string): ProviderKeychainEntry {
37+
const { Entry } = nodeRequire("@napi-rs/keyring") as { Entry: new (s: string, a: string) => ProviderKeychainEntry };
38+
return new Entry(service, account);
39+
}
40+
41+
let entryFactory: ProviderKeychainEntryFactory = defaultEntryFactory;
42+
const resolvedCache = new Map<string, string>();
43+
const warnedAccounts = new Set<string>();
44+
45+
/** Test seam: swap the OS entry for an in-memory one and drop caches. */
46+
export function setProviderKeychainEntryFactoryForTests(factory: ProviderKeychainEntryFactory | null): void {
47+
entryFactory = factory ?? defaultEntryFactory;
48+
resolvedCache.clear();
49+
warnedAccounts.clear();
50+
}
51+
52+
/** Write-path seam: a store/restore mutated secrets, so cached reads and warnings are stale. */
53+
export function invalidateResolvedProviderKeyCache(): void {
54+
resolvedCache.clear();
55+
warnedAccounts.clear();
56+
}
57+
58+
export function isKeychainReference(value: string | undefined): value is string {
59+
return typeof value === "string" && value.startsWith(KEYCHAIN_REFERENCE_PREFIX) && value.length > KEYCHAIN_REFERENCE_PREFIX.length;
60+
}
61+
62+
export function keychainAccount(reference: string): string {
63+
return reference.slice(KEYCHAIN_REFERENCE_PREFIX.length);
64+
}
65+
66+
/**
67+
* A reference belongs to `name` only when its account is that provider's own active account
68+
* or one of its pool accounts. `storeProviderKeyInKeychain` writes exactly those two shapes,
69+
* so anything else in a provider's config names another provider's secret.
70+
*/
71+
export function keychainReferenceBelongsToProvider(reference: string, name: string): boolean {
72+
const account = keychainAccount(reference);
73+
return account === name || account.startsWith(`${name}/`);
74+
}
75+
76+
/** Entry for `account` under the provider-key service; read and write paths share the factory. */
77+
export function providerKeychainEntry(account: string): ProviderKeychainEntry {
78+
return entryFactory(PROVIDER_KEYCHAIN_SERVICE, account);
79+
}
80+
81+
function readKeychain(account: string): string | undefined {
82+
const cached = resolvedCache.get(account);
83+
if (cached !== undefined) return cached;
84+
try {
85+
const value = providerKeychainEntry(account).getPassword();
86+
if (typeof value === "string" && value.trim()) {
87+
resolvedCache.set(account, value);
88+
return value;
89+
}
90+
} catch {
91+
// fall through to the single warning below
92+
}
93+
if (!warnedAccounts.has(account)) {
94+
warnedAccounts.add(account);
95+
console.warn(`[opencodex] provider key reference keychain:${account} could not be read from the OS keychain; requests for this provider have no credential until the keychain is available (no plaintext fallback)`);
96+
}
97+
return undefined;
98+
}
99+
100+
/**
101+
* Single resolver for provider key material: env references, keychain references, or the
102+
* literal value. Every request-time read of `apiKey` goes through here.
103+
*/
104+
export function resolveProviderApiKey(value: string | undefined): string | undefined {
105+
if (!value) return undefined;
106+
if (isKeychainReference(value)) return readKeychain(keychainAccount(value));
107+
return resolveEnvValue(value);
108+
}
109+
110+
export type ProviderKeyStoreKind = "keychain" | "env" | "file" | "none";
111+
112+
export function providerKeyStoreKind(provider: Pick<OcxProviderConfig, "apiKey"> | undefined): ProviderKeyStoreKind {
113+
const key = provider?.apiKey;
114+
if (!key) return "none";
115+
if (isKeychainReference(key)) return "keychain";
116+
if (/^\$\{?\w+\}?$/.test(key)) return "env";
117+
return "file";
118+
}
119+
120+
/** Probe the OS keychain with a throwaway account: write, read back, delete. */
121+
export function probeProviderKeychain(): { available: true } | { available: false; reason: string } {
122+
const account = `probe-${process.pid}-${Date.now()}`;
123+
try {
124+
const entry = providerKeychainEntry(account);
125+
entry.setPassword("ok");
126+
const back = entry.getPassword();
127+
try { entry.deletePassword(); } catch { /* best effort */ }
128+
if (back !== "ok") return { available: false, reason: "keychain read-back did not match" };
129+
return { available: true };
130+
} catch (error) {
131+
return { available: false, reason: error instanceof Error ? error.message : "keychain unavailable" };
132+
}
133+
}

‎src/providers/key-store.ts‎

Lines changed: 34 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,34 @@
1-
import { createRequire } from "node:module";
21
import { resolveEnvValue, saveConfigPreservingClaudeCode } from "../config";
32
import type { OcxConfig, OcxProviderConfig } from "../types";
43
import type { ProviderRegistryEntry } from "./registry";
4+
import {
5+
KEYCHAIN_REFERENCE_PREFIX,
6+
invalidateResolvedProviderKeyCache,
7+
isKeychainReference,
8+
keychainAccount,
9+
keychainReferenceBelongsToProvider,
10+
probeProviderKeychain,
11+
providerKeychainEntry,
12+
} from "./api-key-resolve";
13+
14+
// The read-path (reference predicates, the OS entry factory, resolveProviderApiKey, the probe
15+
// and the kind classification) lives in ./api-key-resolve -- a leaf module that
16+
// reasoning-metadata can also import without pulling the ../config barrel into its
17+
// cycle-sensitive graph. Re-exported here so existing key-store consumers keep working.
18+
export {
19+
KEYCHAIN_REFERENCE_PREFIX,
20+
PROVIDER_KEYCHAIN_SERVICE,
21+
isKeychainReference,
22+
probeProviderKeychain,
23+
providerKeyStoreKind,
24+
resolveProviderApiKey,
25+
setProviderKeychainEntryFactoryForTests,
26+
} from "./api-key-resolve";
27+
export type {
28+
ProviderKeychainEntry,
29+
ProviderKeychainEntryFactory,
30+
ProviderKeyStoreKind,
31+
} from "./api-key-resolve";
532

633
/** Shared with routing: a key-mode override is effective only while its key resolves. */
734
export function providerUsesKeyAuthOverride(
@@ -27,109 +54,8 @@ export function providerUsesKeyAuthOverride(
2754
* (headless service, locked session) refuses rather than half-migrating.
2855
*/
2956

30-
export const KEYCHAIN_REFERENCE_PREFIX = "keychain:";
31-
export const PROVIDER_KEYCHAIN_SERVICE = "opencodex.provider-api-key.v1";
32-
33-
export interface ProviderKeychainEntry {
34-
getPassword(): string | null;
35-
setPassword(password: string): void;
36-
deletePassword(): boolean;
37-
}
38-
39-
export type ProviderKeychainEntryFactory = (service: string, account: string) => ProviderKeychainEntry;
40-
41-
const nodeRequire = createRequire(import.meta.url);
42-
43-
function defaultEntryFactory(service: string, account: string): ProviderKeychainEntry {
44-
const { Entry } = nodeRequire("@napi-rs/keyring") as { Entry: new (s: string, a: string) => ProviderKeychainEntry };
45-
return new Entry(service, account);
46-
}
47-
48-
let entryFactory: ProviderKeychainEntryFactory = defaultEntryFactory;
49-
const resolvedCache = new Map<string, string>();
50-
const warnedAccounts = new Set<string>();
51-
52-
/** Test seam: swap the OS entry for an in-memory one and drop caches. */
53-
export function setProviderKeychainEntryFactoryForTests(factory: ProviderKeychainEntryFactory | null): void {
54-
entryFactory = factory ?? defaultEntryFactory;
55-
resolvedCache.clear();
56-
warnedAccounts.clear();
57-
}
58-
59-
export function isKeychainReference(value: string | undefined): value is string {
60-
return typeof value === "string" && value.startsWith(KEYCHAIN_REFERENCE_PREFIX) && value.length > KEYCHAIN_REFERENCE_PREFIX.length;
61-
}
62-
63-
function keychainAccount(reference: string): string {
64-
return reference.slice(KEYCHAIN_REFERENCE_PREFIX.length);
65-
}
66-
67-
/**
68-
* A reference belongs to `name` only when its account is that provider's own active account
69-
* or one of its pool accounts. `storeProviderKeyInKeychain` writes exactly those two shapes,
70-
* so anything else in a provider's config names another provider's secret.
71-
*/
72-
function keychainReferenceBelongsToProvider(reference: string, name: string): boolean {
73-
const account = keychainAccount(reference);
74-
return account === name || account.startsWith(`${name}/`);
75-
}
76-
77-
function readKeychain(account: string): string | undefined {
78-
const cached = resolvedCache.get(account);
79-
if (cached !== undefined) return cached;
80-
try {
81-
const value = entryFactory(PROVIDER_KEYCHAIN_SERVICE, account).getPassword();
82-
if (typeof value === "string" && value.trim()) {
83-
resolvedCache.set(account, value);
84-
return value;
85-
}
86-
} catch {
87-
// fall through to the single warning below
88-
}
89-
if (!warnedAccounts.has(account)) {
90-
warnedAccounts.add(account);
91-
console.warn(`[opencodex] provider key reference keychain:${account} could not be read from the OS keychain; requests for this provider have no credential until the keychain is available (no plaintext fallback)`);
92-
}
93-
return undefined;
94-
}
95-
96-
/**
97-
* Single resolver for provider key material: env references, keychain references, or the
98-
* literal value. Every request-time read of `apiKey` goes through here.
99-
*/
100-
export function resolveProviderApiKey(value: string | undefined): string | undefined {
101-
if (!value) return undefined;
102-
if (isKeychainReference(value)) return readKeychain(keychainAccount(value));
103-
return resolveEnvValue(value);
104-
}
105-
106-
export type ProviderKeyStoreKind = "keychain" | "env" | "file" | "none";
107-
108-
export function providerKeyStoreKind(provider: Pick<OcxProviderConfig, "apiKey"> | undefined): ProviderKeyStoreKind {
109-
const key = provider?.apiKey;
110-
if (!key) return "none";
111-
if (isKeychainReference(key)) return "keychain";
112-
if (/^\$\{?\w+\}?$/.test(key)) return "env";
113-
return "file";
114-
}
115-
116-
/** Probe the OS keychain with a throwaway account: write, read back, delete. */
117-
export function probeProviderKeychain(): { available: true } | { available: false; reason: string } {
118-
const account = `probe-${process.pid}-${Date.now()}`;
119-
try {
120-
const entry = entryFactory(PROVIDER_KEYCHAIN_SERVICE, account);
121-
entry.setPassword("ok");
122-
const back = entry.getPassword();
123-
try { entry.deletePassword(); } catch { /* best effort */ }
124-
if (back !== "ok") return { available: false, reason: "keychain read-back did not match" };
125-
return { available: true };
126-
} catch (error) {
127-
return { available: false, reason: error instanceof Error ? error.message : "keychain unavailable" };
128-
}
129-
}
130-
13157
function writeVerified(account: string, secret: string): void {
132-
const entry = entryFactory(PROVIDER_KEYCHAIN_SERVICE, account);
58+
const entry = providerKeychainEntry(account);
13359
entry.setPassword(secret);
13460
if (entry.getPassword() !== secret) throw new Error(`keychain read-back mismatch for ${account}`);
13561
}
@@ -177,13 +103,12 @@ export function storeProviderKeyInKeychain(config: OcxConfig, name: string): { o
177103
}
178104
} catch (error) {
179105
for (const account of written) {
180-
try { entryFactory(PROVIDER_KEYCHAIN_SERVICE, account).deletePassword(); } catch { /* best effort */ }
106+
try { providerKeychainEntry(account).deletePassword(); } catch { /* best effort */ }
181107
}
182108
return { ok: false, error: `OS keychain write failed: ${error instanceof Error ? error.message : "unknown"}`, status: 503 };
183109
}
184110
for (const apply of planned) apply();
185-
resolvedCache.clear();
186-
warnedAccounts.clear();
111+
invalidateResolvedProviderKeyCache();
187112
saveConfigPreservingClaudeCode(config);
188113
return { ok: true, moved: written.length };
189114
}
@@ -211,7 +136,7 @@ export function restoreProviderKeyFromKeychain(config: OcxConfig, name: string):
211136
const account = keychainAccount(ref);
212137
if (resolved.has(account)) continue;
213138
let value: string | null = null;
214-
try { value = entryFactory(PROVIDER_KEYCHAIN_SERVICE, account).getPassword(); } catch { value = null; }
139+
try { value = providerKeychainEntry(account).getPassword(); } catch { value = null; }
215140
if (!value) return { ok: false, error: `OS keychain has no readable secret for ${ref}; config left unchanged`, status: 503 };
216141
resolved.set(account, value);
217142
}
@@ -220,10 +145,9 @@ export function restoreProviderKeyFromKeychain(config: OcxConfig, name: string):
220145
}
221146
if (isKeychainReference(provider.apiKey)) provider.apiKey = resolved.get(keychainAccount(provider.apiKey))!;
222147
for (const account of resolved.keys()) {
223-
try { entryFactory(PROVIDER_KEYCHAIN_SERVICE, account).deletePassword(); } catch { /* best effort */ }
148+
try { providerKeychainEntry(account).deletePassword(); } catch { /* best effort */ }
224149
}
225-
resolvedCache.clear();
226-
warnedAccounts.clear();
150+
invalidateResolvedProviderKeyCache();
227151
saveConfigPreservingClaudeCode(config);
228152
return { ok: true, restored: resolved.size };
229153
}

‎src/providers/reasoning-metadata.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { join } from "node:path";
2727
import { atomicWriteFile } from "../config/atomic-write";
2828
import { getConfigDir } from "../config/paths";
2929
import type { OcxProviderConfig } from "../types";
30+
import { resolveProviderApiKey } from "./api-key-resolve";
3031

3132
const FILENAME = "reasoning-metadata-cache.json";
3233
const SUPPORT_FILENAME = "reasoning-support-cache.json";
@@ -164,10 +165,20 @@ function modelLadderValue(
164165
* Bind learned capability to the credential that supplied the evidence. A digest keeps the
165166
* credential itself out of the persisted cache while remaining stable across restarts and key
166167
* selection. Providers without key-auth identity may use metadata, but cannot teach the cache.
168+
*
169+
* The hash input is the resolved wire credential, not the configured expression: the catalog
170+
* path carries the raw config string in apiKey (a keychain:/env reference stays unresolved
171+
* there), while the request path carries the resolved secret in apiKey and the configured
172+
* expression in _apiKeyAttempt.reference. Resolving the configured expression on both sides
173+
* hashes the same secret the upstream sees, so a refusal learned at request time also clamps
174+
* the catalog ladder for keychain/env users -- and a rotation behind a stable reference
175+
* starts clean instead of inheriting the previous credential's refusals.
167176
*/
168177
function credentialIdentity(provider: OcxProviderConfig): string | undefined {
169-
if (typeof provider.apiKey !== "string" || provider.apiKey.length === 0) return undefined;
170-
return createHash("sha256").update(provider.apiKey).digest("hex");
178+
const configured = provider._apiKeyAttempt?.reference ?? provider.apiKey;
179+
const resolved = resolveProviderApiKey(configured);
180+
if (typeof resolved !== "string" || resolved.length === 0) return undefined;
181+
return createHash("sha256").update(resolved).digest("hex");
171182
}
172183

173184
/** JSON encoding avoids delimiter ambiguity in provider, model, and effort identifiers. */

0 commit comments

Comments
 (0)