Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Sink from "effect/Sink";
7import * as Stream from "effect/Stream";
8import * as PlatformError from "effect/PlatformError";
9import { ChildProcessSpawner } from "effect/unstable/process";
10
11import {
12 ChromiumKeyError,
13 decodeWindowsWrappedKey,
14 readLinuxSecret,
15 resolveChromiumKeys,
16 unwrapWindowsDpapiKey,
17} from "./ChromiumKeys.ts";
18import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts";
19
20type CapturedCommand = {
21 readonly command: string;
22 readonly args: ReadonlyArray<string>;
23 readonly options: {
24 readonly stdin?: string;
25 readonly env?: Readonly<Record<string, string | undefined>>;
26 };
27};
28
29const helperLayer = (input: {
30 readonly stdout?: string;
31 readonly stderr?: string;
32 readonly stdoutStream?: Stream.Stream<Uint8Array>;
33 readonly stderrStream?: Stream.Stream<Uint8Array>;
34 readonly exitCode?: number;
35 readonly spawnError?: PlatformError.PlatformError;
36 readonly capture?: (command: CapturedCommand) => void;
37}) =>
38 Layer.merge(
39 Layer.succeed(LinuxBrowserSecretPath, "/bundled/browser-secret/t3-browser-secret"),
40 Layer.succeed(
41 ChildProcessSpawner.ChildProcessSpawner,
42 ChildProcessSpawner.make((command) =>
43 input.spawnError
44 ? Effect.fail(input.spawnError)
45 : Effect.succeed(
46 ChildProcessSpawner.makeHandle({
47 pid: ChildProcessSpawner.ProcessId(1),
48 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
49 isRunning: Effect.succeed(false),
50 kill: () => Effect.void,
51 unref: Effect.succeed(Effect.void),
52 stdin: Sink.drain,
53 stdout: input.stdoutStream ?? Stream.encodeText(Stream.make(input.stdout ?? "")),
54 stderr: input.stderrStream ?? Stream.encodeText(Stream.make(input.stderr ?? "")),
55 all: Stream.empty,
56 getInputFd: () => Sink.drain,
57 getOutputFd: () => Stream.empty,
58 }),
59 ).pipe(
60 Effect.tap(() => Effect.sync(() => input.capture?.(command as CapturedCommand))),
61 ),
62 ),
63 ),
64 );
65
66describe("Linux Chromium secrets", () => {
67 it.effect("retains a missing helper failure alongside the keyring-free fallback", () =>
68 Effect.gen(function* () {
69 const keys = yield* resolveChromiumKeys({
70 platform: "linux",
71 keychainService: undefined,
72 keychainAccount: undefined,
73 linuxSecretApplication: "chromium",
74 });
75 expect(keys.cbcV10).toHaveLength(16);
76 expect(keys.cbcV11).toBeUndefined();
77 expect(keys.cbcV11Error?.reason).toBe("keychainUnavailable");
78 }).pipe(
79 Effect.provide(
80 helperLayer({
81 spawnError: PlatformError.systemError({
82 _tag: "NotFound",
83 module: "ChildProcess",
84 method: "spawn",
85 }),
86 }),
87 ),
88 ),
89 );
90
91 it.effect("reports an unconfigured helper without searching PATH", () =>
92 readLinuxSecret("chromium").pipe(
93 Effect.flip,
94 Effect.tap((error) => Effect.sync(() => expect(error.reason).toBe("keychainUnavailable"))),
95 Effect.provideService(
96 ChildProcessSpawner.ChildProcessSpawner,
97 ChildProcessSpawner.make(() => Effect.die("must not spawn")),
98 ),
99 Effect.provideService(LinuxBrowserSecretPath, undefined),
100 ),
101 );
102
103 it.effect("looks up the browser's libsecret application attribute", () => {
104 let captured: CapturedCommand | undefined;
105 return Effect.gen(function* () {
106 const keys = yield* resolveChromiumKeys({
107 platform: "linux",
108 keychainService: "ignored macOS service",
109 keychainAccount: "ignored macOS account",
110 linuxSecretApplication: "msedge",
111 });
112
113 expect(captured?.command).toBe("/bundled/browser-secret/t3-browser-secret");
114 expect(captured?.args).toEqual(["msedge"]);
115 expect(captured?.options.stdin).toBe("ignore");
116 expect(keys.cbcV10).toHaveLength(16);
117 expect(keys.cbcV11).toHaveLength(16);
118 }).pipe(
119 Effect.provide(
120 helperLayer({ stdout: "linux-secret", capture: (value) => (captured = value) }),
121 ),
122 );
123 });
124
125 it.effect("reports an unavailable Secret Service backend as a read failure", () =>
126 Effect.gen(function* () {
127 const error = yield* readLinuxSecret("chrome").pipe(Effect.flip);
128 expect(error).toBeInstanceOf(ChromiumKeyError);
129 expect(error.reason).toBe("keychainUnavailable");
130 }).pipe(
131 Effect.provide(
132 helperLayer({ stderr: "Cannot autolaunch D-Bus without X11 $DISPLAY", exitCode: 1 }),
133 ),
134 ),
135 );
136
137 it.effect("preserves trailing whitespace in the stored secret", () =>
138 Effect.gen(function* () {
139 const secret = yield* readLinuxSecret("chrome");
140 expect(secret).toBe("linux-secret \t\n");
141 }).pipe(Effect.provide(helperLayer({ stdout: "linux-secret \t\n" }))),
142 );
143
144 it.effect("drains stdout and stderr concurrently", () =>
145 Effect.gen(function* () {
146 const stderrDrainStarted = yield* Deferred.make<void>();
147 const stdout = Stream.fromEffect(Deferred.await(stderrDrainStarted)).pipe(
148 Stream.flatMap(() => Stream.encodeText(Stream.make("linux-secret"))),
149 );
150 const stderr = Stream.fromEffect(Deferred.succeed(stderrDrainStarted, undefined)).pipe(
151 Stream.drain,
152 );
153
154 const secret = yield* readLinuxSecret("chrome").pipe(
155 Effect.provide(helperLayer({ stdoutStream: stdout, stderrStream: stderr })),
156 );
157
158 expect(secret).toBe("linux-secret");
159 }),
160 );
161
162 it.effect(
163 "preserves the desktop environment and identifies denial without parsing stderr",
164 () => {
165 let captured: CapturedCommand | undefined;
166 return Effect.gen(function* () {
167 const error = yield* readLinuxSecret("brave").pipe(Effect.flip);
168 expect(error).toBeInstanceOf(ChromiumKeyError);
169 expect(error.reason).toBe("needsKeychainApproval");
170 expect(captured?.options.env?.LC_ALL).toBe("localized");
171 expect(captured?.options.env?.PATH).toBe("/synthetic/bin");
172 expect(captured?.options.env?.SESSION_MARKER).toBe("kept");
173 }).pipe(
174 Effect.provide(
175 helperLayer({
176 stderr: "Zugriff verweigert",
177 exitCode: 3,
178 capture: (value) => (captured = value),
179 }),
180 ),
181 Effect.provideService(HostProcessEnvironment, {
182 PATH: "/synthetic/bin",
183 SESSION_MARKER: "kept",
184 LC_ALL: "localized",
185 }),
186 );
187 },
188 );
189
190 it.effect("does not discard a denied unlock prompt while resolving keys", () =>
191 Effect.gen(function* () {
192 const error = yield* resolveChromiumKeys({
193 platform: "linux",
194 keychainService: undefined,
195 keychainAccount: undefined,
196 linuxSecretApplication: "brave",
197 }).pipe(Effect.flip);
198 expect(error.reason).toBe("needsKeychainApproval");
199 }).pipe(Effect.provide(helperLayer({ stderr: "Keyring is locked", exitCode: 3 }))),
200 );
201
202 it.effect("keeps the v10 fallback when the Secret Service backend is unavailable", () =>
203 Effect.gen(function* () {
204 const keys = yield* resolveChromiumKeys({
205 platform: "linux",
206 keychainService: undefined,
207 keychainAccount: undefined,
208 linuxSecretApplication: "chrome",
209 });
210 expect(keys.cbcV10).toHaveLength(16);
211 expect(keys.cbcV11).toBeUndefined();
212 }).pipe(
213 Effect.provide(
214 helperLayer({
215 stderr: "Cannot autolaunch D-Bus without X11 $DISPLAY",
216 exitCode: 1,
217 }),
218 ),
219 ),
220 );
221
222 it.effect("keeps the v10 fallback when no matching v11 secret exists", () =>
223 Effect.gen(function* () {
224 const keys = yield* resolveChromiumKeys({
225 platform: "linux",
226 keychainService: undefined,
227 keychainAccount: undefined,
228 linuxSecretApplication: "vivaldi",
229 });
230 expect(keys.cbcV10).toHaveLength(16);
231 expect(keys.cbcV11).toBeUndefined();
232 }).pipe(Effect.provide(helperLayer({ exitCode: 2 }))),
233 );
234});
235
236describe("Windows Chromium secrets", () => {
237 it.effect("accepts only DPAPI-wrapped non-app-bound keys", () =>
238 Effect.gen(function* () {
239 const wrapped = Buffer.from("wrapped-key");
240 const encoded = Buffer.concat([Buffer.from("DPAPI"), wrapped]).toString("base64");
241 const localState = `{"os_crypt":{"encrypted_key":"${encoded}"}}`;
242 expect(yield* decodeWindowsWrappedKey(localState)).toEqual(wrapped);
243
244 const appBound = yield* decodeWindowsWrappedKey(
245 `{"os_crypt":{"encrypted_key":"${encoded}","app_bound_encrypted_key":"present"}}`,
246 ).pipe(Effect.flip);
247 expect(appBound.reason).toBe("unsupportedPlatform");
248
249 const malformed = yield* decodeWindowsWrappedKey(
250 `{"os_crypt":{"encrypted_key":"${wrapped.toString("base64")}"}}`,
251 ).pipe(Effect.flip);
252 expect(malformed.reason).toBe("readFailed");
253 }),
254 );
255
256 it.effect("unwraps the binary key through PowerShell without placing it in argv", () => {
257 let captured: CapturedCommand | undefined;
258 const wrapped = Buffer.from("wrapped-key");
259 const key = Buffer.from("0123456789abcdef0123456789abcdef");
260 return Effect.gen(function* () {
261 expect(yield* unwrapWindowsDpapiKey(wrapped)).toEqual(key);
262 expect(captured?.command).toBe(
263 "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
264 );
265 expect(captured?.args).toContain("-NonInteractive");
266 expect(captured?.args.join(" ")).not.toContain(wrapped.toString("base64"));
267 }).pipe(
268 Effect.provide(
269 helperLayer({ stdout: key.toString("base64"), capture: (value) => (captured = value) }),
270 ),
271 Effect.provideService(HostProcessEnvironment, { SystemRoot: "C:\\Windows" }),
272 );
273 });
274});