Repository navigation
Expand file tree
/
Copy pathgithub-token-provider.test.ts
More file actions
292 lines (273 loc) · 10.6 KB
/
Copy pathgithub-token-provider.test.ts
File metadata and controls
292 lines (273 loc) · 10.6 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
import { describe, expect, it, vi } from "vitest";
import { CopilotClient, RuntimeConnection, type GitHubTokenProvider } from "../src/index.js";
function createMockClient(
request: (method: string, params: Record<string, unknown>) => Promise<unknown>
): CopilotClient {
const client = new CopilotClient({
connection: RuntimeConnection.forUri("localhost:1234"),
});
(client as unknown as { connection: unknown }).connection = {
sendRequest: request,
dispose: vi.fn(),
};
return client;
}
function getTokenHandler(client: CopilotClient) {
return (
client as unknown as {
clientGlobalHandlers: {
gitHubToken: {
getToken(params: {
registrationId: string;
host: string;
sessionId?: string;
reason: "initial" | "refresh";
}): Promise<unknown>;
};
};
}
).clientGlobalHandlers.gitHubToken.getToken;
}
describe("session GitHub token providers", () => {
it("rejects a static token and provider together", async () => {
const client = new CopilotClient({
connection: RuntimeConnection.forUri("localhost:1234"),
});
await expect(
client.createSession({
gitHubToken: "static",
gitHubTokenProvider: async () => ({
kind: "token",
accessToken: "dynamic",
expiresIn: 28_800,
}),
})
).rejects.toThrow("gitHubToken and gitHubTokenProvider are mutually exclusive");
});
it("serializes only the opaque registration and maps token and cancellation results", async () => {
let createPayload: Record<string, unknown> | undefined;
const request = vi.fn(async (method: string, params: Record<string, unknown>) => {
if (method === "session.create") {
createPayload = params;
return { sessionId: params.sessionId };
}
throw new Error(`Unexpected method: ${method}`);
});
const observed: unknown[] = [];
const provider: GitHubTokenProvider = vi
.fn()
.mockImplementationOnce(async (args) => {
observed.push(args);
return {
kind: "token",
accessToken: "secret-token",
tokenType: "Bearer",
expiresIn: 28_800,
};
})
.mockImplementationOnce(async (args) => {
observed.push(args);
return { kind: "cancelled" };
});
const client = createMockClient(request);
const session = await client.createSession({
sessionId: "session-one",
gitHubTokenProvider: provider,
});
const registrationId = createPayload?.gitHubTokenProviderRegistrationId;
expect(registrationId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
);
expect(createPayload).not.toHaveProperty("gitHubTokenProvider");
expect(createPayload?.gitHubToken).toBeUndefined();
const handler = getTokenHandler(client);
await expect(
handler({
registrationId: registrationId as string,
host: "github.example.com",
reason: "initial",
})
).resolves.toEqual({
kind: "token",
accessToken: "secret-token",
tokenType: "Bearer",
expiresIn: 28_800,
});
await expect(
handler({
registrationId: registrationId as string,
host: "github.example.com",
sessionId: session.sessionId,
reason: "refresh",
})
).resolves.toEqual({ kind: "cancelled" });
expect(observed).toEqual([
{
host: "github.example.com",
sessionId: "session-one",
reason: "initial",
},
{
host: "github.example.com",
sessionId: "session-one",
reason: "refresh",
},
]);
});
it("preserves callback errors and rejects unknown registrations", async () => {
const client = createMockClient(async (_method, params) => ({
sessionId: params.sessionId,
}));
const failure = new Error("credential broker failed");
await client.createSession({
sessionId: "error-session",
gitHubTokenProvider: () => {
throw failure;
},
});
const registrationId = [
...(
client as unknown as {
githubTokenProviders: Map<string, unknown>;
}
).githubTokenProviders.keys(),
][0];
const handler = getTokenHandler(client);
await expect(
handler({
registrationId,
host: "github.com",
reason: "initial",
})
).rejects.toBe(failure);
await expect(
handler({
registrationId: "unknown",
host: "github.com",
reason: "refresh",
})
).rejects.toThrow("No GitHub token provider registered");
});
it("rolls back failed creation and cleans up on session and client close", async () => {
const failingClient = createMockClient(async () => {
throw new Error("create failed");
});
await expect(
failingClient.createSession({
gitHubTokenProvider: async () => ({ kind: "cancelled" }),
})
).rejects.toThrow("create failed");
expect(
(
failingClient as unknown as {
githubTokenProviders: Map<string, unknown>;
}
).githubTokenProviders
).toHaveLength(0);
const client = createMockClient(async (method, params) => {
if (method === "session.create") return { sessionId: params.sessionId };
if (method === "session.detach") return { success: true };
if (method === "session.delete") return { success: true };
throw new Error(`Unexpected method: ${method}`);
});
const first = await client.createSession({
sessionId: "first",
gitHubTokenProvider: async () => ({ kind: "cancelled" }),
});
await client.createSession({
sessionId: "second",
gitHubTokenProvider: async () => ({ kind: "cancelled" }),
});
const registrations = (
client as unknown as {
githubTokenProviders: Map<string, unknown>;
}
).githubTokenProviders;
expect(registrations).toHaveLength(2);
await first.disconnect();
expect(registrations).toHaveLength(1);
await client.deleteSession("second");
expect(registrations).toHaveLength(0);
await client.forceStop();
expect(registrations).toHaveLength(0);
});
it("rotates a resumed session only after resume succeeds", async () => {
const payloads: Record<string, unknown>[] = [];
const client = createMockClient(async (method, params) => {
payloads.push(params);
if (method === "session.create" || method === "session.resume") {
return { sessionId: params.sessionId };
}
throw new Error(`Unexpected method: ${method}`);
});
const firstProvider = vi.fn(async () => ({ kind: "cancelled" as const }));
const secondProvider = vi.fn(async () => ({ kind: "cancelled" as const }));
await client.createSession({
sessionId: "resumed",
gitHubTokenProvider: firstProvider,
});
const firstRegistration = payloads[0].gitHubTokenProviderRegistrationId as string;
await client.resumeSession("resumed", {
gitHubTokenProvider: secondProvider,
});
const secondRegistration = payloads[1].gitHubTokenProviderRegistrationId as string;
const handler = getTokenHandler(client);
await expect(
handler({
registrationId: firstRegistration,
host: "github.com",
reason: "refresh",
})
).rejects.toThrow("No GitHub token provider registered");
await expect(
handler({
registrationId: secondRegistration,
host: "github.com",
reason: "refresh",
})
).resolves.toEqual({ kind: "cancelled" });
expect(secondProvider).toHaveBeenCalledOnce();
expect(firstProvider).not.toHaveBeenCalled();
});
it("does not retire a concurrent pending registration", async () => {
const resumeResolvers: Array<(value: { sessionId: string }) => void> = [];
const payloads: Record<string, unknown>[] = [];
const client = createMockClient(async (method, params) => {
payloads.push(params);
if (method === "session.create") {
return { sessionId: params.sessionId };
}
if (method === "session.resume") {
return await new Promise<{ sessionId: string }>((resolve) => {
resumeResolvers.push(resolve);
});
}
throw new Error(`Unexpected method: ${method}`);
});
await client.createSession({
sessionId: "concurrent",
gitHubTokenProvider: async () => ({ kind: "cancelled" }),
});
const firstResume = client.resumeSession("concurrent", {
gitHubTokenProvider: async () => ({ kind: "cancelled" }),
});
const secondResume = client.resumeSession("concurrent", {
gitHubTokenProvider: async () => ({ kind: "cancelled" }),
});
await vi.waitFor(() => expect(resumeResolvers).toHaveLength(2));
resumeResolvers[0]({ sessionId: "concurrent" });
await firstResume;
const registrations = (
client as unknown as {
githubTokenProviders: Map<string, unknown>;
}
).githubTokenProviders;
expect(registrations).toHaveLength(2);
resumeResolvers[1]({ sessionId: "concurrent" });
await secondResume;
expect(registrations).toHaveLength(1);
expect(registrations.has(payloads[2].gitHubTokenProviderRegistrationId as string)).toBe(
true
);
});
});