1use std::{
2 collections::BTreeMap,
3 ffi::OsStr,
4 fs,
5 io::{Read, Write},
6 path::{Component, Path, PathBuf},
7};
8
9use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
10use cap_std::fs::{Dir, OpenOptions};
11use chrono::Utc;
12use serde_json::{Value, json};
13use sha2::{Digest, Sha256};
14use unicode_casefold::UnicodeCaseFold;
15use unicode_normalization::UnicodeNormalization;
16use uuid::Uuid;
17
18use crate::model::{
19 InitializationDestinationEntry, InitializationDestinationKind, InitializationRequest,
20};
21use crate::physical_identity::{PhysicalIdentity, RetainedPhysicalIdentity};
22use crate::root_attestation::{DEFAULT_V05_CAPTURE_IGNORE_RULES, metadata_is_link_or_reparse};
23use crate::template::template_package_sha256;
24use crate::traversal_policy::{
25 NestedFolderbaseBoundaryKind, classify_nested_folderbase_boundary_with_observer,
26 is_git_metadata_component, is_reconstructable_directory,
27};
28use crate::{
29 FolderbaseError, FolderbaseKind, InitializationInventoryLimitKind, InitializationOptions,
30 InitializationPlan, InitializationPlanDigest, InitializationResult, PlannedDirectory,
31 PlannedWrite, PreservedPath, Result, TemplateAnswerValue, TemplateArtifactKind,
32 TemplateArtifactPrecondition, TemplatePackage, TemplateRenderPlan, render_template,
33};
34
35const MANIFEST: &str = ".folderbase/manifest.json";
36#[cfg(test)]
37const FOLDERBASE_ENTRY: &str = "FOLDERBASE.md";
38const CODEX_ADAPTER: &str = "AGENTS.md";
39const CLAUDE_ADAPTER: &str = "CLAUDE.md";
40const MAX_INITIALIZATION_INVENTORY_ENTRIES: usize = 50_000;
41const MAX_INITIALIZATION_DEPTH: usize = 64;
42const MAX_INITIALIZATION_PATH_BYTES: usize = 4_096;
43const MAX_INITIALIZATION_ENCODED_INVENTORY_BYTES: usize = 16 * 1024 * 1024;
44const MAX_INITIALIZATION_PATH_COMPONENT_WORK: usize = 2_000_000;
45const MAX_INITIALIZATION_DIRECTORY_ENTRY_WORK: usize = 2_000_000;
46
47pub fn plan_initialization(
49 root: impl AsRef<Path>,
50 options: InitializationOptions,
51) -> Result<InitializationPlan> {
52 plan_initialization_with_template(
53 root.as_ref(),
54 options.clone(),
55 None,
56 InitializationRequest::Ordinary { options },
57 InitializationInventoryBudget::default(),
58 )
59}
60
61pub fn plan_template_initialization(
64 root: impl AsRef<Path>,
65 mut options: InitializationOptions,
66 package: &TemplatePackage,
67 answers: &BTreeMap<String, TemplateAnswerValue>,
68) -> Result<InitializationPlan> {
69 let request = InitializationRequest::Template {
70 options: options.clone(),
71 package: Box::new(package.clone()),
72 answers: answers.clone(),
73 };
74 refuse_symlink_root(root.as_ref())?;
75 let root = canonical_directory(root.as_ref())?;
76 let mut inventory_budget = InitializationInventoryBudget::default();
77 refuse_nested_target(&root, &mut inventory_budget)?;
78 let folderbase_name = resolve_folderbase_name(&root, options.name.as_deref())?;
79 let mut rendered_answers = answers.clone();
80 if package
81 .questions()
82 .iter()
83 .any(|question| question.id() == "folderbase_name")
84 {
85 match rendered_answers.get("folderbase_name") {
86 Some(TemplateAnswerValue::Text(value)) if value == &folderbase_name => {}
87 Some(_) => {
88 return Err(FolderbaseError::InvalidRecord {
89 path: root,
90 message: "template folderbase_name must match the initialized folderbase name"
91 .to_owned(),
92 });
93 }
94 None => {
95 rendered_answers.insert(
96 "folderbase_name".to_owned(),
97 TemplateAnswerValue::Text(folderbase_name.clone()),
98 );
99 }
100 }
101 }
102 options.name = Some(folderbase_name);
103 let rendered = render_template(package, &root, &rendered_answers)?;
104 let preconditions = template_preconditions(&root, package, &rendered, &mut inventory_budget)?;
105 let package_digest = template_package_sha256(package)?;
106 plan_initialization_with_template(
107 &root,
108 options,
109 Some((rendered, preconditions, package_digest)),
110 request,
111 inventory_budget,
112 )
113}
114
115fn plan_initialization_with_template(
116 root: &Path,
117 options: InitializationOptions,
118 rendered_template: Option<(
119 TemplateRenderPlan,
120 Vec<TemplateArtifactPrecondition>,
121 String,
122 )>,
123 request: InitializationRequest,
124 mut inventory_budget: InitializationInventoryBudget,
125) -> Result<InitializationPlan> {
126 let root = canonical_directory(root)?;
127 refuse_nested_target(&root, &mut inventory_budget)?;
128 if is_provider_controlled(&root) {
129 return Err(FolderbaseError::ProviderControlled(root));
130 }
131 let OpenedRootCapability {
132 directory: root_dir,
133 identity: root_identity_guard,
134 digest_identity: root_identity,
135 } = open_root_capability(&root)?;
136
137 let manifest_path = safe_destination(&root, Path::new(MANIFEST))?;
138 match fs::symlink_metadata(&manifest_path) {
139 Ok(_) => return Err(FolderbaseError::WouldOverwrite(manifest_path)),
140 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
141 Err(source) => return Err(FolderbaseError::io(manifest_path, source)),
142 }
143
144 let folderbase_name = resolve_folderbase_name(&root, options.name.as_deref())?;
145 let folderbase_id = format!("folderbase_{}", Uuid::now_v7());
146 let created_at = Utc::now().to_rfc3339();
147
148 let mut directories = Vec::new();
149 let mut writes = Vec::new();
150 let mut template_preconditions = Vec::new();
151 let destination_inventory =
152 snapshot_destination_inventory(&root_dir, &root, &mut inventory_budget)?;
153 let mut preserved_paths = destination_inventory
154 .iter()
155 .filter(|entry| entry.kind == InitializationDestinationKind::File)
156 .map(|entry| PreservedPath {
157 path: entry.path.clone(),
158 })
159 .collect::<Vec<_>>();
160 let mut warnings = Vec::new();
161
162 let template_provenance =
163 if let Some((rendered, preconditions, package_digest)) = rendered_template {
164 template_preconditions = preconditions;
165 for path in rendered
166 .additions
167 .iter()
168 .map(|addition| addition.path.as_path())
169 .chain(rendered.existing_paths.iter().map(PathBuf::as_path))
170 {
171 refuse_template_target_inside_nested_folderbase_capability(
172 &root_dir,
173 &root,
174 path,
175 &mut inventory_budget,
176 )?;
177 }
178 for addition in rendered.additions {
179 match addition.kind {
180 TemplateArtifactKind::Directory => {
181 let destination = safe_destination(&root, &addition.path)?;
182 match fs::symlink_metadata(&destination) {
183 Ok(_) => return Err(FolderbaseError::WouldOverwrite(destination)),
184 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
185 directories.push(PlannedDirectory {
186 path: addition.path,
187 purpose: "Template-proposed additive directory".to_owned(),
188 });
189 }
190 Err(source) => return Err(FolderbaseError::io(destination, source)),
191 }
192 }
193 TemplateArtifactKind::Text => {
194 plan_file(
195 &root,
196 &addition.path,
197 "Template-rendered additive file",
198 addition.content.unwrap_or_default(),
199 &mut writes,
200 &mut preserved_paths,
201 )?;
202 }
203 }
204 }
205 Some((
206 rendered.template_id,
207 rendered.template_version,
208 package_digest,
209 ))
210 } else {
211 None
212 };
213
214 let adapter_paths = if options.create_agent_adapters {
215 vec![
216 json!({ "agent": "codex", "path": CODEX_ADAPTER }),
217 json!({ "agent": "claude", "path": CLAUDE_ADAPTER }),
218 ]
219 } else {
220 Vec::new()
221 };
222 let mut folderbase = json!({
223 "id": folderbase_id,
224 "name": folderbase_name,
225 "kind": folderbase_kind_name(options.kind),
226 "status": "active",
227 "created_at": created_at
228 });
229 if let Some((id, version, package_digest)) = template_provenance {
230 folderbase["template_provenance"] = json!({
231 "id": id,
232 "version": version,
233 "applied_at": created_at,
234 "package_digest": {
235 "algorithm": "sha256",
236 "digest": package_digest
237 }
238 });
239 }
240 let manifest = json!({
241 "$schema": "https://folderbase.ai/protocol/0.5/folderbase.schema.json",
242 "protocol_version": "0.5.0",
243 "folderbase": folderbase,
244 "adapters": adapter_paths,
245 "policies": {
246 "availability": "keep_local",
247 "structural_changes": "approve",
248 "archive": "approve",
249 "cloud_sync": "disabled",
250 "capture_ignore": {
251 "format": "folderbase-capture-ignore-v1",
252 "rules": DEFAULT_V05_CAPTURE_IGNORE_RULES
253 }
254 }
255 });
256 let manifest = serde_json::to_string_pretty(&manifest)
257 .map(|json| format!("{json}\n"))
258 .map_err(|source| FolderbaseError::json(manifest_path.clone(), source))?;
259 writes.push(PlannedWrite {
260 path: PathBuf::from(MANIFEST),
261 purpose: "Machine-readable folderbase root record".to_owned(),
262 content: manifest,
263 });
264
265 if options.create_agent_adapters {
266 plan_agent_adapter_unless_template_owned(
267 &root,
268 Path::new(CODEX_ADAPTER),
269 "Codex bootstrap adapter",
270 agent_adapter(),
271 &mut writes,
272 &mut preserved_paths,
273 )?;
274 plan_agent_adapter_unless_template_owned(
275 &root,
276 Path::new(CLAUDE_ADAPTER),
277 "Claude bootstrap adapter",
278 agent_adapter(),
279 &mut writes,
280 &mut preserved_paths,
281 )?;
282 } else {
283 warnings.push("Agent adapters were disabled for this initialization.".to_owned());
284 }
285
286 let planned_paths = directories
287 .iter()
288 .map(|directory| directory.path.clone())
289 .chain(writes.iter().map(|write| write.path.clone()))
290 .collect::<Vec<_>>();
291 for path in planned_paths {
292 plan_missing_parent_directories(&root, &path, &mut directories)?;
293 }
294 validate_planned_path_collisions(&root, &directories, &writes)?;
295 validate_planned_paths_against_existing(&root, &directories, &writes)?;
296
297 directories.sort_by(|left, right| {
298 left.path
299 .components()
300 .count()
301 .cmp(&right.path.components().count())
302 .then_with(|| left.path.cmp(&right.path))
303 });
304 writes.sort_by(|left, right| {
305 let left_is_manifest = left.path == Path::new(MANIFEST);
306 let right_is_manifest = right.path == Path::new(MANIFEST);
307 left_is_manifest
308 .cmp(&right_is_manifest)
309 .then_with(|| left.path.cmp(&right.path))
310 });
311 preserved_paths.sort_by(|left, right| left.path.cmp(&right.path));
312 warnings.sort();
313
314 let plan_digest = initialization_plan_digest(InitializationDigestInput {
315 root: &root,
316 root_identity: &root_identity,
317 request: &request,
318 folderbase_kind: options.kind,
319 directories: &directories,
320 writes: &writes,
321 template_preconditions: &template_preconditions,
322 preserved_paths: &preserved_paths,
323 warnings: &warnings,
324 destination_inventory: &destination_inventory,
325 })?;
326
327 Ok(InitializationPlan {
328 root,
329 folderbase_id,
330 folderbase_name,
331 folderbase_kind: options.kind,
332 directories,
333 writes,
334 template_preconditions,
335 preserved_paths,
336 warnings,
337 plan_digest,
338 root_identity: root_identity_guard,
339 destination_inventory,
340 })
341}
342
343struct InitializationDigestInput<'a> {
344 root: &'a Path,
345 root_identity: &'a [u8],
346 request: &'a InitializationRequest,
347 folderbase_kind: FolderbaseKind,
348 directories: &'a [PlannedDirectory],
349 writes: &'a [PlannedWrite],
350 template_preconditions: &'a [TemplateArtifactPrecondition],
351 preserved_paths: &'a [PreservedPath],
352 warnings: &'a [String],
353 destination_inventory: &'a [InitializationDestinationEntry],
354}
355
356fn initialization_plan_digest(
357 input: InitializationDigestInput<'_>,
358) -> Result<InitializationPlanDigest> {
359 let mut hasher = Sha256::new();
360 digest_bytes(&mut hasher, b"domain", b"folderbase.initialization-plan.v1");
361 digest_path(&mut hasher, b"root", input.root);
362 digest_bytes(&mut hasher, b"root_identity", input.root_identity);
363 digest_text(
364 &mut hasher,
365 b"resolved_folderbase_kind",
366 folderbase_kind_name(input.folderbase_kind),
367 );
368 digest_request(&mut hasher, input.request)?;
369
370 digest_u64(
371 &mut hasher,
372 b"directory_count",
373 input.directories.len() as u64,
374 );
375 for directory in input.directories {
376 digest_path(&mut hasher, b"directory_path", &directory.path);
377 digest_text(
378 &mut hasher,
379 b"directory_purpose",
380 directory.purpose.as_str(),
381 );
382 }
383
384 digest_u64(&mut hasher, b"write_count", input.writes.len() as u64);
385 for write in input.writes {
386 digest_path(&mut hasher, b"write_path", &write.path);
387 digest_text(&mut hasher, b"write_purpose", write.purpose.as_str());
388 if write.path == Path::new(MANIFEST) {
389 let mut manifest = serde_json::from_str::<Value>(&write.content)
390 .map_err(|source| FolderbaseError::json(input.root.join(MANIFEST), source))?;
391 for pointer in [
392 "/folderbase/id",
393 "/folderbase/created_at",
394 "/folderbase/template_provenance/applied_at",
395 ] {
396 if let Some(value) = manifest.pointer_mut(pointer) {
397 *value = Value::String("<volatile>".to_owned());
398 }
399 }
400 digest_json_value(&mut hasher, b"write_manifest_semantics", &manifest);
401 } else {
402 digest_bytes(&mut hasher, b"write_content", write.content.as_bytes());
403 }
404 }
405
406 digest_u64(
407 &mut hasher,
408 b"template_precondition_count",
409 input.template_preconditions.len() as u64,
410 );
411 for precondition in input.template_preconditions {
412 digest_path(
413 &mut hasher,
414 b"template_precondition_path",
415 &precondition.path,
416 );
417 digest_text(
418 &mut hasher,
419 b"template_precondition_kind",
420 template_artifact_kind_name(precondition.kind),
421 );
422 }
423
424 digest_u64(
425 &mut hasher,
426 b"preserved_path_count",
427 input.preserved_paths.len() as u64,
428 );
429 for preserved in input.preserved_paths {
430 digest_path(&mut hasher, b"preserved_path", &preserved.path);
431 }
432
433 digest_u64(&mut hasher, b"warning_count", input.warnings.len() as u64);
434 for warning in input.warnings {
435 digest_text(&mut hasher, b"warning", warning);
436 }
437
438 digest_u64(
439 &mut hasher,
440 b"destination_inventory_count",
441 input.destination_inventory.len() as u64,
442 );
443 for entry in input.destination_inventory {
444 digest_path(&mut hasher, b"destination_path", &entry.path);
445 digest_text(
446 &mut hasher,
447 b"destination_kind",
448 destination_kind_name(entry.kind),
449 );
450 }
451
452 Ok(InitializationPlanDigest {
453 algorithm: "sha256".to_owned(),
454 digest: format!("{:x}", hasher.finalize()),
455 })
456}
457
458fn digest_request(hasher: &mut Sha256, request: &InitializationRequest) -> Result<()> {
459 let options = match request {
460 InitializationRequest::Ordinary { options } => {
461 digest_text(hasher, b"request_type", "ordinary");
462 options
463 }
464 InitializationRequest::Template {
465 options,
466 package,
467 answers,
468 } => {
469 digest_text(hasher, b"request_type", "template");
470 digest_text(hasher, b"template_id", package.id());
471 digest_text(hasher, b"template_version", package.version());
472 digest_text(
473 hasher,
474 b"template_package_sha256",
475 &template_package_sha256(package)?,
476 );
477 digest_u64(hasher, b"template_answer_count", answers.len() as u64);
478 for (id, answer) in answers {
479 digest_text(hasher, b"template_answer_id", id);
480 match answer {
481 TemplateAnswerValue::Text(value) => {
482 digest_text(hasher, b"template_answer_type", "text");
483 digest_text(hasher, b"template_answer_value", value);
484 }
485 TemplateAnswerValue::Boolean(value) => {
486 digest_text(hasher, b"template_answer_type", "boolean");
487 digest_text(
488 hasher,
489 b"template_answer_value",
490 if *value { "true" } else { "false" },
491 );
492 }
493 }
494 }
495 options
496 }
497 };
498 match &options.name {
499 Some(name) => {
500 digest_text(hasher, b"request_name_present", "true");
501 digest_text(hasher, b"request_name", name);
502 }
503 None => digest_text(hasher, b"request_name_present", "false"),
504 }
505 digest_text(hasher, b"request_kind", folderbase_kind_name(options.kind));
506 digest_text(
507 hasher,
508 b"request_create_agent_adapters",
509 if options.create_agent_adapters {
510 "true"
511 } else {
512 "false"
513 },
514 );
515 Ok(())
516}
517
518fn digest_json_value(hasher: &mut Sha256, label: &[u8], value: &Value) {
519 digest_bytes(hasher, b"json_label", label);
520 match value {
521 Value::Null => digest_text(hasher, b"json_type", "null"),
522 Value::Bool(value) => {
523 digest_text(hasher, b"json_type", "boolean");
524 digest_text(
525 hasher,
526 b"json_boolean",
527 if *value { "true" } else { "false" },
528 );
529 }
530 Value::Number(value) => {
531 digest_text(hasher, b"json_type", "number");
532 digest_text(hasher, b"json_number", &value.to_string());
533 }
534 Value::String(value) => {
535 digest_text(hasher, b"json_type", "string");
536 digest_text(hasher, b"json_string", value);
537 }
538 Value::Array(values) => {
539 digest_text(hasher, b"json_type", "array");
540 digest_u64(hasher, b"json_array_length", values.len() as u64);
541 for value in values {
542 digest_json_value(hasher, b"json_array_value", value);
543 }
544 }
545 Value::Object(values) => {
546 digest_text(hasher, b"json_type", "object");
547 digest_u64(hasher, b"json_object_length", values.len() as u64);
548 let mut keys = values.keys().collect::<Vec<_>>();
549 keys.sort();
550 for key in keys {
551 digest_text(hasher, b"json_object_key", key);
552 digest_json_value(hasher, b"json_object_value", &values[key]);
553 }
554 }
555 }
556}
557
558fn digest_path(hasher: &mut Sha256, label: &[u8], path: &Path) {
559 digest_bytes(hasher, b"path_label", label);
560 digest_os_str(hasher, b"path_value", path.as_os_str());
561}
562
563fn digest_os_str(hasher: &mut Sha256, label: &[u8], value: &std::ffi::OsStr) {
564 #[cfg(unix)]
565 {
566 use std::os::unix::ffi::OsStrExt;
567 digest_bytes(hasher, label, value.as_bytes());
568 }
569 #[cfg(windows)]
570 {
571 use std::os::windows::ffi::OsStrExt;
572 let bytes = value
573 .encode_wide()
574 .flat_map(u16::to_le_bytes)
575 .collect::<Vec<_>>();
576 digest_bytes(hasher, label, &bytes);
577 }
578 #[cfg(not(any(unix, windows)))]
579 digest_bytes(hasher, label, value.as_encoded_bytes());
580}
581
582fn digest_text(hasher: &mut Sha256, label: &[u8], value: &str) {
583 digest_bytes(hasher, label, value.as_bytes());
584}
585
586fn digest_u64(hasher: &mut Sha256, label: &[u8], value: u64) {
587 digest_bytes(hasher, label, &value.to_be_bytes());
588}
589
590fn digest_bytes(hasher: &mut Sha256, label: &[u8], value: &[u8]) {
591 hasher.update((label.len() as u64).to_be_bytes());
592 hasher.update(label);
593 hasher.update((value.len() as u64).to_be_bytes());
594 hasher.update(value);
595}
596
597fn template_artifact_kind_name(kind: TemplateArtifactKind) -> &'static str {
598 match kind {
599 TemplateArtifactKind::Directory => "directory",
600 TemplateArtifactKind::Text => "text",
601 }
602}
603
604fn destination_kind_name(kind: InitializationDestinationKind) -> &'static str {
605 match kind {
606 InitializationDestinationKind::Directory => "directory",
607 InitializationDestinationKind::File => "file",
608 InitializationDestinationKind::Symlink => "symlink",
609 InitializationDestinationKind::ReconstructableDirectory => "reconstructable_directory",
610 InitializationDestinationKind::GitMetadata => "git_metadata",
611 InitializationDestinationKind::NestedFolderbase => "nested_folderbase",
612 InitializationDestinationKind::Other => "other",
613 }
614}
615
616fn resolve_folderbase_name(root: &Path, requested: Option<&str>) -> Result<String> {
617 let name = requested
618 .filter(|name| !name.trim().is_empty())
619 .map(str::trim)
620 .map(ToOwned::to_owned)
621 .or_else(|| {
622 root.file_name()
623 .and_then(|name| name.to_str())
624 .map(str::trim)
625 .map(ToOwned::to_owned)
626 })
627 .unwrap_or_else(|| "Untitled Folderbase".to_owned());
628 if name.is_empty()
629 || name.chars().count() > 120
630 || name
631 .chars()
632 .any(|character| character.is_control() || matches!(character, '\u{2028}' | '\u{2029}'))
633 {
634 return Err(FolderbaseError::InvalidRecord {
635 path: root.to_path_buf(),
636 message: "folderbase name must be nonblank, single-line text of at most 120 characters"
637 .to_owned(),
638 });
639 }
640 Ok(name)
641}
642
643pub fn initialize(plan: &InitializationPlan) -> Result<InitializationResult> {
650 let root = canonical_directory(&plan.root)?;
651 if root != plan.root {
652 return Err(FolderbaseError::PlanRootMismatch {
653 planned_root: plan.root.clone(),
654 actual_root: root,
655 });
656 }
657
658 let opened_root = open_root_capability(&root)?;
659 if opened_root.identity.identity() != plan.root_identity.identity() {
660 return Err(FolderbaseError::PlanRootIdentityChanged(root));
661 }
662 let mut preflight_budget = InitializationInventoryBudget::default();
663 refuse_nested_target(&root, &mut preflight_budget)?;
664 let root_dir = opened_root.directory;
665
666 verify_template_preconditions(&root_dir, plan, &mut preflight_budget)?;
667 validate_planned_paths_against_existing(&plan.root, &plan.directories, &plan.writes)?;
668 verify_destinations_absent(&root_dir, plan, &mut preflight_budget)?;
669 if snapshot_destination_inventory(&root_dir, &root, &mut preflight_budget)?
670 != plan.destination_inventory
671 {
672 return Err(FolderbaseError::InitializationDestinationChanged(root));
673 }
674
675 for directory in &plan.directories {
676 create_directory_no_clobber(&root_dir, &plan.root, &directory.path)?;
677 }
678
679 let mut created_paths = plan
680 .directories
681 .iter()
682 .map(|directory| directory.path.clone())
683 .collect::<Vec<_>>();
684 for write in &plan.writes {
685 install_text_no_clobber(
686 &root_dir,
687 &plan.root,
688 &write.path,
689 write.content.as_bytes(),
690 "init",
691 )?;
692 created_paths.push(write.path.clone());
693 }
694
695 Ok(InitializationResult {
696 root: plan.root.clone(),
697 folderbase_id: plan.folderbase_id.clone(),
698 created_paths,
699 preserved_paths: plan
700 .preserved_paths
701 .iter()
702 .map(|preserved| preserved.path.clone())
703 .collect(),
704 applied_plan_digest: plan.plan_digest.clone(),
705 })
706}
707
708pub fn initialize_with_expected_plan_digest(
711 plan: &InitializationPlan,
712 expected: &InitializationPlanDigest,
713) -> Result<InitializationResult> {
714 expected.validate()?;
715 if plan.plan_digest != *expected {
716 return Err(FolderbaseError::InitializationPlanChanged {
717 expected: expected.digest.clone(),
718 actual: plan.plan_digest.digest.clone(),
719 });
720 }
721 initialize(plan)
722}
723
724pub(crate) fn create_directory_no_clobber(root_dir: &Dir, root: &Path, path: &Path) -> Result<()> {
725 ensure_safe_relative(path)?;
726 let (parent, name) = open_parent_dir_nofollow(root_dir, root, path)?;
727 let builder = cap_std::fs::DirBuilder::new();
728 #[cfg(unix)]
729 let builder = {
730 use cap_std::fs::DirBuilderExt;
731
732 let mut builder = builder;
733 if path.starts_with(".folderbase") {
734 builder.mode(0o700);
735 }
736 builder
737 };
738 if let Err(source) = parent.create_dir_with(&name, &builder) {
739 return Err(if source.kind() == std::io::ErrorKind::AlreadyExists {
740 FolderbaseError::WouldOverwrite(root.join(path))
741 } else {
742 FolderbaseError::io(root.join(path), source)
743 });
744 }
745 Ok(())
746}
747
748pub(crate) fn install_text_no_clobber(
749 root_dir: &Dir,
750 root: &Path,
751 path: &Path,
752 content: &[u8],
753 staging_label: &str,
754) -> Result<()> {
755 ensure_safe_relative(path)?;
756 let (destination_parent, destination_name) = open_parent_dir_nofollow(root_dir, root, path)?;
757
758 let staged_path = PathBuf::from(format!(
759 ".folderbase/.{staging_label}-{}.tmp",
760 Uuid::now_v7()
761 ));
762 let (staging_parent, staging_name) = open_parent_dir_nofollow(root_dir, root, &staged_path)?;
763 let mut options = OpenOptions::new();
764 options
765 .write(true)
766 .create_new(true)
767 .follow(FollowSymlinks::No);
768 #[cfg(unix)]
769 {
770 use cap_std::fs::OpenOptionsExt;
771
772 if path.starts_with(".folderbase") {
773 options.mode(0o600);
774 }
775 }
776 let mut staged = staging_parent
777 .open_with(&staging_name, &options)
778 .map_err(|source| FolderbaseError::io(root.join(&staged_path), source))?;
779 if let Err(source) = staged.write_all(content).and_then(|()| staged.sync_all()) {
780 drop(staged);
781 let _ = staging_parent.remove_file(&staging_name);
782 return Err(FolderbaseError::io(root.join(&staged_path), source));
783 }
784 drop(staged);
785
786 if let Err(source) =
787 staging_parent.hard_link(&staging_name, &destination_parent, &destination_name)
788 {
789 let _ = staging_parent.remove_file(&staging_name);
790 return Err(if source.kind() == std::io::ErrorKind::AlreadyExists {
791 FolderbaseError::WouldOverwrite(root.join(path))
792 } else {
793 FolderbaseError::io(root.join(path), source)
794 });
795 }
796 let _ = staging_parent.remove_file(&staging_name);
797 Ok(())
798}
799
800fn open_parent_dir_nofollow(
801 root_dir: &Dir,
802 root: &Path,
803 path: &Path,
804) -> Result<(Dir, std::ffi::OsString)> {
805 ensure_safe_relative(path)?;
806 let name = path
807 .file_name()
808 .ok_or_else(|| FolderbaseError::UnsafePath(path.to_path_buf()))?
809 .to_os_string();
810 let mut current = root_dir
811 .try_clone()
812 .map_err(|source| FolderbaseError::io(root, source))?;
813 if let Some(parent) = path.parent() {
814 let mut traversed = PathBuf::new();
815 for component in parent.components() {
816 let Component::Normal(component) = component else {
817 return Err(FolderbaseError::UnsafePath(path.to_path_buf()));
818 };
819 traversed.push(component);
820 current = current
821 .open_dir_nofollow(component)
822 .map_err(|source| FolderbaseError::io(root.join(&traversed), source))?;
823 }
824 }
825 Ok((current, name))
826}
827
828pub(crate) fn canonical_directory(path: &Path) -> Result<PathBuf> {
829 if !path.is_dir() {
830 return Err(FolderbaseError::InvalidRoot(path.to_path_buf()));
831 }
832 path.canonicalize()
833 .map_err(|source| FolderbaseError::io(path, source))
834}
835
836pub(crate) fn refuse_symlink_root(root: &Path) -> Result<()> {
837 let metadata =
838 fs::symlink_metadata(root).map_err(|source| FolderbaseError::io(root, source))?;
839 if metadata.file_type().is_symlink() {
840 return Err(FolderbaseError::InvalidRecord {
841 path: root.to_path_buf(),
842 message: "template adoption destination root is a symlink".to_owned(),
843 });
844 }
845 if !metadata.is_dir() {
846 return Err(FolderbaseError::InvalidRoot(root.to_path_buf()));
847 }
848 Ok(())
849}
850
851fn template_preconditions(
852 root: &Path,
853 package: &TemplatePackage,
854 rendered: &TemplateRenderPlan,
855 boundary_budget: &mut InitializationInventoryBudget,
856) -> Result<Vec<TemplateArtifactPrecondition>> {
857 let root_dir = open_root_capability(root)?.directory;
858 let mut preconditions = Vec::new();
859 for path in &rendered.existing_paths {
860 let artifact = package
861 .artifacts
862 .iter()
863 .find(|artifact| artifact.target == *path)
864 .ok_or_else(|| FolderbaseError::InvalidRecord {
865 path: path.clone(),
866 message: "rendered existing target is not declared by its template".to_owned(),
867 })?;
868 let destination = safe_destination(root, path)?;
869 let metadata = root_dir
870 .symlink_metadata(path)
871 .map_err(|source| FolderbaseError::io(&destination, source))?;
872 let expected_type = match artifact.kind {
873 TemplateArtifactKind::Directory => metadata.is_dir(),
874 TemplateArtifactKind::Text => metadata.is_file(),
875 };
876 if metadata.file_type().is_symlink() || !expected_type {
877 return Err(FolderbaseError::InvalidRecord {
878 path: destination,
879 message: format!(
880 "existing template target has the wrong type; expected {:?}",
881 artifact.kind
882 ),
883 });
884 }
885 let identity = match artifact.kind {
886 TemplateArtifactKind::Directory => {
887 let directory = root_dir
888 .open_dir_nofollow(path)
889 .map_err(|source| FolderbaseError::io(&destination, source))?;
890 if has_nested_folderbase_marker_capability(
891 &directory,
892 destination.clone(),
893 boundary_budget,
894 )? {
895 return Err(FolderbaseError::InvalidRecord {
896 path: destination,
897 message: "existing template directory is already a nested folderbase"
898 .to_owned(),
899 });
900 }
901 RetainedPhysicalIdentity::from_file(
902 directory
903 .try_clone()
904 .map_err(|source| FolderbaseError::io(&destination, source))?
905 .into_std_file(),
906 )
907 .map_err(|source| FolderbaseError::io(&destination, source))?
908 }
909 TemplateArtifactKind::Text => {
910 let mut options = OpenOptions::new();
911 options.read(true).follow(FollowSymlinks::No);
912 let file = root_dir
913 .open_with(path, &options)
914 .map_err(|source| FolderbaseError::io(&destination, source))?;
915 RetainedPhysicalIdentity::from_file(file.into_std())
916 .map_err(|source| FolderbaseError::io(&destination, source))?
917 }
918 };
919 preconditions.push(TemplateArtifactPrecondition {
920 path: path.clone(),
921 kind: artifact.kind,
922 identity,
923 });
924 }
925 preconditions.sort_by(|left, right| left.path.cmp(&right.path));
926 Ok(preconditions)
927}
928
929fn verify_template_preconditions(
930 root_dir: &Dir,
931 plan: &InitializationPlan,
932 boundary_budget: &mut InitializationInventoryBudget,
933) -> Result<()> {
934 for precondition in &plan.template_preconditions {
935 let changed = || FolderbaseError::PlanPreconditionChanged(precondition.path.clone());
936 ensure_safe_relative(&precondition.path).map_err(|_| changed())?;
937 let destination =
938 safe_destination(&plan.root, &precondition.path).map_err(|_| changed())?;
939 let metadata = root_dir
940 .symlink_metadata(&precondition.path)
941 .map_err(|_| changed())?;
942 let expected_type = match precondition.kind {
943 TemplateArtifactKind::Directory => metadata.is_dir(),
944 TemplateArtifactKind::Text => metadata.is_file(),
945 };
946 if metadata.file_type().is_symlink() || !expected_type {
947 return Err(changed());
948 }
949 let current_identity = match precondition.kind {
950 TemplateArtifactKind::Directory => {
951 let directory = root_dir
952 .open_dir_nofollow(&precondition.path)
953 .map_err(|_| changed())?;
954 let is_nested = match has_nested_folderbase_marker_capability(
955 &directory,
956 destination.clone(),
957 boundary_budget,
958 ) {
959 Ok(is_nested) => is_nested,
960 Err(error @ FolderbaseError::InitializationInventoryLimitExceeded { .. }) => {
961 return Err(error);
962 }
963 Err(_) => return Err(changed()),
964 };
965 if is_nested {
966 return Err(changed());
967 }
968 let file = directory
969 .try_clone()
970 .map_err(|_| changed())?
971 .into_std_file();
972 PhysicalIdentity::from_file(&file).map_err(|_| changed())?
973 }
974 TemplateArtifactKind::Text => {
975 let mut options = OpenOptions::new();
976 options.read(true).follow(FollowSymlinks::No);
977 let file = root_dir
978 .open_with(&precondition.path, &options)
979 .map_err(|_| changed())?;
980 PhysicalIdentity::from_file(&file.into_std()).map_err(|_| changed())?
981 }
982 };
983 if current_identity != precondition.identity.identity() {
984 return Err(changed());
985 }
986 }
987 Ok(())
988}
989
990fn refuse_nested_target(root: &Path, budget: &mut InitializationInventoryBudget) -> Result<()> {
991 for ancestor in root.ancestors().skip(1) {
992 let metadata = fs::symlink_metadata(ancestor)
993 .map_err(|source| FolderbaseError::io(ancestor, source))?;
994 if metadata.file_type().is_symlink() || !metadata.is_dir() {
995 continue;
996 }
997 let directory = open_root_capability(ancestor)?.directory;
998 if has_nested_folderbase_marker_capability(&directory, ancestor.to_path_buf(), budget)? {
999 return Err(FolderbaseError::InvalidRecord {
1000 path: root.to_path_buf(),
1001 message: format!(
1002 "initialization target is nested inside another folderbase at {}",
1003 ancestor.display()
1004 ),
1005 });
1006 }
1007 }
1008 Ok(())
1009}
1010
1011#[cfg(test)]
1012pub(crate) fn refuse_template_target_inside_nested_folderbase(
1013 root: &Path,
1014 target: &Path,
1015) -> Result<()> {
1016 let root_dir = open_root_capability(root)?.directory;
1017 let mut budget = InitializationInventoryBudget::default();
1018 refuse_template_target_inside_nested_folderbase_capability(&root_dir, root, target, &mut budget)
1019}
1020
1021fn refuse_template_target_inside_nested_folderbase_capability(
1022 root_dir: &Dir,
1023 root: &Path,
1024 target: &Path,
1025 budget: &mut InitializationInventoryBudget,
1026) -> Result<()> {
1027 ensure_safe_relative(target)?;
1028 let mut current_dir = root_dir
1029 .try_clone()
1030 .map_err(|source| FolderbaseError::io(root, source))?;
1031 let mut current_path = root.to_path_buf();
1032 if let Some(parent) = target.parent() {
1033 for component in parent.components() {
1034 let Component::Normal(component) = component else {
1035 return Err(FolderbaseError::UnsafePath(target.to_path_buf()));
1036 };
1037 current_path.push(component);
1038 let metadata = match current_dir.symlink_metadata(component) {
1039 Ok(metadata) => metadata,
1040 Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(()),
1041 Err(source) => return Err(FolderbaseError::io(¤t_path, source)),
1042 };
1043 if metadata.file_type().is_symlink() || !metadata.is_dir() {
1044 return Err(FolderbaseError::UnsafePath(current_path));
1045 }
1046 current_dir = current_dir
1047 .open_dir_nofollow(component)
1048 .map_err(|source| FolderbaseError::io(¤t_path, source))?;
1049 if has_nested_folderbase_marker_capability(¤t_dir, current_path.clone(), budget)?
1050 {
1051 return Err(FolderbaseError::InvalidRecord {
1052 path: target.to_path_buf(),
1053 message: format!(
1054 "template target is inside nested folderbase at {}",
1055 current_path.display()
1056 ),
1057 });
1058 }
1059 }
1060 }
1061 Ok(())
1062}
1063
1064struct OpenedRootCapability {
1065 directory: Dir,
1066 identity: RetainedPhysicalIdentity,
1067 digest_identity: Vec<u8>,
1068}
1069
1070fn open_root_capability(root: &Path) -> Result<OpenedRootCapability> {
1071 let mut options = fs::OpenOptions::new();
1072 options.read(true);
1073 #[cfg(unix)]
1074 {
1075 use std::os::unix::fs::OpenOptionsExt;
1076
1077 options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
1078 }
1079 #[cfg(windows)]
1080 {
1081 use std::os::windows::fs::OpenOptionsExt;
1082 use windows_sys::Win32::Storage::FileSystem::{
1083 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
1084 FILE_SHARE_WRITE,
1085 };
1086
1087 options
1088 .access_mode(0)
1095 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1096 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
1097 }
1098 let file = options
1099 .open(root)
1100 .map_err(|source| FolderbaseError::io(root, source))?;
1101 let metadata = file
1102 .metadata()
1103 .map_err(|source| FolderbaseError::io(root, source))?;
1104 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
1105 return Err(FolderbaseError::InvalidRoot(root.to_path_buf()));
1106 }
1107 let digest_identity = root_digest_identity(&file, &metadata, root)?;
1108 let identity = RetainedPhysicalIdentity::from_file(
1109 file.try_clone()
1110 .map_err(|source| FolderbaseError::io(root, source))?,
1111 )
1112 .map_err(|source| FolderbaseError::io(root, source))?;
1113 Ok(OpenedRootCapability {
1114 directory: Dir::from_std_file(file),
1115 identity,
1116 digest_identity,
1117 })
1118}
1119
1120#[cfg(unix)]
1121fn root_digest_identity(
1122 _file: &fs::File,
1123 metadata: &fs::Metadata,
1124 _root: &Path,
1125) -> Result<Vec<u8>> {
1126 use std::os::unix::fs::MetadataExt;
1127
1128 let mut identity = Vec::with_capacity(16);
1129 identity.extend_from_slice(&metadata.dev().to_be_bytes());
1130 identity.extend_from_slice(&metadata.ino().to_be_bytes());
1131 Ok(identity)
1132}
1133
1134#[cfg(windows)]
1135fn root_digest_identity(file: &fs::File, _metadata: &fs::Metadata, root: &Path) -> Result<Vec<u8>> {
1136 let information =
1137 winapi_util::file::information(file).map_err(|source| FolderbaseError::io(root, source))?;
1138 let mut identity = Vec::with_capacity(12);
1139 identity.extend_from_slice(&(information.volume_serial_number() as u32).to_be_bytes());
1140 identity.extend_from_slice(&information.file_index().to_be_bytes());
1141 Ok(identity)
1142}
1143
1144#[cfg(not(any(unix, windows)))]
1145fn root_digest_identity(
1146 _file: &fs::File,
1147 _metadata: &fs::Metadata,
1148 root: &Path,
1149) -> Result<Vec<u8>> {
1150 Err(FolderbaseError::InvalidRecord {
1151 path: root.to_path_buf(),
1152 message: "filesystem does not expose a supported stable root identity".to_owned(),
1153 })
1154}
1155
1156struct InitializationInventoryBudget {
1157 entries: usize,
1158 encoded_bytes: usize,
1159 path_component_work: usize,
1160 directory_entry_work: usize,
1161}
1162
1163impl Default for InitializationInventoryBudget {
1164 fn default() -> Self {
1165 Self {
1166 entries: 0,
1167 encoded_bytes: digest_frame_len(b"destination_inventory_count", 8),
1168 path_component_work: 0,
1169 directory_entry_work: 0,
1170 }
1171 }
1172}
1173
1174impl InitializationInventoryBudget {
1175 fn record_path(&mut self, path: &Path, depth: usize) -> Result<()> {
1176 if depth > MAX_INITIALIZATION_DEPTH {
1177 return Err(inventory_limit(
1178 InitializationInventoryLimitKind::Depth,
1179 MAX_INITIALIZATION_DEPTH as u64,
1180 ));
1181 }
1182 let path_bytes = digest_os_str_len(path.as_os_str());
1183 if path_bytes > MAX_INITIALIZATION_PATH_BYTES {
1184 return Err(inventory_limit(
1185 InitializationInventoryLimitKind::PathBytes,
1186 MAX_INITIALIZATION_PATH_BYTES as u64,
1187 ));
1188 }
1189 self.entries = self.entries.saturating_add(1);
1190 if self.entries > MAX_INITIALIZATION_INVENTORY_ENTRIES {
1191 return Err(inventory_limit(
1192 InitializationInventoryLimitKind::Entries,
1193 MAX_INITIALIZATION_INVENTORY_ENTRIES as u64,
1194 ));
1195 }
1196 self.encoded_bytes = self
1197 .encoded_bytes
1198 .saturating_add(digest_frame_len(b"path_label", b"destination_path".len()))
1199 .saturating_add(digest_frame_len(b"path_value", path_bytes));
1200 if self.encoded_bytes > MAX_INITIALIZATION_ENCODED_INVENTORY_BYTES {
1201 return Err(inventory_limit(
1202 InitializationInventoryLimitKind::EncodedInventoryBytes,
1203 MAX_INITIALIZATION_ENCODED_INVENTORY_BYTES as u64,
1204 ));
1205 }
1206 self.path_component_work = self.path_component_work.saturating_add(depth);
1207 if self.path_component_work > MAX_INITIALIZATION_PATH_COMPONENT_WORK {
1208 return Err(inventory_limit(
1209 InitializationInventoryLimitKind::PathComponentWork,
1210 MAX_INITIALIZATION_PATH_COMPONENT_WORK as u64,
1211 ));
1212 }
1213 Ok(())
1214 }
1215
1216 fn record_kind(&mut self, kind: InitializationDestinationKind) -> Result<()> {
1217 self.encoded_bytes = self.encoded_bytes.saturating_add(digest_frame_len(
1218 b"destination_kind",
1219 destination_kind_name(kind).len(),
1220 ));
1221 if self.encoded_bytes > MAX_INITIALIZATION_ENCODED_INVENTORY_BYTES {
1222 return Err(inventory_limit(
1223 InitializationInventoryLimitKind::EncodedInventoryBytes,
1224 MAX_INITIALIZATION_ENCODED_INVENTORY_BYTES as u64,
1225 ));
1226 }
1227 Ok(())
1228 }
1229
1230 fn observe_directory_entry(&mut self) -> Result<()> {
1231 self.directory_entry_work = self.directory_entry_work.saturating_add(1);
1232 if self.directory_entry_work > MAX_INITIALIZATION_DIRECTORY_ENTRY_WORK {
1233 return Err(inventory_limit(
1234 InitializationInventoryLimitKind::DirectoryEntryWork,
1235 MAX_INITIALIZATION_DIRECTORY_ENTRY_WORK as u64,
1236 ));
1237 }
1238 Ok(())
1239 }
1240}
1241
1242fn digest_frame_len(label: &[u8], value_len: usize) -> usize {
1243 16usize
1244 .saturating_add(label.len())
1245 .saturating_add(value_len)
1246}
1247
1248fn digest_os_str_len(value: &OsStr) -> usize {
1249 #[cfg(unix)]
1250 {
1251 use std::os::unix::ffi::OsStrExt;
1252 value.as_bytes().len()
1253 }
1254 #[cfg(windows)]
1255 {
1256 use std::os::windows::ffi::OsStrExt;
1257 value.encode_wide().count().saturating_mul(2)
1258 }
1259 #[cfg(not(any(unix, windows)))]
1260 value.as_encoded_bytes().len()
1261}
1262
1263fn inventory_limit(limit: InitializationInventoryLimitKind, maximum: u64) -> FolderbaseError {
1264 FolderbaseError::InitializationInventoryLimitExceeded { limit, maximum }
1265}
1266
1267fn snapshot_destination_inventory(
1268 root_dir: &Dir,
1269 root: &Path,
1270 budget: &mut InitializationInventoryBudget,
1271) -> Result<Vec<InitializationDestinationEntry>> {
1272 fn visit(
1273 root: &Path,
1274 current_dir: &Dir,
1275 relative_parent: &Path,
1276 depth: usize,
1277 budget: &mut InitializationInventoryBudget,
1278 inventory: &mut Vec<InitializationDestinationEntry>,
1279 ) -> Result<()> {
1280 let entries = current_dir
1281 .read_dir(".")
1282 .map_err(|source| FolderbaseError::io(root.join(relative_parent), source))?;
1283 let mut names = Vec::new();
1284 for entry in entries {
1285 let entry =
1286 entry.map_err(|source| FolderbaseError::io(root.join(relative_parent), source))?;
1287 budget.observe_directory_entry()?;
1288 let name = entry.file_name();
1289 let relative = relative_parent.join(&name);
1290 budget.record_path(&relative, depth)?;
1291 names.push(name);
1292 }
1293 names.sort();
1294
1295 for name in names {
1296 let relative = relative_parent.join(&name);
1297 let metadata = current_dir
1298 .symlink_metadata(&name)
1299 .map_err(|source| FolderbaseError::io(root.join(&relative), source))?;
1300 let kind = if metadata.file_type().is_symlink() {
1301 InitializationDestinationKind::Symlink
1302 } else if metadata.is_dir() {
1303 if is_git_metadata_component(&name) {
1304 InitializationDestinationKind::GitMetadata
1305 } else if is_reconstructable_directory(&name) {
1306 InitializationDestinationKind::ReconstructableDirectory
1307 } else {
1308 let child = current_dir
1309 .open_dir_nofollow(&name)
1310 .map_err(|source| FolderbaseError::io(root.join(&relative), source))?;
1311 if has_nested_folderbase_marker_capability(
1312 &child,
1313 root.join(&relative),
1314 budget,
1315 )? {
1316 InitializationDestinationKind::NestedFolderbase
1317 } else {
1318 budget.record_kind(InitializationDestinationKind::Directory)?;
1319 inventory.push(InitializationDestinationEntry {
1320 path: relative.clone(),
1321 kind: InitializationDestinationKind::Directory,
1322 });
1323 visit(root, &child, &relative, depth + 1, budget, inventory)?;
1324 continue;
1325 }
1326 }
1327 } else if metadata.is_file() {
1328 InitializationDestinationKind::File
1329 } else {
1330 InitializationDestinationKind::Other
1331 };
1332 budget.record_kind(kind)?;
1333 inventory.push(InitializationDestinationEntry {
1334 path: relative,
1335 kind,
1336 });
1337 }
1338 Ok(())
1339 }
1340
1341 let mut inventory = Vec::new();
1342 visit(root, root_dir, Path::new(""), 1, budget, &mut inventory)?;
1343 inventory.sort_by(|left, right| left.path.cmp(&right.path));
1344 Ok(inventory)
1345}
1346
1347fn has_nested_folderbase_marker_capability(
1348 directory: &Dir,
1349 display_path: PathBuf,
1350 budget: &mut InitializationInventoryBudget,
1351) -> Result<bool> {
1352 match classify_nested_folderbase_boundary_with_observer(directory, &display_path, || {
1353 budget.observe_directory_entry()
1354 })? {
1355 NestedFolderbaseBoundaryKind::ExactBoundary => Ok(true),
1356 NestedFolderbaseBoundaryKind::None => Ok(false),
1357 NestedFolderbaseBoundaryKind::UnsafeAliasShape => {
1358 Err(FolderbaseError::UnsafePath(display_path))
1359 }
1360 }
1361}
1362
1363fn plan_missing_parent_directories(
1364 root: &Path,
1365 relative_path: &Path,
1366 directories: &mut Vec<PlannedDirectory>,
1367) -> Result<()> {
1368 ensure_safe_relative(relative_path)?;
1369 let mut current = root.to_path_buf();
1370 let Some(parent) = relative_path.parent() else {
1371 return Ok(());
1372 };
1373 let mut relative = PathBuf::new();
1374 for component in parent.components() {
1375 let Component::Normal(component) = component else {
1376 return Err(FolderbaseError::UnsafePath(relative_path.to_path_buf()));
1377 };
1378 current.push(component);
1379 relative.push(component);
1380 match fs::symlink_metadata(¤t) {
1381 Ok(metadata) if metadata.file_type().is_symlink() => {
1382 return Err(FolderbaseError::UnsafePath(current));
1383 }
1384 Ok(metadata) if !metadata.is_dir() => {
1385 return Err(FolderbaseError::WouldOverwrite(current));
1386 }
1387 Ok(_) => {}
1388 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
1389 if !directories
1390 .iter()
1391 .any(|directory| directory.path == relative)
1392 {
1393 directories.push(PlannedDirectory {
1394 path: relative.clone(),
1395 purpose: "Parent directory for an additive protocol file".to_owned(),
1396 });
1397 }
1398 }
1399 Err(source) => return Err(FolderbaseError::io(current, source)),
1400 }
1401 }
1402 Ok(())
1403}
1404
1405fn validate_planned_path_collisions(
1406 root: &Path,
1407 directories: &[PlannedDirectory],
1408 writes: &[PlannedWrite],
1409) -> Result<()> {
1410 validate_template_path_collisions(
1411 root,
1412 directories
1413 .iter()
1414 .map(|directory| (directory.path.as_path(), true))
1415 .chain(writes.iter().map(|write| (write.path.as_path(), false))),
1416 )
1417}
1418
1419pub(crate) fn validate_template_path_collisions<'a>(
1420 root: &Path,
1421 planned_paths: impl IntoIterator<Item = (&'a Path, bool)>,
1422) -> Result<()> {
1423 let mut planned = planned_paths
1424 .into_iter()
1425 .map(|(path, is_directory)| {
1426 let text = path
1427 .to_str()
1428 .ok_or_else(|| FolderbaseError::UnsafePath(path.to_path_buf()))?;
1429 Ok((
1430 path,
1431 text.nfc()
1432 .collect::<String>()
1433 .case_fold()
1434 .collect::<String>()
1435 .nfc()
1436 .collect::<String>(),
1437 is_directory,
1438 ))
1439 })
1440 .collect::<Result<Vec<_>>>()?;
1441 planned.sort_by(|left, right| left.1.cmp(&right.1));
1442
1443 let mut seen = BTreeMap::<String, (&Path, bool)>::new();
1444 for (path, folded, is_directory) in planned {
1445 if let Some((existing, _)) = seen.get(&folded) {
1446 return planned_collision(root, existing, path);
1447 }
1448 for (index, character) in folded.char_indices() {
1449 if character != '/' {
1450 continue;
1451 }
1452 if let Some((ancestor, ancestor_is_directory)) = seen.get(&folded[..index])
1453 && !ancestor_is_directory
1454 {
1455 return planned_collision(root, ancestor, path);
1456 }
1457 }
1458 seen.insert(folded, (path, is_directory));
1459 }
1460 Ok(())
1461}
1462
1463fn validate_planned_paths_against_existing(
1464 root: &Path,
1465 directories: &[PlannedDirectory],
1466 writes: &[PlannedWrite],
1467) -> Result<()> {
1468 validate_template_paths_against_existing_casefold(
1469 root,
1470 directories
1471 .iter()
1472 .map(|directory| directory.path.as_path())
1473 .chain(writes.iter().map(|write| write.path.as_path())),
1474 false,
1475 )
1476}
1477
1478pub(crate) fn validate_template_paths_against_existing_casefold<'a>(
1479 root: &Path,
1480 planned_paths: impl IntoIterator<Item = &'a Path>,
1481 allow_exact_target: bool,
1482) -> Result<()> {
1483 for planned in planned_paths {
1484 let mut parent = root.to_path_buf();
1485 let component_count = planned.components().count();
1486 for (index, component) in planned.components().enumerate() {
1487 let Component::Normal(component) = component else {
1488 return Err(FolderbaseError::UnsafePath(planned.to_path_buf()));
1489 };
1490 let component_text = component
1491 .to_str()
1492 .ok_or_else(|| FolderbaseError::UnsafePath(planned.to_path_buf()))?;
1493 let folded_component = component_text
1494 .nfc()
1495 .collect::<String>()
1496 .case_fold()
1497 .collect::<String>()
1498 .nfc()
1499 .collect::<String>();
1500 let mut exact = None;
1501 for entry in
1502 fs::read_dir(&parent).map_err(|source| FolderbaseError::io(&parent, source))?
1503 {
1504 let entry = entry.map_err(|source| FolderbaseError::io(&parent, source))?;
1505 let name = entry.file_name();
1506 let Some(name_text) = name.to_str() else {
1507 continue;
1511 };
1512 if name_text
1513 .nfc()
1514 .collect::<String>()
1515 .case_fold()
1516 .collect::<String>()
1517 .nfc()
1518 .collect::<String>()
1519 != folded_component
1520 {
1521 continue;
1522 }
1523 if name == component {
1524 exact = Some(entry);
1525 } else {
1526 return Err(FolderbaseError::InvalidRecord {
1527 path: root.to_path_buf(),
1528 message: format!(
1529 "planned path collision: {} aliases existing {}",
1530 planned.display(),
1531 entry.path().display()
1532 ),
1533 });
1534 }
1535 }
1536
1537 let Some(entry) = exact else {
1538 break;
1539 };
1540 if index + 1 == component_count {
1541 if allow_exact_target {
1542 break;
1543 }
1544 return Err(FolderbaseError::WouldOverwrite(entry.path()));
1545 }
1546 let file_type = entry
1547 .file_type()
1548 .map_err(|source| FolderbaseError::io(entry.path(), source))?;
1549 if file_type.is_symlink() || !file_type.is_dir() {
1550 return Err(FolderbaseError::InvalidRecord {
1551 path: root.to_path_buf(),
1552 message: format!(
1553 "planned path collision: ancestor {} is not a safe directory",
1554 entry.path().display()
1555 ),
1556 });
1557 }
1558 parent = entry.path();
1559 }
1560 }
1561 Ok(())
1562}
1563
1564fn planned_collision(root: &Path, left: &Path, right: &Path) -> Result<()> {
1565 Err(FolderbaseError::InvalidRecord {
1566 path: root.to_path_buf(),
1567 message: format!(
1568 "template/core planned path collision: {} and {}",
1569 left.display(),
1570 right.display()
1571 ),
1572 })
1573}
1574
1575fn is_provider_controlled(root: &Path) -> bool {
1576 root.components().any(|component| {
1577 let Component::Normal(value) = component else {
1578 return false;
1579 };
1580 matches!(
1581 value.to_str(),
1582 Some("Mobile Documents" | "CloudStorage" | "File Provider Storage")
1583 )
1584 })
1585}
1586
1587pub(crate) fn ensure_safe_relative(path: &Path) -> Result<()> {
1588 if path.as_os_str().is_empty()
1589 || path.is_absolute()
1590 || path
1591 .components()
1592 .any(|component| !matches!(component, Component::Normal(_)))
1593 {
1594 return Err(FolderbaseError::UnsafePath(path.to_path_buf()));
1595 }
1596 Ok(())
1597}
1598
1599pub(crate) fn safe_destination(root: &Path, relative_path: &Path) -> Result<PathBuf> {
1600 ensure_safe_relative(relative_path)?;
1601 let mut current = root.to_path_buf();
1602 if let Some(parent) = relative_path.parent() {
1603 for component in parent.components() {
1604 let Component::Normal(component) = component else {
1605 return Err(FolderbaseError::UnsafePath(relative_path.to_path_buf()));
1606 };
1607 current.push(component);
1608 match fs::symlink_metadata(¤t) {
1609 Ok(metadata) if metadata.file_type().is_symlink() => {
1610 return Err(FolderbaseError::UnsafePath(current));
1611 }
1612 Ok(metadata) if !metadata.is_dir() => {
1613 return Err(FolderbaseError::WouldOverwrite(current));
1614 }
1615 Ok(_) => {}
1616 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
1617 Err(source) => return Err(FolderbaseError::io(current, source)),
1618 }
1619 }
1620 }
1621 Ok(root.join(relative_path))
1622}
1623
1624fn plan_agent_adapter_unless_template_owned(
1625 root: &Path,
1626 relative_path: &Path,
1627 purpose: &str,
1628 content: String,
1629 writes: &mut Vec<PlannedWrite>,
1630 preserved_paths: &mut Vec<PreservedPath>,
1631) -> Result<()> {
1632 if writes.iter().any(|write| write.path == relative_path) {
1633 return Ok(());
1634 }
1635 plan_file(
1636 root,
1637 relative_path,
1638 purpose,
1639 content,
1640 writes,
1641 preserved_paths,
1642 )
1643}
1644
1645fn plan_file(
1646 root: &Path,
1647 relative_path: &Path,
1648 purpose: &str,
1649 content: String,
1650 writes: &mut Vec<PlannedWrite>,
1651 preserved_paths: &mut Vec<PreservedPath>,
1652) -> Result<()> {
1653 let destination = safe_destination(root, relative_path)?;
1654 match fs::symlink_metadata(&destination) {
1655 Ok(metadata) if metadata.file_type().is_symlink() => {
1656 return Err(FolderbaseError::UnsafePath(destination));
1657 }
1658 Ok(metadata) if metadata.is_file() => {
1659 if !preserved_paths
1660 .iter()
1661 .any(|preserved| preserved.path == relative_path)
1662 {
1663 preserved_paths.push(PreservedPath {
1664 path: relative_path.to_path_buf(),
1665 });
1666 }
1667 }
1668 Ok(_) => return Err(FolderbaseError::WouldOverwrite(destination)),
1669 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
1670 writes.push(PlannedWrite {
1671 path: relative_path.to_path_buf(),
1672 purpose: purpose.to_owned(),
1673 content,
1674 });
1675 }
1676 Err(source) => return Err(FolderbaseError::io(destination, source)),
1677 }
1678 Ok(())
1679}
1680
1681fn verify_destinations_absent(
1682 root_dir: &Dir,
1683 plan: &InitializationPlan,
1684 budget: &mut InitializationInventoryBudget,
1685) -> Result<()> {
1686 for path in plan
1687 .directories
1688 .iter()
1689 .map(|directory| &directory.path)
1690 .chain(plan.writes.iter().map(|write| &write.path))
1691 {
1692 ensure_safe_relative(path)?;
1693 safe_destination(&plan.root, path)?;
1694 refuse_template_target_inside_nested_folderbase_capability(
1695 root_dir, &plan.root, path, budget,
1696 )?;
1697 match root_dir.symlink_metadata(path) {
1698 Ok(_) => return Err(FolderbaseError::WouldOverwrite(plan.root.join(path))),
1699 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
1700 Err(source) => return Err(FolderbaseError::io(plan.root.join(path), source)),
1701 }
1702 }
1703 Ok(())
1704}
1705
1706pub(crate) fn sha256_reader(reader: &mut impl Read) -> std::io::Result<String> {
1707 let mut hasher = Sha256::new();
1708 let mut buffer = [0_u8; 64 * 1024];
1709 loop {
1710 let read = reader.read(&mut buffer)?;
1711 if read == 0 {
1712 break;
1713 }
1714 hasher.update(&buffer[..read]);
1715 }
1716 Ok(format!("{:x}", hasher.finalize()))
1717}
1718
1719fn folderbase_kind_name(kind: FolderbaseKind) -> &'static str {
1720 match kind {
1721 FolderbaseKind::Person => "person",
1722 FolderbaseKind::Organization => "organization",
1723 FolderbaseKind::Engagement => "engagement",
1724 FolderbaseKind::Project => "project",
1725 FolderbaseKind::Customer => "customer",
1726 FolderbaseKind::Temporary => "temporary",
1727 FolderbaseKind::Custom => "custom",
1728 }
1729}
1730
1731fn agent_adapter() -> String {
1732 "<!-- folderbase:begin -->\n\
1733 # Folderbase\n\n\
1734 Confirm this root through `.folderbase/manifest.json`, then work with its ordinary \
1735 files using Folderbase Core context and boundary rules. Treat summaries and questions \
1736 as optional hints, never as mutation or sharing authority.\n\
1737 <!-- folderbase:end -->\n"
1738 .to_owned()
1739}
1740
1741#[cfg(test)]
1742mod tests {
1743 use super::*;
1744
1745 #[test]
1746 fn planning_is_read_only_and_initialize_creates_a_folderbase() {
1747 let temp = tempfile::tempdir().unwrap();
1748
1749 let plan = plan_initialization(temp.path(), InitializationOptions::default()).unwrap();
1750 assert!(!temp.path().join(FOLDERBASE_ENTRY).exists());
1751 assert!(!temp.path().join(MANIFEST).exists());
1752
1753 let result = initialize(&plan).unwrap();
1754 assert_eq!(result.folderbase_id, plan.folderbase_id);
1755 assert!(temp.path().join(MANIFEST).exists());
1756 assert!(!temp.path().join(CODEX_ADAPTER).exists());
1757 assert!(!temp.path().join(CLAUDE_ADAPTER).exists());
1758 }
1759
1760 #[test]
1761 fn existing_entry_and_adapters_are_preserved() {
1762 let temp = tempfile::tempdir().unwrap();
1763 fs::write(temp.path().join(FOLDERBASE_ENTRY), "# Existing\n").unwrap();
1764 fs::write(temp.path().join(CODEX_ADAPTER), "user owned\n").unwrap();
1765
1766 let plan = plan_initialization(temp.path(), InitializationOptions::default()).unwrap();
1767 assert!(
1768 plan.preserved_paths
1769 .iter()
1770 .any(|preserved| preserved.path == Path::new(FOLDERBASE_ENTRY))
1771 );
1772 assert!(
1773 plan.preserved_paths
1774 .iter()
1775 .any(|preserved| preserved.path == Path::new(CODEX_ADAPTER))
1776 );
1777
1778 initialize(&plan).unwrap();
1779 assert_eq!(
1780 fs::read_to_string(temp.path().join(FOLDERBASE_ENTRY)).unwrap(),
1781 "# Existing\n"
1782 );
1783 assert_eq!(
1784 fs::read_to_string(temp.path().join(CODEX_ADAPTER)).unwrap(),
1785 "user owned\n"
1786 );
1787 }
1788
1789 #[test]
1790 fn applying_a_stale_plan_never_overwrites() {
1791 let temp = tempfile::tempdir().unwrap();
1792 let plan = plan_initialization(temp.path(), InitializationOptions::default()).unwrap();
1793 fs::write(temp.path().join(FOLDERBASE_ENTRY), "# Arrived later\n").unwrap();
1794
1795 let error = initialize(&plan).unwrap_err();
1796 assert!(matches!(
1797 error,
1798 FolderbaseError::InitializationDestinationChanged(_)
1799 ));
1800 assert_eq!(
1801 fs::read_to_string(temp.path().join(FOLDERBASE_ENTRY)).unwrap(),
1802 "# Arrived later\n"
1803 );
1804 assert!(!temp.path().join(MANIFEST).exists());
1805 }
1806
1807 #[test]
1808 fn deleting_a_preserved_entry_invalidates_the_plan_before_writes() {
1809 let temp = tempfile::tempdir().unwrap();
1810 fs::write(temp.path().join(FOLDERBASE_ENTRY), "# Existing\n").unwrap();
1811 let plan = plan_initialization(temp.path(), InitializationOptions::default()).unwrap();
1812 fs::remove_file(temp.path().join(FOLDERBASE_ENTRY)).unwrap();
1813
1814 let error = initialize(&plan).unwrap_err();
1815 assert!(matches!(
1816 error,
1817 FolderbaseError::InitializationDestinationChanged(_)
1818 ));
1819 assert!(!temp.path().join(MANIFEST).exists());
1820 assert!(!temp.path().join(CODEX_ADAPTER).exists());
1821 }
1822
1823 #[cfg(unix)]
1824 #[test]
1825 fn dangling_symlink_from_a_stale_plan_is_never_removed() {
1826 use std::os::unix::fs::symlink;
1827
1828 let temp = tempfile::tempdir().unwrap();
1829 let plan = plan_initialization(temp.path(), InitializationOptions::default()).unwrap();
1830 let entry = temp.path().join(FOLDERBASE_ENTRY);
1831 symlink("missing-user-target.md", &entry).unwrap();
1832
1833 let error = initialize(&plan).unwrap_err();
1834 assert!(matches!(
1835 error,
1836 FolderbaseError::InitializationDestinationChanged(_)
1837 ));
1838 assert!(
1839 fs::symlink_metadata(&entry)
1840 .unwrap()
1841 .file_type()
1842 .is_symlink()
1843 );
1844 assert!(!temp.path().join(MANIFEST).exists());
1845 }
1846
1847 #[test]
1848 fn provider_controlled_folder_is_refused() {
1849 let temp = tempfile::tempdir().unwrap();
1850 let provider_root = temp.path().join("CloudStorage/project");
1851 fs::create_dir_all(&provider_root).unwrap();
1852
1853 let error =
1854 plan_initialization(&provider_root, InitializationOptions::default()).unwrap_err();
1855 assert!(matches!(error, FolderbaseError::ProviderControlled(_)));
1856 assert!(!provider_root.join(MANIFEST).exists());
1857 }
1858
1859 #[cfg(unix)]
1860 #[test]
1861 fn template_parent_probe_never_follows_a_symlink_outside_the_root() {
1862 use std::os::unix::fs::symlink;
1863
1864 let root = tempfile::tempdir().unwrap();
1865 let outside = tempfile::tempdir().unwrap();
1866 symlink(outside.path(), root.path().join("Nested")).unwrap();
1867
1868 let error = refuse_template_target_inside_nested_folderbase(
1869 root.path(),
1870 Path::new("Nested/file.md"),
1871 )
1872 .expect_err("a template parent symlink must fail closed");
1873
1874 assert!(matches!(error, FolderbaseError::UnsafePath(_)));
1875 assert!(fs::read_dir(outside.path()).unwrap().next().is_none());
1876 }
1877}