1use std::{
8 collections::{BTreeMap, BTreeSet},
9 ffi::{OsStr, OsString},
10 fmt, fs,
11 io::{self, Read},
12 path::{Component, Path, PathBuf},
13};
14
15use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
16use cap_std::fs::{Dir, DirEntry, Metadata, OpenOptions, ReadDir};
17use ignore::{
18 Match,
19 gitignore::{Gitignore, GitignoreBuilder},
20};
21use serde::{Deserialize, Serialize};
22use sha2::{Digest, Sha256};
23use unicode_casefold::UnicodeCaseFold;
24use unicode_normalization::UnicodeNormalization;
25
26use crate::{
27 FolderbaseError, FolderbaseRootAttestation, RootAttestationError,
28 folderbase_restore_authority::{
29 MAX_RESTORE_AUTHORITIES, MAX_RESTORE_AUTHORITY_BYTES, RESTORE_AUTHORITIES_DIRECTORY,
30 RESTORE_AUTHORITY_FORMAT_V1, RestoreAuthorityRecord, restore_authority_record_path,
31 restore_stage_path, stable_file_identity_sha256, stable_file_link_count,
32 },
33 folderbase_state::FolderbaseState,
34 folderbase_version::{
35 FolderbaseVersionError, MAX_OBJECT_BYTES, MAX_VERSION_ENTRIES, validate_capture_path,
36 validate_capture_sha256, validate_capture_symlink_targets, validate_capture_version_id,
37 },
38 physical_identity::PhysicalIdentity,
39 root_attestation::{
40 ManifestProtocolProfile, RootInstanceAuthority, attest_folderbase_root_with_profile,
41 },
42 traversal_policy::{
43 NestedFolderbaseBoundaryKind, RECONSTRUCTABLE_DIRECTORIES,
44 classify_nested_folderbase_boundary, is_folderbase_state_component,
45 },
46};
47
48#[cfg(unix)]
49use crate::folderbase_restore_authority::stable_unix_file_identity_sha256;
50
51pub const MAX_FOLDERBASEIGNORE_BYTES: u64 = 1024 * 1024;
52pub const MAX_LOCAL_HEAD_BYTES: u64 = 4096;
53pub const MAX_CAPTURE_PLAN_RECORDS: usize = MAX_VERSION_ENTRIES;
54const LOCAL_HEAD_PATH: &str = ".folderbase/local/head.json";
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum CapturePlanLimitKind {
58 Entries,
59 ObjectBytes,
60}
61
62impl fmt::Display for CapturePlanLimitKind {
63 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
64 formatter.write_str(match self {
65 Self::Entries => "entries",
66 Self::ObjectBytes => "object_bytes",
67 })
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum CaptureEntryKind {
75 Directory,
76 RegularFile,
77 Symlink,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct CapturePlanEntry {
83 path: String,
84 kind: CaptureEntryKind,
85 bytes: Option<u64>,
86 executable: Option<bool>,
87 symlink_target: Option<String>,
88 observed: CaptureMetadataFingerprint,
89 link_commitment: CaptureLinkCommitment,
90}
91
92impl CapturePlanEntry {
93 pub fn path(&self) -> &str {
94 &self.path
95 }
96
97 pub fn kind(&self) -> CaptureEntryKind {
98 self.kind
99 }
100
101 pub fn bytes(&self) -> Option<u64> {
102 self.bytes
103 }
104
105 pub fn executable(&self) -> Option<bool> {
106 self.executable
107 }
108
109 pub fn symlink_target(&self) -> Option<&str> {
110 self.symlink_target.as_deref()
111 }
112
113 pub(crate) fn observed(&self) -> &CaptureMetadataFingerprint {
114 &self.observed
115 }
116
117 pub(crate) fn link_commitment(&self) -> &CaptureLinkCommitment {
118 &self.link_commitment
119 }
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(deny_unknown_fields)]
124pub(crate) struct CaptureAuthorityLink {
125 receipt_path: String,
126 receipt_sha256: String,
127 private_stage_path: String,
128 published_identity_sha256: String,
129}
130
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
132#[serde(deny_unknown_fields)]
133pub(crate) struct CaptureLinkCommitment {
134 expected_live_link_count: u64,
135 authority_set_sha256: Option<String>,
136 authorities: Vec<CaptureAuthorityLink>,
137}
138
139impl Default for CaptureLinkCommitment {
140 fn default() -> Self {
141 Self {
142 expected_live_link_count: 1,
143 authority_set_sha256: None,
144 authorities: Vec::new(),
145 }
146 }
147}
148
149impl CaptureLinkCommitment {
150 pub(crate) fn is_legacy_default(&self) -> bool {
151 self == &Self::default()
152 }
153
154 pub(crate) fn is_well_formed(&self) -> bool {
155 let exact_link_count = self
156 .authorities
157 .len()
158 .checked_add(1)
159 .and_then(|count| u64::try_from(count).ok());
160 let expected_digest =
161 (!self.authorities.is_empty()).then(|| capture_authority_set_sha256(&self.authorities));
162 if exact_link_count != Some(self.expected_live_link_count)
163 || self.authority_set_sha256 != expected_digest
164 {
165 return false;
166 }
167 let mut previous = None;
168 for authority in &self.authorities {
169 if previous
170 .is_some_and(|path: &str| path.as_bytes() >= authority.receipt_path.as_bytes())
171 || validate_capture_sha256(&authority.receipt_sha256).is_err()
172 || validate_capture_sha256(&authority.published_identity_sha256).is_err()
173 {
174 return false;
175 }
176 let receipt_path = Path::new(&authority.receipt_path);
177 let Some(transaction_id) = receipt_path
178 .parent()
179 .and_then(Path::file_name)
180 .and_then(OsStr::to_str)
181 else {
182 return false;
183 };
184 if restore_authority_record_path(transaction_id) != receipt_path
185 || restore_stage_path(transaction_id) != Path::new(&authority.private_stage_path)
186 {
187 return false;
188 }
189 previous = Some(authority.receipt_path.as_str());
190 }
191 true
192 }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub(crate) struct CaptureMetadataFingerprint {
197 pub(crate) bytes: u64,
198 pub(crate) modified_unix_nanos: Option<u128>,
199 pub(crate) readonly: bool,
200 pub(crate) executable: bool,
201 pub(crate) device: Option<u64>,
202 pub(crate) inode: Option<u64>,
203 #[serde(default)]
204 pub(crate) physical_identity: Option<String>,
205}
206
207impl CaptureMetadataFingerprint {
208 pub(crate) fn from_cap_metadata(metadata: &Metadata) -> Self {
209 let modified_unix_nanos = metadata
210 .modified()
211 .ok()
212 .and_then(|value| value.into_std().duration_since(std::time::UNIX_EPOCH).ok())
213 .map(|value| value.as_nanos());
214 #[cfg(unix)]
215 let (device, inode) = {
216 use cap_std::fs::MetadataExt;
217
218 (Some(metadata.dev()), Some(metadata.ino()))
219 };
220 #[cfg(not(unix))]
221 let (device, inode) = (None, None);
222 Self {
223 bytes: metadata.len(),
224 modified_unix_nanos,
225 readonly: metadata.permissions().readonly(),
226 executable: is_executable(metadata),
227 device,
228 inode,
229 physical_identity: physical_identity_from_cap_metadata(metadata),
230 }
231 }
232
233 pub(crate) fn from_std_metadata(metadata: &fs::Metadata) -> Self {
234 let modified_unix_nanos = metadata
235 .modified()
236 .ok()
237 .and_then(|value| value.duration_since(std::time::UNIX_EPOCH).ok())
238 .map(|value| value.as_nanos());
239 #[cfg(unix)]
240 let (device, inode, executable) = {
241 use std::os::unix::fs::{MetadataExt, PermissionsExt};
242
243 (
244 Some(metadata.dev()),
245 Some(metadata.ino()),
246 metadata.permissions().mode() & 0o111 != 0,
247 )
248 };
249 #[cfg(not(unix))]
250 let (device, inode, executable) = (None, None, false);
251 Self {
252 bytes: metadata.len(),
253 modified_unix_nanos,
254 readonly: metadata.permissions().readonly(),
255 executable,
256 device,
257 inode,
258 physical_identity: physical_identity_from_std_metadata(metadata),
259 }
260 }
261
262 pub(crate) fn from_std_file(file: &fs::File) -> io::Result<Self> {
263 let metadata = file.metadata()?;
264 let fingerprint = Self::from_std_metadata(&metadata);
265 #[cfg(windows)]
266 {
267 return Ok(fingerprint.with_physical_identity(Some(windows_file_identity(file)?)));
268 }
269 #[cfg(not(windows))]
270 Ok(fingerprint)
271 }
272
273 #[cfg(windows)]
274 fn with_physical_identity(mut self, physical_identity: Option<String>) -> Self {
275 self.physical_identity = physical_identity;
276 self
277 }
278}
279
280#[cfg(unix)]
281fn physical_identity_from_cap_metadata(metadata: &Metadata) -> Option<String> {
282 use cap_std::fs::MetadataExt;
283
284 Some(format!(
285 "unix:{:016x}:{:016x}",
286 metadata.dev(),
287 metadata.ino()
288 ))
289}
290
291#[cfg(not(unix))]
292fn physical_identity_from_cap_metadata(_metadata: &Metadata) -> Option<String> {
293 None
294}
295
296#[cfg(unix)]
297fn physical_identity_from_std_metadata(metadata: &fs::Metadata) -> Option<String> {
298 use std::os::unix::fs::MetadataExt;
299
300 Some(format!(
301 "unix:{:016x}:{:016x}",
302 metadata.dev(),
303 metadata.ino()
304 ))
305}
306
307#[cfg(not(unix))]
308fn physical_identity_from_std_metadata(_metadata: &fs::Metadata) -> Option<String> {
309 None
310}
311
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
313#[serde(rename_all = "snake_case")]
314pub enum CaptureExclusionKind {
315 NestedFolderbase,
316 HardLink,
317 Fifo,
318 Socket,
319 BlockDevice,
320 CharacterDevice,
321 OtherSpecial,
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "kebab-case")]
326pub enum CaptureExclusionReason {
327 NestedFolderbaseBoundary,
328 UnsupportedV1,
329}
330
331#[derive(Debug, Clone, PartialEq, Eq)]
333pub struct CapturePlanExclusion {
334 path: String,
335 kind: CaptureExclusionKind,
336 reason: CaptureExclusionReason,
337}
338
339impl CapturePlanExclusion {
340 pub fn path(&self) -> &str {
341 &self.path
342 }
343
344 pub fn kind(&self) -> CaptureExclusionKind {
345 self.kind
346 }
347
348 pub fn reason(&self) -> CaptureExclusionReason {
349 self.reason
350 }
351}
352
353#[derive(Debug, Clone, PartialEq, Eq)]
355pub struct CaptureIgnoredPath {
356 path: String,
357}
358
359impl CaptureIgnoredPath {
360 pub fn path(&self) -> &str {
361 &self.path
362 }
363}
364
365#[derive(Debug, Clone, PartialEq, Eq)]
367pub struct CaptureLocalHead {
368 version_id: String,
369 version_sha256: String,
370 authority: LocalHeadAuthority,
371}
372
373#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(tag = "kind", deny_unknown_fields)]
376pub enum LocalHeadAuthority {
377 #[serde(rename = "capture_transaction_v1")]
378 CaptureTransactionV1 { sha256: String },
379 #[serde(rename = "version_derived_v1")]
380 VersionDerivedV1 { sha256: String },
381}
382
383impl LocalHeadAuthority {
384 pub fn sha256(&self) -> &str {
385 match self {
386 Self::CaptureTransactionV1 { sha256 } | Self::VersionDerivedV1 { sha256 } => sha256,
387 }
388 }
389}
390
391pub(crate) fn version_derived_local_head_sha256(
392 folderbase_id: &str,
393 root_instance_sha256: &str,
394 version_id: &str,
395 version_sha256: &str,
396) -> Result<String, FolderbaseCaptureError> {
397 #[derive(Serialize)]
398 struct VersionDerivedLocalHeadAuthority<'a> {
399 format: &'static str,
400 folderbase_id: &'a str,
401 root_instance_sha256: &'a str,
402 version_id: &'a str,
403 version_sha256: &'a str,
404 }
405
406 let authority = serde_json::to_vec(&VersionDerivedLocalHeadAuthority {
407 format: "folderbase-local-head-authority-v1",
408 folderbase_id,
409 root_instance_sha256,
410 version_id,
411 version_sha256,
412 })
413 .map_err(|source| {
414 FolderbaseCaptureError::InvalidLocalHead(format!(
415 "Local Head authority encoding failed: {source}"
416 ))
417 })?;
418 Ok(format!("{:x}", Sha256::digest(authority)))
419}
420
421#[derive(Debug, Deserialize)]
422#[serde(untagged)]
423enum LocalHeadWire {
424 V2(LocalHeadWireV2),
425 V1(LocalHeadWireV1),
426}
427
428#[derive(Debug, Deserialize)]
429#[serde(deny_unknown_fields)]
430struct LocalHeadWireV2 {
431 format: String,
432 folderbase_id: String,
433 root_instance_sha256: String,
434 version_id: String,
435 version_sha256: String,
436 authority: LocalHeadAuthority,
437}
438
439#[derive(Debug, Deserialize)]
440#[serde(deny_unknown_fields)]
441struct LocalHeadWireV1 {
442 format: String,
443 folderbase_id: String,
444 root_instance_sha256: String,
445 version_id: String,
446 version_sha256: String,
447 transaction_sha256: String,
448}
449
450impl CaptureLocalHead {
451 pub fn version_id(&self) -> &str {
452 &self.version_id
453 }
454
455 pub fn version_sha256(&self) -> &str {
456 &self.version_sha256
457 }
458
459 pub fn authority(&self) -> &LocalHeadAuthority {
460 &self.authority
461 }
462}
463
464#[derive(Debug)]
466pub struct CapturePlan {
467 root_attestation: FolderbaseRootAttestation,
468 root_manifest_bytes: u64,
469 folderbase_version_protocol: &'static str,
470 current_local_head: Option<CaptureLocalHead>,
471 ignore_policy_sha256: String,
472 entries: Vec<CapturePlanEntry>,
473 exclusions: Vec<CapturePlanExclusion>,
474 ignored_paths: Vec<CaptureIgnoredPath>,
475}
476
477impl CapturePlan {
478 pub fn root(&self) -> &Path {
479 &self.root_attestation.root
480 }
481
482 pub fn folderbase_id(&self) -> &str {
483 &self.root_attestation.folderbase_id
484 }
485
486 pub fn root_instance_sha256(&self) -> &str {
487 &self.root_attestation.root_instance_sha256
488 }
489
490 pub fn root_manifest_sha256(&self) -> &str {
491 &self.root_attestation.manifest_sha256
492 }
493
494 pub fn root_manifest_bytes(&self) -> u64 {
495 self.root_manifest_bytes
496 }
497
498 pub(crate) fn folderbase_version_protocol(&self) -> &'static str {
499 self.folderbase_version_protocol
500 }
501
502 pub fn current_local_head(&self) -> Option<&CaptureLocalHead> {
503 self.current_local_head.as_ref()
504 }
505
506 pub fn ignore_policy_sha256(&self) -> &str {
507 &self.ignore_policy_sha256
508 }
509
510 pub fn entries(&self) -> &[CapturePlanEntry] {
511 &self.entries
512 }
513
514 pub fn exclusions(&self) -> &[CapturePlanExclusion] {
515 &self.exclusions
516 }
517
518 pub fn ignored_paths(&self) -> &[CaptureIgnoredPath] {
519 &self.ignored_paths
520 }
521}
522
523#[derive(Debug, thiserror::Error)]
525#[non_exhaustive]
526pub enum FolderbaseCaptureError {
527 #[error(transparent)]
528 RootAttestation(#[from] RootAttestationError),
529
530 #[error("required capture marker is missing or not a regular file: {0}")]
531 RequiredMarker(PathBuf),
532
533 #[error("capture inventory contains an unsafe portable path: {0}")]
534 UnsafePortablePath(PathBuf),
535
536 #[error("portable capture paths collide: {existing} and {path}")]
537 PortablePathCollision { existing: String, path: String },
538
539 #[error("capture inventory contains an unsafe symlink target at: {0}")]
540 UnsafeSymlinkTarget(PathBuf),
541
542 #[error("Folderbase ignore policy exceeds {maximum_bytes} bytes")]
543 IgnorePolicyTooLarge { maximum_bytes: u64 },
544
545 #[error("Folderbase ignore policy is not valid UTF-8")]
546 IgnorePolicyNotUtf8,
547
548 #[error("Folderbase ignore policy is invalid: {0}")]
549 InvalidIgnorePolicy(String),
550
551 #[error("Local Head exceeds {maximum_bytes} bytes")]
552 LocalHeadTooLarge { maximum_bytes: u64 },
553
554 #[error("Local Head is not a safe regular JSON file")]
555 UnsafeLocalHead,
556
557 #[error("Local Head is invalid: {0}")]
558 InvalidLocalHead(String),
559
560 #[error("capture planning state changed while it was being observed")]
561 PlanningStateChanged,
562
563 #[error("capture state changed after planning at: {0}")]
564 CaptureStateChanged(PathBuf),
565
566 #[error("capture plan belongs to a different Folderbase Version Store")]
567 PlanStoreMismatch,
568
569 #[error("Local Head changed after capture planning")]
570 LocalHeadChanged,
571
572 #[error("the prior Local Head cannot be verified: {0}")]
573 InvalidPriorLocalHead(String),
574
575 #[error("a prior live Path Binding became hidden by capture policy or an exclusion: {0}")]
576 PriorBindingHidden(PathBuf),
577
578 #[error("durable capture transaction is invalid: {0}")]
579 InvalidCaptureTransaction(String),
580
581 #[error("no Local Head exists to restore from")]
582 MissingLocalHead,
583
584 #[error("the current Local Head has no Tombstone at: {0}")]
585 TombstoneNotFound(PathBuf),
586
587 #[error("the current Tombstone kind is not supported by v1 restore at: {0}")]
588 UnsupportedTombstoneKind(PathBuf),
589
590 #[error("Tombstone restore ancestry is invalid: {0}")]
591 InvalidRestoreAncestry(String),
592
593 #[error("durable Tombstone restore transaction is invalid: {0}")]
594 InvalidRestoreTransaction(String),
595
596 #[error(
597 "Tombstone restore authority maintenance is required at the bounded limit of {maximum}"
598 )]
599 RestoreAuthorityMaintenanceRequired { maximum: usize },
600
601 #[error("Tombstone restore namespace repair is required before retrying at: {0}")]
602 RestoreNamespaceRepairRequired(PathBuf),
603
604 #[error("Tombstone restore refuses to overwrite the occupied path: {0}")]
605 RestoreTargetOccupied(PathBuf),
606
607 #[error("another Folderbase transaction is active: {0}")]
608 ConflictingTransaction(&'static str),
609
610 #[error(transparent)]
611 LocalStore(#[from] FolderbaseError),
612
613 #[error(transparent)]
614 FolderbaseVersion(#[from] FolderbaseVersionError),
615
616 #[error("capture inventory exceeded the {limit} limit of {maximum} at {path}")]
617 InventoryLimitExceeded {
618 limit: CapturePlanLimitKind,
619 maximum: u64,
620 path: PathBuf,
621 },
622
623 #[error("filesystem I/O failed while planning capture at {path}: {source}")]
624 Io {
625 path: PathBuf,
626 #[source]
627 source: io::Error,
628 },
629}
630
631#[derive(Debug)]
633pub struct FolderbaseVersionStore {
634 pub(crate) root_attestation: FolderbaseRootAttestation,
635 pub(crate) root_instance_authority: RootInstanceAuthority,
636 pub(crate) protocol_profile: ManifestProtocolProfile,
637}
638
639impl FolderbaseVersionStore {
640 pub fn open(root: impl AsRef<Path>) -> Result<Self, FolderbaseCaptureError> {
642 let requested_root = root.as_ref();
643 let (requested_attestation, _, requested_profile) =
644 attest_folderbase_root_with_profile(requested_root)?;
645 let canonical_root =
646 requested_root
647 .canonicalize()
648 .map_err(|source| FolderbaseCaptureError::Io {
649 path: requested_root.to_path_buf(),
650 source,
651 })?;
652 let (root_attestation, root_instance_authority, protocol_profile) =
653 attest_folderbase_root_with_profile(&canonical_root)?;
654 if requested_attestation.folderbase_id != root_attestation.folderbase_id
655 || requested_attestation.protocol_version != root_attestation.protocol_version
656 || requested_attestation.manifest_sha256 != root_attestation.manifest_sha256
657 || requested_attestation.root_instance_sha256 != root_attestation.root_instance_sha256
658 || requested_profile != protocol_profile
659 {
660 return Err(RootAttestationError::RootChangedDuringAttestation.into());
661 }
662 let root_capability = open_planning_root(&canonical_root)?;
663 verify_root_capability(&root_capability, &canonical_root)?;
664 let legacy_root_files = protocol_profile.requires_legacy_root_files();
665 if legacy_root_files {
666 require_regular_marker(
667 &root_capability,
668 &canonical_root,
669 Path::new(".folderbaseignore"),
670 )?;
671 }
672 read_local_head(
673 &root_attestation,
674 &root_instance_authority,
675 &root_capability,
676 )?;
677 verify_root_capability(&root_capability, &canonical_root)?;
678 Ok(Self {
679 root_attestation,
680 root_instance_authority,
681 protocol_profile,
682 })
683 }
684
685 pub fn plan_capture(&self) -> Result<CapturePlan, FolderbaseCaptureError> {
687 let (current, _, current_profile) =
688 attest_folderbase_root_with_profile(&self.root_attestation.root)?;
689 if current.root_instance_sha256 != self.root_attestation.root_instance_sha256 {
690 return Err(RootAttestationError::RootChangedDuringAttestation.into());
691 }
692 if current_profile != self.protocol_profile {
693 return Err(RootAttestationError::RootChangedDuringAttestation.into());
694 }
695 let root_capability = open_planning_root(¤t.root)?;
696 verify_root_capability(&root_capability, ¤t.root)?;
697 let legacy_root_files = current_profile.requires_legacy_root_files();
698 if legacy_root_files {
699 require_regular_marker(
700 &root_capability,
701 ¤t.root,
702 Path::new(".folderbaseignore"),
703 )?;
704 }
705 let root_manifest_bytes = protocol_file_length(
706 &root_capability,
707 ¤t.root,
708 Path::new(".folderbase/manifest.json"),
709 )?;
710 let ignore = read_ignore_policy(&root_capability, ¤t.root, ¤t_profile)?;
711 let current_local_head =
712 read_local_head(¤t, &self.root_instance_authority, &root_capability)?;
713 let restore_authorities = read_restore_authorities(
714 ¤t,
715 &self.root_instance_authority,
716 MAX_RESTORE_AUTHORITIES,
717 )?;
718
719 let mut planner = CapturePlanner::new(
720 ¤t.root,
721 &ignore,
722 restore_authorities,
723 legacy_root_files,
724 );
725 planner.visit_directory(&root_capability, Path::new(""))?;
726 verify_root_capability(&root_capability, ¤t.root)?;
727
728 let mut entries = planner.entries;
729 let mut exclusions = planner.exclusions;
730 let mut ignored_paths = planner.ignored_paths;
731 entries.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
732 exclusions.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
733 ignored_paths.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
734 let nested_boundaries = exclusions
735 .iter()
736 .filter(|exclusion| exclusion.kind == CaptureExclusionKind::NestedFolderbase)
737 .map(|exclusion| exclusion.path.clone())
738 .collect::<Vec<_>>();
739 validate_capture_symlink_targets(
740 entries.iter().filter_map(|entry| {
741 entry
742 .symlink_target
743 .as_deref()
744 .map(|target| (entry.path.as_str(), target))
745 }),
746 &nested_boundaries,
747 )
748 .map_err(|path| FolderbaseCaptureError::UnsafeSymlinkTarget(PathBuf::from(path)))?;
749 let final_ignore = read_ignore_policy(&root_capability, ¤t.root, ¤t_profile)?;
750 let final_local_head =
751 read_local_head(¤t, &self.root_instance_authority, &root_capability)?;
752 let final_manifest_bytes = protocol_file_length(
753 &root_capability,
754 ¤t.root,
755 Path::new(".folderbase/manifest.json"),
756 )?;
757 verify_root_capability(&root_capability, ¤t.root)?;
758 let (final_attestation, _, final_profile) =
759 attest_folderbase_root_with_profile(¤t.root)?;
760 if final_local_head != current_local_head
761 || final_ignore.sha256 != ignore.sha256
762 || final_attestation != current
763 || final_profile != current_profile
764 || final_manifest_bytes != root_manifest_bytes
765 {
766 return Err(FolderbaseCaptureError::PlanningStateChanged);
767 }
768
769 Ok(CapturePlan {
770 root_attestation: current,
771 root_manifest_bytes,
772 folderbase_version_protocol: current_profile.folderbase_version_protocol(),
773 current_local_head,
774 ignore_policy_sha256: ignore.sha256,
775 entries,
776 exclusions,
777 ignored_paths,
778 })
779 }
780}
781
782struct CapturePlanner<'a> {
783 root: &'a Path,
784 ignore: &'a IgnorePolicy,
785 restore_authorities: RestoreAuthorityRegistry,
786 legacy_root_files: bool,
787 entries: Vec<CapturePlanEntry>,
788 exclusions: Vec<CapturePlanExclusion>,
789 ignored_paths: Vec<CaptureIgnoredPath>,
790 path_index: CapturePathIndex,
791}
792
793struct ObservedRestoreAuthority {
794 record: RestoreAuthorityRecord,
795 encoded: Vec<u8>,
796}
797
798struct RestoreAuthorityRegistry {
799 state: FolderbaseState,
800 records: Vec<ObservedRestoreAuthority>,
801}
802
803impl RestoreAuthorityRegistry {
804 fn validated_link_commitment(
805 &self,
806 workspace_identity: &str,
807 link_count: usize,
808 workspace_path: &str,
809 display_path: &Path,
810 ) -> Result<CaptureLinkCommitment, FolderbaseCaptureError> {
811 validated_link_commitment(
812 &self.state,
813 &self.records,
814 workspace_identity,
815 link_count,
816 workspace_path,
817 display_path,
818 )
819 }
820}
821
822fn validated_link_commitment(
823 state: &FolderbaseState,
824 records: &[ObservedRestoreAuthority],
825 workspace_identity: &str,
826 link_count: usize,
827 workspace_path: &str,
828 display_path: &Path,
829) -> Result<CaptureLinkCommitment, FolderbaseCaptureError> {
830 let mut validated_paths = BTreeSet::new();
831 for observed in records.iter().filter(|observed| {
832 observed.record.workspace_path == workspace_path
833 && observed.record.published_identity_sha256 == workspace_identity
834 }) {
835 let record_path = restore_authority_record_path(&observed.record.transaction_id);
836 if state
837 .read_bounded(&record_path, MAX_RESTORE_AUTHORITY_BYTES)?
838 .as_deref()
839 != Some(observed.encoded.as_slice())
840 {
841 return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
842 "restore authority changed during capture planning".to_owned(),
843 ));
844 }
845 let observed_identity = state.planned_workspace_restore_identity_sha256(
846 Path::new(&observed.record.private_stage_path),
847 Path::new(workspace_path),
848 )?;
849 if observed_identity != workspace_identity {
850 return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
851 "restore authority no longer names the current workspace file".to_owned(),
852 ));
853 }
854 if !validated_paths.insert(observed.record.private_stage_path.as_str()) {
855 return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
856 "restore authorities name one private link more than once".to_owned(),
857 ));
858 }
859 }
860 state.verify_still_attached()?;
861 let mut authorities = records
862 .iter()
863 .filter(|observed| {
864 observed.record.workspace_path == workspace_path
865 && observed.record.published_identity_sha256 == workspace_identity
866 })
867 .map(|observed| {
868 let receipt_path = restore_authority_record_path(&observed.record.transaction_id);
869 CaptureAuthorityLink {
870 receipt_path: receipt_path
871 .to_str()
872 .expect("restore authority paths are UTF-8")
873 .to_owned(),
874 receipt_sha256: format!("{:x}", Sha256::digest(&observed.encoded)),
875 private_stage_path: observed.record.private_stage_path.clone(),
876 published_identity_sha256: observed.record.published_identity_sha256.clone(),
877 }
878 })
879 .collect::<Vec<_>>();
880 authorities.sort_by(|left, right| left.receipt_path.cmp(&right.receipt_path));
881 let authority_set_sha256 =
882 (!authorities.is_empty()).then(|| capture_authority_set_sha256(&authorities));
883 Ok(CaptureLinkCommitment {
884 expected_live_link_count: u64::try_from(link_count)
885 .map_err(|_| FolderbaseCaptureError::CaptureStateChanged(display_path.to_path_buf()))?,
886 authority_set_sha256,
887 authorities,
888 })
889}
890
891fn capture_authority_set_sha256(authorities: &[CaptureAuthorityLink]) -> String {
892 #[derive(Serialize)]
893 struct AuthoritySet<'a> {
894 format: &'static str,
895 authorities: &'a [CaptureAuthorityLink],
896 }
897
898 let encoded = serde_json::to_vec(&AuthoritySet {
899 format: "folderbase-capture-authority-set-v1",
900 authorities,
901 })
902 .expect("capture authority commitments are serializable");
903 format!("{:x}", Sha256::digest(encoded))
904}
905
906pub(crate) fn restore_authority_count(
907 root_attestation: &FolderbaseRootAttestation,
908 root_instance_authority: &RootInstanceAuthority,
909 maximum: usize,
910) -> Result<usize, FolderbaseCaptureError> {
911 Ok(
912 read_restore_authorities(root_attestation, root_instance_authority, maximum)?
913 .records
914 .len(),
915 )
916}
917
918fn read_restore_authorities(
919 root_attestation: &FolderbaseRootAttestation,
920 root_instance_authority: &RootInstanceAuthority,
921 maximum: usize,
922) -> Result<RestoreAuthorityRegistry, FolderbaseCaptureError> {
923 let state = FolderbaseState::open_existing_read_only(&root_attestation.root)?;
924 let records =
925 read_restore_authority_records(root_attestation, root_instance_authority, &state, maximum)?;
926 Ok(RestoreAuthorityRegistry { state, records })
927}
928
929fn read_restore_authority_records(
930 root_attestation: &FolderbaseRootAttestation,
931 root_instance_authority: &RootInstanceAuthority,
932 state: &FolderbaseState,
933 maximum: usize,
934) -> Result<Vec<ObservedRestoreAuthority>, FolderbaseCaptureError> {
935 let names = match state.private_directory_names(
936 Path::new(RESTORE_AUTHORITIES_DIRECTORY),
937 MAX_RESTORE_AUTHORITIES.saturating_add(1024),
938 ) {
939 Ok(names) => names,
940 Err(FolderbaseError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
941 Vec::new()
942 }
943 Err(error) => return Err(error.into()),
944 };
945 let mut records = Vec::new();
946 for name in names {
947 let Some(transaction_id) = name.to_str() else {
948 continue;
949 };
950 let Some(uuid) = transaction_id.strip_prefix("fbrestore_") else {
951 continue;
952 };
953 if uuid::Uuid::parse_str(uuid).is_err() {
954 continue;
955 }
956 let relative = restore_authority_record_path(transaction_id);
957 let Some(encoded) = state.read_bounded(&relative, MAX_RESTORE_AUTHORITY_BYTES)? else {
958 continue;
959 };
960 let record: RestoreAuthorityRecord =
961 serde_json::from_slice(&encoded).map_err(|source| {
962 FolderbaseCaptureError::InvalidRestoreTransaction(format!(
963 "restore authority is invalid JSON: {source}"
964 ))
965 })?;
966 validate_restore_authority(
967 root_attestation,
968 root_instance_authority,
969 transaction_id,
970 &record,
971 )?;
972 records.push(ObservedRestoreAuthority { record, encoded });
973 if records.len() > maximum {
974 return Err(FolderbaseCaptureError::RestoreAuthorityMaintenanceRequired { maximum });
975 }
976 }
977 state.verify_still_attached()?;
978 Ok(records)
979}
980
981pub(crate) fn verify_capture_link_commitment(
982 root_attestation: &FolderbaseRootAttestation,
983 root_instance_authority: &RootInstanceAuthority,
984 state: &FolderbaseState,
985 entry: &CapturePlanEntry,
986 workspace_file: &fs::File,
987) -> Result<(), FolderbaseCaptureError> {
988 if entry.kind() != CaptureEntryKind::RegularFile {
989 return Ok(());
990 }
991 let display_path = root_attestation.root.join(entry.path());
992 let link_count = usize::try_from(stable_file_link_count(workspace_file).map_err(|source| {
993 FolderbaseCaptureError::Io {
994 path: display_path.clone(),
995 source,
996 }
997 })?)
998 .map_err(|_| FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(entry.path())))?;
999 let records = read_restore_authority_records(
1000 root_attestation,
1001 root_instance_authority,
1002 state,
1003 MAX_RESTORE_AUTHORITIES,
1004 )?;
1005 let workspace_identity = stable_file_identity_sha256(workspace_file).map_err(|source| {
1006 FolderbaseCaptureError::Io {
1007 path: display_path.clone(),
1008 source,
1009 }
1010 })?;
1011 let actual = validated_link_commitment(
1012 state,
1013 &records,
1014 &workspace_identity,
1015 link_count,
1016 entry.path(),
1017 &display_path,
1018 )?;
1019 let exact_expected_link_count = entry
1020 .link_commitment()
1021 .authorities
1022 .len()
1023 .checked_add(1)
1024 .and_then(|count| u64::try_from(count).ok());
1025 let exact_actual_link_count = actual
1026 .authorities
1027 .len()
1028 .checked_add(1)
1029 .and_then(|count| u64::try_from(count).ok());
1030 let expected_digest = (!entry.link_commitment().authorities.is_empty())
1031 .then(|| capture_authority_set_sha256(&entry.link_commitment().authorities));
1032 if exact_expected_link_count != Some(entry.link_commitment().expected_live_link_count)
1033 || entry.link_commitment().authority_set_sha256 != expected_digest
1034 || exact_actual_link_count != Some(actual.expected_live_link_count)
1035 || &actual != entry.link_commitment()
1036 {
1037 return Err(FolderbaseCaptureError::CaptureStateChanged(PathBuf::from(
1038 entry.path(),
1039 )));
1040 }
1041 Ok(())
1042}
1043
1044fn validate_restore_authority(
1045 root_attestation: &FolderbaseRootAttestation,
1046 root_instance_authority: &RootInstanceAuthority,
1047 transaction_id: &str,
1048 record: &RestoreAuthorityRecord,
1049) -> Result<(), FolderbaseCaptureError> {
1050 if record.format != RESTORE_AUTHORITY_FORMAT_V1
1051 || record.folderbase_id != root_attestation.folderbase_id
1052 || root_instance_authority
1053 .admit(&record.root_instance_sha256)
1054 .is_none()
1055 || record.transaction_id != transaction_id
1056 || record.private_stage_path
1057 != restore_stage_path(transaction_id)
1058 .to_str()
1059 .expect("restore authority paths are UTF-8")
1060 || validate_capture_path(&record.workspace_path).is_err()
1061 || validate_capture_sha256(&record.published_identity_sha256).is_err()
1062 {
1063 return Err(FolderbaseCaptureError::InvalidRestoreTransaction(
1064 "restore authority does not match its Folderbase, path, identity, or slot".to_owned(),
1065 ));
1066 }
1067 Ok(())
1068}
1069
1070struct CaptureDirectoryFrame {
1071 directory: Dir,
1072 entries: ReadDir,
1073 relative_parent: PathBuf,
1074 completion: Option<CaptureChildVerification>,
1075}
1076
1077struct CaptureChildVerification {
1078 name: OsString,
1079 identity: PhysicalIdentity,
1080 display_path: PathBuf,
1081}
1082
1083struct PendingCaptureDirectory {
1084 directory: Dir,
1085 relative_parent: PathBuf,
1086 verification: CaptureChildVerification,
1087}
1088
1089impl<'a> CapturePlanner<'a> {
1090 fn new(
1091 root: &'a Path,
1092 ignore: &'a IgnorePolicy,
1093 restore_authorities: RestoreAuthorityRegistry,
1094 legacy_root_files: bool,
1095 ) -> Self {
1096 Self {
1097 root,
1098 ignore,
1099 restore_authorities,
1100 legacy_root_files,
1101 entries: Vec::new(),
1102 exclusions: Vec::new(),
1103 ignored_paths: Vec::new(),
1104 path_index: CapturePathIndex::default(),
1105 }
1106 }
1107
1108 fn visit_directory(
1109 &mut self,
1110 directory: &Dir,
1111 relative_parent: &Path,
1112 ) -> Result<(), FolderbaseCaptureError> {
1113 let root_directory =
1114 directory
1115 .try_clone()
1116 .map_err(|source| FolderbaseCaptureError::Io {
1117 path: self.root.join(relative_parent),
1118 source,
1119 })?;
1120 let mut stack = vec![capture_directory_frame(
1121 root_directory,
1122 relative_parent.to_path_buf(),
1123 self.root,
1124 None,
1125 )?];
1126
1127 while !stack.is_empty() {
1128 let next = stack
1129 .last_mut()
1130 .expect("non-empty traversal stack")
1131 .entries
1132 .next();
1133 let Some(entry) = next else {
1134 let completed = stack.pop().expect("non-empty traversal stack");
1135 if let Some(verification) = completed.completion {
1136 let parent = stack
1137 .last()
1138 .ok_or(FolderbaseCaptureError::PlanningStateChanged)?;
1139 verify_child_identity(
1140 &parent.directory,
1141 &verification.name,
1142 &verification.identity,
1143 &verification.display_path,
1144 )?;
1145 }
1146 continue;
1147 };
1148 let entry = entry.map_err(|source| {
1149 let relative_parent = &stack
1150 .last()
1151 .expect("non-empty traversal stack")
1152 .relative_parent;
1153 FolderbaseCaptureError::Io {
1154 path: self.root.join(relative_parent),
1155 source,
1156 }
1157 })?;
1158 let pending = {
1159 let current = stack.last().expect("non-empty traversal stack");
1160 self.visit_entry(¤t.directory, ¤t.relative_parent, entry)?
1161 };
1162 if let Some(pending) = pending {
1163 stack.push(capture_directory_frame(
1164 pending.directory,
1165 pending.relative_parent,
1166 self.root,
1167 Some(pending.verification),
1168 )?);
1169 }
1170 }
1171 Ok(())
1172 }
1173
1174 fn visit_entry(
1175 &mut self,
1176 directory: &Dir,
1177 relative_parent: &Path,
1178 entry: DirEntry,
1179 ) -> Result<Option<PendingCaptureDirectory>, FolderbaseCaptureError> {
1180 let name = entry.file_name();
1181 let relative = relative_parent.join(&name);
1182 let display_path = self.root.join(&relative);
1183 let metadata =
1184 directory
1185 .symlink_metadata(&name)
1186 .map_err(|source| FolderbaseCaptureError::Io {
1187 path: display_path.clone(),
1188 source,
1189 })?;
1190
1191 if name == OsStr::new(".folderbase") {
1192 return Ok(None);
1193 }
1194 if is_folderbase_state_component(&name) {
1195 return Err(FolderbaseCaptureError::UnsafePortablePath(relative));
1196 }
1197
1198 let required_marker = relative == Path::new(".folderbaseignore")
1199 || (self.legacy_root_files && relative == Path::new("FOLDERBASE.md"));
1200 let force_included = relative == Path::new(".folderbaseignore")
1201 || (self.legacy_root_files && relative == Path::new("FOLDERBASE.md"));
1202 if !force_included
1203 && matches!(
1204 self.ignore
1205 .matcher
1206 .matched(self.root.join(&relative), metadata.is_dir()),
1207 Match::Ignore(_)
1208 )
1209 {
1210 self.ensure_capacity(&relative)?;
1211 self.ignored_paths.push(CaptureIgnoredPath {
1212 path: portable_relative(&relative)?,
1213 });
1214 return Ok(None);
1215 }
1216
1217 self.ensure_capacity(&relative)?;
1218 let path = portable_relative(&relative)?;
1219 validate_capture_path(&path)
1220 .map_err(|_| FolderbaseCaptureError::UnsafePortablePath(relative.clone()))?;
1221 self.path_index.insert(&path)?;
1222
1223 if metadata.is_dir() && !metadata.file_type().is_symlink() {
1224 let (child, identity) = open_stable_child(directory, &name, &display_path)?;
1225 match classify_nested_folderbase_boundary(&child, &display_path)? {
1226 NestedFolderbaseBoundaryKind::ExactBoundary => {
1227 verify_child_identity(directory, &name, &identity, &display_path)?;
1228 self.exclusions.push(CapturePlanExclusion {
1229 path,
1230 kind: CaptureExclusionKind::NestedFolderbase,
1231 reason: CaptureExclusionReason::NestedFolderbaseBoundary,
1232 });
1233 return Ok(None);
1234 }
1235 NestedFolderbaseBoundaryKind::UnsafeAliasShape => {
1236 return Err(FolderbaseCaptureError::UnsafePortablePath(display_path));
1237 }
1238 NestedFolderbaseBoundaryKind::None => {}
1239 }
1240 self.entries.push(CapturePlanEntry {
1241 path,
1242 kind: CaptureEntryKind::Directory,
1243 bytes: None,
1244 executable: None,
1245 symlink_target: None,
1246 observed: capture_entry_fingerprint(
1247 directory,
1248 &name,
1249 CaptureEntryKind::Directory,
1250 &metadata,
1251 &display_path,
1252 )?,
1253 link_commitment: CaptureLinkCommitment::default(),
1254 });
1255 return Ok(Some(PendingCaptureDirectory {
1256 directory: child,
1257 relative_parent: relative,
1258 verification: CaptureChildVerification {
1259 name,
1260 identity,
1261 display_path,
1262 },
1263 }));
1264 }
1265
1266 let mut link_commitment = CaptureLinkCommitment::default();
1267 let mut regular_observed = None;
1268 let mut regular_bytes = None;
1269 let mut regular_executable = None;
1270 if metadata.is_file() && !metadata.file_type().is_symlink() {
1271 let (observed, workspace_identity, link_count) =
1272 planned_regular_link_observation(directory, &name, &metadata, &display_path)?;
1273 regular_bytes = Some(observed.bytes);
1274 regular_executable = Some(observed.executable);
1275 regular_observed = Some(observed);
1276 link_commitment = self.restore_authorities.validated_link_commitment(
1277 &workspace_identity,
1278 link_count,
1279 &path,
1280 &display_path,
1281 )?;
1282 if link_count != link_commitment.authorities.len().saturating_add(1) {
1283 if required_marker {
1284 return Err(FolderbaseCaptureError::RequiredMarker(display_path));
1285 }
1286 self.exclusions.push(CapturePlanExclusion {
1287 path,
1288 kind: CaptureExclusionKind::HardLink,
1289 reason: CaptureExclusionReason::UnsupportedV1,
1290 });
1291 return Ok(None);
1292 }
1293 }
1294
1295 if let Some(kind) = unsupported_entry_kind(directory, &name, &display_path, &metadata)? {
1296 if required_marker {
1297 return Err(FolderbaseCaptureError::RequiredMarker(display_path));
1298 }
1299 self.exclusions.push(CapturePlanExclusion {
1300 path,
1301 kind,
1302 reason: CaptureExclusionReason::UnsupportedV1,
1303 });
1304 return Ok(None);
1305 }
1306
1307 let (kind, bytes, executable, symlink_target) = if metadata.file_type().is_symlink() {
1308 let target = read_stable_symlink(directory, &name, &relative, &display_path)?;
1309 (CaptureEntryKind::Symlink, None, None, Some(target))
1310 } else if metadata.is_file() {
1311 let bytes = regular_bytes.ok_or(FolderbaseCaptureError::PlanningStateChanged)?;
1312 if bytes > MAX_OBJECT_BYTES {
1313 return Err(FolderbaseCaptureError::InventoryLimitExceeded {
1314 limit: CapturePlanLimitKind::ObjectBytes,
1315 maximum: MAX_OBJECT_BYTES,
1316 path: relative,
1317 });
1318 }
1319 (
1320 CaptureEntryKind::RegularFile,
1321 Some(bytes),
1322 regular_executable,
1323 None,
1324 )
1325 } else {
1326 return Err(FolderbaseCaptureError::PlanningStateChanged);
1327 };
1328 let observed = match kind {
1329 CaptureEntryKind::RegularFile => {
1330 regular_observed.ok_or(FolderbaseCaptureError::PlanningStateChanged)?
1331 }
1332 CaptureEntryKind::Directory | CaptureEntryKind::Symlink => {
1333 capture_entry_fingerprint(directory, &name, kind, &metadata, &display_path)?
1334 }
1335 };
1336 self.entries.push(CapturePlanEntry {
1337 path,
1338 kind,
1339 bytes,
1340 executable,
1341 symlink_target,
1342 observed,
1343 link_commitment,
1344 });
1345 Ok(None)
1346 }
1347
1348 fn ensure_capacity(&self, path: &Path) -> Result<(), FolderbaseCaptureError> {
1349 ensure_record_capacity(
1350 self.entries.len() + self.exclusions.len() + self.ignored_paths.len(),
1351 path,
1352 )
1353 }
1354}
1355
1356fn capture_directory_frame(
1357 directory: Dir,
1358 relative_parent: PathBuf,
1359 root: &Path,
1360 completion: Option<CaptureChildVerification>,
1361) -> Result<CaptureDirectoryFrame, FolderbaseCaptureError> {
1362 let entries = directory
1363 .read_dir(".")
1364 .map_err(|source| FolderbaseCaptureError::Io {
1365 path: root.join(&relative_parent),
1366 source,
1367 })?;
1368 Ok(CaptureDirectoryFrame {
1369 directory,
1370 entries,
1371 relative_parent,
1372 completion,
1373 })
1374}
1375
1376struct IgnorePolicy {
1377 matcher: ignore::gitignore::Gitignore,
1378 sha256: String,
1379}
1380
1381#[derive(Default)]
1382struct CapturePathIndex {
1383 exact: BTreeMap<String, String>,
1384 nfc: BTreeMap<String, String>,
1385 folded: BTreeMap<String, String>,
1386}
1387
1388impl CapturePathIndex {
1389 fn insert(&mut self, path: &str) -> Result<(), FolderbaseCaptureError> {
1390 let nfc = path.nfc().collect::<String>();
1391 let folded = nfc
1392 .case_fold()
1393 .collect::<String>()
1394 .nfc()
1395 .collect::<String>();
1396 if let Some(existing) = self.exact.get(path) {
1397 return Err(FolderbaseCaptureError::PortablePathCollision {
1398 existing: existing.clone(),
1399 path: path.to_owned(),
1400 });
1401 }
1402 if let Some(existing) = [self.nfc.get(&nfc), self.folded.get(&folded)]
1403 .into_iter()
1404 .flatten()
1405 .next()
1406 {
1407 return Err(FolderbaseCaptureError::PortablePathCollision {
1408 existing: existing.clone(),
1409 path: path.to_owned(),
1410 });
1411 }
1412 self.exact.insert(path.to_owned(), path.to_owned());
1413 self.nfc.insert(nfc, path.to_owned());
1414 self.folded.insert(folded, path.to_owned());
1415 Ok(())
1416 }
1417}
1418
1419fn portable_relative(path: &Path) -> Result<String, FolderbaseCaptureError> {
1420 let mut parts = Vec::new();
1421 for component in path.components() {
1422 let Component::Normal(part) = component else {
1423 return Err(FolderbaseCaptureError::UnsafePortablePath(
1424 path.to_path_buf(),
1425 ));
1426 };
1427 parts.push(
1428 part.to_str()
1429 .ok_or_else(|| FolderbaseCaptureError::UnsafePortablePath(path.to_path_buf()))?
1430 .to_owned(),
1431 );
1432 }
1433 if parts.is_empty() {
1434 return Err(FolderbaseCaptureError::UnsafePortablePath(
1435 path.to_path_buf(),
1436 ));
1437 }
1438 Ok(parts.join("/"))
1439}
1440
1441#[cfg(unix)]
1442fn is_executable(metadata: &Metadata) -> bool {
1443 use cap_std::fs::PermissionsExt;
1444
1445 metadata.permissions().mode() & 0o111 != 0
1446}
1447
1448#[cfg(windows)]
1449fn is_executable(_metadata: &Metadata) -> bool {
1450 false
1451}
1452
1453#[cfg(unix)]
1454pub(crate) fn capture_entry_fingerprint(
1455 _directory: &Dir,
1456 _name: &OsStr,
1457 _kind: CaptureEntryKind,
1458 metadata: &Metadata,
1459 _display_path: &Path,
1460) -> Result<CaptureMetadataFingerprint, FolderbaseCaptureError> {
1461 Ok(CaptureMetadataFingerprint::from_cap_metadata(metadata))
1462}
1463
1464#[cfg(windows)]
1465pub(crate) fn capture_entry_fingerprint(
1466 directory: &Dir,
1467 name: &OsStr,
1468 kind: CaptureEntryKind,
1469 metadata: &Metadata,
1470 display_path: &Path,
1471) -> Result<CaptureMetadataFingerprint, FolderbaseCaptureError> {
1472 let file = match kind {
1473 CaptureEntryKind::Directory => directory
1474 .open_dir_nofollow(name)
1475 .map_err(|source| FolderbaseCaptureError::Io {
1476 path: display_path.to_path_buf(),
1477 source,
1478 })?
1479 .into_std_file(),
1480 CaptureEntryKind::RegularFile | CaptureEntryKind::Symlink => {
1481 use cap_std::fs::OpenOptionsExt;
1482 use windows_sys::Win32::Storage::FileSystem::{
1483 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
1484 };
1485
1486 let mut options = OpenOptions::new();
1487 options
1488 .read(true)
1489 .follow(FollowSymlinks::No)
1490 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
1491 directory
1492 .open_with(name, &options)
1493 .map_err(|source| FolderbaseCaptureError::Io {
1494 path: display_path.to_path_buf(),
1495 source,
1496 })?
1497 .into_std()
1498 }
1499 };
1500 let identity = windows_file_identity(&file).map_err(|source| FolderbaseCaptureError::Io {
1501 path: display_path.to_path_buf(),
1502 source,
1503 })?;
1504 Ok(CaptureMetadataFingerprint::from_cap_metadata(metadata)
1505 .with_physical_identity(Some(identity)))
1506}
1507
1508#[cfg(unix)]
1509fn planned_regular_link_observation(
1510 _directory: &Dir,
1511 _name: &OsStr,
1512 metadata: &Metadata,
1513 _display_path: &Path,
1514) -> Result<(CaptureMetadataFingerprint, String, usize), FolderbaseCaptureError> {
1515 use cap_std::fs::MetadataExt;
1516
1517 let link_count = usize::try_from(metadata.nlink())
1518 .map_err(|_| FolderbaseCaptureError::PlanningStateChanged)?;
1519 Ok((
1520 CaptureMetadataFingerprint::from_cap_metadata(metadata),
1521 stable_unix_file_identity_sha256(metadata.dev(), metadata.ino()),
1522 link_count,
1523 ))
1524}
1525
1526#[cfg(windows)]
1527fn planned_regular_link_observation(
1528 directory: &Dir,
1529 name: &OsStr,
1530 metadata: &Metadata,
1531 display_path: &Path,
1532) -> Result<(CaptureMetadataFingerprint, String, usize), FolderbaseCaptureError> {
1533 use cap_std::fs::OpenOptionsExt;
1534 use windows_sys::Win32::Storage::FileSystem::{
1535 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE,
1536 FILE_SHARE_READ, FILE_SHARE_WRITE,
1537 };
1538
1539 let mut options = OpenOptions::new();
1540 options
1541 .access_mode(0)
1542 .follow(FollowSymlinks::No)
1543 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1544 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
1545 let file = directory
1546 .open_with(name, &options)
1547 .map_err(|source| FolderbaseCaptureError::Io {
1548 path: display_path.to_path_buf(),
1549 source,
1550 })?
1551 .into_std();
1552 let identity =
1553 stable_file_identity_sha256(&file).map_err(|source| FolderbaseCaptureError::Io {
1554 path: display_path.to_path_buf(),
1555 source,
1556 })?;
1557 let link_count = usize::try_from(stable_file_link_count(&file).map_err(|source| {
1558 FolderbaseCaptureError::Io {
1559 path: display_path.to_path_buf(),
1560 source,
1561 }
1562 })?)
1563 .map_err(|_| FolderbaseCaptureError::PlanningStateChanged)?;
1564 Ok((
1565 CaptureMetadataFingerprint::from_cap_metadata(metadata).with_physical_identity(Some(
1566 windows_file_identity(&file).map_err(|source| FolderbaseCaptureError::Io {
1567 path: display_path.to_path_buf(),
1568 source,
1569 })?,
1570 )),
1571 identity,
1572 link_count,
1573 ))
1574}
1575
1576#[cfg(windows)]
1577fn windows_file_identity(file: &fs::File) -> io::Result<String> {
1578 use std::{mem::size_of, os::windows::io::AsRawHandle};
1579 use windows_sys::Win32::{
1580 Foundation::HANDLE,
1581 Storage::FileSystem::{FILE_ID_INFO, FileIdInfo, GetFileInformationByHandleEx},
1582 };
1583
1584 let mut information = FILE_ID_INFO::default();
1585 if unsafe {
1586 GetFileInformationByHandleEx(
1587 file.as_raw_handle() as HANDLE,
1588 FileIdInfo,
1589 (&raw mut information).cast(),
1590 size_of::<FILE_ID_INFO>() as u32,
1591 )
1592 } == 0
1593 {
1594 return Err(io::Error::last_os_error());
1595 }
1596 let mut encoded = format!(
1597 "windows-file-id-128:{:016x}:",
1598 information.VolumeSerialNumber
1599 );
1600 for byte in information.FileId.Identifier {
1601 use fmt::Write as _;
1602 let _ = write!(encoded, "{byte:02x}");
1603 }
1604 Ok(encoded)
1605}
1606
1607#[cfg(unix)]
1608fn unsupported_entry_kind(
1609 _directory: &Dir,
1610 _name: &OsStr,
1611 _display_path: &Path,
1612 metadata: &Metadata,
1613) -> Result<Option<CaptureExclusionKind>, FolderbaseCaptureError> {
1614 use cap_std::fs::FileTypeExt;
1615
1616 let file_type = metadata.file_type();
1617 let kind = if file_type.is_fifo() {
1618 Some(CaptureExclusionKind::Fifo)
1619 } else if file_type.is_socket() {
1620 Some(CaptureExclusionKind::Socket)
1621 } else if file_type.is_block_device() {
1622 Some(CaptureExclusionKind::BlockDevice)
1623 } else if file_type.is_char_device() {
1624 Some(CaptureExclusionKind::CharacterDevice)
1625 } else if !metadata.is_file() && !metadata.is_dir() && !metadata.file_type().is_symlink() {
1626 Some(CaptureExclusionKind::OtherSpecial)
1627 } else {
1628 None
1629 };
1630 Ok(kind)
1631}
1632
1633#[cfg(windows)]
1634fn unsupported_entry_kind(
1635 _directory: &Dir,
1636 _name: &OsStr,
1637 _display_path: &Path,
1638 _metadata: &Metadata,
1639) -> Result<Option<CaptureExclusionKind>, FolderbaseCaptureError> {
1640 Ok(None)
1641}
1642
1643fn open_planning_root(root: &Path) -> Result<Dir, FolderbaseCaptureError> {
1644 let mut options = fs::OpenOptions::new();
1645 options.read(true);
1646 #[cfg(unix)]
1647 {
1648 use std::os::unix::fs::OpenOptionsExt;
1649
1650 options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
1651 }
1652 #[cfg(windows)]
1653 {
1654 use std::os::windows::fs::OpenOptionsExt;
1655 use windows_sys::Win32::Storage::FileSystem::{
1656 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE,
1657 FILE_SHARE_READ, FILE_SHARE_WRITE,
1658 };
1659
1660 options
1661 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1662 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
1663 }
1664 let file = options
1665 .open(root)
1666 .map_err(|source| FolderbaseCaptureError::Io {
1667 path: root.to_path_buf(),
1668 source,
1669 })?;
1670 let metadata = file
1671 .metadata()
1672 .map_err(|source| FolderbaseCaptureError::Io {
1673 path: root.to_path_buf(),
1674 source,
1675 })?;
1676 if !metadata.is_dir() || std_metadata_is_link_or_reparse(&metadata) {
1677 return Err(FolderbaseCaptureError::PlanningStateChanged);
1678 }
1679 Ok(Dir::from_std_file(file))
1680}
1681
1682#[cfg(unix)]
1683fn std_metadata_is_link_or_reparse(metadata: &fs::Metadata) -> bool {
1684 metadata.file_type().is_symlink()
1685}
1686
1687#[cfg(windows)]
1688fn std_metadata_is_link_or_reparse(metadata: &fs::Metadata) -> bool {
1689 use std::os::windows::fs::MetadataExt;
1690 use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
1691
1692 metadata.file_type().is_symlink()
1693 || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
1694}
1695
1696fn directory_identity(
1697 directory: &Dir,
1698 display_path: &Path,
1699) -> Result<PhysicalIdentity, FolderbaseCaptureError> {
1700 let file = directory
1701 .try_clone()
1702 .map_err(|source| FolderbaseCaptureError::Io {
1703 path: display_path.to_path_buf(),
1704 source,
1705 })?
1706 .into_std_file();
1707 PhysicalIdentity::from_file(&file).map_err(|source| FolderbaseCaptureError::Io {
1708 path: display_path.to_path_buf(),
1709 source,
1710 })
1711}
1712
1713fn verify_root_capability(expected: &Dir, root: &Path) -> Result<(), FolderbaseCaptureError> {
1714 let expected = directory_identity(expected, root)?;
1715 let reopened = open_planning_root(root)?;
1716 if directory_identity(&reopened, root)? != expected {
1717 return Err(FolderbaseCaptureError::PlanningStateChanged);
1718 }
1719 Ok(())
1720}
1721
1722fn open_stable_child(
1723 parent: &Dir,
1724 name: &OsStr,
1725 display_path: &Path,
1726) -> Result<(Dir, PhysicalIdentity), FolderbaseCaptureError> {
1727 let child = parent
1728 .open_dir_nofollow(name)
1729 .map_err(|source| FolderbaseCaptureError::Io {
1730 path: display_path.to_path_buf(),
1731 source,
1732 })?;
1733 let identity = directory_identity(&child, display_path)?;
1734 verify_child_identity(parent, name, &identity, display_path)?;
1735 Ok((child, identity))
1736}
1737
1738fn verify_child_identity(
1739 parent: &Dir,
1740 name: &OsStr,
1741 expected: &PhysicalIdentity,
1742 display_path: &Path,
1743) -> Result<(), FolderbaseCaptureError> {
1744 let reopened = parent
1745 .open_dir_nofollow(name)
1746 .map_err(|source| FolderbaseCaptureError::Io {
1747 path: display_path.to_path_buf(),
1748 source,
1749 })?;
1750 if &directory_identity(&reopened, display_path)? != expected {
1751 return Err(FolderbaseCaptureError::PlanningStateChanged);
1752 }
1753 Ok(())
1754}
1755
1756fn read_stable_symlink(
1757 directory: &Dir,
1758 name: &OsStr,
1759 relative: &Path,
1760 display_path: &Path,
1761) -> Result<String, FolderbaseCaptureError> {
1762 let target = directory
1763 .read_link(name)
1764 .map_err(|source| FolderbaseCaptureError::Io {
1765 path: display_path.to_path_buf(),
1766 source,
1767 })?;
1768 let rechecked = directory
1769 .read_link(name)
1770 .map_err(|source| FolderbaseCaptureError::Io {
1771 path: display_path.to_path_buf(),
1772 source,
1773 })?;
1774 if rechecked != target {
1775 return Err(FolderbaseCaptureError::PlanningStateChanged);
1776 }
1777 target
1778 .to_str()
1779 .map(str::to_owned)
1780 .ok_or_else(|| FolderbaseCaptureError::UnsafeSymlinkTarget(relative.to_path_buf()))
1781}
1782
1783fn ensure_record_capacity(current: usize, path: &Path) -> Result<(), FolderbaseCaptureError> {
1784 if current == MAX_CAPTURE_PLAN_RECORDS {
1785 return Err(FolderbaseCaptureError::InventoryLimitExceeded {
1786 limit: CapturePlanLimitKind::Entries,
1787 maximum: MAX_CAPTURE_PLAN_RECORDS as u64,
1788 path: path.to_path_buf(),
1789 });
1790 }
1791 Ok(())
1792}
1793
1794fn read_local_head(
1795 attestation: &FolderbaseRootAttestation,
1796 root_instance_authority: &RootInstanceAuthority,
1797 root: &Dir,
1798) -> Result<Option<CaptureLocalHead>, FolderbaseCaptureError> {
1799 let path = attestation.root.join(LOCAL_HEAD_PATH);
1800 let state = root
1801 .open_dir_nofollow(".folderbase")
1802 .map_err(|_| FolderbaseCaptureError::UnsafeLocalHead)?;
1803 let local_metadata = match state.symlink_metadata("local") {
1804 Ok(metadata) => metadata,
1805 Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(None),
1806 Err(source) => return Err(FolderbaseCaptureError::Io { path, source }),
1807 };
1808 if local_metadata.file_type().is_symlink() || !local_metadata.is_dir() {
1809 return Err(FolderbaseCaptureError::UnsafeLocalHead);
1810 }
1811 let local = state
1812 .open_dir_nofollow("local")
1813 .map_err(|_| FolderbaseCaptureError::UnsafeLocalHead)?;
1814 let metadata = match local.symlink_metadata("head.json") {
1815 Ok(metadata) => metadata,
1816 Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(None),
1817 Err(source) => return Err(FolderbaseCaptureError::Io { path, source }),
1818 };
1819 if metadata.file_type().is_symlink() || !metadata.is_file() {
1820 return Err(FolderbaseCaptureError::UnsafeLocalHead);
1821 }
1822 if metadata.len() > MAX_LOCAL_HEAD_BYTES {
1823 return Err(FolderbaseCaptureError::LocalHeadTooLarge {
1824 maximum_bytes: MAX_LOCAL_HEAD_BYTES,
1825 });
1826 }
1827 let mut file = open_regular_nofollow(&local, Path::new("head.json"))
1828 .map_err(|_| FolderbaseCaptureError::UnsafeLocalHead)?;
1829 let mut encoded = Vec::new();
1830 file.by_ref()
1831 .take(MAX_LOCAL_HEAD_BYTES + 1)
1832 .read_to_end(&mut encoded)
1833 .map_err(|source| FolderbaseCaptureError::Io {
1834 path: path.clone(),
1835 source,
1836 })?;
1837 if encoded.len() as u64 > MAX_LOCAL_HEAD_BYTES {
1838 return Err(FolderbaseCaptureError::LocalHeadTooLarge {
1839 maximum_bytes: MAX_LOCAL_HEAD_BYTES,
1840 });
1841 }
1842 let head: LocalHeadWire = serde_json::from_slice(&encoded)
1843 .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
1844 let (folderbase_id, root_instance_sha256, version_id, version_sha256, authority) = match head {
1845 LocalHeadWire::V2(head) if head.format == "folderbase-local-head-v2" => (
1846 head.folderbase_id,
1847 head.root_instance_sha256,
1848 head.version_id,
1849 head.version_sha256,
1850 head.authority,
1851 ),
1852 LocalHeadWire::V1(head) if head.format == "folderbase-local-head-v1" => (
1853 head.folderbase_id,
1854 head.root_instance_sha256,
1855 head.version_id,
1856 head.version_sha256,
1857 LocalHeadAuthority::CaptureTransactionV1 {
1858 sha256: head.transaction_sha256,
1859 },
1860 ),
1861 _ => {
1862 return Err(FolderbaseCaptureError::InvalidLocalHead(
1863 "record has an unsupported Local Head format".to_owned(),
1864 ));
1865 }
1866 };
1867 if folderbase_id != attestation.folderbase_id
1868 || root_instance_authority
1869 .admit(&root_instance_sha256)
1870 .is_none()
1871 {
1872 return Err(FolderbaseCaptureError::InvalidLocalHead(
1873 "record does not bind the attested physical Folderbase Root".to_owned(),
1874 ));
1875 }
1876 validate_capture_sha256(&root_instance_sha256)
1877 .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
1878 validate_capture_version_id(&version_id)
1879 .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
1880 validate_capture_sha256(&version_sha256)
1881 .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
1882 validate_capture_sha256(authority.sha256())
1883 .map_err(|error| FolderbaseCaptureError::InvalidLocalHead(error.to_string()))?;
1884 if let LocalHeadAuthority::VersionDerivedV1 { sha256 } = &authority {
1885 let expected = version_derived_local_head_sha256(
1886 &folderbase_id,
1887 &root_instance_sha256,
1888 &version_id,
1889 &version_sha256,
1890 )?;
1891 if sha256 != &expected {
1892 return Err(FolderbaseCaptureError::InvalidLocalHead(
1893 "version-derived Local Head authority does not match its bound Folderbase Version"
1894 .to_owned(),
1895 ));
1896 }
1897 }
1898 Ok(Some(CaptureLocalHead {
1899 version_id,
1900 version_sha256,
1901 authority,
1902 }))
1903}
1904
1905fn read_ignore_policy(
1906 root_directory: &Dir,
1907 root: &Path,
1908 profile: &ManifestProtocolProfile,
1909) -> Result<IgnorePolicy, FolderbaseCaptureError> {
1910 let required = profile.requires_legacy_root_files();
1911 let path = root.join(".folderbaseignore");
1912 let mut encoded = Vec::new();
1913 let present = match root_directory.symlink_metadata(".folderbaseignore") {
1914 Ok(metadata) => {
1915 if metadata.file_type().is_symlink() || !metadata.is_file() {
1916 return Err(FolderbaseCaptureError::RequiredMarker(path));
1917 }
1918 if metadata.len() > MAX_FOLDERBASEIGNORE_BYTES {
1919 return Err(FolderbaseCaptureError::IgnorePolicyTooLarge {
1920 maximum_bytes: MAX_FOLDERBASEIGNORE_BYTES,
1921 });
1922 }
1923 let mut file = open_regular_nofollow(root_directory, Path::new(".folderbaseignore"))
1924 .map_err(|source| FolderbaseCaptureError::Io {
1925 path: path.clone(),
1926 source,
1927 })?;
1928 file.by_ref()
1929 .take(MAX_FOLDERBASEIGNORE_BYTES + 1)
1930 .read_to_end(&mut encoded)
1931 .map_err(|source| FolderbaseCaptureError::Io {
1932 path: path.clone(),
1933 source,
1934 })?;
1935 true
1936 }
1937 Err(source) if source.kind() == io::ErrorKind::NotFound && !required => false,
1938 Err(_) if required => return Err(FolderbaseCaptureError::RequiredMarker(path)),
1939 Err(source) => return Err(FolderbaseCaptureError::Io { path, source }),
1940 };
1941 if encoded.len() as u64 > MAX_FOLDERBASEIGNORE_BYTES {
1942 return Err(FolderbaseCaptureError::IgnorePolicyTooLarge {
1943 maximum_bytes: MAX_FOLDERBASEIGNORE_BYTES,
1944 });
1945 }
1946 let policy =
1947 std::str::from_utf8(&encoded).map_err(|_| FolderbaseCaptureError::IgnorePolicyNotUtf8)?;
1948 let mut digest = Sha256::new();
1949 let engine_rules = if required {
1950 digest.update(b"folderbase-ignore-policy-v1\0");
1951 RECONSTRUCTABLE_DIRECTORIES
1952 .iter()
1953 .map(|directory| format!("{directory}/"))
1954 .chain([".DS_Store", "*.tmp", "~$*"].into_iter().map(str::to_owned))
1955 .collect::<Vec<_>>()
1956 } else {
1957 digest.update(b"folderbase-ignore-policy-v2\0");
1958 digest.update(if present {
1959 b"present\0".as_slice()
1960 } else {
1961 b"absent\0".as_slice()
1962 });
1963 profile
1964 .capture_ignore_rules()
1965 .expect("ordinary profile carries exact engine rules")
1966 .to_vec()
1967 };
1968 for pattern in &engine_rules {
1969 digest.update(pattern.as_bytes());
1970 digest.update(b"\n");
1971 }
1972 digest.update(b"\0");
1973 digest.update(&encoded);
1974 let matcher = build_folderbaseignore_matcher(root, &path, &engine_rules, policy)?;
1975 Ok(IgnorePolicy {
1976 matcher,
1977 sha256: format!("{:x}", digest.finalize()),
1978 })
1979}
1980
1981pub(crate) fn validate_folderbaseignore_content(
1982 root: &Path,
1983 content: &str,
1984) -> Result<(), FolderbaseCaptureError> {
1985 build_folderbaseignore_matcher(root, &root.join(".folderbaseignore"), &[], content).map(drop)
1986}
1987
1988fn build_folderbaseignore_matcher(
1989 root: &Path,
1990 path: &Path,
1991 engine_rules: &[String],
1992 content: &str,
1993) -> Result<Gitignore, FolderbaseCaptureError> {
1994 if content.len() as u64 > MAX_FOLDERBASEIGNORE_BYTES {
1995 return Err(FolderbaseCaptureError::IgnorePolicyTooLarge {
1996 maximum_bytes: MAX_FOLDERBASEIGNORE_BYTES,
1997 });
1998 }
1999 let mut builder = GitignoreBuilder::new(root);
2000 for pattern in engine_rules {
2001 builder
2002 .add_line(None, pattern)
2003 .map_err(|error| FolderbaseCaptureError::InvalidIgnorePolicy(error.to_string()))?;
2004 }
2005 for line in content.lines() {
2006 builder
2007 .add_line(Some(path.to_path_buf()), line)
2008 .map_err(|error| FolderbaseCaptureError::InvalidIgnorePolicy(error.to_string()))?;
2009 }
2010 builder
2011 .build()
2012 .map_err(|error| FolderbaseCaptureError::InvalidIgnorePolicy(error.to_string()))
2013}
2014
2015fn require_regular_marker(
2016 root_directory: &Dir,
2017 root: &Path,
2018 relative: &Path,
2019) -> Result<(), FolderbaseCaptureError> {
2020 let path = root.join(relative);
2021 let metadata = root_directory
2022 .symlink_metadata(relative)
2023 .map_err(|_| FolderbaseCaptureError::RequiredMarker(path.clone()))?;
2024 if metadata.file_type().is_symlink() || !metadata.is_file() {
2025 return Err(FolderbaseCaptureError::RequiredMarker(path));
2026 }
2027 Ok(())
2028}
2029
2030fn protocol_file_length(
2031 root_directory: &Dir,
2032 root: &Path,
2033 relative: &Path,
2034) -> Result<u64, FolderbaseCaptureError> {
2035 let path = root.join(relative);
2036 let state_directory = root_directory
2037 .open_dir_nofollow(".folderbase")
2038 .map_err(|source| FolderbaseCaptureError::Io {
2039 path: path.clone(),
2040 source,
2041 })?;
2042 let file =
2043 open_regular_nofollow(&state_directory, Path::new("manifest.json")).map_err(|source| {
2044 FolderbaseCaptureError::Io {
2045 path: path.clone(),
2046 source,
2047 }
2048 })?;
2049 let metadata = file
2050 .metadata()
2051 .map_err(|source| FolderbaseCaptureError::Io { path, source })?;
2052 if !metadata.is_file() {
2053 return Err(FolderbaseCaptureError::RequiredMarker(root.join(relative)));
2054 }
2055 Ok(metadata.len())
2056}
2057
2058fn open_regular_nofollow(root: &Dir, relative: &Path) -> io::Result<fs::File> {
2059 let mut options = OpenOptions::new();
2060 options.read(true).follow(FollowSymlinks::No);
2061 root.open_with(relative, &options)
2062 .map(|file| file.into_std())
2063}
2064
2065#[cfg(test)]
2066mod capability_tests {
2067 use super::*;
2068
2069 #[cfg(unix)]
2070 #[test]
2071 fn retained_child_identity_rejects_a_directory_to_symlink_swap() {
2072 let root = tempfile::tempdir().expect("root");
2073 let outside = tempfile::tempdir().expect("outside");
2074 fs::create_dir(root.path().join("child")).expect("child");
2075 let root_directory = open_planning_root(root.path()).expect("root capability");
2076 let (_child, identity) = open_stable_child(
2077 &root_directory,
2078 OsStr::new("child"),
2079 &root.path().join("child"),
2080 )
2081 .expect("retained child");
2082
2083 fs::rename(root.path().join("child"), root.path().join("detached")).expect("detach child");
2084 std::os::unix::fs::symlink(outside.path(), root.path().join("child"))
2085 .expect("outside replacement");
2086
2087 assert!(
2088 verify_child_identity(
2089 &root_directory,
2090 OsStr::new("child"),
2091 &identity,
2092 &root.path().join("child"),
2093 )
2094 .is_err()
2095 );
2096 }
2097}