Skip to main content

rings_node/onion/
mod.rs

1//! The onion privacy layer: its directory, route selection and loop data plane.
2//!
3//! This module deliberately sits in `rings-node`, not `rings-core`: Chord
4//! remains the storage and discovery substrate, while exit policy is an
5//! application protocol decision.
6//!
7//! The data plane runs client-sealed loops of fixed-width Sphinx cells (`circuit`, `sphinx`). A
8//! loop evaluates a pipeline over the static signature `Σ` of operation symbols (`signature`):
9//! every hop's step interprets the identity symbol `relay`, and each node's Σ-algebra interprets
10//! the world-facing symbols it registers, as sessions (`session`) over their worlds (`tcp`,
11//! `https`). Route selection places a pipeline on a guard-closed loop (`loop_shape`) whose every
12//! position is a node registering that position's symbol at its current process epoch.
13
14use std::borrow::Borrow;
15use std::sync::Arc;
16use std::sync::RwLock;
17use std::time::Duration;
18
19use async_trait::async_trait;
20use rings_core::delegation::DelegateeKey;
21use rings_core::dht::Did;
22use rings_core::domain_tag;
23use rings_core::ecc::PublicKey;
24use rings_core::ecc::VerificationPublicKey;
25use rings_core::error::Error as CoreError;
26use rings_core::error::Result as CoreResult;
27use rings_core::message::DomainTag;
28use rings_core::message::MessageSigner;
29use rings_core::message::MessageVerification;
30use rings_core::utils::SharedClock;
31#[cfg(all(test, not(target_family = "wasm")))]
32use rings_core::utils::SystemClock;
33use serde::Deserialize;
34use serde::Serialize;
35
36use crate::descriptor::heard_elements;
37use crate::descriptor::latest_valid_by_key;
38use crate::descriptor::sign_descriptor_body;
39use crate::descriptor::RegistryElement;
40use crate::descriptor::SignedDescriptor;
41use crate::descriptor::SignedDescriptorBody;
42use crate::error::Error;
43use crate::error::Result;
44use crate::online::OnlineNodeType;
45use crate::registration::DhtRegistrationPublisher;
46use crate::registration::LeaseTerms;
47use crate::registration::RegistrationContext;
48use crate::registration::RegistrationTask;
49
50pub mod circuit;
51pub(crate) mod directory;
52mod entry_guard;
53pub(crate) mod exit_accounting;
54mod failure;
55#[cfg(rings_native)]
56mod gateway;
57#[cfg(any(rings_native, rings_browser))]
58pub mod https;
59pub(crate) mod invoke_accounting;
60pub mod invoke_descriptor;
61mod loop_shape;
62#[cfg(rings_native)]
63pub mod native;
64pub mod pipeline;
65pub mod proxy;
66mod role;
67pub mod route;
68pub(crate) mod runtime;
69pub(crate) mod session;
70pub mod signature;
71pub(crate) mod sphinx;
72pub mod target;
73#[cfg(rings_native)]
74pub mod tcp;
75pub mod udp;
76
77pub use circuit::OnionInvokeBackend;
78pub use circuit::OnionInvokeCall;
79pub use circuit::OnionInvokeFn;
80pub use entry_guard::OnionEntryGuardState;
81pub use entry_guard::OnionEntryGuardStorage;
82pub(crate) use entry_guard::OnionEntryGuards;
83pub use failure::OnionExitFailure;
84pub use failure::OnionRouteError;
85#[cfg(rings_native)]
86pub use gateway::NativeOnionGatewayConnector;
87pub use invoke_descriptor::OnionInvokeDescriptor;
88pub use invoke_descriptor::OnionInvokeDescriptorBody;
89pub use invoke_descriptor::OnionInvokeDescriptorDecodeReport;
90pub use invoke_descriptor::OnionInvokePolicy;
91pub(crate) use invoke_descriptor::OnionInvokeRegistration;
92pub use invoke_descriptor::ONION_INVOKES_TOPIC;
93pub use loop_shape::OnionLoop;
94pub(crate) use loop_shape::OnionLoopRelay;
95pub use loop_shape::OnionLoopRole;
96pub use loop_shape::OnionLoopShape;
97pub(crate) use loop_shape::OnionPipelineSymbols;
98pub use loop_shape::MAX_ONION_LOOP_HOPS;
99pub use loop_shape::MAX_ONION_LOOP_SYMBOLS;
100pub use loop_shape::ONION_SEGMENT_RELAYS;
101pub use pipeline::OnionInvokeArguments;
102pub use pipeline::OnionInvokePipeline;
103pub use pipeline::OnionInvokeStage;
104pub use pipeline::OnionPipeline;
105pub use pipeline::OnionPipelineError;
106pub use pipeline::OnionPipelineTerm;
107pub use pipeline::OnionValueType;
108pub use role::OnionExitOffer;
109pub use role::OnionInvokeOffer;
110pub use role::OnionRole;
111pub(crate) use route::select_onion_route_from_candidates;
112pub use route::OnionPipelineRoute;
113pub use route::OnionPipelineRouteRequest;
114pub use route::OnionRoute;
115pub(crate) use route::OnionRouteCandidates;
116pub use route::OnionRouteHop;
117pub use route::OnionRouteRequest;
118pub use runtime::OnionPipelineHandle;
119pub use signature::OnionBackendName;
120pub use signature::OnionInputType;
121pub use signature::OnionInvokeShape;
122pub use signature::OnionLatencyClass;
123pub use signature::OnionServiceName;
124pub use signature::OnionShape;
125pub use signature::OnionWidthClass;
126pub use signature::ONION_BACKEND_NAME_MAX_BYTES;
127pub use sphinx::class::OnionLoopClass;
128pub use target::OnionProxyTarget;
129pub use target::OnionProxyTargetError;
130#[cfg(rings_native)]
131pub use udp::NativeOnionUdpSession;
132pub use udp::OnionUdpBindConfig;
133pub use udp::OnionUdpBindMode;
134pub use udp::OnionUdpClientFrame;
135pub use udp::OnionUdpPinholeTable;
136pub use udp::OnionUdpServerFrame;
137
138/// DHT topic used for application-layer onion exit descriptors.
139pub const ONION_EXITS_TOPIC: &str = "onion_exits";
140
141/// Process epoch `e_n` of one node process (#834 D2), drawn afresh at every process start.
142///
143/// Every symbol a process registers carries its `e_n`: `relay` in the online-node capabilities and
144/// every other symbol in its signed descriptor, so a process registers exactly one epoch,
145///
146/// ```text
147/// ∀ f ∈ Σ_n.  epoch(f) = e_n,
148/// ```
149///
150/// and a layer sealed for an earlier process of the same node names an epoch no current
151/// registration carries.
152#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
153pub struct OnionProcessEpoch([u8; 16]);
154
155impl OnionProcessEpoch {
156    /// Build a process epoch from explicit bytes.
157    pub const fn new(bytes: [u8; 16]) -> Self {
158        Self(bytes)
159    }
160
161    /// Return the epoch bytes, the `e` field of the uniform layer (#834 D6″).
162    pub(crate) const fn to_bytes(self) -> [u8; 16] {
163        self.0
164    }
165
166    /// Draw a fresh process epoch from an explicit cryptographic RNG.
167    pub fn from_rng(rng: &mut impl rand::RngCore) -> Self {
168        let mut bytes = [0_u8; 16];
169        rng.fill_bytes(&mut bytes);
170        Self(bytes)
171    }
172
173    /// Draw a fresh process epoch for one process lifetime.
174    pub fn random() -> Self {
175        Self::from_rng(&mut rings_core::utils::SystemEntropy)
176    }
177}
178
179/// The current process epoch `e_n` of this node, shared by the onion admission state, which
180/// renews it, and the registrations, which publish it at every heartbeat (#834 D2, L9).
181///
182/// Law: the epoch changes only by `renew`, to an epoch drawn independently and
183/// uniformly, when admission detects a clock rollback beyond `X₀`; every registration published
184/// after the renewal names the new epoch, and every layer sealed for the old one is rejected.
185#[derive(Clone, Debug)]
186pub struct OnionProcessEpochCell(Arc<RwLock<OnionProcessEpoch>>);
187
188impl OnionProcessEpochCell {
189    /// A cell holding `epoch`, the epoch drawn at process start.
190    pub fn new(epoch: OnionProcessEpoch) -> Self {
191        Self(Arc::new(RwLock::new(epoch)))
192    }
193
194    /// The current epoch.
195    pub fn get(&self) -> OnionProcessEpoch {
196        self.0
197            .read()
198            .map_or_else(|poisoned| *poisoned.into_inner(), |epoch| *epoch)
199    }
200
201    /// Replace the current epoch by `epoch`, after an admission reset.
202    pub(crate) fn renew(&self, epoch: OnionProcessEpoch) {
203        match self.0.write() {
204            Ok(mut current) => *current = epoch,
205            Err(poisoned) => *poisoned.into_inner() = epoch,
206        }
207    }
208}
209
210const DEFAULT_ONION_EXIT_HEARTBEAT_INTERVAL_SECS: u64 = 30;
211const DEFAULT_ONION_EXIT_TTL_SECS: u64 = 90;
212/// Message family of the onion-exit descriptor signature.
213const ONION_EXIT_DESCRIPTOR_DOMAIN_TAG: DomainTag = domain_tag!("rings-node:onion-exit-descriptor");
214
215/// Default onion-exit registry heartbeat interval in seconds.
216pub(crate) const fn default_onion_exit_heartbeat_interval_secs() -> u64 {
217    DEFAULT_ONION_EXIT_HEARTBEAT_INTERVAL_SECS
218}
219
220/// Default onion-exit registry descriptor TTL in seconds.
221pub(crate) const fn default_onion_exit_ttl_secs() -> u64 {
222    DEFAULT_ONION_EXIT_TTL_SECS
223}
224
225/// Default onion relay advertisement enablement.
226pub(crate) const fn default_advertise_onion_relay() -> bool {
227    false
228}
229
230/// Default onion exit advertisement enablement.
231pub(crate) const fn default_advertise_onion_exit() -> bool {
232    false
233}
234
235/// Default native exit services: the world-facing symbols of the onion signature, in table order.
236/// It is only published when onion-exit advertisement is enabled.
237pub fn default_onion_exit_services() -> Vec<OnionServiceName> {
238    OnionServiceName::world_facing().collect()
239}
240
241/// Standard HTTPS onion-exit service set: the single `https` symbol of the onion signature.
242pub fn https_onion_exit_services() -> Vec<OnionServiceName> {
243    vec![OnionServiceName::https()]
244}
245
246/// Default exit policy. It is intentionally closed until the operator configures targets.
247pub fn default_onion_exit_policy() -> OnionExitPolicy {
248    OnionExitPolicy::default()
249}
250
251/// Signed policy fields for an onion exit.
252///
253/// Unknown fields are refused, so a removed limit (`max_circuits`, `max_streams_per_circuit`)
254/// in an old config fails to load rather than leaving the operator's limit unspecified.
255#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
256#[serde(deny_unknown_fields)]
257pub struct OnionExitPolicy {
258    /// Target allow-list entries understood by the exit implementation. Empty means closed.
259    pub allowed_targets: Vec<OnionExitTarget>,
260    /// Target deny-list entries understood by the exit implementation. Deny entries override allows.
261    pub denied_targets: Vec<OnionExitTarget>,
262    /// Maximum concurrent sessions this exit wants to serve. `0` means unspecified.
263    pub max_sessions: u32,
264    /// Maximum bytes per minute. `0` means unspecified.
265    pub max_bytes_per_minute: u64,
266}
267
268/// One entry of an onion exit policy: a pattern over target authorities.
269///
270/// ```text
271/// OnionExitTarget = Any | AnyHost(port) | Authority(host, port)
272/// encode:  *:*      *:port          host:port | [ipv6]:port        (canonical, lowercase)
273/// matches(Any, t) = ⊤    matches(AnyHost(p), t) = (port(t) = p)
274/// matches(Authority(a), t) = (a = t)
275/// ```
276///
277/// Laws: `parse ∘ encode = Ok` on every pattern, `encode ∘ parse` is canonicalisation, and
278/// `matches` is monotone in the pattern order `Authority(h, p) ≤ AnyHost(p) ≤ Any`. The port
279/// wildcard is how an operator expresses HTTPS-only egress: `https` is a fetch only, so a TLS
280/// tunnel is `tcp` restricted to `*:443` (#834 D1′).
281#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
282#[serde(try_from = "String", into = "String")]
283pub struct OnionExitTarget(OnionExitTargetPattern);
284
285/// The pattern of an [`OnionExitTarget`]; see its encoding table.
286#[derive(Clone, Debug, Eq, PartialEq)]
287enum OnionExitTargetPattern {
288    /// `*:*`: every target.
289    Any,
290    /// `*:port`: every host on one port.
291    AnyHost(u16),
292    /// `host:port`: exactly one canonical authority.
293    Authority(OnionProxyTarget),
294}
295
296impl OnionExitTarget {
297    /// The wildcard host `*` of a pattern.
298    const WILDCARD: &'static str = "*";
299
300    /// Parse and canonicalize an exit target pattern: `*`, `*:*`, `*:port` or `host:port`.
301    pub fn parse(target: impl AsRef<str>) -> Result<Self> {
302        let raw = target.as_ref().trim();
303        let invalid = |error: &dyn std::fmt::Display| {
304            Error::InvalidConfig(format!(
305                "invalid onion exit target {:?}; expected host:port, *:port or *:*: {error}",
306                target.as_ref()
307            ))
308        };
309        let pattern = match raw.split_once(':') {
310            _ if raw == Self::WILDCARD => OnionExitTargetPattern::Any,
311            Some((Self::WILDCARD, Self::WILDCARD)) => OnionExitTargetPattern::Any,
312            Some((Self::WILDCARD, port)) => match port.parse::<u16>() {
313                Ok(0) => return Err(invalid(&OnionProxyTargetError::ZeroPort)),
314                Ok(port) => OnionExitTargetPattern::AnyHost(port),
315                Err(_) => return Err(invalid(&OnionProxyTargetError::InvalidPort)),
316            },
317            _ => OnionExitTargetPattern::Authority(
318                OnionProxyTarget::parse_authority(raw).map_err(|error| invalid(&error))?,
319            ),
320        };
321        Ok(Self(pattern))
322    }
323
324    /// Return whether `target` falls under this pattern.
325    pub fn matches(&self, target: &OnionProxyTarget) -> bool {
326        match &self.0 {
327            OnionExitTargetPattern::Any => true,
328            OnionExitTargetPattern::AnyHost(port) => target.port() == *port,
329            OnionExitTargetPattern::Authority(authority) => authority == target,
330        }
331    }
332
333    /// Return whether this target pattern is a single canonical public IP-literal authority.
334    pub fn is_public_ip_literal_authority(&self) -> bool {
335        matches!(
336            &self.0,
337            OnionExitTargetPattern::Authority(target)
338                if target::validate_public_ip_literal(target).is_ok()
339        )
340    }
341}
342
343impl std::fmt::Display for OnionExitTarget {
344    /// The canonical encoding of the pattern.
345    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346        match &self.0 {
347            OnionExitTargetPattern::Any => write!(formatter, "*:*"),
348            OnionExitTargetPattern::AnyHost(port) => write!(formatter, "*:{port}"),
349            OnionExitTargetPattern::Authority(authority) => {
350                formatter.write_str(authority.authority().as_str())
351            }
352        }
353    }
354}
355
356impl TryFrom<String> for OnionExitTarget {
357    type Error = String;
358
359    fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
360        Self::parse(&value).map_err(|error| error.to_string())
361    }
362}
363
364impl From<OnionExitTarget> for String {
365    fn from(target: OnionExitTarget) -> Self {
366        target.to_string()
367    }
368}
369
370impl OnionExitPolicy {
371    /// Build a policy from raw target strings at configuration or API boundaries.
372    pub fn from_target_strings(
373        allowed_targets: Vec<String>,
374        denied_targets: Vec<String>,
375    ) -> Result<Self> {
376        Ok(Self {
377            allowed_targets: parse_exit_targets(allowed_targets)?,
378            denied_targets: parse_exit_targets(denied_targets)?,
379            ..Self::default()
380        })
381    }
382
383    /// Return whether this policy denies every exit target.
384    pub fn is_closed(&self) -> bool {
385        self.allowed_targets.is_empty()
386    }
387
388    /// Validate target lists for an advertised onion exit.
389    pub fn validate_targets(&self) -> Result<()> {
390        if self.is_closed() {
391            return Err(Error::InvalidConfig(
392                "advertise_onion_exit requires at least one valid onion_exit_policy allowed target"
393                    .to_string(),
394            ));
395        }
396        Ok(())
397    }
398
399    /// Validate target lists for a browser onion exit, which can only enforce address-level
400    /// public-IP admission on explicit public IP-literal targets.
401    pub fn validate_browser_targets(&self) -> Result<()> {
402        self.validate_targets()?;
403        if let Some(target) = self
404            .allowed_targets
405            .iter()
406            .find(|target| !target.is_public_ip_literal_authority())
407        {
408            return Err(Error::InvalidConfig(format!(
409                "browser HTTPS onion exit policy only supports public IP-literal allowed_targets, got {target}"
410            )));
411        }
412        Ok(())
413    }
414
415    /// Return whether `target` is admitted by this policy: some allow entry matches it and no
416    /// deny entry does.
417    pub fn allows_target(&self, target: &OnionProxyTarget) -> bool {
418        !self.is_closed() && !self.denies(target) && self.allows(target)
419    }
420
421    /// Return whether this policy can admit an unconnected `onion::udp` socket bound under `mode`.
422    ///
423    /// Unlike `tcp` and `https`, an `onion::udp` session opens with a synthetic bind-mode authority
424    /// (`0.0.0.0:1`, `0.0.0.0:2`, `[::]:1`, or `[::]:2`) and enforces [`Self::allows_target`] on
425    /// every inbound and outbound peer datagram. Session open is admitted iff the policy is open
426    /// and at least one allowed pattern can match an IP-literal peer of `mode`'s address family
427    /// without being shadowed by `denied_targets`.
428    pub fn allows_udp_bind(&self, mode: OnionUdpBindMode) -> bool {
429        if self.is_closed()
430            || self
431                .denied_targets
432                .iter()
433                .any(|denied| matches!(denied.0, OnionExitTargetPattern::Any))
434        {
435            return false;
436        }
437        self.allowed_targets.iter().any(|allowed| match &allowed.0 {
438            OnionExitTargetPattern::Any => true,
439            OnionExitTargetPattern::AnyHost(port) => !self.denied_targets.iter().any(|denied| {
440                matches!(
441                    denied.0,
442                    OnionExitTargetPattern::AnyHost(denied_port) if denied_port == *port
443                )
444            }),
445            OnionExitTargetPattern::Authority(authority) => {
446                authority
447                    .host()
448                    .parse::<std::net::IpAddr>()
449                    .is_ok_and(|ip| ip.is_ipv6() == mode.is_ipv6())
450                    && !self.denies(authority)
451            }
452        })
453    }
454
455    /// Whether an allow entry matches `target`.
456    fn allows(&self, target: &OnionProxyTarget) -> bool {
457        self.allowed_targets
458            .iter()
459            .any(|allowed| allowed.matches(target))
460    }
461
462    /// Whether a deny entry matches `target`.
463    fn denies(&self, target: &OnionProxyTarget) -> bool {
464        self.denied_targets
465            .iter()
466            .any(|denied| denied.matches(target))
467    }
468}
469
470fn parse_exit_targets(targets: Vec<String>) -> Result<Vec<OnionExitTarget>> {
471    targets
472        .into_iter()
473        .map(OnionExitTarget::parse)
474        .collect::<Result<Vec<_>>>()
475}
476
477/// Descriptor fields covered by the onion-exit signature.
478#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
479pub struct OnionExitDescriptorBody {
480    /// DID of the exit node/account.
481    pub did: Did,
482    /// Account public key corresponding to `did`.
483    pub public_key: VerificationPublicKey,
484    /// Delegation public key: the Sphinx key `pk_i` a loop's header blinds the exit's layer to.
485    pub delegatee_public_key: PublicKey<33>,
486    /// Process epoch `e_n` of the registering process, equal to its `relay` registration's.
487    pub process_epoch: OnionProcessEpoch,
488    /// Runtime family of this exit node.
489    pub node_type: OnlineNodeType,
490    /// Network identifier.
491    pub network_id: u32,
492    /// Service this descriptor is willing to expose.
493    pub service: OnionServiceName,
494    /// Signed exit policy.
495    pub policy: OnionExitPolicy,
496    /// Process start timestamp in milliseconds since Unix epoch.
497    pub started_at_ms: u128,
498    /// Freshness window `T` in milliseconds: a reader holds the descriptor live only while it
499    /// heard it within `T` (see the lease law of `descriptor`).
500    pub fresh_for_ms: u64,
501    /// Lease end `ℓ` in milliseconds since Unix epoch.
502    pub expires_at_ms: u128,
503    /// Node software version.
504    pub version: String,
505}
506
507impl OnionExitDescriptorBody {
508    fn body_ref(&self) -> OnionExitDescriptorBodyRef<'_> {
509        OnionExitDescriptorBodyRef {
510            did: self.did,
511            public_key: &self.public_key,
512            delegatee_public_key: &self.delegatee_public_key,
513            process_epoch: self.process_epoch,
514            node_type: &self.node_type,
515            network_id: self.network_id,
516            service: &self.service,
517            policy: &self.policy,
518            started_at_ms: self.started_at_ms,
519            fresh_for_ms: self.fresh_for_ms,
520            expires_at_ms: self.expires_at_ms,
521            version: self.version.as_str(),
522        }
523    }
524
525    fn signing_data(&self) -> CoreResult<Vec<u8>> {
526        self.body_ref().signing_data()
527    }
528}
529
530impl SignedDescriptorBody for OnionExitDescriptorBody {
531    type Descriptor = OnionExitDescriptor;
532
533    const DOMAIN_TAG: DomainTag = ONION_EXIT_DESCRIPTOR_DOMAIN_TAG;
534
535    fn body_did(&self) -> Did {
536        self.did
537    }
538
539    fn body_public_key(&self) -> &VerificationPublicKey {
540        &self.public_key
541    }
542
543    fn body_network_id(&self) -> u32 {
544        self.network_id
545    }
546
547    fn body_signing_data(&self) -> CoreResult<Vec<u8>> {
548        self.signing_data()
549    }
550
551    fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
552        OnionExitDescriptor {
553            did: self.did,
554            public_key: self.public_key,
555            delegatee_public_key: self.delegatee_public_key,
556            process_epoch: self.process_epoch,
557            node_type: self.node_type,
558            network_id: self.network_id,
559            service: self.service,
560            policy: self.policy,
561            started_at_ms: self.started_at_ms,
562            heartbeat_at_ms: 0,
563            fresh_for_ms: self.fresh_for_ms,
564            expires_at_ms: self.expires_at_ms,
565            version: self.version,
566            signature,
567        }
568    }
569}
570
571#[derive(Serialize)]
572struct OnionExitDescriptorBodyRef<'a> {
573    did: Did,
574    public_key: &'a VerificationPublicKey,
575    delegatee_public_key: &'a PublicKey<33>,
576    process_epoch: OnionProcessEpoch,
577    node_type: &'a OnlineNodeType,
578    network_id: u32,
579    service: &'a OnionServiceName,
580    policy: &'a OnionExitPolicy,
581    started_at_ms: u128,
582    fresh_for_ms: u64,
583    expires_at_ms: u128,
584    version: &'a str,
585}
586
587impl OnionExitDescriptorBodyRef<'_> {
588    fn signing_data(&self) -> CoreResult<Vec<u8>> {
589        rings_codec::serialize(self).map_err(CoreError::CodecSerialize)
590    }
591}
592
593/// Signed descriptor published by onion exits.
594#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
595pub struct OnionExitDescriptor {
596    /// DID of the exit node/account.
597    pub did: Did,
598    /// Account public key corresponding to `did`.
599    pub public_key: VerificationPublicKey,
600    /// Delegation public key: the Sphinx key `pk_i` a loop's header blinds the exit's layer to.
601    pub delegatee_public_key: PublicKey<33>,
602    /// Process epoch `e_n` of the registering process, equal to its `relay` registration's.
603    pub process_epoch: OnionProcessEpoch,
604    /// Runtime family of this exit node.
605    pub node_type: OnlineNodeType,
606    /// Network identifier.
607    pub network_id: u32,
608    /// Service this descriptor is willing to expose.
609    pub service: OnionServiceName,
610    /// Signed exit policy.
611    pub policy: OnionExitPolicy,
612    /// Process start timestamp in milliseconds since Unix epoch.
613    pub started_at_ms: u128,
614    /// When the reader last heard this descriptor, in milliseconds since Unix epoch: the dot of
615    /// its element in the fetched registry carrier. Not signed and not encoded (see the lease
616    /// law of `descriptor`); `0` until heard.
617    #[serde(skip)]
618    pub heartbeat_at_ms: u128,
619    /// Freshness window `T` in milliseconds.
620    pub fresh_for_ms: u64,
621    /// Lease end `ℓ` in milliseconds since Unix epoch.
622    pub expires_at_ms: u128,
623    /// Node software version.
624    pub version: String,
625    /// Signature covering every descriptor field above except `heartbeat_at_ms`.
626    pub signature: MessageVerification,
627}
628
629impl OnionExitDescriptor {
630    /// Create and sign an onion-exit descriptor.
631    pub fn new_signed(
632        body: OnionExitDescriptorBody,
633        signer: MessageSigner<impl Borrow<DelegateeKey>>,
634    ) -> CoreResult<Self> {
635        sign_descriptor_body(
636            body,
637            signer,
638            "onion exit descriptor DID/public key/session mismatch",
639        )
640    }
641
642    fn body_ref(&self) -> OnionExitDescriptorBodyRef<'_> {
643        let Self {
644            did,
645            public_key,
646            delegatee_public_key,
647            process_epoch,
648            node_type,
649            network_id,
650            service,
651            policy,
652            started_at_ms,
653            heartbeat_at_ms: _,
654            fresh_for_ms,
655            expires_at_ms,
656            version,
657            signature: _,
658        } = self;
659
660        OnionExitDescriptorBodyRef {
661            did: *did,
662            public_key,
663            delegatee_public_key,
664            process_epoch: *process_epoch,
665            node_type,
666            network_id: *network_id,
667            service,
668            policy,
669            started_at_ms: *started_at_ms,
670            fresh_for_ms: *fresh_for_ms,
671            expires_at_ms: *expires_at_ms,
672            version: version.as_str(),
673        }
674    }
675
676    fn signing_data(&self) -> CoreResult<Vec<u8>> {
677        self.body_ref().signing_data()
678    }
679
680    /// Return whether this descriptor offers the service named `service`, after service-name
681    /// canonicalization: the predicate of the RPC boundary, where the name is still a string.
682    /// Typed callers compare [`Self::service`] directly.
683    pub fn offers_service(&self, service: &str) -> bool {
684        self.service.matches(service)
685    }
686
687    /// Verify the descriptor signature and DID/public-key binding.
688    pub fn verify_signature(&self, network_id: u32) -> bool {
689        self.descriptor_verify_signature(network_id)
690    }
691
692    /// Returns whether this descriptor is expired at `now_ms`: its lease ended, or it was not
693    /// heard within its freshness window.
694    pub fn is_expired_at(&self, now_ms: u128) -> bool {
695        self.descriptor_is_expired_at(now_ms)
696    }
697
698    /// Returns whether a reader lists this descriptor: it has a valid signature, admissible
699    /// lease terms, and is not expired (the lease law of `descriptor`).
700    pub fn is_live_at(&self, now_ms: u128, network_id: u32) -> bool {
701        self.descriptor_is_live_at(now_ms, network_id)
702    }
703
704    /// Select the newest valid onion-exit descriptor per `(DID, service)`.
705    ///
706    /// Invariant: an exit may publish independent TCP and HTTPS registrations under the same DID.
707    /// Preservation: heartbeat ordering is compared only inside each `(DID, service name)` key.
708    pub fn latest_valid_by_service_did(
709        descriptors: impl IntoIterator<Item = Self>,
710        now_ms: u128,
711        network_id: u32,
712        include_expired: bool,
713    ) -> Vec<Self> {
714        latest_valid_by_key(
715            descriptors,
716            Self::registration_key,
717            now_ms,
718            network_id,
719            include_expired,
720        )
721        .into_values()
722        .collect()
723    }
724
725    /// Return the key `(DID, service)` of this registration: an exit registers each service it
726    /// offers independently.
727    pub(crate) fn registration_key(&self) -> (Did, OnionServiceName) {
728        (self.did, self.service.clone())
729    }
730}
731
732impl SignedDescriptor for OnionExitDescriptor {
733    type Body = OnionExitDescriptorBody;
734
735    fn descriptor_did(&self) -> Did {
736        self.did
737    }
738
739    fn descriptor_public_key(&self) -> &VerificationPublicKey {
740        &self.public_key
741    }
742
743    fn descriptor_network_id(&self) -> u32 {
744        self.network_id
745    }
746
747    fn descriptor_signature(&self) -> &MessageVerification {
748        &self.signature
749    }
750
751    fn descriptor_heartbeat_at_ms(&self) -> u128 {
752        self.heartbeat_at_ms
753    }
754
755    fn descriptor_expires_at_ms(&self) -> u128 {
756        self.expires_at_ms
757    }
758
759    fn descriptor_fresh_for_ms(&self) -> u64 {
760        self.fresh_for_ms
761    }
762
763    fn descriptor_signing_data(&self) -> CoreResult<Vec<u8>> {
764        self.signing_data()
765    }
766
767    fn heard_at(self, heartbeat_at_ms: u128) -> Self {
768        Self {
769            heartbeat_at_ms,
770            ..self
771        }
772    }
773}
774
775impl RegistryElement for OnionExitDescriptor {}
776
777/// Result of decoding one onion-exit registry entry.
778#[derive(Clone, Debug, Default, Eq, PartialEq)]
779pub struct OnionExitDescriptorDecodeReport {
780    /// Descriptors that decoded successfully under the total-cutover wire shape.
781    pub descriptors: Vec<OnionExitDescriptor>,
782    /// Number of registry values explicitly rejected at the decode boundary.
783    pub rejected_values: usize,
784}
785
786impl OnionExitDescriptorDecodeReport {
787    /// Return whether the entry contained values this node could not decode.
788    pub const fn has_rejections(&self) -> bool {
789        self.rejected_values > 0
790    }
791}
792
793/// Periodic node-layer registration for onion exit policy.
794#[derive(Clone, Debug)]
795pub(crate) struct OnionExitRegistration {
796    heartbeat_interval: Duration,
797    node_type: OnlineNodeType,
798    process_epoch: OnionProcessEpochCell,
799    clock: SharedClock,
800    started_at_ms: u128,
801    offer: OnionExitOffer,
802    publisher: DhtRegistrationPublisher<Vec<OnionExitDescriptor>>,
803}
804
805impl OnionExitRegistration {
806    #[cfg(all(test, not(target_family = "wasm")))]
807    pub(crate) fn new(
808        heartbeat_interval: Duration,
809        ttl: Duration,
810        node_type: OnlineNodeType,
811        offer: OnionExitOffer,
812        process_epoch: OnionProcessEpochCell,
813    ) -> Self {
814        Self::new_with_clock(
815            heartbeat_interval,
816            ttl,
817            node_type,
818            offer,
819            process_epoch,
820            Arc::new(SystemClock),
821        )
822    }
823
824    pub(crate) fn new_with_clock(
825        heartbeat_interval: Duration,
826        ttl: Duration,
827        node_type: OnlineNodeType,
828        offer: OnionExitOffer,
829        process_epoch: OnionProcessEpochCell,
830        clock: SharedClock,
831    ) -> Self {
832        let started_at_ms = clock.now_ms();
833        Self {
834            heartbeat_interval,
835            node_type,
836            process_epoch,
837            clock,
838            started_at_ms,
839            offer,
840            publisher: DhtRegistrationPublisher::new(ONION_EXITS_TOPIC, heartbeat_interval, ttl),
841        }
842    }
843
844    /// Build this node's signed onion-exit descriptors under the lease `terms`.
845    pub fn descriptors_at(
846        &self,
847        context: &RegistrationContext<'_>,
848        terms: LeaseTerms,
849    ) -> Result<Vec<OnionExitDescriptor>> {
850        self.offer
851            .services()
852            .iter()
853            .cloned()
854            .map(|service| self.descriptor_for_service(context, terms, service))
855            .collect()
856    }
857
858    fn descriptor_for_service(
859        &self,
860        context: &RegistrationContext<'_>,
861        terms: LeaseTerms,
862        service: OnionServiceName,
863    ) -> Result<OnionExitDescriptor> {
864        OnionExitDescriptor::new_signed(
865            OnionExitDescriptorBody {
866                did: context.did(),
867                public_key: context.delegator_verification_pubkey()?,
868                delegatee_public_key: context.delegatee_key().delegatee_public_key(),
869                process_epoch: self.process_epoch.get(),
870                node_type: self.node_type.clone(),
871                network_id: context.network_id(),
872                service,
873                policy: self.offer.policy().clone(),
874                started_at_ms: self.started_at_ms,
875                fresh_for_ms: terms.fresh_for_ms,
876                expires_at_ms: terms.expires_at_ms,
877                version: crate::util::build_version(),
878            },
879            context.message_signer(),
880        )
881        .map_err(Error::CoreError)
882    }
883
884    /// Publish one heartbeat of this node's signed onion-exit descriptors, returning them as
885    /// heard now.
886    pub async fn publish_descriptors(
887        &self,
888        context: &RegistrationContext<'_>,
889    ) -> Result<Vec<OnionExitDescriptor>> {
890        self.publisher
891            .publish_lease(context, self.clock.now_ms(), |terms| {
892                self.descriptors_at(context, terms)
893            })
894            .await
895    }
896
897    /// Decode onion-exit descriptors from a DHT entry, each heard at its element's dot.
898    pub fn decode_descriptors_from_entry(
899        entry: &rings_core::dht::entry::Entry,
900    ) -> OnionExitDescriptorDecodeReport {
901        let mut report = OnionExitDescriptorDecodeReport::default();
902        for (value, heard_at_ms) in heard_elements(entry) {
903            match OnionExitDescriptor::from_element(value) {
904                Ok(descriptor) => report.descriptors.push(descriptor.heard_at(heard_at_ms)),
905                Err(error) => {
906                    report.rejected_values = report.rejected_values.saturating_add(1);
907                    tracing::debug!(
908                        "rejected onion-exit descriptor registry value at schema boundary: {error}"
909                    );
910                }
911            }
912        }
913        report
914    }
915
916    /// Decode onion-exit descriptors from a DHT entry, dropping values rejected at the schema boundary.
917    pub fn descriptors_from_entry(
918        entry: &rings_core::dht::entry::Entry,
919    ) -> Vec<OnionExitDescriptor> {
920        let report = Self::decode_descriptors_from_entry(entry);
921        if report.has_rejections() {
922            tracing::warn!(
923                rejected_values = report.rejected_values,
924                "ignored unsupported onion-exit descriptor registry values"
925            );
926        }
927        report.descriptors
928    }
929}
930
931#[cfg_attr(rings_browser, async_trait(?Send))]
932#[cfg_attr(rings_native, async_trait)]
933impl RegistrationTask for OnionExitRegistration {
934    fn name(&self) -> &'static str {
935        "onion-exit"
936    }
937
938    fn interval(&self) -> Duration {
939        self.heartbeat_interval
940    }
941
942    async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
943        self.publish_descriptors(context).await.map(|_| ())
944    }
945}
946
947#[cfg(test)]
948pub(crate) mod tests;