Skip to main content

hns_loopback_proxy/
lib.rs

1//! Authenticated exact-origin loopback proxy admission.
2//!
3//! This crate owns the platform-neutral boundary in front of a native browser
4//! proxy. It admits only strict loopback `CONNECT` requests carrying one
5//! per-instance Basic capability, then requires a non-forgeable
6//! current-generation browser-bridge authorization from `hns-dane-engine`
7//! before an exact-host tunnel grant can be issued. Socket accept loops, local
8//! CA storage, and TLS I/O remain native-host adapter responsibilities.
9
10#![forbid(unsafe_code)]
11#![allow(
12    clippy::doc_markdown,
13    clippy::missing_errors_doc,
14    clippy::module_name_repetitions,
15    reason = "HNS, HTTP, TLS, and SNI are protocol names"
16)]
17
18use std::collections::HashMap;
19use std::fmt;
20use std::net::{IpAddr, SocketAddr};
21use std::sync::atomic::{AtomicU64, Ordering};
22
23use hns_dane_engine::{
24    AuthorityState, BrowserBridgeAuthorization, Engine, EngineError, EngineSnapshot,
25};
26use subtle::ConstantTimeEq;
27use thiserror::Error;
28
29static NEXT_PROXY_INSTANCE_ID: AtomicU64 = AtomicU64::new(1);
30
31const PROXY_USERNAME: &str = "hns-browser";
32const CAPABILITY_BYTES: usize = 32;
33const REALM_NONCE_BYTES: usize = 16;
34const DEFAULT_ORIGIN_PORT: u16 = 443;
35/// HTTP proxy authorization header.
36pub const PROXY_AUTHORIZATION_HEADER: &str = "proxy-authorization";
37/// HTTP proxy authentication challenge header.
38pub const PROXY_AUTHENTICATE_HEADER: &str = "Proxy-Authenticate";
39/// Default maximum CONNECT head bytes.
40pub const DEFAULT_MAXIMUM_HEAD_BYTES: usize = 16_384;
41/// Default maximum header fields.
42pub const DEFAULT_MAXIMUM_HEADERS: usize = 64;
43/// Default maximum simultaneous pending CONNECT admissions.
44pub const DEFAULT_MAXIMUM_PENDING: usize = 64;
45
46/// Per-instance loopback proxy capability.
47pub struct ProxyAuthorization {
48    realm: String,
49    expected_token: Vec<u8>,
50}
51
52impl ProxyAuthorization {
53    /// Derive fixed-size Basic credentials from platform-generated random
54    /// nonce and capability bytes.
55    #[must_use]
56    pub fn from_capability(
57        realm_nonce: [u8; REALM_NONCE_BYTES],
58        mut capability: [u8; CAPABILITY_BYTES],
59    ) -> Self {
60        let mut credentials = Vec::with_capacity(PROXY_USERNAME.len() + 1 + CAPABILITY_BYTES * 2);
61        credentials.extend_from_slice(PROXY_USERNAME.as_bytes());
62        credentials.push(b':');
63        append_hex(&mut credentials, &capability);
64        let expected_token = encode_base64(&credentials).into_bytes();
65        credentials.fill(0);
66        capability.fill(0);
67        Self {
68            realm: format!("hns-loopback-{}", encode_hex(&realm_nonce)),
69            expected_token,
70        }
71    }
72
73    /// Authentication realm; safe to expose in a 407 challenge.
74    #[must_use]
75    pub fn realm(&self) -> &str {
76        &self.realm
77    }
78
79    /// Complete Basic authorization header value for the browser callback.
80    #[must_use]
81    pub fn authorization_header_value(&self) -> String {
82        let token = std::str::from_utf8(&self.expected_token).unwrap_or_default();
83        format!("Basic {token}")
84    }
85
86    /// Complete challenge header value.
87    #[must_use]
88    pub fn challenge_header_value(&self) -> String {
89        format!("Basic realm=\"{}\"", self.realm)
90    }
91
92    /// Verify exactly one Basic header using a fixed-width constant-time
93    /// capability comparison.
94    #[must_use]
95    pub fn verify_header_values<'a>(&self, values: impl IntoIterator<Item = &'a str>) -> bool {
96        let mut values = values.into_iter();
97        let Some(value) = values.next() else {
98            return false;
99        };
100        if values.next().is_some() {
101            return false;
102        }
103        let Some(token) = basic_token(value) else {
104            return false;
105        };
106        if token.len() != self.expected_token.len() {
107            return false;
108        }
109        token.as_bytes().ct_eq(&self.expected_token).unwrap_u8() == 1
110    }
111
112    /// Match a browser authentication challenge only to the exact configured
113    /// numeric loopback endpoint and realm.
114    #[must_use]
115    pub fn matches_challenge(
116        &self,
117        endpoint: LoopbackEndpoint,
118        host: &str,
119        port: u16,
120        realm: &str,
121    ) -> bool {
122        let candidate = host
123            .strip_prefix('[')
124            .and_then(|value| value.strip_suffix(']'))
125            .unwrap_or(host);
126        candidate == endpoint.address().ip().to_string()
127            && port == endpoint.address().port()
128            && realm == self.realm
129    }
130}
131
132impl Drop for ProxyAuthorization {
133    fn drop(&mut self) {
134        self.expected_token.fill(0);
135    }
136}
137
138impl fmt::Debug for ProxyAuthorization {
139    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
140        formatter
141            .debug_struct("ProxyAuthorization")
142            .field("realm", &"[redacted]")
143            .field("expected_token", &"[redacted]")
144            .finish()
145    }
146}
147
148/// Numeric loopback endpoint; hostnames and wildcard binds are impossible.
149#[derive(Clone, Copy, Debug, Eq, PartialEq)]
150pub struct LoopbackEndpoint(SocketAddr);
151
152impl LoopbackEndpoint {
153    /// Validate a nonzero numeric loopback bind.
154    pub fn new(address: SocketAddr) -> Result<Self, ProxyError> {
155        if !address.ip().is_loopback() {
156            return Err(ProxyError::NonLoopbackEndpoint);
157        }
158        if address.port() == 0 {
159            return Err(ProxyError::ZeroProxyPort);
160        }
161        Ok(Self(address))
162    }
163
164    /// Exact bind address.
165    #[must_use]
166    pub const fn address(self) -> SocketAddr {
167        self.0
168    }
169}
170
171/// Strict lowercase ASCII DNS host.
172#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
173pub struct NormalizedHost(String);
174
175impl NormalizedHost {
176    /// Normalize browser-emitted ASCII/punycode DNS text.
177    pub fn parse(input: &str) -> Result<Self, ProxyError> {
178        if input.is_empty()
179            || input.trim() != input
180            || input.chars().any(|character| {
181                character.is_control()
182                    || character.is_whitespace()
183                    || matches!(
184                        character,
185                        '/' | ':' | '?' | '#' | '@' | '[' | ']' | '\\' | '<' | '>' | '"'
186                    )
187            })
188        {
189            return Err(ProxyError::InvalidHost);
190        }
191        let without_dot = input.strip_suffix('.').unwrap_or(input);
192        if without_dot.is_empty() || without_dot.ends_with('.') {
193            return Err(ProxyError::InvalidHost);
194        }
195        let normalized = without_dot.to_ascii_lowercase();
196        if normalized.len() > 253
197            || !normalized.is_ascii()
198            || normalized.split('.').any(|label| {
199                label.is_empty()
200                    || label.len() > 63
201                    || label.starts_with('-')
202                    || label.ends_with('-')
203                    || !label
204                        .bytes()
205                        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
206            })
207            || normalized.parse::<IpAddr>().is_ok()
208            || looks_like_legacy_ipv4(&normalized)
209        {
210            return Err(ProxyError::InvalidHost);
211        }
212        Ok(Self(normalized))
213    }
214
215    /// Canonical ASCII host.
216    #[must_use]
217    pub fn as_str(&self) -> &str {
218        &self.0
219    }
220}
221
222impl fmt::Debug for NormalizedHost {
223    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
224        formatter.write_str("NormalizedHost([redacted])")
225    }
226}
227
228/// Immutable HNS TLD scope.
229#[derive(Clone, Debug, Eq, PartialEq)]
230pub struct HostScope {
231    root: NormalizedHost,
232}
233
234impl HostScope {
235    /// Construct from a proof-verified single-label HNS TLD.
236    pub fn from_verified_hns_tld(root: &str) -> Result<Self, ProxyError> {
237        let root = NormalizedHost::parse(root)?;
238        if root.as_str().contains('.') {
239            return Err(ProxyError::ScopeMustBeHnsTld);
240        }
241        Ok(Self { root })
242    }
243
244    /// Verify equality or a label-boundary subdomain.
245    pub fn authorize(&self, candidate: &str) -> Result<NormalizedHost, ProxyError> {
246        let candidate = NormalizedHost::parse(candidate)?;
247        if candidate == self.root {
248            return Ok(candidate);
249        }
250        let prefix = candidate
251            .as_str()
252            .strip_suffix(self.root.as_str())
253            .ok_or(ProxyError::HostOutsideScope)?;
254        if !prefix.ends_with('.') {
255            return Err(ProxyError::HostOutsideScope);
256        }
257        Ok(candidate)
258    }
259
260    /// Redacted canonical scope root for equality checks.
261    #[must_use]
262    pub const fn root(&self) -> &NormalizedHost {
263        &self.root
264    }
265}
266
267/// Deterministic proxy resource bounds.
268#[derive(Clone, Copy, Debug, Eq, PartialEq)]
269pub struct ProxyLimits {
270    /// Maximum complete CONNECT head.
271    pub maximum_head_bytes: usize,
272    /// Maximum HTTP fields.
273    pub maximum_headers: usize,
274    /// Maximum pending two-phase admissions.
275    pub maximum_pending: usize,
276}
277
278impl Default for ProxyLimits {
279    fn default() -> Self {
280        Self {
281            maximum_head_bytes: DEFAULT_MAXIMUM_HEAD_BYTES,
282            maximum_headers: DEFAULT_MAXIMUM_HEADERS,
283            maximum_pending: DEFAULT_MAXIMUM_PENDING,
284        }
285    }
286}
287
288impl ProxyLimits {
289    fn validate(self) -> Result<Self, ProxyError> {
290        if self.maximum_head_bytes < 256
291            || self.maximum_head_bytes > 65_536
292            || self.maximum_headers == 0
293            || self.maximum_headers > 256
294            || self.maximum_pending == 0
295            || self.maximum_pending > 1_024
296        {
297            return Err(ProxyError::InvalidLimits);
298        }
299        Ok(self)
300    }
301}
302
303/// One proxy instance configuration.
304pub struct ProxyConfig {
305    endpoint: LoopbackEndpoint,
306    runtime_session: [u8; 16],
307    runtime_generation: u64,
308    scope: HostScope,
309    authorization: ProxyAuthorization,
310    limits: ProxyLimits,
311    origin_port: u16,
312}
313
314impl ProxyConfig {
315    /// Bind a fresh proxy capability to one runtime generation and HNS TLD.
316    pub fn new(
317        endpoint: LoopbackEndpoint,
318        runtime_session: [u8; 16],
319        runtime_generation: u64,
320        scope: HostScope,
321        authorization: ProxyAuthorization,
322        limits: ProxyLimits,
323    ) -> Result<Self, ProxyError> {
324        if runtime_generation == 0 {
325            return Err(ProxyError::ZeroRuntimeGeneration);
326        }
327        Ok(Self {
328            endpoint,
329            runtime_session,
330            runtime_generation,
331            scope,
332            authorization,
333            limits: limits.validate()?,
334            origin_port: DEFAULT_ORIGIN_PORT,
335        })
336    }
337
338    /// Exact numeric loopback endpoint.
339    #[must_use]
340    pub const fn endpoint(&self) -> LoopbackEndpoint {
341        self.endpoint
342    }
343
344    /// Browser callback authorization header.
345    #[must_use]
346    pub fn authorization_header_value(&self) -> String {
347        self.authorization.authorization_header_value()
348    }
349
350    /// Browser challenge realm.
351    #[must_use]
352    pub fn realm(&self) -> &str {
353        self.authorization.realm()
354    }
355}
356
357impl fmt::Debug for ProxyConfig {
358    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
359        formatter
360            .debug_struct("ProxyConfig")
361            .field("endpoint", &self.endpoint)
362            .field("runtime_session", &self.runtime_session)
363            .field("runtime_generation", &self.runtime_generation)
364            .field("scope", &"[redacted]")
365            .field("authorization", &"[redacted]")
366            .field("limits", &self.limits)
367            .field("origin_port", &self.origin_port)
368            .finish()
369    }
370}
371
372#[derive(Clone, Debug, Eq, PartialEq)]
373struct PendingRecord {
374    host: NormalizedHost,
375    port: u16,
376}
377
378/// Opaque authenticated CONNECT awaiting exact-origin DANE authorization.
379#[derive(Clone, Eq, PartialEq)]
380pub struct PendingConnect {
381    instance_id: u64,
382    sequence: u64,
383    host: NormalizedHost,
384    port: u16,
385}
386
387impl PendingConnect {
388    /// Exact normalized target host.
389    #[must_use]
390    pub fn host(&self) -> &str {
391        self.host.as_str()
392    }
393
394    /// Exact target port.
395    #[must_use]
396    pub const fn port(&self) -> u16 {
397        self.port
398    }
399}
400
401impl fmt::Debug for PendingConnect {
402    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
403        formatter
404            .debug_struct("PendingConnect")
405            .field("instance_id", &self.instance_id)
406            .field("sequence", &self.sequence)
407            .field("host", &"[redacted]")
408            .field("port", &self.port)
409            .finish()
410    }
411}
412
413/// Exact-host backend permission issued after engine DANE authorization.
414#[derive(Eq, PartialEq)]
415pub struct TunnelGrant {
416    host: NormalizedHost,
417    port: u16,
418    runtime_session: [u8; 16],
419    runtime_generation: u64,
420    authorization_event: u64,
421    valid_from: u64,
422    valid_until: u64,
423}
424
425impl TunnelGrant {
426    /// Exact normalized leaf/tunnel host.
427    #[must_use]
428    pub fn host(&self) -> &str {
429        self.host.as_str()
430    }
431
432    /// Exact origin port.
433    #[must_use]
434    pub const fn port(&self) -> u16 {
435        self.port
436    }
437
438    /// Current runtime generation.
439    #[must_use]
440    pub const fn runtime_generation(&self) -> u64 {
441        self.runtime_generation
442    }
443
444    /// Runtime session that admitted the grant.
445    #[must_use]
446    pub const fn runtime_session(&self) -> [u8; 16] {
447        self.runtime_session
448    }
449
450    /// Exact engine event that authorized the grant.
451    #[must_use]
452    pub const fn authorization_event(&self) -> u64 {
453        self.authorization_event
454    }
455
456    /// Inclusive beginning of the chain-anchor validity window.
457    #[must_use]
458    pub const fn valid_from(&self) -> u64 {
459        self.valid_from
460    }
461
462    /// Inclusive chain-anchor validity deadline.
463    #[must_use]
464    pub const fn valid_until(&self) -> u64 {
465        self.valid_until
466    }
467}
468
469impl fmt::Debug for TunnelGrant {
470    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
471        formatter
472            .debug_struct("TunnelGrant")
473            .field("host", &"[redacted]")
474            .field("port", &self.port)
475            .field("runtime_session", &self.runtime_session)
476            .field("runtime_generation", &self.runtime_generation)
477            .field("authorization_event", &self.authorization_event)
478            .field("valid_from", &self.valid_from)
479            .field("valid_until", &self.valid_until)
480            .finish()
481    }
482}
483
484/// Platform-neutral authenticated proxy admission state.
485#[derive(Debug)]
486pub struct ProxySession {
487    instance_id: u64,
488    config: ProxyConfig,
489    sequence: u64,
490    pending: HashMap<u64, PendingRecord>,
491}
492
493impl ProxySession {
494    /// Open one non-cloneable proxy session.
495    pub fn new(config: ProxyConfig) -> Result<Self, ProxyError> {
496        let instance_id = NEXT_PROXY_INSTANCE_ID
497            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
498                current.checked_add(1)
499            })
500            .map_err(|_| ProxyError::InstanceSequenceExhausted)?;
501        Ok(Self {
502            instance_id,
503            config,
504            sequence: 0,
505            pending: HashMap::new(),
506        })
507    }
508
509    /// Exact numeric loopback endpoint.
510    #[must_use]
511    pub const fn endpoint(&self) -> LoopbackEndpoint {
512        self.config.endpoint
513    }
514
515    /// Browser callback authorization value.
516    #[must_use]
517    pub fn authorization_header_value(&self) -> String {
518        self.config.authorization_header_value()
519    }
520
521    /// Bounded 407 response for missing/invalid proxy authentication.
522    #[must_use]
523    pub fn authentication_challenge(&self) -> Vec<u8> {
524        format!(
525            "HTTP/1.1 407 Proxy Authentication Required\r\n{}: {}\r\nCache-Control: no-store\r\nConnection: close\r\nContent-Length: 0\r\n\r\n",
526            PROXY_AUTHENTICATE_HEADER,
527            self.config.authorization.challenge_header_value()
528        )
529        .into_bytes()
530    }
531
532    /// Admit one strict authenticated loopback CONNECT before origin TLS.
533    pub fn admit_connect(
534        &mut self,
535        engine: &Engine,
536        client: SocketAddr,
537        request_head: &[u8],
538    ) -> Result<PendingConnect, ProxyError> {
539        let snapshot = engine.snapshot()?;
540        self.ensure_runtime_ready(snapshot, false)?;
541        if !client.ip().is_loopback() {
542            return Err(ProxyError::NonLoopbackClient);
543        }
544        if self.pending.len() >= self.config.limits.maximum_pending {
545            return Err(ProxyError::PendingLimit);
546        }
547        let parsed = parse_connect_head(request_head, self.config.limits)?;
548        if parsed.port != self.config.origin_port {
549            return Err(ProxyError::OriginPortRejected);
550        }
551        let host = self.config.scope.authorize(parsed.host.as_str())?;
552        if !self
553            .config
554            .authorization
555            .verify_header_values(parsed.authorization.iter().filter_map(SecretHeader::as_str))
556        {
557            return Err(ProxyError::AuthenticationFailed);
558        }
559        let sequence = self
560            .sequence
561            .checked_add(1)
562            .ok_or(ProxyError::RequestSequenceExhausted)?;
563        let record = PendingRecord {
564            host: host.clone(),
565            port: parsed.port,
566        };
567        self.pending.insert(sequence, record);
568        self.sequence = sequence;
569        Ok(PendingConnect {
570            instance_id: self.instance_id,
571            sequence,
572            host,
573            port: parsed.port,
574        })
575    }
576
577    /// Convert one pending CONNECT into an exact-host tunnel grant.
578    pub fn authorize_connect(
579        &mut self,
580        engine: &Engine,
581        pending: PendingConnect,
582        authorization: &BrowserBridgeAuthorization,
583        now: u64,
584    ) -> Result<TunnelGrant, ProxyError> {
585        let PendingConnect {
586            instance_id,
587            sequence,
588            host,
589            port,
590        } = pending;
591        if instance_id != self.instance_id {
592            return Err(ProxyError::PendingMismatch);
593        }
594        let record = self
595            .pending
596            .get(&sequence)
597            .ok_or(ProxyError::PendingMismatch)?;
598        if record.host != host || record.port != port {
599            return Err(ProxyError::PendingMismatch);
600        }
601        let record = self
602            .pending
603            .remove(&sequence)
604            .ok_or(ProxyError::PendingMismatch)?;
605        let snapshot = engine.snapshot()?;
606        self.ensure_runtime_ready(snapshot, true)?;
607        if authorization.runtime_session() != snapshot.runtime_session
608            || authorization.runtime_generation() != snapshot.runtime_generation
609            || authorization.policy_generation() != snapshot.policy.generation()
610            || authorization.event_sequence() != snapshot.event_sequence
611            || now < authorization.valid_from()
612            || now > authorization.valid_until()
613            || authorization.origin() != record.host.as_str()
614        {
615            return Err(ProxyError::BridgeAuthorizationMismatch);
616        }
617        Ok(TunnelGrant {
618            host: record.host,
619            port: record.port,
620            runtime_session: snapshot.runtime_session,
621            runtime_generation: snapshot.runtime_generation,
622            authorization_event: authorization.event_sequence(),
623            valid_from: authorization.valid_from(),
624            valid_until: authorization.valid_until(),
625        })
626    }
627
628    /// Cancel one exact pending request.
629    pub fn cancel(&mut self, pending: &PendingConnect) -> Result<(), ProxyError> {
630        if pending.instance_id != self.instance_id {
631            return Err(ProxyError::PendingMismatch);
632        }
633        self.pending
634            .remove(&pending.sequence)
635            .map(|_| ())
636            .ok_or(ProxyError::PendingMismatch)
637    }
638
639    fn ensure_runtime_ready(
640        &self,
641        snapshot: EngineSnapshot,
642        bridge_required: bool,
643    ) -> Result<(), ProxyError> {
644        if snapshot.runtime_session != self.config.runtime_session
645            || snapshot.runtime_generation != self.config.runtime_generation
646        {
647            return Err(ProxyError::StaleRuntime);
648        }
649        let ready = if bridge_required {
650            matches!(
651                snapshot.authority_state,
652                AuthorityState::BrowserBridgeReady | AuthorityState::Active
653            )
654        } else {
655            matches!(
656                snapshot.authority_state,
657                AuthorityState::ResolutionTransportReady
658                    | AuthorityState::DnssecVerified
659                    | AuthorityState::DaneOriginVerified
660                    | AuthorityState::BrowserBridgeReady
661                    | AuthorityState::Active
662            )
663        };
664        if !ready {
665            return Err(ProxyError::AuthorityNotReady);
666        }
667        Ok(())
668    }
669}
670
671struct SecretHeader(Vec<u8>);
672
673impl SecretHeader {
674    fn as_str(&self) -> Option<&str> {
675        std::str::from_utf8(&self.0).ok()
676    }
677}
678
679impl Drop for SecretHeader {
680    fn drop(&mut self) {
681        self.0.fill(0);
682    }
683}
684
685struct ParsedConnect {
686    host: NormalizedHost,
687    port: u16,
688    authorization: Vec<SecretHeader>,
689}
690
691fn parse_connect_head(input: &[u8], limits: ProxyLimits) -> Result<ParsedConnect, ProxyError> {
692    if input.len() > limits.maximum_head_bytes
693        || !input.ends_with(b"\r\n\r\n")
694        || input.windows(2).filter(|pair| *pair == b"\r\n").count() < 2
695    {
696        return Err(ProxyError::MalformedRequest);
697    }
698    let text = std::str::from_utf8(input).map_err(|_| ProxyError::MalformedRequest)?;
699    if input.first() == Some(&b'\n')
700        || input
701            .windows(2)
702            .any(|window| window.get(1) == Some(&b'\n') && window.first() != Some(&b'\r'))
703    {
704        return Err(ProxyError::MalformedRequest);
705    }
706    let mut lines = text
707        .strip_suffix("\r\n\r\n")
708        .ok_or(ProxyError::MalformedRequest)?
709        .split("\r\n");
710    let request_line = lines.next().ok_or(ProxyError::MalformedRequest)?;
711    if request_line.contains('\t') {
712        return Err(ProxyError::MalformedRequest);
713    }
714    let mut parts = request_line.split(' ');
715    let method = parts.next().ok_or(ProxyError::MalformedRequest)?;
716    let target = parts.next().ok_or(ProxyError::MalformedRequest)?;
717    let version = parts.next().ok_or(ProxyError::MalformedRequest)?;
718    if method != "CONNECT" || version != "HTTP/1.1" || parts.next().is_some() || target.is_empty() {
719        return Err(ProxyError::MalformedRequest);
720    }
721    let (host, port) = parse_authority(target)?;
722    let mut host_values = Vec::new();
723    let mut authorization = Vec::new();
724    let mut header_count = 0_usize;
725    for line in lines {
726        header_count = header_count
727            .checked_add(1)
728            .ok_or(ProxyError::MalformedRequest)?;
729        if header_count > limits.maximum_headers || line.is_empty() || line.starts_with([' ', '\t'])
730        {
731            return Err(ProxyError::MalformedRequest);
732        }
733        let (name, raw_value) = line.split_once(':').ok_or(ProxyError::MalformedRequest)?;
734        if name.is_empty()
735            || !name
736                .bytes()
737                .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
738        {
739            return Err(ProxyError::MalformedRequest);
740        }
741        let value = raw_value.trim_matches([' ', '\t']);
742        if value.is_empty()
743            || value
744                .chars()
745                .any(|character| character.is_control() && !matches!(character, '\t'))
746        {
747            return Err(ProxyError::MalformedRequest);
748        }
749        if name.eq_ignore_ascii_case("host") {
750            host_values.push(value.to_owned());
751        } else if name.eq_ignore_ascii_case(PROXY_AUTHORIZATION_HEADER) {
752            authorization.push(SecretHeader(value.as_bytes().to_vec()));
753        } else if name.eq_ignore_ascii_case("content-length")
754            || name.eq_ignore_ascii_case("transfer-encoding")
755            || name.eq_ignore_ascii_case("upgrade")
756            || name.eq_ignore_ascii_case("expect")
757            || ((name.eq_ignore_ascii_case("connection")
758                || name.eq_ignore_ascii_case("proxy-connection"))
759                && value
760                    .split(',')
761                    .any(|token| token.trim().eq_ignore_ascii_case("upgrade")))
762        {
763            return Err(ProxyError::RequestBodyOrUpgrade);
764        }
765    }
766    if host_values.len() != 1 || authorization.len() != 1 {
767        return Err(ProxyError::MalformedRequest);
768    }
769    let (host_header, host_port) =
770        parse_authority(host_values.first().ok_or(ProxyError::MalformedRequest)?)?;
771    if host_header != host || host_port != port {
772        return Err(ProxyError::AuthorityMismatch);
773    }
774    Ok(ParsedConnect {
775        host,
776        port,
777        authorization,
778    })
779}
780
781fn parse_authority(input: &str) -> Result<(NormalizedHost, u16), ProxyError> {
782    let (host, port_text) = input
783        .rsplit_once(':')
784        .ok_or(ProxyError::MalformedAuthority)?;
785    if host.contains(':')
786        || port_text.is_empty()
787        || (port_text.len() > 1 && port_text.starts_with('0'))
788        || !port_text.bytes().all(|byte| byte.is_ascii_digit())
789    {
790        return Err(ProxyError::MalformedAuthority);
791    }
792    let port = port_text
793        .parse::<u16>()
794        .map_err(|_| ProxyError::MalformedAuthority)?;
795    if port == 0 {
796        return Err(ProxyError::MalformedAuthority);
797    }
798    Ok((NormalizedHost::parse(host)?, port))
799}
800
801fn basic_token(value: &str) -> Option<&str> {
802    if value
803        .chars()
804        .any(|character| character.is_control() && !matches!(character, ' ' | '\t'))
805    {
806        return None;
807    }
808    let value = value.trim_matches([' ', '\t']);
809    let separator = value.find([' ', '\t'])?;
810    let (scheme, remainder) = value.split_at(separator);
811    if !scheme.eq_ignore_ascii_case("Basic") {
812        return None;
813    }
814    let token = remainder.trim_start_matches([' ', '\t']);
815    if token.is_empty() || token.chars().any(char::is_whitespace) {
816        return None;
817    }
818    Some(token)
819}
820
821fn encode_hex(input: &[u8]) -> String {
822    let mut output = Vec::with_capacity(input.len() * 2);
823    append_hex(&mut output, input);
824    String::from_utf8(output).unwrap_or_default()
825}
826
827fn append_hex(output: &mut Vec<u8>, input: &[u8]) {
828    const HEX: &[u8; 16] = b"0123456789abcdef";
829    for byte in input {
830        output.push(HEX.get(usize::from(byte >> 4)).copied().unwrap_or(b'0'));
831        output.push(HEX.get(usize::from(byte & 0x0f)).copied().unwrap_or(b'0'));
832    }
833}
834
835fn encode_base64(input: &[u8]) -> String {
836    let mut output = String::with_capacity(input.len().div_ceil(3) * 4);
837    for chunk in input.chunks(3) {
838        let first = u32::from(chunk.first().copied().unwrap_or(0));
839        let second = chunk.get(1).copied().map_or(0, u32::from);
840        let third = chunk.get(2).copied().map_or(0, u32::from);
841        let value = (first << 16) | (second << 8) | third;
842        output.push(base64_character((value >> 18) & 0x3f));
843        output.push(base64_character((value >> 12) & 0x3f));
844        output.push(if chunk.len() > 1 {
845            base64_character((value >> 6) & 0x3f)
846        } else {
847            '='
848        });
849        output.push(if chunk.len() > 2 {
850            base64_character(value & 0x3f)
851        } else {
852            '='
853        });
854    }
855    output
856}
857
858fn base64_character(index: u32) -> char {
859    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
860    let index = usize::try_from(index).unwrap_or(0);
861    char::from(ALPHABET.get(index).copied().unwrap_or(b'A'))
862}
863
864fn looks_like_legacy_ipv4(host: &str) -> bool {
865    let mut count = 0_usize;
866    let numeric = host.split('.').all(|label| {
867        count += 1;
868        if let Some(hex) = label
869            .strip_prefix("0x")
870            .or_else(|| label.strip_prefix("0X"))
871        {
872            return !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit());
873        }
874        if label.len() > 1 && label.starts_with('0') {
875            return label.bytes().all(|byte| matches!(byte, b'0'..=b'7'));
876        }
877        !label.is_empty() && label.bytes().all(|byte| byte.is_ascii_digit())
878    });
879    numeric && (1..=4).contains(&count)
880}
881
882/// Proxy configuration, request, runtime, or bridge failure.
883#[derive(Debug, Error)]
884#[non_exhaustive]
885pub enum ProxyError {
886    /// Engine state could not be read or advanced.
887    #[error("browser engine failure: {0}")]
888    Engine(#[from] EngineError),
889    /// Listener endpoint is not numeric loopback.
890    #[error("proxy endpoint must be numeric loopback")]
891    NonLoopbackEndpoint,
892    /// Port zero cannot be advertised in PAC/native messaging.
893    #[error("proxy endpoint port must be nonzero")]
894    ZeroProxyPort,
895    /// Client did not connect from a loopback address.
896    #[error("proxy client must be loopback")]
897    NonLoopbackClient,
898    /// Runtime generation must begin above zero.
899    #[error("proxy runtime generation must be nonzero")]
900    ZeroRuntimeGeneration,
901    /// Proxy resource bounds are invalid.
902    #[error("invalid proxy limits")]
903    InvalidLimits,
904    /// Host is not strict ASCII/punycode DNS text.
905    #[error("invalid proxy host")]
906    InvalidHost,
907    /// Scope root must be one proof-verified HNS TLD label.
908    #[error("proxy scope root must be one HNS TLD")]
909    ScopeMustBeHnsTld,
910    /// CONNECT target is outside the immutable HNS scope.
911    #[error("proxy target is outside HNS scope")]
912    HostOutsideScope,
913    /// Runtime session/generation was revoked or differs from this proxy.
914    #[error("proxy runtime is stale")]
915    StaleRuntime,
916    /// Engine authority state is not ready for this phase.
917    #[error("proxy authority is not ready")]
918    AuthorityNotReady,
919    /// Request head is malformed, incomplete, oversized, or ambiguous.
920    #[error("malformed CONNECT request")]
921    MalformedRequest,
922    /// CONNECT authority is not canonical host:port.
923    #[error("malformed CONNECT authority")]
924    MalformedAuthority,
925    /// Host header does not exactly match the request target.
926    #[error("CONNECT Host header and target differ")]
927    AuthorityMismatch,
928    /// CONNECT request attempted a body or protocol upgrade.
929    #[error("CONNECT request body or upgrade is prohibited")]
930    RequestBodyOrUpgrade,
931    /// Only the configured secure origin port is admitted.
932    #[error("CONNECT origin port is not permitted")]
933    OriginPortRejected,
934    /// Proxy capability is missing, duplicated, or incorrect.
935    #[error("proxy authentication failed")]
936    AuthenticationFailed,
937    /// Pending request bound is full.
938    #[error("proxy pending request limit reached")]
939    PendingLimit,
940    /// Process-local proxy instance counter cannot advance.
941    #[error("proxy instance sequence exhausted")]
942    InstanceSequenceExhausted,
943    /// Request sequence cannot advance.
944    #[error("proxy request sequence exhausted")]
945    RequestSequenceExhausted,
946    /// Pending token belongs to another proxy, was changed, or was consumed.
947    #[error("proxy pending CONNECT mismatch")]
948    PendingMismatch,
949    /// Engine bridge capability does not authorize this exact current origin.
950    #[error("browser bridge authorization mismatch")]
951    BridgeAuthorizationMismatch,
952}
953
954#[cfg(test)]
955#[allow(
956    clippy::unwrap_used,
957    reason = "tests fail immediately on invalid deterministic proxy fixtures"
958)]
959mod tests {
960    use hns_browser_testkit::{
961        STRICT_HNS_ORIGIN, STRICT_RUNTIME_SESSION, StrictRegtestDaneFixture,
962    };
963    use hns_dane::DaneLimits;
964    use hns_dane_engine::{CompletionContext, EngineConfig, RuntimeSessionId, ValidatedDaneInput};
965    use hns_dns_wire::ParseLimits;
966    use hns_resolution_policy::{Network, PolicySnapshot, ResolutionTransport};
967
968    use super::*;
969
970    fn ready_engine(session: [u8; 16]) -> Engine {
971        let engine = Engine::new(EngineConfig {
972            runtime_session: RuntimeSessionId::new(session).unwrap(),
973            network: Network::Regtest,
974            policy: PolicySnapshot::default(),
975        });
976        for state in [
977            AuthorityState::LocalStateOpened,
978            AuthorityState::HeaderSyncing,
979            AuthorityState::HeaderCurrent,
980            AuthorityState::ProofReady,
981            AuthorityState::ResolutionTransportReady,
982        ] {
983            engine.advance_authority_state(state).unwrap();
984        }
985        engine
986    }
987
988    fn authorization() -> ProxyAuthorization {
989        ProxyAuthorization::from_capability([7; 16], [9; 32])
990    }
991
992    fn session(session_id: [u8; 16], maximum_pending: usize) -> (Engine, ProxySession) {
993        let engine = ready_engine(session_id);
994        let snapshot = engine.snapshot().unwrap();
995        let config = ProxyConfig::new(
996            LoopbackEndpoint::new("127.0.0.1:39000".parse().unwrap()).unwrap(),
997            snapshot.runtime_session,
998            snapshot.runtime_generation,
999            HostScope::from_verified_hns_tld("alpha").unwrap(),
1000            authorization(),
1001            ProxyLimits {
1002                maximum_pending,
1003                ..ProxyLimits::default()
1004            },
1005        )
1006        .unwrap();
1007        (engine, ProxySession::new(config).unwrap())
1008    }
1009
1010    fn connect_request_for(host: &str, authorization: &str) -> Vec<u8> {
1011        format!(
1012            "CONNECT {host}:443 HTTP/1.1\r\nHost: {host}:443\r\nProxy-Authorization: {authorization}\r\nProxy-Connection: keep-alive\r\n\r\n"
1013        )
1014        .into_bytes()
1015    }
1016
1017    fn connect_request(authorization: &str) -> Vec<u8> {
1018        connect_request_for("www.alpha", authorization)
1019    }
1020
1021    #[test]
1022    fn capability_auth_is_exact_constant_time_and_redacted() {
1023        let authorization = authorization();
1024        let valid = authorization.authorization_header_value();
1025        assert!(authorization.verify_header_values([valid.as_str()]));
1026        assert!(authorization.verify_header_values([valid.replacen("Basic", "bAsIc", 1).as_str()]));
1027        assert!(!authorization.verify_header_values(std::iter::empty()));
1028        assert!(!authorization.verify_header_values([valid.as_str(), valid.as_str()]));
1029        assert!(!authorization.verify_header_values(["Basic wrong"]));
1030        assert!(!authorization.verify_header_values(["Bearer wrong"]));
1031        let debug = format!("{authorization:?}");
1032        assert!(!debug.contains(authorization.realm()));
1033        assert!(!debug.contains(valid.split_once(' ').unwrap().1));
1034    }
1035
1036    #[test]
1037    fn endpoint_challenge_and_clients_are_exact_loopback() {
1038        assert!(matches!(
1039            LoopbackEndpoint::new("0.0.0.0:39000".parse().unwrap()),
1040            Err(ProxyError::NonLoopbackEndpoint)
1041        ));
1042        assert!(matches!(
1043            LoopbackEndpoint::new("127.0.0.1:0".parse().unwrap()),
1044            Err(ProxyError::ZeroProxyPort)
1045        ));
1046        let (engine, mut proxy) = session([1; 16], 2);
1047        let endpoint = proxy.endpoint();
1048        assert!(proxy.config.authorization.matches_challenge(
1049            endpoint,
1050            "127.0.0.1",
1051            39000,
1052            proxy.config.realm()
1053        ));
1054        let request = connect_request(&proxy.authorization_header_value());
1055        assert!(matches!(
1056            proxy.admit_connect(&engine, "192.0.2.1:50000".parse().unwrap(), &request),
1057            Err(ProxyError::NonLoopbackClient)
1058        ));
1059    }
1060
1061    #[test]
1062    fn host_scope_is_label_bound_and_rejects_ip_forms() {
1063        let scope = HostScope::from_verified_hns_tld("ALPHA.").unwrap();
1064        assert_eq!(scope.authorize("WWW.Alpha.").unwrap().as_str(), "www.alpha");
1065        assert!(matches!(
1066            scope.authorize("notalpha"),
1067            Err(ProxyError::HostOutsideScope)
1068        ));
1069        for invalid in ["127.0.0.1", "2130706433", "0x7f000001", "[::1]", "bad name"] {
1070            assert!(matches!(
1071                NormalizedHost::parse(invalid),
1072                Err(ProxyError::InvalidHost)
1073            ));
1074        }
1075        assert!(matches!(
1076            HostScope::from_verified_hns_tld("www.alpha"),
1077            Err(ProxyError::ScopeMustBeHnsTld)
1078        ));
1079    }
1080
1081    #[test]
1082    fn admits_only_strict_authenticated_connect() {
1083        let (engine, mut proxy) = session([2; 16], 4);
1084        let authorization = proxy.authorization_header_value();
1085        let valid = connect_request(&authorization);
1086        let pending = proxy
1087            .admit_connect(&engine, "127.0.0.1:50000".parse().unwrap(), &valid)
1088            .unwrap();
1089        assert_eq!(pending.host(), "www.alpha");
1090        assert_eq!(pending.port(), 443);
1091
1092        for invalid in [
1093            b"GET https://www.alpha/ HTTP/1.1\r\nHost: www.alpha\r\n\r\n".to_vec(),
1094            connect_request("Basic wrong"),
1095            format!(
1096                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: other.alpha:443\r\nProxy-Authorization: {authorization}\r\n\r\n"
1097            )
1098            .into_bytes(),
1099            format!(
1100                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: www.alpha:443\r\nProxy-Authorization: {authorization}\r\nProxy-Authorization: {authorization}\r\n\r\n"
1101            )
1102            .into_bytes(),
1103            format!(
1104                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: www.alpha:443\r\nProxy-Authorization: {authorization}\r\nContent-Length: 1\r\n\r\nx"
1105            )
1106            .into_bytes(),
1107            format!(
1108                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: www.alpha:443\r\nProxy-Authorization: {authorization}\r\nExpect: 100-continue\r\n\r\n"
1109            )
1110            .into_bytes(),
1111            format!(
1112                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: www.alpha:443\r\nProxy-Authorization: {authorization}\r\nConnection: keep-alive, Upgrade\r\n\r\n"
1113            )
1114            .into_bytes(),
1115        ] {
1116            assert!(proxy
1117                .admit_connect(
1118                    &engine,
1119                    "127.0.0.1:50000".parse().unwrap(),
1120                    &invalid
1121                )
1122                .is_err());
1123        }
1124    }
1125
1126    #[test]
1127    fn pending_tokens_are_bounded_cancelled_and_instance_scoped() {
1128        let (engine, mut first) = session([3; 16], 1);
1129        let (_, mut second) = session([3; 16], 1);
1130        let request = connect_request(&first.authorization_header_value());
1131        let pending = first
1132            .admit_connect(&engine, "127.0.0.1:50000".parse().unwrap(), &request)
1133            .unwrap();
1134        assert!(matches!(
1135            first.admit_connect(&engine, "127.0.0.1:50001".parse().unwrap(), &request),
1136            Err(ProxyError::PendingLimit)
1137        ));
1138        assert!(matches!(
1139            second.cancel(&pending),
1140            Err(ProxyError::PendingMismatch)
1141        ));
1142        first.cancel(&pending).unwrap();
1143        assert!(matches!(
1144            first.cancel(&pending),
1145            Err(ProxyError::PendingMismatch)
1146        ));
1147    }
1148
1149    #[test]
1150    fn stale_runtime_and_authentication_challenge_fail_closed() {
1151        let (engine, mut proxy) = session([4; 16], 2);
1152        let challenge = String::from_utf8(proxy.authentication_challenge()).unwrap();
1153        assert!(challenge.starts_with("HTTP/1.1 407 Proxy Authentication Required\r\n"));
1154        assert!(challenge.contains(PROXY_AUTHENTICATE_HEADER));
1155        assert!(challenge.contains("Cache-Control: no-store"));
1156
1157        let before = engine.snapshot().unwrap().policy;
1158        let mut next = before.config();
1159        next.authenticated_authoritative_doh = false;
1160        engine.update_policy(before.generation(), next).unwrap();
1161        let request = connect_request(&proxy.authorization_header_value());
1162        assert!(matches!(
1163            proxy.admit_connect(&engine, "127.0.0.1:50000".parse().unwrap(), &request),
1164            Err(ProxyError::StaleRuntime)
1165        ));
1166    }
1167
1168    #[test]
1169    fn strict_regtest_path_mints_only_an_exact_current_tunnel_grant() {
1170        let fixture = StrictRegtestDaneFixture::new().unwrap();
1171        let validation_time = fixture.validation_time();
1172        let (engine, mut proxy) = session(STRICT_RUNTIME_SESSION, 4);
1173        let authorization = proxy.authorization_header_value();
1174        let exact_request = connect_request_for(STRICT_HNS_ORIGIN, &authorization);
1175        let pending = proxy
1176            .admit_connect(&engine, "127.0.0.1:50000".parse().unwrap(), &exact_request)
1177            .unwrap();
1178
1179        let attempt = engine
1180            .admit_resolution(
1181                ResolutionTransport::DirectAuthoritativeTcp,
1182                fixture.query().clone(),
1183            )
1184            .unwrap();
1185        let parsed = engine
1186            .parse_response(&attempt, fixture.response(), ParseLimits::requester())
1187            .unwrap();
1188        let validated = fixture.validate_response(parsed.message()).unwrap();
1189        engine
1190            .advance_authority_state(AuthorityState::DnssecVerified)
1191            .unwrap();
1192        let certificate_chain = [fixture.certificate()];
1193        let completion = engine
1194            .complete_resolution_with_validated_tlsa(
1195                &attempt,
1196                &parsed,
1197                ValidatedDaneInput {
1198                    validated: &validated,
1199                    certificate_chain_der: &certificate_chain,
1200                    origin_sni: STRICT_HNS_ORIGIN,
1201                    validation_unix_time: i64::from(validation_time),
1202                    limits: DaneLimits::default(),
1203                },
1204                CompletionContext::default(),
1205            )
1206            .unwrap();
1207        let bridge = engine
1208            .authorize_browser_bridge(&completion, u64::from(validation_time))
1209            .unwrap();
1210        let grant = proxy
1211            .authorize_connect(&engine, pending, &bridge, u64::from(validation_time))
1212            .unwrap();
1213        assert_eq!(grant.host(), STRICT_HNS_ORIGIN);
1214        assert_eq!(grant.port(), 443);
1215        assert_eq!(
1216            grant.runtime_generation(),
1217            engine.snapshot().unwrap().runtime_generation
1218        );
1219        assert_eq!(grant.runtime_session(), STRICT_RUNTIME_SESSION);
1220        assert_eq!(grant.authorization_event(), bridge.event_sequence());
1221        assert_eq!(grant.valid_from(), bridge.valid_from());
1222        assert_eq!(grant.valid_until(), bridge.valid_until());
1223
1224        let wrong_origin = proxy
1225            .admit_connect(
1226                &engine,
1227                "127.0.0.1:50001".parse().unwrap(),
1228                &connect_request(&authorization),
1229            )
1230            .unwrap();
1231        assert!(matches!(
1232            proxy.authorize_connect(&engine, wrong_origin, &bridge, u64::from(validation_time)),
1233            Err(ProxyError::BridgeAuthorizationMismatch)
1234        ));
1235
1236        let too_early = proxy
1237            .admit_connect(&engine, "127.0.0.1:50002".parse().unwrap(), &exact_request)
1238            .unwrap();
1239        assert!(matches!(
1240            proxy.authorize_connect(
1241                &engine,
1242                too_early,
1243                &bridge,
1244                bridge.valid_from().checked_sub(1).unwrap()
1245            ),
1246            Err(ProxyError::BridgeAuthorizationMismatch)
1247        ));
1248
1249        let expired = proxy
1250            .admit_connect(&engine, "127.0.0.1:50003".parse().unwrap(), &exact_request)
1251            .unwrap();
1252        assert!(matches!(
1253            proxy.authorize_connect(
1254                &engine,
1255                expired,
1256                &bridge,
1257                bridge.valid_until().checked_add(1).unwrap()
1258            ),
1259            Err(ProxyError::BridgeAuthorizationMismatch)
1260        ));
1261
1262        let stale_event = proxy
1263            .admit_connect(&engine, "127.0.0.1:50004".parse().unwrap(), &exact_request)
1264            .unwrap();
1265        let _new_attempt = engine
1266            .admit_resolution(
1267                ResolutionTransport::DirectAuthoritativeTcp,
1268                fixture.query().clone(),
1269            )
1270            .unwrap();
1271        assert!(matches!(
1272            proxy.authorize_connect(&engine, stale_event, &bridge, u64::from(validation_time)),
1273            Err(ProxyError::BridgeAuthorizationMismatch)
1274        ));
1275    }
1276}