Skip to main content

rings_node/onion/
failure.rs

1//! Algebraic failure values for local onion routing and exit wire responses.
2
3use std::fmt;
4
5use serde::Deserialize;
6use serde::Serialize;
7
8use crate::error::Error;
9
10/// Local route and session failure before any user-facing rendering.
11#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
12pub enum OnionRouteError {
13    /// A pipeline has no symbol application or more than the loop admits (#834 D4a).
14    #[error("onion pipeline has {symbols} symbol applications; a loop admits 1 to {max_symbols}")]
15    LoopSymbolsOutOfBounds {
16        /// Number of symbol applications of the pipeline.
17        symbols: usize,
18        /// Largest number of symbol applications of one loop.
19        max_symbols: usize,
20    },
21    /// Fewer distinct eligible hops exist than the loop's `H − 1` positions require (#834 D5).
22    #[error("onion loop requires {required} distinct hops but only {eligible} are eligible")]
23    NotEnoughLoopHops {
24        /// Distinct hops the loop requires.
25        required: usize,
26        /// Distinct eligible hops found.
27        eligible: usize,
28    },
29    /// The symbol registrants admit no assignment of pairwise distinct hops to the symbol
30    /// positions of a loop.
31    #[error("onion symbol registrants admit no distinct hop per symbol position")]
32    NoDistinctSymbolHops,
33    /// A loop draw found no candidate although its matching guaranteed one: a violated invariant
34    /// of loop selection, never a property of the network.
35    #[error("onion loop selection violated its invariant: a guaranteed draw had no candidate")]
36    LoopDrawInvariant,
37    /// Route construction could not select a first hop accepted by the caller.
38    #[error("no onion route has a permitted first hop")]
39    NoPermittedFirstHop,
40    /// No live exit descriptor offers the requested service.
41    #[error("no live onion exit offers service {service:?}")]
42    NoLiveExit {
43        /// Requested service name.
44        service: String,
45    },
46    /// Every live exit of the service differs from its node's current relay registration in
47    /// session key or process epoch: the exit registered from another process, typically before
48    /// a restart, and its descriptors have not converged (#834 D2).
49    #[error(
50        "every onion exit offering service {service:?} differs from its node's current relay \
51         registration in session key or process epoch"
52    )]
53    ExitRelayRegistrationMismatch {
54        /// Requested service name.
55        service: String,
56    },
57    /// Every live exit of the service belongs to a node that registers no `relay` (#834 D2).
58    #[error("every onion exit offering service {service:?} lacks a relay registration")]
59    ExitWithoutRelayRegistration {
60        /// Requested service name.
61        service: String,
62    },
63    /// Live exits advertise the service, but none can serve the requested proxy protocol.
64    #[error("no live onion exit offers service {service:?} for proxy protocol {protocol:?}")]
65    NoExitForProxyProtocol {
66        /// Requested service name.
67        service: String,
68        /// Requested proxy protocol label.
69        protocol: String,
70    },
71    /// Live exits advertise the service, but no policy allows the target.
72    #[error("no live onion exit for service {service:?} allows target {target:?}")]
73    NoExitAllowsTarget {
74        /// Requested service name.
75        service: String,
76        /// Requested target authority.
77        target: String,
78    },
79    /// A session's symbol does not match the service its route was selected for.
80    #[error(
81        "onion payload service {payload_service:?} does not match route service \
82         {route_service:?}"
83    )]
84    PayloadServiceMismatch {
85        /// Symbol the session applies.
86        payload_service: String,
87        /// Service label selected by the route.
88        route_service: String,
89    },
90    /// A queued endpoint cell lost its drain task before the overlay reported a result.
91    #[error("onion link send was cancelled before overlay completion")]
92    LinkSendCancelled,
93    /// An endpoint's cell found no room on its lane, or did not leave, within the send deadline.
94    #[error("onion link send timed out")]
95    LinkSendTimedOut,
96    /// An HTTPS response channel closed before the exit's outcome was delivered.
97    #[error("onion HTTPS response channel closed")]
98    HttpsResponseClosed,
99    /// The exit's `tcp` world failed at its target: a connect, read, write or shutdown of the
100    /// target's socket. The reason stays at the exit; the client sees only a failed session.
101    #[error("onion TCP target: {0}")]
102    TcpTarget(String),
103    /// The exit's connect to a `tcp` target did not complete within its open timeout.
104    #[error("onion TCP open timed out")]
105    TcpOpenTimedOut,
106    /// A session's driver has already ended.
107    #[error("onion TCP stream is closed")]
108    TcpStreamClosed,
109    /// The exit's `udp` world failed at its bound socket or frame stream. The reason stays at the
110    /// exit; the client sees only a failed session.
111    #[error("onion UDP target: {0}")]
112    UdpTarget(String),
113    /// The exit's `udp` socket bind did not complete within its open timeout.
114    #[error("onion UDP open timed out")]
115    UdpOpenTimedOut,
116    /// A `udp` session's driver has already ended.
117    #[error("onion UDP session is closed")]
118    UdpSessionClosed,
119    /// The client could not build a loop over its route (a value too wide for its class, or a
120    /// key failure of negligible probability).
121    #[error("could not build an onion loop: {0}")]
122    LoopBuild(String),
123    /// The exit answered the session's open with a refusal; the exit gives no reason (#834 D2′).
124    /// A session that ends locally before the exit answers reports its own error instead
125    /// (#1118).
126    #[error("the onion exit refused the session")]
127    ExitRefused,
128    /// A session failed closed: a gap in its sequence, its liveness deadline, a lost reply, or
129    /// the exit's abort, whether before or after the exit answered its open.
130    #[error("the onion session failed closed")]
131    SessionFailed,
132    /// An exit-reported failure reached the local route client.
133    #[error("{0}")]
134    ExitFailure(OnionExitFailure),
135    /// No live `invoke` descriptor offers `(shape, backend)`.
136    #[error("no live onion node registers invoke symbol ({shape}, {backend:?})")]
137    NoLiveSymbol {
138        /// Canonical `invoke` shape string.
139        shape: String,
140        /// Requested backend name.
141        backend: String,
142    },
143    /// Every live `invoke` registrant of `(shape, backend)` differs from its node's current relay
144    /// registration in session key or process epoch (#834 D2).
145    #[error(
146        "every onion registrant of ({shape}, {backend:?}) differs from its node's current relay \
147         registration in session key or process epoch"
148    )]
149    SymbolRelayRegistrationMismatch {
150        /// Canonical `invoke` shape string.
151        shape: String,
152        /// Requested backend name.
153        backend: String,
154    },
155    /// Every live `invoke` registrant of `(shape, backend)` lacks a relay registration (#834 D2).
156    #[error("every onion registrant of ({shape}, {backend:?}) lacks a relay registration")]
157    SymbolWithoutRelayRegistration {
158        /// Canonical `invoke` shape string.
159        shape: String,
160        /// Requested backend name.
161        backend: String,
162    },
163    /// A Kleisli pipeline's `(shape, backend)` sequence does not match the selected route's.
164    #[error("onion pipeline symbols do not match the selected pipeline route")]
165    PipelineRouteMismatch,
166    /// A one-shot Kleisli pipeline did not return before its loop expiry `x`.
167    #[error("onion Kleisli pipeline timed out before loop expiry")]
168    PipelineTimedOut,
169    /// A one-shot Kleisli pipeline failed closed (e.g., its guard link retired or dropped).
170    #[error("onion Kleisli pipeline failed closed")]
171    PipelineFailed,
172}
173
174/// Why an `https` exit returned no response: the encoded failure of a fetch outcome. It carries
175/// no local diagnostic, so a failure reveals nothing of the exit beyond its class.
176#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
177pub enum OnionExitFailure {
178    /// The exit policy or its byte budget denied the fetch.
179    PermissionDenied,
180    /// The session's stream did not decode as a request.
181    MalformedRequest,
182    /// The fetch failed at the exit.
183    Internal,
184}
185
186impl OnionExitFailure {
187    /// Convert a local node error into a wire failure at the adapter boundary.
188    pub fn from_error(error: &Error) -> Self {
189        match error {
190            Error::NoPermission => Self::PermissionDenied,
191            _ => Self::Internal,
192        }
193    }
194}
195
196impl fmt::Display for OnionExitFailure {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        match self {
199            Self::PermissionDenied => Error::NoPermission.fmt(f),
200            Self::MalformedRequest => f.write_str("onion exit received a malformed HTTPS request"),
201            Self::Internal => f.write_str("onion exit internal failure"),
202        }
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::OnionExitFailure;
209    use crate::error::Error;
210
211    #[test]
212    fn test_wire_internal_failure_does_not_expose_local_diagnostic() {
213        let diagnostic = "secret local filesystem and resolver detail";
214        let failure = OnionExitFailure::from_error(&Error::InvalidConfig(diagnostic.to_string()));
215        let encoded = rings_codec::serialize(&failure).expect("encode wire failure");
216
217        assert_eq!(failure, OnionExitFailure::Internal);
218        assert!(!failure.to_string().contains(diagnostic));
219        assert!(!encoded
220            .windows(diagnostic.len())
221            .any(|window| window == diagnostic.as_bytes()));
222    }
223}