8000 fix: keep Gemini API keys out of request URLs by simon-inkie · Pull Request #5 · simon-inkie/inkie-auto-mode · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .notes/ink-927-gemini-api-key-header/SPEC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# INK-927: Gemini API key header transport

## Scope

Move the Gemini `generateContent` API key from the URL query string to the
`x-goog-api-key` header in the Cursor, Claude Code and OpenClaw adapters.

## Contract

- The Google request URL contains no `key` query parameter.
- The chosen existing credential is sent as `x-goog-api-key`.
- Existing credential precedence, request payloads, response parsing and error
behaviour remain unchanged.
- Tests capture the outgoing URL and headers and assert both the positive
header case and the absent URL-key case for all three adapters.

## Boundaries

- No benchmark files or INK-923 worktree changes.
- No live provider call before patch review and an approved non-secret route.
- No key values in source, tests, logs, commits or MR text.
- No provider, endpoint, model default or runtime configuration change.

## Verification

Run `npm test`, `npm run typecheck` and `npm run build`. Obtain focused Andor
and Aggy reviews before opening the separate INK-927 MR.
7 changes: 5 additions & 2 deletions adapters/claude-code/src/model-call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,13 @@ export const modelCall: ModelCallFn = async (options: ModelCallOptions) => {
"No GOOGLE_GENERATIVE_AI_API_KEY / GEMINI_API_KEY / GOOGLE_API_KEY in env",
);
const res = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent?key=${apiKey}`,
`https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
headers: {
"Content-Type": "application/json",
"x-goog-api-key": apiKey,
},
body: JSON.stringify({
systemInstruction: { parts: [{ text: options.system }] },
contents: options.messages.map((m) => ({
Expand Down
7 changes: 5 additions & 2 deletions adapters/cursor/src/model-call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,13 @@ export const modelCall: ModelCallFn = async (options: ModelCallOptions) => {
"No GOOGLE_GENERATIVE_AI_API_KEY / GEMINI_API_KEY / GOOGLE_API_KEY in env",
);
const res = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent?key=${apiKey}`,
`https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
headers: {
"Content-Type": "application/json",
"x-goog-api-key": apiKey,
},
body: JSON.stringify({
systemInstruction: { parts: [{ text: options.system }] },
contents: options.messages.map((m) => ({
Expand Down
101 changes: 54 additions & 47 deletions adapters/openclaw/src/plugin.ts
8000
Original file line number Diff line number Diff line change
Expand Up @@ -47,50 +47,45 @@ function resolveConfig(pluginConfig?: Record<string, unknown>): ClassifierConfig
};
}

export default definePluginEntry({
id: 'io-auto-mode',
name: 'Io Auto Mode',
description: 'Hybrid static + LLM exec and MCP security classifier.',

register(api) {
// Set log path to absolute workspace location
setLogPath(join(homedir(), '.openclaw', 'workspace', 'memory', 'auto-mode-log.jsonl'));

const modelCallFn: ModelCallFn = async (options: ModelCallOptions) => {
const [provider, ...modelParts] = options.model.split("/");
const modelId = modelParts.join("/");

// Get API key via OpenClaw runtime auth
let apiKey: string | undefined;
try {
const auth = await api.runtime.modelAuth.resolveApiKeyForProvider({
provider,
cfg: api.config,
});
apiKey = (auth as { apiKey?: string })?.apiKey;
} catch { /* fall through */ }

// Fallback to env vars. GOOGLE_GENERATIVE_AI_API_KEY is the canonical
// supported name; GEMINI_API_KEY / GOOGLE_API_KEY (the names Google's
// own SDKs auto-discover) are back-compat fallbacks.
// `||`, not `??`: these vars are routinely set-but-empty in agent
// environments, and `??` only falls through on null/undefined, so an
// empty canonical value would mask a populated fallback below it.
if (!apiKey && provider === "google")
apiKey =
process.env.GOOGLE_GENERATIVE_AI_API_KEY ||
process.env.GEMINI_API_KEY ||
process.env.GOOGLE_API_KEY;
if (!apiKey && provider === "anthropic") apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) throw new Error(`No API key for provider: ${provider}`);

try {
if (provider === "google") {
type OpenClawModelApi = Pick<OpenClawPluginApi, 'config' | 'runtime'>;

/** Build the model caller separately so its HTTP contract can be unit tested. */
export function createModelCall(api: OpenClawModelApi): ModelCallFn {
return async (options: ModelCallOptions) => {
const [provider, ...modelParts] = options.model.split("/");
const modelId = modelParts.join("/");

// Get API key via OpenClaw runtime auth
let apiKey: string | undefined;
try {
const auth = await api.runtime.modelAuth.resolveApiKeyForProvider({
provider,
cfg: api.config,
});< 8000 /span>
apiKey = (auth as { apiKey?: string })?.apiKey;
} catch { /* fall through */ }

// Fallback to env vars. GOOGLE_GENERATIVE_AI_API_KEY is the canonical
// supported name; GEMINI_API_KEY / GOOGLE_API_KEY (the names Google's
// own SDKs auto-discover) are back-compat fallbacks.
// `||`, not `??`: these vars are routinely set-but-empty in agent
// environments, and `??` only falls through on null/undefined, so an
// empty canonical value would mask a populated fallback below it.
if (!apiKey && provider === "google")
apiKey =
process.env.GOOGLE_GENERATIVE_AI_API_KEY ||
process.env.GEMINI_API_KEY ||
process.env.GOOGLE_API_KEY;
if (!apiKey && provider === "anthropic") apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) throw new Error(`No API key for provider: ${provider}`);

try {
if (provider === "google") {
const res = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent?key=${apiKey}`,
`https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
body: JSON.stringify({
systemInstruction: { parts: [{ text: options.system }] },
contents: options.messages.map((m) => ({
Expand Down Expand Up @@ -122,12 +117,24 @@ export default definePluginEntry({
return data.content?.[0]?.text ?? "";
}

throw new Error(`Unsupported provider: ${provider}`);
} catch (err) {
logDecision(options.model, { decision: 'block', stage: 'error', durationMs: 0, reason: `API call threw: ${err}` });
throw err;
}
};
throw new Error(`Unsupported provider: ${provider}`);
} catch (err) {
logDecision(options.model, { decision: 'block', stage: 'error', durationMs: 0, reason: `API call threw: ${err}` });
throw err;
}
};
}

export default definePluginEntry({
id: 'io-auto-mode',
name: 'Io Auto Mode',
description: 'Hybrid static + LLM exec and MCP security classifier.',

register(api) {
// Set log path to absolute workspace location
setLogPath(join(homedir(), '.openclaw', 'workspace', 'memory', 'auto-mode-log.jsonl'));

const modelCallFn = createModelCall(api);

// Cache user messages for transcript context
api.on('message_received', (event, _ctx) => {
Expand Down
56 changes: 43 additions & 13 deletions tests/model-call-credentials.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { test, describe, beforeEach, afterEach } from "node:test";
import { strict as assert } from "node:assert";
import { modelCall } from "../adapters/claude-code/src/model-call.js";
import { modelCall as cursorModelCall } from "../adapters/cursor/src/model-call.js";
import { createModelCall as createOpenClawModelCall } from "../adapters/openclaw/src/plugin.js";

const KEY_VARS = [
"GOOGLE_GENERATIVE_AI_API_KEY",
Expand All @@ -38,12 +39,16 @@ const KEY_VARS = [
const originalEnv: Record<string, string | undefined> = {};
const realFetch = globalThis.fetch;

/** Captures the key query param off the outgoing request, then short-circuits. */
function stubFetch(): { keys: string[] } {
const captured: { keys: string[] } = { keys: [] };
globalThis.fetch = (async (url: string | URL) => {
const match = String(url).match(/[?&]key=([^&]*)/);
captured.keys.push(match ? match[1] : "");
/** Captures outgoing request URLs and headers, then short-circuits. */
function stubFetch(): { requests: Array<{ url: string; headers: Headers }> } {
const captured: { requests: Array<{ url: string; headers: Headers }> } = {
requests: [],
};
globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
captured.requests.push({
url: String(url),
headers: new Headers(init?.headers),
});
return {
ok: true,
status: 200,
Expand All @@ -54,6 +59,16 @@ function stubFetch(): { keys: string[] } {
return captured;
}

function assertGeminiAuth(
captured: ReturnType<typeof stubFetch>,
expectedKey: string,
): void {
assert.equal(captured.requests.length, 1);
assert.equal(captured.requests[0]!.headers.get("x-goog-api-key"), expectedKey);
assert.equal(new URL(captured.requests[0]!.url).search, "");
assert.ok(!captured.requests[0]!.url.includes(expectedKey));
}

function setEnv(vars: Partial<Record<(typeof KEY_VARS)[number], string | undefined>>): void {
for (const v of KEY_VARS) {
const val = vars[v];
Expand Down Expand Up @@ -88,7 +103,7 @@ describe("model-call: Google credential resolution", () => {
setEnv({ GOOGLE_GENERATIVE_AI_API_KEY: "canonical-key" });
const cap = stubFetch();
await modelCall(OPTS);
assert.deepEqual(cap.keys, ["canonical-key"]);
assertGeminiAuth(cap, "canonical-key");
});

test("canonical key wins when every candidate is populated", async () => {
Expand All @@ -99,28 +114,28 @@ describe("model-call: Google credential resolution", () => {
});
const cap = stubFetch();
await modelCall(OPTS);
assert.deepEqual(cap.keys, ["canonical-key"]);
assertGeminiAuth(cap, "canonical-key");
});

test("an empty-string canonical var falls through to the populated legacy key", async () => {
setEnv({ GOOGLE_GENERATIVE_AI_API_KEY: "", GEMINI_API_KEY: "legacy-gemini" });
const cap = stubFetch();
await modelCall(OPTS);
assert.deepEqual(cap.keys, ["legacy-gemini"]);
assertGeminiAuth(cap, "legacy-gemini");
});

test("an empty-string GEMINI_API_KEY does not mask a populated GOOGLE_API_KEY", async () => {
setEnv({ GEMINI_API_KEY: "", GOOGLE_API_KEY: "legacy-google" });
const cap = stubFetch();
await modelCall(OPTS);
assert.deepEqual(cap.keys, ["legacy-google"]);
assertGeminiAuth(cap, "legacy-google");
});

test("legacy-only environments keep working (back-compat)", async () => {
setEnv({ GEMINI_API_KEY: "legacy-gemini" });
const cap = stubFetch();
await modelCall(OPTS);
assert.deepEqual(cap.keys, ["legacy-gemini"]);
assertGeminiAuth(cap, "legacy-gemini");
});

test("no credential at all throws naming all three accepted vars", async () => {
Expand All @@ -141,13 +156,28 @@ describe("model-call: Google credential resolution", () => {
setEnv({ GOOGLE_GENERATIVE_AI_API_KEY: "", GEMINI_API_KEY: "", GOOGLE_API_KEY: "" });
const cap = stubFetch();
await assert.rejects(() => modelCall(OPTS));
assert.deepEqual(cap.keys, [], "must not put an empty key on the wire");
assert.deepEqual(cap.requests, [], "must not put an empty key on the wire");
});

test("the cursor adapter resolves credentials identically", async () => {
setEnv({ GOOGLE_GENERATIVE_AI_API_KEY: "canonical-key", GEMINI_API_KEY: "" });
const cap = stubFetch();
await cursorModelCall(OPTS);
assert.deepEqual(cap.keys, ["canonical-key"]);
assertGeminiAuth(cap, "canonical-key");
});

test("the OpenClaw adapter sends its runtime credential only in the header", async () => {
setEnv({});
const cap = stubFetch();
const openClawModelCall = createOpenClawModelCall({
config: {},
runtime: {
modelAuth: {
resolveApiKeyForProvider: async () => ({ apiKey: "openclaw-key" }),
},
},
} as unknown as Parameters<typeof createOpenClawModelCall>[0]);
await openClawModelCall(OPTS);
assertGeminiAuth(cap, "openclaw-key");
});
});
Loading
0