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 / aien-allen-memory / src / store.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 | //! The store `<home>.allen-memory/`: |
| 17 | //! log/ `l<20 digits>.json` immutable hash-chained records (ciphertext only) |
| 18 | //! keys/ `<item>-v<version>.key`, 32 random bytes, mode 0600 (dir 0700) |
| 19 | //! pending/ forget intent markers (item id or scope only) |
| 20 | //! Append order: temp file, fsync, `hard_link` (fails if the number exists: |
| 21 | //! a lost race), fsync dir, remove temp. A crash leaves the old head or the |
| 22 | //! new head. Anything unexpected in `log/` is a refusal, never skipped. |
| 23 | use crate::refusal::MemoryRefusal as R; |
| 24 | use crate::schema::*; |
| 25 | use aien_allen::{hex, Resolved}; |
| 26 | use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305}; |
| 27 | use ring::rand::{SecureRandom, SystemRandom}; |
| 28 | use serde::Serialize; |
| 29 | use sha2::{Digest, Sha256}; |
| 30 | use std::collections::BTreeMap; |
| 31 | use std::io::Write; |
| 32 | use std::path::{Path, PathBuf}; |
| 33 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 34 | |
| 35 | /// `<home>.allen-memory`, beside `<home>.allen-binding`. |
| 36 | pub fn memory_dir(home: &Path) -> PathBuf { |
| 37 | let mut n = home.as_os_str().to_owned(); |
| 38 | n.push(".allen-memory"); |
| 39 | PathBuf::from(n) |
| 40 | } |
| 41 | |
| 42 | /// Named points in a write, for crash injection (feature `fault-injection`). |
| 43 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 44 | pub enum Step { |
| 45 | KeyWritten, |
| 46 | TempCreated, |
| 47 | TempWritten, |
| 48 | TempSynced, |
| 49 | Linked, |
| 50 | DirSynced, |
| 51 | TempRemoved, |
| 52 | MarkerWritten, |
| 53 | KeyZeroed, |
| 54 | KeyUnlinked, |
| 55 | KeysDestroyed, |
| 56 | ForgetRecorded, |
| 57 | MarkerRemoved, |
| 58 | SupersededKeyDestroyed, |
| 59 | } |
| 60 | |
| 61 | #[cfg(feature = "fault-injection")] |
| 62 | type Hook = std::sync::Arc<dyn Fn(Step) -> bool + Send + Sync>; |
| 63 | |
| 64 | /// The right to read ONE scope. Built by the daemon from the request's |
| 65 | /// authorised context. There is no constructor from text found in a query, |
| 66 | /// a model reply or a task, and no "all" value. |
| 67 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 68 | pub struct ScopeGrant { |
| 69 | scope: Scope, |
| 70 | } |
| 71 | |
| 72 | impl ScopeGrant { |
| 73 | pub fn new(scope: Scope) -> ScopeGrant { |
| 74 | ScopeGrant { scope } |
| 75 | } |
| 76 | pub fn scope(&self) -> &Scope { |
| 77 | &self.scope |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Owner-facing inspect across all scopes. Only `inspect_all` and |
| 82 | /// `goals_all` take it; recall and export never do. (Type-level discipline: |
| 83 | /// the crate cannot stop a caller from constructing it. UNVERIFIED beyond that.) |
| 84 | #[derive(Debug, Clone, Copy)] |
| 85 | pub struct InspectAll(()); |
| 86 | |
| 87 | /// Who is asking to change an item: a grant for one scope, or the owner. |
| 88 | #[derive(Clone, Copy)] |
| 89 | pub enum Authority<'a> { |
| 90 | Scope(&'a ScopeGrant), |
| 91 | Owner(&'a InspectAll), |
| 92 | } |
| 93 | |
| 94 | impl<'a> From<&'a ScopeGrant> for Authority<'a> { |
| 95 | fn from(g: &'a ScopeGrant) -> Self { |
| 96 | Authority::Scope(g) |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | impl<'a> From<&'a InspectAll> for Authority<'a> { |
| 101 | fn from(g: &'a InspectAll) -> Self { |
| 102 | Authority::Owner(g) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | impl Authority<'_> { |
| 107 | fn check(&self, item: &str, scope: &Scope) -> Result<(), R> { |
| 108 | match self { |
| 109 | Authority::Owner(_) => Ok(()), |
| 110 | Authority::Scope(g) if g.scope == *scope => Ok(()), |
| 111 | Authority::Scope(_) => Err(R::ScopeMismatch(item.to_string())), |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | impl InspectAll { |
| 117 | pub fn owner() -> InspectAll { |
| 118 | InspectAll(()) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[derive(Debug, Clone, Copy)] |
| 123 | pub struct RecallLimits { |
| 124 | pub max_items: usize, |
| 125 | pub max_bytes: usize, |
| 126 | } |
| 127 | |
| 128 | impl Default for RecallLimits { |
| 129 | fn default() -> Self { |
| 130 | RecallLimits { |
| 131 | max_items: 16, |
| 132 | max_bytes: 4096, |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | pub enum ForgetTarget { |
| 138 | Item(String), |
| 139 | Scope(Scope), |
| 140 | } |
| 141 | |
| 142 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 143 | pub enum ItemStatus { |
| 144 | Live, |
| 145 | Corrected, |
| 146 | Closed, |
| 147 | Forgotten, |
| 148 | /// Intent recorded, record not yet appended. `key_missing` says whether the key is already gone. |
| 149 | ForgottenPending { |
| 150 | key_missing: bool, |
| 151 | }, |
| 152 | Unresolved(String), |
| 153 | } |
| 154 | |
| 155 | impl ItemStatus { |
| 156 | pub fn text(&self) -> String { |
| 157 | match self { |
| 158 | ItemStatus::Live => "live".into(), |
| 159 | ItemStatus::Corrected => "corrected".into(), |
| 160 | ItemStatus::Closed => "closed".into(), |
| 161 | ItemStatus::Forgotten => "forgotten".into(), |
| 162 | ItemStatus::ForgottenPending { key_missing: true } => { |
| 163 | "forgotten (key missing, record pending)".into() |
| 164 | } |
| 165 | ItemStatus::ForgottenPending { key_missing: false } => { |
| 166 | "forgotten (key removal pending)".into() |
| 167 | } |
| 168 | ItemStatus::Unresolved(w) => format!("Unresolved: {w}"), |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 174 | pub struct ItemView { |
| 175 | pub item: String, |
| 176 | pub scope: String, |
| 177 | pub kind: Kind, |
| 178 | pub version: u32, |
| 179 | pub created: String, |
| 180 | pub state: String, |
| 181 | /// Present only for live and closed items. Forgotten items never show content. |
| 182 | pub text: Option<String>, |
| 183 | /// Set on goals: "host goal record, not a subject intent". |
| 184 | pub label: Option<&'static str>, |
| 185 | #[serde(skip)] |
| 186 | pub status: Option<ItemStatus>, |
| 187 | } |
| 188 | |
| 189 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 190 | pub struct Recall { |
| 191 | pub scope: Scope, |
| 192 | pub items: Vec<ItemView>, |
| 193 | /// Items left out because of the count or byte limit. |
| 194 | pub omitted: usize, |
| 195 | /// Items in this scope whose key is missing (never treated as live). |
| 196 | pub unresolved: Vec<String>, |
| 197 | } |
| 198 | |
| 199 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 200 | pub struct GoalView { |
| 201 | pub item: String, |
| 202 | pub scope: String, |
| 203 | pub text: String, |
| 204 | pub created: String, |
| 205 | /// `open` or `closed`. |
| 206 | pub state: &'static str, |
| 207 | pub label: &'static str, |
| 208 | } |
| 209 | |
| 210 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 211 | pub struct GoalList { |
| 212 | pub label: &'static str, |
| 213 | pub goals: Vec<GoalView>, |
| 214 | } |
| 215 | |
| 216 | struct Ver { |
| 217 | version: u32, |
| 218 | at: String, |
| 219 | ciphertext: Vec<u8>, |
| 220 | nonce: [u8; NONCE_LEN], |
| 221 | } |
| 222 | |
| 223 | struct Item { |
| 224 | scope: Scope, |
| 225 | kind: Kind, |
| 226 | created_seq: u64, |
| 227 | versions: Vec<Ver>, |
| 228 | forgotten: bool, |
| 229 | closed: bool, |
| 230 | } |
| 231 | |
| 232 | impl Item { |
| 233 | fn current(&self) -> &Ver { |
| 234 | self.versions.last().expect("an item has a version") |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | struct Replay { |
| 239 | items: BTreeMap<String, Item>, |
| 240 | head_seq: u64, |
| 241 | head_sha: String, |
| 242 | } |
| 243 | |
| 244 | pub struct Memory { |
| 245 | read_only: bool, |
| 246 | dir: PathBuf, |
| 247 | agent: [u8; 32], |
| 248 | root: [u8; 32], |
| 249 | #[cfg(feature = "fault-injection")] |
| 250 | hook: Option<Hook>, |
| 251 | } |
| 252 | |
| 253 | fn io(what: &str, e: std::io::Error) -> R { |
| 254 | R::Io(format!("{what}: {e}")) |
| 255 | } |
| 256 | |
| 257 | fn sha_hex(b: &[u8]) -> String { |
| 258 | hex(&Sha256::digest(b)) |
| 259 | } |
| 260 | |
| 261 | fn log_name(n: u64) -> String { |
| 262 | format!("l{n:020}.json") |
| 263 | } |
| 264 | |
| 265 | fn parse_log_name(s: &str) -> Option<u64> { |
| 266 | let d = s.strip_prefix('l')?.strip_suffix(".json")?; |
| 267 | if d.len() != 20 || !d.bytes().all(|b| b.is_ascii_digit()) { |
| 268 | return None; |
| 269 | } |
| 270 | d.parse().ok().filter(|n| *n >= 1) |
| 271 | } |
| 272 | |
| 273 | fn sync_dir(p: &Path) -> Result<(), R> { |
| 274 | std::fs::File::open(p) |
| 275 | .and_then(|d| d.sync_all()) |
| 276 | .map_err(|e| io("sync dir", e)) |
| 277 | } |
| 278 | |
| 279 | fn rand_hex(n: usize) -> Result<String, R> { |
| 280 | let mut b = vec![0u8; n]; |
| 281 | SystemRandom::new() |
| 282 | .fill(&mut b) |
| 283 | .map_err(|_| R::Io("random source failed".into()))?; |
| 284 | Ok(hex(&b)) |
| 285 | } |
| 286 | |
| 287 | impl Memory { |
| 288 | /// Open the store for the engaged identity. `None` (not engaged) is refused. |
| 289 | /// Verifies the whole log, finishes any pending forget, and re-destroys keys |
| 290 | /// of forgotten or superseded versions (see [`Memory::reapply_forgets`]). |
| 291 | pub fn open(home: &Path, engaged: Option<&Resolved>) -> Result<Memory, R> { |
| 292 | Memory::at(memory_dir(home), engaged) |
| 293 | } |
| 294 | |
| 295 | pub fn at(dir: PathBuf, engaged: Option<&Resolved>) -> Result<Memory, R> { |
| 296 | let r = engaged.ok_or(R::NotEngaged)?; |
| 297 | let m = Memory { |
| 298 | read_only: false, |
| 299 | dir, |
| 300 | agent: r.agent, |
| 301 | root: r.root, |
| 302 | #[cfg(feature = "fault-injection")] |
| 303 | hook: None, |
| 304 | }; |
| 305 | m.recover()?; |
| 306 | Ok(m) |
| 307 | } |
| 308 | |
| 309 | /// Reopen with a crash hook installed AFTER recovery (test seam). |
| 310 | #[cfg(feature = "fault-injection")] |
| 311 | pub fn with_fault_hook(mut self, hook: Hook) -> Memory { |
| 312 | self.hook = Some(hook); |
| 313 | self |
| 314 | } |
| 315 | |
| 316 | /// Open without recovery, sweeping or writing: safe beside a running writer. |
| 317 | pub fn open_read_only(home: &Path, engaged: Option<&Resolved>) -> Result<Memory, R> { |
| 318 | let r = engaged.ok_or(R::NotEngaged)?; |
| 319 | let m = Memory { |
| 320 | read_only: true, |
| 321 | dir: memory_dir(home), |
| 322 | agent: r.agent, |
| 323 | root: r.root, |
| 324 | #[cfg(feature = "fault-injection")] |
| 325 | hook: None, |
| 326 | }; |
| 327 | m.check_layout()?; |
| 328 | m.replay()?; |
| 329 | Ok(m) |
| 330 | } |
| 331 | |
| 332 | /// Exclusive writer lock (flock on `<store>/lock`), held until dropped. |
| 333 | fn lock(&self) -> Result<std::fs::File, R> { |
| 334 | if self.read_only { |
| 335 | return Err(R::Invalid("this memory was opened read-only".into())); |
| 336 | } |
| 337 | let f = self.lock_file()?; |
| 338 | f.lock().map_err(|e| io("lock", e))?; |
| 339 | Ok(f) |
| 340 | } |
| 341 | |
| 342 | fn lock_file(&self) -> Result<std::fs::File, R> { |
| 343 | std::fs::create_dir_all(&self.dir).map_err(|e| io("create store folder", e))?; |
| 344 | std::fs::OpenOptions::new() |
| 345 | .read(true) |
| 346 | .write(true) |
| 347 | .create(true) |
| 348 | .truncate(false) |
| 349 | .open(self.dir.join("lock")) |
| 350 | .map_err(|e| io("open lock", e)) |
| 351 | } |
| 352 | |
| 353 | pub fn dir(&self) -> &Path { |
| 354 | &self.dir |
| 355 | } |
| 356 | |
| 357 | fn after(&self, step: Step) -> Result<(), R> { |
| 358 | #[cfg(feature = "fault-injection")] |
| 359 | if let Some(h) = &self.hook { |
| 360 | if h(step) { |
| 361 | return Err(R::Crashed(format!("{step:?}"))); |
| 362 | } |
| 363 | } |
| 364 | let _ = step; |
| 365 | Ok(()) |
| 366 | } |
| 367 | |
| 368 | fn log_dir(&self) -> PathBuf { |
| 369 | self.dir.join("log") |
| 370 | } |
| 371 | fn keys_dir(&self) -> PathBuf { |
| 372 | self.dir.join("keys") |
| 373 | } |
| 374 | fn pending_dir(&self) -> PathBuf { |
| 375 | self.dir.join("pending") |
| 376 | } |
| 377 | fn key_path(&self, kid: &str) -> PathBuf { |
| 378 | self.keys_dir().join(format!("{kid}.key")) |
| 379 | } |
| 380 | |
| 381 | // ---------- reading the log ---------- |
| 382 | |
| 383 | fn replay(&self) -> Result<Replay, R> { |
| 384 | let mut rp = Replay { |
| 385 | items: BTreeMap::new(), |
| 386 | head_seq: 0, |
| 387 | head_sha: GENESIS_PREV.to_string(), |
| 388 | }; |
| 389 | let rd = match std::fs::read_dir(self.log_dir()) { |
| 390 | Ok(rd) => rd, |
| 391 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(rp), |
| 392 | Err(e) => return Err(io("read memory log", e)), |
| 393 | }; |
| 394 | let mut nums = Vec::new(); |
| 395 | for ent in rd { |
| 396 | let ent = ent.map_err(|e| io("read memory log", e))?; |
| 397 | let name = ent.file_name().to_string_lossy().into_owned(); |
| 398 | if name.starts_with(".tmp-") { |
| 399 | continue; // a crashed writer's leftover |
| 400 | } |
| 401 | match parse_log_name(&name) { |
| 402 | Some(n) => nums.push(n), |
| 403 | None => return Err(R::Damaged(format!("unexpected file \"{name}\""))), |
| 404 | } |
| 405 | } |
| 406 | nums.sort_unstable(); |
| 407 | if nums.len() as u64 > MAX_RECORDS { |
| 408 | return Err(R::Damaged("too many records".into())); |
| 409 | } |
| 410 | for (i, n) in nums.iter().enumerate() { |
| 411 | if *n != i as u64 + 1 { |
| 412 | return Err(R::Damaged(format!( |
| 413 | "records are not contiguous (found {n} where {} was expected)", |
| 414 | i + 1 |
| 415 | ))); |
| 416 | } |
| 417 | } |
| 418 | let (agent, root) = (hex(&self.agent), hex(&self.root)); |
| 419 | for n in nums { |
| 420 | let path = self.log_dir().join(log_name(n)); |
| 421 | let meta = std::fs::metadata(&path).map_err(|e| io("stat record", e))?; |
| 422 | if meta.len() > MAX_RECORD_BYTES { |
| 423 | return Err(R::Damaged(format!("record {n} is {} bytes", meta.len()))); |
| 424 | } |
| 425 | let bytes = std::fs::read(&path).map_err(|e| io("read record", e))?; |
| 426 | let rec: Record = serde_json::from_slice(&bytes) |
| 427 | .map_err(|e| R::Damaged(format!("record {n}: {e}")))?; |
| 428 | rec.validate() |
| 429 | .map_err(|e| R::Damaged(format!("record {n}: {e}")))?; |
| 430 | if rec.agent != agent || rec.root != root { |
| 431 | return Err(R::ForeignMemory(format!( |
| 432 | "record {n} names agent {}", |
| 433 | &rec.agent[..8] |
| 434 | ))); |
| 435 | } |
| 436 | if rec.seq != n { |
| 437 | return Err(R::Damaged(format!("record {n} says it is {}", rec.seq))); |
| 438 | } |
| 439 | if rec.prev_sha256 != rp.head_sha { |
| 440 | return Err(R::Damaged(format!("record {n} breaks the hash chain"))); |
| 441 | } |
| 442 | apply(&mut rp, &rec).map_err(|e| R::Damaged(format!("record {n}: {e}")))?; |
| 443 | rp.head_seq = n; |
| 444 | rp.head_sha = sha_hex(&bytes); |
| 445 | } |
| 446 | Ok(rp) |
| 447 | } |
| 448 | |
| 449 | fn markers(&self) -> Result<Vec<(PathBuf, Marker)>, R> { |
| 450 | let rd = match std::fs::read_dir(self.pending_dir()) { |
| 451 | Ok(rd) => rd, |
| 452 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), |
| 453 | Err(e) => return Err(io("read pending", e)), |
| 454 | }; |
| 455 | let mut out = Vec::new(); |
| 456 | for ent in rd { |
| 457 | let ent = ent.map_err(|e| io("read pending", e))?; |
| 458 | let name = ent.file_name().to_string_lossy().into_owned(); |
| 459 | if name.starts_with(".tmp-") { |
| 460 | let _ = std::fs::remove_file(ent.path()); |
| 461 | continue; |
| 462 | } |
| 463 | let bytes = std::fs::read(ent.path()).map_err(|e| io("read marker", e))?; |
| 464 | if bytes.len() > 512 { |
| 465 | return Err(R::Damaged(format!("marker {name} is oversize"))); |
| 466 | } |
| 467 | let m: Marker = serde_json::from_slice(&bytes) |
| 468 | .map_err(|e| R::Damaged(format!("marker {name}: {e}")))?; |
| 469 | out.push((ent.path(), m)); |
| 470 | } |
| 471 | out.sort_by(|a, b| a.0.cmp(&b.0)); |
| 472 | Ok(out) |
| 473 | } |
| 474 | |
| 475 | fn marker_covers(markers: &[(PathBuf, Marker)], id: &str, it: &Item) -> bool { |
| 476 | markers.iter().any(|(_, m)| match m { |
| 477 | Marker::Item(i) => i == id, |
| 478 | Marker::Scope(s) => *s == it.scope, |
| 479 | }) |
| 480 | } |
| 481 | |
| 482 | // ---------- crypto and keys ---------- |
| 483 | |
| 484 | fn aad(&self, item: &str, version: u32, scope: &Scope, kind: Kind) -> Vec<u8> { |
| 485 | format!( |
| 486 | "{MEMORY_SCHEMA}|{}|{}|{item}|{version}|{scope}|{}", |
| 487 | hex(&self.agent), |
| 488 | hex(&self.root), |
| 489 | kind.as_str() |
| 490 | ) |
| 491 | .into_bytes() |
| 492 | } |
| 493 | |
| 494 | fn make_key(&self, kid: &str) -> Result<[u8; 32], R> { |
| 495 | let mut key = [0u8; 32]; |
| 496 | SystemRandom::new() |
| 497 | .fill(&mut key) |
| 498 | .map_err(|_| R::Io("random source failed".into()))?; |
| 499 | self.ensure_dirs()?; |
| 500 | // A key file for a version that is not in the log yet can only be an |
| 501 | // orphan of a crashed write (single writer): destroy it, then create. |
| 502 | self.destroy_key(kid)?; |
| 503 | let mut oo = std::fs::OpenOptions::new(); |
| 504 | oo.write(true).create_new(true); |
| 505 | { |
| 506 | use std::os::unix::fs::OpenOptionsExt; |
| 507 | oo.mode(0o600); |
| 508 | } |
| 509 | let mut f = oo |
| 510 | .open(self.key_path(kid)) |
| 511 | .map_err(|e| io("create key", e))?; |
| 512 | f.write_all(&key).map_err(|e| io("write key", e))?; |
| 513 | f.sync_all().map_err(|e| io("fsync key", e))?; |
| 514 | drop(f); |
| 515 | sync_dir(&self.keys_dir())?; |
| 516 | self.after(Step::KeyWritten)?; |
| 517 | Ok(key) |
| 518 | } |
| 519 | |
| 520 | fn seal(&self, key: &[u8; 32], aad: &[u8], text: &str) -> Result<(String, String), R> { |
| 521 | let mut nonce = [0u8; NONCE_LEN]; |
| 522 | SystemRandom::new() |
| 523 | .fill(&mut nonce) |
| 524 | .map_err(|_| R::Io("random source failed".into()))?; |
| 525 | let k = LessSafeKey::new( |
| 526 | UnboundKey::new(&CHACHA20_POLY1305, key).map_err(|_| R::Io("bad key".into()))?, |
| 527 | ); |
| 528 | let mut buf = text.as_bytes().to_vec(); |
| 529 | k.seal_in_place_append_tag( |
| 530 | Nonce::assume_unique_for_key(nonce), |
| 531 | Aad::from(aad), |
| 532 | &mut buf, |
| 533 | ) |
| 534 | .map_err(|_| R::Io("seal failed".into()))?; |
| 535 | Ok((hex(&buf), hex(&nonce))) |
| 536 | } |
| 537 | |
| 538 | /// Err(Ok(status)) shapes are avoided: returns the plaintext or an `ItemStatus::Unresolved` reason. |
| 539 | fn read_text(&self, id: &str, it: &Item, v: &Ver) -> Result<String, ItemStatus> { |
| 540 | let kid = key_id(id, v.version); |
| 541 | let key = match read_key(&self.key_path(&kid)) { |
| 542 | Ok(k) if k.len() == 32 => k, |
| 543 | Ok(_) => return Err(ItemStatus::Unresolved("key damaged".into())), |
| 544 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 545 | return Err(ItemStatus::Unresolved("key missing".into())) |
| 546 | } |
| 547 | Err(_) => return Err(ItemStatus::Unresolved("key unreadable".into())), |
| 548 | }; |
| 549 | let k = LessSafeKey::new( |
| 550 | UnboundKey::new(&CHACHA20_POLY1305, &key) |
| 551 | .map_err(|_| ItemStatus::Unresolved("key damaged".into()))?, |
| 552 | ); |
| 553 | let aad = self.aad(id, v.version, &it.scope, it.kind); |
| 554 | let mut buf = v.ciphertext.clone(); |
| 555 | match k.open_in_place( |
| 556 | Nonce::assume_unique_for_key(v.nonce), |
| 557 | Aad::from(&aad[..]), |
| 558 | &mut buf, |
| 559 | ) { |
| 560 | Ok(p) => String::from_utf8(p.to_vec()) |
| 561 | .map_err(|_| ItemStatus::Unresolved("cannot decrypt".into())), |
| 562 | Err(_) => Err(ItemStatus::Unresolved("cannot decrypt".into())), |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | /// Overwrite with zeros, fsync, unlink. Returns whether a file existed. |
| 567 | fn destroy_key(&self, kid: &str) -> Result<bool, R> { |
| 568 | let p = self.key_path(kid); |
| 569 | let (mut f, len) = match open_regular(&p, true) { |
| 570 | Ok(f) => { |
| 571 | let len = f.metadata().map_err(|e| io("stat key", e))?.len() as usize; |
| 572 | (f, len) |
| 573 | } |
| 574 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), |
| 575 | Err(e) => { |
| 576 | return Err(R::Damaged(format!( |
| 577 | "key file {kid} is not a plain file ({e}); refusing to touch it" |
| 578 | ))) |
| 579 | } |
| 580 | }; |
| 581 | { |
| 582 | f.write_all(&vec![0u8; len]) |
| 583 | .map_err(|e| io("zero key", e))?; |
| 584 | f.sync_all().map_err(|e| io("fsync key", e))?; |
| 585 | } |
| 586 | self.after(Step::KeyZeroed)?; |
| 587 | std::fs::remove_file(&p).map_err(|e| io("unlink key", e))?; |
| 588 | self.after(Step::KeyUnlinked)?; |
| 589 | Ok(true) |
| 590 | } |
| 591 | |
| 592 | fn destroy_keys(&self, kids: &[String]) -> Result<usize, R> { |
| 593 | let mut n = 0; |
| 594 | for k in kids { |
| 595 | if self.destroy_key(k)? { |
| 596 | n += 1; |
| 597 | } |
| 598 | } |
| 599 | if self.keys_dir().exists() { |
| 600 | sync_dir(&self.keys_dir())?; |
| 601 | } |
| 602 | self.after(Step::KeysDestroyed)?; |
| 603 | Ok(n) |
| 604 | } |
| 605 | |
| 606 | fn all_kids(id: &str, it: &Item) -> Vec<String> { |
| 607 | it.versions.iter().map(|v| key_id(id, v.version)).collect() |
| 608 | } |
| 609 | |
| 610 | // ---------- writing ---------- |
| 611 | |
| 612 | fn ensure_dirs(&self) -> Result<(), R> { |
| 613 | for (sub, mode) in [("log", 0o755), ("keys", 0o700), ("pending", 0o755)] { |
| 614 | let p = self.dir.join(sub); |
| 615 | if p.exists() { |
| 616 | continue; |
| 617 | } |
| 618 | std::fs::create_dir_all(&p).map_err(|e| io("create folder", e))?; |
| 619 | #[cfg(unix)] |
| 620 | { |
| 621 | use std::os::unix::fs::PermissionsExt; |
| 622 | std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode)) |
| 623 | .map_err(|e| io("set folder mode", e))?; |
| 624 | } |
| 625 | let _ = mode; |
| 626 | sync_dir(&self.dir)?; |
| 627 | if let Some(parent) = self.dir.parent() { |
| 628 | sync_dir(parent)?; |
| 629 | } |
| 630 | } |
| 631 | Ok(()) |
| 632 | } |
| 633 | |
| 634 | fn append(&self, rp: &Replay, op: Op) -> Result<(), R> { |
| 635 | if rp.head_seq >= MAX_RECORDS { |
| 636 | return Err(R::Invalid("the memory log is full".into())); |
| 637 | } |
| 638 | self.ensure_dirs()?; |
| 639 | let rec = Record { |
| 640 | schema: MEMORY_SCHEMA.into(), |
| 641 | agent: hex(&self.agent), |
| 642 | root: hex(&self.root), |
| 643 | seq: rp.head_seq + 1, |
| 644 | prev_sha256: rp.head_sha.clone(), |
| 645 | at: now_utc(), |
| 646 | op, |
| 647 | }; |
| 648 | let bytes = serde_json::to_vec(&rec).map_err(|e| R::Io(format!("serialize: {e}")))?; |
| 649 | if bytes.len() as u64 > MAX_RECORD_BYTES { |
| 650 | return Err(R::Invalid("record too large".into())); |
| 651 | } |
| 652 | static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 653 | let nanos = std::time::SystemTime::now() |
| 654 | .duration_since(std::time::UNIX_EPOCH) |
| 655 | .map(|d| d.as_nanos()) |
| 656 | .unwrap_or(0); |
| 657 | let tmp = self.log_dir().join(format!( |
| 658 | ".tmp-{}-{}-{nanos}", |
| 659 | std::process::id(), |
| 660 | COUNTER.fetch_add(1, Ordering::SeqCst) |
| 661 | )); |
| 662 | let r = self.append_steps(&tmp, &self.log_dir().join(log_name(rec.seq)), &bytes); |
| 663 | match &r { |
| 664 | Err(R::Crashed(_)) | Ok(()) => {} |
| 665 | Err(_) => { |
| 666 | let _ = std::fs::remove_file(&tmp); |
| 667 | } |
| 668 | } |
| 669 | r |
| 670 | } |
| 671 | |
| 672 | fn append_steps(&self, tmp: &Path, dst: &Path, bytes: &[u8]) -> Result<(), R> { |
| 673 | let mut oo = std::fs::OpenOptions::new(); |
| 674 | oo.write(true).create_new(true); |
| 675 | #[cfg(unix)] |
| 676 | { |
| 677 | use std::os::unix::fs::OpenOptionsExt; |
| 678 | oo.mode(0o600); |
| 679 | } |
| 680 | let mut f = oo.open(tmp).map_err(|e| io("create temp", e))?; |
| 681 | self.after(Step::TempCreated)?; |
| 682 | f.write_all(bytes).map_err(|e| io("write", e))?; |
| 683 | self.after(Step::TempWritten)?; |
| 684 | f.sync_all().map_err(|e| io("fsync", e))?; |
| 685 | drop(f); |
| 686 | self.after(Step::TempSynced)?; |
| 687 | match std::fs::hard_link(tmp, dst) { |
| 688 | Ok(()) => {} |
| 689 | Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { |
| 690 | let _ = std::fs::remove_file(tmp); |
| 691 | return Err(R::Conflict); |
| 692 | } |
| 693 | Err(e) => return Err(io("link record", e)), |
| 694 | } |
| 695 | self.after(Step::Linked)?; |
| 696 | sync_dir(&self.log_dir())?; |
| 697 | self.after(Step::DirSynced)?; |
| 698 | std::fs::remove_file(tmp).map_err(|e| io("remove temp", e))?; |
| 699 | self.after(Step::TempRemoved)?; |
| 700 | Ok(()) |
| 701 | } |
| 702 | |
| 703 | fn write_marker(&self, m: &Marker) -> Result<PathBuf, R> { |
| 704 | self.ensure_dirs()?; |
| 705 | let name = format!("forget-{}.json", rand_hex(8)?); |
| 706 | let (tmp, dst) = ( |
| 707 | self.pending_dir().join(format!(".tmp-{name}")), |
| 708 | self.pending_dir().join(&name), |
| 709 | ); |
| 710 | let mut oo = std::fs::OpenOptions::new(); |
| 711 | oo.write(true).create(true).truncate(true); |
| 712 | { |
| 713 | use std::os::unix::fs::OpenOptionsExt; |
| 714 | oo.mode(0o600); |
| 715 | } |
| 716 | let mut f = oo.open(&tmp).map_err(|e| io("create marker", e))?; |
| 717 | f.write_all(&serde_json::to_vec(m).map_err(|e| R::Io(e.to_string()))?) |
| 718 | .map_err(|e| io("write marker", e))?; |
| 719 | f.sync_all().map_err(|e| io("fsync marker", e))?; |
| 720 | drop(f); |
| 721 | std::fs::rename(&tmp, &dst).map_err(|e| io("rename marker", e))?; |
| 722 | sync_dir(&self.pending_dir())?; |
| 723 | self.after(Step::MarkerWritten)?; |
| 724 | Ok(dst) |
| 725 | } |
| 726 | |
| 727 | fn remove_marker(&self, p: &Path) -> Result<(), R> { |
| 728 | std::fs::remove_file(p).map_err(|e| io("remove marker", e))?; |
| 729 | sync_dir(&self.pending_dir())?; |
| 730 | self.after(Step::MarkerRemoved) |
| 731 | } |
| 732 | |
| 733 | // ---------- recovery ---------- |
| 734 | |
| 735 | /// Destroy any key whose item has a Forget record, any key of a |
| 736 | /// superseded version, and any orphan key no record refers to. Idempotent; returns how many key files it removed. |
| 737 | /// Run on every open, so restoring an old copy of `keys/` cannot bring |
| 738 | /// forgotten content back once the log is intact. |
| 739 | pub fn reapply_forgets(&self) -> Result<usize, R> { |
| 740 | let _g = self.lock()?; |
| 741 | self.reapply_inner() |
| 742 | } |
| 743 | |
| 744 | fn reapply_inner(&self) -> Result<usize, R> { |
| 745 | let rp = self.replay()?; |
| 746 | let mut keep = std::collections::BTreeSet::new(); |
| 747 | for (id, it) in &rp.items { |
| 748 | if !it.forgotten { |
| 749 | keep.insert(key_id(id, it.current().version)); |
| 750 | } |
| 751 | } |
| 752 | let rd = match std::fs::read_dir(self.keys_dir()) { |
| 753 | Ok(rd) => rd, |
| 754 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0), |
| 755 | Err(e) => return Err(io("read keys folder", e)), |
| 756 | }; |
| 757 | let mut kids = Vec::new(); |
| 758 | for ent in rd { |
| 759 | let name = ent |
| 760 | .map_err(|e| io("read keys folder", e))? |
| 761 | .file_name() |
| 762 | .to_string_lossy() |
| 763 | .into_owned(); |
| 764 | if let Some(kid) = name.strip_suffix(".key") { |
| 765 | if !keep.contains(kid) { |
| 766 | kids.push(kid.to_string()); |
| 767 | } |
| 768 | } |
| 769 | } |
| 770 | kids.sort(); |
| 771 | self.destroy_keys(&kids) |
| 772 | } |
| 773 | |
| 774 | fn check_layout(&self) -> Result<(), R> { |
| 775 | check_dir(&self.dir, false)?; |
| 776 | check_dir(&self.log_dir(), false)?; |
| 777 | check_dir(&self.keys_dir(), true)?; |
| 778 | check_dir(&self.pending_dir(), false) |
| 779 | } |
| 780 | |
| 781 | fn recover(&self) -> Result<(), R> { |
| 782 | self.check_layout()?; |
| 783 | // Sweeping and finishing forgets need the writer lock. If another process |
| 784 | // holds it, it may be mid-write: only verify, change nothing. |
| 785 | let _guard = match self.lock_file() { |
| 786 | Ok(f) if f.try_lock().is_ok() => f, |
| 787 | _ => { |
| 788 | self.replay()?; |
| 789 | return Ok(()); |
| 790 | } |
| 791 | }; |
| 792 | // Leftovers of a crashed append (single writer: none can be in flight now). |
| 793 | if let Ok(rd) = std::fs::read_dir(self.log_dir()) { |
| 794 | for ent in rd.flatten() { |
| 795 | if ent.file_name().to_string_lossy().starts_with(".tmp-") { |
| 796 | let _ = std::fs::remove_file(ent.path()); |
| 797 | } |
| 798 | } |
| 799 | } |
| 800 | // Finish interrupted forgets: destroy keys, append the record, drop the marker. |
| 801 | for (path, m) in self.markers()? { |
| 802 | let rp = self.replay()?; |
| 803 | let mut kids = Vec::new(); |
| 804 | let mut need_record: Vec<(String, Scope)> = Vec::new(); |
| 805 | for (id, it) in &rp.items { |
| 806 | let hit = match &m { |
| 807 | Marker::Item(i) => i == id, |
| 808 | Marker::Scope(s) => *s == it.scope, |
| 809 | }; |
| 810 | if hit { |
| 811 | kids.extend(Memory::all_kids(id, it)); |
| 812 | if !it.forgotten { |
| 813 | need_record.push((id.clone(), it.scope.clone())); |
| 814 | } |
| 815 | } |
| 816 | } |
| 817 | if self.keys_dir().exists() { |
| 818 | self.destroy_keys(&kids)?; |
| 819 | } |
| 820 | match &m { |
| 821 | Marker::Scope(s) if !need_record.is_empty() => { |
| 822 | self.append(&rp, Op::ForgetScope { scope: s.clone() })?; |
| 823 | } |
| 824 | Marker::Item(i) if !need_record.is_empty() => { |
| 825 | self.append( |
| 826 | &rp, |
| 827 | Op::ForgetItem { |
| 828 | item: i.clone(), |
| 829 | scope: need_record[0].1.clone(), |
| 830 | }, |
| 831 | )?; |
| 832 | } |
| 833 | _ => {} |
| 834 | } |
| 835 | self.remove_marker(&path)?; |
| 836 | } |
| 837 | self.replay()?; // verify the log even when nothing is pending |
| 838 | self.reapply_inner()?; |
| 839 | Ok(()) |
| 840 | } |
| 841 | |
| 842 | // ---------- public operations ---------- |
| 843 | |
| 844 | fn check_text(text: &str) -> Result<(), R> { |
| 845 | if text.trim().is_empty() { |
| 846 | return Err(R::Invalid("empty content".into())); |
| 847 | } |
| 848 | if text.len() > MAX_TEXT_BYTES { |
| 849 | return Err(R::Invalid(format!( |
| 850 | "content is {} bytes (limit {MAX_TEXT_BYTES})", |
| 851 | text.len() |
| 852 | ))); |
| 853 | } |
| 854 | Ok(()) |
| 855 | } |
| 856 | |
| 857 | /// Store a new item; returns its id. |
| 858 | pub fn put(&self, scope: Scope, kind: Kind, text: &str) -> Result<String, R> { |
| 859 | Memory::check_text(text)?; |
| 860 | let _g = self.lock()?; |
| 861 | let rp = self.replay()?; |
| 862 | let item = rand_hex(16)?; |
| 863 | let kid = key_id(&item, 1); |
| 864 | let key = self.make_key(&kid)?; |
| 865 | let (ciphertext, nonce) = self.seal(&key, &self.aad(&item, 1, &scope, kind), text)?; |
| 866 | self.append( |
| 867 | &rp, |
| 868 | Op::Put { |
| 869 | item: item.clone(), |
| 870 | scope, |
| 871 | kind, |
| 872 | version: 1, |
| 873 | ciphertext, |
| 874 | nonce, |
| 875 | key_id: kid, |
| 876 | }, |
| 877 | )?; |
| 878 | Ok(item) |
| 879 | } |
| 880 | |
| 881 | /// Write a new version and destroy the superseded version's key. |
| 882 | pub fn correct<'a>( |
| 883 | &self, |
| 884 | auth: impl Into<Authority<'a>>, |
| 885 | item: &str, |
| 886 | text: &str, |
| 887 | ) -> Result<u32, R> { |
| 888 | Memory::check_text(text)?; |
| 889 | let _g = self.lock()?; |
| 890 | let rp = self.replay()?; |
| 891 | let it = rp |
| 892 | .items |
| 893 | .get(item) |
| 894 | .ok_or_else(|| R::UnknownItem(item.into()))?; |
| 895 | auth.into().check(item, &it.scope)?; |
| 896 | let markers = self.markers()?; |
| 897 | if it.forgotten || Memory::marker_covers(&markers, item, it) { |
| 898 | return Err(R::ItemForgotten(item.into())); |
| 899 | } |
| 900 | let old = it.current().version; |
| 901 | let new = old + 1; |
| 902 | let kid = key_id(item, new); |
| 903 | let key = self.make_key(&kid)?; |
| 904 | let (ciphertext, nonce) = |
| 905 | self.seal(&key, &self.aad(item, new, &it.scope, it.kind), text)?; |
| 906 | self.append( |
| 907 | &rp, |
| 908 | Op::Correct { |
| 909 | item: item.into(), |
| 910 | supersedes_version: old, |
| 911 | version: new, |
| 912 | ciphertext, |
| 913 | nonce, |
| 914 | key_id: kid, |
| 915 | }, |
| 916 | )?; |
| 917 | self.destroy_keys(&[key_id(item, old)])?; |
| 918 | self.after(Step::SupersededKeyDestroyed)?; |
| 919 | Ok(new) |
| 920 | } |
| 921 | |
| 922 | /// Forget an item or a whole scope. Order: intent marker, destroy keys |
| 923 | /// (zero, fsync, unlink, fsync dir), append Forget record, drop marker. |
| 924 | /// Returns the ids forgotten. |
| 925 | pub fn forget<'a>( |
| 926 | &self, |
| 927 | auth: impl Into<Authority<'a>>, |
| 928 | target: ForgetTarget, |
| 929 | ) -> Result<Vec<String>, R> { |
| 930 | let _g = self.lock()?; |
| 931 | let rp = self.replay()?; |
| 932 | let auth = auth.into(); |
| 933 | let (marker, ids, op) = match &target { |
| 934 | ForgetTarget::Item(i) => { |
| 935 | let it = rp.items.get(i).ok_or_else(|| R::UnknownItem(i.clone()))?; |
| 936 | auth.check(i, &it.scope)?; |
| 937 | if it.forgotten { |
| 938 | return Err(R::NothingToForget); |
| 939 | } |
| 940 | ( |
| 941 | Marker::Item(i.clone()), |
| 942 | vec![i.clone()], |
| 943 | Op::ForgetItem { |
| 944 | item: i.clone(), |
| 945 | scope: it.scope.clone(), |
| 946 | }, |
| 947 | ) |
| 948 | } |
| 949 | ForgetTarget::Scope(s) => { |
| 950 | auth.check("(scope)", s)?; |
| 951 | let ids: Vec<String> = rp |
| 952 | .items |
| 953 | .iter() |
| 954 | .filter(|(_, it)| it.scope == *s && !it.forgotten) |
| 955 | .map(|(i, _)| i.clone()) |
| 956 | .collect(); |
| 957 | if ids.is_empty() { |
| 958 | return Err(R::NothingToForget); |
| 959 | } |
| 960 | ( |
| 961 | Marker::Scope(s.clone()), |
| 962 | ids, |
| 963 | Op::ForgetScope { scope: s.clone() }, |
| 964 | ) |
| 965 | } |
| 966 | }; |
| 967 | let kids: Vec<String> = ids |
| 968 | .iter() |
| 969 | .flat_map(|i| Memory::all_kids(i, &rp.items[i])) |
| 970 | .collect(); |
| 971 | let mpath = self.write_marker(&marker)?; |
| 972 | if self.keys_dir().exists() { |
| 973 | self.destroy_keys(&kids)?; |
| 974 | } |
| 975 | self.append(&rp, op)?; |
| 976 | self.after(Step::ForgetRecorded)?; |
| 977 | self.remove_marker(&mpath)?; |
| 978 | Ok(ids) |
| 979 | } |
| 980 | |
| 981 | /// Mark a goal closed. Its content stays readable (the key is kept). |
| 982 | pub fn close_goal<'a>(&self, auth: impl Into<Authority<'a>>, item: &str) -> Result<(), R> { |
| 983 | let _g = self.lock()?; |
| 984 | let rp = self.replay()?; |
| 985 | let it = rp |
| 986 | .items |
| 987 | .get(item) |
| 988 | .ok_or_else(|| R::UnknownItem(item.into()))?; |
| 989 | auth.into().check(item, &it.scope)?; |
| 990 | if it.kind != Kind::Goal { |
| 991 | return Err(R::NotAGoal(item.into())); |
| 992 | } |
| 993 | if it.forgotten { |
| 994 | return Err(R::ItemForgotten(item.into())); |
| 995 | } |
| 996 | if it.closed { |
| 997 | return Err(R::Invalid("goal is already closed".into())); |
| 998 | } |
| 999 | self.append(&rp, Op::GoalClose { item: item.into() }) |
| 1000 | } |
| 1001 | |
| 1002 | fn views(&self, only: Option<&Scope>) -> Result<Vec<ItemView>, R> { |
| 1003 | let rp = self.replay()?; |
| 1004 | let markers = self.markers()?; |
| 1005 | let mut order: Vec<(&String, &Item)> = rp |
| 1006 | .items |
| 1007 | .iter() |
| 1008 | .filter(|(_, it)| only.is_none_or(|s| *s == it.scope)) |
| 1009 | .collect(); |
| 1010 | order.sort_by(|a, b| (a.1.created_seq, a.0).cmp(&(b.1.created_seq, b.0))); |
| 1011 | let mut out = Vec::new(); |
| 1012 | for (id, it) in order { |
| 1013 | let label = (it.kind == Kind::Goal).then_some(GOAL_LABEL); |
| 1014 | let mk = |v: &Ver, st: ItemStatus, text: Option<String>| ItemView { |
| 1015 | item: id.clone(), |
| 1016 | scope: it.scope.to_string(), |
| 1017 | kind: it.kind, |
| 1018 | version: v.version, |
| 1019 | created: v.at.clone(), |
| 1020 | state: st.text(), |
| 1021 | text, |
| 1022 | label, |
| 1023 | status: Some(st), |
| 1024 | }; |
| 1025 | let cur = it.current(); |
| 1026 | if it.forgotten { |
| 1027 | out.push(mk(cur, ItemStatus::Forgotten, None)); |
| 1028 | continue; |
| 1029 | } |
| 1030 | for v in &it.versions[..it.versions.len() - 1] { |
| 1031 | out.push(mk(v, ItemStatus::Corrected, None)); |
| 1032 | } |
| 1033 | if Memory::marker_covers(&markers, id, it) { |
| 1034 | let gone = !self.key_path(&key_id(id, cur.version)).exists(); |
| 1035 | out.push(mk( |
| 1036 | cur, |
| 1037 | ItemStatus::ForgottenPending { key_missing: gone }, |
| 1038 | None, |
| 1039 | )); |
| 1040 | continue; |
| 1041 | } |
| 1042 | match self.read_text(id, it, cur) { |
| 1043 | Ok(t) => { |
| 1044 | let st = if it.closed { |
| 1045 | ItemStatus::Closed |
| 1046 | } else { |
| 1047 | ItemStatus::Live |
| 1048 | }; |
| 1049 | out.push(mk(cur, st, Some(t))); |
| 1050 | } |
| 1051 | Err(st) => out.push(mk(cur, st, None)), |
| 1052 | } |
| 1053 | } |
| 1054 | Ok(out) |
| 1055 | } |
| 1056 | |
| 1057 | /// Owner-facing: every item in one scope, with its state. |
| 1058 | pub fn inspect(&self, grant: &ScopeGrant) -> Result<Vec<ItemView>, R> { |
| 1059 | self.views(Some(&grant.scope)) |
| 1060 | } |
| 1061 | |
| 1062 | /// Owner-facing: every item in every scope. |
| 1063 | pub fn inspect_all(&self, _all: &InspectAll) -> Result<Vec<ItemView>, R> { |
| 1064 | self.views(None) |
| 1065 | } |
| 1066 | |
| 1067 | /// Context assembly. Returns only items in the granted scope whose content |
| 1068 | /// is live (open goals included, closed goals excluded). `query`, if given, |
| 1069 | /// is a case-insensitive substring filter on the plaintext; it can never |
| 1070 | /// widen the scope. Deterministic order (creation order, then id), bounded |
| 1071 | /// by `limits`. A missing key is listed in `unresolved`; a failed integrity |
| 1072 | /// check is an error. |
| 1073 | pub fn recall( |
| 1074 | &self, |
| 1075 | grant: &ScopeGrant, |
| 1076 | query: Option<&str>, |
| 1077 | limits: &RecallLimits, |
| 1078 | ) -> Result<Recall, R> { |
| 1079 | let rp = self.replay()?; |
| 1080 | let markers = self.markers()?; |
| 1081 | let mut order: Vec<(&String, &Item)> = rp |
| 1082 | .items |
| 1083 | .iter() |
| 1084 | .filter(|(_, it)| it.scope == grant.scope && !it.forgotten && !it.closed) |
| 1085 | .collect(); |
| 1086 | order.sort_by(|a, b| (a.1.created_seq, a.0).cmp(&(b.1.created_seq, b.0))); |
| 1087 | let q = query.map(|q| q.to_lowercase()); |
| 1088 | let mut rc = Recall { |
| 1089 | scope: grant.scope.clone(), |
| 1090 | items: Vec::new(), |
| 1091 | omitted: 0, |
| 1092 | unresolved: Vec::new(), |
| 1093 | }; |
| 1094 | let (mut bytes, mut full) = (0usize, false); |
| 1095 | for (id, it) in order { |
| 1096 | if Memory::marker_covers(&markers, id, it) { |
| 1097 | continue; |
| 1098 | } |
| 1099 | let cur = it.current(); |
| 1100 | let text = match self.read_text(id, it, cur) { |
| 1101 | Ok(t) => t, |
| 1102 | Err(ItemStatus::Unresolved(w)) if w == "cannot decrypt" => { |
| 1103 | return Err(R::Tampered(id.clone())) |
| 1104 | } |
| 1105 | Err(_) => { |
| 1106 | rc.unresolved.push(id.clone()); |
| 1107 | continue; |
| 1108 | } |
| 1109 | }; |
| 1110 | if q.as_ref().is_some_and(|q| !text.to_lowercase().contains(q)) { |
| 1111 | continue; |
| 1112 | } |
| 1113 | if full || rc.items.len() >= limits.max_items || bytes + text.len() > limits.max_bytes { |
| 1114 | full = true; |
| 1115 | rc.omitted += 1; |
| 1116 | continue; |
| 1117 | } |
| 1118 | bytes += text.len(); |
| 1119 | rc.items.push(ItemView { |
| 1120 | item: id.clone(), |
| 1121 | scope: it.scope.to_string(), |
| 1122 | kind: it.kind, |
| 1123 | version: cur.version, |
| 1124 | created: cur.at.clone(), |
| 1125 | state: ItemStatus::Live.text(), |
| 1126 | text: Some(text), |
| 1127 | label: (it.kind == Kind::Goal).then_some(GOAL_LABEL), |
| 1128 | status: Some(ItemStatus::Live), |
| 1129 | }); |
| 1130 | } |
| 1131 | Ok(rc) |
| 1132 | } |
| 1133 | |
| 1134 | /// JSON of the live (and closed) items' plaintext in one scope, for the owner. |
| 1135 | pub fn export(&self, grant: &ScopeGrant) -> Result<String, R> { |
| 1136 | let items: Vec<ItemView> = self |
| 1137 | .views(Some(&grant.scope))? |
| 1138 | .into_iter() |
| 1139 | .filter(|v| matches!(v.status, Some(ItemStatus::Live | ItemStatus::Closed))) |
| 1140 | .collect(); |
| 1141 | serde_json::to_string_pretty(&serde_json::json!({ |
| 1142 | "schema": "aien.allen.memory.export/1", |
| 1143 | "scope": grant.scope.to_string(), |
| 1144 | "items": items, |
| 1145 | })) |
| 1146 | .map_err(|e| R::Io(e.to_string())) |
| 1147 | } |
| 1148 | |
| 1149 | fn goal_list(&self, only: Option<&Scope>) -> Result<GoalList, R> { |
| 1150 | let goals = self |
| 1151 | .views(only)? |
| 1152 | .into_iter() |
| 1153 | .filter(|v| { |
| 1154 | v.kind == Kind::Goal |
| 1155 | && matches!(v.status, Some(ItemStatus::Live | ItemStatus::Closed)) |
| 1156 | }) |
| 1157 | .map(|v| GoalView { |
| 1158 | item: v.item, |
| 1159 | scope: v.scope, |
| 1160 | text: v.text.unwrap_or_default(), |
| 1161 | created: v.created, |
| 1162 | state: if v.status == Some(ItemStatus::Closed) { |
| 1163 | "closed" |
| 1164 | } else { |
| 1165 | "open" |
| 1166 | }, |
| 1167 | label: GOAL_LABEL, |
| 1168 | }) |
| 1169 | .collect(); |
| 1170 | Ok(GoalList { |
| 1171 | label: GOAL_LABEL, |
| 1172 | goals, |
| 1173 | }) |
| 1174 | } |
| 1175 | |
| 1176 | /// Host standing goals in one scope. Not subject intents. |
| 1177 | pub fn goals(&self, grant: &ScopeGrant) -> Result<GoalList, R> { |
| 1178 | self.goal_list(Some(&grant.scope)) |
| 1179 | } |
| 1180 | |
| 1181 | /// Host standing goals in every scope (owner-facing). |
| 1182 | pub fn goals_all(&self, _all: &InspectAll) -> Result<GoalList, R> { |
| 1183 | self.goal_list(None) |
| 1184 | } |
| 1185 | } |
| 1186 | |
| 1187 | fn apply(rp: &mut Replay, rec: &Record) -> Result<(), String> { |
| 1188 | let nonce_of = |s: &str| -> Result<[u8; NONCE_LEN], String> { |
| 1189 | unhex(s) |
| 1190 | .and_then(|v| v.try_into().ok()) |
| 1191 | .ok_or_else(|| "bad nonce".to_string()) |
| 1192 | }; |
| 1193 | let ct_of = |s: &str| unhex(s).ok_or_else(|| "bad ciphertext".to_string()); |
| 1194 | match &rec.op { |
| 1195 | Op::Put { |
| 1196 | item, |
| 1197 | scope, |
| 1198 | kind, |
| 1199 | version, |
| 1200 | ciphertext, |
| 1201 | nonce, |
| 1202 | .. |
| 1203 | } => { |
| 1204 | if rp.items.contains_key(item) { |
| 1205 | return Err("item put twice".into()); |
| 1206 | } |
| 1207 | rp.items.insert( |
| 1208 | item.clone(), |
| 1209 | Item { |
| 1210 | scope: scope.clone(), |
| 1211 | kind: *kind, |
| 1212 | created_seq: rec.seq, |
| 1213 | versions: vec![Ver { |
| 1214 | version: *version, |
| 1215 | at: rec.at.clone(), |
| 1216 | ciphertext: ct_of(ciphertext)?, |
| 1217 | nonce: nonce_of(nonce)?, |
| 1218 | }], |
| 1219 | forgotten: false, |
| 1220 | closed: false, |
| 1221 | }, |
| 1222 | ); |
| 1223 | } |
| 1224 | Op::Correct { |
| 1225 | item, |
| 1226 | supersedes_version, |
| 1227 | version, |
| 1228 | ciphertext, |
| 1229 | nonce, |
| 1230 | .. |
| 1231 | } => { |
| 1232 | let it = rp.items.get_mut(item).ok_or("correct of unknown item")?; |
| 1233 | if it.forgotten || it.current().version != *supersedes_version { |
| 1234 | return Err("correct does not follow the current version".into()); |
| 1235 | } |
| 1236 | it.versions.push(Ver { |
| 1237 | version: *version, |
| 1238 | at: rec.at.clone(), |
| 1239 | ciphertext: ct_of(ciphertext)?, |
| 1240 | nonce: nonce_of(nonce)?, |
| 1241 | }); |
| 1242 | } |
| 1243 | Op::ForgetItem { item, scope } => { |
| 1244 | let it = rp.items.get_mut(item).ok_or("forget of unknown item")?; |
| 1245 | if it.scope != *scope { |
| 1246 | return Err("forget names the wrong scope".into()); |
| 1247 | } |
| 1248 | it.forgotten = true; |
| 1249 | } |
| 1250 | Op::ForgetScope { scope } => { |
| 1251 | for it in rp.items.values_mut().filter(|i| i.scope == *scope) { |
| 1252 | it.forgotten = true; |
| 1253 | } |
| 1254 | } |
| 1255 | Op::GoalClose { item } => { |
| 1256 | let it = rp.items.get_mut(item).ok_or("close of unknown item")?; |
| 1257 | if it.kind != Kind::Goal || it.forgotten { |
| 1258 | return Err("close of a non-goal or forgotten item".into()); |
| 1259 | } |
| 1260 | it.closed = true; |
| 1261 | } |
| 1262 | } |
| 1263 | Ok(()) |
| 1264 | } |
| 1265 | |
| 1266 | /// Open an existing regular file without following a symlink: lstat must say |
| 1267 | /// "regular file" and the opened handle must be the same inode (no swap race). |
| 1268 | fn open_regular(path: &Path, write: bool) -> std::io::Result<std::fs::File> { |
| 1269 | open_regular_with(path, write, || {}) |
| 1270 | } |
| 1271 | |
| 1272 | /// `between` runs after the lstat and before the open (test seam for the swap race). |
| 1273 | fn open_regular_with( |
| 1274 | path: &Path, |
| 1275 | write: bool, |
| 1276 | between: impl FnOnce(), |
| 1277 | ) -> std::io::Result<std::fs::File> { |
| 1278 | use std::os::unix::fs::MetadataExt; |
| 1279 | let bad = |w: &str| std::io::Error::new(std::io::ErrorKind::PermissionDenied, w.to_string()); |
| 1280 | let l = std::fs::symlink_metadata(path)?; |
| 1281 | if !l.file_type().is_file() { |
| 1282 | return Err(bad("not a regular file")); |
| 1283 | } |
| 1284 | between(); |
| 1285 | let f = std::fs::OpenOptions::new() |
| 1286 | .read(true) |
| 1287 | .write(write) |
| 1288 | .open(path)?; |
| 1289 | let m = f.metadata()?; |
| 1290 | if m.dev() != l.dev() || m.ino() != l.ino() { |
| 1291 | return Err(bad("file changed while opening")); |
| 1292 | } |
| 1293 | Ok(f) |
| 1294 | } |
| 1295 | |
| 1296 | fn read_key(path: &Path) -> std::io::Result<Vec<u8>> { |
| 1297 | use std::io::Read; |
| 1298 | let mut b = Vec::new(); |
| 1299 | open_regular(path, false)?.take(65).read_to_end(&mut b)?; |
| 1300 | Ok(b) |
| 1301 | } |
| 1302 | |
| 1303 | /// A real directory (not a symlink), mode 0700 when `private`; looser modes |
| 1304 | /// are tightened. |
| 1305 | fn check_dir(p: &Path, private: bool) -> Result<(), R> { |
| 1306 | use std::os::unix::fs::PermissionsExt; |
| 1307 | let m = match std::fs::symlink_metadata(p) { |
| 1308 | Ok(m) => m, |
| 1309 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), |
| 1310 | Err(e) => return Err(io("stat folder", e)), |
| 1311 | }; |
| 1312 | if !m.file_type().is_dir() { |
| 1313 | return Err(R::Damaged(format!( |
| 1314 | "{} is not a plain folder (symlink or file)", |
| 1315 | p.display() |
| 1316 | ))); |
| 1317 | } |
| 1318 | if private && m.permissions().mode() & 0o077 != 0 { |
| 1319 | std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o700)) |
| 1320 | .map_err(|e| io("tighten folder mode", e))?; |
| 1321 | } |
| 1322 | Ok(()) |
| 1323 | } |
| 1324 | |
| 1325 | #[cfg(test)] |
| 1326 | mod tests { |
| 1327 | use super::*; |
| 1328 | |
| 1329 | #[test] |
| 1330 | fn open_regular_refuses_a_file_swapped_between_lstat_and_open() { |
| 1331 | let d = std::env::temp_dir().join(format!("aienmem-swap-{}", std::process::id())); |
| 1332 | let _ = std::fs::remove_dir_all(&d); |
| 1333 | std::fs::create_dir_all(&d).unwrap(); |
| 1334 | let (a, b) = (d.join("a"), d.join("b")); |
| 1335 | std::fs::write(&a, b"original").unwrap(); |
| 1336 | std::fs::write(&b, b"other inode").unwrap(); |
| 1337 | let r = open_regular_with(&a, false, || { |
| 1338 | std::fs::rename(&b, &a).unwrap(); // a now names a different inode |
| 1339 | }); |
| 1340 | assert_eq!(r.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied); |
| 1341 | // no swap: opens fine; symlink: refused |
| 1342 | std::fs::write(d.join("c"), b"x").unwrap(); |
| 1343 | assert!(open_regular(&d.join("c"), false).is_ok()); |
| 1344 | std::os::unix::fs::symlink(d.join("c"), d.join("l")).unwrap(); |
| 1345 | assert!(open_regular(&d.join("l"), false).is_err()); |
| 1346 | let _ = std::fs::remove_dir_all(&d); |
| 1347 | } |
| 1348 | } |