Skip to main content

rings_core/message/
admission_delegation.rs

1//! Delegated admission of direct-edge application traffic (#888).
2//!
3//! Every final-destination transaction is charged to the origin quota record keyed by
4//! `(network, origin account, destination, class)`, with a message bucket and a byte bucket.
5//!
6//! Some application protocols admit each sending neighbour themselves, through their own
7//! per-neighbour admission before their own processing (after core's admission: decode, both
8//! signature checks, and replay classification). For their direct-edge traffic the
9//! generic per-origin message limit is a second, tighter bound on the same traffic, and it refuses
10//! what the protocol admits. Such a namespace may declare *delegated admission*, a flag with no
11//! rate, and core then skips only the message-count limit for it:
12//!
13//! ```text
14//! limit(m, edge, delegated) ≜ Delegated   if class(m) = Application ∧ edge = Neighbour ∧ delegated
15//!                             Enforced    otherwise
16//! ```
17//!
18//! A delegated transaction neither needs nor consumes a message token. It is still charged to
19//! the same record's byte bucket, at least `DELEGATED_MIN_CHARGE` bytes, and the record bound
20//! still applies. The byte bound on the neighbour's application traffic is unchanged, and the
21//! floor bounds how many delegated messages core admits, and so the per-message work that
22//! follows admission (the replay-record persist onwards), which no delegating protocol can
23//! bound because it runs before the protocol sees the message. The decode and signature checks
24//! precede the quota and are not bounded by it. Core takes a flag, not a rate, and has no
25//! vocabulary of the protocol that declares it.
26//!
27//! # Why only the authenticated neighbour qualifies
28//!
29//! Delegation applies only when [`EdgeRelation::Neighbour`] holds, that is, the frame arrived
30//! on the handshake-authenticated connection of the transaction's own origin account. The
31//! declaring protocol's admission is per sending neighbour:
32//!
33//! - A relayed transaction arrives from a neighbour that is not its origin. Its origin's
34//!   traffic reaches us through any number of neighbours, and no per-neighbour admission bounds
35//!   it by origin, so skipping the per-origin limit would leave it unbounded in messages.
36//! - A relay forwarding a foreign origin's fresh traffic must not escape that origin's limit
37//!   just because the namespace delegates admission for direct neighbours.
38//! - The relay carrier (`hop_budget`, next hop) is not signed, so "direct" cannot be read from
39//!   the payload. The only unforgeable witness is the authenticated connection itself.
40//!
41//! Traffic that fails the predicate keeps the enforced class limits, so delegation never widens
42//! what a relayed or foreign origin can send.
43//!
44//! # Trust
45//!
46//! Delegation is trusted local configuration. The application registers it in advance as data,
47//! through `Swarm::set_admission_delegation` (in the node, by registering a `Protocol`), with
48//! the authority of the operator who configures the quota; core matches it without calling the
49//! application (#935). A namespace that declares it must enforce its own per-neighbour
50//! admission.
51//!
52//! # Delegated replay (#1081)
53//!
54//! The replay counterpart, by the same eligibility and the same registration as data: a
55//! namespace may declare *delegated replay*, and its direct-edge traffic is then admitted in a
56//! volatile replay window of the link it arrived on instead of the durable one
57//! (durable-records, Law Window by classification):
58//!
59//! ```text
60//! window(m, edge, delegated) ≜ Link      if class(m) = Application ∧ edge = Neighbour ∧ delegated
61//!                              Durable   otherwise
62//! ```
63//!
64//! A declaring namespace owes Obligation R of durable-records: it acts on each of its payloads
65//! at most once, by its own replay key, across connections, generations, envelopes and restarts
66//! of the receiver. Only the origin itself can present a link-local transaction again
67//! (Prop. What the durable window gave a link-local transaction), so the durable window
68//! protected nothing that R does not.
69
70use crate::dht::Did;
71use crate::message::types::MessageCategory;
72
73/// How the delivering connection relates to a transaction's origin account.
74#[derive(Clone, Copy, Debug, Eq, PartialEq)]
75pub(crate) enum EdgeRelation {
76    /// The frame arrived on the handshake-authenticated connection of the origin itself.
77    Neighbour,
78    /// The origin is not the authenticated neighbour: relayed, foreign, local or unauthenticated.
79    Remote,
80}
81
82impl EdgeRelation {
83    /// Relate an authenticated connection peer to an origin account.
84    ///
85    /// `authenticated_peer` must be `Some` only when the connection's handshake authenticated
86    /// that peer and its generation is still active; any other frame is [`Self::Remote`].
87    pub(crate) fn of(authenticated_peer: Option<Did>, origin: Did) -> Self {
88        if authenticated_peer == Some(origin) {
89            Self::Neighbour
90        } else {
91            Self::Remote
92        }
93    }
94}
95
96/// Whether an admission checks and consumes the per-origin message limit.
97#[derive(Clone, Copy, Debug, Eq, PartialEq)]
98pub enum MessageLimit {
99    /// The message bucket must hold a token, and the admission consumes it.
100    Enforced,
101    /// The declaring namespace admits this traffic itself: the message bucket is skipped.
102    Delegated,
103}
104
105/// How one final-destination transaction is charged: its class record, and whether that
106/// record's message limit applies.
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108pub(crate) struct OriginQuotaCharge {
109    /// The class whose origin record is charged.
110    pub(crate) lane: MessageCategory,
111    /// Whether the record's message limit applies.
112    pub(crate) message_limit: MessageLimit,
113}
114
115impl OriginQuotaCharge {
116    /// Select the charge: see the module documentation for the law.
117    ///
118    /// `delegated` asks the application layer whether the message's namespace declared delegated
119    /// admission. It is consulted only for Application traffic from the authenticated neighbour
120    /// that originated it, so no other traffic reaches the application layer's classifier.
121    pub(crate) fn select(
122        lane: MessageCategory,
123        edge: EdgeRelation,
124        delegated: impl FnOnce() -> bool,
125    ) -> Self {
126        let eligible = lane == MessageCategory::Application && edge == EdgeRelation::Neighbour;
127        let message_limit = if eligible && delegated() {
128            MessageLimit::Delegated
129        } else {
130            MessageLimit::Enforced
131        };
132        Self {
133            lane,
134            message_limit,
135        }
136    }
137}
138
139/// The replay window a final-destination transaction is admitted in (#1081).
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141pub enum ReplayWindow {
142    /// The durable window of its stream, written to the replay store.
143    Durable,
144    /// The volatile window of its stream on the link it arrived on, never written and released
145    /// with the link: the declaring namespace guards its own replay (Obligation R).
146    Link,
147}
148
149impl ReplayWindow {
150    /// Select the window: see the module documentation for the law. `delegated` asks whether
151    /// the message's namespace declared delegated replay; it is consulted only for
152    /// Application traffic from the authenticated neighbour that originated it.
153    pub(crate) fn select(
154        lane: MessageCategory,
155        edge: EdgeRelation,
156        delegated: impl FnOnce() -> bool,
157    ) -> Self {
158        let eligible = lane == MessageCategory::Application && edge == EdgeRelation::Neighbour;
159        if eligible && delegated() {
160            Self::Link
161        } else {
162            Self::Durable
163        }
164    }
165}
166
167impl From<MessageCategory> for OriginQuotaCharge {
168    fn from(lane: MessageCategory) -> Self {
169        Self {
170            lane,
171            message_limit: MessageLimit::Enforced,
172        }
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use std::cell::Cell;
179
180    use super::EdgeRelation;
181    use super::MessageLimit;
182    use super::OriginQuotaCharge;
183    use super::ReplayWindow;
184    use crate::dht::Did;
185    use crate::message::types::MessageCategory;
186
187    /// The selection law over every class and edge relation, with and without a declaration;
188    /// the classifier is consulted only where the law can delegate.
189    #[test]
190    fn test_only_neighbour_application_traffic_may_be_delegated() {
191        let classes = [
192            MessageCategory::DhtControl,
193            MessageCategory::Storage,
194            MessageCategory::E2e,
195            MessageCategory::Application,
196        ];
197        for lane in classes {
198            for edge in [EdgeRelation::Neighbour, EdgeRelation::Remote] {
199                for declared in [false, true] {
200                    let consulted = Cell::new(false);
201                    let charge = OriginQuotaCharge::select(lane, edge, || {
202                        consulted.set(true);
203                        declared
204                    });
205                    let eligible =
206                        lane == MessageCategory::Application && edge == EdgeRelation::Neighbour;
207                    assert_eq!(consulted.get(), eligible);
208                    assert_eq!(charge.lane, lane);
209                    let expected = if eligible && declared {
210                        MessageLimit::Delegated
211                    } else {
212                        MessageLimit::Enforced
213                    };
214                    assert_eq!(charge.message_limit, expected);
215                }
216            }
217        }
218    }
219
220    /// The replay window law over every class and edge relation, with and without a
221    /// declaration: only Application traffic of a declaring namespace from the authenticated
222    /// neighbour that originated it meets a link window, so a relayed copy, and all DHT,
223    /// storage and E2E traffic, keep the durable window; the classifier is consulted only where
224    /// the law can delegate.
225    #[test]
226    fn test_only_neighbour_application_traffic_may_meet_a_link_window() {
227        let classes = [
228            MessageCategory::DhtControl,
229            MessageCategory::Storage,
230            MessageCategory::E2e,
231            MessageCategory::Application,
232        ];
233        for lane in classes {
234            for edge in [EdgeRelation::Neighbour, EdgeRelation::Remote] {
235                for declared in [false, true] {
236                    let consulted = Cell::new(false);
237                    let window = ReplayWindow::select(lane, edge, || {
238                        consulted.set(true);
239                        declared
240                    });
241                    let eligible =
242                        lane == MessageCategory::Application && edge == EdgeRelation::Neighbour;
243                    assert_eq!(consulted.get(), eligible);
244                    let expected = if eligible && declared {
245                        ReplayWindow::Link
246                    } else {
247                        ReplayWindow::Durable
248                    };
249                    assert_eq!(window, expected);
250                }
251            }
252        }
253    }
254
255    /// Only the authenticated peer that is the origin itself is a neighbour.
256    #[test]
257    fn test_edge_relation_requires_the_authenticated_origin() {
258        let origin = Did::from(1_u32);
259        assert_eq!(
260            EdgeRelation::of(Some(origin), origin),
261            EdgeRelation::Neighbour
262        );
263        assert_eq!(
264            EdgeRelation::of(Some(Did::from(2_u32)), origin),
265            EdgeRelation::Remote
266        );
267        assert_eq!(EdgeRelation::of(None, origin), EdgeRelation::Remote);
268    }
269}