Skip to content

Commit bf05df7

Browse files
committed
fix(server): apply discovered shell certificates to live TLS trust
1 parent ef65695 commit bf05df7

2 files changed

Lines changed: 148 additions & 37 deletions

File tree

‎apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts‎

Lines changed: 95 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,113 @@
11
// @effect-diagnostics nodeBuiltinImport:off
22

33
import { it } from "@effect/vitest";
4+
import * as NodeTls from "node:tls";
5+
import * as NodeCrypto from "node:crypto";
6+
import * as NodeServices from "@effect/platform-node/NodeServices";
47
import * as Effect from "effect/Effect";
5-
import { describe, expect, it as test } from "vite-plus/test";
8+
import * as FileSystem from "effect/FileSystem";
9+
import * as Path from "effect/Path";
10+
import { describe, expect } from "vite-plus/test";
611

712
import {
8-
applyDesktopShellEnvironmentSnapshot,
13+
makeApplyDesktopShellEnvironmentSnapshot,
914
requireDesktopTelemetryWriteProgress,
1015
} from "./DesktopTelemetryReceiver.ts";
1116

1217
describe("DesktopTelemetryReceiver", () => {
13-
test.each([
18+
it.effect("updates live TLS trust when shell certificates arrive after startup", () =>
19+
Effect.gen(function* () {
20+
const fs = yield* FileSystem.FileSystem;
21+
const path = yield* Path.Path;
22+
const directory = yield* fs.makeTempDirectoryScoped();
23+
const certificatePath = path.join(directory, "extra-ca.pem");
24+
const original = NodeTls.getCACertificates("default");
25+
yield* Effect.addFinalizer(() =>
26+
Effect.sync(() => NodeTls.setDefaultCACertificates(original)),
27+
);
28+
const baseline = NodeTls.rootCertificates[0]!;
29+
const extra = NodeTls.rootCertificates[1]!;
30+
const replacement = NodeTls.rootCertificates[2]!;
31+
NodeTls.setDefaultCACertificates([baseline]);
32+
yield* fs.writeFileString(certificatePath, `${extra}\n${replacement}`);
33+
const environment: NodeJS.ProcessEnv = { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" };
34+
const applySnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, "darwin");
35+
const message = {
36+
version: 1,
37+
type: "shellEnvironment",
38+
platform: "darwin",
39+
discovered: true,
40+
environment: { NODE_EXTRA_CA_CERTS: certificatePath },
41+
} as const;
42+
const fingerprints = (certificates: ReadonlyArray<string>) =>
43+
certificates.map((pem) => new NodeCrypto.X509Certificate(pem).fingerprint256).sort();
44+
yield* applySnapshot({ ...message, platform: "win32" });
45+
expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(fingerprints([baseline]));
46+
expect(environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING).toBe("1");
47+
yield* applySnapshot(message);
48+
expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(
49+
fingerprints([baseline, extra, replacement]),
50+
);
51+
expect(environment.NODE_EXTRA_CA_CERTS).toBe(certificatePath);
52+
expect(environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING).toBeUndefined();
53+
54+
yield* fs.writeFileString(certificatePath, replacement);
55+
yield* applySnapshot(message);
56+
expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(
57+
fingerprints([baseline, replacement]),
58+
);
59+
60+
yield* fs.writeFileString(
61+
certificatePath,
62+
"-----BEGIN CERTIFICATE-----\ninvalid\n-----END CERTIFICATE-----",
63+
);
64+
yield* applySnapshot(message);
65+
expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(
66+
fingerprints([baseline, replacement]),
67+
);
68+
yield* fs.remove(certificatePath);
69+
yield* applySnapshot(message);
70+
expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(
71+
fingerprints([baseline, replacement]),
72+
);
73+
74+
yield* applySnapshot({ ...message, environment: { NODE_EXTRA_CA_CERTS: null } });
75+
expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(fingerprints([baseline]));
76+
expect(environment.NODE_EXTRA_CA_CERTS).toBeUndefined();
77+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
78+
);
79+
80+
it.effect.each([
1481
{ platform: "darwin", discovered: true, applied: true, pending: false },
1582
{ platform: "win32", discovered: true, applied: false, pending: true },
1683
{ platform: "darwin", discovered: false, applied: true, pending: true },
1784
])(
1885
"applies platform=$platform discovered=$discovered with pending=$pending",
19-
({ platform, discovered, applied, pending }) => {
20-
const environment: NodeJS.ProcessEnv = {
21-
PATH: "/old/bin",
22-
JAVA_HOME: "/old/java",
23-
UNRELATED: "keep",
24-
T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1",
25-
};
26-
applyDesktopShellEnvironmentSnapshot(environment, "darwin", {
27-
version: 1,
28-
type: "shellEnvironment",
29-
platform,
30-
discovered,
31-
environment: { PATH: "/fresh/bin", JAVA_HOME: null },
32-
});
33-
expect(environment).toEqual({
34-
PATH: applied ? "/fresh/bin" : "/old/bin",
35-
...(applied ? {} : { JAVA_HOME: "/old/java" }),
36-
UNRELATED: "keep",
37-
...(pending ? { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" } : {}),
38-
});
39-
},
86+
({ platform, discovered, applied, pending }) =>
87+
Effect.gen(function* () {
88+
const environment: NodeJS.ProcessEnv = {
89+
PATH: "/old/bin",
90+
JAVA_HOME: "/old/java",
91+
UNRELATED: "keep",
92+
T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1",
93+
};
94+
yield* makeApplyDesktopShellEnvironmentSnapshot(
95+
environment,
96+
"darwin",
97+
)({
98+
version: 1,
99+
type: "shellEnvironment",
100+
platform,
101+
discovered,
102+
environment: { PATH: "/fresh/bin", JAVA_HOME: null },
103+
});
104+
expect(environment).toEqual({
105+
PATH: applied ? "/fresh/bin" : "/old/bin",
106+
...(applied ? {} : { JAVA_HOME: "/old/java" }),
107+
UNRELATED: "keep",
108+
...(pending ? { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" } : {}),
109+
});
110+
}).pipe(Effect.provide(NodeServices.layer)),
40111
);
41112

42113
it.effect("models a zero-byte control write as a stalled descriptor", () =>

‎apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts‎

Lines changed: 53 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// @effect-diagnostics nodeBuiltinImport:off
22
import * as NodeFS from "node:fs";
33
import * as NodeNet from "node:net";
4+
import * as NodeTls from "node:tls";
45

56
import * as NodeStream from "@effect/platform-node/NodeStream";
67
import {
@@ -20,6 +21,7 @@ import * as Context from "effect/Context";
2021
import * as DateTime from "effect/DateTime";
2122
import * as Duration from "effect/Duration";
2223
import * as Effect from "effect/Effect";
24+
import * as FileSystem from "effect/FileSystem";
2325
import * as Layer from "effect/Layer";
2426
import * as Option from "effect/Option";
2527
import * as PubSub from "effect/PubSub";
@@ -205,14 +207,57 @@ export class DesktopTelemetryReceiver extends Context.Service<
205207
}
206208
>()("t3/resourceTelemetry/DesktopTelemetryReceiver") {}
207209

208-
export function applyDesktopShellEnvironmentSnapshot(
210+
class DesktopShellCertificatesUpdateFailed extends Schema.TaggedError<DesktopShellCertificatesUpdateFailed>()(
211+
"DesktopShellCertificatesUpdateFailed",
212+
{ cause: Schema.Defect() },
213+
) {
214+
override get message(): string {
215+
return "Failed to update desktop shell TLS certificates.";
216+
}
217+
}
218+
219+
export function makeApplyDesktopShellEnvironmentSnapshot(
209220
environment: NodeJS.ProcessEnv,
210221
platform: NodeJS.Platform,
211-
message: DesktopShellEnvironmentSnapshot,
212-
): void {
213-
if (message.platform !== platform) return;
214-
applyShellEnvironment(environment, message.environment);
215-
if (message.discovered) delete environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING;
222+
) {
223+
let baseCertificates: Array<string> | undefined;
224+
return Effect.fn("resourceTelemetry.desktopTelemetryReceiver.applyShellEnvironment")(function* (
225+
message: DesktopShellEnvironmentSnapshot,
226+
) {
227+
if (message.platform !== platform) return;
228+
applyShellEnvironment(environment, message.environment);
229+
if (message.environment.NODE_EXTRA_CA_CERTS !== undefined) {
230+
yield* Effect.gen(function* () {
231+
if (baseCertificates === undefined) {
232+
// Remove only the startup extras, preserving duplicates from bundled or system trust.
233+
const extras = [...NodeTls.getCACertificates("extra")];
234+
baseCertificates = NodeTls.getCACertificates("default").filter((certificate) => {
235+
const index = extras.indexOf(certificate);
236+
if (index === -1) return true;
237+
extras.splice(index, 1);
238+
return false;
239+
});
240+
}
241+
const fs = yield* FileSystem.FileSystem;
242+
const file = message.environment.NODE_EXTRA_CA_CERTS;
243+
const bundle = file ? yield* fs.readFileString(file) : undefined;
244+
yield* Effect.try({
245+
try: () => {
246+
const extras =
247+
bundle?.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? [];
248+
if (bundle?.trim() && extras.length === 0) {
249+
throw new Error("No PEM certificates found.");
250+
}
251+
NodeTls.setDefaultCACertificates([...baseCertificates!, ...extras]);
252+
},
253+
catch: (cause) => new DesktopShellCertificatesUpdateFailed({ cause }),
254+
});
255+
}).pipe(
256+
Effect.catch(() => Effect.logWarning("Failed to update desktop shell TLS certificates.")),
257+
);
258+
}
259+
if (message.discovered) delete environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING;
260+
});
216261
}
217262

218263
const decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage);
@@ -343,6 +388,7 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
343388
const config = yield* ServerConfig.ServerConfig;
344389
const environment = yield* HostProcess.Environment;
345390
const platform = yield* HostProcess.Platform;
391+
const applyShellSnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, platform);
346392
const serverSettings = yield* ServerSettings.ServerSettingsService;
347393
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
348394
const receiverStartedAt = yield* DateTime.now;
@@ -539,13 +585,7 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
539585
}
540586

541587
if (message.type === "shellEnvironment") {
542-
return recordContact.pipe(
543-
Effect.andThen(
544-
Effect.sync(() => {
545-
applyDesktopShellEnvironmentSnapshot(environment, platform, message);
546-
}),
547-
),
548-
);
588+
return recordContact.pipe(Effect.andThen(applyShellSnapshot(message)));
549589
}
550590

551591
if (message.type === "desktopUpdateStatus") {

0 commit comments

Comments
 (0)