1use super::delivered::{self, Lineage, LineageRefusal};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct RecoveryId(String);
28
29impl RecoveryId {
30 #[must_use]
33 pub fn parse(id: &str) -> Option<Self> {
34 (id.len() == 64
35 && id
36 .bytes()
37 .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()))
38 .then(|| Self(id.to_owned()))
39 }
40
41 #[must_use]
42 pub fn as_str(&self) -> &str {
43 &self.0
44 }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum RecoveryRefusal {
50 UnknownLineage,
52 SourceNotPresented,
54 SourceNoLongerAdmitted,
57 NotStorable,
60 Missing,
62}
63
64impl From<LineageRefusal> for RecoveryRefusal {
65 fn from(refusal: LineageRefusal) -> Self {
66 match refusal {
67 LineageRefusal::Unknown => Self::UnknownLineage,
68 LineageRefusal::SourceNotPresented => Self::SourceNotPresented,
69 LineageRefusal::SourceNoLongerAdmitted => Self::SourceNoLongerAdmitted,
70 }
71 }
72}
73
74impl std::fmt::Display for RecoveryRefusal {
75 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 formatter.write_str(match self {
77 Self::UnknownLineage => "recovery.unknown_lineage",
78 Self::SourceNotPresented => "recovery.source_not_presented",
79 Self::SourceNoLongerAdmitted => "recovery.source_no_longer_admitted",
80 Self::NotStorable => "recovery.not_storable",
81 Self::Missing => "recovery.missing",
82 })
83 }
84}
85
86fn storable_exactly(original: &str) -> bool {
91 !original.is_empty()
92 && original.len() <= super::MAX_ARCHIVE_SIZE
93 && crate::core::policy::content::protect_active(original)
94 .is_ok_and(|protected| &*protected == original)
95 && crate::core::context_admission::recovery::admit_for_storage(original)
96 .is_some_and(|admitted| admitted == original)
97}
98
99fn lineage_id(lineage: &Lineage, content: &str) -> Option<String> {
100 let mut hash = blake3::Hasher::new();
101 hash.update(b"leanctx-lineage-archive-v1\0");
102 hash.update(lineage.identity_digest()?.as_bytes());
103 hash.update(b"\0");
104 hash.update(content.as_bytes());
105 Some(hash.finalize().to_hex().to_string())
106}
107
108pub fn store_recovery_with_lineage(
115 original: &str,
116 lineage: &Lineage,
117) -> Result<RecoveryId, RecoveryRefusal> {
118 lineage.still_admitted()?;
119 let storable = crate::core::policy::runtime::with_source_view(|| storable_exactly(original))
120 .unwrap_or(false);
121 if !storable || !super::is_enabled() {
122 return Err(RecoveryRefusal::NotStorable);
123 }
124 if let Some(files) = lineage.files_only() {
125 return super::store_with_authority(
126 "recovery",
127 "recovery-copy",
128 original,
129 None,
130 Some(files),
131 )
132 .filter(|stored| !stored.truncated)
133 .and_then(|stored| RecoveryId::parse(&stored.id))
134 .inspect(issued)
135 .ok_or(RecoveryRefusal::NotStorable);
136 }
137 let id = lineage_id(lineage, original).ok_or(RecoveryRefusal::UnknownLineage)?;
138 let stored = super::with_archive_lock(|| {
139 let content_path = super::content_path(&id);
140 if content_path.exists() && super::meta_path(&id).exists() {
141 return Some(());
142 }
143 std::fs::create_dir_all(super::entry_dir(&id)).ok()?;
144 if !content_path.exists() {
145 crate::core::atomic_fs::try_atomic_write(&content_path, original.as_bytes(), None)
146 .ok()?;
147 #[cfg(unix)]
148 super::set_private_file_perms(&content_path);
149 }
150 let mut entry = super::new_entry(
153 &id,
154 "recovery",
155 "recovery-copy",
156 original,
157 None,
158 lean_ctx_time::UtcDateTime::now(),
159 );
160 entry.lineage = Some(lineage.recorded_for_presenter());
163 if super::write_metadata(&entry).is_none() {
164 let _ = std::fs::remove_file(content_path);
165 return None;
166 }
167 Some(())
168 })
169 .flatten();
170 match stored {
171 Some(()) => RecoveryId::parse(&id)
172 .inspect(issued)
173 .ok_or(RecoveryRefusal::NotStorable),
174 None => Err(RecoveryRefusal::NotStorable),
175 }
176}
177
178fn issued(id: &RecoveryId) {
182 crate::core::context_admission::receipt_store::references::note_recovery(id.as_str());
183}
184
185pub fn retrieve_recovery_checked(id: &RecoveryId) -> Result<String, RecoveryRefusal> {
191 let entry = super::read_entry(id.as_str()).ok_or(RecoveryRefusal::Missing)?;
192 let Some(lineage) = entry.lineage else {
193 if entry.authority.is_none() {
197 return Err(RecoveryRefusal::UnknownLineage);
198 }
199 return super::retrieve_checked(id.as_str()).map_err(|error| match error {
200 super::ArchiveResolveError::Refused(_) => RecoveryRefusal::SourceNoLongerAdmitted,
201 super::ArchiveResolveError::Missing | super::ArchiveResolveError::Malformed => {
202 RecoveryRefusal::Missing
203 }
204 });
205 };
206 lineage.still_admitted()?;
207 let content = crate::core::atomic_fs::read_store_file(
208 &super::archive_base_dir(),
209 &super::content_path(id.as_str()),
210 )
211 .map_err(|_| RecoveryRefusal::Missing)?;
212 if content.len() > super::MAX_ARCHIVE_SIZE
213 || lineage_id(&lineage, &content).as_deref() != Some(id.as_str())
214 {
215 return Err(RecoveryRefusal::Missing);
217 }
218 let released = crate::core::policy::runtime::with_source_view(|| {
221 crate::core::policy::content::protect_active(&content)
222 .is_ok_and(|protected| *protected == content)
223 && readmitted(id, &content)
224 })
225 .unwrap_or(false);
226 if !released {
227 return Err(RecoveryRefusal::SourceNoLongerAdmitted);
228 }
229 delivered::record_lineage(&delivered::digest(&content), &lineage);
230 Ok(content)
231}
232
233fn readmitted(id: &RecoveryId, content: &str) -> bool {
244 let unchanged = crate::core::context_admission::admit_bound_context_source(
245 content,
246 &crate::core::context_admission::origin::SourceClass::Unclassified { tool: "recovery" },
247 )
248 .is_ok();
249 if unchanged {
250 let reference = format!("recovery:{}", id.as_str());
251 crate::core::context_admission::capture::note_source_id(&reference);
252 }
253 unchanged
254}
255
256#[must_use]
260pub fn recovery_lineage(id: &RecoveryId) -> Option<Lineage> {
261 super::read_entry(id.as_str())?.lineage
262}
263
264#[cfg(test)]
265mod tests {
266 use std::path::{Path, PathBuf};
267
268 use super::*;
269 use crate::core::archive::authority::ArchiveAuthority;
270 use crate::core::archive::presented::{PresentedBinding, record_presentation};
271 use crate::core::policy::runtime::{REQUEST_PROJECT, TestPolicyOverride};
272
273 const GOVERNED: &str = "[context_gateway]\nmode = \"governed\"\nclassification = \"warn\"\n";
274 const ORIGINAL: &str = "pub fn kept() {}\n";
275
276 fn isolated(config: &str) -> crate::core::data_dir::IsolatedDataDir {
277 let data = crate::core::data_dir::isolated_data_dir();
278 let dir = crate::core::paths::config_dir_read_only().expect("isolated config dir");
279 std::fs::create_dir_all(&dir).expect("config dir");
280 std::fs::write(dir.join("config.toml"), config).expect("config");
281 data
282 }
283
284 fn project() -> (tempfile::TempDir, PathBuf) {
285 let directory = tempfile::tempdir().expect("project");
286 let root = directory.path().canonicalize().expect("canonical root");
287 (directory, root)
288 }
289
290 fn scoped<T>(root: &Path, operation: impl FnOnce() -> T) -> T {
291 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(root.to_path_buf())), operation)
292 }
293
294 fn file_lineage(root: &Path, name: &str, content: &str) -> Lineage {
295 let path = root.join(name);
296 std::fs::write(&path, content).expect("source");
297 let admitted = crate::core::rooted_read::read_file_for_tool_rooted(
298 path.to_str().expect("utf-8 path"),
299 root.to_str().expect("utf-8 root"),
300 "ctx_read",
301 )
302 .expect("admitted read");
303 Lineage::of_files(
304 ArchiveAuthority::file(
305 root,
306 path.to_str().expect("utf-8 path"),
307 "ctx_read",
308 &admitted,
309 )
310 .expect("protection is active: the read is bound"),
311 )
312 }
313
314 fn stored_files(data: &crate::core::data_dir::IsolatedDataDir) -> usize {
315 fn count(directory: &Path) -> usize {
316 std::fs::read_dir(directory).map_or(0, |entries| {
317 entries
318 .flatten()
319 .map(|entry| {
320 let path = entry.path();
321 if path.is_dir() {
322 count(&path)
323 } else {
324 usize::from(path.extension().is_some_and(|ext| ext == "txt"))
325 }
326 })
327 .sum()
328 })
329 }
330 count(&data.path().join("archives"))
331 }
332
333 #[test]
338 fn a_file_bound_recovery_copy_resolves_only_while_its_source_holds() {
339 let _data = isolated(GOVERNED);
340 let _community = TestPolicyOverride::set(None);
341 let (_directory, root) = project();
342 scoped(&root, || {
343 let lineage = file_lineage(&root, "kept.rs", ORIGINAL);
344 let id = store_recovery_with_lineage(ORIGINAL, &lineage).expect("stored");
345 assert_eq!(
346 store_recovery_with_lineage(ORIGINAL, &lineage).as_ref(),
347 Ok(&id),
348 "identical input, identical id"
349 );
350 assert_eq!(retrieve_recovery_checked(&id).as_deref(), Ok(ORIGINAL));
351 assert_eq!(
352 crate::core::archive::retrieve_checked(id.as_str()).as_deref(),
353 Ok(ORIGINAL),
354 "one entry for the archive and the recovery path"
355 );
356
357 let stub = format!("[compressed; recover with {}]", id.as_str());
360 let known = delivered::lineage_of(&delivered::digest(ORIGINAL)).expect("on record");
361 assert!(delivered::record_derived(&delivered::digest(&stub), &known));
362 assert_eq!(
363 delivered::lineage_of(&delivered::digest(&stub)),
364 Some(known)
365 );
366
367 std::fs::remove_file(root.join("kept.rs")).expect("delete the source");
368 assert_eq!(
369 retrieve_recovery_checked(&id),
370 Err(RecoveryRefusal::SourceNoLongerAdmitted)
371 );
372 assert_eq!(
373 delivered::lineage_of(&delivered::digest(&stub))
374 .expect("still on record")
375 .still_admitted(),
376 Err(LineageRefusal::SourceNoLongerAdmitted)
377 );
378 assert_eq!(
379 store_recovery_with_lineage(ORIGINAL, &lineage),
380 Err(RecoveryRefusal::SourceNoLongerAdmitted)
381 );
382 });
383 }
384
385 #[test]
388 fn unknown_or_restricted_lineage_stores_nothing() {
389 let data = isolated(GOVERNED);
390 let _community = TestPolicyOverride::set(None);
391 let (_directory, root) = project();
392 scoped(&root, || {
393 assert_eq!(
394 store_recovery_with_lineage(ORIGINAL, &Lineage::of_presented(Vec::new())),
395 Err(RecoveryRefusal::UnknownLineage)
396 );
397
398 let marked = "*** TOP SECRET ***\nlaunch window\n";
401 let restricted = file_lineage(&root, "plan.md", marked);
402 assert!(matches!(
403 store_recovery_with_lineage("launch window\n", &restricted),
404 Err(RecoveryRefusal::SourceNoLongerAdmitted | RecoveryRefusal::NotStorable)
405 ));
406 let clean = file_lineage(&root, "kept.rs", ORIGINAL);
408 assert_eq!(
409 store_recovery_with_lineage(marked, &clean),
410 Err(RecoveryRefusal::NotStorable)
411 );
412 assert_eq!(stored_files(&data), 0, "nothing on disk");
413
414 assert!(RecoveryId::parse("../../etc/passwd").is_none());
415 let absent = RecoveryId::parse(&"0".repeat(64)).expect("canonical id");
416 assert_eq!(
417 retrieve_recovery_checked(&absent),
418 Err(RecoveryRefusal::Missing)
419 );
420 });
421 let lineage = scoped(&root, || file_lineage(&root, "kept.rs", ORIGINAL));
423 assert!(store_recovery_with_lineage(ORIGINAL, &lineage).is_err());
424 assert_eq!(stored_files(&data), 0);
425 }
426
427 #[test]
432 fn a_presented_recovery_copy_needs_a_current_presentation() {
433 let data = isolated("");
434 let _community = TestPolicyOverride::set(None);
435 let (_directory, root) = project();
436 let prepared = "## leanctx-source-v1\ninvoice ledger\n";
437 scoped(&root, || {
438 let binding =
439 PresentedBinding::admitted_now(&root, "ref-quartz", "source-one", "sha256:aa")
440 .expect("policy identity available");
441 let lineage = Lineage::of_presented(vec![binding.clone()]);
442 assert_eq!(
443 store_recovery_with_lineage(prepared, &lineage),
444 Err(RecoveryRefusal::SourceNotPresented),
445 "bound, but never presented"
446 );
447 assert_eq!(stored_files(&data), 0);
448
449 assert!(record_presentation(&binding));
450 let id = store_recovery_with_lineage(prepared, &lineage).expect("stored");
451 assert_eq!(
452 store_recovery_with_lineage(prepared, &lineage).as_ref(),
453 Ok(&id)
454 );
455 assert_eq!(retrieve_recovery_checked(&id).as_deref(), Ok(prepared));
456 assert!(
457 crate::core::archive::retrieve_checked(id.as_str()).is_err(),
458 "the ordinary archive read never serves a lineage-bound copy"
459 );
460 assert!(
461 crate::core::archive::list_entries(None)
462 .iter()
463 .all(|entry| entry.id != id.as_str()),
464 "and does not list it"
465 );
466
467 let presented = data
469 .path()
470 .join("archives")
471 .join(crate::core::archive::presented::REGISTER_DIRECTORY);
472 std::fs::remove_dir_all(&presented).expect("presentation register");
473 assert_eq!(
474 retrieve_recovery_checked(&id),
475 Err(RecoveryRefusal::SourceNotPresented)
476 );
477 assert!(record_presentation(&binding));
479 assert_eq!(retrieve_recovery_checked(&id).as_deref(), Ok(prepared));
480
481 let dir = crate::core::paths::config_dir_read_only().expect("config dir");
484 std::fs::write(
485 dir.join("config.toml"),
486 "[context_gateway]\nmode = \"governed\"\n",
487 )
488 .expect("config");
489 assert_eq!(
490 retrieve_recovery_checked(&id),
491 Err(RecoveryRefusal::SourceNoLongerAdmitted)
492 );
493 let renewed =
494 PresentedBinding::admitted_now(&root, "ref-quartz", "source-one", "sha256:aa")
495 .expect("policy identity available");
496 assert!(record_presentation(&renewed));
497 assert_eq!(
498 retrieve_recovery_checked(&id),
499 Err(RecoveryRefusal::SourceNoLongerAdmitted)
500 );
501 let renewed_id =
503 store_recovery_with_lineage(prepared, &Lineage::of_presented(vec![renewed]))
504 .expect("stored under the current policy");
505 assert_ne!(renewed_id, id);
506 assert_eq!(
507 retrieve_recovery_checked(&renewed_id).as_deref(),
508 Ok(prepared)
509 );
510 });
511 }
512
513 #[test]
518 fn a_presented_copy_is_readmitted_in_the_call_that_expands_it() {
519 use crate::core::context_admission::capture::{
520 ADMISSIONS, AdmissionCapture, CallSnapshot, SourceName,
521 };
522 let _data = isolated(GOVERNED);
523 let _community = TestPolicyOverride::set(None);
524 let (_directory, root) = project();
525 let prepared = "## leanctx-source-v1\ninvoice ledger\n";
526 scoped(&root, || {
527 let binding =
528 PresentedBinding::admitted_now(&root, "ref-quartz", "source-one", "sha256:aa")
529 .expect("policy identity available");
530 assert!(record_presentation(&binding));
531 let lineage = Lineage::of_presented(vec![binding]);
532 let id = store_recovery_with_lineage(prepared, &lineage).expect("stored");
533 let capture = AdmissionCapture::for_call(CallSnapshot::take());
534 let expanded =
535 ADMISSIONS.sync_scope(Some(capture.clone()), || retrieve_recovery_checked(&id));
536 assert_eq!(expanded.as_deref(), Ok(prepared));
537 let (named, _) = capture.source_references();
538 assert_eq!(named.len(), 1, "the expansion's own decision");
539 assert_eq!(
540 named[0].1,
541 SourceName::Id(format!("recovery:{}", id.as_str()))
542 );
543
544 let masked = "## leanctx-source-v1\npaid with card 4111 1111 1111 1111\n";
545 match store_recovery_with_lineage(masked, &lineage) {
546 Ok(id) => assert_eq!(
547 retrieve_recovery_checked(&id),
548 Err(RecoveryRefusal::SourceNoLongerAdmitted)
549 ),
550 Err(refusal) => assert!(matches!(
551 refusal,
552 RecoveryRefusal::NotStorable | RecoveryRefusal::SourceNoLongerAdmitted
553 )),
554 }
555 });
556 }
557}