openai/codex · error · anyhow::Error

API key may only contain ASCII letters, numbers, '-' or '_'

Error message

API key may only contain ASCII letters, numbers, '-' or '_'

What it means

After the Bearer prefix is stripped and newlines trimmed, validate_auth_header_bytes requires every remaining byte to be an ASCII letter, digit, '-' or '_' (equivalent to ^[A-Za-z0-9_-]+$). Any other character - quotes, dots, '+', '/', '=', spaces, NUL, or UTF-8 - fails validation, and read_auth_header_with zeroizes the buffer and returns this error.

Source

Thrown at codex-rs/responses-api-proxy/src/read_api_key.rs:216

    }

    let _ = unsafe { mlock(start as *const c_void, size) };
}

#[cfg(not(unix))]
fn mlock_str(_value: &str) {}

/// The key should match /^[A-Za-z0-9\-_]+$/. Ensure there is no funny business
/// with NUL characters and whatnot.
fn validate_auth_header_bytes(key_bytes: &[u8]) -> Result<()> {
    if key_bytes
        .iter()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
    {
        return Ok(());
    }

    Err(anyhow!(
        "API key may only contain ASCII letters, numbers, '-' or '_'"
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::VecDeque;
    use std::io;

    #[test]
    fn reads_key_with_no_newlines() {
        let mut sent = false;
        let result = read_auth_header_with(|buf| {
            if sent {
                return Ok(0);
            }
            let data = b"sk-abc123";

View on GitHub (pinned to 339751715c)

Solutions

  1. Pipe the environment variable verbatim: printenv OPENAI_API_KEY | codex responses-api-proxy - no shell quoting artifacts
  2. Validate first: [[ "$OPENAI_API_KEY" =~ ^[A-Za-z0-9_-]+$ ]] || exit 1
  3. If the provider's key format uses other punctuation, it is unsupported by this proxy - transform it upstream or request support

Example fix

# before: quotes and dots are data
echo '"sk-proj.abc123"' | codex responses-api-proxy ...
# after: raw [A-Za-z0-9_-]+ key
printenv OPENAI_API_KEY | codex responses-api-proxy ...
Defensive patterns

Strategy: validation

Validate before calling

case "$OPENAI_API_KEY" in
  ''|*[!A-Za-z0-9_-]*) echo 'key contains characters outside [A-Za-z0-9_-]' >&2; exit 1;;
esac
printenv OPENAI_API_KEY | codex responses-api-proxy "$@"

Prevention

When it happens

Trigger: Piping a value with characters outside the whitelist: data containing literal quote characters, JWT-style tokens with dots, base64 values with +, /, or = padding, JSON objects, or any binary input.

Common situations: Keys wrapped in extra quoting so the quotes become part of the data; provider tokens using punctuation beyond hyphen/underscore; accidentally piping a config file; values with interior whitespace or tabs.

Related errors


AI-assisted analysis of openai/codex@339751715c (2026-08-25). Data as JSON: /api/errors/b1a9b56dabee9637. Report an issue: GitHub.