Codex CLI Security & Privacy Guide (2026) — Is Your Code Safe?

"Does Codex CLI send my code to OpenAI?" — this is the #1 security question developers ask. The short answer is yes, since Codex CLI relies on the OpenAI API for inference. But that doesn't mean your code is unprotected — this guide explains every security dimension and provides solutions for different privacy requirements.

Security Overview
Security Dimension Default Behavior How to Harden
Code DataSent to OpenAI APIExclude sensitive files via .codexignore / use Ollama locally
Filesystem AccessRead-only (modifications require confirmation in suggest mode)Restrict directories in AGENTS.md
Command ExecutionRequires confirmation in auto-edit modeAvoid full-auto; disable dangerous commands in AGENTS.md
API Key~/.codex/auth.json (current user only)Environment variable + system keychain
Training DataAPI calls used for model improvement (default)Enterprise Zero Data Retention

1. How Code Data Flows

Understanding how Codex CLI transmits data is the first step toward proper security hygiene. Here is the default data transmission path:

Default Flow

Your code (local) → Codex CLI → OpenAI API → Model inference → Result returned

What Gets Sent

What Does Not Get Sent

OpenAI Data Usage Policy (as of 2026)

Compliance Notice: If you handle medical records, financial data, government classified information, or customer PII, evaluate your compliance requirements (GDPR, HIPAA, SOC 2, etc.) before using Codex CLI, and consider a fully local Ollama deployment.

2. Sandbox Mechanism Deep Dive

Codex CLI provides three approval modes with different security profiles. Choosing the right mode is critical for protecting your system.

Approval Mode File Modifications Command Execution Security Level Best For
suggest (default)Requires diff confirmationDoes not execute commands⭐⭐⭐⭐⭐ SafestDaily development
auto-editApplies automaticallyDoes not execute commands⭐⭐⭐⭐ SafeRefactoring tasks
full-autoApplies automaticallyExecutes automatically⭐⭐ Use with careControlled CI/CD environments

Restricting Command Execution in AGENTS.md

The AGENTS.md file lets you constrain Codex behavior at the project level, applying even in full-auto mode:

## Disallowed commands (never executed, even in full-auto mode)
disallow_commands:
  - "rm -rf"
  - "git push --force"
  - "chmod 777"
  - "curl | bash"
  - "wget | sh"
  - "sudo"
  - "dd"
  - "mkfs"

## Only allow the following commands
allow_commands:
  - "npm test"
  - "npm run build"
  - "npm run lint"
  - "pytest"
  - "go test ./..."
Critical Warning: When using full-auto mode in CI/CD, always run inside an isolated Docker container and strictly limit allowed commands via AGENTS.md. Never run full-auto on a production server without isolation.

3. API Key Security

Your API key is the credential for accessing OpenAI services. A leaked key leads to financial exposure and data risk. Here are five security levels, from least to most secure:

Level 1 (Least Secure): Hardcoded in Source

# Never do this
OPENAI_API_KEY="sk-..." codex "task"  # Visible in shell history

Level 2 (Basic): Environment Variable

# ~/.zshrc or ~/.bashrc
export OPENAI_API_KEY="sk-..."

# Better than hardcoding, but never commit .env files to git

Level 3 (Recommended): System Keychain

# macOS Keychain
security add-generic-password -a "$USER" -s "openai-api-key" -w "sk-..."
# Retrieve when needed
export OPENAI_API_KEY=$(security find-generic-password -a "$USER" -s "openai-api-key" -w)

# Linux Secret Service (GNOME Keyring)
secret-tool store --label="OpenAI API Key" service openai username codex
export OPENAI_API_KEY=$(secret-tool lookup service openai username codex)

Level 4 (Team): Secret Management Tools

# Using direnv (.envrc auto-loads)
echo 'export OPENAI_API_KEY=$(op read "op://Personal/OpenAI/api_key")' >> .envrc
direnv allow

# Using 1Password CLI
export OPENAI_API_KEY=$(op read "op://Personal/OpenAI/api_key")

# Using AWS Secrets Manager
export OPENAI_API_KEY=$(aws secretsmanager get-secret-value \
  --secret-id openai-api-key --query SecretString --output text)

Level 5 (Most Secure): Short-Lived Keys + Least Privilege

# Create a dedicated CI/CD API Key (restrict usage and models in OpenAI platform)
# GitHub Actions
env:
  OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}  # Never exposed in logs

# Rotate keys regularly (recommended every 90 days)

Protecting auth.json (codex login method)

# Check file permissions (should be 600)
ls -la ~/.codex/auth.json
# -rw------- 1 user group ... ~/.codex/auth.json

# Fix permissions if incorrect
chmod 600 ~/.codex/auth.json

4. .codexignore for Sensitive File Protection

Similar to .gitignore, the .codexignore file tells Codex which files and directories should never be read or included in its context. This is the most direct way to prevent sensitive data from being transmitted to OpenAI.

# .codexignore — Security Configuration Template

# === Credentials & Keys ===
.env
.env.*
*.pem
*.key
*.cert
*.pfx
secrets/
credentials/
.aws/credentials
.ssh/

# === Database Files ===
*.sqlite
*.db
*.dump
*.sql

# === Sensitive Business Data ===
data/customers/
data/financial/
exports/
reports/
contracts/

# === Config Files (containing production info) ===
config/production.*
config/staging.*
infrastructure/terraform/
k8s/secrets/

# === Logs (may contain PII) ===
logs/
*.log
Best Practice: Commit .codexignore to git so your entire team uses the same exclusion rules, preventing anyone from accidentally including sensitive files in Codex context.

5. Enterprise Security Configuration

Default configuration is insufficient for enterprise environments. These five measures raise Codex CLI to enterprise security standards:

1. Use OpenAI Enterprise API (Zero Data Retention)

# ~/.codex/config.toml
# Enterprise config: route through company API proxy or enterprise endpoint
[providers.openai-enterprise]
name = "OpenAI Enterprise"
baseURL = "https://your-company-openai-proxy.internal/v1"
envKey = "OPENAI_ENTERPRISE_KEY"

2. Principle of Least Privilege in CI/CD

# GitHub Actions — minimal privilege API key
- name: Codex task
  env:
    OPENAI_API_KEY: ${{ secrets.CODEX_CI_KEY }}  # Dedicated CI key with usage limits
  run: |
    codex exec --approval-mode auto-edit \
      --disable-server \  # Do not start local server
      "run tests and fix failures"

3. Network Isolation (Prevent Codex from Accessing Internal Services)

# Run Codex with Docker network isolation
docker run --rm \
  --network=none \  # Disable network (use host mode with egress control if needed)
  -e OPENAI_API_KEY="$OPENAI_API_KEY" \
  -v "$(pwd)":/workspace \
  node:20 \
  bash -c "npm install -g @openai/codex && codex exec 'run tests'"

4. Operation Audit Logs

# Codex operation log location
~/.codex/logs/

# Save logs in CI/CD pipelines
codex exec "task" 2&1 | tee codex-audit.log
# Upload logs to S3/GCS for auditing

5. Pre-Scan for Secrets (Prevent Credential Leakage)

# Scan before committing to prevent sending keys to Codex
# Using gitleaks
gitleaks protect --staged

# Using trufflehog
trufflehog git file://. --since-commit HEAD --only-verified

6. Fully Local with Ollama

When data privacy requirements are extreme — healthcare, legal, defense, or government sectors — Ollama local models are the only solution that guarantees code never leaves your machine.

# Install Ollama
brew install ollama  # macOS

# Pull a local code model
ollama pull qwen2.5-coder:32b  # Best code quality
ollama pull deepseek-coder-v2:16b  # Balanced performance

# Configure Codex to use the local model
export OPENAI_BASE_URL=http://localhost:11434/v1
export OPENAI_API_KEY=ollama

# Run Codex — code never leaves your machine
codex "refactor this module"

Local vs Cloud Comparison

Dimension Ollama Local OpenAI API
Code DataFully localSent to OpenAI
GDPR/HIPAA Compliant✅ No external transfer⚠️ Requires evaluation
Code QualityGoodBest-in-class
CostZeroPer-token billing
Works Offline

For detailed setup instructions, see the Ollama Local Models Guide.

7. Security Best Practices Checklist

Daily Development

Team / Enterprise

Highly Sensitive Projects

8. FAQ

Does Codex CLI upload my code to OpenAI?

Yes. Codex CLI sends your prompts and relevant code context to the OpenAI API for inference. To minimize exposure: (1) use .codexignore to exclude sensitive files; (2) use Ollama local models (code stays entirely on your machine); (3) use OpenAI Enterprise with Zero Data Retention (ZDR).

Does Codex CLI's sandbox prevent malicious code execution?

In suggest and auto-edit modes, Codex shows all file changes before applying them and does not auto-execute system commands. full-auto mode does auto-execute commands — use AGENTS.md disallow_commands and Docker isolation to constrain it. Never use full-auto on a production server without proper isolation.

Where does Codex CLI store API keys and is it secure?

OAuth tokens from codex login are stored in ~/.codex/auth.json (readable only by the current user). Using the OPENAI_API_KEY environment variable with a system keychain (macOS Keychain, Linux Secret Service) is more secure. Never hardcode API keys in source files or commit .env files to git.

Can enterprises use Codex CLI securely?

Yes, with proper configuration: (1) Use OpenAI Enterprise API with Zero Data Retention; (2) restrict access scope with AGENTS.md; (3) exclude core business logic with .codexignore; (4) use short-lived API keys in CI/CD; (5) run in Docker isolation with network controls; (6) audit operation logs at ~/.codex/logs/.

← Sandbox & Approval Modes Local Model Option →