Skip to main content

pb_mapper_auth/
config.rs

1//! Authentication configuration and platform state-directory defaults.
2use super::*;
3
4pub fn default_auth_state_dir() -> PathBuf {
5    std::env::var_os("PB_MAPPER_AUTH_STATE_DIR")
6        .map(PathBuf::from)
7        .unwrap_or_else(platform_default_auth_state_dir)
8}
9
10/// Linux systemd/Docker keep `/var/lib/pb-mapper/auth` when that path is usable
11/// (root, or an already-writable service directory). Unprivileged Linux,
12/// macOS, and Windows binaries need an application data directory instead.
13pub(crate) fn platform_default_auth_state_dir() -> PathBuf {
14    #[cfg(windows)]
15    {
16        let base = std::env::var_os("LOCALAPPDATA")
17            .or_else(|| std::env::var_os("APPDATA"))
18            .map(PathBuf::from)
19            .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"));
20        base.join("pb-mapper").join("auth")
21    }
22    #[cfg(target_os = "macos")]
23    {
24        match std::env::var_os("HOME") {
25            Some(home) => PathBuf::from(home)
26                .join("Library")
27                .join("Application Support")
28                .join("pb-mapper")
29                .join("auth"),
30            None => PathBuf::from("/Library/Application Support/pb-mapper/auth"),
31        }
32    }
33    #[cfg(not(any(windows, target_os = "macos")))]
34    {
35        linux_default_auth_state_dir(
36            unix_effective_uid(),
37            linux_system_auth_dir_usable(),
38            std::env::var_os("XDG_DATA_HOME").as_deref(),
39            std::env::var_os("HOME").as_deref(),
40        )
41    }
42}
43
44#[cfg(not(any(windows, target_os = "macos")))]
45pub(crate) fn linux_default_auth_state_dir(
46    euid: u32,
47    system_dir_usable: bool,
48    xdg_data_home: Option<&std::ffi::OsStr>,
49    home: Option<&std::ffi::OsStr>,
50) -> PathBuf {
51    if euid == 0 || system_dir_usable {
52        return PathBuf::from(DEFAULT_AUTH_STATE_DIR);
53    }
54    if let Some(xdg) = xdg_data_home
55        && !xdg.is_empty()
56    {
57        return PathBuf::from(xdg).join("pb-mapper").join("auth");
58    }
59    if let Some(home) = home
60        && !home.is_empty()
61    {
62        return PathBuf::from(home)
63            .join(".local")
64            .join("share")
65            .join("pb-mapper")
66            .join("auth");
67    }
68    PathBuf::from(DEFAULT_AUTH_STATE_DIR)
69}
70
71#[cfg(not(any(windows, target_os = "macos")))]
72pub(super) fn unix_effective_uid() -> u32 {
73    unsafe extern "C" {
74        fn geteuid() -> u32;
75    }
76    unsafe { geteuid() }
77}
78
79#[cfg(not(any(windows, target_os = "macos")))]
80pub(super) fn linux_system_auth_dir_usable() -> bool {
81    let path = Path::new(DEFAULT_AUTH_STATE_DIR);
82    path.is_dir() && unix_path_is_writable(path)
83}
84
85#[cfg(not(any(windows, target_os = "macos")))]
86fn unix_path_is_writable(path: &Path) -> bool {
87    use std::os::unix::ffi::OsStrExt;
88    let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
89        return false;
90    };
91    unsafe extern "C" {
92        fn access(pathname: *const std::os::raw::c_char, mode: i32) -> i32;
93    }
94    const W_OK: i32 = 2;
95    unsafe { access(c_path.as_ptr(), W_OK) == 0 }
96}
97
98/// Values that take the place of the environment variables
99/// [`AuthConfig::from_env_with`] reads: each `Some` replaces one, which is then
100/// not read at all, and each `None` leaves it in charge.
101#[derive(Clone, Debug, Default)]
102pub struct AuthConfigOverrides {
103    /// Replaces `PB_MAPPER_AUTH_STATE_DIR` and the platform default behind it.
104    pub state_dir: Option<PathBuf>,
105    /// Replaces `PB_MAPPER_AUTH_MAX_TEMP_KEYS`.
106    pub max_temporary_keys: Option<usize>,
107    /// Replaces `PB_MAPPER_AUTH_MAX_TEMP_TTL_SECS`.
108    pub max_temporary_key_ttl: Option<Duration>,
109    /// Replaces `PB_MAPPER_LEGACY_PROTOCOL`.
110    pub legacy_protocol: Option<LegacyProtocolPolicy>,
111}
112
113impl AuthConfig {
114    /// The configuration the environment sets, except where `overrides` says
115    /// otherwise. An overridden variable is not read, so it neither applies nor
116    /// logs a complaint about its value. Overrides are taken as given, as the
117    /// fields of an `AuthConfig` literal are; a start refuses a limit outside
118    /// the range the environment accepts.
119    pub fn from_env_with(overrides: AuthConfigOverrides) -> Self {
120        let AuthConfigOverrides {
121            state_dir,
122            max_temporary_keys,
123            max_temporary_key_ttl,
124            legacy_protocol,
125        } = overrides;
126        Self {
127            state_dir: state_dir.unwrap_or_else(default_auth_state_dir),
128            max_temporary_keys: max_temporary_keys.unwrap_or_else(|| {
129                env_usize(
130                    "PB_MAPPER_AUTH_MAX_TEMP_KEYS",
131                    DEFAULT_TEMP_KEY_CAPACITY,
132                    1,
133                    MAX_TEMP_KEY_CAPACITY,
134                )
135            }),
136            max_temporary_key_ttl: max_temporary_key_ttl.unwrap_or_else(|| {
137                Duration::from_secs(env_u64(
138                    "PB_MAPPER_AUTH_MAX_TEMP_TTL_SECS",
139                    DEFAULT_MAX_TEMP_KEY_TTL.as_secs(),
140                    MIN_TEMP_KEY_TTL.as_secs(),
141                    MAX_TEMP_KEY_TTL.as_secs(),
142                ))
143            }),
144            legacy_protocol: legacy_protocol.unwrap_or_else(legacy_protocol_from_env),
145        }
146    }
147
148    /// Refuses limits outside the range the CLI and the environment accept,
149    /// which a literal or an override can still hold. Past it, a capacity
150    /// near `usize::MAX` aborts on allocation, and a key could live longer
151    /// than the timing wheel can hold, so it would be retired as it is issued.
152    pub(crate) fn check_limits(&self) -> Result<(), AuthFailure> {
153        let invalid = |message| AuthFailure::new(codes::AUTH_CONFIG_INVALID, message, false);
154        if !(1..=MAX_TEMP_KEY_CAPACITY).contains(&self.max_temporary_keys) {
155            return Err(invalid(format!(
156                "the temporary key capacity must be between 1 and {MAX_TEMP_KEY_CAPACITY}, not {}",
157                self.max_temporary_keys
158            )));
159        }
160        if !(MIN_TEMP_KEY_TTL..=MAX_TEMP_KEY_TTL).contains(&self.max_temporary_key_ttl) {
161            return Err(invalid(format!(
162                "the maximum temporary key TTL must be between {} and {} seconds, not {:?}",
163                MIN_TEMP_KEY_TTL.as_secs(),
164                MAX_TEMP_KEY_TTL.as_secs(),
165                self.max_temporary_key_ttl
166            )));
167        }
168        Ok(())
169    }
170}
171
172impl Default for AuthConfig {
173    /// The configuration the environment sets: [`AuthConfig::from_env_with`]
174    /// with no overrides.
175    fn default() -> Self {
176        Self::from_env_with(AuthConfigOverrides::default())
177    }
178}
179
180fn legacy_protocol_from_env() -> LegacyProtocolPolicy {
181    match std::env::var("PB_MAPPER_LEGACY_PROTOCOL") {
182        Err(std::env::VarError::NotPresent) => LegacyProtocolPolicy::Allow,
183        Err(std::env::VarError::NotUnicode(_)) => {
184            tracing::error!(
185                event = "legacy_protocol_config_invalid",
186                "PB_MAPPER_LEGACY_PROTOCOL is not UTF-8; denying legacy framing"
187            );
188            LegacyProtocolPolicy::Deny
189        }
190        Ok(value) => parse_legacy_protocol_policy(&value).unwrap_or_else(|| {
191            tracing::error!(
192                event = "legacy_protocol_config_invalid",
193                value,
194                "PB_MAPPER_LEGACY_PROTOCOL must be `allow` or `deny`; denying legacy framing"
195            );
196            LegacyProtocolPolicy::Deny
197        }),
198    }
199}
200
201pub(super) fn parse_legacy_protocol_policy(value: &str) -> Option<LegacyProtocolPolicy> {
202    match value.trim().to_ascii_lowercase().as_str() {
203        "allow" => Some(LegacyProtocolPolicy::Allow),
204        "deny" => Some(LegacyProtocolPolicy::Deny),
205        _ => None,
206    }
207}
208
209fn env_usize(name: &str, default: usize, min: usize, max: usize) -> usize {
210    env_bounded(name, default, min, max)
211}
212
213fn env_u64(name: &str, default: u64, min: u64, max: u64) -> u64 {
214    env_bounded(name, default, min, max)
215}
216
217fn env_bounded<T>(name: &str, default: T, min: T, max: T) -> T
218where
219    T: std::str::FromStr + PartialOrd + Copy + fmt::Display,
220{
221    match std::env::var(name) {
222        Err(std::env::VarError::NotPresent) => default,
223        Ok(raw) => match raw.parse::<T>() {
224            Ok(value) if value >= min && value <= max => value,
225            _ => {
226                tracing::warn!(
227                    event = "auth_config_value_invalid",
228                    variable = name,
229                    value = raw,
230                    min = %min,
231                    max = %max,
232                    fallback = %default,
233                    "invalid authentication configuration value; using the default"
234                );
235                default
236            }
237        },
238        Err(std::env::VarError::NotUnicode(_)) => {
239            tracing::warn!(
240                event = "auth_config_value_invalid",
241                variable = name,
242                min = %min,
243                max = %max,
244                fallback = %default,
245                "authentication configuration value is not UTF-8; using the default"
246            );
247            default
248        }
249    }
250}