node-device-session 7.7.1

Shared server for /econ-v1/device-session/1 behind transport-neutral traits (C-5)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! [`serve`]: the C-5 device-session accept loop.

use crate::messages::{
    endpoint_hex, scope_allows, service, stamp, OpenMode, OpenOk, OpenRequest, RenewOk,
    RenewRequest, ServiceCall, StampIdentity,
};
use crate::registry::{SessionClose, SessionRegistry};
use crate::traits::{BoxRecv, BoxSend, HostBus, SessionStreams, WebRtcSignaling};
use crate::tunnel;
use crate::types::{IngressSocket, Refusal, Session, SessionEnd, SessionPath, WireSocket};
use crate::wire::{
    decode_request, encode_response, peek_method, DEVICE_CALL_METHOD, HTTP_REQUEST_METHOD,
    MAX_FRAME_BYTES, RESPONSE_STATUS_ERR, RESPONSE_STATUS_OK, SESSION_OPEN_METHOD,
    SESSION_RENEW_METHOD, WEBRTC_SIGNAL_METHOD, WIRE_METHOD, WS_STREAM_METHOD,
};
use crate::wire_stream;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::task::JoinSet;

const OPEN_DEADLINE: Duration = Duration::from_secs(10);
const CALL_DEADLINE: Duration = Duration::from_secs(30);
const CALL_READ_DEADLINE: Duration = Duration::from_secs(30);
const CLOSE_GRACE: Duration = Duration::from_secs(2);
const MAX_SESSION_STREAMS: usize = 16;
const RENEWAL_LIFETIME: Duration = Duration::from_secs(120);
const PROTOCOL_CLOSE_CODE: u32 = 1;

fn err_frame(code: &str, message: &str) -> Vec<u8> {
    encode_response(RESPONSE_STATUS_ERR, format!("{code}: {message}").as_bytes())
}

fn session_from_verify(session: Session) -> OpenOk {
    OpenOk {
        mode: OpenMode::Full,
        device_id: session.device_id,
        device_did: session.device_did,
        scopes: session.scopes,
        expires_at: session.expires_at,
    }
}

fn session_from_admit(session: Session) -> OpenOk {
    OpenOk {
        mode: OpenMode::Renewal,
        device_id: session.device_id,
        device_did: session.device_did,
        scopes: vec![],
        expires_at: if session.expires_at.is_empty() {
            renewal_expires_at()
        } else {
            session.expires_at
        },
    }
}

fn map_verify_refusal(refusal: Refusal) -> Vec<u8> {
    match refusal.code.as_str() {
        "invalid_request"
        | "endpoint_mismatch"
        | "invalid_credential"
        | "device_revoked"
        | "expired"
        | "verifier_unavailable" => err_frame(&refusal.code, &refusal.message),
        _ => err_frame(
            "verifier_unavailable",
            "verification is temporarily unavailable",
        ),
    }
}

fn map_renew_refusal(refusal: Refusal) -> (&'static str, &'static str) {
    match refusal.code.as_str() {
        "device_revoked" => ("device_revoked", "the device is revoked"),
        "device_not_registered" => ("device_not_registered", "the device is not registered"),
        "pending_approval" => ("pending_approval", "the device awaits approval"),
        "rejected" => ("rejected", "the device was rejected"),
        "rate_limited" => ("rate_limited", "try renewal later"),
        "invalid_request" => ("invalid_request", "invalid renewal request"),
        "internal_error" => ("internal_error", "renewal failed"),
        _ => ("renew_unavailable", "renewal is temporarily unavailable"),
    }
}

fn map_admit_refusal(refusal: Refusal) -> Vec<u8> {
    match refusal.code.as_str() {
        "rate_limited" => err_frame("rate_limited", "renewal admission rate limited"),
        "device_revoked" => err_frame("device_revoked", "the device is revoked"),
        "unknown_endpoint" => err_frame("unknown_endpoint", "the endpoint is not registered"),
        _ => err_frame(
            "verifier_unavailable",
            "verification is temporarily unavailable",
        ),
    }
}

async fn respond(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
    let _ = send.write_all(&frame).await;
    let _ = send.shutdown().await;
}

async fn respond_before_close(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
    respond(send, frame).await;
    tokio::time::sleep(CLOSE_GRACE).await;
}

/// Optional knobs for [`serve_with_options`].
///
/// Additive: existing [`serve`] / [`serve_with_registry`] keep their signatures
/// and behave as today (no wire socket → `wire/1` refused).
#[non_exhaustive]
#[derive(Clone, Default)]
pub struct ServeOptions {
    /// Live-session registry for periodic revalidation; `None` skips registration.
    pub registry: Option<SessionRegistry>,
    /// Node wire socket `wire/1` splices onto; default (no path) refuses.
    pub wire: WireSocket,
}

/// Serve one authenticated peer connection until it ends.
///
/// `webrtc` is the carrier hook for `webrtc.signal/1`. Pass [`Some`] when the
/// carrier can answer WebRTC on this connection (iroh); pass [`None`] to refuse
/// with `unsupported_transport`.
///
/// Does not touch a [`SessionRegistry`]. Carriers that need live-session
/// revalidation should call [`serve_with_registry`] instead. Carriers that
/// need `wire/1` should call [`serve_with_options`].
pub async fn serve<C, B>(
    conn: C,
    bus: B,
    ingress: IngressSocket,
    path: SessionPath,
    webrtc: Option<Arc<dyn WebRtcSignaling>>,
) -> Result<(), SessionEnd>
where
    C: SessionStreams + 'static,
    B: HostBus + 'static,
{
    serve_with_options(conn, bus, ingress, path, webrtc, ServeOptions::default()).await
}

/// Like [`serve`], but registers a successful full-mode open in `registry`
/// (for once-a-minute revalidation) and removes it when this call returns.
///
/// The close callback stored in the registry closes the [`SessionStreams`]
/// connection. Bind a [`crate::WebRtcHandle`] with
/// [`SessionRegistry::bind_webrtc`] so revocation also tears down WebRTC.
///
/// For `wire/1`, use [`serve_with_options`] with both `registry` and `wire`.
pub async fn serve_with_registry<C, B>(
    conn: C,
    bus: B,
    ingress: IngressSocket,
    path: SessionPath,
    webrtc: Option<Arc<dyn WebRtcSignaling>>,
    registry: SessionRegistry,
) -> Result<(), SessionEnd>
where
    C: SessionStreams + 'static,
    B: HostBus + 'static,
{
    serve_with_options(
        conn,
        bus,
        ingress,
        path,
        webrtc,
        ServeOptions {
            registry: Some(registry),
            ..ServeOptions::default()
        },
    )
    .await
}

/// Like [`serve`], with optional registry and wire socket via [`ServeOptions`].
pub async fn serve_with_options<C, B>(
    conn: C,
    bus: B,
    ingress: IngressSocket,
    path: SessionPath,
    webrtc: Option<Arc<dyn WebRtcSignaling>>,
    options: ServeOptions,
) -> Result<(), SessionEnd>
where
    C: SessionStreams + 'static,
    B: HostBus + 'static,
{
    serve_inner(
        conn,
        bus,
        ingress,
        options.wire,
        path,
        webrtc,
        options.registry,
    )
    .await
}

async fn serve_inner<C, B>(
    conn: C,
    bus: B,
    ingress: IngressSocket,
    wire: WireSocket,
    path: SessionPath,
    webrtc: Option<Arc<dyn WebRtcSignaling>>,
    registry: Option<SessionRegistry>,
) -> Result<(), SessionEnd>
where
    C: SessionStreams + 'static,
    B: HostBus + 'static,
{
    let conn = Arc::new(conn);
    let bus = Arc::new(bus);
    let ingress = Arc::new(ingress);
    let wire = Arc::new(wire);

    let attempt = tokio::time::timeout(OPEN_DEADLINE, async {
        let (mut send, mut recv) = conn.accept_bi().await?;
        let mut bytes = Vec::new();
        (&mut recv)
            .take(MAX_FRAME_BYTES as u64 + 1)
            .read_to_end(&mut bytes)
            .await?;
        if bytes.len() > MAX_FRAME_BYTES {
            conn.close(PROTOCOL_CLOSE_CODE, b"frame too large or unreadable");
            return Err(SessionEnd::NotOpened("frame too large".into()));
        }
        match decode_request(&bytes) {
            Ok((method, payload)) if method == SESSION_OPEN_METHOD => {
                open_first(conn.as_ref(), bus.as_ref(), send, payload).await
            }
            Ok((method, payload)) if method == SESSION_RENEW_METHOD => {
                // Renew is one-shot and never registers a live session.
                renew_first(conn.as_ref(), bus.as_ref(), send, payload)
                    .await
                    .map(|(send, ok)| (send, ok, None))
            }
            _ => {
                respond_before_close(
                    &mut send,
                    err_frame("not_open", "the first stream must be session.open/1"),
                )
                .await;
                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
                Err(SessionEnd::NotOpened("not_open".into()))
            }
        }
    })
    .await;

    let (send, identity, credential) = match attempt {
        Ok(Ok(v)) => v,
        Ok(Err(e)) => return Err(e),
        Err(_) => {
            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened in time");
            return Err(SessionEnd::OpenTimeout);
        }
    };

    let registered = match (registry.as_ref(), credential) {
        (Some(registry), Some(credential)) => {
            let conn_close = conn.clone();
            let close: SessionClose = Arc::new(move |code, reason| {
                conn_close.close(code, reason);
            });
            let device_id = identity.device_id.clone();
            let endpoint = endpoint_hex(&conn.peer_key());
            let session_id = registry.insert(device_id.clone(), credential, endpoint, close);
            Some((device_id, session_id))
        }
        _ => None,
    };

    let result = serve_opened(conn, bus, ingress, wire, path, webrtc, send, identity).await;

    if let (Some(registry), Some((device_id, session_id))) = (registry, registered) {
        registry.remove_if(&device_id, session_id);
    }
    result
}

async fn open_first(
    conn: &impl SessionStreams,
    bus: &impl HostBus,
    mut send: BoxSend,
    payload: &[u8],
) -> Result<(BoxSend, OpenOk, Option<String>), SessionEnd> {
    let request: OpenRequest = match serde_json::from_slice(payload) {
        Ok(r) => r,
        Err(_) => {
            respond_before_close(
                &mut send,
                err_frame(
                    "invalid_request",
                    "session.open/1 needs {credential} or {mode: renewal}",
                ),
            )
            .await;
            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
            return Err(SessionEnd::NotOpened("invalid_request".into()));
        }
    };

    let endpoint = endpoint_hex(&conn.peer_key());
    let (ok, credential) = if request.mode == Some(OpenMode::Renewal) {
        if request.credential.is_some() {
            respond_before_close(
                &mut send,
                err_frame("invalid_request", "renewal mode takes no credential"),
            )
            .await;
            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
            return Err(SessionEnd::NotOpened("invalid_request".into()));
        }
        let ok = match bus.admit_renewal(&endpoint).await {
            Ok(session) => session_from_admit(session),
            Err(refusal) => {
                respond_before_close(&mut send, map_admit_refusal(refusal)).await;
                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
                return Err(SessionEnd::NotOpened("admit refused".into()));
            }
        };
        (ok, None)
    } else {
        let credential = match request.credential.filter(|c| !c.is_empty()) {
            Some(c) => c,
            None => {
                respond_before_close(
                    &mut send,
                    err_frame("invalid_request", "full mode needs a credential"),
                )
                .await;
                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
                return Err(SessionEnd::NotOpened("invalid_request".into()));
            }
        };
        let ok = match bus.verify(&credential, &endpoint).await {
            Ok(session) => session_from_verify(session),
            Err(refusal) => {
                respond_before_close(&mut send, map_verify_refusal(refusal)).await;
                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
                return Err(SessionEnd::NotOpened("verify refused".into()));
            }
        };
        (ok, Some(credential))
    };

    let body = serde_json::to_vec(&ok).map_err(|_| SessionEnd::NotOpened("encode".into()))?;
    respond(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
    Ok((send, ok, credential))
}

async fn renew_first(
    conn: &impl SessionStreams,
    bus: &impl HostBus,
    mut send: BoxSend,
    payload: &[u8],
) -> Result<(BoxSend, OpenOk), SessionEnd> {
    let endpoint = endpoint_hex(&conn.peer_key());
    let value: serde_json::Value = match serde_json::from_slice::<serde_json::Value>(payload) {
        Ok(v) if v.is_object() => v,
        _ => {
            respond_before_close(
                &mut send,
                err_frame("invalid_request", "session.renew/1 needs {}"),
            )
            .await;
            conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
            return Err(SessionEnd::NotOpened("invalid_request".into()));
        }
    };
    if serde_json::from_value::<RenewRequest>(value).is_err() {
        respond_before_close(
            &mut send,
            err_frame("invalid_request", "session.renew/1 needs {}"),
        )
        .await;
        conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
        return Err(SessionEnd::NotOpened("invalid_request".into()));
    }

    match bus.renew(&endpoint).await {
        Ok(session) => {
            let ok = RenewOk {
                credential: session.credential.unwrap_or_default(),
                expires_at: session.expires_at,
                scopes: session.scopes,
                device_id: session.device_id,
                device_did: session.device_did,
                revocation_id: None,
            };
            let body = serde_json::to_vec(&ok).unwrap_or_default();
            respond_before_close(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
            conn.close(0, b"renewal complete");
            Err(SessionEnd::Closed)
        }
        Err(refusal) => {
            let (code, detail) = map_renew_refusal(refusal);
            respond_before_close(&mut send, err_frame(code, detail)).await;
            conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
            Err(SessionEnd::NotOpened(code.into()))
        }
    }
}

fn renewal_expires_at() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
        + RENEWAL_LIFETIME.as_secs();
    format!("{secs}")
}

#[allow(clippy::too_many_arguments)]
async fn serve_opened<C, B>(
    conn: Arc<C>,
    bus: Arc<B>,
    ingress: Arc<IngressSocket>,
    wire: Arc<WireSocket>,
    path: SessionPath,
    webrtc: Option<Arc<dyn WebRtcSignaling>>,
    _open_send: BoxSend,
    identity: OpenOk,
) -> Result<(), SessionEnd>
where
    C: SessionStreams + 'static,
    B: HostBus + 'static,
{
    let identity = Arc::new(identity);
    let peer = conn.peer_key();
    let mut streams = JoinSet::new();
    let lifetime = async {
        if identity.mode == OpenMode::Renewal {
            tokio::time::sleep(RENEWAL_LIFETIME).await;
        } else {
            std::future::pending::<()>().await;
        }
    };
    tokio::pin!(lifetime);

    let serve = async {
        loop {
            while streams.try_join_next().is_some() {}
            let (send, recv) = match conn.accept_bi().await {
                Ok(s) => s,
                Err(_) => break,
            };
            if streams.len() >= MAX_SESSION_STREAMS {
                let mut send = send;
                let mut recv = recv;
                let _ = tokio::time::timeout(CALL_READ_DEADLINE, async {
                    if let Ok(method) = peek_method(&mut recv).await {
                        let _ = tunnel::refuse(&mut send, &method, "too_many_streams").await;
                    }
                })
                .await;
                let _ = send.shutdown().await;
                continue;
            }
            let bus = bus.clone();
            let ingress = ingress.clone();
            let wire = wire.clone();
            let identity = identity.clone();
            let webrtc = webrtc.clone();
            streams.spawn(async move {
                serve_stream(
                    bus, ingress, wire, path, peer, &identity, webrtc, send, recv,
                )
                .await;
            });
        }
    };

    tokio::select! {
        biased;
        _ = &mut lifetime => {
            conn.close(PROTOCOL_CLOSE_CODE, b"renewal session expired");
        }
        _ = serve => {}
    }
    streams.abort_all();
    while streams.join_next().await.is_some() {}
    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn serve_stream<B: HostBus>(
    bus: Arc<B>,
    ingress: Arc<IngressSocket>,
    wire: Arc<WireSocket>,
    path: SessionPath,
    peer: [u8; 32],
    identity: &OpenOk,
    webrtc: Option<Arc<dyn WebRtcSignaling>>,
    mut send: BoxSend,
    mut recv: BoxRecv,
) {
    let deadline = tokio::time::Instant::now() + CALL_READ_DEADLINE;
    let method = match tokio::time::timeout_at(deadline, peek_method(&mut recv)).await {
        Err(_) | Ok(Err(_)) => {
            let _ = tunnel::refuse(&mut send, "unknown/1", "invalid_request").await;
            let _ = send.shutdown().await;
            return;
        }
        Ok(Ok(method)) => method,
    };

    if identity.mode == OpenMode::Renewal && method != HTTP_REQUEST_METHOD {
        let _ = tunnel::refuse(&mut send, &method, "renewal_only").await;
        let _ = send.shutdown().await;
        return;
    }

    if method == WEBRTC_SIGNAL_METHOD {
        match webrtc {
            Some(hook) => {
                hook.handle(identity, peer, send, recv).await;
            }
            None => {
                let _ = tunnel::refuse(&mut send, &method, "unsupported_transport").await;
                let _ = send.shutdown().await;
            }
        }
        return;
    }

    // Post-open wire/1 for a FULL session only (renewal already refused above).
    if method == WIRE_METHOD {
        match wire.path.as_ref() {
            Some(socket) => {
                // Device-session carriers omit peer (no browser TCP IP).
                let _ =
                    wire_stream::splice_to_wire_socket(socket, path.as_str(), None, "", send, recv)
                        .await;
            }
            None => {
                let _ = tunnel::refuse(&mut send, WIRE_METHOD, "wire_unavailable").await;
                let _ = send.shutdown().await;
            }
        }
        return;
    }

    if method == HTTP_REQUEST_METHOD {
        let _ = tunnel::serve_http(
            &ingress,
            path,
            &mut recv,
            &mut send,
            identity.mode == OpenMode::Renewal,
        )
        .await;
        let _ = send.shutdown().await;
        return;
    }

    if method == WS_STREAM_METHOD {
        let _ = tunnel::serve_ws(&ingress, path, recv, send).await;
        return;
    }

    let mut payload = Vec::new();
    let read = tokio::time::timeout_at(
        deadline,
        recv.take((MAX_FRAME_BYTES - 2 - method.len()) as u64)
            .read_to_end(&mut payload),
    )
    .await;
    if read.is_err() || matches!(read, Ok(Err(_))) {
        respond(
            &mut send,
            err_frame("invalid_request", "frame too large or unreadable"),
        )
        .await;
        return;
    }

    let response = if method == SESSION_OPEN_METHOD {
        err_frame("already_open", "this connection already has a session")
    } else if method == DEVICE_CALL_METHOD {
        match device_call(bus.as_ref(), identity, &peer, &payload).await {
            Ok(body) => encode_response(RESPONSE_STATUS_OK, body.to_string().as_bytes()),
            Err(frame) => frame,
        }
    } else {
        err_frame("unknown_method", &method)
    };
    respond(&mut send, response).await;
}

async fn device_call(
    bus: &impl HostBus,
    identity: &OpenOk,
    peer: &[u8; 32],
    payload: &[u8],
) -> Result<serde_json::Value, Vec<u8>> {
    let call: ServiceCall = serde_json::from_slice(payload)
        .map_err(|_| err_frame("invalid_request", "device.call/1 needs {service, payload}"))?;
    let svc = service(&call.service).ok_or_else(|| err_frame("unknown_service", &call.service))?;
    if !scope_allows(&identity.scopes, svc.scope) {
        return Err(err_frame("scope_denied", svc.scope));
    }
    let endpoint = endpoint_hex(peer);
    let stamped = stamp(
        call.payload,
        &StampIdentity {
            device_id: &identity.device_id,
            device_did: &identity.device_did,
            scopes: &identity.scopes,
            endpoint_hex: &endpoint,
        },
    );
    match tokio::time::timeout(CALL_DEADLINE, bus.invoke(svc.capability, stamped)).await {
        Err(_) => Err(err_frame(
            "timeout",
            "the node service did not answer in time",
        )),
        Ok(Ok(value)) => Ok(value),
        Ok(Err(refusal)) => Err(err_frame("service_error", &refusal.message)),
    }
}