Skip to content

Commit ca8c5d3

Browse files
committed
merge(dev): take upstream Path-casing release-helper shim fix
2 parents 51d9c56 + afe2aa3 commit ca8c5d3

8 files changed

Lines changed: 188 additions & 8 deletions

‎src/cli/doctor.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -307,13 +307,47 @@ export type ConfiguredProxyDiagnostic = {
307307
detail: string;
308308
};
309309

310-
function envReferenceName(value: string): string | null {
310+
export function envReferenceName(value: string): string | null {
311311
const braced = value.match(/^\$\{(\w+)\}$/);
312312
if (braced) return braced[1]!;
313313
const bare = value.match(/^\$(\w+)$/);
314314
return bare ? bare[1]! : null;
315315
}
316316

317+
export type ProviderApiKeyDiagnostic = {
318+
provider: string;
319+
envName: string;
320+
detail: string;
321+
};
322+
323+
/** Warn when a key-auth provider's apiKey env reference resolves empty in this process. */
324+
export function collectProviderApiKeyDiagnostics(
325+
providers: Record<string, { authMode?: string; apiKey?: string }> = readConfigDiagnostics().config.providers ?? {},
326+
env: EnvMap = process.env,
327+
): ProviderApiKeyDiagnostic[] {
328+
const resolveInEnv = (value: string): string | undefined => {
329+
const name = envReferenceName(value);
330+
if (!name) return value;
331+
return env[name];
332+
};
333+
const rows: ProviderApiKeyDiagnostic[] = [];
334+
for (const [provider, config] of Object.entries(providers)) {
335+
if (config.authMode !== "key") continue;
336+
const raw = typeof config.apiKey === "string" ? config.apiKey.trim() : "";
337+
if (!raw) continue;
338+
const envName = envReferenceName(raw);
339+
if (!envName) continue;
340+
const resolved = resolveInEnv(raw);
341+
if (resolved?.trim()) continue;
342+
rows.push({
343+
provider,
344+
envName,
345+
detail: `provider ${provider}: env reference ${envName} is unset or empty in this process`,
346+
});
347+
}
348+
return rows;
349+
}
350+
317351
export function collectConfiguredProxy(): ConfiguredProxyDiagnostic {
318352
const diagnostics = readConfigDiagnostics();
319353
const rawProxy = typeof diagnostics.config.proxy === "string" ? diagnostics.config.proxy.trim() : "";
@@ -742,6 +776,16 @@ export async function runDoctor(args: string[] = []): Promise<void> {
742776
console.log("\nConfigured proxy (value hidden)");
743777
console.log(` ${configuredProxy.present ? "set " : "unset "} ${configuredProxy.key} (${configuredProxy.source}; ${configuredProxy.detail})`);
744778

779+
const providerApiKeys = collectProviderApiKeyDiagnostics(doctorConfig.providers);
780+
console.log("\nProvider API keys (value hidden)");
781+
if (providerApiKeys.length === 0) {
782+
console.log(" ok no empty env-referenced provider keys detected in this process");
783+
} else {
784+
for (const row of providerApiKeys) {
785+
console.log(` !! ${row.detail}`);
786+
}
787+
}
788+
745789
console.log("\nRunning proxy process proxy env (presence only)");
746790
if (runningProxyEnv.status === "not_running") {
747791
console.log(" -- no running ocx proxy process found");
@@ -825,6 +869,9 @@ export async function runDoctor(args: string[] = []): Promise<void> {
825869
serviceViable: startup.serviceViable,
826870
});
827871
if (proxyDown) hints.push(proxyDown);
872+
for (const row of providerApiKeys) {
873+
hints.push(`${row.detail}. Set ${row.envName} in the shell that starts the proxy, or store a literal key in config (value hidden here).`);
874+
}
828875
const anyDrvfs = paths.some(p => detectFsType(p.path, mounts).isDrvfs || detectFsType(p.path, mounts).isMntDrive);
829876
const noProxy = currentProxyEnv.every(p => !p.present) && !configuredProxy.present;
830877
if (!startup.rebootSafe) {

‎src/lib/destination-policy.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,13 +130,20 @@ function registryAllowsPrivateNetwork(name: string): boolean {
130130
return getProviderRegistryEntry(name)?.allowPrivateNetworkByDefault === true;
131131
}
132132

133+
/** True when the provider config or registry default admits private/loopback destinations. */
134+
export function providerAllowsPrivateNetwork(
135+
name: string,
136+
provider: Pick<OcxProviderConfig, "allowPrivateNetwork">,
137+
): boolean {
138+
return provider.allowPrivateNetwork === true || registryAllowsPrivateNetwork(name);
139+
}
140+
133141
export function providerDestinationConfigError(name: string, provider: Pick<OcxProviderConfig, "baseUrl" | "allowPrivateNetwork">): string | null {
134142
const assessment = assessDestination(provider.baseUrl);
135143
if (!assessment) return null;
136144
if (assessment.kind === "public" || assessment.kind === "hostname") return null;
137145
if (assessment.kind === "metadata") return "baseUrl targets a blocked metadata endpoint";
138-
if (registryAllowsPrivateNetwork(name)) return null;
139-
if (provider.allowPrivateNetwork === true) return null;
146+
if (providerAllowsPrivateNetwork(name, provider)) return null;
140147
return `baseUrl points to a ${assessment.detail}; set allowPrivateNetwork:true only for intentionally local/self-hosted providers`;
141148
}
142149

@@ -174,7 +181,7 @@ export async function providerDestinationResolvedError(
174181
if (!hostname || isIP(hostname) !== 0 || hostname === "localhost" || hostname.endsWith(".localhost")) {
175182
return null; // literals and localhost are fully handled by the sync path
176183
}
177-
if (registryAllowsPrivateNetwork(name) || provider.allowPrivateNetwork === true) return null;
184+
if (providerAllowsPrivateNetwork(name, provider)) return null;
178185
let addresses: { address: string }[];
179186
try {
180187
addresses = await lookup(hostname, { all: true, verbatim: true });

‎src/lib/provider-outbound.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { OcxProviderConfig } from "../types";
22
import {
33
assessUrlDestination,
44
DestinationDnsResolutionError,
5+
providerAllowsPrivateNetwork,
56
providerDestinationConfigError,
67
resolvePublicAddresses,
78
} from "./destination-policy";
@@ -116,7 +117,8 @@ export async function providerOutboundGet(
116117
if (assessment?.kind === "metadata" || assessment?.kind === "link-local" || assessment?.kind === "unspecified") {
117118
throw new ProviderOutboundPolicyError(`provider URL targets ${assessment.detail}`);
118119
}
119-
if (!provider.allowPrivateNetwork) {
120+
const allowPrivate = providerAllowsPrivateNetwork(name, provider);
121+
if (!allowPrivate) {
120122
const destinationError = providerDestinationConfigError(name, {
121123
baseUrl: url,
122124
allowPrivateNetwork: false,
@@ -129,11 +131,12 @@ export async function providerOutboundGet(
129131
const proxyConfigured = configuredProxyFor();
130132
const resolveAddresses = dependencies.resolveAddresses ?? resolvePublicAddresses;
131133
const pinnedGet = dependencies.pinnedGet ?? pinnedHttpGet;
134+
const allowPrivate = providerAllowsPrivateNetwork(name, provider);
132135
let resolved: Awaited<ReturnType<typeof resolvePublicAddresses>>;
133136
try {
134137
resolved = await resolveAddresses(url, {
135138
context: "provider URL",
136-
allowPrivateNetwork: provider.allowPrivateNetwork,
139+
allowPrivateNetwork: allowPrivate,
137140
});
138141
} catch (error) {
139142
const dnsResolutionFailed = error instanceof DestinationDnsResolutionError

‎src/lib/win-exec.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,18 @@ export function resolveWindowsCommand(command: string, deps: ResolveDeps = {}):
4444
if (win32.extname(command) || command.includes("\\") || command.includes("/") || win32.isAbsolute(command)) {
4545
return command;
4646
}
47-
const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
48-
for (const dir of (env.PATH ?? env.Path ?? "").split(win32.delimiter).filter(Boolean)) {
47+
// Windows environment variables are case-insensitive, and a spawned child can
48+
// arrive with `Path`, `PATH`, or both depending on who built its env. Reading
49+
// only two fixed spellings silently resolved against the wrong list once a
50+
// caller added a second casing, so match however the key is spelled.
51+
const lookup = (name: string): string | undefined => {
52+
const direct = env[name] ?? env[name.toUpperCase()] ?? env[name.toLowerCase()];
53+
if (direct !== undefined) return direct;
54+
const key = Object.keys(env).find(k => k.toLowerCase() === name.toLowerCase());
55+
return key ? env[key] : undefined;
56+
};
57+
const exts = (lookup("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
58+
for (const dir of (lookup("PATH") ?? "").split(win32.delimiter).filter(Boolean)) {
4959
for (const ext of exts) {
5060
const candidate = win32.join(dir, command + ext.toLowerCase());
5161
if (exists(candidate)) return candidate;
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { collectProviderApiKeyDiagnostics } from "../src/cli/doctor";
3+
4+
describe("doctor provider apiKey env diagnostics (#762)", () => {
5+
test("warns when a key-auth env reference resolves empty without printing secrets", () => {
6+
const rows = collectProviderApiKeyDiagnostics({
7+
openrouter: {
8+
authMode: "key",
9+
apiKey: "${OPENROUTER_API_KEY}",
10+
},
11+
}, {});
12+
expect(rows).toEqual([{
13+
provider: "openrouter",
14+
envName: "OPENROUTER_API_KEY",
15+
detail: "provider openrouter: env reference OPENROUTER_API_KEY is unset or empty in this process",
16+
}]);
17+
});
18+
19+
test("passes when the referenced env var is set", () => {
20+
const rows = collectProviderApiKeyDiagnostics({
21+
openrouter: {
22+
authMode: "key",
23+
apiKey: "${OPENROUTER_API_KEY}",
24+
},
25+
}, { OPENROUTER_API_KEY: "secret-value" });
26+
expect(rows).toEqual([]);
27+
});
28+
29+
test("ignores literal keys and non-key providers", () => {
30+
const rows = collectProviderApiKeyDiagnostics({
31+
openrouter: { authMode: "key", apiKey: "sk-live-not-an-env-ref" },
32+
openai: { authMode: "forward", apiKey: "${SHOULD_NOT_MATTER}" },
33+
}, {});
34+
expect(rows).toEqual([]);
35+
});
36+
});

‎tests/provider-outbound.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,36 @@ describe("provider outbound GET transport", () => {
9090
expect(captured.address).toBeUndefined();
9191
});
9292

93+
test("built-in ollama admits loopback discovery without an explicit allowPrivateNetwork flag (#758)", async () => {
94+
for (const key of proxyKeys) delete process.env[key];
95+
const { providerOutboundGet } = await import("../src/lib/provider-outbound");
96+
let sawAllowPrivate: boolean | undefined;
97+
const dependencies: ProviderOutboundDependencies = {
98+
resolveAddresses: mock(async (_url, options) => {
99+
sawAllowPrivate = typeof options === "object" && options?.allowPrivateNetwork === true;
100+
return {
101+
hostname: "127.0.0.1",
102+
addresses: [{ address: "127.0.0.1", family: 4 }],
103+
privateNetwork: true,
104+
};
105+
}),
106+
pinnedGet: mock(async () => new Response('{"data":[{"id":"llama"}]}', {
107+
status: 200,
108+
headers: { "content-type": "application/json" },
109+
})),
110+
};
111+
112+
const response = await providerOutboundGet(
113+
"ollama",
114+
{ baseUrl: "http://127.0.0.1:11434/v1" },
115+
"http://127.0.0.1:11434/v1/models",
116+
{},
117+
dependencies,
118+
);
119+
expect(sawAllowPrivate).toBe(true);
120+
expect(await response.json()).toEqual({ data: [{ id: "llama" }] });
121+
});
122+
93123
test("direct redirects return the same credential-safe final-URL guidance", async () => {
94124
for (const key of proxyKeys) delete process.env[key];
95125
const redirectTarget = new URL("https://final.example/v1/models?token=secret#fragment");

‎tests/release-helper.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,13 +192,33 @@ function runRelease(version: string, scenario: ReleaseScenario = {}) {
192192
installCommandShim(shimDir, name);
193193
}
194194

195+
<<<<<<< HEAD
195196
const pathPrefix = `${shimDir}${process.platform === "win32" ? ";" : ":"}${process.env.PATH ?? process.env.Path ?? ""}`;
196197
const result = spawnSync(process.execPath, [releaseScriptPath, version], {
197198
cwd: repoRoot,
198199
env: {
199200
...process.env,
200201
PATH: pathPrefix,
201202
...(process.platform === "win32" ? { Path: pathPrefix } : {}),
203+
=======
204+
// Windows names the variable `Path`, and `...process.env` copies it in under
205+
// that spelling. Adding a separate `PATH` key leaves BOTH present, and which
206+
// one wins is not something this test should be gambling on — the child saw
207+
// the real git instead of the shim, so the branch guard read `dev` and the
208+
// script aborted before logging a single call. Strip every case variant, then
209+
// set exactly one.
210+
const inheritedEnv = Object.fromEntries(
211+
Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "path"),
212+
);
213+
const pathKey = process.platform === "win32" ? "Path" : "PATH";
214+
const pathValue = `${shimDir}${process.platform === "win32" ? ";" : ":"}${process.env.PATH ?? process.env.Path ?? ""}`;
215+
216+
const result = spawnSync(process.execPath, [releaseScriptPath, version], {
217+
cwd: repoRoot,
218+
env: {
219+
...inheritedEnv,
220+
[pathKey]: pathValue,
221+
>>>>>>> upstream/dev
202222
FAKE_RELEASE_LOG: logPath,
203223
FAKE_GIT_BRANCH: scenario.branch ?? "main",
204224
FAKE_GIT_HEAD_SHA: scenario.headSha ?? "abc123def456",

‎tests/win-exec.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,33 @@ describe("resolveWindowsCommand", () => {
6060
expect(resolveWindowsCommand("claude", { env, exists: () => false })).toBe("claude");
6161
expect(resolveWindowsCommand("claude", { env: {}, exists: () => true })).toBe("claude");
6262
});
63+
64+
/**
65+
* Windows env vars are case-insensitive and a spawned child can arrive with
66+
* `Path`, `PATH`, or both — `{...process.env, PATH: x}` on Windows leaves the
67+
* inherited `Path` in place beside the new `PATH`. Reading two fixed spellings
68+
* resolved against whichever happened to be listed first, which is how a test
69+
* that put shims on PATH still reached the real `git`: the branch guard then
70+
* read the wrong branch and the script aborted before running anything.
71+
*/
72+
test("PATH and PATHEXT resolve whatever casing the child was handed", () => {
73+
const exists = (p: string) => p === "D:\\shims\\git.cmd";
74+
75+
for (const pathKey of ["PATH", "Path", "path"]) {
76+
const cased = { [pathKey]: "D:\\shims", PATHEXT: ".COM;.EXE;.BAT;.CMD" };
77+
expect(resolveWindowsCommand("git", { env: cased, exists })).toBe("D:\\shims\\git.cmd");
78+
}
79+
80+
for (const extKey of ["PATHEXT", "PathExt", "pathext"]) {
81+
const cased = { Path: "D:\\shims", [extKey]: ".COM;.EXE;.BAT;.CMD" };
82+
expect(resolveWindowsCommand("git", { env: cased, exists })).toBe("D:\\shims\\git.cmd");
83+
}
84+
85+
// Both spellings present: the shim directory must still win, whichever key
86+
// the platform ends up honouring.
87+
const both = { Path: "D:\\shims", PATH: "D:\\shims", PATHEXT: ".CMD" };
88+
expect(resolveWindowsCommand("git", { env: both, exists })).toBe("D:\\shims\\git.cmd");
89+
});
6390
});
6491

6592
describe("commandInvocation", () => {

0 commit comments

Comments
 (0)