forked from github/copilot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_github_token_provider.py
More file actions
273 lines (236 loc) · 10 KB
/
Copy pathtest_github_token_provider.py
File metadata and controls
273 lines (236 loc) · 10 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
from __future__ import annotations
import asyncio
from typing import Any, cast
import pytest
from copilot import (
CopilotClient,
GitHubTokenAcquireReason,
RuntimeConnection,
)
from copilot._jsonrpc import JsonRpcClient, JsonRpcError
from copilot.rpc import GitHubTokenAcquireRequest
class FakeJsonRpcClient:
def __init__(self, *, fail_method: str | None = None) -> None:
self.fail_method = fail_method
self.requests: list[tuple[str, dict[str, Any]]] = []
self.request_handlers: dict[str, Any] = {}
self.notification_method_handlers: dict[str, Any] = {}
async def request(self, method: str, params: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
self.requests.append((method, params))
if method == self.fail_method:
raise RuntimeError(f"{method} failed")
if method in {"session.create", "session.resume"}:
response = {"sessionId": params["sessionId"]}
callback = kwargs.get("on_response_inline")
if callback is not None:
callback(response)
return response
if method == "session.destroy":
return {}
if method == "session.delete":
return {"success": True}
raise RuntimeError(f"Unexpected method: {method}")
async def stop(self) -> None:
pass
def set_request_handler(self, method: str, handler: Any) -> None:
self.request_handlers[method] = handler
def set_notification_method_handler(self, method: str, handler: Any) -> None:
self.notification_method_handlers[method] = handler
class ConcurrentResumeJsonRpcClient(FakeJsonRpcClient):
def __init__(self) -> None:
super().__init__()
self.resume_responses: list[asyncio.Future[dict[str, Any]]] = []
async def request(self, method: str, params: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
self.requests.append((method, params))
if method == "session.create":
response = {"sessionId": params["sessionId"]}
callback = kwargs.get("on_response_inline")
if callback is not None:
callback(response)
return response
if method == "session.resume":
response = asyncio.get_running_loop().create_future()
self.resume_responses.append(response)
return await response
raise RuntimeError(f"Unexpected method: {method}")
def make_client(fake: FakeJsonRpcClient) -> CopilotClient:
client = CopilotClient(connection=RuntimeConnection.for_uri("localhost:1234"))
client._client = cast(JsonRpcClient, fake)
return client
class TestGitHubTokenProvider:
async def test_mutual_exclusion(self) -> None:
client = CopilotClient(connection=RuntimeConnection.for_uri("localhost:1234"))
with pytest.raises(
ValueError, match="github_token and github_token_provider are mutually exclusive"
):
await client.create_session(
github_token="static",
github_token_provider=lambda _: {"kind": "cancelled"},
)
async def test_wire_mapping_token_and_cancelled(self) -> None:
fake = FakeJsonRpcClient()
client = make_client(fake)
observed: list[dict[str, Any]] = []
async def provider(args):
observed.append(dict(args))
if len(observed) == 1:
return {
"kind": "token",
"accessToken": "secret-token",
"tokenType": "Bearer",
"expiresIn": 28_800,
}
return {"kind": "cancelled"}
await client.create_session(
session_id="python-session",
github_token_provider=provider,
)
create_payload = fake.requests[0][1]
registration_id = create_payload["gitHubTokenProviderRegistrationId"]
assert "github_token_provider" not in create_payload
assert "gitHubToken" not in create_payload
client._register_client_global_handlers()
get_token = fake.request_handlers["gitHubToken.getToken"]
token = await get_token(
{
"registrationId": registration_id,
"host": "github.example.com",
"reason": "initial",
}
)
cancelled = await get_token(
{
"registrationId": registration_id,
"host": "github.example.com",
"reason": "refresh",
"sessionId": "python-session",
}
)
assert token == {
"kind": "token",
"accessToken": "secret-token",
"tokenType": "Bearer",
"expiresIn": 28_800,
}
assert cancelled == {"kind": "cancelled"}
assert observed == [
{
"host": "github.example.com",
"session_id": "python-session",
"reason": GitHubTokenAcquireReason.INITIAL,
},
{
"host": "github.example.com",
"session_id": "python-session",
"reason": GitHubTokenAcquireReason.REFRESH,
},
]
async def test_callback_and_unknown_registration_errors(self) -> None:
fake = FakeJsonRpcClient()
client = make_client(fake)
failure = RuntimeError("credential broker failed")
def provider(_args):
raise failure
await client.create_session(
session_id="error-session",
github_token_provider=provider,
)
registration_id = fake.requests[0][1]["gitHubTokenProviderRegistrationId"]
with pytest.raises(RuntimeError, match="credential broker failed") as exc:
await client._github_token_provider_adapter.get_token(
GitHubTokenAcquireRequest(
registration_id=registration_id,
host="github.com",
reason=GitHubTokenAcquireReason.INITIAL,
)
)
assert exc.value is failure
with pytest.raises(JsonRpcError, match="No GitHub token provider registered"):
await client._github_token_provider_adapter.get_token(
GitHubTokenAcquireRequest(
registration_id="unknown",
host="github.com",
reason=GitHubTokenAcquireReason.REFRESH,
)
)
async def test_failure_session_close_and_client_close_cleanup(self) -> None:
failing = make_client(FakeJsonRpcClient(fail_method="session.create"))
with pytest.raises(RuntimeError, match="session.create failed"):
await failing.create_session(github_token_provider=lambda _: {"kind": "cancelled"})
assert failing._github_token_providers == {}
fake = FakeJsonRpcClient()
client = make_client(fake)
first = await client.create_session(
session_id="first",
github_token_provider=lambda _: {"kind": "cancelled"},
)
await client.create_session(
session_id="second",
github_token_provider=lambda _: {"kind": "cancelled"},
)
assert len(client._github_token_providers) == 2
await first.disconnect()
assert len(client._github_token_providers) == 1
await client.delete_session("second")
assert client._github_token_providers == {}
await client.force_stop()
assert client._github_token_providers == {}
async def test_resume_rotates_provider(self) -> None:
fake = FakeJsonRpcClient()
client = make_client(fake)
calls: list[str] = []
await client.create_session(
session_id="resumed",
github_token_provider=lambda _: calls.append("first") or {"kind": "cancelled"},
)
first_registration = fake.requests[0][1]["gitHubTokenProviderRegistrationId"]
await client.resume_session(
"resumed",
github_token_provider=lambda _: calls.append("second") or {"kind": "cancelled"},
)
second_registration = fake.requests[1][1]["gitHubTokenProviderRegistrationId"]
with pytest.raises(JsonRpcError):
await client._github_token_provider_adapter.get_token(
GitHubTokenAcquireRequest(
registration_id=first_registration,
host="github.com",
reason=GitHubTokenAcquireReason.REFRESH,
)
)
assert await client._github_token_provider_adapter.get_token(
GitHubTokenAcquireRequest(
registration_id=second_registration,
host="github.com",
reason=GitHubTokenAcquireReason.REFRESH,
)
) == {"kind": "cancelled"}
assert calls == ["second"]
async def test_concurrent_resume_keeps_pending_registration(self) -> None:
fake = ConcurrentResumeJsonRpcClient()
client = make_client(fake)
await client.create_session(
session_id="concurrent",
github_token_provider=lambda _: {"kind": "cancelled"},
)
first_resume = asyncio.create_task(
client.resume_session(
"concurrent",
github_token_provider=lambda _: {"kind": "cancelled"},
)
)
second_resume = asyncio.create_task(
client.resume_session(
"concurrent",
github_token_provider=lambda _: {"kind": "cancelled"},
)
)
while len(fake.resume_responses) < 2:
await asyncio.sleep(0)
fake.resume_responses[0].set_result({"sessionId": "concurrent"})
await first_resume
assert len(client._github_token_providers) == 2
fake.resume_responses[1].set_result({"sessionId": "concurrent"})
await second_resume
assert len(client._github_token_providers) == 1
second_registration = fake.requests[2][1]["gitHubTokenProviderRegistrationId"]
assert second_registration in client._github_token_providers