post-at-lib 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.
post_at/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Unofficial client for the Österreichische Post (post.at) app API."""
2
+
3
+ from . import models
4
+ from .auth import PendingLogin, Session
5
+ from .client import PostAtClient
6
+ from .errors import (
7
+ ApiError,
8
+ AuthenticationError,
9
+ GraphQLError,
10
+ InteractionRequiredError,
11
+ NotAuthenticatedError,
12
+ PostAtError,
13
+ )
14
+
15
+ __all__ = [
16
+ "ApiError",
17
+ "AuthenticationError",
18
+ "GraphQLError",
19
+ "InteractionRequiredError",
20
+ "NotAuthenticatedError",
21
+ "PendingLogin",
22
+ "PostAtClient",
23
+ "PostAtError",
24
+ "Session",
25
+ "models",
26
+ ]
post_at/auth.py ADDED
@@ -0,0 +1,292 @@
1
+ """Azure AD B2C authentication as performed by the Österreichische Post Android app.
2
+
3
+ The app uses MSAL against the custom policy ``B2C_1A_signup_signin_mobileapp``
4
+ (public client, authorization code + PKCE). The BFF accepts tokens for three
5
+ resources; all of them are minted from the same refresh token:
6
+
7
+ * :data:`SCOPE_APP` – sent as ``Authorization`` on every authenticated call.
8
+ * :data:`SCOPE_USER_CONTEXT` – additionally sent as ``X-Authorization`` for
9
+ user profile and receiving-option endpoints.
10
+ * :data:`SCOPE_ID_AUSTRIA` – additionally sent as ``X-Authorization`` for the
11
+ identification endpoints.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import hashlib
18
+ import json
19
+ import re
20
+ import secrets
21
+ import time
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+ from typing import Any, Callable
25
+ from urllib.parse import parse_qs, urljoin, urlsplit
26
+
27
+ import httpx
28
+
29
+ from .errors import AuthenticationError, InteractionRequiredError, NotAuthenticatedError
30
+
31
+ CLIENT_ID = "228c4360-3391-4b1c-93a2-e5d7d946b647"
32
+ REDIRECT_URI = f"msal{CLIENT_ID}://at.post.app/auth"
33
+ LOGIN_HOST = "https://login.post.at"
34
+ TENANT_ID = "f098c632-5a55-45ba-9bf4-c13870157cf1"
35
+ POLICY = "B2C_1A_signup_signin_mobileapp"
36
+ AUTHORITY = f"{LOGIN_HOST}/{TENANT_ID}/{POLICY}"
37
+ AUTHORIZE_URL = f"{AUTHORITY}/oauth2/v2.0/authorize"
38
+ TOKEN_URL = f"{AUTHORITY}/oauth2/v2.0/token"
39
+ LOGOUT_URL = f"{AUTHORITY}/oauth2/v2.0/logout"
40
+
41
+ SCOPE_APP = "https://login.post.at/postag/PostApp2.AllAccess"
42
+ SCOPE_USER_CONTEXT = "https://kiamprod.onmicrosoft.com/kiam-api/KIAM.Service.UserContext.All"
43
+ SCOPE_ID_AUSTRIA = "https://kiamprod.onmicrosoft.com/kiam-api/Kiam.Identifications.IdAustria.Create"
44
+
45
+ # MSAL always adds the OIDC scopes to whatever resource scope is requested.
46
+ _OIDC_SCOPES = "openid offline_access profile"
47
+ # Refresh this many seconds before the access token actually expires.
48
+ _EXPIRY_SKEW = 60
49
+ _BROWSER_UA = (
50
+ "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 "
51
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36"
52
+ )
53
+ _SETTINGS_RE = re.compile(r"var SETTINGS = (\{.*?\});", re.S)
54
+
55
+
56
+ @dataclass
57
+ class AccessToken:
58
+ token: str
59
+ expires_at: float
60
+
61
+ @property
62
+ def expired(self) -> bool:
63
+ return time.time() >= self.expires_at - _EXPIRY_SKEW
64
+
65
+
66
+ @dataclass
67
+ class Session:
68
+ """Persistable login state: the rotating refresh token plus cached access tokens."""
69
+
70
+ refresh_token: str
71
+ access_tokens: dict[str, AccessToken] = field(default_factory=dict)
72
+ id_token: str | None = None
73
+
74
+ def to_dict(self) -> dict[str, Any]:
75
+ return {
76
+ "refresh_token": self.refresh_token,
77
+ "id_token": self.id_token,
78
+ "access_tokens": {
79
+ scope: {"token": t.token, "expires_at": t.expires_at}
80
+ for scope, t in self.access_tokens.items()
81
+ },
82
+ }
83
+
84
+ @classmethod
85
+ def from_dict(cls, data: dict[str, Any]) -> Session:
86
+ return cls(
87
+ refresh_token=data["refresh_token"],
88
+ id_token=data.get("id_token"),
89
+ access_tokens={
90
+ scope: AccessToken(t["token"], t["expires_at"])
91
+ for scope, t in data.get("access_tokens", {}).items()
92
+ },
93
+ )
94
+
95
+ def save(self, path: str | Path) -> None:
96
+ path = Path(path)
97
+ path.write_text(json.dumps(self.to_dict()))
98
+ path.chmod(0o600)
99
+
100
+ @classmethod
101
+ def load(cls, path: str | Path) -> Session:
102
+ return cls.from_dict(json.loads(Path(path).read_text()))
103
+
104
+ @property
105
+ def claims(self) -> dict[str, Any]:
106
+ """Unverified claims of the ID token (name, email, ``extension_SSOID``, ...)."""
107
+ if not self.id_token:
108
+ return {}
109
+ payload = self.id_token.split(".")[1]
110
+ return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class PendingLogin:
115
+ """State of a browser login started with :meth:`Authenticator.begin_browser_login`."""
116
+
117
+ url: str
118
+ state: str
119
+ code_verifier: str
120
+
121
+
122
+ def _pkce_pair() -> tuple[str, str]:
123
+ verifier = secrets.token_urlsafe(64)
124
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=")
125
+ return verifier, challenge.decode()
126
+
127
+
128
+ class Authenticator:
129
+ """Obtains and refreshes B2C tokens. Thread-unsafe; one instance per session."""
130
+
131
+ def __init__(
132
+ self,
133
+ http: httpx.Client,
134
+ session: Session | None = None,
135
+ on_session_change: Callable[[Session | None], None] | None = None,
136
+ ) -> None:
137
+ self._http = http
138
+ self.session = session
139
+ self._on_session_change = on_session_change
140
+
141
+ # -- login ---------------------------------------------------------------
142
+
143
+ def login(self, email: str, password: str) -> Session:
144
+ """Headless login by replaying the B2C sign-in page's XHR calls."""
145
+ verifier, challenge = _pkce_pair()
146
+ state = secrets.token_urlsafe(16)
147
+ with httpx.Client(headers={"User-Agent": _BROWSER_UA}, timeout=self._http.timeout) as web:
148
+ page = web.get(AUTHORIZE_URL, params=self._authorize_params(challenge, state), follow_redirects=True)
149
+ settings = self._page_settings(page)
150
+ tenant = LOGIN_HOST + settings["hosts"]["tenant"]
151
+ tx = {"tx": settings["transId"], "p": settings["hosts"]["policy"]}
152
+
153
+ submitted = web.post(
154
+ f"{tenant}/SelfAsserted",
155
+ params=tx,
156
+ data={"request_type": "RESPONSE", "signInName": email, "password": password},
157
+ headers={
158
+ "X-CSRF-TOKEN": settings["csrf"],
159
+ "X-Requested-With": "XMLHttpRequest",
160
+ "Referer": str(page.url),
161
+ },
162
+ )
163
+ result = submitted.json()
164
+ if result.get("status") != "200":
165
+ raise AuthenticationError(f"{result.get('errorCode')}: {result.get('message')}")
166
+
167
+ response = web.get(
168
+ f"{tenant}/api/{settings['api']}/confirmed",
169
+ params={"rememberMe": "false", "csrf_token": settings["csrf"], **tx},
170
+ )
171
+ for _ in range(10):
172
+ location = response.headers.get("location")
173
+ if not response.is_redirect or location is None:
174
+ raise InteractionRequiredError(
175
+ "B2C did not redirect back to the app after sign-in; "
176
+ "finish the login in a browser via begin_browser_login()"
177
+ )
178
+ if location.startswith(REDIRECT_URI):
179
+ return self._redeem(location, state, verifier)
180
+ response = web.get(urljoin(str(response.url), location))
181
+ raise AuthenticationError("too many redirects during B2C login")
182
+
183
+ def begin_browser_login(self) -> PendingLogin:
184
+ """Start a login the user completes in a real browser (needed for MFA or new terms).
185
+
186
+ Open ``url``, sign in, then pass the final ``msal…://at.post.app/auth?code=…``
187
+ URL to :meth:`complete_browser_login`. Desktop browsers cannot open that
188
+ scheme; copy it from the address bar/error page or the devtools network tab.
189
+ """
190
+ verifier, challenge = _pkce_pair()
191
+ state = secrets.token_urlsafe(16)
192
+ url = httpx.URL(AUTHORIZE_URL, params=self._authorize_params(challenge, state))
193
+ return PendingLogin(str(url), state, verifier)
194
+
195
+ def complete_browser_login(self, pending: PendingLogin, redirect_url: str) -> Session:
196
+ return self._redeem(redirect_url, pending.state, pending.code_verifier)
197
+
198
+ def logout(self) -> None:
199
+ """Forget the local session. B2C refresh tokens cannot be revoked by a public client."""
200
+ self._set_session(None)
201
+
202
+ # -- tokens --------------------------------------------------------------
203
+
204
+ def access_token(self, scope: str = SCOPE_APP) -> str:
205
+ """Return a valid access token for ``scope``, refreshing it if necessary."""
206
+ if self.session is None:
207
+ raise NotAuthenticatedError("not logged in")
208
+ cached = self.session.access_tokens.get(scope)
209
+ if cached is None or cached.expired:
210
+ self._token_request(
211
+ {"grant_type": "refresh_token", "refresh_token": self.session.refresh_token},
212
+ scope,
213
+ )
214
+ cached = self.session.access_tokens[scope]
215
+ return cached.token
216
+
217
+ def invalidate(self, scope: str) -> None:
218
+ """Drop a cached access token so the next call fetches a fresh one."""
219
+ if self.session is not None:
220
+ self.session.access_tokens.pop(scope, None)
221
+
222
+ # -- internals -----------------------------------------------------------
223
+
224
+ @staticmethod
225
+ def _authorize_params(challenge: str, state: str) -> dict[str, str]:
226
+ return {
227
+ "client_id": CLIENT_ID,
228
+ "response_type": "code",
229
+ "redirect_uri": REDIRECT_URI,
230
+ "scope": f"{SCOPE_APP} {_OIDC_SCOPES}",
231
+ "code_challenge": challenge,
232
+ "code_challenge_method": "S256",
233
+ "state": state,
234
+ "nonce": secrets.token_urlsafe(16),
235
+ "prompt": "login",
236
+ }
237
+
238
+ @staticmethod
239
+ def _page_settings(page: httpx.Response) -> dict[str, Any]:
240
+ page.raise_for_status()
241
+ match = _SETTINGS_RE.search(page.text)
242
+ if match is None:
243
+ raise AuthenticationError(f"unexpected B2C login page at {page.url}")
244
+ return json.loads(match.group(1))
245
+
246
+ def _redeem(self, redirect_url: str, state: str, verifier: str) -> Session:
247
+ query = parse_qs(urlsplit(redirect_url).query)
248
+ if "error" in query:
249
+ raise AuthenticationError(
250
+ f"{query['error'][0]}: {query.get('error_description', [''])[0]}"
251
+ )
252
+ if query.get("state", [None])[0] != state:
253
+ raise AuthenticationError("state mismatch in redirect URL")
254
+ if "code" not in query:
255
+ raise AuthenticationError("redirect URL contains no authorization code")
256
+ self._token_request(
257
+ {
258
+ "grant_type": "authorization_code",
259
+ "code": query["code"][0],
260
+ "redirect_uri": REDIRECT_URI,
261
+ "code_verifier": verifier,
262
+ },
263
+ SCOPE_APP,
264
+ )
265
+ assert self.session is not None
266
+ return self.session
267
+
268
+ def _token_request(self, grant: dict[str, str], scope: str) -> None:
269
+ response = self._http.post(
270
+ TOKEN_URL,
271
+ data={"client_id": CLIENT_ID, "scope": f"{scope} {_OIDC_SCOPES}", **grant},
272
+ )
273
+ body = response.json()
274
+ if response.status_code != 200 or "access_token" not in body:
275
+ raise AuthenticationError(
276
+ f"token request failed ({response.status_code}): "
277
+ f"{body.get('error')}: {body.get('error_description')}"
278
+ )
279
+ token = AccessToken(body["access_token"], time.time() + int(body["expires_in"]))
280
+ if self.session is None:
281
+ session = Session(body["refresh_token"], {scope: token}, body.get("id_token"))
282
+ else:
283
+ session = self.session
284
+ session.refresh_token = body.get("refresh_token", session.refresh_token)
285
+ session.id_token = body.get("id_token", session.id_token)
286
+ session.access_tokens[scope] = token
287
+ self._set_session(session)
288
+
289
+ def _set_session(self, session: Session | None) -> None:
290
+ self.session = session
291
+ if self._on_session_change is not None:
292
+ self._on_session_change(session)