Skip to main content

nono_proxy/
server.rs

1//! Proxy server: TCP listener, connection dispatch, and lifecycle.
2//!
3//! The server binds to `127.0.0.1:0` (OS-assigned port), accepts TCP
4//! connections, reads the first HTTP line to determine the mode, and
5//! dispatches to the appropriate handler.
6//!
7//! CONNECT method -> [`connect`] or [`external`] handler
8//! Other methods  -> [`reverse`] handler (credential injection)
9
10use crate::audit;
11use crate::config::ProxyConfig;
12use crate::connect;
13use crate::credential::CredentialStore;
14use crate::error::{ProxyError, Result};
15use crate::external;
16use crate::filter::ProxyFilter;
17use crate::reverse;
18use crate::route::RouteStore;
19use crate::tls_intercept::{self, CertCache, EphemeralCa};
20use crate::token;
21use std::net::SocketAddr;
22use std::path::PathBuf;
23use std::sync::Arc;
24use std::sync::atomic::{AtomicUsize, Ordering};
25use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
26use tokio::net::TcpListener;
27use tokio::sync::watch;
28use tracing::{debug, info, warn};
29use zeroize::Zeroizing;
30
31/// Maximum total size of HTTP headers (64 KiB). Prevents OOM from
32/// malicious clients sending unbounded header data.
33const MAX_HEADER_SIZE: usize = 64 * 1024;
34
35/// Handle returned when the proxy server starts.
36///
37/// Contains the assigned port, session token, and a shutdown channel.
38/// Drop the handle or send to `shutdown_tx` to stop the proxy.
39pub struct ProxyHandle {
40    /// The actual port the proxy is listening on
41    pub port: u16,
42    /// Session token for client authentication
43    pub token: Zeroizing<String>,
44    /// Shared in-memory network audit log
45    audit_log: audit::SharedAuditLog,
46    /// Send `true` to trigger graceful shutdown
47    shutdown_tx: watch::Sender<bool>,
48    /// Route prefixes that have credentials actually loaded.
49    /// Routes whose credentials were unavailable are excluded so we
50    /// don't inject phantom tokens that shadow valid external credentials.
51    loaded_routes: std::collections::HashSet<String>,
52    /// Non-credential allowed hosts that should bypass the proxy (NO_PROXY).
53    /// Computed at startup: `allowed_hosts` minus credential upstream hosts.
54    no_proxy_hosts: Vec<String>,
55    /// Path to the TLS-intercept trust bundle written at startup, when
56    /// interception is active. The CLI passes this path to the sandboxed
57    /// child via env vars (`SSL_CERT_FILE` etc.) and grants a Landlock /
58    /// Seatbelt read capability on it. `None` when interception is not
59    /// configured (no `intercept_ca_dir`) or no route requires L7 visibility.
60    intercept_ca_path: Option<PathBuf>,
61}
62
63impl ProxyHandle {
64    /// Signal the proxy to shut down gracefully.
65    pub fn shutdown(&self) {
66        let _ = self.shutdown_tx.send(true);
67    }
68
69    /// Drain and return collected network audit events.
70    #[must_use]
71    pub fn drain_audit_events(&self) -> Vec<nono::undo::NetworkAuditEvent> {
72        audit::drain_audit_events(&self.audit_log)
73    }
74
75    /// Path to the TLS-intercept trust bundle, when interception is active.
76    ///
77    /// The CLI uses this to:
78    /// * point `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE` / `NODE_EXTRA_CA_CERTS`
79    ///   / `CURL_CA_BUNDLE` at the file in the child env;
80    /// * grant the sandboxed child a Landlock / Seatbelt read capability
81    ///   on the file before applying the sandbox.
82    ///
83    /// `None` when interception is not configured (no `intercept_ca_dir`
84    /// in `ProxyConfig`) or when no configured route requires L7 visibility.
85    #[must_use]
86    pub fn intercept_ca_path(&self) -> Option<&std::path::Path> {
87        self.intercept_ca_path.as_deref()
88    }
89
90    /// One-line-per-route diagnostic summary suitable for surfacing at
91    /// session start. Returns `(prefix, summary)` pairs.
92    ///
93    /// Each summary names: upstream URL, credential resolution status
94    /// (✓ / ✗ + source label), TLS-intercept on/off, and `endpoint_rules`
95    /// count. Designed to make silent credential-resolution failures
96    /// noisy by default, addressing the common "I created the keychain
97    /// entry but the warn at debug level got missed" footgun.
98    ///
99    /// `config` is the same `ProxyConfig` that was passed to `start()`;
100    /// the handle doesn't keep a copy, so the CLI passes it back in.
101    #[must_use]
102    pub fn route_diagnostics(&self, config: &ProxyConfig) -> Vec<(String, String)> {
103        let mut rows = Vec::with_capacity(config.routes.len());
104        for route in &config.routes {
105            let prefix = route.prefix.trim_matches('/').to_string();
106            let cred_summary = if let Some(ref key) = route.credential_key {
107                let resolved = self.loaded_routes.contains(&prefix);
108                if resolved {
109                    format!("creds: {} ✓", key)
110                } else {
111                    format!("creds: {} ✗ (not found)", key)
112                }
113            } else if route.oauth2.is_some() {
114                let resolved = self.loaded_routes.contains(&prefix);
115                if resolved {
116                    "creds: oauth2 ✓".to_string()
117                } else {
118                    "creds: oauth2 ✗ (token exchange failed)".to_string()
119                }
120            } else {
121                "creds: none".to_string()
122            };
123
124            let intercept_summary = if self.intercept_ca_path.is_some()
125                && (route.credential_key.is_some()
126                    || route.oauth2.is_some()
127                    || !route.endpoint_rules.is_empty())
128            {
129                "intercept: on"
130            } else {
131                "intercept: off"
132            };
133
134            let rules_summary = format!("endpoint_rules: {}", route.endpoint_rules.len());
135            let summary = format!(
136                "→ {} | {} | {} | {}",
137                route.upstream, cred_summary, intercept_summary, rules_summary
138            );
139            rows.push((prefix, summary));
140        }
141        rows
142    }
143
144    /// Environment variables to inject into the child process.
145    ///
146    /// The proxy URL includes `nono:<token>@` userinfo so that standard HTTP
147    /// clients (curl, Python requests, etc.) automatically send
148    /// `Proxy-Authorization: Basic ...` on every request. The raw token is
149    /// also provided via `NONO_PROXY_TOKEN` for nono-aware clients that
150    /// prefer Bearer auth.
151    ///
152    /// When TLS interception is active (`intercept_ca_path()` is `Some`),
153    /// the standard runtime CA-trust env vars are also set so the agent
154    /// trusts the proxy's ephemeral CA when minted leaf certs are
155    /// presented during interception.
156    #[must_use]
157    pub fn env_vars(&self) -> Vec<(String, String)> {
158        let proxy_url = format!("http://nono:{}@127.0.0.1:{}", &*self.token, self.port);
159
160        // Build NO_PROXY: always include loopback, plus non-credential
161        // allowed hosts. Credential upstreams are excluded so their traffic
162        // goes through the reverse proxy for L7 filtering + injection.
163        let mut no_proxy_parts = vec!["localhost".to_string(), "127.0.0.1".to_string()];
164        for host in &self.no_proxy_hosts {
165            // Strip port for NO_PROXY (most HTTP clients match on hostname).
166            // Handle IPv6 brackets: "[::1]:443" → "[::1]", "host:443" → "host"
167            let hostname = if host.contains("]:") {
168                // IPv6 with port: split at "]:port"
169                host.rsplit_once("]:")
170                    .map(|(h, _)| format!("{}]", h))
171                    .unwrap_or_else(|| host.clone())
172            } else {
173                host.rsplit_once(':')
174                    .and_then(|(h, p)| p.parse::<u16>().ok().map(|_| h.to_string()))
175                    .unwrap_or_else(|| host.clone())
176            };
177            if !no_proxy_parts.contains(&hostname.to_string()) {
178                no_proxy_parts.push(hostname.to_string());
179            }
180        }
181        let no_proxy = no_proxy_parts.join(",");
182
183        let mut vars = vec![
184            ("HTTP_PROXY".to_string(), proxy_url.clone()),
185            ("HTTPS_PROXY".to_string(), proxy_url.clone()),
186            ("NO_PROXY".to_string(), no_proxy.clone()),
187            ("NONO_PROXY_TOKEN".to_string(), self.token.to_string()),
188        ];
189
190        // Lowercase variants for compatibility
191        vars.push(("http_proxy".to_string(), proxy_url.clone()));
192        vars.push(("https_proxy".to_string(), proxy_url));
193        vars.push(("no_proxy".to_string(), no_proxy));
194
195        // Node.js 20.6+ needs an explicit hint to use HTTPS_PROXY for built-in
196        // fetch(). Without it, Node-based clients can bypass the proxy and hit
197        // the sandboxed network directly.
198        // NODE_USE_ENV_PROXY tells Node's built-in fetch() to read HTTPS_PROXY
199        // from the environment.
200        // Harmless to non-Node runtimes — they ignore unknown env vars.
201        vars.push(("NODE_USE_ENV_PROXY".to_string(), "1".to_string()));
202
203        // TLS-intercept trust injection. The bundle file at this path
204        // contains the parent's `SSL_CERT_FILE` (if any) + the host's
205        // system trust store + the ephemeral session CA, so standard
206        // runtimes see a superset of the trust they had before nono.
207        //
208        // Replacement semantics (swap out the default store entirely):
209        //   SSL_CERT_FILE, REQUESTS_CA_BUNDLE, CURL_CA_BUNDLE, GIT_SSL_CAINFO
210        // Additive semantics (default + this file):
211        //   NODE_EXTRA_CA_CERTS
212        //
213        // Pointing all five at the same bundle is safe: Node sees system
214        // roots twice (harmless), and all other runtimes get the union of
215        // trust they need.
216        if let Some(path) = self.intercept_ca_path.as_deref() {
217            let path_str = path.to_string_lossy().to_string();
218            vars.push(("SSL_CERT_FILE".to_string(), path_str.clone()));
219            vars.push(("REQUESTS_CA_BUNDLE".to_string(), path_str.clone()));
220            vars.push(("NODE_EXTRA_CA_CERTS".to_string(), path_str.clone()));
221            vars.push(("CURL_CA_BUNDLE".to_string(), path_str.clone()));
222            vars.push(("GIT_SSL_CAINFO".to_string(), path_str));
223        }
224
225        vars
226    }
227
228    /// Environment variables for reverse proxy credential routes.
229    ///
230    /// Returns two types of env vars per route:
231    /// 1. SDK base URL overrides (e.g., `OPENAI_BASE_URL=http://127.0.0.1:PORT/openai`)
232    /// 2. SDK API key vars set to the session token (e.g., `OPENAI_API_KEY=<token>`)
233    ///
234    /// The SDK sends the session token as its "API key" (phantom token pattern).
235    /// The proxy validates this token and swaps it for the real credential.
236    #[must_use]
237    pub fn credential_env_vars(&self, config: &ProxyConfig) -> Vec<(String, String)> {
238        let mut vars = Vec::new();
239        for route in &config.routes {
240            // Strip any leading or trailing '/' from the prefix — prefix should
241            // be a bare service name (e.g., "anthropic"), not a URL path.
242            // Defensively handle both forms to prevent malformed env var names
243            // and double-slashed URLs.
244            let prefix = route.prefix.trim_matches('/');
245
246            // Base URL override (e.g., OPENAI_BASE_URL)
247            let base_url_name = format!("{}_BASE_URL", prefix.to_uppercase());
248            let url = format!("http://127.0.0.1:{}/{}", self.port, prefix);
249            vars.push((base_url_name, url));
250
251            // Only inject phantom token env vars for routes whose credentials
252            // were actually loaded. If a credential was unavailable (e.g.,
253            // GITHUB_TOKEN env var not set), injecting a phantom token would
254            // shadow valid credentials from other sources (keyring, gh auth).
255            if !self.loaded_routes.contains(prefix) {
256                continue;
257            }
258
259            // API key set to session token (phantom token pattern).
260            // Use explicit env_var if set (required for URI manager refs), otherwise
261            // fall back to uppercasing the credential_key (e.g., "openai_api_key" -> "OPENAI_API_KEY").
262            if let Some(ref env_var) = route.env_var {
263                vars.push((env_var.clone(), self.token.to_string()));
264            } else if let Some(ref cred_key) = route.credential_key {
265                // Skip URI-format keys (e.g. env://, op://, apple-password://) —
266                // uppercasing a URI produces a nonsensical env var name. These
267                // routes must declare an explicit env_var to get phantom token injection.
268                if !cred_key.contains("://") {
269                    let api_key_name = cred_key.to_uppercase();
270                    vars.push((api_key_name, self.token.to_string()));
271                }
272            }
273        }
274        vars
275    }
276}
277
278impl Drop for ProxyHandle {
279    /// Best-effort cleanup of the TLS-intercept trust bundle on shutdown.
280    ///
281    /// The CA private key was never persisted to disk (it lives only in a
282    /// `Zeroizing<Vec<u8>>` inside the running proxy task and is zeroized
283    /// when that task drops). Here we remove the public certificate file
284    /// so the next session doesn't inherit a stale bundle path.
285    ///
286    /// Errors are intentionally swallowed — `Drop` has no good way to
287    /// surface them, and the file may already be gone if the user invoked
288    /// `shutdown()` from another path.
289    fn drop(&mut self) {
290        if let Some(path) = self.intercept_ca_path.take() {
291            let _ = std::fs::remove_file(&path);
292            // If the parent dir is now empty (we may have been the only
293            // tenant in `~/.nono/sessions/<id>/`), tidy up. A non-empty
294            // dir simply fails the rmdir and leaves unrelated contents
295            // in place — exactly what we want.
296            if let Some(parent) = path.parent() {
297                let _ = std::fs::remove_dir(parent);
298            }
299        }
300    }
301}
302
303/// Shared state for the proxy server.
304struct ProxyState {
305    filter: ProxyFilter,
306    session_token: Zeroizing<String>,
307    /// Route-level configuration (upstream, L7 filtering, custom TLS CA) for all routes.
308    route_store: RouteStore,
309    /// Credential-specific configuration (inject mode, headers, secrets) for routes with credentials.
310    credential_store: CredentialStore,
311    config: ProxyConfig,
312    /// Shared TLS connector for upstream connections (reverse proxy mode).
313    /// Created once at startup to avoid rebuilding the root cert store per request.
314    tls_connector: tokio_rustls::TlsConnector,
315    /// Active connection count for connection limiting.
316    active_connections: AtomicUsize,
317    /// Shared network audit log for this proxy session.
318    audit_log: audit::SharedAuditLog,
319    /// Matcher for hosts that bypass the external proxy and route direct.
320    /// Built once at startup from `ExternalProxyConfig.bypass_hosts`.
321    bypass_matcher: external::BypassMatcher,
322    /// Per-hostname leaf-certificate cache backed by the session ephemeral
323    /// CA, when TLS interception is active. `None` disables the intercept
324    /// CONNECT branch (CONNECTs fall through to the existing 403/tunnel
325    /// dispatch even for routes that would otherwise require L7).
326    cert_cache: Option<Arc<CertCache>>,
327}
328
329/// Start the proxy server.
330///
331/// Binds to `config.bind_addr:config.bind_port` (port 0 = OS-assigned),
332/// generates a session token, and begins accepting connections.
333///
334/// Returns a `ProxyHandle` with the assigned port and session token.
335/// The server runs until the handle is dropped or `shutdown()` is called.
336pub async fn start(config: ProxyConfig) -> Result<ProxyHandle> {
337    // Generate session token
338    let session_token = token::generate_session_token()?;
339
340    // Bind listener
341    let bind_addr = SocketAddr::new(config.bind_addr, config.bind_port);
342    let listener = TcpListener::bind(bind_addr)
343        .await
344        .map_err(|e| ProxyError::Bind {
345            addr: bind_addr.to_string(),
346            source: e,
347        })?;
348
349    let local_addr = listener.local_addr().map_err(|e| ProxyError::Bind {
350        addr: bind_addr.to_string(),
351        source: e,
352    })?;
353    let port = local_addr.port();
354
355    info!("Proxy server listening on {}", local_addr);
356
357    // Load route-level configuration (upstream, L7 filtering, custom TLS CA)
358    // for ALL routes, regardless of credential presence.
359    let route_store = if config.routes.is_empty() {
360        RouteStore::empty()
361    } else {
362        RouteStore::load(&config.routes)?
363    };
364    // Build shared TLS connector (root cert store is expensive to construct).
365    // Use the ring provider explicitly to avoid ambiguity when multiple
366    // crypto providers are in the dependency tree.
367    // Must be created before CredentialStore::load() because OAuth2 token
368    // exchange needs TLS.
369    let mut root_store = rustls::RootCertStore::empty();
370    root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
371    let native = rustls_native_certs::load_native_certs();
372    if !native.errors.is_empty() {
373        debug!(
374            "failed to load {} native cert(s); continuing with webpki roots + any that succeeded",
375            native.errors.len()
376        );
377    }
378    let native_count = native.certs.len();
379    for cert in native.certs {
380        if let Err(e) = root_store.add(cert) {
381            debug!("skipping unparseable native cert: {e}");
382        }
383    }
384    if native_count > 0 {
385        debug!("added {native_count} native system CA(s) to upstream trust store");
386    }
387    let tls_config = rustls::ClientConfig::builder_with_provider(Arc::new(
388        rustls::crypto::ring::default_provider(),
389    ))
390    .with_safe_default_protocol_versions()
391    .map_err(|e| ProxyError::Config(format!("TLS config error: {}", e)))?
392    .with_root_certificates(root_store)
393    .with_no_client_auth();
394    let tls_connector = tokio_rustls::TlsConnector::from(Arc::new(tls_config));
395
396    // Load credentials for reverse proxy routes (static keystore + OAuth2)
397    let credential_store = if config.routes.is_empty() {
398        CredentialStore::empty()
399    } else {
400        CredentialStore::load(&config.routes, &tls_connector)?
401    };
402    let loaded_routes = credential_store.loaded_prefixes();
403
404    // Build filter
405    let filter = if config.allowed_hosts.is_empty() {
406        ProxyFilter::allow_all()
407    } else {
408        ProxyFilter::new(&config.allowed_hosts)
409    };
410
411    // Build bypass matcher from external proxy config (once, not per-request)
412    let bypass_matcher = config
413        .external_proxy
414        .as_ref()
415        .map(|ext| external::BypassMatcher::new(&ext.bypass_hosts))
416        .unwrap_or_else(|| external::BypassMatcher::new(&[]));
417
418    // Shutdown channel
419    let (shutdown_tx, shutdown_rx) = watch::channel(false);
420    let audit_log = audit::new_audit_log();
421
422    // Compute NO_PROXY hosts: allowed_hosts that can be reached via
423    // direct TCP connections (i.e. their port is in direct_connect_ports).
424    // Hosts without a direct TCP grant MUST go through the proxy —
425    // adding them to NO_PROXY would cause clients to attempt direct
426    // connections that the sandbox (Landlock / Seatbelt) denies.
427    //
428    // Route upstreams are always excluded so their traffic goes through
429    // the proxy for L7 path filtering and/or credential injection.
430    //
431    // On macOS this MUST be empty regardless: Seatbelt's ProxyOnly mode
432    // blocks ALL direct outbound. See #580.
433    let no_proxy_hosts: Vec<String> = if cfg!(target_os = "macos") {
434        Vec::new()
435    } else {
436        let route_hosts = route_store.route_upstream_hosts();
437        config
438            .allowed_hosts
439            .iter()
440            .filter(|host| {
441                let normalised = {
442                    let h = host.to_lowercase();
443                    if h.starts_with('[') {
444                        // IPv6 literal: "[::1]:443" has port, "[::1]" needs default
445                        if h.contains("]:") {
446                            h
447                        } else {
448                            format!("{}:443", h)
449                        }
450                    } else if h.contains(':') {
451                        h
452                    } else {
453                        format!("{}:443", h)
454                    }
455                };
456                if route_hosts.contains(&normalised) {
457                    return false;
458                }
459                // Only bypass the proxy if the sandbox grants direct
460                // TCP on this host's port (via --allow-connect-port).
461                let port = normalised
462                    .rsplit_once(':')
463                    .and_then(|(_, p)| p.parse::<u16>().ok())
464                    .unwrap_or(443);
465                config.direct_connect_ports.contains(&port)
466            })
467            .cloned()
468            .collect()
469    };
470
471    if !no_proxy_hosts.is_empty() {
472        debug!("Smart NO_PROXY bypass hosts: {:?}", no_proxy_hosts);
473    }
474
475    // Initialise TLS interception if a directory was supplied AND at least
476    // one configured route actually requires L7 visibility. Routes are
477    // checked here (rather than relying solely on the CLI's decision) so a
478    // misconfigured `intercept_ca_dir` without intercept-bearing routes
479    // doesn't generate a useless CA on disk.
480    let any_intercept_route = route_store
481        .route_upstream_hosts()
482        .iter()
483        .any(|hp| route_store.has_intercept_route(hp));
484    let (cert_cache, intercept_ca_path) = match (&config.intercept_ca_dir, any_intercept_route) {
485        (Some(dir), true) => {
486            let intercept_route_count = route_store
487                .route_upstream_hosts()
488                .iter()
489                .filter(|hp| route_store.has_intercept_route(hp))
490                .count();
491            let ca_result = if let Some(ref preloaded) = config.preloaded_ca {
492                EphemeralCa::from_existing(&preloaded.key_der, &preloaded.cert_pem)
493            } else {
494                let validity = config
495                    .ca_validity
496                    .unwrap_or(crate::tls_intercept::ca::CA_VALIDITY_DEFAULT);
497                EphemeralCa::generate_with_cn("nono-session-ca", validity)
498            };
499            match ca_result.and_then(|ca| {
500                let ca = Arc::new(ca);
501                let cache = Arc::new(CertCache::new(Arc::clone(&ca)));
502                let path = tls_intercept::write_bundle(tls_intercept::BundleInputs {
503                    dir,
504                    filename: "intercept-ca.pem",
505                    parent_ssl_cert_file: config.intercept_parent_ca_pems.as_deref(),
506                    ephemeral_ca_pem: ca.cert_pem(),
507                })?;
508                Ok((cache, path))
509            }) {
510                Ok((cache, path)) => {
511                    info!(
512                        "TLS interception active for {} route(s); trust bundle at {}",
513                        intercept_route_count,
514                        path.display()
515                    );
516                    (Some(cache), Some(path))
517                }
518                Err(e) => {
519                    warn!(
520                        "TLS interception setup failed for {} route(s): {}. \
521                         Continuing with interception disabled; reverse-proxy routes remain available.",
522                        intercept_route_count, e
523                    );
524                    (None, None)
525                }
526            }
527        }
528        (Some(_), false) => {
529            debug!(
530                "TLS interception requested but no configured route requires L7 visibility; \
531                 skipping CA generation"
532            );
533            (None, None)
534        }
535        (None, _) => (None, None),
536    };
537
538    let state = Arc::new(ProxyState {
539        filter,
540        session_token: session_token.clone(),
541        route_store,
542        credential_store,
543        config,
544        tls_connector,
545        active_connections: AtomicUsize::new(0),
546        audit_log: Arc::clone(&audit_log),
547        bypass_matcher,
548        cert_cache,
549    });
550
551    // Spawn accept loop as a task within the current runtime.
552    // The caller MUST ensure this runtime is being driven (e.g., via
553    // a dedicated thread calling block_on or a multi-thread runtime).
554    tokio::spawn(accept_loop(listener, state, shutdown_rx));
555
556    Ok(ProxyHandle {
557        port,
558        token: session_token,
559        audit_log,
560        shutdown_tx,
561        loaded_routes,
562        no_proxy_hosts,
563        intercept_ca_path,
564    })
565}
566
567/// Accept loop: listen for connections until shutdown.
568async fn accept_loop(
569    listener: TcpListener,
570    state: Arc<ProxyState>,
571    mut shutdown_rx: watch::Receiver<bool>,
572) {
573    loop {
574        tokio::select! {
575            result = listener.accept() => {
576                match result {
577                    Ok((stream, addr)) => {
578                        // Connection limit enforcement
579                        let max = state.config.max_connections;
580                        if max > 0 {
581                            let current = state.active_connections.load(Ordering::Relaxed);
582                            if current >= max {
583                                warn!("Connection limit reached ({}/{}), rejecting {}", current, max, addr);
584                                // Drop the stream (connection refused)
585                                drop(stream);
586                                continue;
587                            }
588                        }
589                        state.active_connections.fetch_add(1, Ordering::Relaxed);
590
591                        debug!("Accepted connection from {}", addr);
592                        let state = Arc::clone(&state);
593                        tokio::spawn(async move {
594                            if let Err(e) = handle_connection(stream, &state).await {
595                                debug!("Connection handler error: {}", e);
596                            }
597                            state.active_connections.fetch_sub(1, Ordering::Relaxed);
598                        });
599                    }
600                    Err(e) => {
601                        warn!("Accept error: {}", e);
602                    }
603                }
604            }
605            _ = shutdown_rx.changed() => {
606                if *shutdown_rx.borrow() {
607                    info!("Proxy server shutting down");
608                    return;
609                }
610            }
611        }
612    }
613}
614
615/// Handle a single client connection.
616///
617/// Reads the first HTTP line to determine the proxy mode:
618/// - CONNECT method -> tunnel (Mode 1 or 3)
619/// - Other methods  -> reverse proxy (Mode 2)
620async fn handle_connection(mut stream: tokio::net::TcpStream, state: &ProxyState) -> Result<()> {
621    // Read the first line and headers through a BufReader.
622    // We keep the BufReader alive until we've consumed the full header
623    // to prevent data loss (BufReader may read ahead into the body).
624    let mut buf_reader = BufReader::new(&mut stream);
625    let mut first_line = String::new();
626    buf_reader.read_line(&mut first_line).await?;
627
628    if first_line.is_empty() {
629        return Ok(()); // Client disconnected
630    }
631
632    // Read remaining headers (up to empty line), with size limit to prevent OOM.
633    let mut header_bytes = Vec::new();
634    loop {
635        let mut line = String::new();
636        let n = buf_reader.read_line(&mut line).await?;
637        if n == 0 || line.trim().is_empty() {
638            break;
639        }
640        header_bytes.extend_from_slice(line.as_bytes());
641        if header_bytes.len() > MAX_HEADER_SIZE {
642            drop(buf_reader);
643            let response = "HTTP/1.1 431 Request Header Fields Too Large\r\n\r\n";
644            stream.write_all(response.as_bytes()).await?;
645            return Ok(());
646        }
647    }
648
649    // Extract any data buffered beyond headers before dropping BufReader.
650    // BufReader may have read ahead into the request body. We capture
651    // those bytes and pass them to the reverse proxy handler so no body
652    // data is lost. For CONNECT requests this is always empty (no body).
653    let buffered = buf_reader.buffer().to_vec();
654    drop(buf_reader);
655
656    let first_line = first_line.trim_end();
657
658    // Dispatch by method
659    if first_line.starts_with("CONNECT ") {
660        // CONNECT requests targeting a configured route's upstream get
661        // special handling. There are three sub-cases:
662        //
663        // 1. Route requires L7 visibility (`endpoint_rules`, `credential_key`,
664        //    or `oauth2`) AND TLS interception is configured: terminate TLS
665        //    locally so credential injection / endpoint filtering can run.
666        // 2. Route requires L7 visibility but interception is *not* configured:
667        //    fall back to the existing 403 — the agent must use the reverse
668        //    proxy path. Without interception we can't enforce L7 over CONNECT.
669        // 3. Route exists but is purely declarative (no L7 requirements):
670        //    keep the existing 403 — the route exists to provide a `*_BASE_URL`
671        //    env var, and CONNECT would bypass that intent.
672        //
673        // Anything else (host not matching any route) falls through to the
674        // existing transparent-tunnel / external-proxy paths.
675        if !state.route_store.is_empty()
676            && let Some(authority) = first_line.split_whitespace().nth(1)
677        {
678            // Normalise authority to host:port. Handle IPv6 brackets:
679            // "[::1]:443" already has port, "[::1]" needs default, "host:443" has port.
680            let host_port = if authority.starts_with('[') {
681                if authority.contains("]:") {
682                    authority.to_lowercase()
683                } else {
684                    format!("{}:443", authority.to_lowercase())
685                }
686            } else if authority.contains(':') {
687                authority.to_lowercase()
688            } else {
689                format!("{}:443", authority.to_lowercase())
690            };
691
692            if state.route_store.is_route_upstream(&host_port) {
693                let route_id = state
694                    .route_store
695                    .lookup_by_upstream(&host_port)
696                    .map(|(prefix, _)| prefix);
697                let (host, port) = host_port
698                    .rsplit_once(':')
699                    .map(|(h, p)| (h.to_string(), p.parse::<u16>().unwrap_or(443)))
700                    .unwrap_or_else(|| (host_port.clone(), 443));
701
702                let intercept_eligible = state.route_store.has_intercept_route(&host_port);
703
704                match (intercept_eligible, state.cert_cache.as_ref()) {
705                    // Case 1: intercept-eligible route + cert cache available.
706                    (true, Some(cache)) => {
707                        // Strict OUTER auth: intercept is a privileged op
708                        // (we mint a leaf cert and decrypt traffic), so
709                        // unlike the lenient transparent-tunnel path we
710                        // require Proxy-Authorization here.
711                        if let Err(e) =
712                            token::validate_proxy_auth(&header_bytes, &state.session_token)
713                        {
714                            debug!(
715                                "tls_intercept: rejecting CONNECT to {}:{} — {}",
716                                host, port, e
717                            );
718                            audit::log_denied(
719                                    Some(&state.audit_log),
720                                    audit::ProxyMode::ConnectIntercept,
721                                    &audit::EventContext {
722                                        route_id,
723                                        auth_mechanism: Some(
724                                            nono::undo::NetworkAuditAuthMechanism::ProxyAuthorization,
725                                        ),
726                                        auth_outcome: Some(
727                                            nono::undo::NetworkAuditAuthOutcome::Failed,
728                                        ),
729                                        denial_category: Some(
730                                            nono::undo::NetworkAuditDenialCategory::AuthenticationFailed,
731                                        ),
732                                        ..audit::EventContext::default()
733                                    },
734                                    &host,
735                                    port,
736                                    "proxy auth missing or invalid",
737                                );
738                            let response = "HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"nono\"\r\nContent-Length: 0\r\n\r\n";
739                            stream.write_all(response.as_bytes()).await?;
740                            return Ok(());
741                        }
742
743                        let ctx = tls_intercept::InterceptCtx {
744                            route_id,
745                            host: &host,
746                            port,
747                            route_store: &state.route_store,
748                            credential_store: &state.credential_store,
749                            session_token: &state.session_token,
750                            cert_cache: Arc::clone(cache),
751                            tls_connector: &state.tls_connector,
752                            filter: &state.filter,
753                            audit_log: Some(&state.audit_log),
754                        };
755                        return tls_intercept::handle_intercept_connect(&mut stream, ctx).await;
756                    }
757                    // Case 2 & 3: route exists but interception is unavailable
758                    // or the route is purely declarative — keep the existing
759                    // 403 to force SDK cooperation with the reverse-proxy path.
760                    _ => {
761                        debug!(
762                            "Blocked CONNECT to route upstream {} — use reverse proxy path instead",
763                            authority
764                        );
765                        audit::log_denied(
766                            Some(&state.audit_log),
767                            audit::ProxyMode::Connect,
768                            &audit::EventContext {
769                                route_id,
770                                denial_category: Some(
771                                    nono::undo::NetworkAuditDenialCategory::ConnectBypassesL7,
772                                ),
773                                ..audit::EventContext::default()
774                            },
775                            &host,
776                            port,
777                            "route upstream: CONNECT bypasses L7 filtering",
778                        );
779                        let response = "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n";
780                        stream.write_all(response.as_bytes()).await?;
781                        return Ok(());
782                    }
783                }
784            }
785        }
786
787        // Check if external proxy is configured and host is not bypassed
788        let use_external = if let Some(ref ext_config) = state.config.external_proxy {
789            if state.bypass_matcher.is_empty() {
790                Some(ext_config)
791            } else {
792                // Parse host from CONNECT line to check bypass
793                let host = first_line
794                    .split_whitespace()
795                    .nth(1)
796                    .and_then(|authority| {
797                        authority
798                            .rsplit_once(':')
799                            .map(|(h, _)| h)
800                            .or(Some(authority))
801                    })
802                    .unwrap_or("");
803                if state.bypass_matcher.matches(host) {
804                    debug!("Bypassing external proxy for {}", host);
805                    None
806                } else {
807                    Some(ext_config)
808                }
809            }
810        } else {
811            None
812        };
813
814        if let Some(ext_config) = use_external {
815            external::handle_external_proxy(
816                first_line,
817                &mut stream,
818                &header_bytes,
819                &state.filter,
820                &state.session_token,
821                ext_config,
822                Some(&state.audit_log),
823            )
824            .await
825        } else if state.config.external_proxy.is_some() {
826            // Bypass route: enforce strict session token validation before
827            // routing direct. Without this, bypassed hosts would inherit
828            // connect::handle_connect()'s lenient auth (which tolerates
829            // missing Proxy-Authorization for Node.js undici compat).
830            token::validate_proxy_auth(&header_bytes, &state.session_token)?;
831            connect::handle_connect(
832                first_line,
833                &mut stream,
834                &state.filter,
835                &state.session_token,
836                &header_bytes,
837                Some(&state.audit_log),
838            )
839            .await
840        } else {
841            connect::handle_connect(
842                first_line,
843                &mut stream,
844                &state.filter,
845                &state.session_token,
846                &header_bytes,
847                Some(&state.audit_log),
848            )
849            .await
850        }
851    } else if !state.route_store.is_empty() {
852        // Non-CONNECT request with routes configured -> reverse proxy
853        let ctx = reverse::ReverseProxyCtx {
854            route_store: &state.route_store,
855            credential_store: &state.credential_store,
856            session_token: &state.session_token,
857            filter: &state.filter,
858            tls_connector: &state.tls_connector,
859            audit_log: Some(&state.audit_log),
860        };
861        reverse::handle_reverse_proxy(first_line, &mut stream, &header_bytes, &ctx, &buffered).await
862    } else {
863        // No routes configured, reject non-CONNECT requests
864        let response = "HTTP/1.1 400 Bad Request\r\n\r\n";
865        stream.write_all(response.as_bytes()).await?;
866        Ok(())
867    }
868}
869
870#[cfg(test)]
871#[allow(clippy::unwrap_used)]
872mod tests {
873    use super::*;
874
875    #[tokio::test]
876    async fn test_proxy_starts_and_binds() {
877        let config = ProxyConfig::default();
878        let handle = start(config).await.unwrap();
879
880        // Port should be non-zero (OS-assigned)
881        assert!(handle.port > 0);
882        // Token should be 64 hex chars
883        assert_eq!(handle.token.len(), 64);
884
885        // Shutdown
886        handle.shutdown();
887    }
888
889    /// End-to-end smoke test: when `intercept_ca_dir` is set AND a route
890    /// requires L7 visibility, the proxy:
891    /// 1. generates an ephemeral CA;
892    /// 2. writes a trust bundle file with at least the ephemeral cert + system roots;
893    /// 3. exposes the path via `intercept_ca_path()`;
894    /// 4. emits trust env vars (`SSL_CERT_FILE` etc.) pointing at it;
895    /// 5. cleans the file on `Drop`.
896    #[tokio::test]
897    async fn test_intercept_lifecycle_end_to_end() {
898        let dir = tempfile::tempdir().unwrap();
899        let ca_path_clone;
900
901        {
902            let config = ProxyConfig {
903                routes: vec![crate::config::RouteConfig {
904                    prefix: "openai".to_string(),
905                    upstream: "https://api.openai.com".to_string(),
906                    credential_key: Some("env://NONO_TEST_TOTALLY_MISSING".to_string()),
907                    inject_mode: Default::default(),
908                    inject_header: "Authorization".to_string(),
909                    credential_format: Some("Bearer {}".to_string()),
910                    path_pattern: None,
911                    path_replacement: None,
912                    query_param_name: None,
913                    proxy: None,
914                    env_var: None,
915                    endpoint_rules: vec![],
916                    tls_ca: None,
917                    tls_client_cert: None,
918                    tls_client_key: None,
919                    oauth2: None,
920                }],
921                intercept_ca_dir: Some(dir.path().to_path_buf()),
922                ..Default::default()
923            };
924            let handle = start(config).await.unwrap();
925            assert!(
926                handle.intercept_ca_path().is_some(),
927                "intercept-eligible route + intercept_ca_dir → bundle path should be Some"
928            );
929            ca_path_clone = handle.intercept_ca_path().unwrap().to_path_buf();
930            assert!(
931                ca_path_clone.exists(),
932                "bundle file should have been written"
933            );
934
935            let contents = std::fs::read_to_string(&ca_path_clone).unwrap();
936            assert!(
937                contents.contains("BEGIN CERTIFICATE"),
938                "bundle should contain at least one PEM block"
939            );
940
941            // Trust env vars should reference the bundle.
942            let vars = handle.env_vars();
943            let ssl = vars
944                .iter()
945                .find(|(k, _)| k == "SSL_CERT_FILE")
946                .expect("SSL_CERT_FILE should be set when intercept active");
947            assert_eq!(std::path::Path::new(&ssl.1), ca_path_clone);
948            assert!(vars.iter().any(|(k, _)| k == "REQUESTS_CA_BUNDLE"));
949            assert!(vars.iter().any(|(k, _)| k == "NODE_EXTRA_CA_CERTS"));
950            assert!(vars.iter().any(|(k, _)| k == "CURL_CA_BUNDLE"));
951
952            handle.shutdown();
953        }
954        // After `handle` is dropped, the bundle file should be gone.
955        assert!(
956            !ca_path_clone.exists(),
957            "bundle should be removed when ProxyHandle drops"
958        );
959    }
960
961    /// When `intercept_ca_dir` is set but no route requires L7 visibility,
962    /// the proxy should NOT generate a CA (it would just be wasted material).
963    #[tokio::test]
964    async fn test_intercept_skipped_for_purely_declarative_routes() {
965        let dir = tempfile::tempdir().unwrap();
966        let config = ProxyConfig {
967            routes: vec![crate::config::RouteConfig {
968                prefix: "alias".to_string(),
969                upstream: "https://aliased.example.com".to_string(),
970                credential_key: None,
971                inject_mode: Default::default(),
972                inject_header: "Authorization".to_string(),
973                credential_format: Some("Bearer {}".to_string()),
974                path_pattern: None,
975                path_replacement: None,
976                query_param_name: None,
977                proxy: None,
978                env_var: None,
979                endpoint_rules: vec![],
980                tls_ca: None,
981                tls_client_cert: None,
982                tls_client_key: None,
983                oauth2: None,
984            }],
985            intercept_ca_dir: Some(dir.path().to_path_buf()),
986            ..Default::default()
987        };
988        let handle = start(config).await.unwrap();
989        assert!(
990            handle.intercept_ca_path().is_none(),
991            "no L7-bearing route → no CA should be generated"
992        );
993        let vars = handle.env_vars();
994        assert!(
995            vars.iter().all(|(k, _)| k != "SSL_CERT_FILE"),
996            "trust env vars must not be set when intercept inactive"
997        );
998        handle.shutdown();
999    }
1000
1001    /// Intercept setup failures must not abort proxy startup for reverse-proxy
1002    /// routes. We degrade to "intercept off" so credential routes still work,
1003    /// while CONNECT interception remains unavailable and will keep its
1004    /// existing deny behaviour.
1005    #[tokio::test]
1006    async fn test_intercept_setup_failure_degrades_without_aborting_proxy() {
1007        let missing_dir = tempfile::tempdir()
1008            .unwrap()
1009            .path()
1010            .join("missing")
1011            .join("intercept");
1012        let config = ProxyConfig {
1013            routes: vec![crate::config::RouteConfig {
1014                prefix: "openai".to_string(),
1015                upstream: "https://api.openai.com".to_string(),
1016                credential_key: Some("env://NONO_TEST_TOTALLY_MISSING".to_string()),
1017                inject_mode: Default::default(),
1018                inject_header: "Authorization".to_string(),
1019                credential_format: Some("Bearer {}".to_string()),
1020                path_pattern: None,
1021                path_replacement: None,
1022                query_param_name: None,
1023                proxy: None,
1024                env_var: None,
1025                endpoint_rules: vec![],
1026                tls_ca: None,
1027                tls_client_cert: None,
1028                tls_client_key: None,
1029                oauth2: None,
1030            }],
1031            intercept_ca_dir: Some(missing_dir),
1032            ..Default::default()
1033        };
1034        let handle = start(config.clone()).await.unwrap();
1035        assert!(
1036            handle.intercept_ca_path().is_none(),
1037            "intercept setup failure should disable interception instead of aborting startup"
1038        );
1039        let vars = handle.env_vars();
1040        assert!(
1041            vars.iter().all(|(k, _)| k != "SSL_CERT_FILE"),
1042            "trust env vars must not be set when interception setup fails"
1043        );
1044        let route_vars = handle.credential_env_vars(&config);
1045        assert!(
1046            route_vars.iter().any(|(k, _)| k == "OPENAI_BASE_URL"),
1047            "reverse-proxy route env vars should still be emitted"
1048        );
1049        handle.shutdown();
1050    }
1051
1052    /// `route_diagnostics()` returns one row per route summarising
1053    /// upstream, credential resolution, intercept on/off, and rule count.
1054    #[tokio::test]
1055    async fn test_route_diagnostics_summarises_each_route() {
1056        let dir = tempfile::tempdir().unwrap();
1057        let config = ProxyConfig {
1058            routes: vec![
1059                crate::config::RouteConfig {
1060                    prefix: "openai".to_string(),
1061                    upstream: "https://api.openai.com".to_string(),
1062                    credential_key: Some("env://NONO_TEST_MISSING".to_string()),
1063                    inject_mode: Default::default(),
1064                    inject_header: "Authorization".to_string(),
1065                    credential_format: Some("Bearer {}".to_string()),
1066                    path_pattern: None,
1067                    path_replacement: None,
1068                    query_param_name: None,
1069                    proxy: None,
1070                    env_var: None,
1071                    endpoint_rules: vec![],
1072                    tls_ca: None,
1073                    tls_client_cert: None,
1074                    tls_client_key: None,
1075                    oauth2: None,
1076                },
1077                crate::config::RouteConfig {
1078                    prefix: "alias".to_string(),
1079                    upstream: "https://aliased.example.com".to_string(),
1080                    credential_key: None,
1081                    inject_mode: Default::default(),
1082                    inject_header: "Authorization".to_string(),
1083                    credential_format: Some("Bearer {}".to_string()),
1084                    path_pattern: None,
1085                    path_replacement: None,
1086                    query_param_name: None,
1087                    proxy: None,
1088                    env_var: None,
1089                    endpoint_rules: vec![],
1090                    tls_ca: None,
1091                    tls_client_cert: None,
1092                    tls_client_key: None,
1093                    oauth2: None,
1094                },
1095            ],
1096            intercept_ca_dir: Some(dir.path().to_path_buf()),
1097            ..Default::default()
1098        };
1099        let handle = start(config.clone()).await.unwrap();
1100        let rows = handle.route_diagnostics(&config);
1101        assert_eq!(rows.len(), 2);
1102
1103        let openai = rows.iter().find(|(p, _)| p == "openai").unwrap();
1104        assert!(openai.1.contains("api.openai.com"));
1105        assert!(openai.1.contains("intercept: on"));
1106        assert!(
1107            openai.1.contains("✗") || openai.1.contains("not found"),
1108            "missing credential should show ✗, got: {}",
1109            openai.1
1110        );
1111
1112        let alias = rows.iter().find(|(p, _)| p == "alias").unwrap();
1113        assert!(alias.1.contains("creds: none"));
1114        assert!(alias.1.contains("intercept: off"));
1115
1116        handle.shutdown();
1117    }
1118
1119    #[tokio::test]
1120    async fn test_proxy_env_vars() {
1121        let config = ProxyConfig::default();
1122        let handle = start(config).await.unwrap();
1123
1124        let vars = handle.env_vars();
1125        let http_proxy = vars.iter().find(|(k, _)| k == "HTTP_PROXY");
1126        assert!(http_proxy.is_some());
1127        assert!(http_proxy.unwrap().1.starts_with("http://nono:"));
1128
1129        let token_var = vars.iter().find(|(k, _)| k == "NONO_PROXY_TOKEN");
1130        assert!(token_var.is_some());
1131        assert_eq!(token_var.unwrap().1.len(), 64);
1132
1133        let node_proxy_flag = vars.iter().find(|(k, _)| k == "NODE_USE_ENV_PROXY");
1134        assert!(
1135            node_proxy_flag.is_some(),
1136            "proxy env must set NODE_USE_ENV_PROXY for Node 20.6+ (undici 5.22+) built-in fetch()"
1137        );
1138        assert_eq!(
1139            node_proxy_flag.unwrap().1,
1140            "1",
1141            "NODE_USE_ENV_PROXY must be '1'"
1142        );
1143
1144        handle.shutdown();
1145    }
1146
1147    #[tokio::test]
1148    async fn test_proxy_credential_env_vars() {
1149        let config = ProxyConfig {
1150            routes: vec![crate::config::RouteConfig {
1151                prefix: "openai".to_string(),
1152                upstream: "https://api.openai.com".to_string(),
1153                credential_key: None,
1154                inject_mode: crate::config::InjectMode::Header,
1155                inject_header: "Authorization".to_string(),
1156                credential_format: Some("Bearer {}".to_string()),
1157                path_pattern: None,
1158                path_replacement: None,
1159                query_param_name: None,
1160                proxy: None,
1161                env_var: None,
1162                endpoint_rules: vec![],
1163                tls_ca: None,
1164                tls_client_cert: None,
1165                tls_client_key: None,
1166                oauth2: None,
1167            }],
1168            ..Default::default()
1169        };
1170        let handle = start(config.clone()).await.unwrap();
1171
1172        let vars = handle.credential_env_vars(&config);
1173        assert_eq!(vars.len(), 1);
1174        assert_eq!(vars[0].0, "OPENAI_BASE_URL");
1175        assert!(vars[0].1.contains("/openai"));
1176
1177        handle.shutdown();
1178    }
1179
1180    #[test]
1181    fn test_proxy_credential_env_vars_fallback_to_uppercase_key() {
1182        // When env_var is None and credential_key is set, the env var name
1183        // should be derived from uppercasing credential_key. This is the
1184        // backward-compatible path for keyring-backed credentials.
1185        let (shutdown_tx, _) = tokio::sync::watch::channel(false);
1186        let handle = ProxyHandle {
1187            port: 12345,
1188            token: Zeroizing::new("test_token".to_string()),
1189            audit_log: audit::new_audit_log(),
1190            shutdown_tx,
1191            loaded_routes: ["openai".to_string()].into_iter().collect(),
1192            no_proxy_hosts: Vec::new(),
1193            intercept_ca_path: None,
1194        };
1195        let config = ProxyConfig {
1196            routes: vec![crate::config::RouteConfig {
1197                prefix: "openai".to_string(),
1198                upstream: "https://api.openai.com".to_string(),
1199                credential_key: Some("openai_api_key".to_string()),
1200                inject_mode: crate::config::InjectMode::Header,
1201                inject_header: "Authorization".to_string(),
1202                credential_format: Some("Bearer {}".to_string()),
1203                path_pattern: None,
1204                path_replacement: None,
1205                query_param_name: None,
1206                proxy: None,
1207                env_var: None, // No explicit env_var — should fall back to uppercase
1208                endpoint_rules: vec![],
1209                tls_ca: None,
1210                tls_client_cert: None,
1211                tls_client_key: None,
1212                oauth2: None,
1213            }],
1214            ..Default::default()
1215        };
1216
1217        let vars = handle.credential_env_vars(&config);
1218        assert_eq!(vars.len(), 2); // BASE_URL + API_KEY
1219
1220        // Should derive OPENAI_API_KEY from uppercasing "openai_api_key"
1221        let api_key_var = vars.iter().find(|(k, _)| k == "OPENAI_API_KEY");
1222        assert!(
1223            api_key_var.is_some(),
1224            "Should derive env var name from credential_key.to_uppercase()"
1225        );
1226
1227        let (_, val) = api_key_var.expect("OPENAI_API_KEY should exist");
1228        assert_eq!(val, "test_token");
1229    }
1230
1231    #[test]
1232    fn test_proxy_credential_env_vars_with_explicit_env_var() {
1233        // When env_var is set on a route, it should be used instead of
1234        // deriving from credential_key. This is essential for URI manager
1235        // credential refs (e.g., op://, apple-password://)
1236        // where uppercasing produces nonsensical env var names.
1237        //
1238        // We construct a ProxyHandle directly to test env var generation
1239        // without starting a real proxy (which would try to load credentials).
1240        let (shutdown_tx, _) = tokio::sync::watch::channel(false);
1241        let handle = ProxyHandle {
1242            port: 12345,
1243            token: Zeroizing::new("test_token".to_string()),
1244            audit_log: audit::new_audit_log(),
1245            shutdown_tx,
1246            loaded_routes: ["openai".to_string()].into_iter().collect(),
1247            no_proxy_hosts: Vec::new(),
1248            intercept_ca_path: None,
1249        };
1250        let config = ProxyConfig {
1251            routes: vec![crate::config::RouteConfig {
1252                prefix: "openai".to_string(),
1253                upstream: "https://api.openai.com".to_string(),
1254                credential_key: Some("op://Development/OpenAI/credential".to_string()),
1255                inject_mode: crate::config::InjectMode::Header,
1256                inject_header: "Authorization".to_string(),
1257                credential_format: Some("Bearer {}".to_string()),
1258                path_pattern: None,
1259                path_replacement: None,
1260                query_param_name: None,
1261                proxy: None,
1262                env_var: Some("OPENAI_API_KEY".to_string()),
1263                endpoint_rules: vec![],
1264                tls_ca: None,
1265                tls_client_cert: None,
1266                tls_client_key: None,
1267                oauth2: None,
1268            }],
1269            ..Default::default()
1270        };
1271
1272        let vars = handle.credential_env_vars(&config);
1273        assert_eq!(vars.len(), 2); // BASE_URL + API_KEY
1274
1275        let api_key_var = vars.iter().find(|(k, _)| k == "OPENAI_API_KEY");
1276        assert!(
1277            api_key_var.is_some(),
1278            "Should use explicit env_var name, not derive from credential_key"
1279        );
1280
1281        // Verify the value is the phantom token, not the real credential
1282        let (_, val) = api_key_var.expect("OPENAI_API_KEY var should exist");
1283        assert_eq!(val, "test_token");
1284
1285        // Verify no nonsensical OP:// env var was generated
1286        let bad_var = vars.iter().find(|(k, _)| k.starts_with("OP://"));
1287        assert!(
1288            bad_var.is_none(),
1289            "Should not generate env var from op:// URI uppercase"
1290        );
1291    }
1292
1293    #[test]
1294    fn test_proxy_credential_env_vars_skips_unloaded_routes() {
1295        // When a credential is unavailable (e.g., GITHUB_TOKEN not set),
1296        // the route should NOT inject a phantom token env var. Otherwise
1297        // the phantom token shadows valid credentials from other sources
1298        // like the system keyring. See: #234
1299        let (shutdown_tx, _) = tokio::sync::watch::channel(false);
1300        let handle = ProxyHandle {
1301            port: 12345,
1302            token: Zeroizing::new("test_token".to_string()),
1303            audit_log: audit::new_audit_log(),
1304            shutdown_tx,
1305            // Only "openai" was loaded; "github" credential was unavailable
1306            loaded_routes: ["openai".to_string()].into_iter().collect(),
1307            no_proxy_hosts: Vec::new(),
1308            intercept_ca_path: None,
1309        };
1310        let config = ProxyConfig {
1311            routes: vec![
1312                crate::config::RouteConfig {
1313                    prefix: "openai".to_string(),
1314                    upstream: "https://api.openai.com".to_string(),
1315                    credential_key: Some("openai_api_key".to_string()),
1316                    inject_mode: crate::config::InjectMode::Header,
1317                    inject_header: "Authorization".to_string(),
1318                    credential_format: Some("Bearer {}".to_string()),
1319                    path_pattern: None,
1320                    path_replacement: None,
1321                    query_param_name: None,
1322                    proxy: None,
1323                    env_var: None,
1324                    endpoint_rules: vec![],
1325                    tls_ca: None,
1326                    tls_client_cert: None,
1327                    tls_client_key: None,
1328                    oauth2: None,
1329                },
1330                crate::config::RouteConfig {
1331                    prefix: "github".to_string(),
1332                    upstream: "https://api.github.com".to_string(),
1333                    credential_key: Some("env://GITHUB_TOKEN".to_string()),
1334                    inject_mode: crate::config::InjectMode::Header,
1335                    inject_header: "Authorization".to_string(),
1336                    credential_format: Some("token {}".to_string()),
1337                    path_pattern: None,
1338                    path_replacement: None,
1339                    query_param_name: None,
1340                    proxy: None,
1341                    env_var: Some("GITHUB_TOKEN".to_string()),
1342                    endpoint_rules: vec![],
1343                    tls_ca: None,
1344                    tls_client_cert: None,
1345                    tls_client_key: None,
1346                    oauth2: None,
1347                },
1348            ],
1349            ..Default::default()
1350        };
1351
1352        let vars = handle.credential_env_vars(&config);
1353
1354        // openai should have BASE_URL + API_KEY (credential loaded)
1355        let openai_base = vars.iter().find(|(k, _)| k == "OPENAI_BASE_URL");
1356        assert!(openai_base.is_some(), "loaded route should have BASE_URL");
1357        let openai_key = vars.iter().find(|(k, _)| k == "OPENAI_API_KEY");
1358        assert!(openai_key.is_some(), "loaded route should have API key");
1359
1360        // github should have BASE_URL (always set for declared routes) but
1361        // must NOT have GITHUB_TOKEN (credential was not loaded)
1362        let github_base = vars.iter().find(|(k, _)| k == "GITHUB_BASE_URL");
1363        assert!(
1364            github_base.is_some(),
1365            "declared route should still have BASE_URL"
1366        );
1367        let github_token = vars.iter().find(|(k, _)| k == "GITHUB_TOKEN");
1368        assert!(
1369            github_token.is_none(),
1370            "unloaded route must not inject phantom GITHUB_TOKEN"
1371        );
1372    }
1373
1374    #[test]
1375    fn test_proxy_credential_env_vars_strips_slashes() {
1376        // When prefix includes leading/trailing slashes, the env var name
1377        // must not contain slashes and the URL must not double-slash.
1378        // Regression test for user-reported bug where "/anthropic" produced
1379        // "/ANTHROPIC_BASE_URL=http://127.0.0.1:PORT//anthropic".
1380        let (shutdown_tx, _) = tokio::sync::watch::channel(false);
1381        let handle = ProxyHandle {
1382            port: 58406,
1383            token: Zeroizing::new("test_token".to_string()),
1384            audit_log: audit::new_audit_log(),
1385            shutdown_tx,
1386            loaded_routes: std::collections::HashSet::new(),
1387            no_proxy_hosts: Vec::new(),
1388            intercept_ca_path: None,
1389        };
1390
1391        // Test leading slash
1392        let config = ProxyConfig {
1393            routes: vec![crate::config::RouteConfig {
1394                prefix: "/anthropic".to_string(),
1395                upstream: "https://api.anthropic.com".to_string(),
1396                credential_key: None,
1397                inject_mode: crate::config::InjectMode::Header,
1398                inject_header: "Authorization".to_string(),
1399                credential_format: Some("Bearer {}".to_string()),
1400                path_pattern: None,
1401                path_replacement: None,
1402                query_param_name: None,
1403                proxy: None,
1404                env_var: None,
1405                endpoint_rules: vec![],
1406                tls_ca: None,
1407                tls_client_cert: None,
1408                tls_client_key: None,
1409                oauth2: None,
1410            }],
1411            ..Default::default()
1412        };
1413
1414        let vars = handle.credential_env_vars(&config);
1415        assert_eq!(vars.len(), 1);
1416        assert_eq!(
1417            vars[0].0, "ANTHROPIC_BASE_URL",
1418            "env var name must not have leading slash"
1419        );
1420        assert_eq!(
1421            vars[0].1, "http://127.0.0.1:58406/anthropic",
1422            "URL must not have double slash"
1423        );
1424
1425        // Test trailing slash
1426        let config = ProxyConfig {
1427            routes: vec![crate::config::RouteConfig {
1428                prefix: "openai/".to_string(),
1429                upstream: "https://api.openai.com".to_string(),
1430                credential_key: None,
1431                inject_mode: crate::config::InjectMode::Header,
1432                inject_header: "Authorization".to_string(),
1433                credential_format: Some("Bearer {}".to_string()),
1434                path_pattern: None,
1435                path_replacement: None,
1436                query_param_name: None,
1437                proxy: None,
1438                env_var: None,
1439                endpoint_rules: vec![],
1440                tls_ca: None,
1441                tls_client_cert: None,
1442                tls_client_key: None,
1443                oauth2: None,
1444            }],
1445            ..Default::default()
1446        };
1447
1448        let vars = handle.credential_env_vars(&config);
1449        assert_eq!(
1450            vars[0].0, "OPENAI_BASE_URL",
1451            "env var name must not have trailing slash"
1452        );
1453        assert_eq!(
1454            vars[0].1, "http://127.0.0.1:58406/openai",
1455            "URL must not have trailing slash in path"
1456        );
1457    }
1458
1459    #[test]
1460    fn test_anthropic_credential_phantom_token_regression() {
1461        // Regression test for issue #624: the built-in anthropic credential
1462        // entry had no env_var or credential_key, so ANTHROPIC_API_KEY was
1463        // never set to the phantom token. Only ANTHROPIC_BASE_URL was injected,
1464        // leaving the sandbox to send the host's real key directly.
1465        //
1466        // Pre-fix state: route in loaded_routes but no env_var / credential_key
1467        // => ANTHROPIC_API_KEY must NOT appear (demonstrates the bug).
1468        let (shutdown_tx, _) = tokio::sync::watch::channel(false);
1469        let handle_no_env_var = ProxyHandle {
1470            port: 12345,
1471            token: Zeroizing::new("phantom".to_string()),
1472            audit_log: audit::new_audit_log(),
1473            shutdown_tx: shutdown_tx.clone(),
1474            loaded_routes: ["anthropic".to_string()].into_iter().collect(),
1475            no_proxy_hosts: Vec::new(),
1476            intercept_ca_path: None,
1477        };
1478        let config_no_env_var = ProxyConfig {
1479            routes: vec![crate::config::RouteConfig {
1480                prefix: "anthropic".to_string(),
1481                upstream: "https://api.anthropic.com".to_string(),
1482                credential_key: None,
1483                inject_mode: crate::config::InjectMode::Header,
1484                inject_header: "x-api-key".to_string(),
1485                credential_format: Some("{}".to_string()),
1486                path_pattern: None,
1487                path_replacement: None,
1488                query_param_name: None,
1489                proxy: None,
1490                env_var: None,
1491                endpoint_rules: vec![],
1492                tls_ca: None,
1493                tls_client_cert: None,
1494                tls_client_key: None,
1495                oauth2: None,
1496            }],
1497            ..Default::default()
1498        };
1499        let vars_no_env_var = handle_no_env_var.credential_env_vars(&config_no_env_var);
1500        assert!(
1501            vars_no_env_var
1502                .iter()
1503                .all(|(k, _)| k != "ANTHROPIC_API_KEY"),
1504            "pre-fix: ANTHROPIC_API_KEY must not be set when neither env_var nor credential_key is defined (bug reproduced)"
1505        );
1506
1507        // Post-fix state: route has env_var = "ANTHROPIC_API_KEY"
1508        // => ANTHROPIC_API_KEY must be set to the phantom token.
1509        let (shutdown_tx2, _) = tokio::sync::watch::channel(false);
1510        let handle_fixed = ProxyHandle {
1511            port: 12345,
1512            token: Zeroizing::new("phantom".to_string()),
1513            audit_log: audit::new_audit_log(),
1514            shutdown_tx: shutdown_tx2,
1515            loaded_routes: ["anthropic".to_string()].into_iter().collect(),
1516            no_proxy_hosts: Vec::new(),
1517            intercept_ca_path: None,
1518        };
1519        let config_fixed = ProxyConfig {
1520            routes: vec![crate::config::RouteConfig {
1521                prefix: "anthropic".to_string(),
1522                upstream: "https://api.anthropic.com".to_string(),
1523                credential_key: Some("ANTHROPIC_API_KEY".to_string()),
1524                inject_mode: crate::config::InjectMode::Header,
1525                inject_header: "x-api-key".to_string(),
1526                credential_format: Some("{}".to_string()),
1527                path_pattern: None,
1528                path_replacement: None,
1529                query_param_name: None,
1530                proxy: None,
1531                env_var: Some("ANTHROPIC_API_KEY".to_string()),
1532                endpoint_rules: vec![],
1533                tls_ca: None,
1534                tls_client_cert: None,
1535                tls_client_key: None,
1536                oauth2: None,
1537            }],
1538            ..Default::default()
1539        };
1540        let vars_fixed = handle_fixed.credential_env_vars(&config_fixed);
1541        let api_key_var = vars_fixed.iter().find(|(k, _)| k == "ANTHROPIC_API_KEY");
1542        assert!(
1543            api_key_var.is_some(),
1544            "post-fix: ANTHROPIC_API_KEY must be set to the phantom token"
1545        );
1546        assert_eq!(api_key_var.unwrap().1, "phantom");
1547    }
1548
1549    #[test]
1550    fn test_no_proxy_excludes_credential_upstreams() {
1551        let (shutdown_tx, _) = tokio::sync::watch::channel(false);
1552        let handle = ProxyHandle {
1553            port: 12345,
1554            token: Zeroizing::new("test_token".to_string()),
1555            audit_log: audit::new_audit_log(),
1556            shutdown_tx,
1557            loaded_routes: std::collections::HashSet::new(),
1558            no_proxy_hosts: vec![
1559                "nats.internal:4222".to_string(),
1560                "opencode.internal:4096".to_string(),
1561            ],
1562            intercept_ca_path: None,
1563        };
1564
1565        let vars = handle.env_vars();
1566        let no_proxy = vars.iter().find(|(k, _)| k == "NO_PROXY").unwrap();
1567        assert!(
1568            no_proxy.1.contains("nats.internal"),
1569            "non-credential host should be in NO_PROXY"
1570        );
1571        assert!(
1572            no_proxy.1.contains("opencode.internal"),
1573            "non-credential host should be in NO_PROXY"
1574        );
1575        assert!(
1576            no_proxy.1.contains("localhost"),
1577            "localhost should always be in NO_PROXY"
1578        );
1579    }
1580
1581    #[test]
1582    fn test_no_proxy_empty_when_no_non_credential_hosts() {
1583        let (shutdown_tx, _) = tokio::sync::watch::channel(false);
1584        let handle = ProxyHandle {
1585            port: 12345,
1586            token: Zeroizing::new("test_token".to_string()),
1587            audit_log: audit::new_audit_log(),
1588            shutdown_tx,
1589            loaded_routes: std::collections::HashSet::new(),
1590            no_proxy_hosts: Vec::new(),
1591            intercept_ca_path: None,
1592        };
1593
1594        let vars = handle.env_vars();
1595        let no_proxy = vars.iter().find(|(k, _)| k == "NO_PROXY").unwrap();
1596        assert_eq!(
1597            no_proxy.1, "localhost,127.0.0.1",
1598            "NO_PROXY should only contain loopback when no bypass hosts"
1599        );
1600    }
1601
1602    #[tokio::test]
1603    async fn test_no_proxy_empty_without_direct_connect_ports() {
1604        // When direct_connect_ports is empty (no --allow-connect-port),
1605        // allowed_hosts should NOT appear in NO_PROXY because the sandbox
1606        // blocks direct TCP and clients would fail to connect. See #760.
1607        let config = ProxyConfig {
1608            allowed_hosts: vec!["github.com".to_string()],
1609            ..Default::default()
1610        };
1611        let handle = start(config).await.unwrap();
1612
1613        let vars = handle.env_vars();
1614        let no_proxy = vars.iter().find(|(k, _)| k == "NO_PROXY").unwrap();
1615        assert_eq!(
1616            no_proxy.1, "localhost,127.0.0.1",
1617            "allowed_hosts must not appear in NO_PROXY without direct_connect_ports"
1618        );
1619
1620        handle.shutdown();
1621    }
1622
1623    #[cfg(not(target_os = "macos"))]
1624    #[tokio::test]
1625    async fn test_no_proxy_includes_hosts_with_matching_connect_port() {
1626        // When direct_connect_ports includes port 443, allowed_hosts on
1627        // that port SHOULD appear in NO_PROXY (direct TCP is permitted).
1628        // macOS always returns empty NO_PROXY (Seatbelt blocks all direct outbound).
1629        let config = ProxyConfig {
1630            allowed_hosts: vec!["github.com".to_string(), "server.internal:4222".to_string()],
1631            direct_connect_ports: vec![443],
1632            ..Default::default()
1633        };
1634        let handle = start(config).await.unwrap();
1635
1636        let vars = handle.env_vars();
1637        let no_proxy = vars.iter().find(|(k, _)| k == "NO_PROXY").unwrap();
1638        assert!(
1639            no_proxy.1.contains("github.com"),
1640            "host on port 443 should be in NO_PROXY when 443 is in direct_connect_ports"
1641        );
1642        assert!(
1643            !no_proxy.1.contains("server.internal"),
1644            "host on port 4222 should NOT be in NO_PROXY when only 443 is allowed"
1645        );
1646
1647        handle.shutdown();
1648    }
1649}