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

Identify.test.ts

286 lines11.0 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 ServerSecretStore from "../auth/ServerSecretStore.ts";
14import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts";
15import * as ServerConfig from "../config.ts";
16import * as Identify from "./Identify.ts";
17​
18interface CapturedLog {
19 readonly message: unknown;
20 readonly annotations: Readonly<Record<string, unknown>>;
22​
23const sha256 = Effect.fn("test.sha256")(function* (value: string) {
24 const crypto = yield* Crypto.Crypto;
25 return Hex.encode(
26 yield* crypto.digest("SHA-256", new TextEncoder().encode(value)).pipe(Effect.orDie),
27 );
28});
29​
30const makeCaptureLogger = (logs: CapturedLog[]) =>
31 Logger.make(({ fiber, message }) => {
32 logs.push({
33 message,
34 annotations: fiber.getRef(References.CurrentLogAnnotations),
35 });
36 });
37​
38const findIdentityLog = (
39 logs: ReadonlyArray<CapturedLog>,
40 source: Identify.TelemetryIdentitySource,
41 errorTag: string,
42) => logs.find((log) => log.annotations.source === source && log.annotations.errorTag === errorTag);
43​
44const unsignedJwt = (claims: Readonly<Record<string, unknown>>) =>
45 ["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "signature"].join(".");
46​
47const layerIdentity = (prefix: string, logs?: CapturedLog[]) =>
48 Layer.provideMerge(
49 ServerSecretStore.layer,
50 ServerConfig.layerTest(process.cwd(), { prefix }),
51 ).pipe(
52 Layer.merge(
53 logs === undefined
54 ? Layer.empty
55 : Logger.layer([makeCaptureLogger(logs)], { mergeWithExisting: false }),
56 ),
57 );
58​
59const writeHomeFile = Effect.fn("test.writeHomeFile")(function* (
60 homeDirectory: string,
61 relativePath: string,
62 contents: string,
63) {
64 const fileSystem = yield* FileSystem.FileSystem;
65 const path = yield* Path.Path;
66 const filePath = path.join(homeDirectory, relativePath);
67 yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });
68 yield* fileSystem.writeFileString(filePath, contents);
69 return filePath;
70});
71​
72it.layer(NodeServices.layer)("telemetry identity", (it) => {
73 it.effect("keeps the old distinct_id rule and a fixed install id as logins change", () =>
74 Effect.gen(function* () {
75 const config = yield* ServerConfig.ServerConfig;
76 const fileSystem = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 const homeDirectory = path.join(config.baseDir, "home");
79 const anonymousId = "persisted-anonymous-id";
80 yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
81 const installId = yield* sha256(anonymousId);
82 const identity = () => Identify.getTelemetryIdentityForHome(homeDirectory);
83​
84 assert.deepEqual(yield* identity(), { distinctId: installId, installId });
85​
86 yield* writeHomeFile(homeDirectory, ".claude.json", `{"userID":"claude-machine"}`);
87 assert.deepEqual(yield* identity(), {
88 distinctId: yield* sha256("claude-machine"),
89 installId,
90 });
91​
92 yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"auth_mode":"apikey"}`);
93 assert.equal((yield* identity()).distinctId, yield* sha256("claude-machine"));
94​
95 yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"tokens":{"account_id":"ws-1"}}`);
96 assert.deepEqual(yield* identity(), { distinctId: yield* sha256("ws-1"), installId });
97 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-install-"))),
98 );
99​
100 it.effect("keeps a provider distinct_id when the install id cannot be saved", () =>
101 Effect.gen(function* () {
102 const config = yield* ServerConfig.ServerConfig;
103 const fileSystem = yield* FileSystem.FileSystem;
104 const path = yield* Path.Path;
105 const homeDirectory = path.join(config.baseDir, "home");
106 yield* fileSystem.makeDirectory(config.anonymousIdPath);
107 yield* writeHomeFile(homeDirectory, ".claude.json", `{"userID":"claude-machine"}`);
108​
109 assert.deepEqual(yield* Identify.getTelemetryIdentityForHome(homeDirectory), {
110 distinctId: yield* sha256("claude-machine"),
111 installId: null,
112 });
113 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-noinstall-"))),
114 );
115​
116 it.effect("leaves no torn anonymous id behind when its write fails midway", () =>
117 Effect.gen(function* () {
118 const config = yield* ServerConfig.ServerConfig;
119 const fileSystem = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 const tornWrites = FileSystem.FileSystem.of({
122 ...fileSystem,
123 writeFileString: (filePath, data, options) =>
124 fileSystem
125 .writeFileString(filePath, data.slice(0, Math.floor(data.length / 2)), options)
126 .pipe(
127 Effect.andThen(
128 Effect.fail(
129 PlatformError.systemError({
130 _tag: "WriteZero",
131 module: "FileSystem",
132 method: "writeFileString",
133 pathOrDescriptor: filePath,
134 }),
135 ),
136 ),
137 ),
138 });
139​
140 const identity = yield* Identify.getTelemetryIdentityForHome(
141 path.join(config.baseDir, "home"),
142 ).pipe(Effect.provideService(FileSystem.FileSystem, tornWrites));
143​
144 assert.deepEqual(identity, { distinctId: null, installId: null });
145 assert.isFalse(yield* fileSystem.exists(config.anonymousIdPath));
146 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-torn-"))),
147 );
148​
149 it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => {
150 const logs: CapturedLog[] = [];
151​
152 return Effect.gen(function* () {
153 const config = yield* ServerConfig.ServerConfig;
154 const fileSystem = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156 yield* fileSystem.makeDirectory(config.anonymousIdPath);
157​
158 const identity = yield* Identify.getTelemetryIdentityForHome(
159 path.join(config.baseDir, "home"),
160 );
161 assert.deepEqual(identity, { distinctId: null, installId: null });
162 assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []);
163​
164 const readLog = findIdentityLog(logs, "anonymous", "TelemetryIdentityReadError");
165 assert.equal(readLog?.annotations.filePath, config.anonymousIdPath);
166 assert.notEqual(readLog?.annotations.platformReason, "NotFound");
167 assert.notProperty(readLog?.annotations ?? {}, "cause");
168 assert.isUndefined(
169 findIdentityLog(logs, "anonymous", "TelemetryAnonymousIdPersistenceError"),
170 );
171 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-read-", logs)));
172 });
173​
174 it.effect("reads the Connect account and each provider account as owners", () =>
175 Effect.gen(function* () {
176 const config = yield* ServerConfig.ServerConfig;
177 const secrets = yield* ServerSecretStore.ServerSecretStore;
178 const path = yield* Path.Path;
179 const homeDirectory = path.join(config.baseDir, "home");
180 yield* secrets.set(CLOUD_LINKED_USER_ID, new TextEncoder().encode("user_connect"));
181 yield* writeHomeFile(
182 homeDirectory,
183 ".codex/auth.json",
184 JSON.stringify({
185 tokens: {
186 account_id: "team-workspace",
187 id_token: unsignedJwt({
188 sub: "google-oauth2|login-method",
189 "https://api.openai.com/auth": { user_id: "user-openai-person" },
190 }),
191 },
192 }),
193 );
194 yield* writeHomeFile(
195 homeDirectory,
196 ".claude.json",
197 JSON.stringify({
198 userID: "claude-machine",
199 oauthAccount: { accountUuid: "claude-person" },
200 }),
201 );
202​
203 const owners = yield* Identify.getServerOwnersForHome(homeDirectory);
204​
205 assert.deepEqual(owners, [
206 { source: "connect", ownerId: yield* sha256("user_connect") },
207 { source: "openai", ownerId: yield* sha256("user-openai-person") },
208 { source: "claude", ownerId: yield* sha256("claude-person") },
209 ]);
210 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-owners-"))),
211 );
212​
213 it.effect.each([
214 {
215 login: "an API key",
216 secret: "sk-private-openai-api-key",
217 authJson: (secret: string) => `{"auth_mode":"apikey","OPENAI_API_KEY":"${secret}"}`,
218 },
219 {
220 login: "an agent identity",
221 secret: "private-agent-identity-jwt",
222 authJson: (secret: string) =>
223 `{"auth_mode":"agentIdentity","OPENAI_API_KEY":null,"agent_identity":"${secret}"}`,
224 },
225 {
226 login: "a personal access token",
227 secret: "private-personal-access-token",
228 authJson: (secret: string) => `{"OPENAI_API_KEY":null,"personal_access_token":"${secret}"}`,
229 },
230 ])(
231 "adds no owner and logs nothing when Codex authenticates with $login",
232 ({ secret, authJson }) => {
233 const logs: CapturedLog[] = [];
234​
235 return Effect.gen(function* () {
236 const config = yield* ServerConfig.ServerConfig;
237 const path = yield* Path.Path;
238 const homeDirectory = path.join(config.baseDir, "home");
239 yield* writeHomeFile(homeDirectory, ".codex/auth.json", authJson(secret));
240​
241 assert.deepEqual(yield* Identify.getServerOwnersForHome(homeDirectory), []);
242 assert.deepEqual(logs, []);
243 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-tokenless-", logs)));
244 },
245 );
246​
247 it.effect(
248 "warns about malformed Codex auth without its tokens and keeps the other owners",
249 () => {
250 const logs: CapturedLog[] = [];
251​
252 return Effect.gen(function* () {
253 const config = yield* ServerConfig.ServerConfig;
254 const path = yield* Path.Path;
255 const homeDirectory = path.join(config.baseDir, "home");
256 const privateAccessToken = "private-codex-access-token";
257 const codexAuthPath = yield* writeHomeFile(
258 homeDirectory,
259 ".codex/auth.json",
260 `{"tokens":{"access_token":"${privateAccessToken}"}}`,
261 );
262 yield* writeHomeFile(
263 homeDirectory,
264 ".claude.json",
265 `{"oauthAccount":{"accountUuid":"claude-person"}}`,
266 );
267​
268 assert.deepEqual(yield* Identify.getServerOwnersForHome(homeDirectory), [
269 { source: "claude", ownerId: yield* sha256("claude-person") },
270 ]);
271 const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError");
272 assert.equal(
273 decodeLog?.message,
274 `Failed to decode codex telemetry identity at '${codexAuthPath}'.`,
275 );
276 assert.equal(decodeLog?.annotations.causeKind, "schema");
277 assert.notInclude(
278 Object.values(decodeLog?.annotations ?? {})
279 .map(String)
280 .join("\n"),
281 privateAccessToken,
282 );
283 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-decode-", logs)));
284 },
285 );
286});