25. Configuration, Features, and Sign-In

Codex builds its configuration by folding TOML layers in the order of ten fixed precedence values, then lets a separate requirements stack bound what any layer may choose. Feature flags and credentials ride on the same machinery: flags are keys in that TOML, and sign-in writes to a file or keyring under the same CODEX_HOME.

Every surface reads the same configuration. The terminal UI, codex exec, and the app server (see Chapter 21) all call into codex-config and codex-core, so one config.toml and one auth.json govern every client on a machine. That makes three questions central for an operator: which file wins when two disagree, how an administrator can pin a value, and where the agent’s credentials come from.

This chapter answers them in order. It starts with CODEX_HOME and the shape of config.toml, walks the layer stack and its precedence numbers, then covers the requirements stack that constrains values, config editing, and schema generation. The second half covers the feature-flag registry and the sign-in flows. Approval and sandbox keys belong to Chapters 13 and 14, and MCP server tables to Chapter 17.

The picture

Configuration layers stack from packaged defaults at precedence -10 through system, cloud, user, profile, project, and session layers to legacy managed config at 40 and 50; the folded result passes through requirements constraints into Config, and the features table becomes ManagedFeatures, which requirements can also pin.

Follow the grey chain from the top left. Each arrow means “the next layer overrides this one,” so packaged defaults lose to everything and legacy managed configuration wins over everything. The project layer is dashed because it loads but stays disabled until you trust the directory. The fold produces one effective TOML value, and the red arrows show requirements.toml acting from the side: it does not add a layer, it rejects or replaces values that the layers chose. The [features] table from the result becomes ManagedFeatures, which requirements can pin as well.

Where configuration lives

CODEX_HOME

find_codex_home in codex-rs/utils/home-dir/src/lib.rs returns the CODEX_HOME environment variable when it is set and non-empty, else ~/.codex. A set CODEX_HOME must already exist and be a directory; the function canonicalizes it and fails otherwise. The default path is not checked. Everything in Chapter 24 lives here unless redirected: sessions/, history.jsonl, the SQLite files (movable with CODEX_SQLITE_HOME or sqlite_home), auth.json, and config.toml.

config.toml and its schema

ConfigToml in codex-rs/config/src/config_toml.rs is the type that ~/.codex/config.toml deserializes into. Keys are flat or grouped into tables. This excerpt is trimmed from the fixture create_test_fixture in codex-rs/core/src/config/config_tests.rs. The last table adds a trust entry in the shape the same test file uses:

model = "o3"
approval_policy = "on-request"

[analytics]
enabled = true

[model_providers.openai-custom]
name = "OpenAI custom"
base_url = "https://api.openai.com/v1"
env_key = "OPENAI_API_KEY"
wire_api = "responses"
request_max_retries = 4            # retry failed HTTP requests
stream_max_retries = 10            # retry dropped SSE streams

[profiles.o3]
model = "o3"
model_provider = "openai"
approval_policy = "never"
model_reasoning_effort = "high"

[projects."/home/me/repo"]
trust_level = "trusted"

A JSON Schema of this type is committed at codex-rs/core/config.schema.json (291,492 bytes at this commit) so editors can validate and complete keys. The codex-write-config-schema binary regenerates it through codex_config::schema::write_config_schema, and just write-config-schema runs that binary. ConfigToml carries #[schemars(deny_unknown_fields)], so the published schema flags unknown keys; the attribute shapes the schema output, not the Serde parser.

Layers and precedence

The precedence table

ConfigLayerSource::precedence in codex-rs/config/src/config_layer_source.rs assigns each source a number, and a higher number overrides a lower one. The table lists all ten values.

Precedence Source Where it comes from
-10 PackagedDefaults defaults.toml compiled into the binary, or a package file
0 Mdm Managed preferences (see note below)
10 System /etc/codex/config.toml, or %ProgramData%\OpenAI\Codex\config.toml
15 EnterpriseManaged Enterprise cloud config bundle
20 User ${CODEX_HOME}/config.toml
21 User with profile ${CODEX_HOME}/<name>.config.toml
25 Project .codex/config.toml in the cwd, parents, or repo root
30 SessionFlags -c, --enable, UI selections
40 LegacyManagedConfigTomlFromFile managed_config.toml
50 LegacyManagedConfigTomlFromMdm macOS managed preferences

The Mdm variant at 0 is declared and handled across the code, but the loader at this commit turns macOS managed preferences (domain com.openai.codex, key config_toml_base64) into the LegacyManagedConfigTomlFromMdm layer at 50. No loader path that constructs Mdm was found in the code read for this chapter. The loader README describes the two legacy managed layers as “being phased out.”

Folding and origins

load_config_layers_state in codex-rs/config/src/loader/mod.rs reads every source and returns a ConfigLayerStack. The stack stores layers lowest precedence first, so effective_config() can fold them in order with merge_toml_values, letting later tables override earlier keys. The README lists two extra outputs: per-key origins, which tell a UI which layer won each key, and per-layer version fingerprints for optimistic concurrency when a client writes back. A layer with a disabled_reason still appears in the stack for display, but the fold skips it. This is a layered configuration with explicit provenance, and it lets the TUI’s /debug-config command show config layers and requirement sources without guessing.

Overrides with -c

CliConfigOverrides in codex-rs/utils/cli/src/config_override.rs collects every -c key=value. It splits on the first =, so values may contain =. It parses the right side as TOML and falls back to a literal string, which is why -c model=o3 works without quotes. Dotted keys address nested tables. The help text now calls the flag “Deprecated. Override a legacy configuration key,” and points users to dedicated flags or config.toml. Feature switches use the same path: --enable X and --disable X validate X against the registry, then expand to features.X=true or features.X=false in the SessionFlags layer.

Profiles

Two profile forms coexist. The legacy form is a [profiles.<name>] table inside config.toml, selected by a profile = "<name>" key; ConfigToml still parses it into HashMap<String, ConfigProfile>. The newer form is a separate file, ${CODEX_HOME}/<name>.config.toml. The loader adds it “as a second user layer on top so the profile only needs to contain overrides.” Mixing them is an error: --profile foo fails with a message that names both files if config.toml still contains profile = "foo" or a [profiles.foo] table.

Project config and trust

Project layers come from repository contents, which an attacker can write. The loader loads them but sets a disabled_reason until the directory is trusted. The message names what is gated: “project-local config, hooks, and exec policies.” Even a trusted project layer loses keys on PROJECT_LOCAL_CONFIG_DENYLIST, including model_provider, model_providers, openai_base_url, chatgpt_base_url, notify, profile, profiles, and otel. The source comment gives the reason: project config “should not get to choose where a user’s credentials are sent or which local commands are run.” The loader removes those keys and records them as ignored.

Requirements: the constraint stack

Configuration says what you want; requirements say what is allowed. The requirements stack merges, in ascending order, /etc/codex/requirements.toml (or %ProgramData%\OpenAI\Codex\requirements.toml), enterprise cloud bundles, the legacy /etc/codex/managed_config.toml reinterpreted as requirements, and on macOS the managed preference key requirements_toml_base64. ConfigRequirementsToml in codex-rs/config/src/config_requirements.rs holds the fields. Many are allow-lists: allowed_approval_policies, allowed_sandbox_modes, allowed_login_methods, allowed_chatgpt_workspaces, and allowed_web_search_modes. Others pin a value, such as model_provider, sqlite_home, or cli_auth_credentials_store, and a [features] table pins flags.

Each constrained setting is a Constrained<T> from codex-rs/config/src/constraint.rs: a value plus a validator and an optional normalizer, so every later set is checked. When a configured value fails, apply_requirement_constrained_value in codex-rs/core/src/config/mod.rs keeps the required value. It also adds a startup warning that begins “Configured value for {field_name} is disallowed by requirements; falling back to required value” and then names the value and the error. Codex starts with a compliant value instead of refusing to start, and the warning names the field.

Editing configuration

Clients change settings through ConfigEdit, an enum in codex-rs/core/src/config/edit.rs with variants such as SetModel, EditMcpServer, SetSkillConfig, and SetTuiNotificationsEnabled. ConfigEditsBuilder batches edits, parses the current file as a toml_edit::DocumentMut, applies them, and writes the result with write_atomically. toml_edit preserves your comments and ordering, so a UI toggle does not reformat a hand-written file. codex features enable memories is one caller: it validates the key, calls set_feature_enabled, and prints a warning when the flag is still under development.

Feature flags

Declaring a flag

Every flag is one entry in the static FEATURES table in codex-rs/features/src/lib.rs. A FeatureSpec has four fields: the Feature enum value, the TOML key, a Stage, and default_enabled. An experimental flag also carries the text for the /experimental menu:

FeatureSpec {
    id: Feature::NetworkProxy,
    key: "network_proxy",
    stage: Stage::Experimental {
        name: "Network proxy",
        menu_description: "Apply network proxy restrictions to sandboxed sessions that already have network access.",
        announcement: "NEW: Network proxy can now be enabled from /experimental. Restart Codex after enabling it.",
    },
    default_enabled: false,
},

One reviewed table is a registry pattern: the CLI’s is_known_feature_key, the config schema, and codex features list all read the same list, so a typo in --enable fails with “Unknown feature flag” before Codex starts.

Stages and counts

The table holds 237 specs at this commit. The counts below come from a script over the FEATURES source and match the stage on macOS, Linux, and Windows.

Stage Specs Default on
UNDER DEVELOPMENT 100 1 (instant_interrupt)
STABLE 75 69, plus secret_auth_storage on Windows
REMOVED 52 10
EXPERIMENTAL 6 0
DEPRECATED 4 1 (multi_agent)
Total 237 81 (82 on Windows)

Five specs are always experimental; the sixth, prevent_idle_sleep, is experimental on those three systems and under development elsewhere. The 52 removed specs stay in the table so that old config files still parse. One of them, sqlite, is removed and on by default, which means SQLite state is no longer optional.

Resolution

Features::from_sources(base, profile, overrides) starts from every spec’s default. For the base config and then the legacy profile, it applies legacy toggles and the [features] table, mapping old aliases such as connectors to apps and recording a legacy-usage notice. It then applies the one remaining typed override, web_search_request, and calls normalize_dependencies, whose only rule enables code_mode when code_mode_only is on. ManagedFeatures in codex-rs/core/src/config/managed_features.rs wraps the result in a constrained value, so feature requirements apply at construction and on every later change.

Ten notable flags

These ten show the range of what flags gate. Stage and default are read from FEATURES.

Key Stage Default Gates
unified_exec STABLE on PTY-backed exec tool (see Chapter 10)
hooks STABLE on Lifecycle hooks from hooks.json
guardian_approval STABLE on Automatic review of approval prompts
apps STABLE on Apps (legacy alias connectors)
memories STABLE off Memory extraction and consolidation
multi_agent_v2 STABLE off Task-path multi-agent routing
multi_agent DEPRECATED on Original collab tools
code_mode UNDER DEVELOPMENT off JavaScript code mode
network_proxy EXPERIMENTAL off Managed network proxy
secret_auth_storage STABLE Windows only Encrypted secrets backend for auth

Sign-in

Modes

AuthMode in codex-rs/protocol/src/auth.rs has eight variants: ApiKey, Chatgpt, ChatgptAuthTokens, Headers, AgentIdentity, PersonalAccessToken, BedrockApiKey, and BedrockAccessKeys. Only Chatgpt, ChatgptAuthTokens, and PersonalAccessToken count as a ChatGPT account. The two common paths for a person are Sign in with ChatGPT and an API key; forced_login_method in config and allowed_login_methods in requirements can restrict which one is offered.

Sign in with ChatGPT

Plain codex login calls run_login_with_browser, which runs an Open Authorization (OAuth) 2.0 authorization-code flow with Proof Key for Code Exchange (PKCE). run_login_server in codex-rs/login/src/server.rs binds a local HTTP server on 127.0.0.1:1455. If the port is busy, it asks a previous login server on that port to cancel and retries up to 10 times, 200 ms apart. It then falls back to port 1457, which a source comment ties to the registered redirect allow-list. The redirect URI is http://127.0.0.1:<port>/auth/callback.

generate_pkce in codex-rs/login/src/oauth/pkce.rs makes the proof key. PKCE lets a client without a secret prove at token time that it started the request:

where is 64 random bytes, is URL-safe Base64 without padding, is the code verifier, and is the S256 code challenge. With these sizes has 86 characters and has 43. The browser opens {issuer}/oauth/authorize with the challenge, a random state, the client ID, and the scopes openid profile email offline_access api.connectors.read api.connectors.invoke. The default issuer is https://auth.openai.com.

The callback handler rejects a mismatched state with HTTP 400, then posts the code and to {issuer}/oauth/token. With tokens in hand, it checks any workspace restriction against the ID token. It then tries an OAuth token exchange for an API-key style token, tolerating failure, and persists everything before it redirects the browser to a success page.

Device code and API keys

codex login --device-auth serves machines with no local browser. request_device_code posts to {issuer}/api/accounts/deviceauth/usercode and prints a one-time code with the URL {issuer}/codex/device. poll_for_token then polls /deviceauth/token at the server’s interval, treating HTTP 403 and 404 as “not yet,” and gives up after 15 minutes.

For API keys, codex login --with-api-key reads the key from standard input, so it never appears in shell history or process lists. --with-access-token does the same for an access token. The old --api-key flag is hidden and only prints guidance. Some CLI entry points let CODEX_API_KEY in the environment take precedence over stored credentials, and the TUI’s onboarding screen pre-fills its key field from OPENAI_API_KEY.

Where credentials live

Credentials serialize as AuthDotJson in codex-rs/login/src/auth/storage.rs, with fields for auth_mode, OPENAI_API_KEY, tokens, last_refresh, agent_identity, personal_access_token, and the two Bedrock credential forms. cli_auth_credentials_store picks the backend. file, the default, writes CODEX_HOME/auth.json through a private temporary file (mode 0600 on Unix) that is synced and renamed into place. A reader therefore sees the old or the new document, never a torn one. keyring uses the OS keyring with service Codex Auth and account cli|<hash>. The hash is the first 16 hex characters of the SHA-256 of the canonical CODEX_HOME path, which gives each home its own entry. auto tries the keyring and falls back to the file, and ephemeral keeps credentials in memory for one process.

Token refresh

proactive_refresh_reason in codex-rs/login/src/auth/manager.rs decides when a ChatGPT session refreshes before a request:

where is the current time, is the expiry parsed from the access token’s JSON Web Token (JWT), and is last_refresh from storage. When the expiry parses, the function returns from the first branch, so the 8-day schedule applies only to tokens without a readable expiry. Refresh posts to https://auth.openai.com/oauth/token, or to {issuer}/oauth/token when the stored sign-in records its issuer; CODEX_REFRESH_TOKEN_URL_OVERRIDE replaces either. Failures map to distinct messages for an expired, reused, revoked, or account-mismatched refresh token, each telling you to sign in again.

Choosing auth per provider

Auth depends on the selected model provider. The built-ins are openai, amazon-bedrock, amazon-bedrock-runtime, gcp, ollama, and lmstudio; others come from [model_providers]. resolve_provider_auth in codex-rs/model-provider/src/auth.rs applies a fixed order, a chain of strategies:

  1. An API key from the provider’s env_key environment variable.
  2. The provider’s experimental_bearer_token.
  3. No credentials at all if the provider neither sets requires_openai_auth nor configures an auth command.
  4. Otherwise the stored sign-in, which the login screen created.

The openai provider sets requires_openai_auth = true, so it uses your ChatGPT sign-in or stored API key. A custom provider with only env_key never shows the login screen. A provider with an auth command gets an external bearer token from that command, and the Amazon Bedrock providers can sign requests with AWS Signature Version 4 (SigV4).

Status at commit 081295be9d. Layered config with ten precedence values: IMPLEMENTED. Mdm layer at 0: declared; no loader path builds it in the code read. Legacy managed layers at 40 and 50: IMPLEMENTED, described as being phased out. Managed preferences: PLATFORM-SPECIFIC (macOS). -c: IMPLEMENTED, help text says deprecated. Profile-v2 files: IMPLEMENTED alongside legacy [profiles]. secret_auth_storage: STABLE, on by default only on Windows. Feature counts: 237 specs, 81 on by default outside Windows. Read in code, not run.

What breaks

Symptom Cause Check
Codex exits at start naming CODEX_HOME The variable points to a missing path or a file find_codex_home
Project .codex/config.toml has no effect Directory untrusted, or key on the denylist [projects."<path>"] trust_level; startup warnings
--profile foo errors at start Legacy profile = "foo" or [profiles.foo] remains Loader message “cannot be used while”
A setting snaps back to another value A requirement disallows it Startup warning “disallowed by requirements”
A user setting is ignored A legacy managed layer at 40 or 50 sets it /etc/codex/managed_config.toml, MDM profile
“Unknown feature flag” Typo in --enable or --disable codex features list
Browser login hangs Ports 1455 and 1457 blocked codex login --device-auth
“refresh token was already used” Another process refreshed the same token Sign in again

Code map

What it is Where it lives Identifier
Precedence numbers codex:codex-rs/config/src/config_layer_source.rs pub fn precedence
Layer loader codex:codex-rs/config/src/loader/mod.rs PROJECT_LOCAL_CONFIG_DENYLIST
-c parsing codex:codex-rs/utils/cli/src/config_override.rs CliConfigOverrides
Requirements fields codex:codex-rs/config/src/config_requirements.rs allowed_sandbox_modes
Feature registry codex:codex-rs/features/src/lib.rs pub const FEATURES
Browser login codex:codex-rs/login/src/server.rs build_authorize_url
Credential storage codex:codex-rs/login/src/auth/storage.rs compute_store_key
Provider auth order codex:codex-rs/model-provider/src/auth.rs resolve_provider_auth

Recall check

Which wins, a key in config.toml or the same key passed with -c?
The -c value; SessionFlags has precedence 30, above the user layer at 20.

What happens when config.toml asks for a sandbox mode that requirements.toml forbids?
Codex falls back to the required value and adds a startup warning.

Why can a repository’s .codex/config.toml not set model_provider?
The key is on the project denylist, so repository contents cannot redirect credentials.

How many feature specs exist, and how many default on outside Windows?
237 specs, of which 81 default on.

What does PKCE protect in the browser login?
It proves at the token exchange that the same client started the request, using a hashed 64-byte verifier.