Skip to main content

node_device_session/
serve.rs

1//! [`serve`]: the C-5 device-session accept loop.
2
3use crate::messages::{
4    endpoint_hex, scope_allows, service, stamp, OpenMode, OpenOk, OpenRequest, RenewOk,
5    RenewRequest, ServiceCall, StampIdentity,
6};
7use crate::traits::{BoxRecv, BoxSend, HostBus, SessionStreams, WebRtcSignaling};
8use crate::types::{IngressSocket, Refusal, Session, SessionEnd, SessionPath};
9use crate::wire::{
10    decode_request, encode_response, peek_method, DEVICE_CALL_METHOD, HTTP_REQUEST_METHOD,
11    MAX_FRAME_BYTES, RESPONSE_STATUS_ERR, RESPONSE_STATUS_OK, SESSION_OPEN_METHOD,
12    SESSION_RENEW_METHOD, WEBRTC_SIGNAL_METHOD, WS_STREAM_METHOD,
13};
14use crate::tunnel;
15use std::sync::Arc;
16use std::time::Duration;
17use tokio::io::{AsyncReadExt, AsyncWriteExt};
18use tokio::task::JoinSet;
19
20const OPEN_DEADLINE: Duration = Duration::from_secs(10);
21const CALL_DEADLINE: Duration = Duration::from_secs(30);
22const CALL_READ_DEADLINE: Duration = Duration::from_secs(30);
23const CLOSE_GRACE: Duration = Duration::from_secs(2);
24const MAX_SESSION_STREAMS: usize = 16;
25const RENEWAL_LIFETIME: Duration = Duration::from_secs(120);
26const PROTOCOL_CLOSE_CODE: u32 = 1;
27
28fn err_frame(code: &str, message: &str) -> Vec<u8> {
29    encode_response(RESPONSE_STATUS_ERR, format!("{code}: {message}").as_bytes())
30}
31
32fn session_from_verify(session: Session) -> OpenOk {
33    OpenOk {
34        mode: OpenMode::Full,
35        device_id: session.device_id,
36        device_did: session.device_did,
37        scopes: session.scopes,
38        expires_at: session.expires_at,
39    }
40}
41
42fn session_from_admit(session: Session) -> OpenOk {
43    OpenOk {
44        mode: OpenMode::Renewal,
45        device_id: session.device_id,
46        device_did: session.device_did,
47        scopes: vec![],
48        expires_at: if session.expires_at.is_empty() {
49            renewal_expires_at()
50        } else {
51            session.expires_at
52        },
53    }
54}
55
56fn map_verify_refusal(refusal: Refusal) -> Vec<u8> {
57    match refusal.code.as_str() {
58        "invalid_request"
59        | "endpoint_mismatch"
60        | "invalid_credential"
61        | "device_revoked"
62        | "expired"
63        | "verifier_unavailable" => err_frame(&refusal.code, &refusal.message),
64        _ => err_frame(
65            "verifier_unavailable",
66            "verification is temporarily unavailable",
67        ),
68    }
69}
70
71fn map_renew_refusal(refusal: Refusal) -> (&'static str, &'static str) {
72    match refusal.code.as_str() {
73        "device_revoked" => ("device_revoked", "the device is revoked"),
74        "device_not_registered" => ("device_not_registered", "the device is not registered"),
75        "pending_approval" => ("pending_approval", "the device awaits approval"),
76        "rejected" => ("rejected", "the device was rejected"),
77        "rate_limited" => ("rate_limited", "try renewal later"),
78        "invalid_request" => ("invalid_request", "invalid renewal request"),
79        "internal_error" => ("internal_error", "renewal failed"),
80        _ => ("renew_unavailable", "renewal is temporarily unavailable"),
81    }
82}
83
84fn map_admit_refusal(refusal: Refusal) -> Vec<u8> {
85    match refusal.code.as_str() {
86        "rate_limited" => err_frame("rate_limited", "renewal admission rate limited"),
87        "device_revoked" => err_frame("device_revoked", "the device is revoked"),
88        "unknown_endpoint" => err_frame("unknown_endpoint", "the endpoint is not registered"),
89        _ => err_frame(
90            "verifier_unavailable",
91            "verification is temporarily unavailable",
92        ),
93    }
94}
95
96async fn respond(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
97    let _ = send.write_all(&frame).await;
98    let _ = send.shutdown().await;
99}
100
101async fn respond_before_close(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
102    respond(send, frame).await;
103    tokio::time::sleep(CLOSE_GRACE).await;
104}
105
106/// Serve one authenticated peer connection until it ends.
107///
108/// `webrtc` is the carrier hook for `webrtc.signal/1`. Pass [`Some`] when the
109/// carrier can answer WebRTC on this connection (iroh); pass [`None`] to refuse
110/// with `unsupported_transport`.
111pub async fn serve<C, B>(
112    conn: C,
113    bus: B,
114    ingress: IngressSocket,
115    path: SessionPath,
116    webrtc: Option<Arc<dyn WebRtcSignaling>>,
117) -> Result<(), SessionEnd>
118where
119    C: SessionStreams + 'static,
120    B: HostBus + 'static,
121{
122    let conn = Arc::new(conn);
123    let bus = Arc::new(bus);
124    let ingress = Arc::new(ingress);
125
126    let attempt = tokio::time::timeout(OPEN_DEADLINE, async {
127        let (mut send, mut recv) = conn.accept_bi().await?;
128        let mut bytes = Vec::new();
129        (&mut recv)
130            .take(MAX_FRAME_BYTES as u64 + 1)
131            .read_to_end(&mut bytes)
132            .await?;
133        if bytes.len() > MAX_FRAME_BYTES {
134            conn.close(PROTOCOL_CLOSE_CODE, b"frame too large or unreadable");
135            return Err(SessionEnd::NotOpened("frame too large".into()));
136        }
137        match decode_request(&bytes) {
138            Ok((method, payload)) if method == SESSION_OPEN_METHOD => {
139                open_first(conn.as_ref(), bus.as_ref(), send, payload).await
140            }
141            Ok((method, payload)) if method == SESSION_RENEW_METHOD => {
142                renew_first(conn.as_ref(), bus.as_ref(), send, payload).await
143            }
144            _ => {
145                respond_before_close(
146                    &mut send,
147                    err_frame("not_open", "the first stream must be session.open/1"),
148                )
149                .await;
150                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
151                Err(SessionEnd::NotOpened("not_open".into()))
152            }
153        }
154    })
155    .await;
156
157    let (send, identity) = match attempt {
158        Ok(Ok(v)) => v,
159        Ok(Err(e)) => return Err(e),
160        Err(_) => {
161            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened in time");
162            return Err(SessionEnd::OpenTimeout);
163        }
164    };
165
166    serve_opened(conn, bus, ingress, path, webrtc, send, identity).await
167}
168
169async fn open_first(
170    conn: &impl SessionStreams,
171    bus: &impl HostBus,
172    mut send: BoxSend,
173    payload: &[u8],
174) -> Result<(BoxSend, OpenOk), SessionEnd> {
175    let request: OpenRequest = match serde_json::from_slice(payload) {
176        Ok(r) => r,
177        Err(_) => {
178            respond_before_close(
179                &mut send,
180                err_frame(
181                    "invalid_request",
182                    "session.open/1 needs {credential} or {mode: renewal}",
183                ),
184            )
185            .await;
186            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
187            return Err(SessionEnd::NotOpened("invalid_request".into()));
188        }
189    };
190
191    let endpoint = endpoint_hex(&conn.peer_key());
192    let ok = if request.mode == Some(OpenMode::Renewal) {
193        if request.credential.is_some() {
194            respond_before_close(
195                &mut send,
196                err_frame("invalid_request", "renewal mode takes no credential"),
197            )
198            .await;
199            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
200            return Err(SessionEnd::NotOpened("invalid_request".into()));
201        }
202        match bus.admit_renewal(&endpoint).await {
203            Ok(session) => session_from_admit(session),
204            Err(refusal) => {
205                respond_before_close(&mut send, map_admit_refusal(refusal)).await;
206                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
207                return Err(SessionEnd::NotOpened("admit refused".into()));
208            }
209        }
210    } else {
211        let credential = match request.credential.filter(|c| !c.is_empty()) {
212            Some(c) => c,
213            None => {
214                respond_before_close(
215                    &mut send,
216                    err_frame("invalid_request", "full mode needs a credential"),
217                )
218                .await;
219                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
220                return Err(SessionEnd::NotOpened("invalid_request".into()));
221            }
222        };
223        match bus.verify(&credential, &endpoint).await {
224            Ok(session) => session_from_verify(session),
225            Err(refusal) => {
226                respond_before_close(&mut send, map_verify_refusal(refusal)).await;
227                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
228                return Err(SessionEnd::NotOpened("verify refused".into()));
229            }
230        }
231    };
232
233    let body = serde_json::to_vec(&ok).map_err(|_| SessionEnd::NotOpened("encode".into()))?;
234    respond(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
235    Ok((send, ok))
236}
237
238async fn renew_first(
239    conn: &impl SessionStreams,
240    bus: &impl HostBus,
241    mut send: BoxSend,
242    payload: &[u8],
243) -> Result<(BoxSend, OpenOk), SessionEnd> {
244    let endpoint = endpoint_hex(&conn.peer_key());
245    let value: serde_json::Value = match serde_json::from_slice::<serde_json::Value>(payload) {
246        Ok(v) if v.is_object() => v,
247        _ => {
248            respond_before_close(
249                &mut send,
250                err_frame("invalid_request", "session.renew/1 needs {}"),
251            )
252            .await;
253            conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
254            return Err(SessionEnd::NotOpened("invalid_request".into()));
255        }
256    };
257    if serde_json::from_value::<RenewRequest>(value).is_err() {
258        respond_before_close(
259            &mut send,
260            err_frame("invalid_request", "session.renew/1 needs {}"),
261        )
262        .await;
263        conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
264        return Err(SessionEnd::NotOpened("invalid_request".into()));
265    }
266
267    match bus.renew(&endpoint).await {
268        Ok(session) => {
269            let ok = RenewOk {
270                credential: session.credential.unwrap_or_default(),
271                expires_at: session.expires_at,
272                scopes: session.scopes,
273                device_id: session.device_id,
274                device_did: session.device_did,
275                revocation_id: None,
276            };
277            let body = serde_json::to_vec(&ok).unwrap_or_default();
278            respond_before_close(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
279            conn.close(0, b"renewal complete");
280            Err(SessionEnd::Closed)
281        }
282        Err(refusal) => {
283            let (code, detail) = map_renew_refusal(refusal);
284            respond_before_close(&mut send, err_frame(code, detail)).await;
285            conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
286            Err(SessionEnd::NotOpened(code.into()))
287        }
288    }
289}
290
291fn renewal_expires_at() -> String {
292    use std::time::{SystemTime, UNIX_EPOCH};
293    let secs = SystemTime::now()
294        .duration_since(UNIX_EPOCH)
295        .unwrap_or_default()
296        .as_secs()
297        + RENEWAL_LIFETIME.as_secs();
298    format!("{secs}")
299}
300
301async fn serve_opened<C, B>(
302    conn: Arc<C>,
303    bus: Arc<B>,
304    ingress: Arc<IngressSocket>,
305    path: SessionPath,
306    webrtc: Option<Arc<dyn WebRtcSignaling>>,
307    _open_send: BoxSend,
308    identity: OpenOk,
309) -> Result<(), SessionEnd>
310where
311    C: SessionStreams + 'static,
312    B: HostBus + 'static,
313{
314    let identity = Arc::new(identity);
315    let peer = conn.peer_key();
316    let mut streams = JoinSet::new();
317    let lifetime = async {
318        if identity.mode == OpenMode::Renewal {
319            tokio::time::sleep(RENEWAL_LIFETIME).await;
320        } else {
321            std::future::pending::<()>().await;
322        }
323    };
324    tokio::pin!(lifetime);
325
326    let serve = async {
327        loop {
328            while streams.try_join_next().is_some() {}
329            let (send, recv) = match conn.accept_bi().await {
330                Ok(s) => s,
331                Err(_) => break,
332            };
333            if streams.len() >= MAX_SESSION_STREAMS {
334                let mut send = send;
335                let mut recv = recv;
336                let _ = tokio::time::timeout(CALL_READ_DEADLINE, async {
337                    if let Ok(method) = peek_method(&mut recv).await {
338                        let _ = tunnel::refuse(&mut send, &method, "too_many_streams").await;
339                    }
340                })
341                .await;
342                let _ = send.shutdown().await;
343                continue;
344            }
345            let bus = bus.clone();
346            let ingress = ingress.clone();
347            let identity = identity.clone();
348            let webrtc = webrtc.clone();
349            streams.spawn(async move {
350                serve_stream(bus, ingress, path, peer, &identity, webrtc, send, recv).await;
351            });
352        }
353    };
354
355    tokio::select! {
356        biased;
357        _ = &mut lifetime => {
358            conn.close(PROTOCOL_CLOSE_CODE, b"renewal session expired");
359        }
360        _ = serve => {}
361    }
362    streams.abort_all();
363    while streams.join_next().await.is_some() {}
364    Ok(())
365}
366
367#[allow(clippy::too_many_arguments)]
368async fn serve_stream<B: HostBus>(
369    bus: Arc<B>,
370    ingress: Arc<IngressSocket>,
371    path: SessionPath,
372    peer: [u8; 32],
373    identity: &OpenOk,
374    webrtc: Option<Arc<dyn WebRtcSignaling>>,
375    mut send: BoxSend,
376    mut recv: BoxRecv,
377) {
378    let deadline = tokio::time::Instant::now() + CALL_READ_DEADLINE;
379    let method = match tokio::time::timeout_at(deadline, peek_method(&mut recv)).await {
380        Err(_) | Ok(Err(_)) => {
381            let _ = tunnel::refuse(&mut send, "unknown/1", "invalid_request").await;
382            let _ = send.shutdown().await;
383            return;
384        }
385        Ok(Ok(method)) => method,
386    };
387
388    if identity.mode == OpenMode::Renewal && method != HTTP_REQUEST_METHOD {
389        let _ = tunnel::refuse(&mut send, &method, "renewal_only").await;
390        let _ = send.shutdown().await;
391        return;
392    }
393
394    if method == WEBRTC_SIGNAL_METHOD {
395        match webrtc {
396            Some(hook) => {
397                hook.handle(identity, peer, send, recv).await;
398            }
399            None => {
400                let _ = tunnel::refuse(&mut send, &method, "unsupported_transport").await;
401                let _ = send.shutdown().await;
402            }
403        }
404        return;
405    }
406
407    if method == HTTP_REQUEST_METHOD {
408        let _ = tunnel::serve_http(
409            &ingress,
410            path,
411            &mut recv,
412            &mut send,
413            identity.mode == OpenMode::Renewal,
414        )
415        .await;
416        let _ = send.shutdown().await;
417        return;
418    }
419
420    if method == WS_STREAM_METHOD {
421        let _ = tunnel::serve_ws(&ingress, path, recv, send).await;
422        return;
423    }
424
425    let mut payload = Vec::new();
426    let read = tokio::time::timeout_at(
427        deadline,
428        recv.take((MAX_FRAME_BYTES - 2 - method.len()) as u64)
429            .read_to_end(&mut payload),
430    )
431    .await;
432    if read.is_err() || matches!(read, Ok(Err(_))) {
433        respond(
434            &mut send,
435            err_frame("invalid_request", "frame too large or unreadable"),
436        )
437        .await;
438        return;
439    }
440
441    let response = if method == SESSION_OPEN_METHOD {
442        err_frame("already_open", "this connection already has a session")
443    } else if method == DEVICE_CALL_METHOD {
444        match device_call(bus.as_ref(), identity, &peer, &payload).await {
445            Ok(body) => encode_response(RESPONSE_STATUS_OK, body.to_string().as_bytes()),
446            Err(frame) => frame,
447        }
448    } else {
449        err_frame("unknown_method", &method)
450    };
451    respond(&mut send, response).await;
452}
453
454async fn device_call(
455    bus: &impl HostBus,
456    identity: &OpenOk,
457    peer: &[u8; 32],
458    payload: &[u8],
459) -> Result<serde_json::Value, Vec<u8>> {
460    let call: ServiceCall = serde_json::from_slice(payload)
461        .map_err(|_| err_frame("invalid_request", "device.call/1 needs {service, payload}"))?;
462    let svc = service(&call.service).ok_or_else(|| err_frame("unknown_service", &call.service))?;
463    if !scope_allows(&identity.scopes, svc.scope) {
464        return Err(err_frame("scope_denied", svc.scope));
465    }
466    let endpoint = endpoint_hex(peer);
467    let stamped = stamp(
468        call.payload,
469        &StampIdentity {
470            device_id: &identity.device_id,
471            device_did: &identity.device_did,
472            scopes: &identity.scopes,
473            endpoint_hex: &endpoint,
474        },
475    );
476    match tokio::time::timeout(CALL_DEADLINE, bus.invoke(svc.capability, stamped)).await {
477        Err(_) => Err(err_frame(
478            "timeout",
479            "the node service did not answer in time",
480        )),
481        Ok(Ok(value)) => Ok(value),
482        Ok(Err(refusal)) => Err(err_frame("service_error", &refusal.message)),
483    }
484}