brewsorted-cli 0.8.4__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.
@@ -0,0 +1,273 @@
1
+ """Protected, single-binding OAuth state for the future private CLI cutover."""
2
+ from __future__ import annotations
3
+
4
+ import fcntl
5
+ import json
6
+ import os
7
+ import secrets
8
+ import stat
9
+ import time
10
+ from contextlib import contextmanager
11
+ from dataclasses import asdict, dataclass, replace
12
+ from pathlib import Path
13
+ from typing import Callable, Iterator
14
+ from urllib.parse import urlsplit
15
+
16
+ import httpx
17
+
18
+ from . import USER_AGENT
19
+ from .http import http_client
20
+
21
+
22
+ class AuthStateError(ValueError):
23
+ pass
24
+
25
+
26
+ class SignInRequired(AuthStateError):
27
+ pass
28
+
29
+
30
+ class IssuerUnavailable(AuthStateError):
31
+ pass
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class AuthBinding:
36
+ format_version: int
37
+ service_origin: str
38
+ issuer: str
39
+ subject: str
40
+ username: str
41
+ audience: str
42
+ client_id: str
43
+ token_endpoint: str
44
+ revocation_endpoint: str
45
+ access_token: str
46
+ refresh_token: str
47
+ expires_at: int
48
+
49
+ def __post_init__(self) -> None:
50
+ if type(self.format_version) is not int or self.format_version != 1:
51
+ raise AuthStateError("Unknown credential file version; use login again")
52
+ if not all(isinstance(value, str) and value for value in (
53
+ self.service_origin, self.issuer, self.subject, self.username,
54
+ self.audience, self.client_id, self.token_endpoint,
55
+ self.revocation_endpoint, self.access_token, self.refresh_token,
56
+ )) or type(self.expires_at) is not int:
57
+ raise AuthStateError("Credential file is invalid; use login again")
58
+ parsed = urlsplit(self.service_origin)
59
+ loopback = parsed.hostname in {"127.0.0.1", "::1", "localhost"}
60
+ if (parsed.scheme not in ({"http", "https"} if loopback else {"https"})
61
+ or not parsed.netloc or parsed.path or parsed.query or parsed.fragment
62
+ or self.issuer != f"{self.service_origin}/id/realms/brewsorted"
63
+ or self.token_endpoint != f"{self.issuer}/protocol/openid-connect/token"
64
+ or self.revocation_endpoint != f"{self.issuer}/protocol/openid-connect/revoke"
65
+ or self.audience != "brewsorted-api"
66
+ or self.client_id != "brewsorted-cli"):
67
+ raise AuthStateError("Credential issuer does not match the selected service")
68
+
69
+
70
+ def default_state_path() -> Path:
71
+ base = os.environ.get("XDG_STATE_HOME")
72
+ if base is not None:
73
+ root = Path(base)
74
+ if not root.is_absolute():
75
+ raise AuthStateError("XDG_STATE_HOME must be absolute")
76
+ else:
77
+ root = Path.home() / ".local" / "state"
78
+ return root / "brewsorted" / "auth.json"
79
+
80
+
81
+ def select_state_path(
82
+ service_origin: str, default_origin: str, override: str | None = None,
83
+ ) -> Path:
84
+ explicit = override or os.environ.get("BREWSORTED_STATE_FILE")
85
+ if service_origin != default_origin and explicit is None:
86
+ raise AuthStateError("A custom service requires an explicit separate --state-file")
87
+ selected = Path(explicit) if explicit else default_state_path()
88
+ if not selected.is_absolute():
89
+ raise AuthStateError("Credential file path must be absolute")
90
+ if selected.name in {"", ".", ".."}:
91
+ raise AuthStateError("Credential file path is invalid")
92
+ return selected
93
+
94
+
95
+ class AuthState:
96
+ def __init__(self, path: Path, service_origin: str):
97
+ if not path.is_absolute():
98
+ raise AuthStateError("Credential file path must be absolute")
99
+ self.path = path
100
+ self.service_origin = service_origin
101
+
102
+ def _prepare_directory(self) -> None:
103
+ self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
104
+ info = self.path.parent.lstat()
105
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
106
+ raise AuthStateError("Credential directory must be user-owned mode 0700")
107
+
108
+ @staticmethod
109
+ def _open_protected(path: Path, *, create: bool = False) -> int:
110
+ flags = os.O_RDWR if create else os.O_RDONLY
111
+ flags |= getattr(os, "O_NOFOLLOW", 0)
112
+ if create:
113
+ flags |= os.O_CREAT
114
+ try:
115
+ descriptor = os.open(path, flags, 0o600)
116
+ except FileNotFoundError:
117
+ raise SignInRequired("No local Connection; run brewsorted login") from None
118
+ except OSError as exc:
119
+ raise AuthStateError("Credential file is inaccessible or unsafe") from exc
120
+ info = os.fstat(descriptor)
121
+ if (
122
+ not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
123
+ or info.st_mode & 0o077 or info.st_nlink != 1
124
+ ):
125
+ os.close(descriptor)
126
+ raise AuthStateError("Credential file must be user-owned mode 0600")
127
+ return descriptor
128
+
129
+ def _load(self) -> AuthBinding:
130
+ descriptor = self._open_protected(self.path)
131
+ try:
132
+ with os.fdopen(descriptor, "r", encoding="utf-8") as stream:
133
+ data = json.load(stream)
134
+ except (ValueError, UnicodeError, OSError) as exc:
135
+ raise AuthStateError("Credential file is invalid; use login again") from exc
136
+ if not isinstance(data, dict) or set(data) != set(AuthBinding.__dataclass_fields__):
137
+ raise AuthStateError("Credential file is invalid; use login again")
138
+ binding = AuthBinding(**data)
139
+ if binding.service_origin != self.service_origin:
140
+ raise AuthStateError("Credential service does not match the selected service")
141
+ return binding
142
+
143
+ @contextmanager
144
+ def locked(self) -> Iterator[None]:
145
+ self._prepare_directory()
146
+ lock_path = self.path.with_name(self.path.name + ".lock")
147
+ descriptor = self._open_protected(lock_path, create=True)
148
+ try:
149
+ fcntl.flock(descriptor, fcntl.LOCK_EX)
150
+ yield
151
+ finally:
152
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
153
+ os.close(descriptor)
154
+
155
+ def _save(self, binding: AuthBinding) -> None:
156
+ if binding.service_origin != self.service_origin:
157
+ raise AuthStateError("Credential service does not match the selected service")
158
+ if self.path.exists() or self.path.is_symlink():
159
+ descriptor = self._open_protected(self.path)
160
+ os.close(descriptor)
161
+ temporary = self.path.with_name(f".{self.path.name}.{secrets.token_hex(12)}.tmp")
162
+ try:
163
+ descriptor = os.open(
164
+ temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
165
+ 0o600,
166
+ )
167
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
168
+ json.dump(asdict(binding), stream, sort_keys=True)
169
+ stream.write("\n")
170
+ stream.flush()
171
+ os.fsync(stream.fileno())
172
+ os.replace(temporary, self.path)
173
+ directory = os.open(self.path.parent, os.O_RDONLY)
174
+ try:
175
+ os.fsync(directory)
176
+ finally:
177
+ os.close(directory)
178
+ finally:
179
+ temporary.unlink(missing_ok=True)
180
+
181
+ def save_new(self, binding: AuthBinding) -> None:
182
+ with self.locked():
183
+ if self.path.exists() or self.path.is_symlink():
184
+ existing = self._load()
185
+ raise AuthStateError(
186
+ f"Already connected as {existing.username} to {existing.service_origin}; logout first"
187
+ )
188
+ self._save(binding)
189
+
190
+ def read(self) -> AuthBinding:
191
+ with self.locked():
192
+ return self._load()
193
+
194
+ def access_token(
195
+ self, *, client: httpx.Client | None = None, proxy: str | None = None,
196
+ verify_access_token: Callable[[str], None] | None = None,
197
+ now_epoch: int | None = None,
198
+ ) -> str:
199
+ with self.locked():
200
+ binding = self._load()
201
+ if binding.expires_at > (now_epoch if now_epoch is not None else int(time.time())) + 30:
202
+ return binding.access_token
203
+ own_client = client is None
204
+ transport = client or http_client(proxy=proxy)
205
+ try:
206
+ try:
207
+ response = transport.post(binding.token_endpoint, data={
208
+ "grant_type": "refresh_token", "client_id": binding.client_id,
209
+ "refresh_token": binding.refresh_token,
210
+ }, headers={"User-Agent": USER_AGENT})
211
+ except httpx.RequestError as exc:
212
+ raise IssuerUnavailable("Issuer unavailable; retry this operation later") from exc
213
+ if response.status_code in (400, 401):
214
+ raise SignInRequired("Connection expired or revoked; run brewsorted login")
215
+ if response.status_code != 200:
216
+ raise IssuerUnavailable("Issuer response is unavailable or invalid")
217
+ if response.headers.get("content-type", "").split(";", 1)[0] != "application/json":
218
+ self.path.unlink(missing_ok=True)
219
+ raise SignInRequired("Refresh result is uncertain; sign in again")
220
+ try:
221
+ payload = response.json()
222
+ except ValueError as exc:
223
+ self.path.unlink(missing_ok=True)
224
+ raise SignInRequired("Refresh result is uncertain; sign in again") from exc
225
+ access = payload.get("access_token") if isinstance(payload, dict) else None
226
+ refresh = payload.get("refresh_token") if isinstance(payload, dict) else None
227
+ expires = payload.get("expires_in") if isinstance(payload, dict) else None
228
+ if (
229
+ not isinstance(access, str) or not access
230
+ or not isinstance(refresh, str) or not refresh
231
+ or type(expires) is not int or not 1 <= expires <= 300
232
+ ):
233
+ self.path.unlink(missing_ok=True)
234
+ raise SignInRequired("Refresh result is uncertain; sign in again")
235
+ try:
236
+ if verify_access_token is not None:
237
+ verify_access_token(access)
238
+ refreshed = replace(
239
+ binding, access_token=access, refresh_token=refresh,
240
+ expires_at=int(time.time()) + expires,
241
+ )
242
+ self._save(refreshed)
243
+ except Exception as exc:
244
+ self.path.unlink(missing_ok=True)
245
+ raise SignInRequired("Credential update failed; sign in again") from exc
246
+ return access
247
+ finally:
248
+ if own_client:
249
+ transport.close()
250
+
251
+ def logout(self, *, local_only: bool = False, client: httpx.Client | None = None,
252
+ proxy: str | None = None) -> bool:
253
+ with self.locked():
254
+ binding = self._load()
255
+ confirmed = False
256
+ if not local_only:
257
+ own_client = client is None
258
+ transport = client or http_client(proxy=proxy)
259
+ try:
260
+ try:
261
+ response = transport.post(binding.revocation_endpoint, data={
262
+ "client_id": binding.client_id,
263
+ "token": binding.refresh_token,
264
+ "token_type_hint": "refresh_token",
265
+ }, headers={"User-Agent": USER_AGENT})
266
+ confirmed = response.status_code == 200
267
+ except httpx.RequestError:
268
+ confirmed = False
269
+ finally:
270
+ if own_client:
271
+ transport.close()
272
+ self.path.unlink()
273
+ return confirmed