DEV Community

Darkø Tasevski
Darkø Tasevski

Posted on Originally published at darkotasevski.dev

Letting a coding agent run live API-key checks without seeing the keys

The next time an agent has to check a real API key I'll want this script again, so here is how I let a coding agent call OpenAI, Anthropic, Gemini and OpenRouter with live keys while the keys stay out of everything the agent records.

I'm building a reading app that lets you bring your own AI key, and the feature I was working on checks a key with the provider before saving it, so that a typo'd key gets rejected on the spot instead of failing later in the middle of a summary. The check itself is simple (call a cheap metadata endpoint and look at the status code), but the code that maps those status codes to "bad key", "no permission" or "unknown model" rested on a handful of assumptions about what each provider sends back, and some of those came from community examples rather than the docs, such as OpenAI's invalid_api_key error code or Gemini answering a bad key with a 400 instead of a 401. The only way to settle them was to call the real APIs with real keys.

The plan that made it a chore

The plan I wrote together with the agent took it as a given that the agent should never touch a real key, which is a fair rule, so the live check was written as a table of curl commands for me to run in a separate terminal and type the status codes back into the chat, which meant four providers with three or so cases each and swapping headers and model names by hand for every one, the kind of task you keep putting off until tomorrow :|

What I'd missed is that the rule worth keeping is about where the key ends up, and running the call doesn't break it by itself. The key has to stay out of the transcript (which gets saved, replayed into subagents and quoted in handoff notes), out of the process list (where other processes running as you can read any argument with ps while the command runs) and out of the output, and as long as a script keeps it out of all three, the agent can run that script itself.

Secret references instead of keys

The keys live in 1Password, so instead of handing the agent a key we can hand it an op:// secret reference, which is just a path to a field in a vault item. I wrote a bit about these references in the post on MCP server credentials, and the same op run does the work here. The agent writes an env file of references:

OPENAI_API_KEY="op://Agent test keys/OpenAI/credential"
ANTHROPIC_API_KEY="op://Agent test keys/Anthropic/credential"
GEMINI_API_KEY="op://Agent test keys/Gemini/credential"
OPENROUTER_API_KEY="op://Agent test keys/OpenRouter/credential"
Enter fullscreen mode Exit fullscreen mode

(The vault and item names here are made up, and the values are quoted because the vault name has spaces in it.)

Give the agent a vault of its own. A reference is useless to someone without your 1Password, but it doesn't keep the agent out, because the same unlocked 1Password that lets the agent's shell run op run also lets it run op read op://…, whose output isn't masked. I ran this with the desktop app's CLI integration and the test keys in my main vault, and with that integration an authorized op can read every vault on the account, so the keys stayed out of the transcript only because the script never printed them and the agent never went looking. What I'd change next time is a 1Password service account with read access to a vault that holds only the test keys (op service-account create agent-test-keys --vault "Agent test keys:read_items"), with its token exported as OP_SERVICE_ACCOUNT_TOKEN in the agent's environment from outside the chat, so a stray op read could reach the test keys and nothing else.

Then the agent runs the probe script under op run (with the desktop app integration, the first op run in a session asks you to approve it in 1Password, so you need to be at the machine for that one):

op run --env-file=./keys.env -- ./probe.sh
Enter fullscreen mode Exit fullscreen mode

op run swaps each reference for the real value in the script's environment and masks secrets in its output, both covered in more detail in the MCP post, and since the masking only matches the exact secret (a key printed in pieces or encoded gets through), the script below is written to never print one in the first place.

Keeping the key off the command line

The obvious way to call an API with curl is curl -H "Authorization: Bearer $OPENAI_API_KEY" ..., and that puts the key in curl's arguments, which other processes running as you can read with ps for as long as the request runs. curl can read headers from a file instead, and -H @- means "read them from stdin", so we can pipe the header in:

printf '%s\n' "Authorization: Bearer $OPENAI_API_KEY" \
  | curl -s -o /dev/null -w '%{http_code}' -H @- https://api.openai.com/v1/models/gpt-4.1
Enter fullscreen mode Exit fullscreen mode

printf here has to be bash's builtin, not /usr/bin/printf. bash still forks a subshell for its side of the pipe, but a builtin never execs a separate program, so the expanded key never becomes anyone's argument list, while the external binary would get the key as an argument and you'd have moved the leak from curl to printf. On curl 8.3 or newer there's also --variable %OPENAI_API_KEY --expand-header 'Authorization: Bearer {{OPENAI_API_KEY}}', which has curl read the variable itself and needs no pipe at all, but -H @- works back to curl 7.55, so it's the one I'd reach for first.

Gemini's docs often put the key in the URL as ?key=…, which lands it right back in curl's arguments, so the script sends it in an x-goog-api-key header, the same way the other three send theirs.

The full script prints only what we need, which is the model it picked, the status code and the provider's error code, and never the response body as a whole, since some providers echo part of the key back in their error messages. It needs jq, and all four references have to be in the env file, because set -u stops the run on the first one that's missing:

#!/bin/bash
set -u
W=$(mktemp -d); trap 'rm -rf "$W"' EXIT

probe() { # label url header...
  local label=$1 url=$2; shift 2
  local code ec
  code=$(printf '%s\n' "$@" | curl -s --max-time 20 -o "$W/b" -w '%{http_code}' -H @- "$url")
  ec=$(jq -r '.error.code // .error.status // .error.type // "none"' "$W/b" 2>/dev/null || echo non-json)
  echo "$label: $code $ec"
  rm -f "$W/b"
}

firstid() { # url jq-filter header...
  local url=$1 filter=$2; shift 2
  printf '%s\n' "$@" | curl -s --max-time 20 -H @- "$url" | jq -r "$filter" 2>/dev/null
}

need() { [[ -n $2 && $2 != null ]] || { echo "no $1 model picked" >&2; exit 1; }; }

OA="Authorization: Bearer $OPENAI_API_KEY"
AN="x-api-key: $ANTHROPIC_API_KEY"; AV="anthropic-version: 2023-06-01"
GE="x-goog-api-key: $GEMINI_API_KEY"
OR="Authorization: Bearer $OPENROUTER_API_KEY"
GB=https://generativelanguage.googleapis.com/v1beta/models

OAM=$(firstid https://api.openai.com/v1/models '[.data[].id|select(test("^gpt-"))]|sort|.[0]' "$OA")
ANM=$(firstid https://api.anthropic.com/v1/models '.data[0].id' "$AN" "$AV")
GEM=$(firstid $GB '[.models[].name|select(test("gemini"))]|.[0]|sub("^models/";"")' "$GE")
need OpenAI "$OAM"; need Anthropic "$ANM"; need Gemini "$GEM"
echo "models: openai=$OAM anthropic=$ANM gemini=$GEM"

probe "OpenAI real"        "https://api.openai.com/v1/models/$OAM" "$OA"
probe "OpenAI unknown"     https://api.openai.com/v1/models/no-such-model-xyz "$OA"
probe "OpenAI bad key"     "https://api.openai.com/v1/models/$OAM" "Authorization: Bearer sk-invalid000000000000"
probe "Anthropic real"     "https://api.anthropic.com/v1/models/$ANM" "$AN" "$AV"
probe "Anthropic unknown"  https://api.anthropic.com/v1/models/no-such-model-xyz "$AN" "$AV"
probe "Anthropic bad key"  "https://api.anthropic.com/v1/models/$ANM" "x-api-key: sk-ant-invalid000000000000" "$AV"
probe "Gemini real"        "$GB/$GEM" "$GE"
probe "Gemini unknown"     "$GB/no-such-model-xyz" "$GE"
probe "Gemini bad key"     "$GB/$GEM" "x-goog-api-key: AIzaInvalid000000000000"
probe "OpenRouter real"    https://openrouter.ai/api/v1/key "$OR"
probe "OpenRouter bad key" https://openrouter.ai/api/v1/key "Authorization: Bearer sk-or-v1-invalid000000000000"
Enter fullscreen mode Exit fullscreen mode

probe takes any number of header lines, which is how Anthropic gets its second anthropic-version header without a special case. The "bad key" rows use a made-up key with each provider's prefix, so they test what a provider says to a key it doesn't recognize, without needing a real one to break. Instead of hardcoding model ids, firstid asks each provider for its own model list and takes the first match, and need stops the run if a pick comes back empty, since an empty id would turn /models/$OAM into the list endpoint, which answers a valid key with a 200, so the "real" row would pass without checking any model. --max-time is there because an agent running this unattended would otherwise wait on a stalled connection forever.

If something goes wrong, don't debug it with bash -x, curl -v, --trace or --trace-ascii, since xtrace prints the expanded header assignments and the curl options print the request headers, with only op run's masking between those and the transcript. Masking won't catch a key in --trace's hex dump, or one that --trace-ascii wraps across two lines, so swap in the made-up keys first if you need any of them.

What came back

All eleven probes ran in one pass, and the transcript ended up with nothing in it but op:// references and this:

models: openai=gpt-4.1 anthropic=claude-fable-5-2 gemini=gemini-2.5-flash-preview-tts
OpenAI real: 200 none
OpenAI unknown: 404 model_not_found
OpenAI bad key: 401 invalid_api_key
Anthropic real: 200 none
Anthropic unknown: 404 not_found_error
Anthropic bad key: 401 authentication_error
Gemini real: 200 none
Gemini unknown: 404 404
Gemini bad key: 400 400
OpenRouter real: 200 none
OpenRouter bad key: 401 401
Enter fullscreen mode Exit fullscreen mode

Gemini and OpenRouter put the HTTP status itself in error.code, so the jq fallback never reaches the readable name and their lines just repeat the number. For Gemini the name lives in error.status (INVALID_ARGUMENT, with API_KEY_INVALID as the reason in the error details), so if you care about the name more than the status, put .error.status first in the filter.

Every case the script ran matched what the plan assumed, including the two that came from community examples, so those parts of the status mapping didn't need a change. It doesn't cover everything the app maps, though, since nothing here produced a 403 for "no permission", OpenRouter has no unknown-model row, and a 200 from a metadata endpoint only says the key authenticates, not that it has quota left or is allowed to generate. The model firstid picked for Gemini was a text-to-speech preview model, which still proved the endpoint and the header but not the model the app would really use, and the OpenAI pick is just the first gpt- id in alphabetical order, so if the model matters to your check, filter for it instead of taking the first one.

The keys were separate test keys that expire, and every call went to a model-list, model-metadata or key-info endpoint (GET /models, GET /models/{model}, or OpenRouter's GET /api/v1/key), so nothing ever hit a generation endpoint or spent money. The keys do sit in the environment of the script and of curl while they run, where any process running as you could read them, so the script only stops a key from landing in the transcript, the argument list or the output by mistake, and only something like the service account above would limit an agent that goes looking.

The way to let an agent run live key checks itself, then, is to get the keys to the script as op:// references through op run, send each header to curl on stdin from bash's builtin printf, and have the script print nothing but model ids, status codes and error codes, which keeps the keys out of the transcript, the argument list and the output while the agent does the work, and a service account that can read only the test keys' vault is what keeps an agent that does go looking away from everything else.

Top comments (0)