Skip to main content

surjection_core/
env.rs

1//! Process environment facade: OS, known folders, environment variables, host
2//! name and clock. The core reads these only through [`Env`]; the CLI and the app build
3//! one from the process, tests build one from a temp root.
4
5use std::collections::BTreeMap;
6use std::ffi::{OsStr, OsString};
7use std::fmt;
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10use std::time::SystemTime;
11
12use crate::error::{CoreError, ErrorCode};
13
14/// Operating system whose conventions apply (paths, variable name casing).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum Os {
17    Windows,
18    /// Linux and other XDG-style Unix systems.
19    Linux,
20    MacOs,
21}
22
23impl Os {
24    /// Stable `snake_case` name used in CLI and IPC output.
25    pub const fn as_str(self) -> &'static str {
26        match self {
27            Os::Windows => "windows",
28            Os::Linux => "linux",
29            Os::MacOs => "macos",
30        }
31    }
32}
33
34/// Windows Known Folders besides the profile (which is [`Env::home`]).
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum KnownFolder {
37    /// `FOLDERID_LocalAppData` (`%LOCALAPPDATA%`).
38    LocalAppData,
39    /// `FOLDERID_RoamingAppData` (`%APPDATA%`).
40    RoamingAppData,
41}
42
43/// Source of the current time.
44pub trait Clock: fmt::Debug + Send + Sync {
45    fn now(&self) -> SystemTime;
46}
47
48/// The real system clock.
49#[derive(Debug, Clone, Copy, Default)]
50pub struct SystemClock;
51
52impl Clock for SystemClock {
53    fn now(&self) -> SystemTime {
54        SystemTime::now()
55    }
56}
57
58/// A clock frozen at one instant, for deterministic tests.
59#[derive(Debug, Clone, Copy)]
60pub struct FixedClock(pub SystemTime);
61
62impl Clock for FixedClock {
63    fn now(&self) -> SystemTime {
64        self.0
65    }
66}
67
68/// Everything the core may know about the process it runs in.
69#[derive(Debug, Clone)]
70pub struct Env {
71    os: Os,
72    home: PathBuf,
73    local_app_data: Option<PathBuf>,
74    roaming_app_data: Option<PathBuf>,
75    vars: BTreeMap<String, OsString>,
76    hostname: Option<String>,
77    clock: Arc<dyn Clock>,
78}
79
80impl Env {
81    /// Starts an environment for `os` whose user profile (`~`) is `home`.
82    /// On Windows `home` is `FOLDERID_Profile`, never `$HOME`.
83    pub fn builder(os: Os, home: impl Into<PathBuf>) -> EnvBuilder {
84        EnvBuilder {
85            env: Env {
86                os,
87                home: home.into(),
88                local_app_data: None,
89                roaming_app_data: None,
90                vars: BTreeMap::new(),
91                hostname: None,
92                clock: Arc::new(SystemClock),
93            },
94        }
95    }
96
97    pub fn os(&self) -> Os {
98        self.os
99    }
100
101    /// The user profile directory (`~`).
102    pub fn home(&self) -> &Path {
103        &self.home
104    }
105
106    /// A Windows Known Folder, if known.
107    pub fn known_folder(&self, folder: KnownFolder) -> Option<&Path> {
108        match folder {
109            KnownFolder::LocalAppData => self.local_app_data.as_deref(),
110            KnownFolder::RoamingAppData => self.roaming_app_data.as_deref(),
111        }
112    }
113
114    /// An environment variable. Names are case-insensitive on Windows. Empty
115    /// values read as unset, matching how Windows and the XDG spec treat them.
116    pub fn var(&self, name: &str) -> Option<&OsStr> {
117        self.vars
118            .get(&var_key(self.os, name))
119            .map(OsString::as_os_str)
120            .filter(|value| !value.is_empty())
121    }
122
123    /// Every variable (names upper-cased on Windows), for the environment
124    /// of a child process the core starts (the 1Password CLI).
125    pub fn vars(&self) -> impl Iterator<Item = (&str, &OsStr)> {
126        self.vars
127            .iter()
128            .map(|(name, value)| (name.as_str(), value.as_os_str()))
129    }
130
131    /// A copy with `name` set to `value`, for the environment of one child
132    /// process (the 1Password CLI with a service account token).
133    pub fn with_var(&self, name: &str, value: impl Into<OsString>) -> Env {
134        let mut env = self.clone();
135        env.vars.insert(var_key(env.os, name), value.into());
136        env
137    }
138
139    /// The current time from the injected clock.
140    pub fn now(&self) -> SystemTime {
141        self.clock.now()
142    }
143
144    /// The computer's host name, if known. The default machine label.
145    pub fn hostname(&self) -> Option<&str> {
146        self.hostname
147            .as_deref()
148            .filter(|name| !name.trim().is_empty())
149    }
150}
151
152impl Env {
153    /// Builds the environment of the running process (the CLI and the app;
154    /// never tests). On Windows the profile and app data folders come from
155    /// `USERPROFILE`, `LOCALAPPDATA` and `APPDATA` when set (hermetic tests
156    /// of the binaries set them), else from the Known Folders; `HOME` is
157    /// never used there.
158    pub fn from_process() -> Result<Env, CoreError> {
159        let os = if cfg!(windows) {
160            Os::Windows
161        } else if cfg!(target_os = "macos") {
162            Os::MacOs
163        } else {
164            Os::Linux
165        };
166        let var_path = |name: &str| {
167            std::env::var_os(name)
168                .map(PathBuf::from)
169                .filter(|path| path.is_absolute())
170        };
171        let (home, local_app_data, roaming_app_data) = match os {
172            Os::Windows => (
173                var_path("USERPROFILE").or_else(dirs::home_dir),
174                var_path("LOCALAPPDATA").or_else(dirs::data_local_dir),
175                var_path("APPDATA").or_else(dirs::data_dir),
176            ),
177            Os::Linux | Os::MacOs => (var_path("HOME").or_else(dirs::home_dir), None, None),
178        };
179        let home = home.ok_or_else(|| {
180            CoreError::new(
181                ErrorCode::ProfileNotFound,
182                "cannot determine the user profile directory",
183            )
184        })?;
185
186        let mut builder = Env::builder(os, home).clock(SystemClock);
187        if let Some(path) = local_app_data {
188            builder = builder.known_folder(KnownFolder::LocalAppData, path);
189        }
190        if let Some(path) = roaming_app_data {
191            builder = builder.known_folder(KnownFolder::RoamingAppData, path);
192        }
193        for (name, value) in std::env::vars_os() {
194            if let Some(name) = name.to_str() {
195                builder = builder.var(name, value);
196            }
197        }
198        if let Some(name) = process_hostname(os) {
199            builder = builder.hostname(name);
200        }
201        Ok(builder.build())
202    }
203}
204
205/// `COMPUTERNAME` on Windows; elsewhere `HOSTNAME`, then `/etc/hostname`.
206fn process_hostname(os: Os) -> Option<String> {
207    let var = |name: &str| std::env::var(name).ok();
208    let name = match os {
209        Os::Windows => var("COMPUTERNAME"),
210        Os::Linux | Os::MacOs => {
211            var("HOSTNAME").or_else(|| std::fs::read_to_string("/etc/hostname").ok())
212        }
213    }?;
214    let name = name.trim();
215    (!name.is_empty()).then(|| name.to_owned())
216}
217
218/// Builder for [`Env`]. The clock defaults to [`SystemClock`].
219#[derive(Debug, Clone)]
220pub struct EnvBuilder {
221    env: Env,
222}
223
224impl EnvBuilder {
225    pub fn known_folder(mut self, folder: KnownFolder, path: impl Into<PathBuf>) -> Self {
226        let path = Some(path.into());
227        match folder {
228            KnownFolder::LocalAppData => self.env.local_app_data = path,
229            KnownFolder::RoamingAppData => self.env.roaming_app_data = path,
230        }
231        self
232    }
233
234    pub fn var(mut self, name: &str, value: impl Into<OsString>) -> Self {
235        self.env
236            .vars
237            .insert(var_key(self.env.os, name), value.into());
238        self
239    }
240
241    pub fn hostname(mut self, name: impl Into<String>) -> Self {
242        self.env.hostname = Some(name.into());
243        self
244    }
245
246    pub fn clock(mut self, clock: impl Clock + 'static) -> Self {
247        self.env.clock = Arc::new(clock);
248        self
249    }
250
251    pub fn build(self) -> Env {
252        self.env
253    }
254}
255
256fn var_key(os: Os, name: &str) -> String {
257    match os {
258        Os::Windows => name.to_ascii_uppercase(),
259        Os::Linux | Os::MacOs => name.to_owned(),
260    }
261}