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_folderbase_root_with_profile_allowing_upgrade_recovery(
332 root: &Path,
333) -> Result<
334 (
335 FolderbaseRootAttestation,
336 RootInstanceAuthority,
337 ManifestProtocolProfile,
338 ),
339 RootAttestationError,
340> {
341 attest_folderbase_root_with_authority_inner(root, || {}, true)
342}
343
344fn attest_folderbase_root_inner(
345 root: &Path,
346 before_final_validation: impl FnOnce(),
347) -> Result<FolderbaseRootAttestation, RootAttestationError> {
348 attest_folderbase_root_with_authority_inner(root, before_final_validation, false)
349 .map(|(attestation, _, _)| attestation)
350}
351
352fn attest_folderbase_root_with_authority_inner(
353 root: &Path,
354 before_final_validation: impl FnOnce(),
355 allow_upgrade_recovery: bool,
356) -> Result<
357 (
358 FolderbaseRootAttestation,
359 RootInstanceAuthority,
360 ManifestProtocolProfile,
361 ),
362 RootAttestationError,
363> {
364 classify_root(root)?;
365 let root_file = open_root_nofollow(root).map_err(|source| RootAttestationError::Io {
366 path: root.to_path_buf(),
367 source,
368 })?;
369 let opened_root_metadata = root_file
370 .metadata()
371 .map_err(|source| RootAttestationError::Io {
372 path: root.to_path_buf(),
373 source,
374 })?;
375 if metadata_is_link_or_reparse(&opened_root_metadata) {
376 return Err(RootAttestationError::RootSymlink {
377 root: root.to_path_buf(),
378 });
379 }
380 if !opened_root_metadata.is_dir() {
381 return Err(RootAttestationError::RootNotDirectory {
382 root: root.to_path_buf(),
383 });
384 }
385 let root_identity =
386 PhysicalIdentity::from_file(&root_file).map_err(|source| RootAttestationError::Io {
387 path: root.to_path_buf(),
388 source,
389 })?;
390 let root_instance_authority = root_instance_authority(&root_file, root)?;
391 let root_instance_sha256 = root_instance_authority.current_sha256().to_owned();
392 let root_dir = Dir::from_std_file(root_file);
393
394 let state_metadata = marker_metadata(
395 &root_dir,
396 STATE_DIRECTORY,
397 FolderbaseRootMarker::StateDirectory,
398 root,
399 )?;
400 if state_metadata.file_type().is_symlink() {
401 return Err(RootAttestationError::MarkerSymlink {
402 marker: FolderbaseRootMarker::StateDirectory,
403 });
404 }
405 if !state_metadata.is_dir() {
406 return Err(RootAttestationError::MarkerWrongType {
407 marker: FolderbaseRootMarker::StateDirectory,
408 });
409 }
410 let state_dir = root_dir
411 .open_dir_nofollow(STATE_DIRECTORY)
412 .map_err(|source| marker_open_error(root, FolderbaseRootMarker::StateDirectory, source))?;
413 let state_file = state_dir
414 .try_clone()
415 .map_err(|source| RootAttestationError::Io {
416 path: root.join(STATE_DIRECTORY),
417 source,
418 })?
419 .into_std_file();
420 let opened_state_metadata =
421 state_file
422 .metadata()
423 .map_err(|source| RootAttestationError::Io {
424 path: root.join(STATE_DIRECTORY),
425 source,
426 })?;
427 if metadata_is_link_or_reparse(&opened_state_metadata) {
428 return Err(RootAttestationError::MarkerSymlink {
429 marker: FolderbaseRootMarker::StateDirectory,
430 });
431 }
432 if !opened_state_metadata.is_dir() {
433 return Err(RootAttestationError::MarkerWrongType {
434 marker: FolderbaseRootMarker::StateDirectory,
435 });
436 }
437 let state_identity =
438 PhysicalIdentity::from_file(&state_file).map_err(|source| RootAttestationError::Io {
439 path: root.join(STATE_DIRECTORY),
440 source,
441 })?;
442
443 let mut manifest = open_regular_marker(
444 &state_dir,
445 MANIFEST_FILE,
446 FolderbaseRootMarker::Manifest,
447 root,
448 )?;
449 if manifest.snapshot.bytes > MAX_FOLDERBASE_MANIFEST_BYTES {
450 return Err(RootAttestationError::ManifestTooLarge {
451 maximum_bytes: MAX_FOLDERBASE_MANIFEST_BYTES,
452 });
453 }
454 let manifest_bytes = read_manifest_bounded(&mut manifest.file, root)?;
455 if FileSnapshot::read(&manifest.file).map_err(|source| RootAttestationError::Io {
456 path: root.join(FolderbaseRootMarker::Manifest.relative_path()),
457 source,
458 })? != manifest.snapshot
459 {
460 return Err(RootAttestationError::RootChangedDuringAttestation);
461 }
462
463 let (_, folderbase_id, protocol_version, protocol_profile) =
464 decode_manifest_protocol_profile(&manifest_bytes)?;
465 let entry = if !protocol_profile.requires_legacy_root_files() {
466 None
467 } else {
468 Some(open_regular_marker(
469 &root_dir,
470 ENTRY_FILE,
471 FolderbaseRootMarker::Entry,
472 root,
473 )?)
474 };
475 let manifest_sha256 = hex_sha256(&manifest_bytes);
476
477 before_final_validation();
478
479 let reopened_root = revalidate_root(root, &root_identity)?;
480 let reopened_state = revalidate_directory(
481 &reopened_root,
482 STATE_DIRECTORY,
483 FolderbaseRootMarker::StateDirectory,
484 &state_identity,
485 )?;
486 revalidate_manifest(
487 &reopened_state,
488 MANIFEST_FILE,
489 FolderbaseRootMarker::Manifest,
490 &manifest.identity,
491 &manifest_sha256,
492 root,
493 )?;
494 if let Some(entry) = entry {
495 revalidate_file(
496 &reopened_root,
497 ENTRY_FILE,
498 FolderbaseRootMarker::Entry,
499 &entry.identity,
500 Some(&entry.snapshot),
501 root,
502 )?;
503 }
504 if !allow_upgrade_recovery && has_pending_protocol_upgrade(&reopened_state) {
505 return Err(RootAttestationError::ProtocolUpgradeRecoveryRequired);
506 }
507
508 Ok((
509 FolderbaseRootAttestation {
510 root: root.to_path_buf(),
511 folderbase_id,
512 protocol_version,
513 manifest_sha256,
514 root_instance_sha256,
515 },
516 root_instance_authority,
517 protocol_profile,
518 ))
519}
520
521pub(crate) fn decode_manifest_protocol_profile(
522 encoded: &[u8],
523) -> Result<(Value, String, String, ManifestProtocolProfile), RootAttestationError> {
524 let manifest = decode_unique_json(encoded)?;
525 let (folderbase_id, protocol_version) = required_manifest_fields(&manifest)?;
526 validate_folderbase_id(&folderbase_id)?;
527 let version = Version::parse(&protocol_version)
528 .map_err(|_| RootAttestationError::InvalidProtocolVersion)?;
529 let profile = manifest_protocol_profile(&manifest, &version)?;
530 Ok((manifest, folderbase_id, protocol_version, profile))
531}
532
533fn manifest_protocol_profile(
534 manifest: &Value,
535 version: &Version,
536) -> Result<ManifestProtocolProfile, RootAttestationError> {
537 if version.major == 0 && matches!(version.minor, 1 | 2) {
538 return Ok(ManifestProtocolProfile::LegacyV01V02);
539 }
540 if version != &Version::new(0, 5, 0) {
541 return Err(RootAttestationError::UnsupportedProtocolVersion);
542 }
543 validate_ordinary_manifest_shape(manifest)?;
544 let policy = manifest
545 .pointer("/policies/capture_ignore")
546 .and_then(Value::as_object)
547 .ok_or(RootAttestationError::InvalidCaptureIgnorePolicy)?;
548 if policy.len() != 2 || !policy.contains_key("format") || !policy.contains_key("rules") {
549 return Err(RootAttestationError::InvalidCaptureIgnorePolicy);
550 }
551 if policy.get("format").and_then(Value::as_str) != Some("folderbase-capture-ignore-v1") {
552 return Err(RootAttestationError::InvalidCaptureIgnorePolicy);
553 }
554 let rules = policy
555 .get("rules")
556 .and_then(Value::as_array)
557 .ok_or(RootAttestationError::InvalidCaptureIgnorePolicy)?;
558 if rules.len() > MAX_CAPTURE_IGNORE_RULES {
559 return Err(RootAttestationError::InvalidCaptureIgnorePolicy);
560 }
561 let capture_ignore_rules = rules
562 .iter()
563 .map(|rule| {
564 let rule = rule
565 .as_str()
566 .ok_or(RootAttestationError::InvalidCaptureIgnorePolicy)?;
567 if rule.is_empty()
568 || rule.len() > MAX_CAPTURE_IGNORE_RULE_BYTES
569 || rule.as_bytes().contains(&0)
570 {
571 return Err(RootAttestationError::InvalidCaptureIgnorePolicy);
572 }
573 Ok(rule.to_owned())
574 })
575 .collect::<Result<Vec<_>, _>>()?;
576 Ok(ManifestProtocolProfile::OrdinaryV05 {
577 capture_ignore_rules,
578 })
579}
580
581fn validate_ordinary_manifest_shape(manifest: &Value) -> Result<(), RootAttestationError> {
582 let record = manifest
583 .as_object()
584 .ok_or(RootAttestationError::InvalidManifestShape)?;
585 if record.get("$schema").is_some_and(|schema| {
586 schema.as_str() != Some("https://folderbase.ai/protocol/0.5/folderbase.schema.json")
587 }) {
588 return Err(RootAttestationError::InvalidManifestShape);
589 }
590 let folderbase = record
591 .get("folderbase")
592 .and_then(Value::as_object)
593 .ok_or(RootAttestationError::InvalidManifestShape)?;
594 let valid_nonempty = |key: &str| {
595 folderbase
596 .get(key)
597 .and_then(Value::as_str)
598 .is_some_and(|value| !value.is_empty())
599 };
600 if !valid_nonempty("name")
601 || !matches!(
602 folderbase.get("kind").and_then(Value::as_str),
603 Some(
604 "person"
605 | "organization"
606 | "engagement"
607 | "project"
608 | "customer"
609 | "temporary"
610 | "custom"
611 )
612 )
613 || !matches!(
614 folderbase.get("status").and_then(Value::as_str),
615 Some("active" | "paused" | "archived")
616 )
617 || folderbase
618 .get("created_at")
619 .and_then(Value::as_str)
620 .is_none_or(|created_at| DateTime::parse_from_rfc3339(created_at).is_err())
621 || folderbase
622 .get("template_provenance")
623 .is_some_and(|value| !value.is_object())
624 {
625 return Err(RootAttestationError::InvalidManifestShape);
626 }
627
628 let policies = record
629 .get("policies")
630 .and_then(Value::as_object)
631 .ok_or(RootAttestationError::InvalidManifestShape)?;
632 if !matches!(
633 policies.get("availability").and_then(Value::as_str),
634 Some("keep_local" | "managed" | "cloud_only")
635 ) || !matches!(
636 policies.get("structural_changes").and_then(Value::as_str),
637 Some("suggest" | "approve" | "autonomous")
638 ) || !matches!(
639 policies.get("archive").and_then(Value::as_str),
640 Some("manual" | "approve" | "automatic")
641 ) || !matches!(
642 policies.get("cloud_sync").and_then(Value::as_str),
643 Some("disabled" | "enabled")
644 ) {
645 return Err(RootAttestationError::InvalidManifestShape);
646 }
647
648 if let Some(adapters) = record.get("adapters") {
649 let adapters = adapters
650 .as_array()
651 .ok_or(RootAttestationError::InvalidManifestShape)?;
652 for adapter in adapters {
653 let adapter = adapter
654 .as_object()
655 .ok_or(RootAttestationError::InvalidManifestShape)?;
656 let agent = adapter
657 .get("agent")
658 .and_then(Value::as_str)
659 .ok_or(RootAttestationError::InvalidManifestShape)?;
660 let mut agent_bytes = agent.bytes();
661 if !agent_bytes
662 .next()
663 .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
664 || !agent_bytes.all(|byte| {
665 byte.is_ascii_lowercase()
666 || byte.is_ascii_digit()
667 || matches!(byte, b'_' | b'-')
668 })
669 {
670 return Err(RootAttestationError::InvalidManifestShape);
671 }
672 let path = adapter
673 .get("path")
674 .and_then(Value::as_str)
675 .ok_or(RootAttestationError::InvalidManifestShape)?;
676 if crate::folderbase_version::validate_capture_path(path).is_err()
677 || Path::new(path)
678 .components()
679 .filter_map(|component| match component {
680 std::path::Component::Normal(name) => Some(name),
681 _ => None,
682 })
683 .any(crate::traversal_policy::is_reserved_workspace_component)
684 {
685 return Err(RootAttestationError::InvalidManifestShape);
686 }
687 }
688 }
689 if let Some(receipt) = record.get(PROTOCOL_UPGRADE_RECEIPT_FIELD)
690 && (!valid_protocol_upgrade_receipt(receipt)
691 || !protocol_upgrade_receipt_binds_target(manifest, receipt))
692 {
693 return Err(RootAttestationError::InvalidProtocolUpgradeReceipt);
694 }
695 Ok(())
696}
697
698fn protocol_upgrade_receipt_binds_target(manifest: &Value, receipt: &Value) -> bool {
699 let Some(expected) = receipt
700 .get("target_manifest_without_receipt_sha256")
701 .and_then(Value::as_str)
702 else {
703 return false;
704 };
705 let mut target = manifest.clone();
706 let Some(record) = target.as_object_mut() else {
707 return false;
708 };
709 record.remove(PROTOCOL_UPGRADE_RECEIPT_FIELD);
710 let Ok(encoded) = serde_json::to_string_pretty(&target) else {
711 return false;
712 };
713 let encoded = format!("{encoded}\n");
714 hex_sha256(encoded.as_bytes()) == expected
715}
716
717fn has_pending_protocol_upgrade(state: &Dir) -> bool {
718 let transactions = match state.open_dir_nofollow("transactions") {
719 Ok(directory) => directory,
720 Err(source) if source.kind() == io::ErrorKind::NotFound => return false,
721 Err(_) => return true,
722 };
723 let upgrades = match transactions.open_dir_nofollow("protocol-upgrades") {
724 Ok(directory) => directory,
725 Err(source) if source.kind() == io::ErrorKind::NotFound => return false,
726 Err(_) => return true,
727 };
728 match upgrades.symlink_metadata("active.json") {
729 Ok(_) => true,
730 Err(source) if source.kind() == io::ErrorKind::NotFound => false,
731 Err(_) => true,
732 }
733}
734
735fn valid_protocol_upgrade_receipt(receipt: &Value) -> bool {
736 let Some(receipt) = receipt.as_object() else {
737 return false;
738 };
739 if receipt.len() != 4
740 || receipt.get("format").and_then(Value::as_str) != Some(PROTOCOL_UPGRADE_RECEIPT_FORMAT)
741 || !receipt
742 .get("from_protocol_version")
743 .and_then(Value::as_str)
744 .is_some_and(|version| {
745 matches!(
746 Version::parse(version),
747 Ok(version) if version.major == 0 && matches!(version.minor, 1 | 2)
748 )
749 })
750 || !receipt
751 .get("target_manifest_without_receipt_sha256")
752 .and_then(Value::as_str)
753 .is_some_and(valid_sha256)
754 {
755 return false;
756 }
757 let Some(plan_digest) = receipt.get("plan_digest").and_then(Value::as_object) else {
758 return false;
759 };
760 plan_digest.len() == 2
761 && plan_digest.get("algorithm").and_then(Value::as_str) == Some("sha256")
762 && plan_digest
763 .get("digest")
764 .and_then(Value::as_str)
765 .is_some_and(valid_sha256)
766}
767
768fn valid_sha256(value: &str) -> bool {
769 value.len() == 64
770 && value
771 .bytes()
772 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
773}
774
775fn classify_root(root: &Path) -> Result<(), RootAttestationError> {
776 let metadata = fs::symlink_metadata(root).map_err(|source| {
777 if source.kind() == io::ErrorKind::NotFound {
778 RootAttestationError::RootNotFound {
779 root: root.to_path_buf(),
780 }
781 } else {
782 RootAttestationError::Io {
783 path: root.to_path_buf(),
784 source,
785 }
786 }
787 })?;
788 if metadata_is_link_or_reparse(&metadata) {
789 return Err(RootAttestationError::RootSymlink {
790 root: root.to_path_buf(),
791 });
792 }
793 if !metadata.is_dir() {
794 return Err(RootAttestationError::RootNotDirectory {
795 root: root.to_path_buf(),
796 });
797 }
798 Ok(())
799}
800
801pub(crate) fn metadata_is_link_or_reparse(metadata: &fs::Metadata) -> bool {
802 if metadata.file_type().is_symlink() {
803 return true;
804 }
805
806 #[cfg(windows)]
807 {
808 use std::os::windows::fs::MetadataExt;
809
810 return windows_attributes_are_reparse(metadata.file_attributes());
811 }
812
813 #[cfg(not(windows))]
814 false
815}
816
817#[cfg(any(windows, test))]
818pub(crate) const fn windows_attributes_are_reparse(attributes: u32) -> bool {
819 const FILE_ATTRIBUTE_REPARSE_POINT_VALUE: u32 = 0x0000_0400;
820
821 attributes & FILE_ATTRIBUTE_REPARSE_POINT_VALUE != 0
822}
823
824fn marker_metadata(
825 directory: &Dir,
826 name: &str,
827 marker: FolderbaseRootMarker,
828 root: &Path,
829) -> Result<cap_std::fs::Metadata, RootAttestationError> {
830 directory
831 .symlink_metadata(name)
832 .map_err(|source| marker_open_error(root, marker, source))
833}
834
835fn open_root_nofollow(path: &Path) -> io::Result<fs::File> {
836 let mut options = fs::OpenOptions::new();
837 options.read(true);
838 #[cfg(unix)]
839 {
840 use std::os::unix::fs::OpenOptionsExt;
841
842 options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
843 }
844 #[cfg(windows)]
845 {
846 use std::os::windows::fs::OpenOptionsExt;
847 use windows_sys::Win32::Storage::FileSystem::{
848 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
849 FILE_SHARE_WRITE,
850 };
851
852 options
853 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
854 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
855 }
856 options.open(path)
857}
858
859fn marker_open_error(
860 root: &Path,
861 marker: FolderbaseRootMarker,
862 source: io::Error,
863) -> RootAttestationError {
864 if source.kind() == io::ErrorKind::NotFound {
865 RootAttestationError::MarkerMissing { marker }
866 } else {
867 RootAttestationError::Io {
868 path: root.join(marker.relative_path()),
869 source,
870 }
871 }
872}
873
874fn open_regular_marker(
875 directory: &Dir,
876 name: &str,
877 marker: FolderbaseRootMarker,
878 root: &Path,
879) -> Result<OpenedMarker, RootAttestationError> {
880 let metadata = marker_metadata(directory, name, marker, root)?;
881 if metadata.file_type().is_symlink() {
882 return Err(RootAttestationError::MarkerSymlink { marker });
883 }
884 if !metadata.is_file() {
885 if metadata.is_dir() {
886 let opened_directory = directory
887 .open_dir_nofollow(name)
888 .map_err(|source| marker_open_error(root, marker, source))?;
889 let opened_file = opened_directory
890 .try_clone()
891 .map_err(|source| RootAttestationError::Io {
892 path: root.join(marker.relative_path()),
893 source,
894 })?
895 .into_std_file();
896 let opened_metadata =
897 opened_file
898 .metadata()
899 .map_err(|source| RootAttestationError::Io {
900 path: root.join(marker.relative_path()),
901 source,
902 })?;
903 if metadata_is_link_or_reparse(&opened_metadata) {
904 return Err(RootAttestationError::MarkerSymlink { marker });
905 }
906 }
907 return Err(RootAttestationError::MarkerWrongType { marker });
908 }
909 let mut options = OpenOptions::new();
910 options.read(true).follow(FollowSymlinks::No);
911 let file = directory
912 .open_with(name, &options)
913 .map_err(|source| marker_open_error(root, marker, source))?
914 .into_std();
915 let snapshot = FileSnapshot::read(&file).map_err(|source| RootAttestationError::Io {
916 path: root.join(marker.relative_path()),
917 source,
918 })?;
919 let opened_metadata = file.metadata().map_err(|source| RootAttestationError::Io {
920 path: root.join(marker.relative_path()),
921 source,
922 })?;
923 if metadata_is_link_or_reparse(&opened_metadata) {
924 return Err(RootAttestationError::MarkerSymlink { marker });
925 }
926 if !opened_metadata.is_file() {
927 return Err(RootAttestationError::MarkerWrongType { marker });
928 }
929 let identity =
930 PhysicalIdentity::from_file(&file).map_err(|source| RootAttestationError::Io {
931 path: root.join(marker.relative_path()),
932 source,
933 })?;
934 Ok(OpenedMarker {
935 identity,
936 snapshot,
937 file,
938 })
939}
940
941fn read_manifest_bounded(
942 manifest: &mut fs::File,
943 root: &Path,
944) -> Result<Vec<u8>, RootAttestationError> {
945 let mut bytes = Vec::new();
946 manifest
947 .by_ref()
948 .take(MAX_FOLDERBASE_MANIFEST_BYTES + 1)
949 .read_to_end(&mut bytes)
950 .map_err(|source| RootAttestationError::Io {
951 path: root.join(FolderbaseRootMarker::Manifest.relative_path()),
952 source,
953 })?;
954 if bytes.len() as u64 > MAX_FOLDERBASE_MANIFEST_BYTES {
955 return Err(RootAttestationError::ManifestTooLarge {
956 maximum_bytes: MAX_FOLDERBASE_MANIFEST_BYTES,
957 });
958 }
959 Ok(bytes)
960}
961
962fn revalidate_root(root: &Path, expected: &PhysicalIdentity) -> Result<Dir, RootAttestationError> {
963 let reopened =
964 open_root_nofollow(root).map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
965 let metadata = reopened
966 .metadata()
967 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
968 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
969 return Err(RootAttestationError::RootChangedDuringAttestation);
970 }
971 let actual = PhysicalIdentity::from_file(&reopened)
972 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
973 if &actual != expected {
974 return Err(RootAttestationError::RootChangedDuringAttestation);
975 }
976 Ok(Dir::from_std_file(reopened))
977}
978
979fn revalidate_directory(
980 parent: &Dir,
981 name: &str,
982 _marker: FolderbaseRootMarker,
983 expected: &PhysicalIdentity,
984) -> Result<Dir, RootAttestationError> {
985 let directory = parent
986 .open_dir_nofollow(name)
987 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
988 let reopened = directory
989 .try_clone()
990 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?
991 .into_std_file();
992 let metadata = reopened
993 .metadata()
994 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
995 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
996 return Err(RootAttestationError::RootChangedDuringAttestation);
997 }
998 let actual = PhysicalIdentity::from_file(&reopened)
999 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1000 if &actual != expected {
1001 return Err(RootAttestationError::RootChangedDuringAttestation);
1002 }
1003 Ok(directory)
1004}
1005
1006fn revalidate_file(
1007 parent: &Dir,
1008 name: &str,
1009 marker: FolderbaseRootMarker,
1010 expected: &PhysicalIdentity,
1011 expected_snapshot: Option<&FileSnapshot>,
1012 root: &Path,
1013) -> Result<(), RootAttestationError> {
1014 let reopened = open_regular_marker(parent, name, marker, root)
1015 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1016 if &reopened.identity != expected
1017 || expected_snapshot.is_some_and(|snapshot| snapshot != &reopened.snapshot)
1018 {
1019 return Err(RootAttestationError::RootChangedDuringAttestation);
1020 }
1021 Ok(())
1022}
1023
1024fn revalidate_manifest(
1025 parent: &Dir,
1026 name: &str,
1027 marker: FolderbaseRootMarker,
1028 expected: &PhysicalIdentity,
1029 expected_sha256: &str,
1030 root: &Path,
1031) -> Result<(), RootAttestationError> {
1032 let mut reopened = open_regular_marker(parent, name, marker, root)
1033 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1034 if &reopened.identity != expected {
1035 return Err(RootAttestationError::RootChangedDuringAttestation);
1036 }
1037 let bytes = read_manifest_bounded(&mut reopened.file, root)
1038 .map_err(|_| RootAttestationError::RootChangedDuringAttestation)?;
1039 if hex_sha256(&bytes) != expected_sha256 {
1040 return Err(RootAttestationError::RootChangedDuringAttestation);
1041 }
1042 Ok(())
1043}
1044
1045fn required_manifest_fields(value: &Value) -> Result<(String, String), RootAttestationError> {
1046 let object = value
1047 .as_object()
1048 .ok_or(RootAttestationError::ManifestFieldWrongType { field: "$" })?;
1049 let protocol_version_value =
1050 object
1051 .get("protocol_version")
1052 .ok_or(RootAttestationError::ManifestFieldMissing {
1053 field: "protocol_version",
1054 })?;
1055 let protocol_version =
1056 protocol_version_value
1057 .as_str()
1058 .ok_or(RootAttestationError::ManifestFieldWrongType {
1059 field: "protocol_version",
1060 })?;
1061 let folderbase_value =
1062 object
1063 .get("folderbase")
1064 .ok_or(RootAttestationError::ManifestFieldMissing {
1065 field: "folderbase",
1066 })?;
1067 let folderbase =
1068 folderbase_value
1069 .as_object()
1070 .ok_or(RootAttestationError::ManifestFieldWrongType {
1071 field: "folderbase",
1072 })?;
1073 let folderbase_id_value =
1074 folderbase
1075 .get("id")
1076 .ok_or(RootAttestationError::ManifestFieldMissing {
1077 field: "folderbase.id",
1078 })?;
1079 let folderbase_id =
1080 folderbase_id_value
1081 .as_str()
1082 .ok_or(RootAttestationError::ManifestFieldWrongType {
1083 field: "folderbase.id",
1084 })?;
1085 Ok((folderbase_id.to_owned(), protocol_version.to_owned()))
1086}
1087
1088fn validate_folderbase_id(folderbase_id: &str) -> Result<(), RootAttestationError> {
1089 let suffix = folderbase_id
1090 .strip_prefix("folderbase_")
1091 .ok_or(RootAttestationError::InvalidFolderbaseId)?;
1092 let uuid = Uuid::parse_str(suffix).map_err(|_| RootAttestationError::InvalidFolderbaseId)?;
1093 if suffix != uuid.hyphenated().to_string() {
1094 return Err(RootAttestationError::InvalidFolderbaseId);
1095 }
1096 Ok(())
1097}
1098
1099fn decode_unique_json(bytes: &[u8]) -> Result<Value, RootAttestationError> {
1100 serde_json::from_slice::<UniqueJson>(bytes)
1101 .map(|value| value.0)
1102 .map_err(|source| {
1103 if source.to_string().contains(DUPLICATE_KEY_SENTINEL) {
1104 RootAttestationError::ManifestDuplicateField
1105 } else {
1106 RootAttestationError::ManifestInvalidJson
1107 }
1108 })
1109}
1110
1111struct UniqueJson(Value);
1112
1113impl<'de> Deserialize<'de> for UniqueJson {
1114 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1115 where
1116 D: Deserializer<'de>,
1117 {
1118 deserializer.deserialize_any(UniqueJsonVisitor)
1119 }
1120}
1121
1122struct UniqueJsonVisitor;
1123
1124impl<'de> Visitor<'de> for UniqueJsonVisitor {
1125 type Value = UniqueJson;
1126
1127 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1128 formatter.write_str("a JSON value without duplicate object keys")
1129 }
1130
1131 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
1132 Ok(UniqueJson(Value::Bool(value)))
1133 }
1134
1135 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
1136 Ok(UniqueJson(Value::Number(value.into())))
1137 }
1138
1139 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
1140 Ok(UniqueJson(Value::Number(value.into())))
1141 }
1142
1143 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1144 where
1145 E: de::Error,
1146 {
1147 Number::from_f64(value)
1148 .map(Value::Number)
1149 .map(UniqueJson)
1150 .ok_or_else(|| E::custom("non-finite JSON number"))
1151 }
1152
1153 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
1154 Ok(UniqueJson(Value::String(value.to_owned())))
1155 }
1156
1157 fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
1158 Ok(UniqueJson(Value::String(value)))
1159 }
1160
1161 fn visit_none<E>(self) -> Result<Self::Value, E> {
1162 Ok(UniqueJson(Value::Null))
1163 }
1164
1165 fn visit_unit<E>(self) -> Result<Self::Value, E> {
1166 Ok(UniqueJson(Value::Null))
1167 }
1168
1169 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1170 where
1171 D: Deserializer<'de>,
1172 {
1173 UniqueJson::deserialize(deserializer)
1174 }
1175
1176 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1177 where
1178 A: SeqAccess<'de>,
1179 {
1180 let mut values = Vec::new();
1181 while let Some(value) = sequence.next_element::<UniqueJson>()? {
1182 values.push(value.0);
1183 }
1184 Ok(UniqueJson(Value::Array(values)))
1185 }
1186
1187 fn visit_map<A>(self, mut object: A) -> Result<Self::Value, A::Error>
1188 where
1189 A: MapAccess<'de>,
1190 {
1191 let mut values = Map::new();
1192 while let Some(key) = object.next_key::<String>()? {
1193 if values.contains_key(&key) {
1194 return Err(de::Error::custom(DUPLICATE_KEY_SENTINEL));
1195 }
1196 let value = object.next_value::<UniqueJson>()?;
1197 values.insert(key, value.0);
1198 }
1199 Ok(UniqueJson(Value::Object(values)))
1200 }
1201}
1202
1203fn hex_sha256(bytes: &[u8]) -> String {
1204 format!("{:x}", Sha256::digest(bytes))
1205}
1206
1207fn root_instance_authority(
1208 file: &fs::File,
1209 root: &Path,
1210) -> Result<RootInstanceAuthority, RootAttestationError> {
1211 #[cfg(unix)]
1212 {
1213 use std::os::unix::fs::MetadataExt;
1214
1215 let metadata = file.metadata().map_err(|source| RootAttestationError::Io {
1216 path: root.to_path_buf(),
1217 source,
1218 })?;
1219 Ok(RootInstanceAuthority {
1220 current_sha256: root_instance_digest(
1221 ROOT_INSTANCE_FORMAT_V1,
1222 b"unix",
1223 &[&metadata.dev().to_be_bytes(), &metadata.ino().to_be_bytes()],
1224 ),
1225 legacy_v1_sha256: None,
1226 })
1227 }
1228
1229 #[cfg(windows)]
1230 {
1231 let full_identity =
1232 PhysicalIdentity::from_file(file).map_err(|source| RootAttestationError::Io {
1233 path: root.to_path_buf(),
1234 source,
1235 })?;
1236 let PhysicalIdentity::Windows {
1237 volume_serial,
1238 file_id,
1239 } = full_identity
1240 else {
1241 return Err(RootAttestationError::PhysicalIdentityUnavailable);
1242 };
1243 let legacy =
1244 winapi_util::file::information(file).map_err(|source| RootAttestationError::Io {
1245 path: root.to_path_buf(),
1246 source,
1247 })?;
1248 Ok(windows_root_instance_authority(
1249 volume_serial,
1250 file_id,
1251 legacy.volume_serial_number() as u32,
1252 legacy.file_index(),
1253 ))
1254 }
1255
1256 #[cfg(not(any(unix, windows)))]
1257 {
1258 let _ = file;
1259 let _ = root;
1260 Err(RootAttestationError::PhysicalIdentityUnavailable)
1261 }
1262}
1263
1264fn root_instance_digest(format: &str, platform: &[u8], fields: &[&[u8]]) -> String {
1265 let mut digest = Sha256::new();
1266 digest.update(format.as_bytes());
1267 digest.update([0]);
1268 digest.update(platform);
1269 digest.update([0]);
1270 for field in fields {
1271 digest.update(field);
1272 }
1273 format!("{:x}", digest.finalize())
1274}
1275
1276#[cfg(any(windows, test))]
1277fn windows_root_instance_authority(
1278 volume_serial: u64,
1279 file_id: [u8; 16],
1280 legacy_volume_serial: u32,
1281 legacy_file_index: u64,
1282) -> RootInstanceAuthority {
1283 RootInstanceAuthority {
1284 current_sha256: root_instance_digest(
1285 ROOT_INSTANCE_FORMAT_V2,
1286 b"windows",
1287 &[&volume_serial.to_be_bytes(), &file_id],
1288 ),
1289 legacy_v1_sha256: Some(root_instance_digest(
1290 ROOT_INSTANCE_FORMAT_V1,
1291 b"windows",
1292 &[
1293 &legacy_volume_serial.to_be_bytes(),
1294 &legacy_file_index.to_be_bytes(),
1295 ],
1296 )),
1297 }
1298}
1299
1300#[cfg(test)]
1301mod tests {
1302 use super::*;
1303 use tempfile::tempdir;
1304
1305 #[test]
1306 fn released_windows_v1_root_identity_remains_compatible_without_weakening_v2() {
1307 let first = windows_root_instance_authority(
1308 0x1020_3040_5060_7080,
1309 [
1310 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0,
1311 0xf0, 0x01,
1312 ],
1313 0x1020_3040,
1314 0x1122_3344_5566_7788,
1315 );
1316 let legacy_collision = windows_root_instance_authority(
1317 0x1020_3040_5060_7080,
1318 [
1319 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
1320 0x0f, 0x10,
1321 ],
1322 0x1020_3040,
1323 0x1122_3344_5566_7788,
1324 );
1325
1326 assert_eq!(
1327 first.current_sha256(),
1328 "8ff64630529b2fbda0062c3c15b8109e050e99f905cf497ad3a864cc19db6b2c"
1329 );
1330 assert_eq!(
1331 first.legacy_v1_sha256.as_deref(),
1332 Some("b3bd16243ce08bcb477e45af8682519dbbbeb3d33bd50d4a1660fe04a073bc03")
1333 );
1334 let current = first.admit(first.current_sha256()).unwrap();
1335 assert_eq!(current.recorded_sha256(), first.current_sha256());
1336 assert!(!current.is_legacy_v1());
1337 let legacy = first
1338 .admit(first.legacy_v1_sha256.as_deref().unwrap())
1339 .unwrap();
1340 assert_eq!(
1341 legacy.recorded_sha256(),
1342 first.legacy_v1_sha256.as_deref().unwrap()
1343 );
1344 assert!(legacy.is_legacy_v1());
1345 assert_ne!(
1346 first.current_sha256(),
1347 legacy_collision.current_sha256(),
1348 "new Windows authority must reject a ReFS upper-bit collision"
1349 );
1350 assert!(first.admit(legacy_collision.current_sha256()).is_none());
1351 assert_eq!(
1352 legacy_collision.current_sha256(),
1353 "2afb8ccf76a5f517a400d52b539060d66a99ee816b9f2c94f63a7c3e2a32b6dc"
1354 );
1355 }
1356
1357 #[test]
1358 fn released_unix_v1_root_identity_vector_is_unchanged() {
1359 assert_eq!(
1360 root_instance_digest(
1361 ROOT_INSTANCE_FORMAT_V1,
1362 b"unix",
1363 &[
1364 &0x0102_0304_0506_0708_u64.to_be_bytes(),
1365 &0x1122_3344_5566_7788_u64.to_be_bytes(),
1366 ],
1367 ),
1368 "f3684cd589445d66add75c1151f5df853fa89d37beae54a51e324606ba43736a"
1369 );
1370 }
1371
1372 #[test]
1373 fn closed_marker_paths_are_stable() {
1374 let paths = [
1375 (FolderbaseRootMarker::StateDirectory, ".folderbase"),
1376 (FolderbaseRootMarker::Manifest, ".folderbase/manifest.json"),
1377 (FolderbaseRootMarker::Entry, "FOLDERBASE.md"),
1378 ];
1379
1380 for (marker, expected) in paths {
1381 assert_eq!(marker.relative_path(), expected);
1382 assert_eq!(marker.to_string(), expected);
1383 }
1384 }
1385
1386 #[test]
1387 fn windows_reparse_attribute_is_rejected_independently_of_symlink_tag() {
1388 assert!(windows_attributes_are_reparse(0x0000_0400));
1389 assert!(windows_attributes_are_reparse(0x0000_0410));
1390 assert!(!windows_attributes_are_reparse(0x0000_0010));
1391 }
1392
1393 #[test]
1394 fn final_validation_rejects_equal_length_in_place_manifest_rewrite() {
1395 let root = tempdir().expect("root");
1396 fs::create_dir(root.path().join(STATE_DIRECTORY)).expect("state");
1397 let first = br#"{"protocol_version":"0.2.0","folderbase":{"id":"folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c473"}}"#;
1398 let changed = br#"{"protocol_version":"0.2.0","folderbase":{"id":"folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c474"}}"#;
1399 assert_eq!(first.len(), changed.len());
1400 let manifest_path = root.path().join(".folderbase/manifest.json");
1401 fs::write(&manifest_path, first).expect("manifest");
1402 fs::write(root.path().join(ENTRY_FILE), b"# Folderbase\n").expect("entry");
1403
1404 let result = attest_folderbase_root_inner(root.path(), || {
1405 fs::write(&manifest_path, changed).expect("equal-length in-place rewrite");
1406 });
1407
1408 assert!(matches!(
1409 result,
1410 Err(RootAttestationError::RootChangedDuringAttestation)
1411 ));
1412 }
1413}