Skip to main content

node_device_session/
revalidate.rs

1//! Periodic revalidation of live sessions.
2//!
3//! Ported from `node-app-iroh`'s `iroh.device.revalidate`: re-verify every live
4//! session so a device revoked, unpaired or expired since it connected loses
5//! its session within a minute.
6//!
7//! Only a *definitive* refusal from the host closes a session.
8//! `verifier_unavailable`, timeouts and other errors leave the session open
9//! and are counted as skipped.
10
11use crate::registry::SessionRegistry;
12use crate::traits::HostBus;
13use std::time::Duration;
14
15/// Per-session verify budget during a revalidation pass.
16const VERIFY_DEADLINE: Duration = Duration::from_secs(10);
17
18/// Verify-refusal codes that are a definitive refusal of the credential
19/// itself — the host has positively decided this session is no longer valid.
20const DEFINITIVE_REFUSALS: &[&str] = &[
21    "device_revoked",
22    "expired",
23    "invalid_credential",
24    "endpoint_mismatch",
25];
26
27/// The six refusal codes `core.device_session.verify` can answer with.
28const VERIFY_REFUSAL_CODES: &[&str] = &[
29    "invalid_request",
30    "endpoint_mismatch",
31    "invalid_credential",
32    "device_revoked",
33    "expired",
34    "verifier_unavailable",
35];
36
37/// Result of one [`SessionRegistry::revalidate`] pass.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct RevalidateReport {
40    /// Device ids whose sessions were closed on a definitive refusal.
41    pub closed: Vec<String>,
42    /// Sessions left open because verify failed non-definitively (or timed out).
43    pub skipped: u64,
44}
45
46/// Exact-match check: only these codes close a live session.
47pub fn is_definitive_refusal_code(code: &str) -> bool {
48    DEFINITIVE_REFUSALS
49        .iter()
50        .copied()
51        .any(|known| known == code)
52}
53
54/// Pull a known verify refusal *code* out of a host error string, if (and only
55/// if) it is one of the six codes the host's refusal shape carries.
56///
57/// Accepts either a bare code (`"device_revoked"`), a wire form
58/// (`"device_revoked: detail"`), or the production capability-bus shape
59/// (`"core.device_session.verify failed: device_revoked: detail"`). An
60/// invocation failure (`"… invocation failed: …"`) never parses to a code.
61pub fn verify_refusal_code(error: &str) -> Option<&str> {
62    let prefix = format!("{} failed: ", crate::caps::VERIFY);
63    let rest = error.strip_prefix(prefix.as_str()).unwrap_or(error);
64    let candidate = rest.split(':').next().unwrap_or(rest).trim();
65    VERIFY_REFUSAL_CODES
66        .iter()
67        .copied()
68        .find(|&known| known == candidate)
69}
70
71impl SessionRegistry {
72    /// Re-verify every live session via [`HostBus::verify`].
73    ///
74    /// Closes a session only on a definitive refusal code
75    /// (`device_revoked`, `expired`, `invalid_credential`, `endpoint_mismatch`).
76    /// `verifier_unavailable`, timeouts and other errors leave it open and
77    /// increment [`RevalidateReport::skipped`].
78    pub async fn revalidate(&self, bus: &dyn HostBus) -> RevalidateReport {
79        let live = self.credentials();
80        let mut closed = Vec::new();
81        let mut skipped = 0u64;
82        for (device_id, session_id, credential, endpoint_hex) in &live {
83            let verdict =
84                tokio::time::timeout(VERIFY_DEADLINE, bus.verify(credential, endpoint_hex)).await;
85            match verdict {
86                Ok(Ok(_)) => {}
87                Ok(Err(refusal)) if is_definitive_refusal_code(&refusal.code) => {
88                    if self.close(device_id, *session_id, b"revoked or expired") {
89                        closed.push(device_id.clone());
90                    }
91                }
92                Ok(Err(_)) | Err(_) => {
93                    skipped += 1;
94                }
95            }
96        }
97        RevalidateReport { closed, skipped }
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn definitive_codes_are_exact_matches_only() {
107        assert!(is_definitive_refusal_code("device_revoked"));
108        assert!(is_definitive_refusal_code("expired"));
109        assert!(is_definitive_refusal_code("invalid_credential"));
110        assert!(is_definitive_refusal_code("endpoint_mismatch"));
111        assert!(!is_definitive_refusal_code("verifier_unavailable"));
112        assert!(!is_definitive_refusal_code("invalid_request"));
113        assert!(!is_definitive_refusal_code("device_revoked_extra"));
114        assert!(!is_definitive_refusal_code(""));
115    }
116
117    #[test]
118    fn verify_refusal_code_parses_production_shapes() {
119        for code in VERIFY_REFUSAL_CODES {
120            let error = format!("{} failed: {code}: some detail", crate::caps::VERIFY);
121            assert_eq!(verify_refusal_code(&error), Some(*code));
122            assert_eq!(verify_refusal_code(code), Some(*code));
123        }
124        assert_eq!(
125            verify_refusal_code(&format!(
126                "{} invocation failed: host closed",
127                crate::caps::VERIFY
128            )),
129            None
130        );
131        assert_eq!(
132            verify_refusal_code(&format!(
133                "{} failed: something_else: detail",
134                crate::caps::VERIFY
135            )),
136            None
137        );
138        assert_eq!(verify_refusal_code("totally unrelated string"), None);
139        assert_eq!(verify_refusal_code(""), None);
140    }
141}