Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Logger from "effect/Logger";
8import * as Path from "effect/Path";
9import * as PlatformError from "effect/PlatformError";
10import * as References from "effect/References";
11
12import * as ServerConfig from "../config.ts";
13import * as Identify from "./Identify.ts";
14
15interface CapturedLog {
16 readonly message: unknown;
17 readonly annotations: Readonly<Record<string, unknown>>;
18}
19
20const sha256 = (value: string) =>
21 NodeCrypto.createHash("sha256").update(value, "utf8").digest("hex");
22
23const makeCaptureLogger = (logs: CapturedLog[]) =>
24 Logger.make(({ fiber, message }) => {
25 logs.push({
26 message,
27 annotations: fiber.getRef(References.CurrentLogAnnotations),
28 });
29 });
30
31const findIdentityLog = (
32 logs: ReadonlyArray<CapturedLog>,
33 source: Identify.TelemetryIdentitySource,
34 errorTag: string,
35) => logs.find((log) => log.annotations.source === source && log.annotations.errorTag === errorTag);
36
37it.layer(NodeServices.layer)("telemetry identity", (it) => {
38 it.effect("uses the persisted anonymous id when provider identities are absent", () =>
39 Effect.gen(function* () {
40 const config = yield* ServerConfig.ServerConfig;
41 const fileSystem = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43 const anonymousId = "persisted-anonymous-id";
44
45 yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
46
47 const identifier = yield* Identify.getTelemetryIdentifierForHome(
48 path.join(config.baseDir, "home"),
49 );
50
51 assert.equal(identifier, sha256(anonymousId));
52 }).pipe(
53 Effect.provide(
54 ServerConfig.layerTest(process.cwd(), {
55 prefix: "t3-telemetry-identify-anonymous-",
56 }),
57 ),
58 ),
59 );
60
61 it.effect("leaves no torn anonymous id behind when its write fails midway", () =>
62 Effect.gen(function* () {
63 const config = yield* ServerConfig.ServerConfig;
64 const fileSystem = yield* FileSystem.FileSystem;
65 const path = yield* Path.Path;
66 const tornWrites = FileSystem.FileSystem.of({
67 ...fileSystem,
68 writeFileString: (filePath, data, options) =>
69 fileSystem
70 .writeFileString(filePath, data.slice(0, Math.floor(data.length / 2)), options)
71 .pipe(
72 Effect.andThen(
73 Effect.fail(
74 PlatformError.systemError({
75 _tag: "WriteZero",
76 module: "FileSystem",
77 method: "writeFileString",
78 pathOrDescriptor: filePath,
79 }),
80 ),
81 ),
82 ),
83 });
84
85 const identifier = yield* Identify.getTelemetryIdentifierForHome(
86 path.join(config.baseDir, "home"),
87 ).pipe(Effect.provideService(FileSystem.FileSystem, tornWrites));
88
89 assert.isNull(identifier);
90 assert.isFalse(yield* fileSystem.exists(config.anonymousIdPath));
91 }).pipe(
92 Effect.provide(
93 ServerConfig.layerTest(process.cwd(), {
94 prefix: "t3-telemetry-identify-torn-",
95 }),
96 ),
97 ),
98 );
99
100 it.effect.each([
101 {
102 login: "an API key",
103 secret: "sk-private-openai-api-key",
104 authJson: (secret: string) => `{"auth_mode":"apikey","OPENAI_API_KEY":"${secret}"}`,
105 },
106 {
107 login: "an agent identity",
108 secret: "private-agent-identity-jwt",
109 authJson: (secret: string) =>
110 `{"auth_mode":"agentIdentity","OPENAI_API_KEY":null,"agent_identity":"${secret}"}`,
111 },
112 {
113 login: "a personal access token",
114 secret: "private-personal-access-token",
115 authJson: (secret: string) => `{"OPENAI_API_KEY":null,"personal_access_token":"${secret}"}`,
116 },
117 ])("falls back quietly when Codex authenticates with $login", ({ secret, authJson }) => {
118 const logs: CapturedLog[] = [];
119 const logger = makeCaptureLogger(logs);
120
121 return Effect.gen(function* () {
122 const config = yield* ServerConfig.ServerConfig;
123 const fileSystem = yield* FileSystem.FileSystem;
124 const path = yield* Path.Path;
125 const homeDirectory = path.join(config.baseDir, "home");
126 const codexAuthPath = path.join(homeDirectory, ".codex", "auth.json");
127 const anonymousId = "tokenless-codex-anonymous-id";
128
129 yield* fileSystem.makeDirectory(path.dirname(codexAuthPath), { recursive: true });
130 yield* fileSystem.writeFileString(codexAuthPath, authJson(secret));
131 yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
132
133 const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
134
135 assert.equal(identifier, sha256(anonymousId));
136 assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError"));
137 assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityReadError"));
138 const allLogs = logs
139 .map((log) =>
140 [String(log.message), ...Object.values(log.annotations).map(String)].join("\n"),
141 )
142 .join("\n");
143 assert.notInclude(allLogs, secret);
144 }).pipe(
145 Effect.provide(
146 Layer.merge(
147 ServerConfig.layerTest(process.cwd(), {
148 prefix: "t3-telemetry-identify-tokenless-",
149 }),
150 Logger.layer([logger], { mergeWithExisting: false }),
151 ),
152 ),
153 );
154 });
155
156 it.effect("logs structured decode context and falls back from malformed Codex auth", () => {
157 const logs: CapturedLog[] = [];
158 const logger = makeCaptureLogger(logs);
159
160 return Effect.gen(function* () {
161 const config = yield* ServerConfig.ServerConfig;
162 const fileSystem = yield* FileSystem.FileSystem;
163 const path = yield* Path.Path;
164 const homeDirectory = path.join(config.baseDir, "home");
165 const codexAuthPath = path.join(homeDirectory, ".codex", "auth.json");
166 const anonymousId = "decode-fallback-anonymous-id";
167 const privateAccessToken = "private-codex-access-token";
168
169 yield* fileSystem.makeDirectory(path.dirname(codexAuthPath), { recursive: true });
170 yield* fileSystem.writeFileString(
171 codexAuthPath,
172 `{"tokens":{"access_token":"${privateAccessToken}"}}`,
173 );
174 yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
175
176 const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
177
178 assert.equal(identifier, sha256(anonymousId));
179 const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError");
180 assert.isDefined(decodeLog);
181 assert.equal(
182 decodeLog?.message,
183 `Failed to decode codex telemetry identity at '${codexAuthPath}'.`,
184 );
185
186 assert.equal(decodeLog?.annotations.filePath, codexAuthPath);
187 assert.equal(decodeLog?.annotations.causeKind, "schema");
188 assert.notProperty(decodeLog?.annotations ?? {}, "cause");
189 const errorStack = decodeLog?.annotations.errorStack;
190 assert.isString(errorStack);
191 assert.include(errorStack, "Failed to decode codex telemetry identity");
192 const annotations = Object.values(decodeLog?.annotations ?? {})
193 .map(String)
194 .join("\n");
195 assert.notInclude(annotations, privateAccessToken);
196 }).pipe(
197 Effect.provide(
198 Layer.merge(
199 ServerConfig.layerTest(process.cwd(), {
200 prefix: "t3-telemetry-identify-decode-",
201 }),
202 Logger.layer([logger], { mergeWithExisting: false }),
203 ),
204 ),
205 );
206 });
207
208 it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => {
209 const logs: CapturedLog[] = [];
210 const logger = makeCaptureLogger(logs);
211
212 return Effect.gen(function* () {
213 const config = yield* ServerConfig.ServerConfig;
214 const fileSystem = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const homeDirectory = path.join(config.baseDir, "home");
217
218 yield* fileSystem.makeDirectory(config.anonymousIdPath);
219
220 const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
221
222 assert.isNull(identifier);
223 assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []);
224
225 const readLog = findIdentityLog(logs, "anonymous", "TelemetryIdentityReadError");
226 assert.isDefined(readLog);
227 assert.equal(readLog?.annotations.filePath, config.anonymousIdPath);
228 assert.equal(readLog?.annotations.causeKind, "platform");
229 assert.notEqual(readLog?.annotations.platformReason, "NotFound");
230 assert.notProperty(readLog?.annotations ?? {}, "cause");
231 const errorStack = readLog?.annotations.errorStack;
232 assert.isString(errorStack);
233 assert.include(errorStack, "Failed to read anonymous telemetry identity");
234 assert.isUndefined(
235 findIdentityLog(logs, "anonymous", "TelemetryAnonymousIdPersistenceError"),
236 );
237 }).pipe(
238 Effect.provide(
239 Layer.merge(
240 ServerConfig.layerTest(process.cwd(), {
241 prefix: "t3-telemetry-identify-read-",
242 }),
243 Logger.layer([logger], { mergeWithExisting: false }),
244 ),
245 ),
246 );
247 });
248});