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 an atomically published,
6//! current-generation [`hns_dane_engine::ProviderAuthorityContext`] before an
7//! exact-origin tunnel grant can be issued. Socket accept loops, DNS wire I/O,
8//! origin dialing, local CA storage, and TLS I/O remain native-host adapter
9//! responsibilities.
10
11#![forbid(unsafe_code)]
12#![allow(
13    clippy::doc_markdown,
14    clippy::missing_errors_doc,
15    clippy::module_name_repetitions,
16    reason = "HNS, HTTP, TLS, and SNI are protocol names"
17)]
18
19use std::collections::HashMap;
20use std::fmt;
21use std::net::{IpAddr, SocketAddr};
22use std::sync::atomic::{AtomicU64, Ordering};
23
24use hns_dane_engine::{
25    AuthenticatedContextStatus, AuthorityState, Engine, EngineError, EngineSnapshot, HnsNetwork,
26    LogicalOrigin, Namespace, OriginScheme, ProviderAuthorityContext, TlsTrustPolicy,
27};
28use subtle::ConstantTimeEq;
29use thiserror::Error;
30
31static NEXT_PROXY_INSTANCE_ID: AtomicU64 = AtomicU64::new(1);
32
33const PROXY_USERNAME: &str = "hns-browser";
34const CAPABILITY_BYTES: usize = 32;
35const REALM_NONCE_BYTES: usize = 16;
36/// HTTP proxy authorization header.
37pub const PROXY_AUTHORIZATION_HEADER: &str = "proxy-authorization";
38/// HTTP proxy authentication challenge header.
39pub const PROXY_AUTHENTICATE_HEADER: &str = "Proxy-Authenticate";
40/// Default maximum CONNECT head bytes.
41pub const DEFAULT_MAXIMUM_HEAD_BYTES: usize = 16_384;
42/// Default maximum header fields.
43pub const DEFAULT_MAXIMUM_HEADERS: usize = 64;
44/// Default maximum simultaneous pending CONNECT admissions.
45pub const DEFAULT_MAXIMUM_PENDING: usize = 64;
46/// Default lifetime of one pending CONNECT admission, in seconds.
47pub const DEFAULT_MAXIMUM_PENDING_LIFETIME_SECONDS: u64 = 15;
48/// Hard maximum lifetime of one pending CONNECT admission, in seconds.
49pub const MAXIMUM_PENDING_LIFETIME_SECONDS: u64 = 60;
50/// Default maximum simultaneously published provider authorities.
51pub const DEFAULT_MAXIMUM_PUBLICATIONS: usize = 64;
52/// Default maximum lifetime of one in-memory publication, in seconds.
53pub const DEFAULT_MAXIMUM_PUBLICATION_LIFETIME_SECONDS: u64 = 300;
54/// Default maximum lifetime of one issued tunnel grant, in seconds.
55pub const DEFAULT_MAXIMUM_GRANT_LIFETIME_SECONDS: u64 = 30;
56/// Hard maximum lifetime of one issued tunnel grant, in seconds.
57pub const MAXIMUM_GRANT_LIFETIME_SECONDS: u64 = 60;
58
59/// Per-instance loopback proxy capability.
60pub struct ProxyAuthorization {
61    realm: String,
62    expected_token: Vec<u8>,
63}
64
65impl ProxyAuthorization {
66    /// Derive fixed-size Basic credentials from platform-generated random
67    /// nonce and capability bytes.
68    #[must_use]
69    pub fn from_capability(
70        realm_nonce: [u8; REALM_NONCE_BYTES],
71        mut capability: [u8; CAPABILITY_BYTES],
72    ) -> Self {
73        let mut credentials = Vec::with_capacity(PROXY_USERNAME.len() + 1 + CAPABILITY_BYTES * 2);
74        credentials.extend_from_slice(PROXY_USERNAME.as_bytes());
75        credentials.push(b':');
76        append_hex(&mut credentials, &capability);
77        let expected_token = encode_base64(&credentials).into_bytes();
78        credentials.fill(0);
79        capability.fill(0);
80        Self {
81            realm: format!("hns-loopback-{}", encode_hex(&realm_nonce)),
82            expected_token,
83        }
84    }
85
86    /// Authentication realm; safe to expose in a 407 challenge.
87    #[must_use]
88    pub fn realm(&self) -> &str {
89        &self.realm
90    }
91
92    /// Complete Basic authorization header value for the browser callback.
93    #[must_use]
94    pub fn authorization_header_value(&self) -> String {
95        let token = std::str::from_utf8(&self.expected_token).unwrap_or_default();
96        format!("Basic {token}")
97    }
98
99    /// Complete challenge header value.
100    #[must_use]
101    pub fn challenge_header_value(&self) -> String {
102        format!("Basic realm=\"{}\"", self.realm)
103    }
104
105    /// Verify exactly one Basic header using a fixed-width constant-time
106    /// capability comparison.
107    #[must_use]
108    pub fn verify_header_values<'a>(&self, values: impl IntoIterator<Item = &'a str>) -> bool {
109        let mut values = values.into_iter();
110        let Some(value) = values.next() else {
111            return false;
112        };
113        if values.next().is_some() {
114            return false;
115        }
116        let Some(token) = basic_token(value) else {
117            return false;
118        };
119        if token.len() != self.expected_token.len() {
120            return false;
121        }
122        token.as_bytes().ct_eq(&self.expected_token).unwrap_u8() == 1
123    }
124
125    /// Match a browser authentication challenge only to the exact configured
126    /// numeric loopback endpoint and realm.
127    #[must_use]
128    pub fn matches_challenge(
129        &self,
130        endpoint: LoopbackEndpoint,
131        host: &str,
132        port: u16,
133        realm: &str,
134    ) -> bool {
135        let candidate = host
136            .strip_prefix('[')
137            .and_then(|value| value.strip_suffix(']'))
138            .unwrap_or(host);
139        candidate == endpoint.address().ip().to_string()
140            && port == endpoint.address().port()
141            && realm == self.realm
142    }
143}
144
145impl Drop for ProxyAuthorization {
146    fn drop(&mut self) {
147        self.expected_token.fill(0);
148    }
149}
150
151impl fmt::Debug for ProxyAuthorization {
152    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
153        formatter
154            .debug_struct("ProxyAuthorization")
155            .field("realm", &"[redacted]")
156            .field("expected_token", &"[redacted]")
157            .finish()
158    }
159}
160
161/// Numeric loopback endpoint; hostnames and wildcard binds are impossible.
162#[derive(Clone, Copy, Debug, Eq, PartialEq)]
163pub struct LoopbackEndpoint(SocketAddr);
164
165impl LoopbackEndpoint {
166    /// Validate a nonzero numeric loopback bind.
167    pub fn new(address: SocketAddr) -> Result<Self, ProxyError> {
168        if !address.ip().is_loopback() {
169            return Err(ProxyError::NonLoopbackEndpoint);
170        }
171        if address.port() == 0 {
172            return Err(ProxyError::ZeroProxyPort);
173        }
174        Ok(Self(address))
175    }
176
177    /// Exact bind address.
178    #[must_use]
179    pub const fn address(self) -> SocketAddr {
180        self.0
181    }
182}
183
184/// Native-process and listener lifecycle identity for replay isolation.
185///
186/// The native host must generate a fresh unpredictable process session on
187/// every process start and advance both generations for their corresponding
188/// lifecycle replacement. This value is configuration identity, not provider
189/// authority.
190#[derive(Clone, Copy, Eq, PartialEq)]
191pub struct ProxyInstanceIdentity {
192    process_session: [u8; 16],
193    process_generation: u64,
194    listener_generation: u64,
195}
196
197impl ProxyInstanceIdentity {
198    /// Validate nonzero process and listener lifecycle stamps.
199    pub fn new(
200        process_session: [u8; 16],
201        process_generation: u64,
202        listener_generation: u64,
203    ) -> Result<Self, ProxyError> {
204        if process_session == [0; 16] {
205            return Err(ProxyError::ZeroProcessSession);
206        }
207        if process_generation == 0 {
208            return Err(ProxyError::ZeroProcessGeneration);
209        }
210        if listener_generation == 0 {
211            return Err(ProxyError::ZeroListenerGeneration);
212        }
213        Ok(Self {
214            process_session,
215            process_generation,
216            listener_generation,
217        })
218    }
219
220    /// Fresh native-process session stamp.
221    #[must_use]
222    pub const fn process_session(self) -> [u8; 16] {
223        self.process_session
224    }
225
226    /// Native-process lifecycle generation.
227    #[must_use]
228    pub const fn process_generation(self) -> u64 {
229        self.process_generation
230    }
231
232    /// Exact listener lifecycle generation.
233    #[must_use]
234    pub const fn listener_generation(self) -> u64 {
235        self.listener_generation
236    }
237}
238
239impl fmt::Debug for ProxyInstanceIdentity {
240    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
241        formatter
242            .debug_struct("ProxyInstanceIdentity")
243            .field("process_session", &"[redacted]")
244            .field("process_generation", &self.process_generation)
245            .field("listener_generation", &self.listener_generation)
246            .finish()
247    }
248}
249
250/// Strict lowercase ASCII DNS host.
251#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
252pub struct NormalizedHost(String);
253
254impl NormalizedHost {
255    /// Normalize browser-emitted ASCII/punycode DNS text.
256    pub fn parse(input: &str) -> Result<Self, ProxyError> {
257        if input.is_empty()
258            || input.trim() != input
259            || input.chars().any(|character| {
260                character.is_control()
261                    || character.is_whitespace()
262                    || matches!(
263                        character,
264                        '/' | ':' | '?' | '#' | '@' | '[' | ']' | '\\' | '<' | '>' | '"'
265                    )
266            })
267        {
268            return Err(ProxyError::InvalidHost);
269        }
270        let without_dot = input.strip_suffix('.').unwrap_or(input);
271        if without_dot.is_empty() || without_dot.ends_with('.') {
272            return Err(ProxyError::InvalidHost);
273        }
274        let normalized = without_dot.to_ascii_lowercase();
275        if normalized.len() > 253
276            || !normalized.is_ascii()
277            || normalized.split('.').any(|label| {
278                label.is_empty()
279                    || label.len() > 63
280                    || label.starts_with('-')
281                    || label.ends_with('-')
282                    || !label
283                        .bytes()
284                        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
285            })
286            || normalized.parse::<IpAddr>().is_ok()
287            || looks_like_legacy_ipv4(&normalized)
288        {
289            return Err(ProxyError::InvalidHost);
290        }
291        Ok(Self(normalized))
292    }
293
294    /// Canonical ASCII host.
295    #[must_use]
296    pub fn as_str(&self) -> &str {
297        &self.0
298    }
299}
300
301impl fmt::Debug for NormalizedHost {
302    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
303        formatter.write_str("NormalizedHost([redacted])")
304    }
305}
306
307/// Immutable HNS TLD scope.
308#[derive(Clone, Debug, Eq, PartialEq)]
309pub struct HostScope {
310    root: NormalizedHost,
311}
312
313impl HostScope {
314    /// Construct from a proof-verified single-label HNS TLD.
315    pub fn from_verified_hns_tld(root: &str) -> Result<Self, ProxyError> {
316        let root = NormalizedHost::parse(root)?;
317        if root.as_str().contains('.') {
318            return Err(ProxyError::ScopeMustBeHnsTld);
319        }
320        Ok(Self { root })
321    }
322
323    /// Verify equality or a label-boundary subdomain.
324    pub fn authorize(&self, candidate: &str) -> Result<NormalizedHost, ProxyError> {
325        let candidate = NormalizedHost::parse(candidate)?;
326        if candidate == self.root {
327            return Ok(candidate);
328        }
329        let prefix = candidate
330            .as_str()
331            .strip_suffix(self.root.as_str())
332            .ok_or(ProxyError::HostOutsideScope)?;
333        if !prefix.ends_with('.') {
334            return Err(ProxyError::HostOutsideScope);
335        }
336        Ok(candidate)
337    }
338
339    /// Redacted canonical scope root for equality checks.
340    #[must_use]
341    pub const fn root(&self) -> &NormalizedHost {
342        &self.root
343    }
344}
345
346/// Deterministic proxy resource bounds.
347#[derive(Clone, Copy, Debug, Eq, PartialEq)]
348pub struct ProxyLimits {
349    /// Maximum complete CONNECT head.
350    pub maximum_head_bytes: usize,
351    /// Maximum HTTP fields.
352    pub maximum_headers: usize,
353    /// Maximum pending two-phase admissions.
354    pub maximum_pending: usize,
355    /// Maximum lifetime of one pending admission, in seconds.
356    pub maximum_pending_lifetime_seconds: u64,
357    /// Maximum simultaneously published provider authorities.
358    pub maximum_publications: usize,
359    /// Maximum lifetime of one publication, in seconds.
360    pub maximum_publication_lifetime_seconds: u64,
361    /// Maximum lifetime of one tunnel grant, in seconds.
362    pub maximum_grant_lifetime_seconds: u64,
363}
364
365impl Default for ProxyLimits {
366    fn default() -> Self {
367        Self {
368            maximum_head_bytes: DEFAULT_MAXIMUM_HEAD_BYTES,
369            maximum_headers: DEFAULT_MAXIMUM_HEADERS,
370            maximum_pending: DEFAULT_MAXIMUM_PENDING,
371            maximum_pending_lifetime_seconds: DEFAULT_MAXIMUM_PENDING_LIFETIME_SECONDS,
372            maximum_publications: DEFAULT_MAXIMUM_PUBLICATIONS,
373            maximum_publication_lifetime_seconds: DEFAULT_MAXIMUM_PUBLICATION_LIFETIME_SECONDS,
374            maximum_grant_lifetime_seconds: DEFAULT_MAXIMUM_GRANT_LIFETIME_SECONDS,
375        }
376    }
377}
378
379impl ProxyLimits {
380    fn validate(self) -> Result<Self, ProxyError> {
381        if self.maximum_head_bytes < 256
382            || self.maximum_head_bytes > 65_536
383            || self.maximum_headers == 0
384            || self.maximum_headers > 256
385            || self.maximum_pending == 0
386            || self.maximum_pending > 1_024
387            || self.maximum_pending_lifetime_seconds == 0
388            || self.maximum_pending_lifetime_seconds > MAXIMUM_PENDING_LIFETIME_SECONDS
389            || self.maximum_publications == 0
390            || self.maximum_publications > 1_024
391            || self.maximum_publication_lifetime_seconds == 0
392            || self.maximum_publication_lifetime_seconds > 3_600
393            || self.maximum_grant_lifetime_seconds == 0
394            || self.maximum_grant_lifetime_seconds > self.maximum_publication_lifetime_seconds
395            || self.maximum_grant_lifetime_seconds > MAXIMUM_GRANT_LIFETIME_SECONDS
396        {
397            return Err(ProxyError::InvalidLimits);
398        }
399        Ok(self)
400    }
401}
402
403/// One proxy instance configuration.
404pub struct ProxyConfig {
405    endpoint: LoopbackEndpoint,
406    instance_identity: ProxyInstanceIdentity,
407    runtime_session: [u8; 16],
408    runtime_generation: u64,
409    scope: HostScope,
410    authorization: ProxyAuthorization,
411    limits: ProxyLimits,
412}
413
414impl ProxyConfig {
415    /// Bind a fresh process/listener identity and proxy capability to one
416    /// runtime generation, HNS TLD, and bounded lifetime configuration.
417    pub fn new(
418        endpoint: LoopbackEndpoint,
419        instance_identity: ProxyInstanceIdentity,
420        runtime_session: [u8; 16],
421        runtime_generation: u64,
422        scope: HostScope,
423        authorization: ProxyAuthorization,
424        limits: ProxyLimits,
425    ) -> Result<Self, ProxyError> {
426        if runtime_session == [0; 16] {
427            return Err(ProxyError::ZeroRuntimeSession);
428        }
429        if runtime_generation == 0 {
430            return Err(ProxyError::ZeroRuntimeGeneration);
431        }
432        Ok(Self {
433            endpoint,
434            instance_identity,
435            runtime_session,
436            runtime_generation,
437            scope,
438            authorization,
439            limits: limits.validate()?,
440        })
441    }
442
443    /// Exact numeric loopback endpoint.
444    #[must_use]
445    pub const fn endpoint(&self) -> LoopbackEndpoint {
446        self.endpoint
447    }
448
449    /// Browser callback authorization header.
450    #[must_use]
451    pub fn authorization_header_value(&self) -> String {
452        self.authorization.authorization_header_value()
453    }
454
455    /// Browser challenge realm.
456    #[must_use]
457    pub fn realm(&self) -> &str {
458        self.authorization.realm()
459    }
460}
461
462impl fmt::Debug for ProxyConfig {
463    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
464        formatter
465            .debug_struct("ProxyConfig")
466            .field("endpoint", &self.endpoint)
467            .field("instance_identity", &self.instance_identity)
468            .field("runtime_session", &"[redacted]")
469            .field("runtime_generation", &self.runtime_generation)
470            .field("scope", &"[redacted]")
471            .field("authorization", &"[redacted]")
472            .field("limits", &self.limits)
473            .finish()
474    }
475}
476
477#[derive(Debug, Eq, PartialEq)]
478struct PendingRecord {
479    host: NormalizedHost,
480    port: u16,
481    admitted_at: u64,
482    expires_at: u64,
483}
484
485/// Opaque authenticated CONNECT awaiting exact provider-authority admission.
486#[derive(Eq, PartialEq)]
487pub struct PendingConnect {
488    instance_id: u64,
489    sequence: u64,
490    host: NormalizedHost,
491    port: u16,
492    admitted_at: u64,
493    expires_at: u64,
494}
495
496impl PendingConnect {
497    /// Exact normalized target host.
498    #[must_use]
499    pub fn host(&self) -> &str {
500        self.host.as_str()
501    }
502
503    /// Exact target port.
504    #[must_use]
505    pub const fn port(&self) -> u16 {
506        self.port
507    }
508
509    /// Trusted admission time.
510    #[must_use]
511    pub const fn admitted_at(&self) -> u64 {
512        self.admitted_at
513    }
514
515    /// Exclusive pending-admission expiry.
516    #[must_use]
517    pub const fn expires_at(&self) -> u64 {
518        self.expires_at
519    }
520}
521
522impl fmt::Debug for PendingConnect {
523    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
524        formatter
525            .debug_struct("PendingConnect")
526            .field("instance_id", &self.instance_id)
527            .field("sequence", &self.sequence)
528            .field("host", &"[redacted]")
529            .field("port", &self.port)
530            .field("admitted_at", &self.admitted_at)
531            .field("expires_at", &self.expires_at)
532            .finish()
533    }
534}
535
536struct PublicationRecord {
537    publication_id: u64,
538    publication_generation: u64,
539    selected_namespace: Namespace,
540    authenticated_context: AuthenticatedContextStatus,
541    hns_network: HnsNetwork,
542    service_port: u16,
543    tls_policy: TlsTrustPolicy,
544    runtime_session: [u8; 16],
545    runtime_generation: u64,
546    policy_generation: u64,
547    event_sequence: u64,
548    decision_fingerprint: [u8; 32],
549    authority_valid_from: u64,
550    authority_valid_until: u64,
551    published_at: u64,
552    publication_valid_until: u64,
553    endpoint: LoopbackEndpoint,
554    process_session: [u8; 16],
555    process_generation: u64,
556    listener_generation: u64,
557    authority: ProviderAuthorityContext,
558}
559
560/// Opaque handle to one atomically published provider authority.
561///
562/// This type is deliberately neither cloneable nor serializable. It can only
563/// be returned by [`ProxySession::publish_authority`] or
564/// [`ProxySession::replace_authority`], both of which consume an engine-issued
565/// [`ProviderAuthorityContext`].
566#[derive(Eq, PartialEq)]
567pub struct PublishedAdmission {
568    instance_id: u64,
569    logical_origin: LogicalOrigin,
570    publication_id: u64,
571    publication_generation: u64,
572    registry_generation: u64,
573    endpoint: LoopbackEndpoint,
574    process_session: [u8; 16],
575    process_generation: u64,
576    listener_generation: u64,
577}
578
579impl PublishedAdmission {
580    /// Exact normalized logical-origin host.
581    #[must_use]
582    pub fn host(&self) -> &str {
583        self.logical_origin.host()
584    }
585
586    /// Exact logical-origin port.
587    #[must_use]
588    pub const fn origin_port(&self) -> u16 {
589        self.logical_origin.port()
590    }
591
592    /// Registry generation committed by this publication operation.
593    #[must_use]
594    pub const fn registry_generation(&self) -> u64 {
595        self.registry_generation
596    }
597
598    /// Generation of this exact origin publication.
599    #[must_use]
600    pub const fn publication_generation(&self) -> u64 {
601        self.publication_generation
602    }
603}
604
605impl fmt::Debug for PublishedAdmission {
606    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
607        formatter
608            .debug_struct("PublishedAdmission")
609            .field("instance_id", &self.instance_id)
610            .field("logical_origin", &"[redacted]")
611            .field("publication_id", &self.publication_id)
612            .field("publication_generation", &self.publication_generation)
613            .field("registry_generation", &self.registry_generation)
614            .field("endpoint", &self.endpoint)
615            .field("process_session", &"[redacted]")
616            .field("process_generation", &self.process_generation)
617            .field("listener_generation", &self.listener_generation)
618            .finish()
619    }
620}
621
622/// Short-lived, single-CONNECT exact-origin permission.
623///
624/// This grant is deliberately opaque, non-cloneable, and non-serializable. A
625/// native host must move it into one tunnel attempt and re-check lifecycle
626/// cancellation before I/O. It is not a DNS, TLS, certificate, or wallet
627/// permission verdict.
628#[derive(Eq, PartialEq)]
629pub struct TunnelGrant {
630    instance_id: u64,
631    logical_origin: LogicalOrigin,
632    selected_namespace: Namespace,
633    authenticated_context: AuthenticatedContextStatus,
634    hns_network: HnsNetwork,
635    service_port: u16,
636    tls_policy: TlsTrustPolicy,
637    runtime_session: [u8; 16],
638    runtime_generation: u64,
639    policy_generation: u64,
640    event_sequence: u64,
641    decision_fingerprint: [u8; 32],
642    authority_valid_from: u64,
643    authority_valid_until: u64,
644    endpoint: LoopbackEndpoint,
645    process_session: [u8; 16],
646    process_generation: u64,
647    listener_generation: u64,
648    registry_generation: u64,
649    publication_id: u64,
650    publication_generation: u64,
651    connect_sequence: u64,
652    issued_at: u64,
653    expires_at: u64,
654}
655
656impl TunnelGrant {
657    /// Exact normalized leaf/tunnel host.
658    #[must_use]
659    pub fn host(&self) -> &str {
660        self.logical_origin.host()
661    }
662
663    /// Exact logical-origin port requested by CONNECT.
664    #[must_use]
665    pub const fn port(&self) -> u16 {
666        self.logical_origin.port()
667    }
668
669    /// Exact logical-origin URL scheme.
670    #[must_use]
671    pub const fn scheme(&self) -> OriginScheme {
672        self.logical_origin.scheme()
673    }
674
675    /// Exact selected namespace.
676    #[must_use]
677    pub const fn selected_namespace(&self) -> Namespace {
678        self.selected_namespace
679    }
680
681    /// Exact trusted authentication path.
682    #[must_use]
683    pub const fn authenticated_context(&self) -> AuthenticatedContextStatus {
684        self.authenticated_context
685    }
686
687    /// Exact Handshake network retained by the namespace decision.
688    #[must_use]
689    pub const fn hns_network(&self) -> HnsNetwork {
690        self.hns_network
691    }
692
693    /// Exact selected TCP service port for native origin dialing.
694    #[must_use]
695    pub const fn service_port(&self) -> u16 {
696        self.service_port
697    }
698
699    /// Exact selected TLS trust policy.
700    #[must_use]
701    pub const fn tls_policy(&self) -> TlsTrustPolicy {
702        self.tls_policy
703    }
704
705    /// Current runtime generation.
706    #[must_use]
707    pub const fn runtime_generation(&self) -> u64 {
708        self.runtime_generation
709    }
710
711    /// Runtime session that admitted the grant.
712    #[must_use]
713    pub const fn runtime_session(&self) -> [u8; 16] {
714        self.runtime_session
715    }
716
717    /// Exact engine event that authorized the grant.
718    #[must_use]
719    pub const fn authorization_event(&self) -> u64 {
720        self.event_sequence
721    }
722
723    /// Exact policy generation that authorized publication.
724    #[must_use]
725    pub const fn policy_generation(&self) -> u64 {
726        self.policy_generation
727    }
728
729    /// Complete query, plan, root outcome, evidence, and policy identity.
730    #[must_use]
731    pub const fn decision_fingerprint(&self) -> [u8; 32] {
732        self.decision_fingerprint
733    }
734
735    /// Original provider-authority validity beginning.
736    #[must_use]
737    pub const fn authority_valid_from(&self) -> u64 {
738        self.authority_valid_from
739    }
740
741    /// Original exclusive provider-authority expiry.
742    #[must_use]
743    pub const fn authority_valid_until(&self) -> u64 {
744        self.authority_valid_until
745    }
746
747    /// Exact numeric loopback listener endpoint.
748    #[must_use]
749    pub const fn endpoint(&self) -> LoopbackEndpoint {
750        self.endpoint
751    }
752
753    /// Fresh native-process session stamp.
754    #[must_use]
755    pub const fn process_session(&self) -> [u8; 16] {
756        self.process_session
757    }
758
759    /// Native-process lifecycle generation.
760    #[must_use]
761    pub const fn process_generation(&self) -> u64 {
762        self.process_generation
763    }
764
765    /// Listener lifecycle generation.
766    #[must_use]
767    pub const fn listener_generation(&self) -> u64 {
768        self.listener_generation
769    }
770
771    /// Registry generation revalidated for this grant.
772    #[must_use]
773    pub const fn registry_generation(&self) -> u64 {
774        self.registry_generation
775    }
776
777    /// Exact origin-publication generation revalidated for this grant.
778    #[must_use]
779    pub const fn publication_generation(&self) -> u64 {
780        self.publication_generation
781    }
782
783    /// Grant issue time and inclusive start of its short validity window.
784    #[must_use]
785    pub const fn valid_from(&self) -> u64 {
786        self.issued_at
787    }
788
789    /// Exclusive short grant expiry.
790    #[must_use]
791    pub const fn valid_until(&self) -> u64 {
792        self.expires_at
793    }
794}
795
796impl fmt::Debug for TunnelGrant {
797    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
798        formatter
799            .debug_struct("TunnelGrant")
800            .field("instance_id", &self.instance_id)
801            .field("logical_origin", &"[redacted]")
802            .field("selected_namespace", &self.selected_namespace)
803            .field("authenticated_context", &self.authenticated_context)
804            .field("hns_network", &self.hns_network)
805            .field("service_port", &self.service_port)
806            .field("tls_policy", &self.tls_policy)
807            .field("runtime_session", &"[redacted]")
808            .field("runtime_generation", &self.runtime_generation)
809            .field("policy_generation", &self.policy_generation)
810            .field("event_sequence", &self.event_sequence)
811            .field("decision_fingerprint", &"[redacted]")
812            .field("authority_valid_from", &self.authority_valid_from)
813            .field("authority_valid_until", &self.authority_valid_until)
814            .field("endpoint", &self.endpoint)
815            .field("process_session", &"[redacted]")
816            .field("process_generation", &self.process_generation)
817            .field("listener_generation", &self.listener_generation)
818            .field("registry_generation", &self.registry_generation)
819            .field("publication_id", &self.publication_id)
820            .field("publication_generation", &self.publication_generation)
821            .field("connect_sequence", &self.connect_sequence)
822            .field("issued_at", &self.issued_at)
823            .field("expires_at", &self.expires_at)
824            .finish()
825    }
826}
827
828/// Platform-neutral authenticated proxy admission state.
829pub struct ProxySession {
830    instance_id: u64,
831    config: ProxyConfig,
832    last_observed_time: Option<u64>,
833    sequence: u64,
834    pending: HashMap<u64, PendingRecord>,
835    registry_generation: u64,
836    publication_sequence: u64,
837    publications: HashMap<LogicalOrigin, PublicationRecord>,
838}
839
840impl fmt::Debug for ProxySession {
841    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
842        formatter
843            .debug_struct("ProxySession")
844            .field("instance_id", &self.instance_id)
845            .field("config", &self.config)
846            .field("last_observed_time", &self.last_observed_time)
847            .field("request_sequence", &self.sequence)
848            .field("pending_count", &self.pending.len())
849            .field("registry_generation", &self.registry_generation)
850            .field("publication_sequence", &self.publication_sequence)
851            .field("publication_count", &self.publications.len())
852            .finish()
853    }
854}
855
856impl ProxySession {
857    /// Open one non-cloneable proxy session.
858    pub fn new(config: ProxyConfig) -> Result<Self, ProxyError> {
859        let instance_id = NEXT_PROXY_INSTANCE_ID
860            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
861                current.checked_add(1)
862            })
863            .map_err(|_| ProxyError::InstanceSequenceExhausted)?;
864        Ok(Self {
865            instance_id,
866            config,
867            last_observed_time: None,
868            sequence: 0,
869            pending: HashMap::new(),
870            registry_generation: 1,
871            publication_sequence: 0,
872            publications: HashMap::new(),
873        })
874    }
875
876    /// Exact numeric loopback endpoint.
877    #[must_use]
878    pub const fn endpoint(&self) -> LoopbackEndpoint {
879        self.config.endpoint
880    }
881
882    /// Browser callback authorization value.
883    #[must_use]
884    pub fn authorization_header_value(&self) -> String {
885        self.config.authorization_header_value()
886    }
887
888    /// Current in-memory publication-registry generation.
889    #[must_use]
890    pub const fn registry_generation(&self) -> u64 {
891        self.registry_generation
892    }
893
894    /// Number of publication records currently resident in memory.
895    #[must_use]
896    pub fn publication_count(&self) -> usize {
897        self.publications.len()
898    }
899
900    /// Bounded 407 response for missing/invalid proxy authentication.
901    #[must_use]
902    pub fn authentication_challenge(&self) -> Vec<u8> {
903        format!(
904            "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",
905            PROXY_AUTHENTICATE_HEADER,
906            self.config.authorization.challenge_header_value()
907        )
908        .into_bytes()
909    }
910
911    /// Admit one strict authenticated loopback CONNECT before origin TLS.
912    ///
913    /// `now` must come from the native host's trusted nondecreasing clock.
914    /// Rollback is rejected. Expired pending records are removed before the
915    /// capacity check, and every returned handle carries its exact exclusive
916    /// deadline.
917    pub fn admit_connect(
918        &mut self,
919        engine: &Engine,
920        client: SocketAddr,
921        request_head: &[u8],
922        now: u64,
923    ) -> Result<PendingConnect, ProxyError> {
924        let snapshot = engine.snapshot()?;
925        self.ensure_runtime_ready(snapshot, false)?;
926        self.observe_time(now)?;
927        if !client.ip().is_loopback() {
928            return Err(ProxyError::NonLoopbackClient);
929        }
930        self.pending.retain(|_, record| now < record.expires_at);
931        if self.pending.len() >= self.config.limits.maximum_pending {
932            return Err(ProxyError::PendingLimit);
933        }
934        let parsed = parse_connect_head(request_head, self.config.limits)?;
935        let host = self.config.scope.authorize(parsed.host.as_str())?;
936        if !self
937            .config
938            .authorization
939            .verify_header_values(parsed.authorization.iter().filter_map(SecretHeader::as_str))
940        {
941            return Err(ProxyError::AuthenticationFailed);
942        }
943        let sequence = self
944            .sequence
945            .checked_add(1)
946            .ok_or(ProxyError::RequestSequenceExhausted)?;
947        let expires_at = now
948            .checked_add(self.config.limits.maximum_pending_lifetime_seconds)
949            .ok_or(ProxyError::TimeOverflow)?;
950        let record = PendingRecord {
951            host: host.clone(),
952            port: parsed.port,
953            admitted_at: now,
954            expires_at,
955        };
956        self.pending.insert(sequence, record);
957        self.sequence = sequence;
958        Ok(PendingConnect {
959            instance_id: self.instance_id,
960            sequence,
961            host,
962            port: parsed.port,
963            admitted_at: now,
964            expires_at,
965        })
966    }
967
968    /// Atomically publish one engine-issued provider authority.
969    ///
970    /// The context is consumed even when publication fails. Expired or
971    /// engine-invalid records are reclaimed before uniqueness and capacity
972    /// checks without advancing the generation because they can no longer
973    /// authorize a tunnel. Current records are unchanged unless every
974    /// authority, lifecycle, bound, time, uniqueness, capacity, and
975    /// expected-generation check succeeds.
976    pub fn publish_authority(
977        &mut self,
978        engine: &Engine,
979        expected_registry_generation: u64,
980        authority: ProviderAuthorityContext,
981        now: u64,
982    ) -> Result<PublishedAdmission, ProxyError> {
983        self.ensure_registry_generation(expected_registry_generation)?;
984        self.observe_time(now)?;
985        let next_registry_generation = self.next_registry_generation()?;
986        let publication_id = self
987            .publication_sequence
988            .checked_add(1)
989            .ok_or(ProxyError::PublicationSequenceExhausted)?;
990        let (logical_origin, record) = self.bind_authority(
991            engine,
992            authority,
993            publication_id,
994            next_registry_generation,
995            now,
996        )?;
997        let mut reclaimable = Vec::new();
998        let mut current_publications = 0_usize;
999        let mut duplicate = false;
1000        for (origin, existing) in &self.publications {
1001            if Self::publication_is_current(engine, existing, now)? {
1002                current_publications += 1;
1003                duplicate |= origin == &logical_origin;
1004            } else {
1005                reclaimable.push(origin.clone());
1006            }
1007        }
1008        for origin in reclaimable {
1009            self.publications.remove(&origin);
1010        }
1011        if duplicate {
1012            return Err(ProxyError::PublicationAlreadyExists);
1013        }
1014        if current_publications >= self.config.limits.maximum_publications {
1015            return Err(ProxyError::PublicationLimit);
1016        }
1017        let admission = self.admission_for(
1018            logical_origin.clone(),
1019            publication_id,
1020            next_registry_generation,
1021        );
1022        self.publications.insert(logical_origin, record);
1023        self.publication_sequence = publication_id;
1024        self.registry_generation = next_registry_generation;
1025        Ok(admission)
1026    }
1027
1028    /// Atomically replace one exact-origin publication with fresh authority.
1029    ///
1030    /// The old handle and replacement context are consumed. Replacement cannot
1031    /// change the logical origin, publication identity, process, or listener.
1032    #[allow(
1033        clippy::needless_pass_by_value,
1034        reason = "the admission is an intentionally consumed linear publication capability"
1035    )]
1036    pub fn replace_authority(
1037        &mut self,
1038        engine: &Engine,
1039        expected_registry_generation: u64,
1040        admission: PublishedAdmission,
1041        authority: ProviderAuthorityContext,
1042        now: u64,
1043    ) -> Result<PublishedAdmission, ProxyError> {
1044        self.ensure_registry_generation(expected_registry_generation)?;
1045        self.observe_time(now)?;
1046        let publication_id = self.validate_admission(&admission)?.publication_id;
1047        let next_registry_generation = self.next_registry_generation()?;
1048        let (logical_origin, record) = self.bind_authority(
1049            engine,
1050            authority,
1051            publication_id,
1052            next_registry_generation,
1053            now,
1054        )?;
1055        if logical_origin != admission.logical_origin {
1056            return Err(ProxyError::PublicationMismatch);
1057        }
1058        let replacement = self.admission_for(
1059            logical_origin.clone(),
1060            publication_id,
1061            next_registry_generation,
1062        );
1063        self.publications.insert(logical_origin, record);
1064        self.registry_generation = next_registry_generation;
1065        Ok(replacement)
1066    }
1067
1068    /// Atomically revoke one exact-origin publication.
1069    ///
1070    /// The handle is consumed and the generation advances only after the exact
1071    /// publication and expected registry generation match.
1072    #[allow(
1073        clippy::needless_pass_by_value,
1074        reason = "the admission is an intentionally consumed linear publication capability"
1075    )]
1076    pub fn revoke_authority(
1077        &mut self,
1078        expected_registry_generation: u64,
1079        admission: PublishedAdmission,
1080    ) -> Result<u64, ProxyError> {
1081        self.ensure_registry_generation(expected_registry_generation)?;
1082        self.validate_admission(&admission)?;
1083        let next_registry_generation = self.next_registry_generation()?;
1084        self.publications
1085            .remove(&admission.logical_origin)
1086            .ok_or(ProxyError::PublicationMismatch)?;
1087        self.registry_generation = next_registry_generation;
1088        Ok(next_registry_generation)
1089    }
1090
1091    /// Convert one pending CONNECT into a short-lived exact-origin grant.
1092    ///
1093    /// The pending token is consumed before any publication or engine check can
1094    /// succeed or fail. The published admission remains usable for another
1095    /// separately authenticated CONNECT only while every generation remains
1096    /// current.
1097    pub fn authorize_connect(
1098        &mut self,
1099        engine: &Engine,
1100        pending: PendingConnect,
1101        admission: &PublishedAdmission,
1102        expected_registry_generation: u64,
1103        now: u64,
1104    ) -> Result<TunnelGrant, ProxyError> {
1105        let PendingConnect {
1106            instance_id,
1107            sequence,
1108            host,
1109            port,
1110            admitted_at,
1111            expires_at,
1112        } = pending;
1113        if instance_id != self.instance_id {
1114            return Err(ProxyError::PendingMismatch);
1115        }
1116        let record = self
1117            .pending
1118            .get(&sequence)
1119            .ok_or(ProxyError::PendingMismatch)?;
1120        if record.host != host
1121            || record.port != port
1122            || record.admitted_at != admitted_at
1123            || record.expires_at != expires_at
1124        {
1125            return Err(ProxyError::PendingMismatch);
1126        }
1127        let record = self
1128            .pending
1129            .remove(&sequence)
1130            .ok_or(ProxyError::PendingMismatch)?;
1131        self.observe_time(now)?;
1132        if now < record.admitted_at || now >= record.expires_at {
1133            return Err(ProxyError::PendingExpired);
1134        }
1135        self.ensure_registry_generation(expected_registry_generation)?;
1136        let snapshot = engine.snapshot()?;
1137        self.ensure_runtime_ready(snapshot, true)?;
1138        let publication = self.validate_admission(admission)?;
1139        if admission.logical_origin.scheme() != OriginScheme::Https
1140            || admission.logical_origin.host() != record.host.as_str()
1141            || admission.logical_origin.port() != record.port
1142            || !Self::publication_is_current(engine, publication, now)?
1143        {
1144            return Err(ProxyError::ProviderAuthorityMismatch);
1145        }
1146        let grant_deadline = now
1147            .checked_add(self.config.limits.maximum_grant_lifetime_seconds)
1148            .ok_or(ProxyError::TimeOverflow)?;
1149        let grant_expires_at = publication.publication_valid_until.min(grant_deadline);
1150        if grant_expires_at <= now {
1151            return Err(ProxyError::ProviderAuthorityExpired);
1152        }
1153        Ok(TunnelGrant {
1154            instance_id: self.instance_id,
1155            logical_origin: admission.logical_origin.clone(),
1156            selected_namespace: publication.selected_namespace,
1157            authenticated_context: publication.authenticated_context,
1158            hns_network: publication.hns_network,
1159            service_port: publication.service_port,
1160            tls_policy: publication.tls_policy,
1161            runtime_session: publication.runtime_session,
1162            runtime_generation: publication.runtime_generation,
1163            policy_generation: publication.policy_generation,
1164            event_sequence: publication.event_sequence,
1165            decision_fingerprint: publication.decision_fingerprint,
1166            authority_valid_from: publication.authority_valid_from,
1167            authority_valid_until: publication.authority_valid_until,
1168            endpoint: publication.endpoint,
1169            process_session: publication.process_session,
1170            process_generation: publication.process_generation,
1171            listener_generation: publication.listener_generation,
1172            registry_generation: self.registry_generation,
1173            publication_id: publication.publication_id,
1174            publication_generation: publication.publication_generation,
1175            connect_sequence: sequence,
1176            issued_at: now,
1177            expires_at: grant_expires_at,
1178        })
1179    }
1180
1181    /// Revalidate a grant immediately before native listener or origin I/O.
1182    ///
1183    /// This check is intentionally generation-wide: any publish, replace, or
1184    /// revoke invalidates an outstanding grant until the CONNECT is admitted
1185    /// again. It also rejects another process/listener instance, a replaced or
1186    /// revoked exact-origin publication, security-invalidating engine
1187    /// transition, and expiry. Ordinary later engine admissions do not revoke
1188    /// the retained opaque authority.
1189    pub fn revalidate_tunnel_grant(
1190        &mut self,
1191        engine: &Engine,
1192        grant: &TunnelGrant,
1193        expected_registry_generation: u64,
1194        now: u64,
1195    ) -> Result<(), ProxyError> {
1196        self.ensure_registry_generation(expected_registry_generation)?;
1197        self.observe_time(now)?;
1198        if grant.registry_generation != expected_registry_generation
1199            || grant.instance_id != self.instance_id
1200            || grant.endpoint != self.config.endpoint
1201        {
1202            return Err(ProxyError::PublicationMismatch);
1203        }
1204        let identity = self.config.instance_identity;
1205        if grant.process_session != identity.process_session()
1206            || grant.process_generation != identity.process_generation()
1207            || grant.listener_generation != identity.listener_generation()
1208        {
1209            return Err(ProxyError::PublicationMismatch);
1210        }
1211        if now < grant.issued_at || now >= grant.expires_at {
1212            return Err(ProxyError::ProviderAuthorityExpired);
1213        }
1214        let snapshot = engine.snapshot()?;
1215        self.ensure_runtime_ready(snapshot, true)?;
1216        let publication = self
1217            .publications
1218            .get(&grant.logical_origin)
1219            .ok_or(ProxyError::PublicationMismatch)?;
1220        if publication.publication_id != grant.publication_id
1221            || publication.publication_generation != grant.publication_generation
1222            || publication.selected_namespace != grant.selected_namespace
1223            || publication.authenticated_context != grant.authenticated_context
1224            || publication.hns_network != grant.hns_network
1225            || publication.service_port != grant.service_port
1226            || publication.tls_policy != grant.tls_policy
1227            || publication.runtime_session != grant.runtime_session
1228            || publication.runtime_generation != grant.runtime_generation
1229            || publication.policy_generation != grant.policy_generation
1230            || publication.event_sequence != grant.event_sequence
1231            || publication.decision_fingerprint != grant.decision_fingerprint
1232            || publication.authority_valid_from != grant.authority_valid_from
1233            || publication.authority_valid_until != grant.authority_valid_until
1234            || publication.endpoint != grant.endpoint
1235            || publication.process_session != grant.process_session
1236            || publication.process_generation != grant.process_generation
1237            || publication.listener_generation != grant.listener_generation
1238            || grant.expires_at > publication.publication_valid_until
1239            || !Self::publication_is_current(engine, publication, now)?
1240        {
1241            return Err(ProxyError::ProviderAuthorityMismatch);
1242        }
1243        Ok(())
1244    }
1245
1246    /// Cancel one exact pending request.
1247    pub fn cancel(&mut self, pending: &PendingConnect) -> Result<(), ProxyError> {
1248        if pending.instance_id != self.instance_id {
1249            return Err(ProxyError::PendingMismatch);
1250        }
1251        self.pending
1252            .remove(&pending.sequence)
1253            .map(|_| ())
1254            .ok_or(ProxyError::PendingMismatch)
1255    }
1256
1257    fn bind_authority(
1258        &self,
1259        engine: &Engine,
1260        authority: ProviderAuthorityContext,
1261        publication_id: u64,
1262        publication_generation: u64,
1263        now: u64,
1264    ) -> Result<(LogicalOrigin, PublicationRecord), ProxyError> {
1265        let snapshot = engine.snapshot()?;
1266        self.ensure_runtime_ready(snapshot, true)?;
1267        let logical_origin = authority.logical_origin().clone();
1268        let host = self.config.scope.authorize(logical_origin.host())?;
1269        if logical_origin.scheme() != OriginScheme::Https
1270            || host.as_str() != logical_origin.host()
1271            || logical_origin.port() == 0
1272            || authority.service_port() == 0
1273            || authority.authenticated_context() == AuthenticatedContextStatus::Unauthenticated
1274            || authority.tls_policy() == TlsTrustPolicy::Cleartext
1275            || authority.runtime_session() != snapshot.runtime_session
1276            || authority.runtime_generation() != snapshot.runtime_generation
1277            || authority.policy_generation() != snapshot.policy.generation()
1278            || authority.hns_network() != snapshot.hns_network()
1279        {
1280            return Err(ProxyError::ProviderAuthorityMismatch);
1281        }
1282        if now < authority.valid_from() {
1283            return Err(ProxyError::ProviderAuthorityNotYetValid);
1284        }
1285        if now >= authority.valid_until() {
1286            return Err(ProxyError::ProviderAuthorityExpired);
1287        }
1288        if !engine.provider_authority_is_current(&authority, now)? {
1289            return Err(ProxyError::ProviderAuthorityMismatch);
1290        }
1291        let publication_deadline = now
1292            .checked_add(self.config.limits.maximum_publication_lifetime_seconds)
1293            .ok_or(ProxyError::TimeOverflow)?;
1294        let publication_valid_until = authority.valid_until().min(publication_deadline);
1295        if publication_valid_until <= now {
1296            return Err(ProxyError::ProviderAuthorityExpired);
1297        }
1298        let identity = self.config.instance_identity;
1299        Ok((
1300            logical_origin,
1301            PublicationRecord {
1302                publication_id,
1303                publication_generation,
1304                selected_namespace: authority.selected_namespace(),
1305                authenticated_context: authority.authenticated_context(),
1306                hns_network: authority.hns_network(),
1307                service_port: authority.service_port(),
1308                tls_policy: authority.tls_policy(),
1309                runtime_session: authority.runtime_session(),
1310                runtime_generation: authority.runtime_generation(),
1311                policy_generation: authority.policy_generation(),
1312                event_sequence: authority.event_sequence(),
1313                decision_fingerprint: authority.decision_fingerprint(),
1314                authority_valid_from: authority.valid_from(),
1315                authority_valid_until: authority.valid_until(),
1316                published_at: now,
1317                publication_valid_until,
1318                endpoint: self.config.endpoint,
1319                process_session: identity.process_session(),
1320                process_generation: identity.process_generation(),
1321                listener_generation: identity.listener_generation(),
1322                authority,
1323            },
1324        ))
1325    }
1326
1327    fn admission_for(
1328        &self,
1329        logical_origin: LogicalOrigin,
1330        publication_id: u64,
1331        publication_generation: u64,
1332    ) -> PublishedAdmission {
1333        let identity = self.config.instance_identity;
1334        PublishedAdmission {
1335            instance_id: self.instance_id,
1336            logical_origin,
1337            publication_id,
1338            publication_generation,
1339            registry_generation: publication_generation,
1340            endpoint: self.config.endpoint,
1341            process_session: identity.process_session(),
1342            process_generation: identity.process_generation(),
1343            listener_generation: identity.listener_generation(),
1344        }
1345    }
1346
1347    fn validate_admission(
1348        &self,
1349        admission: &PublishedAdmission,
1350    ) -> Result<&PublicationRecord, ProxyError> {
1351        let identity = self.config.instance_identity;
1352        if admission.instance_id != self.instance_id
1353            || admission.endpoint != self.config.endpoint
1354            || admission.process_session != identity.process_session()
1355            || admission.process_generation != identity.process_generation()
1356            || admission.listener_generation != identity.listener_generation()
1357        {
1358            return Err(ProxyError::PublicationMismatch);
1359        }
1360        let record = self
1361            .publications
1362            .get(&admission.logical_origin)
1363            .ok_or(ProxyError::PublicationMismatch)?;
1364        if record.publication_id != admission.publication_id
1365            || record.publication_generation != admission.publication_generation
1366            || record.endpoint != admission.endpoint
1367            || record.process_session != admission.process_session
1368            || record.process_generation != admission.process_generation
1369            || record.listener_generation != admission.listener_generation
1370        {
1371            return Err(ProxyError::PublicationMismatch);
1372        }
1373        Ok(record)
1374    }
1375
1376    fn publication_is_current(
1377        engine: &Engine,
1378        publication: &PublicationRecord,
1379        now: u64,
1380    ) -> Result<bool, ProxyError> {
1381        let authority = &publication.authority;
1382        Ok(
1383            publication.selected_namespace == authority.selected_namespace()
1384                && publication.authenticated_context == authority.authenticated_context()
1385                && publication.hns_network == authority.hns_network()
1386                && publication.service_port == authority.service_port()
1387                && publication.tls_policy == authority.tls_policy()
1388                && publication.runtime_session == authority.runtime_session()
1389                && publication.runtime_generation == authority.runtime_generation()
1390                && publication.policy_generation == authority.policy_generation()
1391                && publication.event_sequence == authority.event_sequence()
1392                && publication.decision_fingerprint == authority.decision_fingerprint()
1393                && publication.authority_valid_from == authority.valid_from()
1394                && publication.authority_valid_until == authority.valid_until()
1395                && now >= publication.authority_valid_from
1396                && now < publication.authority_valid_until
1397                && now >= publication.published_at
1398                && now < publication.publication_valid_until
1399                && engine.provider_authority_is_current(authority, now)?,
1400        )
1401    }
1402
1403    fn ensure_registry_generation(&self, expected: u64) -> Result<(), ProxyError> {
1404        if expected != self.registry_generation {
1405            return Err(ProxyError::StaleRegistryGeneration);
1406        }
1407        Ok(())
1408    }
1409
1410    fn observe_time(&mut self, now: u64) -> Result<(), ProxyError> {
1411        if self
1412            .last_observed_time
1413            .is_some_and(|last_observed| now < last_observed)
1414        {
1415            return Err(ProxyError::ClockRollback);
1416        }
1417        self.last_observed_time = Some(now);
1418        Ok(())
1419    }
1420
1421    fn next_registry_generation(&self) -> Result<u64, ProxyError> {
1422        self.registry_generation
1423            .checked_add(1)
1424            .ok_or(ProxyError::RegistryGenerationExhausted)
1425    }
1426
1427    fn ensure_runtime_ready(
1428        &self,
1429        snapshot: EngineSnapshot,
1430        bridge_required: bool,
1431    ) -> Result<(), ProxyError> {
1432        if snapshot.runtime_session != self.config.runtime_session
1433            || snapshot.runtime_generation != self.config.runtime_generation
1434        {
1435            return Err(ProxyError::StaleRuntime);
1436        }
1437        let ready = if bridge_required {
1438            matches!(
1439                snapshot.authority_state,
1440                AuthorityState::BrowserBridgeReady | AuthorityState::Active
1441            )
1442        } else {
1443            matches!(
1444                snapshot.authority_state,
1445                AuthorityState::ResolutionTransportReady
1446                    | AuthorityState::DnssecVerified
1447                    | AuthorityState::DaneOriginVerified
1448                    | AuthorityState::BrowserBridgeReady
1449                    | AuthorityState::Active
1450            )
1451        };
1452        if !ready {
1453            return Err(ProxyError::AuthorityNotReady);
1454        }
1455        Ok(())
1456    }
1457}
1458
1459impl Drop for ProxySession {
1460    fn drop(&mut self) {
1461        self.pending.clear();
1462        self.publications.clear();
1463    }
1464}
1465
1466struct SecretHeader(Vec<u8>);
1467
1468impl SecretHeader {
1469    fn as_str(&self) -> Option<&str> {
1470        std::str::from_utf8(&self.0).ok()
1471    }
1472}
1473
1474impl Drop for SecretHeader {
1475    fn drop(&mut self) {
1476        self.0.fill(0);
1477    }
1478}
1479
1480struct ParsedConnect {
1481    host: NormalizedHost,
1482    port: u16,
1483    authorization: Vec<SecretHeader>,
1484}
1485
1486fn parse_connect_head(input: &[u8], limits: ProxyLimits) -> Result<ParsedConnect, ProxyError> {
1487    if input.len() > limits.maximum_head_bytes
1488        || !input.ends_with(b"\r\n\r\n")
1489        || input.windows(2).filter(|pair| *pair == b"\r\n").count() < 2
1490    {
1491        return Err(ProxyError::MalformedRequest);
1492    }
1493    let text = std::str::from_utf8(input).map_err(|_| ProxyError::MalformedRequest)?;
1494    if input.first() == Some(&b'\n')
1495        || input
1496            .windows(2)
1497            .any(|window| window.get(1) == Some(&b'\n') && window.first() != Some(&b'\r'))
1498    {
1499        return Err(ProxyError::MalformedRequest);
1500    }
1501    let mut lines = text
1502        .strip_suffix("\r\n\r\n")
1503        .ok_or(ProxyError::MalformedRequest)?
1504        .split("\r\n");
1505    let request_line = lines.next().ok_or(ProxyError::MalformedRequest)?;
1506    if request_line.contains('\t') {
1507        return Err(ProxyError::MalformedRequest);
1508    }
1509    let mut parts = request_line.split(' ');
1510    let method = parts.next().ok_or(ProxyError::MalformedRequest)?;
1511    let target = parts.next().ok_or(ProxyError::MalformedRequest)?;
1512    let version = parts.next().ok_or(ProxyError::MalformedRequest)?;
1513    if method != "CONNECT" || version != "HTTP/1.1" || parts.next().is_some() || target.is_empty() {
1514        return Err(ProxyError::MalformedRequest);
1515    }
1516    let (host, port) = parse_authority(target)?;
1517    let mut host_values = Vec::new();
1518    let mut authorization = Vec::new();
1519    let mut header_count = 0_usize;
1520    for line in lines {
1521        header_count = header_count
1522            .checked_add(1)
1523            .ok_or(ProxyError::MalformedRequest)?;
1524        if header_count > limits.maximum_headers || line.is_empty() || line.starts_with([' ', '\t'])
1525        {
1526            return Err(ProxyError::MalformedRequest);
1527        }
1528        let (name, raw_value) = line.split_once(':').ok_or(ProxyError::MalformedRequest)?;
1529        if name.is_empty()
1530            || !name
1531                .bytes()
1532                .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
1533        {
1534            return Err(ProxyError::MalformedRequest);
1535        }
1536        let value = raw_value.trim_matches([' ', '\t']);
1537        if value.is_empty()
1538            || value
1539                .chars()
1540                .any(|character| character.is_control() && !matches!(character, '\t'))
1541        {
1542            return Err(ProxyError::MalformedRequest);
1543        }
1544        if name.eq_ignore_ascii_case("host") {
1545            host_values.push(value.to_owned());
1546        } else if name.eq_ignore_ascii_case(PROXY_AUTHORIZATION_HEADER) {
1547            authorization.push(SecretHeader(value.as_bytes().to_vec()));
1548        } else if name.eq_ignore_ascii_case("content-length")
1549            || name.eq_ignore_ascii_case("transfer-encoding")
1550            || name.eq_ignore_ascii_case("upgrade")
1551            || name.eq_ignore_ascii_case("expect")
1552            || ((name.eq_ignore_ascii_case("connection")
1553                || name.eq_ignore_ascii_case("proxy-connection"))
1554                && value
1555                    .split(',')
1556                    .any(|token| token.trim().eq_ignore_ascii_case("upgrade")))
1557        {
1558            return Err(ProxyError::RequestBodyOrUpgrade);
1559        }
1560    }
1561    if host_values.len() != 1 || authorization.len() != 1 {
1562        return Err(ProxyError::MalformedRequest);
1563    }
1564    let (host_header, host_port) =
1565        parse_authority(host_values.first().ok_or(ProxyError::MalformedRequest)?)?;
1566    if host_header != host || host_port != port {
1567        return Err(ProxyError::AuthorityMismatch);
1568    }
1569    Ok(ParsedConnect {
1570        host,
1571        port,
1572        authorization,
1573    })
1574}
1575
1576fn parse_authority(input: &str) -> Result<(NormalizedHost, u16), ProxyError> {
1577    let (host, port_text) = input
1578        .rsplit_once(':')
1579        .ok_or(ProxyError::MalformedAuthority)?;
1580    if host.contains(':')
1581        || port_text.is_empty()
1582        || (port_text.len() > 1 && port_text.starts_with('0'))
1583        || !port_text.bytes().all(|byte| byte.is_ascii_digit())
1584    {
1585        return Err(ProxyError::MalformedAuthority);
1586    }
1587    let port = port_text
1588        .parse::<u16>()
1589        .map_err(|_| ProxyError::MalformedAuthority)?;
1590    if port == 0 {
1591        return Err(ProxyError::MalformedAuthority);
1592    }
1593    Ok((NormalizedHost::parse(host)?, port))
1594}
1595
1596fn basic_token(value: &str) -> Option<&str> {
1597    if value
1598        .chars()
1599        .any(|character| character.is_control() && !matches!(character, ' ' | '\t'))
1600    {
1601        return None;
1602    }
1603    let value = value.trim_matches([' ', '\t']);
1604    let separator = value.find([' ', '\t'])?;
1605    let (scheme, remainder) = value.split_at(separator);
1606    if !scheme.eq_ignore_ascii_case("Basic") {
1607        return None;
1608    }
1609    let token = remainder.trim_start_matches([' ', '\t']);
1610    if token.is_empty() || token.chars().any(char::is_whitespace) {
1611        return None;
1612    }
1613    Some(token)
1614}
1615
1616fn encode_hex(input: &[u8]) -> String {
1617    let mut output = Vec::with_capacity(input.len() * 2);
1618    append_hex(&mut output, input);
1619    String::from_utf8(output).unwrap_or_default()
1620}
1621
1622fn append_hex(output: &mut Vec<u8>, input: &[u8]) {
1623    const HEX: &[u8; 16] = b"0123456789abcdef";
1624    for byte in input {
1625        output.push(HEX.get(usize::from(byte >> 4)).copied().unwrap_or(b'0'));
1626        output.push(HEX.get(usize::from(byte & 0x0f)).copied().unwrap_or(b'0'));
1627    }
1628}
1629
1630fn encode_base64(input: &[u8]) -> String {
1631    let mut output = String::with_capacity(input.len().div_ceil(3) * 4);
1632    for chunk in input.chunks(3) {
1633        let first = u32::from(chunk.first().copied().unwrap_or(0));
1634        let second = chunk.get(1).copied().map_or(0, u32::from);
1635        let third = chunk.get(2).copied().map_or(0, u32::from);
1636        let value = (first << 16) | (second << 8) | third;
1637        output.push(base64_character((value >> 18) & 0x3f));
1638        output.push(base64_character((value >> 12) & 0x3f));
1639        output.push(if chunk.len() > 1 {
1640            base64_character((value >> 6) & 0x3f)
1641        } else {
1642            '='
1643        });
1644        output.push(if chunk.len() > 2 {
1645            base64_character(value & 0x3f)
1646        } else {
1647            '='
1648        });
1649    }
1650    output
1651}
1652
1653fn base64_character(index: u32) -> char {
1654    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1655    let index = usize::try_from(index).unwrap_or(0);
1656    char::from(ALPHABET.get(index).copied().unwrap_or(b'A'))
1657}
1658
1659fn looks_like_legacy_ipv4(host: &str) -> bool {
1660    let mut count = 0_usize;
1661    let numeric = host.split('.').all(|label| {
1662        count += 1;
1663        if let Some(hex) = label
1664            .strip_prefix("0x")
1665            .or_else(|| label.strip_prefix("0X"))
1666        {
1667            return !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit());
1668        }
1669        if label.len() > 1 && label.starts_with('0') {
1670            return label.bytes().all(|byte| matches!(byte, b'0'..=b'7'));
1671        }
1672        !label.is_empty() && label.bytes().all(|byte| byte.is_ascii_digit())
1673    });
1674    numeric && (1..=4).contains(&count)
1675}
1676
1677/// Proxy configuration, request, runtime, or provider-publication failure.
1678#[derive(Debug, Error)]
1679#[non_exhaustive]
1680pub enum ProxyError {
1681    /// Engine state could not be read or advanced.
1682    #[error("browser engine failure: {0}")]
1683    Engine(#[from] EngineError),
1684    /// Listener endpoint is not numeric loopback.
1685    #[error("proxy endpoint must be numeric loopback")]
1686    NonLoopbackEndpoint,
1687    /// Port zero cannot be advertised in PAC/native messaging.
1688    #[error("proxy endpoint port must be nonzero")]
1689    ZeroProxyPort,
1690    /// Client did not connect from a loopback address.
1691    #[error("proxy client must be loopback")]
1692    NonLoopbackClient,
1693    /// Browser runtime session must be nonzero.
1694    #[error("proxy runtime session must be nonzero")]
1695    ZeroRuntimeSession,
1696    /// Runtime generation must begin above zero.
1697    #[error("proxy runtime generation must be nonzero")]
1698    ZeroRuntimeGeneration,
1699    /// Native process session must be nonzero and fresh per start.
1700    #[error("proxy process session must be nonzero")]
1701    ZeroProcessSession,
1702    /// Native process generation must begin above zero.
1703    #[error("proxy process generation must be nonzero")]
1704    ZeroProcessGeneration,
1705    /// Listener generation must begin above zero.
1706    #[error("proxy listener generation must be nonzero")]
1707    ZeroListenerGeneration,
1708    /// Proxy resource bounds are invalid.
1709    #[error("invalid proxy limits")]
1710    InvalidLimits,
1711    /// Caller-supplied trusted time moved backwards within this session.
1712    #[error("proxy trusted clock moved backwards")]
1713    ClockRollback,
1714    /// A bounded absolute deadline cannot be represented.
1715    #[error("proxy absolute deadline overflow")]
1716    TimeOverflow,
1717    /// Host is not strict ASCII/punycode DNS text.
1718    #[error("invalid proxy host")]
1719    InvalidHost,
1720    /// Scope root must be one proof-verified HNS TLD label.
1721    #[error("proxy scope root must be one HNS TLD")]
1722    ScopeMustBeHnsTld,
1723    /// CONNECT target is outside the immutable HNS scope.
1724    #[error("proxy target is outside HNS scope")]
1725    HostOutsideScope,
1726    /// Runtime session/generation was revoked or differs from this proxy.
1727    #[error("proxy runtime is stale")]
1728    StaleRuntime,
1729    /// Engine authority state is not ready for this phase.
1730    #[error("proxy authority is not ready")]
1731    AuthorityNotReady,
1732    /// Request head is malformed, incomplete, oversized, or ambiguous.
1733    #[error("malformed CONNECT request")]
1734    MalformedRequest,
1735    /// CONNECT authority is not canonical host:port.
1736    #[error("malformed CONNECT authority")]
1737    MalformedAuthority,
1738    /// Host header does not exactly match the request target.
1739    #[error("CONNECT Host header and target differ")]
1740    AuthorityMismatch,
1741    /// CONNECT request attempted a body or protocol upgrade.
1742    #[error("CONNECT request body or upgrade is prohibited")]
1743    RequestBodyOrUpgrade,
1744    /// Proxy capability is missing, duplicated, or incorrect.
1745    #[error("proxy authentication failed")]
1746    AuthenticationFailed,
1747    /// Pending request bound is full.
1748    #[error("proxy pending request limit reached")]
1749    PendingLimit,
1750    /// Pending CONNECT reached its exclusive expiry.
1751    #[error("proxy pending CONNECT expired")]
1752    PendingExpired,
1753    /// Process-local proxy instance counter cannot advance.
1754    #[error("proxy instance sequence exhausted")]
1755    InstanceSequenceExhausted,
1756    /// Request sequence cannot advance.
1757    #[error("proxy request sequence exhausted")]
1758    RequestSequenceExhausted,
1759    /// Publication sequence cannot advance.
1760    #[error("proxy publication sequence exhausted")]
1761    PublicationSequenceExhausted,
1762    /// Registry generation cannot advance.
1763    #[error("proxy publication registry generation exhausted")]
1764    RegistryGenerationExhausted,
1765    /// Caller did not present the exact current registry generation.
1766    #[error("proxy publication registry generation is stale")]
1767    StaleRegistryGeneration,
1768    /// Publication registry reached its configured capacity.
1769    #[error("proxy publication registry capacity reached")]
1770    PublicationLimit,
1771    /// Exact logical origin already has a publication.
1772    #[error("proxy origin publication already exists")]
1773    PublicationAlreadyExists,
1774    /// Admission belongs to another, replaced, revoked, or restarted registry.
1775    #[error("proxy origin publication mismatch")]
1776    PublicationMismatch,
1777    /// Pending token belongs to another proxy, was changed, or was consumed.
1778    #[error("proxy pending CONNECT mismatch")]
1779    PendingMismatch,
1780    /// Engine-issued provider authority is not valid for the exact current binding.
1781    #[error("provider authority does not match the current proxy binding")]
1782    ProviderAuthorityMismatch,
1783    /// Provider authority predates its validity window.
1784    #[error("provider authority is not yet valid")]
1785    ProviderAuthorityNotYetValid,
1786    /// Provider authority or its short publication lifetime expired.
1787    #[error("provider authority publication expired")]
1788    ProviderAuthorityExpired,
1789}
1790
1791#[cfg(test)]
1792#[allow(
1793    clippy::unwrap_used,
1794    reason = "tests fail immediately on invalid deterministic proxy fixtures"
1795)]
1796mod tests {
1797    use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1798
1799    use hns_dane_engine::{
1800        EngineConfig, IcannOriginAuthentication, IcannOriginAuthenticationRequest,
1801        NamespaceDecision, RuntimeSessionId,
1802    };
1803    use hns_namespace_resolution::{
1804        AbsenceKind, ApplicationProtocol, CanonicalHost, EvidenceProvenance, Freshness,
1805        IcannChainState, OriginPlanInput, OriginQuery, ProtocolCapabilities, RootLookup,
1806        SelectionPolicy, ServiceBinding, ServiceBindingInput, ServiceTransport, ValidatedAbsence,
1807        ValidatedOriginPlan, decide_namespace,
1808    };
1809    use hns_resolution_policy::{Network, PolicySnapshot};
1810
1811    use super::*;
1812
1813    const AUTHORITY_NOW: u64 = 1_700_000_000;
1814
1815    fn ready_engine(session: [u8; 16]) -> Engine {
1816        let engine = Engine::new(EngineConfig {
1817            runtime_session: RuntimeSessionId::new(session).unwrap(),
1818            network: Network::Regtest,
1819            policy: PolicySnapshot::default(),
1820        });
1821        for state in [
1822            AuthorityState::LocalStateOpened,
1823            AuthorityState::HeaderSyncing,
1824            AuthorityState::HeaderCurrent,
1825            AuthorityState::ProofReady,
1826            AuthorityState::ResolutionTransportReady,
1827        ] {
1828            engine.advance_authority_state(state).unwrap();
1829        }
1830        engine
1831    }
1832
1833    fn authorization() -> ProxyAuthorization {
1834        ProxyAuthorization::from_capability([7; 16], [9; 32])
1835    }
1836
1837    fn proxy_for_engine(
1838        engine: &Engine,
1839        process_session: [u8; 16],
1840        maximum_pending: usize,
1841        maximum_publications: usize,
1842    ) -> ProxySession {
1843        proxy_for_engine_with_limits(
1844            engine,
1845            process_session,
1846            ProxyLimits {
1847                maximum_pending,
1848                maximum_publications,
1849                ..ProxyLimits::default()
1850            },
1851        )
1852    }
1853
1854    fn proxy_for_engine_with_limits(
1855        engine: &Engine,
1856        process_session: [u8; 16],
1857        limits: ProxyLimits,
1858    ) -> ProxySession {
1859        let snapshot = engine.snapshot().unwrap();
1860        let config = ProxyConfig::new(
1861            LoopbackEndpoint::new("127.0.0.1:39000".parse().unwrap()).unwrap(),
1862            ProxyInstanceIdentity::new(process_session, 1, 1).unwrap(),
1863            snapshot.runtime_session,
1864            snapshot.runtime_generation,
1865            HostScope::from_verified_hns_tld("alpha").unwrap(),
1866            authorization(),
1867            limits,
1868        )
1869        .unwrap();
1870        ProxySession::new(config).unwrap()
1871    }
1872
1873    fn session(session_id: [u8; 16], maximum_pending: usize) -> (Engine, ProxySession) {
1874        let engine = ready_engine(session_id);
1875        let proxy = proxy_for_engine(&engine, [90; 16], maximum_pending, 4);
1876        (engine, proxy)
1877    }
1878
1879    fn active_engine(session_id: [u8; 16]) -> Engine {
1880        let engine = ready_engine(session_id);
1881        for state in [
1882            AuthorityState::DnssecVerified,
1883            AuthorityState::BrowserBridgeReady,
1884            AuthorityState::Active,
1885        ] {
1886            engine.advance_authority_state(state).unwrap();
1887        }
1888        engine
1889    }
1890
1891    fn recover_active_engine(engine: &Engine) {
1892        for state in [
1893            AuthorityState::HeaderSyncing,
1894            AuthorityState::HeaderCurrent,
1895            AuthorityState::ProofReady,
1896            AuthorityState::ResolutionTransportReady,
1897            AuthorityState::BrowserBridgeReady,
1898            AuthorityState::Active,
1899        ] {
1900            engine.advance_authority_state(state).unwrap();
1901        }
1902    }
1903
1904    fn provider_decision(host: &str) -> NamespaceDecision {
1905        let query = OriginQuery::new(
1906            CanonicalHost::parse(host).unwrap(),
1907            OriginScheme::Https,
1908            None,
1909            ProtocolCapabilities::all(),
1910        );
1911        let target = query.host().clone();
1912        let port = query.origin_port();
1913        let freshness = Freshness::new(AUTHORITY_NOW - 10, AUTHORITY_NOW + 100).unwrap();
1914        let service = ServiceBinding::new(ServiceBindingInput {
1915            priority: None,
1916            service_target: target.clone(),
1917            mandatory_keys: Vec::new(),
1918            advertised_alpn: Vec::new(),
1919            selected_protocol: ApplicationProtocol::Http11,
1920            effective_port: port,
1921            transport: ServiceTransport::Tcp,
1922            connection_hints: Vec::new(),
1923            ech_config: None,
1924            parameters: Vec::new(),
1925        })
1926        .unwrap();
1927        let icann = ValidatedOriginPlan::new(OriginPlanInput {
1928            namespace: Namespace::Icann,
1929            query: query.clone(),
1930            alias_path: Vec::new(),
1931            terminal_target: target.clone(),
1932            endpoint_alias_path: Vec::new(),
1933            endpoint_target: target,
1934            endpoints: vec![SocketAddr::new(
1935                IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)),
1936                port.get(),
1937            )],
1938            service,
1939            tls_policy: TlsTrustPolicy::WebPkiAuthenticatedAbsence,
1940            tlsa_records: Vec::new(),
1941            provenance: EvidenceProvenance::IcannDoh {
1942                chain_state: IcannChainState::Secure,
1943            },
1944            freshness,
1945        })
1946        .unwrap();
1947        let hns_absence = ValidatedAbsence::new(
1948            Namespace::Hns,
1949            query.clone(),
1950            AbsenceKind::HnsCurrentUrkelNonInclusion,
1951            EvidenceProvenance::Hns {
1952                network: HnsNetwork::Regtest,
1953                tree_root: [21; 32],
1954                height: 42,
1955            },
1956            freshness,
1957        )
1958        .unwrap();
1959        decide_namespace(
1960            &query,
1961            RootLookup::Absent(hns_absence),
1962            RootLookup::Present(icann),
1963            SelectionPolicy::default(),
1964            AUTHORITY_NOW,
1965        )
1966        .unwrap()
1967    }
1968
1969    #[allow(
1970        clippy::unnecessary_wraps,
1971        reason = "the test adapter implements the optional trusted-authenticator result"
1972    )]
1973    fn trusted_icann_webpki(
1974        request: &IcannOriginAuthenticationRequest,
1975    ) -> Option<IcannOriginAuthentication> {
1976        Some(request.attest_webpki_verified())
1977    }
1978
1979    fn provider_authority(
1980        engine: &Engine,
1981        decision: &NamespaceDecision,
1982    ) -> ProviderAuthorityContext {
1983        let context = engine
1984            .bind_icann_origin_context(decision, &trusted_icann_webpki, AUTHORITY_NOW)
1985            .unwrap();
1986        engine
1987            .authorize_provider_injection(decision, &context, AUTHORITY_NOW)
1988            .unwrap()
1989            .into_context()
1990            .unwrap()
1991    }
1992
1993    fn connect_request_for(host: &str, authorization: &str) -> Vec<u8> {
1994        format!(
1995            "CONNECT {host}:443 HTTP/1.1\r\nHost: {host}:443\r\nProxy-Authorization: {authorization}\r\nProxy-Connection: keep-alive\r\n\r\n"
1996        )
1997        .into_bytes()
1998    }
1999
2000    fn connect_request(authorization: &str) -> Vec<u8> {
2001        connect_request_for("www.alpha", authorization)
2002    }
2003
2004    #[test]
2005    fn capability_auth_is_exact_constant_time_and_redacted() {
2006        let authorization = authorization();
2007        let valid = authorization.authorization_header_value();
2008        assert!(authorization.verify_header_values([valid.as_str()]));
2009        assert!(authorization.verify_header_values([valid.replacen("Basic", "bAsIc", 1).as_str()]));
2010        assert!(!authorization.verify_header_values(std::iter::empty()));
2011        assert!(!authorization.verify_header_values([valid.as_str(), valid.as_str()]));
2012        assert!(!authorization.verify_header_values(["Basic wrong"]));
2013        assert!(!authorization.verify_header_values(["Bearer wrong"]));
2014        let debug = format!("{authorization:?}");
2015        assert!(!debug.contains(authorization.realm()));
2016        assert!(!debug.contains(valid.split_once(' ').unwrap().1));
2017    }
2018
2019    #[test]
2020    fn endpoint_challenge_and_clients_are_exact_loopback() {
2021        assert!(matches!(
2022            LoopbackEndpoint::new("0.0.0.0:39000".parse().unwrap()),
2023            Err(ProxyError::NonLoopbackEndpoint)
2024        ));
2025        assert!(matches!(
2026            LoopbackEndpoint::new("127.0.0.1:0".parse().unwrap()),
2027            Err(ProxyError::ZeroProxyPort)
2028        ));
2029        let (engine, mut proxy) = session([1; 16], 2);
2030        let endpoint = proxy.endpoint();
2031        assert!(proxy.config.authorization.matches_challenge(
2032            endpoint,
2033            "127.0.0.1",
2034            39000,
2035            proxy.config.realm()
2036        ));
2037        let request = connect_request(&proxy.authorization_header_value());
2038        assert!(matches!(
2039            proxy.admit_connect(&engine, "192.0.2.1:50000".parse().unwrap(), &request, 1,),
2040            Err(ProxyError::NonLoopbackClient)
2041        ));
2042    }
2043
2044    #[test]
2045    fn host_scope_is_label_bound_and_rejects_ip_forms() {
2046        let scope = HostScope::from_verified_hns_tld("ALPHA.").unwrap();
2047        assert_eq!(scope.authorize("WWW.Alpha.").unwrap().as_str(), "www.alpha");
2048        assert!(matches!(
2049            scope.authorize("notalpha"),
2050            Err(ProxyError::HostOutsideScope)
2051        ));
2052        for invalid in ["127.0.0.1", "2130706433", "0x7f000001", "[::1]", "bad name"] {
2053            assert!(matches!(
2054                NormalizedHost::parse(invalid),
2055                Err(ProxyError::InvalidHost)
2056            ));
2057        }
2058        assert!(matches!(
2059            HostScope::from_verified_hns_tld("www.alpha"),
2060            Err(ProxyError::ScopeMustBeHnsTld)
2061        ));
2062    }
2063
2064    #[test]
2065    fn admits_only_strict_authenticated_connect() {
2066        let (engine, mut proxy) = session([2; 16], 4);
2067        let authorization = proxy.authorization_header_value();
2068        let valid = connect_request(&authorization);
2069        let pending = proxy
2070            .admit_connect(&engine, "127.0.0.1:50000".parse().unwrap(), &valid, 1)
2071            .unwrap();
2072        assert_eq!(pending.host(), "www.alpha");
2073        assert_eq!(pending.port(), 443);
2074
2075        for invalid in [
2076            b"GET https://www.alpha/ HTTP/1.1\r\nHost: www.alpha\r\n\r\n".to_vec(),
2077            connect_request("Basic wrong"),
2078            format!(
2079                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: other.alpha:443\r\nProxy-Authorization: {authorization}\r\n\r\n"
2080            )
2081            .into_bytes(),
2082            format!(
2083                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: www.alpha:443\r\nProxy-Authorization: {authorization}\r\nProxy-Authorization: {authorization}\r\n\r\n"
2084            )
2085            .into_bytes(),
2086            format!(
2087                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: www.alpha:443\r\nProxy-Authorization: {authorization}\r\nContent-Length: 1\r\n\r\nx"
2088            )
2089            .into_bytes(),
2090            format!(
2091                "CONNECT www.alpha:443 HTTP/1.1\r\nHost: www.alpha:443\r\nProxy-Authorization: {authorization}\r\nExpect: 100-continue\r\n\r\n"
2092            )
2093            .into_bytes(),
2094            format!(
2095                "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"
2096            )
2097            .into_bytes(),
2098        ] {
2099            assert!(proxy
2100                .admit_connect(
2101                    &engine,
2102                    "127.0.0.1:50000".parse().unwrap(),
2103                    &invalid,
2104                    1,
2105                )
2106                .is_err());
2107        }
2108    }
2109
2110    #[test]
2111    fn pending_tokens_are_bounded_cancelled_and_instance_scoped() {
2112        let (engine, mut first) = session([3; 16], 1);
2113        let (_, mut second) = session([3; 16], 1);
2114        let request = connect_request(&first.authorization_header_value());
2115        let pending = first
2116            .admit_connect(&engine, "127.0.0.1:50000".parse().unwrap(), &request, 10)
2117            .unwrap();
2118        assert_eq!(pending.admitted_at(), 10);
2119        assert_eq!(
2120            pending.expires_at(),
2121            10 + DEFAULT_MAXIMUM_PENDING_LIFETIME_SECONDS
2122        );
2123        assert!(matches!(
2124            first.admit_connect(&engine, "127.0.0.1:50001".parse().unwrap(), &request, 10,),
2125            Err(ProxyError::PendingLimit)
2126        ));
2127        assert!(matches!(
2128            second.cancel(&pending),
2129            Err(ProxyError::PendingMismatch)
2130        ));
2131        let replacement = first
2132            .admit_connect(
2133                &engine,
2134                "127.0.0.1:50002".parse().unwrap(),
2135                &request,
2136                pending.expires_at(),
2137            )
2138            .unwrap();
2139        assert!(matches!(
2140            first.cancel(&pending),
2141            Err(ProxyError::PendingMismatch)
2142        ));
2143        assert!(matches!(
2144            first.admit_connect(
2145                &engine,
2146                "127.0.0.1:50003".parse().unwrap(),
2147                &request,
2148                replacement.admitted_at() - 1,
2149            ),
2150            Err(ProxyError::ClockRollback)
2151        ));
2152        first.cancel(&replacement).unwrap();
2153    }
2154
2155    #[test]
2156    fn stale_runtime_and_authentication_challenge_fail_closed() {
2157        let (engine, mut proxy) = session([4; 16], 2);
2158        let challenge = String::from_utf8(proxy.authentication_challenge()).unwrap();
2159        assert!(challenge.starts_with("HTTP/1.1 407 Proxy Authentication Required\r\n"));
2160        assert!(challenge.contains(PROXY_AUTHENTICATE_HEADER));
2161        assert!(challenge.contains("Cache-Control: no-store"));
2162
2163        let before = engine.snapshot().unwrap().policy;
2164        let mut next = before.config();
2165        next.authenticated_authoritative_doh = false;
2166        engine.update_policy(before.generation(), next).unwrap();
2167        let request = connect_request(&proxy.authorization_header_value());
2168        assert!(matches!(
2169            proxy.admit_connect(&engine, "127.0.0.1:50000".parse().unwrap(), &request, 1,),
2170            Err(ProxyError::StaleRuntime)
2171        ));
2172    }
2173
2174    #[test]
2175    #[allow(
2176        clippy::too_many_lines,
2177        reason = "one lifecycle test covers atomic publication, replacement, revocation, restart, and expiry"
2178    )]
2179    fn provider_publication_is_atomic_bounded_and_restart_scoped() {
2180        let engine = active_engine([7; 16]);
2181        let decision = provider_decision("www.alpha");
2182        let mut proxy = proxy_for_engine(&engine, [90; 16], 4, 1);
2183        let initial_generation = proxy.registry_generation();
2184
2185        let stale_authority = provider_authority(&engine, &decision);
2186        assert!(matches!(
2187            proxy.publish_authority(
2188                &engine,
2189                initial_generation + 1,
2190                stale_authority,
2191                AUTHORITY_NOW,
2192            ),
2193            Err(ProxyError::StaleRegistryGeneration)
2194        ));
2195        assert_eq!(proxy.registry_generation(), initial_generation);
2196        assert_eq!(proxy.publication_count(), 0);
2197
2198        let authority = provider_authority(&engine, &decision);
2199        let decision_fingerprint = authority.decision_fingerprint();
2200        let authority_valid_from = authority.valid_from();
2201        let authority_valid_until = authority.valid_until();
2202        let admission = proxy
2203            .publish_authority(&engine, initial_generation, authority, AUTHORITY_NOW)
2204            .unwrap();
2205        assert_eq!(admission.host(), "www.alpha");
2206        assert_eq!(admission.origin_port(), 443);
2207        assert_eq!(admission.registry_generation(), initial_generation + 1);
2208        assert_eq!(proxy.publication_count(), 1);
2209        assert!(!format!("{admission:?}").contains("www.alpha"));
2210
2211        let other = provider_decision("other.alpha");
2212        let capacity_authority = provider_authority(&engine, &other);
2213        let capacity_generation = proxy.registry_generation();
2214        assert!(matches!(
2215            proxy.publish_authority(
2216                &engine,
2217                capacity_generation,
2218                capacity_authority,
2219                AUTHORITY_NOW,
2220            ),
2221            Err(ProxyError::PublicationLimit)
2222        ));
2223        assert_eq!(proxy.registry_generation(), capacity_generation);
2224        assert_eq!(proxy.publication_count(), 1);
2225
2226        let mut restarted = proxy_for_engine(&engine, [91; 16], 4, 1);
2227        let restarted_request =
2228            connect_request_for("www.alpha", &restarted.authorization_header_value());
2229        let restarted_pending = restarted
2230            .admit_connect(
2231                &engine,
2232                "127.0.0.1:50000".parse().unwrap(),
2233                &restarted_request,
2234                AUTHORITY_NOW,
2235            )
2236            .unwrap();
2237        let restarted_generation = restarted.registry_generation();
2238        assert!(matches!(
2239            restarted.authorize_connect(
2240                &engine,
2241                restarted_pending,
2242                &admission,
2243                restarted_generation,
2244                AUTHORITY_NOW,
2245            ),
2246            Err(ProxyError::PublicationMismatch)
2247        ));
2248
2249        let request = connect_request_for("www.alpha", &proxy.authorization_header_value());
2250        let pending = proxy
2251            .admit_connect(
2252                &engine,
2253                "127.0.0.1:50001".parse().unwrap(),
2254                &request,
2255                AUTHORITY_NOW,
2256            )
2257            .unwrap();
2258        let grant_generation = proxy.registry_generation();
2259        let grant = proxy
2260            .authorize_connect(
2261                &engine,
2262                pending,
2263                &admission,
2264                grant_generation,
2265                AUTHORITY_NOW,
2266            )
2267            .unwrap();
2268        assert_eq!(grant.host(), "www.alpha");
2269        assert_eq!(grant.scheme(), OriginScheme::Https);
2270        assert_eq!(grant.port(), 443);
2271        assert_eq!(grant.selected_namespace(), Namespace::Icann);
2272        assert_eq!(
2273            grant.authenticated_context(),
2274            AuthenticatedContextStatus::IcannWebPkiAuthenticatedAbsence
2275        );
2276        assert_eq!(grant.hns_network(), HnsNetwork::Regtest);
2277        assert_eq!(grant.service_port(), 443);
2278        assert_eq!(
2279            grant.tls_policy(),
2280            TlsTrustPolicy::WebPkiAuthenticatedAbsence
2281        );
2282        assert_eq!(grant.runtime_session(), [7; 16]);
2283        assert_eq!(grant.policy_generation(), 1);
2284        assert_eq!(grant.decision_fingerprint(), decision_fingerprint);
2285        assert_eq!(grant.authority_valid_from(), authority_valid_from);
2286        assert_eq!(grant.authority_valid_until(), authority_valid_until);
2287        assert_eq!(grant.endpoint(), proxy.endpoint());
2288        assert_eq!(grant.process_session(), [90; 16]);
2289        assert_eq!(grant.process_generation(), 1);
2290        assert_eq!(grant.listener_generation(), 1);
2291        assert_eq!(grant.registry_generation(), proxy.registry_generation());
2292        assert_eq!(grant.valid_from(), AUTHORITY_NOW);
2293        assert_eq!(
2294            grant.valid_until(),
2295            AUTHORITY_NOW + DEFAULT_MAXIMUM_GRANT_LIFETIME_SECONDS
2296        );
2297        let revalidation_generation = proxy.registry_generation();
2298        proxy
2299            .revalidate_tunnel_grant(&engine, &grant, revalidation_generation, AUTHORITY_NOW)
2300            .unwrap();
2301
2302        let replacement_authority = provider_authority(&engine, &decision);
2303        let previous_publication_generation = admission.publication_generation();
2304        let replacement_generation = proxy.registry_generation();
2305        let replacement = proxy
2306            .replace_authority(
2307                &engine,
2308                replacement_generation,
2309                admission,
2310                replacement_authority,
2311                AUTHORITY_NOW,
2312            )
2313            .unwrap();
2314        assert!(replacement.publication_generation() > previous_publication_generation);
2315        assert!(grant.registry_generation() < proxy.registry_generation());
2316        let stale_grant_generation = proxy.registry_generation();
2317        assert!(matches!(
2318            proxy.revalidate_tunnel_grant(&engine, &grant, stale_grant_generation, AUTHORITY_NOW,),
2319            Err(ProxyError::PublicationMismatch)
2320        ));
2321        let revocation_generation = proxy.registry_generation();
2322        let revoked_generation = proxy
2323            .revoke_authority(revocation_generation, replacement)
2324            .unwrap();
2325        assert_eq!(revoked_generation, proxy.registry_generation());
2326        assert_eq!(proxy.publication_count(), 0);
2327
2328        let mut reclaiming = proxy_for_engine_with_limits(
2329            &engine,
2330            [92; 16],
2331            ProxyLimits {
2332                maximum_publications: 1,
2333                maximum_publication_lifetime_seconds: 1,
2334                maximum_grant_lifetime_seconds: 1,
2335                ..ProxyLimits::default()
2336            },
2337        );
2338        let expiring_authority = provider_authority(&engine, &decision);
2339        let expiring_generation = reclaiming.registry_generation();
2340        let expired = reclaiming
2341            .publish_authority(
2342                &engine,
2343                expiring_generation,
2344                expiring_authority,
2345                AUTHORITY_NOW,
2346            )
2347            .unwrap();
2348        let reclaim_generation = reclaiming.registry_generation();
2349        let replacement_authority = provider_authority(&engine, &other);
2350        let reclaimed = reclaiming
2351            .publish_authority(
2352                &engine,
2353                reclaim_generation,
2354                replacement_authority,
2355                AUTHORITY_NOW + 1,
2356            )
2357            .unwrap();
2358        assert_eq!(reclaiming.registry_generation(), reclaim_generation + 1);
2359        assert_eq!(reclaiming.publication_count(), 1);
2360        assert_eq!(reclaimed.host(), "other.alpha");
2361        assert!(matches!(
2362            reclaiming.validate_admission(&expired),
2363            Err(ProxyError::PublicationMismatch)
2364        ));
2365    }
2366
2367    #[test]
2368    fn publication_survives_unrelated_authority_admissions() {
2369        let engine = active_engine([17; 16]);
2370        let decision = provider_decision("www.alpha");
2371        let mut proxy = proxy_for_engine(&engine, [93; 16], 2, 2);
2372        let generation = proxy.registry_generation();
2373        let admission = proxy
2374            .publish_authority(
2375                &engine,
2376                generation,
2377                provider_authority(&engine, &decision),
2378                AUTHORITY_NOW,
2379            )
2380            .unwrap();
2381
2382        let unrelated = provider_decision("other.alpha");
2383        let _unrelated_authority = provider_authority(&engine, &unrelated);
2384
2385        let request = connect_request_for("www.alpha", &proxy.authorization_header_value());
2386        let pending = proxy
2387            .admit_connect(
2388                &engine,
2389                "127.0.0.1:50010".parse().unwrap(),
2390                &request,
2391                AUTHORITY_NOW,
2392            )
2393            .unwrap();
2394        let generation = proxy.registry_generation();
2395        let grant = proxy
2396            .authorize_connect(&engine, pending, &admission, generation, AUTHORITY_NOW)
2397            .unwrap();
2398        proxy
2399            .revalidate_tunnel_grant(&engine, &grant, generation, AUTHORITY_NOW)
2400            .unwrap();
2401    }
2402
2403    #[test]
2404    fn invalidated_publication_is_reclaimed_before_capacity() {
2405        let engine = active_engine([18; 16]);
2406        let first = provider_decision("www.alpha");
2407        let second = provider_decision("other.alpha");
2408        let mut proxy = proxy_for_engine(&engine, [94; 16], 2, 1);
2409        let generation = proxy.registry_generation();
2410        let stale = proxy
2411            .publish_authority(
2412                &engine,
2413                generation,
2414                provider_authority(&engine, &first),
2415                AUTHORITY_NOW,
2416            )
2417            .unwrap();
2418
2419        engine
2420            .advance_authority_state(AuthorityState::Degraded)
2421            .unwrap();
2422        recover_active_engine(&engine);
2423
2424        let generation = proxy.registry_generation();
2425        let replacement = proxy
2426            .publish_authority(
2427                &engine,
2428                generation,
2429                provider_authority(&engine, &second),
2430                AUTHORITY_NOW,
2431            )
2432            .unwrap();
2433        assert_eq!(replacement.host(), "other.alpha");
2434        assert_eq!(proxy.publication_count(), 1);
2435        assert!(matches!(
2436            proxy.validate_admission(&stale),
2437            Err(ProxyError::PublicationMismatch)
2438        ));
2439    }
2440}