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