Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
load("//:defs.bzl", "codex_rust_crate")
load("//bazel/rules:runtime_package.bzl", "release_binary")
codex_rust_crate(
name = "responses-api-proxy",
crate_name = "codex_responses_api_proxy",
)
release_binary(
binary = ":codex-responses-api-proxy",
)

View File

@@ -0,0 +1,39 @@
[package]
name = "codex-responses-api-proxy"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
name = "codex_responses_api_proxy"
path = "src/lib.rs"
doctest = false
[[bin]]
name = "codex-responses-api-proxy"
path = "src/main.rs"
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
bytes = { workspace = true }
clap = { workspace = true, features = ["derive"] }
codex-http-client = { workspace = true }
codex-process-hardening = { workspace = true }
ctor = { workspace = true }
http = { workspace = true }
libc = { workspace = true }
reqwest = { workspace = true, features = ["blocking", "json", "rustls-tls"] }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tiny_http = { workspace = true }
tokio = { workspace = true, features = ["rt", "time", "net"] }
url = { workspace = true }
zeroize = { workspace = true, features = ["serde"] }
[dev-dependencies]
pretty_assertions = { workspace = true }
tracing = { workspace = true }
tracing-test = { workspace = true, features = ["no-env-filter"] }

View File

@@ -0,0 +1,198 @@
# codex-responses-api-proxy
#### tl;dr:
```
# Launch the proxy, dump request/response pairs to /tmp/proxy
cd path/to/codex/codex-rs
cargo build
echo $OPENAI_API_KEY | ./target/debug/codex-responses-api-proxy \
--port 60001 \
--dump-dir /tmp/proxy
# Add this to ~/.codex/config.toml:
[model_providers.codex-responses-api-proxy]
name = 'codex-responses-api-proxy'
base_url = 'http://127.0.0.1:60001/v1'
wire_api='responses'
[profiles.proxy]
model_provider = "codex-responses-api-proxy"
# Use it
codex -p proxy
```
# Detailed docs
A strict HTTP proxy that forwards `POST /v1/responses` to the OpenAI API
(`https://api.openai.com`). It authenticates with an API key by default, or with
short-lived OpenAI credentials obtained through GitHub Actions OIDC. Other
requests are rejected with `403 Forbidden`, except for the optional shutdown
endpoint described below.
## API-key usage (default)
**IMPORTANT:** `codex-responses-api-proxy` is designed to be run by a privileged user with access to `OPENAI_API_KEY` so that an unprivileged user cannot inspect or tamper with the process. Though if `--http-shutdown` is specified, an unprivileged user _can_ make a `GET` request to `/shutdown` to shutdown the server, as an unprivileged user could not send `SIGTERM` to kill the process.
A privileged user (i.e., `root` or a user with `sudo`) who has access to `OPENAI_API_KEY` would run the following to start the server, as `codex-responses-api-proxy` reads the auth token from `stdin`:
```shell
printenv OPENAI_API_KEY | env -u OPENAI_API_KEY codex-responses-api-proxy --http-shutdown --server-info /tmp/server-info.json
```
A non-privileged user would then run Codex as follows, specifying the `model_provider` dynamically:
```shell
PROXY_PORT=$(jq .port /tmp/server-info.json)
PROXY_BASE_URL="http://127.0.0.1:${PROXY_PORT}"
codex exec -c "model_providers.openai-proxy={ name = 'OpenAI Proxy', base_url = '${PROXY_BASE_URL}/v1', wire_api='responses' }" \
-c model_provider="openai-proxy" \
'Your prompt here'
```
When the unprivileged user was finished, they could shutdown the server using `curl` (since `kill -SIGTERM` is not an option):
```shell
curl --fail --silent --show-error "${PROXY_BASE_URL}/shutdown"
```
## GitHub Actions OIDC (OpenAI API)
The proxy can exchange GitHub Actions OIDC identities for short-lived OpenAI
API service account credentials. This removes the need to store a long-lived
OpenAI API key in GitHub secrets. It requires a workflow/job with
`permissions: { id-token: write, contents: read }` and an OpenAI organization
owner to configure a workload identity provider and service account mapping.
See the [OpenAI GitHub Actions federation guide](https://developers.openai.com/api/docs/guides/workload-identity-federation/github-actions).
Set the provider audience to the exact value used by the workflow, and restrict
the mapping to trusted repository, ref, and workflow claims.
In this mode, stdin supplies GitHub's `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, **not**
the minted GitHub OIDC JWT or an OpenAI API key. The proxy needs that request
credential to request fresh subject tokens during long runs.
For the npm-installed proxy, use Node.js 24 or newer for the example below.
It sets `NODE_OPTIONS=--disable-sigusr1` to protect the launcher's credential
input from Node's debugger. Some older Node versions accepted by the npm package
do not support this option and will exit before starting the proxy. To run
without Node.js, replace `codex-responses-api-proxy` in the example with the
path to the native binary; keep the same pipe and environment handling.
Supply the audience, provider ID, and service account ID as GitHub Actions
variables (they are not secrets). Start the proxy as a privileged user, as in
the API-key example:
```bash
printenv ACTIONS_ID_TOKEN_REQUEST_TOKEN | (
exec env -u ACTIONS_ID_TOKEN_REQUEST_TOKEN -u NODE_OPTIONS \
NODE_OPTIONS=--disable-sigusr1 \
codex-responses-api-proxy \
--github-oidc \
--oidc-audience "$OPENAI_WIF_AUDIENCE" \
--identity-provider-id "$OPENAI_IDENTITY_PROVIDER_ID" \
--service-account-id "$OPENAI_SERVICE_ACCOUNT_ID" \
--github-oidc-request-url "$ACTIONS_ID_TOKEN_REQUEST_URL" \
--http-shutdown --server-info /tmp/server-info.json
)
```
All four OIDC settings are required with `--github-oidc` and are rejected
without it. Pass `--github-oidc-request-url` directly from
`ACTIONS_ID_TOKEN_REQUEST_URL` supplied by the trusted GitHub runner, as shown
above. Do not set or overwrite it from workflow inputs, repository content, or
an untrusted subprocess. The proxy sends the GitHub request credential to that
URL. It requires HTTPS and refuses redirects, but it does not verify that GitHub
owns the destination. Do not substitute an OIDC issuer or discovery URL.
In OIDC mode only the default `https://api.openai.com/v1/responses` upstream is
allowed, and redirects on both token and Responses requests are disabled.
Azure/custom provider URLs continue to work in API-key mode.
Use a real pipe for either credential type, as in the examples above. Bash
here-strings and here-documents can create a seekable temporary file containing
the credential. If you background the proxy, do not wrap the entire pipeline
in another shell: it could retain the original credential environment while
it waits.
The proxy performs an initial exchange before writing server info. It keeps
the access token in process memory, renews it using a fresh GitHub JWT before
expiry, and serializes concurrent renewals. A failed renewal fails closed with
HTTP 502; it does not reuse an expired token or replay a Responses POST. It
shares the failure with waiting requests and delays further exchange attempts
by one second, doubling after each failure up to 30 seconds. A successful
exchange resets that delay. If the Responses endpoint returns 401, the proxy
passes through that response and discards only the credential used for it;
the next request can obtain a fresh one.
The proxy never returns tokens over its local HTTP API. Token endpoint error
bodies and credential-bearing URL errors are suppressed in diagnostics.
**Caller responsibilities:** run the proxy with the existing privileged-process
protections. Remove `ACTIONS_ID_TOKEN_REQUEST_TOKEN` and
`ACTIONS_ID_TOKEN_REQUEST_URL` from the environment **before** launching Codex
or any untrusted subprocess. The proxy cannot sanitize the parent GitHub
runner's environment for other steps. Never put GitHub or OpenAI bearer tokens
in arguments, Codex config, server-info files, `GITHUB_OUTPUT`, or
`GITHUB_ENV`. Retain the same privilege separation as API-key mode. The
OIDC mode uses sensitive HTTP headers and zeroizes temporary credential
buffers; it does not make the API-key path's single static, mlocked-allocation
guarantee for tokens passing through the HTTP/JSON client.
## Behavior
- By default reads the API key from `stdin`. With `--github-oidc`, reads the GitHub OIDC request credential instead; see above.
- In API-key mode, formats the header value as `Bearer <key>` and attempts to `mlock(2)` the memory holding that header so it is not swapped to disk.
- Listens on the provided port or an ephemeral port if `--port` is not specified.
- Accepts exactly `POST /v1/responses` (no query string). The request body is forwarded to the configured upstream (by default `https://api.openai.com/v1/responses`) with `Authorization` set to the selected API key or OpenAI access token. All original request headers (except any incoming `Authorization`) are forwarded upstream, with `Host` overridden to the upstream host. For other requests, it responds with `403`, aside from the optional shutdown endpoint.
- Optionally writes a single-line JSON file with server info, currently `{ "port": <u16>, "pid": <u32> }`.
- Optionally writes request/response JSON dumps to a directory. Each accepted request gets a pair of files that share a sequence/timestamp prefix, for example `000001-1846179912345-request.json` and `000001-1846179912345-response.json`. Header values are dumped in full except `Authorization` and any header whose name includes `cookie`, which are redacted. Bodies are written as parsed JSON when possible, otherwise as UTF-8 text.
- Optional `--http-shutdown` enables `GET /shutdown` to terminate the process with exit code `0`. This allows one user (e.g., `root`) to start the proxy and another unprivileged user on the host to shut it down.
## CLI
```
codex-responses-api-proxy [--port <PORT>] [--server-info <FILE>] [--http-shutdown] [--upstream-url <URL>] [--dump-dir <DIR>]
[--github-oidc --oidc-audience <AUDIENCE> --identity-provider-id <ID>
--service-account-id <ID> --github-oidc-request-url <URL>]
```
- `--port <PORT>`: Port to bind on `127.0.0.1`. If omitted, an ephemeral port is chosen.
- `--server-info <FILE>`: If set, the proxy writes a single line of JSON with `{ "port": <PORT>, "pid": <PID> }` once listening.
- `--http-shutdown`: If set, enables `GET /shutdown` to exit the process with code `0`.
- `--upstream-url <URL>`: Absolute URL to forward requests to. Defaults to `https://api.openai.com/v1/responses`.
- `--dump-dir <DIR>`: If set, writes one request JSON file and one response JSON file per accepted proxy call under this directory. Filenames use a shared sequence/timestamp prefix so each pair is easy to correlate.
- Authentication is `Authorization: Bearer <key>` in API-key mode and `Authorization: Bearer <OpenAI access token>` in OIDC mode.
For Azure, for example (ensure your deployment accepts `Authorization: Bearer <key>`):
```shell
printenv AZURE_OPENAI_API_KEY | env -u AZURE_OPENAI_API_KEY codex-responses-api-proxy \
--http-shutdown \
--server-info /tmp/server-info.json \
--upstream-url "https://YOUR_PROJECT_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT/responses?api-version=2025-04-01-preview"
```
## Notes
- Only `POST /v1/responses` is permitted. No query strings are allowed.
- All request headers are forwarded to the upstream call (aside from overriding `Authorization` and `Host`). Response status and content-type are mirrored from upstream.
## Hardening Details
Care is taken to restrict access/copying to the value of `OPENAI_API_KEY` retained in memory:
- We leverage [`codex_process_hardening`](https://github.com/openai/codex/blob/main/codex-rs/process-hardening/README.md) so `codex-responses-api-proxy` is run with standard process-hardening techniques.
- At startup, we allocate a `1024` byte buffer on the stack and copy `"Bearer "` into the start of the buffer.
- We then read from `stdin`, copying the contents into the buffer after `"Bearer "`.
- After verifying the key matches `/^[a-zA-Z0-9_-]+$/` (and does not exceed the buffer), we create a `String` from that buffer (so the data is now on the heap).
- We zero out the stack-allocated buffer using https://crates.io/crates/zeroize so it is not optimized away by the compiler.
- We invoke `.leak()` on the `String` so we can treat its contents as a `&'static str`, as it will live for the rest of the process.
- On UNIX, we `mlock(2)` the memory backing the `&'static str`.
- When using the `&'static str` when building an HTTP request, we use `HeaderValue::from_static()` to avoid copying the `&str`.
- We also invoke `.set_sensitive(true)` on the `HeaderValue`, which in theory indicates to other parts of the HTTP stack that the header should be treated with "special care" to avoid leakage:
https://github.com/hyperium/http/blob/439d1c50d71e3be3204b6c4a1bf2255ed78e1f93/src/header/value.rs#L346-L376

View File

@@ -0,0 +1,13 @@
# @openai/codex-responses-api-proxy
<p align="center"><code>npm i -g @openai/codex-responses-api-proxy</code> to install <code>codex-responses-api-proxy</code></p>
This package distributes the prebuilt [Codex Responses API proxy binary](https://github.com/openai/codex/tree/main/codex-rs/responses-api-proxy) for macOS, Linux, and Windows.
To see available options, run:
```
node ./bin/codex-responses-api-proxy.js --help
```
Refer to [`codex-rs/responses-api-proxy/README.md`](https://github.com/openai/codex/blob/main/codex-rs/responses-api-proxy/README.md) for detailed documentation.

View File

@@ -0,0 +1,104 @@
#!/usr/bin/env node
// Entry point for the Codex responses API proxy binary.
import { spawn } from "node:child_process";
import { closeSync } from "node:fs";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function determineTargetTriple(platform, arch) {
switch (platform) {
case "linux":
case "android":
if (arch === "x64") {
return "x86_64-unknown-linux-musl";
}
if (arch === "arm64") {
return "aarch64-unknown-linux-musl";
}
break;
case "darwin":
if (arch === "x64") {
return "x86_64-apple-darwin";
}
if (arch === "arm64") {
return "aarch64-apple-darwin";
}
break;
case "win32":
if (arch === "x64") {
return "x86_64-pc-windows-msvc";
}
if (arch === "arm64") {
return "aarch64-pc-windows-msvc";
}
break;
default:
break;
}
return null;
}
const targetTriple = determineTargetTriple(process.platform, process.arch);
if (!targetTriple) {
throw new Error(
`Unsupported platform: ${process.platform} (${process.arch})`,
);
}
const vendorRoot = path.join(__dirname, "..", "vendor");
const archRoot = path.join(vendorRoot, targetTriple);
const binaryBaseName = "codex-responses-api-proxy";
const binaryPath = path.join(
archRoot,
binaryBaseName,
process.platform === "win32" ? `${binaryBaseName}.exe` : binaryBaseName,
);
const child = spawn(binaryPath, process.argv.slice(2), {
stdio: "inherit",
});
child.once("spawn", () => {
// The child has inherited stdin. Close our copy so credential input
// cannot be reread through the long-lived Node launcher.
closeSync(0);
});
child.on("error", (err) => {
console.error(err);
process.exit(1);
});
const forwardSignal = (signal) => {
if (!child.killed) {
try {
child.kill(signal);
} catch {
/* ignore */
}
}
};
["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => {
process.on(sig, () => forwardSignal(sig));
});
const childResult = await new Promise((resolve) => {
child.on("exit", (code, signal) => {
if (signal) {
resolve({ type: "signal", signal });
} else {
resolve({ type: "code", exitCode: code ?? 1 });
}
});
});
if (childResult.type === "signal") {
process.kill(process.pid, childResult.signal);
} else {
process.exit(childResult.exitCode);
}

View File

@@ -0,0 +1,22 @@
{
"name": "@openai/codex-responses-api-proxy",
"version": "0.0.0-dev",
"license": "Apache-2.0",
"bin": {
"codex-responses-api-proxy": "bin/codex-responses-api-proxy.js"
},
"type": "module",
"engines": {
"node": ">=16"
},
"files": [
"bin",
"vendor"
],
"repository": {
"type": "git",
"url": "git+https://github.com/openai/codex.git",
"directory": "codex-rs/responses-api-proxy/npm"
},
"packageManager": "pnpm@10.34.5+sha512.a4ee05f2f73658255bd6a89859c065a45c28a57daefae2c893a168ee2b73168c37b91e83e57ea67654ad03f03031746430e8bce38e362e042605fb8abc80192e"
}

View File

@@ -0,0 +1,424 @@
//! Authenticates proxy requests using a locked API key or renewable OpenAI credentials.
//! Federated exchanges are serialized, fail closed on renewal errors, and never replay requests.
//! Token clients never follow redirects or emit credential-bearing URL diagnostics.
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use anyhow::Result;
use anyhow::anyhow;
use bytes::Bytes;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClient;
use codex_http_client::HttpClientBuilder;
use codex_http_client::HttpClientFactory;
use codex_http_client::HttpResponse;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::RouteAwareClientPool;
use http::HeaderValue;
use http::header::CONTENT_TYPE;
use serde::Deserialize;
use serde::Serialize;
use serde::de::DeserializeOwned;
use tokio::runtime::Runtime;
use url::Url;
use zeroize::Zeroizing;
use crate::OPENAI_RESPONSES_URL;
const OPENAI_TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
pub(crate) const MAX_TOKEN_BYTES: usize = 16 * 1024;
const MAX_RESPONSE_BYTES: usize = 64 * 1024;
// Bound the complete serialized token and provider metadata, including JSON escaping.
const MAX_EXCHANGE_REQUEST_BYTES: usize = 64 * 1024;
pub(crate) const TOKEN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_FEDERATED_TOKEN_LIFETIME: Duration = Duration::from_secs(3600);
const INITIAL_RENEWAL_BACKOFF: Duration = Duration::from_secs(1);
const MAX_RENEWAL_BACKOFF: Duration = Duration::from_secs(30);
/// Supplies a fresh JWT whenever an OpenAI credential needs to be issued.
/// Acquisition stays asynchronous so callers can compose it with the exchange.
/// Implementations must not include tokens, credential-bearing URLs, or upstream
/// response bodies in errors. The exchange deliberately has no issuer-specific config.
pub(crate) trait SubjectTokenSource: Send {
fn subject_token<'a>(&'a mut self, client: &'a TokenClient) -> SubjectTokenFuture<'a>;
}
// Keep the source usable as a trait object while acquisition runs asynchronously.
pub(crate) type SubjectTokenFuture<'a> =
Pin<Box<dyn Future<Output = Result<Zeroizing<String>>> + Send + 'a>>;
/// Credential requests must not follow redirects or log URLs or response headers.
/// The private field prevents other modules from wrapping arbitrary HTTP clients.
pub(crate) struct TokenClient(HttpClient);
impl TokenClient {
pub(crate) fn new() -> Self {
// The standalone proxy does not load Codex's session config. For its
// opt-in auth flow, resolve system and environment proxy settings per URL.
let factory = HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy);
Self(
RouteAwareClientPool::with_builder(factory, ClientRouteClass::Auth, Self::builder())
.into_client(),
)
}
fn builder() -> HttpClientBuilder {
HttpClientBuilder::new()
.connect_timeout(Duration::from_secs(10))
.without_redirects()
.without_request_logging()
}
pub(crate) fn http(&self) -> &HttpClient {
&self.0
}
}
pub(crate) enum Auth {
ApiKey(&'static str),
Federated { state: Box<Mutex<FederatedAuth>> },
}
impl fmt::Debug for Auth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ApiKey(_) => f.debug_tuple("ApiKey").field(&"[REDACTED]").finish(),
Self::Federated { .. } => f
.debug_struct("Federated")
.field("state", &"[REDACTED]")
.finish(),
}
}
}
/// The sensitive header and, for federation, the rejection state of this issuance.
/// In-flight requests share only their own issuance's flag, never a replacement's.
#[derive(Clone, Debug)]
pub(crate) struct AuthHeader {
pub(crate) value: HeaderValue,
rejected: Option<Arc<AtomicBool>>,
}
impl AuthHeader {
pub(crate) fn invalidate(&self) {
if let Some(rejected) = &self.rejected {
// This flag carries no other state; credentials remain mutex-protected.
rejected.store(true, Ordering::Relaxed);
}
}
}
impl Auth {
/// Must be checked before reading any source credential, including stdin.
pub(crate) fn validate_federated_upstream(upstream: &str) -> Result<()> {
if upstream != OPENAI_RESPONSES_URL {
return Err(anyhow!(
"workload identity requires the default OpenAI Responses endpoint"
));
}
Ok(())
}
pub(crate) fn federated(
source: impl SubjectTokenSource + 'static,
provider: String,
service_account: String,
) -> Result<Self> {
let client = TokenClient::new();
// Only credential acquisition needs an async runtime. The proxy's
// blocking request threads drive it while holding the credential mutex.
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|_| anyhow!("could not start workload identity HTTP runtime"))?;
Ok(Self::Federated {
state: Box::new(Mutex::new(FederatedAuth {
client,
runtime,
token_url: Url::parse(OPENAI_TOKEN_URL)?,
source: Box::new(source),
provider,
service_account,
cached: None,
renewal_failure: None,
})),
})
}
pub(crate) fn redirect_policy(&self) -> reqwest::redirect::Policy {
match self {
Self::ApiKey(_) => reqwest::redirect::Policy::default(),
// A federated credential must never be sent to a redirect target.
Self::Federated { .. } => reqwest::redirect::Policy::none(),
}
}
/// Returns a sensitive authorization header.
///
/// API keys are validated when read. Federated authentication can fail if the
/// credential cache cannot be locked, or if token acquisition, exchange, or
/// validation fails.
pub(crate) fn header(&self) -> Result<AuthHeader> {
match self {
Self::ApiKey(value) => {
// Keep the existing locked, static API key allocation.
let mut header = HeaderValue::from_static(value);
header.set_sensitive(true);
Ok(AuthHeader {
value: header,
rejected: None,
})
}
Self::Federated { state } => state
.lock()
.map_err(|_| anyhow!("workload identity credential cache unavailable"))?
.header(Instant::now),
}
}
}
pub(crate) struct FederatedAuth {
client: TokenClient,
runtime: Runtime,
token_url: Url,
source: Box<dyn SubjectTokenSource>,
provider: String,
service_account: String,
cached: Option<CachedToken>,
renewal_failure: Option<RenewalFailure>,
}
struct CachedToken {
header: AuthHeader,
renew_at: Instant,
expires_at: SystemTime,
}
struct RenewalFailure {
retry_at: Instant,
delay: Duration,
}
impl FederatedAuth {
fn header(&mut self, clock: impl Fn() -> Instant) -> Result<AuthHeader> {
let now = clock();
if let Some(cached) = &self.cached
&& now < cached.renew_at
// Monotonic time can stop while a host is suspended.
&& SystemTime::now() < cached.expires_at
&& cached
.header
.rejected
.as_ref()
.is_none_or(|rejected| !rejected.load(Ordering::Relaxed))
{
return Ok(cached.header.clone());
}
if let Some(failure) = &self.renewal_failure
&& now < failure.retry_at
{
// Keep neither the failed token nor an error that could hold source
// credentials. The initiating request reports the original safe error.
return Err(anyhow!(
"workload identity renewal temporarily unavailable; retry later"
));
}
// One exchange at a time (under Auth's mutex), including during startup.
// On failure, fail closed instead of reusing an expired/revoked token.
self.cached = None;
match self.exchange() {
Ok(cached) => {
let header = cached.header.clone();
self.cached = Some(cached);
self.renewal_failure = None;
Ok(header)
}
Err(err) => {
// Waiters share this failure instead of each retrying the token
// endpoints. Later requests may retry after a bounded delay.
let delay = self
.renewal_failure
.as_ref()
.map(|failure| (failure.delay * 2).min(MAX_RENEWAL_BACKOFF))
.unwrap_or(INITIAL_RENEWAL_BACKOFF);
self.renewal_failure = Some(RenewalFailure {
retry_at: clock() + delay,
delay,
});
Err(err)
}
}
}
fn exchange(&mut self) -> Result<CachedToken> {
let (started, exchange): (Instant, ExchangeResponse) = self.runtime.block_on(async {
let subject = self.source.subject_token(&self.client).await?;
if subject.is_empty() || subject.len() > MAX_TOKEN_BYTES {
return Err(anyhow!(
"workload identity source returned an invalid subject token"
));
}
let request = ExchangeRequest {
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
subject_token_type: "urn:ietf:params:oauth:token-type:jwt",
subject_token: subject.as_str(),
identity_provider_id: &self.provider,
service_account_id: &self.service_account,
};
// Serialize through a fixed slice so secret-bearing storage cannot grow.
// The HTTP body owns this buffer, including any request clones used for retries.
let mut body = Zeroizing::new(vec![0u8; MAX_EXCHANGE_REQUEST_BYTES]);
let written = {
let mut writer = std::io::Cursor::new(body.as_mut_slice());
serde_json::to_writer(&mut writer, &request).map_err(|_| {
anyhow!(
"OpenAI workload identity exchange request exceeds {MAX_EXCHANGE_REQUEST_BYTES} bytes"
)
})?;
writer.position() as usize
};
body.truncate(written);
// Start the lifetime clock before the OpenAI exchange, after obtaining
// the subject. expires_in is measured from issuance, not receipt.
let started = Instant::now();
let response = self
.client
.http()
.post(self.token_url.clone())
.timeout(TOKEN_REQUEST_TIMEOUT)
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.body(Bytes::from_owner(body))
.send()
.await
.map_err(|_| anyhow!("OpenAI workload identity token exchange failed"))?;
let exchange = read_response(response, "OpenAI workload identity").await?;
Ok((started, exchange))
})?;
if !exchange.token_type.eq_ignore_ascii_case("bearer")
|| exchange.issued_token_type != "urn:ietf:params:oauth:token-type:access_token"
{
return Err(anyhow!(
"OpenAI returned an unsupported workload identity token type"
));
}
if exchange.expires_in > MAX_FEDERATED_TOKEN_LIFETIME.as_secs() {
return Err(anyhow!("OpenAI returned an invalid token lifetime"));
}
let header = bearer_header(exchange.access_token.as_bytes())?;
let expires_at = UNIX_EPOCH
.checked_add(Duration::from_secs(exchange.expires_at))
.ok_or_else(|| anyhow!("OpenAI returned an expired workload identity token"))?;
let now = SystemTime::now();
let remaining_absolute = expires_at
.duration_since(now)
.map_err(|_| anyhow!("OpenAI returned an expired workload identity token"))?;
let remaining_relative = Duration::from_secs(exchange.expires_in)
.checked_sub(started.elapsed())
.ok_or_else(|| anyhow!("OpenAI returned an expired workload identity token"))?;
let remaining = remaining_absolute.min(remaining_relative);
if remaining.is_zero() {
return Err(anyhow!(
"OpenAI returned an expired workload identity token"
));
}
// Bound the wall-clock deadline too, even when the issuer's clock is
// ahead. Otherwise a host suspend could outlast the shorter relative TTL.
let expires_at = now
.checked_add(remaining)
.ok_or_else(|| anyhow!("OpenAI returned an invalid token lifetime"))?;
// Proactive renewal without a fixed skew that rejects short-lived subject tokens.
let skew = (remaining / 10).min(Duration::from_secs(60));
let renew_at = Instant::now()
.checked_add(remaining - skew)
.ok_or_else(|| anyhow!("OpenAI returned an invalid token lifetime"))?;
Ok(CachedToken {
header: AuthHeader {
value: header,
rejected: Some(Arc::new(AtomicBool::new(/*v*/ false))),
},
renew_at,
expires_at,
})
}
}
#[derive(Serialize)]
struct ExchangeRequest<'a> {
grant_type: &'static str,
subject_token_type: &'static str,
subject_token: &'a str,
identity_provider_id: &'a str,
service_account_id: &'a str,
}
#[derive(Deserialize)]
struct ExchangeResponse {
access_token: Zeroizing<String>,
token_type: String,
issued_token_type: String,
expires_in: u64,
expires_at: u64,
}
pub(crate) async fn read_response<T: DeserializeOwned>(
mut response: HttpResponse,
source: &str,
) -> Result<T> {
if !response.status().is_success() {
// Never read or log the error body; it may echo a credential. Redirects are
// failures too. HTTP errors can contain the URL, so don't attach them.
return Err(anyhow!(
"{source} token request rejected (HTTP {})",
response.status().as_u16()
));
}
// Keep secret-bearing response bytes in one allocation, including on errors.
let mut body = Zeroizing::new(Vec::with_capacity(MAX_RESPONSE_BYTES));
while let Some(chunk) = response
.chunk()
.await
.map_err(|_| anyhow!("{source} returned an unreadable token response"))?
{
if chunk.len() > MAX_RESPONSE_BYTES - body.len() {
return Err(anyhow!("{source} returned an oversized token response"));
}
body.extend_from_slice(&chunk);
}
serde_json::from_slice(&body)
.map_err(|_| anyhow!("{source} returned an invalid token response"))
}
// RFC 6750 bearer token characters, rather than the API key's narrower alphabet.
// Accept JWT periods, but never control bytes, whitespace, or header injection.
fn bearer_header(token: &[u8]) -> Result<HeaderValue> {
if token.is_empty()
|| token.len() > MAX_TOKEN_BYTES
|| !token.iter().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(byte, b'-' | b'.' | b'_' | b'~' | b'+' | b'/' | b'=')
})
{
return Err(anyhow!("invalid workload identity bearer credential"));
}
let mut bytes = Zeroizing::new(Vec::with_capacity(7 + token.len()));
bytes.extend_from_slice(b"Bearer ");
bytes.extend_from_slice(token);
let mut header = HeaderValue::from_bytes(&bytes)
.map_err(|_| anyhow!("invalid workload identity bearer credential"))?;
header.set_sensitive(true);
Ok(header)
}
#[cfg(test)]
#[path = "auth_tests.rs"]
pub(crate) mod tests;

View File

@@ -0,0 +1,912 @@
//! Tests credential-safe diagnostics, federated exchanges, expiry, and transport.
use super::*;
use pretty_assertions::assert_eq;
use reqwest::blocking::Client;
use serde_json::json;
use std::sync::Arc;
use std::sync::Barrier;
use std::sync::mpsc;
use std::thread;
use tiny_http::Header;
use tiny_http::Server;
use tiny_http::StatusCode;
pub(crate) fn direct_token_client() -> TokenClient {
TokenClient(TokenClient::builder().build_direct().unwrap())
}
#[test]
fn debug_redacts_api_keys_in_both_formats() {
let auth = Auth::ApiKey("Bearer test-secret-for-proxy-auth");
for output in [format!("{auth:?}"), format!("{auth:#?}")] {
assert!(!output.contains("test-secret-for-proxy-auth"));
assert!(output.contains("ApiKey"));
assert!(output.contains("[REDACTED]"));
}
}
// A non-GitHub issuer: each renewal must ask the source for a fresh subject.
struct RotatingSource {
calls: usize,
}
impl SubjectTokenSource for RotatingSource {
fn subject_token<'a>(&'a mut self, _client: &'a TokenClient) -> SubjectTokenFuture<'a> {
Box::pin(async move {
self.calls += 1;
Ok(Zeroizing::new(format!("issuer.subject.{}", self.calls)))
})
}
}
fn server() -> (Server, Url) {
let server = Server::http("127.0.0.1:0").unwrap();
let url = Url::parse(&format!("http://{}", server.server_addr())).unwrap();
(server, url)
}
fn auth_at(url: &Url) -> Auth {
let auth = Auth::federated(
RotatingSource { calls: 0 },
"ip-test".to_owned(),
"sa-test".to_owned(),
)
.unwrap();
let Auth::Federated { state, .. } = &auth else {
unreachable!()
};
let mut state = state.lock().unwrap();
state.token_url = url.join("/oauth/token").unwrap();
// Fixtures must not use a developer's system or environment proxy.
state.client = direct_token_client();
drop(state);
auth
}
fn recv(server: &Server) -> tiny_http::Request {
server
.recv_timeout(Duration::from_secs(5))
.unwrap()
.expect("expected HTTP request")
}
fn recv_exchange(server: &Server, subject: &str) -> tiny_http::Request {
let mut req = recv(server);
assert_eq!(req.url(), "/oauth/token");
assert_eq!(req.method(), &tiny_http::Method::Post);
assert!(!req.headers().iter().any(|h| h.field.equiv("Authorization")));
assert_eq!(
req.headers()
.iter()
.find(|h| h.field.equiv("Content-Type"))
.map(|h| h.value.as_str()),
Some("application/json")
);
let mut body = String::new();
req.as_reader().read_to_string(&mut body).unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&body).unwrap(),
json!({
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
"subject_token": subject,
"identity_provider_id": "ip-test",
"service_account_id": "sa-test",
})
);
req
}
fn recv_response_request(
server: &Server,
expected_token: &str,
expected_body: &str,
) -> tiny_http::Request {
let mut req = recv(server);
assert_eq!(req.url(), "/v1/responses");
assert_eq!(req.method(), &tiny_http::Method::Post);
assert!(req.headers().iter().any(|h| h.field.equiv("Authorization")
&& h.value.as_str() == format!("Bearer {expected_token}")));
let mut body = String::new();
req.as_reader().read_to_string(&mut body).unwrap();
assert_eq!(body, expected_body);
req
}
fn serve_exchange(server: &Server, subject: &str, token: &str, expires_in: u64, expires_at: u64) {
respond_exchange(
recv_exchange(server, subject),
token,
expires_in,
expires_at,
);
}
fn respond_exchange(req: tiny_http::Request, token: &str, expires_in: u64, expires_at: u64) {
req.respond(
tiny_http::Response::from_string(
json!({
"access_token": token, "token_type": "Bearer",
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
"expires_in": expires_in, "expires_at": expires_at,
})
.to_string(),
)
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap()),
)
.unwrap();
}
fn epoch_seconds() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
#[test]
fn oversized_serialized_exchange_request_is_rejected_before_sending() {
let (server, url) = server();
let auth = auth_at(&url);
let Auth::Federated { state, .. } = &auth else {
unreachable!()
};
// Fits unescaped, but JSON escaping makes the serialized request exceed the limit.
state.lock().unwrap().provider = "\0".repeat(MAX_EXCHANGE_REQUEST_BYTES / 6 + 1);
assert_eq!(
auth.header().unwrap_err().to_string(),
format!(
"OpenAI workload identity exchange request exceeds {MAX_EXCHANGE_REQUEST_BYTES} bytes"
)
);
assert!(state.lock().unwrap().cached.is_none());
assert!(server.try_recv().unwrap().is_none());
}
#[test]
fn shared_oidc_transport_honors_custom_ca_in_cli_blocking_context() {
// Use a subprocess so certificate settings cannot affect parallel tests.
// run_main also runs under spawn_blocking when invoked via the Codex CLI.
const CHILD_ENV: &str = "CODEX_TEST_PROXY_OIDC_CUSTOM_CA";
if std::env::var_os(CHILD_ENV).is_some() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
tokio::task::spawn_blocking(|| {
let (server, url) = server();
let auth = Auth::federated(
RotatingSource { calls: 0 },
"ip-test".to_owned(),
"sa-test".to_owned(),
)
.unwrap();
let Auth::Federated { state, .. } = &auth else {
unreachable!()
};
// Exercise the production pool, only replacing the destination.
state.lock().unwrap().token_url = url.join("/oauth/token").unwrap();
let error = format!("{:#}", auth.header().unwrap_err());
assert_eq!(error, "OpenAI workload identity token exchange failed");
assert!(
server
.recv_timeout(Duration::from_millis(100))
.unwrap()
.is_none(),
"must fail closed when a configured CA cannot be loaded"
);
})
.await
.unwrap();
});
return;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"auth::tests::shared_oidc_transport_honors_custom_ca_in_cli_blocking_context",
"--nocapture",
])
.env(CHILD_ENV, "1")
.env(
"CODEX_CA_CERTIFICATE",
"/invalid-oidc-test-ca/credential.pem",
)
.output()
.unwrap();
assert!(
output.status.success(),
"stdout: {}\nstderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
#[test]
fn oversized_exchange_never_becomes_a_cached_credential() {
let (server, url) = server();
let worker = thread::spawn(move || {
let body = json!({
"access_token": "secret".repeat(MAX_RESPONSE_BYTES),
"token_type": "Bearer",
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
"expires_in": 300,
"expires_at": epoch_seconds() + 300,
});
let _ = recv_exchange(&server, "issuer.subject.1").respond(
tiny_http::Response::from_string(body.to_string())
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap()),
);
});
let auth = auth_at(&url);
let error = format!("{:#}", auth.header().unwrap_err());
assert_eq!(
error,
"OpenAI workload identity returned an oversized token response"
);
let Auth::Federated { state, .. } = &auth else {
unreachable!()
};
assert!(state.lock().unwrap().cached.is_none());
worker.join().unwrap();
}
#[test]
fn exchanges_once_for_concurrent_requests_and_renews_with_a_new_subject() {
let (server, url) = server();
let auth = Arc::new(auth_at(&url));
let (attempt_tx, attempt_rx) = mpsc::channel();
let (in_flight_tx, in_flight_rx) = mpsc::channel();
let worker = thread::spawn(move || {
let pending = recv_exchange(&server, "issuer.subject.1");
in_flight_tx.send(()).unwrap();
// Each other caller must observe the lock held during the first exchange.
for _ in 0..7 {
attempt_rx.recv_timeout(Duration::from_secs(5)).unwrap();
}
assert!(server.try_recv().unwrap().is_none());
respond_exchange(
pending,
"openai.first.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
serve_exchange(
&server,
"issuer.subject.2",
"openai.second.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
});
let first = {
let auth = Arc::clone(&auth);
thread::spawn(move || auth.header().unwrap())
};
in_flight_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let callers: Vec<_> = (0..7)
.map(|_| {
let auth = Arc::clone(&auth);
let attempted = attempt_tx.clone();
thread::spawn(move || {
let Auth::Federated { state } = auth.as_ref() else {
unreachable!()
};
assert!(matches!(
state.try_lock(),
Err(std::sync::TryLockError::WouldBlock)
));
attempted.send(()).unwrap();
auth.header().unwrap()
})
})
.collect();
for caller in std::iter::once(first).chain(callers) {
let header = caller.join().unwrap();
assert!(header.value.is_sensitive());
assert_eq!(header.value.to_str().unwrap(), "Bearer openai.first.jwt");
}
let Auth::Federated { state, .. } = auth.as_ref() else {
unreachable!()
};
state.lock().unwrap().cached.as_mut().unwrap().renew_at = Instant::now();
assert_eq!(
auth.header().unwrap().value.to_str().unwrap(),
"Bearer openai.second.jwt"
);
worker.join().unwrap();
}
#[test]
fn exchange_is_never_cached_if_expired_or_lifetime_exceeds_the_contract() {
for (expires_in, expires_at, expected_error) in [
(
3600,
epoch_seconds() - 1,
"OpenAI returned an expired workload identity token",
),
(
0,
epoch_seconds() + 3600,
"OpenAI returned an expired workload identity token",
),
(
3601,
epoch_seconds() + 7200,
"OpenAI returned an invalid token lifetime",
),
] {
let (server, url) = server();
let worker = thread::spawn(move || {
serve_exchange(
&server,
"issuer.subject.1",
"expired.secret.token",
expires_in,
expires_at,
);
});
let auth = auth_at(&url);
assert_eq!(auth.header().unwrap_err().to_string(), expected_error);
let Auth::Federated { state, .. } = auth else {
unreachable!()
};
assert!(state.lock().unwrap().cached.is_none());
worker.join().unwrap();
}
}
#[test]
fn unsupported_or_missing_issued_token_type_is_never_cached_or_echoed() {
for (issued_type, expected_error) in [
(
Some("urn:ietf:params:oauth:token-type:id_token"),
"OpenAI returned an unsupported workload identity token type",
),
(
Some("echoed.secret.in.type"),
"OpenAI returned an unsupported workload identity token type",
),
(
None,
"OpenAI workload identity returned an invalid token response",
),
] {
let (server, url) = server();
let worker = thread::spawn(move || {
let mut body = json!({
"access_token": "openai.secret.jwt", "token_type": "Bearer",
"expires_in": 300, "expires_at": epoch_seconds() + 300,
});
if let Some(issued_type) = issued_type {
body["issued_token_type"] = json!(issued_type);
}
recv_exchange(&server, "issuer.subject.1")
.respond(tiny_http::Response::from_string(body.to_string()))
.unwrap();
});
let auth = auth_at(&url);
assert_eq!(format!("{:#}", auth.header().unwrap_err()), expected_error);
let Auth::Federated { state, .. } = auth else {
unreachable!()
};
assert!(state.lock().unwrap().cached.is_none());
worker.join().unwrap();
}
}
#[test]
fn absolute_expiry_forces_renewal_and_discards_cached_credential_on_failure() {
let (server, url) = server();
let worker = thread::spawn(move || {
serve_exchange(
&server,
"issuer.subject.1",
"openai.first.jwt",
/*expires_in*/ 300,
// The issuer's clock is ahead. Accept the token, but don't cache it
// past the shorter relative TTL, including across host suspension.
epoch_seconds() + 7200,
);
serve_exchange(
&server,
"issuer.subject.2",
"openai.second.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
recv_exchange(&server, "issuer.subject.3")
.respond(tiny_http::Response::empty(tiny_http::StatusCode(503)))
.unwrap();
});
let auth = auth_at(&url);
assert_eq!(
auth.header().unwrap().value.to_str().unwrap(),
"Bearer openai.first.jwt"
);
let Auth::Federated { state, .. } = &auth else {
unreachable!()
};
{
let mut state = state.lock().unwrap();
let cached = state.cached.as_mut().unwrap();
// Model a suspend: wall time has crossed expiry but Instant has not advanced.
assert!(Instant::now() < cached.renew_at);
assert!(cached.expires_at <= SystemTime::now() + Duration::from_secs(300));
cached.expires_at = UNIX_EPOCH;
}
assert_eq!(
auth.header().unwrap().value.to_str().unwrap(),
"Bearer openai.second.jwt"
);
state.lock().unwrap().cached.as_mut().unwrap().expires_at = UNIX_EPOCH;
assert_eq!(
auth.header().unwrap_err().to_string(),
"OpenAI workload identity token request rejected (HTTP 503)"
);
assert!(state.lock().unwrap().cached.is_none());
worker.join().unwrap();
}
#[test]
fn rejected_renewal_discards_old_credential_and_does_not_log_or_follow_redirect() {
let (server, url) = server();
let target = url.join("/credential-leak").unwrap();
let worker = thread::spawn(move || {
serve_exchange(
&server,
"issuer.subject.1",
"original.token",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
recv_exchange(&server, "issuer.subject.2")
.respond(
tiny_http::Response::from_string("issuer.subject.2 original.token")
.with_status_code(StatusCode(302))
.with_header(Header::from_bytes("Location", target.as_str()).unwrap()),
)
.unwrap();
assert!(
server
.recv_timeout(Duration::from_millis(200))
.unwrap()
.is_none()
);
});
let auth = auth_at(&url);
assert_eq!(
auth.header().unwrap().value.to_str().unwrap(),
"Bearer original.token"
);
let Auth::Federated { ref state, .. } = auth else {
unreachable!()
};
state.lock().unwrap().cached.as_mut().unwrap().renew_at = Instant::now();
let error = format!("{:#}", auth.header().unwrap_err());
assert!(error.contains("302"), "{error}");
for secret in ["issuer.subject.2", "original.token", url.as_str()] {
assert!(!error.contains(secret), "{error}");
}
assert!(state.lock().unwrap().cached.is_none());
worker.join().unwrap();
}
#[test]
fn invalid_subjects_are_rejected_before_exchange() {
struct InvalidSource(String);
impl SubjectTokenSource for InvalidSource {
fn subject_token<'a>(&'a mut self, _client: &'a TokenClient) -> SubjectTokenFuture<'a> {
Box::pin(async move { Ok(Zeroizing::new(self.0.clone())) })
}
}
for token in [String::new(), "a".repeat(MAX_TOKEN_BYTES + 1)] {
let auth = Auth::federated(
InvalidSource(token),
"ip-test".to_owned(),
"sa-test".to_owned(),
)
.unwrap();
assert_eq!(
auth.header().unwrap_err().to_string(),
"workload identity source returned an invalid subject token"
);
}
}
#[test]
fn forwards_401_without_replay_then_reacquires_but_keeps_token_on_403() {
let (upstream, upstream_url) = server();
let auth = auth_at(&upstream_url);
let (proxy, proxy_url) = server();
let upstream_worker = thread::spawn(move || {
serve_exchange(
&upstream,
"issuer.subject.1",
"openai.first.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
recv_response_request(&upstream, "openai.first.jwt", "first")
.respond(
tiny_http::Response::from_string("rejected")
.with_status_code(StatusCode(401))
.with_header(Header::from_bytes("WWW-Authenticate", "Bearer").unwrap()),
)
.unwrap();
// No Responses replay or speculative exchange: the caller submits a
// distinct POST. A permission failure on that POST must not evict auth.
serve_exchange(
&upstream,
"issuer.subject.2",
"openai.second.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
recv_response_request(&upstream, "openai.second.jwt", "second")
.respond(
tiny_http::Response::from_string("forbidden").with_status_code(StatusCode(403)),
)
.unwrap();
recv_response_request(&upstream, "openai.second.jwt", "third")
.respond(tiny_http::Response::from_string("success"))
.unwrap();
});
let proxy_worker = thread::spawn(move || {
let client = Client::builder()
.no_proxy()
.timeout(Duration::from_secs(5))
.redirect(auth.redirect_policy())
.build()
.unwrap();
let config = crate::ForwardConfig {
host_header: HeaderValue::from_str(upstream_url.authority()).unwrap(),
upstream_url: upstream_url.join("/v1/responses").unwrap(),
};
for _ in 0..3 {
crate::forward_request(
&client,
&auth,
&config,
/*dump_dir*/ None,
recv(&proxy),
)
.unwrap();
}
});
let client = Client::builder()
.no_proxy()
.timeout(Duration::from_secs(5))
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
let response_url = proxy_url.join("/v1/responses").unwrap();
let response = client
.post(response_url.clone())
.body("first")
.send()
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED);
assert_eq!(
response.headers().get("www-authenticate").unwrap(),
"Bearer"
);
assert_eq!(response.text().unwrap(), "rejected");
let response = client
.post(response_url.clone())
.body("second")
.send()
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::FORBIDDEN);
assert_eq!(response.text().unwrap(), "forbidden");
let response = client.post(response_url).body("third").send().unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(response.text().unwrap(), "success");
proxy_worker.join().unwrap();
upstream_worker.join().unwrap();
}
#[test]
fn late_rejection_does_not_invalidate_a_newer_credential() {
let (server, url) = server();
let worker = thread::spawn(move || {
serve_exchange(
&server,
"issuer.subject.1",
"openai.first.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
serve_exchange(
&server,
"issuer.subject.2",
"openai.second.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
});
let auth = auth_at(&url);
let original = auth.header().unwrap();
original.invalidate();
let renewed = auth.header().unwrap();
assert_eq!(renewed.value.to_str().unwrap(), "Bearer openai.second.jwt");
worker.join().unwrap();
// Model an in-flight request made with the old token completing after
// the refresh. The server is closed, so an accidental third exchange fails.
original.invalidate();
assert_eq!(auth.header().unwrap().value, renewed.value);
}
#[test]
fn forwards_401_before_an_inflight_renewal_finishes() {
let (upstream, upstream_url) = server();
let auth = Arc::new(auth_at(&upstream_url));
let acquiring = Arc::clone(&auth);
let first = thread::spawn(move || acquiring.header().unwrap());
serve_exchange(
&upstream,
"issuer.subject.1",
"openai.first.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
let original = first.join().unwrap();
let (proxy, proxy_url) = server();
let forwarding = Arc::clone(&auth);
let config = crate::ForwardConfig {
host_header: HeaderValue::from_str(upstream_url.authority()).unwrap(),
upstream_url: upstream_url.join("/v1/responses").unwrap(),
};
let proxy_worker = thread::spawn(move || {
let client = Client::builder()
.no_proxy()
.redirect(forwarding.redirect_policy())
.build()
.unwrap();
crate::forward_request(
&client,
&forwarding,
&config,
/*dump_dir*/ None,
recv(&proxy),
)
.unwrap();
});
let (sent, received) = mpsc::sync_channel(1);
let caller = thread::spawn(move || {
let response = Client::builder()
.no_proxy()
.build()
.unwrap()
.post(proxy_url.join("/v1/responses").unwrap())
.body("first")
.send()
.unwrap();
sent.send((response.status(), response.text().unwrap()))
.unwrap();
});
// The request is already at upstream with the first credential. Hold its
// response until a concurrent rejection has started a new exchange.
let response_request = recv_response_request(&upstream, "openai.first.jwt", "first");
original.invalidate();
let acquiring = Arc::clone(&auth);
let renewal = thread::spawn(move || acquiring.header().unwrap());
let exchange = recv_exchange(&upstream, "issuer.subject.2");
response_request
.respond(tiny_http::Response::from_string("rejected").with_status_code(StatusCode(401)))
.unwrap();
// This must arrive before we let the exchange finish and release the mutex.
// Always release it before asserting so a regression cannot strand workers.
let response = received.recv_timeout(Duration::from_secs(5));
respond_exchange(
exchange,
"openai.second.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
let renewed = renewal.join().unwrap();
caller.join().unwrap();
proxy_worker.join().unwrap();
assert_eq!(
response.unwrap(),
(reqwest::StatusCode::UNAUTHORIZED, "rejected".to_string())
);
assert_eq!(auth.header().unwrap().value, renewed.value);
}
fn header_at(auth: &Auth, now: Instant) -> Result<AuthHeader> {
let Auth::Federated { state } = auth else {
unreachable!()
};
state.lock().unwrap().header(|| now)
}
// Advance to the recorded retry deadline without waiting on real time.
fn elapse_backoff(auth: &Auth, now: &mut Instant) -> Duration {
let Auth::Federated { state } = auth else {
unreachable!()
};
let state = state.lock().unwrap();
assert!(state.cached.is_none());
let failure = state.renewal_failure.as_ref().unwrap();
*now = failure.retry_at;
failure.delay
}
#[test]
fn renewal_backoff_starts_after_a_slow_exchange_fails() {
let (server, url) = server();
let started = Instant::now();
let failed = started + Duration::from_secs(10);
let clock = Arc::new(Mutex::new(started));
let upstream_clock = Arc::clone(&clock);
let worker = thread::spawn(move || {
serve_exchange(
&server,
"issuer.subject.1",
"openai.first.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
let exchange = recv_exchange(&server, "issuer.subject.2");
// Simulate time spent waiting on the failed renewal, longer than its cooldown.
*upstream_clock.lock().unwrap() = failed;
exchange
.respond(
tiny_http::Response::from_string("temporarily unavailable")
.with_status_code(StatusCode(503)),
)
.unwrap();
});
let auth = auth_at(&url);
auth.header().unwrap().invalidate();
let Auth::Federated { state } = &auth else {
unreachable!()
};
let error = state
.lock()
.unwrap()
.header(|| *clock.lock().unwrap())
.unwrap_err();
worker.join().unwrap();
assert_eq!(
error.to_string(),
"OpenAI workload identity token request rejected (HTTP 503)"
);
let retry_at = failed + Duration::from_secs(1);
assert_eq!(
state
.lock()
.unwrap()
.renewal_failure
.as_ref()
.unwrap()
.retry_at,
retry_at
);
assert_eq!(
header_at(&auth, retry_at - Duration::from_nanos(1))
.unwrap_err()
.to_string(),
"workload identity renewal temporarily unavailable; retry later"
);
}
#[test]
fn concurrent_renewal_failure_backs_off_caps_and_resets_after_success() {
let (server, url) = server();
let worker = thread::spawn(move || {
serve_exchange(
&server,
"issuer.subject.1",
"openai.first.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
for subject in 2..=8 {
recv_exchange(&server, &format!("issuer.subject.{subject}"))
.respond(
tiny_http::Response::from_string("private-issuer-token openai.first.jwt")
.with_status_code(StatusCode(503)),
)
.unwrap();
}
serve_exchange(
&server,
"issuer.subject.9",
"openai.recovered.jwt",
/*expires_in*/ 300,
epoch_seconds() + 300,
);
recv_exchange(&server, "issuer.subject.10")
.respond(
tiny_http::Response::from_string("private-issuer-token")
.with_status_code(StatusCode(503)),
)
.unwrap();
});
let auth = Arc::new(auth_at(&url));
let original = auth.header().unwrap();
let Auth::Federated { state, .. } = auth.as_ref() else {
unreachable!()
};
let mut now = Instant::now();
state.lock().unwrap().cached.as_mut().unwrap().renew_at = now;
let barrier = Arc::new(Barrier::new(8));
// Start every participant before joining any of them.
let mut callers = Vec::with_capacity(8);
for _ in 0..8 {
let auth = Arc::clone(&auth);
let barrier = Arc::clone(&barrier);
callers.push(thread::spawn(move || {
barrier.wait();
format!("{:#}", header_at(&auth, now).unwrap_err())
}));
}
let errors: Vec<_> = callers
.into_iter()
.map(|caller| caller.join().unwrap())
.collect();
assert_eq!(errors.iter().filter(|e| e.contains("503")).count(), 1);
assert_eq!(
errors.iter().filter(|e| e.contains("retry later")).count(),
7
);
for error in &errors {
for secret in ["private-issuer-token", "openai.first.jwt", url.as_str()] {
assert!(!error.contains(secret), "{error}");
}
}
// An older 401 arriving during backoff cannot trigger another renewal.
original.invalidate();
assert!(
header_at(&auth, now)
.unwrap_err()
.to_string()
.contains("retry later")
);
for seconds in [1, 2, 4, 8, 16, 30] {
assert_eq!(
elapse_backoff(&auth, &mut now),
Duration::from_secs(seconds)
);
assert!(
header_at(&auth, now)
.unwrap_err()
.to_string()
.contains("503")
);
assert!(
header_at(&auth, now)
.unwrap_err()
.to_string()
.contains("retry later")
);
}
assert_eq!(elapse_backoff(&auth, &mut now), Duration::from_secs(30));
let renewed = header_at(&auth, now).unwrap();
assert_eq!(
renewed.value.to_str().unwrap(),
"Bearer openai.recovered.jwt"
);
assert!(state.lock().unwrap().renewal_failure.is_none());
renewed.invalidate();
assert!(
header_at(&auth, now)
.unwrap_err()
.to_string()
.contains("503")
);
assert!(
header_at(&auth, now)
.unwrap_err()
.to_string()
.contains("retry later")
);
assert_eq!(elapse_backoff(&auth, &mut now), Duration::from_secs(1));
worker.join().unwrap();
}

View File

@@ -0,0 +1,378 @@
use std::fs;
use std::io;
use std::io::Read;
use std::path::PathBuf;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use reqwest::header::HeaderMap;
use serde::Serialize;
use serde_json::Value;
use tiny_http::Header;
use tiny_http::Method;
const AUTHORIZATION_HEADER_NAME: &str = "authorization";
const REDACTED_HEADER_VALUE: &str = "[REDACTED]";
pub(crate) struct ExchangeDumper {
dump_dir: PathBuf,
next_sequence: AtomicU64,
}
impl ExchangeDumper {
pub(crate) fn new(dump_dir: PathBuf) -> io::Result<Self> {
fs::create_dir_all(&dump_dir)?;
Ok(Self {
dump_dir,
next_sequence: AtomicU64::new(1),
})
}
pub(crate) fn dump_request(
&self,
method: &Method,
url: &str,
headers: &[Header],
body: &[u8],
) -> io::Result<ExchangeDump> {
let sequence = self.next_sequence.fetch_add(1, Ordering::Relaxed);
let timestamp_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |duration| duration.as_millis());
let prefix = format!("{sequence:06}-{timestamp_ms}");
let request_path = self.dump_dir.join(format!("{prefix}-request.json"));
let response_path = self.dump_dir.join(format!("{prefix}-response.json"));
let request_dump = RequestDump {
method: method.as_str().to_string(),
url: url.to_string(),
headers: headers.iter().map(HeaderDump::from).collect(),
body: dump_body(body),
};
write_json_dump(&request_path, &request_dump)?;
Ok(ExchangeDump { response_path })
}
}
pub(crate) struct ExchangeDump {
response_path: PathBuf,
}
impl ExchangeDump {
pub(crate) fn tee_response_body<R: Read>(
self,
status: u16,
headers: &HeaderMap,
response_body: R,
) -> ResponseBodyDump<R> {
ResponseBodyDump {
response_body,
response_path: self.response_path,
status,
headers: headers.iter().map(HeaderDump::from).collect(),
body: Vec::new(),
dump_written: false,
}
}
}
pub(crate) struct ResponseBodyDump<R> {
response_body: R,
response_path: PathBuf,
status: u16,
headers: Vec<HeaderDump>,
body: Vec<u8>,
dump_written: bool,
}
impl<R> ResponseBodyDump<R> {
fn write_dump_if_needed(&mut self) {
if self.dump_written {
return;
}
self.dump_written = true;
let response_dump = ResponseDump {
status: self.status,
headers: std::mem::take(&mut self.headers),
body: dump_body(&self.body),
};
if let Err(err) = write_json_dump(&self.response_path, &response_dump) {
eprintln!(
"responses-api-proxy failed to write {}: {err}",
self.response_path.display()
);
}
}
}
impl<R: Read> Read for ResponseBodyDump<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let bytes_read = self.response_body.read(buf)?;
if bytes_read == 0 {
self.write_dump_if_needed();
return Ok(0);
}
self.body.extend_from_slice(&buf[..bytes_read]);
Ok(bytes_read)
}
}
impl<R> Drop for ResponseBodyDump<R> {
fn drop(&mut self) {
self.write_dump_if_needed();
}
}
#[derive(Serialize)]
struct RequestDump {
method: String,
url: String,
headers: Vec<HeaderDump>,
body: Value,
}
#[derive(Serialize)]
struct ResponseDump {
status: u16,
headers: Vec<HeaderDump>,
body: Value,
}
#[derive(Debug, Serialize)]
struct HeaderDump {
name: String,
value: String,
}
impl From<&Header> for HeaderDump {
fn from(header: &Header) -> Self {
let name = header.field.as_str().to_string();
let value = if should_redact_header(&name) {
REDACTED_HEADER_VALUE.to_string()
} else {
header.value.as_str().to_string()
};
Self { name, value }
}
}
impl From<(&reqwest::header::HeaderName, &reqwest::header::HeaderValue)> for HeaderDump {
fn from(header: (&reqwest::header::HeaderName, &reqwest::header::HeaderValue)) -> Self {
let name = header.0.as_str();
let value = if should_redact_header(name) {
REDACTED_HEADER_VALUE.to_string()
} else {
String::from_utf8_lossy(header.1.as_bytes()).into_owned()
};
Self {
name: name.to_string(),
value,
}
}
}
fn should_redact_header(name: &str) -> bool {
name.eq_ignore_ascii_case(AUTHORIZATION_HEADER_NAME)
|| name.to_ascii_lowercase().contains("cookie")
}
fn dump_body(body: &[u8]) -> Value {
serde_json::from_slice(body)
.unwrap_or_else(|_| Value::String(String::from_utf8_lossy(body).into_owned()))
}
fn write_json_dump(path: &PathBuf, dump: &impl Serialize) -> io::Result<()> {
let mut bytes = serde_json::to_vec_pretty(dump)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
bytes.push(b'\n');
fs::write(path, bytes)
}
#[cfg(test)]
mod tests {
use std::fs;
use std::io::Cursor;
use std::io::Read;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use pretty_assertions::assert_eq;
use reqwest::header::AUTHORIZATION;
use reqwest::header::CONTENT_TYPE;
use reqwest::header::HeaderMap;
use reqwest::header::HeaderValue;
use serde_json::json;
use tiny_http::Header;
use tiny_http::Method;
use super::ExchangeDumper;
static NEXT_TEST_DIR: AtomicU64 = AtomicU64::new(0);
#[test]
fn dump_request_writes_redacted_headers_and_json_body() {
let dump_dir = test_dump_dir();
let dumper = ExchangeDumper::new(dump_dir.clone()).expect("create dumper");
let headers = vec![
Header::from_bytes(&b"Authorization"[..], &b"Bearer secret"[..])
.expect("authorization header"),
Header::from_bytes(&b"Cookie"[..], &b"user-session=secret"[..]).expect("cookie header"),
Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..])
.expect("content-type header"),
Header::from_bytes(&b"x-codex-window-id"[..], &b"thread-1:0"[..])
.expect("window id header"),
Header::from_bytes(&b"x-codex-parent-thread-id"[..], &b"parent-thread-1"[..])
.expect("parent thread id header"),
Header::from_bytes(&b"x-openai-subagent"[..], &b"collab_spawn"[..])
.expect("subagent header"),
];
let exchange_dump = dumper
.dump_request(
&Method::Post,
"/v1/responses",
&headers,
br#"{"model":"gpt-5.4"}"#,
)
.expect("dump request");
let request_dump = fs::read_to_string(dump_file_with_suffix(&dump_dir, "-request.json"))
.expect("read request dump");
assert_eq!(
serde_json::from_str::<serde_json::Value>(&request_dump).expect("parse request dump"),
json!({
"method": "POST",
"url": "/v1/responses",
"headers": [
{
"name": "Authorization",
"value": "[REDACTED]"
},
{
"name": "Cookie",
"value": "[REDACTED]"
},
{
"name": "Content-Type",
"value": "application/json"
},
{
"name": "x-codex-window-id",
"value": "thread-1:0"
},
{
"name": "x-codex-parent-thread-id",
"value": "parent-thread-1"
},
{
"name": "x-openai-subagent",
"value": "collab_spawn"
}
],
"body": {
"model": "gpt-5.4"
}
})
);
assert!(
exchange_dump
.response_path
.file_name()
.expect("response dump file name")
.to_string_lossy()
.ends_with("-response.json")
);
fs::remove_dir_all(dump_dir).expect("remove test dump dir");
}
#[test]
fn response_body_dump_streams_body_and_writes_response_file() {
let dump_dir = test_dump_dir();
let dumper = ExchangeDumper::new(dump_dir.clone()).expect("create dumper");
let exchange_dump = dumper
.dump_request(&Method::Post, "/v1/responses", &[], b"{}")
.expect("dump request");
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer secret"));
headers.insert(
"set-cookie",
HeaderValue::from_static("user-session=secret"),
);
let mut response_body = String::new();
exchange_dump
.tee_response_body(
/*status*/ 200,
&headers,
Cursor::new(b"data: hello\n\n".to_vec()),
)
.read_to_string(&mut response_body)
.expect("read response body");
let response_dump = fs::read_to_string(dump_file_with_suffix(&dump_dir, "-response.json"))
.expect("read response dump");
assert_eq!(response_body, "data: hello\n\n");
assert_eq!(
serde_json::from_str::<serde_json::Value>(&response_dump).expect("parse response dump"),
json!({
"status": 200,
"headers": [
{
"name": "content-type",
"value": "text/event-stream"
},
{
"name": "authorization",
"value": "[REDACTED]"
},
{
"name": "set-cookie",
"value": "[REDACTED]"
}
],
"body": "data: hello\n\n"
})
);
fs::remove_dir_all(dump_dir).expect("remove test dump dir");
}
fn test_dump_dir() -> std::path::PathBuf {
let test_id = NEXT_TEST_DIR.fetch_add(1, Ordering::Relaxed);
let dump_dir = std::env::temp_dir().join(format!(
"codex-responses-api-proxy-dump-test-{}-{test_id}",
std::process::id()
));
fs::create_dir_all(&dump_dir).expect("create test dump dir");
dump_dir
}
fn dump_file_with_suffix(dump_dir: &std::path::Path, suffix: &str) -> std::path::PathBuf {
let mut matches = fs::read_dir(dump_dir)
.expect("read dump dir")
.map(|entry| entry.expect("read dump entry").path())
.filter(|path| path.to_string_lossy().ends_with(suffix))
.collect::<Vec<_>>();
matches.sort();
assert_eq!(matches.len(), 1);
matches.pop().expect("single dump file")
}
}

View File

@@ -0,0 +1,125 @@
//! Obtains fresh GitHub Actions OIDC subject tokens for the federated exchange.
//! The stdin request credential and minted tokens must never appear in diagnostics.
use anyhow::Result;
use anyhow::anyhow;
use http::header::AUTHORIZATION;
use http::header::HeaderValue;
use serde::Deserialize;
use url::Url;
use zeroize::Zeroizing;
use crate::auth::MAX_TOKEN_BYTES;
use crate::auth::SubjectTokenFuture;
use crate::auth::SubjectTokenSource;
use crate::auth::TOKEN_REQUEST_TIMEOUT;
use crate::auth::TokenClient;
use crate::auth::read_response;
use crate::read_api_key::AUTH_HEADER_PREFIX;
use crate::read_api_key::read_auth_header_with;
use crate::read_api_key::read_from_stdin;
// Allow space for "Bearer " and a trailing CRLF.
const REQUEST_AUTH_BUFFER_SIZE: usize = AUTH_HEADER_PREFIX.len() + MAX_TOKEN_BYTES + 2;
// Intentionally no Debug: request_auth contains a credential.
pub(crate) struct GithubOidc {
request_url: Url,
request_auth: HeaderValue,
}
impl GithubOidc {
pub(crate) fn from_stdin(request_url: &str, audience: &str) -> Result<Self> {
// Avoid echoing caller-supplied URL parameters in parsing errors.
let mut request_url =
Url::parse(request_url).map_err(|_| anyhow!("invalid GitHub OIDC request URL"))?;
if request_url.scheme() != "https"
|| request_url.host_str().is_none()
|| !request_url.username().is_empty()
|| request_url.password().is_some()
|| request_url.fragment().is_some()
{
return Err(anyhow!(
"GitHub OIDC request URL must be HTTPS without user info or fragment"
));
}
// Replace any existing audience; preserve GitHub's other query parameters.
let pairs: Vec<(String, String)> = request_url
.query_pairs()
.filter(|(key, _)| key != "audience")
.map(|(key, value)| (key.into_owned(), value.into_owned()))
.collect();
request_url
.query_pairs_mut()
.clear()
.extend_pairs(pairs)
.append_pair("audience", audience);
Ok(Self {
request_url,
request_auth: read_request_auth(read_from_stdin)?,
})
}
}
impl SubjectTokenSource for GithubOidc {
fn subject_token<'a>(&'a mut self, client: &'a TokenClient) -> SubjectTokenFuture<'a> {
Box::pin(async move {
let response = client
.http()
.get(self.request_url.clone())
.timeout(TOKEN_REQUEST_TIMEOUT)
.header(AUTHORIZATION, self.request_auth.clone())
.send()
.await
.map_err(|_| anyhow!("GitHub OIDC token request failed"))?;
let response: GithubResponse = read_response(response, "GitHub OIDC").await?;
Ok(response.value)
})
}
}
#[derive(Deserialize)]
struct GithubResponse {
value: Zeroizing<String>,
}
// The launcher must remove ACTIONS_ID_TOKEN_REQUEST_TOKEN from its environment
// before exec. This header is retained for the lifetime of the proxy.
fn read_request_auth<F>(mut read: F) -> Result<HeaderValue>
where
F: FnMut(&mut [u8]) -> std::io::Result<usize>,
{
let read_credential = |buf: &mut [u8]| {
read(buf).map_err(|_| {
std::io::Error::other("could not read GitHub OIDC request credential from stdin")
})
};
let value = read_auth_header_with::<REQUEST_AUTH_BUFFER_SIZE>(
read_credential,
validate_github_request_token,
|| anyhow!("GitHub OIDC request credential too large"),
)?;
let mut header = HeaderValue::from_static(value);
header.set_sensitive(true);
Ok(header)
}
fn validate_github_request_token(token: &[u8]) -> Result<usize> {
let token = token.strip_suffix(b"\n").unwrap_or(token);
let token = token.strip_suffix(b"\r").unwrap_or(token);
// RFC 6750 permits JWT periods; reject whitespace and control bytes.
if token.is_empty()
|| token.len() > MAX_TOKEN_BYTES
|| !token.iter().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(byte, b'-' | b'.' | b'_' | b'~' | b'+' | b'/' | b'=')
})
{
return Err(anyhow!("invalid workload identity bearer credential"));
}
Ok(token.len())
}
#[cfg(test)]
#[path = "github_oidc_tests.rs"]
mod tests;

View File

@@ -0,0 +1,255 @@
use super::*;
use crate::Args;
use crate::auth::tests::direct_token_client;
use clap::Parser;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::io::Cursor;
use std::io::Read;
use std::thread;
use std::time::Duration;
use tiny_http::Header;
use tiny_http::Server;
use tiny_http::StatusCode;
use tokio::runtime::Runtime;
const FLAGS: &[&str] = &[
"responses-api-proxy",
"--github-oidc",
"--oidc-audience",
"https://api.openai.com/v1",
"--identity-provider-id",
"ip-test",
"--service-account-id",
"sa-test",
"--github-oidc-request-url",
"https://example.github.test/oidc?opaque=1",
];
#[test]
fn cli_requires_complete_oidc_configuration_and_keeps_api_key_default() {
assert!(!Args::try_parse_from(["proxy"]).unwrap().github_oidc);
assert!(Args::try_parse_from(["proxy", "--github-oidc"]).is_err());
assert!(Args::try_parse_from(["proxy", "--oidc-audience", "openai"]).is_err());
assert!(Args::try_parse_from(FLAGS).unwrap().github_oidc);
for name in [
"--oidc-audience",
"--identity-provider-id",
"--service-account-id",
"--github-oidc-request-url",
] {
let pos = FLAGS.iter().position(|flag| *flag == name).unwrap();
let mut missing = FLAGS.to_vec();
missing.drain(pos..pos + 2);
assert!(Args::try_parse_from(missing).is_err(), "missing {name}");
}
}
#[test]
fn oidc_disallows_provider_overrides_before_reading_any_credentials() {
let mut flags = FLAGS.to_vec();
flags.extend(["--upstream-url", "https://example.test/v1/responses"]);
let args = Args::try_parse_from(flags).unwrap();
assert!(
crate::run_main(args)
.unwrap_err()
.to_string()
.contains("default OpenAI")
);
}
#[test]
fn rejects_unsafe_or_empty_oidc_settings_without_echoing_input() {
for url in [
"http://example.test?secret=sensitive",
"https://name:sensitive@example.test/",
"https://example.test/#sensitive",
"sensitive",
] {
let mut args = Args::try_parse_from(FLAGS).unwrap();
args.github_oidc_request_url = Some(url.to_owned());
let Err(err) = args.auth() else {
panic!("accepted {url}")
};
let error = format!("{err:#}");
assert!(!error.contains("sensitive"), "{error}");
}
let mut args = Args::try_parse_from(FLAGS).unwrap();
args.oidc_audience = Some(" ".to_owned());
let Err(err) = args.auth() else {
panic!("accepted empty audience")
};
assert!(err.to_string().contains("--oidc-audience"));
}
#[test]
fn stdin_accepts_bounded_bearer_tokens_in_short_reads_and_rejects_injection() {
let token = format!("{}.payload.sig", "a".repeat(2000));
let input = format!("{token}\r\n");
let mut cursor = Cursor::new(input.as_bytes());
let header = read_request_auth(|buf| {
let len = buf.len().min(3);
cursor.read(&mut buf[..len])
})
.unwrap();
assert_eq!(header.to_str().unwrap(), format!("Bearer {token}"));
assert!(header.is_sensitive());
for token in ["", "a\rb", "a b", "a\0b", "x:y", "💥", "a\r\r", "a\r\r\n"] {
let mut cursor = Cursor::new(token.as_bytes());
assert!(read_request_auth(|buf| cursor.read(buf)).is_err());
}
for suffix in ["", "\n", "\r\n"] {
let max_token = "a".repeat(MAX_TOKEN_BYTES);
let input = format!("{max_token}{suffix}");
let mut cursor = Cursor::new(input.as_bytes());
let header = read_request_auth(|buf| cursor.read(buf)).unwrap();
assert_eq!(header.to_str().unwrap(), format!("Bearer {max_token}"));
let input = format!("a{max_token}{suffix}");
let mut cursor = Cursor::new(input.as_bytes());
assert!(read_request_auth(|buf| cursor.read(buf)).is_err());
}
}
#[test]
fn stdin_read_error_cannot_echo_a_github_credential() {
let mut sent = false;
let error = read_request_auth(|buf| {
if sent {
return Err(std::io::Error::other("private.github.request"));
}
sent = true;
buf[..3].copy_from_slice(b"abc");
Ok(3)
})
.unwrap_err();
assert_eq!(
format!("{error:#}"),
"could not read GitHub OIDC request credential from stdin"
);
}
fn server() -> (Server, Url) {
let server = Server::http("127.0.0.1:0").unwrap();
let url = Url::parse(&format!("http://{}", server.server_addr())).unwrap();
(server, url)
}
fn source_at(url: &Url) -> GithubOidc {
let mut cursor = Cursor::new(b"private.github.request");
GithubOidc {
request_url: url.join("/github").unwrap(),
request_auth: read_request_auth(|buf| cursor.read(buf)).unwrap(),
}
}
fn client() -> (TokenClient, Runtime) {
let client = direct_token_client();
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
(client, runtime)
}
fn recv(server: &Server) -> tiny_http::Request {
server
.recv_timeout(Duration::from_secs(5))
.unwrap()
.expect("expected HTTP request")
}
#[test]
fn obtains_fresh_subject_tokens_using_github_request_credential() {
let (server, url) = server();
let worker = thread::spawn(move || {
for token in ["github.first.jwt", "github.second.jwt"] {
let req = recv(&server);
assert_eq!(req.url(), "/github");
assert_eq!(req.method(), &tiny_http::Method::Get);
assert!(req.headers().iter().any(|h| h.field.equiv("Authorization")
&& h.value.as_str() == "Bearer private.github.request"));
req.respond(
tiny_http::Response::from_string(json!({"value": token}).to_string())
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap()),
)
.unwrap();
}
});
let mut source: Box<dyn SubjectTokenSource> = Box::new(source_at(&url));
let (client, runtime) = client();
runtime.block_on(async {
assert_eq!(
source.subject_token(&client).await.unwrap().as_str(),
"github.first.jwt"
);
assert_eq!(
source.subject_token(&client).await.unwrap().as_str(),
"github.second.jwt"
);
});
worker.join().unwrap();
}
#[test]
#[tracing_test::traced_test]
fn rejected_subject_does_not_log_response_or_follow_redirect() {
tracing::debug!(target: "codex_http_client::client", "credential log capture sentinel");
let (server, url) = server();
let target = url.join("/credential-leak").unwrap();
let worker = thread::spawn(move || {
let req = recv(&server);
assert_eq!(req.url(), "/github?opaque=private.github.url");
req.respond(
tiny_http::Response::from_string("private.github.request")
.with_status_code(StatusCode(302))
.with_header(Header::from_bytes("Location", target.as_str()).unwrap()),
)
.unwrap();
assert!(
server
.recv_timeout(Duration::from_millis(200))
.unwrap()
.is_none()
);
});
let (client, runtime) = client();
let mut source = source_at(&url);
source
.request_url
.set_query(Some("opaque=private.github.url"));
let error = format!(
"{:#}",
runtime.block_on(source.subject_token(&client)).unwrap_err()
);
assert!(error.contains("302"), "{error}");
assert!(!error.contains("private.github.request"), "{error}");
assert!(!error.contains("private.github.url"), "{error}");
assert!(!error.contains(url.as_str()), "{error}");
worker.join().unwrap();
assert!(logs_contain("credential log capture sentinel"));
assert!(!logs_contain("private.github.url"));
assert!(!logs_contain("private.github.request"));
}
#[test]
fn malformed_json_cannot_echo_a_secret_in_diagnostics() {
let (server, url) = server();
let worker = thread::spawn(move || {
recv(&server)
.respond(tiny_http::Response::from_string(
r#"{"value": private.github.request}"#,
))
.unwrap();
});
let (client, runtime) = client();
let error = format!(
"{:#}",
runtime
.block_on(source_at(&url).subject_token(&client))
.unwrap_err()
);
assert!(error.contains("invalid token response"), "{error}");
assert!(!error.contains("private.github.request"), "{error}");
worker.join().unwrap();
}

View File

@@ -0,0 +1,348 @@
use std::fs::File;
use std::fs::{self};
use std::io::Read;
use std::io::Write;
use std::net::SocketAddr;
use std::net::TcpListener;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use clap::Parser;
use reqwest::Url;
use reqwest::blocking::Client;
use reqwest::header::AUTHORIZATION;
use reqwest::header::HOST;
use reqwest::header::HeaderMap;
use reqwest::header::HeaderName;
use reqwest::header::HeaderValue;
use serde::Serialize;
use tiny_http::Header;
use tiny_http::Method;
use tiny_http::Request;
use tiny_http::Response;
use tiny_http::Server;
use tiny_http::StatusCode;
mod auth;
mod dump;
mod github_oidc;
mod read_api_key;
use auth::Auth;
use dump::ExchangeDumper;
use github_oidc::GithubOidc;
use read_api_key::read_auth_header_from_stdin;
const OPENAI_RESPONSES_URL: &str = "https://api.openai.com/v1/responses";
/// CLI arguments for the proxy.
#[derive(Clone, Debug, Parser)]
#[command(name = "responses-api-proxy", about = "Minimal OpenAI responses proxy")]
pub struct Args {
/// Port to listen on. If not set, an ephemeral port is used.
#[arg(long)]
pub port: Option<u16>,
/// Path to a JSON file to write startup info (single line). Includes {"port": <u16>}.
#[arg(long, value_name = "FILE")]
pub server_info: Option<PathBuf>,
/// Enable HTTP shutdown endpoint at GET /shutdown
#[arg(long)]
pub http_shutdown: bool,
/// Absolute URL the proxy should forward requests to (defaults to OpenAI).
#[arg(long, default_value = "https://api.openai.com/v1/responses")]
pub upstream_url: String,
/// Directory where request/response dumps should be written as JSON.
#[arg(long, value_name = "DIR")]
pub dump_dir: Option<PathBuf>,
/// Authenticate to the OpenAI API using GitHub Actions workload identity.
/// In this mode stdin supplies the GitHub OIDC request token, not an API key.
#[arg(long, requires_all = ["oidc_audience", "identity_provider_id", "service_account_id", "github_oidc_request_url"])]
pub github_oidc: bool,
/// Audience configured on the OpenAI workload identity provider.
#[arg(long, requires = "github_oidc", value_name = "AUDIENCE")]
pub oidc_audience: Option<String>,
/// OpenAI workload identity provider ID.
#[arg(long, requires = "github_oidc", value_name = "ID")]
pub identity_provider_id: Option<String>,
/// OpenAI service account ID selected by the provider mapping.
#[arg(long, requires = "github_oidc", value_name = "ID")]
pub service_account_id: Option<String>,
/// HTTPS token-request URL from GitHub's runner-provided ACTIONS_ID_TOKEN_REQUEST_URL.
///
/// Use the value directly from the trusted runner environment, never from
/// a workflow input or repository content. The proxy sends the GitHub
/// request credential to this URL.
#[arg(long, requires = "github_oidc", value_name = "URL")]
pub github_oidc_request_url: Option<String>,
}
impl Args {
fn auth(&self) -> Result<Auth> {
if self.github_oidc {
Auth::validate_federated_upstream(&self.upstream_url)?;
let provider = required(&self.identity_provider_id, "--identity-provider-id")?;
let service_account = required(&self.service_account_id, "--service-account-id")?;
let audience = required(&self.oidc_audience, "--oidc-audience")?;
let request_url = required(&self.github_oidc_request_url, "--github-oidc-request-url")?;
Auth::federated(
GithubOidc::from_stdin(request_url, audience)?,
provider.to_owned(),
service_account.to_owned(),
)
} else {
Ok(Auth::ApiKey(read_auth_header_from_stdin()?))
}
}
}
fn required<'a>(value: &'a Option<String>, name: &str) -> Result<&'a str> {
value
.as_deref()
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| anyhow!("workload identity requires a nonempty {name}"))
}
#[derive(Serialize)]
struct ServerInfo {
port: u16,
pid: u32,
}
struct ForwardConfig {
upstream_url: Url,
host_header: HeaderValue,
}
/// Entry point for the library main, for parity with other crates.
pub fn run_main(args: Args) -> Result<()> {
let auth = Arc::new(args.auth()?);
if args.github_oidc {
// Complete the initial exchange before publishing server info.
// API keys have already been validated when read from stdin.
auth.header()?;
}
let upstream_url = Url::parse(&args.upstream_url).context("parsing --upstream-url")?;
let host = match (upstream_url.host_str(), upstream_url.port()) {
(Some(host), Some(port)) => format!("{host}:{port}"),
(Some(host), None) => host.to_string(),
_ => return Err(anyhow!("upstream URL must include a host")),
};
let host_header =
HeaderValue::from_str(&host).context("constructing Host header from upstream URL")?;
let forward_config = Arc::new(ForwardConfig {
upstream_url,
host_header,
});
let dump_dir = args
.dump_dir
.map(ExchangeDumper::new)
.transpose()
.context("creating --dump-dir")?
.map(Arc::new);
let (listener, bound_addr) = bind_listener(args.port)?;
if let Some(path) = args.server_info.as_ref() {
write_server_info(path, bound_addr.port())?;
}
let server = Server::from_listener(listener, None)
.map_err(|err| anyhow!("creating HTTP server: {err}"))?;
let client = Arc::new(
Client::builder()
.redirect(auth.redirect_policy())
// Disable reqwest's 30s default so long-lived response streams keep flowing.
.timeout(None::<Duration>)
.build()
.context("building reqwest client")?,
);
eprintln!("responses-api-proxy listening on {bound_addr}");
let http_shutdown = args.http_shutdown;
for request in server.incoming_requests() {
let client = client.clone();
let auth = auth.clone();
let forward_config = forward_config.clone();
let dump_dir = dump_dir.clone();
std::thread::spawn(move || {
if http_shutdown && request.method() == &Method::Get && request.url() == "/shutdown" {
let _ = request.respond(Response::new_empty(StatusCode(200)));
std::process::exit(0);
}
if let Err(e) = forward_request(
&client,
&auth,
&forward_config,
dump_dir.as_deref(),
request,
) {
eprintln!("forwarding error: {e}");
}
});
}
Err(anyhow!("server stopped unexpectedly"))
}
fn bind_listener(port: Option<u16>) -> Result<(TcpListener, SocketAddr)> {
let addr = SocketAddr::from(([127, 0, 0, 1], port.unwrap_or(0)));
let listener = TcpListener::bind(addr).with_context(|| format!("failed to bind {addr}"))?;
let bound = listener.local_addr().context("failed to read local_addr")?;
Ok((listener, bound))
}
fn write_server_info(path: &Path, port: u16) -> Result<()> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent)?;
}
let info = ServerInfo {
port,
pid: std::process::id(),
};
let mut data = serde_json::to_string(&info)?;
data.push('\n');
let mut f = File::create(path)?;
f.write_all(data.as_bytes())?;
Ok(())
}
fn forward_request(
client: &Client,
auth: &Auth,
config: &ForwardConfig,
dump_dir: Option<&ExchangeDumper>,
mut req: Request,
) -> Result<()> {
// Only allow POST /v1/responses exactly, no query string.
let method = req.method().clone();
let url_path = req.url().to_string();
let allow = method == Method::Post && url_path == "/v1/responses";
if !allow {
let resp = Response::new_empty(StatusCode(403));
let _ = req.respond(resp);
return Ok(());
}
// Read request body
let mut body = Vec::new();
let reader = req.as_reader();
reader.read_to_end(&mut body)?;
let exchange_dump = dump_dir.and_then(|dump_dir| {
dump_dir
.dump_request(&method, &url_path, req.headers(), &body)
.map_err(|err| {
eprintln!("responses-api-proxy failed to dump request: {err}");
err
})
.ok()
});
// Build headers for upstream, forwarding everything from the incoming
// request except Authorization (we replace it below).
let mut headers = HeaderMap::new();
for header in req.headers() {
let name_ascii = header.field.as_str();
let lower = name_ascii.to_ascii_lowercase();
if lower.as_str() == "authorization" || lower.as_str() == "host" {
continue;
}
let header_name = match HeaderName::from_bytes(lower.as_bytes()) {
Ok(name) => name,
Err(_) => continue,
};
if let Ok(value) = HeaderValue::from_bytes(header.value.as_bytes()) {
headers.append(header_name, value);
}
}
let auth_header = match auth.header() {
Ok(value) => value,
Err(err) => {
// No token, request URL or upstream error body is exposed to the caller.
let _ = req.respond(Response::new_empty(StatusCode(502)));
return Err(err);
}
};
headers.insert(AUTHORIZATION, auth_header.value.clone());
headers.insert(HOST, config.host_header.clone());
let upstream_resp = client
.post(config.upstream_url.clone())
.headers(headers)
.body(body)
.send()
.context("forwarding request to upstream")?;
// We have to create an adapter between a `reqwest::blocking::Response`
// and a `tiny_http::Response`. Fortunately, `reqwest::blocking::Response`
// implements `Read`, so we can use it directly as the body of the
// `tiny_http::Response`.
let status = upstream_resp.status();
if status == reqwest::StatusCode::UNAUTHORIZED {
// Do not replay a Responses POST. A subsequent request can obtain a
// fresh credential, but a late 401 must not evict one renewed in-flight.
auth_header.invalidate();
}
let mut response_headers = Vec::new();
for (name, value) in upstream_resp.headers().iter() {
// Skip headers that tiny_http manages itself.
if matches!(
name.as_str(),
"content-length" | "transfer-encoding" | "connection" | "trailer" | "upgrade"
) {
continue;
}
if let Ok(header) = Header::from_bytes(name.as_str().as_bytes(), value.as_bytes()) {
response_headers.push(header);
}
}
let content_length = upstream_resp.content_length().and_then(|len| {
if len <= usize::MAX as u64 {
Some(len as usize)
} else {
None
}
});
let response_body: Box<dyn Read + Send> = if let Some(exchange_dump) = exchange_dump {
let headers = upstream_resp.headers().clone();
Box::new(exchange_dump.tee_response_body(status.as_u16(), &headers, upstream_resp))
} else {
Box::new(upstream_resp)
};
let response = Response::new(
StatusCode(status.as_u16()),
response_headers,
response_body,
content_length,
None,
);
let _ = req.respond(response);
Ok(())
}

View File

@@ -0,0 +1,12 @@
use clap::Parser;
use codex_responses_api_proxy::Args as ResponsesApiProxyArgs;
#[ctor::ctor]
fn pre_main() {
codex_process_hardening::pre_main_hardening();
}
pub fn main() -> anyhow::Result<()> {
let args = ResponsesApiProxyArgs::parse();
codex_responses_api_proxy::run_main(args)
}

View File

@@ -0,0 +1,361 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use zeroize::Zeroize;
/// Use a generous buffer size to avoid truncation and to allow for longer API
/// keys in the future.
const BUFFER_SIZE: usize = 1024;
pub(crate) const AUTH_HEADER_PREFIX: &[u8] = b"Bearer ";
/// Reads the auth token from stdin and returns a static `Authorization` header
/// value with the auth token used with `Bearer`. The header value is returned
/// as a `&'static str` whose bytes are locked in memory to avoid accidental
/// exposure.
pub(crate) fn read_auth_header_from_stdin() -> Result<&'static str> {
read_api_key_with(read_from_stdin)
}
fn read_api_key_with(
read_fn: impl FnMut(&mut [u8]) -> std::io::Result<usize>,
) -> Result<&'static str> {
read_auth_header_with::<BUFFER_SIZE>(read_fn, validate_auth_header_bytes, || {
anyhow!("API key is too large to fit in the {BUFFER_SIZE}-byte buffer")
})
}
#[cfg(windows)]
pub(crate) fn read_from_stdin(buffer: &mut [u8]) -> std::io::Result<usize> {
use std::io::Read;
// Use of `stdio::io::stdin()` has the problem mentioned in the docstring on
// the UNIX version of `read_from_stdin()`, so this should ultimately
// be replaced the low-level Windows equivalent. Because we do not have an
// equivalent of mlock() on Windows right now, it is not pressing until we
// address that issue.
std::io::stdin().read(buffer)
}
/// We perform a low-level read with `read(2)` because `stdio::io::stdin()` has
/// an internal BufReader:
///
/// https://github.com/rust-lang/rust/blob/bcbbdcb8522fd3cb4a8dde62313b251ab107694d/library/std/src/io/stdio.rs#L250-L252
///
/// that can end up retaining a copy of stdin data in memory with no way to zero
/// it out, whereas we aim to guarantee there is exactly one copy of the API key
/// in memory, protected by mlock(2).
#[cfg(unix)]
pub(crate) fn read_from_stdin(buffer: &mut [u8]) -> std::io::Result<usize> {
use libc::c_void;
use libc::read;
// Perform a single read(2) call into the provided buffer slice.
// Looping and newline/EOF handling are managed by the caller.
loop {
let result = unsafe {
read(
libc::STDIN_FILENO,
buffer.as_mut_ptr().cast::<c_void>(),
buffer.len(),
)
};
if result == 0 {
return Ok(0);
}
if result < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::Interrupted {
continue;
}
return Err(err);
}
return Ok(result as usize);
}
}
/// Reads and locks one permanent credential. The validator receives the raw
/// token line and returns the length of its validated prefix after trimming.
/// The buffer size includes the Bearer prefix and any line terminators.
/// Do not use for renewable tokens: the allocation lives until process exit.
pub(crate) fn read_auth_header_with<const N: usize>(
mut read_fn: impl FnMut(&mut [u8]) -> std::io::Result<usize>,
validate: impl FnOnce(&[u8]) -> Result<usize>,
buffer_full_error: impl FnOnce() -> anyhow::Error,
) -> Result<&'static str> {
// TAKE CARE WHEN MODIFYING THIS CODE!!!
//
// This function goes to great lengths to avoid leaving the credential in
// memory longer than necessary and to avoid copying it around. We read
// directly into a stack buffer so the only heap allocation should be the
// one to create the String (with the exact size) for the header value,
// which we then immediately protect with mlock(2).
let mut buf = [0u8; N];
buf[..AUTH_HEADER_PREFIX.len()].copy_from_slice(AUTH_HEADER_PREFIX);
let prefix_len = AUTH_HEADER_PREFIX.len();
let capacity = buf.len() - prefix_len;
let mut total_read = 0usize; // number of bytes read into the token region
let mut saw_newline = false;
let mut saw_eof = false;
while total_read < capacity {
let slice = &mut buf[prefix_len + total_read..];
let read = match read_fn(slice) {
Ok(n) => n,
Err(err) => {
buf.zeroize();
return Err(err.into());
}
};
if read == 0 {
saw_eof = true;
break;
}
// Search only the newly written region for a newline.
let newly_written = &slice[..read];
if let Some(pos) = newly_written.iter().position(|&b| b == b'\n') {
total_read += pos + 1; // include the newline for trimming below
saw_newline = true;
break;
}
total_read += read;
// Continue loop; if buffer fills without newline/EOF we'll error below.
}
// If buffer filled and we did not see newline or EOF, error out.
if total_read == capacity && !saw_newline && !saw_eof {
buf.zeroize();
return Err(buffer_full_error());
}
let total = match validate(&buf[prefix_len..prefix_len + total_read]) {
Ok(len) => prefix_len + len,
Err(err) => {
buf.zeroize();
return Err(err);
}
};
let header_str = match std::str::from_utf8(&buf[..total]) {
Ok(value) => value,
Err(err) => {
// In theory, the validator should have caught
// any invalid UTF-8 sequences, but just in case...
buf.zeroize();
return Err(err).context("reading Authorization header from stdin as UTF-8");
}
};
let header_value = String::from(header_str);
buf.zeroize();
let leaked: &'static mut str = header_value.leak();
mlock_str(leaked);
Ok(leaked)
}
#[cfg(unix)]
fn mlock_str(value: &'static str) {
use libc::_SC_PAGESIZE;
use libc::c_void;
use libc::mlock;
use libc::sysconf;
if value.is_empty() {
return;
}
let page_size = unsafe { sysconf(_SC_PAGESIZE) };
if page_size <= 0 {
return;
}
let page_size = page_size as usize;
if page_size == 0 {
return;
}
let addr = value.as_ptr() as usize;
let len = value.len();
let start = addr & !(page_size - 1);
let addr_end = match addr.checked_add(len) {
Some(v) => match v.checked_add(page_size - 1) {
Some(total) => total,
None => return,
},
None => return,
};
let end = addr_end & !(page_size - 1);
let size = end.saturating_sub(start);
if size == 0 {
return;
}
let _ = unsafe { mlock(start as *const c_void, size) };
}
#[cfg(not(unix))]
fn mlock_str(_value: &'static 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(mut key_bytes: &[u8]) -> Result<usize> {
while key_bytes
.last()
.is_some_and(|byte| matches!(byte, b'\n' | b'\r'))
{
key_bytes = &key_bytes[..key_bytes.len() - 1];
}
if key_bytes.is_empty() {
return Err(anyhow!(
"API key must be provided via stdin (e.g. printenv OPENAI_API_KEY | env -u OPENAI_API_KEY codex-responses-api-proxy)"
));
}
if key_bytes
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
{
return Ok(key_bytes.len());
}
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_api_key_with(|buf| {
if sent {
return Ok(0);
}
let data = b"sk-abc123";
buf[..data.len()].copy_from_slice(data);
sent = true;
Ok(data.len())
})
.unwrap();
assert_eq!(result, "Bearer sk-abc123");
}
#[test]
fn reads_key_with_short_reads() {
let mut chunks: VecDeque<&[u8]> =
VecDeque::from(vec![b"sk-".as_ref(), b"abc".as_ref(), b"123\n".as_ref()]);
let result = read_api_key_with(|buf| match chunks.pop_front() {
Some(chunk) if !chunk.is_empty() => {
buf[..chunk.len()].copy_from_slice(chunk);
Ok(chunk.len())
}
_ => Ok(0),
})
.unwrap();
assert_eq!(result, "Bearer sk-abc123");
}
#[test]
fn reads_key_and_trims_newlines() {
let mut sent = false;
let result = read_api_key_with(|buf| {
if sent {
return Ok(0);
}
let data = b"sk-abc123\r\n";
buf[..data.len()].copy_from_slice(data);
sent = true;
Ok(data.len())
})
.unwrap();
assert_eq!(result, "Bearer sk-abc123");
}
#[test]
fn errors_when_no_input_provided() {
let err = read_api_key_with(|_| Ok(0)).unwrap_err();
let message = format!("{err:#}");
assert!(message.contains("must be provided"));
}
#[test]
fn errors_when_buffer_filled() {
let err = read_api_key_with(|buf| {
let data = vec![b'a'; BUFFER_SIZE - AUTH_HEADER_PREFIX.len()];
buf[..data.len()].copy_from_slice(&data);
Ok(data.len())
})
.unwrap_err();
let message = format!("{err:#}");
let expected_error =
format!("API key is too large to fit in the {BUFFER_SIZE}-byte buffer");
assert!(message.contains(&expected_error));
}
#[test]
fn propagates_io_error() {
let err = read_api_key_with(|_| Err(io::Error::other("boom"))).unwrap_err();
let io_error = err.downcast_ref::<io::Error>().unwrap();
assert_eq!(io_error.kind(), io::ErrorKind::Other);
assert_eq!(io_error.to_string(), "boom");
}
#[test]
fn errors_on_invalid_utf8() {
let mut sent = false;
let err = read_api_key_with(|buf| {
if sent {
return Ok(0);
}
let data = b"sk-abc\xff";
buf[..data.len()].copy_from_slice(data);
sent = true;
Ok(data.len())
})
.unwrap_err();
let message = format!("{err:#}");
assert!(message.contains("API key may only contain ASCII letters, numbers, '-' or '_'"));
}
#[test]
fn errors_on_invalid_characters() {
for data in [
b"sk-abc!23".as_slice(),
b"sk.abc123",
b"sk-abc+123",
b"sk-abc=123",
] {
let mut sent = false;
let err = read_api_key_with(|buf| {
if sent {
return Ok(0);
}
buf[..data.len()].copy_from_slice(data);
sent = true;
Ok(data.len())
})
.unwrap_err();
let message = format!("{err:#}");
assert!(
message.contains("API key may only contain ASCII letters, numbers, '-' or '_'")
);
}
}
}