Repository navigation
fix(provider-core): opt out of proxy discovery for qualification (cherry-pick of #122) #123
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ac4219b
fix(provider-core): opt out of proxy discovery for qualification
KooshaPari 1c87e83
fix(portal): XJ-03 LIVE verification — bridge reaches OAuth authorize…
KooshaPari daf6f1d
ci: re-trigger workflow (queue pass)
KooshaPari 587ba41
merge: bring in master to resolve conflict (queue pass)
KooshaPari 5ee58e8
docs(kcode): address PR 123 review requests
KooshaPari d45f02b
Merge remote-tracking branch 'origin/master' into HEAD
KooshaPari File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
| } else { | ||
| reqwest::Client::new() | ||
| } | ||
| } | ||
190 changes: 190 additions & 0 deletions
190
crates/jcode-provider-core/tests/qualification_proxy.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"))); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.