policy.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. //! Rule #1, enforced at runtime: game-derived data never lands in the repo.
  2. //!
  3. //! Everything VIctory produces from the user's files (converted assets,
  4. //! prepared images, shader caches, crash dumps) is as much "from the game"
  5. //! as the files themselves. Every tool that writes such output must call
  6. //! [`ensure_outside_repo`] on the destination first. The static half of the
  7. //! rule is `cargo xtask policy`, which checks what git tracks.
  8. use std::path::{Component, Path, PathBuf};
  9. /// Marker file at the root of the source tree.
  10. pub const ROOT_MARKER: &str = ".victory-root";
  11. /// The source tree this binary was compiled from.
  12. fn compiled_workspace_root() -> PathBuf {
  13. // crates/victory-core -> workspace root
  14. Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..")
  15. }
  16. #[derive(Debug, thiserror::Error)]
  17. pub enum PolicyError {
  18. #[error(
  19. "refusing to use {path} for game-derived data: it is inside the VIctory source tree \
  20. ({root}). Keep game files, caches and outputs outside the repository \
  21. (see docs/asset-policy.md)"
  22. )]
  23. InsideRepo { path: PathBuf, root: PathBuf },
  24. #[error("cannot resolve {path}: {source}")]
  25. Io {
  26. path: PathBuf,
  27. source: std::io::Error,
  28. },
  29. }
  30. /// Returns `Ok` only if `path` is outside every VIctory source tree.
  31. ///
  32. /// `path` does not have to exist yet. Two checks are made:
  33. /// 1. it is not below the source tree this binary was built from;
  34. /// 2. none of its ancestors contains the [`ROOT_MARKER`] file (catches
  35. /// other clones/copies of the repository).
  36. pub fn ensure_outside_repo(path: &Path) -> Result<(), PolicyError> {
  37. let resolved = resolve(path)?;
  38. if let Ok(root) = std::fs::canonicalize(compiled_workspace_root())
  39. && root.join(ROOT_MARKER).is_file()
  40. && resolved.starts_with(&root)
  41. {
  42. return Err(PolicyError::InsideRepo {
  43. path: path.to_path_buf(),
  44. root,
  45. });
  46. }
  47. for ancestor in resolved.ancestors() {
  48. if ancestor.join(ROOT_MARKER).is_file() {
  49. return Err(PolicyError::InsideRepo {
  50. path: path.to_path_buf(),
  51. root: ancestor.to_path_buf(),
  52. });
  53. }
  54. }
  55. Ok(())
  56. }
  57. /// Canonicalizes the longest existing prefix of `path` and re-appends the
  58. /// rest, so that paths which do not exist yet can still be compared.
  59. fn resolve(path: &Path) -> Result<PathBuf, PolicyError> {
  60. let absolute = if path.is_absolute() {
  61. path.to_path_buf()
  62. } else {
  63. std::env::current_dir()
  64. .map_err(|source| PolicyError::Io {
  65. path: path.to_path_buf(),
  66. source,
  67. })?
  68. .join(path)
  69. };
  70. let mut existing = absolute.as_path();
  71. let mut rest = Vec::new();
  72. loop {
  73. match std::fs::canonicalize(existing) {
  74. Ok(canon) => {
  75. let mut out = canon;
  76. for component in rest.iter().rev() {
  77. out.push(component);
  78. }
  79. return Ok(normalize(&out));
  80. }
  81. Err(source) => match (existing.parent(), existing.file_name()) {
  82. (Some(parent), Some(name)) => {
  83. rest.push(name.to_os_string());
  84. existing = parent;
  85. }
  86. _ => {
  87. return Err(PolicyError::Io {
  88. path: path.to_path_buf(),
  89. source,
  90. });
  91. }
  92. },
  93. }
  94. }
  95. }
  96. /// Removes `.` and resolves `..` lexically (only used on the non-existing tail).
  97. fn normalize(path: &Path) -> PathBuf {
  98. let mut out = PathBuf::new();
  99. for component in path.components() {
  100. match component {
  101. Component::CurDir => {}
  102. Component::ParentDir => {
  103. out.pop();
  104. }
  105. c => out.push(c),
  106. }
  107. }
  108. out
  109. }
  110. #[cfg(test)]
  111. mod tests {
  112. use super::*;
  113. #[test]
  114. fn rejects_paths_inside_this_repo() {
  115. let inside = compiled_workspace_root().join("cache").join("textures");
  116. assert!(matches!(
  117. ensure_outside_repo(&inside),
  118. Err(PolicyError::InsideRepo { .. })
  119. ));
  120. let sneaky = std::env::temp_dir().join("..").join("x"); // sanity: no panic
  121. let _ = ensure_outside_repo(&sneaky);
  122. }
  123. #[test]
  124. fn rejects_dotdot_escapes_back_into_repo() {
  125. let root = compiled_workspace_root();
  126. let path = root
  127. .join("crates")
  128. .join("..")
  129. .join("not-yet-created")
  130. .join("out");
  131. assert!(ensure_outside_repo(&path).is_err());
  132. }
  133. #[test]
  134. fn rejects_other_clones_via_marker() {
  135. let tmp = tempfile::tempdir().unwrap();
  136. std::fs::write(tmp.path().join(ROOT_MARKER), "").unwrap();
  137. assert!(ensure_outside_repo(&tmp.path().join("cache")).is_err());
  138. }
  139. #[test]
  140. fn accepts_unrelated_directories() {
  141. let tmp = tempfile::tempdir().unwrap();
  142. ensure_outside_repo(&tmp.path().join("does").join("not").join("exist")).unwrap();
  143. }
  144. }