Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Identify.test.ts

253 lines9.3 KB

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