didupwrapper 0.2.0__tar.gz → 0.2.1__tar.gz
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.
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/PKG-INFO +2 -2
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/README.md +1 -1
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/__init__.py +1 -1
- didupwrapper-0.2.1/didupwrapper/auth.py +642 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/models.py +30 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/workers/poller.py +1 -1
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/pyproject.toml +1 -1
- didupwrapper-0.2.1/tests/test_auth.py +428 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/tests/test_models.py +35 -0
- didupwrapper-0.2.0/didupwrapper/auth.py +0 -341
- didupwrapper-0.2.0/tests/test_auth.py +0 -182
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/.gitignore +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/LICENSE +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/client.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/endpoints/__init__.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/endpoints/assenze.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/endpoints/bacheca.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/endpoints/fuori_classe.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/endpoints/promemoria.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/endpoints/registro.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/endpoints/voti.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/exceptions.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/py.typed +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/didupwrapper/workers/__init__.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/tests/__init__.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/tests/test_client.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/tests/test_poller.py +0 -0
- {didupwrapper-0.2.0 → didupwrapper-0.2.1}/tests/test_versione.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: didupwrapper
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
4
4
|
Summary: Wrapper Python (sync + async) per le API non documentate del registro elettronico DiDUP / Argo Famiglia
|
|
5
5
|
Project-URL: Homepage, https://github.com/Rocciadura/didupAPI-wrapper
|
|
6
6
|
Project-URL: Issues, https://github.com/Rocciadura/didupAPI-wrapper/issues
|
|
@@ -193,7 +193,7 @@ Disponibili sia su `DiDUPClient` (con `await`) sia su `DiDUPClientSync`.
|
|
|
193
193
|
| `get_bacheca_alunno()` | File della bacheca alunno (`list[FileBachecaAlunno]`) |
|
|
194
194
|
| `get_promemoria()` | Promemoria dei docenti (`list[Promemoria]`) |
|
|
195
195
|
| `get_fuori_classe()` | Attività fuori classe (`list[FuoriClasse]`) |
|
|
196
|
-
| `get_note_disciplinari()` | Note disciplinari (`list[NotaDisciplinare]`) |
|
|
196
|
+
| `get_note_disciplinari()` | Note disciplinari (`list[NotaDisciplinare]`, testo in `nota.testo`) |
|
|
197
197
|
| `get_materie()` | Materie (`list[Materia]`) |
|
|
198
198
|
| `get_docenti()` | Docenti della classe (`list[Docente]`) |
|
|
199
199
|
| `get_periodi()` | Periodi / quadrimestri (`list[Periodo]`) |
|
|
@@ -163,7 +163,7 @@ Disponibili sia su `DiDUPClient` (con `await`) sia su `DiDUPClientSync`.
|
|
|
163
163
|
| `get_bacheca_alunno()` | File della bacheca alunno (`list[FileBachecaAlunno]`) |
|
|
164
164
|
| `get_promemoria()` | Promemoria dei docenti (`list[Promemoria]`) |
|
|
165
165
|
| `get_fuori_classe()` | Attività fuori classe (`list[FuoriClasse]`) |
|
|
166
|
-
| `get_note_disciplinari()` | Note disciplinari (`list[NotaDisciplinare]`) |
|
|
166
|
+
| `get_note_disciplinari()` | Note disciplinari (`list[NotaDisciplinare]`, testo in `nota.testo`) |
|
|
167
167
|
| `get_materie()` | Materie (`list[Materia]`) |
|
|
168
168
|
| `get_docenti()` | Docenti della classe (`list[Docente]`) |
|
|
169
169
|
| `get_periodi()` | Periodi / quadrimestri (`list[Periodo]`) |
|
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
"""Login su Argo: il flusso OAuth2/PKCE che fa l'app, e la sessione che ne esce.
|
|
2
|
+
|
|
3
|
+
Argo non offre un'API di login "pulita": imitiamo passo passo quello che fa
|
|
4
|
+
l'app ufficiale, seguendo a mano i redirect del portale SSO fino a ottenere
|
|
5
|
+
il ``code`` da scambiare con il token.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import hashlib
|
|
12
|
+
import html
|
|
13
|
+
import logging
|
|
14
|
+
import re
|
|
15
|
+
import secrets
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
from html.parser import HTMLParser
|
|
20
|
+
from typing import Any
|
|
21
|
+
from urllib.parse import parse_qs, quote, urlencode, urljoin, urlparse
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from .exceptions import AuthError, from_response
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"APP_BUNDLE_ID",
|
|
29
|
+
"ArgoConfig",
|
|
30
|
+
"Autenticatore",
|
|
31
|
+
"Credenziali",
|
|
32
|
+
"LoginLink",
|
|
33
|
+
"SessioneToken",
|
|
34
|
+
"formatta_data",
|
|
35
|
+
"recupera_versione_app",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger("didupwrapper.auth")
|
|
39
|
+
|
|
40
|
+
APP_BUNDLE_ID = "it.argosoft.didup.famiglia.new"
|
|
41
|
+
_APP_LOOKUP_URL = "https://itunes.apple.com/lookup"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def recupera_versione_app(
|
|
45
|
+
http: httpx.AsyncClient | None = None, *, bundle_id: str = APP_BUNDLE_ID
|
|
46
|
+
) -> str | None:
|
|
47
|
+
"""Chiede all'App Store l'ultima versione pubblicata dell'app DiDUP.
|
|
48
|
+
|
|
49
|
+
Ci serve per l'header ``argo-client-version``. Se qualcosa va storto
|
|
50
|
+
(niente rete, risposta strana) restituisce ``None`` invece di sollevare.
|
|
51
|
+
"""
|
|
52
|
+
chiudi = http is None
|
|
53
|
+
client = http or httpx.AsyncClient(timeout=15.0)
|
|
54
|
+
try:
|
|
55
|
+
risposta = await client.get(_APP_LOOKUP_URL, params={"bundleId": bundle_id})
|
|
56
|
+
risposta.raise_for_status()
|
|
57
|
+
risultati = risposta.json().get("results") or []
|
|
58
|
+
return risultati[0].get("version") if risultati else None
|
|
59
|
+
except (httpx.HTTPError, ValueError, KeyError, IndexError):
|
|
60
|
+
return None
|
|
61
|
+
finally:
|
|
62
|
+
if chiudi:
|
|
63
|
+
await client.aclose()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _random_string(length: int) -> str:
|
|
70
|
+
return "".join(secrets.choice(_ALPHABET) for _ in range(length))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _pkce_challenge(code_verifier: str) -> str:
|
|
74
|
+
"""La code challenge PKCE (metodo S256): SHA-256 del verifier in base64url, senza ``=``."""
|
|
75
|
+
digest = hashlib.sha256(code_verifier.encode()).digest()
|
|
76
|
+
return base64.urlsafe_b64encode(digest).decode().rstrip("=")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def formatta_data(dt: datetime) -> str:
|
|
80
|
+
"""Scrive una data nel formato che usa l'API: ``YYYY-MM-DD HH:MM:SS.mmm``."""
|
|
81
|
+
return dt.strftime("%Y-%m-%d %H:%M:%S.") + f"{dt.microsecond // 1000:03d}"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class ArgoConfig:
|
|
86
|
+
"""Indirizzi e parametri dell'app ufficiale che usiamo per parlare con Argo.
|
|
87
|
+
|
|
88
|
+
Di solito vanno bene i default; l'unico valore che potresti voler
|
|
89
|
+
cambiare è ``version``, che deve seguire gli aggiornamenti dell'app.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
api_base_url: str = "https://www.portaleargo.it/appfamiglia/api/rest/"
|
|
93
|
+
oauth_auth_url: str = "https://auth.portaleargo.it/oauth2/auth"
|
|
94
|
+
oauth_token_url: str = "https://auth.portaleargo.it/oauth2/token"
|
|
95
|
+
sso_login_url: str = "https://www.portaleargo.it/auth/sso/login"
|
|
96
|
+
client_id: str = "72fd6dea-d0ab-4bb9-8eaa-3ac24c84886c"
|
|
97
|
+
redirect_uri: str = "it.argosoft.didup.famiglia.new://login-callback"
|
|
98
|
+
scopes: tuple[str, ...] = ("openid", "offline", "profile", "user.roles", "argo")
|
|
99
|
+
version: str = "1.29.2"
|
|
100
|
+
|
|
101
|
+
def headers_base(self) -> dict[str, str]:
|
|
102
|
+
"""Gli header che mandiamo sempre, token esclusi."""
|
|
103
|
+
return {
|
|
104
|
+
"accept": "application/json",
|
|
105
|
+
"argo-client-version": self.version,
|
|
106
|
+
"content-type": "application/json; charset=utf-8",
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class Credenziali:
|
|
112
|
+
"""Codice scuola, username e password: quelli che useresti nell'app."""
|
|
113
|
+
|
|
114
|
+
codice_scuola: str
|
|
115
|
+
username: str
|
|
116
|
+
password: str
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass
|
|
120
|
+
class LoginLink:
|
|
121
|
+
"""L'URL di login OAuth e i valori casuali (PKCE) generati per quel tentativo."""
|
|
122
|
+
|
|
123
|
+
url: str
|
|
124
|
+
code_verifier: str
|
|
125
|
+
state: str
|
|
126
|
+
nonce: str
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass
|
|
130
|
+
class SessioneToken:
|
|
131
|
+
"""Il token OAuth ottenuto al login, con la sua scadenza."""
|
|
132
|
+
|
|
133
|
+
access_token: str
|
|
134
|
+
refresh_token: str | None = None
|
|
135
|
+
scope: str = ""
|
|
136
|
+
token_type: str = "bearer"
|
|
137
|
+
expires_at: float | None = None # epoch seconds
|
|
138
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def is_scaduto(self) -> bool:
|
|
142
|
+
if self.expires_at is None:
|
|
143
|
+
return False
|
|
144
|
+
# Lo consideriamo scaduto con 30 secondi di anticipo, per non rischiare
|
|
145
|
+
# che scada proprio a metà di una richiesta.
|
|
146
|
+
return time.time() >= (self.expires_at - 30)
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def expire_datetime(self) -> datetime:
|
|
150
|
+
return datetime.fromtimestamp(self.expires_at or time.time())
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class Autenticatore:
|
|
154
|
+
"""Fa il login OAuth2/PKCE e si ricorda la sessione ottenuta."""
|
|
155
|
+
|
|
156
|
+
def __init__(
|
|
157
|
+
self,
|
|
158
|
+
credenziali: Credenziali | None = None,
|
|
159
|
+
config: ArgoConfig | None = None,
|
|
160
|
+
*,
|
|
161
|
+
sessione: SessioneToken | None = None,
|
|
162
|
+
) -> None:
|
|
163
|
+
self.credenziali = credenziali
|
|
164
|
+
self.config = config or ArgoConfig()
|
|
165
|
+
self.sessione = sessione
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def autenticato(self) -> bool:
|
|
169
|
+
return self.sessione is not None and not self.sessione.is_scaduto
|
|
170
|
+
|
|
171
|
+
# ------------------------------------------------------------------ #
|
|
172
|
+
# Orchestrazione #
|
|
173
|
+
# ------------------------------------------------------------------ #
|
|
174
|
+
async def assicura_sessione(self, http: httpx.AsyncClient) -> SessioneToken:
|
|
175
|
+
"""Restituisce la sessione attuale, rifacendo il login se manca o è scaduta."""
|
|
176
|
+
if self.autenticato:
|
|
177
|
+
assert self.sessione is not None
|
|
178
|
+
return self.sessione
|
|
179
|
+
return await self.login(http)
|
|
180
|
+
|
|
181
|
+
async def login(self, http: httpx.AsyncClient) -> SessioneToken:
|
|
182
|
+
"""Fa tutto il giro OAuth2/PKCE da capo e salva il token ottenuto."""
|
|
183
|
+
if self.credenziali is None:
|
|
184
|
+
raise AuthError("Credenziali assenti: impossibile effettuare il login")
|
|
185
|
+
link = self._genera_login_link()
|
|
186
|
+
code = await self._ottieni_code(link)
|
|
187
|
+
self.sessione = await self._ottieni_token(http, link, code)
|
|
188
|
+
return self.sessione
|
|
189
|
+
|
|
190
|
+
# ------------------------------------------------------------------ #
|
|
191
|
+
# Step OAuth #
|
|
192
|
+
# ------------------------------------------------------------------ #
|
|
193
|
+
def _genera_login_link(self) -> LoginLink:
|
|
194
|
+
code_verifier = _random_string(43)
|
|
195
|
+
state = _random_string(22)
|
|
196
|
+
nonce = _random_string(22)
|
|
197
|
+
challenge = _pkce_challenge(code_verifier)
|
|
198
|
+
params = (
|
|
199
|
+
f"redirect_uri={quote(self.config.redirect_uri, safe='')}"
|
|
200
|
+
f"&client_id={self.config.client_id}"
|
|
201
|
+
f"&response_type=code"
|
|
202
|
+
f"&prompt=login"
|
|
203
|
+
f"&state={state}"
|
|
204
|
+
f"&nonce={nonce}"
|
|
205
|
+
f"&scope={quote(' '.join(self.config.scopes), safe='')}"
|
|
206
|
+
f"&code_challenge={challenge}"
|
|
207
|
+
f"&code_challenge_method=S256"
|
|
208
|
+
)
|
|
209
|
+
return LoginLink(
|
|
210
|
+
url=f"{self.config.oauth_auth_url}?{params}",
|
|
211
|
+
code_verifier=code_verifier,
|
|
212
|
+
state=state,
|
|
213
|
+
nonce=nonce,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
async def _ottieni_code(self, link: LoginLink) -> str:
|
|
217
|
+
"""Segue i redirect del portale SSO finché non salta fuori il ``code``.
|
|
218
|
+
|
|
219
|
+
I redirect li seguiamo a mano (leggendo ``Location``) e i cookie li
|
|
220
|
+
gestiamo noi come farebbe un browser: ogni cookie torna solo all'host
|
|
221
|
+
(o al dominio) che l'ha impostato. Il cookie jar di httpx li
|
|
222
|
+
manderebbe anche dove il server non se li aspetta.
|
|
223
|
+
|
|
224
|
+
Se un passaggio risponde con una pagina HTML invece che con un redirect
|
|
225
|
+
(es. la pagina di consenso OAuth), la interpretiamo come un browser:
|
|
226
|
+
vedi :class:`_PaginaHtml`.
|
|
227
|
+
"""
|
|
228
|
+
assert self.credenziali is not None
|
|
229
|
+
cookies = _CookieJar()
|
|
230
|
+
|
|
231
|
+
async with httpx.AsyncClient(follow_redirects=False, timeout=30.0) as c:
|
|
232
|
+
|
|
233
|
+
async def passo(
|
|
234
|
+
n: int, method: str, url: str, **kwargs: Any
|
|
235
|
+
) -> httpx.Response:
|
|
236
|
+
headers = dict(kwargs.pop("headers", None) or {})
|
|
237
|
+
cookie = cookies.header_per(url)
|
|
238
|
+
if cookie:
|
|
239
|
+
headers["cookie"] = cookie
|
|
240
|
+
r = await c.request(method, url, headers=headers, **kwargs)
|
|
241
|
+
c.cookies.clear() # i cookie li gestiamo noi, vedi sopra
|
|
242
|
+
cookies.raccogli(r)
|
|
243
|
+
logger.debug(
|
|
244
|
+
"OAuth passo %d: %s %s -> HTTP %d", n, method, _senza_query(url), r.status_code
|
|
245
|
+
)
|
|
246
|
+
return r
|
|
247
|
+
|
|
248
|
+
# 1) Apriamo l'URL OAuth: ci rimanda alla pagina di login con un login_challenge.
|
|
249
|
+
r0 = await passo(0, "GET", link.url)
|
|
250
|
+
loc = _location(r0)
|
|
251
|
+
if not loc:
|
|
252
|
+
raise AuthError("Avvio OAuth: redirect mancante", status_code=r0.status_code)
|
|
253
|
+
challenge = _query_param(loc, "login_challenge")
|
|
254
|
+
if not challenge:
|
|
255
|
+
raise AuthError("Avvio OAuth: 'login_challenge' non trovato")
|
|
256
|
+
|
|
257
|
+
# 2) Mandiamo le credenziali, come se compilassimo il form di login.
|
|
258
|
+
body = "&".join(
|
|
259
|
+
[
|
|
260
|
+
f"challenge={challenge}",
|
|
261
|
+
f"client_id={self.config.client_id}",
|
|
262
|
+
"prefill=false",
|
|
263
|
+
f"famiglia_customer_code={quote(self.credenziali.codice_scuola, safe='')}",
|
|
264
|
+
f"username={quote(self.credenziali.username, safe='')}",
|
|
265
|
+
f"password={quote(self.credenziali.password, safe='')}",
|
|
266
|
+
"login=true",
|
|
267
|
+
]
|
|
268
|
+
)
|
|
269
|
+
r1 = await passo(
|
|
270
|
+
1,
|
|
271
|
+
"POST",
|
|
272
|
+
self.config.sso_login_url,
|
|
273
|
+
content=body,
|
|
274
|
+
headers={"content-type": "application/x-www-form-urlencoded"},
|
|
275
|
+
)
|
|
276
|
+
url = _location(r1)
|
|
277
|
+
if not url:
|
|
278
|
+
raise AuthError(
|
|
279
|
+
"Login SSO fallito: credenziali errate o flusso cambiato",
|
|
280
|
+
status_code=r1.status_code,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
# 3) Dopo il login il portale fa ancora qualche passaggio prima di
|
|
284
|
+
# rimandarci al redirect_uri dell'app con il code. Di solito sono
|
|
285
|
+
# redirect, ma alcuni passaggi (es. il consenso OAuth su
|
|
286
|
+
# /auth/sso/consent/) rispondono con una pagina HTML: in quel caso
|
|
287
|
+
# facciamo quello che farebbe un browser (inviamo il form, seguiamo
|
|
288
|
+
# il link "Continua", il meta refresh, ...).
|
|
289
|
+
metodo = "GET"
|
|
290
|
+
extra: dict[str, Any] = {}
|
|
291
|
+
for n in range(2, 2 + _MAX_REDIRECT):
|
|
292
|
+
if url.startswith(self.config.redirect_uri):
|
|
293
|
+
break
|
|
294
|
+
r = await passo(n, metodo, url, **extra)
|
|
295
|
+
metodo, extra = "GET", {}
|
|
296
|
+
prossimo = _location(r)
|
|
297
|
+
if prossimo:
|
|
298
|
+
url = prossimo
|
|
299
|
+
continue
|
|
300
|
+
pagina = _PaginaHtml.da_risposta(r) if r.is_success else None
|
|
301
|
+
successivo = (
|
|
302
|
+
pagina.passo_successivo(url, self.config) if pagina is not None else None
|
|
303
|
+
)
|
|
304
|
+
if successivo is None:
|
|
305
|
+
dettaglio = f" (pagina «{pagina.titolo}»)" if pagina and pagina.titolo else ""
|
|
306
|
+
raise AuthError(
|
|
307
|
+
f"Catena OAuth interrotta (redirect {n}): "
|
|
308
|
+
f"HTTP {r.status_code} da {_senza_query(url)}{dettaglio}",
|
|
309
|
+
status_code=r.status_code,
|
|
310
|
+
)
|
|
311
|
+
logger.debug(
|
|
312
|
+
"OAuth passo %d: pagina HTML, prossimo passo %s %s",
|
|
313
|
+
n,
|
|
314
|
+
successivo.metodo,
|
|
315
|
+
_senza_query(successivo.url),
|
|
316
|
+
)
|
|
317
|
+
url, metodo = successivo.url, successivo.metodo
|
|
318
|
+
if successivo.corpo is not None:
|
|
319
|
+
extra = {
|
|
320
|
+
"content": successivo.corpo,
|
|
321
|
+
"headers": {"content-type": "application/x-www-form-urlencoded"},
|
|
322
|
+
}
|
|
323
|
+
else:
|
|
324
|
+
raise AuthError("Catena OAuth interrotta: troppi redirect")
|
|
325
|
+
|
|
326
|
+
code = _query_param(url, "code")
|
|
327
|
+
if not code:
|
|
328
|
+
errore = _query_param(url, "error")
|
|
329
|
+
if errore:
|
|
330
|
+
descrizione = _query_param(url, "error_description") or ""
|
|
331
|
+
raise AuthError(f"Accesso rifiutato da Argo: {errore} {descrizione}".strip())
|
|
332
|
+
raise AuthError(f"Code non presente nel redirect finale: {_senza_query(url)}")
|
|
333
|
+
return code
|
|
334
|
+
|
|
335
|
+
async def _ottieni_token(
|
|
336
|
+
self, http: httpx.AsyncClient, link: LoginLink, code: str
|
|
337
|
+
) -> SessioneToken:
|
|
338
|
+
"""Scambia il ``code`` con l'access token vero e proprio."""
|
|
339
|
+
risposta = await http.post(
|
|
340
|
+
self.config.oauth_token_url,
|
|
341
|
+
data={
|
|
342
|
+
"code": code,
|
|
343
|
+
"grant_type": "authorization_code",
|
|
344
|
+
"redirect_uri": self.config.redirect_uri,
|
|
345
|
+
"code_verifier": link.code_verifier,
|
|
346
|
+
"client_id": self.config.client_id,
|
|
347
|
+
},
|
|
348
|
+
headers={"content-type": "application/x-www-form-urlencoded"},
|
|
349
|
+
)
|
|
350
|
+
if risposta.is_error:
|
|
351
|
+
raise from_response(risposta)
|
|
352
|
+
try:
|
|
353
|
+
dati = risposta.json()
|
|
354
|
+
except ValueError as exc:
|
|
355
|
+
raise AuthError(
|
|
356
|
+
"Risposta OAuth non leggibile (non è JSON)",
|
|
357
|
+
status_code=risposta.status_code,
|
|
358
|
+
) from exc
|
|
359
|
+
if "error" in dati:
|
|
360
|
+
raise AuthError(
|
|
361
|
+
f"{dati.get('error')}: {dati.get('error_description', '')}".strip(": "),
|
|
362
|
+
payload=dati,
|
|
363
|
+
)
|
|
364
|
+
access_token = dati.get("access_token")
|
|
365
|
+
if not access_token:
|
|
366
|
+
raise AuthError("Token non presente nella risposta OAuth", payload=dati)
|
|
367
|
+
|
|
368
|
+
expires_in = dati.get("expires_in")
|
|
369
|
+
return SessioneToken(
|
|
370
|
+
access_token=access_token,
|
|
371
|
+
refresh_token=dati.get("refresh_token"),
|
|
372
|
+
scope=dati.get("scope", ""),
|
|
373
|
+
token_type=dati.get("token_type", "bearer"),
|
|
374
|
+
expires_at=(time.time() + float(expires_in)) if expires_in else None,
|
|
375
|
+
extra=dati,
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
_MAX_REDIRECT = 15
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
@dataclass
|
|
383
|
+
class _Passo:
|
|
384
|
+
"""Una richiesta da fare per proseguire la catena di login."""
|
|
385
|
+
|
|
386
|
+
metodo: str
|
|
387
|
+
url: str
|
|
388
|
+
corpo: str | None = None # form url-encoded, solo per i POST
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
@dataclass
|
|
392
|
+
class _Form:
|
|
393
|
+
action: str | None
|
|
394
|
+
metodo: str
|
|
395
|
+
campi: list[tuple[str, str]] = field(default_factory=list)
|
|
396
|
+
# (name, value, testo visibile) dei bottoni di invio
|
|
397
|
+
bottoni: list[tuple[str | None, str, str]] = field(default_factory=list)
|
|
398
|
+
ha_password: bool = False
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
# Bottoni che non vogliamo premere: negano il consenso o annullano il login.
|
|
402
|
+
_BOTTONE_NEGATIVO = re.compile(r"rifiut|nega|deny|reject|annull|cancel|indietro", re.IGNORECASE)
|
|
403
|
+
# Link che portano avanti nel flusso ("Accesso completato... Continua").
|
|
404
|
+
_LINK_AVANTI = re.compile(r"continu|prosegui|avanti|accedi all'app|apri", re.IGNORECASE)
|
|
405
|
+
_META_REFRESH_URL = re.compile(r"url\s*=\s*['\"]?([^'\";]+)", re.IGNORECASE)
|
|
406
|
+
_JS_LOCATION = re.compile(
|
|
407
|
+
r"""location(?:\.href)?\s*=\s*["'`]([^"'`]+)["'`]"""
|
|
408
|
+
r"""|location\.(?:replace|assign)\(\s*["'`]([^"'`]+)["'`]""",
|
|
409
|
+
re.IGNORECASE,
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _decodifica_html(testo: str) -> str:
|
|
414
|
+
"""Toglie entità HTML ed escape JavaScript tipici, per trovare URL dentro script e attributi."""
|
|
415
|
+
testo = html.unescape(testo)
|
|
416
|
+
for vecchio, nuovo in (("\\/", "/"), ("\\u0026", "&"), ("\\u003d", "="), ("\\x26", "&")):
|
|
417
|
+
testo = testo.replace(vecchio, nuovo)
|
|
418
|
+
return testo
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
class _PaginaHtml(HTMLParser):
|
|
422
|
+
"""Legge una pagina intermedia del portale e capisce come andare avanti.
|
|
423
|
+
|
|
424
|
+
Il parser è volutamente tollerante: raccoglie form, link, meta refresh e
|
|
425
|
+
titolo, senza pretendere HTML valido.
|
|
426
|
+
"""
|
|
427
|
+
|
|
428
|
+
def __init__(self) -> None:
|
|
429
|
+
super().__init__(convert_charrefs=True)
|
|
430
|
+
self.testo = ""
|
|
431
|
+
self.titolo = ""
|
|
432
|
+
self.forms: list[_Form] = []
|
|
433
|
+
self.link: list[tuple[str, str]] = [] # (href, testo)
|
|
434
|
+
self.meta_refresh: str | None = None
|
|
435
|
+
self._form: _Form | None = None
|
|
436
|
+
self._link: tuple[str, list[str]] | None = None
|
|
437
|
+
self._bottone: tuple[str | None, str, list[str]] | None = None
|
|
438
|
+
self._in_titolo = False
|
|
439
|
+
|
|
440
|
+
@classmethod
|
|
441
|
+
def da_risposta(cls, response: httpx.Response) -> _PaginaHtml:
|
|
442
|
+
pagina = cls()
|
|
443
|
+
pagina.testo = response.text or ""
|
|
444
|
+
try:
|
|
445
|
+
pagina.feed(pagina.testo)
|
|
446
|
+
pagina.close()
|
|
447
|
+
except Exception: # pragma: no cover - HTMLParser è già molto tollerante
|
|
448
|
+
logger.debug("Pagina HTML non interpretabile", exc_info=True)
|
|
449
|
+
return pagina
|
|
450
|
+
|
|
451
|
+
# -- raccolta ------------------------------------------------------- #
|
|
452
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
453
|
+
a = {k.lower(): (v if v is not None else "") for k, v in attrs}
|
|
454
|
+
presenti = {k.lower() for k, _ in attrs}
|
|
455
|
+
if tag == "form":
|
|
456
|
+
self._form = _Form(action=a.get("action"), metodo=(a.get("method") or "get").upper())
|
|
457
|
+
self.forms.append(self._form)
|
|
458
|
+
elif tag == "input" and self._form is not None:
|
|
459
|
+
self._input(a, presenti)
|
|
460
|
+
elif tag == "button" and self._form is not None:
|
|
461
|
+
if (a.get("type") or "submit").lower() == "submit":
|
|
462
|
+
self._bottone = (a.get("name") or None, a.get("value", ""), [])
|
|
463
|
+
elif tag == "a" and a.get("href"):
|
|
464
|
+
self._link = (a["href"], [])
|
|
465
|
+
elif tag == "meta" and a.get("http-equiv", "").lower() == "refresh":
|
|
466
|
+
m = _META_REFRESH_URL.search(a.get("content", ""))
|
|
467
|
+
if m and self.meta_refresh is None:
|
|
468
|
+
self.meta_refresh = m.group(1).strip()
|
|
469
|
+
elif tag == "title":
|
|
470
|
+
self._in_titolo = True
|
|
471
|
+
|
|
472
|
+
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
473
|
+
self.handle_starttag(tag, attrs)
|
|
474
|
+
if tag == "button":
|
|
475
|
+
self.handle_endtag(tag)
|
|
476
|
+
|
|
477
|
+
def _input(self, a: dict[str, str], presenti: set[str]) -> None:
|
|
478
|
+
assert self._form is not None
|
|
479
|
+
tipo = (a.get("type") or "text").lower()
|
|
480
|
+
nome = a.get("name") or ""
|
|
481
|
+
valore = a.get("value", "")
|
|
482
|
+
if tipo in ("submit", "image"):
|
|
483
|
+
self._form.bottoni.append((nome or None, valore, valore))
|
|
484
|
+
elif tipo == "password":
|
|
485
|
+
self._form.ha_password = True
|
|
486
|
+
elif tipo in ("checkbox", "radio"):
|
|
487
|
+
# Come il browser mandiamo le caselle spuntate; le caselle degli
|
|
488
|
+
# scope le spuntiamo comunque (sono quelli che abbiamo chiesto).
|
|
489
|
+
if nome and ("checked" in presenti or "scope" in nome.lower()):
|
|
490
|
+
self._form.campi.append((nome, valore or "on"))
|
|
491
|
+
elif tipo in ("button", "reset", "file"):
|
|
492
|
+
return
|
|
493
|
+
elif nome:
|
|
494
|
+
self._form.campi.append((nome, valore))
|
|
495
|
+
|
|
496
|
+
def handle_endtag(self, tag: str) -> None:
|
|
497
|
+
if tag == "form":
|
|
498
|
+
self._form = None
|
|
499
|
+
elif tag == "button" and self._bottone is not None and self._form is not None:
|
|
500
|
+
nome, valore, testo = self._bottone
|
|
501
|
+
self._form.bottoni.append((nome, valore, " ".join(testo).strip()))
|
|
502
|
+
self._bottone = None
|
|
503
|
+
elif tag == "a" and self._link is not None:
|
|
504
|
+
href, testo = self._link
|
|
505
|
+
self.link.append((href, " ".join(testo).strip()))
|
|
506
|
+
self._link = None
|
|
507
|
+
elif tag == "title":
|
|
508
|
+
self._in_titolo = False
|
|
509
|
+
|
|
510
|
+
def handle_data(self, data: str) -> None:
|
|
511
|
+
if self._in_titolo:
|
|
512
|
+
self.titolo = (self.titolo + " " + data.strip()).strip()
|
|
513
|
+
if self._link is not None:
|
|
514
|
+
self._link[1].append(data.strip())
|
|
515
|
+
if self._bottone is not None:
|
|
516
|
+
self._bottone[2].append(data.strip())
|
|
517
|
+
|
|
518
|
+
# -- decisione ------------------------------------------------------ #
|
|
519
|
+
def passo_successivo(self, url: str, config: ArgoConfig) -> _Passo | None:
|
|
520
|
+
"""Il passo con cui un browser andrebbe avanti da questa pagina, o ``None``."""
|
|
521
|
+
testo = _decodifica_html(self.testo)
|
|
522
|
+
|
|
523
|
+
# a) La pagina contiene già il redirect verso l'app, con il code.
|
|
524
|
+
app = re.search(re.escape(config.redirect_uri) + r"\?[^\s\"'<>\\`]+", testo)
|
|
525
|
+
if app:
|
|
526
|
+
return _Passo("GET", app.group(0))
|
|
527
|
+
|
|
528
|
+
# b) Meta refresh o redirect via JavaScript.
|
|
529
|
+
if self.meta_refresh:
|
|
530
|
+
return _Passo("GET", urljoin(url, self.meta_refresh))
|
|
531
|
+
js = _JS_LOCATION.search(testo)
|
|
532
|
+
if js:
|
|
533
|
+
destinazione = js.group(1) or js.group(2)
|
|
534
|
+
if destinazione and not destinazione.startswith(("#", "javascript:")):
|
|
535
|
+
return _Passo("GET", urljoin(url, destinazione))
|
|
536
|
+
|
|
537
|
+
# c) Un form da inviare (tipicamente la pagina di consenso OAuth).
|
|
538
|
+
for form in self.forms:
|
|
539
|
+
passo = self._invia_form(form, url)
|
|
540
|
+
if passo is not None:
|
|
541
|
+
return passo
|
|
542
|
+
|
|
543
|
+
# d) Un link "Continua".
|
|
544
|
+
for href, etichetta in self.link:
|
|
545
|
+
if href.startswith(("#", "javascript:", "mailto:", "tel:")):
|
|
546
|
+
continue
|
|
547
|
+
if _LINK_AVANTI.search(etichetta):
|
|
548
|
+
return _Passo("GET", urljoin(url, href))
|
|
549
|
+
|
|
550
|
+
# e) Pagina di consenso senza form riconoscibile: accettiamo come fa l'app.
|
|
551
|
+
challenge = _query_param(url, "consent_challenge")
|
|
552
|
+
if challenge:
|
|
553
|
+
campi = [("challenge", challenge)]
|
|
554
|
+
campi += [("grant_scope", s) for s in config.scopes]
|
|
555
|
+
campi.append(("consent", "Accetta"))
|
|
556
|
+
return _Passo("POST", _senza_query(url), urlencode(campi))
|
|
557
|
+
return None
|
|
558
|
+
|
|
559
|
+
@staticmethod
|
|
560
|
+
def _invia_form(form: _Form, url: str) -> _Passo | None:
|
|
561
|
+
if form.ha_password:
|
|
562
|
+
# È di nuovo il form di login: inviarlo vuoto non serve a nulla.
|
|
563
|
+
return None
|
|
564
|
+
campi = list(form.campi)
|
|
565
|
+
if form.bottoni:
|
|
566
|
+
buoni = [
|
|
567
|
+
(nome, valore, testo)
|
|
568
|
+
for nome, valore, testo in form.bottoni
|
|
569
|
+
if not _BOTTONE_NEGATIVO.search(f"{nome or ''} {valore} {testo}")
|
|
570
|
+
]
|
|
571
|
+
if not buoni:
|
|
572
|
+
return None
|
|
573
|
+
nome, valore, _ = buoni[0]
|
|
574
|
+
if nome:
|
|
575
|
+
campi.append((nome, valore))
|
|
576
|
+
if not campi and not form.action:
|
|
577
|
+
return None
|
|
578
|
+
action = urljoin(url, form.action) if form.action else url
|
|
579
|
+
if form.metodo == "POST":
|
|
580
|
+
return _Passo("POST", action, urlencode(campi))
|
|
581
|
+
base = urlparse(action)
|
|
582
|
+
return _Passo("GET", base._replace(query=urlencode(campi)).geturl())
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
class _CookieJar:
|
|
586
|
+
"""Un cookie jar minimale: rimanda ogni cookie solo all'host o al dominio giusto.
|
|
587
|
+
|
|
588
|
+
Senza attributo ``Domain`` un cookie vale solo per l'host che l'ha
|
|
589
|
+
impostato; con ``Domain=portaleargo.it`` vale anche per i sottodomini.
|
|
590
|
+
"""
|
|
591
|
+
|
|
592
|
+
def __init__(self) -> None:
|
|
593
|
+
# (dominio, solo_host) -> {nome: valore}, in ordine di arrivo
|
|
594
|
+
self._cookie: dict[tuple[str, bool], dict[str, str]] = {}
|
|
595
|
+
|
|
596
|
+
def raccogli(self, response: httpx.Response) -> None:
|
|
597
|
+
host = response.request.url.host
|
|
598
|
+
for header in response.headers.get_list("set-cookie"):
|
|
599
|
+
coppia, *attributi = (parte.strip() for parte in header.split(";"))
|
|
600
|
+
nome, sep, valore = coppia.partition("=")
|
|
601
|
+
if not sep or not nome:
|
|
602
|
+
continue
|
|
603
|
+
dominio, solo_host, cancella = host, True, False
|
|
604
|
+
for attributo in attributi:
|
|
605
|
+
chiave, _, val = attributo.partition("=")
|
|
606
|
+
chiave = chiave.strip().lower()
|
|
607
|
+
if chiave == "domain" and val.strip():
|
|
608
|
+
dominio, solo_host = val.strip().lstrip(".").lower(), False
|
|
609
|
+
elif chiave == "max-age" and val.strip().lstrip("-").isdigit():
|
|
610
|
+
cancella = int(val) <= 0
|
|
611
|
+
jar = self._cookie.setdefault((dominio, solo_host), {})
|
|
612
|
+
jar.pop(nome, None)
|
|
613
|
+
if not cancella:
|
|
614
|
+
jar[nome] = valore
|
|
615
|
+
|
|
616
|
+
def header_per(self, url: str) -> str:
|
|
617
|
+
host = httpx.URL(url).host
|
|
618
|
+
coppie = [
|
|
619
|
+
f"{nome}={valore}"
|
|
620
|
+
for (dominio, solo_host), jar in self._cookie.items()
|
|
621
|
+
if host == dominio or (not solo_host and host.endswith("." + dominio))
|
|
622
|
+
for nome, valore in jar.items()
|
|
623
|
+
]
|
|
624
|
+
return "; ".join(coppie)
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def _location(response: httpx.Response) -> str | None:
|
|
628
|
+
"""Il ``Location`` di un redirect, reso assoluto se il server lo manda relativo."""
|
|
629
|
+
if not response.is_redirect:
|
|
630
|
+
return None
|
|
631
|
+
loc = response.headers.get("location")
|
|
632
|
+
return urljoin(str(response.request.url), loc) if loc else None
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def _senza_query(url: str) -> str:
|
|
636
|
+
"""L'URL senza query string, per log ed errori (la query contiene code e challenge)."""
|
|
637
|
+
return url.split("?", 1)[0]
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def _query_param(url: str, nome: str) -> str | None:
|
|
641
|
+
valori = parse_qs(urlparse(url).query).get(nome)
|
|
642
|
+
return valori[0] if valori else None
|