Skip to main content

hns_dane_engine_ffi/
lib.rs

1//! Versioned C ABI for [`hns_dane_engine`].
2//!
3//! Every entry point catches Rust panics. Pointer validity, allocation
4//! ownership, and buffer lengths remain explicit caller obligations documented
5//! in `include/hns_dane_engine.h`.
6
7#![allow(
8    clippy::doc_markdown,
9    clippy::missing_errors_doc,
10    clippy::module_name_repetitions,
11    reason = "the C header is the normative error contract and uses protocol acronyms"
12)]
13
14use std::panic::{AssertUnwindSafe, catch_unwind};
15use std::slice;
16use std::str;
17use std::sync::Arc;
18
19use hns_dane::DaneLimits;
20use hns_dane_engine::{
21    AuthorityState, CompletionContext, Engine, EngineConfig, EngineError, LocalDanePrerequisites,
22    ProviderAuthorityContext, ResolutionAttempt, RuntimeSessionId,
23};
24use hns_dns_wire::{Name, ParseLimits, Query, RecordType};
25use hns_resolution_policy::{
26    DnsRelayRequesterPolicy, EvidenceState, HnsrPolicy, Network, ObliviousDnsPolicy, PolicyConfig,
27    PolicyError, PolicySnapshot, ProviderPolicy, ResolutionTransport, WireProfile,
28};
29
30/// C ABI version implemented by this library.
31pub const ABI_VERSION: u32 = 1;
32/// Policy ABI version that exposes recursive-HNS-DoH requester consent.
33pub const POLICY_ABI_VERSION_V2: u32 = 2;
34/// Provider-authority consumer ABI version.
35pub const PROVIDER_AUTHORITY_ABI_VERSION_V1: u32 = 1;
36/// All caller-supplied prerequisite bits required before local DANE matching.
37pub const PREREQUISITES_ALL_VERIFIED: u32 = 0x33;
38/// Maximum bytes in each fixed-size C transport identity.
39pub const ABI_IDENTITY_CAPACITY: usize = 128;
40
41const PROVIDER_DNS_RELAY: u16 = 1 << 0;
42const PROVIDER_ODOH_PROXY: u16 = 1 << 1;
43const PROVIDER_ODOH_TARGET: u16 = 1 << 2;
44const PROVIDER_MARKET_GOSSIP: u16 = 1 << 3;
45const PROVIDER_KNOWN: u16 =
46    PROVIDER_DNS_RELAY | PROVIDER_ODOH_PROXY | PROVIDER_ODOH_TARGET | PROVIDER_MARKET_GOSSIP;
47
48const EFFECT_STOP_DISABLED: u32 = 1 << 0;
49const EFFECT_CANCEL_OR_DRAIN: u32 = 1 << 1;
50const EFFECT_CLEAR_REQUESTER: u32 = 1 << 2;
51const EFFECT_WITHDRAW_ADVERTISEMENTS: u32 = 1 << 3;
52const EFFECT_WITHDRAW_HNSR: u32 = 1 << 4;
53const EFFECT_REVOKE_TARGETS: u32 = 1 << 5;
54const EFFECT_RENEGOTIATE: u32 = 1 << 6;
55const EFFECT_UPDATE_STATUS: u32 = 1 << 7;
56
57/// Opaque engine handle declaration.
58#[repr(C)]
59pub struct HnsDaneEngine {
60    _private: [u8; 0],
61}
62
63/// Opaque admitted-attempt handle declaration.
64#[repr(C)]
65pub struct HnsDaneAttempt {
66    _private: [u8; 0],
67}
68
69/// Opaque authorized provider-context handle declaration.
70///
71/// C callers cannot construct or import this handle. A trusted Rust authority
72/// host must move an engine-issued [`ProviderAuthorityContext`] through
73/// [`provider_authority_into_ffi`].
74#[repr(C)]
75pub struct HnsDaneProviderAuthority {
76    _private: [u8; 0],
77}
78
79struct EngineHandle {
80    engine: Engine,
81}
82
83struct AttemptHandle {
84    attempt: ResolutionAttempt,
85}
86
87struct ProviderAuthorityHandle {
88    engine: Arc<Engine>,
89    authority: ProviderAuthorityContext,
90}
91
92/// C ABI status.
93#[repr(i32)]
94#[derive(Clone, Copy, Debug, Eq, PartialEq)]
95pub enum HnsDaneStatus {
96    /// Success.
97    Ok = 0,
98    /// Required pointer was null.
99    NullPointer = 1,
100    /// ABI version or struct size is unsupported.
101    AbiMismatch = 2,
102    /// Input encoding or enum discriminant is invalid.
103    InvalidArgument = 3,
104    /// Output buffer is too small.
105    BufferTooSmall = 4,
106    /// Expected generation is stale.
107    StaleGeneration = 5,
108    /// Requested transport is disabled.
109    TransportDisabled = 6,
110    /// Browser authority state is not ready.
111    AuthorityNotReady = 7,
112    /// DNS packet is malformed or uncorrelated.
113    DnsRejected = 8,
114    /// Local validation evidence is incomplete.
115    EvidenceRejected = 9,
116    /// Internal engine state failed.
117    Internal = 10,
118    /// A Rust panic was contained at the ABI boundary.
119    PanicContained = 255,
120}
121
122impl HnsDaneStatus {
123    const fn code(self) -> i32 {
124        self as i32
125    }
126}
127
128/// Versioned C policy structure.
129#[repr(C)]
130#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
131pub struct HnsDanePolicyV1 {
132    /// Set to `sizeof(HnsDanePolicyV1)`.
133    pub struct_size: u32,
134    /// Set to [`ABI_VERSION`].
135    pub abi_version: u32,
136    /// Current policy generation on output; expected generation on input.
137    pub generation: u64,
138    /// [`DnsRelayRequesterPolicy`] discriminant.
139    pub dns_relay_requester: u8,
140    /// [`ObliviousDnsPolicy`] discriminant.
141    pub oblivious_dns: u8,
142    /// Independent [`HnsrPolicy`] role bits.
143    pub hnsr: u8,
144    /// [`WireProfile`] discriminant.
145    pub wire_profile: u8,
146    /// One when proof-authenticated authoritative DoH is enabled.
147    pub authenticated_authoritative_doh: u8,
148    /// One when bounded legacy regtest compatibility is enabled.
149    pub allow_legacy_regtest_compatibility: u8,
150    /// Explicit provider-role bitset.
151    pub provider_flags: u16,
152    /// Must be zero.
153    pub reserved: [u8; 8],
154}
155
156/// Versioned C policy structure with recursive-HNS-DoH requester consent.
157#[repr(C)]
158#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
159pub struct HnsDanePolicyV2 {
160    /// Set to `sizeof(HnsDanePolicyV2)`.
161    pub struct_size: u32,
162    /// Set to [`POLICY_ABI_VERSION_V2`].
163    pub abi_version: u32,
164    /// Current policy generation on output; expected generation on input.
165    pub generation: u64,
166    /// [`DnsRelayRequesterPolicy`] discriminant.
167    pub dns_relay_requester: u8,
168    /// [`ObliviousDnsPolicy`] discriminant.
169    pub oblivious_dns: u8,
170    /// Independent [`HnsrPolicy`] role bits.
171    pub hnsr: u8,
172    /// [`WireProfile`] discriminant.
173    pub wire_profile: u8,
174    /// One when proof-authenticated authoritative DoH is enabled.
175    pub authenticated_authoritative_doh: u8,
176    /// One when bounded legacy regtest compatibility is enabled.
177    pub allow_legacy_regtest_compatibility: u8,
178    /// Explicit provider-role bitset.
179    pub provider_flags: u16,
180    /// One only after explicit recursive-HNS-DoH requester consent.
181    pub user_configured_recursive_hns_doh: u8,
182    /// Must be zero.
183    pub reserved: [u8; 7],
184}
185
186/// Versioned transport identity context.
187#[repr(C)]
188#[derive(Clone, Copy, Debug, Eq, PartialEq)]
189pub struct HnsDaneTransportContextV1 {
190    /// Set to `sizeof(HnsDaneTransportContextV1)`.
191    pub struct_size: u32,
192    /// Set to [`ABI_VERSION`].
193    pub abi_version: u32,
194    /// Used bytes in `peer_identity`.
195    pub peer_identity_len: u16,
196    /// Used bytes in `proxy_identity`.
197    pub proxy_identity_len: u16,
198    /// Used bytes in `target_identity`.
199    pub target_identity_len: u16,
200    /// One only when ODoH downgraded to a direct relay attempt.
201    pub direct_relay_fallback: u8,
202    /// Must be zero.
203    pub reserved: u8,
204    /// UTF-8 relay or peer identity.
205    pub peer_identity: [u8; ABI_IDENTITY_CAPACITY],
206    /// UTF-8 ODoH proxy identity.
207    pub proxy_identity: [u8; ABI_IDENTITY_CAPACITY],
208    /// UTF-8 ODoH target identity.
209    pub target_identity: [u8; ABI_IDENTITY_CAPACITY],
210}
211
212impl Default for HnsDaneTransportContextV1 {
213    fn default() -> Self {
214        Self {
215            struct_size: u32::try_from(std::mem::size_of::<Self>()).unwrap_or(u32::MAX),
216            abi_version: ABI_VERSION,
217            peer_identity_len: 0,
218            proxy_identity_len: 0,
219            target_identity_len: 0,
220            direct_relay_fallback: 0,
221            reserved: 0,
222            peer_identity: [0; ABI_IDENTITY_CAPACITY],
223            proxy_identity: [0; ABI_IDENTITY_CAPACITY],
224            target_identity: [0; ABI_IDENTITY_CAPACITY],
225        }
226    }
227}
228
229/// Versioned validated response summary.
230#[repr(C)]
231#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
232pub struct HnsDaneResultV1 {
233    /// Set to `sizeof(HnsDaneResultV1)`.
234    pub struct_size: u32,
235    /// Result schema version.
236    pub schema_version: u16,
237    /// [`ResolutionTransport`] discriminant.
238    pub transport: u8,
239    /// One if the remote packet asserted AD; never local evidence.
240    pub untrusted_ad_claim: u8,
241    /// Runtime generation that accepted the result.
242    pub runtime_generation: u64,
243    /// Policy generation that accepted the result.
244    pub policy_generation: u64,
245    /// Monotonic engine event sequence.
246    pub event_sequence: u64,
247    /// Parsed answer count.
248    pub answer_count: u16,
249    /// Index in the exact-owner TLSA RRset that matched.
250    pub tlsa_record_index: u16,
251    /// Matched TLSA certificate usage.
252    pub tlsa_usage: u8,
253    /// Matched TLSA selector.
254    pub tlsa_selector: u8,
255    /// Matched TLSA association matching type.
256    pub tlsa_matching_type: u8,
257    /// Reserved and zero.
258    pub reserved: u8,
259}
260
261/// Immutable typed bindings carried by one authorized provider context.
262///
263/// This is an output-only projection. Its fields cannot be imported or used to
264/// reconstruct authority; possession of the corresponding opaque handle and a
265/// successful currentness check remain mandatory.
266#[repr(C)]
267#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
268pub struct HnsDaneProviderAuthorityInfoV1 {
269    /// Set to `sizeof(HnsDaneProviderAuthorityInfoV1)`.
270    pub struct_size: u32,
271    /// Set to [`PROVIDER_AUTHORITY_ABI_VERSION_V1`].
272    pub abi_version: u32,
273    /// [`hns_dane_engine::OriginScheme`] discriminant.
274    pub origin_scheme: u8,
275    /// [`hns_dane_engine::Namespace`] discriminant.
276    pub selected_namespace: u8,
277    /// [`hns_dane_engine::AuthenticatedContextStatus`] discriminant.
278    pub authenticated_context: u8,
279    /// [`hns_dane_engine::HnsNetwork`] discriminant.
280    pub hns_network: u8,
281    /// [`hns_dane_engine::TlsTrustPolicy`] discriminant.
282    pub tls_policy: u8,
283    /// Must be zero.
284    pub reserved0: u8,
285    /// Effective URL-origin port.
286    pub origin_port: u16,
287    /// Exact selected TCP service port.
288    pub service_port: u16,
289    /// Must be zero.
290    pub reserved1: [u8; 6],
291    /// Browser-authority process session.
292    pub runtime_session: [u8; 16],
293    /// Browser-authority runtime generation.
294    pub runtime_generation: u64,
295    /// Persistent trust-policy generation.
296    pub policy_generation: u64,
297    /// Exact authority event that stamped the context.
298    pub event_sequence: u64,
299    /// Complete namespace-decision identity.
300    pub decision_fingerprint: [u8; 32],
301    /// First time at which the context may be consumed.
302    pub valid_from: u64,
303    /// Exclusive context expiry.
304    pub valid_until: u64,
305    /// Must be zero.
306    pub reserved: [u8; 8],
307}
308
309/// Move an authorized Rust context into a caller-owned opaque C handle.
310///
311/// This Rust-only handoff is deliberately the sole constructor. It retains
312/// the exact live engine used for future currentness checks and accepts no
313/// diagnostic decision or caller-provided permission fields. The returned
314/// pointer must be destroyed exactly once with
315/// [`hns_dane_engine_provider_v1_authority_destroy`] after concurrent borrows
316/// have stopped, and must never be exposed to page JavaScript.
317/// A retained engine that does not admit the context cannot make the handle
318/// current; the projection never substitutes for this check. The handle keeps
319/// its engine alive until destruction.
320#[must_use = "the returned provider-authority handle is caller-owned"]
321pub fn provider_authority_into_ffi(
322    engine: Arc<Engine>,
323    authority: ProviderAuthorityContext,
324) -> *mut HnsDaneProviderAuthority {
325    Box::into_raw(Box::new(ProviderAuthorityHandle { engine, authority }))
326        .cast::<HnsDaneProviderAuthority>()
327}
328
329/// Return the ABI version without dereferencing caller memory.
330#[unsafe(no_mangle)]
331pub extern "C" fn hns_dane_engine_v1_abi_version() -> u32 {
332    ABI_VERSION
333}
334
335/// Return the policy-v2 ABI version without dereferencing caller memory.
336#[unsafe(no_mangle)]
337pub extern "C" fn hns_dane_engine_v2_abi_version() -> u32 {
338    POLICY_ABI_VERSION_V2
339}
340
341/// Return the provider-authority consumer ABI version without dereferencing caller memory.
342#[unsafe(no_mangle)]
343pub extern "C" fn hns_dane_engine_provider_v1_abi_version() -> u32 {
344    PROVIDER_AUTHORITY_ABI_VERSION_V1
345}
346
347/// Create an engine.
348///
349/// `runtime_session` must contain a fresh, unpredictable, nonzero value for
350/// this process start. The all-zero sentinel is rejected.
351///
352/// An empty policy blob selects secure defaults. A nonempty blob must be the
353/// exact checksummed representation returned by the export function.
354///
355/// # Safety
356///
357/// `runtime_session` must reference 16 readable bytes. `policy_blob` must
358/// reference `policy_blob_len` readable bytes when the length is nonzero.
359/// `output` must be valid for one pointer write and becomes caller-owned.
360#[unsafe(no_mangle)]
361pub unsafe extern "C" fn hns_dane_engine_v1_create(
362    runtime_session: *const u8,
363    network: u8,
364    policy_blob: *const u8,
365    policy_blob_len: usize,
366    output: *mut *mut HnsDaneEngine,
367) -> i32 {
368    ffi_guard(|| {
369        if runtime_session.is_null() || output.is_null() {
370            return Err(HnsDaneStatus::NullPointer);
371        }
372        let network = network_from_u8(network)?;
373        // SAFETY: The caller contract requires 16 readable session bytes.
374        let session_slice = unsafe { slice::from_raw_parts(runtime_session, 16) };
375        let mut session = [0u8; 16];
376        session.copy_from_slice(session_slice);
377        let session = RuntimeSessionId::new(session).map_err(|_| HnsDaneStatus::InvalidArgument)?;
378        let policy = if policy_blob_len == 0 {
379            PolicySnapshot::default()
380        } else {
381            if policy_blob.is_null() {
382                return Err(HnsDaneStatus::NullPointer);
383            }
384            // SAFETY: The caller contract requires policy_blob_len readable bytes.
385            let blob = unsafe { slice::from_raw_parts(policy_blob, policy_blob_len) };
386            PolicySnapshot::decode(blob).map_err(map_policy_error)?
387        };
388        let handle = Box::new(EngineHandle {
389            engine: Engine::new(EngineConfig {
390                runtime_session: session,
391                network,
392                policy,
393            }),
394        });
395        // SAFETY: output is caller-provided writable storage and the allocation
396        // is intentionally transferred to the matching destroy function.
397        unsafe {
398            output.write(Box::into_raw(handle).cast::<HnsDaneEngine>());
399        }
400        Ok(())
401    })
402}
403
404/// Destroy an engine returned by the create function.
405///
406/// # Safety
407///
408/// `engine` must be null or a live pointer returned by this library, and must
409/// be destroyed at most once with no concurrent calls.
410#[unsafe(no_mangle)]
411pub unsafe extern "C" fn hns_dane_engine_v1_destroy(engine: *mut HnsDaneEngine) -> i32 {
412    ffi_guard(|| {
413        if engine.is_null() {
414            return Ok(());
415        }
416        // SAFETY: Ownership is returned by the caller under the function contract.
417        unsafe {
418            drop(Box::from_raw(engine.cast::<EngineHandle>()));
419        }
420        Ok(())
421    })
422}
423
424/// Destroy an admitted attempt.
425///
426/// # Safety
427///
428/// `attempt` must be null or a live pointer returned by the admit function,
429/// and must be destroyed at most once.
430#[unsafe(no_mangle)]
431pub unsafe extern "C" fn hns_dane_engine_v1_attempt_destroy(attempt: *mut HnsDaneAttempt) -> i32 {
432    ffi_guard(|| {
433        if attempt.is_null() {
434            return Ok(());
435        }
436        // SAFETY: Ownership is returned by the caller under the function contract.
437        unsafe {
438            drop(Box::from_raw(attempt.cast::<AttemptHandle>()));
439        }
440        Ok(())
441    })
442}
443
444/// Destroy an opaque provider-authority handle.
445///
446/// # Safety
447///
448/// `authority` must be null or a live pointer returned by
449/// [`provider_authority_into_ffi`], and must be destroyed at most once after
450/// concurrent calls using it have stopped.
451#[unsafe(no_mangle)]
452pub unsafe extern "C" fn hns_dane_engine_provider_v1_authority_destroy(
453    authority: *mut HnsDaneProviderAuthority,
454) -> i32 {
455    ffi_guard(|| {
456        if authority.is_null() {
457            return Ok(());
458        }
459        // SAFETY: Ownership is returned by the caller under the function contract.
460        unsafe {
461            drop(Box::from_raw(authority.cast::<ProviderAuthorityHandle>()));
462        }
463        Ok(())
464    })
465}
466
467/// Read immutable typed bindings from an opaque provider authority.
468///
469/// The projection is diagnostic and cannot recreate or replace the handle.
470///
471/// # Safety
472///
473/// `authority` must be a live handle and `output` valid for one structure write.
474#[unsafe(no_mangle)]
475pub unsafe extern "C" fn hns_dane_engine_provider_v1_authority_get_info(
476    authority: *const HnsDaneProviderAuthority,
477    output: *mut HnsDaneProviderAuthorityInfoV1,
478) -> i32 {
479    ffi_guard(|| {
480        if output.is_null() {
481            return Err(HnsDaneStatus::NullPointer);
482        }
483        // SAFETY: The caller contract requires a live provider-authority handle.
484        let authority = unsafe { provider_authority_ref(authority)? };
485        let info = provider_authority_info(&authority.authority)?;
486        // SAFETY: output is required writable by the caller contract.
487        unsafe {
488            output.write(info);
489        }
490        Ok(())
491    })
492}
493
494/// Copy the exact canonical logical-origin host from an opaque authority.
495///
496/// The host is returned as exact UTF-8 bytes without a trailing NUL. A sizing
497/// call may pass a null `output` with zero `capacity`; `written` then receives
498/// the required length and the function returns `BufferTooSmall`.
499///
500/// # Safety
501///
502/// `authority` must be a live handle. `written` must be writable. `output`
503/// must reference `capacity` writable bytes when capacity is sufficient.
504#[unsafe(no_mangle)]
505pub unsafe extern "C" fn hns_dane_engine_provider_v1_authority_copy_host(
506    authority: *const HnsDaneProviderAuthority,
507    output: *mut u8,
508    capacity: usize,
509    written: *mut usize,
510) -> i32 {
511    ffi_guard(|| {
512        if written.is_null() {
513            return Err(HnsDaneStatus::NullPointer);
514        }
515        // SAFETY: The caller contract requires a live provider-authority handle.
516        let authority = unsafe { provider_authority_ref(authority)? };
517        let host = authority.authority.logical_origin().host().as_bytes();
518        // SAFETY: written is required writable by the caller contract.
519        unsafe {
520            written.write(host.len());
521        }
522        if capacity < host.len() {
523            return Err(HnsDaneStatus::BufferTooSmall);
524        }
525        if output.is_null() {
526            return Err(HnsDaneStatus::NullPointer);
527        }
528        // SAFETY: capacity was checked and output must reference writable storage.
529        unsafe {
530            slice::from_raw_parts_mut(output, capacity)[..host.len()].copy_from_slice(host);
531        }
532        Ok(())
533    })
534}
535
536/// Check an opaque authority against its retained engine and trusted time.
537///
538/// Expiry or any session, network, policy, runtime, or invalidation mismatch is
539/// a normal successful query that writes zero to `current`.
540/// `now_unix` must come from the trusted native lifecycle, never page input;
541/// the platform is responsible for rejecting clock rollback.
542///
543/// # Safety
544///
545/// `authority` must be a live handle and `current` writable. No caller may
546/// destroy the handle concurrently with this call.
547#[unsafe(no_mangle)]
548pub unsafe extern "C" fn hns_dane_engine_provider_v1_authority_is_current(
549    authority: *const HnsDaneProviderAuthority,
550    now_unix: u64,
551    current: *mut u8,
552) -> i32 {
553    ffi_guard(|| {
554        if current.is_null() {
555            return Err(HnsDaneStatus::NullPointer);
556        }
557        // SAFETY: The caller contract requires a live authority handle.
558        let authority = unsafe { provider_authority_ref(authority)? };
559        let is_current = authority
560            .engine
561            .provider_authority_is_current(&authority.authority, now_unix)
562            .map_err(map_engine_error)?;
563        // SAFETY: current is required writable by the caller contract.
564        unsafe {
565            current.write(u8::from(is_current));
566        }
567        Ok(())
568    })
569}
570
571/// Export the versioned persistent policy blob.
572///
573/// # Safety
574///
575/// `engine` must be a live handle. `written` must be writable. `output` must
576/// reference `capacity` writable bytes when capacity is nonzero.
577#[unsafe(no_mangle)]
578pub unsafe extern "C" fn hns_dane_engine_v1_export_policy(
579    engine: *const HnsDaneEngine,
580    output: *mut u8,
581    capacity: usize,
582    written: *mut usize,
583) -> i32 {
584    ffi_guard(|| {
585        if written.is_null() {
586            return Err(HnsDaneStatus::NullPointer);
587        }
588        // SAFETY: The caller contract requires a live engine handle.
589        let engine = unsafe { engine_ref(engine)? };
590        let blob = engine.engine.export_policy().map_err(map_engine_error)?;
591        // SAFETY: written is required writable by the caller contract.
592        unsafe {
593            written.write(blob.len());
594        }
595        if capacity < blob.len() {
596            return Err(HnsDaneStatus::BufferTooSmall);
597        }
598        if output.is_null() {
599            return Err(HnsDaneStatus::NullPointer);
600        }
601        // SAFETY: capacity was checked and output must reference writable storage.
602        unsafe {
603            slice::from_raw_parts_mut(output, capacity)[..blob.len()].copy_from_slice(&blob);
604        }
605        Ok(())
606    })
607}
608
609/// Read the policy-V1 projection.
610///
611/// Returns [`HnsDaneStatus::AbiMismatch`] while recursive-HNS-DoH consent is
612/// enabled because policy V1 cannot represent that permission.
613///
614/// # Safety
615///
616/// `engine` must be a live handle and `output` valid for one structure write.
617#[unsafe(no_mangle)]
618pub unsafe extern "C" fn hns_dane_engine_v1_get_policy(
619    engine: *const HnsDaneEngine,
620    output: *mut HnsDanePolicyV1,
621) -> i32 {
622    ffi_guard(|| {
623        if output.is_null() {
624            return Err(HnsDaneStatus::NullPointer);
625        }
626        // SAFETY: The caller contract requires a live engine handle.
627        let engine = unsafe { engine_ref(engine)? };
628        let snapshot = engine.engine.snapshot().map_err(map_engine_error)?.policy;
629        if snapshot.config().user_configured_recursive_hns_doh {
630            return Err(HnsDaneStatus::AbiMismatch);
631        }
632        let policy = policy_to_ffi_v1(snapshot);
633        // SAFETY: output is required writable by the caller contract.
634        unsafe {
635            output.write(policy);
636        }
637        Ok(())
638    })
639}
640
641/// Replace policy through the V1 fail-closed boundary.
642///
643/// A successful V1 update always disables recursive-HNS-DoH consent because
644/// policy V1 cannot represent or retain that permission.
645///
646/// # Safety
647///
648/// `engine` must be a live handle; `policy`, `new_generation`, and `effects`
649/// must be valid readable/writable pointers for their respective types.
650#[unsafe(no_mangle)]
651pub unsafe extern "C" fn hns_dane_engine_v1_set_policy(
652    engine: *const HnsDaneEngine,
653    policy: *const HnsDanePolicyV1,
654    new_generation: *mut u64,
655    effects: *mut u32,
656) -> i32 {
657    ffi_guard(|| {
658        if policy.is_null() || new_generation.is_null() || effects.is_null() {
659            return Err(HnsDaneStatus::NullPointer);
660        }
661        // SAFETY: The caller contract requires a live engine handle.
662        let engine = unsafe { engine_ref(engine)? };
663        // SAFETY: policy is required readable by the caller contract.
664        let policy = unsafe { policy.read() };
665        let (expected_generation, config) = policy_from_ffi_v1(policy)?;
666        let transition = engine
667            .engine
668            .update_policy(expected_generation, config)
669            .map_err(map_engine_error)?;
670        let effect_bits = effects_to_bits(transition.effects);
671        // SAFETY: output pointers are required writable by the caller contract.
672        unsafe {
673            new_generation.write(transition.current.generation());
674            effects.write(effect_bits);
675        }
676        Ok(())
677    })
678}
679
680/// Read typed current policy, including recursive-HNS-DoH requester consent.
681///
682/// # Safety
683///
684/// `engine` must be a live handle and `output` valid for one structure write.
685#[unsafe(no_mangle)]
686pub unsafe extern "C" fn hns_dane_engine_v2_get_policy(
687    engine: *const HnsDaneEngine,
688    output: *mut HnsDanePolicyV2,
689) -> i32 {
690    ffi_guard(|| {
691        if output.is_null() {
692            return Err(HnsDaneStatus::NullPointer);
693        }
694        // SAFETY: The caller contract requires a live engine handle.
695        let engine = unsafe { engine_ref(engine)? };
696        let snapshot = engine.engine.snapshot().map_err(map_engine_error)?.policy;
697        let policy = policy_to_ffi_v2(snapshot);
698        // SAFETY: output is required writable by the caller contract.
699        unsafe {
700            output.write(policy);
701        }
702        Ok(())
703    })
704}
705
706/// Replace typed policy, including recursive-HNS-DoH requester consent.
707///
708/// # Safety
709///
710/// `engine` must be a live handle; `policy`, `new_generation`, and `effects`
711/// must be valid readable/writable pointers for their respective types.
712#[unsafe(no_mangle)]
713pub unsafe extern "C" fn hns_dane_engine_v2_set_policy(
714    engine: *const HnsDaneEngine,
715    policy: *const HnsDanePolicyV2,
716    new_generation: *mut u64,
717    effects: *mut u32,
718) -> i32 {
719    ffi_guard(|| {
720        if policy.is_null() || new_generation.is_null() || effects.is_null() {
721            return Err(HnsDaneStatus::NullPointer);
722        }
723        // SAFETY: The caller contract requires a live engine handle.
724        let engine = unsafe { engine_ref(engine)? };
725        // SAFETY: policy is required readable by the caller contract.
726        let policy = unsafe { policy.read() };
727        let (expected_generation, config) = policy_from_ffi_v2(policy)?;
728        let transition = engine
729            .engine
730            .update_policy(expected_generation, config)
731            .map_err(map_engine_error)?;
732        let effect_bits = effects_to_bits(transition.effects);
733        // SAFETY: output pointers are required writable by the caller contract.
734        unsafe {
735            new_generation.write(transition.current.generation());
736            effects.write(effect_bits);
737        }
738        Ok(())
739    })
740}
741
742/// Advance the explicit authority state machine.
743///
744/// # Safety
745///
746/// `engine` must be a live handle.
747#[unsafe(no_mangle)]
748pub unsafe extern "C" fn hns_dane_engine_v1_advance_authority(
749    engine: *const HnsDaneEngine,
750    state: u8,
751) -> i32 {
752    ffi_guard(|| {
753        // SAFETY: The caller contract requires a live engine handle.
754        let engine = unsafe { engine_ref(engine)? };
755        engine
756            .engine
757            .advance_authority_state(authority_state_from_u8(state)?)
758            .map_err(map_engine_error)?;
759        Ok(())
760    })
761}
762
763/// Return the number of currently ordered transport candidates.
764///
765/// # Safety
766///
767/// `engine` must be live and `count` writable.
768#[unsafe(no_mangle)]
769pub unsafe extern "C" fn hns_dane_engine_v1_transport_count(
770    engine: *const HnsDaneEngine,
771    count: *mut usize,
772) -> i32 {
773    ffi_guard(|| {
774        if count.is_null() {
775            return Err(HnsDaneStatus::NullPointer);
776        }
777        // SAFETY: The caller contract requires a live engine handle.
778        let engine = unsafe { engine_ref(engine)? };
779        let length = engine
780            .engine
781            .transport_plan()
782            .map_err(map_engine_error)?
783            .as_slice()
784            .len();
785        // SAFETY: count is required writable by the caller contract.
786        unsafe {
787            count.write(length);
788        }
789        Ok(())
790    })
791}
792
793/// Read one current transport candidate by index.
794///
795/// # Safety
796///
797/// `engine` must be live and `transport` writable.
798#[unsafe(no_mangle)]
799pub unsafe extern "C" fn hns_dane_engine_v1_transport_at(
800    engine: *const HnsDaneEngine,
801    index: usize,
802    transport: *mut u8,
803) -> i32 {
804    ffi_guard(|| {
805        if transport.is_null() {
806            return Err(HnsDaneStatus::NullPointer);
807        }
808        // SAFETY: The caller contract requires a live engine handle.
809        let engine = unsafe { engine_ref(engine)? };
810        let plan = engine.engine.transport_plan().map_err(map_engine_error)?;
811        let value = plan
812            .as_slice()
813            .get(index)
814            .copied()
815            .ok_or(HnsDaneStatus::InvalidArgument)?;
816        // SAFETY: transport is required writable by the caller contract.
817        unsafe {
818            transport.write(value as u8);
819        }
820        Ok(())
821    })
822}
823
824/// Admit one exact class-IN query on one transport.
825///
826/// # Safety
827///
828/// `engine` must be live. `name` must reference `name_len` readable UTF-8
829/// bytes. `output` must be writable and becomes caller-owned on success.
830#[unsafe(no_mangle)]
831pub unsafe extern "C" fn hns_dane_engine_v1_admit(
832    engine: *const HnsDaneEngine,
833    transport: u8,
834    query_id: u16,
835    name: *const u8,
836    name_len: usize,
837    record_type: u16,
838    output: *mut *mut HnsDaneAttempt,
839) -> i32 {
840    ffi_guard(|| {
841        if name.is_null() || output.is_null() {
842            return Err(HnsDaneStatus::NullPointer);
843        }
844        // SAFETY: The caller contract requires a live engine handle.
845        let engine = unsafe { engine_ref(engine)? };
846        // SAFETY: name is required to reference name_len readable bytes.
847        let name_bytes = unsafe { slice::from_raw_parts(name, name_len) };
848        let name_text = str::from_utf8(name_bytes).map_err(|_| HnsDaneStatus::InvalidArgument)?;
849        let query = Query::new(
850            query_id,
851            Name::from_ascii(name_text).map_err(|_| HnsDaneStatus::InvalidArgument)?,
852            RecordType::from_code(record_type),
853        )
854        .map_err(|_| HnsDaneStatus::InvalidArgument)?;
855        let attempt = engine
856            .engine
857            .admit_resolution(
858                ResolutionTransport::try_from(transport).map_err(map_policy_error)?,
859                query,
860            )
861            .map_err(map_engine_error)?;
862        let attempt = Box::new(AttemptHandle { attempt });
863        // SAFETY: output is writable and receives ownership of the allocation.
864        unsafe {
865            output.write(Box::into_raw(attempt).cast::<HnsDaneAttempt>());
866        }
867        Ok(())
868    })
869}
870
871/// Parse, correlate, and locally match one TLSA response and certificate.
872///
873/// `prerequisite_mask` bits 0, 1, 4, and 5 represent HNS proof, DNSSEC, chain
874/// currency, and SNI respectively. TLSA and DANE cannot be asserted by the
875/// caller: they are derived from the correlated response and certificate.
876/// `context` may be null only for a direct transport.
877///
878/// # Safety
879///
880/// `engine` and `attempt` must be live handles. `response` must reference
881/// `response_len` readable bytes. `certificate_der` must reference
882/// `certificate_der_len` readable bytes. `output` must be writable.
883#[unsafe(no_mangle)]
884pub unsafe extern "C" fn hns_dane_engine_v1_validate_response(
885    engine: *const HnsDaneEngine,
886    attempt: *const HnsDaneAttempt,
887    response: *const u8,
888    response_len: usize,
889    certificate_der: *const u8,
890    certificate_der_len: usize,
891    context: *const HnsDaneTransportContextV1,
892    prerequisite_mask: u32,
893    output: *mut HnsDaneResultV1,
894) -> i32 {
895    ffi_guard(|| {
896        if response.is_null() || certificate_der.is_null() || output.is_null() {
897            return Err(HnsDaneStatus::NullPointer);
898        }
899        // SAFETY: The caller contract requires live engine and attempt handles.
900        let engine = unsafe { engine_ref(engine)? };
901        // SAFETY: The caller contract requires a live admitted-attempt handle.
902        let attempt = unsafe { attempt_ref(attempt)? };
903        // SAFETY: response is required to reference response_len readable bytes.
904        let bytes = unsafe { slice::from_raw_parts(response, response_len) };
905        // SAFETY: certificate_der must reference certificate_der_len readable bytes.
906        let certificate = unsafe { slice::from_raw_parts(certificate_der, certificate_der_len) };
907        let parsed = engine
908            .engine
909            .parse_response(&attempt.attempt, bytes, ParseLimits::requester())
910            .map_err(map_engine_error)?;
911        let prerequisites = prerequisites_from_mask(prerequisite_mask)?;
912        let context = if context.is_null() {
913            CompletionContext::default()
914        } else {
915            // SAFETY: A nonnull context is required to reference one readable structure.
916            context_from_ffi(unsafe { &*context })?
917        };
918        let answer_count =
919            u16::try_from(parsed.message().answers.len()).map_err(|_| HnsDaneStatus::Internal)?;
920        let completed = engine
921            .engine
922            .complete_resolution_with_local_dane(
923                &attempt.attempt,
924                &parsed,
925                prerequisites,
926                certificate,
927                DaneLimits::default(),
928                context,
929            )
930            .map_err(map_engine_error)?;
931        let provenance = completed.provenance().clone();
932        let dane_match = completed.dane_match();
933        let record_index =
934            u16::try_from(dane_match.record_index()).map_err(|_| HnsDaneStatus::Internal)?;
935        let result = HnsDaneResultV1 {
936            struct_size: size_u32::<HnsDaneResultV1>()?,
937            schema_version: provenance.schema_version,
938            transport: provenance.transport as u8,
939            untrusted_ad_claim: u8::from(provenance.untrusted_ad_claim),
940            runtime_generation: provenance.runtime_generation,
941            policy_generation: provenance.policy_generation,
942            event_sequence: provenance.event_sequence,
943            answer_count,
944            tlsa_record_index: record_index,
945            tlsa_usage: dane_match.usage() as u8,
946            tlsa_selector: dane_match.selector() as u8,
947            tlsa_matching_type: dane_match.matching_type() as u8,
948            reserved: 0,
949        };
950        // SAFETY: output is required writable by the caller contract.
951        unsafe {
952            output.write(result);
953        }
954        Ok(())
955    })
956}
957
958fn ffi_guard(operation: impl FnOnce() -> Result<(), HnsDaneStatus>) -> i32 {
959    match catch_unwind(AssertUnwindSafe(operation)) {
960        Ok(Ok(())) => HnsDaneStatus::Ok.code(),
961        Ok(Err(status)) => status.code(),
962        Err(_) => HnsDaneStatus::PanicContained.code(),
963    }
964}
965
966unsafe fn engine_ref<'a>(engine: *const HnsDaneEngine) -> Result<&'a EngineHandle, HnsDaneStatus> {
967    if engine.is_null() {
968        return Err(HnsDaneStatus::NullPointer);
969    }
970    // SAFETY: The caller guarantees this is a live handle from create.
971    Ok(unsafe { &*engine.cast::<EngineHandle>() })
972}
973
974unsafe fn attempt_ref<'a>(
975    attempt: *const HnsDaneAttempt,
976) -> Result<&'a AttemptHandle, HnsDaneStatus> {
977    if attempt.is_null() {
978        return Err(HnsDaneStatus::NullPointer);
979    }
980    // SAFETY: The caller guarantees this is a live handle from admit.
981    Ok(unsafe { &*attempt.cast::<AttemptHandle>() })
982}
983
984unsafe fn provider_authority_ref<'a>(
985    authority: *const HnsDaneProviderAuthority,
986) -> Result<&'a ProviderAuthorityHandle, HnsDaneStatus> {
987    if authority.is_null() {
988        return Err(HnsDaneStatus::NullPointer);
989    }
990    // SAFETY: The caller guarantees this is a live handle from the Rust handoff.
991    Ok(unsafe { &*authority.cast::<ProviderAuthorityHandle>() })
992}
993
994fn provider_authority_info(
995    authority: &ProviderAuthorityContext,
996) -> Result<HnsDaneProviderAuthorityInfoV1, HnsDaneStatus> {
997    Ok(HnsDaneProviderAuthorityInfoV1 {
998        struct_size: size_u32::<HnsDaneProviderAuthorityInfoV1>()?,
999        abi_version: PROVIDER_AUTHORITY_ABI_VERSION_V1,
1000        origin_scheme: authority.logical_origin().scheme() as u8,
1001        selected_namespace: authority.selected_namespace() as u8,
1002        authenticated_context: authority.authenticated_context() as u8,
1003        hns_network: authority.hns_network() as u8,
1004        tls_policy: authority.tls_policy() as u8,
1005        reserved0: 0,
1006        origin_port: authority.logical_origin().port(),
1007        service_port: authority.service_port(),
1008        reserved1: [0; 6],
1009        runtime_session: authority.runtime_session(),
1010        runtime_generation: authority.runtime_generation(),
1011        policy_generation: authority.policy_generation(),
1012        event_sequence: authority.event_sequence(),
1013        decision_fingerprint: authority.decision_fingerprint(),
1014        valid_from: authority.valid_from(),
1015        valid_until: authority.valid_until(),
1016        reserved: [0; 8],
1017    })
1018}
1019
1020fn network_from_u8(value: u8) -> Result<Network, HnsDaneStatus> {
1021    match value {
1022        0 => Ok(Network::Mainnet),
1023        1 => Ok(Network::Testnet),
1024        2 => Ok(Network::Regtest),
1025        3 => Ok(Network::Simnet),
1026        _ => Err(HnsDaneStatus::InvalidArgument),
1027    }
1028}
1029
1030fn authority_state_from_u8(value: u8) -> Result<AuthorityState, HnsDaneStatus> {
1031    match value {
1032        0 => Ok(AuthorityState::Uninitialized),
1033        1 => Ok(AuthorityState::LocalStateOpened),
1034        2 => Ok(AuthorityState::HeaderSyncing),
1035        3 => Ok(AuthorityState::HeaderCurrent),
1036        4 => Ok(AuthorityState::ProofReady),
1037        5 => Ok(AuthorityState::ResolutionTransportReady),
1038        6 => Ok(AuthorityState::DnssecVerified),
1039        7 => Ok(AuthorityState::DaneOriginVerified),
1040        8 => Ok(AuthorityState::BrowserBridgeReady),
1041        9 => Ok(AuthorityState::Active),
1042        10 => Ok(AuthorityState::Degraded),
1043        11 => Ok(AuthorityState::Revoked),
1044        12 => Ok(AuthorityState::Stopped),
1045        _ => Err(HnsDaneStatus::InvalidArgument),
1046    }
1047}
1048
1049fn policy_to_ffi_v1(snapshot: PolicySnapshot) -> HnsDanePolicyV1 {
1050    let config = snapshot.config();
1051    HnsDanePolicyV1 {
1052        struct_size: u32::try_from(std::mem::size_of::<HnsDanePolicyV1>()).unwrap_or(u32::MAX),
1053        abi_version: ABI_VERSION,
1054        generation: snapshot.generation(),
1055        dns_relay_requester: config.dns_relay_requester as u8,
1056        oblivious_dns: config.oblivious_dns as u8,
1057        hnsr: config.hnsr.bits(),
1058        wire_profile: config.wire_profile as u8,
1059        authenticated_authoritative_doh: u8::from(config.authenticated_authoritative_doh),
1060        allow_legacy_regtest_compatibility: u8::from(config.allow_legacy_regtest_compatibility),
1061        provider_flags: provider_flags(config.providers),
1062        reserved: [0; 8],
1063    }
1064}
1065
1066fn policy_to_ffi_v2(snapshot: PolicySnapshot) -> HnsDanePolicyV2 {
1067    let config = snapshot.config();
1068    HnsDanePolicyV2 {
1069        struct_size: u32::try_from(std::mem::size_of::<HnsDanePolicyV2>()).unwrap_or(u32::MAX),
1070        abi_version: POLICY_ABI_VERSION_V2,
1071        generation: snapshot.generation(),
1072        dns_relay_requester: config.dns_relay_requester as u8,
1073        oblivious_dns: config.oblivious_dns as u8,
1074        hnsr: config.hnsr.bits(),
1075        wire_profile: config.wire_profile as u8,
1076        authenticated_authoritative_doh: u8::from(config.authenticated_authoritative_doh),
1077        allow_legacy_regtest_compatibility: u8::from(config.allow_legacy_regtest_compatibility),
1078        provider_flags: provider_flags(config.providers),
1079        user_configured_recursive_hns_doh: u8::from(config.user_configured_recursive_hns_doh),
1080        reserved: [0; 7],
1081    }
1082}
1083
1084fn policy_from_ffi_v1(policy: HnsDanePolicyV1) -> Result<(u64, PolicyConfig), HnsDaneStatus> {
1085    if policy.struct_size != size_u32::<HnsDanePolicyV1>()?
1086        || policy.abi_version != ABI_VERSION
1087        || policy.reserved != [0; 8]
1088        || policy.provider_flags & !PROVIDER_KNOWN != 0
1089        || policy.authenticated_authoritative_doh > 1
1090        || policy.allow_legacy_regtest_compatibility > 1
1091    {
1092        return Err(HnsDaneStatus::AbiMismatch);
1093    }
1094    Ok((
1095        policy.generation,
1096        PolicyConfig {
1097            dns_relay_requester: DnsRelayRequesterPolicy::try_from(policy.dns_relay_requester)
1098                .map_err(map_policy_error)?,
1099            oblivious_dns: ObliviousDnsPolicy::try_from(policy.oblivious_dns)
1100                .map_err(map_policy_error)?,
1101            hnsr: HnsrPolicy::from_bits(policy.hnsr).map_err(map_policy_error)?,
1102            authenticated_authoritative_doh: policy.authenticated_authoritative_doh != 0,
1103            user_configured_recursive_hns_doh: false,
1104            providers: providers_from_flags(policy.provider_flags),
1105            wire_profile: WireProfile::try_from(policy.wire_profile).map_err(map_policy_error)?,
1106            allow_legacy_regtest_compatibility: policy.allow_legacy_regtest_compatibility != 0,
1107        },
1108    ))
1109}
1110
1111fn policy_from_ffi_v2(policy: HnsDanePolicyV2) -> Result<(u64, PolicyConfig), HnsDaneStatus> {
1112    if policy.struct_size != size_u32::<HnsDanePolicyV2>()?
1113        || policy.abi_version != POLICY_ABI_VERSION_V2
1114        || policy.reserved != [0; 7]
1115        || policy.provider_flags & !PROVIDER_KNOWN != 0
1116        || policy.authenticated_authoritative_doh > 1
1117        || policy.allow_legacy_regtest_compatibility > 1
1118        || policy.user_configured_recursive_hns_doh > 1
1119    {
1120        return Err(HnsDaneStatus::AbiMismatch);
1121    }
1122    Ok((
1123        policy.generation,
1124        PolicyConfig {
1125            dns_relay_requester: DnsRelayRequesterPolicy::try_from(policy.dns_relay_requester)
1126                .map_err(map_policy_error)?,
1127            oblivious_dns: ObliviousDnsPolicy::try_from(policy.oblivious_dns)
1128                .map_err(map_policy_error)?,
1129            hnsr: HnsrPolicy::from_bits(policy.hnsr).map_err(map_policy_error)?,
1130            authenticated_authoritative_doh: policy.authenticated_authoritative_doh != 0,
1131            user_configured_recursive_hns_doh: policy.user_configured_recursive_hns_doh != 0,
1132            providers: providers_from_flags(policy.provider_flags),
1133            wire_profile: WireProfile::try_from(policy.wire_profile).map_err(map_policy_error)?,
1134            allow_legacy_regtest_compatibility: policy.allow_legacy_regtest_compatibility != 0,
1135        },
1136    ))
1137}
1138
1139const fn provider_flags(providers: ProviderPolicy) -> u16 {
1140    (if providers.dns_relay {
1141        PROVIDER_DNS_RELAY
1142    } else {
1143        0
1144    }) | (if providers.odoh_proxy {
1145        PROVIDER_ODOH_PROXY
1146    } else {
1147        0
1148    }) | (if providers.odoh_target {
1149        PROVIDER_ODOH_TARGET
1150    } else {
1151        0
1152    }) | (if providers.market_gossip {
1153        PROVIDER_MARKET_GOSSIP
1154    } else {
1155        0
1156    })
1157}
1158
1159const fn providers_from_flags(flags: u16) -> ProviderPolicy {
1160    ProviderPolicy {
1161        dns_relay: flags & PROVIDER_DNS_RELAY != 0,
1162        odoh_proxy: flags & PROVIDER_ODOH_PROXY != 0,
1163        odoh_target: flags & PROVIDER_ODOH_TARGET != 0,
1164        market_gossip: flags & PROVIDER_MARKET_GOSSIP != 0,
1165    }
1166}
1167
1168fn effects_to_bits(effects: hns_resolution_policy::PolicyChangeEffects) -> u32 {
1169    (if effects.stop_admitting_disabled_work {
1170        EFFECT_STOP_DISABLED
1171    } else {
1172        0
1173    }) | (if effects.cancel_or_drain_inflight {
1174        EFFECT_CANCEL_OR_DRAIN
1175    } else {
1176        0
1177    }) | (if effects.clear_requester_selections {
1178        EFFECT_CLEAR_REQUESTER
1179    } else {
1180        0
1181    }) | (if effects.withdraw_advertisements {
1182        EFFECT_WITHDRAW_ADVERTISEMENTS
1183    } else {
1184        0
1185    }) | (if effects.withdraw_hnsr_routes {
1186        EFFECT_WITHDRAW_HNSR
1187    } else {
1188        0
1189    }) | (if effects.revoke_target_configurations {
1190        EFFECT_REVOKE_TARGETS
1191    } else {
1192        0
1193    }) | (if effects.renegotiate_peer_connections {
1194        EFFECT_RENEGOTIATE
1195    } else {
1196        0
1197    }) | (if effects.update_structured_status {
1198        EFFECT_UPDATE_STATUS
1199    } else {
1200        0
1201    })
1202}
1203
1204const fn evidence_state(mask: u32, bit: u32) -> EvidenceState {
1205    if mask & bit != 0 {
1206        EvidenceState::Verified
1207    } else {
1208        EvidenceState::Unavailable
1209    }
1210}
1211
1212fn prerequisites_from_mask(mask: u32) -> Result<LocalDanePrerequisites, HnsDaneStatus> {
1213    if mask & !PREREQUISITES_ALL_VERIFIED != 0 {
1214        return Err(HnsDaneStatus::InvalidArgument);
1215    }
1216    Ok(LocalDanePrerequisites {
1217        hns_proof: evidence_state(mask, 1 << 0),
1218        dnssec: evidence_state(mask, 1 << 1),
1219        chain_current: evidence_state(mask, 1 << 4),
1220        origin_sni: evidence_state(mask, 1 << 5),
1221    })
1222}
1223
1224fn context_from_ffi(
1225    context: &HnsDaneTransportContextV1,
1226) -> Result<CompletionContext, HnsDaneStatus> {
1227    if context.struct_size != size_u32::<HnsDaneTransportContextV1>()?
1228        || context.abi_version != ABI_VERSION
1229        || context.reserved != 0
1230        || context.direct_relay_fallback > 1
1231    {
1232        return Err(HnsDaneStatus::AbiMismatch);
1233    }
1234    Ok(CompletionContext {
1235        chain_anchor: None,
1236        peer_identity: decode_identity(&context.peer_identity, context.peer_identity_len)?,
1237        proxy_identity: decode_identity(&context.proxy_identity, context.proxy_identity_len)?,
1238        target_identity: decode_identity(&context.target_identity, context.target_identity_len)?,
1239        direct_relay_fallback: context.direct_relay_fallback != 0,
1240    })
1241}
1242
1243fn decode_identity(
1244    storage: &[u8; ABI_IDENTITY_CAPACITY],
1245    length: u16,
1246) -> Result<Option<String>, HnsDaneStatus> {
1247    let length = usize::from(length);
1248    if length > storage.len() {
1249        return Err(HnsDaneStatus::InvalidArgument);
1250    }
1251    if length == 0 {
1252        return Ok(None);
1253    }
1254    let text = str::from_utf8(
1255        storage
1256            .get(..length)
1257            .ok_or(HnsDaneStatus::InvalidArgument)?,
1258    )
1259    .map_err(|_| HnsDaneStatus::InvalidArgument)?;
1260    Ok(Some(text.to_owned()))
1261}
1262
1263fn size_u32<T>() -> Result<u32, HnsDaneStatus> {
1264    u32::try_from(std::mem::size_of::<T>()).map_err(|_| HnsDaneStatus::Internal)
1265}
1266
1267fn map_policy_error(error: PolicyError) -> HnsDaneStatus {
1268    match error {
1269        PolicyError::StaleGeneration => HnsDaneStatus::StaleGeneration,
1270        PolicyError::TransportDisabled => HnsDaneStatus::TransportDisabled,
1271        PolicyError::UnverifiedEvidence => HnsDaneStatus::EvidenceRejected,
1272        PolicyError::InvalidEncoding
1273        | PolicyError::UnsupportedSchema
1274        | PolicyError::ChecksumMismatch
1275        | PolicyError::ZeroGeneration
1276        | PolicyError::ConflictingPolicies => HnsDaneStatus::InvalidArgument,
1277        _ => HnsDaneStatus::Internal,
1278    }
1279}
1280
1281#[allow(
1282    clippy::needless_pass_by_value,
1283    reason = "map_err requires ownership while nested policy errors are moved without cloning"
1284)]
1285fn map_engine_error(error: EngineError) -> HnsDaneStatus {
1286    match error {
1287        EngineError::AuthorityNotReady | EngineError::InvalidAuthorityTransition => {
1288            HnsDaneStatus::AuthorityNotReady
1289        }
1290        EngineError::StaleRuntimeGeneration => HnsDaneStatus::StaleGeneration,
1291        EngineError::ResponseAttemptMismatch
1292        | EngineError::UnsuccessfulDnsResponse
1293        | EngineError::Wire(_) => HnsDaneStatus::DnsRejected,
1294        EngineError::Dane(_) => HnsDaneStatus::EvidenceRejected,
1295        EngineError::ExpectedTlsaQuery
1296        | EngineError::InvalidRuntimeSession
1297        | EngineError::MissingTransportIdentity
1298        | EngineError::InvalidTransportIdentity
1299        | EngineError::ProxyTargetNotSeparated
1300        | EngineError::InvalidCompletionContext => HnsDaneStatus::InvalidArgument,
1301        EngineError::Policy(error) => map_policy_error(error),
1302        _ => HnsDaneStatus::Internal,
1303    }
1304}
1305
1306#[cfg(test)]
1307#[allow(
1308    clippy::borrow_as_ptr,
1309    clippy::too_many_lines,
1310    clippy::undocumented_unsafe_blocks,
1311    clippy::unwrap_used,
1312    reason = "tests pass stack addresses through complete audited ABI flows and fail immediately on invariants"
1313)]
1314mod tests {
1315    use super::*;
1316    use hns_dane_engine::{
1317        AuthenticatedContextStatus, HnsNetwork, IcannOriginAuthentication,
1318        IcannOriginAuthenticationRequest, Namespace, NamespaceDecision, OriginScheme,
1319        TlsTrustPolicy,
1320    };
1321    use hns_dns_wire::{Flags, Header, Message, Rdata, ResourceRecord, Tlsa};
1322    use hns_namespace_resolution::{
1323        AbsenceKind, ApplicationProtocol, CanonicalHost, EvidenceProvenance, Freshness,
1324        IcannChainState, OriginPlanInput, OriginQuery, ProtocolCapabilities, RootLookup,
1325        SelectionPolicy, ServiceBinding, ServiceBindingInput, ServiceTransport, ValidatedAbsence,
1326        ValidatedOriginPlan, decide_namespace,
1327    };
1328    use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1329    use std::ptr;
1330    use std::sync::Arc;
1331
1332    const PROVIDER_AUTHORITY_NOW: u64 = 1_700_000_000;
1333
1334    fn decode_hex(input: &str) -> Vec<u8> {
1335        let compact: Vec<u8> = input
1336            .bytes()
1337            .filter(|byte| !byte.is_ascii_whitespace())
1338            .collect();
1339        assert!(compact.len().is_multiple_of(2));
1340        compact
1341            .chunks_exact(2)
1342            .map(|pair| {
1343                let high = (pair[0] as char).to_digit(16).unwrap();
1344                let low = (pair[1] as char).to_digit(16).unwrap();
1345                u8::try_from((high << 4) | low).unwrap()
1346            })
1347            .collect()
1348    }
1349
1350    fn provider_authority_ffi_engine(session: [u8; 16]) -> Engine {
1351        let engine = Engine::new(EngineConfig {
1352            runtime_session: RuntimeSessionId::new(session).unwrap(),
1353            network: Network::Regtest,
1354            policy: PolicySnapshot::default(),
1355        });
1356        for state in [
1357            AuthorityState::LocalStateOpened,
1358            AuthorityState::HeaderSyncing,
1359            AuthorityState::HeaderCurrent,
1360            AuthorityState::ProofReady,
1361            AuthorityState::ResolutionTransportReady,
1362            AuthorityState::DnssecVerified,
1363            AuthorityState::BrowserBridgeReady,
1364            AuthorityState::Active,
1365        ] {
1366            engine.advance_authority_state(state).unwrap();
1367        }
1368        engine
1369    }
1370
1371    fn provider_authority_ffi_decision(host: &str) -> NamespaceDecision {
1372        let query = OriginQuery::new(
1373            CanonicalHost::parse(host).unwrap(),
1374            OriginScheme::Https,
1375            None,
1376            ProtocolCapabilities::all(),
1377        );
1378        let target = query.host().clone();
1379        let port = query.origin_port();
1380        let freshness =
1381            Freshness::new(PROVIDER_AUTHORITY_NOW - 10, PROVIDER_AUTHORITY_NOW + 100).unwrap();
1382        let service = ServiceBinding::new(ServiceBindingInput {
1383            priority: None,
1384            service_target: target.clone(),
1385            mandatory_keys: Vec::new(),
1386            advertised_alpn: Vec::new(),
1387            selected_protocol: ApplicationProtocol::Http11,
1388            effective_port: port,
1389            transport: ServiceTransport::Tcp,
1390            connection_hints: Vec::new(),
1391            ech_config: None,
1392            parameters: Vec::new(),
1393        })
1394        .unwrap();
1395        let icann = ValidatedOriginPlan::new(OriginPlanInput {
1396            namespace: Namespace::Icann,
1397            query: query.clone(),
1398            alias_path: Vec::new(),
1399            terminal_target: target.clone(),
1400            endpoint_alias_path: Vec::new(),
1401            endpoint_target: target,
1402            endpoints: vec![SocketAddr::new(
1403                IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)),
1404                port.get(),
1405            )],
1406            service,
1407            tls_policy: TlsTrustPolicy::WebPkiAuthenticatedAbsence,
1408            tlsa_records: Vec::new(),
1409            provenance: EvidenceProvenance::IcannDoh {
1410                chain_state: IcannChainState::Secure,
1411            },
1412            freshness,
1413        })
1414        .unwrap();
1415        let hns_absence = ValidatedAbsence::new(
1416            Namespace::Hns,
1417            query.clone(),
1418            AbsenceKind::HnsCurrentUrkelNonInclusion,
1419            EvidenceProvenance::Hns {
1420                network: HnsNetwork::Regtest,
1421                tree_root: [21; 32],
1422                height: 42,
1423            },
1424            freshness,
1425        )
1426        .unwrap();
1427        decide_namespace(
1428            &query,
1429            RootLookup::Absent(hns_absence),
1430            RootLookup::Present(icann),
1431            SelectionPolicy::default(),
1432            PROVIDER_AUTHORITY_NOW,
1433        )
1434        .unwrap()
1435    }
1436
1437    #[allow(
1438        clippy::unnecessary_wraps,
1439        reason = "the deterministic test principal implements the optional authenticator result"
1440    )]
1441    fn provider_authority_ffi_webpki(
1442        request: &IcannOriginAuthenticationRequest,
1443    ) -> Option<IcannOriginAuthentication> {
1444        Some(request.attest_webpki_verified())
1445    }
1446
1447    fn provider_authority_ffi_context(
1448        engine: &Engine,
1449        decision: &NamespaceDecision,
1450    ) -> ProviderAuthorityContext {
1451        let context = engine
1452            .bind_icann_origin_context(
1453                decision,
1454                &provider_authority_ffi_webpki,
1455                PROVIDER_AUTHORITY_NOW,
1456            )
1457            .unwrap();
1458        engine
1459            .authorize_provider_injection(decision, &context, PROVIDER_AUTHORITY_NOW)
1460            .unwrap()
1461            .into_context()
1462            .unwrap()
1463    }
1464
1465    #[test]
1466    fn provider_authority_ffi_projects_and_checks_authorized_handle() {
1467        assert_eq!(std::mem::size_of::<HnsDaneProviderAuthorityInfoV1>(), 120);
1468        assert_eq!(
1469            hns_dane_engine_provider_v1_abi_version(),
1470            PROVIDER_AUTHORITY_ABI_VERSION_V1
1471        );
1472
1473        let engine = Arc::new(provider_authority_ffi_engine([41; 16]));
1474        let decision = provider_authority_ffi_decision("wallet.example");
1475        let authority = provider_authority_ffi_context(&engine, &decision);
1476        let authority = provider_authority_into_ffi(Arc::clone(&engine), authority);
1477        assert!(!authority.is_null());
1478
1479        let mut info = HnsDaneProviderAuthorityInfoV1::default();
1480        // SAFETY: authority is live and info is writable local storage.
1481        assert_eq!(
1482            unsafe { hns_dane_engine_provider_v1_authority_get_info(authority, &mut info) },
1483            HnsDaneStatus::Ok.code()
1484        );
1485        assert_eq!(info.struct_size, 120);
1486        assert_eq!(info.abi_version, PROVIDER_AUTHORITY_ABI_VERSION_V1);
1487        assert_eq!(info.origin_scheme, OriginScheme::Https as u8);
1488        assert_eq!(info.selected_namespace, Namespace::Icann as u8);
1489        assert_eq!(
1490            info.authenticated_context,
1491            AuthenticatedContextStatus::IcannWebPkiAuthenticatedAbsence as u8
1492        );
1493        assert_eq!(info.hns_network, HnsNetwork::Regtest as u8);
1494        assert_eq!(
1495            info.tls_policy,
1496            TlsTrustPolicy::WebPkiAuthenticatedAbsence as u8
1497        );
1498        assert_eq!(info.origin_port, 443);
1499        assert_eq!(info.service_port, 443);
1500        assert_eq!(info.runtime_session, [41; 16]);
1501        assert_eq!(info.runtime_generation, 1);
1502        assert_eq!(info.policy_generation, 1);
1503        assert_ne!(info.event_sequence, 0);
1504        assert_ne!(info.decision_fingerprint, [0; 32]);
1505        assert_eq!(info.valid_from, PROVIDER_AUTHORITY_NOW);
1506        assert_eq!(info.valid_until, PROVIDER_AUTHORITY_NOW + 100);
1507        assert_eq!(info.reserved0, 0);
1508        assert_eq!(info.reserved1, [0; 6]);
1509        assert_eq!(info.reserved, [0; 8]);
1510
1511        let mut required = 0usize;
1512        // SAFETY: authority is live and required is writable local storage.
1513        assert_eq!(
1514            unsafe {
1515                hns_dane_engine_provider_v1_authority_copy_host(
1516                    authority,
1517                    ptr::null_mut(),
1518                    0,
1519                    &mut required,
1520                )
1521            },
1522            HnsDaneStatus::BufferTooSmall.code()
1523        );
1524        assert_eq!(required, b"wallet.example".len());
1525        let mut host = vec![0; required];
1526        // SAFETY: authority is live, host has the reported capacity, and required is writable.
1527        assert_eq!(
1528            unsafe {
1529                hns_dane_engine_provider_v1_authority_copy_host(
1530                    authority,
1531                    host.as_mut_ptr(),
1532                    host.len(),
1533                    &mut required,
1534                )
1535            },
1536            HnsDaneStatus::Ok.code()
1537        );
1538        assert_eq!(host.as_slice(), b"wallet.example");
1539
1540        let mut current = 0;
1541        // SAFETY: authority is live and current is writable.
1542        assert_eq!(
1543            unsafe {
1544                hns_dane_engine_provider_v1_authority_is_current(
1545                    authority,
1546                    PROVIDER_AUTHORITY_NOW,
1547                    &mut current,
1548                )
1549            },
1550            HnsDaneStatus::Ok.code()
1551        );
1552        assert_eq!(current, 1);
1553
1554        let unrelated_query = Query::new(
1555            0x4040,
1556            Name::from_ascii("_443._tcp.other.example").unwrap(),
1557            RecordType::Tlsa,
1558        )
1559        .unwrap();
1560        engine
1561            .admit_resolution(ResolutionTransport::DirectAuthoritativeTcp, unrelated_query)
1562            .unwrap();
1563        // SAFETY: authority remains live and current is writable.
1564        assert_eq!(
1565            unsafe {
1566                hns_dane_engine_provider_v1_authority_is_current(
1567                    authority,
1568                    PROVIDER_AUTHORITY_NOW,
1569                    &mut current,
1570                )
1571            },
1572            HnsDaneStatus::Ok.code()
1573        );
1574        assert_eq!(current, 1);
1575
1576        let authority_engine = Arc::new(provider_authority_ffi_engine([42; 16]));
1577        let authority_decision = provider_authority_ffi_decision("mismatch.example");
1578        let mismatched_authority =
1579            provider_authority_ffi_context(&authority_engine, &authority_decision);
1580        let mismatched_engine = Arc::new(provider_authority_ffi_engine([43; 16]));
1581        let mismatched_engine_lifetime = Arc::downgrade(&mismatched_engine);
1582        let mismatched_authority =
1583            provider_authority_into_ffi(mismatched_engine, mismatched_authority);
1584        assert!(mismatched_engine_lifetime.upgrade().is_some());
1585        // SAFETY: mismatched_authority is live and current is writable.
1586        assert_eq!(
1587            unsafe {
1588                hns_dane_engine_provider_v1_authority_is_current(
1589                    mismatched_authority,
1590                    PROVIDER_AUTHORITY_NOW,
1591                    &mut current,
1592                )
1593            },
1594            HnsDaneStatus::Ok.code()
1595        );
1596        assert_eq!(current, 0);
1597        // SAFETY: mismatched_authority is its still-live caller-owned allocation.
1598        assert_eq!(
1599            unsafe { hns_dane_engine_provider_v1_authority_destroy(mismatched_authority) },
1600            HnsDaneStatus::Ok.code()
1601        );
1602        assert!(mismatched_engine_lifetime.upgrade().is_none());
1603
1604        // SAFETY: authority is live and current is writable.
1605        assert_eq!(
1606            unsafe {
1607                hns_dane_engine_provider_v1_authority_is_current(
1608                    authority,
1609                    PROVIDER_AUTHORITY_NOW + 100,
1610                    &mut current,
1611                )
1612            },
1613            HnsDaneStatus::Ok.code()
1614        );
1615        assert_eq!(current, 0);
1616
1617        engine
1618            .advance_authority_state(AuthorityState::Degraded)
1619            .unwrap();
1620        for state in [
1621            AuthorityState::HeaderSyncing,
1622            AuthorityState::HeaderCurrent,
1623            AuthorityState::ProofReady,
1624            AuthorityState::ResolutionTransportReady,
1625            AuthorityState::BrowserBridgeReady,
1626            AuthorityState::Active,
1627        ] {
1628            engine.advance_authority_state(state).unwrap();
1629        }
1630        // SAFETY: authority is live and current is writable.
1631        assert_eq!(
1632            unsafe {
1633                hns_dane_engine_provider_v1_authority_is_current(
1634                    authority,
1635                    PROVIDER_AUTHORITY_NOW,
1636                    &mut current,
1637                )
1638            },
1639            HnsDaneStatus::Ok.code()
1640        );
1641        assert_eq!(current, 0);
1642
1643        // SAFETY: each pointer is its still-live caller-owned allocation.
1644        assert_eq!(
1645            unsafe { hns_dane_engine_provider_v1_authority_destroy(authority) },
1646            HnsDaneStatus::Ok.code()
1647        );
1648    }
1649
1650    #[test]
1651    fn provider_authority_ffi_rejects_nulls_without_constructing_authority() {
1652        let mut info = HnsDaneProviderAuthorityInfoV1::default();
1653        let mut written = 0usize;
1654        let mut current = 0u8;
1655        // SAFETY: null inputs are explicitly admitted for fail-closed validation.
1656        assert_eq!(
1657            unsafe { hns_dane_engine_provider_v1_authority_get_info(ptr::null(), &mut info) },
1658            HnsDaneStatus::NullPointer.code()
1659        );
1660        // SAFETY: null inputs are explicitly admitted for fail-closed validation.
1661        assert_eq!(
1662            unsafe {
1663                hns_dane_engine_provider_v1_authority_copy_host(
1664                    ptr::null(),
1665                    ptr::null_mut(),
1666                    0,
1667                    &mut written,
1668                )
1669            },
1670            HnsDaneStatus::NullPointer.code()
1671        );
1672        // SAFETY: null inputs are explicitly admitted for fail-closed validation.
1673        assert_eq!(
1674            unsafe {
1675                hns_dane_engine_provider_v1_authority_is_current(
1676                    ptr::null(),
1677                    PROVIDER_AUTHORITY_NOW,
1678                    &mut current,
1679                )
1680            },
1681            HnsDaneStatus::NullPointer.code()
1682        );
1683        // SAFETY: destroying a null provider-authority handle is explicitly a no-op.
1684        assert_eq!(
1685            unsafe { hns_dane_engine_provider_v1_authority_destroy(ptr::null_mut()) },
1686            HnsDaneStatus::Ok.code()
1687        );
1688    }
1689
1690    #[test]
1691    fn c_abi_rejects_zero_runtime_session() {
1692        let session = [0u8; 16];
1693        let mut engine = ptr::null_mut();
1694        // SAFETY: All pointers reference live local storage of the documented sizes.
1695        let status = unsafe {
1696            hns_dane_engine_v1_create(
1697                session.as_ptr(),
1698                Network::Mainnet as u8,
1699                ptr::null(),
1700                0,
1701                &mut engine,
1702            )
1703        };
1704        assert_eq!(status, HnsDaneStatus::InvalidArgument.code());
1705        assert!(engine.is_null());
1706    }
1707
1708    #[test]
1709    fn c_abi_policy_round_trip_and_provider_default() {
1710        assert_eq!(std::mem::size_of::<HnsDanePolicyV1>(), 32);
1711        assert_eq!(std::mem::size_of::<HnsDanePolicyV2>(), 32);
1712        assert_eq!(std::mem::size_of::<HnsDaneTransportContextV1>(), 400);
1713        assert_eq!(std::mem::size_of::<HnsDaneResultV1>(), 40);
1714        assert_eq!(hns_dane_engine_v1_abi_version(), ABI_VERSION);
1715        assert_eq!(hns_dane_engine_v2_abi_version(), POLICY_ABI_VERSION_V2);
1716
1717        let session = [9u8; 16];
1718        let mut engine = ptr::null_mut();
1719        // SAFETY: All pointers reference live local storage of the documented sizes.
1720        let status = unsafe {
1721            hns_dane_engine_v1_create(
1722                session.as_ptr(),
1723                Network::Mainnet as u8,
1724                ptr::null(),
1725                0,
1726                &mut engine,
1727            )
1728        };
1729        assert_eq!(status, HnsDaneStatus::Ok.code());
1730        assert!(!engine.is_null());
1731
1732        let mut policy = HnsDanePolicyV1::default();
1733        // SAFETY: engine is live and policy is writable.
1734        assert_eq!(
1735            unsafe { hns_dane_engine_v1_get_policy(engine, &mut policy) },
1736            HnsDaneStatus::Ok.code()
1737        );
1738        assert_eq!(policy.hnsr, HnsrPolicy::client_relay_default().bits());
1739        assert_eq!(policy.provider_flags, PROVIDER_ODOH_PROXY);
1740        assert_eq!(policy.provider_flags & PROVIDER_ODOH_TARGET, 0);
1741        policy.dns_relay_requester = DnsRelayRequesterPolicy::Disabled as u8;
1742        let mut generation = 0;
1743        let mut effects = 0;
1744        // SAFETY: engine and all structure/output pointers are live.
1745        assert_eq!(
1746            unsafe {
1747                hns_dane_engine_v1_set_policy(engine, &policy, &mut generation, &mut effects)
1748            },
1749            HnsDaneStatus::Ok.code()
1750        );
1751        assert_eq!(generation, 2);
1752        assert_ne!(effects & EFFECT_CANCEL_OR_DRAIN, 0);
1753
1754        let mut required = 0usize;
1755        // SAFETY: engine is live and required is writable.
1756        assert_eq!(
1757            unsafe { hns_dane_engine_v1_export_policy(engine, ptr::null_mut(), 0, &mut required,) },
1758            HnsDaneStatus::BufferTooSmall.code()
1759        );
1760        assert_eq!(required, 32);
1761
1762        // SAFETY: engine is the live allocation returned by create.
1763        assert_eq!(
1764            unsafe { hns_dane_engine_v1_destroy(engine) },
1765            HnsDaneStatus::Ok.code()
1766        );
1767    }
1768
1769    #[test]
1770    fn policy_v2_exposes_consent_and_v1_can_only_fail_closed() {
1771        let session = [8u8; 16];
1772        let mut engine = ptr::null_mut();
1773        // SAFETY: All pointers reference live local storage of documented sizes.
1774        assert_eq!(
1775            unsafe {
1776                hns_dane_engine_v1_create(
1777                    session.as_ptr(),
1778                    Network::Mainnet as u8,
1779                    ptr::null(),
1780                    0,
1781                    &mut engine,
1782                )
1783            },
1784            HnsDaneStatus::Ok.code()
1785        );
1786
1787        let mut policy_v2 = HnsDanePolicyV2::default();
1788        // SAFETY: engine is live and policy_v2 is writable.
1789        assert_eq!(
1790            unsafe { hns_dane_engine_v2_get_policy(engine, &mut policy_v2) },
1791            HnsDaneStatus::Ok.code()
1792        );
1793        assert_eq!(policy_v2.user_configured_recursive_hns_doh, 0);
1794        policy_v2.user_configured_recursive_hns_doh = 1;
1795        let mut generation = 0;
1796        let mut effects = 0;
1797        // SAFETY: engine and all structure/output pointers are live.
1798        assert_eq!(
1799            unsafe {
1800                hns_dane_engine_v2_set_policy(engine, &policy_v2, &mut generation, &mut effects)
1801            },
1802            HnsDaneStatus::Ok.code()
1803        );
1804        assert_eq!(generation, 2);
1805        assert_ne!(effects & EFFECT_CLEAR_REQUESTER, 0);
1806
1807        let mut count = 0;
1808        // SAFETY: engine is live and count is writable.
1809        assert_eq!(
1810            unsafe { hns_dane_engine_v1_transport_count(engine, &mut count) },
1811            HnsDaneStatus::Ok.code()
1812        );
1813        let mut terminal = u8::MAX;
1814        // SAFETY: engine is live and terminal is writable.
1815        assert_eq!(
1816            unsafe { hns_dane_engine_v1_transport_at(engine, count - 1, &mut terminal) },
1817            HnsDaneStatus::Ok.code()
1818        );
1819        assert_eq!(
1820            terminal,
1821            ResolutionTransport::UserConfiguredRecursiveHnsDoh as u8
1822        );
1823        for state in 2..=5 {
1824            // SAFETY: engine is live and each state is the next valid transition.
1825            assert_eq!(
1826                unsafe { hns_dane_engine_v1_advance_authority(engine, state) },
1827                HnsDaneStatus::Ok.code()
1828            );
1829        }
1830        let owner = b"_443._tcp.example";
1831        let mut attempt = ptr::null_mut();
1832        // SAFETY: engine and output are live; owner is readable.
1833        assert_eq!(
1834            unsafe {
1835                hns_dane_engine_v1_admit(
1836                    engine,
1837                    ResolutionTransport::LocalHnsProof as u8,
1838                    1,
1839                    owner.as_ptr(),
1840                    owner.len(),
1841                    RecordType::Tlsa.code(),
1842                    &mut attempt,
1843                )
1844            },
1845            HnsDaneStatus::TransportDisabled.code()
1846        );
1847        assert!(attempt.is_null());
1848
1849        let mut policy_v1 = HnsDanePolicyV1::default();
1850        // SAFETY: engine is live and policy_v1 is writable.
1851        assert_eq!(
1852            unsafe { hns_dane_engine_v1_get_policy(engine, &mut policy_v1) },
1853            HnsDaneStatus::AbiMismatch.code()
1854        );
1855
1856        let enabled = PolicyConfig {
1857            user_configured_recursive_hns_doh: true,
1858            ..PolicyConfig::default()
1859        };
1860        policy_v1 = policy_to_ffi_v1(PolicySnapshot::new(generation, enabled).unwrap());
1861        // SAFETY: engine and all structure/output pointers are live. Policy V1
1862        // deliberately decodes its unrepresentable consent field as disabled.
1863        assert_eq!(
1864            unsafe {
1865                hns_dane_engine_v1_set_policy(engine, &policy_v1, &mut generation, &mut effects)
1866            },
1867            HnsDaneStatus::Ok.code()
1868        );
1869        assert_eq!(generation, 3);
1870
1871        // SAFETY: engine is live and policy_v2 is writable.
1872        assert_eq!(
1873            unsafe { hns_dane_engine_v2_get_policy(engine, &mut policy_v2) },
1874            HnsDaneStatus::Ok.code()
1875        );
1876        assert_eq!(policy_v2.user_configured_recursive_hns_doh, 0);
1877
1878        // SAFETY: engine is the live allocation returned by create.
1879        assert_eq!(
1880            unsafe { hns_dane_engine_v1_destroy(engine) },
1881            HnsDaneStatus::Ok.code()
1882        );
1883    }
1884
1885    #[test]
1886    fn c_transport_context_requires_distinct_utf8_identities() {
1887        let mut context = HnsDaneTransportContextV1::default();
1888        context.proxy_identity[..5].copy_from_slice(b"proxy");
1889        context.proxy_identity_len = 5;
1890        context.target_identity[..6].copy_from_slice(b"target");
1891        context.target_identity_len = 6;
1892
1893        let decoded = context_from_ffi(&context).unwrap();
1894        assert_eq!(decoded.proxy_identity.as_deref(), Some("proxy"));
1895        assert_eq!(decoded.target_identity.as_deref(), Some("target"));
1896    }
1897
1898    #[test]
1899    fn c_abi_derives_dane_match_and_rejects_caller_dane_bits() {
1900        let session = [3u8; 16];
1901        let mut engine = ptr::null_mut();
1902        // SAFETY: All pointers reference live local storage of documented sizes.
1903        assert_eq!(
1904            unsafe {
1905                hns_dane_engine_v1_create(
1906                    session.as_ptr(),
1907                    Network::Mainnet as u8,
1908                    ptr::null(),
1909                    0,
1910                    &mut engine,
1911                )
1912            },
1913            HnsDaneStatus::Ok.code()
1914        );
1915        for state in 1..=6 {
1916            // SAFETY: engine is live and each state is the next valid transition.
1917            assert_eq!(
1918                unsafe { hns_dane_engine_v1_advance_authority(engine, state) },
1919                HnsDaneStatus::Ok.code()
1920            );
1921        }
1922
1923        let owner = b"_443._tcp.example";
1924        let mut attempt = ptr::null_mut();
1925        // SAFETY: engine and output are live; owner is readable.
1926        assert_eq!(
1927            unsafe {
1928                hns_dane_engine_v1_admit(
1929                    engine,
1930                    ResolutionTransport::DirectAuthoritativeTcp as u8,
1931                    0x2345,
1932                    owner.as_ptr(),
1933                    owner.len(),
1934                    RecordType::Tlsa.code(),
1935                    &mut attempt,
1936                )
1937            },
1938            HnsDaneStatus::Ok.code()
1939        );
1940
1941        let certificate = decode_hex(include_str!("../fixtures/dane/self-signed-cert.der.hex"));
1942        let query = Query::new(
1943            0x2345,
1944            Name::from_ascii("_443._tcp.example").unwrap(),
1945            RecordType::Tlsa,
1946        )
1947        .unwrap();
1948        let response = Message {
1949            header: Header {
1950                id: query.id,
1951                flags: Flags::from_bits(0x8400),
1952                question_count: 1,
1953                answer_count: 1,
1954                authority_count: 0,
1955                additional_count: 0,
1956            },
1957            questions: vec![query.question.clone()],
1958            answers: vec![ResourceRecord {
1959                name: query.question.name,
1960                record_type: RecordType::Tlsa,
1961                class: hns_dns_wire::CLASS_IN,
1962                ttl: 300,
1963                rdata: Rdata::Tlsa(Tlsa {
1964                    usage: 3,
1965                    selector: 0,
1966                    matching_type: 0,
1967                    association_data: certificate.clone(),
1968                }),
1969            }],
1970            authorities: Vec::new(),
1971            additionals: Vec::new(),
1972        }
1973        .encode(u16::MAX.into())
1974        .unwrap();
1975        let mut result = HnsDaneResultV1::default();
1976
1977        // SAFETY: Every pointer references readable/writable local storage.
1978        assert_eq!(
1979            unsafe {
1980                hns_dane_engine_v1_validate_response(
1981                    engine,
1982                    attempt,
1983                    response.as_ptr(),
1984                    response.len(),
1985                    certificate.as_ptr(),
1986                    certificate.len(),
1987                    ptr::null(),
1988                    0x3f,
1989                    &mut result,
1990                )
1991            },
1992            HnsDaneStatus::InvalidArgument.code()
1993        );
1994        // SAFETY: Every pointer references readable/writable local storage.
1995        assert_eq!(
1996            unsafe {
1997                hns_dane_engine_v1_validate_response(
1998                    engine,
1999                    attempt,
2000                    response.as_ptr(),
2001                    response.len(),
2002                    certificate.as_ptr(),
2003                    certificate.len(),
2004                    ptr::null(),
2005                    PREREQUISITES_ALL_VERIFIED,
2006                    &mut result,
2007                )
2008            },
2009            HnsDaneStatus::Ok.code()
2010        );
2011        assert_eq!(result.tlsa_record_index, 0);
2012        assert_eq!(result.tlsa_usage, 3);
2013        assert_eq!(result.tlsa_selector, 0);
2014        assert_eq!(result.tlsa_matching_type, 0);
2015
2016        // SAFETY: handles are the live allocations returned above.
2017        assert_eq!(
2018            unsafe { hns_dane_engine_v1_attempt_destroy(attempt) },
2019            HnsDaneStatus::Ok.code()
2020        );
2021        // SAFETY: handle is the live allocation returned above.
2022        assert_eq!(
2023            unsafe { hns_dane_engine_v1_destroy(engine) },
2024            HnsDaneStatus::Ok.code()
2025        );
2026    }
2027}