-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathzoo-code-auth.test.ts
More file actions
388 lines (319 loc) · 11.3 KB
/
Copy pathzoo-code-auth.test.ts
File metadata and controls
388 lines (319 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import * as vscode from "vscode"
import {
clearZooCodeToken,
clearZooCodeUserInfo,
disconnectZooCode,
getCachedZooCodeToken,
getCachedZooCodeUserInfo,
getZooCodeBaseUrl,
handleAuthCallback,
initZooCodeAuth,
resolveZooGatewaySessionToken,
setZooCodeToken,
setZooCodeUserInfo,
verifyZooCodeToken,
} from "../zoo-code-auth"
vi.mock("vscode", () => ({
workspace: {
getConfiguration: vi.fn(() => ({
get: vi.fn((key: string, defaultValue?: string) => defaultValue),
})),
},
window: {
showErrorMessage: vi.fn(),
showInformationMessage: vi.fn(),
},
}))
vi.mock("../i18n", () => ({
t: vi.fn((key: string) => key),
}))
const mockFetch = vi.fn()
global.fetch = mockFetch as any
describe("zoo-code-auth", () => {
let mockSecrets: any
let mockContext: any
beforeEach(() => {
vi.clearAllMocks()
mockFetch.mockReset()
const secretStore: Record<string, string> = {}
mockSecrets = {
get: vi.fn(async (key: string) => secretStore[key]),
store: vi.fn(async (key: string, value: string) => {
secretStore[key] = value
}),
delete: vi.fn(async (key: string) => {
delete secretStore[key]
}),
onDidChange: vi.fn(() => ({ dispose: vi.fn() })),
}
mockContext = {
secrets: mockSecrets,
}
})
afterEach(async () => {
await clearZooCodeToken()
await clearZooCodeUserInfo()
vi.restoreAllMocks()
})
describe("getCachedZooCodeToken", () => {
it("returns an empty string when no token is set", async () => {
await clearZooCodeToken()
expect(getCachedZooCodeToken()).toBe("")
})
it("preloads the cached token during initialization", async () => {
await mockSecrets.store("zoo-code-session-token", "zoo_ext_cached_token")
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ valid: true }),
})
await initZooCodeAuth(mockContext)
await Promise.resolve()
expect(getCachedZooCodeToken()).toBe("zoo_ext_cached_token")
})
})
describe("initZooCodeAuth", () => {
it("clears stored user info and token when the cached token is invalid", async () => {
await mockSecrets.store("zoo-code-session-token", "zoo_ext_stale_token")
await mockSecrets.store("zoo-code-user-name", "Jane Doe")
await mockSecrets.store("zoo-code-user-email", "jane@example.com")
await mockSecrets.store("zoo-code-user-image", "https://example.com/avatar.png")
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ valid: false }),
})
await initZooCodeAuth(mockContext)
// Both token and user info should be cleared on a definitive invalid response
expect(getCachedZooCodeToken()).toBe("")
expect(getCachedZooCodeUserInfo()).toEqual({
name: undefined,
email: undefined,
image: undefined,
})
})
it("clears stored user info and token when backend returns HTTP error (invalid token)", async () => {
await mockSecrets.store("zoo-code-session-token", "zoo_ext_stale_token")
await mockSecrets.store("zoo-code-user-name", "Jane Doe")
await mockSecrets.store("zoo-code-user-email", "jane@example.com")
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
statusText: "Unauthorized",
})
await initZooCodeAuth(mockContext)
expect(getCachedZooCodeToken()).toBe("")
expect(getCachedZooCodeUserInfo()).toEqual({
name: undefined,
email: undefined,
image: undefined,
})
})
it("preserves token and user info when the backend is temporarily unreachable", async () => {
await mockSecrets.store("zoo-code-session-token", "zoo_ext_valid_token")
await mockSecrets.store("zoo-code-user-name", "Jane Doe")
await mockSecrets.store("zoo-code-user-email", "jane@example.com")
// Simulate a network error during verification
mockFetch.mockRejectedValueOnce(new Error("Network error"))
await initZooCodeAuth(mockContext)
expect(getCachedZooCodeToken()).toBe("zoo_ext_valid_token")
expect(getCachedZooCodeUserInfo().name).toBe("Jane Doe")
})
it("preserves token and user info when verify returns 5xx (transient backend error)", async () => {
await mockSecrets.store("zoo-code-session-token", "zoo_ext_valid_token")
await mockSecrets.store("zoo-code-user-name", "Jane Doe")
await mockSecrets.store("zoo-code-user-email", "jane@example.com")
mockFetch.mockResolvedValueOnce({
ok: false,
status: 503,
statusText: "Service Unavailable",
})
await initZooCodeAuth(mockContext)
expect(getCachedZooCodeToken()).toBe("zoo_ext_valid_token")
expect(getCachedZooCodeUserInfo().name).toBe("Jane Doe")
})
})
describe("clearZooCodeToken", () => {
it("clears the cached token", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_test_token")
await clearZooCodeToken()
expect(getCachedZooCodeToken()).toBe("")
})
})
describe("getZooCodeBaseUrl", () => {
it("returns the default URL when ZOO_CODE_BASE_URL is not set", () => {
const originalEnv = process.env.ZOO_CODE_BASE_URL
delete process.env.ZOO_CODE_BASE_URL
expect(getZooCodeBaseUrl()).toBe("https://www.zoocode.dev")
if (originalEnv) {
process.env.ZOO_CODE_BASE_URL = originalEnv
}
})
it("respects ZOO_CODE_BASE_URL", () => {
const originalEnv = process.env.ZOO_CODE_BASE_URL
process.env.ZOO_CODE_BASE_URL = "https://staging.zoocode.dev"
expect(getZooCodeBaseUrl()).toBe("https://staging.zoocode.dev")
if (originalEnv) {
process.env.ZOO_CODE_BASE_URL = originalEnv
} else {
delete process.env.ZOO_CODE_BASE_URL
}
})
})
describe("handleAuthCallback", () => {
it("does not persist a token when backend verification fails", async () => {
await initZooCodeAuth(mockContext)
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ valid: false }),
})
const success = await handleAuthCallback("zoo_ext_fake_token")
expect(success).toBe(false)
expect(getCachedZooCodeToken()).toBe("")
expect(mockSecrets.store).not.toHaveBeenCalledWith("zoo-code-session-token", "zoo_ext_fake_token")
})
it("persists a token only after backend verification succeeds", async () => {
await initZooCodeAuth(mockContext)
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ valid: true }),
})
const success = await handleAuthCallback("zoo_ext_real_token")
expect(success).toBe(true)
expect(getCachedZooCodeToken()).toBe("zoo_ext_real_token")
expect(mockSecrets.store).toHaveBeenCalledWith("zoo-code-session-token", "zoo_ext_real_token")
})
})
describe("verifyZooCodeToken", () => {
it("returns 'valid' when the backend confirms the token", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_valid_token")
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ valid: true }),
})
expect(await verifyZooCodeToken()).toBe("valid")
// Token should NOT be cleared — no side effects
expect(getCachedZooCodeToken()).toBe("zoo_ext_valid_token")
})
it("returns 'invalid' when the backend reports valid: false", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_invalid_token")
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ valid: false }),
})
expect(await verifyZooCodeToken()).toBe("invalid")
// No side effects — caller decides what to do
expect(getCachedZooCodeToken()).toBe("zoo_ext_invalid_token")
})
it("returns 'invalid' when the backend returns 4xx", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_invalid_token")
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
statusText: "Unauthorized",
})
expect(await verifyZooCodeToken()).toBe("invalid")
})
it("returns 'unreachable' when the backend returns 5xx (transient)", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_token")
mockFetch.mockResolvedValueOnce({
ok: false,
status: 503,
statusText: "Service Unavailable",
})
expect(await verifyZooCodeToken()).toBe("unreachable")
expect(getCachedZooCodeToken()).toBe("zoo_ext_token")
})
it("returns 'unreachable' when a network error occurs", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_token")
mockFetch.mockRejectedValueOnce(new Error("Network error"))
expect(await verifyZooCodeToken()).toBe("unreachable")
// Token must NOT be cleared on network error
expect(getCachedZooCodeToken()).toBe("zoo_ext_token")
})
it("returns 'invalid' when no token is stored", async () => {
await initZooCodeAuth(mockContext)
expect(await verifyZooCodeToken()).toBe("invalid")
})
})
describe("setZooCodeUserInfo", () => {
it("clears email when passed null", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeUserInfo({
name: "Jane Doe",
email: "jane@example.com",
image: "https://example.com/avatar.png",
})
// Verify email is set
expect(getCachedZooCodeUserInfo().email).toBe("jane@example.com")
// Clear email with null
await setZooCodeUserInfo({ email: null })
// Email should be cleared, but other fields should remain
const info = getCachedZooCodeUserInfo()
expect(info.email).toBeUndefined()
expect(info.name).toBe("Jane Doe")
expect(info.image).toBe("https://example.com/avatar.png")
})
it("does not clear email when passed undefined", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeUserInfo({
name: "Jane Doe",
email: "jane@example.com",
image: "https://example.com/avatar.png",
})
// Pass undefined for email - should preserve existing value
await setZooCodeUserInfo({ name: "John Doe", email: undefined })
const info = getCachedZooCodeUserInfo()
expect(info.email).toBe("jane@example.com")
expect(info.name).toBe("John Doe")
})
})
describe("resolveZooGatewaySessionToken", () => {
it("prefers the cached token over a profile token", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_cached")
expect(resolveZooGatewaySessionToken("zoo_ext_profile")).toBe("zoo_ext_cached")
})
it("ignores profile tokens after an explicit sign-out clear", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_cached")
await clearZooCodeToken()
expect(resolveZooGatewaySessionToken("zoo_ext_stale_profile")).toBeUndefined()
})
it("falls back to the profile token when the cache is empty and not cleared", async () => {
await initZooCodeAuth(mockContext)
expect(resolveZooGatewaySessionToken("zoo_ext_profile")).toBe("zoo_ext_profile")
})
})
describe("disconnectZooCode", () => {
it("revokes the current token and clears cached auth state", async () => {
await initZooCodeAuth(mockContext)
await setZooCodeToken("zoo_ext_real_token")
await setZooCodeUserInfo({
name: "Jane Doe",
email: "jane@example.com",
image: "https://example.com/avatar.png",
})
mockFetch.mockResolvedValueOnce({ ok: true })
await disconnectZooCode()
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining("/api/extension/auth/revoke"),
expect.objectContaining({
method: "POST",
headers: { Authorization: "Bearer zoo_ext_real_token" },
}),
)
expect(getCachedZooCodeToken()).toBe("")
expect(getCachedZooCodeUserInfo()).toEqual({
name: undefined,
email: undefined,
image: undefined,
})
})
})
})