policy.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //! Rule #1, statically: the repository only ever contains small text files
  2. //! that we wrote. See docs/asset-policy.md.
  3. //!
  4. //! This is an allowlist, not a blocklist: a file passes only if its name is
  5. //! on the list, it is not too big, it is text, and it does not smuggle data
  6. //! inside text (long hex/base64 runs).
  7. use std::path::Path;
  8. use std::process::Command;
  9. use anyhow::{Context, Result, bail};
  10. const MAX_FILE_SIZE: usize = 512 * 1024;
  11. const MAX_ENCODED_RUN: usize = 512;
  12. const ALLOWED_EXTENSIONS: &[&str] = &[
  13. "rs", "toml", "md", "txt", "lock", "yml", "yaml", "json", "hlsl", "hlsli", "ps1", "cmd", "sh",
  14. ];
  15. const ALLOWED_NAMES: &[&str] = &[
  16. ".gitignore",
  17. ".gitattributes",
  18. ".editorconfig",
  19. ".victory-root",
  20. "pre-commit",
  21. "LICENSE",
  22. "LICENSE-MIT",
  23. "LICENSE-APACHE",
  24. ];
  25. /// Paths explicitly exempted, with a reason. Keep this empty if at all possible.
  26. const EXCEPTIONS: &[(&str, &str)] = &[(
  27. "crates/victory-formats/src/bcpack-tables.bin",
  28. "the BCPack format's constant tables: nothing decodes without them and they cannot be derived (owner's decision, 2026-11-23; docs/asset-policy.md)",
  29. )];
  30. /// Signatures of formats that must never be committed.
  31. const FORBIDDEN_MAGIC: &[(&[u8], &str)] = &[
  32. (b"MZ", "PE executable"),
  33. (b"DXBC", "shader container"),
  34. (b"DDS ", "DDS texture"),
  35. (b"RIFF", "RIFF (audio/video)"),
  36. (b"BC\xC0\xDE", "LLVM bitcode"),
  37. (b"Microsoft C/C++ MSF", "PDB"),
  38. (b"!<arch>", "library archive"),
  39. (b"PK\x03\x04", "zip"),
  40. (b"7z\xBC\xAF", "7-zip"),
  41. (b"MSCF", "cabinet"),
  42. (b"\xD0\xCF\x11\xE0", "MSI/OLE"),
  43. ];
  44. pub fn run(root: &Path, staged: bool) -> Result<()> {
  45. let files = list_files(root, staged)?;
  46. let mut violations = Vec::new();
  47. for path in &files {
  48. if EXCEPTIONS.iter().any(|(p, _)| p == path) {
  49. continue;
  50. }
  51. let content = if staged {
  52. let out = Command::new("git")
  53. .args(["show", &format!(":{path}")])
  54. .current_dir(root)
  55. .output()?;
  56. if !out.status.success() {
  57. continue; // deleted in the index
  58. }
  59. out.stdout
  60. } else {
  61. match std::fs::read(root.join(path)) {
  62. Ok(c) => c,
  63. Err(_) => continue,
  64. }
  65. };
  66. for problem in check(path, &content) {
  67. violations.push(format!("{path}: {problem}"));
  68. }
  69. }
  70. if violations.is_empty() {
  71. println!("asset policy: {} files ok", files.len());
  72. return Ok(());
  73. }
  74. for v in &violations {
  75. eprintln!("POLICY: {v}");
  76. }
  77. bail!(
  78. "{} asset-policy violation(s). Nothing from the game may be committed; \
  79. see docs/asset-policy.md",
  80. violations.len()
  81. )
  82. }
  83. fn list_files(root: &Path, staged: bool) -> Result<Vec<String>> {
  84. let git = |args: &[&str]| -> Result<Option<Vec<String>>> {
  85. let out = Command::new("git")
  86. .args(args)
  87. .current_dir(root)
  88. .output()
  89. .context("running git")?;
  90. if !out.status.success() {
  91. return Ok(None);
  92. }
  93. Ok(Some(
  94. out.stdout
  95. .split(|&b| b == 0)
  96. .filter(|s| !s.is_empty())
  97. .map(|s| String::from_utf8_lossy(s).replace('\\', "/"))
  98. .collect(),
  99. ))
  100. };
  101. if staged {
  102. return git(&[
  103. "diff",
  104. "--cached",
  105. "--name-only",
  106. "--diff-filter=ACMR",
  107. "-z",
  108. ])?
  109. .context("--staged needs a git repository");
  110. }
  111. if let Some(mut tracked) = git(&[
  112. "ls-files",
  113. "-z",
  114. "--cached",
  115. "--others",
  116. "--exclude-standard",
  117. ])? {
  118. tracked.sort();
  119. tracked.dedup();
  120. return Ok(tracked);
  121. }
  122. // Not a git repository: walk everything except build output.
  123. Ok(walkdir::WalkDir::new(root)
  124. .into_iter()
  125. .filter_entry(|e| !matches!(e.file_name().to_str(), Some("target" | ".git")))
  126. .filter_map(Result::ok)
  127. .filter(|e| e.file_type().is_file())
  128. .filter_map(|e| {
  129. e.path()
  130. .strip_prefix(root)
  131. .ok()
  132. .map(|p| p.to_string_lossy().replace('\\', "/"))
  133. })
  134. .collect())
  135. }
  136. /// All problems with one file. Pure, for testing.
  137. pub fn check(path: &str, content: &[u8]) -> Vec<String> {
  138. let mut problems = Vec::new();
  139. let name = path.rsplit('/').next().unwrap_or(path);
  140. let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
  141. let allowed = ALLOWED_NAMES.contains(&name)
  142. || ext
  143. .as_deref()
  144. .is_some_and(|e| ALLOWED_EXTENSIONS.contains(&e));
  145. if !allowed {
  146. problems.push("file type not on the allowlist".to_owned());
  147. }
  148. if content.len() > MAX_FILE_SIZE {
  149. problems.push(format!(
  150. "{} bytes exceeds the {MAX_FILE_SIZE}-byte limit",
  151. content.len()
  152. ));
  153. }
  154. for (magic, what) in FORBIDDEN_MAGIC {
  155. if content.starts_with(magic) {
  156. problems.push(format!("looks like a {what}"));
  157. }
  158. }
  159. if content.contains(&0) {
  160. problems.push("binary content (NUL bytes)".to_owned());
  161. } else if let Some(run) = longest_encoded_run(content)
  162. && run > MAX_ENCODED_RUN
  163. {
  164. problems.push(format!("{run}-character hex/base64 run (embedded data?)"));
  165. } else {
  166. let digits = longest_hex_literal_run(content);
  167. if digits > MAX_ENCODED_RUN {
  168. problems.push(format!(
  169. "{digits} hex digits in one run of \\x/0x literals (embedded data?)"
  170. ));
  171. }
  172. }
  173. problems
  174. }
  175. /// Longest run of characters that could be hex or base64 payload.
  176. fn longest_encoded_run(content: &[u8]) -> Option<usize> {
  177. let is_payload = |b: &u8| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=');
  178. content.split(|b| !is_payload(b)).map(<[u8]>::len).max()
  179. }
  180. /// Most hex digits in `\xNN` escapes or `0x` literals with only commas,
  181. /// whitespace or backslashes between them: a byte string or `xxd -i` array,
  182. /// which `longest_encoded_run` sees as many 3- or 4-character runs.
  183. /// shortcut: decimal arrays (`[77, 90, ...]`) still pass, add a literal count if one shows up.
  184. fn longest_hex_literal_run(content: &[u8]) -> usize {
  185. let (mut i, mut run, mut longest) = (0, 0, 0);
  186. while i < content.len() {
  187. match &content[i..] {
  188. [b'\\' | b'0', b'x' | b'X', rest @ ..] => {
  189. let len = rest
  190. .iter()
  191. .take_while(|b| b.is_ascii_hexdigit() || **b == b'_')
  192. .count();
  193. run += rest[..len].iter().filter(|b| b.is_ascii_hexdigit()).count();
  194. longest = longest.max(run);
  195. // Skip a type suffix such as `u8` or `u32`.
  196. let suffix = rest[len..]
  197. .iter()
  198. .take_while(|b| b.is_ascii_alphanumeric())
  199. .count();
  200. i += 2 + len + suffix;
  201. }
  202. [b, ..] if matches!(b, b',' | b'\\') || b.is_ascii_whitespace() => i += 1,
  203. _ => {
  204. run = 0;
  205. i += 1;
  206. }
  207. }
  208. }
  209. longest
  210. }
  211. #[cfg(test)]
  212. mod tests {
  213. use super::check;
  214. /// Enforces the policy wherever tests run, even in clones without the hook.
  215. #[test]
  216. fn repository_passes_policy() {
  217. super::run(&crate::workspace_root(), false).unwrap();
  218. }
  219. #[test]
  220. fn accepts_source() {
  221. assert!(check("crates/x/src/lib.rs", b"fn main() {}\n").is_empty());
  222. assert!(check(".gitignore", b"/target/\n").is_empty());
  223. assert!(check(".githooks/pre-commit", b"#!/bin/sh\n").is_empty());
  224. }
  225. #[test]
  226. fn rejects_game_like_files() {
  227. assert!(!check("assets/tex.dds", b"DDS \x7c\0\0\0").is_empty());
  228. assert!(
  229. !check("notes.txt", b"MZ\x90\0").is_empty(),
  230. "magic wins over extension"
  231. );
  232. assert!(
  233. !check("data.bin", b"hello").is_empty(),
  234. "extension not allowed"
  235. );
  236. assert!(
  237. !check("a.rs", &vec![b'a'; 600 * 1024]).is_empty(),
  238. "too big"
  239. );
  240. }
  241. #[test]
  242. fn rejects_data_smuggled_into_text() {
  243. let blob = format!("const DATA: &str = \"{}\";", "A1".repeat(400));
  244. assert!(!check("src/blob.rs", blob.as_bytes()).is_empty());
  245. }
  246. /// Synthetic bytes, never game data.
  247. fn synthetic(n: u32) -> impl Iterator<Item = u32> {
  248. (0..n).map(|i| (i * 37 + 11) % 256)
  249. }
  250. #[test]
  251. fn rejects_data_smuggled_as_an_escaped_byte_string() {
  252. // 4096 bytes as one unbroken `\xNN` hex run, the shape a byte-string
  253. // literal of copied data takes.
  254. let esc: String = synthetic(4096).map(|b| format!("\\x{b:02x}")).collect();
  255. let src = format!("pub const DATA: &[u8] = b\"{esc}\";\n");
  256. assert!(
  257. !check("src/data.rs", src.as_bytes()).is_empty(),
  258. "{} bytes of \\x-escaped hex passed",
  259. src.len()
  260. );
  261. }
  262. #[test]
  263. fn rejects_data_smuggled_as_a_hex_byte_array() {
  264. // `xxd -i` style: 4096 bytes as hex literals.
  265. let lits: Vec<String> = synthetic(4096).map(|b| format!("0x{b:02x}")).collect();
  266. let src = format!("pub const DATA: [u8; 4096] = [{}];\n", lits.join(", "));
  267. assert!(
  268. !check("src/data.rs", src.as_bytes()).is_empty(),
  269. "{} bytes of hex array passed",
  270. src.len()
  271. );
  272. // A short constant table, like the 16-entry ones in the tree, stays legal.
  273. let table: Vec<String> = synthetic(16).map(|w| format!("0x{w:08x}_u32")).collect();
  274. let src = format!(
  275. "const T: [u32; 16] = [\n {},\n];\n",
  276. table.join(",\n ")
  277. );
  278. assert!(check("src/table.rs", src.as_bytes()).is_empty());
  279. }
  280. }