Skip to main content

tunnet_core/
state.rs

1use std::net::Ipv4Addr;
2use std::path::PathBuf;
3
4use anyhow::Context;
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7use uuid::Uuid;
8
9#[derive(Clone)]
10pub struct StatePaths {
11    pub dir: PathBuf,
12}
13
14impl StatePaths {
15    pub fn system_dir() -> PathBuf {
16        #[cfg(unix)]
17        {
18            PathBuf::from("/var/lib/tunnet")
19        }
20        #[cfg(windows)]
21        {
22            let base = std::env::var("PROGRAMDATA").unwrap_or_else(|_| r"C:\ProgramData".into());
23            PathBuf::from(base).join("tunnet")
24        }
25        #[cfg(not(any(unix, windows)))]
26        {
27            PathBuf::from("./tunnet-state")
28        }
29    }
30
31    pub fn resolve(explicit: Option<&str>) -> Self {
32        if let Some(p) = explicit {
33            return Self {
34                dir: PathBuf::from(p),
35            };
36        }
37        if let Ok(p) = std::env::var("TUNNET_STATE_DIR")
38            && !p.is_empty()
39        {
40            return Self {
41                dir: PathBuf::from(p),
42            };
43        }
44
45        let system = Self::system_dir();
46        if system.join("state.json").is_file() {
47            return Self { dir: system };
48        }
49        if running_as_service_user() {
50            return Self { dir: system };
51        }
52
53        #[cfg(unix)]
54        {
55            if let Ok(xdg) = std::env::var("XDG_STATE_HOME") {
56                return Self {
57                    dir: PathBuf::from(xdg).join("tunnet"),
58                };
59            }
60            if let Ok(home) = std::env::var("HOME") {
61                return Self {
62                    dir: PathBuf::from(home).join(".local/state/tunnet"),
63                };
64            }
65        }
66        #[cfg(windows)]
67        {
68            if let Ok(appdata) = std::env::var("LOCALAPPDATA") {
69                return Self {
70                    dir: PathBuf::from(appdata).join("tunnet"),
71                };
72            }
73        }
74        Self {
75            dir: PathBuf::from("./tunnet-state"),
76        }
77    }
78
79    pub fn state_file(&self) -> PathBuf {
80        self.dir.join("state.json")
81    }
82    pub fn cache_file(&self) -> PathBuf {
83        self.dir.join("routing_cache.json")
84    }
85    /// Unified agent configuration (TOML)
86    pub fn config_toml_file(&self) -> PathBuf {
87        self.dir.join("tunnet.toml")
88    }
89    /// Encrypted secrets (identity, network PSK, tickets, auth).
90    pub fn secrets_file(&self) -> PathBuf {
91        self.dir.join("state.enc")
92    }
93    /// Seal metadata for `state.enc` (tier, wrapped DEK / salt).
94    pub fn secrets_meta_file(&self) -> PathBuf {
95        self.dir.join("state.enc.meta")
96    }
97    /// Auto-update pending marker + previous binary live under this dir.
98    pub fn update_dir(&self) -> PathBuf {
99        self.dir.join("update")
100    }
101    pub fn update_pending_file(&self) -> PathBuf {
102        self.update_dir().join("pending.json")
103    }
104    pub fn update_previous_bin(&self) -> PathBuf {
105        self.update_dir().join("tunnet.prev")
106    }
107    /// Per-network iroh-docs store root.
108    pub fn docs_dir(&self, network_id: Uuid) -> PathBuf {
109        self.dir.join("docs").join(network_id.to_string())
110    }
111    /// Pending coordinator firewall suggestion for a network.
112    pub fn firewall_pending_file(&self, network_id: Uuid) -> PathBuf {
113        self.dir
114            .join("firewall_pending")
115            .join(format!("{network_id}.json"))
116    }
117    pub fn invites_file(&self, network_id: Uuid) -> PathBuf {
118        self.dir
119            .join("direct_invites")
120            .join(format!("{network_id}.json"))
121    }
122    pub fn pending_file(&self, network_id: Uuid) -> PathBuf {
123        self.dir
124            .join("direct_pending")
125            .join(format!("{network_id}.json"))
126    }
127    /// Manual IP overrides for birthday collisions (`override-ip`).
128    pub fn ip_overrides_file(&self) -> PathBuf {
129        self.dir.join("ip_overrides.json")
130    }
131
132    pub fn ensure(&self) -> anyhow::Result<()> {
133        std::fs::create_dir_all(&self.dir)
134            .with_context(|| format!("mkdir {}", self.dir.display()))?;
135        Ok(())
136    }
137
138    pub fn ensure_network_dirs(&self, network_id: Uuid) -> anyhow::Result<()> {
139        self.ensure()?;
140        for sub in [
141            self.docs_dir(network_id),
142            self.dir.join("firewall_pending"),
143            self.dir.join("direct_invites"),
144            self.dir.join("direct_pending"),
145        ] {
146            std::fs::create_dir_all(&sub).with_context(|| format!("mkdir {}", sub.display()))?;
147        }
148        Ok(())
149    }
150
151    pub fn clone_paths(&self) -> StatePaths {
152        StatePaths {
153            dir: self.dir.clone(),
154        }
155    }
156}
157
158fn running_as_service_user() -> bool {
159    #[cfg(unix)]
160    {
161        if std::env::var("USER").ok().as_deref() == Some("root") {
162            return true;
163        }
164        if std::env::var("HOME").ok().as_deref() == Some("/root") {
165            return true;
166        }
167        // systemd sets this when StateDirectory= is used.
168        if std::env::var("STATE_DIRECTORY").is_ok() {
169            return true;
170        }
171    }
172    #[cfg(windows)]
173    {
174        if std::env::var("USERNAME")
175            .ok()
176            .is_some_and(|u| u.eq_ignore_ascii_case("SYSTEM"))
177        {
178            return true;
179        }
180    }
181    false
182}
183
184/// Operating mode of this agent for the persisted network.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "lowercase")]
187pub enum NodeMode {
188    Managed,
189    Direct,
190}
191
192/// Managed-mode enrollment state (control plane).
193#[derive(Debug, Clone, Serialize, Deserialize)]
194pub struct ManagedState {
195    pub control_url: String,
196    pub network_name: String,
197    pub network_id: Uuid,
198    pub organization_id: String,
199    pub enrolled_at: DateTime<Utc>,
200}
201
202/// Direct-mode P2P network state (no control plane).
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct DirectState {
205    pub network_name: String,
206    /// Hex-encoded 32-byte network secret (PSK). In-memory only - sealed in `state.enc`.
207    #[serde(skip)]
208    pub network_secret: String,
209    /// Hex topic id = blake3(network_name || secret).
210    pub topic_hash: String,
211    /// Deterministic UUID derived from topic_hash (for IPC / gossip topic helpers).
212    pub network_id: Uuid,
213    pub coordinator: bool,
214    /// Auto-admit valid invite codes without manual approval.
215    #[serde(default)]
216    pub open: bool,
217    pub assigned_ipv4: Ipv4Addr,
218    #[serde(default)]
219    pub collision_index: u8,
220    pub hostname: String,
221    /// Optional coordinator endpoint id (hex) known at join time.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub coordinator_endpoint_id: Option<String>,
224    /// iroh-docs write ticket. In-memory only - sealed in `state.enc`.
225    #[serde(skip)]
226    pub doc_ticket: Option<String>,
227    /// iroh-docs namespace id (hex). Network document identity.
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub namespace_id: Option<String>,
230    /// Auto-accept coordinator firewall policy suggestions.
231    #[serde(default)]
232    pub auto_accept_firewall: bool,
233    pub created_at: DateTime<Utc>,
234}
235
236#[derive(Debug, Clone, Serialize, Deserialize)]
237#[serde(tag = "mode", rename_all = "lowercase")]
238pub enum PersistedState {
239    Managed(ManagedState),
240    Direct {
241        /// Join order = vec order (first = outbound winner on IP clash).
242        networks: Vec<DirectState>,
243    },
244}
245
246impl PersistedState {
247    /// Write public (non-secret) fields to `state.json`.
248    pub fn save_public(&self, paths: &StatePaths) -> anyhow::Result<()> {
249        paths.ensure()?;
250        let json = serde_json::to_vec_pretty(self)?;
251        std::fs::write(paths.state_file(), json)?;
252        Ok(())
253    }
254
255    /// Alias: public state only. Secrets go through [`crate::secret_store`].
256    pub fn save(&self, paths: &StatePaths) -> anyhow::Result<()> {
257        self.save_public(paths)
258    }
259
260    pub fn load(paths: &StatePaths) -> anyhow::Result<Self> {
261        let s = std::fs::read(paths.state_file())
262            .with_context(|| format!("read {}", paths.state_file().display()))?;
263        serde_json::from_slice(&s).context("parse state.json")
264    }
265
266    /// Load state if present; `Ok(None)` when no state file exists yet.
267    pub fn try_load(paths: &StatePaths) -> anyhow::Result<Option<Self>> {
268        if !paths.state_file().exists() {
269            return Ok(None);
270        }
271        Ok(Some(Self::load(paths)?))
272    }
273
274    /// Merge secrets from `state.enc` into this in-memory state.
275    pub fn apply_secrets(&mut self, secrets: &crate::secret_store::AgentSecrets) {
276        if let PersistedState::Direct { networks } = self {
277            for d in networks.iter_mut() {
278                if let Some(ns) = secrets.networks.get(&d.network_id) {
279                    d.network_secret = ns.network_secret.clone();
280                    d.doc_ticket = ns.doc_ticket.clone();
281                }
282            }
283        }
284    }
285
286    pub fn mode(&self) -> NodeMode {
287        match self {
288            PersistedState::Managed(_) => NodeMode::Managed,
289            PersistedState::Direct { .. } => NodeMode::Direct,
290        }
291    }
292
293    pub fn is_managed(&self) -> bool {
294        matches!(self, PersistedState::Managed(_))
295    }
296
297    pub fn is_direct(&self) -> bool {
298        matches!(self, PersistedState::Direct { .. })
299    }
300
301    pub fn as_managed(&self) -> Option<&ManagedState> {
302        match self {
303            PersistedState::Managed(m) => Some(m),
304            _ => None,
305        }
306    }
307
308    pub fn direct_networks(&self) -> &[DirectState] {
309        match self {
310            PersistedState::Direct { networks } => networks,
311            _ => &[],
312        }
313    }
314
315    pub fn direct_networks_mut(&mut self) -> Option<&mut Vec<DirectState>> {
316        match self {
317            PersistedState::Direct { networks } => Some(networks),
318            _ => None,
319        }
320    }
321
322    pub fn direct_by_name(&self, name: &str) -> Option<&DirectState> {
323        self.direct_networks()
324            .iter()
325            .find(|d| d.network_name.eq_ignore_ascii_case(name))
326    }
327
328    pub fn direct_by_id(&self, id: Uuid) -> Option<&DirectState> {
329        self.direct_networks().iter().find(|d| d.network_id == id)
330    }
331
332    /// Resolve a Direct network by optional name. If `name` is `None` and exactly
333    /// one network is joined, returns that network.
334    pub fn require_direct_network(&self, name: Option<&str>) -> anyhow::Result<&DirectState> {
335        let networks = match self {
336            PersistedState::Direct { networks } => networks,
337            PersistedState::Managed(_) => anyhow::bail!(
338                "this command requires Direct mode; this agent is in Managed mode \
339                 (run `tunnet reset --yes` to switch)"
340            ),
341        };
342        if networks.is_empty() {
343            anyhow::bail!("no Direct networks joined");
344        }
345        match name {
346            Some(n) => self
347                .direct_by_name(n)
348                .with_context(|| format!("Direct network '{n}' not found")),
349            None if networks.len() == 1 => Ok(&networks[0]),
350            None => anyhow::bail!(
351                "multiple Direct networks joined; pass --network <name> \
352                 (joined: {})",
353                networks
354                    .iter()
355                    .map(|d| d.network_name.as_str())
356                    .collect::<Vec<_>>()
357                    .join(", ")
358            ),
359        }
360    }
361
362    pub fn require_managed(&self) -> anyhow::Result<&ManagedState> {
363        self.as_managed().context(
364            "this command requires Managed mode; this agent is in Direct mode \
365             (run `tunnet reset --yes` to switch)",
366        )
367    }
368
369    /// Managed network id, or first Direct network id (status / display helpers).
370    pub fn primary_network_id(&self) -> Option<Uuid> {
371        match self {
372            PersistedState::Managed(m) => Some(m.network_id),
373            PersistedState::Direct { networks } => networks.first().map(|d| d.network_id),
374        }
375    }
376
377    pub fn primary_network_name(&self) -> Option<&str> {
378        match self {
379            PersistedState::Managed(m) => Some(&m.network_name),
380            PersistedState::Direct { networks } => {
381                networks.first().map(|d| d.network_name.as_str())
382            }
383        }
384    }
385}
386
387/// Tokens from `tunnet login` (OAuth PKCE against management).
388#[derive(Debug, Clone, Serialize, Deserialize)]
389pub struct CliAuthTokens {
390    pub management_url: String,
391    pub access_token: String,
392    pub refresh_token: Option<String>,
393    pub token_type: String,
394    pub scope: Option<String>,
395    pub expires_at: Option<DateTime<Utc>>,
396    pub obtained_at: DateTime<Utc>,
397}
398
399impl CliAuthTokens {
400    /// Persist auth tokens into `state.enc` (creates a sealed vault if needed).
401    pub fn save(&self, paths: &StatePaths) -> anyhow::Result<()> {
402        crate::secret_store::store_auth(paths, self.clone())
403    }
404
405    pub fn load(paths: &StatePaths) -> anyhow::Result<Self> {
406        crate::secret_store::load_auth(paths)?.context("no auth tokens in state.enc")
407    }
408
409    pub fn clear(paths: &StatePaths) -> anyhow::Result<()> {
410        crate::secret_store::clear_auth(paths)
411    }
412
413    pub fn access_token_valid(&self) -> bool {
414        match self.expires_at {
415            Some(exp) => exp > Utc::now() + chrono::Duration::seconds(30),
416            None => true,
417        }
418    }
419}
420
421pub fn save_snapshot_cache(
422    paths: &StatePaths,
423    snap: &tunnet_common::EndpointSnapshot,
424) -> anyhow::Result<()> {
425    paths.ensure()?;
426    let json = serde_json::to_vec(snap)?;
427    std::fs::write(paths.cache_file(), json)?;
428    Ok(())
429}
430
431pub fn load_snapshot_cache(paths: &StatePaths) -> Option<tunnet_common::EndpointSnapshot> {
432    let s = std::fs::read(paths.cache_file()).ok()?;
433    serde_json::from_slice(&s).ok()
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    #[test]
441    fn tagged_direct_roundtrip() {
442        let s = PersistedState::Direct {
443            networks: vec![DirectState {
444                network_name: "home".into(),
445                network_secret: "aa".repeat(32),
446                topic_hash: "bb".repeat(32),
447                network_id: Uuid::nil(),
448                coordinator: true,
449                open: true,
450                assigned_ipv4: "100.64.0.1".parse().unwrap(),
451                collision_index: 0,
452                hostname: "laptop".into(),
453                coordinator_endpoint_id: None,
454                doc_ticket: None,
455                namespace_id: None,
456                auto_accept_firewall: false,
457                created_at: Utc::now(),
458            }],
459        };
460        let bytes = serde_json::to_vec(&s).unwrap();
461        let loaded: PersistedState = serde_json::from_slice(&bytes).unwrap();
462        assert!(loaded.is_direct());
463        let d = loaded.require_direct_network(None).unwrap();
464        assert!(
465            d.network_secret.is_empty(),
466            "secrets must not live in state.json"
467        );
468        assert!(d.doc_ticket.is_none());
469    }
470
471    #[test]
472    fn tagged_managed_roundtrip() {
473        let s = PersistedState::Managed(ManagedState {
474            control_url: "http://localhost:8080".into(),
475            network_name: "default".into(),
476            network_id: Uuid::nil(),
477            organization_id: "org".into(),
478            enrolled_at: Utc::now(),
479        });
480        let bytes = serde_json::to_vec(&s).unwrap();
481        let loaded: PersistedState = serde_json::from_slice(&bytes).unwrap();
482        assert!(loaded.is_managed());
483        assert_eq!(loaded.primary_network_name(), Some("default"));
484    }
485
486    #[test]
487    fn require_direct_network_multi() {
488        let s = PersistedState::Direct {
489            networks: vec![
490                DirectState {
491                    network_name: "gaming".into(),
492                    network_secret: String::new(),
493                    topic_hash: "aa".repeat(32),
494                    network_id: Uuid::from_u128(1),
495                    coordinator: true,
496                    open: false,
497                    assigned_ipv4: "100.64.0.1".parse().unwrap(),
498                    collision_index: 0,
499                    hostname: "laptop".into(),
500                    coordinator_endpoint_id: None,
501                    doc_ticket: None,
502                    namespace_id: None,
503                    auto_accept_firewall: false,
504                    created_at: Utc::now(),
505                },
506                DirectState {
507                    network_name: "homelab".into(),
508                    network_secret: String::new(),
509                    topic_hash: "bb".repeat(32),
510                    network_id: Uuid::from_u128(2),
511                    coordinator: false,
512                    open: false,
513                    assigned_ipv4: "100.64.0.1".parse().unwrap(),
514                    collision_index: 0,
515                    hostname: "laptop".into(),
516                    coordinator_endpoint_id: None,
517                    doc_ticket: None,
518                    namespace_id: None,
519                    auto_accept_firewall: false,
520                    created_at: Utc::now(),
521                },
522            ],
523        };
524        assert!(s.require_direct_network(None).is_err());
525        assert_eq!(
526            s.require_direct_network(Some("homelab"))
527                .unwrap()
528                .network_name,
529            "homelab"
530        );
531    }
532}