Skip to main content

aft_base/secret_proxy/
mod.rs

1//! A command-private CONNECT proxy. The launcher supplies only scanned, resolved
2//! labels and arms the new command session before releasing the child. The job
3//! owner retains the handle and reports process-tree end or the end of the
4//! configured lifetime SecretScope, either of which stops the proxy.
5//! The armed leader's start time pins its generation. Loss or replacement of
6//! that leader also stops the proxy, even if orphaned descendants remain.
7//! Each proxy admits at most 16 connections and 32 in-flight requests/streams.
8//! Sockets have a 30-second activity-based idle timeout (also the TCP connect
9//! deadline). Response coding depth is at most four. At most 32 label/key
10//! matcher sets and 4096 bytes per material value are accepted; old matchers
11//! are never evicted to make room. JSON input remains capped at 1 MiB and grows
12//! only as body bytes arrive. Limits refuse new work rather than weaken scrub.
13//! On an approved target, a header placeholder whose label was not granted at
14//! launch refuses by label and host without fetching material. It is not added
15//! to the command's substitution set. Other destinations remain literal.
16//!
17//! # Memory boundary
18//!
19//! Vault material, matcher patterns, overlap windows, and all proxy-created
20//! material-bearing request staging use zeroizing owners. This includes the Bytes owners behind
21//! substituted header values, query-bearing URIs, and JSON bodies. The rules
22//! evaluator plans locations with public dummy bytes, never real material.
23//!
24//! Third-party codec buffers are outside that ownership guarantee: rustls owns
25//! TLS plaintext/record buffers; h2 owns HTTP/2 stream and HPACK buffers; Hyper
26//! owns its HTTP/1 encoder write buffer; async-compression and its codec crates
27//! own decompression workspaces. These codecs allocate and manage their own
28//! buffers rather than accepting AFT's zeroizing owners. The proxy does not
29//! persist or log any of them, or format key-bearing requests or responses with
30//! `Debug` or `Display`. Zeroization is defence in depth in the daemon, not a claim
31//! that third-party protocol implementations erase every transient copy.
32//!
33//! # What the response scrub does not catch
34//!
35//! Responses are scrubbed as a stream with `Scrubber::push` and `finish`, held
36//! back by a fixed window of `6k - 1` bytes for the longest installed key of
37//! `k` bytes. Unlike a placeholder URL fetch, the proxy runs no residual check
38//! over the finished response. A covered server, one this command was allowed
39//! to send the key to, can therefore make these reach the command's stdout:
40//!
41//! - Base64 of a key split by spaces, tabs or line breaks whose span, from the
42//!   first to the last character of the spelling, is longer than six times the
43//!   longest key, when a read boundary falls inside that span. Shorter split
44//!   spellings, and every other spelling in the scrubber's families (raw,
45//!   `%XX`, form, JSON escapes, hex, contiguous base64), are always caught.
46//! - Every spelling outside those families, in any chunking: nested
47//!   percent-encoding (`%2530%2531...`), HTML character references, base64
48//!   separated by vertical tab, form feed or punctuation (`MDEy.MzQ1...`),
49//!   Markdown escapes, and a key split across markup.
50//!
51//! This is accepted: that server already holds the key, and catching these in
52//! a stream would need a holdback with no bound, since such a spelling has no
53//! length limit.
54
55mod audit;
56mod diagnostics;
57mod limits;
58mod peer;
59mod request;
60mod response;
61mod websocket;
62
63use std::collections::BTreeSet;
64use std::net::{Ipv4Addr, SocketAddr};
65use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
66use std::sync::Arc;
67use std::thread::JoinHandle;
68use std::time::Duration;
69
70use base64::Engine;
71use bytes::Bytes;
72use http_body_util::{BodyExt, Full};
73use hyper::body::Incoming;
74use hyper::service::service_fn;
75use hyper::{Method, Request, Response, StatusCode};
76use hyper_util::rt::{TokioExecutor, TokioIo};
77use parking_lot::Mutex;
78use rcgen::{BasicConstraints, CertificateParams, IsCa, KeyPair};
79use secret_rules::scrub::{MatcherSet, Scrubber};
80use secret_rules::target::ConnectAuthority;
81use tokio::net::{TcpListener, TcpStream};
82use tokio::sync::watch;
83use zeroize::Zeroizing;
84
85use crate::secret::vault::SecretVault;
86use crate::secret::SecretScope;
87
88pub(crate) type Body = http_body_util::combinators::UnsyncBoxBody<Bytes, std::io::Error>;
89
90/// Constant agent-visible wording; labels and hosts are appended as data.
91pub const PROXY_REFUSAL: &str = "Secret proxy refused the request";
92
93pub struct ProxyConfig {
94    pub vault: Arc<dyn SecretVault>,
95    pub authorization_scope: SecretScope,
96    pub lifetime_scope: SecretScope,
97    pub scanned_labels: Vec<String>,
98    pub consent_context: Option<(std::path::PathBuf, String)>,
99    #[cfg(any(test, feature = "test-support"))]
100    pub test_https_port: Option<u16>,
101    #[cfg(any(test, feature = "test-support"))]
102    pub approval_clock: Option<Arc<dyn crate::secret::requests::ApprovalClock>>,
103    pub origin: String,
104}
105
106impl ProxyConfig {
107    // Cargo feature unification can change test-only fields; keep the constructor signature fixed.
108    pub fn new(
109        vault: Arc<dyn SecretVault>,
110        authorization_scope: SecretScope,
111        lifetime_scope: SecretScope,
112        scanned_labels: Vec<String>,
113        consent_context: Option<(std::path::PathBuf, String)>,
114        test_https_port: Option<u16>,
115        origin: String,
116    ) -> Self {
117        #[cfg(not(any(test, feature = "test-support")))]
118        let _ = test_https_port;
119        Self {
120            vault,
121            authorization_scope,
122            lifetime_scope,
123            scanned_labels,
124            consent_context,
125            #[cfg(any(test, feature = "test-support"))]
126            test_https_port,
127            #[cfg(any(test, feature = "test-support"))]
128            approval_clock: None,
129            origin,
130        }
131    }
132}
133
134/// Errors contain no transport diagnostics, URLs, credentials or vault text.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum ProxyError {
137    UnsupportedPlatform,
138    InvalidRules,
139    Initialization,
140    InvalidSession,
141    Stopped,
142}
143
144#[rustfmt::skip]
145test_support_visibility! {
146
147/// This protection is process-wide and intentionally irreversible. Resolution
148/// adapters can transiently receive material, so every proxy owner must prevent
149/// core dumps before starting a secret runtime.
150pub(crate) fn protect_secret_process() -> Result<(), ProxyError> {
151    // Test builds harden for real only inside the isolated child processes the
152    // audit tests spawn. In a shared test process the change would outlive the
153    // test that made it: on Linux a non-dumpable process can no longer read its
154    // own /proc/self/io, which breaks unrelated tests that run afterwards.
155    #[cfg(any(test, feature = "test-support"))]
156    {
157        test_hardening::mark();
158        if std::env::var_os(test_hardening::REAL_ENV).is_none() {
159            return Ok(());
160        }
161    }
162    #[cfg(unix)]
163    {
164        let limit = libc::rlimit {
165            rlim_cur: 0,
166            rlim_max: 0,
167        };
168        if unsafe { libc::setrlimit(libc::RLIMIT_CORE, &limit) } != 0 {
169            return Err(ProxyError::Initialization);
170        }
171        #[cfg(target_os = "linux")]
172        if unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) } != 0 {
173            return Err(ProxyError::Initialization);
174        }
175    }
176    Ok(())
177}
178}
179
180pub(crate) struct State {
181    approvals: crate::secret::requests::RequestSecrets,
182    config: ProxyConfig,
183    session: AtomicI32,
184    session_birth: std::sync::atomic::AtomicU64,
185    stopped: Arc<AtomicBool>,
186    token: Zeroizing<String>,
187    expected_auth: Zeroizing<Vec<u8>>,
188    ca: rcgen::Certificate,
189    ca_key: KeyPair,
190    upstream: rustls::ClientConfig,
191    material_gate: Mutex<()>,
192    connections: Arc<tokio::sync::Semaphore>,
193    requests: Arc<tokio::sync::Semaphore>,
194    // Keep each installed key as an exact-byte matcher for response scrubbers.
195    // Rotation adds a matcher instead of replacing earlier key values.
196    // Retain these zeroizing patterns until the command ends solely to scrub
197    // echoed keys; they never authorize or supply another upstream request.
198    patterns: Mutex<Vec<(String, Zeroizing<Vec<u8>>)>>,
199    #[cfg(any(test, feature = "test-support"))]
200    headers_sensitive: AtomicBool,
201    #[cfg(any(test, feature = "test-support"))]
202    test_identity_generation: std::sync::atomic::AtomicU64,
203    #[cfg(any(test, feature = "test-support"))]
204    test_idle_timeout_ms: std::sync::atomic::AtomicU64,
205    #[cfg(any(test, feature = "test-support"))]
206    test_upstream: Mutex<std::collections::HashMap<String, SocketAddr>>,
207    #[cfg(any(test, feature = "test-support"))]
208    test_refusals: Mutex<Vec<String>>,
209}
210
211impl State {
212    fn is_https_port(&self, port: u16) -> bool {
213        #[cfg(any(test, feature = "test-support"))]
214        if self.config.test_https_port == Some(port) {
215            return true;
216        }
217        port == 443
218    }
219    fn idle_timeout(&self) -> Duration {
220        #[cfg(any(test, feature = "test-support"))]
221        {
222            let ms = self.test_idle_timeout_ms.load(Ordering::Acquire);
223            if ms != 0 {
224                return Duration::from_millis(ms);
225            }
226        }
227        limits::IDLE
228    }
229    fn generation_valid(&self) -> bool {
230        let pid = self.session.load(Ordering::Acquire);
231        if pid <= 0 {
232            return false;
233        }
234        let current = peer::process_start_time(pid);
235        #[cfg(any(test, feature = "test-support"))]
236        let current = {
237            let changed = self.test_identity_generation.load(Ordering::Acquire);
238            if changed != 0 {
239                Some(changed)
240            } else {
241                current
242            }
243        };
244        current.is_some_and(|birth| birth == self.session_birth.load(Ordering::Acquire))
245    }
246
247    fn mark_stopped(&self) {
248        // Latch cancellation before waiting for a synchronous vault callback.
249        // Its return must not authorize dispatch just because stop is waiting.
250        self.stopped.store(true, Ordering::Release);
251        let _gate = self.material_gate.lock();
252    }
253
254    fn scrubber(&self) -> Result<Scrubber, ()> {
255        let patterns = self.patterns.lock();
256        let sets = patterns
257            .iter()
258            .map(|(label, key)| MatcherSet::new(label, key).map_err(|_| ()))
259            .collect::<Result<Vec<_>, _>>()?;
260        Scrubber::new(sets).map_err(|_| ())
261    }
262
263    fn refresh(&self, scrubber: &mut Scrubber) -> Result<(), ()> {
264        let patterns = self.patterns.lock();
265        for (label, key) in &patterns[scrubber.matcher_count()..] {
266            scrubber
267                .install(MatcherSet::new(label, key).map_err(|_| ())?)
268                .map_err(|_| ())?;
269        }
270        Ok(())
271    }
272
273    fn install(&self, label: &str, key: &[u8]) -> Result<(), ()> {
274        if key.len() > limits::MATERIAL_BYTES {
275            return Err(());
276        }
277        let mut patterns = self.patterns.lock();
278        if self.stopped.load(Ordering::Acquire) {
279            return Err(());
280        }
281        if patterns
282            .iter()
283            .any(|(l, k)| l == label && k.as_slice() == key)
284        {
285            return Ok(());
286        }
287        if patterns.len() >= limits::MATCHERS {
288            return Err(());
289        }
290        let mut sets = patterns
291            .iter()
292            .map(|(l, k)| MatcherSet::new(l, k).map_err(|_| ()))
293            .collect::<Result<Vec<_>, _>>()?;
294        sets.push(MatcherSet::new(label, key).map_err(|_| ())?);
295        Scrubber::new(sets).map_err(|_| ())?;
296        patterns.push((label.to_owned(), Zeroizing::new(key.to_vec())));
297        Ok(())
298    }
299
300    fn scrub(&self, bytes: &[u8]) -> Result<Vec<u8>, ()> {
301        let mut scrubber = self.scrubber()?;
302        let mut out = scrubber.push(bytes);
303        out.extend(scrubber.finish());
304        Ok(out)
305    }
306
307    fn tls_for(&self, host: &str) -> Result<rustls::ServerConfig, ()> {
308        let host = network_host(host);
309        let key = KeyPair::generate().map_err(|_| ())?;
310        // Distinct issuer/leaf names and an issuing-key identifier keep clients
311        // from treating the leaf as self-issued or choosing another bundle CA.
312        let mut params = CertificateParams::new(vec![host.to_owned()]).map_err(|_| ())?;
313        params.distinguished_name = rcgen::DistinguishedName::new();
314        params
315            .distinguished_name
316            .push(rcgen::DnType::CommonName, host);
317        params.use_authority_key_identifier_extension = true;
318        let cert = params
319            .signed_by(&key, &self.ca, &self.ca_key)
320            .map_err(|_| ())?;
321        let der = Zeroizing::new(key.serialize_der());
322        let private_key = rustls::pki_types::PrivatePkcs8KeyDer::from(der.to_vec()).into();
323        let mut config = rustls::ServerConfig::builder()
324            .with_no_client_auth()
325            .with_single_cert(vec![cert.der().clone()], private_key)
326            .map_err(|_| ())?;
327        config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
328        Ok(config)
329    }
330}
331
332/// Dropping or stopping the handle closes the listener and all connections.
333/// Keep it in the background job, not in the launching tool call's stack frame.
334pub struct SecretProxy {
335    address: SocketAddr,
336    ca_pem: String,
337    state: Arc<State>,
338    stop: watch::Sender<bool>,
339    thread: Option<JoinHandle<()>>,
340}
341
342impl SecretProxy {
343    #[cfg(all(any(test, feature = "test-support"), unix))]
344    pub fn start_for_test(
345        config: ProxyConfig,
346        upstream: rustls::ClientConfig,
347    ) -> Result<Self, ProxyError> {
348        Self::start_with_tls(config, upstream)
349    }
350
351    pub fn start(config: ProxyConfig) -> Result<Self, ProxyError> {
352        protect_secret_process()?;
353        let upstream =
354            crate::platform_tls::client_config().map_err(|_| ProxyError::Initialization)?;
355        Self::start_with_tls(config, upstream)
356    }
357
358    #[rustfmt::skip]
359    test_support_visibility! {
360
361    fn start_with_tls(
362        config: ProxyConfig,
363        upstream: rustls::ClientConfig,
364    ) -> Result<Self, ProxyError> {
365        protect_secret_process()?;
366        if !cfg!(any(target_os = "linux", target_os = "macos")) {
367            return Err(ProxyError::UnsupportedPlatform);
368        }
369        let scanned: BTreeSet<_> = config.scanned_labels.iter().collect();
370        if scanned.is_empty()
371            || scanned.len() != config.scanned_labels.len()
372            || scanned
373                .iter()
374                .any(|label| !secret_rules::placeholder::is_label(label))
375        {
376            return Err(ProxyError::InvalidRules);
377        }
378        let _ = rustls::crypto::ring::default_provider().install_default();
379        let mut params =
380            CertificateParams::new(Vec::new()).map_err(|_| ProxyError::Initialization)?;
381        params.distinguished_name = rcgen::DistinguishedName::new();
382        params
383            .distinguished_name
384            .push(rcgen::DnType::CommonName, "AFT per-command secret proxy CA");
385        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
386        params.key_usages = vec![
387            rcgen::KeyUsagePurpose::KeyCertSign,
388            rcgen::KeyUsagePurpose::DigitalSignature,
389        ];
390        let ca_key = KeyPair::generate().map_err(|_| ProxyError::Initialization)?;
391        let ca = params
392            .self_signed(&ca_key)
393            .map_err(|_| ProxyError::Initialization)?;
394        let ca_pem = ca.pem();
395        let mut random = Zeroizing::new([0u8; 32]);
396        getrandom::fill(&mut random[..]).map_err(|_| ProxyError::Initialization)?;
397        let token =
398            Zeroizing::new(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&random[..]));
399        let expected_auth = basic_credentials(&token)?;
400        let stopped = Arc::new(AtomicBool::new(false));
401        let cancelled = stopped.clone();
402        let approvals = crate::secret::requests::RequestSecrets::new(
403            config.vault.clone(),
404            config.authorization_scope.clone(),
405            config.consent_context.clone(),
406        )
407        .with_request_cancellation(move || cancelled.load(Ordering::Acquire));
408        #[cfg(any(test, feature = "test-support"))]
409        let approvals = approvals.with_clock(config.approval_clock.clone());
410        let state = Arc::new(State {
411            approvals,
412            config,
413            session: AtomicI32::new(0),
414            session_birth: std::sync::atomic::AtomicU64::new(0),
415            stopped,
416            token,
417            expected_auth,
418            ca,
419            ca_key,
420            upstream,
421            material_gate: Mutex::new(()),
422            connections: Arc::new(tokio::sync::Semaphore::new(limits::CONNECTIONS)),
423            requests: Arc::new(tokio::sync::Semaphore::new(limits::REQUESTS)),
424            patterns: Mutex::new(Vec::new()),
425            #[cfg(any(test, feature = "test-support"))]
426            headers_sensitive: AtomicBool::new(false),
427            #[cfg(any(test, feature = "test-support"))]
428            test_identity_generation: std::sync::atomic::AtomicU64::new(0),
429            #[cfg(any(test, feature = "test-support"))]
430            test_idle_timeout_ms: std::sync::atomic::AtomicU64::new(0),
431            #[cfg(any(test, feature = "test-support"))]
432            test_upstream: Mutex::default(),
433            #[cfg(any(test, feature = "test-support"))]
434            test_refusals: Mutex::default(),
435        });
436        let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
437            .map_err(|_| ProxyError::Initialization)?;
438        listener
439            .set_nonblocking(true)
440            .map_err(|_| ProxyError::Initialization)?;
441        let address = listener
442            .local_addr()
443            .map_err(|_| ProxyError::Initialization)?;
444        let runtime = tokio::runtime::Builder::new_multi_thread()
445            .worker_threads(2)
446            .enable_all()
447            .build()
448            .map_err(|_| ProxyError::Initialization)?;
449        let (stop, receiver) = watch::channel(false);
450        let shared = state.clone();
451        let thread = std::thread::Builder::new()
452            .name("secret-proxy".into())
453            .spawn(move || {
454                runtime.block_on(serve(listener, shared.clone(), receiver));
455                shared.mark_stopped();
456                runtime.shutdown_timeout(Duration::from_secs(1));
457                shared.patterns.lock().clear();
458            })
459            .map_err(|_| ProxyError::Initialization)?;
460        Ok(Self {
461            address,
462            ca_pem,
463            state,
464            stop,
465            thread: Some(thread),
466        })
467    }
468    }
469
470    pub fn address(&self) -> SocketAddr {
471        self.address
472    }
473
474    #[cfg(unix)]
475    pub fn approval_status(&self) -> Vec<String> {
476        self.state
477            .approvals
478            .status()
479            .into_iter()
480            .filter_map(|line| {
481                self.state
482                    .scrub(line.as_bytes())
483                    .ok()
484                    .and_then(|bytes| String::from_utf8(bytes).ok())
485            })
486            .collect()
487    }
488
489    /// Exec-time only: never persist the returned credential with a task request.
490    pub fn proxy_url(&self) -> Zeroizing<String> {
491        let address = self.address.to_string();
492        let mut url = Zeroizing::new(String::with_capacity(
493            9 + self.state.token.len() + address.len(),
494        ));
495        url.push_str("http://");
496        url.push_str(&self.state.token);
497        url.push_str(":@");
498        url.push_str(&address);
499        url
500    }
501
502    /// Public CA certificate only; the signer stays in daemon memory.
503    pub fn ca_pem(&self) -> &str {
504        &self.ca_pem
505    }
506
507    /// Arm only a newly created session leader, while the child is held at its
508    /// exec barrier. Connections handled while no session is armed are refused.
509    pub fn arm_command(&self, pid: u32) -> Result<(), ProxyError> {
510        let pid = i32::try_from(pid).map_err(|_| ProxyError::InvalidSession)?;
511        let _gate = self.state.material_gate.lock();
512        if self.state.stopped.load(Ordering::Acquire) {
513            return Err(ProxyError::Stopped);
514        }
515        if !peer::is_session_leader(pid) || self.state.session.load(Ordering::Acquire) != 0 {
516            return Err(ProxyError::InvalidSession);
517        }
518        let birth = peer::process_start_time(pid).ok_or(ProxyError::InvalidSession)?;
519        self.state.session_birth.store(birth, Ordering::Release);
520        self.state.session.store(pid, Ordering::Release);
521        Ok(())
522    }
523
524    pub fn stop_if_scope_ended(&mut self, scope: &SecretScope) {
525        if &self.state.config.lifetime_scope == scope {
526            self.stop();
527        }
528    }
529
530    /// The job's process-tree owner calls this even if a descendant escaped its
531    /// original session; session disappearance is also watched defensively.
532    pub fn process_tree_ended(&mut self) {
533        self.stop();
534    }
535
536    pub fn stop(&mut self) {
537        self.state.mark_stopped();
538        let _ = self.stop.send(true);
539        if let Some(thread) = self.thread.take() {
540            let _ = thread.join();
541        }
542        self.state.patterns.lock().clear();
543    }
544}
545
546impl Drop for SecretProxy {
547    fn drop(&mut self) {
548        self.stop();
549    }
550}
551
552async fn serve(
553    listener: std::net::TcpListener,
554    state: Arc<State>,
555    mut stop: watch::Receiver<bool>,
556) {
557    let Ok(listener) = TcpListener::from_std(listener) else {
558        return;
559    };
560    let mut connections = tokio::task::JoinSet::new();
561    let mut monitor = tokio::time::interval(Duration::from_millis(100));
562    loop {
563        tokio::select! {
564            biased;
565            _ = stop.changed() => break,
566            _ = monitor.tick() => {
567                let session = state.session.load(Ordering::Acquire);
568                if session > 0 && (!state.generation_valid() || !peer::session_alive(session)) { break; }
569            }
570            accepted = listener.accept() => {
571                let Ok((socket, _)) = accepted else { break; };
572                let Ok(lease) = state.connections.clone().try_acquire_owned() else { continue; };
573                let lease = Arc::new(lease);
574                let state = state.clone();
575                connections.spawn(async move {
576                    let session = state.session.load(Ordering::Acquire);
577                    if session <= 0 || !state.generation_valid() || !peer::authorized(&socket, session) || !state.generation_valid() { return; }
578                    let refused_upload = Arc::new(AtomicBool::new(false));
579                    let socket = limits::IdleIo::new(socket, state.idle_timeout())
580                        .with_approval_waits(state.approvals.activity())
581                        .with_refused_upload_drain(refused_upload.clone());
582                    let service = service_fn(move |request| {
583                        connect(request, state.clone(), lease.clone(), refused_upload.clone())
584                    });
585                    let _ = hyper::server::conn::http1::Builder::new()
586                        .serve_connection(TokioIo::new(socket), service).with_upgrades().await;
587                });
588            }
589            Some(_) = connections.join_next(), if !connections.is_empty() => {}
590        }
591    }
592    state.mark_stopped();
593    connections.abort_all();
594    while connections.join_next().await.is_some() {}
595}
596
597async fn connect(
598    mut request: Request<Incoming>,
599    state: Arc<State>,
600    lease: Arc<tokio::sync::OwnedSemaphorePermit>,
601    refused_upload: Arc<AtomicBool>,
602) -> Result<Response<Body>, std::convert::Infallible> {
603    use diagnostics::Reason;
604    let host = request
605        .uri()
606        .authority()
607        .and_then(|value| ConnectAuthority::parse(value.as_str()).ok())
608        .map(|authority| authority.host)
609        .unwrap_or_default();
610    let refused = |reason| {
611        diagnostics::log_refusal(
612            &state,
613            reason,
614            state
615                .config
616                .scanned_labels
617                .first()
618                .map_or("", String::as_str),
619            &host,
620        );
621        refusal(Bytes::from(diagnostics::refusal_line(reason, "", "")))
622    };
623    if request.method() != Method::CONNECT {
624        return Ok(refused(Reason::ConnectMethod));
625    }
626    if state.stopped.load(Ordering::Acquire) {
627        return Ok(refused(Reason::Stopped));
628    }
629    let mut credentials = request.headers().get_all("proxy-authorization").iter();
630    if credentials.next().map(|v| v.as_bytes()) != Some(state.expected_auth.as_slice())
631        || credentials.next().is_some()
632    {
633        return Ok(refused(Reason::ProxyAuth));
634    }
635    let Some(authority) = request.uri().authority() else {
636        return Ok(refused(Reason::ConnectAuthority));
637    };
638    let Ok(authority) = ConnectAuthority::parse(authority.as_str()) else {
639        return Ok(refused(Reason::ConnectAuthority));
640    };
641    if request.headers().get_all("host").iter().any(|h| {
642        h.to_str().ok().is_none_or(|h| {
643            secret_rules::target::authority_matches_connect(&authority, Some(h), None, "/").is_err()
644        })
645    }) {
646        return Ok(refused(Reason::HostMismatch));
647    }
648    let intercepted = state.is_https_port(authority.port);
649    let tls = if intercepted {
650        match state.tls_for(&authority.host) {
651            Ok(tls) => Some(tls),
652            Err(()) => return Ok(refused(Reason::TlsConfiguration)),
653        }
654    } else {
655        None
656    };
657    let upstream = if intercepted {
658        None
659    } else {
660        match tokio::time::timeout(
661            state.idle_timeout(),
662            TcpStream::connect((network_host(&authority.host), authority.port)),
663        )
664        .await
665        {
666            Ok(Ok(socket)) => Some(limits::IdleIo::new(socket, state.idle_timeout())),
667            Ok(Err(_)) => return Ok(refused(Reason::UpstreamConnect)),
668            Err(_) => return Ok(refused(Reason::UpstreamConnectTimeout)),
669        }
670    };
671    tokio::spawn(async move {
672        let _lease = lease;
673        let Ok(upgraded) = hyper::upgrade::on(&mut request).await else {
674            return;
675        };
676        let mut io = TokioIo::new(upgraded);
677        if let Some(mut upstream) = upstream {
678            let _ = tokio::io::copy_bidirectional(&mut io, &mut upstream).await;
679        } else if let Some(tls) = tls {
680            let Ok(tls) = tokio_rustls::TlsAcceptor::from(Arc::new(tls))
681                .accept(io)
682                .await
683            else {
684                return;
685            };
686            let service = service_fn(move |request| {
687                request::forward(
688                    request,
689                    authority.clone(),
690                    state.clone(),
691                    refused_upload.clone(),
692                )
693            });
694            let _ = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
695                .serve_connection_with_upgrades(TokioIo::new(tls), service)
696                .await;
697        }
698    });
699    Ok(Response::new(full(Bytes::new())))
700}
701
702fn basic_credentials(token: &str) -> Result<Zeroizing<Vec<u8>>, ProxyError> {
703    let mut userinfo = Zeroizing::new(Vec::with_capacity(token.len() + 1));
704    userinfo.extend_from_slice(token.as_bytes());
705    userinfo.push(b':');
706    let encoded = base64::encoded_len(userinfo.len(), true).ok_or(ProxyError::Initialization)?;
707    let mut header = Zeroizing::new(vec![0u8; 6 + encoded]);
708    header[..6].copy_from_slice(b"Basic ");
709    base64::engine::general_purpose::STANDARD
710        .encode_slice(&userinfo[..], &mut header[6..])
711        .map_err(|_| ProxyError::Initialization)?;
712    Ok(header)
713}
714
715pub(crate) fn full(bytes: Bytes) -> Body {
716    Full::new(bytes)
717        .map_err(|never| match never {})
718        .boxed_unsync()
719}
720
721struct SecretBytes(Zeroizing<Vec<u8>>);
722
723impl AsRef<[u8]> for SecretBytes {
724    fn as_ref(&self) -> &[u8] {
725        &self.0
726    }
727}
728
729pub(crate) fn secret_bytes(bytes: Zeroizing<Vec<u8>>) -> Bytes {
730    Bytes::from_owner(SecretBytes(bytes))
731}
732
733// Brackets belong to an HTTP authority, not an IP SAN, socket lookup or TLS name.
734pub(super) fn network_host(host: &str) -> &str {
735    host.strip_prefix('[')
736        .and_then(|h| h.strip_suffix(']'))
737        .unwrap_or(host)
738}
739
740fn refusal(bytes: Bytes) -> Response<Body> {
741    let mut response = Response::new(full(bytes));
742    *response.status_mut() = StatusCode::FORBIDDEN;
743    response.headers_mut().insert(
744        "content-type",
745        hyper::header::HeaderValue::from_static("text/plain; charset=utf-8"),
746    );
747    response
748}
749
750/// Test-build record of `protect_secret_process` calls, so fakes can check that
751/// hardening ran before resolution without hardening the shared test process.
752#[cfg(any(test, feature = "test-support"))]
753pub mod test_hardening {
754    use std::cell::Cell;
755
756    /// Set by the audit tests' isolated child processes; only there does
757    /// `protect_secret_process` change the real process limits.
758    pub const REAL_ENV: &str = "AFT_S4_AUDIT_CHILD";
759
760    thread_local! {
761        static HARDENED: Cell<bool> = const { Cell::new(false) };
762    }
763
764    pub fn mark() {
765        HARDENED.with(|hardened| hardened.set(true));
766    }
767
768    /// Whether `protect_secret_process` ran on this thread. Each test runs on
769    /// its own thread, so one test's call never satisfies another's check.
770    #[cfg_attr(not(unix), allow(dead_code))]
771    pub fn hardened_on_this_thread() -> bool {
772        HARDENED.with(Cell::get)
773    }
774}
775
776#[cfg(all(any(test, feature = "test-support"), unix))]
777#[cfg_attr(not(test), allow(dead_code, unused_imports))]
778pub mod tests;