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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ The request size limit defaults to 64 MiB. Override it with `CODEX_GATEWAY_MAX_R
(pass it with Docker `-e`) or add `--max-request-bytes 67108864` to the executable
arguments. See [request limits](docs/common.md).

By default, only basic inference endpoints are exposed. Account, history,
workspace, auth, file storage, Realtime and arbitrary proxy routes return 403.
To enable the full API, pass `--restricted-api` or set
`CODEX_GATEWAY_RESTRICTED_API=true`
(Docker: `-e CODEX_GATEWAY_RESTRICTED_API=true`). See the
[allowed endpoints and account API audit](docs/restricted-api.md).

## Use

Generate text with the official OpenAI Python SDK:
Expand Down
1 change: 1 addition & 0 deletions docs/common.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ Gateway errors use this shape; `message` describes the failure:
| --- | --- |
| 400 | Invalid or unsupported request |
| 401 | Missing/wrong gateway key or unavailable subscription credentials |
| 403 | Endpoint disabled by [restricted-api mode](restricted-api.md) |
| 404 | Unknown endpoint |
| 413 | Request size limit exceeded; some JSON extractor failures use 400 |
| 415 | Unsupported media type or native content encoding |
Expand Down
5 changes: 5 additions & 0 deletions docs/native.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ The gateway uses Codex **0.162.1** and retains the native route inventory audite

## Credentials

By default, only the [inference allowlist](restricted-api.md) is accessible.
Other native routes, including generic proxy paths and account APIs, return
403 before forwarding. Pass `--restricted-api` or set
`CODEX_GATEWAY_RESTRICTED_API=true` to enable them.

Subscription routes use the gateway's Codex credentials. Send `Authorization: Bearer <gateway-key>`. The gateway removes caller authorization, account ID and actor-auth headers, then adds the original subscription identity. Subscription authorization is refreshed through Codex's auth manager.

Platform, API-key turn costs, personal-token identity, OAuth browser authorization, and remote-control server/pairing routes need their own upstream credentials:
Expand Down
86 changes: 86 additions & 0 deletions docs/restricted-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Restricted API mode

By default, the gateway exposes only the inference allowlist below. Account,
stored-data and generic proxy APIs are disabled. To allow these restricted APIs
and enable all gateway routes, pass `--restricted-api` (or
`--restricted-api=true`) or set `CODEX_GATEWAY_RESTRICTED_API=true`. Here the
flag means "allow restricted APIs." Restart the gateway after changing it.

```sh
# Default: basic inference only.
cargo run --locked --release -- --listen 127.0.0.1:8080
# Explicitly enable the full API:
cargo run --locked --release -- --restricted-api
# Equivalent environment variable:
CODEX_GATEWAY_RESTRICTED_API=true cargo run --locked --release
```

For Docker, pass `-e CODEX_GATEWAY_RESTRICTED_API=true` before the image name
only when the full API is needed. Unset or `false` keeps the default restrictions.
The CLI flag takes precedence over the environment variable;
`--restricted-api=false` explicitly keeps the restrictions enabled.
The gateway key and all existing request limits still apply in either mode.

## Allowed endpoints

Only these complete method/path combinations are allowed. Queries do not
change the policy. No wildcard proxy prefix is allowed.

| Methods | Paths | Purpose |
| --- | --- | --- |
| GET, HEAD | `/healthz` | Gateway health; no gateway key required |
| GET, HEAD | `/v1/models`, `/codex/models`, `/backend-api/codex/models` | Available model catalog |
| POST, GET | `/v1/responses`, `/codex/responses`, `/backend-api/codex/responses` | Inference over HTTP/SSE or WebSocket |
| POST | `/v1/responses/compact`, `/codex/responses/compact`, `/backend-api/codex/responses/compact` | Context compaction |
| POST | `/v1/images/generations`, `/codex/images/generations`, `/backend-api/codex/images/generations` | Image generation |
| POST | `/v1/images/edits`, `/codex/images/edits`, `/backend-api/codex/images/edits` | Image editing |
| POST | `/v1/alpha/search`, `/codex/alpha/search`, `/backend-api/codex/alpha/search` | Standalone search |
| POST | `/v1/audio/transcriptions`, `/transcribe`, `/backend-api/transcribe` | Audio transcription |

Everything else returns HTTP **403** with `error.code = "endpoint_disabled"`,
including unknown routes, unsupported methods, and new endpoints added later.
Protected requests without a valid gateway key still return 401. Rejection
happens before body extraction, concurrency acquisition, upstream forwarding
or WebSocket upgrade. A trailing slash, encoded path, or extra path component
does not grant access to an unlisted route.

## Account and stored-data API audit

The following groups were reviewed against the router, native origin/auth
selection, and all `gateway_paths` in
[`baseline/api-inventory.json`](../baseline/api-inventory.json). All are
disabled in this mode, including aliases.

| Group | Existing routes or families | Account or data exposure |
| --- | --- | --- |
| Account identity and profiles | `/backend-api/wham/accounts/check`, `/backend-api/wham/profiles/me`; `/api/codex/` aliases | Account membership, capabilities and profile statistics |
| Settings and workspace | `/backend-api/wham/settings/user`, `/backend-api/wham/config/bundle`, `/backend-api/wham/workspace-messages`; `/api/codex/` aliases | User preferences, configuration and workspace content |
| Usage and credits | `/backend-api/wham/usage`, `/backend-api/wham/usage/thread-estimates/query`, `/backend-api/wham/usage/thread_usage/query`, `/backend-api/wham/rate-limit-reset-credits` and `/consume`, `/backend-api/wham/accounts/send_add_credits_nudge_email`; `/api/codex/` aliases | Subscription usage, per-thread estimates, credits and credit-related actions |
| Cloud tasks and environments | `/backend-api/wham/tasks/*`, `/backend-api/wham/tasks`, `/backend-api/wham/environments/*`, `/backend-api/wham/environments`; `/api/codex/` aliases | Tasks, task turns, repository and environment metadata |
| History, notes and memory | `/codex/alpha/history/v2/*`, `/codex/alpha/notes/v2/*`, `/codex/memories/trace_summarize`; `/backend-api/codex/` aliases | Stored conversation history and notes; excluded memory helpers |
| Files and transfers | `/v1/files`, `/backend-api/files`, `/backend-api/files/*`, `/transfers/*` | Account file uploads, upload completion and signed blob capabilities |
| Apps, connectors, plugins and skills | `/backend-api/connectors/*`, `/backend-api/ps/*`, `/backend-api/public/plugins/*`, `/backend-api/plugins/*`, `/api/codex/ps/mcp` | Connected apps, installed/shared plugins, workspace skills and mutation operations |
| Remote control | `/backend-api/wham/remote/control/*`; `/api/codex/` aliases | Enrolled servers, pairing, clients and control channels |
| Authentication and agent identity | `/auth/*`, `/oauth/authorize`, `/backend-api/wham/agent-identities/jwks`; `/api/codex/` alias | Token/device exchanges, revocation, personal-token identity and agent registration |
| Platform proxy | `/platform/*` | Arbitrary public API resources using caller credentials, including stored resources |
| Realtime, live and guardian | `/v1/realtime*`, `/codex/realtime*`, `/backend-api/codex/realtime*`, `/v1/live*`, `/codex/live*`, `/backend-api/codex/live*`, `/codex/guardian`, `/codex/guardian-classifier`; backend aliases | Excluded session/control APIs and specialized inference surfaces |
| Telemetry and distribution | `/telemetry/*`, `/codex/analytics-events/events`, `/backend-api/codex/analytics-events/events`, `/distribution/*`, `/backend-api/wham/app/appcast`; `/api/codex/` alias | Cost reporting, metrics, feedback, updates and assets are outside the minimal surface |
| Generic native forwarding | Unlisted `/backend-api/*`, `/codex/*`, `/api/codex/*`, `/auth/*` paths | Prevents unreviewed or future upstream account APIs from bypassing this mode |

Some excluded endpoints use the caller's upstream credential rather than the
gateway's subscription, and some serve public data. They remain excluded to
keep the exposed surface explicit and small.

## Scope

This is an HTTP endpoint policy. Generation still runs with the configured
ChatGPT subscription and consumes its quota. Model discovery, authentication
refresh and startup device login continue internally; they are not exposed
as caller-accessible authentication routes.

Model availability, native inference responses, generated files and upstream
headers can still reflect subscription capabilities or inference metadata.
This mode does not redact inference output, isolate callers' upstream state,
or restrict tool execution inside an allowed inference request.
Account-management features in a connected Codex client that need excluded
routes will fail with 403. File uploads and Realtime/live are also unavailable.
36 changes: 35 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ struct Args {
/// Maximum HTTP body, decoded zstd body, and WebSocket message/frame size in bytes.
#[arg(long, env = "CODEX_GATEWAY_MAX_REQUEST_BYTES", default_value_t = 64 * 1024 * 1024, value_parser = parse_request_bytes)]
max_request_bytes: usize,
/// Allow restricted account, stored-data, and proxy APIs (disabled by default).
#[arg(long, env = "CODEX_GATEWAY_RESTRICTED_API", action = clap::ArgAction::Set,
num_args = 0..=1, require_equals = true, default_missing_value = "true",
default_value_t = false)]
restricted_api: bool,
}
fn parse_request_bytes(value: &str) -> Result<usize, String> {
let bytes = value.parse::<usize>().map_err(|e| e.to_string())?;
Expand Down Expand Up @@ -71,6 +76,7 @@ async fn main() -> anyhow::Result<()> {
let telemetry =
tokio::task::spawn_blocking(codex_api_gateway::telemetry::Telemetry::from_env).await??;
let gateway = Gateway {
allow_restricted_api: args.restricted_api,
telemetry: telemetry.clone(),
backend,
models,
Expand All @@ -83,7 +89,7 @@ async fn main() -> anyhow::Result<()> {
transfers,
};
let listener = tokio::net::TcpListener::bind(args.listen).await?;
tracing::info!(listen=%listener.local_addr()?, "Codex Responses gateway ready");
tracing::info!(listen=%listener.local_addr()?, allow_restricted_api=args.restricted_api, "Codex Responses gateway ready");
axum::serve(listener, router(gateway))
.with_graceful_shutdown(async {
#[cfg(unix)]
Expand All @@ -107,6 +113,34 @@ async fn main() -> anyhow::Result<()> {
mod tests {
use super::*;

#[test]
fn full_api_is_opt_in() {
// Inspect the CLI definition so an inherited environment cannot change
// the assertion about the default, or mask a missing flag.
use clap::CommandFactory;
let command = Args::command();
let argument = command
.get_arguments()
.find(|arg| arg.get_id() == "restricted_api")
.unwrap();
assert_eq!(argument.get_long(), Some("restricted-api"));
assert_eq!(
argument.get_env(),
Some(std::ffi::OsStr::new("CODEX_GATEWAY_RESTRICTED_API"))
);
let defaults = command
.mut_arg("restricted_api", |arg| arg.env(None::<&str>))
.try_get_matches_from(["gateway"])
.unwrap();
assert!(!defaults.get_flag("restricted_api"));
for flag in ["--restricted-api", "--restricted-api=true"] {
let args = Args::try_parse_from(["gateway", flag]).unwrap();
assert!(args.restricted_api);
}
let args = Args::try_parse_from(["gateway", "--restricted-api=false"]).unwrap();
assert!(!args.restricted_api);
}

#[test]
fn request_limit_defaults_to_64_mib() {
use clap::CommandFactory;
Expand Down
58 changes: 56 additions & 2 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use axum::{
body::Body,
extract::{DefaultBodyLimit, Query, State, rejection::JsonRejection},
http::{HeaderMap, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::{get, post},
};
Expand All @@ -14,6 +15,7 @@ use std::{sync::Arc, time::Duration};
use tokio::sync::Semaphore;

pub struct Gateway {
pub allow_restricted_api: bool,
pub backend: Backend,
pub models: Vec<ModelInfo>,
pub key: Option<String>,
Expand All @@ -25,6 +27,8 @@ pub struct Gateway {
}

pub fn router(gateway: Gateway) -> Router {
let max_request_bytes = gateway.max_request_bytes;
let gateway = Arc::new(gateway);
Router::new()
.route(
"/healthz",
Expand Down Expand Up @@ -72,8 +76,58 @@ pub fn router(gateway: Gateway) -> Router {
.route("/v1/live/sessions/{session_id}/attach", get(crate::realtime::upgrade))
.route("/transfers/{handle}", axum::routing::any(transfer))
.fallback(crate::native::handle)
.layer(DefaultBodyLimit::max(gateway.max_request_bytes))
.with_state(Arc::new(gateway))
.layer(DefaultBodyLimit::max(max_request_bytes))
.layer(middleware::from_fn_with_state(gateway.clone(), restricted_api_policy))
.with_state(gateway)
}

// Match complete paths and methods, including native aliases. New routes and
// arbitrary proxy paths stay closed until explicitly reviewed for this mode.
fn is_allowed_restricted_api(method: &http::Method, path: &str) -> bool {
use http::Method;
match path {
"/healthz" | "/v1/models" | "/codex/models" | "/backend-api/codex/models" => {
method == Method::GET || method == Method::HEAD
}
"/v1/responses" | "/codex/responses" | "/backend-api/codex/responses" => {
method == Method::POST || method == Method::GET
}
"/v1/responses/compact"
| "/codex/responses/compact"
| "/backend-api/codex/responses/compact"
| "/v1/images/generations"
| "/v1/images/edits"
| "/codex/images/generations"
| "/codex/images/edits"
| "/backend-api/codex/images/generations"
| "/backend-api/codex/images/edits"
| "/v1/alpha/search"
| "/codex/alpha/search"
| "/backend-api/codex/alpha/search"
| "/v1/audio/transcriptions"
| "/transcribe"
| "/backend-api/transcribe" => method == Method::POST,
_ => false,
}
}

async fn restricted_api_policy(
State(gateway): State<Arc<Gateway>>,
request: axum::extract::Request,
next: Next,
) -> Result<Response, GatewayError> {
if !gateway.allow_restricted_api
&& !is_allowed_restricted_api(request.method(), request.uri().path())
{
authorize(&gateway, request.headers())?;
return Err(GatewayError {
upstream_response: None,
status: StatusCode::FORBIDDEN,
code: "endpoint_disabled",
message: "endpoint disabled; enable full API access with --restricted-api".into(),
});
}
Ok(next.run(request).await)
}
async fn transfer(
State(gateway): State<Arc<Gateway>>,
Expand Down
Loading
Loading