Config, auth, and local state
Overview
This area owns Codex's local configuration model, the local Codex home, authentication storage and login flows, encrypted local secrets, cloud-managed configuration, feature and hook configuration, workload identity/AWS auth helpers, and repository/worktree helpers used while resolving configuration and trust.
Configuration is centered in codex-rs/…/config_toml.rs and codex-rs/…/types.rs. ConfigToml is the deserializable shape for config.toml, with schemars annotations and validation helpers such as validate_model_providers; types.rs holds effective/runtime-facing value types such as AuthCredentialsStoreMode, OAuthCredentialsStoreMode, AuthKeyringBackendKind, history/TUI/auth storage enums, and other simple settings. codex-rs/…/schema.rs turns these TOML types plus codex-rs/features metadata into the JSON schema, and the codex-rs/…/main.rs binary writes that schema to codex-rs/…/config.schema.json by default. The legacy codex-rs/config.md is only a pointer to the current docs.
Config loading is orchestrated by codex-rs/…/mod.rs. load_config_layers_state builds a ConfigLayerStack from low to high precedence: packaged defaults, macOS MDM where available, system config (etc/…/config.toml on Unix or the ProgramData equivalent on Windows), enterprise cloud fragments, $CODEX_HOME/config.toml, optional profile-v2 config ($CODEX_HOME/<profile>.config.toml), trusted project-local .codex/config.toml layers, runtime/session overrides, thread config layers, and legacy managed config. The same file also loads requirements in a parallel order (requirements.toml, cloud requirements, legacy managed requirements, and admin/MDM requirements) and composes them into ConfigRequirements. codex-rs/…/config_layer_source.rs defines source provenance and precedence, while codex-rs/…/state.rs stores materialized layers, versions/fingerprints, disabled reasons, the applied cloud/config-server binding, project trust status, and update helpers such as with_user_config and with_session_config.
Project config is deliberately narrower than user/system config. codex-rs/…/mod.rs discovers project roots using codex-rs/…/project_discovery.rs, Git trust helpers from codex-rs/…/trust.rs, and configured project-root markers, then disables untrusted project layers and strips project-local keys that could redirect credentials, change providers, run notifications, or alter proxy/credential-broker behavior. codex-rs/…/project_trust.rs, codex-rs/…/project_root_markers.rs, and the projects table in ConfigToml store trust decisions. Relative paths in config are resolved against the layer base directory before use; raw TOML is preserved in ConfigLayerEntry for diagnostics and hook discovery.
Local Codex home behavior is split by purpose. codex-rs/…/mod.rs loads global user instructions from $CODEX_HOME/AGENTS.override.md first and then $CODEX_HOME/AGENTS.md, caches the last successful instructions when a read fails, and suppresses repeated warnings until recovery. Config and auth code use $CODEX_HOME/config.toml, $CODEX_HOME/<profile>.config.toml, $CODEX_HOME/auth.json, $CODEX_HOME/auth.lock, $CODEX_HOME/secrets/*.age, $CODEX_HOME/cloud-config-bundle-cache.json, and $CODEX_HOME/managed-config-<namespace>.json as described by their owning modules. codex-rs/…/settings.rs also defaults managed worktrees to $CODEX_HOME/worktrees unless Desktop supplies an absolute desktop.git-worktree-root.
Authentication is exposed through codex-rs/…/lib.rs, which re-exports login helpers and AuthManager. codex-rs/…/manager.rs resolves auth from environment (OPENAI_API_KEY, CODEX_API_KEY, CODEX_ACCESS_TOKEN), persisted CLI auth, externally supplied bearer providers, workload identity, ChatGPT OAuth tokens, personal access tokens, agent identity JWTs, Bedrock API keys, or AWS access keys. AuthManagerConfig is the boundary used by callers (notably core config) so codex-login can read only resolved auth-related values: Codex home, credential store mode, keyring backend kind, forced login/workspace restrictions, managed auth policy, ChatGPT base URL, and auth route config. AuthManager caches the current CodexAuth, owns refresh locks and account-change notifications, applies managed login restrictions, and provides unauthorized recovery paths for callers that can retry after token refresh.
Interactive ChatGPT login uses two entry points. codex-rs/…/server.rs runs a localhost OAuth callback server with PKCE, defaulting to port 1455 with a fallback port, opens the browser when configured, validates forced workspace/account restrictions, exchanges the callback code, and persists resulting tokens via the selected auth store. codex-rs/…/device_code_auth.rs implements device-code login against /api/accounts/deviceauth/*, prints the user code, polls for an authorization code for up to 15 minutes, exchanges it through the same token path, and persists through server::persist_tokens_async. codex-rs/…/oauth_session.rs is a separate OAuth-session manager for gateway/config-server credentials: it uses provider OAuthSessionConfig, stores grants via file/keyring-backed OAuth storage, refreshes or starts browser login according to policy, and supports request-scoped retry after rejected access tokens.
CLI auth persistence is implemented in codex-rs/…/storage.rs. The file backend reads/writes $CODEX_HOME/auth.json atomically and guards commits with both an in-process mutex and $CODEX_HOME/auth.lock. The keyring backend stores serialized auth under service Codex Auth and an account derived from the canonical Codex home hash. AuthCredentialsStoreMode::Auto tries keyring first and falls back to file on load/save, while AuthCredentialsStoreMode::Keyring fails on keyring write errors. AuthKeyringBackendKind::Secrets stores auth in the encrypted secrets backend under the CODEX_AUTH secret instead of directly in the OS keyring; this is the Windows default in codex-rs/…/types.rs. codex-rs/…/lib.rs is the small OS-keyring abstraction used by auth, secrets, and OAuth storage; it intentionally hides payload-bearing keyring errors from error chains.
Encrypted local secrets live in codex-rs/secrets. codex-rs/…/lib.rs defines SecretName, SecretScope, SecretsManager, and environment_id_from_cwd; SecretName accepts only A-Z, digits, and _, while SecretScope serializes keys as global/<name> or env/<environment>/<name>. codex-rs/…/local.rs stores encrypted JSON maps in $CODEX_HOME/secrets/local.age, codex_auth.age, mcp_oauth.age, or gateway_oauth.age, depending on LocalSecretsNamespace; an age/scrypt passphrase is generated locally and stored in the OS keyring under service codex with an account derived from Codex home and namespace. Writes are atomic, decrypted snapshots are cached per namespace but revalidated against ciphertext and keyring passphrase, and gateway OAuth has an isolated file and key. codex-rs/…/sanitizer.rs provides best-effort redaction for OpenAI keys, AWS access key IDs, bearer tokens, and assignment-looking secret fields.
Cloud-managed config is fetched by codex-rs/cloud-config. codex-rs/…/bundle_loader.rs builds CloudConfigBundleLoader instances for ChatGPT-managed bundles or an explicit config server. ChatGPT bundles use codex-rs/…/chatgpt.rs, which only applies to backend-capable ChatGPT auth on business/education/enterprise/science-like plans and recovers one unauthorized fetch through AuthManager. Config-server bundles use codex-rs/…/config_server.rs, optionally authenticate with OAuthSessionManager, and scope cache namespaces to the endpoint plus OAuth grant identity. codex-rs/…/service.rs loads startup bundles with a 20-second timeout, prefers a valid cache, retries remote fetches up to five times, publishes snapshots to the config loader, and refreshes every 15 minutes in the background. codex-rs/…/cache.rs signs cache payloads with HMAC, enforces a one-hour TTL, and requires cache identity to match the active account; codex-rs/…/validation.rs parses bundle fragments through codex-config and validates managed model-provider requirements before caching or applying.
Feature flags are centralized in codex-rs/…/lib.rs. Feature and FEATURES define canonical keys, stage, default state, and experimental-menu metadata. Features::from_sources starts from defaults, applies base/profile [features] TOML, legacy experimental_use_unified_exec_tool, and runtime overrides, then normalizes dependencies such as enabling code_mode when code_mode_only is set. FeaturesToml supports both boolean toggles and structured per-feature tables from codex-rs/…/feature_configs.rs and codex-rs/…/runtime_auth.rs; codex-rs/…/legacy.rs maps legacy keys such as web_search, connectors, and codex_hooks to canonical features and records user-facing deprecation notices. codex-rs/…/schema.rs must stay in sync with this registry because it builds the schema for known structured feature tables and legacy keys.
Hook configuration straddles codex-rs/config and codex-rs/hooks. codex-rs/…/hook_config.rs defines the TOML/JSON-compatible config containers, hook state (enabled, trusted hash, trusted content hash), and managed hook requirements. codex-rs/…/lib.rs publishes the event-name contract, state key format, list APIs, and event request/outcome types. Runtime discovery in codex-rs/…/discovery.rs walks the active ConfigLayerStack, loads both hooks JSON files from each layer's .codex folder and TOML hook tables from config layers, applies managed-only restrictions from requirements, tracks hook trust state, and records required managed hook load failures. Dispatch in codex-rs/…/dispatcher.rs selects handlers by event and matcher, runs synchronous hooks in configured order, schedules async command/executor-scoped hooks, and only allows synchronous handlers to apply control effects. Command and MCP execution are implemented under codex-rs/…/command_runner.rs and mcp_runner.rs; hook input/output JSON schemas are generated from codex-rs/…/schema.rs and checked into codex-rs/hooks/schema/generated/**.
Workload identity is handled by codex-rs/workload-identity. codex-rs/…/lib.rs validates a non-empty federation rule and an assertion source that is either an absolute file path or a SpiffeWorkloadApi. codex-rs/…/assertion.rs reopens file assertions for every exchange, trims and rejects empty/NUL/over-16KiB assertions. codex-rs/…/spiffe.rs connects to a Unix SPIFFE Workload API endpoint, requests a JWT-SVID for one audience and optional SPIFFE ID, validates only selection claims locally, and leaves signature/expiry validation to the token endpoint. codex-rs/…/exchange.rs exchanges JWT bearer assertions for short-lived access tokens over HTTPS or loopback HTTP, uses the caller's HttpClientFactory and network policy, single-flights concurrent exchanges, refreshes before expiry, and reuses still-valid cached tokens after transient exchange failures.
AWS auth helpers live in codex-rs/aws-auth. codex-rs/…/config.rs loads AWS SDK config through the application-owned HTTP transport; codex-rs/…/transport.rs builds a Smithy HTTP connector that uses Codex route-aware auth clients, does not follow redirects, does not log requests, and preserves network-policy behavior. codex-rs/…/lib.rs resolves credentials from the SDK chain, a selected profile, static access keys, or a caller-supplied AwsCredentialsProvider, then signs AwsRequestToSign values with SigV4 after acquiring network-policy permission for the target URL. codex-rs/…/discovery.rs lists and validates shared AWS profiles, sorted with the selected profile first.
Worktree and Git helpers are covered because config trust, local state, and Desktop interop route through them. codex-rs/…/lib.rs creates managed detached worktrees from a source repo, allocates a destination under configured root, disables checkout filters while materializing files, preserves relative cwd, and lists/removes only worktrees whose linked Git metadata points back to the source repository. codex-rs/…/git.rs runs Git with inherited repo selectors removed, hooks disabled, fsmonitor disabled, terminal prompts off, and clean/smudge/process filters disabled for working-tree operations. codex-rs/…/settings.rs reads Desktop-compatible worktree settings from [desktop]. codex-rs/…/lib.rs exposes lightweight repository discovery, remote/canonical URL collection, branch/default-branch helpers, status checks, baseline/apply-patch helpers, and worktree identity helpers. codex-rs/…/git_process.rs bounds async Git subprocesses with timeouts and kills process trees on drop; codex-rs/…/worktree.rs validates linked worktree metadata without executing Git; codex-rs/…/trust.rs resolves the main checkout used for project trust through native or executor filesystem APIs without following unsafe .git symlink substitutions.
User verification is a local credential boundary in codex-rs/user-verification. codex-rs/…/lib.rs exposes a UserVerificationProvider trait that reads status, ensures/deletes a local protected key, and signs caller-supplied challenge bytes without performing network registration. codex-rs/…/credential.rs defines public key/proof encoding: P-256 public keys are exported as DER SubjectPublicKeyInfo, credential IDs are SHA-256 hashes encoded base64url, and proofs redact credential IDs/signatures in Debug. codex-rs/…/guard.rs lets callers cancel queued native work and bind operations to a captured active identity; codex-rs/…/native_operation.rs waits for OS authentication completion while propagating cancellation. macOS native integration is compiled through codex-rs/…/platform_macos.rs; non-macOS builds return the unsupported provider.
Path-routing notes for this doc: changes under codex-rs/config/**, codex-rs/config-schema/**, codex-rs/config.md, and codex-rs/codex-home/** belong here when they affect config shape, loading, schema generation, or Codex home files. Changes under codex-rs/login/**, codex-rs/keyring-store/**, codex-rs/secrets/**, codex-rs/user-verification/**, codex-rs/workload-identity/**, and codex-rs/aws-auth/** belong here when they affect local credentials, auth flows, secret storage, device verification, or external credential exchange. Changes under codex-rs/cloud-config/**, codex-rs/features/**, and codex-rs/hooks/** belong here for managed config, feature-flag config, and hook config/discovery behavior. Changes under codex-rs/worktree/** and codex-rs/git-utils/** belong here when they support config trust, local worktree state, or Git metadata helpers rather than a higher-level product flow.
Coupling
- If
ConfigTomlor any exported config type in codex-rs/…/config_toml.rs, codex-rs/…/types.rs, codex-rs/…/feature_configs.rs, or codex-rs/…/runtime_auth.rs changes, also check codex-rs/…/schema.rs and codex-rs/…/main.rs; schema generation is hand-curated for structured feature tables and special config enums, so new fields can be accepted by TOML but missing from generated schema. - If the config layer order or precedence changes in codex-rs/…/mod.rs or codex-rs/…/config_layer_source.rs, verify codex-rs/…/state.rs update helpers and codex-rs/…/discovery.rs; hook discovery walks the same layer stack and assumes
ConfigLayerEntry::config_folderandhooks_config_folderpoint to the correct source directory for each layer. - If project-local config keys are added in codex-rs/…/config_toml.rs, check
PROJECT_LOCAL_CONFIG_DENYLISTandsanitize_project_configin codex-rs/…/mod.rs; repository-owned .codex/config.toml must not gain the ability to redirect credentials, override providers, run local notification commands, or alter credential-broker/proxy behavior. - If auth storage modes or keyring backend kinds change in codex-rs/…/types.rs, update codex-rs/…/storage.rs and codex-rs/…/local.rs;
AuthCredentialsStoreMode::Auto/Keyringsemantics andAuthKeyringBackendKind::Secretsdepend on both the auth store and encrypted secrets namespace/keyring account calculation. - If
$CODEX_HOMEfilenames change in codex-rs/…/storage.rs, codex-rs/…/local.rs, codex-rs/…/cache.rs, or codex-rs/…/mod.rs, check migration and cleanup behavior across all local-state owners; several stores derive keys from canonical Codex home and intentionally delete old file fallbacks after successful secure-store writes. - If
AuthManagerConfigin codex-rs/…/manager.rs changes, update callers that adapt resolved runtime config into auth config. The login crate intentionally avoids depending on core config, so missing trait updates cause auth managers to silently ignore new restrictions or route settings. - If forced workspace/login restrictions change in codex-rs/…/config_toml.rs or codex-rs/…/manager.rs, verify codex-rs/…/server.rs, codex-rs/…/device_code_auth.rs, and codex-rs/…/manager.rs; browser, device-code, access-token, stored-token, and agent-identity logins each enforce workspace restrictions at different points.
- If OAuth credential storage changes in codex-rs/…/oauth_session.rs or its storage/token submodules, verify codex-rs/…/config_server.rs; config-server managed bundles use the OAuth session manager non-interactively and depend on
authorization_idfor cache identity before refreshing access tokens. - If feature keys or defaults change in codex-rs/…/lib.rs, update codex-rs/…/schema.rs, codex-rs/…/legacy.rs, and any managed requirements that constrain features;
FeaturesToml::entriesflattens structured feature config into boolean enablement and legacy keys can still affect runtime behavior. - If hook event names, schemas, or handler output shapes change under
codex-rs/hooks/src/events/**or codex-rs/…/schema.rs, regenerate/checkcodex-rs/hooks/schema/generated/**and update codex-rs/…/hook_config.rs; config loading, discovery, and external hook authors rely on those JSON schema files as the wire contract. - If cloud bundle structure changes in codex-rs/…/cloud_config_bundle.rs or codex-rs/…/backend.rs, update codex-rs/…/validation.rs, codex-rs/…/cache.rs, and codex-rs/…/mod.rs; invalid bundles must fail before being cached, and the config loader expects already-parsed enterprise-managed config/requirements layers.
- If Git trust or worktree metadata validation changes in codex-rs/…/trust.rs, codex-rs/…/worktree.rs, or codex-rs/…/lib.rs, verify project config loading in codex-rs/…/mod.rs; project trust is based on the main checkout root for linked worktrees and must not follow attacker-controlled
.gitsymlink substitutions. - If AWS or workload identity auth starts using new HTTP endpoints, verify codex-rs/…/transport.rs, codex-rs/…/lib.rs, and codex-rs/…/exchange.rs; these modules deliberately route through auth-class HTTP clients without redirects or request logging and acquire network-policy permits before credential or signing network work.
Risks
- codex-rs/…/mod.rs is a security boundary for project-local config. If a new credential/provider/proxy-capable setting is not filtered from untrusted project .codex/config.toml, opening a repository can redirect tokens or enable credential-bearing network paths before the user notices.
- codex-rs/…/storage.rs and codex-rs/…/storage_file.rs protect credential atomicity. If compare-and-save or file replacement stops checking the currently selected generation, token refresh can overwrite a newer login or split identity across file/keyring fallback stores.
- codex-rs/…/local.rs depends on the OS keyring passphrase matching the encrypted file. If namespace/account derivation or cache validation changes incorrectly, one Codex home can fail to decrypt its own secrets or accidentally reuse a cached decrypted snapshot for another namespace.
- codex-rs/…/cache.rs and codex-rs/…/service.rs apply managed policy from disk before remote fetches. If HMAC, TTL, identity matching, or validation is weakened, stale or edited managed config could be applied to a different account or persisted across policy changes.
- codex-rs/…/discovery.rs and codex-rs/…/dispatcher.rs run user/project/managed commands. If trust state, managed-only filtering, or sync-vs-async control-effect checks regress, optional hooks can become fail-closed policy hooks or untrusted project hooks can block/modify operations.
- codex-rs/…/git.rs, codex-rs/…/trust.rs, and codex-rs/…/worktree.rs avoid repository-controlled Git hooks, filters, fsmonitor helpers, and unsafe worktree links. If inherited Git environment/config is allowed back in, merely creating/listing a managed worktree or resolving trust can execute repository-configured helpers.