use std::{fs, path::Path};
use folderbase_core::{
CaptureEntryKind, CaptureExclusionKind, CaptureExclusionReason, CapturePlanLimitKind,
FolderbaseCaptureError, FolderbaseVersionStore, MAX_CAPTURE_PLAN_RECORDS, RootAttestationError,
attest_folderbase_root,
};
use tempfile::{TempDir, tempdir};
const FOLDERBASE_ID: &str = "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c473";
const MANIFEST: &[u8] = br#"{
"protocol_version": "0.1.0",
"folderbase": {
"id": "folderbase_019f9b75-4f42-7f65-a012-2bfecdd8c473"
}
}
"#;
fn folderbase() -> TempDir {
let root = tempdir().expect("temporary Folderbase");
fs::create_dir(root.path().join(".folderbase")).expect("state directory");
fs::write(root.path().join(".folderbase/manifest.json"), MANIFEST).expect("manifest");
fs::write(root.path().join(".folderbaseignore"), "").expect("ignore policy");
fs::write(root.path().join("FOLDERBASE.md"), "# Folderbase\n").expect("entry");
root
}
fn entry_paths(plan: &folderbase_core::CapturePlan) -> Vec<(&str, CaptureEntryKind, Option<u64>)> {
plan.entries()
.iter()
.map(|entry| (entry.path(), entry.kind(), entry.bytes()))
.collect()
}
#[test]
fn open_and_plan_bind_metadata_to_one_attested_root_without_writing() {
let root = folderbase();
fs::create_dir(root.path().join("docs")).expect("docs");
fs::write(root.path().join("docs/notes.md"), "ordinary content\n").expect("notes");
let state_before = state_paths(root.path());
let store = FolderbaseVersionStore::open(root.path()).expect("open exact Folderbase");
let plan = store.plan_capture().expect("metadata plan");
assert_eq!(plan.root(), root.path().canonicalize().unwrap());
assert_eq!(plan.folderbase_id(), FOLDERBASE_ID);
assert_eq!(plan.root_instance_sha256().len(), 64);
assert_eq!(plan.root_manifest_sha256().len(), 64);
assert_eq!(plan.root_manifest_bytes(), MANIFEST.len() as u64);
assert_eq!(plan.current_local_head(), None);
assert_eq!(plan.ignore_policy_sha256().len(), 64);
assert_eq!(
entry_paths(&plan),
vec![
(".folderbaseignore", CaptureEntryKind::RegularFile, Some(0)),
("FOLDERBASE.md", CaptureEntryKind::RegularFile, Some(13)),
("docs", CaptureEntryKind::Directory, None),
("docs/notes.md", CaptureEntryKind::RegularFile, Some(17)),
]
);
assert_eq!(plan.exclusions().len(), 0);
assert_eq!(plan.ignored_paths().len(), 0);
assert_eq!(state_paths(root.path()), state_before);
}
#[cfg(unix)]
#[test]
fn open_rejects_a_supplied_symlink_root_before_canonicalizing_it() {
let root = folderbase();
let links = tempdir().expect("link parent");
let linked_root = links.path().join("linked-folderbase");
std::os::unix::fs::symlink(root.path(), &linked_root).expect("root symlink");
assert!(matches!(
FolderbaseVersionStore::open(&linked_root),
Err(FolderbaseCaptureError::RootAttestation(
RootAttestationError::RootSymlink { root }
)) if root == linked_root
));
}
#[cfg(windows)]
#[test]
fn open_rejects_a_supplied_windows_directory_reparse_root() {
let root = folderbase();
let links = tempdir().expect("link parent");
let linked_root = links.path().join("linked-folderbase");
if let Err(source) = std::os::windows::fs::symlink_dir(root.path(), &linked_root) {
if source.kind() == std::io::ErrorKind::PermissionDenied {
return;
}
panic!("directory reparse point: {source}");
}
assert!(matches!(
FolderbaseVersionStore::open(&linked_root),
Err(FolderbaseCaptureError::RootAttestation(
RootAttestationError::RootSymlink { root }
)) if root == linked_root
));
}
#[test]
fn ordered_ignore_policy_applies_defaults_negation_required_overrides_and_prunes_directories() {
let root = folderbase();
fs::write(
root.path().join(".folderbaseignore"),
include_str!("fixtures/capture/ordered.folderbaseignore"),
)
.expect("ordered policy");
fs::write(root.path().join("drop.tmp"), "ignored").expect("temporary file");
fs::write(root.path().join("keep.tmp"), "included").expect("negated temporary");
fs::write(root.path().join("important.log"), "last rule wins").expect("ordered file");
fs::create_dir_all(root.path().join("node_modules/pkg")).expect("reincluded generated tree");
fs::write(
root.path().join("node_modules/pkg/index.js"),
"opaque generated bytes",
)
.expect("reincluded generated file");
fs::create_dir_all(root.path().join("dist/deep")).expect("default excluded directory");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::write(root.path().join("dist/deep/CON"), "must never be visited")
.expect("nonportable descendant");
fs::set_permissions(root.path().join("dist"), fs::Permissions::from_mode(0o0))
.expect("excluded directory cannot be opened");
}
let planned = FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(root.path().join("dist"), fs::Permissions::from_mode(0o700))
.expect("restore cleanup access");
}
let plan = planned.expect("ignored directory is pruned before opening or traversing it");
let paths = plan
.entries()
.iter()
.map(|entry| entry.path())
.collect::<Vec<_>>();
let ignored = plan
.ignored_paths()
.iter()
.map(|entry| entry.path())
.collect::<Vec<_>>();
assert!(paths.contains(&".folderbaseignore"));
assert!(paths.contains(&"FOLDERBASE.md"));
assert!(paths.contains(&"keep.tmp"));
assert!(paths.contains(&"node_modules"));
assert!(paths.contains(&"node_modules/pkg/index.js"));
assert!(!paths.contains(&"drop.tmp"));
assert!(!paths.contains(&"important.log"));
assert!(!paths.iter().any(|path| path.starts_with("dist/")));
assert_eq!(ignored, vec!["dist", "drop.tmp", "important.log"]);
}
#[test]
fn nested_folderbases_are_typed_boundaries_and_all_regular_file_formats_remain_opaque() {
let root = folderbase();
for (path, contents) in [
("reference.pdf", b"%PDF opaque".as_slice()),
("movie.mov", b"opaque video".as_slice()),
("data.csv", b"a,b\n1,2\n".as_slice()),
("database.sqlite", b"SQLite format 3\0opaque".as_slice()),
("archive.unknown", b"unknown opaque".as_slice()),
(
".git/objects/pack/pack-test.pack",
b"git pack opaque".as_slice(),
),
] {
let path = root.path().join(path);
fs::create_dir_all(path.parent().unwrap()).expect("opaque parent");
fs::write(path, contents).expect("opaque regular file");
}
let child = root.path().join("Clients/Prosperna");
fs::create_dir_all(child.join(".folderbase")).expect("nested state");
fs::write(
child.join(".folderbase/manifest.json"),
b"{not-json and still opaque",
)
.expect("opaque nested manifest");
fs::write(child.join("FOLDERBASE.md"), "# Child\n").expect("nested entry");
#[cfg(unix)]
fs::write(child.join("CON"), "must not be traversed").expect("unsafe nested descendant");
#[cfg(windows)]
fs::write(child.join("private.bin"), "must not be traversed").expect("nested descendant");
let plan = FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.expect("plan with opaque boundary");
for expected in [
"reference.pdf",
"movie.mov",
"data.csv",
"database.sqlite",
"archive.unknown",
".git/objects/pack/pack-test.pack",
] {
let entry = plan
.entries()
.iter()
.find(|entry| entry.path() == expected)
.unwrap_or_else(|| panic!("missing opaque regular file {expected}"));
assert_eq!(entry.kind(), CaptureEntryKind::RegularFile);
assert!(entry.bytes().is_some());
}
assert!(
!plan
.entries()
.iter()
.any(|entry| entry.path().starts_with("Clients/Prosperna/"))
);
let boundary = plan
.exclusions()
.iter()
.find(|exclusion| exclusion.path() == "Clients/Prosperna")
.expect("typed nested boundary");
assert_eq!(boundary.kind(), CaptureExclusionKind::NestedFolderbase);
assert_eq!(
boundary.reason(),
CaptureExclusionReason::NestedFolderbaseBoundary
);
}
#[cfg(unix)]
#[test]
fn malformed_nested_entry_marker_still_closes_the_nested_boundary() {
let root = folderbase();
let child = root.path().join("Clients/Malformed");
fs::create_dir_all(child.join(".folderbase")).expect("nested state");
fs::write(child.join(".folderbase/manifest.json"), MANIFEST).expect("nested manifest");
std::os::unix::fs::symlink("missing-entry", child.join("FOLDERBASE.md"))
.expect("malformed nested entry marker");
fs::write(child.join("CON"), "must not be traversed").expect("unsafe nested descendant");
let plan = FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.expect("malformed child is still an opaque nested boundary");
let boundary = plan
.exclusions()
.iter()
.find(|exclusion| exclusion.path() == "Clients/Malformed")
.expect("typed nested boundary");
assert_eq!(boundary.kind(), CaptureExclusionKind::NestedFolderbase);
assert_eq!(
boundary.reason(),
CaptureExclusionReason::NestedFolderbaseBoundary
);
}
#[test]
fn capture_refuses_case_folded_marker_aliases_without_granting_them_authority() {
let root = folderbase();
let child = root.path().join("Clients/Alias");
fs::create_dir_all(child.join(".FOLDERBASE")).expect("nested alias state");
fs::write(child.join(".FOLDERBASE/MANIFEST.JSON"), b"opaque").expect("nested alias manifest");
fs::write(child.join("private.bin"), b"must not be captured").expect("private descendant");
assert!(
FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.is_err(),
"an alias-shaped marker fails closed but never becomes protocol authority"
);
}
#[cfg(unix)]
#[test]
fn capture_refuses_a_symlink_shaped_marker_without_following_it() {
let root = folderbase();
let child = root.path().join("Clients/Symlink");
fs::create_dir_all(&child).expect("child");
std::os::unix::fs::symlink(root.path().join("missing-state"), child.join(".folderbase"))
.expect("state symlink");
fs::write(child.join("private.bin"), b"must not be captured").expect("private descendant");
assert!(
FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.is_err()
);
}
#[cfg(unix)]
#[test]
fn sparse_ten_gibibyte_file_is_planned_by_metadata_and_v1_object_size_is_bounded() {
let root = folderbase();
let movie = root.path().join("feature.mov");
let file = fs::File::create(&movie).expect("sparse movie");
file.set_len(10 * 1024 * 1024 * 1024)
.expect("10 GiB sparse length");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&movie, fs::Permissions::from_mode(0o0))
.expect("ordinary file contents are unreadable");
}
let plan = FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.expect("metadata-only planning never opens ordinary bytes");
let planned = plan
.entries()
.iter()
.find(|entry| entry.path() == "feature.mov")
.expect("movie metadata");
assert_eq!(planned.kind(), CaptureEntryKind::RegularFile);
assert_eq!(planned.bytes(), Some(10 * 1024 * 1024 * 1024));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&movie, fs::Permissions::from_mode(0o600))
.expect("restore test cleanup permissions");
}
let oversized = root.path().join("too-large.bin");
let file = fs::File::create(&oversized).expect("oversized sparse file");
file.set_len(1024 * 1024 * 1024 * 1024 + 1)
.expect("v1 boundary probe");
assert!(matches!(
FolderbaseVersionStore::open(root.path())
.expect("reopen")
.plan_capture(),
Err(FolderbaseCaptureError::InventoryLimitExceeded {
limit,
maximum,
..
}) if limit == CapturePlanLimitKind::ObjectBytes
&& maximum == 1024 * 1024 * 1024 * 1024
));
}
#[cfg(windows)]
#[test]
fn windows_hard_links_are_typed_exclusions() {
let root = folderbase();
fs::write(root.path().join("original.bin"), "same inode").expect("regular file");
fs::hard_link(
root.path().join("original.bin"),
root.path().join("alias.bin"),
)
.expect("hard link");
let plan = FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.expect("typed hard links");
assert_eq!(
plan.exclusions()
.iter()
.filter(|entry| entry.kind() == CaptureExclusionKind::HardLink)
.count(),
2
);
}
#[test]
fn plan_is_bound_to_the_current_optional_device_local_head() {
let root = folderbase();
let receipt = attest_folderbase_root(root.path()).expect("root receipt");
fs::create_dir_all(root.path().join(".folderbase/local")).expect("local state");
fs::write(
root.path().join(".folderbase/local/head.json"),
serde_json::to_vec_pretty(&serde_json::json!({
"format": "folderbase-local-head-v1",
"folderbase_id": FOLDERBASE_ID,
"root_instance_sha256": receipt.root_instance_sha256,
"version_id": "fbversion_0198ee40-a111-7aaa-8000-000000000001",
"version_sha256": "a".repeat(64),
"transaction_sha256": "d".repeat(64)
}))
.expect("head JSON"),
)
.expect("local head");
let plan = FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.expect("plan with current local head");
let head = plan.current_local_head().expect("observed head");
assert_eq!(
head.version_id(),
"fbversion_0198ee40-a111-7aaa-8000-000000000001"
);
assert_eq!(head.version_sha256(), "a".repeat(64));
}
#[cfg(unix)]
#[test]
fn local_head_never_follows_an_intermediate_state_symlink() {
let root = folderbase();
let receipt = attest_folderbase_root(root.path()).expect("root receipt");
let outside = tempdir().expect("outside local state");
fs::write(
outside.path().join("head.json"),
serde_json::to_vec(&serde_json::json!({
"format": "folderbase-local-head-v1",
"folderbase_id": FOLDERBASE_ID,
"root_instance_sha256": receipt.root_instance_sha256,
"version_id": "fbversion_0198ee40-a111-7aaa-8000-000000000001",
"version_sha256": "c".repeat(64),
"transaction_sha256": "e".repeat(64)
}))
.expect("head JSON"),
)
.expect("outside head");
std::os::unix::fs::symlink(outside.path(), root.path().join(".folderbase/local"))
.expect("intermediate state symlink");
assert!(FolderbaseVersionStore::open(root.path()).is_err());
}
#[test]
fn capture_inventory_enforces_the_folderbase_version_entry_bound() {
let root = folderbase();
for index in 0..(MAX_CAPTURE_PLAN_RECORDS - 1) {
fs::create_dir(root.path().join(format!("d{index:05}"))).expect("bounded directory");
}
assert!(matches!(
FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture(),
Err(FolderbaseCaptureError::InventoryLimitExceeded {
limit: CapturePlanLimitKind::Entries,
maximum,
..
}) if maximum == MAX_CAPTURE_PLAN_RECORDS as u64
));
}
#[cfg(unix)]
#[test]
fn hard_links_and_special_nodes_are_typed_exclusions_instead_of_silent_loss() {
use std::{ffi::CString, os::unix::ffi::OsStrExt};
let root = folderbase();
fs::write(root.path().join("original.bin"), "same inode").expect("regular file");
fs::hard_link(
root.path().join("original.bin"),
root.path().join("alias.bin"),
)
.expect("hard link");
let fifo = root.path().join("events.fifo");
let fifo_path = CString::new(fifo.as_os_str().as_bytes()).expect("FIFO path");
assert_eq!(unsafe { libc::mkfifo(fifo_path.as_ptr(), 0o600) }, 0);
let plan = FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.expect("typed unsupported nodes");
assert!(
!plan
.entries()
.iter()
.any(|entry| matches!(entry.path(), "original.bin" | "alias.bin" | "events.fifo"))
);
let observed = plan
.exclusions()
.iter()
.map(|entry| (entry.path(), entry.kind(), entry.reason()))
.collect::<Vec<_>>();
assert_eq!(
observed,
vec![
(
"alias.bin",
CaptureExclusionKind::HardLink,
CaptureExclusionReason::UnsupportedV1,
),
(
"events.fifo",
CaptureExclusionKind::Fifo,
CaptureExclusionReason::UnsupportedV1,
),
(
"original.bin",
CaptureExclusionKind::HardLink,
CaptureExclusionReason::UnsupportedV1,
),
]
);
}
#[cfg(unix)]
#[test]
fn symlink_metadata_preserves_a_safe_exact_target_and_rejects_escape() {
use std::os::unix::fs::symlink;
let root = folderbase();
fs::create_dir_all(root.path().join("docs")).expect("docs");
fs::write(root.path().join("docs/readme.md"), "opaque").expect("target");
fs::create_dir(root.path().join("links")).expect("links");
symlink("../docs/readme.md", root.path().join("links/readme")).expect("safe link");
let plan = FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture()
.expect("safe link metadata");
let link = plan
.entries()
.iter()
.find(|entry| entry.path() == "links/readme")
.expect("link entry");
assert_eq!(link.kind(), CaptureEntryKind::Symlink);
assert_eq!(link.symlink_target(), Some("../docs/readme.md"));
symlink("../../outside", root.path().join("links/escape")).expect("unsafe link");
assert!(matches!(
FolderbaseVersionStore::open(root.path())
.expect("reopen")
.plan_capture(),
Err(FolderbaseCaptureError::UnsafeSymlinkTarget(path))
if path == Path::new("links/escape")
));
}
#[test]
fn in_scope_paths_fail_closed_when_the_portable_depth_limit_is_exceeded() {
let root = folderbase();
let too_deep = std::iter::repeat_n("d", 129).collect::<Vec<_>>().join("/");
fs::create_dir_all(root.path().join(&too_deep)).expect("deep tree");
assert!(matches!(
FolderbaseVersionStore::open(root.path())
.expect("open")
.plan_capture(),
Err(FolderbaseCaptureError::UnsafePortablePath(path))
if path.components().count() == 129
));
}
#[test]
fn portable_depth_refusal_does_not_depend_on_native_thread_stack_size() {
let root = folderbase();
let too_deep = std::iter::repeat_n("d", 129).collect::<Vec<_>>().join("/");
fs::create_dir_all(root.path().join(&too_deep)).expect("deep tree");
let root_path = root.path().to_path_buf();
let result = std::thread::Builder::new()
.name("bounded-capture-depth".to_owned())
.stack_size(256 * 1024)
.spawn(move || {
FolderbaseVersionStore::open(&root_path)
.expect("open")
.plan_capture()
})
.expect("spawn bounded-stack capture planner")
.join()
.expect("capture planner must return a typed result without stack overflow");
assert!(matches!(
result,
Err(FolderbaseCaptureError::UnsafePortablePath(path))
if path.components().count() == 129
));
}
#[cfg(target_os = "linux")]
#[test]
fn in_scope_paths_fail_closed_on_non_utf8_and_portable_case_collisions() {
use std::{ffi::OsString, os::unix::ffi::OsStringExt};
let non_utf8 = folderbase();
fs::write(
non_utf8
.path()
.join(OsString::from_vec(vec![0xff, b'.', b'b', b'i', b'n'])),
"opaque",
)
.expect("non-UTF-8 path");
assert!(matches!(
FolderbaseVersionStore::open(non_utf8.path())
.expect("open")
.plan_capture(),
Err(FolderbaseCaptureError::UnsafePortablePath(_))
));
let collision = folderbase();
fs::write(collision.path().join("Readme.md"), "one").expect("first case");
fs::write(collision.path().join("README.md"), "two").expect("second case");
assert!(matches!(
FolderbaseVersionStore::open(collision.path())
.expect("open")
.plan_capture(),
Err(FolderbaseCaptureError::PortablePathCollision { .. })
));
}
#[test]
fn required_ignore_marker_and_capture_policy_validation_fail_closed() {
let missing = folderbase();
fs::remove_file(missing.path().join(".folderbaseignore")).expect("remove marker");
assert!(matches!(
FolderbaseVersionStore::open(missing.path()),
Err(FolderbaseCaptureError::RequiredMarker(path))
if path.ends_with(".folderbaseignore")
));
let oversized = folderbase();
let policy = fs::File::options()
.write(true)
.open(oversized.path().join(".folderbaseignore"))
.expect("policy");
policy
.set_len(folderbase_core::MAX_FOLDERBASEIGNORE_BYTES + 1)
.expect("oversized policy");
assert!(matches!(
FolderbaseVersionStore::open(oversized.path())
.expect("marker is present")
.plan_capture(),
Err(FolderbaseCaptureError::IgnorePolicyTooLarge { maximum_bytes })
if maximum_bytes == folderbase_core::MAX_FOLDERBASEIGNORE_BYTES
));
let invalid = folderbase();
fs::write(invalid.path().join(".folderbaseignore"), "{a,b\n").expect("invalid ignore policy");
assert!(matches!(
FolderbaseVersionStore::open(invalid.path())
.expect("marker is present")
.plan_capture(),
Err(FolderbaseCaptureError::InvalidIgnorePolicy(_))
));
}
#[cfg(unix)]
#[test]
fn required_visible_markers_cannot_be_downgraded_to_hard_link_exclusions() {
let root = folderbase();
fs::hard_link(
root.path().join(".folderbaseignore"),
root.path().join("ignore-policy.backup"),
)
.expect("hard-linked required marker");
assert!(matches!(
FolderbaseVersionStore::open(root.path())
.expect("regular marker opens")
.plan_capture(),
Err(FolderbaseCaptureError::RequiredMarker(path))
if path.ends_with(".folderbaseignore")
));
}
#[test]
fn local_head_from_another_physical_root_is_rejected() {
let source = folderbase();
let destination = folderbase();
let receipt = attest_folderbase_root(source.path()).expect("source root");
fs::create_dir_all(destination.path().join(".folderbase/local")).expect("local state");
fs::write(
destination.path().join(".folderbase/local/head.json"),
serde_json::to_vec(&serde_json::json!({
"format": "folderbase-local-head-v1",
"folderbase_id": FOLDERBASE_ID,
"root_instance_sha256": receipt.root_instance_sha256,
"version_id": "fbversion_0198ee40-a111-7aaa-8000-000000000001",
"version_sha256": "b".repeat(64),
"transaction_sha256": "f".repeat(64)
}))
.expect("head JSON"),
)
.expect("foreign head");
assert!(matches!(
FolderbaseVersionStore::open(destination.path()),
Err(FolderbaseCaptureError::InvalidLocalHead(message))
if message.contains("attested physical Folderbase Root")
));
}
#[test]
fn public_capture_fails_closed_at_the_shared_boundary_work_ceiling() {
const EXPECTED_SHARED_WORK_CEILING: usize = 16_384;
let root = folderbase();
let crowded = root.path().join("crowded");
fs::create_dir(&crowded).expect("crowded directory");
for index in 0..=EXPECTED_SHARED_WORK_CEILING {
fs::write(crowded.join(format!("entry-{index:05}")), b"").expect("ordinary entry");
}
let error = FolderbaseVersionStore::open(root.path())
.expect("open Folderbase")
.plan_capture()
.expect_err("shared classifier work must be bounded");
assert!(
error
.to_string()
.contains("nested Folderbase boundary inspection exceeded"),
"public callers must inherit the shared classifier's hard work ceiling, got: {error}"
);
}
fn state_paths(root: &Path) -> Vec<String> {
let mut paths = walkdir::WalkDir::new(root.join(".folderbase"))
.into_iter()
.map(|entry| {
entry
.expect("state entry")
.path()
.strip_prefix(root)
.expect("relative state")
.to_string_lossy()
.into_owned()
})
.collect::<Vec<_>>();
paths.sort();
paths
}