repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

fix: converge crypto and hooks during link

7108b3680a6ef17646cb5b2cba0d013421593c81

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

AGENTS.md

Modified
67 67 ```sh
68 68 mise run check
69 +mise run secrets-scan
71 72 Heavy integration:
84 85 mise run clean
87 -`link` only validates manifests and creates symlinks; it does not configure crypto, restore secrets, install hooks, or fix unrelated permissions.
88 -For initial checkout decryption, explicitly run `mise run setup-crypto`.
89 -It refuses staged edits, local edits, and deletions before writing any tracked secret.
90 -`bootstrap` no longer restores secrets automatically.
88 +`link` validates manifests, converges crypto state, restores unchanged ciphertext, installs or repairs Git hooks, and creates symlinks; it never executes Gitleaks or fixes unrelated permissions.
89 +Crypto convergence is idempotent: a ready plaintext worktree does not rewrite secrets, keys, attributes, or Git config, and does not run routine AES self-tests.
90 +Commits and pushes require `gitleaks` on Git's `PATH`; missing Gitleaks blocks the Git operation, not linking.
91 +Git hooks validate only and never bootstrap crypto.
92 +`mise run setup-crypto` exposes the same crypto convergence independently.
93 +Restoration refuses staged changes, deletions, symlinks, changed ciphertext, or mixed ciphertext plus changed plaintext before writing any tracked secret.
92 95 Crypto/hooks:
94 97 ```sh
95 98 java bootstripper.java check
96 99 java bootstripper.java pre-commit
100 +java bootstripper.java pre-push
97 101 java bootstripper.java install-hooks
98 102 java bootstripper.java init-crypto
99 103 java bootstripper.java setup-crypto

bootstripper.java

Modified
4 4 import static java.text.MessageFormat.format;
6 6 import java.io.ByteArrayOutputStream;
7 7 import java.io.IOException;
8 8 import java.net.InetAddress;
9 9 import java.nio.charset.StandardCharsets;
10 +import java.nio.file.AtomicMoveNotSupportedException;
10 11 import java.nio.file.Files;
11 12 import java.nio.file.LinkOption;
12 13 import java.nio.file.Path;
14 +import java.nio.file.StandardCopyOption;
13 15 import java.nio.file.attribute.PosixFilePermissions;
14 16 import java.security.SecureRandom;
15 17 import java.util.ArrayList;
17 19 import java.util.HashSet;
18 20 import java.util.List;
19 21 import java.util.LinkedHashMap;
20 -import java.util.regex.Pattern;
22 +import java.util.LinkedHashSet;
21 23 import java.util.stream.Collectors;
22 24 import javax.crypto.SecretKeyFactory;
23 25 import javax.crypto.spec.PBEKeySpec;
27 29 private final static boolean win32 = operating_system.toLowerCase().contains("win");
28 30 private final static String filter_name = "dotfiles-aes";
29 31 private final static String key_file = "dotfiles-aes.key";
32 + private final static String aes_cache_file = "dotfiles-aes.java";
30 33 private final static String salt_file = ".dotfiles-aes-salt";
31 34 private final static String secrets_file = ".secrets";
32 35 private final static String attributes_begin = "# BEGIN bootstripper secrets";
33 36 private final static String attributes_end = "# END bootstripper secrets";
37 + private final static String hook_marker = "# Managed by dorkfiles bootstripper.java";
34 38 private final static byte[] aes_magic = new byte[] { 'D', 'F', 'A', 'E', 'S', '1' };
35 39 private final static int salt_bytes = 32;
36 40 private final static int derived_key_bits = 512;
70 74 return;
72 76 if ("pre-commit".equals(command)) {
73 - setup_crypto(root);
74 77 pre_commit(root);
75 78 return;
80 + if ("pre-push".equals(command)) {
81 + pre_push(root);
82 + return;
83 + }
77 84 if ("install-hooks".equals(command)) {
78 85 require_git_repo(root);
79 86 install_hooks(root);
90 97 if ("link".equals(command)) {
98 + var symlinks_file = symlinks_file(root);
91 99 check_symlink_sources(root);
92 - create_symlinks(root, symlinks_file(root));
100 + converge_crypto(root);
101 + install_hooks(root);
102 + create_symlinks(root, symlinks_file);
93 103 print_attention(false);
94 104 return;
97 - setup_crypto(root);
98 107 if ("setup-crypto".equals(command)) {
99 - restore_tracked_secrets(root, read_secrets(root));
108 + converge_crypto(root);
100 109 return;
111 + var symlinks_file = symlinks_file(root);
112 + check_symlink_sources(root);
113 + converge_crypto(root);
102 114 install_hooks(root);
103 115 check(root);
104 - var symlinks_file = symlinks_file(root);
105 116 create_symlinks(root, symlinks_file);
106 117 print_attention(false);
109 120 static boolean is_command(String argument) {
110 - return "bootstrap".equals(argument) || "link".equals(argument) || "clean".equals(argument) || "check".equals(argument) || "pre-commit".equals(argument) || "install-hooks".equals(argument) || "init-crypto".equals(argument) || "setup-crypto".equals(argument);
121 + return "bootstrap".equals(argument) || "link".equals(argument) || "clean".equals(argument) || "check".equals(argument) || "pre-commit".equals(argument) || "pre-push".equals(argument) || "install-hooks".equals(argument) || "init-crypto".equals(argument) || "setup-crypto".equals(argument);
113 124 static void init_crypto(Path root) throws Throwable {
123 134 log("Created crypto salt: {0}", emphasize_local(salt_file));
126 - static void setup_crypto(Path root) throws Throwable {
137 + static List<String> setup_crypto(Path root) throws Throwable {
127 138 require_git_repo(root);
128 139 var secrets = read_secrets(root);
129 140 if (secrets.isEmpty())
130 - return;
141 + return secrets;
142 + validate_secret_paths(root, secrets);
143 + install_aes_tool(root);
144 + ensure_key(root, secrets);
131 145 install_filter(root);
132 146 write_attributes(root, secrets);
133 147 remove_local_attributes(root);
134 - ensure_key(root);
135 - self_test_aes(root);
136 148 apply_secret_permissions(root, secrets);
149 + return secrets;
152 + static void converge_crypto(Path root) throws Throwable {
153 + var secrets = setup_crypto(root);
154 + if (!secrets.isEmpty())
155 + restore_tracked_secrets(root, secrets);
139 158 static void require_git_repo(Path root) throws Throwable {
156 175 return key_path(root).toString();
159 - static String aes_tool_argument(Path root) {
160 - return root.resolve("tools/aes.java").toAbsolutePath().toString();
178 + static String aes_tool_argument(Path root) throws Throwable {
179 + return git_common_path(root, aes_cache_file).toString();
182 + static String clean_filter_command(Path root) throws Throwable {
183 + return "java " + quote_shell(aes_tool_argument(root)) + " encrypt --key-file " + quote_shell(key_argument(root));
186 + static String smudge_filter_command(Path root) throws Throwable {
187 + return "java " + quote_shell(aes_tool_argument(root)) + " decrypt --key-file " + quote_shell(key_argument(root));
190 + static String merge_filter_command(Path root) throws Throwable {
191 + var merge_inputs = win32 ? "\\\"%O\\\" \\\"%A\\\" \\\"%B\\\"" : "\"%O\" \"%A\" \"%B\"";
192 + return "java " + quote_shell(aes_tool_argument(root)) + " merge --key-file " + quote_shell(key_argument(root)) + " " + merge_inputs;
163 195 static List<String> read_secrets(Path root) throws IOException {
169 201 var line = raw.strip();
170 202 if (line.isEmpty() || line.startsWith("#"))
171 203 continue;
172 - if (line.contains(" ") || line.contains("\t") || line.startsWith("/") || line.contains("\\"))
204 + if (line.contains(" ") || line.contains("\t") || line.startsWith("/") || line.contains("\\")
205 + || line.startsWith(":") || line.contains("*") || line.contains("?") || line.contains("["))
173 206 throw new IllegalArgumentException("invalid secret path: " + line);
174 207 secrets.add(line);
176 209 return secrets;
212 + static void install_aes_tool(Path root) throws Throwable {
213 + var source = root.resolve("tools/aes.java");
214 + if (!Files.isRegularFile(source, LinkOption.NOFOLLOW_LINKS))
215 + throw fail("Expected a regular AES tool source at: {0}", source);
216 + var target = git_common_path(root, aes_cache_file);
217 + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
218 + if (!Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS))
219 + throw fail("Refusing to replace non-file cached AES tool: {0}", target);
220 + if (Files.mismatch(source, target) == -1L)
221 + return;
223 + Files.createDirectories(target.getParent());
224 + var temporary = Files.createTempFile(target.getParent(), "." + aes_cache_file + ".", ".tmp");
225 + try {
226 + Files.copy(source, temporary, StandardCopyOption.REPLACE_EXISTING);
227 + try {
228 + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
229 + } catch (AtomicMoveNotSupportedException ignored) {
230 + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
232 + } finally {
233 + Files.deleteIfExists(temporary);
237 + static void validate_secret_paths(Path root, List<String> secrets) throws Throwable {
238 + for (var secret : secrets) {
239 + var original = Path.of(secret);
240 + for (var component : original)
241 + if (component.toString().equals(".."))
242 + throw fail("Secret path must not contain parent components: {0}", secret);
243 + var relative = original.normalize();
244 + if (relative.isAbsolute() || relative.startsWith(".."))
245 + throw fail("Secret path must stay inside the repository: {0}", secret);
246 + var current = root;
247 + for (var component : relative) {
248 + current = current.resolve(component);
249 + if (Files.isSymbolicLink(current))
250 + throw fail("Secret path must not contain symlinks: {0}", secret);
252 + if (Files.exists(current, LinkOption.NOFOLLOW_LINKS) && !Files.isRegularFile(current, LinkOption.NOFOLLOW_LINKS))
253 + throw fail("Secret path must name a regular file: {0}", secret);
179 257 static void install_filter(Path root) throws Throwable {
180 - var key = quote_shell(key_argument(root));
181 - var aes = quote_shell(aes_tool_argument(root));
182 - run(root, List.of("git", "config", "--local", "filter." + filter_name + ".clean",
183 - "java " + aes + " encrypt --key-file " + key), null, false);
184 - run(root, List.of("git", "config", "--local", "filter." + filter_name + ".smudge",
185 - "java " + aes + " decrypt --key-file " + key), null, false);
186 - run(root, List.of("git", "config", "--local", "filter." + filter_name + ".required", "true"), null, false);
187 - var merge_inputs = win32 ? "\\\"%O\\\" \\\"%A\\\" \\\"%B\\\"" : "\"%O\" \"%A\" \"%B\"";
188 - run(root, List.of("git", "config", "--local", "merge." + filter_name + ".driver",
189 - "java " + aes + " merge --key-file " + key + " " + merge_inputs), null, false);
258 + set_local_config(root, "filter." + filter_name + ".clean", clean_filter_command(root));
259 + set_local_config(root, "filter." + filter_name + ".smudge", smudge_filter_command(root));
260 + set_local_config(root, "filter." + filter_name + ".required", "true");
261 + set_local_config(root, "merge." + filter_name + ".driver", merge_filter_command(root));
264 + static void set_local_config(Path root, String name, String value) throws Throwable {
265 + var current = run(root, List.of("git", "config", "--local", "--get", name), null, false, false);
266 + if (current.exit != 0 || !current.text().strip().equals(value))
267 + run(root, List.of("git", "config", "--local", name, value), null, false);
192 270 static String quote_shell(String argument) {
203 281 for (var secret : secrets)
204 282 lines.add(secret + " -text filter=" + filter_name + " -diff merge=" + filter_name);
205 283 lines.add(attributes_end);
206 - Files.writeString(attributes, content + String.join("\n", lines) + "\n", StandardCharsets.UTF_8);
284 + var desired = content + String.join("\n", lines) + "\n";
285 + if (!Files.exists(attributes) || !Files.readString(attributes).equals(desired))
286 + Files.writeString(attributes, desired, StandardCharsets.UTF_8);
209 289 static void remove_local_attributes(Path root) throws Throwable {
234 314 return String.join("\n", lines);
237 - static void ensure_key(Path root) throws Throwable {
317 + static void ensure_key(Path root, List<String> secrets) throws Throwable {
238 318 var key = key_path(root);
239 - if (Files.exists(key))
319 + if (Files.exists(key, LinkOption.NOFOLLOW_LINKS)) {
320 + validate_key(key);
321 + ensure_permissions(key, "rw-------");
240 322 return;
241 324 Files.createDirectories(key.getParent());
242 - var salt = read_salt(root);
243 - var passphrase = passphrase();
325 + var temporary = Files.createTempFile(key.getParent(), key_file + ".", ".tmp");
326 + char[] passphrase = null;
328 + passphrase = passphrase();
245 329 var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
246 - var spec = new PBEKeySpec(passphrase, salt, pbkdf2_iterations, derived_key_bits);
330 + var spec = new PBEKeySpec(passphrase, read_salt(root), pbkdf2_iterations, derived_key_bits);
247 331 var encoded = factory.generateSecret(spec).getEncoded();
248 - Files.writeString(key, Base64.getEncoder().encodeToString(encoded) + "\n", StandardCharsets.UTF_8);
249 - chmod(key, "rw-------");
332 + Files.writeString(temporary, Base64.getEncoder().encodeToString(encoded) + "\n", StandardCharsets.UTF_8);
333 + ensure_permissions(temporary, "rw-------");
334 + if (!authenticate_key(root, secrets, temporary))
335 + self_test_aes(root, temporary);
336 + try {
337 + Files.move(temporary, key, StandardCopyOption.ATOMIC_MOVE);
338 + } catch (AtomicMoveNotSupportedException ignored) {
339 + Files.move(temporary, key);
250 341 log("Cached dotfiles AES key in {0}", emphasize_local(key.toString()));
251 342 } finally {
252 - Arrays.fill(passphrase, '\0');
343 + if (passphrase != null)
344 + Arrays.fill(passphrase, '\0');
345 + Files.deleteIfExists(temporary);
349 + static void validate_key(Path key) throws IOException {
350 + if (!Files.isRegularFile(key, LinkOption.NOFOLLOW_LINKS) || !Files.isReadable(key))
351 + throw new IllegalStateException("Dotfiles AES key must be a readable regular file: " + key);
352 + try {
353 + if (Base64.getDecoder().decode(Files.readString(key).trim()).length != derived_key_bits / 8)
354 + throw new IllegalStateException("Dotfiles AES key has the wrong length: " + key);
355 + } catch (IllegalArgumentException problem) {
356 + throw new IllegalStateException("Dotfiles AES key is not valid Base64: " + key);
360 + static boolean authenticate_key(Path root, List<String> secrets, Path key) throws Throwable {
361 + String encrypted_secret = null;
362 + for (var secret : secrets) {
363 + var committed = run(root, List.of("git", "cat-file", "blob", "HEAD:" + secret), null, false, false);
364 + if (committed.exit != 0 || !starts_with(committed.stdout, aes_magic))
365 + continue;
366 + encrypted_secret = secret;
367 + var decrypted = run(root, List.of("java", aes_tool_argument(root), "decrypt", "--key-file", key.toString()), committed.stdout, false, false);
368 + if (decrypted.exit == 0)
369 + return true;
371 + if (encrypted_secret != null)
372 + throw new IllegalStateException("Passphrase does not decrypt committed secrets, including: " + encrypted_secret);
373 + return false;
256 376 static byte[] read_salt(Path root) throws IOException {
257 377 var path = root.resolve(salt_file);
258 378 if (!Files.exists(path))
275 395 return first;
278 - static void self_test_aes(Path root) throws Throwable {
398 + static void self_test_aes(Path root, Path key) throws Throwable {
279 399 var plain = "bootstripper self-test".getBytes(StandardCharsets.UTF_8);
280 - var key = key_argument(root);
281 400 var aes = aes_tool_argument(root);
282 - var encrypted = run(root, List.of("java", aes, "encrypt", "--key-file", key), plain, false).stdout;
283 - if (!starts_with(encrypted, aes_magic))
284 - throw fail("AES self-test did not produce expected magic header.");
285 - var decrypted = run(root, List.of("java", aes, "decrypt", "--key-file", key), encrypted, false).stdout;
286 - if (!Arrays.equals(plain, decrypted))
287 - throw fail("AES self-test failed to round-trip.");
401 + var encrypted = run(root, List.of("java", aes, "encrypt", "--key-file", key.toString()), plain, false, false);
402 + if (encrypted.exit != 0 || !starts_with(encrypted.stdout, aes_magic))
403 + throw new IllegalStateException("AES self-test encryption failed: " + encrypted.error().strip());
404 + var decrypted = run(root, List.of("java", aes, "decrypt", "--key-file", key.toString()), encrypted.stdout, false, false);
405 + if (decrypted.exit != 0 || !Arrays.equals(plain, decrypted.stdout))
406 + throw new IllegalStateException("AES self-test decryption failed: " + decrypted.error().strip());
290 409 static void restore_tracked_secrets(Path root, List<String> secrets) throws Throwable {
291 - var pending = new LinkedHashMap<Path, byte[]>();
292 - for (var secret : secrets) {
293 - var committed = run(root, List.of("git", "cat-file", "blob", "HEAD:" + secret), null, false, false);
294 - if (committed.exit != 0)
295 - continue;
410 + var tree_command = new ArrayList<>(List.of("git", "--literal-pathspecs", "ls-tree", "--name-only", "-z", "HEAD", "--"));
411 + tree_command.addAll(secrets);
412 + var tracked_output = run(root, tree_command, null, false, false);
413 + if (tracked_output.exit != 0)
414 + return;
415 + var tracked = new LinkedHashSet<String>();
416 + for (var path : new String(tracked_output.stdout, StandardCharsets.UTF_8).split("\u0000"))
417 + if (!path.isEmpty()) tracked.add(path);
418 + if (tracked.isEmpty())
419 + return;
421 + var staged_command = new ArrayList<>(List.of("git", "--literal-pathspecs", "diff", "--cached", "--quiet", "HEAD", "--"));
422 + staged_command.addAll(tracked);
423 + if (run(root, staged_command, null, false, false).exit != 0) {
424 + for (var secret : tracked)
425 + if (run(root, List.of("git", "--literal-pathspecs", "diff", "--cached", "--quiet", "HEAD", "--", secret), null, false, false).exit != 0)
426 + throw fail("Refusing to restore locally changed secret: {0}", secret);
429 + var current = new LinkedHashMap<String, byte[]>();
430 + var needs_restoration = false;
431 + for (var secret : tracked) {
296 432 var path = root.resolve(secret);
297 - var staged = run(root, List.of("git", "diff", "--cached", "--quiet", "HEAD", "--", secret), null, false, false);
298 - if (staged.exit != 0 || !Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
433 + if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
299 434 throw fail("Refusing to restore locally changed secret: {0}", secret);
435 + var bytes = Files.readAllBytes(path);
436 + current.put(secret, bytes);
437 + needs_restoration |= starts_with(bytes, aes_magic);
439 + if (!needs_restoration)
440 + return;
442 + var pending = new LinkedHashMap<Path, byte[]>();
443 + for (var secret : tracked) {
444 + var committed = run(root, List.of("git", "cat-file", "blob", "HEAD:" + secret), null, false);
300 445 var plain = run(root, List.of("java", aes_tool_argument(root), "decrypt", "--key-file", key_argument(root)), committed.stdout, false).stdout;
301 - var current = Files.readAllBytes(path);
302 - if (Arrays.equals(current, committed.stdout))
303 - pending.put(path, plain);
304 - else if (!Arrays.equals(current, plain))
446 + var bytes = current.get(secret);
447 + if (Arrays.equals(bytes, committed.stdout))
448 + pending.put(root.resolve(secret), plain);
449 + else if (!Arrays.equals(bytes, plain))
305 450 throw fail("Refusing to restore locally changed secret: {0}", secret);
307 452 for (var entry : pending.entrySet())
312 457 for (var secret : secrets) {
313 458 var path = root.resolve(secret);
314 459 if (Files.exists(path) && secret.startsWith("ssh/") && secret.endsWith(".key"))
315 - chmod(path, "rw-------");
460 + ensure_permissions(path, "rw-------");
319 464 static void install_hooks(Path root) throws Throwable {
320 - var hooks = git_common_path(root, "hooks");
465 + var hooks = git_hooks_path(root);
466 + var pre_commit = hooks.resolve("pre-commit");
467 + var pre_push = hooks.resolve("pre-push");
468 + var legacy_pre_commit = "#!/bin/sh\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java pre-commit\n";
469 + var pre_commit_content = hook_content("pre-commit");
470 + var pre_push_content = hook_content("pre-push");
471 + check_hook_destination(pre_commit, pre_commit_content, legacy_pre_commit);
472 + check_hook_destination(pre_push, pre_push_content, null);
473 + install_hook(hooks, pre_commit, pre_commit_content);
474 + install_hook(hooks, pre_push, pre_push_content);
477 + static Path git_hooks_path(Path root) throws Throwable {
478 + var configured = run(root, List.of("git", "config", "--show-scope", "--get", "core.hooksPath"), null, false, false);
479 + if (configured.exit == 0 && !configured.text().matches("(?s)^(local|worktree)\\s+.*"))
480 + throw fail("Refusing to modify inherited core.hooksPath. Configure a repository-local hooks path or unset it.");
481 + var result = run(root, List.of("git", "rev-parse", "--path-format=absolute", "--git-path", "hooks"), null, false).text().strip();
482 + var hooks = Path.of(result).toAbsolutePath().normalize();
483 + if (hooks.equals(Path.of("/dev/null")) || Files.exists(hooks, LinkOption.NOFOLLOW_LINKS) && !Files.isDirectory(hooks, LinkOption.NOFOLLOW_LINKS))
484 + throw fail("Invalid Git hooks directory: {0}", hooks);
485 + return hooks;
488 + static String hook_content(String command) {
489 + return "#!/bin/sh\n" + hook_marker + "\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java " + command + "\n";
492 + static void check_hook_destination(Path hook, String expected, String legacy) throws Throwable {
493 + if (!Files.exists(hook, LinkOption.NOFOLLOW_LINKS))
494 + return;
495 + if (Files.isSymbolicLink(hook) || !Files.isRegularFile(hook, LinkOption.NOFOLLOW_LINKS))
496 + throw fail("Refusing to replace non-file Git hook: {0}", hook);
497 + var content = Files.readString(hook);
498 + if (content.equals(expected) || content.equals(legacy) || content.contains("\n" + hook_marker + "\n"))
499 + return;
500 + throw fail("Refusing to replace unmanaged Git hook: {0}", hook);
503 + static void install_hook(Path hooks, Path hook, String content) throws Throwable {
504 + var content_matches = Files.isRegularFile(hook, LinkOption.NOFOLLOW_LINKS) && Files.readString(hook).equals(content);
505 + var permissions_match = hook_permissions_match(hook);
506 + if (content_matches && permissions_match)
507 + return;
321 508 Files.createDirectories(hooks);
322 - var hook = hooks.resolve("pre-commit");
323 - Files.writeString(hook, "#!/bin/sh\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java pre-commit\n", StandardCharsets.UTF_8);
324 - chmod(hook, "rwxr-xr-x");
325 - log("Installed Git hook: {0}", emphasize_local(".git/hooks/pre-commit"));
509 + if (!content_matches) {
510 + var temporary = Files.createTempFile(hooks, "." + hook.getFileName() + ".", ".tmp");
511 + try {
512 + Files.writeString(temporary, content, StandardCharsets.UTF_8);
513 + chmod(temporary, "rwxr-xr-x");
514 + try {
515 + Files.move(temporary, hook, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
516 + } catch (AtomicMoveNotSupportedException ignored) {
517 + Files.move(temporary, hook, StandardCopyOption.REPLACE_EXISTING);
519 + } finally {
520 + Files.deleteIfExists(temporary);
522 + } else {
523 + chmod(hook, "rwxr-xr-x");
525 + log("Installed Git hook: {0}", emphasize_local(hook.toString()));
528 + static boolean hook_permissions_match(Path hook) throws IOException {
529 + if (win32)
530 + return true;
531 + try {
532 + return Files.exists(hook) && Files.getPosixFilePermissions(hook).equals(PosixFilePermissions.fromString("rwxr-xr-x"));
533 + } catch (UnsupportedOperationException ignored) {
534 + return Files.isExecutable(hook);
328 538 static void pre_commit(Path root) throws Throwable {
329 - check(root);
539 + run_gitleaks(root, List.of("--pre-commit", "--staged"));
330 540 check_staged_matches_worktree(root, secrets_file);
331 541 check_staged_matches_worktree(root, ".gitattributes");
542 + check(root);
545 + static void pre_push(Path root) throws Throwable {
546 + for (var line : new String(System.in.readAllBytes(), StandardCharsets.UTF_8).lines().toList()) {
547 + if (line.isBlank())
548 + continue;
549 + var fields = line.strip().split("\\s+");
550 + if (fields.length != 4)
551 + throw fail("Invalid pre-push input: expected four fields.");
552 + var local_oid = fields[1];
553 + var remote_oid = fields[3];
554 + if (is_zero_oid(local_oid))
555 + continue;
556 + if (!is_oid(local_oid) || !is_oid(remote_oid))
557 + throw fail("Invalid object ID in pre-push input.");
558 + var local_commit = resolve_commit(root, local_oid, "local");
559 + var remote_commit = run(root, List.of("git", "rev-parse", "--verify", remote_oid + "^{commit}"), null, false, false);
560 + var revisions = is_zero_oid(remote_oid) || remote_commit.exit != 0
561 + ? local_commit
562 + : remote_commit.text().strip() + ".." + local_commit;
563 + var log_options = "--full-history --diff-merges=first-parent --no-ext-diff --no-textconv " + revisions;
564 + run_gitleaks(root, List.of("--log-opts=" + log_options));
568 + static boolean is_oid(String value) {
569 + return value.matches("[0-9a-fA-F]{40}|[0-9a-fA-F]{64}");
572 + static boolean is_zero_oid(String value) {
573 + return is_oid(value) && value.chars().allMatch(character -> character == '0');
576 + static String resolve_commit(Path root, String oid, String label) throws Throwable {
577 + var result = run(root, List.of("git", "rev-parse", "--verify", oid + "^{commit}"), null, false, false);
578 + if (result.exit != 0)
579 + throw fail("Pre-push {0} object is not a commit: {1}", label, oid);
580 + return result.text().strip();
583 + static void run_gitleaks(Path root, List<String> scan_arguments) throws Throwable {
584 + var command = new ArrayList<>(List.of("gitleaks", "git"));
585 + command.addAll(scan_arguments);
586 + command.addAll(List.of("--redact=100", "--no-banner"));
587 + Result result;
588 + try {
589 + result = run(root, command, null, true, false);
590 + } catch (IOException error) {
591 + throw fail("Gitleaks is required for Git hooks. Install Gitleaks, ensure it is on Git''s PATH, then retry.");
593 + if (result.exit != 0)
594 + throw fail("Gitleaks blocked the operation (exit {0}). Review its redacted output.", result.exit);
334 597 static void check_staged_matches_worktree(Path root, String path) throws Throwable {
335 598 var tracked = run(root, List.of("git", "ls-files", "--error-unmatch", "--", path), null, false, false);
336 - var changed = run(root, List.of("git", "diff", "--quiet", "--", path), null, false, false);
599 + var changed = run(root, List.of("git", "-c", "diff.autoRefreshIndex=false", "diff", "--no-ext-diff", "--no-textconv", "--quiet", "--", path), null, false, false);
337 600 if (tracked.exit != 0 || changed.exit != 0)
338 601 throw fail("{0} must match the staged version.", path);
341 604 static void check(Path root) throws Throwable {
342 605 var secrets = read_secrets(root);
343 606 if (!secrets.isEmpty()) {
607 + if (!Files.isReadable(key_path(root)))
608 + throw fail("Dotfiles AES key is unavailable. Run `mise run setup-crypto`, then retry.");
344 609 check_filter(root);
345 610 check_attributes(root, secrets);
346 611 check_worktree_secrets_decrypted(root, secrets);
348 613 check_staged_secrets(root, secrets);
350 615 check_symlink_sources(root);
351 - check_staged_plaintext_patterns(root);
352 616 log("OK bootstripper check passed.");
355 - static void check_staged_plaintext_patterns(Path root) throws Throwable {
356 - var diff = run(root, List.of("git", "diff", "--cached", "-U0"), null, false).text();
357 - var patterns = List.of(
358 - Pattern.compile("gh[pousr]_[A-Za-z0-9_]{20,}"),
359 - Pattern.compile("github_personal_access_token\\s*\\\":\\s*\\\"[^<G][^\\\"]+\\\""),
360 - Pattern.compile("oauth_(access|refresh)_token\\s*=\\s*\\S+"),
361 - Pattern.compile("Authorization\\s*[:=]\\s*Bearer\\s+[A-Za-z0-9._-]{20,}", Pattern.CASE_INSENSITIVE));
362 - for (var pattern : patterns) {
363 - var matcher = pattern.matcher(diff);
364 - if (matcher.find())
365 - throw fail("Potential plaintext secret in staged diff.");
366 - }
367 - }
369 619 static void check_filter(Path root) throws Throwable {
370 - var key = quote_shell(key_argument(root));
371 - var aes = quote_shell(aes_tool_argument(root));
372 620 var clean = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".clean"), null, false).text().strip();
373 621 var smudge = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".smudge"), null, false).text().strip();
374 622 var required = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".required"), null, false).text().strip();
375 623 var merge = run(root, List.of("git", "config", "--local", "--get", "merge." + filter_name + ".driver"), null, false).text().strip();
376 - if (!clean.equals("java " + aes + " encrypt --key-file " + key))
624 + if (!clean.equals(clean_filter_command(root)))
377 625 throw fail("Unexpected clean filter: {0}", clean);
378 - if (!smudge.equals("java " + aes + " decrypt --key-file " + key))
626 + if (!smudge.equals(smudge_filter_command(root)))
379 627 throw fail("Unexpected smudge filter: {0}", smudge);
380 628 if (!required.equals("true"))
381 629 throw fail("Filter is not required.");
382 - if (!merge.equals("java " + aes + " merge --key-file " + key + " \"%O\" \"%A\" \"%B\""))
630 + if (!merge.equals(merge_filter_command(root)))
383 631 throw fail("Unexpected merge driver: {0}", merge);
386 634 static void check_attributes(Path root, List<String> secrets) throws Throwable {
387 635 for (var secret : secrets) {
388 - var output = run(root, List.of("git", "check-attr", "text", "filter", "diff", "merge", "--", secret), null, false).text();
636 + var output = run(root, List.of("git", "--literal-pathspecs", "check-attr", "text", "filter", "diff", "merge", "--", secret), null, false).text();
389 637 if (!output.contains(secret + ": text: unset"))
390 638 throw fail("Missing -text attribute for {0}: {1}", secret, output.strip());
391 639 if (!output.contains(secret + ": filter: " + filter_name))
417 665 static void check_staged_secrets(Path root, List<String> secrets) throws Throwable {
418 666 for (var secret : secrets) {
419 - var status = run(root, List.of("git", "diff", "--cached", "--name-status", "--", secret), null, false).text().strip();
667 + var status = run(root, List.of("git", "--literal-pathspecs", "diff", "--cached", "--name-status", "--", secret), null, false).text().strip();
420 668 if (status.isEmpty() || status.startsWith("D"))
421 669 continue;
422 670 var blob = run(root, List.of("git", "show", ":" + secret), null, false).stdout;
640 888 return detected;
891 + static void ensure_permissions(Path path, String permissions) throws IOException {
892 + if (win32)
893 + return;
894 + try {
895 + var desired = PosixFilePermissions.fromString(permissions);
896 + if (!Files.getPosixFilePermissions(path).equals(desired))
897 + Files.setPosixFilePermissions(path, desired);
898 + } catch (UnsupportedOperationException ignored) {}
643 901 static void chmod(Path path, String permissions) throws IOException {
644 902 if (win32)
645 903 return;
686 944 static void usage() {
687 945 log("Bootstraps bugabingas {0}.", emphasize_local("dorkfiles"));
688 - log("{0}: java bootstripper.java [bootstrap|link|init-crypto|setup-crypto|check|pre-commit|install-hooks|clean] [dotfiles root path]", emphasize_global("Usage"));
946 + log("{0}: java bootstripper.java [bootstrap|link|init-crypto|setup-crypto|check|pre-commit|pre-push|install-hooks|clean] [dotfiles root path]", emphasize_global("Usage"));
691 949 static String emphasize_global(String message) {

mise.toml

Modified
23 23 run = 'run("java", "./scripts/dotfiles_integration_test.java", "--inside");'
25 25 [tasks.crypto-test]
26 -description = "Run focused crypto integration tests"
26 +description = "Run the complete crypto acceptance suite"
27 27 hide = true
28 28 run = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto");'
30 +[tasks.crypto-git-test]
31 +description = "Run focused encrypted Git filter and merge tests"
32 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto-git");'
34 +[tasks.crypto-restore-test]
35 +description = "Run focused encrypted-secret restoration tests"
36 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto-restore");'
38 +[tasks.fresh-checkout-crypto-test]
39 +description = "Test link-time crypto setup from a fresh encrypted checkout"
40 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--fresh-checkout-crypto");'
42 +[tasks.bootstrap-test]
43 +description = "Run focused bootstrap and platform-selection tests"
44 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--bootstrap");'
46 +[tasks.hooks-test]
47 +description = "Run isolated Git hook and link integration tests"
48 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--hooks");'
50 +[tasks.mise-shell-test]
51 +description = "Run focused Mise Java task-shell tests"
52 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--mise-shell");'
54 +[tasks.mise-route-test]
55 +description = "Test the production Mise link-task route"
56 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--mise-route");'
58 +[tasks.manifests-test]
59 +description = "Validate all repository symlink manifest contracts"
60 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--manifest-contracts");'
62 +[tasks.process-harness-test]
63 +description = "Test integration subprocess timeout and cleanup"
64 +run = 'run("java", "./scripts/dotfiles_integration_test.java", "--process-cleanup");'
66 +[tasks.secrets-scan]
67 +description = "Scan committed Git history for plaintext secrets"
68 +run = 'run("gitleaks", "git", "--redact=100", "--no-banner", "--log-opts=--all --full-history --diff-merges=first-parent --no-ext-diff --no-textconv");'
30 70 [tasks.link]
31 -description = "Validate manifests and link dorkfiles into HOME"
71 +description = "Converge crypto and hooks, validate manifests, and link dorkfiles into HOME"
32 72 run = 'run("java", "bootstripper.java", "link");'
34 74 [tasks.setup-crypto]

scripts/dotfiles_integration_test.java

Modified
1 1 import java.io.*;
2 2 import java.nio.file.*;
3 +import java.nio.file.attribute.PosixFilePermissions;
3 4 import java.time.*;
4 5 import java.util.*;
6 7 public class dotfiles_integration_test {
8 + static final String CLEAN_ENV = "DOTFILES_TEST_CLEAN_ENV";
9 + static final Path SETSID = findExecutable("setsid");
10 + static final Path KILL = findExecutable("kill");
11 + static final Set<Long> ACTIVE_PROCESS_GROUPS = java.util.concurrent.ConcurrentHashMap.newKeySet();
7 12 static Path root;
13 + static {
14 + Runtime.getRuntime().addShutdownHook(new Thread(() -> ACTIVE_PROCESS_GROUPS.forEach(dotfiles_integration_test::killGroup), "dotfiles-test-process-cleanup"));
15 + }
9 17 public static void main(String[] args) throws Exception {
10 - if (args.length > 0 && args[0].equals("--inside")) inside();
11 - else if (args.length > 0 && args[0].equals("--crypto")) {
12 - root = Path.of(run(null, "git", "rev-parse", "--show-toplevel").trim());
13 - freshCryptoChecks();
14 - } else host();
18 + root = Path.of(run(null, "git", "rev-parse", "--show-toplevel").trim());
19 + if (args.length == 0) host();
20 + else switch (args[0]) {
21 + case "--inside" -> inside();
22 + case "--crypto" -> freshCryptoChecks(CryptoScope.ALL);
23 + case "--crypto-git" -> freshCryptoChecks(CryptoScope.GIT);
24 + case "--crypto-restore" -> freshCryptoChecks(CryptoScope.RESTORE);
25 + case "--fresh-checkout-crypto" -> freshCheckoutCryptoChecks();
26 + case "--bootstrap" -> freshCryptoChecks(CryptoScope.BOOTSTRAP);
27 + case "--hooks" -> freshHookChecks();
28 + case "--manifests" -> manifestChecks();
29 + case "--manifest-contracts" -> manifestContractChecks();
30 + case "--mise-shell" -> miseShellSmoke();
31 + case "--mise-route" -> miseRouteChecks();
32 + case "--process-cleanup" -> processCleanupChecks();
33 + case "--process-cancellation-child" -> processCancellationChild(Path.of(args[1]), false);
34 + case "--process-inherit-cancellation-child" -> processCancellationChild(Path.of(args[1]), true);
35 + default -> throw new IllegalArgumentException("unknown suite: " + args[0]);
36 + }
17 39 static void host() throws Exception {
43 65 ok("mise-trusted");
44 66 step("install mise tools");
45 67 runInherit(null, "podman", "exec", "-w", "/root/work/dotfiles", container, "mise", "install");
68 + runInherit(null, "podman", "exec", "-w", "/root/work/dotfiles", container, "mise", "install", "gitleaks@8.30.1");
46 69 step("run ci check");
47 - runInherit(null, "podman", "exec", "-w", "/root/work/dotfiles", container, "mise", "exec", "--", "java", "./scripts/dotfiles_integration_test.java", "--inside");
70 + runInherit(null, "podman", "exec", "-w", "/root/work/dotfiles", container, "mise", "exec", "gitleaks@8.30.1", "--", "java", "./scripts/dotfiles_integration_test.java", "--inside");
48 71 } finally {
49 72 runAllowFail(null, "podman", "rm", "-f", container);
72 95 System.out.println(run(root, "mise", "--version").trim());
73 96 System.out.println(run(root, "java", "-version").lines().findFirst().orElse("java"));
74 97 miseShellSmoke();
98 + run(root, "gitleaks", "git", "--redact=100", "--no-banner", "--log-opts=--all --full-history --diff-merges=first-parent --no-ext-diff --no-textconv");
99 + ok("gitleaks-history");
76 101 run(root, "mise", "run", "hook");
77 102 var common = Path.of(run(root, "git", "rev-parse", "--git-common-dir").trim());
78 103 var hook = (common.isAbsolute() ? common : root.resolve(common)).resolve("hooks/pre-commit");
79 104 if (!Files.isExecutable(hook)) fail("hook-executable");
80 105 if (!Files.readString(hook).contains("exec java bootstripper.java pre-commit")) fail("hook-content");
106 + var pushHook = hook.resolveSibling("pre-push");
107 + if (!Files.isExecutable(pushHook) || !Files.readString(pushHook).contains("exec java bootstripper.java pre-push")) fail("push-hook-content");
81 108 ok("install-hooks");
83 110 if (!run(root, "git", "show", "HEAD:nushell/secrets.nu").startsWith("DFAES1")) fail("committed-encrypted");
84 111 ok("committed-encrypted");
86 113 run(root, "mise", "run", "setup-crypto");
87 - var hosts = allHosts();
88 - System.out.println("manifests=" + String.join(" ", hosts));
89 - for (var host : hosts) runManifest(host);
90 - ok("symlink-manifests:" + hosts.size());
114 + manifestChecks();
92 116 if (Files.readString(root.resolve("nushell/secrets.nu")).startsWith("DFAES1")) fail("worktree-still-encrypted");
93 117 ok("worktree-decrypted");
98 122 ok("pre-commit-hook");
100 124 freshCryptoChecks();
125 + freshCheckoutCryptoChecks();
126 + freshHookChecks();
127 + miseRouteChecks();
101 128 System.out.println("RESULT:ok");
104 131 static void miseShellSmoke() throws Exception {
105 - var smoke = "mise-shell-smoke";
106 - var snippet = """
107 - mkdir(\"%1$s/tree\");
108 - write(\"%1$s/a.txt\", \"alpha\");
109 - IO.println(read(\"%1$s/a.txt\"));
110 - IO.println(out(\"java\", \"-version\").contains(\"openjdk\"));
111 - rm(\"%1$s/a.txt\");
112 - write(\"%1$s/tree/b.txt\", \"beta\");
113 - rmTree(\"%1$s/tree\");
114 - rmdir(\"%1$s\");
115 - """.formatted(smoke);
116 - var out = run(root, "java", "scripts/mise_shell.java", snippet);
117 - if (!out.contains("alpha") || !out.contains("true")) fail("mise-shell-helpers");
118 - if (!runExpectFail(root, Map.of(), "java", "scripts/mise_shell.java", "bad();").contains("cannot find symbol")) fail("mise-shell-errors");
119 - ok("mise-shell");
132 + var temporary = Files.createTempDirectory("dotfiles-mise-shell-");
133 + var smoke = temporary.resolve("smoke");
134 + var shell = root.resolve("scripts/mise_shell.java").toString();
135 + try {
136 + var snippet = """
137 + mkdir(\"%1$s/tree\");
138 + write(\"%1$s/a.txt\", \"alpha\");
139 + IO.println(read(\"%1$s/a.txt\"));
140 + IO.println(out(\"java\", \"-version\").contains(\"openjdk\"));
141 + rm(\"%1$s/a.txt\");
142 + write(\"%1$s/tree/b.txt\", \"beta\");
143 + rmTree(\"%1$s/tree\");
144 + rmdir(\"%1$s\");
145 + """.formatted(smoke);
146 + var out = run(temporary, "java", shell, snippet);
147 + if (!out.contains("alpha") || !out.contains("true")) fail("mise-shell-helpers");
148 + if (!runExpectFail(temporary, Map.of(), "java", shell, "bad();").contains("cannot find symbol")) fail("mise-shell-errors");
149 + ok("mise-shell");
150 + } finally {
151 + deleteTree(temporary);
155 + static void processCleanupChecks() throws Exception {
156 + if (SETSID == null || KILL == null) fail("process-group-tools-unavailable");
157 + var temporary = Files.createTempDirectory("dotfiles-process-cleanup-");
158 + var pidFile = temporary.resolve("child.pid");
159 + try {
160 + runExpectFail(temporary, Map.of(), "sh", "-c", "sleep 30 & echo $! > '" + pidFile + "'; exit 7");
161 + assertProcessDead(Long.parseLong(Files.readString(pidFile).strip()), "descendant-survived-command-failure");
163 + var successPidFile = temporary.resolve("successful-child.pid");
164 + run(temporary, "sh", "-c", "sleep 30 </dev/null >/dev/null 2>&1 & echo $! > '" + successPidFile + "'; exit 0");
165 + assertProcessDead(Long.parseLong(Files.readString(successPidFile).strip()), "descendant-survived-successful-command");
167 + var stdinPidFile = temporary.resolve("stdin-child.pid");
168 + var stdinFailed = false;
169 + try {
170 + runInput(temporary, Map.of(), "x".repeat(256 * 1024), "sh", "-c", "exec 0<&-; sleep 30 & echo $! > '" + stdinPidFile + "'; exit 7");
171 + } catch (Exception expected) {
172 + stdinFailed = true;
174 + if (!stdinFailed) fail("stdin-failure-not-reported");
175 + assertProcessDead(Long.parseLong(Files.readString(stdinPidFile).strip()), "descendant-survived-stdin-failure");
177 + var inheritPidFile = temporary.resolve("inherit-child.pid");
178 + try {
179 + runInherit(temporary, "sh", "-c", "sleep 30 & echo $! > '" + inheritPidFile + "'; exit 7");
180 + fail("inherited-command-failure-not-reported");
181 + } catch (CommandFailed expected) {}
182 + assertProcessDead(Long.parseLong(Files.readString(inheritPidFile).strip()), "descendant-survived-inherited-command-failure");
184 + assertCancellationCleanup(temporary, "--process-cancellation-child", "captured");
185 + assertCancellationCleanup(temporary, "--process-inherit-cancellation-child", "inherited");
186 + ok("process-cleanup");
187 + } finally {
188 + deleteTree(temporary);
192 + static void assertProcessDead(long pid, String failure) throws Exception {
193 + var process = ProcessHandle.of(pid);
194 + for (var attempts = 0; process.isPresent() && process.get().isAlive() && attempts < 20; attempts++) Thread.sleep(50);
195 + if (process.isPresent() && process.get().isAlive()) fail(failure);
198 + static void assertCancellationCleanup(Path temporary, String mode, String name) throws Exception {
199 + var pidFile = temporary.resolve(name + "-cancellation-child.pid");
200 + var javaCommand = ProcessHandle.current().info().command().orElseThrow();
201 + var harness = root.resolve("scripts/dotfiles_integration_test.java").toString();
202 + var process = new ProcessBuilder(javaCommand, harness, mode, pidFile.toString())
203 + .redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(ProcessBuilder.Redirect.DISCARD).start();
204 + try {
205 + for (var attempts = 0; !Files.exists(pidFile) && process.isAlive() && attempts < 200; attempts++) Thread.sleep(50);
206 + if (!Files.exists(pidFile)) fail(name + "-cancellation-child-not-started");
207 + var childPid = Long.parseLong(Files.readString(pidFile).strip());
208 + process.destroy();
209 + if (!process.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)) process.destroyForcibly();
210 + assertProcessDead(childPid, "descendant-survived-" + name + "-cancellation");
211 + } finally {
212 + if (process.isAlive()) process.destroyForcibly();
216 + static void processCancellationChild(Path pidFile, boolean inherit) throws Exception {
217 + var command = new String[] { "sh", "-c", "sleep 30 & echo $! > '" + pidFile + "'; wait" };
218 + if (inherit) runInherit(root, command);
219 + else run(root, command);
222 + static void manifestContractChecks() throws Exception {
223 + var syntheticHome = Path.of("/home/dotfiles-test");
224 + var hosts = allHosts();
225 + for (var host : hosts) {
226 + var targets = new HashSet<Path>();
227 + forEachMapping(root.resolve(host + ".symlinks"), (source, target) -> {
228 + if (!Files.exists(root.resolve(source), LinkOption.NOFOLLOW_LINKS)) fail("missing-source:" + host + ":" + source);
229 + var resolved = targetPath(syntheticHome, target).normalize();
230 + if (!resolved.startsWith(syntheticHome)) fail("outside-home:" + host + ":" + target);
231 + if (!targets.add(resolved)) fail("duplicate-target:" + host + ":" + target);
232 + });
234 + ok("manifest-contracts:" + hosts.size());
237 + static void manifestChecks() throws Exception {
238 + var hosts = allHosts();
239 + System.out.println("manifests=" + String.join(" ", hosts));
240 + for (var host : hosts) runManifest(host);
241 + ok("symlink-manifests:" + hosts.size());
122 244 static List<String> allHosts() throws IOException {
150 272 ok("clean:" + host);
275 + record Fixture(Path home, Path repo, Path classes, Path realJava, Map<String, String> env) {}
276 + enum CryptoScope { ALL, GIT, RESTORE, BOOTSTRAP }
153 278 static void freshCryptoChecks() throws Exception {
154 - var home = Files.createTempDirectory(Path.of(System.getProperty("user.home")), "dotfiles-crypto-test-");
279 + freshCryptoChecks(CryptoScope.ALL);
282 + static void freshCryptoChecks(CryptoScope scope) throws Exception {
283 + var name = scope == CryptoScope.ALL ? "crypto" : "crypto-" + scope.name().toLowerCase(Locale.ROOT);
284 + withFixture(name, fixture -> cryptoChecks(fixture, scope));
287 + static void freshCheckoutCryptoChecks() throws Exception {
288 + withFixture("fresh-checkout-crypto", fixture -> {
289 + var repo = fixture.repo();
290 + var realEnv = new HashMap<>(fixture.env());
291 + realEnv.put("PATH", System.getenv("PATH"));
292 + var missingManifestEnv = new HashMap<>(realEnv);
293 + missingManifestEnv.remove("DOTFILES_AES_PASSPHRASE");
294 + missingManifestEnv.put("DOTFILES_SYMLINKS", "missing");
295 + if (!bootExpectFail(fixture, missingManifestEnv, "link").contains("Expected a file containing symlinks")) fail("missing-manifest-not-rejected-first");
296 + if (Files.exists(repo.resolve(".git/dotfiles-aes.key")) || Files.exists(repo.resolve(".git/dotfiles-aes.java")) || Files.exists(repo.resolve(".gitattributes")) || Files.exists(repo.resolve(".git/hooks/pre-commit"))) fail("missing-manifest-mutated-state");
297 + var failingAesEnv = new HashMap<>(fixture.env());
298 + failingAesEnv.put("FAKE_AES_EXIT", "1");
299 + if (!bootExpectFail(fixture, failingAesEnv, "setup-crypto").contains("AES self-test encryption failed")) fail("aes-self-test-failure-not-rejected");
300 + if (Files.exists(repo.resolve(".git/dotfiles-aes.key"))) fail("aes-self-test-failure-cached-key");
301 + try (var files = Files.list(repo.resolve(".git"))) {
302 + if (files.anyMatch(path -> path.getFileName().toString().startsWith("dotfiles-aes.key.") && path.getFileName().toString().endsWith(".tmp"))) fail("aes-self-test-failure-left-temporary-key");
304 + boot(fixture, realEnv, "setup-crypto");
305 + var plain = Files.readAllBytes(repo.resolve("secret.txt"));
306 + var ciphertext = repo.resolve("secret.ciphertext");
307 + run(repo, realEnv, fixture.realJava().toString(), "-cp", fixture.classes().toString(), "aes", "encrypt", "--key-file",
308 + repo.resolve(".git/dotfiles-aes.key").toString(), repo.resolve("secret.txt").toString(), ciphertext.toString());
309 + run(repo, realEnv, "git", "add", ".dotfiles-aes-salt", ".gitattributes", ".secrets", "secret.txt", "bootstripper.java", "tools/aes.java", "mini.symlinks", "dummy.txt");
310 + run(repo, realEnv, "git", "commit", "--quiet", "-m", "encrypted checkout");
311 + var index = Files.readAllBytes(repo.resolve(".git/index"));
312 + Files.delete(repo.resolve(".git/dotfiles-aes.key"));
313 + run(repo, realEnv, "git", "config", "--local", "--remove-section", "filter.dotfiles-aes");
314 + run(repo, realEnv, "git", "config", "--local", "--remove-section", "merge.dotfiles-aes");
315 + var encrypted = Files.readAllBytes(ciphertext);
316 + Files.write(repo.resolve("secret.txt"), encrypted);
317 + Files.delete(ciphertext);
319 + var wrongEnv = new HashMap<>(realEnv);
320 + wrongEnv.put("DOTFILES_AES_PASSPHRASE", "wrong");
321 + if (!bootExpectFail(fixture, wrongEnv, "link").contains("Passphrase does not decrypt committed secret")) fail("wrong-passphrase-not-rejected");
322 + if (Files.exists(repo.resolve(".git/dotfiles-aes.key"))) fail("wrong-passphrase-poisoned-key-cache");
323 + try (var files = Files.list(repo.resolve(".git"))) {
324 + if (files.anyMatch(path -> path.getFileName().toString().startsWith("dotfiles-aes.key.") && path.getFileName().toString().endsWith(".tmp"))) fail("wrong-passphrase-left-temporary-key");
326 + if (!Arrays.equals(Files.readAllBytes(repo.resolve("secret.txt")), encrypted)) fail("wrong-passphrase-rewrote-secret");
327 + var key = repo.resolve(".git/dotfiles-aes.key");
328 + Files.writeString(key, "invalid\n");
329 + if (!bootExpectFail(fixture, realEnv, "link").contains("Dotfiles AES key")) fail("malformed-key-not-rejected");
330 + if (!Files.readString(key).equals("invalid\n")) fail("malformed-key-replaced");
331 + Files.delete(key);
333 + boot(fixture, realEnv, "link");
334 + if (!Arrays.equals(Files.readAllBytes(repo.resolve("secret.txt")), plain)) fail("link-fresh-checkout-not-decrypted");
335 + if (!Arrays.equals(Files.readAllBytes(repo.resolve(".git/index")), index)) fail("link-fresh-checkout-changed-index");
336 + var keyModified = Files.getLastModifiedTime(repo.resolve(".git/dotfiles-aes.key"));
337 + var aesToolModified = Files.getLastModifiedTime(repo.resolve(".git/dotfiles-aes.java"));
338 + var configModified = Files.getLastModifiedTime(repo.resolve(".git/config"));
339 + var attributesModified = Files.getLastModifiedTime(repo.resolve(".gitattributes"));
340 + var secretModified = Files.getLastModifiedTime(repo.resolve("secret.txt"));
341 + var warmEnv = new HashMap<>(realEnv);
342 + warmEnv.remove("DOTFILES_AES_PASSPHRASE");
343 + boot(fixture, warmEnv, "link");
344 + if (!Files.getLastModifiedTime(repo.resolve(".git/dotfiles-aes.key")).equals(keyModified)) fail("warm-link-rewrote-key");
345 + if (!Files.getLastModifiedTime(repo.resolve(".git/dotfiles-aes.java")).equals(aesToolModified)) fail("warm-link-rewrote-aes-tool");
346 + if (!Files.getLastModifiedTime(repo.resolve(".git/config")).equals(configModified)) fail("warm-link-rewrote-config");
347 + if (!Files.getLastModifiedTime(repo.resolve(".gitattributes")).equals(attributesModified)) fail("warm-link-rewrote-attributes");
348 + if (!Files.getLastModifiedTime(repo.resolve("secret.txt")).equals(secretModified)) fail("warm-link-rewrote-secret");
349 + Files.writeString(repo.resolve("secret.txt"), "local plaintext edit\n");
350 + index = Files.readAllBytes(repo.resolve(".git/index"));
351 + boot(fixture, warmEnv, "link");
352 + if (!Files.readString(repo.resolve("secret.txt")).equals("local plaintext edit\n")) fail("warm-link-overwrote-local-plaintext");
353 + if (!Arrays.equals(Files.readAllBytes(repo.resolve(".git/index")), index)) fail("warm-link-with-local-edit-changed-index");
355 + var linkedHome = fixture.home().resolve("real-linked-home");
356 + var linked = linkedHome.resolve("repo");
357 + Files.createDirectories(linkedHome);
358 + var filterBeforeWorktree = run(repo, realEnv, "git", "config", "--local", "--get", "filter.dotfiles-aes.clean").strip();
359 + var configTimeBeforeWorktree = Files.getLastModifiedTime(repo.resolve(".git/config"));
360 + run(repo, realEnv, "git", "worktree", "add", "--quiet", "-b", "real-linked-test", linked.toString());
361 + if (!Arrays.equals(Files.readAllBytes(linked.resolve("secret.txt")), plain)) fail("real-linked-worktree-not-decrypted");
362 + var linkedEnv = new HashMap<>(realEnv);
363 + linkedEnv.put("HOME", linkedHome.toString());
364 + linkedEnv.put("JAVA_TOOL_OPTIONS", "-Duser.home=" + linkedHome);
365 + bootAt(fixture, linkedEnv, "link", linked);
366 + if (!run(repo, realEnv, "git", "config", "--local", "--get", "filter.dotfiles-aes.clean").strip().equals(filterBeforeWorktree) || !Files.getLastModifiedTime(repo.resolve(".git/config")).equals(configTimeBeforeWorktree)) fail("real-linked-worktree-rewrote-filter");
367 + run(repo, realEnv, "git", "worktree", "remove", "--force", linked.toString());
368 + ok("fresh-checkout-link-crypto");
369 + });
372 + static void freshHookChecks() throws Exception {
373 + withFixture("hooks", fixture -> {
374 + Files.writeString(fixture.repo().resolve(".gitattributes"), "");
375 + run(fixture.repo(), fixture.env(), "git", "add", ".secrets", ".gitattributes", "bootstripper.java", "mini.symlinks", "dummy.txt");
376 + run(fixture.repo(), fixture.env(), "git", "commit", "--quiet", "-m", "base");
377 + linkAndHookChecks(fixture);
378 + });
381 + static void miseRouteChecks() throws Exception {
382 + withFixture("mise-route", fixture -> {
383 + run(fixture.repo(), fixture.env(), "mise", "trust", "--yes");
384 + run(fixture.repo(), fixture.env(), "mise", "run", "--skip-tools", "link");
385 + if (!Files.isSymbolicLink(fixture.home().resolve("dummy.txt"))) fail("mise-route-link");
386 + ok("mise-route");
387 + });
390 + interface FixtureCheck { void run(Fixture fixture) throws Exception; }
392 + static void withFixture(String name, FixtureCheck check) throws Exception {
393 + var home = Files.createTempDirectory(Path.of(System.getProperty("user.home")), "dotfiles-" + name + "-");
394 + var started = System.nanoTime();
156 - freshCryptoChecks(home);
396 + check.run(createFixture(home));
397 + ok(name + ":" + Duration.ofNanos(System.nanoTime() - started).toMillis() + "ms");
157 398 } finally {
158 399 deleteTree(home);
162 - static void freshCryptoChecks(Path home) throws Exception {
403 + static Fixture createFixture(Path home) throws Exception {
163 404 var repo = home.resolve("repo");
405 + var classes = home.resolve("classes");
406 + var bin = home.resolve("bin");
164 407 Files.createDirectories(repo.resolve("tools"));
165 - Files.createDirectories(home);
408 + Files.createDirectories(repo.resolve("scripts"));
409 + Files.createDirectories(classes);
410 + Files.createDirectories(bin);
166 411 Files.copy(root.resolve("bootstripper.java"), repo.resolve("bootstripper.java"));
167 412 Files.copy(root.resolve("tools/aes.java"), repo.resolve("tools/aes.java"));
168 - Files.copy(root.resolve("mise.toml"), repo.resolve("mise.toml"));
169 - Files.createDirectories(repo.resolve("scripts"));
413 + Files.copy(root.resolve(".dotfiles-aes-salt"), repo.resolve(".dotfiles-aes-salt"));
170 414 Files.copy(root.resolve("scripts/mise_shell.java"), repo.resolve("scripts/mise_shell.java"));
415 + try (var files = Files.list(root)) {
416 + for (var source : files.filter(path -> {
417 + var filename = path.getFileName().toString();
418 + return filename.equals(".miserc.toml") || filename.equals("mise.lock") || filename.matches("^\\.?mise(?:\\..+)?\\.toml$");
419 + }).toList())
420 + Files.copy(source, repo.resolve(source.getFileName()));
171 422 Files.writeString(repo.resolve(".secrets"), "secret.txt\n");
172 423 Files.writeString(repo.resolve("mini.symlinks"), "dummy.txt\n~/dummy.txt\n");
173 424 Files.writeString(repo.resolve("secret.txt"), "alpha=base\nmiddle=stable\nomega=base\n");
174 425 Files.writeString(repo.resolve("dummy.txt"), "dummy\n");
175 - run(repo, "git", "init", "--quiet");
176 - run(repo, "git", "config", "user.name", "Dotfiles Test");
177 - run(repo, "git", "config", "user.email", "dotfiles@example.invalid");
426 + var gitleaks = bin.resolve("gitleaks");
427 + Files.writeString(gitleaks, "#!/bin/sh\nif [ -n \"${FAKE_GITLEAKS_LOG:-}\" ]; then printf '%s\\n' \"$*\" >> \"$FAKE_GITLEAKS_LOG\"; fi\nif [ \"${FAKE_GITLEAKS_EXIT:-0}\" != 0 ]; then echo 'Finding: REDACTED' >&2; exit \"$FAKE_GITLEAKS_EXIT\"; fi\nexit 0\n");
428 + Files.setPosixFilePermissions(gitleaks, PosixFilePermissions.fromString("rwxr-xr-x"));
429 + var xdg = home.resolve("xdg");
430 + var temporary = home.resolve("tmp");
431 + var gitConfig = home.resolve("empty.gitconfig");
432 + var gitTemplates = home.resolve("git-templates");
433 + Files.createDirectories(xdg);
434 + Files.createDirectories(temporary);
435 + Files.createDirectories(gitTemplates);
436 + Files.writeString(gitConfig, "");
437 + var env = new HashMap<String, String>();
438 + env.put(CLEAN_ENV, "1");
439 + env.put("HOME", home.toString());
440 + env.put("USER", "dotfiles-test");
441 + env.put("SHELL", "/bin/sh");
442 + env.put("LANG", "C");
443 + env.put("LC_ALL", "C");
444 + env.put("TMPDIR", temporary.toString());
445 + env.put("XDG_CONFIG_HOME", xdg.resolve("config").toString());
446 + env.put("XDG_CACHE_HOME", xdg.resolve("cache").toString());
447 + env.put("XDG_DATA_HOME", xdg.resolve("data").toString());
448 + env.put("XDG_STATE_HOME", xdg.resolve("state").toString());
449 + env.put("MISE_DATA_DIR", xdg.resolve("mise-data").toString());
450 + env.put("MISE_CACHE_DIR", xdg.resolve("mise-cache").toString());
451 + env.put("MISE_SYSTEM_CONFIG_DIR", xdg.resolve("mise-system").toString());
452 + env.put("MISE_GLOBAL_CONFIG_FILE", xdg.resolve("mise-global.toml").toString());
453 + env.put("MISE_CEILING_PATHS", home.toString());
454 + env.put("GIT_CONFIG_NOSYSTEM", "1");
455 + env.put("GIT_CONFIG_GLOBAL", gitConfig.toString());
456 + env.put("GIT_ATTR_NOSYSTEM", "1");
457 + env.put("GIT_TEMPLATE_DIR", gitTemplates.toString());
458 + env.put("GIT_TERMINAL_PROMPT", "0");
459 + env.put("GIT_CEILING_DIRECTORIES", home.toString());
460 + env.put("DOTFILES_AES_PASSPHRASE", "test");
461 + env.put("JAVA_TOOL_OPTIONS", "-Duser.home=" + home);
462 + env.put("PATH", bin + File.pathSeparator + System.getenv("PATH"));
463 + env.put("DOTFILES_SYMLINKS", "mini");
464 + run(repo, env, "git", "init", "--quiet");
465 + run(repo, env, "git", "config", "user.name", "Dotfiles Test");
466 + run(repo, env, "git", "config", "user.email", "dotfiles@example.invalid");
467 + run(repo, env, "git", "config", "commit.gpgSign", "false");
468 + Files.createDirectories(repo.resolve(".git/info"));
178 469 Files.writeString(repo.resolve(".git/info/attributes"), "*.bin -diff\n# BEGIN bootstripper secrets\nsecret.txt -text filter=dotfiles-aes -diff merge=dotfiles-aes\n# END bootstripper secrets\n");
179 - var env = Map.of("DOTFILES_AES_PASSPHRASE", "test", "JAVA_TOOL_OPTIONS", "-Duser.home=" + home);
180 - run(repo, "mise", "trust", "--yes");
181 - linkOnlyChecks(repo, home, env);
182 - run(repo, env, "java", "bootstripper.java", "init-crypto");
183 - run(repo, env, "mise", "run", "setup-crypto");
184 - run(repo, env, "java", "bootstripper.java", "check");
470 + // Exercise restoration directly so refusal cases do not repeat unrelated filter setup.
471 + Files.writeString(repo.resolve("scripts/restore_test_driver.java"), """
472 + import java.nio.file.Path;
474 + class restore_test_driver {
475 + public static void main(String[] arguments) throws Throwable {
476 + var root = Path.of(arguments[0]).toRealPath();
477 + bootstripper.restore_tracked_secrets(root, bootstripper.read_secrets(root));
480 + """);
481 + Files.writeString(repo.resolve("scripts/real_aes_test_driver.java"), """
482 + import java.nio.charset.StandardCharsets;
483 + import java.nio.file.*;
484 + import java.util.*;
486 + class real_aes_test_driver {
487 + static byte[] bytes(String text) { return text.getBytes(StandardCharsets.UTF_8); }
488 + static void require(boolean condition, String message) {
489 + if (!condition) throw new AssertionError(message);
491 + static void writeEncrypted(Path path, byte[] key, String text) throws Exception {
492 + Files.write(path, aes.encrypt(key, bytes(text)));
494 + public static void main(String[] arguments) throws Exception {
495 + var key = Base64.getDecoder().decode(Files.readString(Path.of(arguments[0])).trim());
496 + var work = Path.of(arguments[1]);
497 + Files.createDirectories(work);
498 + var plain = bytes("synthetic secret\\n");
499 + var encrypted = aes.encrypt(key, plain);
500 + require(Arrays.equals(encrypted, aes.encrypt(key, plain)), "encryption is not deterministic");
501 + require(Arrays.equals(plain, aes.decrypt(key, encrypted)), "round trip failed");
502 + try { aes.encrypt(key, encrypted); throw new AssertionError("double encryption accepted"); }
503 + catch (IllegalArgumentException expected) {}
505 + var base = work.resolve("base");
506 + var current = work.resolve("current");
507 + var other = work.resolve("other");
508 + writeEncrypted(base, key, "alpha=base\\nmiddle=stable\\nomega=base\\n");
509 + writeEncrypted(current, key, "alpha=base\\nmiddle=stable\\nomega=current\\n");
510 + writeEncrypted(other, key, "alpha=other\\nmiddle=stable\\nomega=base\\n");
511 + require(aes.merge(key, base, current, other) == 0, "clean merge failed");
512 + var merged = new String(aes.decrypt(key, Files.readAllBytes(current)), StandardCharsets.UTF_8);
513 + require(merged.contains("alpha=other") && merged.contains("omega=current"), "clean merge lost changes");
515 + writeEncrypted(base, key, "value=base\\n");
516 + writeEncrypted(current, key, "value=current\\n");
517 + writeEncrypted(other, key, "value=other\\n");
518 + require(aes.merge(key, base, current, other) == 1, "conflicting merge did not conflict");
519 + var conflict = new String(aes.decrypt(key, Files.readAllBytes(current)), StandardCharsets.UTF_8);
520 + require(conflict.contains("<<<<<<< current") && conflict.contains("value=other"), "conflict markers missing");
523 + """);
524 + run(repo, env, "javac", "-d", classes.toString(), "bootstripper.java", "tools/aes.java", "scripts/restore_test_driver.java", "scripts/real_aes_test_driver.java");
525 + var realJava = Path.of(ProcessHandle.current().info().command().orElseThrow()).toAbsolutePath();
526 + // Native Git uses a fast deterministic codec; realAesChecks covers the production codec separately.
527 + var fastAes = bin.resolve("test-aes");
528 + Files.writeString(fastAes, """
529 + #!/bin/sh
530 + set -eu
531 + command=$1; shift
532 + if [ -n "${FAKE_AES_LOG:-}" ]; then printf '%s\\n' "$command" >> "$FAKE_AES_LOG"; fi
533 + if [ "${FAKE_AES_EXIT:-0}" != 0 ]; then echo 'synthetic AES failure' >&2; exit "$FAKE_AES_EXIT"; fi
534 + [ "$1" = --key-file ]; shift 2
535 + tmp=${TMPDIR:-/tmp}/dotfiles-test-aes-$$
536 + trap 'rm -rf "$tmp"' EXIT
537 + mkdir "$tmp"
538 + decrypt() { [ "$(head -c 6 "$1")" = DFAES1 ] || { echo 'invalid dotfiles AES blob' >&2; return 1; }; tail -c +7 "$1"; }
539 + case "$command" in
540 + encrypt)
541 + if [ "$#" -eq 0 ]; then cat > "$tmp/in"; input=$tmp/in; output=-; else input=$1; output=$2; [ ! -e "$output" ]; fi
542 + [ "$(head -c 6 "$input")" != DFAES1 ] || { echo 'input is already a dotfiles AES blob' >&2; exit 2; }
543 + if [ "$output" = - ]; then printf DFAES1; cat "$input"; else { printf DFAES1; cat "$input"; } > "$output"; fi;;
544 + decrypt)
545 + if [ "$#" -eq 0 ]; then cat > "$tmp/in"; decrypt "$tmp/in"; else [ ! -e "$2" ]; decrypt "$1" > "$2"; fi;;
546 + merge)
547 + decrypt "$1" > "$tmp/base"; decrypt "$2" > "$tmp/current"; decrypt "$3" > "$tmp/other"
548 + status=0; git merge-file -L current -L base -L other "$tmp/current" "$tmp/base" "$tmp/other" || status=$?
549 + { printf DFAES1; cat "$tmp/current"; } > "$2"
550 + exit "$status";;
551 + *) exit 2;;
552 + esac
553 + """);
554 + Files.setPosixFilePermissions(fastAes, PosixFilePermissions.fromString("rwxr-xr-x"));
555 + var java = bin.resolve("java");
556 + Files.writeString(java, "#!/bin/sh\ncase \"$1\" in\n */tools/aes.java|tools/aes.java|*/dotfiles-aes.java) shift; exec " + shellQuote(fastAes) + " \"$@\";;\n *) exec " + shellQuote(realJava) + " \"$@\";;\nesac\n");
557 + Files.setPosixFilePermissions(java, PosixFilePermissions.fromString("rwxr-xr-x"));
558 + return new Fixture(home, repo, classes, realJava, Map.copyOf(env));
561 + static String shellQuote(Path path) {
562 + return "'" + path.toString().replace("'", "'\"'\"'") + "'";
565 + static String boot(Fixture fixture, String command) throws Exception {
566 + return boot(fixture, fixture.env(), command);
569 + static String boot(Fixture fixture, Map<String, String> env, String command) throws Exception {
570 + return bootAt(fixture, env, command, fixture.repo());
573 + static String bootAt(Fixture fixture, Map<String, String> env, String command, Path root) throws Exception {
574 + return run(root, env, "java", "-cp", fixture.classes().toString(), "bootstripper", command, root.toString());
577 + static String bootExpectFail(Fixture fixture, Map<String, String> env, String command) throws Exception {
578 + try {
579 + var output = boot(fixture, env, command);
580 + throw new AssertionError("expected failure: bootstripper " + command + "\n" + output);
581 + } catch (CommandFailed error) {
582 + return error.getMessage();
586 + static String restoreExpectFail(Fixture fixture) throws Exception {
587 + return runExpectFail(fixture.repo(), fixture.env(), "java", "-cp", fixture.classes().toString(), "restore_test_driver", fixture.repo().toString());
590 + static void cryptoChecks(Fixture fixture, CryptoScope scope) throws Exception {
591 + var home = fixture.home();
592 + var repo = fixture.repo();
593 + var env = fixture.env();
594 + boot(fixture, "init-crypto");
595 + boot(fixture, "setup-crypto");
596 + if (scope == CryptoScope.ALL || scope == CryptoScope.GIT) realAesChecks(fixture);
597 + boot(fixture, "check");
185 598 if (!Files.readString(repo.resolve(".gitattributes")).contains("secret.txt -text filter=dotfiles-aes -diff merge=dotfiles-aes")) fail("tracked-attributes-generated");
186 599 if (!Files.readString(repo.resolve(".git/info/attributes")).equals("*.bin -diff\n")) fail("local-attributes-migrated");
187 - if (!runExpectFail(repo, env, "java", "bootstripper.java", "pre-commit").contains(".secrets must match the staged version")) fail("unstaged-secret-manifest-not-rejected");
188 600 run(repo, env, "git", "add", ".dotfiles-aes-salt", ".gitattributes", ".secrets", "bootstripper.java", "tools/aes.java", "mini.symlinks", "dummy.txt", "secret.txt");
189 - run(repo, env, "java", "bootstripper.java", "pre-commit");
190 - if (!run(repo, "git", "show", ":secret.txt").startsWith("DFAES1")) fail("fresh-staged-encrypted");
191 - run(repo, "git", "commit", "--quiet", "-m", "base");
192 - var base = run(repo, "git", "rev-parse", "HEAD").trim();
194 - Files.writeString(repo.resolve(".gitattributes"), Files.readString(repo.resolve(".gitattributes")) + "*.tmp -diff\n");
195 - if (!runExpectFail(repo, env, "java", "bootstripper.java", "pre-commit").contains(".gitattributes must match the staged version")) fail("unstaged-attributes-not-rejected");
196 - run(repo, "git", "restore", ".gitattributes");
601 + if (!run(repo, env, "git", "show", ":secret.txt").startsWith("DFAES1")) fail("fresh-staged-encrypted");
602 + run(repo, env, "git", "commit", "--quiet", "-m", "base");
603 + var base = run(repo, env, "git", "rev-parse", "HEAD").trim();
197 604 Files.writeString(repo.resolve(".secrets"), "secret.txt\nincoming-secret.txt\n");
198 605 Files.writeString(repo.resolve("incoming-secret.txt"), "incoming=plain\n");
199 - run(repo, env, "java", "bootstripper.java", "check");
200 - run(repo, "git", "add", ".secrets", ".gitattributes", "incoming-secret.txt");
201 - run(repo, env, "java", "bootstripper.java", "pre-commit");
202 - run(repo, "git", "commit", "--quiet", "-m", "add encrypted secret");
203 - var incoming = run(repo, "git", "rev-parse", "HEAD").trim();
204 - run(repo, "git", "switch", "--quiet", "--detach", base);
205 - run(repo, "git", "merge", "--quiet", "--ff-only", incoming);
606 + boot(fixture, "check");
607 + run(repo, env, "git", "add", ".secrets", ".gitattributes", "incoming-secret.txt");
608 + run(repo, env, "git", "commit", "--quiet", "-m", "add encrypted secret");
609 + var incoming = run(repo, env, "git", "rev-parse", "HEAD").trim();
610 + run(repo, env, "git", "switch", "--quiet", "--detach", base);
611 + run(repo, env, "git", "merge", "--quiet", "--ff-only", incoming);
206 612 if (!Files.readString(repo.resolve("incoming-secret.txt")).equals("incoming=plain\n")) fail("same-pull-secret-not-smudged");
207 613 ok("same-pull-secret-smudged");
208 614 base = incoming;
209 - cryptoRestoreChecks(repo, env);
615 + if (scope == CryptoScope.ALL || scope == CryptoScope.RESTORE) cryptoRestoreChecks(fixture);
616 + if (scope == CryptoScope.RESTORE) {
617 + ok("crypto-restore");
618 + return;
211 - run(repo, "git", "switch", "--quiet", "-c", "secret-other");
212 - Files.writeString(repo.resolve("secret.txt"), "alpha=other\nmiddle=stable\nomega=base\n");
213 - run(repo, "git", "add", "secret.txt");
214 - run(repo, "git", "commit", "--quiet", "-m", "other secret change");
215 - run(repo, "git", "switch", "--quiet", "-c", "secret-current", base);
216 - Files.writeString(repo.resolve("secret.txt"), "alpha=base\nmiddle=stable\nomega=current\n");
217 - run(repo, "git", "add", "secret.txt");
218 - run(repo, "git", "commit", "--quiet", "-m", "current secret change");
219 - run(repo, "git", "merge", "--quiet", "--no-edit", "secret-other");
220 - var merged = Files.readString(repo.resolve("secret.txt"));
221 - if (!merged.contains("alpha=other") || !merged.contains("omega=current") || merged.startsWith("DFAES1")) fail("secret-clean-merge");
222 - if (!run(repo, "git", "show", "HEAD:secret.txt").startsWith("DFAES1")) fail("secret-merge-committed-encrypted");
223 - ok("secret-clean-merge");
225 - var conflictBase = run(repo, "git", "rev-parse", "HEAD").trim();
226 - run(repo, "git", "switch", "--quiet", "-c", "secret-conflict-other");
227 - Files.writeString(repo.resolve("secret.txt"), "alpha=conflict-other\nmiddle=stable\nomega=current\n");
228 - run(repo, "git", "add", "secret.txt");
229 - run(repo, "git", "commit", "--quiet", "-m", "other conflicting secret change");
230 - run(repo, "git", "switch", "--quiet", "-c", "secret-conflict-current", conflictBase);
231 - Files.writeString(repo.resolve("secret.txt"), "alpha=conflict-current\nmiddle=stable\nomega=current\n");
232 - run(repo, "git", "add", "secret.txt");
233 - run(repo, "git", "commit", "--quiet", "-m", "current conflicting secret change");
234 - runExpectFail(repo, env, "git", "merge", "--quiet", "--no-edit", "secret-conflict-other");
235 - var conflicted = Files.readString(repo.resolve("secret.txt"));
236 - if (!conflicted.contains("<<<<<<< current") || !conflicted.contains("alpha=conflict-current") || !conflicted.contains("alpha=conflict-other") || conflicted.startsWith("DFAES1")) fail("secret-conflict-plaintext");
237 - run(repo, "git", "merge", "--abort");
238 - ok("secret-conflict-plaintext");
240 - run(repo, env, "java", "tools/aes.java", "encrypt", "--key-file", ".git/dotfiles-aes.key", "secret.txt", "encrypted-secret.txt");
241 - Files.write(repo.resolve("secret.txt"), Files.readAllBytes(repo.resolve("encrypted-secret.txt")));
242 - Files.delete(repo.resolve("encrypted-secret.txt"));
243 - if (!runExpectFail(repo, env, "git", "add", "secret.txt").contains("input is already a dotfiles AES blob")) fail("encrypted-worktree-clean-not-rejected");
621 + if (scope != CryptoScope.BOOTSTRAP) {
622 + cryptoGitChecks(fixture, base);
623 + if (scope == CryptoScope.GIT) return;
244 625 Files.writeString(repo.resolve("secret.txt"), "not a real secret\n");
245 626 var wslHome = home.resolve("fresh-wsl-home");
246 627 Files.createDirectories(wslHome);
247 628 var wslEnv = new HashMap<>(env);
629 + wslEnv.remove("DOTFILES_SYMLINKS");
248 630 wslEnv.put("JAVA_TOOL_OPTIONS", "-Duser.home=" + wslHome);
249 631 wslEnv.put("COMPUTERNAME", "");
250 632 wslEnv.put("WSL_DISTRO_NAME", "mini");
251 633 wslEnv.put("HOSTNAME", "ignored");
252 - run(repo, wslEnv, "java", "bootstripper.java", "bootstrap");
634 + boot(fixture, wslEnv, "bootstrap");
253 635 if (!Files.readString(repo.resolve("secret.txt")).equals("not a real secret\n")) fail("bootstrap-overwrote-local-secret");
254 636 if (!Files.isSymbolicLink(wslHome.resolve("dummy.txt"))) fail("fresh-wsl-distro-manifest");
255 - run(repo, wslEnv, "java", "bootstripper.java", "clean");
256 - var env2 = new HashMap<>(env); env2.put("HOSTNAME", "mini");
637 + boot(fixture, wslEnv, "clean");
638 + var env2 = new HashMap<>(env);
639 + env2.remove("DOTFILES_SYMLINKS");
640 + env2.put("HOSTNAME", "mini");
257 641 Files.createSymbolicLink(home.resolve("dummy.txt"), Path.of("/usr/lib/outside-home"));
258 - if (!runExpectFail(repo, env2, "java", "bootstripper.java", "bootstrap").contains("outside HOME")) fail("outside-home-symlink-not-rejected");
642 + if (!bootExpectFail(fixture, env2, "bootstrap").contains("outside HOME")) fail("outside-home-symlink-not-rejected");
259 643 Files.delete(home.resolve("dummy.txt"));
260 - run(repo, env2, "java", "bootstripper.java", "bootstrap");
644 + boot(fixture, env2, "bootstrap");
261 645 if (!Files.isSymbolicLink(home.resolve("dummy.txt"))) fail("fresh-link");
262 - run(repo, env2, "java", "bootstripper.java", "clean");
263 - ok("fresh-crypto");
646 + boot(fixture, env2, "clean");
647 + ok(scope == CryptoScope.ALL ? "fresh-crypto" : "bootstrap");
266 - static void linkOnlyChecks(Path repo, Path home, Map<String, String> env) throws Exception {
650 + static void cryptoGitChecks(Fixture fixture, String base) throws Exception {
651 + var repo = fixture.repo();
652 + var env = fixture.env();
653 + run(repo, env, "git", "switch", "--quiet", "-c", "secret-other");
654 + Files.writeString(repo.resolve("secret.txt"), "alpha=other\nmiddle=stable\nomega=base\n");
655 + run(repo, env, "git", "add", "secret.txt");
656 + run(repo, env, "git", "commit", "--quiet", "-m", "other secret change");
657 + run(repo, env, "git", "switch", "--quiet", "-c", "secret-current", base);
658 + Files.writeString(repo.resolve("secret.txt"), "alpha=base\nmiddle=stable\nomega=current\n");
659 + run(repo, env, "git", "add", "secret.txt");
660 + run(repo, env, "git", "commit", "--quiet", "-m", "current secret change");
661 + run(repo, env, "git", "merge", "--quiet", "--no-edit", "secret-other");
662 + var merged = Files.readString(repo.resolve("secret.txt"));
663 + if (!merged.contains("alpha=other") || !merged.contains("omega=current") || merged.startsWith("DFAES1")) fail("secret-clean-merge");
664 + if (!run(repo, env, "git", "show", "HEAD:secret.txt").startsWith("DFAES1")) fail("secret-merge-committed-encrypted");
665 + ok("secret-clean-merge");
667 + var conflictBase = run(repo, env, "git", "rev-parse", "HEAD").trim();
668 + run(repo, env, "git", "switch", "--quiet", "-c", "secret-conflict-other");
669 + Files.writeString(repo.resolve("secret.txt"), "alpha=conflict-other\nmiddle=stable\nomega=current\n");
670 + run(repo, env, "git", "add", "secret.txt");
671 + run(repo, env, "git", "commit", "--quiet", "-m", "other conflicting secret change");
672 + run(repo, env, "git", "switch", "--quiet", "-c", "secret-conflict-current", conflictBase);
673 + Files.writeString(repo.resolve("secret.txt"), "alpha=conflict-current\nmiddle=stable\nomega=current\n");
674 + run(repo, env, "git", "add", "secret.txt");
675 + run(repo, env, "git", "commit", "--quiet", "-m", "current conflicting secret change");
676 + runExpectFail(repo, env, "git", "merge", "--quiet", "--no-edit", "secret-conflict-other");
677 + var conflicted = Files.readString(repo.resolve("secret.txt"));
678 + if (!conflicted.contains("<<<<<<< current") || !conflicted.contains("alpha=conflict-current") || !conflicted.contains("alpha=conflict-other") || conflicted.startsWith("DFAES1")) fail("secret-conflict-plaintext");
679 + run(repo, env, "git", "merge", "--abort");
680 + ok("secret-conflict-plaintext");
682 + run(repo, env, fixture.home().resolve("bin/test-aes").toString(), "encrypt", "--key-file", ".git/dotfiles-aes.key", "secret.txt", "encrypted-secret.txt");
683 + Files.write(repo.resolve("secret.txt"), Files.readAllBytes(repo.resolve("encrypted-secret.txt")));
684 + Files.delete(repo.resolve("encrypted-secret.txt"));
685 + if (!runExpectFail(repo, env, "git", "add", "secret.txt").contains("input is already a dotfiles AES blob")) fail("encrypted-worktree-clean-not-rejected");
686 + ok("crypto-git");
689 + static void realAesChecks(Fixture fixture) throws Exception {
690 + run(fixture.repo(), fixture.env(), fixture.realJava().toString(), "-cp", fixture.classes().toString(), "real_aes_test_driver",
691 + fixture.repo().resolve(".git/dotfiles-aes.key").toString(), fixture.home().resolve("real-aes").toString());
692 + ok("real-aes-contract");
695 + static void linkAndHookChecks(Fixture fixture) throws Exception {
696 + var repo = fixture.repo();
697 + var home = fixture.home();
698 + var env = fixture.env();
267 699 var linkEnv = new HashMap<>(env);
268 700 linkEnv.put("DOTFILES_SYMLINKS", "mini");
269 - var config = Files.readString(repo.resolve(".git/config"));
270 - var attributes = Files.readString(repo.resolve(".git/info/attributes"));
701 + var gitleaksLog = home.resolve("gitleaks.log");
702 + var aesLog = home.resolve("aes.log");
703 + linkEnv.put("FAKE_GITLEAKS_LOG", gitleaksLog.toString());
704 + linkEnv.put("FAKE_AES_LOG", aesLog.toString());
271 705 var secret = Files.readString(repo.resolve("secret.txt"));
272 - for (var attempt = 0; attempt < 2; attempt++) run(repo, linkEnv, "mise", "run", "link");
273 - if (!Files.isSymbolicLink(home.resolve("dummy.txt")) || !Files.isSameFile(home.resolve("dummy.txt"), repo.resolve("dummy.txt"))) fail("link-only-target");
274 - if (!Files.readString(repo.resolve("secret.txt")).equals(secret)) fail("link-only-secret-changed");
275 - if (!Files.readString(repo.resolve(".git/config")).equals(config)) fail("link-only-config-changed");
276 - if (!Files.readString(repo.resolve(".git/info/attributes")).equals(attributes)) fail("link-only-attributes-changed");
277 - for (var path : List.of(".git/dotfiles-aes.key", ".gitattributes", ".git/hooks/pre-commit"))
278 - if (Files.exists(repo.resolve(path))) fail("link-only-created:" + path);
706 + var hook = repo.resolve(".git/hooks/pre-commit");
707 + var pushHook = repo.resolve(".git/hooks/pre-push");
708 + boot(fixture, linkEnv, "link");
709 + if (Files.exists(gitleaksLog)) fail("link-invoked-gitleaks");
710 + if (!Files.isReadable(repo.resolve(".git/dotfiles-aes.key"))) fail("link-key-created");
711 + if (!Files.readString(repo.resolve("secret.txt")).equals(secret)) fail("link-plaintext-secret-changed");
712 + var configured = Files.readString(repo.resolve(".git/config"));
713 + var trackedAttributes = Files.readString(repo.resolve(".gitattributes"));
714 + var localAttributes = Files.readString(repo.resolve(".git/info/attributes"));
715 + if (!trackedAttributes.contains("secret.txt -text filter=dotfiles-aes -diff merge=dotfiles-aes")) fail("link-attributes-configured");
716 + if (!localAttributes.equals("*.bin -diff\n")) fail("link-local-attributes-migrated");
717 + if (!Files.isExecutable(hook) || !Files.readString(hook).contains("exec java bootstripper.java pre-commit")) fail("link-hook-installed");
718 + if (!Files.isExecutable(pushHook) || !Files.readString(pushHook).contains("exec java bootstripper.java pre-push")) fail("link-push-hook-installed");
719 + Files.writeString(repo.resolve(".secrets"), "secret.txt\nother.txt\n");
720 + if (!runExpectFail(repo, linkEnv, hook.toString()).contains(".secrets must match the staged version")) fail("pre-commit-staged-manifest-check");
721 + run(repo, env, "git", "restore", ".secrets");
722 + Files.writeString(repo.resolve(".gitattributes"), "*.tmp -diff\n");
723 + if (!runExpectFail(repo, linkEnv, hook.toString()).contains(".gitattributes must match the staged version")) fail("pre-commit-staged-attributes-check");
724 + Files.writeString(repo.resolve(".gitattributes"), trackedAttributes);
725 + Files.deleteIfExists(gitleaksLog);
726 + var keyModified = Files.getLastModifiedTime(repo.resolve(".git/dotfiles-aes.key"));
727 + var blockedEnv = new HashMap<>(linkEnv);
728 + blockedEnv.put("FAKE_GITLEAKS_EXIT", "1");
729 + if (!bootExpectFail(fixture, blockedEnv, "pre-commit").contains("Gitleaks blocked the operation")) fail("gitleaks-finding-not-rejected");
730 + Files.deleteIfExists(gitleaksLog);
731 + var base = run(repo, env, "git", "rev-parse", "HEAD").trim();
732 + var zero = "0".repeat(base.length());
733 + runInput(repo, linkEnv, "refs/heads/main " + base + " refs/heads/main " + zero + "\n", pushHook.toString());
734 + var pushArguments = Files.readString(gitleaksLog);
735 + if (!pushArguments.contains("--full-history") || !pushArguments.contains(base)) fail("pre-push-new-ref-range");
736 + Files.delete(gitleaksLog);
737 + var pushBlockedEnv = new HashMap<>(linkEnv);
738 + pushBlockedEnv.put("FAKE_GITLEAKS_EXIT", "1");
739 + if (!runInputExpectFail(repo, pushBlockedEnv, "refs/heads/main " + base + " refs/heads/main " + zero + "\n", pushHook.toString()).contains("Gitleaks blocked the operation")) fail("pre-push-gitleaks-failure");
740 + Files.deleteIfExists(gitleaksLog);
741 + runInput(repo, linkEnv, "refs/heads/main " + zero + " refs/heads/main " + base + "\n", pushHook.toString());
742 + if (Files.exists(gitleaksLog)) fail("pre-push-deletion-scan");
743 + Files.deleteIfExists(gitleaksLog);
744 + var unchanged = java.nio.file.attribute.FileTime.from(Instant.parse("2000-01-01T00:00:00Z"));
745 + Files.setLastModifiedTime(hook, unchanged);
746 + Files.setLastModifiedTime(pushHook, unchanged);
747 + var configModified = Files.getLastModifiedTime(repo.resolve(".git/config"));
748 + var aesToolModified = Files.getLastModifiedTime(repo.resolve(".git/dotfiles-aes.java"));
749 + var attributesModified = Files.getLastModifiedTime(repo.resolve(".gitattributes"));
750 + var secretModified = Files.getLastModifiedTime(repo.resolve("secret.txt"));
751 + Files.deleteIfExists(aesLog);
752 + boot(fixture, linkEnv, "link");
753 + if (Files.exists(aesLog)) fail("link-warm-noop-invoked-aes");
754 + if (!Files.getLastModifiedTime(hook).equals(unchanged) || !Files.getLastModifiedTime(pushHook).equals(unchanged)) fail("link-hook-not-idempotent");
755 + if (!Files.getLastModifiedTime(repo.resolve(".git/config")).equals(configModified)) fail("link-config-not-idempotent");
756 + if (!Files.getLastModifiedTime(repo.resolve(".git/dotfiles-aes.java")).equals(aesToolModified)) fail("link-aes-tool-not-idempotent");
757 + if (!Files.getLastModifiedTime(repo.resolve(".gitattributes")).equals(attributesModified)) fail("link-attributes-not-idempotent");
758 + if (!Files.getLastModifiedTime(repo.resolve("secret.txt")).equals(secretModified)) fail("link-secret-not-idempotent");
759 + if (!Files.getLastModifiedTime(repo.resolve(".git/dotfiles-aes.key")).equals(keyModified)) fail("link-key-not-idempotent");
760 + run(repo, env, "git", "config", "--local", "filter.dotfiles-aes.clean", "broken");
761 + Files.writeString(repo.resolve(".gitattributes"), "");
762 + Files.setPosixFilePermissions(repo.resolve(".git/dotfiles-aes.key"), PosixFilePermissions.fromString("rw-r--r--"));
763 + boot(fixture, linkEnv, "link");
764 + if (!Files.readString(repo.resolve(".git/config")).equals(configured)) fail("link-filter-not-repaired");
765 + if (!Files.readString(repo.resolve(".gitattributes")).equals(trackedAttributes)) fail("link-attributes-not-repaired");
766 + if (!Files.getPosixFilePermissions(repo.resolve(".git/dotfiles-aes.key")).equals(PosixFilePermissions.fromString("rw-------"))) fail("link-key-mode-not-repaired");
767 + Files.writeString(hook, "#!/bin/sh\n# Managed by dorkfiles bootstripper.java\nbroken\n");
768 + Files.setPosixFilePermissions(hook, PosixFilePermissions.fromString("rw-r--r--"));
769 + boot(fixture, linkEnv, "link");
770 + if (!Files.isExecutable(hook) || !Files.readString(hook).contains("exec java bootstripper.java pre-commit")) fail("link-hook-not-repaired");
771 + var managed = Files.readString(hook);
772 + Files.writeString(hook, "#!/bin/sh\nexit 0\n");
773 + if (!bootExpectFail(fixture, linkEnv, "link").contains("Refusing to replace unmanaged Git hook")) fail("link-unmanaged-hook-not-rejected");
774 + if (!Files.readString(hook).equals("#!/bin/sh\nexit 0\n")) fail("link-unmanaged-hook-changed");
775 + Files.writeString(hook, managed);
776 + Files.setPosixFilePermissions(hook, PosixFilePermissions.fromString("rwxr-xr-x"));
777 + var symlinkTarget = home.resolve("unmanaged-hook");
778 + Files.writeString(symlinkTarget, "unmanaged\n");
779 + Files.delete(hook);
780 + Files.createSymbolicLink(hook, symlinkTarget);
781 + if (!bootExpectFail(fixture, linkEnv, "link").contains("Refusing to replace non-file Git hook")) fail("link-symlink-hook-not-rejected");
782 + if (!Files.readString(symlinkTarget).equals("unmanaged\n")) fail("link-symlink-target-changed");
783 + Files.delete(hook);
784 + Files.writeString(hook, managed);
785 + Files.setPosixFilePermissions(hook, PosixFilePermissions.fromString("rwxr-xr-x"));
786 + if (!Files.isSymbolicLink(home.resolve("dummy.txt")) || !Files.isSameFile(home.resolve("dummy.txt"), repo.resolve("dummy.txt"))) fail("link-target");
787 + if (!Files.readString(repo.resolve("secret.txt")).equals(secret)) fail("link-secret-changed");
788 + if (!Files.readString(repo.resolve(".gitattributes")).equals(trackedAttributes)) fail("link-tracked-attributes-changed");
789 + if (!Files.readString(repo.resolve(".git/config")).equals(configured)) fail("link-config-changed");
790 + if (!Files.readString(repo.resolve(".git/info/attributes")).equals(localAttributes)) fail("link-local-attributes-changed");
791 + if (!Files.isReadable(repo.resolve(".git/dotfiles-aes.key"))) fail("link-key-missing");
792 + run(repo, env, "git", "config", "--local", "core.hooksPath", "custom-hooks");
793 + boot(fixture, linkEnv, "link");
794 + var customHooks = Path.of(run(repo, env, "git", "rev-parse", "--path-format=absolute", "--git-path", "hooks").trim());
795 + if (!Files.isExecutable(customHooks.resolve("pre-commit")) || !Files.isExecutable(customHooks.resolve("pre-push"))) fail("custom-hooks-path");
796 + run(repo, env, "git", "config", "--local", "--unset", "core.hooksPath");
797 + run(repo, env, "git", "config", "--local", "extensions.worktreeConfig", "true");
798 + run(repo, env, "git", "config", "--worktree", "core.hooksPath", "worktree-hooks");
799 + boot(fixture, linkEnv, "link");
800 + var worktreeHooks = Path.of(run(repo, env, "git", "rev-parse", "--path-format=absolute", "--git-path", "hooks").trim());
801 + if (!Files.isExecutable(worktreeHooks.resolve("pre-commit")) || !Files.isExecutable(worktreeHooks.resolve("pre-push"))) fail("worktree-hooks-path");
802 + run(repo, env, "git", "config", "--worktree", "--unset", "core.hooksPath");
279 803 Files.delete(home.resolve("dummy.txt"));
281 805 var manifest = repo.resolve("mini.symlinks");
282 806 var original = Files.readString(manifest);
283 807 for (var invalid : List.of("missing.txt\n~/missing.txt\n", "dummy.txt\n", "dummy.txt\n~/dummy.txt\n", "dummy.txt\n/etc/dotfiles-test\n")) {
284 808 Files.writeString(manifest, original + invalid);
285 - runExpectFail(repo, linkEnv, "mise", "run", "link");
809 + bootExpectFail(fixture, linkEnv, "link");
286 810 if (Files.exists(home.resolve("dummy.txt"), LinkOption.NOFOLLOW_LINKS)) fail("link-before-validation");
288 812 Files.writeString(manifest, original);
289 - ok("link-only-and-manifest-validation");
813 + boot(fixture, "init-crypto");
814 + boot(fixture, "setup-crypto");
815 + run(repo, env, "git", "add", ".dotfiles-aes-salt", ".gitattributes", ".secrets", "secret.txt", "tools/aes.java");
816 + run(repo, env, "git", "-c", "core.hooksPath=/dev/null", "commit", "--quiet", "-m", "configure crypto");
817 + Files.writeString(repo.resolve("secret.txt"), "valid staged secret\n");
818 + run(repo, env, "git", "add", "secret.txt");
819 + boot(fixture, "pre-commit");
820 + run(repo, env, "git", "reset", "--quiet", "HEAD", "--", "secret.txt");
821 + run(repo, env, "git", "restore", "secret.txt");
823 + var outsideSecret = home.resolve("outside-secret");
824 + Files.writeString(outsideSecret, "outside\n");
825 + Files.setPosixFilePermissions(outsideSecret, PosixFilePermissions.fromString("rw-r--r--"));
826 + Files.createDirectories(repo.resolve("ssh"));
827 + Files.createSymbolicLink(repo.resolve("ssh/test.key"), outsideSecret);
828 + Files.writeString(repo.resolve(".secrets"), "secret.txt\nssh/test.key\n");
829 + if (!bootExpectFail(fixture, linkEnv, "link").contains("Secret path must not contain symlinks")) fail("secret-symlink-not-rejected");
830 + if (!Files.readString(outsideSecret).equals("outside\n") || !Files.getPosixFilePermissions(outsideSecret).equals(PosixFilePermissions.fromString("rw-r--r--"))) fail("secret-symlink-mutated-target");
831 + Files.delete(repo.resolve("ssh/test.key"));
832 + Files.delete(repo.resolve("ssh"));
833 + var canceledOutside = home.resolve("canceled-outside");
834 + Files.createDirectories(canceledOutside.resolve("child"));
835 + var canceledTarget = canceledOutside.resolve("victim.key");
836 + Files.writeString(canceledTarget, "canceled outside\n");
837 + Files.setPosixFilePermissions(canceledTarget, PosixFilePermissions.fromString("rw-r--r--"));
838 + Files.createDirectories(repo.resolve("ssh"));
839 + Files.createSymbolicLink(repo.resolve("ssh/jump"), canceledOutside.resolve("child"));
840 + Files.writeString(repo.resolve(".secrets"), "secret.txt\nssh/jump/../victim.key\n");
841 + if (!bootExpectFail(fixture, linkEnv, "link").contains("Secret path must not contain parent components")) fail("secret-canceled-component-not-rejected");
842 + if (!Files.readString(canceledTarget).equals("canceled outside\n") || !Files.getPosixFilePermissions(canceledTarget).equals(PosixFilePermissions.fromString("rw-r--r--"))) fail("secret-canceled-component-mutated-target");
843 + Files.delete(repo.resolve("ssh/jump"));
844 + Files.delete(repo.resolve("ssh"));
845 + var outsideDirectory = home.resolve("outside-directory");
846 + Files.createDirectories(outsideDirectory);
847 + Files.writeString(outsideDirectory.resolve("secret.txt"), "outside parent\n");
848 + Files.createSymbolicLink(repo.resolve("nested"), outsideDirectory);
849 + Files.writeString(repo.resolve(".secrets"), "secret.txt\nnested/secret.txt\n");
850 + if (!bootExpectFail(fixture, linkEnv, "link").contains("Secret path must not contain symlinks")) fail("secret-parent-symlink-not-rejected");
851 + if (!Files.readString(outsideDirectory.resolve("secret.txt")).equals("outside parent\n")) fail("secret-parent-symlink-mutated-target");
852 + Files.delete(repo.resolve("nested"));
853 + var listedDirectory = repo.resolve("secret-directory");
854 + Files.createDirectories(listedDirectory);
855 + Files.createSymbolicLink(listedDirectory.resolve("nested"), outsideDirectory);
856 + Files.writeString(repo.resolve(".secrets"), "secret.txt\nsecret-directory\n");
857 + if (!bootExpectFail(fixture, linkEnv, "link").contains("Secret path must name a regular file")) fail("secret-directory-not-rejected");
858 + if (!Files.readString(outsideDirectory.resolve("secret.txt")).equals("outside parent\n")) fail("secret-directory-mutated-descendant");
859 + Files.writeString(repo.resolve(".secrets"), ":(top)secret-directory/\n");
860 + if (!bootExpectFail(fixture, linkEnv, "link").contains("invalid secret path")) fail("secret-pathspec-magic-not-rejected");
861 + if (!Files.readString(outsideDirectory.resolve("secret.txt")).equals("outside parent\n")) fail("secret-pathspec-magic-mutated-descendant");
862 + Files.delete(listedDirectory.resolve("nested"));
863 + Files.delete(listedDirectory);
864 + run(repo, env, "git", "restore", ".secrets");
866 + var filterBeforeWorktree = run(repo, env, "git", "config", "--local", "--get", "filter.dotfiles-aes.clean").strip();
867 + var configBeforeWorktree = Files.readString(repo.resolve(".git/config"));
868 + var configTimeBeforeWorktree = Files.getLastModifiedTime(repo.resolve(".git/config"));
869 + var linkedHome = home.resolve("linked-home");
870 + var linked = linkedHome.resolve("repo");
871 + Files.createDirectories(linkedHome);
872 + run(repo, env, "git", "worktree", "add", "--quiet", "-b", "linked-test", linked.toString());
873 + var linkedEnv = new HashMap<>(linkEnv);
874 + linkedEnv.put("HOME", linkedHome.toString());
875 + linkedEnv.put("JAVA_TOOL_OPTIONS", "-Duser.home=" + linkedHome);
876 + bootAt(fixture, linkedEnv, "link", linked);
877 + bootAt(fixture, linkedEnv, "pre-commit", linked);
878 + boot(fixture, "link");
879 + boot(fixture, "pre-commit");
880 + var sharedFilter = run(repo, env, "git", "config", "--local", "--get", "filter.dotfiles-aes.clean").strip();
881 + var common = Path.of(run(repo, env, "git", "rev-parse", "--git-common-dir").strip());
882 + if (!common.isAbsolute()) common = repo.resolve(common).normalize();
883 + var expectedTool = "'" + common.resolve("dotfiles-aes.java").toAbsolutePath() + "'";
884 + var expectedKey = "'" + common.resolve("dotfiles-aes.key").toAbsolutePath() + "'";
885 + if (!sharedFilter.equals("java " + expectedTool + " encrypt --key-file " + expectedKey) || sharedFilter.contains(linked.toString())) fail("worktree-dependent-filter-command");
886 + if (!sharedFilter.equals(filterBeforeWorktree) || !Files.readString(repo.resolve(".git/config")).equals(configBeforeWorktree) || !Files.getLastModifiedTime(repo.resolve(".git/config")).equals(configTimeBeforeWorktree)) fail("worktree-rewrote-filter-config");
887 + run(repo, env, "git", "worktree", "remove", "--force", linked.toString());
888 + ok("link-hooks-and-manifest-validation");
292 - static void cryptoRestoreChecks(Path repo, Map<String, String> env) throws Exception {
891 + static void cryptoRestoreChecks(Fixture fixture) throws Exception {
892 + var repo = fixture.repo();
893 + var env = fixture.env();
293 894 var first = repo.resolve("secret.txt");
294 895 var second = repo.resolve("incoming-secret.txt");
295 896 var firstPlain = Files.readAllBytes(first);
296 897 var secondPlain = Files.readAllBytes(second);
297 - run(repo, env, "java", "tools/aes.java", "encrypt", "--key-file", ".git/dotfiles-aes.key", "secret.txt", "encrypted-secret.txt");
898 + run(repo, env, fixture.home().resolve("bin/test-aes").toString(), "encrypt", "--key-file", ".git/dotfiles-aes.key", "secret.txt", "encrypted-secret.txt");
298 899 var encrypted = Files.readAllBytes(repo.resolve("encrypted-secret.txt"));
299 900 Files.delete(repo.resolve("encrypted-secret.txt"));
300 901 Files.write(first, encrypted);
301 902 var index = Files.readAllBytes(repo.resolve(".git/index"));
302 - run(repo, env, "mise", "run", "setup-crypto");
903 + boot(fixture, "setup-crypto");
303 904 if (!Arrays.equals(Files.readAllBytes(first), firstPlain)) fail("explicit-crypto-decryption");
304 905 if (!Arrays.equals(Files.readAllBytes(repo.resolve(".git/index")), index)) fail("crypto-changed-index");
305 906 var modified = Files.getLastModifiedTime(first);
306 - run(repo, env, "mise", "run", "setup-crypto");
907 + boot(fixture, "setup-crypto");
307 908 if (!Files.getLastModifiedTime(first).equals(modified)) fail("crypto-rewrote-plaintext");
309 910 for (var change : List.of("plaintext", "ciphertext", "deleted", "staged", "staged-deletion")) {
313 914 case "plaintext", "staged" -> Files.writeString(second, "local change\n");
314 915 case "ciphertext" -> Files.write(second, encrypted);
315 916 case "deleted" -> Files.delete(second);
316 - case "staged-deletion" -> run(repo, "git", "rm", "--cached", "--quiet", "incoming-secret.txt");
917 + case "staged-deletion" -> run(repo, env, "git", "rm", "--cached", "--quiet", "incoming-secret.txt");
318 - if (change.equals("staged")) run(repo, "git", "add", "incoming-secret.txt");
919 + if (change.equals("staged")) run(repo, env, "git", "add", "incoming-secret.txt");
319 920 var before = Files.exists(second) ? Files.readAllBytes(second) : null;
320 921 index = Files.readAllBytes(repo.resolve(".git/index"));
321 - if (!runExpectFail(repo, env, "mise", "run", "setup-crypto").contains("Refusing to restore locally changed secret")) fail("crypto-accepted:" + change);
922 + var refusal = restoreExpectFail(fixture);
923 + if (!refusal.contains("Refusing to restore locally changed secret")) fail("crypto-accepted:" + change);
322 924 if (!Arrays.equals(Files.readAllBytes(first), encrypted)) fail("crypto-partial-restore:" + change);
323 925 if (before == null ? Files.exists(second) : !Arrays.equals(Files.readAllBytes(second), before)) fail("crypto-overwrote:" + change);
324 926 if (!Arrays.equals(Files.readAllBytes(repo.resolve(".git/index")), index)) fail("crypto-changed-index:" + change);
325 - run(repo, "git", "reset", "--quiet", "HEAD", "--", "incoming-secret.txt");
927 + run(repo, env, "git", "reset", "--quiet", "HEAD", "--", "incoming-secret.txt");
326 928 ok("crypto-refuses:" + change);
328 930 var linkEnv = new HashMap<>(env);
329 931 linkEnv.put("DOTFILES_SYMLINKS", "mini");
330 - run(repo, linkEnv, "mise", "run", "link");
331 - if (!Arrays.equals(Files.readAllBytes(first), encrypted)) fail("link-decrypted-secret");
332 - run(repo, linkEnv, "java", "bootstripper.java", "clean");
932 + boot(fixture, linkEnv, "link");
933 + if (!Arrays.equals(Files.readAllBytes(first), firstPlain)) fail("link-did-not-decrypt-secret");
934 + boot(fixture, linkEnv, "clean");
935 + Files.deleteIfExists(repo.resolve(".git/hooks/pre-commit"));
936 + Files.deleteIfExists(repo.resolve(".git/hooks/pre-push"));
333 937 Files.write(first, firstPlain);
334 938 Files.write(second, secondPlain);
335 939 ok("explicit-crypto-preserves-local-changes");
351 955 return target.startsWith("~/") ? home.resolve(target.substring(2)) : Path.of(target);
958 + static Path findExecutable(String name) {
959 + var path = System.getenv("PATH");
960 + if (path == null) return null;
961 + for (var directory : path.split(java.util.regex.Pattern.quote(File.pathSeparator))) {
962 + var candidate = Path.of(directory, name);
963 + if (Files.isExecutable(candidate)) return candidate.toAbsolutePath();
965 + return null;
354 968 static String rootless() throws IOException {
355 969 var p = Path.of("/proc/self/uid_map");
356 970 if (!Files.exists(p)) return "unknown";
370 984 static void log(String message) { System.out.println(message); System.out.flush(); }
371 985 static void fail(String what) { throw new RuntimeException("FAIL:" + what); }
987 + static final class CommandFailed extends RuntimeException {
988 + CommandFailed(String message) { super(message); }
990 + static final class CommandTimedOut extends RuntimeException {
991 + CommandTimedOut(String message) { super(message); }
373 994 static String run(Path dir, String... cmd) throws Exception { return run(dir, Map.of(), cmd); }
374 995 static String run(Path dir, Map<String, String> env, String... cmd) throws Exception {
375 - var pb = new ProcessBuilder(cmd);
376 - if (dir != null) pb.directory(dir.toFile());
377 - pb.environment().putAll(env);
378 - var p = pb.redirectErrorStream(true).start();
379 - var out = new String(p.getInputStream().readAllBytes());
380 - var code = p.waitFor();
381 - if (code != 0) throw new RuntimeException(String.join(" ", cmd) + "\n" + out);
382 - return out;
996 + return runInput(dir, env, null, cmd);
384 - static void runInherit(Path dir, String... cmd) throws Exception {
385 - var pb = new ProcessBuilder(cmd);
998 + static String runInput(Path dir, Map<String, String> env, String input, String... cmd) throws Exception {
999 + var launch = new ArrayList<String>();
1000 + if (SETSID != null) {
1001 + launch.add(SETSID.toString());
1002 + launch.add("--");
1004 + launch.addAll(List.of(cmd));
1005 + var pb = new ProcessBuilder(launch);
386 1006 if (dir != null) pb.directory(dir.toFile());
387 - var code = pb.inheritIO().start().waitFor();
388 - if (code != 0) throw new RuntimeException(String.join(" ", cmd) + " exited " + code);
1007 + applyEnvironment(pb, env);
1008 + var started = System.nanoTime();
1009 + var p = pb.redirectErrorStream(true).start();
1010 + var descendants = new HashSet<ProcessHandle>();
1011 + if (SETSID != null) ACTIVE_PROCESS_GROUPS.add(p.pid());
1012 + try {
1013 + var output = java.util.concurrent.CompletableFuture.supplyAsync(() -> {
1014 + try { return p.getInputStream().readAllBytes(); }
1015 + catch (IOException problem) { throw new UncheckedIOException(problem); }
1016 + });
1017 + var stdin = java.util.concurrent.CompletableFuture.runAsync(() -> {
1018 + try (var stream = p.getOutputStream()) {
1019 + if (input != null) stream.write(input.getBytes());
1020 + } catch (IOException problem) { throw new UncheckedIOException(problem); }
1021 + });
1022 + var deadline = System.nanoTime() + Duration.ofSeconds(90).toNanos();
1023 + while (p.isAlive() && System.nanoTime() < deadline) {
1024 + if (stdin.isCompletedExceptionally()) stdin.join();
1025 + p.descendants().forEach(descendants::add);
1026 + p.waitFor(10, java.util.concurrent.TimeUnit.MILLISECONDS);
1028 + p.descendants().forEach(descendants::add);
1029 + if (p.isAlive()) throw new CommandTimedOut("timed out: " + String.join(" ", cmd));
1030 + try {
1031 + stdin.get(1, java.util.concurrent.TimeUnit.SECONDS);
1032 + } catch (java.util.concurrent.TimeoutException problem) {
1033 + throw new CommandTimedOut("timed out writing input: " + String.join(" ", cmd));
1035 + byte[] bytes;
1036 + var drainTimedOut = false;
1037 + try {
1038 + bytes = output.get(1, java.util.concurrent.TimeUnit.SECONDS);
1039 + } catch (java.util.concurrent.TimeoutException problem) {
1040 + drainTimedOut = true;
1041 + terminate(p, descendants);
1042 + bytes = output.get(5, java.util.concurrent.TimeUnit.SECONDS);
1044 + var out = new String(bytes);
1045 + var elapsed = Duration.ofNanos(System.nanoTime() - started).toMillis();
1046 + if (elapsed >= 2_000) log("slow:" + Path.of(cmd[0]).getFileName() + ":" + elapsed + "ms");
1047 + if (p.exitValue() != 0) throw new CommandFailed(String.join(" ", cmd) + "\n" + out);
1048 + if (drainTimedOut) throw new CommandTimedOut("timed out draining output: " + String.join(" ", cmd));
1049 + return out;
1050 + } catch (Exception | Error problem) {
1051 + terminate(p, descendants);
1052 + throw problem;
1053 + } finally {
1054 + killGroup(p.pid());
1055 + ACTIVE_PROCESS_GROUPS.remove(p.pid());
1058 + static void applyEnvironment(ProcessBuilder builder, Map<String, String> environment) {
1059 + if ("1".equals(environment.get(CLEAN_ENV))) builder.environment().clear();
1060 + for (var entry : environment.entrySet())
1061 + if (!entry.getKey().equals(CLEAN_ENV)) builder.environment().put(entry.getKey(), entry.getValue());
1064 + static void killGroup(long processGroup) {
1065 + if (SETSID == null || KILL == null) return;
1066 + try {
1067 + new ProcessBuilder(KILL.toString(), "-KILL", "--", "-" + processGroup)
1068 + .redirectOutput(ProcessBuilder.Redirect.DISCARD)
1069 + .redirectError(ProcessBuilder.Redirect.DISCARD)
1070 + .start().waitFor(5, java.util.concurrent.TimeUnit.SECONDS);
1071 + } catch (Exception ignored) {}
1074 + static void terminate(Process process, Collection<ProcessHandle> descendants) {
1075 + process.descendants().forEach(descendants::add);
1076 + killGroup(process.pid());
1077 + for (var descendant : descendants) descendant.destroyForcibly();
1078 + process.destroyForcibly();
1081 + static void runInherit(Path dir, String... cmd) throws Exception {
1082 + var launch = new ArrayList<String>();
1083 + if (SETSID != null) {
1084 + launch.add(SETSID.toString());
1085 + launch.add("--");
1087 + launch.addAll(List.of(cmd));
1088 + var builder = new ProcessBuilder(launch);
1089 + if (dir != null) builder.directory(dir.toFile());
1090 + var process = builder.inheritIO().start();
1091 + var descendants = new HashSet<ProcessHandle>();
1092 + if (SETSID != null) ACTIVE_PROCESS_GROUPS.add(process.pid());
1093 + try {
1094 + if (!process.waitFor(10, java.util.concurrent.TimeUnit.MINUTES))
1095 + throw new CommandTimedOut("timed out: " + String.join(" ", cmd));
1096 + if (process.exitValue() != 0)
1097 + throw new CommandFailed(String.join(" ", cmd) + " exited " + process.exitValue());
1098 + } catch (Exception | Error problem) {
1099 + terminate(process, descendants);
1100 + throw problem;
1101 + } finally {
1102 + killGroup(process.pid());
1103 + ACTIVE_PROCESS_GROUPS.remove(process.pid());
391 1107 static String runExpectFail(Path dir, Map<String, String> env, String... cmd) throws Exception {
1108 + return runInputExpectFail(dir, env, null, cmd);
1111 + static String runInputExpectFail(Path dir, Map<String, String> env, String input, String... cmd) throws Exception {
393 - var out = run(dir, env, cmd);
1113 + var out = runInput(dir, env, input, cmd);
394 1114 throw new AssertionError("expected failure: " + String.join(" ", cmd) + "\n" + out);
395 - } catch (RuntimeException error) {
1115 + } catch (CommandFailed error) {
396 1116 return error.getMessage();