forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_auth_oauth.py
More file actions
309 lines (233 loc) · 11 KB
/
Copy pathtest_auth_oauth.py
File metadata and controls
309 lines (233 loc) · 11 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
"""Tests for the OAuth browser flow + refresh logic."""
from __future__ import annotations
import base64
import hashlib
import time
import httpx
import pytest
from omi_cli import config as cfg
from omi_cli.auth import oauth
from omi_cli.auth.store import store_oauth_tokens
from omi_cli.errors import AuthError, UsageError
# ---- needs_refresh ---------------------------------------------------------
def test_needs_refresh_returns_false_for_api_key_profile(config_path) -> None:
profile = cfg.Profile(name="default", auth_method="api_key", api_key="omi_dev_xxx")
assert oauth.needs_refresh(profile) is False
def test_needs_refresh_true_when_no_expiry(config_path) -> None:
profile = cfg.Profile(name="default", auth_method="oauth", id_token="t", refresh_token="r")
assert oauth.needs_refresh(profile) is True
def test_needs_refresh_true_when_expired(config_path) -> None:
profile = cfg.Profile(
name="default",
auth_method="oauth",
id_token="t",
refresh_token="r",
id_token_expires_at=time.time() - 5,
)
assert oauth.needs_refresh(profile) is True
def test_needs_refresh_false_when_far_from_expiry(config_path) -> None:
profile = cfg.Profile(
name="default",
auth_method="oauth",
id_token="t",
refresh_token="r",
id_token_expires_at=time.time() + 3000,
)
assert oauth.needs_refresh(profile) is False
# ---- refresh_id_token ------------------------------------------------------
def test_refresh_rejects_non_oauth_profile(config_path) -> None:
config = cfg.load()
profile = config.get_profile("default")
profile.auth_method = "api_key"
profile.api_key = "omi_dev_x"
config.set_profile(profile)
cfg.save(config)
with pytest.raises(UsageError):
oauth.refresh_id_token("default")
def test_refresh_persists_new_id_token(config_path, monkeypatch) -> None:
store_oauth_tokens(
"default",
id_token="old_id",
refresh_token="refr_1",
expires_at=time.time() - 10,
api_base="https://api.test.omi.local",
)
captured: dict = {}
def fake_post(self, url, **kwargs): # noqa: ANN001
captured["url"] = url
captured["data"] = kwargs.get("data")
return httpx.Response(
200,
json={"id_token": "new_id_token", "refresh_token": "refr_1", "expires_in": "3600"},
)
monkeypatch.setattr(httpx.Client, "post", fake_post)
new = oauth.refresh_id_token("default")
assert new == "new_id_token"
assert captured["data"] == {"grant_type": "refresh_token", "refresh_token": "refr_1"}
reloaded = cfg.load().get_profile("default")
assert reloaded.id_token == "new_id_token"
assert reloaded.refresh_token == "refr_1"
# Expiry should be roughly now + 3600 - margin (60).
assert abs((reloaded.id_token_expires_at or 0) - (time.time() + 3540)) < 5
def test_refresh_persists_rotated_refresh_token(config_path, monkeypatch) -> None:
store_oauth_tokens(
"default",
id_token="old_id",
refresh_token="refr_old",
expires_at=time.time() - 10,
api_base="https://api.test.omi.local",
)
def fake_post(self, url, **kwargs): # noqa: ANN001
return httpx.Response(
200,
json={"id_token": "new_id", "refresh_token": "refr_new_rotated", "expires_in": "3600"},
)
monkeypatch.setattr(httpx.Client, "post", fake_post)
oauth.refresh_id_token("default")
reloaded = cfg.load().get_profile("default")
assert reloaded.id_token == "new_id"
assert reloaded.refresh_token == "refr_new_rotated"
def test_refresh_surfaces_firebase_error(config_path, monkeypatch) -> None:
store_oauth_tokens(
"default",
id_token="old_id",
refresh_token="refr_bad",
expires_at=time.time() - 10,
api_base="https://api.test.omi.local",
)
def fake_post(self, url, **kwargs): # noqa: ANN001
return httpx.Response(401, json={"error": {"message": "INVALID_REFRESH_TOKEN"}})
monkeypatch.setattr(httpx.Client, "post", fake_post)
with pytest.raises(AuthError) as info:
oauth.refresh_id_token("default")
assert "401" in str(info.value)
# ---- login_with_browser surface ------------------------------------------
def test_login_with_browser_rejects_unknown_provider(config_path) -> None:
with pytest.raises(UsageError):
oauth.login_with_browser(
"default",
api_base="https://api.test.omi.local",
provider="microsoft", # unsupported
open_browser=False,
)
# ---- code-exchange wiring -------------------------------------------------
def test_exchange_code_for_custom_token_happy_path(monkeypatch) -> None:
captured: dict = {}
def fake_post(self, url, **kwargs): # noqa: ANN001
captured["url"] = url
captured["data"] = kwargs.get("data")
return httpx.Response(200, json={"custom_token": "ct_abc", "id_token": "google_id"})
monkeypatch.setattr(httpx.Client, "post", fake_post)
token = oauth._exchange_code_for_custom_token(
"https://api.test.omi.local",
code="auth_code",
redirect_uri="http://127.0.0.1:5555/callback",
code_verifier="verifier-123",
)
assert token == "ct_abc"
assert captured["url"] == "https://api.test.omi.local/v1/auth/token"
assert captured["data"]["grant_type"] == "authorization_code"
assert captured["data"]["use_custom_token"] == "true"
assert captured["data"]["code_verifier"] == "verifier-123"
def test_generate_pkce_pair_uses_s256_challenge() -> None:
code_verifier, code_challenge = oauth._generate_pkce_pair()
expected = (
base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii")
)
assert 43 <= len(code_verifier) <= 128
assert code_challenge == expected
def test_exchange_code_raises_on_non_200(monkeypatch) -> None:
def fake_post(self, url, **kwargs): # noqa: ANN001
return httpx.Response(400, json={"detail": "Invalid or expired code"})
monkeypatch.setattr(httpx.Client, "post", fake_post)
with pytest.raises(AuthError):
oauth._exchange_code_for_custom_token(
"https://api.test.omi.local",
code="bad",
redirect_uri="http://127.0.0.1:5555/callback",
code_verifier="verifier-123",
)
def test_exchange_code_raises_when_custom_token_missing(monkeypatch) -> None:
def fake_post(self, url, **kwargs): # noqa: ANN001
return httpx.Response(200, json={"id_token": "google_only", "access_token": "g"})
monkeypatch.setattr(httpx.Client, "post", fake_post)
with pytest.raises(AuthError) as info:
oauth._exchange_code_for_custom_token(
"https://api.test.omi.local",
code="ok",
redirect_uri="http://127.0.0.1:5555/callback",
code_verifier="verifier-123",
)
assert "custom token" in str(info.value).lower()
def test_firebase_signin_with_custom_token_returns_tokens(monkeypatch) -> None:
def fake_post(self, url, **kwargs): # noqa: ANN001
assert "signInWithCustomToken" in url
return httpx.Response(
200,
json={"idToken": "fb_id", "refreshToken": "fb_refr", "expiresIn": "3600"},
)
monkeypatch.setattr(httpx.Client, "post", fake_post)
id_token, refresh_token, expires_in = oauth._firebase_signin_with_custom_token("ct")
assert id_token == "fb_id"
assert refresh_token == "fb_refr"
assert expires_in == 3600
def test_firebase_signin_raises_on_missing_tokens(monkeypatch) -> None:
def fake_post(self, url, **kwargs): # noqa: ANN001
return httpx.Response(200, json={"idToken": "fb_id"}) # missing refreshToken
monkeypatch.setattr(httpx.Client, "post", fake_post)
with pytest.raises(AuthError):
oauth._firebase_signin_with_custom_token("ct")
# ---- Firebase session -> dev API key exchange -----------------------------
def test_exchange_firebase_token_mints_key_and_replaces_own(monkeypatch) -> None:
calls: dict = {"deleted": [], "post": None}
name = oauth._cli_key_name()
def fake_get(self, url, **kwargs): # noqa: ANN001
# One key that's ours (exact name match) + one unrelated key.
return httpx.Response(
200,
json=[
{"id": "ours-1", "name": name},
{"id": "other", "name": "someone elses key"},
],
)
def fake_delete(self, url, **kwargs): # noqa: ANN001
calls["deleted"].append(url)
return httpx.Response(204)
def fake_post(self, url, **kwargs): # noqa: ANN001
calls["post"] = (url, kwargs.get("json"), kwargs.get("headers"))
return httpx.Response(200, json={"id": "new", "name": name, "key": "omi_dev_minted"})
monkeypatch.setattr(httpx.Client, "get", fake_get)
monkeypatch.setattr(httpx.Client, "delete", fake_delete)
monkeypatch.setattr(httpx.Client, "post", fake_post)
key = oauth._exchange_firebase_token_for_dev_key("https://api.test.omi.local/", "fb_id_tok")
assert key == "omi_dev_minted"
# Only our own key was deleted; the unrelated one was left alone.
assert calls["deleted"] == ["https://api.test.omi.local/v1/dev/keys/ours-1"]
url, body, headers = calls["post"]
assert url == "https://api.test.omi.local/v1/dev/keys"
assert body["name"] == name
assert body["scopes"] == oauth._CLI_KEY_SCOPES
assert headers["Authorization"] == "Bearer fb_id_tok"
def test_exchange_firebase_token_proceeds_when_listing_fails(monkeypatch) -> None:
def fake_get(self, url, **kwargs): # noqa: ANN001
raise httpx.ConnectError("listing unavailable")
def fake_post(self, url, **kwargs): # noqa: ANN001
return httpx.Response(200, json={"key": "omi_dev_after_failed_list"})
monkeypatch.setattr(httpx.Client, "get", fake_get)
monkeypatch.setattr(httpx.Client, "post", fake_post)
key = oauth._exchange_firebase_token_for_dev_key("https://api.test.omi.local", "tok")
assert key == "omi_dev_after_failed_list"
def test_exchange_firebase_token_raises_on_non_200(monkeypatch) -> None:
monkeypatch.setattr(httpx.Client, "get", lambda self, url, **kw: httpx.Response(200, json=[]))
monkeypatch.setattr(httpx.Client, "post", lambda self, url, **kw: httpx.Response(403, json={"detail": "nope"}))
with pytest.raises(AuthError) as info:
oauth._exchange_firebase_token_for_dev_key("https://api.test.omi.local", "tok")
assert "create an api key" in str(info.value).lower()
def test_exchange_firebase_token_raises_when_key_field_missing(monkeypatch) -> None:
monkeypatch.setattr(httpx.Client, "get", lambda self, url, **kw: httpx.Response(200, json=[]))
monkeypatch.setattr(
httpx.Client, "post", lambda self, url, **kw: httpx.Response(200, json={"id": "x", "name": "y"})
)
with pytest.raises(AuthError) as info:
oauth._exchange_firebase_token_for_dev_key("https://api.test.omi.local", "tok")
assert "missing the api key" in str(info.value).lower()