Skip to content

fix: add custom CA certificate support for login flows - #6864

Closed
3axap4eHko wants to merge 8 commits into
openai:mainfrom
3axap4eHko:ISSUE-6849
Closed

3axap4eHko wants to merge 8 commits into
openai:mainfrom
3axap4eHko:ISSUE-6849

Conversation

@3axap4eHko

Copy link
Copy Markdown
Contributor

What

Adds support for custom CA certificates in OAuth login flows to fix authentication failures behind corporate
proxies with SSL/TLS inspection.

Why

The Codex CLI fails to authenticate when running behind corporate proxies that perform SSL/TLS inspection with
custom CA certificates. The OAuth token exchange fails because reqwest::Client::new() only trusts system
default certificate roots, causing it to reject connections intercepted by corporate proxies presenting
certificates signed by custom CAs.

This affects all Codex CLI users in enterprise environments with:

  • SSL/TLS inspection proxies (Zscaler, Palo Alto Networks, etc.)
  • Custom internal CA certificates
  • Air-gapped environments with internal certificate authorities

Fixes #6849

How

Implementation:

  • Added build_login_http_client() function that creates an HTTP client with custom CA certificate support
  • Reads CA certificate path from environment variables (priority order):
    1. CODEX_CA_CERTIFICATE (primary)
    2. SSL_CERT_FILE (fallback, standard across many tools)
  • Updated all three authentication flows to use the custom client:
    • exchange_code_for_tokens() (OAuth code exchange)
    • obtain_api_key() (API key exchange)
    • run_device_code_login() (device code flow)
  • Follows the same pattern as existing otel_provider.rs implementation

Testing:

  • Added comprehensive test coverage with 3 new tests:
    • Certificate loading via CODEX_CA_CERTIFICATE env var
    • Certificate loading via SSL_CERT_FILE fallback
    • Invalid certificate rejection with proper error handling
  • All existing tests continue to pass
  • Added serial_test dependency to safely test env var manipulation

Usage:

export CODEX_CA_CERTIFICATE=/path/to/corporate-ca.pem
codex login

or using the standard env var:

export SSL_CERT_FILE=/path/to/corporate-ca.pem
codex login

Testing:

  • ✅ All tests pass (cargo test)
  • ✅ No clippy warnings (cargo clippy --tests -- -D warnings)
  • ✅ Code formatted (cargo fmt --check)
  • ✅ Tested with both environment variables
  • ✅ Invalid certificate properly rejected with clear error message

@github-actions

github-actions Bot commented Nov 19, 2025 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@3axap4eHko

Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

github-actions Bot added a commit that referenced this pull request Nov 19, 2025
@etraut-openai

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread codex-rs/login/src/server.rs Resolved
@3axap4eHko

Copy link
Copy Markdown
Contributor Author

@codex review

1 similar comment
@etraut-openai

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review: Didn't find any major issues. Breezy!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@etraut-openai

Copy link
Copy Markdown
Contributor

@3axap4eHko, thanks for the contribution! It looks like there are some minor code format issues. Please fix those when you have time.

@etraut-openai etraut-openai added needs-response Additional information is requested and removed needs-response Additional information is requested labels Nov 20, 2025
@etraut-openai

Copy link
Copy Markdown
Contributor

@3axap4eHko, the PR is looking good. We'll need to document the new environment variables. Ideally, this should be part of the same PR. Do you want to take a shot at adding the documentation?

@joshka-oai joshka-oai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Brief review notes / questions to help work out whether to do a deeper review.

Comment thread codex-rs/login/src/server.rs Resolved
Comment thread codex-rs/login/src/server.rs Resolved
Comment thread codex-rs/login/src/server.rs Resolved
Comment thread codex-rs/login/src/server.rs Resolved
Comment thread codex-rs/login/src/server.rs Resolved
Comment thread codex-rs/login/src/server.rs Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread codex-rs/login/src/server.rs Resolved
@joshka-oai

Copy link
Copy Markdown
Contributor

I'm assuming that your environment sets some sort of CA root authority that your general tools (browser etc.) properly check, so you don't tend to get errors in non-cli tooling. Is this something that we could generally load from the environment in the same way without having to manually configure this with environment variables? I.e. perhaps configuring the tooling to load from the OS Cert store where this is setup. There's probably a crate that sets this up automatically if that's the case. I'm not sure whether this is relevant to the use cases here, so please forgive the naive question.

@3axap4eHko

Copy link
Copy Markdown
Contributor Author

I'm assuming that your environment sets some sort of CA root authority that your general tools (browser etc.) properly check, so you don't tend to get errors in non-cli tooling. Is this something that we could generally load from the environment in the same way without having to manually configure this with environment variables? I.e. perhaps configuring the tooling to load from the OS Cert store where this is setup. There's probably a crate that sets this up automatically if that's the case. I'm not sure whether this is relevant to the use cases here, so please forgive the naive question.

Totally fair question. Out of the box, reqwest already trusts the platform store (via either system OpenSSL/Schannel/Security‑Framework on the blocking TLS stack or rustls-native-certs when using the rustls backend). That’s the reason browsers and “normal” CLI calls don’t need extra configuration. The new code only kicks in when you explicitly point CODEX_CA_CERTIFICATE or SSL_CERT_FILE at a custom bundle, because corporate proxies often publish their own root chain that isn’t in the OS store.

So, for users whose proxy installs its cert into the regular Windows/macOS/Linux trust store, nothing special is required—the default client still works. The env knob is just for the cases where IT hands you a standalone PEM bundle instead of touching the OS store. In that scenario you still need manual configuration somewhere, either by importing the PEM into the OS trust store (which is painful to automate across platforms) or by telling the app exactly which file to add. The helper we added is that second option.

If we ever run into a platform where the OS store is available but reqwest/rustls can’t discover it, the fix would likely be as simple as enabling the rustls-native-certs crate (or the native-tls backend) for that target. But so far there hasn’t been a report that the default trust roots are being ignored; every bug we’ve seen came from proxy-issued certs that the OS store rightfully doesn’t trust.

@etraut-openai

Copy link
Copy Markdown
Contributor

@3axap4eHko, I wanted to give you an update on this PR. Since it involves security-sensitive code, we have pulled in some security experts outside of the codex team to provide a more thorough code review. This is a holiday week in the U.S. (Thanksgiving), so many OpenAI employees are out of the office. That means we probably won't make any further progress on this until next week.

@joshka-oai

Copy link
Copy Markdown
Contributor

After chatting about this with our internal security, we'd prefer to have the settings for this added to the config.toml file rather than as an environment variable. If you're concerned that you need single call setups (where you don't want to set this at the entire machine level) codex has a --config flag that can generally be used to pass config key/values like this. We don't need to add a specific command line flag for this. Let's call this setting login_ca_certificate.

Let's use rustls-pki-types to open / parse the pem files rather thank hand coded.

Happy to continue the implementation on this with codex, or let you complete it. The things I'd generally want to make sure are covered here:

Comment thread codex-rs/login/src/server.rs Resolved
@etraut-openai etraut-openai added the needs-response Additional information is requested label Nov 27, 2025
@3axap4eHko

Copy link
Copy Markdown
Contributor Author

After chatting about this with our internal security, we'd prefer to have the settings for this added to the config.toml file rather than as an environment variable. If you're concerned that you need single call setups (where you don't want to set this at the entire machine level) codex has a --config flag that can generally be used to pass config key/values like this. We don't need to add a specific command line flag for this. Let's call this setting login_ca_certificate.

Let's use rustls-pki-types to open / parse the pem files rather thank hand coded.

Happy to continue the implementation on this with codex, or let you complete it. The things I'd generally want to make sure are covered here:

@joshka-oai One thing I want to push back on in the "after chatting with internal security" part: environment-based CA configuration is a very common pattern on Unix. SSL_CERT_FILE is the standard OpenSSL convention and is used by tools like curl, git, Python requests, etc. It’s not inherently less secure than putting the same path in config.toml; both are just configuration channels, but it allows to avoid micromanage every cli tool.

If the Codex policy is "all TLS-related overrides must live in config.toml and we intentionally ignore SSL_CERT_FILE", that’s a valid product/design decision. But it’s different from saying that using SSL_CERT_FILE is a security concern. I’d prefer we frame this explicitly as "Codex chooses config-over-env for CA overrides" (and document that) rather than implying the standard env-based mechanism is problematic.

@joshka-oai

Copy link
Copy Markdown
Contributor

I'm in general agreement with you, but I'm not sure if there's things I don't know about this yet.
I'll follow up with our security folk and will get back to you on this shortly.

@joshka-oai

joshka-oai commented Dec 1, 2025 •

Copy link
Copy Markdown
Contributor

I clarified with our Security team. We're fine with using environment variables on this. I misread a recommendation in a message.

The main part of getting this over the line is testing this correctly in a way that doesn't cause other usages of this code path to be impacted. Leaving the ball with you for now to take a look, but feel free to ask more questions or kick it back to us if you're not sure of the right direction on this.

@3axap4eHko

Copy link
Copy Markdown
Contributor Author

@joshka-oai Oh thanks for helping, I didn't expect that. I was a bit off for holidays

@joshka-oai

Copy link
Copy Markdown
Contributor

Rebased on main, and got codex to implement the necessary parts of this that

@joshka-oai Oh thanks for helping, I didn't expect that. I was a bit off for holidays

No problem - take a quick look to see if this change still solves your problem in real testing if you have a few moments.
I think it's likely mostly equivalent to your change, but it's always possible something was missed in the rewrite (e.g. rustls-pki-types does something different in handling the pem load).

@3axap4eHko
3axap4eHko force-pushed the ISSUE-6849 branch 2 times, most recently from b5feeb4 to 16e15ce Compare December 12, 2025 18:05
@joshka-oai

Copy link
Copy Markdown
Contributor

I took a bit of a look at reqwest 0.13. We can update to 0.13 when open-telemetry/opentelemetry-rust#3293 is released.

@3axap4eHko

Copy link
Copy Markdown
Contributor Author

I didn't forget about this PR, still waiting on https://github.com/open-telemetry/opentelemetry-rust release that includes reqwest upgrade. Maybe it worth asking them about any ETA on release, I don't know what is the right way here TBH

swordfish444 pushed a commit to swordfish444/codex that referenced this pull request Feb 26, 2026
@etraut-openai etraut-openai removed the needs-response Additional information is requested label Mar 5, 2026
@joshka-oai

Copy link
Copy Markdown
Contributor

Hey @3axap4eHko — I’m picking this up again to try to get it over the line.

First up, apologies again for the delay here. I had hoped the OpenTelemetry update that adds support for reqwest 0.13 would land before now.

At this point I think it’s reasonable to move forward without waiting on that and handle the reqwest 0.13 upgrade as a follow-up change.

I’m going to take over this PR a bit today: rebase it, squash the commits, and make a few small adjustments so we can get this merged as soon as possible. I’ll push those updates directly to this branch shortly.

3axap4eHko and others added 8 commits March 10, 2026 00:19
Enterprise TLS inspection proxies use custom roots, so OAuth token exchanges
fail when we only trust system CAs. This change switches PEM parsing to
rustls-pki-types (multi-cert bundles included) and surfaces clearer, user-
facing errors that explain how to fix invalid or empty CA files via
CODEX_CA_CERTIFICATE/SSL_CERT_FILE.

To avoid cross-test races with process-wide env vars, CA path selection now
uses a small EnvSource abstraction in unit tests, and environment-dependent
behavior is verified via an assert_cmd-driven login_ca_probe helper binary.
This keeps normal tests isolated while still validating env precedence and
error messaging.

Also updates login dev-deps (assert_cmd/pretty_assertions), removes serial_test,
and re-exports build_login_http_client for the probe helper.
@joshka-oai

Copy link
Copy Markdown
Contributor

Closing this out in preference to #14178
This PR is mostly correct but I wanted some things that would have been difficult to do some back and forth over. There's a note that compares the work to yours in the other PR and I credit you with doing most of the work on this. Thank you again

@joshka-oai joshka-oai closed this Mar 10, 2026
joshka-oai added a commit that referenced this pull request Mar 13, 2026
## Stacked PRs

This work is split across three stacked PRs:

- #14178: add custom CA support for browser and device-code login flows,
docs, and hermetic subprocess tests
- #14239: broaden the shared custom CA path from login to other outbound
`reqwest` clients across Codex
- #14240: extend that shared custom CA handling to secure websocket TLS
so websocket connections honor the same CA env vars

Review order: #14178, then #14239, then #14240.

Supersedes #6864.

Thanks to @3axap4eHko for the original implementation and investigation
here. Although this version rearranges the code and history
significantly, the majority of the credit for this work belongs to them.

## Problem

Login flows need to work in enterprise environments where outbound TLS
is intercepted by an internal proxy or gateway. In those setups, system
root certificates alone are often insufficient to validate the OAuth and
device-code endpoints used during login. The change adds a
login-specific custom CA loading path, but the important contracts
around env precedence, PEM compatibility, test boundaries, and
probe-only workarounds need to be explicit so reviewers can understand
what behavior is intentional.

For users and operators, the behavior is simple: if login needs to trust
a custom root CA, set `CODEX_CA_CERTIFICATE` to a PEM file containing
one or more certificates. If that variable is unset, login falls back to
`SSL_CERT_FILE`. If neither is set, login uses system roots. Invalid or
empty PEM files now fail with an error that points back to those
environment variables and explains how to recover.

## What This Delivers

Users can now make Codex login work behind enterprise TLS interception
by pointing `CODEX_CA_CERTIFICATE` at a PEM bundle containing the
relevant root certificates. If that variable is unset, login falls back
to `SSL_CERT_FILE`, then to system roots.

This PR applies that behavior to both browser-based and device-code
login flows. It also makes login tolerant of the PEM shapes operators
actually have in hand: multi-certificate bundles, OpenSSL `TRUSTED
CERTIFICATE` labels, and bundles that include well-formed CRLs.

## Mental model

`codex-login` is the place where the login flows construct ad hoc
outbound HTTP clients. That makes it the right boundary for a narrow CA
policy: look for `CODEX_CA_CERTIFICATE`, fall back to `SSL_CERT_FILE`,
load every parseable certificate block in that bundle into a
`reqwest::Client`, and fail early with a clear user-facing error if the
bundle is unreadable or malformed.

The implementation is intentionally pragmatic about PEM input shape. It
accepts ordinary certificate bundles, multi-certificate bundles, OpenSSL
`TRUSTED CERTIFICATE` labels, and bundles that also contain CRLs. It
does not validate a certificate chain or prove a handshake; it only
constructs the root store used by login.

## Non-goals

This change does not introduce a general-purpose transport abstraction
for the rest of the product. It does not validate whether the provided
bundle forms a real chain, and it does not add handshake-level
integration tests against a live TLS server. It also does not change
login state management or OAuth semantics beyond ensuring the existing
flows share the same CA-loading rules.

## Tradeoffs

The main tradeoff is keeping this logic scoped to login-specific client
construction rather than lifting it into a broader shared HTTP layer.
That keeps the review surface smaller, but it also means future
login-adjacent code must continue to use `build_login_http_client()` or
it can silently bypass enterprise CA overrides.

The `TRUSTED CERTIFICATE` handling is also intentionally a local
compatibility shim. The rustls ecosystem does not currently accept that
PEM label upstream, so the code normalizes it locally and trims the
OpenSSL `X509_AUX` trailer bytes down to the certificate DER that
`reqwest` can consume.

## Architecture

`custom_ca.rs` is now the single place that owns login CA behavior. It
selects the CA file from the environment, reads it, normalizes PEM label
shape where needed, iterates mixed PEM sections with `rustls-pki-types`,
ignores CRLs, trims OpenSSL trust metadata when necessary, and returns
either a configured `reqwest::Client` or a typed error.

The browser login server and the device-code flow both call
`build_login_http_client()`, so they share the same trust-store policy.
Environment-sensitive tests run through the `login_ca_probe` helper
binary because those tests must control process-wide env vars and cannot
reliably build a real reqwest client in-process on macOS seatbelt runs.

## Observability

The custom CA path logs which environment variable selected the bundle,
which file path was loaded, how many certificates were accepted, when
`TRUSTED CERTIFICATE` labels were normalized, when CRLs were ignored,
and where client construction failed. Returned errors remain user-facing
and include the relevant path, env var, and remediation hint.

This gives enough signal for three audiences:
- users can see why login failed and which env/file caused it
- sysadmins can confirm which override actually won
- developers can tell whether the failure happened during file read, PEM
parsing, certificate registration, or final reqwest client construction

## Tests

Pure unit tests stay limited to env precedence and empty-value handling.
Real client construction lives in subprocess tests so the suite remains
hermetic with respect to process env and macOS sandbox behavior.

The subprocess tests verify:
- `CODEX_CA_CERTIFICATE` precedence over `SSL_CERT_FILE`
- fallback to `SSL_CERT_FILE`
- single-certificate and multi-certificate bundles
- malformed and empty-bundle errors
- OpenSSL `TRUSTED CERTIFICATE` handling
- CRL tolerance for well-formed CRL sections

The named PEM fixtures under `login/tests/fixtures/` are shared by the
tests so their purpose stays reviewable.

---------

Co-authored-by: Ivan Zakharchanka <[email protected]>
Co-authored-by: Codex <[email protected]>
AIALRA-0 pushed a commit to AIALRA-0/codex-turn-engine that referenced this pull request Jun 10, 2026
## Stacked PRs

This work is split across three stacked PRs:

- openai#14178: add custom CA support for browser and device-code login flows,
docs, and hermetic subprocess tests
- openai#14239: broaden the shared custom CA path from login to other outbound
`reqwest` clients across Codex
- openai#14240: extend that shared custom CA handling to secure websocket TLS
so websocket connections honor the same CA env vars

Review order: openai#14178, then openai#14239, then openai#14240.

Supersedes openai#6864.

Thanks to @3axap4eHko for the original implementation and investigation
here. Although this version rearranges the code and history
significantly, the majority of the credit for this work belongs to them.

## Problem

Login flows need to work in enterprise environments where outbound TLS
is intercepted by an internal proxy or gateway. In those setups, system
root certificates alone are often insufficient to validate the OAuth and
device-code endpoints used during login. The change adds a
login-specific custom CA loading path, but the important contracts
around env precedence, PEM compatibility, test boundaries, and
probe-only workarounds need to be explicit so reviewers can understand
what behavior is intentional.

For users and operators, the behavior is simple: if login needs to trust
a custom root CA, set `CODEX_CA_CERTIFICATE` to a PEM file containing
one or more certificates. If that variable is unset, login falls back to
`SSL_CERT_FILE`. If neither is set, login uses system roots. Invalid or
empty PEM files now fail with an error that points back to those
environment variables and explains how to recover.

## What This Delivers

Users can now make Codex login work behind enterprise TLS interception
by pointing `CODEX_CA_CERTIFICATE` at a PEM bundle containing the
relevant root certificates. If that variable is unset, login falls back
to `SSL_CERT_FILE`, then to system roots.

This PR applies that behavior to both browser-based and device-code
login flows. It also makes login tolerant of the PEM shapes operators
actually have in hand: multi-certificate bundles, OpenSSL `TRUSTED
CERTIFICATE` labels, and bundles that include well-formed CRLs.

## Mental model

`codex-login` is the place where the login flows construct ad hoc
outbound HTTP clients. That makes it the right boundary for a narrow CA
policy: look for `CODEX_CA_CERTIFICATE`, fall back to `SSL_CERT_FILE`,
load every parseable certificate block in that bundle into a
`reqwest::Client`, and fail early with a clear user-facing error if the
bundle is unreadable or malformed.

The implementation is intentionally pragmatic about PEM input shape. It
accepts ordinary certificate bundles, multi-certificate bundles, OpenSSL
`TRUSTED CERTIFICATE` labels, and bundles that also contain CRLs. It
does not validate a certificate chain or prove a handshake; it only
constructs the root store used by login.

## Non-goals

This change does not introduce a general-purpose transport abstraction
for the rest of the product. It does not validate whether the provided
bundle forms a real chain, and it does not add handshake-level
integration tests against a live TLS server. It also does not change
login state management or OAuth semantics beyond ensuring the existing
flows share the same CA-loading rules.

## Tradeoffs

The main tradeoff is keeping this logic scoped to login-specific client
construction rather than lifting it into a broader shared HTTP layer.
That keeps the review surface smaller, but it also means future
login-adjacent code must continue to use `build_login_http_client()` or
it can silently bypass enterprise CA overrides.

The `TRUSTED CERTIFICATE` handling is also intentionally a local
compatibility shim. The rustls ecosystem does not currently accept that
PEM label upstream, so the code normalizes it locally and trims the
OpenSSL `X509_AUX` trailer bytes down to the certificate DER that
`reqwest` can consume.

## Architecture

`custom_ca.rs` is now the single place that owns login CA behavior. It
selects the CA file from the environment, reads it, normalizes PEM label
shape where needed, iterates mixed PEM sections with `rustls-pki-types`,
ignores CRLs, trims OpenSSL trust metadata when necessary, and returns
either a configured `reqwest::Client` or a typed error.

The browser login server and the device-code flow both call
`build_login_http_client()`, so they share the same trust-store policy.
Environment-sensitive tests run through the `login_ca_probe` helper
binary because those tests must control process-wide env vars and cannot
reliably build a real reqwest client in-process on macOS seatbelt runs.

## Observability

The custom CA path logs which environment variable selected the bundle,
which file path was loaded, how many certificates were accepted, when
`TRUSTED CERTIFICATE` labels were normalized, when CRLs were ignored,
and where client construction failed. Returned errors remain user-facing
and include the relevant path, env var, and remediation hint.

This gives enough signal for three audiences:
- users can see why login failed and which env/file caused it
- sysadmins can confirm which override actually won
- developers can tell whether the failure happened during file read, PEM
parsing, certificate registration, or final reqwest client construction

## Tests

Pure unit tests stay limited to env precedence and empty-value handling.
Real client construction lives in subprocess tests so the suite remains
hermetic with respect to process env and macOS sandbox behavior.

The subprocess tests verify:
- `CODEX_CA_CERTIFICATE` precedence over `SSL_CERT_FILE`
- fallback to `SSL_CERT_FILE`
- single-certificate and multi-certificate bundles
- malformed and empty-bundle errors
- OpenSSL `TRUSTED CERTIFICATE` handling
- CRL tolerance for well-formed CRL sections

The named PEM fixtures under `login/tests/fixtures/` are shared by the
tests so their purpose stays reviewable.

---------

Co-authored-by: Ivan Zakharchanka <[email protected]>
Co-authored-by: Codex <[email protected]>
wangjiecloud pushed a commit to wangjiecloud/codex that referenced this pull request Jun 27, 2026
## Stacked PRs

This work is split across three stacked PRs:

- openai#14178: add custom CA support for browser and device-code login flows,
docs, and hermetic subprocess tests
- openai#14239: broaden the shared custom CA path from login to other outbound
`reqwest` clients across Codex
- openai#14240: extend that shared custom CA handling to secure websocket TLS
so websocket connections honor the same CA env vars

Review order: openai#14178, then openai#14239, then openai#14240.

Supersedes openai#6864.

Thanks to @3axap4eHko for the original implementation and investigation
here. Although this version rearranges the code and history
significantly, the majority of the credit for this work belongs to them.

## Problem

Login flows need to work in enterprise environments where outbound TLS
is intercepted by an internal proxy or gateway. In those setups, system
root certificates alone are often insufficient to validate the OAuth and
device-code endpoints used during login. The change adds a
login-specific custom CA loading path, but the important contracts
around env precedence, PEM compatibility, test boundaries, and
probe-only workarounds need to be explicit so reviewers can understand
what behavior is intentional.

For users and operators, the behavior is simple: if login needs to trust
a custom root CA, set `CODEX_CA_CERTIFICATE` to a PEM file containing
one or more certificates. If that variable is unset, login falls back to
`SSL_CERT_FILE`. If neither is set, login uses system roots. Invalid or
empty PEM files now fail with an error that points back to those
environment variables and explains how to recover.

## What This Delivers

Users can now make Codex login work behind enterprise TLS interception
by pointing `CODEX_CA_CERTIFICATE` at a PEM bundle containing the
relevant root certificates. If that variable is unset, login falls back
to `SSL_CERT_FILE`, then to system roots.

This PR applies that behavior to both browser-based and device-code
login flows. It also makes login tolerant of the PEM shapes operators
actually have in hand: multi-certificate bundles, OpenSSL `TRUSTED
CERTIFICATE` labels, and bundles that include well-formed CRLs.

## Mental model

`codex-login` is the place where the login flows construct ad hoc
outbound HTTP clients. That makes it the right boundary for a narrow CA
policy: look for `CODEX_CA_CERTIFICATE`, fall back to `SSL_CERT_FILE`,
load every parseable certificate block in that bundle into a
`reqwest::Client`, and fail early with a clear user-facing error if the
bundle is unreadable or malformed.

The implementation is intentionally pragmatic about PEM input shape. It
accepts ordinary certificate bundles, multi-certificate bundles, OpenSSL
`TRUSTED CERTIFICATE` labels, and bundles that also contain CRLs. It
does not validate a certificate chain or prove a handshake; it only
constructs the root store used by login.

## Non-goals

This change does not introduce a general-purpose transport abstraction
for the rest of the product. It does not validate whether the provided
bundle forms a real chain, and it does not add handshake-level
integration tests against a live TLS server. It also does not change
login state management or OAuth semantics beyond ensuring the existing
flows share the same CA-loading rules.

## Tradeoffs

The main tradeoff is keeping this logic scoped to login-specific client
construction rather than lifting it into a broader shared HTTP layer.
That keeps the review surface smaller, but it also means future
login-adjacent code must continue to use `build_login_http_client()` or
it can silently bypass enterprise CA overrides.

The `TRUSTED CERTIFICATE` handling is also intentionally a local
compatibility shim. The rustls ecosystem does not currently accept that
PEM label upstream, so the code normalizes it locally and trims the
OpenSSL `X509_AUX` trailer bytes down to the certificate DER that
`reqwest` can consume.

## Architecture

`custom_ca.rs` is now the single place that owns login CA behavior. It
selects the CA file from the environment, reads it, normalizes PEM label
shape where needed, iterates mixed PEM sections with `rustls-pki-types`,
ignores CRLs, trims OpenSSL trust metadata when necessary, and returns
either a configured `reqwest::Client` or a typed error.

The browser login server and the device-code flow both call
`build_login_http_client()`, so they share the same trust-store policy.
Environment-sensitive tests run through the `login_ca_probe` helper
binary because those tests must control process-wide env vars and cannot
reliably build a real reqwest client in-process on macOS seatbelt runs.

## Observability

The custom CA path logs which environment variable selected the bundle,
which file path was loaded, how many certificates were accepted, when
`TRUSTED CERTIFICATE` labels were normalized, when CRLs were ignored,
and where client construction failed. Returned errors remain user-facing
and include the relevant path, env var, and remediation hint.

This gives enough signal for three audiences:
- users can see why login failed and which env/file caused it
- sysadmins can confirm which override actually won
- developers can tell whether the failure happened during file read, PEM
parsing, certificate registration, or final reqwest client construction

## Tests

Pure unit tests stay limited to env precedence and empty-value handling.
Real client construction lives in subprocess tests so the suite remains
hermetic with respect to process env and macOS sandbox behavior.

The subprocess tests verify:
- `CODEX_CA_CERTIFICATE` precedence over `SSL_CERT_FILE`
- fallback to `SSL_CERT_FILE`
- single-certificate and multi-certificate bundles
- malformed and empty-bundle errors
- OpenSSL `TRUSTED CERTIFICATE` handling
- CRL tolerance for well-formed CRL sections

The named PEM fixtures under `login/tests/fixtures/` are shared by the
tests so their purpose stays reviewable.

---------

Co-authored-by: Ivan Zakharchanka <[email protected]>
Co-authored-by: Codex <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OAuth Login Fails Behind Corporate Proxy with Custom CA Certificates

5 participants