1use std::{
2 fmt, fs,
3 io::{self, Read},
4 path::{Path, PathBuf},
5};
6
7use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
8use cap_std::fs::{Dir, OpenOptions};
9use chrono::DateTime;
10use semver::Version;
11use serde::{
12 Deserialize, Deserializer, Serialize, Serializer,
13 de::{self, MapAccess, SeqAccess, Visitor},
14 ser::SerializeStruct,
15};
16use serde_json::{Map, Number, Value};
17use sha2::{Digest, Sha256};
18use uuid::Uuid;
19
20use crate::physical_identity::PhysicalIdentity;
21
22pub const MAX_FOLDERBASE_MANIFEST_BYTES: u64 = 16 * 1024 * 1024;
24
25pub const ROOT_INSTANCE_FORMAT_V1: &str = "folderbase-physical-root-instance-v1";
27pub const ROOT_INSTANCE_FORMAT_V2: &str = "folderbase-physical-root-instance-v2";
29
30const STATE_DIRECTORY: &str = ".folderbase";
31const MANIFEST_FILE: &str = "manifest.json";
32const ENTRY_FILE: &str = "FOLDERBASE.md";
33const DUPLICATE_KEY_SENTINEL: &str = "folderbase_duplicate_json_object_key";
34const MAX_CAPTURE_IGNORE_RULES: usize = 1_024;
35const MAX_CAPTURE_IGNORE_RULE_BYTES: usize = 4_096;
36pub(crate) const PROTOCOL_UPGRADE_RECEIPT_FIELD: &str = "folderbase_protocol_upgrade";
37pub(crate) const PROTOCOL_UPGRADE_RECEIPT_FORMAT: &str = "folderbase-protocol-upgrade-receipt-v1";
38
39pub(crate) const DEFAULT_V05_CAPTURE_IGNORE_RULES: &[&str] = &[
44 "node_modules/",
45 ".next/",
46 "dist/",
47 "build/",
48 "coverage/",
49 ".venv/",
50 "__pycache__/",
51 ".dart_tool/",
52 "Pods/",
53 ".DS_Store",
54 "*.tmp",
55 "~$*",
56];
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub(crate) enum ManifestProtocolProfile {
60 LegacyV01V02,
61 OrdinaryV05 { capture_ignore_rules: Vec<String> },
62}
63
64impl ManifestProtocolProfile {
65 pub(crate) fn requires_legacy_root_files(&self) -> bool {
66 matches!(self, Self::LegacyV01V02)
67 }
68
69 pub(crate) fn folderbase_version_protocol(&self) -> &'static str {
70 match self {
71 Self::LegacyV01V02 => crate::folderbase_version::VERSION_PROTOCOL_V04,
72 Self::OrdinaryV05 { .. } => crate::folderbase_version::VERSION_PROTOCOL_V05,
73 }
74 }
75
76 pub(crate) fn capture_ignore_rules(&self) -> Option<&[String]> {
77 match self {
78 Self::LegacyV01V02 => None,
79 Self::OrdinaryV05 {
80 capture_ignore_rules,
81 } => Some(capture_ignore_rules),
82 }
83 }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum FolderbaseRootMarker {
89 StateDirectory,
90 Manifest,
91 Entry,
92}
93
94impl FolderbaseRootMarker {
95 pub const fn relative_path(self) -> &'static str {
97 match self {
98 Self::StateDirectory => STATE_DIRECTORY,
99 Self::Manifest => ".folderbase/manifest.json",
100 Self::Entry => ENTRY_FILE,
101 }
102 }
103}
104
105impl fmt::Display for FolderbaseRootMarker {
106 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107 formatter.write_str(self.relative_path())
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct FolderbaseRootAttestation {
116 pub root: PathBuf,
117 pub folderbase_id: String,
118 pub protocol_version: String,
119 pub manifest_sha256: String,
120 pub root_instance_sha256: String,
121}
122
123impl Serialize for FolderbaseRootAttestation {
124 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
125 where
126 S: Serializer,
127 {
128 let mut receipt = serializer.serialize_struct("FolderbaseRootAttestation", 5)?;
129 receipt.serialize_field("root", self.root.to_string_lossy().as_ref())?;
130 receipt.serialize_field("folderbase_id", &self.folderbase_id)?;
131 receipt.serialize_field("protocol_version", &self.protocol_version)?;
132 receipt.serialize_field("manifest_sha256", &self.manifest_sha256)?;
133 receipt.serialize_field("root_instance_sha256", &self.root_instance_sha256)?;
134 receipt.end()
135 }
136}
137
138#[derive(Debug, thiserror::Error)]
140#[non_exhaustive]
141pub enum RootAttestationError {
142 #[error("Folderbase root does not exist: {root}")]
143 RootNotFound { root: PathBuf },
144
145 #[error("Folderbase root must not be a symbolic link or reparse point: {root}")]
146 RootSymlink { root: PathBuf },
147
148 #[error("Folderbase root is not a directory: {root}")]
149 RootNotDirectory { root: PathBuf },
150
151 #[error("required Folderbase marker is missing: {marker}")]
152 MarkerMissing { marker: FolderbaseRootMarker },
153
154 #[error("Folderbase marker must not be a symbolic link or reparse point: {marker}")]
155 MarkerSymlink { marker: FolderbaseRootMarker },
156
157 #[error("Folderbase marker has the wrong filesystem type: {marker}")]
158 MarkerWrongType { marker: FolderbaseRootMarker },
159
160 #[error("Folderbase manifest exceeds the attestation maximum of {maximum_bytes} bytes")]
161 ManifestTooLarge { maximum_bytes: u64 },
162
163 #[error("Folderbase manifest is not valid JSON")]
164 ManifestInvalidJson,
165
166 #[error("Folderbase manifest contains a duplicate object key")]
167 ManifestDuplicateField,
168
169 #[error("Folderbase manifest field is missing: {field}")]
170 ManifestFieldMissing { field: &'static str },
171
172 #[error("Folderbase manifest field has the wrong JSON type: {field}")]
173 ManifestFieldWrongType { field: &'static str },
174
175 #[error("Folderbase manifest id is not folderbase_<lowercase-hyphenated-UUID>")]
176 InvalidFolderbaseId,
177
178 #[error("Folderbase manifest protocol_version is not valid semantic versioning")]
179 InvalidProtocolVersion,
180
181 #[error("Folderbase manifest protocol_version is unsupported")]
182 UnsupportedProtocolVersion,
183
184 #[error("Folderbase manifest capture-ignore policy is invalid")]
185 InvalidCaptureIgnorePolicy,
186
187 #[error("Folderbase manifest does not match the required live 0.5 shape")]
188 InvalidManifestShape,
189
190 #[error("Folderbase manifest protocol-upgrade receipt is invalid or stale")]
191 InvalidProtocolUpgradeReceipt,
192
193 #[error("Folderbase protocol-upgrade recovery must complete before this operation")]
194 ProtocolUpgradeRecoveryRequired,
195
196 #[error("Folderbase root identity changed during attestation")]
197 RootChangedDuringAttestation,
198
199 #[error("this platform does not expose the physical identity required by root-instance-v1")]
200 PhysicalIdentityUnavailable,
201
202 #[error("filesystem I/O failed while attesting {path}: {source}")]
203 Io {
204 path: PathBuf,
205 #[source]
206 source: io::Error,
207 },
208}
209
210impl RootAttestationError {
211 pub const fn code(&self) -> &'static str {
213 match self {
214 Self::RootNotFound { .. } => "root_not_found",
215 Self::RootSymlink { .. } => "root_symlink",
216 Self::RootNotDirectory { .. } => "root_not_directory",
217 Self::MarkerMissing { .. } => "marker_missing",
218 Self::MarkerSymlink { .. } => "marker_symlink",
219 Self::MarkerWrongType { .. } => "marker_wrong_type",
220 Self::ManifestTooLarge { .. } => "manifest_too_large",
221 Self::ManifestInvalidJson => "manifest_invalid_json",
222 Self::ManifestDuplicateField => "manifest_duplicate_field",
223 Self::ManifestFieldMissing { .. } => "manifest_field_missing",
224 Self::ManifestFieldWrongType { .. } => "manifest_field_wrong_type",
225 Self::InvalidFolderbaseId => "invalid_folderbase_id",
226 Self::InvalidProtocolVersion => "invalid_protocol_version",
227 Self::UnsupportedProtocolVersion => "unsupported_protocol_version",
228 Self::InvalidCaptureIgnorePolicy => "invalid_capture_ignore_policy",
229 Self::InvalidManifestShape => "invalid_manifest_shape",
230 Self::InvalidProtocolUpgradeReceipt => "invalid_protocol_upgrade_receipt",
231 Self::ProtocolUpgradeRecoveryRequired => "protocol_upgrade_recovery_required",
232 Self::RootChangedDuringAttestation => "root_changed_during_attestation",
233 Self::PhysicalIdentityUnavailable => "physical_identity_unavailable",
234 Self::Io { .. } => "attestation_io",
235 }
236 }
237}
238
239struct OpenedMarker {
240 identity: PhysicalIdentity,
241 snapshot: FileSnapshot,
242 file: fs::File,
243}
244
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub(crate) struct RootInstanceAuthority {
247 current_sha256: String,
248 legacy_v1_sha256: Option<String>,
249}
250
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub(crate) struct RootInstanceAdmission<'a> {
253 recorded_sha256: &'a str,
254 legacy_v1: bool,
255}
256
257impl RootInstanceAdmission<'_> {
258 pub(crate) fn recorded_sha256(&self) -> &str {
259 self.recorded_sha256
260 }
261
262 pub(crate) fn is_legacy_v1(&self) -> bool {
263 self.legacy_v1
264 }
265}
266
267impl RootInstanceAuthority {
268 pub(crate) fn current_sha256(&self) -> &str {
269 &self.current_sha256
270 }
271
272 pub(crate) fn admit<'a>(&self, candidate: &'a str) -> Option<RootInstanceAdmission<'a>> {
273 if candidate == self.current_sha256 {
274 return Some(RootInstanceAdmission {
275 recorded_sha256: candidate,
276 legacy_v1: false,
277 });
278 }
279 self.legacy_v1_sha256
280 .as_deref()
281 .filter(|legacy| candidate == *legacy)
282 .map(|_| RootInstanceAdmission {
283 recorded_sha256: candidate,
284 legacy_v1: true,
285 })
286 }
287
288 #[cfg(test)]
289 pub(crate) fn for_test(current_sha256: String, legacy_v1_sha256: Option<String>) -> Self {
290 Self {
291 current_sha256,
292 legacy_v1_sha256,
293 }
294 }
295}
296
297#[derive(Debug, Clone, PartialEq, Eq)]
298struct FileSnapshot {
299 bytes: u64,
300}
301
302impl FileSnapshot {
303 fn read(file: &fs::File) -> io::Result<Self> {
304 let metadata = file.metadata()?;
305 Ok(Self {
306 bytes: metadata.len(),
307 })
308 }
309}
310
311pub fn attest_folderbase_root(
313 root: impl AsRef<Path>,
314) -> Result<FolderbaseRootAttestation, RootAttestationError> {
315 attest_folderbase_root_inner(root.as_ref(), || {})
316}
317
318pub(crate) fn attest_folderbase_root_with_profile(
319 root: &Path,
320) -> Result<
321 (
322 FolderbaseRootAttestation,
323 RootInstanceAuthority,
324 ManifestProtocolProfile,
325 ),
326 RootAttestationError,
327> {
328 attest_folderbase_root_with_authority_inner(root, || {}, false)
329}
330
331pub(crate) fn attest_retained_folderbase_root_with_profile(
336 root: &Dir,
337 display_root: &Path,
338) -> Result<
339 (
340 FolderbaseRootAttestation,
341 RootInstanceAuthority,
342 ManifestProtocolProfile,
343 ),
344 RootAttestationError,
345> {
346 let root_file = root
347 .try_clone()
348 .map_err(|source| RootAttestationError::Io {
349 path: display_root.to_path_buf(),
350 source,
351 })?
352 .into_std_file();
353 attest_folderbase_root_from_open_file(
354 root_file,
355 display_root,
356 || {},
357 false,
358 revalidate_retained_root,
359 )
360}
361
362pub(crate) fn attest_folderbase_root_with_profile_allowing_upgrade_recovery(
363 root: &Path,
364) -> Result<
365 (
366 FolderbaseRootAttestation,
367 RootInstanceAuthority,
368 ManifestProtocolProfile,
369 ),
370 RootAttestationError,
371> {
372 attest_folderbase_root_with_authority_inner(root, || {}, true)
373}
374
375fn attest_folderbase_root_inner(
376 root: &Path,
377 before_final_validation: impl FnOnce(),
378) -> Result<FolderbaseRootAttestation, RootAttestationError> {
379 attest_folderbase_root_with_authority_inner(root, before_final_validation, false)
380 .map(|(attestation, _, _)| attestation)
381}
382
383fn attest_folderbase_root_with_authority_inner(
384 root: &Path,
385 before_final_validation: impl FnOnce(),
386 allow_upgrade_recovery: bool,
387) -> Result<
388 (
389 FolderbaseRootAttestation,
390 RootInstanceAuthority,
391 ManifestProtocolProfile,
392 ),
393 RootAttestationError,
394> {
395 classify_root(root)?;
396 let root_file = open_root_nofollow(root).map_err(|source| RootAttestationError::Io {
397 path: root.to_path_buf(),
398 source,
399 })?;
400 attest_folderbase_root_from_open_file(
401 root_file,
402 root,
403 before_final_validation,
404 allow_upgrade_recovery,
405 |_, expected| revalidate_root(root, expected),
406 )
407}
408
409fn attest_folderbase_root_from_open_file<R>(
410 root_file: fs::File,
411 root: &Path,
412 before_final_validation: impl FnOnce(),
413 allow_upgrade_recovery: bool,
414 final_root_revalidation: R,
415) -> Result<
416 (
417 FolderbaseRootAttestation,
418 RootInstanceAuthority,
419 ManifestProtocolProfile,
420 ),
421 RootAttestationError,
422>
423where
424 R: FnOnce(&Dir, &PhysicalIdentity) -> Result<Dir, RootAttestationError>,
425{
426 let opened_root_metadata = root_file
427 .metadata()
428 .map_err(|source| RootAttestationError::Io {
429 path: root.to_path_buf(),
430 source,
431 })?;
432 if metadata_is_link_or_reparse(&opened_root_metadata) {
433 return Err(RootAttestationError::RootSymlink {
434 root: root.to_path_buf(),
435 });
436 }
437 if !opened_root_metadata.is_dir() {
438 return Err(RootAttestationError::RootNotDirectory {
439 root: root.to_path_buf(),
440 });
441 }
442 let root_identity =
443 PhysicalIdentity::from_file(&root_file).map_err(|source| RootAttestationError::Io {
444 path: root.to_path_buf(),
445 source,
446 })?;
447 let root_instance_authority = root_instance_authority(&root_file, root)?;
448 let root_instance_sha256 = root_instance_authority.current_sha256().to_owned();
449 let root_dir = Dir::from_std_file(root_file);
450
451 let state_metadata = marker_metadata(
452 &root_dir,
453 STATE_DIRECTORY,
454 FolderbaseRootMarker::StateDirectory,
455 root,
456 )?;
457 if state_metadata.file_type().is_symlink() {
458 return Err(RootAttestationError::MarkerSymlink {
459 marker: FolderbaseRootMarker::StateDirectory,
460 });
461 }
462 if !state_metadata.is_dir() {
463 return Err(RootAttestationError::MarkerWrongType {
464 marker: FolderbaseRootMarker::StateDirectory,
465 });
466 }
467 let state_dir = root_dir
468 .open_dir_nofollow(STATE_DIRECTORY)
469 .map_err(|source| marker_open_error(root, FolderbaseRootMarker::StateDirectory, source))?;
470 let state_file = state_dir
471 .try_clone()
472 .map_err(|source| RootAttestationError::Io {
473 path: root.join(STATE_DIRECTORY),
474 source,
475 })?
476 .into_std_file();
477 let opened_state_metadata =
478 state_file
479 .metadata()
480 .map_err(|source| RootAttestationError::Io {
481 path: root.join(STATE_DIRECTORY),
482 source,
483 })?;
484 if metadata_is_link_or_reparse(&opened_state_metadata) {
485 return Err(RootAttestationError::MarkerSymlink {
486 marker: FolderbaseRootMarker::StateDirectory,
487 });
488 }
489 if !opened_state_metadata.is_dir() {
490 return Err(RootAttestationError::MarkerWrongType {
491 marker: FolderbaseRootMarker::StateDirectory,
492 });
493 }
494 let state_identity =
495 PhysicalIdentity::from_file(&state_file).map_err(|source| RootAttestationError::Io {
496 path: root.join(STATE_DIRECTORY),
497 source,
498 })?;
499
500 let mut manifest = open_regular_marker(
501 &state_dir,
502 MANIFEST_FILE,
503 FolderbaseRootMarker::Manifest,
504 root,
505 )?;
506 if manifest.snapshot.bytes > MAX_FOLDERBASE_MANIFEST_BYTES {
507 return Err(RootAttestationError::ManifestTooLarge {
508 maximum_bytes: MAX_FOLDERBASE_MANIFEST_BYTES,
509 });
510 }
511 let manifest_bytes = read_manifest_bounded(&mut manifest.file, root)?;
512 if FileSnapshot::read(&manifest.file).map_err(|source| RootAttestationError::Io {
513 path: root.join(FolderbaseRootMarker::Manifest.relative_path()),
514 source,
515 })? != manifest.snapshot
516 {
517 return Err(RootAttestationError::RootChangedDuringAttestation);
518 }
519
520 let (_, folderbase_id, protocol_version, protocol_profile) =
521 decode_manifest_protocol_profile(&manifest_bytes)?;
522 let entry = if !protocol_profile.requires_legacy_root_files() {
523 None
524 } else {
525 Some(open_regular_marker(
526 &root_dir,
527 ENTRY_FILE,
528 FolderbaseRootMarker::Entry,
529 root,
530 )?)
531 };
532 let manifest_sha256 = hex_sha256(&manifest_bytes);
533
534 before_final_validation();
535
536 let reopened_root = final_root_revalidation(&root_dir, &root_identity)?;
537 let reopened_state = revalidate_directory(
538 &reopened_root,
539 STATE_DIRECTORY,
540 FolderbaseRootMarker::StateDirectory,
541 &state_identity,
542 )?;
543 revalidate_manifest(
544 &reopened_state,
545 MANIFEST_FILE,
546 FolderbaseRootMarker::Manifest,
547 &manifest.identity,
548 &manifest_sha256,
549 root,
550 )?;
551 if let Some(entry) = entry {
552 revalidate_file(
553 &reopened_root,
554 ENTRY_FILE,
555 FolderbaseRootMarker::Entry,
556 &entry.identity,
557 Some(&entry.snapshot),
558 root,
559 )?;
560 }
561 if !allow_upgrade_recovery && has_pending_protocol_upgrade(&reopened_state) {
562 return Err(RootAttestationError::ProtocolUpgradeRecoveryRequired);
563 }
564
565 Ok((
566 FolderbaseRootAttestation {
567 root: root.to_path_buf(),
568 folderbase_id,
569 protocol_version,
570 manifest_sha256,
571 root_instance_sha256,
572 },
573 root_instance_authority,
574 protocol_profile,
575 ))
576}
577
578fn revalidate_retained_root(
579 root: &Dir,
580 expected: &PhysicalIdentity,
581) -> Result<Dir, RootAttestationError> {
582 let reopened = root
583 .try_clone()
584 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
585 let file = reopened
586 .try_clone()
587 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?
588 .into_std_file();
589 let metadata = file
590 .metadata()
591 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
592 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
593 return Err(RootAttestationError::RootChangedDuringAttestation);
594 }
595 let actual = PhysicalIdentity::from_file(&file)
596 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
597 if &actual != expected {
598 return Err(RootAttestationError::RootChangedDuringAttestation);
599 }
600 Ok(reopened)
601}
602
603pub(crate) fn decode_manifest_protocol_profile(
604 encoded: &[u8],
605) -> Result<(Value, String, String, ManifestProtocolProfile), RootAttestationError> {
606 let manifest = decode_unique_json(encoded)?;
607 let (folderbase_id, protocol_version) = required_manifest_fields(&manifest)?;
608 validate_folderbase_id(&folderbase_id)?;
609 let version = Version::parse(&protocol_version)
610 .map_err(|_| RootAttestationError::InvalidProtocolVersion)?;
611 let profile = manifest_protocol_profile(&manifest, &version)?;
612 Ok((manifest, folderbase_id, protocol_version, profile))
613}
614
615fn manifest_protocol_profile(
616 manifest: &Value,
617 version: &Version,
618) -> Result<ManifestProtocolProfile, RootAttestationError> {
619 if version.major == 0 && matches!(version.minor, 1 | 2) {
620 return Ok(ManifestProtocolProfile::LegacyV01V02);
621 }
622 if version != &Version::new(0, 5, 0) {
623 return Err(RootAttestationError::UnsupportedProtocolVersion);
624 }
625 validate_ordinary_manifest_shape(manifest)?;
626 let policy = manifest
627 .pointer("/policies/capture_ignore")
628 .and_then(Value::as_object)
629 .ok_or(RootAttestationError::InvalidCaptureIgnorePolicy)?;
630 if policy.len() != 2 || !policy.contains_key("format") || !policy.contains_key("rules") {
631 return Err(RootAttestationError::InvalidCaptureIgnorePolicy);
632 }
633 if policy.get("format").and_then(Value::as_str) != Some("folderbase-capture-ignore-v1") {
634 return Err(RootAttestationError::InvalidCaptureIgnorePolicy);
635 }
636 let rules = policy
637 .get("rules")
638 .and_then(Value::as_array)
639 .ok_or(RootAttestationError::InvalidCaptureIgnorePolicy)?;
640 if rules.len() > MAX_CAPTURE_IGNORE_RULES {
641 return Err(RootAttestationError::InvalidCaptureIgnorePolicy);
642 }
643 let capture_ignore_rules = rules
644 .iter()
645 .map(|rule| {
646 let rule = rule
647 .as_str()
648 .ok_or(RootAttestationError::InvalidCaptureIgnorePolicy)?;
649 if rule.is_empty()
650 || rule.len() > MAX_CAPTURE_IGNORE_RULE_BYTES
651 || rule.as_bytes().contains(&0)
652 {
653 return Err(RootAttestationError::InvalidCaptureIgnorePolicy);
654 }
655 Ok(rule.to_owned())
656 })
657 .collect::<Result<Vec<_>, _>>()?;
658 Ok(ManifestProtocolProfile::OrdinaryV05 {
659 capture_ignore_rules,
660 })
661}
662
663fn validate_ordinary_manifest_shape(manifest: &Value) -> Result<(), RootAttestationError> {
664 let record = manifest
665 .as_object()
666 .ok_or(RootAttestationError::InvalidManifestShape)?;
667 if record.get("$schema").is_some_and(|schema| {
668 schema.as_str() != Some("https://folderbase.ai/protocol/0.5/folderbase.schema.json")
669 }) {
670 return Err(RootAttestationError::InvalidManifestShape);
671 }
672 let folderbase = record
673 .get("folderbase")
674 .and_then(Value::as_object)
675 .ok_or(RootAttestationError::InvalidManifestShape)?;
676 let valid_nonempty = |key: &str| {
677 folderbase
678 .get(key)
679 .and_then(Value::as_str)
680 .is_some_and(|value| !value.is_empty())
681 };
682 if !valid_nonempty("name")
683 || !matches!(
684 folderbase.get("kind").and_then(Value::as_str),
685 Some(
686 "person"
687 | "organization"
688 | "engagement"
689 | "project"
690 | "customer"
691 | "temporary"
692 | "custom"
693 )
694 )
695 || !matches!(
696 folderbase.get("status").and_then(Value::as_str),
697 Some("active" | "paused" | "archived")
698 )
699 || folderbase
700 .get("created_at")
701 .and_then(Value::as_str)
702 .is_none_or(|created_at| DateTime::parse_from_rfc3339(created_at).is_err())
703 || folderbase
704 .get("template_provenance")
705 .is_some_and(|value| !value.is_object())
706 {
707 return Err(RootAttestationError::InvalidManifestShape);
708 }
709
710 let policies = record
711 .get("policies")
712 .and_then(Value::as_object)
713 .ok_or(RootAttestationError::InvalidManifestShape)?;
714 if !matches!(
715 policies.get("availability").and_then(Value::as_str),
716 Some("keep_local" | "managed" | "cloud_only")
717 ) || !matches!(
718 policies.get("structural_changes").and_then(Value::as_str),
719 Some("suggest" | "approve" | "autonomous")
720 ) || !matches!(
721 policies.get("archive").and_then(Value::as_str),
722 Some("manual" | "approve" | "automatic")
723 ) || !matches!(
724 policies.get("cloud_sync").and_then(Value::as_str),
725 Some("disabled" | "enabled")
726 ) {
727 return Err(RootAttestationError::InvalidManifestShape);
728 }
729
730 if let Some(adapters) = record.get("adapters") {
731 let adapters = adapters
732 .as_array()
733 .ok_or(RootAttestationError::InvalidManifestShape)?;
734 for adapter in adapters {
735 let adapter = adapter
736 .as_object()
737 .ok_or(RootAttestationError::InvalidManifestShape)?;
738 let agent = adapter
739 .get("agent")
740 .and_then(Value::as_str)
741 .ok_or(RootAttestationError::InvalidManifestShape)?;
742 let mut agent_bytes = agent.bytes();
743 if !agent_bytes
744 .next()
745 .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
746 || !agent_bytes.all(|byte| {
747 byte.is_ascii_lowercase()
748 || byte.is_ascii_digit()
749 || matches!(byte, b'_' | b'-')
750 })
751 {
752 return Err(RootAttestationError::InvalidManifestShape);
753 }
754 let path = adapter
755 .get("path")
756 .and_then(Value::as_str)
757 .ok_or(RootAttestationError::InvalidManifestShape)?;
758 if crate::folderbase_version::validate_capture_path(path).is_err()
759 || Path::new(path)
760 .components()
761 .filter_map(|component| match component {
762 std::path::Component::Normal(name) => Some(name),
763 _ => None,
764 })
765 .any(crate::traversal_policy::is_reserved_workspace_component)
766 {
767 return Err(RootAttestationError::InvalidManifestShape);
768 }
769 }
770 }
771 if let Some(receipt) = record.get(PROTOCOL_UPGRADE_RECEIPT_FIELD)
772 && (!valid_protocol_upgrade_receipt(receipt)
773 || !protocol_upgrade_receipt_binds_target(manifest, receipt))
774 {
775 return Err(RootAttestationError::InvalidProtocolUpgradeReceipt);
776 }
777 Ok(())
778}
779
780fn protocol_upgrade_receipt_binds_target(manifest: &Value, receipt: &Value) -> bool {
781 let Some(expected) = receipt
782 .get("target_manifest_without_receipt_sha256")
783 .and_then(Value::as_str)
784 else {
785 return false;
786 };
787 let mut target = manifest.clone();
788 let Some(record) = target.as_object_mut() else {
789 return false;
790 };
791 record.remove(PROTOCOL_UPGRADE_RECEIPT_FIELD);
792 let Ok(encoded) = serde_json::to_string_pretty(&target) else {
793 return false;
794 };
795 let encoded = format!("{encoded}\n");
796 hex_sha256(encoded.as_bytes()) == expected
797}
798
799fn has_pending_protocol_upgrade(state: &Dir) -> bool {
800 let transactions = match state.open_dir_nofollow("transactions") {
801 Ok(directory) => directory,
802 Err(source) if source.kind() == io::ErrorKind::NotFound => return false,
803 Err(_) => return true,
804 };
805 let upgrades = match transactions.open_dir_nofollow("protocol-upgrades") {
806 Ok(directory) => directory,
807 Err(source) if source.kind() == io::ErrorKind::NotFound => return false,
808 Err(_) => return true,
809 };
810 match upgrades.symlink_metadata("active.json") {
811 Ok(_) => true,
812 Err(source) if source.kind() == io::ErrorKind::NotFound => false,
813 Err(_) => true,
814 }
815}
816
817fn valid_protocol_upgrade_receipt(receipt: &Value) -> bool {
818 let Some(receipt) = receipt.as_object() else {
819 return false;
820 };
821 if receipt.len() != 4
822 || receipt.get("format").and_then(Value::as_str) != Some(PROTOCOL_UPGRADE_RECEIPT_FORMAT)
823 || !receipt
824 .get("from_protocol_version")
825 .and_then(Value::as_str)
826 .is_some_and(|version| {
827 matches!(
828 Version::parse(version),
829 Ok(version) if version.major == 0 && matches!(version.minor, 1 | 2)
830 )
831 })
832 || !receipt
833 .get("target_manifest_without_receipt_sha256")
834 .and_then(Value::as_str)
835 .is_some_and(valid_sha256)
836 {
837 return false;
838 }
839 let Some(plan_digest) = receipt.get("plan_digest").and_then(Value::as_object) else {
840 return false;
841 };
842 plan_digest.len() == 2
843 && plan_digest.get("algorithm").and_then(Value::as_str) == Some("sha256")
844 && plan_digest
845 .get("digest")
846 .and_then(Value::as_str)
847 .is_some_and(valid_sha256)
848}
849
850fn valid_sha256(value: &str) -> bool {
851 value.len() == 64
852 && value
853 .bytes()
854 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
855}
856
857fn classify_root(root: &Path) -> Result<(), RootAttestationError> {
858 let metadata = fs::symlink_metadata(root).map_err(|source| {
859 if source.kind() == io::ErrorKind::NotFound {
860 RootAttestationError::RootNotFound {
861 root: root.to_path_buf(),
862 }
863 } else {
864 RootAttestationError::Io {
865 path: root.to_path_buf(),
866 source,
867 }
868 }
869 })?;
870 if metadata_is_link_or_reparse(&metadata) {
871 return Err(RootAttestationError::RootSymlink {
872 root: root.to_path_buf(),
873 });
874 }
875 if !metadata.is_dir() {
876 return Err(RootAttestationError::RootNotDirectory {
877 root: root.to_path_buf(),
878 });
879 }
880 Ok(())
881}
882
883pub(crate) fn metadata_is_link_or_reparse(metadata: &fs::Metadata) -> bool {
884 if metadata.file_type().is_symlink() {
885 return true;
886 }
887
888 #[cfg(windows)]
889 {
890 use std::os::windows::fs::MetadataExt;
891
892 return windows_attributes_are_reparse(metadata.file_attributes());
893 }
894
895 #[cfg(not(windows))]
896 false
897}
898
899#[cfg(any(windows, test))]
900pub(crate) const fn windows_attributes_are_reparse(attributes: u32) -> bool {
901 const FILE_ATTRIBUTE_REPARSE_POINT_VALUE: u32 = 0x0000_0400;
902
903 attributes & FILE_ATTRIBUTE_REPARSE_POINT_VALUE != 0
904}
905
906fn marker_metadata(
907 directory: &Dir,
908 name: &str,
909 marker: FolderbaseRootMarker,
910 root: &Path,
911) -> Result<cap_std::fs::Metadata, RootAttestationError> {
912 directory
913 .symlink_metadata(name)
914 .map_err(|source| marker_open_error(root, marker, source))
915}
916
917pub(crate) fn open_root_nofollow(path: &Path) -> io::Result<fs::File> {
918 let mut options = fs::OpenOptions::new();
919 options.read(true);
920 #[cfg(unix)]
921 {
922 use std::os::unix::fs::OpenOptionsExt;
923
924 options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
925 }
926 #[cfg(windows)]
927 {
928 use std::os::windows::fs::OpenOptionsExt;
929 use windows_sys::Win32::Storage::FileSystem::{
930 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
931 FILE_SHARE_WRITE,
932 };
933
934 options
935 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
936 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
937 }
938 options.open(path)
939}
940
941fn marker_open_error(
942 root: &Path,
943 marker: FolderbaseRootMarker,
944 source: io::Error,
945) -> RootAttestationError {
946 if source.kind() == io::ErrorKind::NotFound {
947 RootAttestationError::MarkerMissing { marker }
948 } else {
949 RootAttestationError::Io {
950 path: root.join(marker.relative_path()),
951 source,
952 }
953 }
954}
955
956fn open_regular_marker(
957 directory: &Dir,
958 name: &str,
959 marker: FolderbaseRootMarker,
960 root: &Path,
961) -> Result<OpenedMarker, RootAttestationError> {
962 let metadata = marker_metadata(directory, name, marker, root)?;
963 if metadata.file_type().is_symlink() {
964 return Err(RootAttestationError::MarkerSymlink { marker });
965 }
966 if !metadata.is_file() {
967 if metadata.is_dir() {
968 let opened_directory = directory
969 .open_dir_nofollow(name)
970 .map_err(|source| marker_open_error(root, marker, source))?;
971 let opened_file = opened_directory
972 .try_clone()
973 .map_err(|source| RootAttestationError::Io {
974 path: root.join(marker.relative_path()),
975 source,
976 })?
977 .into_std_file();
978 let opened_metadata =
979 opened_file
980 .metadata()
981 .map_err(|source| RootAttestationError::Io {
982 path: root.join(marker.relative_path()),
983 source,
984 })?;
985 if metadata_is_link_or_reparse(&opened_metadata) {
986 return Err(RootAttestationError::MarkerSymlink { marker });
987 }
988 }
989 return Err(RootAttestationError::MarkerWrongType { marker });
990 }
991 let mut options = OpenOptions::new();
992 options.read(true).follow(FollowSymlinks::No);
993 let file = directory
994 .open_with(name, &options)
995 .map_err(|source| marker_open_error(root, marker, source))?
996 .into_std();
997 let snapshot = FileSnapshot::read(&file).map_err(|source| RootAttestationError::Io {
998 path: root.join(marker.relative_path()),
999 source,
1000 })?;
1001 let opened_metadata = file.metadata().map_err(|source| RootAttestationError::Io {
1002 path: root.join(marker.relative_path()),
1003 source,
1004 })?;
1005 if metadata_is_link_or_reparse(&opened_metadata) {
1006 return Err(RootAttestationError::MarkerSymlink { marker });
1007 }
1008 if !opened_metadata.is_file() {
1009 return Err(RootAttestationError::MarkerWrongType { marker });
1010 }
1011 let identity =
1012 PhysicalIdentity::from_file(&file).map_err(|source| RootAttestationError::Io {
1013 path: root.join(marker.relative_path()),
1014 source,
1015 })?;
1016 Ok(OpenedMarker {
1017 identity,
1018 snapshot,
1019 file,
1020 })
1021}
1022
1023fn read_manifest_bounded(
1024 manifest: &mut fs::File,
1025 root: &Path,
1026) -> Result<Vec<u8>, RootAttestationError> {
1027 let mut bytes = Vec::new();
1028 manifest
1029 .by_ref()
1030 .take(MAX_FOLDERBASE_MANIFEST_BYTES + 1)
1031 .read_to_end(&mut bytes)
1032 .map_err(|source| RootAttestationError::Io {
1033 path: root.join(FolderbaseRootMarker::Manifest.relative_path()),
1034 source,
1035 })?;
1036 if bytes.len() as u64 > MAX_FOLDERBASE_MANIFEST_BYTES {
1037 return Err(RootAttestationError::ManifestTooLarge {
1038 maximum_bytes: MAX_FOLDERBASE_MANIFEST_BYTES,
1039 });
1040 }
1041 Ok(bytes)
1042}
1043
1044fn revalidate_root(root: &Path, expected: &PhysicalIdentity) -> Result<Dir, RootAttestationError> {
1045 let reopened =
1046 open_root_nofollow(root).map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1047 let metadata = reopened
1048 .metadata()
1049 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1050 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
1051 return Err(RootAttestationError::RootChangedDuringAttestation);
1052 }
1053 let actual = PhysicalIdentity::from_file(&reopened)
1054 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1055 if &actual != expected {
1056 return Err(RootAttestationError::RootChangedDuringAttestation);
1057 }
1058 Ok(Dir::from_std_file(reopened))
1059}
1060
1061fn revalidate_directory(
1062 parent: &Dir,
1063 name: &str,
1064 _marker: FolderbaseRootMarker,
1065 expected: &PhysicalIdentity,
1066) -> Result<Dir, RootAttestationError> {
1067 let directory = parent
1068 .open_dir_nofollow(name)
1069 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1070 let reopened = directory
1071 .try_clone()
1072 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?
1073 .into_std_file();
1074 let metadata = reopened
1075 .metadata()
1076 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1077 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
1078 return Err(RootAttestationError::RootChangedDuringAttestation);
1079 }
1080 let actual = PhysicalIdentity::from_file(&reopened)
1081 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1082 if &actual != expected {
1083 return Err(RootAttestationError::RootChangedDuringAttestation);
1084 }
1085 Ok(directory)
1086}
1087
1088fn revalidate_file(
1089 parent: &Dir,
1090 name: &str,
1091 marker: FolderbaseRootMarker,
1092 expected: &PhysicalIdentity,
1093 expected_snapshot: Option<&FileSnapshot>,
1094 root: &Path,
1095) -> Result<(), RootAttestationError> {
1096 let reopened = open_regular_marker(parent, name, marker, root)
1097 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1098 if &reopened.identity != expected
1099 || expected_snapshot.is_some_and(|snapshot| snapshot != &reopened.snapshot)
1100 {
1101 return Err(RootAttestationError::RootChangedDuringAttestation);
1102 }
1103 Ok(())
1104}
1105
1106fn revalidate_manifest(
1107 parent: &Dir,
1108 name: &str,
1109 marker: FolderbaseRootMarker,
1110 expected: &PhysicalIdentity,
1111 expected_sha256: &str,
1112 root: &Path,
1113) -> Result<(), RootAttestationError> {
1114 let mut reopened = open_regular_marker(parent, name, marker, root)
1115 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1116 if &reopened.identity != expected {
1117 return Err(RootAttestationError::RootChangedDuringAttestation);
1118 }
1119 let bytes = read_manifest_bounded(&mut reopened.file, root)
1120 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1121 if hex_sha256(&bytes) != expected_sha256 {
1122 return Err(RootAttestationError::RootChangedDuringAttestation);
1123 }
1124 Ok(())
1125}
1126
1127fn required_manifest_fields(value: &Value) -> Result<(String, String), RootAttestationError> {
1128 let object = value
1129 .as_object()
1130 .ok_or(RootAttestationError::ManifestFieldWrongType { field: "$" })?;
1131 let protocol_version_value =
1132 object
1133 .get("protocol_version")
1134 .ok_or(RootAttestationError::ManifestFieldMissing {
1135 field: "protocol_version",
1136 })?;
1137 let protocol_version =
1138 protocol_version_value
1139 .as_str()
1140 .ok_or(RootAttestationError::ManifestFieldWrongType {
1141 field: "protocol_version",
1142 })?;
1143 let folderbase_value =
1144 object
1145 .get("folderbase")
1146 .ok_or(RootAttestationError::ManifestFieldMissing {
1147 field: "folderbase",
1148 })?;
1149 let folderbase =
1150 folderbase_value
1151 .as_object()
1152 .ok_or(RootAttestationError::ManifestFieldWrongType {
1153 field: "folderbase",
1154 })?;
1155 let folderbase_id_value =
1156 folderbase
1157 .get("id")
1158 .ok_or(RootAttestationError::ManifestFieldMissing {
1159 field: "folderbase.id",
1160 })?;
1161 let folderbase_id =
1162 folderbase_id_value
1163 .as_str()
1164 .ok_or(RootAttestationError::ManifestFieldWrongType {
1165 field: "folderbase.id",
1166 })?;
1167 Ok((folderbase_id.to_owned(), protocol_version.to_owned()))
1168}
1169
1170fn validate_folderbase_id(folderbase_id: &str) -> Result<(), RootAttestationError> {
1171 let suffix = folderbase_id
1172 .strip_prefix("folderbase_")
1173 .ok_or(RootAttestationError::InvalidFolderbaseId)?;
1174 let uuid = Uuid::parse_str(suffix).map_err(|_| RootAttestationError::InvalidFolderbaseId)?;
1175 if suffix != uuid.hyphenated().to_string() {
1176 return Err(RootAttestationError::InvalidFolderbaseId);
1177 }
1178 Ok(())
1179}
1180
1181fn decode_unique_json(bytes: &[u8]) -> Result<Value, RootAttestationError> {
1182 serde_json::from_slice::<UniqueJson>(bytes)
1183 .map(|value| value.0)
1184 .map_err(|source| {
1185 if source.to_string().contains(DUPLICATE_KEY_SENTINEL) {
1186 RootAttestationError::ManifestDuplicateField
1187 } else {
1188 RootAttestationError::ManifestInvalidJson
1189 }
1190 })
1191}
1192
1193struct UniqueJson(Value);
1194
1195impl<'de> Deserialize<'de> for UniqueJson {
1196 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1197 where
1198 D: Deserializer<'de>,
1199 {
1200 deserializer.deserialize_any(UniqueJsonVisitor)
1201 }
1202}
1203
1204struct UniqueJsonVisitor;
1205
1206impl<'de> Visitor<'de> for UniqueJsonVisitor {
1207 type Value = UniqueJson;
1208
1209 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1210 formatter.write_str("a JSON value without duplicate object keys")
1211 }
1212
1213 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
1214 Ok(UniqueJson(Value::Bool(value)))
1215 }
1216
1217 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
1218 Ok(UniqueJson(Value::Number(value.into())))
1219 }
1220
1221 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
1222 Ok(UniqueJson(Value::Number(value.into())))
1223 }
1224
1225 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1226 where
1227 E: de::Error,
1228 {
1229 Number::from_f64(value)
1230 .map(Value::Number)
1231 .map(UniqueJson)
1232 .ok_or_else(|| E::custom("non-finite JSON number"))
1233 }
1234
1235 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
1236 Ok(UniqueJson(Value::String(value.to_owned())))
1237 }
1238
1239 fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
1240 Ok(UniqueJson(Value::String(value)))
1241 }
1242
1243 fn visit_none<E>(self) -> Result<Self::Value, E> {
1244 Ok(UniqueJson(Value::Null))
1245 }
1246
1247 fn visit_unit<E>(self) -> Result<Self::Value, E> {
1248 Ok(UniqueJson(Value::Null))
1249 }
1250
1251 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1252 where
1253 D: Deserializer<'de>,
1254 {
1255 UniqueJson::deserialize(deserializer)
1256 }
1257
1258 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1259 where
1260 A: SeqAccess<'de>,
1261 {
1262 let mut values = Vec::new();
1263 while let Some(value) = sequence.next_element::<UniqueJson>()? {
1264 values.push(value.0);
1265 }
1266 Ok(UniqueJson(Value::Array(values)))
1267 }
1268
1269 fn visit_map<A>(self, mut object: A) -> Result<Self::Value, A::Error>
1270 where
1271 A: MapAccess<'de>,
1272 {
1273 let mut values = Map::new();
1274 while let Some(key) = object.next_key::<String>()? {
1275 if values.contains_key(&key) {
1276 return Err(de::Error::custom(DUPLICATE_KEY_SENTINEL));
1277 }
1278 let value = object.next_value::<UniqueJson>()?;
1279 values.insert(key, value.0);
1280 }
1281 Ok(UniqueJson(Value::Object(values)))
1282 }
1283}
1284
1285fn hex_sha256(bytes: &[u8]) -> String {
1286 format!("{:x}", Sha256::digest(bytes))
1287}
1288
1289fn root_instance_authority(
1290 file: &fs::File,
1291 root: &Path,
1292) -> Result<RootInstanceAuthority, RootAttestationError> {
1293 #[cfg(unix)]
1294 {
1295 use std::os::unix::fs::MetadataExt;
1296
1297 let metadata = file.metadata().map_err(|source| RootAttestationError::Io {
1298 path: root.to_path_buf(),
1299 source,
1300 })?;
1301 Ok(RootInstanceAuthority {
1302 current_sha256: root_instance_digest(
1303 ROOT_INSTANCE_FORMAT_V1,
1304 b"unix",
1305 &[&metadata.dev().to_be_bytes(), &metadata.ino().to_be_bytes()],
1306 ),
1307 legacy_v1_sha256: None,
1308 })
1309 }
1310
1311 #[cfg(windows)]
1312 {
1313 let full_identity =
1314 PhysicalIdentity::from_file(file).map_err(|source| RootAttestationError::Io {
1315 path: root.to_path_buf(),
1316 source,
1317 })?;
1318 let PhysicalIdentity::Windows {
1319 volume_serial,
1320 file_id,
1321 } = full_identity
1322 else {
1323 return Err(RootAttestationError::PhysicalIdentityUnavailable);
1324 };
1325 let legacy =
1326 winapi_util::file::information(file).map_err(|source| RootAttestationError::Io {
1327 path: root.to_path_buf(),
1328 source,
1329 })?;
1330 Ok(windows_root_instance_authority(
1331 volume_serial,
1332 file_id,
1333 legacy.volume_serial_number() as u32,
1334 legacy.file_index(),
1335 ))
1336 }
1337
1338 #[cfg(not(any(unix, windows)))]
1339 {
1340 let _ = file;
1341 let _ = root;
1342 Err(RootAttestationError::PhysicalIdentityUnavailable)
1343 }
1344}
1345
1346fn root_instance_digest(format: &str, platform: &[u8], fields: &[&[u8]]) -> String {
1347 let mut digest = Sha256::new();
1348 digest.update(format.as_bytes());
1349 digest.update([0]);
1350 digest.update(platform);
1351 digest.update([0]);
1352 for field in fields {
1353 digest.update(field);
1354 }
1355 format!("{:x}", digest.finalize())
1356}
1357
1358#[cfg(any(windows, test))]
1359fn windows_root_instance_authority(
1360 volume_serial: u64,
1361 file_id: [u8; 16],
1362 legacy_volume_serial: u32,
1363 legacy_file_index: u64,
1364) -> RootInstanceAuthority {
1365 RootInstanceAuthority {
1366 current_sha256: root_instance_digest(
1367 ROOT_INSTANCE_FORMAT_V2,
1368 b"windows",
1369 &[&volume_serial.to_be_bytes(), &file_id],
1370 ),
1371 legacy_v1_sha256: Some(root_instance_digest(
1372 ROOT_INSTANCE_FORMAT_V1,
1373 b"windows",
1374 &[
1375 &legacy_volume_serial.to_be_bytes(),
1376 &legacy_file_index.to_be_bytes(),
1377 ],
1378 )),
1379 }
1380}
1381
1382#[cfg(test)]
1383mod tests {
1384 use super::*;
1385 use tempfile::tempdir;
1386
1387 #[test]
1388 fn released_windows_v1_root_identity_remains_compatible_without_weakening_v2() {
1389 let first = windows_root_instance_authority(
1390 0x1020_3040_5060_7080,
1391 [
1392 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0,
1393 0xf0, 0x01,
1394 ],
1395 0x1020_3040,
1396 0x1122_3344_5566_7788,
1397 );
1398 let legacy_collision = windows_root_instance_authority(
1399 0x1020_3040_5060_7080,
1400 [
1401 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
1402 0x0f, 0x10,
1403 ],
1404 0x1020_3040,
1405 0x1122_3344_5566_7788,
1406 );
1407
1408 assert_eq!(
1409 first.current_sha256(),
1410 "8ff64630529b2fbda0062c3c15b8109e050e99f905cf497ad3a864cc19db6b2c"
1411 );
1412 assert_eq!(
1413 first.legacy_v1_sha256.as_deref(),
1414 Some("b3bd16243ce08bcb477e45af8682519dbbbeb3d33bd50d4a1660fe04a073bc03")
1415 );
1416 let current = first.admit(first.current_sha256()).unwrap();
1417 assert_eq!(current.recorded_sha256(), first.current_sha256());
1418 assert!(!current.is_legacy_v1());
1419 let legacy = first
1420 .admit(first.legacy_v1_sha256.as_deref().unwrap())
1421 .unwrap();
1422 assert_eq!(
1423 legacy.recorded_sha256(),
1424 first.legacy_v1_sha256.as_deref().unwrap()
1425 );
1426 assert!(legacy.is_legacy_v1());
1427 assert_ne!(
1428 first.current_sha256(),
1429 legacy_collision.current_sha256(),
1430 "new Windows authority must reject a ReFS upper-bit collision"
1431 );
1432 assert!(first.admit(legacy_collision.current_sha256()).is_none());
1433 assert_eq!(
1434 legacy_collision.current_sha256(),
1435 "2afb8ccf76a5f517a400d52b539060d66a99ee816b9f2c94f63a7c3e2a32b6dc"
1436 );
1437 }
1438
1439 #[test]
1440 fn released_unix_v1_root_identity_vector_is_unchanged() {
1441 assert_eq!(
1442 root_instance_digest(
1443 ROOT_INSTANCE_FORMAT_V1,
1444 b"unix",
1445 &[
1446 &0x0102_0304_0506_0708_u64.to_be_bytes(),
1447 &0x1122_3344_5566_7788_u64.to_be_bytes(),
1448 ],
1449 ),
1450 "f3684cd589445d66add75c1151f5df853fa89d37beae54a51e324606ba43736a"
1451 );
1452 }
1453
1454 #[test]
1455 fn closed_marker_paths_are_stable() {
1456 let paths = [
1457 (FolderbaseRootMarker::StateDirectory, ".folderbase"),
1458 (FolderbaseRootMarker::Manifest, ".folderbase/manifest.json"),
1459 (FolderbaseRootMarker::Entry, "FOLDERBASE.md"),
1460 ];
1461
1462 for (marker, expected) in paths {
1463 assert_eq!(marker.relative_path(), expected);
1464 assert_eq!(marker.to_string(), expected);
1465 }
1466 }
1467
1468 #[test]
1469 fn windows_reparse_attribute_is_rejected_independently_of_symlink_tag() {
1470 assert!(windows_attributes_are_reparse(0x0000_0400));
1471 assert!(windows_attributes_are_reparse(0x0000_0410));
1472 assert!(!windows_attributes_are_reparse(0x0000_0010));
1473 }
1474
1475 #[test]
1476 fn final_validation_rejects_equal_length_in_place_manifest_rewrite() {
1477 let root = tempdir().expect("root");
1478 fs::create_dir(root.path().join(STATE_DIRECTORY)).expect("state");
1479 let first = br#"{"protocol_version":"0.2.0","folderbase":{"id":"folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c473"}}"#;
1480 let changed = br#"{"protocol_version":"0.2.0","folderbase":{"id":"folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c474"}}"#;
1481 assert_eq!(first.len(), changed.len());
1482 let manifest_path = root.path().join(".folderbase/manifest.json");
1483 fs::write(&manifest_path, first).expect("manifest");
1484 fs::write(root.path().join(ENTRY_FILE), b"# Folderbase\n").expect("entry");
1485
1486 let result = attest_folderbase_root_inner(root.path(), || {
1487 fs::write(&manifest_path, changed).expect("equal-length in-place rewrite");
1488 });
1489
1490 assert!(matches!(
1491 result,
1492 Err(RootAttestationError::RootChangedDuringAttestation)
1493 ));
1494 }
1495}