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, PairOk, PairRequest,
5    RenewOk, RenewRequest, ServiceCall, StampIdentity,
6};
7use crate::registry::{SessionClose, SessionRegistry};
8use crate::traits::{BoxRecv, BoxSend, HostBus, SessionStreams, WebRtcSignaling};
9use crate::tunnel::{self, Gate};
10use crate::types::{IngressSocket, Refusal, Session, SessionEnd, SessionPath, WireSocket};
11use crate::wire::{
12    decode_request, encode_response, peek_method, DEVICE_CALL_METHOD, HTTP_REQUEST_METHOD,
13    MAX_FRAME_BYTES, RESPONSE_STATUS_ERR, RESPONSE_STATUS_OK, SESSION_OPEN_METHOD,
14    SESSION_PAIR_METHOD, SESSION_RENEW_METHOD, WEBRTC_SIGNAL_METHOD, WIRE_METHOD, WS_STREAM_METHOD,
15};
16use crate::wire_stream;
17use std::sync::Arc;
18use std::time::Duration;
19use tokio::io::{AsyncReadExt, AsyncWriteExt};
20use tokio::task::JoinSet;
21
22const OPEN_DEADLINE: Duration = Duration::from_secs(10);
23const CALL_DEADLINE: Duration = Duration::from_secs(30);
24const CALL_READ_DEADLINE: Duration = Duration::from_secs(30);
25const CLOSE_GRACE: Duration = Duration::from_secs(2);
26const MAX_SESSION_STREAMS: usize = 16;
27const RENEWAL_LIFETIME: Duration = Duration::from_secs(120);
28const PAIRING_LIFETIME: Duration = Duration::from_secs(120);
29const PROTOCOL_CLOSE_CODE: u32 = 1;
30
31/// Which first stream opened the session. The words are the log line's `mode=`.
32#[derive(Clone, Copy)]
33enum OpenedMode {
34    Open,
35    Renew,
36    Pair,
37}
38
39/// Stable `path` and `mode` words for the one INFO line logged per opened session.
40///
41/// `path` is [`SessionPath`]'s wire value. No device, peer, or token is included.
42fn open_log_fields(path: SessionPath, mode: OpenedMode) -> (&'static str, &'static str) {
43    let mode = match mode {
44        OpenedMode::Open => "open",
45        OpenedMode::Renew => "renew",
46        OpenedMode::Pair => "pair",
47    };
48    (path.as_str(), mode)
49}
50
51fn log_session_opened(path: SessionPath, mode: OpenedMode) {
52    let (path, mode) = open_log_fields(path, mode);
53    tracing::info!(
54        target: "node_device_session",
55        "{}",
56        format_args!("device session opened path={path} mode={mode}")
57    );
58}
59
60fn err_frame(code: &str, message: &str) -> Vec<u8> {
61    encode_response(RESPONSE_STATUS_ERR, format!("{code}: {message}").as_bytes())
62}
63
64fn session_from_verify(session: Session) -> OpenOk {
65    OpenOk {
66        mode: OpenMode::Full,
67        device_id: session.device_id,
68        device_did: session.device_did,
69        scopes: session.scopes,
70        expires_at: session.expires_at,
71    }
72}
73
74fn session_from_admit(session: Session) -> OpenOk {
75    OpenOk {
76        mode: OpenMode::Renewal,
77        device_id: session.device_id,
78        device_did: session.device_did,
79        scopes: vec![],
80        expires_at: if session.expires_at.is_empty() {
81            renewal_expires_at()
82        } else {
83            session.expires_at
84        },
85    }
86}
87
88fn map_verify_refusal(refusal: Refusal) -> Vec<u8> {
89    match refusal.code.as_str() {
90        "invalid_request"
91        | "endpoint_mismatch"
92        | "invalid_credential"
93        | "device_revoked"
94        | "expired"
95        | "verifier_unavailable" => err_frame(&refusal.code, &refusal.message),
96        _ => err_frame(
97            "verifier_unavailable",
98            "verification is temporarily unavailable",
99        ),
100    }
101}
102
103fn map_renew_refusal(refusal: Refusal) -> (&'static str, &'static str) {
104    match refusal.code.as_str() {
105        "device_revoked" => ("device_revoked", "the device is revoked"),
106        "device_not_registered" => ("device_not_registered", "the device is not registered"),
107        "pending_approval" => ("pending_approval", "the device awaits approval"),
108        "rejected" => ("rejected", "the device was rejected"),
109        "rate_limited" => ("rate_limited", "try renewal later"),
110        "invalid_request" => ("invalid_request", "invalid renewal request"),
111        "internal_error" => ("internal_error", "renewal failed"),
112        _ => ("renew_unavailable", "renewal is temporarily unavailable"),
113    }
114}
115
116fn map_admit_refusal(refusal: Refusal) -> Vec<u8> {
117    match refusal.code.as_str() {
118        "rate_limited" => err_frame("rate_limited", "renewal admission rate limited"),
119        "device_revoked" => err_frame("device_revoked", "the device is revoked"),
120        "unknown_endpoint" => err_frame("unknown_endpoint", "the endpoint is not registered"),
121        _ => err_frame(
122            "verifier_unavailable",
123            "verification is temporarily unavailable",
124        ),
125    }
126}
127
128/// A pairing-only session, admitted by a door token (C-7) or opened without
129/// one (ADR-399 Amendment 2).
130struct Pairing {
131    /// The door member stamped in `x-node-pairing-door`; `None` for an open
132    /// session, which stamps only the endpoint.
133    member: Option<String>,
134    /// The proven endpoint, stamped in `x-node-pairing-endpoint`.
135    endpoint: String,
136    /// How long this session lives: [`PAIRING_LIFETIME`], or less when the
137    /// token expires first.
138    lifetime: Duration,
139}
140
141fn map_pairing_refusal(refusal: Refusal) -> Vec<u8> {
142    match refusal.code.as_str() {
143        "pairing_token_invalid" => {
144            err_frame("pairing_token_invalid", "the door token is not valid")
145        }
146        "pairing_token_expired" => err_frame("pairing_token_expired", "the door token has expired"),
147        "pairing_token_bound" => err_frame(
148            "pairing_token_bound",
149            "the door token belongs to another device",
150        ),
151        "pairing_rate_limited" => err_frame("pairing_rate_limited", "try pairing later"),
152        "not_open" => err_frame("not_open", "this node does not open pairing sessions"),
153        "invalid_request" => err_frame("invalid_request", "invalid pairing request"),
154        _ => err_frame(
155            "verifier_unavailable",
156            "verification is temporarily unavailable",
157        ),
158    }
159}
160
161/// A member id goes into an HTTP header: only ASCII alphanumerics (node ids are hex).
162fn member_node_id_ok(member: &str) -> bool {
163    !member.is_empty() && member.len() <= 256 && member.bytes().all(|b| b.is_ascii_alphanumeric())
164}
165
166async fn respond(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
167    let _ = send.write_all(&frame).await;
168    let _ = send.shutdown().await;
169}
170
171async fn respond_before_close(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
172    respond(send, frame).await;
173    tokio::time::sleep(CLOSE_GRACE).await;
174}
175
176/// Optional knobs for [`serve_with_options`].
177///
178/// Additive: existing [`serve`] / [`serve_with_registry`] keep their signatures
179/// and behave as today (no wire socket → `wire/1` refused).
180#[non_exhaustive]
181#[derive(Clone, Default)]
182pub struct ServeOptions {
183    /// Live-session registry for periodic revalidation; `None` skips registration.
184    pub registry: Option<SessionRegistry>,
185    /// Node wire socket `wire/1` splices onto; default (no path) refuses.
186    pub wire: WireSocket,
187}
188
189/// Serve one authenticated peer connection until it ends.
190///
191/// `webrtc` is the carrier hook for `webrtc.signal/1`. Pass [`Some`] when the
192/// carrier can answer WebRTC on this connection (iroh); pass [`None`] to refuse
193/// with `unsupported_transport`.
194///
195/// Does not touch a [`SessionRegistry`]. Carriers that need live-session
196/// revalidation should call [`serve_with_registry`] instead. Carriers that
197/// need `wire/1` should call [`serve_with_options`].
198pub async fn serve<C, B>(
199    conn: C,
200    bus: B,
201    ingress: IngressSocket,
202    path: SessionPath,
203    webrtc: Option<Arc<dyn WebRtcSignaling>>,
204) -> Result<(), SessionEnd>
205where
206    C: SessionStreams + 'static,
207    B: HostBus + 'static,
208{
209    serve_with_options(conn, bus, ingress, path, webrtc, ServeOptions::default()).await
210}
211
212/// Like [`serve`], but registers a successful full-mode open in `registry`
213/// (for once-a-minute revalidation) and removes it when this call returns.
214///
215/// The close callback stored in the registry closes the [`SessionStreams`]
216/// connection. Bind a [`crate::WebRtcHandle`] with
217/// [`SessionRegistry::bind_webrtc`] so revocation also tears down WebRTC.
218///
219/// For `wire/1`, use [`serve_with_options`] with both `registry` and `wire`.
220pub async fn serve_with_registry<C, B>(
221    conn: C,
222    bus: B,
223    ingress: IngressSocket,
224    path: SessionPath,
225    webrtc: Option<Arc<dyn WebRtcSignaling>>,
226    registry: SessionRegistry,
227) -> Result<(), SessionEnd>
228where
229    C: SessionStreams + 'static,
230    B: HostBus + 'static,
231{
232    serve_with_options(
233        conn,
234        bus,
235        ingress,
236        path,
237        webrtc,
238        ServeOptions {
239            registry: Some(registry),
240            ..ServeOptions::default()
241        },
242    )
243    .await
244}
245
246/// Like [`serve`], with optional registry and wire socket via [`ServeOptions`].
247pub async fn serve_with_options<C, B>(
248    conn: C,
249    bus: B,
250    ingress: IngressSocket,
251    path: SessionPath,
252    webrtc: Option<Arc<dyn WebRtcSignaling>>,
253    options: ServeOptions,
254) -> Result<(), SessionEnd>
255where
256    C: SessionStreams + 'static,
257    B: HostBus + 'static,
258{
259    serve_inner(
260        conn,
261        bus,
262        ingress,
263        options.wire,
264        path,
265        webrtc,
266        options.registry,
267    )
268    .await
269}
270
271async fn serve_inner<C, B>(
272    conn: C,
273    bus: B,
274    ingress: IngressSocket,
275    wire: WireSocket,
276    path: SessionPath,
277    webrtc: Option<Arc<dyn WebRtcSignaling>>,
278    registry: Option<SessionRegistry>,
279) -> Result<(), SessionEnd>
280where
281    C: SessionStreams + 'static,
282    B: HostBus + 'static,
283{
284    let conn = Arc::new(conn);
285    let bus = Arc::new(bus);
286    let ingress = Arc::new(ingress);
287    let wire = Arc::new(wire);
288
289    let attempt = tokio::time::timeout(OPEN_DEADLINE, async {
290        let (mut send, mut recv) = conn.accept_bi().await?;
291        let mut bytes = Vec::new();
292        (&mut recv)
293            .take(MAX_FRAME_BYTES as u64 + 1)
294            .read_to_end(&mut bytes)
295            .await?;
296        if bytes.len() > MAX_FRAME_BYTES {
297            conn.close(PROTOCOL_CLOSE_CODE, b"frame too large or unreadable");
298            return Err(SessionEnd::NotOpened("frame too large".into()));
299        }
300        match decode_request(&bytes) {
301            Ok((method, payload)) if method == SESSION_OPEN_METHOD => {
302                let opened = open_first(conn.as_ref(), bus.as_ref(), send, payload)
303                    .await
304                    .map(|(send, ok, credential)| (send, ok, credential, None))?;
305                log_session_opened(path, OpenedMode::Open);
306                Ok(opened)
307            }
308            Ok((method, payload)) if method == SESSION_RENEW_METHOD => {
309                // Renew is one-shot and never registers a live session.
310                // A successful renew answers, closes, and returns [`SessionEnd::Closed`].
311                match renew_first(conn.as_ref(), bus.as_ref(), send, payload).await {
312                    Ok((send, ok)) => {
313                        log_session_opened(path, OpenedMode::Renew);
314                        Ok((send, ok, None, None))
315                    }
316                    Err(SessionEnd::Closed) => {
317                        log_session_opened(path, OpenedMode::Renew);
318                        Err(SessionEnd::Closed)
319                    }
320                    Err(end) => Err(end),
321                }
322            }
323            Ok((method, payload)) if method == SESSION_PAIR_METHOD => {
324                // No credential: a pairing-only session never registers.
325                let opened = pair_first(conn.as_ref(), bus.as_ref(), send, payload)
326                    .await
327                    .map(|(send, ok, pairing)| (send, ok, None, Some(pairing)))?;
328                log_session_opened(path, OpenedMode::Pair);
329                Ok(opened)
330            }
331            _ => {
332                respond_before_close(
333                    &mut send,
334                    err_frame("not_open", "the first stream must be session.open/1"),
335                )
336                .await;
337                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
338                Err(SessionEnd::NotOpened("not_open".into()))
339            }
340        }
341    })
342    .await;
343
344    let (send, identity, credential, pairing) = match attempt {
345        Ok(Ok(v)) => v,
346        Ok(Err(e)) => return Err(e),
347        Err(_) => {
348            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened in time");
349            return Err(SessionEnd::OpenTimeout);
350        }
351    };
352
353    let registered = match (registry.as_ref(), credential) {
354        (Some(registry), Some(credential)) => {
355            let conn_close = conn.clone();
356            let close: SessionClose = Arc::new(move |code, reason| {
357                conn_close.close(code, reason);
358            });
359            let device_id = identity.device_id.clone();
360            let endpoint = endpoint_hex(&conn.peer_key());
361            let session_id = registry.insert(device_id.clone(), credential, endpoint, close);
362            Some((device_id, session_id))
363        }
364        _ => None,
365    };
366
367    let result = serve_opened(
368        conn, bus, ingress, wire, path, webrtc, send, identity, pairing,
369    )
370    .await;
371
372    if let (Some(registry), Some((device_id, session_id))) = (registry, registered) {
373        registry.remove_if(&device_id, session_id);
374    }
375    result
376}
377
378async fn open_first(
379    conn: &impl SessionStreams,
380    bus: &impl HostBus,
381    mut send: BoxSend,
382    payload: &[u8],
383) -> Result<(BoxSend, OpenOk, Option<String>), SessionEnd> {
384    let request: OpenRequest = match serde_json::from_slice(payload) {
385        Ok(r) => r,
386        Err(_) => {
387            respond_before_close(
388                &mut send,
389                err_frame(
390                    "invalid_request",
391                    "session.open/1 needs {credential} or {mode: renewal}",
392                ),
393            )
394            .await;
395            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
396            return Err(SessionEnd::NotOpened("invalid_request".into()));
397        }
398    };
399
400    let endpoint = endpoint_hex(&conn.peer_key());
401    let (ok, credential) = if request.mode == Some(OpenMode::Renewal) {
402        if request.credential.is_some() {
403            respond_before_close(
404                &mut send,
405                err_frame("invalid_request", "renewal mode takes no credential"),
406            )
407            .await;
408            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
409            return Err(SessionEnd::NotOpened("invalid_request".into()));
410        }
411        let ok = match bus.admit_renewal(&endpoint).await {
412            Ok(session) => session_from_admit(session),
413            Err(refusal) => {
414                respond_before_close(&mut send, map_admit_refusal(refusal)).await;
415                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
416                return Err(SessionEnd::NotOpened("admit refused".into()));
417            }
418        };
419        (ok, None)
420    } else {
421        let credential = match request.credential.filter(|c| !c.is_empty()) {
422            Some(c) => c,
423            None => {
424                respond_before_close(
425                    &mut send,
426                    err_frame("invalid_request", "full mode needs a credential"),
427                )
428                .await;
429                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
430                return Err(SessionEnd::NotOpened("invalid_request".into()));
431            }
432        };
433        let ok = match bus.verify(&credential, &endpoint).await {
434            Ok(session) => session_from_verify(session),
435            Err(refusal) => {
436                respond_before_close(&mut send, map_verify_refusal(refusal)).await;
437                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
438                return Err(SessionEnd::NotOpened("verify refused".into()));
439            }
440        };
441        (ok, Some(credential))
442    };
443
444    let body = serde_json::to_vec(&ok).map_err(|_| SessionEnd::NotOpened("encode".into()))?;
445    respond(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
446    Ok((send, ok, credential))
447}
448
449async fn renew_first(
450    conn: &impl SessionStreams,
451    bus: &impl HostBus,
452    mut send: BoxSend,
453    payload: &[u8],
454) -> Result<(BoxSend, OpenOk), SessionEnd> {
455    let endpoint = endpoint_hex(&conn.peer_key());
456    let value: serde_json::Value = match serde_json::from_slice::<serde_json::Value>(payload) {
457        Ok(v) if v.is_object() => v,
458        _ => {
459            respond_before_close(
460                &mut send,
461                err_frame("invalid_request", "session.renew/1 needs {}"),
462            )
463            .await;
464            conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
465            return Err(SessionEnd::NotOpened("invalid_request".into()));
466        }
467    };
468    if serde_json::from_value::<RenewRequest>(value).is_err() {
469        respond_before_close(
470            &mut send,
471            err_frame("invalid_request", "session.renew/1 needs {}"),
472        )
473        .await;
474        conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
475        return Err(SessionEnd::NotOpened("invalid_request".into()));
476    }
477
478    match bus.renew(&endpoint).await {
479        Ok(session) => {
480            let ok = RenewOk {
481                credential: session.credential.unwrap_or_default(),
482                expires_at: session.expires_at,
483                scopes: session.scopes,
484                device_id: session.device_id,
485                device_did: session.device_did,
486                revocation_id: None,
487            };
488            let body = serde_json::to_vec(&ok).unwrap_or_default();
489            respond_before_close(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
490            conn.close(0, b"renewal complete");
491            Err(SessionEnd::Closed)
492        }
493        Err(refusal) => {
494            let (code, detail) = map_renew_refusal(refusal);
495            respond_before_close(&mut send, err_frame(code, detail)).await;
496            conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
497            Err(SessionEnd::NotOpened(code.into()))
498        }
499    }
500}
501
502async fn pair_first(
503    conn: &impl SessionStreams,
504    bus: &impl HostBus,
505    mut send: BoxSend,
506    payload: &[u8],
507) -> Result<(BoxSend, OpenOk, Pairing), SessionEnd> {
508    let endpoint = endpoint_hex(&conn.peer_key());
509    // An empty token is a malformed request, never an open session: only a
510    // request without the field asks for one.
511    let request = serde_json::from_slice::<serde_json::Value>(payload)
512        .ok()
513        .filter(serde_json::Value::is_object)
514        .and_then(|v| serde_json::from_value::<PairRequest>(v).ok())
515        .filter(|r| r.token.as_deref() != Some(""));
516    let Some(request) = request else {
517        respond_before_close(
518            &mut send,
519            err_frame(
520                "invalid_request",
521                "session.pair/1 needs {endpoint_id} and, with a door link, its token",
522            ),
523        )
524        .await;
525        conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
526        return Err(SessionEnd::NotOpened("invalid_request".into()));
527    };
528    if !request.endpoint_id.eq_ignore_ascii_case(&endpoint) {
529        respond_before_close(
530            &mut send,
531            err_frame(
532                "endpoint_mismatch",
533                "endpoint_id is not the key this connection proved",
534            ),
535        )
536        .await;
537        conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
538        return Err(SessionEnd::NotOpened("endpoint_mismatch".into()));
539    }
540
541    let admitted = match request.token.as_deref() {
542        Some(token) => match bus.admit_pairing(token, &endpoint).await {
543            Ok(admission) if member_node_id_ok(&admission.member_node_id) => {
544                pairing_from_admission(
545                    Some(admission.member_node_id),
546                    admission.expires_at_ms,
547                    &endpoint,
548                )
549            }
550            // A member id that cannot be a header is a host fault, not the device's.
551            Ok(_) => Err(Refusal::new("internal_error", "unusable member id")),
552            Err(refusal) => Err(refusal),
553        },
554        None => bus
555            .admit_open_pairing(&endpoint)
556            .await
557            .and_then(|admission| pairing_from_admission(None, admission.expires_at_ms, &endpoint)),
558    };
559    let pairing = match admitted {
560        Ok(pairing) => pairing,
561        Err(refusal) => {
562            respond_before_close(&mut send, map_pairing_refusal(refusal)).await;
563            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
564            return Err(SessionEnd::NotOpened("pairing refused".into()));
565        }
566    };
567    let ok = OpenOk {
568        mode: OpenMode::Renewal,
569        device_id: String::new(),
570        device_did: String::new(),
571        scopes: vec![],
572        expires_at: String::new(),
573    };
574    let body = serde_json::to_vec(&PairOk {
575        mode: "pairing",
576        expires_at_ms: now_ms().saturating_add(pairing.lifetime.as_millis() as i64),
577    })
578    .map_err(|_| SessionEnd::NotOpened("encode".into()))?;
579    respond(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
580    Ok((send, ok, pairing))
581}
582
583fn now_ms() -> i64 {
584    use std::time::{SystemTime, UNIX_EPOCH};
585    SystemTime::now()
586        .duration_since(UNIX_EPOCH)
587        .unwrap_or_default()
588        .as_millis() as i64
589}
590
591/// Shortest session worth opening; a token closer to expiry is refused.
592const MIN_PAIRING_LIFETIME: Duration = Duration::from_secs(1);
593
594/// [`PAIRING_LIFETIME`], cut short when the admission expires sooner.
595///
596/// A non-positive expiry is a host fault (`verifier_unavailable`); an
597/// admission that expires within [`MIN_PAIRING_LIFETIME`] is
598/// `pairing_token_expired`.
599fn pairing_from_admission(
600    member: Option<String>,
601    expires_at_ms: i64,
602    endpoint: &str,
603) -> Result<Pairing, Refusal> {
604    if expires_at_ms <= 0 {
605        return Err(Refusal::new(
606            "internal_error",
607            "admission without an expiry",
608        ));
609    }
610    let until_expiry = expires_at_ms.saturating_sub(now_ms());
611    if until_expiry < MIN_PAIRING_LIFETIME.as_millis() as i64 {
612        return Err(Refusal::new(
613            "pairing_token_expired",
614            "the door token has expired",
615        ));
616    }
617    Ok(Pairing {
618        member,
619        endpoint: endpoint.to_string(),
620        lifetime: PAIRING_LIFETIME.min(Duration::from_millis(until_expiry as u64)),
621    })
622}
623
624fn renewal_expires_at() -> String {
625    use std::time::{SystemTime, UNIX_EPOCH};
626    let secs = SystemTime::now()
627        .duration_since(UNIX_EPOCH)
628        .unwrap_or_default()
629        .as_secs()
630        + RENEWAL_LIFETIME.as_secs();
631    format!("{secs}")
632}
633
634#[allow(clippy::too_many_arguments)]
635async fn serve_opened<C, B>(
636    conn: Arc<C>,
637    bus: Arc<B>,
638    ingress: Arc<IngressSocket>,
639    wire: Arc<WireSocket>,
640    path: SessionPath,
641    webrtc: Option<Arc<dyn WebRtcSignaling>>,
642    _open_send: BoxSend,
643    identity: OpenOk,
644    pairing: Option<Pairing>,
645) -> Result<(), SessionEnd>
646where
647    C: SessionStreams + 'static,
648    B: HostBus + 'static,
649{
650    let identity = Arc::new(identity);
651    let pairing = pairing.map(Arc::new);
652    let peer = conn.peer_key();
653    let mut streams = JoinSet::new();
654    let lifetime = async {
655        if let Some(pairing) = pairing.as_ref() {
656            tokio::time::sleep(pairing.lifetime).await;
657        } else if identity.mode == OpenMode::Renewal {
658            tokio::time::sleep(RENEWAL_LIFETIME).await;
659        } else {
660            std::future::pending::<()>().await;
661        }
662    };
663    tokio::pin!(lifetime);
664
665    let serve = async {
666        loop {
667            while streams.try_join_next().is_some() {}
668            let (send, recv) = match conn.accept_bi().await {
669                Ok(s) => s,
670                Err(_) => break,
671            };
672            if streams.len() >= MAX_SESSION_STREAMS {
673                let mut send = send;
674                let mut recv = recv;
675                let _ = tokio::time::timeout(CALL_READ_DEADLINE, async {
676                    if let Ok(method) = peek_method(&mut recv).await {
677                        let _ = tunnel::refuse(&mut send, &method, "too_many_streams").await;
678                    }
679                })
680                .await;
681                let _ = send.shutdown().await;
682                continue;
683            }
684            let bus = bus.clone();
685            let ingress = ingress.clone();
686            let wire = wire.clone();
687            let identity = identity.clone();
688            let pairing = pairing.clone();
689            let webrtc = webrtc.clone();
690            streams.spawn(async move {
691                serve_stream(
692                    bus,
693                    ingress,
694                    wire,
695                    path,
696                    peer,
697                    &identity,
698                    pairing.as_deref(),
699                    webrtc,
700                    send,
701                    recv,
702                )
703                .await;
704            });
705        }
706    };
707
708    tokio::select! {
709        biased;
710        _ = &mut lifetime => {
711            let reason: &[u8] = if pairing.is_some() {
712                b"pairing session expired"
713            } else {
714                b"renewal session expired"
715            };
716            conn.close(PROTOCOL_CLOSE_CODE, reason);
717        }
718        _ = serve => {}
719    }
720    streams.abort_all();
721    while streams.join_next().await.is_some() {}
722    Ok(())
723}
724
725#[allow(clippy::too_many_arguments)]
726async fn serve_stream<B: HostBus>(
727    bus: Arc<B>,
728    ingress: Arc<IngressSocket>,
729    wire: Arc<WireSocket>,
730    path: SessionPath,
731    peer: [u8; 32],
732    identity: &OpenOk,
733    pairing: Option<&Pairing>,
734    webrtc: Option<Arc<dyn WebRtcSignaling>>,
735    mut send: BoxSend,
736    mut recv: BoxRecv,
737) {
738    let deadline = tokio::time::Instant::now() + CALL_READ_DEADLINE;
739    let method = match tokio::time::timeout_at(deadline, peek_method(&mut recv)).await {
740        Err(_) | Ok(Err(_)) => {
741            let _ = tunnel::refuse(&mut send, "unknown/1", "invalid_request").await;
742            let _ = send.shutdown().await;
743            return;
744        }
745        Ok(Ok(method)) => method,
746    };
747
748    // Checked first: a pairing session also carries a renewal-mode identity,
749    // so even without this gate it could do no more than renewal.
750    if pairing.is_some() && method != HTTP_REQUEST_METHOD {
751        let _ = tunnel::refuse(&mut send, &method, "pairing_only").await;
752        let _ = send.shutdown().await;
753        return;
754    }
755
756    if identity.mode == OpenMode::Renewal && method != HTTP_REQUEST_METHOD {
757        let _ = tunnel::refuse(&mut send, &method, "renewal_only").await;
758        let _ = send.shutdown().await;
759        return;
760    }
761
762    if method == WEBRTC_SIGNAL_METHOD {
763        match webrtc {
764            Some(hook) => {
765                hook.handle(identity, peer, send, recv).await;
766            }
767            None => {
768                let _ = tunnel::refuse(&mut send, &method, "unsupported_transport").await;
769                let _ = send.shutdown().await;
770            }
771        }
772        return;
773    }
774
775    // Post-open wire/1 for a FULL session only (renewal already refused above).
776    if method == WIRE_METHOD {
777        match wire.path.as_ref() {
778            Some(socket) => {
779                // Device-session carriers omit peer (no browser TCP IP).
780                let _ =
781                    wire_stream::splice_to_wire_socket(socket, path.as_str(), None, "", send, recv)
782                        .await;
783            }
784            None => {
785                let _ = tunnel::refuse(&mut send, WIRE_METHOD, "wire_unavailable").await;
786                let _ = send.shutdown().await;
787            }
788        }
789        return;
790    }
791
792    if method == HTTP_REQUEST_METHOD {
793        let gate = match (pairing, identity.mode) {
794            (Some(pairing), _) => Gate::Pairing {
795                member: pairing.member.as_deref(),
796                endpoint: &pairing.endpoint,
797            },
798            (None, OpenMode::Renewal) => Gate::Renewal,
799            (None, OpenMode::Full) => Gate::Full,
800        };
801        let _ = tunnel::serve_http(&ingress, path, &mut recv, &mut send, gate).await;
802        let _ = send.shutdown().await;
803        return;
804    }
805
806    if method == WS_STREAM_METHOD {
807        let _ = tunnel::serve_ws(&ingress, path, recv, send).await;
808        return;
809    }
810
811    let mut payload = Vec::new();
812    let read = tokio::time::timeout_at(
813        deadline,
814        recv.take((MAX_FRAME_BYTES - 2 - method.len()) as u64)
815            .read_to_end(&mut payload),
816    )
817    .await;
818    if read.is_err() || matches!(read, Ok(Err(_))) {
819        respond(
820            &mut send,
821            err_frame("invalid_request", "frame too large or unreadable"),
822        )
823        .await;
824        return;
825    }
826
827    let response = if method == SESSION_OPEN_METHOD || method == SESSION_PAIR_METHOD {
828        err_frame("already_open", "this connection already has a session")
829    } else if method == DEVICE_CALL_METHOD {
830        match device_call(bus.as_ref(), identity, &peer, &payload).await {
831            Ok(body) => encode_response(RESPONSE_STATUS_OK, body.to_string().as_bytes()),
832            Err(frame) => frame,
833        }
834    } else {
835        err_frame("unknown_method", &method)
836    };
837    respond(&mut send, response).await;
838}
839
840async fn device_call(
841    bus: &impl HostBus,
842    identity: &OpenOk,
843    peer: &[u8; 32],
844    payload: &[u8],
845) -> Result<serde_json::Value, Vec<u8>> {
846    let call: ServiceCall = serde_json::from_slice(payload)
847        .map_err(|_| err_frame("invalid_request", "device.call/1 needs {service, payload}"))?;
848    let svc = service(&call.service).ok_or_else(|| err_frame("unknown_service", &call.service))?;
849    if !scope_allows(&identity.scopes, svc.scope) {
850        return Err(err_frame("scope_denied", svc.scope));
851    }
852    let endpoint = endpoint_hex(peer);
853    let stamped = stamp(
854        call.payload,
855        &StampIdentity {
856            device_id: &identity.device_id,
857            device_did: &identity.device_did,
858            scopes: &identity.scopes,
859            endpoint_hex: &endpoint,
860        },
861    );
862    match tokio::time::timeout(CALL_DEADLINE, bus.invoke(svc.capability, stamped)).await {
863        Err(_) => Err(err_frame(
864            "timeout",
865            "the node service did not answer in time",
866        )),
867        Ok(Ok(value)) => Ok(value),
868        Ok(Err(refusal)) => Err(err_frame("service_error", &refusal.message)),
869    }
870}
871
872#[cfg(test)]
873mod tests {
874    use super::{open_log_fields, OpenedMode};
875    use crate::types::SessionPath;
876
877    #[test]
878    fn open_log_fields_are_stable_path_and_mode_words() {
879        let cases = [
880            (SessionPath::Relay, OpenedMode::Open, "relay", "open"),
881            (SessionPath::WebRtc, OpenedMode::Open, "webrtc", "open"),
882            (SessionPath::Relay, OpenedMode::Renew, "relay", "renew"),
883            (SessionPath::WebRtc, OpenedMode::Renew, "webrtc", "renew"),
884            (SessionPath::Relay, OpenedMode::Pair, "relay", "pair"),
885            (SessionPath::WebRtc, OpenedMode::Pair, "webrtc", "pair"),
886        ];
887        for (path, mode, path_word, mode_word) in cases {
888            let (logged_path, logged_mode) = open_log_fields(path, mode);
889            assert_eq!((logged_path, logged_mode), (path_word, mode_word));
890            assert_eq!(
891                format!("device session opened path={logged_path} mode={logged_mode}"),
892                format!("device session opened path={path_word} mode={mode_word}")
893            );
894        }
895    }
896}