mouter-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mouter_cli/oauth.py ADDED
@@ -0,0 +1,444 @@
1
+ """Browser PKCE authorization and serialized rotating credentials. No browser cookies."""
2
+
3
+ import asyncio
4
+ import base64
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import math
9
+ import os
10
+ import re
11
+ import secrets
12
+ import socket
13
+ import sys
14
+ import threading
15
+ import time
16
+ import webbrowser
17
+ from http.server import BaseHTTPRequestHandler, HTTPServer
18
+ from typing import Any
19
+ from urllib.parse import parse_qs, urlencode, urlsplit
20
+
21
+ import httpx
22
+
23
+ from mouter_cli.client import Client
24
+ from mouter_cli.config import api_origin
25
+ from mouter_cli.errors import CliError
26
+ from mouter_cli.storage import Credentials
27
+
28
+ SCOPES = "tools:execute tasks:read billing:read"
29
+
30
+
31
+ def auth_error(
32
+ message: str = "CLI authorization expired or was revoked; run mouter auth login.",
33
+ ) -> CliError:
34
+ return CliError("UNAUTHENTICATED", message, 3)
35
+
36
+
37
+ class OAuthHTTP:
38
+ def __init__(self, *, transport: httpx.AsyncBaseTransport | None = None) -> None:
39
+ self.runner = asyncio.Runner()
40
+ self.http = httpx.AsyncClient(
41
+ follow_redirects=False, trust_env=False, timeout=30, transport=transport
42
+ )
43
+
44
+ def __enter__(self) -> "OAuthHTTP":
45
+ return self
46
+
47
+ def __exit__(self, *_: Any) -> None:
48
+ try:
49
+ self.runner.run(self.http.aclose())
50
+ finally:
51
+ self.runner.close()
52
+
53
+ async def _request(
54
+ self, method: str, url: str, body: dict[str, Any] | None, form: bool, remaining: float
55
+ ) -> tuple[int, bytes]:
56
+ async with asyncio.timeout(remaining):
57
+ options: dict[str, Any] = {"data": body} if form else {"json": body}
58
+ async with self.http.stream(method, url, timeout=remaining, **options) as response:
59
+ data = bytearray()
60
+ async for chunk in response.aiter_bytes():
61
+ data.extend(chunk)
62
+ if len(data) > 256 * 1024:
63
+ raise ValueError
64
+ return response.status_code, bytes(data)
65
+
66
+ def request(
67
+ self,
68
+ method: str,
69
+ url: str,
70
+ body: dict[str, Any] | None = None,
71
+ *,
72
+ form: bool = False,
73
+ deadline: float | None = None,
74
+ ) -> dict[str, Any]:
75
+ # Authorization POSTs (including refresh rotation) are never automatically retried.
76
+ try:
77
+ now = time.monotonic()
78
+ wait_limited = deadline is not None and deadline - now <= 30
79
+ remaining = min(30, deadline - now) if deadline is not None else 30
80
+ if remaining <= 0:
81
+ raise CliError(
82
+ "WAIT_TIMEOUT", "Authorization deadline reached; resume the task.", 6
83
+ )
84
+ status, content = self.runner.run(self._request(method, url, body, form, remaining))
85
+ if status in {400, 401, 403}:
86
+ raise auth_error()
87
+ if status != 200 and status != 201:
88
+ raise CliError(
89
+ "AUTH_NETWORK_ERROR",
90
+ "Authorization request failed; retry login or inspect auth status.",
91
+ 3,
92
+ )
93
+ if not content:
94
+ return {}
95
+ value = json.loads(content)
96
+ if not isinstance(value, dict):
97
+ raise ValueError
98
+ return value
99
+ except CliError:
100
+ raise
101
+ except (httpx.HTTPError, TimeoutError, ValueError, UnicodeError) as exc:
102
+ # Windows event-loop timers may fire just before monotonic observes
103
+ # the deadline; the timer's budget still identifies a wait timeout.
104
+ if deadline is not None and (
105
+ time.monotonic() >= deadline or (wait_limited and isinstance(exc, TimeoutError))
106
+ ):
107
+ raise CliError(
108
+ "WAIT_TIMEOUT", "Authorization deadline reached; resume the task.", 6
109
+ ) from None
110
+ raise CliError(
111
+ "AUTH_NETWORK_ERROR",
112
+ "Authorization could not complete; run auth status before retrying.",
113
+ 3,
114
+ ) from None
115
+
116
+
117
+ def endpoint(value: Any, origin: str | None = None) -> str:
118
+ if not isinstance(value, str) or len(value) > 2048:
119
+ raise auth_error("Invalid authorization server metadata.")
120
+ parsed = urlsplit(value)
121
+ base = api_origin(f"{parsed.scheme}://{parsed.netloc}")
122
+ if (
123
+ (origin is not None and base != origin)
124
+ or parsed.query
125
+ or parsed.fragment
126
+ or parsed.username
127
+ or "\\" in value
128
+ ):
129
+ raise auth_error("Untrusted authorization endpoint.")
130
+ return value
131
+
132
+
133
+ def token_record(value: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
134
+ access, refresh, expiry = (
135
+ value.get("access_token"),
136
+ value.get("refresh_token"),
137
+ value.get("expires_in"),
138
+ )
139
+ scope = value.get("scope")
140
+ if (
141
+ not isinstance(access, str)
142
+ or not re.fullmatch(r"mat_[A-Za-z0-9_-]{43}", access)
143
+ or not isinstance(refresh, str)
144
+ or not re.fullmatch(r"mrt_[A-Za-z0-9_-]{43}", refresh)
145
+ or value.get("token_type", "").lower() != "bearer"
146
+ or type(expiry) is not int
147
+ or not 0 < expiry <= 86400
148
+ or not isinstance(scope, str)
149
+ or not set(SCOPES.split()) <= set(scope.split())
150
+ ):
151
+ raise auth_error("Invalid or incomplete CLI authorization response.")
152
+ return {
153
+ **metadata,
154
+ "access_token": access,
155
+ "refresh_token": refresh,
156
+ "expires_at": time.time() + expiry,
157
+ }
158
+
159
+
160
+ def validate_record(record: dict[str, Any]) -> None:
161
+ try:
162
+ issuer = api_origin(record["issuer"])
163
+ endpoint(record["token_endpoint"], issuer)
164
+ endpoint(record["revocation_endpoint"], issuer)
165
+ endpoint(record["resource"], issuer)
166
+ if (
167
+ not re.fullmatch(r"mc_[A-Za-z0-9_-]{43}", record["client_id"])
168
+ or not re.fullmatch(r"mat_[A-Za-z0-9_-]{43}", record["access_token"])
169
+ or not re.fullmatch(r"mrt_[A-Za-z0-9_-]{43}", record["refresh_token"])
170
+ or not re.fullmatch(r"[A-Za-z0-9_-]{1,80}", record["grant_uid"])
171
+ or type(record["expires_at"]) not in {int, float}
172
+ or not math.isfinite(record["expires_at"])
173
+ ):
174
+ raise ValueError
175
+ except (KeyError, TypeError, ValueError):
176
+ raise auth_error("Stored CLI authorization is invalid; run mouter auth login.") from None
177
+
178
+
179
+ class LoopbackServer(HTTPServer):
180
+ deadline: float
181
+
182
+ def get_request(self) -> Any:
183
+ connection, address = super().get_request()
184
+ connection.settimeout(1)
185
+ return connection, address
186
+
187
+ def process_request(self, request: Any, client_address: Any) -> None:
188
+ # A per-recv timeout cannot stop a peer trickling HTTP headers indefinitely.
189
+ def stop() -> None:
190
+ try:
191
+ request.shutdown(socket.SHUT_RDWR)
192
+ except OSError:
193
+ pass
194
+
195
+ timer = threading.Timer(max(0, self.deadline - time.monotonic()), stop)
196
+ timer.daemon = True
197
+ timer.start()
198
+ try:
199
+ super().process_request(request, client_address)
200
+ finally:
201
+ timer.cancel()
202
+
203
+ def handle_error(self, request: Any, client_address: Any) -> None:
204
+ # Browser disconnects/invalid callbacks must not print tracebacks or request data.
205
+ pass
206
+
207
+
208
+ def receive_code(
209
+ url: str, client_id: str, resource: str, *, timeout: float, no_browser: bool
210
+ ) -> tuple[str, str, str]:
211
+ state, verifier = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
212
+ proof = (
213
+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
214
+ )
215
+ received: dict[str, str] = {}
216
+
217
+ class Callback(BaseHTTPRequestHandler):
218
+ def log_message(self, *_: Any) -> None:
219
+ pass
220
+
221
+ def do_GET(self) -> None:
222
+ parsed = urlsplit(self.path)
223
+ try:
224
+ query = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=12)
225
+ except ValueError:
226
+ self.send_error(400, "Invalid callback")
227
+ return
228
+ valid = (
229
+ parsed.path == "/callback"
230
+ and self.headers.get("Host") == f"127.0.0.1:{server.server_port}"
231
+ and len(query.get("state", [])) == 1
232
+ and hmac.compare_digest(query["state"][0], state)
233
+ and (len(query.get("code", [])) == 1 or len(query.get("error", [])) == 1)
234
+ )
235
+ self.send_response(200 if valid else 400)
236
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
237
+ self.send_header("Cache-Control", "no-store")
238
+ self.send_header("Content-Security-Policy", "default-src 'none'")
239
+ self.end_headers()
240
+ self.wfile.write(
241
+ b"Authorization received. Return to your terminal."
242
+ if valid
243
+ else b"Invalid callback."
244
+ )
245
+ if valid:
246
+ received.update(code=query.get("code", [""])[0], error=query.get("error", [""])[0])
247
+
248
+ with LoopbackServer(("127.0.0.1", 0), Callback) as server:
249
+ server.timeout = 0.2
250
+ server.deadline = time.monotonic() + timeout
251
+ redirect = f"http://127.0.0.1:{server.server_port}/callback"
252
+ authorization = (
253
+ url
254
+ + "?"
255
+ + urlencode(
256
+ {
257
+ "client_id": client_id,
258
+ "response_type": "code",
259
+ "redirect_uri": redirect,
260
+ "code_challenge": proof,
261
+ "code_challenge_method": "S256",
262
+ "resource": resource,
263
+ "scope": SCOPES,
264
+ "state": state,
265
+ }
266
+ )
267
+ )
268
+ print("Authorize Mouter CLI in your browser:\n" + authorization, file=sys.stderr)
269
+ if not no_browser:
270
+ webbrowser.open(authorization)
271
+ end = server.deadline
272
+ while not received and time.monotonic() < end:
273
+ server.handle_request()
274
+ if not received:
275
+ raise CliError(
276
+ "AUTH_TIMEOUT", "Browser authorization timed out; run mouter auth login.", 3
277
+ )
278
+ if received["error"] or not re.fullmatch(r"[A-Za-z0-9_-]{1,256}", received["code"]):
279
+ raise auth_error("Browser authorization was declined or failed.")
280
+ return received["code"], verifier, redirect
281
+
282
+
283
+ def login(
284
+ origin: str, store: Credentials, *, timeout: float = 180, no_browser: bool = False
285
+ ) -> dict[str, Any]:
286
+ # Fail before asking the user to authorize if this machine cannot store credentials.
287
+ store.prepare()
288
+ with store.lock():
289
+ if store.oauth() is not None:
290
+ raise auth_error(
291
+ "A CLI authorization is already saved; run auth logout before changing accounts."
292
+ )
293
+ with OAuthHTTP() as http:
294
+ protected = http.request("GET", origin + "/.well-known/oauth-protected-resource/v1")
295
+ servers = protected.get("authorization_servers")
296
+ if not isinstance(servers, list) or len(servers) != 1:
297
+ raise auth_error("Invalid authorization discovery metadata.")
298
+ issuer = api_origin(servers[0])
299
+ resource = endpoint(protected.get("resource"), issuer)
300
+ metadata = http.request("GET", issuer + "/.well-known/oauth-authorization-server")
301
+ if metadata.get("issuer") != issuer or "S256" not in metadata.get(
302
+ "code_challenge_methods_supported", []
303
+ ):
304
+ raise auth_error("Authorization server does not support CLI PKCE.")
305
+ token_url = endpoint(metadata.get("token_endpoint"), issuer)
306
+ revoke_url = endpoint(metadata.get("revocation_endpoint"), issuer)
307
+ registration = endpoint(metadata.get("registration_endpoint"), issuer)
308
+ authorize = endpoint(metadata.get("authorization_endpoint"))
309
+ # Native loopback port is ephemeral; server matches the registered path/IP.
310
+ registered = http.request(
311
+ "POST",
312
+ registration,
313
+ {
314
+ "client_name": "Mouter CLI",
315
+ "redirect_uris": ["http://127.0.0.1/callback"],
316
+ "scope": SCOPES,
317
+ },
318
+ )
319
+ client_id = registered.get("client_id")
320
+ if not isinstance(client_id, str) or not re.fullmatch(
321
+ r"mc_[A-Za-z0-9_-]{43}", client_id
322
+ ):
323
+ raise auth_error("Invalid CLI client registration.")
324
+ code, verifier, redirect = receive_code(
325
+ authorize, client_id, resource, timeout=timeout, no_browser=no_browser
326
+ )
327
+ tokens = http.request(
328
+ "POST",
329
+ token_url,
330
+ {
331
+ "grant_type": "authorization_code",
332
+ "client_id": client_id,
333
+ "code": code,
334
+ "code_verifier": verifier,
335
+ "redirect_uri": redirect,
336
+ "resource": resource,
337
+ },
338
+ form=True,
339
+ )
340
+ record = token_record(
341
+ tokens,
342
+ {
343
+ "issuer": issuer,
344
+ "resource": resource,
345
+ "client_id": client_id,
346
+ "token_endpoint": token_url,
347
+ "revocation_endpoint": revoke_url,
348
+ },
349
+ )
350
+ try:
351
+ with Client(origin, record["access_token"]) as client:
352
+ identity = client.request("GET", "/v1/credentials/current", authenticated=True)
353
+ record["grant_uid"] = identity["data"]["grant_uid"]
354
+ validate_record(record)
355
+ store.save_oauth(record)
356
+ # OAuth becomes the saved default. Environment overrides remain explicit.
357
+ store.delete()
358
+ except BaseException:
359
+ http.request(
360
+ "POST",
361
+ revoke_url,
362
+ {"client_id": client_id, "token": record["refresh_token"]},
363
+ form=True,
364
+ )
365
+ raise
366
+ identity["meta"] = {
367
+ "saved": True,
368
+ "credential_type": "oauth",
369
+ "environment_key_present": "MOUTER_API_KEY" in os.environ,
370
+ }
371
+ return identity
372
+
373
+
374
+ def access_token(
375
+ store: Credentials,
376
+ *,
377
+ expected_grant: str | None = None,
378
+ expected_client: str | None = None,
379
+ deadline: float | None = None,
380
+ ) -> str:
381
+ with store.lock(deadline):
382
+ record = store.oauth()
383
+ if record is None:
384
+ raise auth_error()
385
+ validate_record(record)
386
+ if (expected_grant is not None and record["grant_uid"] != expected_grant) or (
387
+ expected_client is not None and record["client_id"] != expected_client
388
+ ):
389
+ raise auth_error(
390
+ "Saved CLI identity changed; restart the command with the intended account."
391
+ )
392
+ if record["expires_at"] <= time.time() + 60:
393
+ with OAuthHTTP() as http:
394
+ value = http.request(
395
+ "POST",
396
+ record["token_endpoint"],
397
+ {
398
+ "grant_type": "refresh_token",
399
+ "client_id": record["client_id"],
400
+ "refresh_token": record["refresh_token"],
401
+ "resource": record["resource"],
402
+ },
403
+ form=True,
404
+ deadline=deadline,
405
+ )
406
+ record = token_record(value, record)
407
+ try:
408
+ store.save_oauth(record)
409
+ except CliError:
410
+ # Rotation may have consumed the previous refresh token. Revoke the
411
+ # new family if file persistence fails; never continue with it.
412
+ try:
413
+ with OAuthHTTP() as http:
414
+ http.request(
415
+ "POST",
416
+ record["revocation_endpoint"],
417
+ {
418
+ "client_id": record["client_id"],
419
+ "token": record["refresh_token"],
420
+ },
421
+ form=True,
422
+ deadline=deadline,
423
+ )
424
+ except CliError:
425
+ pass
426
+ raise
427
+ return str(record["access_token"])
428
+
429
+
430
+ def logout(store: Credentials) -> bool:
431
+ with store.lock():
432
+ record = store.oauth()
433
+ if record is not None:
434
+ validate_record(record)
435
+ with OAuthHTTP() as http:
436
+ http.request(
437
+ "POST",
438
+ record["revocation_endpoint"],
439
+ {"client_id": record["client_id"], "token": record["refresh_token"]},
440
+ form=True,
441
+ )
442
+ store.delete_oauth()
443
+ store.delete()
444
+ return record is not None