Skip to main content

iroh_live_node/
admission.rs

1//! Admission: who gets a session, and what it may do once it has one.
2
3use std::sync::Arc;
4
5use iroh::{EndpointId, endpoint::Connection};
6/// What a session may subscribe to from this node, and publish into it.
7///
8/// See [`moq_ext_access::Grant`].
9pub use moq_ext_access::Grant;
10/// What a peer asked for when it opened a session.
11pub use moq_ext_access::SessionRequest;
12use n0_error::e;
13use tracing::{debug, info};
14
15use crate::{
16    Direction, Error,
17    handshake::{Hop, SessionParts, authorize_direct, subscriber},
18    node::Shared,
19    policy::{Authorization, Event, PeerRequest, Rejection},
20    state::served,
21    transport::{self, HANDSHAKE_TIMEOUT},
22};
23
24/// How to dial a peer with [`Node::connect_with`](crate::Node::connect_with).
25#[derive(Debug, Clone, Default)]
26#[non_exhaustive]
27pub struct ConnectOptions {
28    /// A token to present, sent in the MoQ SETUP and as `?jwt=` in the setup path.
29    ///
30    /// The accepting node reads it as [`SessionRequest::token`].
31    pub token: Option<String>,
32    /// The path the SETUP requests, without a query.
33    ///
34    /// The accepting node reads it as [`SessionRequest::path`]. `None` requests
35    /// the root.
36    pub path: Option<String>,
37    /// The cost added to every route learned over this link.
38    ///
39    /// `None` keeps moq's default of one.
40    pub cost: Option<u64>,
41    /// iroh's options for the QUIC dial.
42    ///
43    /// Set a transport config here to dial with another
44    /// [`Congestion`](crate::Congestion) controller. The default keeps the
45    /// endpoint's transport config, which runs BBR3 under
46    /// [`MoqPreset`](crate::MoqPreset). It applies to a direct dial only: a
47    /// session that already exists keeps its connection, so close it first to
48    /// dial again with other options. A relay link ignores it.
49    pub quic: iroh::endpoint::ConnectOptions,
50}
51
52impl ConnectOptions {
53    /// Returns these options with `token` presented to the peer.
54    #[must_use]
55    pub fn with_token(mut self, token: impl Into<String>) -> Self {
56        self.token = Some(token.into());
57        self
58    }
59
60    /// Returns these options with `path` requested in the SETUP.
61    #[must_use]
62    pub fn with_path(mut self, path: impl Into<String>) -> Self {
63        self.path = Some(path.into());
64        self
65    }
66
67    /// Returns these options with `cost` added to every route learned over the link.
68    #[must_use]
69    pub fn with_cost(mut self, cost: u64) -> Self {
70        self.cost = Some(cost);
71        self
72    }
73
74    /// Returns these options with iroh's `quic` options for the dial.
75    #[must_use]
76    pub fn with_quic(mut self, quic: iroh::endpoint::ConnectOptions) -> Self {
77        self.quic = quic;
78        self
79    }
80}
81
82/// Admits one incoming connection if the policy does, for the protocol handler.
83pub(crate) async fn accept(shared: &Arc<Shared>, connection: Connection) -> Result<(), Error> {
84    if shared.shutdown.is_cancelled() {
85        return Err(e!(Error::ShutDown));
86    }
87    let peer = connection.remote_id();
88    let transport = transport::Transport::new(connection.clone())?;
89    let opened = tokio::time::timeout(
90        HANDSHAKE_TIMEOUT,
91        moq_net::Server::new().handshake(moq_net::time::Instant::now(), transport),
92    )
93    .await;
94    let handshake = match opened {
95        Ok(opened) => opened.map_err(|source| e!(Error::Moq { source }))?,
96        Err(_) => {
97            debug!(peer = %peer.fmt_short(), "no session setup in time");
98            return Err(e!(Error::Moq {
99                source: moq_net::Error::Timeout
100            }));
101        }
102    };
103    let request = SessionRequest::from_handshake(&handshake);
104    debug!(peer = %peer.fmt_short(), path = request.path(), "session requested");
105    let decided = tokio::select! {
106        decided = authorize(shared, peer, &request, Direction::Accepted) => decided,
107        _ = shared.shutdown.cancelled() => {
108            handshake.close(moq_net::Error::Cancel);
109            return Err(e!(Error::ShutDown));
110        }
111    };
112    let (authorization, reauthorized) = match decided {
113        Ok(decided) => decided,
114        Err(rejection) => {
115            info!(
116                peer = %peer.fmt_short(),
117                reason = rejection.reason(),
118                code = %rejection.code(),
119                "the policy rejected the session",
120            );
121            handshake.close(rejection.code().clone());
122            return Err(e!(Error::Rejected { source: rejection }));
123        }
124    };
125    if shared.shutdown.is_cancelled() {
126        handshake.close(moq_net::Error::Cancel);
127        return Err(e!(Error::ShutDown));
128    }
129    info!(peer = %peer.fmt_short(), grant = ?authorization.grant, "admitting session");
130    let auth = handshake.auth();
131    authorize_direct(shared, &auth, peer, &authorization.grant);
132    let handshake = handshake
133        .with_publisher(served(&shared.table))
134        .with_peer_node(Hop::of(&peer).id())
135        .with_subscriber(subscriber(shared));
136    let (moq, driver) = tokio::time::timeout(HANDSHAKE_TIMEOUT, handshake.ok())
137        .await
138        .map_err(|_| {
139            e!(Error::Moq {
140                source: moq_net::Error::Timeout
141            })
142        })?
143        .map_err(|source| e!(Error::Moq { source }))?;
144    let parts = SessionParts {
145        peer,
146        connection,
147        direction: Direction::Accepted,
148        authorization,
149        reauthorized,
150        request,
151        moq,
152        driver,
153        auth,
154    };
155    shared.register(parts).await?;
156    Ok(())
157}
158
159/// Decides a new session with `peer`, opened in `direction`.
160///
161/// Returns the authorization and the count of `Node::reauthorize` calls
162/// before the decision started, which the session compares when it
163/// registers.
164pub(crate) async fn authorize(
165    shared: &Shared,
166    peer: EndpointId,
167    request: &SessionRequest,
168    direction: Direction,
169) -> Result<(Authorization, u64), Rejection> {
170    let reauthorized = shared.state.lock().expect("poisoned").reauthorized;
171    let request = PeerRequest::new(peer, request.clone(), Event::Connect).with_direction(direction);
172    Ok((decide(shared, &request).await?, reauthorized))
173}
174
175/// Asks the node's policy about `request`, within [`NodeConfig::decide_timeout`].
176///
177/// See [`decide_within`](moq_ext_access::policy::decide_within) for what it
178/// rejects on its own.
179///
180/// [`NodeConfig::decide_timeout`]: crate::NodeConfig::decide_timeout
181pub(crate) async fn decide(
182    shared: &Shared,
183    request: &PeerRequest,
184) -> Result<Authorization, Rejection> {
185    moq_ext_access::policy::decide_within(&*shared.policy, request, shared.decide_timeout).await
186}