Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Cause from "effect/Cause";
4import * as Clock from "effect/Clock";
5import * as ConfigProvider from "effect/ConfigProvider";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
16import { signWithJsign } from "./windows-jsign.ts";
17
18const UNSIGNED = "MZ unsigned payload";
19const TRANSIENT_CHAIN =
20 "jsign: Unable to retrieve the certificate chain 'acct/profile'\nCaused by: java.io.IOException: InternalError - An internal error has occurred.\n";
21const TRANSIENT_SIGN =
22 "jsign: Couldn't sign t3.exe\nCaused by: java.security.GeneralSecurityException: java.io.IOException: InternalError - An internal error has occurred.\n";
23const BAD_SECRET =
24 "jsign: Unable to retrieve the certificate chain 'acct/profile'\nCaused by: java.io.IOException: AADSTS7000215: Invalid client secret provided.\n";
25
26/** What the stub does with the file jsign was given: sign it, or write junk and fail. */
27type Reply = { readonly exitCode: number; readonly stderr?: string; readonly write?: string };
28
29/** Stands in for jsign. Records the bytes it received and applies each reply in turn. */
30function stubJsign(replies: ReadonlyArray<Reply>) {
31 const inputs: Array<{ readonly path: string; readonly content: string }> = [];
32 const spawner = ChildProcessSpawner.make((command) =>
33 Effect.gen(function* () {
34 const fs = yield* FileSystem.FileSystem;
35 const args = ChildProcess.isStandardCommand(command) ? command.args.map(String) : [];
36 const target = args.at(-1)!;
37 inputs.push({ path: target, content: yield* fs.readFileString(target) });
38 const reply = replies[inputs.length - 1] ?? replies.at(-1)!;
39 if (reply.write !== undefined) yield* fs.writeFileString(target, reply.write);
40 return ChildProcessSpawner.makeHandle({
41 pid: ChildProcessSpawner.ProcessId(1),
42 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(reply.exitCode)),
43 exitStatus: Effect.succeed({
44 _tag: "Exited",
45 code: ChildProcessSpawner.ExitCode(reply.exitCode),
46 }),
47 isRunning: Effect.succeed(false),
48 kill: () => Effect.void,
49 unref: Effect.succeed(Effect.void),
50 stdin: Sink.drain,
51 stdout: Stream.empty,
52 stderr: reply.stderr ? Stream.make(new TextEncoder().encode(reply.stderr)) : Stream.empty,
53 all: Stream.empty,
54 getInputFd: () => Sink.drain,
55 getOutputFd: () => Stream.empty,
56 });
57 }).pipe(Effect.provide(NodeServices.layer), Effect.orDie),
58 );
59 return { inputs, spawner };
60}
61
62const signed = (content: string): Reply => ({ exitCode: 0, write: `${content}+signature` });
63
64const runSign = Effect.fn("test.runSign")(function* (replies: ReadonlyArray<Reply>) {
65 const fs = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-jsign-" });
68 const file = path.join(dir, "t3.exe");
69 yield* fs.writeFileString(file, UNSIGNED);
70 const stub = stubJsign(replies);
71 const sleeps: Array<number> = [];
72 const clock = yield* Clock.Clock;
73 const exit = yield* signWithJsign(file).pipe(
74 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, stub.spawner),
75 // Records the backoff instead of waiting it out.
76 Effect.provideService(Clock.Clock, {
77 ...clock,
78 sleep: (duration) => Effect.sync(() => sleeps.push(Duration.toSeconds(duration))),
79 }),
80 Effect.provide(
81 ConfigProvider.layer(
82 ConfigProvider.fromEnv({
83 env: {
84 AZURE_TRUSTED_SIGNING_ENDPOINT: "https://eus.codesigning.azure.net/",
85 AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: "acct",
86 AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: "profile",
87 },
88 }),
89 ),
90 ),
91 Effect.exit,
92 );
93 return {
94 ok: Exit.isSuccess(exit),
95 error: Exit.isFailure(exit)
96 ? Option.getOrUndefined(Cause.findErrorOption(exit.cause))
97 : undefined,
98 sleeps,
99 inputs: stub.inputs,
100 // jsign only ever sees a disposable copy, never the file itself.
101 signedInPlace: stub.inputs.some((input) => input.path === file),
102 content: yield* fs.readFileString(file),
103 // Only the original file is left: every attempt's copy is cleaned up.
104 entries: yield* fs.readDirectory(dir),
105 };
106});
107
108it.layer(NodeServices.layer)("signWithJsign", (it) => {
109 it.effect("retries transient Azure errors on a fresh copy and keeps only the signed file", () =>
110 Effect.gen(function* () {
111 const result = yield* runSign([
112 { exitCode: 1, stderr: TRANSIENT_CHAIN },
113 // A partial write must not reach the next attempt or the original.
114 { exitCode: 1, stderr: TRANSIENT_SIGN, write: "MZ half-written" },
115 signed(UNSIGNED),
116 ]);
117 assert.isTrue(result.ok);
118 assert.strictEqual(result.content, `${UNSIGNED}+signature`);
119 assert.deepStrictEqual(
120 result.inputs.map((input) => input.content),
121 [UNSIGNED, UNSIGNED, UNSIGNED],
122 );
123 assert.isFalse(result.signedInPlace);
124 assert.deepStrictEqual(result.sleeps, [5, 10]);
125 assert.deepStrictEqual(result.entries, ["t3.exe"]);
126 }),
127 );
128
129 it.effect("fails once without retrying on errors that are not transient", () =>
130 Effect.gen(function* () {
131 for (const reply of [
132 { exitCode: 1, stderr: BAD_SECRET },
133 { exitCode: 1, stderr: "jsign: Unsupported file: t3.exe\n", write: "MZ half-written" },
134 ]) {
135 const result = yield* runSign([reply, signed(UNSIGNED)]);
136 assert.strictEqual(result.error?._tag, "JsignFailedError");
137 assert.isFalse(result.error?._tag === "JsignFailedError" && result.error.transient);
138 assert.strictEqual(result.inputs.length, 1);
139 assert.deepStrictEqual(result.sleeps, []);
140 assert.strictEqual(result.content, UNSIGNED);
141 assert.deepStrictEqual(result.entries, ["t3.exe"]);
142 }
143 }),
144 );
145
146 it.effect("gives up after three retries and leaves the input unsigned", () =>
147 Effect.gen(function* () {
148 const result = yield* runSign([{ exitCode: 1, stderr: TRANSIENT_SIGN, write: "MZ junk" }]);
149 assert.isTrue(result.error?._tag === "JsignFailedError" && result.error.transient);
150 assert.strictEqual(result.inputs.length, 4);
151 assert.deepStrictEqual(result.sleeps, [5, 10, 20]);
152 assert.strictEqual(result.content, UNSIGNED);
153 assert.deepStrictEqual(result.entries, ["t3.exe"]);
154 }),
155 );
156});