1use std::io;
7use std::path::Component;
8use std::path::Path;
9use std::path::PathBuf;
10
11use chrono::{DateTime, Utc};
12use serde::{Deserialize, Serialize};
13
14pub const ARTIFACTS_DIR_NAME: &str = "artifacts";
15
16#[cfg(any(test, feature = "test-support"))]
17static TEST_ARTIFACT_SESSIONS_ROOT: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
18
19#[cfg(any(test, feature = "test-support"))]
20pub static TEST_ARTIFACT_SESSIONS_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum ArtifactKind {
25 ToolOutput,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct ArtifactRecord {
30 pub id: String,
31 pub kind: ArtifactKind,
32 #[serde(default)]
33 pub session_id: String,
34 pub tool_call_id: String,
35 pub tool_name: String,
36 pub created_at: DateTime<Utc>,
37 pub byte_size: u64,
38 pub preview: String,
39 pub storage_path: PathBuf,
40}
41
42fn sanitize_id_component(input: &str) -> String {
43 input
44 .chars()
45 .map(|c| {
46 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
47 c
48 } else {
49 '_'
50 }
51 })
52 .collect()
53}
54
55pub fn is_valid_session_id(session_id: &str) -> bool {
56 !session_id.is_empty()
57 && session_id
58 .chars()
59 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
60}
61
62#[must_use]
63pub fn artifact_id_for_tool_call(tool_call_id: &str) -> String {
64 format!("art_{}", sanitize_id_component(tool_call_id))
65}
66
67#[must_use]
68pub fn session_artifact_relative_path(artifact_id: &str) -> PathBuf {
69 PathBuf::from(ARTIFACTS_DIR_NAME).join(format!("{artifact_id}.txt"))
70}
71
72fn session_artifact_relative_path_with_extension(
73 artifact_id: &str,
74 extension: &str,
75) -> io::Result<PathBuf> {
76 let artifact_id = sanitize_id_component(artifact_id);
77 let extension = extension.trim_start_matches('.').to_ascii_lowercase();
78 if artifact_id.is_empty()
79 || extension.is_empty()
80 || !extension
81 .chars()
82 .all(|character| character.is_ascii_alphanumeric())
83 {
84 return Err(io::Error::new(
85 io::ErrorKind::InvalidInput,
86 "artifact id and extension must contain safe ASCII characters",
87 ));
88 }
89 Ok(PathBuf::from(ARTIFACTS_DIR_NAME).join(format!("{artifact_id}.{extension}")))
90}
91
92pub fn artifact_sessions_root() -> Option<PathBuf> {
97 #[cfg(any(test, feature = "test-support"))]
98 if let Some(root) = TEST_ARTIFACT_SESSIONS_ROOT
99 .lock()
100 .unwrap_or_else(|err| err.into_inner())
101 .clone()
102 {
103 return Some(root);
104 }
105 #[cfg(any(test, feature = "test-support"))]
108 if let Some(root) = crate::test_support::unsealed_state_dir("sessions") {
109 return Some(root);
110 }
111
112 codewhale_config::resolve_state_dir("sessions").ok()
115}
116
117#[cfg(any(test, feature = "test-support"))]
118pub fn set_test_artifact_sessions_root(root: Option<PathBuf>) -> Option<PathBuf> {
119 let mut guard = TEST_ARTIFACT_SESSIONS_ROOT
120 .lock()
121 .unwrap_or_else(|err| err.into_inner());
122 std::mem::replace(&mut *guard, root)
123}
124
125#[must_use]
131pub fn session_artifact_absolute_path(session_id: &str, relative_path: &Path) -> Option<PathBuf> {
132 if !is_valid_session_id(session_id) {
133 return None;
134 }
135 if relative_path.is_absolute()
136 || relative_path
137 .components()
138 .any(|component| matches!(component, Component::ParentDir))
139 {
140 return None;
141 }
142 Some(
143 artifact_sessions_root()?
144 .join(session_id)
145 .join(relative_path),
146 )
147}
148
149pub fn write_session_artifact(
150 session_id: &str,
151 artifact_id: &str,
152 content: &str,
153) -> io::Result<(PathBuf, PathBuf)> {
154 let relative_path = session_artifact_relative_path(artifact_id);
155 let absolute_path =
156 session_artifact_absolute_path(session_id, &relative_path).ok_or_else(|| {
157 io::Error::new(
158 io::ErrorKind::InvalidInput,
159 "could not resolve session artifact path (missing home directory)",
160 )
161 })?;
162 open_session_relative(session_id, &relative_path, true)?.replace(content.as_bytes())?;
163 Ok((absolute_path, relative_path))
164}
165
166pub fn write_session_relative_immutable(
170 session_id: &str,
171 relative_path: &Path,
172 content: &[u8],
173) -> io::Result<PathBuf> {
174 let absolute_path =
175 session_artifact_absolute_path(session_id, relative_path).ok_or_else(|| {
176 io::Error::new(io::ErrorKind::InvalidInput, "invalid session artifact path")
177 })?;
178 let destination = open_session_relative(session_id, relative_path, true)?;
179 match destination.publish(content) {
180 Ok(()) => {}
181 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
182 use std::io::Read;
183 let mut existing = Vec::new();
184 destination
185 .open_file()?
186 .take(content.len() as u64 + 1)
187 .read_to_end(&mut existing)?;
188 if existing != content {
189 return Err(io::Error::new(
190 io::ErrorKind::AlreadyExists,
191 "immutable artifact handle already contains different bytes",
192 ));
193 }
194 }
195 Err(err) => return Err(err),
196 }
197 Ok(absolute_path)
198}
199
200pub fn open_session_relative(
203 session_id: &str,
204 relative_path: &Path,
205 create: bool,
206) -> io::Result<codewhale_util::files::WorkspaceFile> {
207 session_artifact_absolute_path(session_id, relative_path).ok_or_else(|| {
208 io::Error::new(io::ErrorKind::InvalidInput, "invalid session artifact path")
209 })?;
210 let root = artifact_sessions_root()
211 .ok_or_else(|| io::Error::other("session artifact root unavailable"))?;
212 if create {
213 std::fs::create_dir_all(&root)?;
214 }
215 codewhale_util::files::WorkspaceFile::open_resolved_root(
219 &root,
220 &PathBuf::from(session_id).join(relative_path),
221 create,
222 )
223}
224
225pub fn write_session_artifact_immutable(
226 session_id: &str,
227 artifact_id: &str,
228 content: &[u8],
229) -> io::Result<(PathBuf, PathBuf)> {
230 let relative_path = session_artifact_relative_path(artifact_id);
231 let absolute_path = write_session_relative_immutable(session_id, &relative_path, content)?;
232 Ok((absolute_path, relative_path))
233}
234
235pub fn write_session_artifact_immutable_from_reader(
236 session_id: &str,
237 artifact_id: &str,
238 reader: &mut (impl io::Read + io::Seek),
239) -> io::Result<(PathBuf, PathBuf, u64, String)> {
240 use sha2::{Digest, Sha256};
241 use std::io::{Read, SeekFrom};
242
243 struct HashingReader<'a, R> {
244 reader: &'a mut R,
245 hash: Sha256,
246 byte_size: u64,
247 }
248 impl<R: Read> Read for HashingReader<'_, R> {
249 fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
250 let count = self.reader.read(buffer)?;
251 self.hash.update(&buffer[..count]);
252 self.byte_size += count as u64;
253 Ok(count)
254 }
255 }
256
257 let relative_path = session_artifact_relative_path(artifact_id);
258 let absolute_path =
259 session_artifact_absolute_path(session_id, &relative_path).ok_or_else(|| {
260 io::Error::new(io::ErrorKind::InvalidInput, "invalid session artifact path")
261 })?;
262 let destination = open_session_relative(session_id, &relative_path, true)?;
263 let start = reader.stream_position()?;
264 let mut hashing = HashingReader {
265 reader,
266 hash: Sha256::new(),
267 byte_size: 0,
268 };
269 let result = destination.publish_from_reader(&mut hashing);
270 let byte_size = hashing.byte_size;
271 let digest = crate::hashing::hex_bytes(hashing.hash.finalize());
272 match result {
273 Ok(()) => {}
274 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
275 reader.seek(SeekFrom::Start(start))?;
276 let mut existing = destination.open_file()?;
277 let mut source_bytes = [0; 8192];
278 let mut existing_bytes = [0; 8192];
279 loop {
280 let count = match reader.read(&mut source_bytes) {
281 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
282 result => result?,
283 };
284 let same_length = match existing.read_exact(&mut existing_bytes[..count]) {
285 Ok(()) => true,
286 Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => false,
287 Err(error) => return Err(error),
288 };
289 if !same_length
290 || existing_bytes[..count] != source_bytes[..count]
291 || (count == 0 && existing.read(&mut existing_bytes[..1])? != 0)
292 {
293 return Err(io::Error::new(
294 io::ErrorKind::AlreadyExists,
295 "immutable artifact handle already contains different bytes",
296 ));
297 }
298 if count == 0 {
299 break;
300 }
301 }
302 }
303 Err(error) => return Err(error),
304 }
305 Ok((absolute_path, relative_path, byte_size, digest))
306}
307
308pub fn write_session_artifact_bytes(
311 session_id: &str,
312 artifact_id: &str,
313 extension: &str,
314 content: &[u8],
315) -> io::Result<(PathBuf, PathBuf)> {
316 let relative_path = session_artifact_relative_path_with_extension(artifact_id, extension)?;
317 let absolute_path =
318 session_artifact_absolute_path(session_id, &relative_path).ok_or_else(|| {
319 io::Error::new(
320 io::ErrorKind::InvalidInput,
321 "could not resolve session artifact path (missing home directory)",
322 )
323 })?;
324 open_session_relative(session_id, &relative_path, true)?.replace(content)?;
325 Ok((absolute_path, relative_path))
326}
327
328fn preview_text(content: &str, max_chars: usize) -> String {
329 let mut preview: String = content.chars().take(max_chars).collect();
330 if content.chars().count() > max_chars {
331 preview.push_str("...");
332 }
333 preview
334}
335
336pub fn record_tool_output_artifact(
337 session_id: &str,
338 tool_call_id: &str,
339 tool_name: &str,
340 storage_path: impl Into<PathBuf>,
341 content: &str,
342) -> ArtifactRecord {
343 let storage_path = storage_path.into();
344 let byte_size = std::fs::metadata(&storage_path)
345 .map(|metadata| metadata.len())
346 .unwrap_or_else(|_| content.len() as u64);
347 record_tool_output_artifact_with_size(
348 session_id,
349 tool_call_id,
350 tool_name,
351 storage_path,
352 byte_size,
353 &preview_text(content, 200),
354 )
355}
356
357pub fn record_tool_output_artifact_with_size(
358 session_id: &str,
359 tool_call_id: &str,
360 tool_name: &str,
361 storage_path: impl Into<PathBuf>,
362 byte_size: u64,
363 preview: &str,
364) -> ArtifactRecord {
365 ArtifactRecord {
366 id: artifact_id_for_tool_call(tool_call_id),
367 kind: ArtifactKind::ToolOutput,
368 session_id: session_id.to_string(),
369 tool_call_id: tool_call_id.to_string(),
370 tool_name: tool_name.to_string(),
371 created_at: Utc::now(),
372 byte_size,
373 preview: preview_text(preview, 200),
374 storage_path: storage_path.into(),
375 }
376}
377
378#[must_use]
379pub fn format_artifact_relative_path(path: &Path) -> String {
380 path.display().to_string().replace('\\', "/")
381}
382
383pub use codewhale_protocol::display::format_byte_size;
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388
389 struct TestArtifactSessionsRoot {
390 prior: Option<PathBuf>,
391 }
392
393 impl Drop for TestArtifactSessionsRoot {
394 fn drop(&mut self) {
395 set_test_artifact_sessions_root(self.prior.take());
396 }
397 }
398
399 fn set_test_sessions_root(root: PathBuf) -> TestArtifactSessionsRoot {
400 TestArtifactSessionsRoot {
401 prior: set_test_artifact_sessions_root(Some(root)),
402 }
403 }
404
405 #[test]
406 fn session_artifact_absolute_path_uses_test_sessions_root() {
407 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
408 .lock()
409 .unwrap_or_else(|err| err.into_inner());
410 let tmp = tempfile::tempdir().unwrap();
411 let _root = set_test_sessions_root(tmp.path().join("sessions"));
412
413 let path = session_artifact_absolute_path(
414 "session-123",
415 &PathBuf::from("artifacts").join("art_call-big.txt"),
416 )
417 .expect("path");
418
419 assert_eq!(
420 path,
421 tmp.path()
422 .join("sessions")
423 .join("session-123")
424 .join("artifacts")
425 .join("art_call-big.txt")
426 );
427 }
428
429 #[test]
430 fn binary_session_artifact_uses_validated_extension_and_exact_bytes() {
431 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
432 .lock()
433 .unwrap_or_else(|err| err.into_inner());
434 let tmp = tempfile::tempdir().unwrap();
435 let _root = set_test_sessions_root(tmp.path().join("sessions"));
436 let bytes = b"\x89PNG\r\n\x1a\nfixture";
437
438 let (absolute, relative) =
439 write_session_artifact_bytes("session-123", "web/media", ".PNG", bytes)
440 .expect("write binary artifact");
441
442 assert_eq!(relative, PathBuf::from("artifacts/web_media.png"));
443 assert_eq!(std::fs::read(absolute).unwrap(), bytes);
444 assert!(write_session_artifact_bytes("session-123", "bad", "../png", bytes).is_err());
445 }
446
447 #[test]
448 fn adaptive_evidence_publication_is_immutable_and_replay_safe() {
449 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
450 .lock()
451 .unwrap_or_else(|err| err.into_inner());
452 let tmp = tempfile::tempdir().unwrap();
453 let _root = set_test_sessions_root(tmp.path().join("sessions"));
454 let relative = PathBuf::from("artifacts/art_call.txt");
455 let bytes = b"first exact payload";
456
457 let first = write_session_relative_immutable("session-a", &relative, bytes).unwrap();
458 let replay = write_session_relative_immutable("session-a", &relative, bytes).unwrap();
459 assert_eq!(first, replay);
460 let err = write_session_relative_immutable("session-a", &relative, b"different")
461 .expect_err("handle aliasing must fail");
462 assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
463 assert_eq!(std::fs::read(first).unwrap(), bytes);
464 }
465
466 #[test]
467 fn streamed_artifact_is_bounded_exact_and_replay_safe() {
468 use std::io::{Read, Seek, SeekFrom, Write};
469
470 struct ChunkedFile(std::fs::File);
471 impl Read for ChunkedFile {
472 fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
473 assert!(buffer.len() <= 64 * 1024);
474 let limit = buffer.len().min(997);
475 self.0.read(&mut buffer[..limit])
476 }
477 }
478 impl Seek for ChunkedFile {
479 fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
480 self.0.seek(position)
481 }
482 }
483
484 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
485 .lock()
486 .unwrap_or_else(|err| err.into_inner());
487 let tmp = tempfile::tempdir().unwrap();
488 let _root = set_test_sessions_root(tmp.path().join("sessions"));
489 let mut fixture = tempfile::tempfile().unwrap();
490 let chunk = [0xab; 8192];
491 for _ in 0..1024 {
492 fixture.write_all(&chunk).unwrap();
493 }
494 fixture.rewind().unwrap();
495 let mut source = ChunkedFile(fixture);
496 let first = write_session_artifact_immutable_from_reader(
497 "session-stream",
498 "art_large",
499 &mut source,
500 )
501 .unwrap();
502 assert_eq!(first.2, 8 * 1024 * 1024);
503 let mut expected = sha2::Sha256::default();
504 use sha2::Digest;
505 for _ in 0..1024 {
506 expected.update(chunk);
507 }
508 assert_eq!(first.3, crate::hashing::hex_bytes(expected.finalize()));
509 source.rewind().unwrap();
510 let replay = write_session_artifact_immutable_from_reader(
511 "session-stream",
512 "art_large",
513 &mut source,
514 )
515 .unwrap();
516 assert_eq!(first, replay);
517 source.0.rewind().unwrap();
518 source.0.write_all(b"changed").unwrap();
519 source.rewind().unwrap();
520 assert_eq!(
521 write_session_artifact_immutable_from_reader(
522 "session-stream",
523 "art_large",
524 &mut source
525 )
526 .unwrap_err()
527 .kind(),
528 io::ErrorKind::AlreadyExists
529 );
530 let mut stored = std::fs::File::open(first.0).unwrap();
531 let mut actual = [0; 8192];
532 for _ in 0..1024 {
533 stored.read_exact(&mut actual).unwrap();
534 assert_eq!(actual, chunk);
535 }
536 assert_eq!(stored.read(&mut actual).unwrap(), 0);
537 }
538
539 #[cfg(unix)]
540 #[test]
541 fn immutable_session_artifact_rejects_symlinked_parent() {
542 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
543 .lock()
544 .unwrap_or_else(|err| err.into_inner());
545 let tmp = tempfile::tempdir().unwrap();
546 let sessions = tmp.path().join("sessions");
547 let _root = set_test_sessions_root(sessions.clone());
548 std::fs::create_dir_all(&sessions).unwrap();
549 let outside = tempfile::tempdir().unwrap();
550 std::os::unix::fs::symlink(outside.path(), sessions.join("session-a")).unwrap();
551 assert!(
552 write_session_relative_immutable(
553 "session-a",
554 Path::new("artifacts/handoff.json"),
555 b"private"
556 )
557 .is_err()
558 );
559 assert!(
560 write_session_artifact_immutable_from_reader(
561 "session-a",
562 "art_stream",
563 &mut io::Cursor::new(b"private")
564 )
565 .is_err()
566 );
567 assert!(!outside.path().join("artifacts").exists());
568 }
569
570 #[test]
571 fn adaptive_evidence_failed_publication_creates_no_handle() {
572 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
573 .lock()
574 .unwrap_or_else(|err| err.into_inner());
575 let tmp = tempfile::tempdir().unwrap();
576 let sessions = tmp.path().join("sessions");
577 let _root = set_test_sessions_root(sessions.clone());
578 std::fs::create_dir_all(sessions.join("session-a")).unwrap();
579 std::fs::write(sessions.join("session-a/artifacts"), b"block directory").unwrap();
580 let relative = PathBuf::from("artifacts/art_failed.txt");
581
582 assert!(write_session_relative_immutable("session-a", &relative, b"payload").is_err());
583 assert!(!sessions.join("session-a/artifacts/art_failed.txt").exists());
584 }
585 #[test]
586 fn streamed_artifact_read_failure_publishes_nothing() {
587 use std::io::{Read, Seek, SeekFrom};
588
589 struct FailingReader(io::Cursor<Vec<u8>>);
590 impl Read for FailingReader {
591 fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
592 if self.0.position() >= 4096 {
593 return Err(io::Error::other("fixture read failure"));
594 }
595 let limit = buffer.len().min(4096);
596 self.0.read(&mut buffer[..limit])
597 }
598 }
599 impl Seek for FailingReader {
600 fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
601 self.0.seek(position)
602 }
603 }
604
605 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
606 .lock()
607 .unwrap_or_else(|err| err.into_inner());
608 let tmp = tempfile::tempdir().unwrap();
609 let sessions = tmp.path().join("sessions");
610 let _root = set_test_sessions_root(sessions.clone());
611 let mut source = FailingReader(io::Cursor::new(vec![0xcd; 8192]));
612 let error =
613 write_session_artifact_immutable_from_reader("session-a", "art_failed", &mut source)
614 .unwrap_err();
615 assert_eq!(error.to_string(), "fixture read failure");
616 assert_eq!(
617 std::fs::read_dir(sessions.join("session-a/artifacts"))
618 .unwrap()
619 .count(),
620 0
621 );
622 }
623
624 #[cfg(unix)]
625 fn check_mutable_parent_links(binary: bool) {
626 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
627 .lock()
628 .unwrap_or_else(|err| err.into_inner());
629 for linked_session in [true, false] {
630 let temp = tempfile::tempdir().unwrap();
631 let sessions = temp.path().join("sessions");
632 let _root = set_test_sessions_root(sessions.clone());
633 std::fs::create_dir_all(&sessions).unwrap();
634 let outside = temp.path().join("outside");
635 let outside_artifacts = if linked_session {
636 outside.join("artifacts")
637 } else {
638 outside.clone()
639 };
640 std::fs::create_dir_all(&outside_artifacts).unwrap();
641 let extension = if binary { "bin" } else { "txt" };
642 let canary = outside_artifacts.join(format!("mutable.{extension}"));
643 std::fs::write(&canary, b"old-exact-artifact-canary").unwrap();
644 if linked_session {
645 std::os::unix::fs::symlink(&outside, sessions.join("session-a")).unwrap();
646 } else {
647 std::fs::create_dir(sessions.join("session-a")).unwrap();
648 std::os::unix::fs::symlink(&outside, sessions.join("session-a/artifacts")).unwrap();
649 }
650 let result = if binary {
651 write_session_artifact_bytes("session-a", "mutable", extension, b"new-byte-payload")
652 } else {
653 write_session_artifact("session-a", "mutable", "new-text-payload")
654 };
655 assert_eq!(
656 std::fs::read(&canary).unwrap(),
657 b"old-exact-artifact-canary",
658 "mutable artifact overwrote a linked outside destination"
659 );
660 assert!(result.is_err(), "linked mutable artifact parent accepted");
661 }
662 }
663
664 #[cfg(unix)]
665 #[test]
666 fn mutable_text_artifact_refuses_linked_session_and_artifacts_parents() {
667 check_mutable_parent_links(false);
668 }
669
670 #[cfg(unix)]
671 #[test]
672 fn mutable_byte_artifact_refuses_linked_session_and_artifacts_parents() {
673 check_mutable_parent_links(true);
674 }
675
676 #[cfg(unix)]
677 #[test]
678 fn mutable_artifacts_replace_exact_bytes_without_following_leaf_links() {
679 use std::os::unix::fs::PermissionsExt;
680 let _guard = TEST_ARTIFACT_SESSIONS_GUARD
681 .lock()
682 .unwrap_or_else(|err| err.into_inner());
683 let temp = tempfile::tempdir().unwrap();
684 let sessions = temp.path().join("sessions");
685 let _root = set_test_sessions_root(sessions.clone());
686 let outside = temp.path().join("outside.txt");
687 std::fs::write(&outside, b"outside-leaf-canary").unwrap();
688 for binary in [false, true] {
689 let extension = if binary { "bin" } else { "txt" };
690 let relative = PathBuf::from(format!("artifacts/mutable.{extension}"));
691 let directory = sessions.join("session-a/artifacts");
692 std::fs::create_dir_all(&directory).unwrap();
693 let path = sessions.join("session-a").join(&relative);
694 std::os::unix::fs::symlink(&outside, &path).unwrap();
695 let (absolute, recorded) = if binary {
696 write_session_artifact_bytes(
697 "session-a",
698 "mutable",
699 extension,
700 b"\0exact-byte-payload",
701 )
702 } else {
703 write_session_artifact("session-a", "mutable", "exact-text-payload")
704 }
705 .unwrap();
706 assert_eq!(absolute, path);
707 assert_eq!(recorded, relative);
708 let expected: &[u8] = if binary {
709 b"\0exact-byte-payload"
710 } else {
711 b"exact-text-payload"
712 };
713 assert_eq!(std::fs::read(&absolute).unwrap(), expected);
714 assert!(
715 !std::fs::symlink_metadata(&absolute)
716 .unwrap()
717 .file_type()
718 .is_symlink()
719 );
720 assert_eq!(
721 std::fs::metadata(&absolute).unwrap().permissions().mode() & 0o777,
722 0o600
723 );
724 assert_eq!(std::fs::read(&outside).unwrap(), b"outside-leaf-canary");
725 }
726 }
727}