2 2 import java.
nio.
file.
*;
3 +import java.
nio.
file.
attribute.
PosixFilePermissions;
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();
14 + Runtime.getRuntime().addShutdownHook(
new Thread(()
-> ACTIVE_PROCESS_GROUPS.forEach(dotfiles_integration_test::killGroup),
"dotfiles-test-process-cleanup"));
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();
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]);
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");
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"));
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());
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();
101 128 System.out.println(
"RESULT:ok");
104 131 static void miseShellSmoke() throws
Exception {
105 - var smoke
= "mise-shell-smoke";
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\"); 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");
132 + var temporary
= Files.createTempDirectory(
"dotfiles-mise-shell-");
133 + var smoke
= temporary.resolve(
"smoke");
134 + var shell
= root.resolve(
"scripts/mise_shell.java").toString();
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\"); 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");
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");
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;
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");
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");
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();
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());
209 + if (
!process.waitFor(
10,
java.
util.
concurrent.
TimeUnit.
SECONDS)) process.destroyForcibly();
210 + assertProcessDead(childPid,
"descendant-survived-" + name
+ "-cancellation");
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);
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");
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");
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);
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");
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");
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$");
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");
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));
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");
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();
527 + var fastAes
= bin.resolve(
"test-aes");
528 + Files.writeString(fastAes,
""" 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 538 + decrypt() { [
"$(head -c 6 "$
1")" = DFAES1 ]
|| { echo
'invalid dotfiles AES blob' >&2;
return 1; }; tail
-c
+7 "$1"; }
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;;
545 + if [
"$#" -eq
0 ]; then cat
> "$tmp/in"; decrypt
"$tmp/in";
else [
! -e
"$2" ]; decrypt
"$1" > "$2"; fi;;
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" 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 {
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");
209 - cryptoRestoreChecks(repo, env);
615 + if (scope
== CryptoScope.
ALL || scope
== CryptoScope.
RESTORE) cryptoRestoreChecks(fixture);
616 + if (scope
== CryptoScope.
RESTORE) {
617 + ok(
"crypto-restore");
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");
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();
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);
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());
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());
1013 + var output
= java.
util.
concurrent.
CompletableFuture.supplyAsync(()
-> {
1014 + try {
return p.getInputStream().readAllBytes(); }
1015 + catch (
IOException problem) {
throw new UncheckedIOException(problem); }
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); }
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));
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));
1036 + var drainTimedOut
= false;
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));
1050 + }
catch (
Exception |
Error problem) {
1051 + terminate(p, descendants);
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;
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());
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());
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);
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();