Skip to content
Closed
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
9 changes: 5 additions & 4 deletions crates/jcode-provider-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod model_names;
pub mod models;
pub mod openai_schema;
pub mod pricing;
mod qualification_http;
pub mod reasoning;
pub mod retry_after;
pub mod selection;
Expand Down Expand Up @@ -730,7 +731,7 @@ pub fn shared_http_client() -> reqwest::Client {
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
CLIENT
.get_or_init(|| {
reqwest::Client::builder()
qualification_http::builder()
.user_agent(KCODE_USER_AGENT)
.connect_timeout(Duration::from_secs(15))
.tcp_keepalive(Some(Duration::from_secs(30)))
Expand All @@ -747,7 +748,7 @@ pub fn shared_http_client() -> reqwest::Client {
.build()
.unwrap_or_else(|err| {
eprintln!("jcode: failed to build shared provider HTTP client: {err}");
match reqwest::Client::builder()
match qualification_http::builder()
.user_agent(KCODE_USER_AGENT)
.build()
{
Expand All @@ -756,7 +757,7 @@ pub fn shared_http_client() -> reqwest::Client {
eprintln!(
"jcode: failed to build fallback provider HTTP client: {fallback_err}"
);
reqwest::Client::new()
qualification_http::fallback_client()
}
}
})
Expand All @@ -774,7 +775,7 @@ pub fn shared_http_client() -> reqwest::Client {
/// that makes transport-fault retries actually succeed). Building a client
/// costs ~10ms, which is fine on a retry path that already backs off >=1s.
pub fn fresh_transport_client() -> reqwest::Client {
reqwest::Client::builder()
qualification_http::builder()
.user_agent(KCODE_USER_AGENT)
.connect_timeout(Duration::from_secs(15))
.tcp_keepalive(Some(Duration::from_secs(30)))
Expand Down
31 changes: 31 additions & 0 deletions crates/jcode-provider-core/src/qualification_http.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//! Explicit provider-client opt-out from proxy discovery for isolated qualification.
//! This does not enforce offline execution: the caller must retain its OS sandbox.
use std::ffi::OsStr;

fn enabled() -> bool {
std::env::var_os("KCODE_QUALIFICATION_NO_PROXY").as_deref() == Some(OsStr::new("1"))
}

pub(crate) fn builder() -> reqwest::ClientBuilder {
let builder = reqwest::Client::builder();
if enabled() {
// Supported reqwest API: skip environment and macOS system proxy discovery.
builder.no_proxy()
} else {
builder
}
}

/// Constructs the last-resort provider HTTP client.
///
/// Constructing this fallback client may panic if reqwest cannot build it.
pub(crate) fn fallback_client() -> reqwest::Client {
if enabled() {
// Do not reintroduce system-proxy discovery via Client::new on a fallback.
builder()
.build()
.expect("failed to build qualification provider HTTP client")
Comment thread
KooshaPari marked this conversation as resolved.
Resolved
} else {
reqwest::Client::new()
}
}
190 changes: 190 additions & 0 deletions crates/jcode-provider-core/tests/qualification_proxy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
//! Process-isolated proxy qualification; no provider credentials or model calls.
use jcode_provider_core::{fresh_transport_client, shared_http_client};
use std::{
io::{Read, Write},
net::TcpListener,
process::{Command, Output},
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
thread,
time::{Duration, Instant},
};

const OPT_IN: &str = "KCODE_QUALIFICATION_NO_PROXY";
const PROBE: &str = "KCODE_PROXY_TEST_PROBE";

fn child(mode: Option<&str>) -> Command {
let mut command = Command::new(std::env::current_exe().unwrap());
command
.env_clear()
.args(["--exact", "client_probe", "--nocapture", "--test-threads=1"])
.env(PROBE, "build")
.env("PATH", "/usr/bin:/bin");
if let Some(value) = mode {
command.env(OPT_IN, value);
}
command
}

fn success(output: Output) {
assert!(
output.status.success(),
"child failed: {}",
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8_lossy(&output.stdout).contains("PROVIDER_CLIENTS_BUILT"));
}

#[tokio::test]
async fn client_probe() {
let Ok(probe) = std::env::var(PROBE) else {
return;
};
// Call twice to exercise the process-wide cache, then its fresh retry path.
let clients = [
shared_http_client(),
shared_http_client(),
fresh_transport_client(),
];
if probe == "network" {
let url = std::env::var("KCODE_PROXY_TEST_URL").unwrap();
let expected = std::env::var("KCODE_PROXY_TEST_BODY").unwrap();
for client in clients {
let response = client
.get(&url)
.timeout(Duration::from_secs(3))
.send()
.await
.unwrap();
assert_eq!(response.text().await.unwrap(), expected);
}
}
println!("PROVIDER_CLIENTS_BUILT");
}

struct Server {
address: String,
requests: Arc<AtomicUsize>,
stop: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}

impl Server {
fn new(body: &'static str) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let address = listener.local_addr().unwrap().to_string();
let requests = Arc::new(AtomicUsize::new(0));
let stop = Arc::new(AtomicBool::new(false));
let (count, stopping) = (requests.clone(), stop.clone());
let worker = thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(30);
while !stopping.load(Ordering::Relaxed) && Instant::now() < deadline {
match listener.accept() {
Ok((mut stream, _)) => {
// Accepted sockets can inherit O_NONBLOCK on macOS.
stream.set_nonblocking(false).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(2)))
.unwrap();
let mut request = [0; 16384];
let bytes = stream.read(&mut request).unwrap();
assert!(bytes > 0);
count.fetch_add(1, Ordering::Relaxed);
write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
)
.unwrap();
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(5))
}
Err(e) => panic!("loopback fixture: {e}"),
}
}
});
Self {
address,
requests,
stop,
worker: Some(worker),
}
}
}

impl Drop for Server {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Err(failure) = self.worker.take().unwrap().join() {
eprintln!("loopback fixture worker panicked");
// Keep the original test failure visible instead of aborting in Drop.
if !thread::panicking() {
std::panic::resume_unwind(failure);
}
}
}
}

#[test]
fn opt_in_bypasses_proxy_while_unset_and_other_values_preserve_it() {
let proxy = Server::new("proxy");
let origin = Server::new("direct");
for (mode, body) in [
(None, "proxy"),
(Some("true"), "proxy"),
(Some("1"), "direct"),
] {
let output = child(mode)
.env(PROBE, "network")
.env("HTTP_PROXY", format!("http://{}", proxy.address))
.env("NO_PROXY", "")
.env(
"KCODE_PROXY_TEST_URL",
format!("http://{}/qualification", origin.address),
)
.env("KCODE_PROXY_TEST_BODY", body)
.output()
.unwrap();
success(output);
}
assert_eq!(proxy.requests.load(Ordering::Relaxed), 6);
assert_eq!(origin.requests.load(Ordering::Relaxed), 3);
}

#[cfg(target_os = "macos")]
#[test]
fn mach_denied_opt_in_builds_real_clients_and_normal_mode_keeps_system_probe() {
// Both modes get the identical restrictions. No Mach or network grant is added.
let profile = "(version 1) (allow default) (deny mach-lookup) (deny network*)";
let restricted = |mode: Option<&str>| {
let probe = child(mode);
let mut command = Command::new("/usr/bin/sandbox-exec");
command
.env_clear()
.args(["-p", profile])
.arg(probe.get_program())
.args(probe.get_args());
for (key, value) in probe.get_envs() {
if let Some(value) = value {
command.env(key, value);
}
}
command.output().unwrap()
};
let normal = restricted(None);
assert!(
!normal.status.success(),
"negative control no longer reproduces denied system-proxy discovery"
);
let stderr = String::from_utf8_lossy(&normal.stderr);
assert!(
stderr.contains("Attempted to create a NULL object"),
"unexpected failure: {stderr}"
);
success(restricted(Some("1")));
}
14 changes: 14 additions & 0 deletions docs/ENVIRONMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,20 @@ is regenerated on each release cut.
| `JCODE_MCP_TOOLS` | (unset) | jcode-base | Override `tools.mcp_tools` config field |
| `JCODE_MCP_TOOLS_TOKEN_THRESHOLD` | (unset) | jcode-base | Override `tools.mcp_tools_token_threshold` config field |

### Isolated provider-client qualification

`KCODE_QUALIFICATION_NO_PROXY=1` opts only generic shared/fresh provider HTTP
clients (including their fallback construction) out of environment and system
proxy discovery using reqwest's `ClientBuilder::no_proxy()`. Unset and all other
values retain the normal production proxy behavior. Set it in the isolated child
process environment before startup; the shared client is cached on first use.

This flag is not a network/offline security boundary. Use it only within an
already restricted qualification sandbox that continues denying outbound network
and Mach access; it neither changes sandbox grants nor prevents direct HTTP
requests. It does not change provider-specific clients outside these generic
constructors or modify installed binaries, shared services, or user profiles.

### ACP adapter

| Env var | Default | Used by | Description |
Expand Down
90 changes: 90 additions & 0 deletions docs/sessions/20261018-qualification-proxy/01_RESEARCH.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Opt-in provider proxy qualification

## Scope and identity

Repository: KooshaPari/KCode; its source checkout is named `jcode`.
Verified fork origin: `https://github.com/KooshaPari/KCode.git`.
Baseline/default branch: `master` at
`028ae83b769a932c013f527b305a5dbf0480ffe0`.
Worktree: isolated branch worktree for this qualification change.
Branch: `codex/qualification-no-proxy-20261018`.
The canonical checkout, unrelated untracked documents, installed profiles,
launchers and shared services were preserved. No upstream publication occurred.

## Root cause and supported API

The supplied sanitized receipt identifies the startup path:
`Server::new_with_name -> AmbientRunnerHandle::new -> NotificationDispatcher::new
-> jcode_provider_core::shared_http_client -> reqwest ClientBuilder::build
-> system proxy -> SystemConfiguration NULL-object panic` when Mach is denied.
The receipt's installed-binary SHA is
`d649bc210a4dbcc29d6e501208d683d45e4a6191ba8a0bc58a2df32e8f89cb5a`;
this does not identify that binary's source revision or qualify a repaired install.

The provider crate enables system proxies and pins reqwest 0.12.28 with
hyper-util 0.1.19. Inspection of matching registry sources confirms that reqwest's
`auto_sys_proxy` defaults true; `build()` adds the system matcher only when this
flag remains true. `no_proxy()` clears proxies and sets it false. Hyper-util's
macOS system matcher calls `SCDynamicStoreBuilder::new("").build()` even after
reading environment proxy settings.

Primary reference: [reqwest 0.12.28 ClientBuilder::no_proxy](https://docs.rs/reqwest/0.12.28/reqwest/struct.ClientBuilder.html#method.no_proxy).
Matching upstream source locations are reqwest `src/async_impl/client.rs` and
hyper-util `src/client/proxy/matcher.rs`; their local registry sources were read.
The official API page was accessible; online source-page fetches were unavailable.

## Implementation

Only exact `KCODE_QUALIFICATION_NO_PROXY=1` invokes the documented `no_proxy()`
API for generic shared/fresh provider clients and fallback construction.
Unset/other values return ordinary reqwest builders, retaining proxy defaults.
The shared cache, User-Agent, timeouts, HTTP/2 keepalive and pooling are unchanged.
No dependency feature defaults or OS sandbox permissions changed.

Set the opt-in before isolated child startup. It is not an offline/network
security boundary: the qualification sandbox must continue denying outbound
network and Mach access. Other independently constructed provider clients and
full daemon/session behavior are outside this narrowly scoped repair.

## Verification and limits

Tests isolate process environment and process-wide client caches. The exact
baseline produced a clean RED: 1 passed, 2 intended failures; opt-in still used
the loopback proxy and still reproduced the SystemConfiguration NULL panic.

After the production patch, the Mach-denied test passed. A separate fixture read
returned WouldBlock and cleanup double-panicked. The failed log was preserved.
The authorized fixture repair explicitly switches accepted sockets to blocking
before their bounded read and avoids a second panic while already unwinding.

Final commands, with the isolated cache and macOS SDK/deployment environment:

```sh
cargo test --locked --jobs 1 -p jcode-provider-core --test qualification_proxy
cargo check -p jcode-provider-core --jobs 1
```

Focused tests: **3 passed, 0 failed**, 1.45s runtime; cached compile 3.03s.
Check: **passed**, exit 0, 37.00s. Formatting and `git diff --check` passed.

The real clients preserve unset/invalid-value loopback proxy routing, bypass it
only for exact opt-in, and build under identical Mach/network denial only with
opt-in. Default mode retains the known NULL-panic negative control. The shared
client is called twice and the fresh-client path is exercised. No provider
credentials or model requests are used. No whole suite, full ACP/daemon startup,
installed artifact, hosted CI, or release gate is claimed.

## Preserved artifacts

Preserved local logs, retained outside the source worktree:

- `kcode-proxy-resume-red.log`: clean baseline RED.
- `kcode-proxy-green.log`: preserved fixture failure; SHA-256
`64321fb06b485db9223563ee88c2cbdb4c6abdcfcf831609585517c8c5c55e2a`.
- `kcode-proxy-fixture-green.log`: final focused GREEN.
- `kcode-proxy-check.log`: successful crate check.

Local compute used one job, no GPU or remote compute. The validation build cache
was moved intact from the isolated worktree to a local state directory after
validation so it remains outside the reviewable source tree. No cache data was
deleted.
Loading