aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / spark-crumbs / src / local.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! `.crumb.local`: advisory, per-directory agent notes (history and |
| 17 | //! whispers), shared by `spark-crumbs` and `aien-cli` (core#924). |
| 18 | //! |
| 19 | //! The file holds notes, never a claim or lock on the directory: exclusive |
| 20 | //! claims belong to the `crumb` tool (aien-architecture `tools/crumb`). What |
| 21 | //! this module guarantees is that the notes are honest: |
| 22 | //! |
| 23 | //! - every worker has its own identity ([`resolve_identity`]); the shared |
| 24 | //! constants `AIEN` / `active-session` that made peers hide each other are |
| 25 | //! refused; |
| 26 | //! - a missing file means no notes yet, while an unreadable or malformed one |
| 27 | //! is an error ([`LocalCrumbError`]), never "no peers"; |
| 28 | //! - a change is one read-modify-write held under an exclusive `flock` on the |
| 29 | //! directory, ending in an atomic, durable replace (temp file in the same |
| 30 | //! directory, fsync, rename, fsync of the directory), so concurrent writers |
| 31 | //! in threads or processes lose no update and a reader never sees a torn |
| 32 | //! file. |
| 33 | |
| 34 | use chrono::{DateTime, Utc}; |
| 35 | use serde::{Deserialize, Serialize}; |
| 36 | use std::fs::{self, File, OpenOptions}; |
| 37 | use std::io::{self, Read, Write}; |
| 38 | use std::path::{Path, PathBuf}; |
| 39 | use std::sync::OnceLock; |
| 40 | |
| 41 | pub const LOCAL_CRUMB_FILENAME: &str = ".crumb.local"; |
| 42 | /// Prefix of the temp file a replace writes next to `.crumb.local`. |
| 43 | pub const LOCAL_CRUMB_TEMP_PREFIX: &str = ".crumb.local.tmp-"; |
| 44 | pub const DEFAULT_TTL_SECS: u64 = 1800; // 30 minutes |
| 45 | /// Entries kept per directory; older ones are dropped first. |
| 46 | pub const HISTORY_CAP: usize = 50; |
| 47 | pub const WHISPER_CAP: usize = 30; |
| 48 | |
| 49 | #[derive(Serialize, Deserialize, Debug, Clone, Default)] |
| 50 | pub struct LocalCrumbData { |
| 51 | #[serde(default)] |
| 52 | pub history: Vec<CrumbHistoryItem>, |
| 53 | #[serde(default)] |
| 54 | pub whispers: Vec<CrumbWhisper>, |
| 55 | } |
| 56 | |
| 57 | #[derive(Serialize, Deserialize, Debug, Clone)] |
| 58 | pub struct CrumbHistoryItem { |
| 59 | pub crumb_id: String, |
| 60 | pub timestamp: String, |
| 61 | pub agent_id: String, |
| 62 | pub session_id: String, |
| 63 | pub action: String, // "signin", "view", "edit", "create", "test" |
| 64 | pub target: String, |
| 65 | pub intent: String, |
| 66 | pub vector: String, |
| 67 | } |
| 68 | |
| 69 | impl CrumbHistoryItem { |
| 70 | pub fn elapsed_secs(&self) -> u64 { |
| 71 | if let Ok(parsed) = DateTime::parse_from_rfc3339(&self.timestamp) { |
| 72 | let age = Utc::now().signed_duration_since(parsed.with_timezone(&Utc)); |
| 73 | age.num_seconds().max(0) as u64 |
| 74 | } else { |
| 75 | 0 |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | pub fn is_active(&self) -> bool { |
| 80 | self.elapsed_secs() < DEFAULT_TTL_SECS |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | #[derive(Serialize, Deserialize, Debug, Clone)] |
| 85 | pub struct CrumbWhisper { |
| 86 | #[serde(default)] |
| 87 | pub whisper_id: String, |
| 88 | pub from_agent: String, |
| 89 | pub timestamp: String, |
| 90 | #[serde(default)] |
| 91 | pub target_file: Option<String>, |
| 92 | pub message: String, |
| 93 | } |
| 94 | |
| 95 | /// A record id that is unique even for writers in the same nanosecond. |
| 96 | pub fn unique_record_id(prefix: &str) -> String { |
| 97 | format!( |
| 98 | "{}-{}-{}", |
| 99 | prefix, |
| 100 | Utc::now().timestamp_nanos_opt().unwrap_or(0), |
| 101 | &uuid::Uuid::new_v4().simple().to_string()[..12] |
| 102 | ) |
| 103 | } |
| 104 | |
| 105 | // --------------------------------------------------------------------------- |
| 106 | // Identity |
| 107 | // --------------------------------------------------------------------------- |
| 108 | |
| 109 | /// Identities that every worker used to share. They are refused even when an |
| 110 | /// environment variable names them, since two workers carrying one of them |
| 111 | /// hide each other's notices in sniff. |
| 112 | pub const SHARED_CONSTANT_IDENTITIES: [&str; 3] = ["AIEN", "active-session", "cli-session"]; |
| 113 | |
| 114 | /// Where an [`AgentIdentity`] came from. |
| 115 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 116 | pub enum IdentitySource { |
| 117 | /// `AIEN_AGENT_ID`, used verbatim. |
| 118 | AgentId, |
| 119 | /// `<AIEN_AGENT_NAME or default>.<AIEN_SESSION_ID or HERMES_SESSION_ID>`. |
| 120 | NameAndSession, |
| 121 | /// No identity in the environment: `<name>@<host>.<pid>.<random>`, |
| 122 | /// generated once per process. |
| 123 | Generated, |
| 124 | } |
| 125 | |
| 126 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 127 | pub struct AgentIdentity { |
| 128 | pub agent_id: String, |
| 129 | pub session_id: String, |
| 130 | pub source: IdentitySource, |
| 131 | } |
| 132 | |
| 133 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 134 | pub struct IdentityError(pub String); |
| 135 | |
| 136 | impl std::fmt::Display for IdentityError { |
| 137 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 138 | write!(f, "agent identity: {}", self.0) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | impl std::error::Error for IdentityError {} |
| 143 | |
| 144 | /// The crumb tool's agent pattern (crumb924 CONTRACT section 1): |
| 145 | /// `^[A-Za-z0-9][A-Za-z0-9._@-]{0,159}$`. Rejected, never rewritten. |
| 146 | pub fn is_valid_agent_id(id: &str) -> bool { |
| 147 | let b = id.as_bytes(); |
| 148 | !b.is_empty() |
| 149 | && b.len() <= 160 |
| 150 | && b[0].is_ascii_alphanumeric() |
| 151 | && b[1..] |
| 152 | .iter() |
| 153 | .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'@' | b'-')) |
| 154 | } |
| 155 | |
| 156 | /// One identity variable, as given. Unset and set-to-empty both mean "not |
| 157 | /// configured" (`Ok(None)`; the next source is used): an empty value can name |
| 158 | /// no worker. Any other value is used verbatim and must itself match the agent |
| 159 | /// pattern, so surrounding whitespace, a whitespace-only value or a non-UTF-8 |
| 160 | /// value (seen here with U+FFFD replacements) is an error. Nothing is trimmed: |
| 161 | /// a trimmed ` worker-1 ` would alias the real `worker-1`. |
| 162 | fn identity_var( |
| 163 | env: &dyn Fn(&str) -> Option<String>, |
| 164 | key: &str, |
| 165 | ) -> Result<Option<String>, IdentityError> { |
| 166 | match env(key) { |
| 167 | None => Ok(None), |
| 168 | Some(v) if v.is_empty() => Ok(None), |
| 169 | Some(v) if is_valid_agent_id(&v) => Ok(Some(v)), |
| 170 | Some(v) => Err(IdentityError(format!( |
| 171 | "{key}={v:?} does not match ^[A-Za-z0-9][A-Za-z0-9._@-]{{0,159}}$; \ |
| 172 | values are used verbatim (surrounding whitespace is rejected, not trimmed)" |
| 173 | ))), |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn host_component() -> String { |
| 178 | let raw = fs::read_to_string("/proc/sys/kernel/hostname") |
| 179 | .ok() |
| 180 | .or_else(|| std::env::var("HOSTNAME").ok()) |
| 181 | .unwrap_or_default(); |
| 182 | let cleaned: String = raw |
| 183 | .trim() |
| 184 | .chars() |
| 185 | .map(|c| { |
| 186 | if c.is_ascii_alphanumeric() || c == '-' || c == '.' { |
| 187 | c |
| 188 | } else { |
| 189 | '-' |
| 190 | } |
| 191 | }) |
| 192 | .collect(); |
| 193 | let cleaned = cleaned.trim_matches(|c| c == '-' || c == '.').to_string(); |
| 194 | if cleaned.is_empty() { |
| 195 | "host".to_string() |
| 196 | } else { |
| 197 | cleaned.chars().take(63).collect() |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /// A per-process unique suffix `<host>.<pid>.<random>`. |
| 202 | fn generated_suffix() -> String { |
| 203 | format!( |
| 204 | "{}.{}.{}", |
| 205 | host_component(), |
| 206 | std::process::id(), |
| 207 | &uuid::Uuid::new_v4().simple().to_string()[..12] |
| 208 | ) |
| 209 | } |
| 210 | |
| 211 | /// Resolves the agent identity from `env` (a lookup such as `std::env::var`): |
| 212 | /// |
| 213 | /// 1. `AIEN_AGENT_ID`, verbatim; |
| 214 | /// 2. else `<AIEN_AGENT_NAME or default_name>.<AIEN_SESSION_ID or HERMES_SESSION_ID>`; |
| 215 | /// 3. else a generated `<AIEN_AGENT_NAME or default_name>@<host>.<pid>.<random>`. |
| 216 | /// |
| 217 | /// The session id is the session variable when set, else the generated |
| 218 | /// suffix. A variable that is unset or empty is not configured and the next |
| 219 | /// source is used; every consulted variable that is set to a non-empty value |
| 220 | /// is taken byte for byte and must match the crumb agent pattern on its own |
| 221 | /// (see `identity_var`), so a padded or otherwise malformed value is an |
| 222 | /// error, never rewritten. An identity that does not match the pattern, or |
| 223 | /// that is one of [`SHARED_CONSTANT_IDENTITIES`], is an error. |
| 224 | pub fn resolve_identity_with( |
| 225 | env: &dyn Fn(&str) -> Option<String>, |
| 226 | default_name: &str, |
| 227 | ) -> Result<AgentIdentity, IdentityError> { |
| 228 | let agent_id_env = identity_var(env, "AIEN_AGENT_ID")?; |
| 229 | let session_env = match identity_var(env, "AIEN_SESSION_ID")? { |
| 230 | Some(s) => Some(s), |
| 231 | None => identity_var(env, "HERMES_SESSION_ID")?, |
| 232 | }; |
| 233 | // The name is consulted only when it becomes part of the identity. |
| 234 | let name = if agent_id_env.is_some() { |
| 235 | default_name.to_string() |
| 236 | } else { |
| 237 | identity_var(env, "AIEN_AGENT_NAME")?.unwrap_or_else(|| default_name.to_string()) |
| 238 | }; |
| 239 | |
| 240 | let identity = if let Some(agent_id) = agent_id_env { |
| 241 | AgentIdentity { |
| 242 | agent_id, |
| 243 | session_id: session_env.unwrap_or_else(generated_suffix), |
| 244 | source: IdentitySource::AgentId, |
| 245 | } |
| 246 | } else if let Some(session) = session_env { |
| 247 | AgentIdentity { |
| 248 | agent_id: format!("{name}.{session}"), |
| 249 | session_id: session, |
| 250 | source: IdentitySource::NameAndSession, |
| 251 | } |
| 252 | } else { |
| 253 | let suffix = generated_suffix(); |
| 254 | AgentIdentity { |
| 255 | agent_id: format!("{name}@{suffix}"), |
| 256 | session_id: suffix, |
| 257 | source: IdentitySource::Generated, |
| 258 | } |
| 259 | }; |
| 260 | |
| 261 | for constant in SHARED_CONSTANT_IDENTITIES { |
| 262 | if identity.agent_id == constant || identity.session_id == constant { |
| 263 | return Err(IdentityError(format!( |
| 264 | "'{constant}' is a shared constant identity; set AIEN_AGENT_ID or \ |
| 265 | AIEN_AGENT_NAME + AIEN_SESSION_ID to a per-worker value" |
| 266 | ))); |
| 267 | } |
| 268 | } |
| 269 | if !is_valid_agent_id(&identity.agent_id) { |
| 270 | return Err(IdentityError(format!( |
| 271 | "'{}' does not match ^[A-Za-z0-9][A-Za-z0-9._@-]{{0,159}}$ (from {:?}); \ |
| 272 | set AIEN_AGENT_ID to a valid per-worker id", |
| 273 | identity.agent_id, identity.source |
| 274 | ))); |
| 275 | } |
| 276 | Ok(identity) |
| 277 | } |
| 278 | |
| 279 | /// [`resolve_identity_with`] over the process environment. A non-UTF-8 value |
| 280 | /// is passed on lossily (with U+FFFD), so it is rejected rather than treated |
| 281 | /// as unset. |
| 282 | pub fn resolve_identity(default_name: &str) -> Result<AgentIdentity, IdentityError> { |
| 283 | resolve_identity_with( |
| 284 | &|k| std::env::var_os(k).map(|v| v.to_string_lossy().into_owned()), |
| 285 | default_name, |
| 286 | ) |
| 287 | } |
| 288 | |
| 289 | /// The identity of this process, resolved once (the first caller's |
| 290 | /// `default_name` wins), so every record a process writes carries one id. |
| 291 | pub fn process_identity(default_name: &str) -> Result<AgentIdentity, IdentityError> { |
| 292 | static IDENTITY: OnceLock<Result<AgentIdentity, IdentityError>> = OnceLock::new(); |
| 293 | IDENTITY |
| 294 | .get_or_init(|| resolve_identity(default_name)) |
| 295 | .clone() |
| 296 | } |
| 297 | |
| 298 | // --------------------------------------------------------------------------- |
| 299 | // Errors |
| 300 | // --------------------------------------------------------------------------- |
| 301 | |
| 302 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 303 | pub enum LocalCrumbErrorKind { |
| 304 | Unreadable, |
| 305 | Malformed, |
| 306 | Lock, |
| 307 | Io, |
| 308 | } |
| 309 | |
| 310 | /// A `.crumb.local` failure. A missing file is not one (it means no notes |
| 311 | /// yet). |
| 312 | #[derive(Debug)] |
| 313 | pub enum LocalCrumbError { |
| 314 | /// The file exists but cannot be read (permissions, a symlink, an I/O |
| 315 | /// error). |
| 316 | Unreadable { path: PathBuf, source: io::Error }, |
| 317 | /// The file was read but is not `.crumb.local` JSON. |
| 318 | Malformed { |
| 319 | path: PathBuf, |
| 320 | source: serde_json::Error, |
| 321 | }, |
| 322 | /// The directory could not be opened or locked. |
| 323 | Lock { path: PathBuf, source: io::Error }, |
| 324 | /// Writing the replacement failed at `op`. For every `op` up to and |
| 325 | /// including `rename`, the old file is untouched and the temp file is |
| 326 | /// removed. For `fsync directory` the rename has already happened: the |
| 327 | /// replacement is visible to readers but its durability is unconfirmed (it |
| 328 | /// may be lost on a crash), and callers must not assume a rollback. |
| 329 | Io { |
| 330 | path: PathBuf, |
| 331 | op: &'static str, |
| 332 | source: io::Error, |
| 333 | }, |
| 334 | } |
| 335 | |
| 336 | impl LocalCrumbError { |
| 337 | pub fn kind(&self) -> LocalCrumbErrorKind { |
| 338 | match self { |
| 339 | LocalCrumbError::Unreadable { .. } => LocalCrumbErrorKind::Unreadable, |
| 340 | LocalCrumbError::Malformed { .. } => LocalCrumbErrorKind::Malformed, |
| 341 | LocalCrumbError::Lock { .. } => LocalCrumbErrorKind::Lock, |
| 342 | LocalCrumbError::Io { .. } => LocalCrumbErrorKind::Io, |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | impl std::fmt::Display for LocalCrumbError { |
| 348 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 349 | match self { |
| 350 | LocalCrumbError::Unreadable { path, source } => { |
| 351 | write!(f, "{} is unreadable: {}", path.display(), source) |
| 352 | } |
| 353 | LocalCrumbError::Malformed { path, source } => { |
| 354 | write!(f, "{} is malformed: {}", path.display(), source) |
| 355 | } |
| 356 | LocalCrumbError::Lock { path, source } => { |
| 357 | write!(f, "cannot lock {}: {}", path.display(), source) |
| 358 | } |
| 359 | LocalCrumbError::Io { path, op, source } => { |
| 360 | write!(f, "{} failed for {}: {}", op, path.display(), source)?; |
| 361 | if *op == OP_FSYNC_DIR { |
| 362 | write!(f, " (replacement visible, durability unconfirmed)")?; |
| 363 | } |
| 364 | Ok(()) |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | impl std::error::Error for LocalCrumbError { |
| 371 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 372 | match self { |
| 373 | LocalCrumbError::Unreadable { source, .. } |
| 374 | | LocalCrumbError::Lock { source, .. } |
| 375 | | LocalCrumbError::Io { source, .. } => Some(source), |
| 376 | LocalCrumbError::Malformed { source, .. } => Some(source), |
| 377 | } |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | // --------------------------------------------------------------------------- |
| 382 | // Load, lock, replace |
| 383 | // --------------------------------------------------------------------------- |
| 384 | |
| 385 | fn nofollow(opts: &mut OpenOptions) -> &mut OpenOptions { |
| 386 | #[cfg(unix)] |
| 387 | { |
| 388 | use std::os::unix::fs::OpenOptionsExt; |
| 389 | opts.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC); |
| 390 | } |
| 391 | opts |
| 392 | } |
| 393 | |
| 394 | /// Reads `dir/.crumb.local`. `Ok(empty)` when it does not exist. The final |
| 395 | /// component is never followed as a symlink (DRA-47), so a planted link is |
| 396 | /// `Unreadable`. Readers take no lock: writers replace the file atomically. |
| 397 | pub fn load_local_crumb(dir: &Path) -> Result<LocalCrumbData, LocalCrumbError> { |
| 398 | let path = dir.join(LOCAL_CRUMB_FILENAME); |
| 399 | let mut bytes = Vec::new(); |
| 400 | match nofollow(OpenOptions::new().read(true)).open(&path) { |
| 401 | Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(LocalCrumbData::default()), |
| 402 | Err(e) => return Err(LocalCrumbError::Unreadable { path, source: e }), |
| 403 | Ok(mut f) => { |
| 404 | if let Err(e) = f.read_to_end(&mut bytes) { |
| 405 | return Err(LocalCrumbError::Unreadable { path, source: e }); |
| 406 | } |
| 407 | } |
| 408 | } |
| 409 | serde_json::from_slice(&bytes).map_err(|e| LocalCrumbError::Malformed { path, source: e }) |
| 410 | } |
| 411 | |
| 412 | /// An exclusive `flock` on the directory itself, held until drop. Locking the |
| 413 | /// directory (rather than a sibling lock file) leaves no extra file in a |
| 414 | /// repository, and its descriptor is the one the replace fsyncs. |
| 415 | struct DirLock { |
| 416 | dir: File, |
| 417 | } |
| 418 | |
| 419 | fn lock_dir(dir: &Path) -> Result<DirLock, LocalCrumbError> { |
| 420 | let mut opts = OpenOptions::new(); |
| 421 | opts.read(true); |
| 422 | #[cfg(unix)] |
| 423 | { |
| 424 | use std::os::unix::fs::OpenOptionsExt; |
| 425 | opts.custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC); |
| 426 | } |
| 427 | let file = opts.open(dir).map_err(|e| LocalCrumbError::Lock { |
| 428 | path: dir.to_path_buf(), |
| 429 | source: e, |
| 430 | })?; |
| 431 | #[cfg(unix)] |
| 432 | { |
| 433 | use std::os::unix::io::AsRawFd; |
| 434 | loop { |
| 435 | // SAFETY: flock on a descriptor this function owns. |
| 436 | let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) }; |
| 437 | if rc == 0 { |
| 438 | break; |
| 439 | } |
| 440 | let e = io::Error::last_os_error(); |
| 441 | if e.kind() != io::ErrorKind::Interrupted { |
| 442 | return Err(LocalCrumbError::Lock { |
| 443 | path: dir.to_path_buf(), |
| 444 | source: e, |
| 445 | }); |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | Ok(DirLock { dir: file }) |
| 450 | } |
| 451 | |
| 452 | /// Removes temp files a crashed writer left behind. Only called while holding |
| 453 | /// the directory lock: every writer creates its temp file under that lock, so |
| 454 | /// any temp file present now belongs to no live writer. |
| 455 | fn sweep_orphan_temps(dir: &Path) { |
| 456 | if let Ok(entries) = fs::read_dir(dir) { |
| 457 | for e in entries.flatten() { |
| 458 | if e.file_name() |
| 459 | .to_string_lossy() |
| 460 | .starts_with(LOCAL_CRUMB_TEMP_PREFIX) |
| 461 | && e.file_type().map(|t| t.is_file()).unwrap_or(false) |
| 462 | { |
| 463 | let _ = fs::remove_file(e.path()); |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | /// The `op` of an [`LocalCrumbError::Io`] raised after the rename. |
| 470 | const OP_FSYNC_DIR: &str = "fsync directory"; |
| 471 | |
| 472 | /// The mode a new `.crumb.local` gets: 0644 masked by the process umask, as a |
| 473 | /// plain `open(O_CREAT, 0644)` would give. The umask is read from |
| 474 | /// `/proc/self/status` (it cannot be read without changing it, which would |
| 475 | /// race other threads); where that is unavailable the restrictive 0600 is |
| 476 | /// used. |
| 477 | #[cfg(unix)] |
| 478 | fn new_file_mode() -> u32 { |
| 479 | let umask = fs::read_to_string("/proc/self/status").ok().and_then(|s| { |
| 480 | s.lines() |
| 481 | .find_map(|l| l.strip_prefix("Umask:")) |
| 482 | .and_then(|v| u32::from_str_radix(v.trim(), 8).ok()) |
| 483 | }); |
| 484 | match umask { |
| 485 | Some(m) => 0o644 & !m, |
| 486 | None => 0o600, |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | /// POSIX access ACL (`system.posix_acl_access`) of the replaced file, copied |
| 491 | /// onto the temp file so a replace keeps named-user/named-group entries and |
| 492 | /// the mask instead of reducing the policy to mode bits (core#924 review). |
| 493 | /// The bytes are the kernel's own xattr encoding and are copied verbatim. |
| 494 | #[cfg(target_os = "linux")] |
| 495 | mod access_acl { |
| 496 | use std::ffi::CString; |
| 497 | use std::fs::File; |
| 498 | use std::io; |
| 499 | use std::os::unix::ffi::OsStrExt; |
| 500 | use std::os::unix::io::AsRawFd; |
| 501 | use std::path::Path; |
| 502 | |
| 503 | const NAME: &[u8] = b"system.posix_acl_access\0"; |
| 504 | |
| 505 | fn name() -> *const libc::c_char { |
| 506 | NAME.as_ptr().cast() |
| 507 | } |
| 508 | |
| 509 | /// "No ACL here": the entry has none (`ENODATA`) or the filesystem does |
| 510 | /// not support ACLs, so it cannot have one. |
| 511 | fn absent(e: &io::Error) -> bool { |
| 512 | let code = e.raw_os_error(); |
| 513 | code == Some(libc::ENODATA) || code == Some(libc::ENOTSUP) || code == Some(libc::EOPNOTSUPP) |
| 514 | } |
| 515 | |
| 516 | /// Size query then read, retried while the ACL grows between the two. |
| 517 | fn get(mut call: impl FnMut(*mut libc::c_void, usize) -> isize) -> io::Result<Option<Vec<u8>>> { |
| 518 | for _ in 0..8 { |
| 519 | let size = call(std::ptr::null_mut(), 0); |
| 520 | if size < 0 { |
| 521 | let e = io::Error::last_os_error(); |
| 522 | return if absent(&e) { Ok(None) } else { Err(e) }; |
| 523 | } |
| 524 | let mut buf = vec![0u8; size as usize]; |
| 525 | let n = call(buf.as_mut_ptr().cast(), buf.len()); |
| 526 | if n < 0 { |
| 527 | let e = io::Error::last_os_error(); |
| 528 | if e.raw_os_error() == Some(libc::ERANGE) { |
| 529 | continue; |
| 530 | } |
| 531 | return if absent(&e) { Ok(None) } else { Err(e) }; |
| 532 | } |
| 533 | buf.truncate(n as usize); |
| 534 | return Ok(Some(buf)); |
| 535 | } |
| 536 | Err(io::Error::from_raw_os_error(libc::ERANGE)) |
| 537 | } |
| 538 | |
| 539 | /// The access ACL of `path` itself (a final symlink is not followed). |
| 540 | pub fn read_path(path: &Path) -> io::Result<Option<Vec<u8>>> { |
| 541 | let c = CString::new(path.as_os_str().as_bytes()) |
| 542 | .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; |
| 543 | // SAFETY: `c` and NAME are NUL-terminated; `buf`/`size` describe a |
| 544 | // writable buffer of that length (or null/0 for the size query). |
| 545 | get(|buf, size| unsafe { libc::lgetxattr(c.as_ptr(), name(), buf, size) }) |
| 546 | } |
| 547 | |
| 548 | pub fn read_fd(f: &File) -> io::Result<Option<Vec<u8>>> { |
| 549 | let fd = f.as_raw_fd(); |
| 550 | // SAFETY: as in `read_path`; `fd` is open for the call's duration. |
| 551 | get(|buf, size| unsafe { libc::fgetxattr(fd, name(), buf, size) }) |
| 552 | } |
| 553 | |
| 554 | pub fn set_fd(f: &File, acl: &[u8]) -> io::Result<()> { |
| 555 | // SAFETY: `acl` is a valid buffer of `acl.len()` bytes. |
| 556 | let r = |
| 557 | unsafe { libc::fsetxattr(f.as_raw_fd(), name(), acl.as_ptr().cast(), acl.len(), 0) }; |
| 558 | if r < 0 { |
| 559 | return Err(io::Error::last_os_error()); |
| 560 | } |
| 561 | Ok(()) |
| 562 | } |
| 563 | |
| 564 | /// Removes an access ACL `f` inherited from a directory default ACL; |
| 565 | /// none present (or no ACL support) is success. |
| 566 | pub fn remove_fd(f: &File) -> io::Result<()> { |
| 567 | // SAFETY: NAME is NUL-terminated; `f` is open. |
| 568 | if unsafe { libc::fremovexattr(f.as_raw_fd(), name()) } < 0 { |
| 569 | let e = io::Error::last_os_error(); |
| 570 | if !absent(&e) { |
| 571 | return Err(e); |
| 572 | } |
| 573 | } |
| 574 | Ok(()) |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | /// Gives the temp file `tmp_file` (created 0600) the permissions of the file |
| 579 | /// it replaces, so a replace never widens access: the existing regular |
| 580 | /// file's group when this process may set it (if it cannot be kept the group |
| 581 | /// bits, and with an ACL the mask, are cleared rather than granted to this |
| 582 | /// process's group), on Linux its POSIX access ACL (or, when it has none, no |
| 583 | /// ACL: one the temp file inherited from a directory default ACL is removed), |
| 584 | /// then its permission bits (setuid/setgid/sticky are dropped). The result is |
| 585 | /// read back and checked. For a new file (or a non-regular entry, which load |
| 586 | /// refuses anyway) the [`new_file_mode`] default applies, with whatever the |
| 587 | /// directory default ACL gives a new file. Runs before any content is |
| 588 | /// written; an error names the failed step. |
| 589 | #[cfg(unix)] |
| 590 | fn match_replaced_permissions( |
| 591 | tmp_file: &File, |
| 592 | path: &Path, |
| 593 | ) -> Result<(), (&'static str, io::Error)> { |
| 594 | use std::os::unix::fs::{MetadataExt, PermissionsExt}; |
| 595 | let old = match fs::symlink_metadata(path) { |
| 596 | Ok(old) if old.file_type().is_file() => Some(old), |
| 597 | Ok(_) => None, |
| 598 | Err(e) if e.kind() == io::ErrorKind::NotFound => None, |
| 599 | Err(e) => return Err(("stat replaced file", e)), |
| 600 | }; |
| 601 | let Some(old) = old else { |
| 602 | return tmp_file |
| 603 | .set_permissions(fs::Permissions::from_mode(new_file_mode())) |
| 604 | .map_err(|e| ("set temp file mode", e)); |
| 605 | }; |
| 606 | let mut mode = old.mode() & 0o777; |
| 607 | let tmp_gid = tmp_file |
| 608 | .metadata() |
| 609 | .map_err(|e| ("stat temp file", e))? |
| 610 | .gid(); |
| 611 | let group_kept = |
| 612 | tmp_gid == old.gid() || std::os::unix::fs::fchown(tmp_file, None, Some(old.gid())).is_ok(); |
| 613 | if !group_kept { |
| 614 | mode &= !0o070; |
| 615 | } |
| 616 | // ACL first: setting it rewrites the mode bits from the ACL; the chmod |
| 617 | // after it then applies `mode`, and with an ACL its group bits become the |
| 618 | // mask, so a group that could not be kept also masks named entries. |
| 619 | #[cfg(target_os = "linux")] |
| 620 | let acl = access_acl::read_path(path).map_err(|e| ("read access ACL", e))?; |
| 621 | #[cfg(target_os = "linux")] |
| 622 | match &acl { |
| 623 | Some(bytes) => access_acl::set_fd(tmp_file, bytes).map_err(|e| ("set temp file ACL", e))?, |
| 624 | None => { |
| 625 | access_acl::remove_fd(tmp_file).map_err(|e| ("remove inherited temp file ACL", e))? |
| 626 | } |
| 627 | } |
| 628 | tmp_file |
| 629 | .set_permissions(fs::Permissions::from_mode(mode)) |
| 630 | .map_err(|e| ("set temp file mode", e))?; |
| 631 | // Re-verify what the temp inode now carries. |
| 632 | let verify = |what: String| ("verify temp file permissions", io::Error::other(what)); |
| 633 | let got = tmp_file |
| 634 | .metadata() |
| 635 | .map_err(|e| ("stat temp file", e))? |
| 636 | .mode() |
| 637 | & 0o7777; |
| 638 | if got != mode { |
| 639 | return Err(verify(format!("mode {got:o}, expected {mode:o}"))); |
| 640 | } |
| 641 | #[cfg(target_os = "linux")] |
| 642 | { |
| 643 | let now = access_acl::read_fd(tmp_file).map_err(|e| ("read temp file ACL", e))?; |
| 644 | let ok = match (&acl, &now) { |
| 645 | (None, None) => true, |
| 646 | (Some(want), Some(have)) => !group_kept || want == have, |
| 647 | _ => false, |
| 648 | }; |
| 649 | if !ok { |
| 650 | return Err(verify(format!( |
| 651 | "access ACL differs from the replaced file's (present before: {}, now: {})", |
| 652 | acl.is_some(), |
| 653 | now.is_some() |
| 654 | ))); |
| 655 | } |
| 656 | } |
| 657 | Ok(()) |
| 658 | } |
| 659 | |
| 660 | /// Writes `data` to a temp file in `dir`, fsyncs it, renames it over |
| 661 | /// `.crumb.local` and fsyncs the directory. The temp file is created 0600 and |
| 662 | /// given the replaced file's permissions, group and (Linux) access ACL (see |
| 663 | /// `match_replaced_permissions`) before any content is written, so access |
| 664 | /// never widens, not even while the temp file exists; if they cannot be |
| 665 | /// copied and verified the replace fails. On any failure up to the rename the old file is |
| 666 | /// untouched and the temp file is removed; a failure of the final directory |
| 667 | /// fsync means the replacement is visible but not confirmed durable. |
| 668 | fn replace_locked( |
| 669 | lock: &DirLock, |
| 670 | dir: &Path, |
| 671 | data: &LocalCrumbData, |
| 672 | ) -> Result<(), LocalCrumbError> { |
| 673 | sweep_orphan_temps(dir); |
| 674 | let path = dir.join(LOCAL_CRUMB_FILENAME); |
| 675 | let json = serde_json::to_vec_pretty(data).map_err(|e| LocalCrumbError::Io { |
| 676 | path: path.clone(), |
| 677 | op: "serialize", |
| 678 | source: io::Error::new(io::ErrorKind::InvalidData, e), |
| 679 | })?; |
| 680 | let tmp = dir.join(format!( |
| 681 | "{}{}-{}", |
| 682 | LOCAL_CRUMB_TEMP_PREFIX, |
| 683 | std::process::id(), |
| 684 | &uuid::Uuid::new_v4().simple().to_string()[..12] |
| 685 | )); |
| 686 | let io_err = |op: &'static str, source: io::Error| LocalCrumbError::Io { |
| 687 | path: path.clone(), |
| 688 | op, |
| 689 | source, |
| 690 | }; |
| 691 | let mut opts = OpenOptions::new(); |
| 692 | opts.write(true).create_new(true); |
| 693 | #[cfg(unix)] |
| 694 | { |
| 695 | use std::os::unix::fs::OpenOptionsExt; |
| 696 | opts.mode(0o600); |
| 697 | } |
| 698 | let mut f = nofollow(&mut opts) |
| 699 | .open(&tmp) |
| 700 | .map_err(|e| io_err("create temp file", e))?; |
| 701 | #[cfg(unix)] |
| 702 | let permitted = match_replaced_permissions(&f, &path).map_err(|(op, e)| io_err(op, e)); |
| 703 | #[cfg(not(unix))] |
| 704 | let permitted: Result<(), LocalCrumbError> = Ok(()); |
| 705 | let written = permitted |
| 706 | .and_then(|_| f.write_all(&json).map_err(|e| io_err("write temp file", e))) |
| 707 | .and_then(|_| f.sync_all().map_err(|e| io_err("fsync temp file", e))); |
| 708 | drop(f); |
| 709 | if let Err(e) = written.and_then(|_| fs::rename(&tmp, &path).map_err(|e| io_err("rename", e))) { |
| 710 | let _ = fs::remove_file(&tmp); |
| 711 | return Err(e); |
| 712 | } |
| 713 | lock.dir.sync_all().map_err(|e| io_err(OP_FSYNC_DIR, e)) |
| 714 | } |
| 715 | |
| 716 | /// Replaces `dir/.crumb.local` with `data` under the directory lock. Prefer |
| 717 | /// [`update_local_crumb`]: a blind save discards a concurrent writer's entries. |
| 718 | pub fn save_local_crumb(dir: &Path, data: &LocalCrumbData) -> Result<(), LocalCrumbError> { |
| 719 | let lock = lock_dir(dir)?; |
| 720 | replace_locked(&lock, dir, data) |
| 721 | } |
| 722 | |
| 723 | /// One read-modify-write of `dir/.crumb.local` under an exclusive lock on the |
| 724 | /// directory: load (an unreadable or malformed file aborts, untouched), apply |
| 725 | /// `f`, replace atomically and durably. |
| 726 | pub fn update_local_crumb<T>( |
| 727 | dir: &Path, |
| 728 | f: impl FnOnce(&mut LocalCrumbData) -> T, |
| 729 | ) -> Result<T, LocalCrumbError> { |
| 730 | let lock = lock_dir(dir)?; |
| 731 | let mut data = load_local_crumb(dir)?; |
| 732 | let out = f(&mut data); |
| 733 | replace_locked(&lock, dir, &data)?; |
| 734 | Ok(out) |
| 735 | } |
| 736 | |
| 737 | /// Appends `item`, keeping the newest [`HISTORY_CAP`] entries. |
| 738 | pub fn push_history(dir: &Path, item: CrumbHistoryItem) -> Result<(), LocalCrumbError> { |
| 739 | update_local_crumb(dir, |d| { |
| 740 | d.history.push(item); |
| 741 | if d.history.len() > HISTORY_CAP { |
| 742 | let excess = d.history.len() - HISTORY_CAP; |
| 743 | d.history.drain(0..excess); |
| 744 | } |
| 745 | }) |
| 746 | } |
| 747 | |
| 748 | /// Appends `whisper`, keeping the newest [`WHISPER_CAP`] entries. |
| 749 | pub fn push_whisper(dir: &Path, whisper: CrumbWhisper) -> Result<(), LocalCrumbError> { |
| 750 | update_local_crumb(dir, |d| { |
| 751 | d.whispers.push(whisper); |
| 752 | if d.whispers.len() > WHISPER_CAP { |
| 753 | let excess = d.whispers.len() - WHISPER_CAP; |
| 754 | d.whispers.drain(0..excess); |
| 755 | } |
| 756 | }) |
| 757 | } |
| 758 | |
| 759 | #[cfg(test)] |
| 760 | mod tests { |
| 761 | use super::*; |
| 762 | use std::collections::HashMap; |
| 763 | |
| 764 | fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> { |
| 765 | let map: HashMap<String, String> = pairs |
| 766 | .iter() |
| 767 | .map(|(k, v)| (k.to_string(), v.to_string())) |
| 768 | .collect(); |
| 769 | move |k| map.get(k).cloned() |
| 770 | } |
| 771 | |
| 772 | fn scratch(tag: &str) -> PathBuf { |
| 773 | let p = std::env::temp_dir().join(format!( |
| 774 | "spark-crumbs-local-{}-{}", |
| 775 | tag, |
| 776 | uuid::Uuid::new_v4().simple() |
| 777 | )); |
| 778 | fs::create_dir_all(&p).unwrap(); |
| 779 | p |
| 780 | } |
| 781 | |
| 782 | fn item(n: usize) -> CrumbHistoryItem { |
| 783 | CrumbHistoryItem { |
| 784 | crumb_id: unique_record_id("crumb"), |
| 785 | timestamp: Utc::now().to_rfc3339(), |
| 786 | agent_id: format!("a{n}"), |
| 787 | session_id: "s".into(), |
| 788 | action: "edit".into(), |
| 789 | target: "f".into(), |
| 790 | intent: format!("{n}"), |
| 791 | vector: String::new(), |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | #[test] |
| 796 | fn identity_precedence() { |
| 797 | let id = resolve_identity_with( |
| 798 | &env_of(&[ |
| 799 | ("AIEN_AGENT_ID", "explicit-1"), |
| 800 | ("AIEN_AGENT_NAME", "worker"), |
| 801 | ("AIEN_SESSION_ID", "s9"), |
| 802 | ]), |
| 803 | "aien-cli", |
| 804 | ) |
| 805 | .unwrap(); |
| 806 | assert_eq!(id.agent_id, "explicit-1"); |
| 807 | assert_eq!(id.session_id, "s9"); |
| 808 | assert_eq!(id.source, IdentitySource::AgentId); |
| 809 | |
| 810 | let id = resolve_identity_with( |
| 811 | &env_of(&[("AIEN_AGENT_NAME", "worker"), ("AIEN_SESSION_ID", "s9")]), |
| 812 | "aien-cli", |
| 813 | ) |
| 814 | .unwrap(); |
| 815 | assert_eq!(id.agent_id, "worker.s9"); |
| 816 | assert_eq!(id.source, IdentitySource::NameAndSession); |
| 817 | |
| 818 | let id = resolve_identity_with(&env_of(&[("HERMES_SESSION_ID", "local-abc")]), "aien-cli") |
| 819 | .unwrap(); |
| 820 | assert_eq!(id.agent_id, "aien-cli.local-abc"); |
| 821 | assert_eq!(id.session_id, "local-abc"); |
| 822 | |
| 823 | // AIEN_SESSION_ID wins over HERMES_SESSION_ID. |
| 824 | let id = resolve_identity_with( |
| 825 | &env_of(&[("AIEN_SESSION_ID", "a"), ("HERMES_SESSION_ID", "h")]), |
| 826 | "n", |
| 827 | ) |
| 828 | .unwrap(); |
| 829 | assert_eq!(id.agent_id, "n.a"); |
| 830 | } |
| 831 | |
| 832 | #[test] |
| 833 | fn generated_identities_are_unique_and_valid() { |
| 834 | // Set-but-empty variables count as unset. |
| 835 | let empty = env_of(&[ |
| 836 | ("AIEN_AGENT_ID", ""), |
| 837 | ("AIEN_AGENT_NAME", ""), |
| 838 | ("AIEN_SESSION_ID", ""), |
| 839 | ("HERMES_SESSION_ID", ""), |
| 840 | ]); |
| 841 | let a = resolve_identity_with(&empty, "aien-cli").unwrap(); |
| 842 | let b = resolve_identity_with(&empty, "aien-cli").unwrap(); |
| 843 | assert_eq!(a.source, IdentitySource::Generated); |
| 844 | assert_ne!(a.agent_id, b.agent_id); |
| 845 | assert_ne!(a.session_id, b.session_id); |
| 846 | let prefix = "aien-cli@"; |
| 847 | assert!(a.agent_id.starts_with(prefix), "{}", a.agent_id); |
| 848 | assert!(a.agent_id.contains(&format!(".{}.", std::process::id()))); |
| 849 | assert!(is_valid_agent_id(&a.agent_id), "{}", a.agent_id); |
| 850 | } |
| 851 | |
| 852 | #[test] |
| 853 | fn shared_constants_and_invalid_ids_are_refused() { |
| 854 | for env in [ |
| 855 | env_of(&[("AIEN_AGENT_ID", "AIEN")]), |
| 856 | env_of(&[ |
| 857 | ("AIEN_AGENT_ID", "x"), |
| 858 | ("AIEN_SESSION_ID", "active-session"), |
| 859 | ]), |
| 860 | env_of(&[("AIEN_AGENT_ID", "bad id")]), |
| 861 | env_of(&[("AIEN_AGENT_ID", "a/b")]), |
| 862 | env_of(&[("AIEN_AGENT_NAME", "-lead"), ("AIEN_SESSION_ID", "s")]), |
| 863 | ] { |
| 864 | assert!(resolve_identity_with(&env, "aien-cli").is_err()); |
| 865 | } |
| 866 | assert!(resolve_identity_with(&env_of(&[]), "AIEN").is_ok_and(|i| i.agent_id != "AIEN")); |
| 867 | assert!(is_valid_agent_id(&"a".repeat(160))); |
| 868 | assert!(is_valid_agent_id("worker.20261106_233000_ab12")); |
| 869 | assert!(!is_valid_agent_id(&"a".repeat(161))); |
| 870 | } |
| 871 | |
| 872 | /// Identity variables are never trimmed: a padded, whitespace-only or |
| 873 | /// otherwise malformed value of any consulted variable is an error (a |
| 874 | /// trimmed ` worker-1 ` used to alias `worker-1`). Valid values are kept |
| 875 | /// byte for byte; unset and empty are the same. |
| 876 | #[test] |
| 877 | fn identity_inputs_are_validated_verbatim() { |
| 878 | for (k, v) in [ |
| 879 | ("AIEN_AGENT_ID", " worker-1 "), |
| 880 | ("AIEN_AGENT_ID", "worker-1 "), |
| 881 | ("AIEN_AGENT_ID", " worker-1"), |
| 882 | ("AIEN_AGENT_ID", "worker-1\n"), |
| 883 | ("AIEN_AGENT_ID", "\tworker-1"), |
| 884 | ("AIEN_AGENT_ID", " "), |
| 885 | ("AIEN_AGENT_ID", "worker-\u{FFFD}"), |
| 886 | ("AIEN_SESSION_ID", " s1"), |
| 887 | ("AIEN_SESSION_ID", "s1 "), |
| 888 | ("HERMES_SESSION_ID", " local-abc"), |
| 889 | ("AIEN_AGENT_NAME", "worker "), |
| 890 | ("AIEN_AGENT_NAME", " "), |
| 891 | ] { |
| 892 | // AIEN_AGENT_NAME is consulted only without AIEN_AGENT_ID. |
| 893 | let mut pairs = vec![(k, v)]; |
| 894 | if k == "AIEN_AGENT_NAME" { |
| 895 | pairs.push(("AIEN_SESSION_ID", "s1")); |
| 896 | } else if k != "AIEN_AGENT_ID" { |
| 897 | pairs.push(("AIEN_AGENT_ID", "worker-1")); |
| 898 | } |
| 899 | let e = resolve_identity_with(&env_of(&pairs), "aien-cli") |
| 900 | .expect_err(&format!("{k}={v:?} was accepted")); |
| 901 | assert!(e.0.contains(k), "{e}"); |
| 902 | } |
| 903 | // A padded value is an error even when it would be shadowed only after |
| 904 | // trimming: AIEN_SESSION_ID is consulted before HERMES_SESSION_ID. |
| 905 | assert!(resolve_identity_with( |
| 906 | &env_of(&[("AIEN_SESSION_ID", " a"), ("HERMES_SESSION_ID", "h")]), |
| 907 | "n" |
| 908 | ) |
| 909 | .is_err()); |
| 910 | // Unused variables are not consulted: AIEN_AGENT_NAME with AIEN_AGENT_ID. |
| 911 | let id = resolve_identity_with( |
| 912 | &env_of(&[("AIEN_AGENT_ID", "worker-1"), ("AIEN_AGENT_NAME", " x ")]), |
| 913 | "aien-cli", |
| 914 | ) |
| 915 | .unwrap(); |
| 916 | assert_eq!(id.agent_id, "worker-1"); |
| 917 | |
| 918 | let id = resolve_identity_with( |
| 919 | &env_of(&[ |
| 920 | ("AIEN_AGENT_ID", "W-1.x_y@h"), |
| 921 | ("AIEN_SESSION_ID", "S_1.a@b-2"), |
| 922 | ]), |
| 923 | "aien-cli", |
| 924 | ) |
| 925 | .unwrap(); |
| 926 | assert_eq!(id.agent_id.as_bytes(), b"W-1.x_y@h"); |
| 927 | assert_eq!(id.session_id.as_bytes(), b"S_1.a@b-2"); |
| 928 | // Empty AIEN_SESSION_ID falls through to HERMES_SESSION_ID. |
| 929 | let id = resolve_identity_with( |
| 930 | &env_of(&[("AIEN_SESSION_ID", ""), ("HERMES_SESSION_ID", "local-abc")]), |
| 931 | "n", |
| 932 | ) |
| 933 | .unwrap(); |
| 934 | assert_eq!(id.agent_id, "n.local-abc"); |
| 935 | assert_eq!(id.source, IdentitySource::NameAndSession); |
| 936 | } |
| 937 | |
| 938 | /// A replace keeps the existing file's permission bits (it used to create |
| 939 | /// a fresh 0644 inode, widening a private 0600 file) and gives a new file |
| 940 | /// the umask default. The process umask is not changed here (that would |
| 941 | /// race other tests); tests/local_state.rs checks umask 022 in a child. |
| 942 | #[cfg(unix)] |
| 943 | #[test] |
| 944 | fn replace_keeps_the_existing_mode() { |
| 945 | use std::os::unix::fs::PermissionsExt; |
| 946 | let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o7777; |
| 947 | for want in [0o600u32, 0o640, 0o400, 0o604] { |
| 948 | let d = scratch("mode"); |
| 949 | let p = d.join(LOCAL_CRUMB_FILENAME); |
| 950 | push_history(&d, item(1)).unwrap(); |
| 951 | fs::set_permissions(&p, fs::Permissions::from_mode(want)).unwrap(); |
| 952 | push_history(&d, item(2)).unwrap(); |
| 953 | assert_eq!(mode(&p), want, "push_history widened/changed {want:o}"); |
| 954 | save_local_crumb(&d, &load_local_crumb(&d).unwrap()).unwrap(); |
| 955 | assert_eq!(mode(&p), want, "save changed {want:o}"); |
| 956 | assert_eq!(load_local_crumb(&d).unwrap().history.len(), 2); |
| 957 | let _ = fs::remove_dir_all(&d); |
| 958 | } |
| 959 | let d = scratch("mode-new"); |
| 960 | push_history(&d, item(1)).unwrap(); |
| 961 | assert_eq!(mode(&d.join(LOCAL_CRUMB_FILENAME)), new_file_mode()); |
| 962 | assert_eq!(new_file_mode() & !0o644, 0, "default wider than 0644"); |
| 963 | let _ = fs::remove_dir_all(&d); |
| 964 | } |
| 965 | |
| 966 | #[test] |
| 967 | fn post_rename_io_error_says_the_replacement_is_visible() { |
| 968 | let e = LocalCrumbError::Io { |
| 969 | path: PathBuf::from("d/.crumb.local"), |
| 970 | op: OP_FSYNC_DIR, |
| 971 | source: io::Error::other("injected"), |
| 972 | }; |
| 973 | assert!( |
| 974 | e.to_string() |
| 975 | .contains("replacement visible, durability unconfirmed"), |
| 976 | "{e}" |
| 977 | ); |
| 978 | let e = LocalCrumbError::Io { |
| 979 | path: PathBuf::from("d/.crumb.local"), |
| 980 | op: "rename", |
| 981 | source: io::Error::other("injected"), |
| 982 | }; |
| 983 | assert!(!e.to_string().contains("visible"), "{e}"); |
| 984 | } |
| 985 | |
| 986 | #[test] |
| 987 | fn missing_is_empty_but_malformed_and_unreadable_are_errors() { |
| 988 | let d = scratch("load"); |
| 989 | assert!(load_local_crumb(&d).unwrap().history.is_empty()); |
| 990 | |
| 991 | fs::write(d.join(LOCAL_CRUMB_FILENAME), "{ nope").unwrap(); |
| 992 | let e = load_local_crumb(&d).unwrap_err(); |
| 993 | assert_eq!(e.kind(), LocalCrumbErrorKind::Malformed, "{e}"); |
| 994 | let e = push_history(&d, item(0)).unwrap_err(); |
| 995 | assert_eq!(e.kind(), LocalCrumbErrorKind::Malformed); |
| 996 | assert_eq!( |
| 997 | fs::read_to_string(d.join(LOCAL_CRUMB_FILENAME)).unwrap(), |
| 998 | "{ nope" |
| 999 | ); |
| 1000 | |
| 1001 | fs::write(d.join(LOCAL_CRUMB_FILENAME), "").unwrap(); |
| 1002 | assert_eq!( |
| 1003 | load_local_crumb(&d).unwrap_err().kind(), |
| 1004 | LocalCrumbErrorKind::Malformed |
| 1005 | ); |
| 1006 | |
| 1007 | #[cfg(unix)] |
| 1008 | { |
| 1009 | use std::os::unix::fs::PermissionsExt; |
| 1010 | let p = d.join(LOCAL_CRUMB_FILENAME); |
| 1011 | fs::write(&p, "{}").unwrap(); |
| 1012 | fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap(); |
| 1013 | if fs::read(&p).is_err() { |
| 1014 | assert_eq!( |
| 1015 | load_local_crumb(&d).unwrap_err().kind(), |
| 1016 | LocalCrumbErrorKind::Unreadable |
| 1017 | ); |
| 1018 | assert_eq!( |
| 1019 | push_history(&d, item(0)).unwrap_err().kind(), |
| 1020 | LocalCrumbErrorKind::Unreadable |
| 1021 | ); |
| 1022 | } |
| 1023 | fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap(); |
| 1024 | } |
| 1025 | let _ = fs::remove_dir_all(&d); |
| 1026 | } |
| 1027 | |
| 1028 | #[cfg(unix)] |
| 1029 | #[test] |
| 1030 | fn a_symlinked_local_crumb_is_unreadable_and_never_written_through() { |
| 1031 | let d = scratch("symlink"); |
| 1032 | let victim = d.join("victim"); |
| 1033 | fs::write(&victim, "{\"history\":[],\"whispers\":[]}").unwrap(); |
| 1034 | std::os::unix::fs::symlink(&victim, d.join(LOCAL_CRUMB_FILENAME)).unwrap(); |
| 1035 | assert_eq!( |
| 1036 | load_local_crumb(&d).unwrap_err().kind(), |
| 1037 | LocalCrumbErrorKind::Unreadable |
| 1038 | ); |
| 1039 | assert!(push_history(&d, item(0)).is_err()); |
| 1040 | assert_eq!( |
| 1041 | fs::read_to_string(&victim).unwrap(), |
| 1042 | "{\"history\":[],\"whispers\":[]}" |
| 1043 | ); |
| 1044 | let _ = fs::remove_dir_all(&d); |
| 1045 | } |
| 1046 | |
| 1047 | #[cfg(unix)] |
| 1048 | #[test] |
| 1049 | fn unwritable_directory_is_an_io_error_and_leaves_the_file() { |
| 1050 | use std::os::unix::fs::PermissionsExt; |
| 1051 | let d = scratch("ro"); |
| 1052 | push_history(&d, item(1)).unwrap(); |
| 1053 | let before = fs::read_to_string(d.join(LOCAL_CRUMB_FILENAME)).unwrap(); |
| 1054 | fs::set_permissions(&d, fs::Permissions::from_mode(0o555)).unwrap(); |
| 1055 | if fs::write(d.join("probe"), "x").is_err() { |
| 1056 | let e = push_history(&d, item(2)).unwrap_err(); |
| 1057 | assert_eq!(e.kind(), LocalCrumbErrorKind::Io, "{e}"); |
| 1058 | assert_eq!( |
| 1059 | fs::read_to_string(d.join(LOCAL_CRUMB_FILENAME)).unwrap(), |
| 1060 | before |
| 1061 | ); |
| 1062 | } |
| 1063 | fs::set_permissions(&d, fs::Permissions::from_mode(0o755)).unwrap(); |
| 1064 | // No temp file is left behind. |
| 1065 | let leftovers: Vec<_> = fs::read_dir(&d) |
| 1066 | .unwrap() |
| 1067 | .flatten() |
| 1068 | .filter(|e| { |
| 1069 | e.file_name() |
| 1070 | .to_string_lossy() |
| 1071 | .starts_with(LOCAL_CRUMB_TEMP_PREFIX) |
| 1072 | }) |
| 1073 | .collect(); |
| 1074 | assert!(leftovers.is_empty()); |
| 1075 | let _ = fs::remove_dir_all(&d); |
| 1076 | } |
| 1077 | |
| 1078 | #[test] |
| 1079 | fn missing_directory_is_a_lock_error() { |
| 1080 | let parent = scratch("gone"); |
| 1081 | let d = parent.join("missing"); |
| 1082 | assert_eq!( |
| 1083 | push_history(&d, item(0)).unwrap_err().kind(), |
| 1084 | LocalCrumbErrorKind::Lock |
| 1085 | ); |
| 1086 | let _ = fs::remove_dir_all(&parent); |
| 1087 | } |
| 1088 | |
| 1089 | /// A temp file left by a writer that died mid-replace is removed by the |
| 1090 | /// next locked write and never read as `.crumb.local`. |
| 1091 | #[test] |
| 1092 | fn orphan_temp_files_are_swept_under_the_lock() { |
| 1093 | let d = scratch("orphan"); |
| 1094 | let orphan = d.join(format!("{LOCAL_CRUMB_TEMP_PREFIX}99999-deadbeef")); |
| 1095 | fs::write(&orphan, "{ partial").unwrap(); |
| 1096 | push_history(&d, item(1)).unwrap(); |
| 1097 | assert!(!orphan.exists()); |
| 1098 | assert_eq!(load_local_crumb(&d).unwrap().history.len(), 1); |
| 1099 | let _ = fs::remove_dir_all(&d); |
| 1100 | } |
| 1101 | |
| 1102 | /// The primitive itself, without the per-directory caps: 8 threads x 50 |
| 1103 | /// read-modify-writes each, while an unlocked reader polls. Every read |
| 1104 | /// parses (the replace is atomic, so no reader sees a torn file) and the |
| 1105 | /// count never goes backwards. |
| 1106 | #[test] |
| 1107 | fn update_is_serialised_across_threads() { |
| 1108 | const N: usize = 8; |
| 1109 | const K: usize = 50; |
| 1110 | let d = scratch("rmw"); |
| 1111 | let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 1112 | let reader = { |
| 1113 | let (d, done) = (d.clone(), done.clone()); |
| 1114 | std::thread::spawn(move || { |
| 1115 | let (mut reads, mut last) = (0usize, 0usize); |
| 1116 | while !done.load(std::sync::atomic::Ordering::SeqCst) { |
| 1117 | let n = load_local_crumb(&d) |
| 1118 | .expect("torn or failed read") |
| 1119 | .history |
| 1120 | .len(); |
| 1121 | assert!(n >= last, "count went backwards: {last} -> {n}"); |
| 1122 | last = n; |
| 1123 | reads += 1; |
| 1124 | } |
| 1125 | reads |
| 1126 | }) |
| 1127 | }; |
| 1128 | let handles: Vec<_> = (0..N) |
| 1129 | .map(|t| { |
| 1130 | let d = d.clone(); |
| 1131 | std::thread::spawn(move || { |
| 1132 | for k in 0..K { |
| 1133 | update_local_crumb(&d, |data| data.history.push(item(t * K + k))).unwrap(); |
| 1134 | } |
| 1135 | }) |
| 1136 | }) |
| 1137 | .collect(); |
| 1138 | for h in handles { |
| 1139 | h.join().unwrap(); |
| 1140 | } |
| 1141 | done.store(true, std::sync::atomic::Ordering::SeqCst); |
| 1142 | let reads = reader.join().expect("reader saw a torn file"); |
| 1143 | println!("unlocked reads during the race: {reads}"); |
| 1144 | let data = load_local_crumb(&d).unwrap(); |
| 1145 | assert_eq!(data.history.len(), N * K); |
| 1146 | let mut ids: Vec<_> = data.history.iter().map(|h| h.crumb_id.clone()).collect(); |
| 1147 | ids.sort(); |
| 1148 | ids.dedup(); |
| 1149 | assert_eq!(ids.len(), N * K, "record ids collide"); |
| 1150 | let _ = fs::remove_dir_all(&d); |
| 1151 | } |
| 1152 | |
| 1153 | #[test] |
| 1154 | fn caps_keep_the_newest_entries() { |
| 1155 | let d = scratch("caps"); |
| 1156 | for n in 0..(HISTORY_CAP + 5) { |
| 1157 | push_history(&d, item(n)).unwrap(); |
| 1158 | } |
| 1159 | let data = load_local_crumb(&d).unwrap(); |
| 1160 | assert_eq!(data.history.len(), HISTORY_CAP); |
| 1161 | assert_eq!(data.history[0].intent, "5"); |
| 1162 | let _ = fs::remove_dir_all(&d); |
| 1163 | } |
| 1164 | } |