Skip to main content

hns_resolution_policy/
lib.rs

1//! Persistent, typed HNS resolution policy and evidence provenance.
2//!
3//! The transport plan deliberately has no operating-system or implicit
4//! public-recursive candidate. Explicit user consent may add one configured
5//! recursive HNS DoH transport as the terminal candidate. A policy mutation
6//! increments the generation, and completion under a stale generation is
7//! rejected even if a path is later re-enabled.
8
9#![forbid(unsafe_code)]
10#![allow(
11    clippy::doc_markdown,
12    clippy::missing_errors_doc,
13    clippy::module_name_repetitions,
14    clippy::struct_excessive_bools,
15    reason = "protocol acronyms, shared PolicyError, and explicit effect fields are intentional"
16)]
17
18use std::fmt;
19
20const PERSISTED_MAGIC: &[u8; 8] = b"HNSPOL1\0";
21const PERSISTED_SCHEMA: u16 = 3;
22const PERSISTED_SCHEMA_V2: u16 = 2;
23const LEGACY_PERSISTED_SCHEMA: u16 = 1;
24const PERSISTED_PAYLOAD_LEN: u16 = 16;
25/// Exact encoded policy snapshot length.
26pub const PERSISTED_POLICY_LEN: usize = 32;
27
28/// P2P DNS Relay requester behavior.
29#[repr(u8)]
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31pub enum DnsRelayRequesterPolicy {
32    /// Permit relay only in the policy-selected fallback position.
33    Auto = 0,
34    /// Never select or transmit through a DNS relay.
35    Disabled = 1,
36    /// Require relay as the terminal fallback if direct authority fails.
37    Required = 2,
38}
39
40impl TryFrom<u8> for DnsRelayRequesterPolicy {
41    type Error = PolicyError;
42
43    fn try_from(value: u8) -> Result<Self, Self::Error> {
44        match value {
45            0 => Ok(Self::Auto),
46            1 => Ok(Self::Disabled),
47            2 => Ok(Self::Required),
48            _ => Err(PolicyError::InvalidEncoding),
49        }
50    }
51}
52
53/// P2P Oblivious DNS requester behavior.
54#[repr(u8)]
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub enum ObliviousDnsPolicy {
57    /// ODoH must be the only experimental fallback.
58    Required = 0,
59    /// Prefer ODoH and prohibit privacy downgrade to direct relay.
60    Preferred = 1,
61    /// Prefer ODoH and permit a final direct-relay fallback.
62    DirectRelayAllowed = 2,
63    /// Never select or transmit through ODoH.
64    Disabled = 3,
65}
66
67impl TryFrom<u8> for ObliviousDnsPolicy {
68    type Error = PolicyError;
69
70    fn try_from(value: u8) -> Result<Self, Self::Error> {
71        match value {
72            0 => Ok(Self::Required),
73            1 => Ok(Self::Preferred),
74            2 => Ok(Self::DirectRelayAllowed),
75            3 => Ok(Self::Disabled),
76            _ => Err(PolicyError::InvalidEncoding),
77        }
78    }
79}
80
81/// Independent HNSR participation roles.
82///
83/// Requester/client and opaque relay participation default on and remain
84/// independently opt-out. Endpoint/output and rendezvous roles require
85/// separate explicit enablement, so one role can never grant another
86/// implicitly.
87#[derive(Clone, Copy, Debug, Eq, PartialEq)]
88pub struct HnsrPolicy {
89    bits: u8,
90}
91
92impl HnsrPolicy {
93    const CLIENT: u8 = 1 << 0;
94    const ENDPOINT: u8 = 1 << 1;
95    const RELAY: u8 = 1 << 2;
96    const RENDEZVOUS: u8 = 1 << 3;
97    const KNOWN_BITS: u8 = Self::CLIENT | Self::ENDPOINT | Self::RELAY | Self::RENDEZVOUS;
98
99    /// Disable every HNSR role.
100    #[must_use]
101    pub const fn disabled() -> Self {
102        Self { bits: 0 }
103    }
104
105    /// Default to opaque relay participation only.
106    #[must_use]
107    pub const fn relay_default() -> Self {
108        Self { bits: Self::RELAY }
109    }
110
111    /// Default to requester/client and opaque relay participation.
112    #[must_use]
113    pub const fn client_relay_default() -> Self {
114        Self::relay_default().with_requester(true)
115    }
116
117    /// Set requester/client participation independently.
118    #[must_use]
119    pub const fn with_requester(mut self, enabled: bool) -> Self {
120        self.bits = set_flag(self.bits, Self::CLIENT, enabled);
121        self
122    }
123
124    /// Set endpoint/output-node participation independently.
125    #[must_use]
126    pub const fn with_endpoint(mut self, enabled: bool) -> Self {
127        self.bits = set_flag(self.bits, Self::ENDPOINT, enabled);
128        self
129    }
130
131    /// Set opaque relay participation independently.
132    #[must_use]
133    pub const fn with_relay(mut self, enabled: bool) -> Self {
134        self.bits = set_flag(self.bits, Self::RELAY, enabled);
135        self
136    }
137
138    /// Set rendezvous-directory participation independently.
139    #[must_use]
140    pub const fn with_rendezvous(mut self, enabled: bool) -> Self {
141        self.bits = set_flag(self.bits, Self::RENDEZVOUS, enabled);
142        self
143    }
144
145    /// Whether this mode permits requester activity.
146    #[must_use]
147    pub const fn requester_enabled(self) -> bool {
148        self.bits & Self::CLIENT != 0
149    }
150
151    /// Whether endpoint/output-node activity is enabled.
152    #[must_use]
153    pub const fn endpoint_enabled(self) -> bool {
154        self.bits & Self::ENDPOINT != 0
155    }
156
157    /// Whether opaque relay activity is enabled.
158    #[must_use]
159    pub const fn relay_enabled(self) -> bool {
160        self.bits & Self::RELAY != 0
161    }
162
163    /// Whether rendezvous-directory activity is enabled.
164    #[must_use]
165    pub const fn rendezvous_enabled(self) -> bool {
166        self.bits & Self::RENDEZVOUS != 0
167    }
168
169    /// Whether this mode advertises any provider capability.
170    #[must_use]
171    pub const fn provider_enabled(self) -> bool {
172        self.provider_bits() != 0
173    }
174
175    /// Stable role bit representation for persistence and platform ABIs.
176    #[must_use]
177    pub const fn bits(self) -> u8 {
178        self.bits
179    }
180
181    /// Decode independent role bits.
182    pub const fn from_bits(bits: u8) -> Result<Self, PolicyError> {
183        if bits & !Self::KNOWN_BITS != 0 {
184            Err(PolicyError::InvalidEncoding)
185        } else {
186            Ok(Self { bits })
187        }
188    }
189
190    const fn provider_bits(self) -> u8 {
191        self.bits & (Self::ENDPOINT | Self::RELAY | Self::RENDEZVOUS)
192    }
193}
194
195impl Default for HnsrPolicy {
196    fn default() -> Self {
197        Self::client_relay_default()
198    }
199}
200
201const fn set_flag(bits: u8, flag: u8, enabled: bool) -> u8 {
202    if enabled { bits | flag } else { bits & !flag }
203}
204
205const fn legacy_hnsr_policy(value: u8) -> Result<HnsrPolicy, PolicyError> {
206    match value {
207        0 => Ok(HnsrPolicy::disabled()),
208        1 => Ok(HnsrPolicy::disabled().with_requester(true)),
209        2 => Ok(HnsrPolicy::disabled().with_endpoint(true)),
210        3 => Ok(HnsrPolicy::disabled().with_relay(true)),
211        4 => Ok(HnsrPolicy::disabled().with_rendezvous(true)),
212        5 => Ok(HnsrPolicy::disabled()
213            .with_requester(true)
214            .with_endpoint(true)),
215        6 => Ok(HnsrPolicy::disabled()
216            .with_requester(true)
217            .with_endpoint(true)
218            .with_relay(true)
219            .with_rendezvous(true)),
220        _ => Err(PolicyError::InvalidEncoding),
221    }
222}
223
224/// Experimental assignment profile.
225#[repr(u8)]
226#[derive(Clone, Copy, Debug, Eq, PartialEq)]
227pub enum WireProfile {
228    /// Shakescape Experimental V1, not an official Handshake assignment.
229    ShakescapeV1 = 0,
230    /// Future official assignment profile.
231    Official = 1,
232    /// Negotiate supported profiles without silent packet-number reuse.
233    Auto = 2,
234}
235
236impl TryFrom<u8> for WireProfile {
237    type Error = PolicyError;
238
239    fn try_from(value: u8) -> Result<Self, Self::Error> {
240        match value {
241            0 => Ok(Self::ShakescapeV1),
242            1 => Ok(Self::Official),
243            2 => Ok(Self::Auto),
244            _ => Err(PolicyError::InvalidEncoding),
245        }
246    }
247}
248
249/// Provider roles with opaque proxying default-on and output roles default-off.
250#[derive(Clone, Copy, Debug, Eq, PartialEq)]
251pub struct ProviderPolicy {
252    /// Offer bounded P2P DNS relay capacity.
253    pub dns_relay: bool,
254    /// Offer P2P ODoH proxy capacity.
255    pub odoh_proxy: bool,
256    /// Offer P2P ODoH target capacity.
257    pub odoh_target: bool,
258    /// Advertise market gossip while the market service is active.
259    pub market_gossip: bool,
260}
261
262impl Default for ProviderPolicy {
263    fn default() -> Self {
264        Self {
265            dns_relay: false,
266            odoh_proxy: true,
267            odoh_target: false,
268            market_gossip: false,
269        }
270    }
271}
272
273impl ProviderPolicy {
274    const DNS_RELAY: u16 = 1 << 0;
275    const ODOH_PROXY: u16 = 1 << 1;
276    const ODOH_TARGET: u16 = 1 << 2;
277    const MARKET_GOSSIP: u16 = 1 << 3;
278    const KNOWN_BITS: u16 =
279        Self::DNS_RELAY | Self::ODOH_PROXY | Self::ODOH_TARGET | Self::MARKET_GOSSIP;
280
281    const fn bits(self) -> u16 {
282        (if self.dns_relay { Self::DNS_RELAY } else { 0 })
283            | (if self.odoh_proxy { Self::ODOH_PROXY } else { 0 })
284            | (if self.odoh_target {
285                Self::ODOH_TARGET
286            } else {
287                0
288            })
289            | (if self.market_gossip {
290                Self::MARKET_GOSSIP
291            } else {
292                0
293            })
294    }
295
296    fn from_bits(bits: u16) -> Result<Self, PolicyError> {
297        if bits & !Self::KNOWN_BITS != 0 {
298            return Err(PolicyError::InvalidEncoding);
299        }
300        Ok(Self {
301            dns_relay: bits & Self::DNS_RELAY != 0,
302            odoh_proxy: bits & Self::ODOH_PROXY != 0,
303            odoh_target: bits & Self::ODOH_TARGET != 0,
304            market_gossip: bits & Self::MARKET_GOSSIP != 0,
305        })
306    }
307}
308
309/// Complete runtime policy, without persistence metadata.
310#[derive(Clone, Copy, Debug, Eq, PartialEq)]
311pub struct PolicyConfig {
312    /// P2P DNS Relay requester policy.
313    pub dns_relay_requester: DnsRelayRequesterPolicy,
314    /// P2P ODoH requester policy.
315    pub oblivious_dns: ObliviousDnsPolicy,
316    /// Independent HNSR requester/provider roles.
317    pub hnsr: HnsrPolicy,
318    /// Permit proof-authenticated authoritative DoH after direct UDP/TCP.
319    pub authenticated_authoritative_doh: bool,
320    /// Permit an explicitly user-configured recursive HNS DoH terminal fallback.
321    pub user_configured_recursive_hns_doh: bool,
322    /// Independent provider controls.
323    pub providers: ProviderPolicy,
324    /// Experimental assignment profile.
325    pub wire_profile: WireProfile,
326    /// Permit specifically bounded legacy compatibility on regtest only.
327    pub allow_legacy_regtest_compatibility: bool,
328}
329
330impl Default for PolicyConfig {
331    fn default() -> Self {
332        Self {
333            dns_relay_requester: DnsRelayRequesterPolicy::Auto,
334            oblivious_dns: ObliviousDnsPolicy::DirectRelayAllowed,
335            hnsr: HnsrPolicy::default(),
336            authenticated_authoritative_doh: true,
337            user_configured_recursive_hns_doh: false,
338            providers: ProviderPolicy::default(),
339            wire_profile: WireProfile::Auto,
340            allow_legacy_regtest_compatibility: true,
341        }
342    }
343}
344
345impl PolicyConfig {
346    /// Validate combinations whose individual typed controls conflict.
347    pub const fn validate(self) -> Result<(), PolicyError> {
348        if matches!(
349            self.oblivious_dns,
350            ObliviousDnsPolicy::Required | ObliviousDnsPolicy::Preferred
351        ) && matches!(self.dns_relay_requester, DnsRelayRequesterPolicy::Required)
352        {
353            return Err(PolicyError::ConflictingPolicies);
354        }
355        Ok(())
356    }
357}
358
359/// Persistent policy with a monotonic generation.
360#[derive(Clone, Copy, Debug, Eq, PartialEq)]
361pub struct PolicySnapshot {
362    generation: u64,
363    config: PolicyConfig,
364}
365
366impl Default for PolicySnapshot {
367    fn default() -> Self {
368        Self {
369            generation: 1,
370            config: PolicyConfig::default(),
371        }
372    }
373}
374
375impl PolicySnapshot {
376    /// Construct a checked snapshot.
377    pub const fn new(generation: u64, config: PolicyConfig) -> Result<Self, PolicyError> {
378        if generation == 0 {
379            return Err(PolicyError::ZeroGeneration);
380        }
381        if config.validate().is_err() {
382            return Err(PolicyError::ConflictingPolicies);
383        }
384        Ok(Self { generation, config })
385    }
386
387    /// Nonzero policy generation.
388    #[must_use]
389    pub const fn generation(self) -> u64 {
390        self.generation
391    }
392
393    /// Typed policy.
394    #[must_use]
395    pub const fn config(self) -> PolicyConfig {
396        self.config
397    }
398
399    /// Encode the versioned, checksummed persistence representation.
400    #[must_use]
401    pub fn encode(self) -> [u8; PERSISTED_POLICY_LEN] {
402        let mut output = [0u8; PERSISTED_POLICY_LEN];
403        output[..8].copy_from_slice(PERSISTED_MAGIC);
404        output[8..10].copy_from_slice(&PERSISTED_SCHEMA.to_be_bytes());
405        output[10..12].copy_from_slice(&PERSISTED_PAYLOAD_LEN.to_be_bytes());
406        output[12..20].copy_from_slice(&self.generation.to_be_bytes());
407        output[20] = self.config.dns_relay_requester as u8;
408        output[21] = self.config.oblivious_dns as u8;
409        output[22] = self.config.hnsr.bits();
410        output[23] = self.config.wire_profile as u8;
411        output[24..26].copy_from_slice(&self.config.providers.bits().to_be_bytes());
412        let settings = u16::from(self.config.authenticated_authoritative_doh)
413            | (u16::from(self.config.allow_legacy_regtest_compatibility) << 1)
414            | (u16::from(self.config.user_configured_recursive_hns_doh) << 2);
415        output[26..28].copy_from_slice(&settings.to_be_bytes());
416        let checksum = crc32(&output[..28]);
417        output[28..32].copy_from_slice(&checksum.to_be_bytes());
418        output
419    }
420
421    /// Decode a versioned snapshot, rejecting unknown flags and corruption.
422    pub fn decode(input: &[u8]) -> Result<Self, PolicyError> {
423        if input.len() != PERSISTED_POLICY_LEN || input.get(..8) != Some(PERSISTED_MAGIC.as_slice())
424        {
425            return Err(PolicyError::InvalidEncoding);
426        }
427        let schema = read_u16(input, 8)?;
428        if !matches!(
429            schema,
430            LEGACY_PERSISTED_SCHEMA | PERSISTED_SCHEMA_V2 | PERSISTED_SCHEMA
431        ) || read_u16(input, 10)? != PERSISTED_PAYLOAD_LEN
432        {
433            return Err(PolicyError::UnsupportedSchema);
434        }
435        let expected_crc = read_u32(input, 28)?;
436        if crc32(input.get(..28).ok_or(PolicyError::InvalidEncoding)?) != expected_crc {
437            return Err(PolicyError::ChecksumMismatch);
438        }
439        let generation = read_u64(input, 12)?;
440        if generation == 0 {
441            return Err(PolicyError::ZeroGeneration);
442        }
443        let provider_bits = read_u16(input, 24)?;
444        let settings = read_u16(input, 26)?;
445        let known_settings = if schema == PERSISTED_SCHEMA {
446            0b111
447        } else {
448            0b011
449        };
450        if settings & !known_settings != 0 {
451            return Err(PolicyError::InvalidEncoding);
452        }
453        let hnsr = if schema == LEGACY_PERSISTED_SCHEMA {
454            legacy_hnsr_policy(byte(input, 22)?)?
455        } else {
456            HnsrPolicy::from_bits(byte(input, 22)?)?
457        };
458        let config = PolicyConfig {
459            dns_relay_requester: DnsRelayRequesterPolicy::try_from(byte(input, 20)?)?,
460            oblivious_dns: ObliviousDnsPolicy::try_from(byte(input, 21)?)?,
461            hnsr,
462            wire_profile: WireProfile::try_from(byte(input, 23)?)?,
463            providers: ProviderPolicy::from_bits(provider_bits)?,
464            authenticated_authoritative_doh: settings & 1 != 0,
465            user_configured_recursive_hns_doh: schema == PERSISTED_SCHEMA && settings & 4 != 0,
466            allow_legacy_regtest_compatibility: settings & 2 != 0,
467        };
468        Self::new(generation, config)
469    }
470}
471
472/// Actual DNS transport, separate from validation authority.
473#[repr(u8)]
474#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
475pub enum ResolutionTransport {
476    /// UDP to a proof-derived delegated authority.
477    DirectAuthoritativeUdp = 0,
478    /// TCP to a proof-derived delegated authority.
479    DirectAuthoritativeTcp = 1,
480    /// DoH endpoint authenticated from local HNS/DNSSEC evidence.
481    AuthenticatedAuthoritativeDoh = 2,
482    /// Shakescape Experimental V1 ODoH intermediary path.
483    HandshakeP2pOdoh = 3,
484    /// Shakescape Experimental V1 recursive relay path.
485    HandshakeP2pDnsRelay = 4,
486    /// No transport succeeded.
487    Unavailable = 5,
488    /// TLS-authenticated validating DoH for the ICANN namespace.
489    ///
490    /// This is status provenance for the separate ICANN path and is never a
491    /// candidate in the fail-closed HNS [`TransportPlan`].
492    ValidatingIcannDoh = 6,
493    /// Explicitly user-configured recursive HNS DoH recovery transport.
494    ///
495    /// This is admitted only when the current policy binds affirmative user
496    /// consent. It is always terminal in the fail-closed HNS [`TransportPlan`].
497    UserConfiguredRecursiveHnsDoh = 7,
498    /// Origin data obtained directly from a locally verified HNS name proof.
499    ///
500    /// This is status provenance for a proof-contained result and is never a
501    /// network candidate in the fail-closed HNS [`TransportPlan`].
502    LocalHnsProof = 8,
503}
504
505impl TryFrom<u8> for ResolutionTransport {
506    type Error = PolicyError;
507
508    fn try_from(value: u8) -> Result<Self, Self::Error> {
509        match value {
510            0 => Ok(Self::DirectAuthoritativeUdp),
511            1 => Ok(Self::DirectAuthoritativeTcp),
512            2 => Ok(Self::AuthenticatedAuthoritativeDoh),
513            3 => Ok(Self::HandshakeP2pOdoh),
514            4 => Ok(Self::HandshakeP2pDnsRelay),
515            5 => Ok(Self::Unavailable),
516            6 => Ok(Self::ValidatingIcannDoh),
517            7 => Ok(Self::UserConfiguredRecursiveHnsDoh),
518            8 => Ok(Self::LocalHnsProof),
519            _ => Err(PolicyError::InvalidEncoding),
520        }
521    }
522}
523
524/// Ordered, fail-closed transport candidates.
525#[derive(Clone, Debug, Eq, PartialEq)]
526pub struct TransportPlan {
527    transports: Vec<ResolutionTransport>,
528}
529
530impl TransportPlan {
531    /// Construct the direct-authoritative-first plan for a policy.
532    #[must_use]
533    pub fn for_policy(config: PolicyConfig) -> Self {
534        let mut transports = vec![
535            ResolutionTransport::DirectAuthoritativeUdp,
536            ResolutionTransport::DirectAuthoritativeTcp,
537        ];
538        if config.authenticated_authoritative_doh {
539            transports.push(ResolutionTransport::AuthenticatedAuthoritativeDoh);
540        }
541        if config.oblivious_dns != ObliviousDnsPolicy::Disabled {
542            transports.push(ResolutionTransport::HandshakeP2pOdoh);
543        }
544        let relay_allowed = match config.oblivious_dns {
545            ObliviousDnsPolicy::Required | ObliviousDnsPolicy::Preferred => false,
546            ObliviousDnsPolicy::DirectRelayAllowed | ObliviousDnsPolicy::Disabled => {
547                config.dns_relay_requester != DnsRelayRequesterPolicy::Disabled
548            }
549        };
550        if relay_allowed {
551            transports.push(ResolutionTransport::HandshakeP2pDnsRelay);
552        }
553        if config.user_configured_recursive_hns_doh {
554            transports.push(ResolutionTransport::UserConfiguredRecursiveHnsDoh);
555        }
556        Self { transports }
557    }
558
559    /// Ordered candidates. No OS or implicit public-recursive candidate is
560    /// admitted here.
561    #[must_use]
562    pub fn as_slice(&self) -> &[ResolutionTransport] {
563        &self.transports
564    }
565
566    /// Whether the plan admits a transport.
567    #[must_use]
568    pub fn contains(&self, transport: ResolutionTransport) -> bool {
569        self.transports.contains(&transport)
570    }
571}
572
573/// Generation-bound permission to start one transport attempt.
574#[derive(Clone, Copy, Debug, Eq, PartialEq)]
575pub struct Admission {
576    /// Policy generation at admission.
577    pub policy_generation: u64,
578    /// Admitted transport.
579    pub transport: ResolutionTransport,
580}
581
582/// Required runtime actions after a policy mutation.
583#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
584pub struct PolicyChangeEffects {
585    /// Immediately stop admitting newly disabled work.
586    pub stop_admitting_disabled_work: bool,
587    /// Cancel or safely drain stale in-flight work.
588    pub cancel_or_drain_inflight: bool,
589    /// Clear cached requester path selections.
590    pub clear_requester_selections: bool,
591    /// Withdraw removed provider advertisements.
592    pub withdraw_advertisements: bool,
593    /// Withdraw removed HNSR routes.
594    pub withdraw_hnsr_routes: bool,
595    /// Revoke disabled ODoH target configurations.
596    pub revoke_target_configurations: bool,
597    /// Reconnect affected peers to renegotiate version service bits.
598    pub renegotiate_peer_connections: bool,
599    /// Publish updated structured status.
600    pub update_structured_status: bool,
601}
602
603/// Result of replacing policy.
604#[derive(Clone, Copy, Debug, Eq, PartialEq)]
605pub struct PolicyTransition {
606    /// Previous snapshot.
607    pub previous: PolicySnapshot,
608    /// Current snapshot.
609    pub current: PolicySnapshot,
610    /// Whether effective policy changed.
611    pub changed: bool,
612    /// Actions adapters must execute.
613    pub effects: PolicyChangeEffects,
614}
615
616/// Deterministic policy controller.
617#[derive(Clone, Debug, Eq, PartialEq)]
618pub struct PolicyController {
619    current: PolicySnapshot,
620}
621
622impl PolicyController {
623    /// Open from a checked persisted snapshot.
624    #[must_use]
625    pub const fn new(snapshot: PolicySnapshot) -> Self {
626        Self { current: snapshot }
627    }
628
629    /// Current snapshot.
630    #[must_use]
631    pub const fn snapshot(&self) -> PolicySnapshot {
632        self.current
633    }
634
635    /// Ordered current transport plan.
636    #[must_use]
637    pub fn transport_plan(&self) -> TransportPlan {
638        TransportPlan::for_policy(self.current.config)
639    }
640
641    /// Admit work only if the current policy contains its transport.
642    pub fn admit(&self, transport: ResolutionTransport) -> Result<Admission, PolicyError> {
643        if transport == ResolutionTransport::Unavailable
644            || !self.transport_plan().contains(transport)
645        {
646            return Err(PolicyError::TransportDisabled);
647        }
648        Ok(Admission {
649            policy_generation: self.current.generation,
650            transport,
651        })
652    }
653
654    /// Validate an in-flight completion against current generation and policy.
655    pub fn accept_completion(&self, admission: Admission) -> Result<(), PolicyError> {
656        if admission.policy_generation != self.current.generation {
657            return Err(PolicyError::StaleGeneration);
658        }
659        if !self.transport_plan().contains(admission.transport) {
660            return Err(PolicyError::TransportDisabled);
661        }
662        Ok(())
663    }
664
665    /// Replace policy using optimistic generation matching.
666    pub fn replace(
667        &mut self,
668        expected_generation: u64,
669        next_config: PolicyConfig,
670    ) -> Result<PolicyTransition, PolicyError> {
671        if expected_generation != self.current.generation {
672            return Err(PolicyError::StaleGeneration);
673        }
674        next_config.validate()?;
675        let previous = self.current;
676        if previous.config == next_config {
677            return Ok(PolicyTransition {
678                previous,
679                current: previous,
680                changed: false,
681                effects: PolicyChangeEffects::default(),
682            });
683        }
684        let generation = previous
685            .generation
686            .checked_add(1)
687            .ok_or(PolicyError::GenerationExhausted)?;
688        let current = PolicySnapshot {
689            generation,
690            config: next_config,
691        };
692        let effects = transition_effects(previous.config, next_config);
693        self.current = current;
694        Ok(PolicyTransition {
695            previous,
696            current,
697            changed: true,
698            effects,
699        })
700    }
701}
702
703fn transition_effects(previous: PolicyConfig, current: PolicyConfig) -> PolicyChangeEffects {
704    let requester_changed = previous.dns_relay_requester != current.dns_relay_requester
705        || previous.oblivious_dns != current.oblivious_dns
706        || previous.authenticated_authoritative_doh != current.authenticated_authoritative_doh
707        || previous.user_configured_recursive_hns_doh != current.user_configured_recursive_hns_doh
708        || previous.hnsr.requester_enabled() != current.hnsr.requester_enabled();
709    let hnsr_providers_changed = previous.hnsr.provider_bits() != current.hnsr.provider_bits();
710    let providers_changed = previous.providers != current.providers || hnsr_providers_changed;
711    let removed_provider = (previous.providers.bits() & !current.providers.bits()) != 0
712        || (previous.hnsr.provider_bits() & !current.hnsr.provider_bits()) != 0;
713    PolicyChangeEffects {
714        stop_admitting_disabled_work: true,
715        cancel_or_drain_inflight: true,
716        clear_requester_selections: requester_changed,
717        withdraw_advertisements: removed_provider,
718        withdraw_hnsr_routes: (previous.hnsr.provider_bits() & !current.hnsr.provider_bits()) != 0,
719        revoke_target_configurations: previous.providers.odoh_target
720            && !current.providers.odoh_target,
721        renegotiate_peer_connections: providers_changed
722            || previous.wire_profile != current.wire_profile,
723        update_structured_status: true,
724    }
725}
726
727/// Explicit local evidence state for browser observability.
728#[repr(u8)]
729#[derive(Clone, Copy, Debug, Eq, PartialEq)]
730pub enum EvidenceState {
731    /// Locally verified.
732    Verified = 0,
733    /// Locally checked and failed.
734    Failed = 1,
735    /// No acceptable evidence was available.
736    Unavailable = 2,
737    /// The required evidence form or algorithm is unsupported.
738    Unsupported = 3,
739    /// Validation has not been attempted.
740    NotAttempted = 4,
741    /// Previously valid evidence is no longer current.
742    Stale = 5,
743    /// Evidence was invalidated by a policy or runtime generation change.
744    Revoked = 6,
745}
746
747/// Local validation evidence required for HNS HTTPS.
748#[derive(Clone, Copy, Debug, Eq, PartialEq)]
749pub struct ValidationEvidence {
750    /// Verified Handshake state and Urkel proof.
751    pub hns_proof: EvidenceState,
752    /// Locally verified DNSSEC chain.
753    pub dnssec: EvidenceState,
754    /// Exact supported TLSA result.
755    pub tlsa: EvidenceState,
756    /// Local DANE origin result.
757    pub dane: EvidenceState,
758    /// Chain currency sufficiency.
759    pub chain_current: EvidenceState,
760    /// Origin SNI match.
761    pub origin_sni: EvidenceState,
762}
763
764impl ValidationEvidence {
765    /// Initial state before any HNS HTTPS validation work.
766    #[must_use]
767    pub const fn not_attempted() -> Self {
768        Self {
769            hns_proof: EvidenceState::NotAttempted,
770            dnssec: EvidenceState::NotAttempted,
771            tlsa: EvidenceState::NotAttempted,
772            dane: EvidenceState::NotAttempted,
773            chain_current: EvidenceState::NotAttempted,
774            origin_sni: EvidenceState::NotAttempted,
775        }
776    }
777
778    /// State after a policy/runtime generation revokes prior work.
779    #[must_use]
780    pub const fn revoked() -> Self {
781        Self {
782            hns_proof: EvidenceState::Revoked,
783            dnssec: EvidenceState::Revoked,
784            tlsa: EvidenceState::Revoked,
785            dane: EvidenceState::Revoked,
786            chain_current: EvidenceState::Revoked,
787            origin_sni: EvidenceState::Revoked,
788        }
789    }
790
791    /// Whether all required local evidence is verified.
792    #[must_use]
793    pub const fn fully_verified(self) -> bool {
794        matches!(self.hns_proof, EvidenceState::Verified)
795            && matches!(self.dnssec, EvidenceState::Verified)
796            && matches!(self.tlsa, EvidenceState::Verified)
797            && matches!(self.dane, EvidenceState::Verified)
798            && matches!(self.chain_current, EvidenceState::Verified)
799            && matches!(self.origin_sni, EvidenceState::Verified)
800    }
801}
802
803/// Handshake network.
804#[repr(u8)]
805#[derive(Clone, Copy, Debug, Eq, PartialEq)]
806pub enum Network {
807    /// Main network.
808    Mainnet = 0,
809    /// Public test network.
810    Testnet = 1,
811    /// Local regression network.
812    Regtest = 2,
813    /// In-memory simulation network.
814    Simnet = 3,
815}
816
817/// Locally authenticated chain anchor.
818#[derive(Clone, Copy, Debug, Eq, PartialEq)]
819pub struct ChainAnchor {
820    /// Validated header height.
821    pub height: u32,
822    /// Validated name-tree root.
823    pub tree_root: [u8; 32],
824}
825
826/// Structured resolution provenance.
827#[derive(Clone, Debug, Eq, PartialEq)]
828pub struct ResolutionProvenance {
829    /// Status schema version.
830    pub schema_version: u16,
831    /// Caller-supplied runtime session identifier.
832    pub runtime_session: [u8; 16],
833    /// Runtime generation.
834    pub runtime_generation: u64,
835    /// Policy generation.
836    pub policy_generation: u64,
837    /// Monotonic event sequence.
838    pub event_sequence: u64,
839    /// Handshake network.
840    pub network: Network,
841    /// Locally validated chain anchor, if available.
842    pub chain_anchor: Option<ChainAnchor>,
843    /// Actual selected transport.
844    pub transport: ResolutionTransport,
845    /// Remote relay peer identity, if applicable.
846    pub peer_identity: Option<String>,
847    /// ODoH proxy identity, if applicable.
848    pub proxy_identity: Option<String>,
849    /// ODoH target identity, if applicable.
850    pub target_identity: Option<String>,
851    /// Whether privacy downgraded to direct relay.
852    pub direct_relay_fallback: bool,
853    /// Experimental assignment profile.
854    pub registry_profile: WireProfile,
855    /// Local validation evidence.
856    pub evidence: ValidationEvidence,
857    /// Whether a remote DNS response asserted AD.
858    pub untrusted_ad_claim: bool,
859}
860
861impl ResolutionProvenance {
862    /// Require all local HNS HTTPS evidence, independent of transport.
863    pub const fn require_verified_hns_https(&self) -> Result<(), PolicyError> {
864        if self.evidence.fully_verified() {
865            Ok(())
866        } else {
867            Err(PolicyError::UnverifiedEvidence)
868        }
869    }
870}
871
872/// Policy, persistence, admission, or evidence failure.
873#[derive(Clone, Copy, Debug, Eq, PartialEq)]
874#[non_exhaustive]
875pub enum PolicyError {
876    /// Persisted bytes are malformed or contain unknown bits.
877    InvalidEncoding,
878    /// Persisted schema is not supported.
879    UnsupportedSchema,
880    /// Persisted checksum does not match.
881    ChecksumMismatch,
882    /// Generations must start at one.
883    ZeroGeneration,
884    /// A generation comparison failed.
885    StaleGeneration,
886    /// No later generation can be represented.
887    GenerationExhausted,
888    /// The selected transport is disabled.
889    TransportDisabled,
890    /// Required local HNS/DNSSEC/TLSA/DANE evidence is not all verified.
891    UnverifiedEvidence,
892    /// Typed requester policies express mutually exclusive requirements.
893    ConflictingPolicies,
894}
895
896impl fmt::Display for PolicyError {
897    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
898        formatter.write_str(match self {
899            Self::InvalidEncoding => "invalid persisted policy encoding",
900            Self::UnsupportedSchema => "unsupported persisted policy schema",
901            Self::ChecksumMismatch => "persisted policy checksum mismatch",
902            Self::ZeroGeneration => "policy generation must be nonzero",
903            Self::StaleGeneration => "stale policy generation",
904            Self::GenerationExhausted => "policy generation exhausted",
905            Self::TransportDisabled => "transport is disabled by policy",
906            Self::UnverifiedEvidence => "required local validation evidence is not verified",
907            Self::ConflictingPolicies => "requester policy requirements conflict",
908        })
909    }
910}
911
912impl std::error::Error for PolicyError {}
913
914fn crc32(input: &[u8]) -> u32 {
915    let mut crc = u32::MAX;
916    for byte in input {
917        crc ^= u32::from(*byte);
918        for _ in 0..8 {
919            let mask = 0u32.wrapping_sub(crc & 1);
920            crc = (crc >> 1) ^ (0xedb8_8320 & mask);
921        }
922    }
923    !crc
924}
925
926fn byte(input: &[u8], offset: usize) -> Result<u8, PolicyError> {
927    input
928        .get(offset)
929        .copied()
930        .ok_or(PolicyError::InvalidEncoding)
931}
932
933fn read_u16(input: &[u8], offset: usize) -> Result<u16, PolicyError> {
934    let value: [u8; 2] = input
935        .get(offset..offset + 2)
936        .ok_or(PolicyError::InvalidEncoding)?
937        .try_into()
938        .map_err(|_| PolicyError::InvalidEncoding)?;
939    Ok(u16::from_be_bytes(value))
940}
941
942fn read_u32(input: &[u8], offset: usize) -> Result<u32, PolicyError> {
943    let value: [u8; 4] = input
944        .get(offset..offset + 4)
945        .ok_or(PolicyError::InvalidEncoding)?
946        .try_into()
947        .map_err(|_| PolicyError::InvalidEncoding)?;
948    Ok(u32::from_be_bytes(value))
949}
950
951fn read_u64(input: &[u8], offset: usize) -> Result<u64, PolicyError> {
952    let value: [u8; 8] = input
953        .get(offset..offset + 8)
954        .ok_or(PolicyError::InvalidEncoding)?
955        .try_into()
956        .map_err(|_| PolicyError::InvalidEncoding)?;
957    Ok(u64::from_be_bytes(value))
958}
959
960#[cfg(test)]
961#[allow(
962    clippy::unwrap_used,
963    clippy::indexing_slicing,
964    reason = "tests intentionally fail immediately on invalid fixtures"
965)]
966mod tests {
967    use super::*;
968
969    #[test]
970    fn transport_discriminants_are_stable_and_recursive_doh_requires_consent() {
971        assert_eq!(ResolutionTransport::DirectAuthoritativeUdp as u8, 0);
972        assert_eq!(ResolutionTransport::DirectAuthoritativeTcp as u8, 1);
973        assert_eq!(ResolutionTransport::AuthenticatedAuthoritativeDoh as u8, 2);
974        assert_eq!(ResolutionTransport::HandshakeP2pOdoh as u8, 3);
975        assert_eq!(ResolutionTransport::HandshakeP2pDnsRelay as u8, 4);
976        assert_eq!(ResolutionTransport::Unavailable as u8, 5);
977        assert_eq!(ResolutionTransport::ValidatingIcannDoh as u8, 6);
978        assert_eq!(ResolutionTransport::UserConfiguredRecursiveHnsDoh as u8, 7);
979        assert_eq!(ResolutionTransport::LocalHnsProof as u8, 8);
980        assert_eq!(
981            ResolutionTransport::try_from(6).unwrap(),
982            ResolutionTransport::ValidatingIcannDoh
983        );
984        assert_eq!(
985            ResolutionTransport::try_from(7).unwrap(),
986            ResolutionTransport::UserConfiguredRecursiveHnsDoh
987        );
988        assert_eq!(
989            ResolutionTransport::try_from(8).unwrap(),
990            ResolutionTransport::LocalHnsProof
991        );
992        assert!(
993            !TransportPlan::for_policy(PolicyConfig::default())
994                .contains(ResolutionTransport::ValidatingIcannDoh)
995        );
996        assert!(
997            !TransportPlan::for_policy(PolicyConfig::default())
998                .contains(ResolutionTransport::UserConfiguredRecursiveHnsDoh)
999        );
1000        assert!(
1001            !TransportPlan::for_policy(PolicyConfig::default())
1002                .contains(ResolutionTransport::LocalHnsProof)
1003        );
1004
1005        let config = PolicyConfig {
1006            user_configured_recursive_hns_doh: true,
1007            ..PolicyConfig::default()
1008        };
1009        let plan = TransportPlan::for_policy(config);
1010        assert_eq!(
1011            plan.as_slice().last(),
1012            Some(&ResolutionTransport::UserConfiguredRecursiveHnsDoh)
1013        );
1014        let controller = PolicyController::new(PolicySnapshot::new(1, config).unwrap());
1015        assert_eq!(
1016            controller.admit(ResolutionTransport::LocalHnsProof),
1017            Err(PolicyError::TransportDisabled)
1018        );
1019    }
1020
1021    #[test]
1022    fn defaults_are_direct_first_with_client_relay_opt_out_and_output_opt_in() {
1023        let snapshot = PolicySnapshot::default();
1024        let plan = TransportPlan::for_policy(snapshot.config);
1025
1026        assert_eq!(
1027            plan.as_slice(),
1028            &[
1029                ResolutionTransport::DirectAuthoritativeUdp,
1030                ResolutionTransport::DirectAuthoritativeTcp,
1031                ResolutionTransport::AuthenticatedAuthoritativeDoh,
1032                ResolutionTransport::HandshakeP2pOdoh,
1033                ResolutionTransport::HandshakeP2pDnsRelay,
1034            ]
1035        );
1036        assert!(!snapshot.config.providers.dns_relay);
1037        assert!(snapshot.config.providers.odoh_proxy);
1038        assert!(!snapshot.config.providers.odoh_target);
1039        assert!(snapshot.config.hnsr.relay_enabled());
1040        assert!(!snapshot.config.hnsr.endpoint_enabled());
1041        assert!(snapshot.config.hnsr.requester_enabled());
1042        assert!(!snapshot.config.hnsr.rendezvous_enabled());
1043        assert!(!snapshot.config.user_configured_recursive_hns_doh);
1044        assert_eq!(snapshot.config.wire_profile, WireProfile::Auto);
1045    }
1046
1047    #[test]
1048    fn requester_opt_out_removes_every_hidden_path() {
1049        let config = PolicyConfig {
1050            dns_relay_requester: DnsRelayRequesterPolicy::Disabled,
1051            oblivious_dns: ObliviousDnsPolicy::Disabled,
1052            ..PolicyConfig::default()
1053        };
1054        let plan = TransportPlan::for_policy(config);
1055
1056        assert!(!plan.contains(ResolutionTransport::HandshakeP2pOdoh));
1057        assert!(!plan.contains(ResolutionTransport::HandshakeP2pDnsRelay));
1058        assert_eq!(
1059            plan.as_slice(),
1060            &[
1061                ResolutionTransport::DirectAuthoritativeUdp,
1062                ResolutionTransport::DirectAuthoritativeTcp,
1063                ResolutionTransport::AuthenticatedAuthoritativeDoh,
1064            ]
1065        );
1066    }
1067
1068    #[test]
1069    fn preferred_odoh_does_not_silently_downgrade_privacy() {
1070        let config = PolicyConfig {
1071            oblivious_dns: ObliviousDnsPolicy::Preferred,
1072            ..PolicyConfig::default()
1073        };
1074        let plan = TransportPlan::for_policy(config);
1075
1076        assert!(plan.contains(ResolutionTransport::HandshakeP2pOdoh));
1077        assert!(!plan.contains(ResolutionTransport::HandshakeP2pDnsRelay));
1078    }
1079
1080    #[test]
1081    fn conflicting_required_privacy_modes_are_rejected() {
1082        let config = PolicyConfig {
1083            dns_relay_requester: DnsRelayRequesterPolicy::Required,
1084            oblivious_dns: ObliviousDnsPolicy::Required,
1085            ..PolicyConfig::default()
1086        };
1087        assert_eq!(
1088            PolicySnapshot::new(1, config),
1089            Err(PolicyError::ConflictingPolicies)
1090        );
1091
1092        let mut controller = PolicyController::new(PolicySnapshot::default());
1093        assert_eq!(
1094            controller.replace(1, config),
1095            Err(PolicyError::ConflictingPolicies)
1096        );
1097        assert_eq!(controller.snapshot(), PolicySnapshot::default());
1098    }
1099
1100    #[test]
1101    fn snapshot_round_trips_and_detects_mutation() {
1102        let snapshot = PolicySnapshot::default();
1103        let encoded = snapshot.encode();
1104        assert_eq!(encoded.len(), PERSISTED_POLICY_LEN);
1105        assert_eq!(read_u16(&encoded, 8).unwrap(), PERSISTED_SCHEMA);
1106        assert_eq!(PolicySnapshot::decode(&encoded).unwrap(), snapshot);
1107
1108        let mut mutated = encoded;
1109        mutated[21] ^= 1;
1110        assert_eq!(
1111            PolicySnapshot::decode(&mutated),
1112            Err(PolicyError::ChecksumMismatch)
1113        );
1114
1115        let explicit_opt_out = PolicyConfig {
1116            dns_relay_requester: DnsRelayRequesterPolicy::Disabled,
1117            oblivious_dns: ObliviousDnsPolicy::Disabled,
1118            hnsr: HnsrPolicy::disabled(),
1119            providers: ProviderPolicy {
1120                dns_relay: false,
1121                odoh_proxy: false,
1122                odoh_target: false,
1123                market_gossip: false,
1124            },
1125            ..PolicyConfig::default()
1126        };
1127        let stored = PolicySnapshot::new(7, explicit_opt_out).unwrap().encode();
1128        assert_eq!(
1129            PolicySnapshot::decode(&stored).unwrap().config(),
1130            explicit_opt_out
1131        );
1132    }
1133
1134    #[test]
1135    fn schema_three_round_trips_recursive_doh_consent_in_fixed_length() {
1136        let config = PolicyConfig {
1137            user_configured_recursive_hns_doh: true,
1138            ..PolicyConfig::default()
1139        };
1140        let snapshot = PolicySnapshot::new(9, config).unwrap();
1141        let encoded = snapshot.encode();
1142
1143        assert_eq!(encoded.len(), 32);
1144        assert_eq!(read_u16(&encoded, 8).unwrap(), PERSISTED_SCHEMA);
1145        assert_eq!(read_u16(&encoded, 26).unwrap() & 4, 4);
1146        assert_eq!(PolicySnapshot::decode(&encoded).unwrap(), snapshot);
1147    }
1148
1149    #[test]
1150    fn schema_two_migrates_without_granting_recursive_doh_consent() {
1151        let mut previous = PolicySnapshot::default().encode();
1152        previous[8..10].copy_from_slice(&PERSISTED_SCHEMA_V2.to_be_bytes());
1153        let checksum = crc32(&previous[..28]);
1154        previous[28..32].copy_from_slice(&checksum.to_be_bytes());
1155
1156        let migrated = PolicySnapshot::decode(&previous).unwrap();
1157
1158        assert!(!migrated.config().user_configured_recursive_hns_doh);
1159        assert_eq!(read_u16(&migrated.encode(), 8).unwrap(), PERSISTED_SCHEMA);
1160
1161        let mut mislabeled = previous;
1162        let settings = read_u16(&mislabeled, 26).unwrap() | 4;
1163        mislabeled[26..28].copy_from_slice(&settings.to_be_bytes());
1164        let checksum = crc32(&mislabeled[..28]);
1165        mislabeled[28..32].copy_from_slice(&checksum.to_be_bytes());
1166        assert_eq!(
1167            PolicySnapshot::decode(&mislabeled),
1168            Err(PolicyError::InvalidEncoding)
1169        );
1170    }
1171
1172    #[test]
1173    fn schema_one_roles_migrate_without_granting_new_consent() {
1174        let mut legacy = PolicySnapshot::default().encode();
1175        legacy[8..10].copy_from_slice(&LEGACY_PERSISTED_SCHEMA.to_be_bytes());
1176        legacy[22] = 0;
1177        legacy[24..26].copy_from_slice(&0u16.to_be_bytes());
1178        let checksum = crc32(&legacy[..28]);
1179        legacy[28..32].copy_from_slice(&checksum.to_be_bytes());
1180
1181        let migrated = PolicySnapshot::decode(&legacy).unwrap();
1182
1183        assert_eq!(migrated.generation(), 1);
1184        assert_eq!(migrated.config().hnsr, HnsrPolicy::disabled());
1185        assert!(!migrated.config().user_configured_recursive_hns_doh);
1186        assert_eq!(
1187            migrated.config().providers,
1188            ProviderPolicy {
1189                dns_relay: false,
1190                odoh_proxy: false,
1191                odoh_target: false,
1192                market_gossip: false,
1193            }
1194        );
1195        assert_eq!(read_u16(&migrated.encode(), 8).unwrap(), PERSISTED_SCHEMA);
1196    }
1197
1198    #[test]
1199    fn schema_one_enum_values_are_not_reinterpreted_as_role_bits() {
1200        let mut legacy = PolicySnapshot::default().encode();
1201        legacy[8..10].copy_from_slice(&LEGACY_PERSISTED_SCHEMA.to_be_bytes());
1202        legacy[22] = 3;
1203        let checksum = crc32(&legacy[..28]);
1204        legacy[28..32].copy_from_slice(&checksum.to_be_bytes());
1205
1206        let migrated = PolicySnapshot::decode(&legacy).unwrap().config().hnsr;
1207
1208        assert!(migrated.relay_enabled());
1209        assert!(!migrated.requester_enabled());
1210        assert!(!migrated.endpoint_enabled());
1211        assert!(!migrated.rendezvous_enabled());
1212
1213        let current = HnsrPolicy::from_bits(3).unwrap();
1214        assert!(current.requester_enabled());
1215        assert!(current.endpoint_enabled());
1216        assert!(!current.relay_enabled());
1217    }
1218
1219    #[test]
1220    fn relay_and_output_node_consent_are_independent() {
1221        let client_relay = PolicyConfig::default();
1222        assert!(client_relay.hnsr.requester_enabled());
1223        assert!(client_relay.hnsr.relay_enabled());
1224        assert!(!client_relay.hnsr.endpoint_enabled());
1225        assert!(client_relay.providers.odoh_proxy);
1226        assert!(!client_relay.providers.odoh_target);
1227
1228        let mut output_enabled = client_relay;
1229        output_enabled.hnsr = output_enabled.hnsr.with_endpoint(true);
1230        output_enabled.providers.odoh_target = true;
1231        assert!(output_enabled.hnsr.relay_enabled());
1232        assert!(output_enabled.hnsr.endpoint_enabled());
1233
1234        output_enabled.hnsr = output_enabled.hnsr.with_relay(false);
1235        output_enabled.providers.odoh_proxy = false;
1236        assert!(!output_enabled.hnsr.relay_enabled());
1237        assert!(output_enabled.hnsr.endpoint_enabled());
1238        assert!(!output_enabled.providers.odoh_proxy);
1239        assert!(output_enabled.providers.odoh_target);
1240    }
1241
1242    #[test]
1243    fn policy_change_revokes_stale_completions() {
1244        let mut controller = PolicyController::new(PolicySnapshot::default());
1245        let admission = controller
1246            .admit(ResolutionTransport::HandshakeP2pDnsRelay)
1247            .unwrap();
1248        let mut next = controller.snapshot().config;
1249        next.dns_relay_requester = DnsRelayRequesterPolicy::Disabled;
1250        let transition = controller.replace(1, next).unwrap();
1251
1252        assert_eq!(transition.current.generation, 2);
1253        assert!(transition.effects.stop_admitting_disabled_work);
1254        assert!(transition.effects.cancel_or_drain_inflight);
1255        assert!(transition.effects.clear_requester_selections);
1256        assert_eq!(
1257            controller.accept_completion(admission),
1258            Err(PolicyError::StaleGeneration)
1259        );
1260        assert_eq!(
1261            controller.admit(ResolutionTransport::HandshakeP2pDnsRelay),
1262            Err(PolicyError::TransportDisabled)
1263        );
1264    }
1265
1266    #[test]
1267    fn recursive_doh_opt_out_revokes_admission_and_stale_completion() {
1268        let enabled = PolicyConfig {
1269            user_configured_recursive_hns_doh: true,
1270            ..PolicyConfig::default()
1271        };
1272        let mut controller = PolicyController::new(PolicySnapshot::new(11, enabled).unwrap());
1273        let admission = controller
1274            .admit(ResolutionTransport::UserConfiguredRecursiveHnsDoh)
1275            .unwrap();
1276        let mut disabled = enabled;
1277        disabled.user_configured_recursive_hns_doh = false;
1278
1279        let transition = controller.replace(11, disabled).unwrap();
1280
1281        assert_eq!(transition.current.generation(), 12);
1282        assert!(transition.effects.stop_admitting_disabled_work);
1283        assert!(transition.effects.cancel_or_drain_inflight);
1284        assert!(transition.effects.clear_requester_selections);
1285        assert_eq!(
1286            controller.accept_completion(admission),
1287            Err(PolicyError::StaleGeneration)
1288        );
1289        assert_eq!(
1290            controller.admit(ResolutionTransport::UserConfiguredRecursiveHnsDoh),
1291            Err(PolicyError::TransportDisabled)
1292        );
1293    }
1294
1295    #[test]
1296    fn provider_disable_requests_withdrawal_and_renegotiation() {
1297        let mut config = PolicyConfig::default();
1298        config.providers.dns_relay = true;
1299        config.providers.odoh_target = true;
1300        config.hnsr = HnsrPolicy::default()
1301            .with_requester(true)
1302            .with_endpoint(true)
1303            .with_rendezvous(true);
1304        let mut controller = PolicyController::new(PolicySnapshot::new(7, config).unwrap());
1305        let mut next = config;
1306        next.providers = ProviderPolicy {
1307            dns_relay: false,
1308            odoh_proxy: false,
1309            odoh_target: false,
1310            market_gossip: false,
1311        };
1312        next.hnsr = HnsrPolicy::disabled();
1313        let transition = controller.replace(7, next).unwrap();
1314
1315        assert!(transition.effects.withdraw_advertisements);
1316        assert!(transition.effects.withdraw_hnsr_routes);
1317        assert!(transition.effects.revoke_target_configurations);
1318        assert!(transition.effects.renegotiate_peer_connections);
1319    }
1320
1321    #[test]
1322    fn requester_change_does_not_mutate_provider_consent() {
1323        let mut config = PolicyConfig::default();
1324        config.hnsr = config.hnsr.with_requester(false);
1325        let mut controller = PolicyController::new(PolicySnapshot::new(4, config).unwrap());
1326        let mut next = config;
1327        next.hnsr = next.hnsr.with_requester(true);
1328
1329        let transition = controller.replace(4, next).unwrap();
1330
1331        assert!(transition.effects.clear_requester_selections);
1332        assert!(!transition.effects.withdraw_advertisements);
1333        assert!(!transition.effects.withdraw_hnsr_routes);
1334        assert!(!transition.effects.renegotiate_peer_connections);
1335        assert!(transition.current.config().hnsr.relay_enabled());
1336        assert!(transition.current.config().hnsr.requester_enabled());
1337    }
1338
1339    #[test]
1340    fn identical_policy_does_not_churn_generation() {
1341        let mut controller = PolicyController::new(PolicySnapshot::default());
1342        let transition = controller.replace(1, PolicyConfig::default()).unwrap();
1343
1344        assert!(!transition.changed);
1345        assert_eq!(transition.current.generation, 1);
1346        assert_eq!(transition.effects, PolicyChangeEffects::default());
1347    }
1348
1349    #[test]
1350    fn transport_never_substitutes_for_local_evidence() {
1351        let provenance = ResolutionProvenance {
1352            schema_version: 1,
1353            runtime_session: [1; 16],
1354            runtime_generation: 1,
1355            policy_generation: 1,
1356            event_sequence: 1,
1357            network: Network::Mainnet,
1358            chain_anchor: None,
1359            transport: ResolutionTransport::HandshakeP2pOdoh,
1360            peer_identity: None,
1361            proxy_identity: Some("proxy".to_owned()),
1362            target_identity: Some("target".to_owned()),
1363            direct_relay_fallback: false,
1364            registry_profile: WireProfile::ShakescapeV1,
1365            evidence: ValidationEvidence {
1366                hns_proof: EvidenceState::Verified,
1367                dnssec: EvidenceState::Verified,
1368                tlsa: EvidenceState::Unavailable,
1369                dane: EvidenceState::Unavailable,
1370                chain_current: EvidenceState::Verified,
1371                origin_sni: EvidenceState::Verified,
1372            },
1373            untrusted_ad_claim: true,
1374        };
1375
1376        assert_eq!(
1377            provenance.require_verified_hns_https(),
1378            Err(PolicyError::UnverifiedEvidence)
1379        );
1380    }
1381}