authforce-rs-labs 0.2.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.
- authforce/__init__.py +27 -0
- authforce/config.py +59 -0
- authforce/dependencies.py +78 -0
- authforce/errors.py +78 -0
- authforce/models.py +105 -0
- authforce/oauth_state.py +53 -0
- authforce/providers/__init__.py +4 -0
- authforce/providers/apple.py +120 -0
- authforce/providers/google.py +163 -0
- authforce/py.typed +0 -0
- authforce/rate_limit.py +56 -0
- authforce/router.py +231 -0
- authforce/security.py +156 -0
- authforce/service.py +444 -0
- authforce_rs_labs-0.2.0.dist-info/METADATA +149 -0
- authforce_rs_labs-0.2.0.dist-info/RECORD +19 -0
- authforce_rs_labs-0.2.0.dist-info/WHEEL +5 -0
- authforce_rs_labs-0.2.0.dist-info/licenses/LICENSE +21 -0
- authforce_rs_labs-0.2.0.dist-info/top_level.txt +1 -0
authforce/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""authforce: autenticazione riusabile per backend FastAPI e SQLAlchemy async.
|
|
2
|
+
|
|
3
|
+
Parti generiche e di sicurezza del login. Le regole di un progetto (inviti,
|
|
4
|
+
email, profilo, statistiche) restano nel progetto e chiamano questi metodi.
|
|
5
|
+
"""
|
|
6
|
+
from authforce import errors, oauth_state, security
|
|
7
|
+
from authforce.config import AuthConfig
|
|
8
|
+
from authforce.dependencies import AuthDependencies, http_error
|
|
9
|
+
from authforce.models import (
|
|
10
|
+
AuthModels,
|
|
11
|
+
CredentialsMixin,
|
|
12
|
+
EmailVerificationMixin,
|
|
13
|
+
OAuthAccountMixin,
|
|
14
|
+
SessionMixin,
|
|
15
|
+
UserMixin,
|
|
16
|
+
)
|
|
17
|
+
from authforce.rate_limit import InMemoryRateLimiter, NoRateLimit, RateLimiter
|
|
18
|
+
from authforce.service import AuthService, OAuthLoginResult, OAuthProfile, TokenPair, UnlinkResult
|
|
19
|
+
|
|
20
|
+
__version__ = "0.2.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"AuthConfig", "AuthDependencies", "AuthModels", "AuthService", "CredentialsMixin",
|
|
24
|
+
"EmailVerificationMixin", "InMemoryRateLimiter", "NoRateLimit", "OAuthAccountMixin",
|
|
25
|
+
"OAuthLoginResult", "OAuthProfile", "RateLimiter", "SessionMixin", "TokenPair", "UnlinkResult", "UserMixin",
|
|
26
|
+
"__version__", "errors", "http_error", "oauth_state", "security",
|
|
27
|
+
]
|
authforce/config.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Configurazione della libreria. Un'istanza per applicazione, costruita dalle
|
|
2
|
+
impostazioni del progetto (variabili d'ambiente, file .env)."""
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
|
|
6
|
+
MIN_SECRET_LENGTH = 32
|
|
7
|
+
# Algoritmi a segreto condiviso: jwt_secret_key e' una stringa, non una chiave
|
|
8
|
+
# asimmetrica. Un valore fuori lista (per esempio "none") non parte.
|
|
9
|
+
ALLOWED_JWT_ALGORITHMS = ("HS256", "HS384", "HS512")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class AuthConfig:
|
|
14
|
+
jwt_secret_key: str
|
|
15
|
+
jwt_algorithm: str = "HS256"
|
|
16
|
+
access_token_ttl: timedelta = timedelta(minutes=30)
|
|
17
|
+
refresh_token_ttl: timedelta = timedelta(days=30)
|
|
18
|
+
email_verification_ttl: timedelta = timedelta(hours=48)
|
|
19
|
+
# Validita' del link "non sei stato tu? scollega" mandato quando un login
|
|
20
|
+
# social si collega a un account esistente.
|
|
21
|
+
unlink_token_ttl: timedelta = timedelta(days=7)
|
|
22
|
+
# Un login riuscito riattiva un account disattivato dall'utente stesso.
|
|
23
|
+
reactivate_on_login: bool = True
|
|
24
|
+
# Valori di auth_provider: account solo locale, e locale piu' social.
|
|
25
|
+
local_provider: str = "local"
|
|
26
|
+
linked_provider: str = "both"
|
|
27
|
+
# Refresh token e token di verifica email salvati come SHA-256: una copia
|
|
28
|
+
# del database non basta per aprire una sessione. Il valore in chiaro
|
|
29
|
+
# viaggia solo verso il client.
|
|
30
|
+
hash_stored_tokens: bool = True
|
|
31
|
+
# Transizione per i progetti che avevano i token in chiaro: la ricerca
|
|
32
|
+
# accetta anche il valore non hashato finche' le vecchie sessioni non
|
|
33
|
+
# scadono o vengono ruotate. Un valore con la forma di un hash non viene
|
|
34
|
+
# mai cercato in chiaro. Da spegnere dopo refresh_token_ttl.
|
|
35
|
+
accept_plain_stored_tokens: bool = True
|
|
36
|
+
# Un refresh token gia' ruotato che viene presentato di nuovo indica un
|
|
37
|
+
# token copiato (o un client che ha perso la risposta). Con True chiude
|
|
38
|
+
# tutte le sessioni dell'utente, come consiglia OAuth 2.1. Con False
|
|
39
|
+
# risponde solo InvalidSession, piu' tollerante con i client che fanno due
|
|
40
|
+
# refresh in parallelo.
|
|
41
|
+
revoke_all_on_refresh_reuse: bool = False
|
|
42
|
+
# Email confrontate senza distinguere maiuscole e spazi ai bordi: una
|
|
43
|
+
# stessa casella non puo' diventare due account.
|
|
44
|
+
normalize_emails: bool = True
|
|
45
|
+
extra: dict = field(default_factory=dict)
|
|
46
|
+
|
|
47
|
+
def __post_init__(self) -> None:
|
|
48
|
+
# Fail-closed: con un segreto vuoto o corto i token sarebbero
|
|
49
|
+
# falsificabili. Meglio un avvio fallito.
|
|
50
|
+
if len(self.jwt_secret_key or "") < MIN_SECRET_LENGTH:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"jwt_secret_key assente o troppo corta (minimo {MIN_SECRET_LENGTH} caratteri)"
|
|
53
|
+
)
|
|
54
|
+
if self.jwt_algorithm not in ALLOWED_JWT_ALGORITHMS:
|
|
55
|
+
raise ValueError(f"jwt_algorithm non ammesso: {self.jwt_algorithm!r} (ammessi {ALLOWED_JWT_ALGORITHMS})")
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def access_token_ttl_seconds(self) -> int:
|
|
59
|
+
return int(self.access_token_ttl.total_seconds())
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Dipendenze FastAPI per le rotte protette, generate per un AuthService e la
|
|
3
|
+
dipendenza che fornisce la sessione DB del progetto.
|
|
4
|
+
|
|
5
|
+
deps = AuthDependencies(auth, get_session)
|
|
6
|
+
|
|
7
|
+
@router.get("/me")
|
|
8
|
+
async def me(user = Depends(deps.current_user)): ...
|
|
9
|
+
|
|
10
|
+
Messaggi in inglese di default; `messages` li sostituisce per codice
|
|
11
|
+
d'errore (errors.*.code).
|
|
12
|
+
"""
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
|
|
15
|
+
from fastapi import Depends, HTTPException, status
|
|
16
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
17
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
18
|
+
|
|
19
|
+
from authforce.errors import AuthError
|
|
20
|
+
from authforce.service import AuthService
|
|
21
|
+
|
|
22
|
+
DEFAULT_MESSAGES = {
|
|
23
|
+
"invalid_token": "Invalid or expired token.",
|
|
24
|
+
"expired_token": "Token expired.",
|
|
25
|
+
"user_not_found": "User not found.",
|
|
26
|
+
"inactive_user": "Account disabled.",
|
|
27
|
+
"forbidden": "Not allowed.",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def http_error(error: AuthError, messages: dict | None = None) -> HTTPException:
|
|
32
|
+
"""HTTPException dell'errore; 401 con WWW-Authenticate: Bearer."""
|
|
33
|
+
detail = (messages or {}).get(error.code) or DEFAULT_MESSAGES.get(error.code) or error.code
|
|
34
|
+
headers = {"WWW-Authenticate": "Bearer"} if error.status_code == status.HTTP_401_UNAUTHORIZED else None
|
|
35
|
+
return HTTPException(status_code=error.status_code, detail=detail, headers=headers)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AuthDependencies:
|
|
39
|
+
def __init__(self, auth: AuthService, get_session: Callable, messages: dict | None = None):
|
|
40
|
+
self.auth = auth
|
|
41
|
+
self.messages = messages or {}
|
|
42
|
+
bearer = HTTPBearer()
|
|
43
|
+
optional_bearer = HTTPBearer(auto_error=False)
|
|
44
|
+
|
|
45
|
+
async def current_user(
|
|
46
|
+
credentials: HTTPAuthorizationCredentials = Depends(bearer),
|
|
47
|
+
db: AsyncSession = Depends(get_session),
|
|
48
|
+
):
|
|
49
|
+
try:
|
|
50
|
+
return await auth.user_from_access_token(db, credentials.credentials)
|
|
51
|
+
except AuthError as exc:
|
|
52
|
+
raise http_error(exc, self.messages) from exc
|
|
53
|
+
|
|
54
|
+
async def optional_user(
|
|
55
|
+
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
|
|
56
|
+
db: AsyncSession = Depends(get_session),
|
|
57
|
+
):
|
|
58
|
+
if credentials is None:
|
|
59
|
+
return None
|
|
60
|
+
try:
|
|
61
|
+
return await auth.user_from_access_token(db, credentials.credentials)
|
|
62
|
+
except AuthError:
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
self.current_user = current_user
|
|
66
|
+
self.optional_user = optional_user
|
|
67
|
+
|
|
68
|
+
def require(self, predicate: Callable[[object], bool], code: str = "forbidden"):
|
|
69
|
+
"""Utente autenticato che soddisfa `predicate` (es. admin), altrimenti 403."""
|
|
70
|
+
current_user = self.current_user
|
|
71
|
+
|
|
72
|
+
async def dependency(user=Depends(current_user)):
|
|
73
|
+
if not predicate(user):
|
|
74
|
+
raise HTTPException(status.HTTP_403_FORBIDDEN,
|
|
75
|
+
detail=self.messages.get(code) or DEFAULT_MESSAGES.get(code, code))
|
|
76
|
+
return user
|
|
77
|
+
|
|
78
|
+
return dependency
|
authforce/errors.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Errori della libreria. Non contengono testi per l'utente: il progetto li
|
|
2
|
+
traduce in risposte HTTP con i propri messaggi e la propria lingua
|
|
3
|
+
(`status_code` e' il codice suggerito)."""
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AuthError(Exception):
|
|
7
|
+
status_code = 400
|
|
8
|
+
code = "auth_error"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EmailAlreadyRegistered(AuthError):
|
|
12
|
+
status_code = 409
|
|
13
|
+
code = "email_already_registered"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PasswordTooLong(AuthError):
|
|
17
|
+
"""bcrypt usa al massimo 72 byte: una password piu' lunga verrebbe troncata."""
|
|
18
|
+
status_code = 400
|
|
19
|
+
code = "password_too_long"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InvalidCredentials(AuthError):
|
|
23
|
+
status_code = 401
|
|
24
|
+
code = "invalid_credentials"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class InvalidToken(AuthError):
|
|
28
|
+
"""Access token assente, malformato, firmato male o di tipo sbagliato."""
|
|
29
|
+
status_code = 401
|
|
30
|
+
code = "invalid_token"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ExpiredToken(InvalidToken):
|
|
34
|
+
code = "expired_token"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class InvalidSession(AuthError):
|
|
38
|
+
"""Refresh token sconosciuto, revocato o scaduto."""
|
|
39
|
+
status_code = 401
|
|
40
|
+
code = "invalid_session"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class UserNotFound(AuthError):
|
|
44
|
+
status_code = 404
|
|
45
|
+
code = "user_not_found"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class InactiveUser(AuthError):
|
|
49
|
+
status_code = 403
|
|
50
|
+
code = "inactive_user"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class InvalidVerificationToken(AuthError):
|
|
54
|
+
status_code = 400
|
|
55
|
+
code = "invalid_verification_token"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class OAuthError(AuthError):
|
|
59
|
+
"""Token o codice del provider rifiutato."""
|
|
60
|
+
status_code = 401
|
|
61
|
+
code = "oauth_error"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class OAuthEmailNotVerified(AuthError):
|
|
65
|
+
"""Il provider non garantisce l'email: non si collega a un account esistente."""
|
|
66
|
+
status_code = 403
|
|
67
|
+
code = "oauth_email_not_verified"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class OAuthEmailMissing(AuthError):
|
|
71
|
+
"""Primo login social senza email (Apple la manda solo la prima volta)."""
|
|
72
|
+
status_code = 400
|
|
73
|
+
code = "oauth_email_missing"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ProviderNotConfigured(AuthError):
|
|
77
|
+
status_code = 500
|
|
78
|
+
code = "provider_not_configured"
|
authforce/models.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Modelli dell'autenticazione.
|
|
3
|
+
|
|
4
|
+
La libreria non crea tabelle da sola. Il progetto le dichiara sulla propria
|
|
5
|
+
Base SQLAlchemy e le passa ad AuthModels:
|
|
6
|
+
|
|
7
|
+
- progetto nuovo: classi che ereditano dai mixin qui sotto, con tabella e
|
|
8
|
+
schema a scelta;
|
|
9
|
+
- progetto esistente: le proprie classi, purche' abbiano gli stessi attributi
|
|
10
|
+
dei mixin (PitQuiz passa i modelli di app_auth senza cambiarli).
|
|
11
|
+
|
|
12
|
+
Esempio:
|
|
13
|
+
|
|
14
|
+
class User(Base, UserMixin):
|
|
15
|
+
__tablename__ = "users"
|
|
16
|
+
|
|
17
|
+
class Session(Base, SessionMixin):
|
|
18
|
+
__tablename__ = "user_sessions"
|
|
19
|
+
__auth_user_fk__ = "users.id"
|
|
20
|
+
|
|
21
|
+
Campi profilo facoltativi sull'utente (full_name, avatar_url): se il modello
|
|
22
|
+
li ha, i login social li riempiono quando sono vuoti.
|
|
23
|
+
|
|
24
|
+
`session_token` ed `email_verification.token` contengono l'hash SHA-256 del
|
|
25
|
+
token dato al client (64 caratteri esadecimali), vedi AuthConfig.hash_stored_tokens.
|
|
26
|
+
"""
|
|
27
|
+
import uuid
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from datetime import UTC, datetime
|
|
30
|
+
|
|
31
|
+
from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text, UniqueConstraint, Uuid
|
|
32
|
+
from sqlalchemy.orm import Mapped, declared_attr, mapped_column
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _now() -> datetime:
|
|
36
|
+
return datetime.now(UTC)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _UserFK:
|
|
40
|
+
# "<tabella>.id" o "<schema>.<tabella>.id" della tabella utenti.
|
|
41
|
+
__auth_user_fk__ = "users.id"
|
|
42
|
+
|
|
43
|
+
@declared_attr
|
|
44
|
+
def user_id(cls) -> Mapped[uuid.UUID]:
|
|
45
|
+
return mapped_column(
|
|
46
|
+
Uuid, ForeignKey(cls.__auth_user_fk__, ondelete="CASCADE"), nullable=False, index=True,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class UserMixin:
|
|
51
|
+
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
|
|
52
|
+
email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
|
|
53
|
+
auth_provider: Mapped[str] = mapped_column(String(20), nullable=False, default="local")
|
|
54
|
+
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
|
55
|
+
is_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
|
56
|
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
|
|
57
|
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class CredentialsMixin(_UserFK):
|
|
61
|
+
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
|
|
62
|
+
hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
|
|
63
|
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
|
|
64
|
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class OAuthAccountMixin(_UserFK):
|
|
68
|
+
@declared_attr.directive
|
|
69
|
+
def __table_args__(cls):
|
|
70
|
+
return (UniqueConstraint("provider", "provider_user_id"),)
|
|
71
|
+
|
|
72
|
+
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
|
|
73
|
+
provider: Mapped[str] = mapped_column(String(20), nullable=False)
|
|
74
|
+
provider_user_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
|
75
|
+
# Apple: serve per revocare l'accesso alla cancellazione dell'account.
|
|
76
|
+
provider_refresh_token: Mapped[str | None] = mapped_column(Text)
|
|
77
|
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class SessionMixin(_UserFK):
|
|
81
|
+
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
|
|
82
|
+
session_token: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
|
|
83
|
+
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
|
84
|
+
is_revoked: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
|
85
|
+
ip_address: Mapped[str | None] = mapped_column(String(45))
|
|
86
|
+
user_agent: Mapped[str | None] = mapped_column(Text)
|
|
87
|
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class EmailVerificationMixin(_UserFK):
|
|
91
|
+
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
|
|
92
|
+
token: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
|
|
93
|
+
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
|
94
|
+
consumed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
95
|
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class AuthModels:
|
|
100
|
+
"""Le classi ORM che la libreria legge e scrive."""
|
|
101
|
+
user: type
|
|
102
|
+
credentials: type
|
|
103
|
+
oauth_account: type
|
|
104
|
+
session: type
|
|
105
|
+
email_verification: type
|
authforce/oauth_state.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Stato anti-CSRF del login OAuth via redirect. Il valore casuale va nel
|
|
3
|
+
parametro `state` verso il provider e in un cookie HttpOnly; al callback i
|
|
4
|
+
due devono coincidere. Il cookie puo' portare un dato in piu' (per esempio
|
|
5
|
+
un codice di invito) dopo il separatore.
|
|
6
|
+
"""
|
|
7
|
+
import secrets
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
COOKIE_NAME = "oauth_state"
|
|
11
|
+
COOKIE_MAX_AGE = 300
|
|
12
|
+
SEPARATOR = "|"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class OAuthState:
|
|
17
|
+
state: str
|
|
18
|
+
payload: str | None = None
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def cookie_value(self) -> str:
|
|
22
|
+
return f"{self.state}{SEPARATOR}{self.payload}" if self.payload else self.state
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def new_state(payload: str | None = None) -> OAuthState:
|
|
26
|
+
return OAuthState(secrets.token_urlsafe(24), payload or None)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def parse_cookie(value: str | None) -> OAuthState | None:
|
|
30
|
+
if not value:
|
|
31
|
+
return None
|
|
32
|
+
state, _, payload = value.partition(SEPARATOR)
|
|
33
|
+
return OAuthState(state, payload or None) if state else None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def verify(cookie_value: str | None, returned_state: str | None) -> OAuthState | None:
|
|
37
|
+
"""Lo stato del cookie se coincide con quello tornato dal provider
|
|
38
|
+
(confronto timing-safe), altrimenti None."""
|
|
39
|
+
parsed = parse_cookie(cookie_value)
|
|
40
|
+
# In byte: lo stato torna da un parametro della query, puo' contenere
|
|
41
|
+
# qualsiasi carattere (compare_digest su str non ASCII solleva TypeError).
|
|
42
|
+
if parsed is None or not returned_state or not secrets.compare_digest(
|
|
43
|
+
parsed.state.encode(), returned_state.encode(),
|
|
44
|
+
):
|
|
45
|
+
return None
|
|
46
|
+
return parsed
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def cookie_kwargs(secure: bool = True) -> dict:
|
|
50
|
+
"""Argomenti per Response.set_cookie: non leggibile da JavaScript, non
|
|
51
|
+
inviato nelle richieste cross-site, solo su HTTPS, scadenza breve.
|
|
52
|
+
`secure=False` solo per lo sviluppo su http senza localhost."""
|
|
53
|
+
return {"key": COOKIE_NAME, "httponly": True, "secure": secure, "samesite": "lax", "max_age": COOKIE_MAX_AGE}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sign in with Apple da app nativa: verifica dell'identity_token (RS256 con le
|
|
3
|
+
chiavi pubbliche di Apple), scambio dell'authorizationCode in un refresh
|
|
4
|
+
token Apple e sua revoca alla cancellazione dell'account (obbligatoria per
|
|
5
|
+
le linee guida App Store 5.1.1(v)).
|
|
6
|
+
"""
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from time import time
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
import jwt
|
|
13
|
+
from jwt import PyJWKClient
|
|
14
|
+
|
|
15
|
+
from authforce.errors import OAuthError, ProviderNotConfigured
|
|
16
|
+
from authforce.service import OAuthProfile
|
|
17
|
+
|
|
18
|
+
ISSUER = "https://appleid.apple.com"
|
|
19
|
+
KEYS_URL = "https://appleid.apple.com/auth/keys"
|
|
20
|
+
TOKEN_URL = "https://appleid.apple.com/auth/token"
|
|
21
|
+
REVOKE_URL = "https://appleid.apple.com/auth/revoke"
|
|
22
|
+
PROVIDER = "apple"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class AppleProfile:
|
|
27
|
+
sub: str
|
|
28
|
+
email: str | None
|
|
29
|
+
email_verified: bool
|
|
30
|
+
# Apple manda il nome solo al primo login, al client: arriva dal client.
|
|
31
|
+
full_name: str | None = None
|
|
32
|
+
|
|
33
|
+
def to_oauth_profile(self, provider_refresh_token: str | None = None) -> OAuthProfile:
|
|
34
|
+
return OAuthProfile(
|
|
35
|
+
provider=PROVIDER, provider_user_id=self.sub, email=self.email,
|
|
36
|
+
email_verified=self.email_verified, full_name=self.full_name,
|
|
37
|
+
provider_refresh_token=provider_refresh_token,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class AppleTokens:
|
|
43
|
+
access_token: str
|
|
44
|
+
refresh_token: str
|
|
45
|
+
id_token: str
|
|
46
|
+
expires_in: int
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class AppleSignIn:
|
|
51
|
+
bundle_id: str
|
|
52
|
+
team_id: str = ""
|
|
53
|
+
key_id: str = ""
|
|
54
|
+
# Legge la chiave privata .p8 di Sign in with Apple (file, secret manager...).
|
|
55
|
+
private_key_loader: Callable[[], str] | None = None
|
|
56
|
+
_jwk_client: PyJWKClient | None = field(default=None, repr=False)
|
|
57
|
+
_private_key: str | None = field(default=None, repr=False)
|
|
58
|
+
|
|
59
|
+
def jwk_client(self) -> PyJWKClient:
|
|
60
|
+
if self._jwk_client is None:
|
|
61
|
+
self._jwk_client = PyJWKClient(KEYS_URL)
|
|
62
|
+
return self._jwk_client
|
|
63
|
+
|
|
64
|
+
def verify_identity_token(self, identity_token: str, full_name: str | None = None,
|
|
65
|
+
jwk_client: PyJWKClient | None = None, nonce: str | None = None) -> AppleProfile:
|
|
66
|
+
"""Firma RS256 con le chiavi di Apple, audience = bundle id,
|
|
67
|
+
issuer = Apple, scadenza. Con `nonce` (hash SHA-256 di quello mandato
|
|
68
|
+
dal client ad Apple) controlla anche il claim nonce, contro il riuso
|
|
69
|
+
di un token rubato. OAuthError se non valido.
|
|
70
|
+
|
|
71
|
+
Sincrona: alla prima chiamata scarica le chiavi di Apple. Da codice
|
|
72
|
+
async conviene chiamarla con asyncio.to_thread."""
|
|
73
|
+
try:
|
|
74
|
+
signing_key = (jwk_client or self.jwk_client()).get_signing_key_from_jwt(identity_token)
|
|
75
|
+
data = jwt.decode(identity_token, signing_key.key, algorithms=["RS256"],
|
|
76
|
+
audience=self.bundle_id, issuer=ISSUER,
|
|
77
|
+
options={"require": ["exp", "sub"]})
|
|
78
|
+
except jwt.PyJWTError as exc:
|
|
79
|
+
raise OAuthError(f"identity_token Apple non valido: {exc}") from exc
|
|
80
|
+
if nonce is not None and data.get("nonce") != nonce:
|
|
81
|
+
raise OAuthError("nonce dell'identity_token Apple non valido")
|
|
82
|
+
return AppleProfile(
|
|
83
|
+
sub=data["sub"], email=data.get("email"),
|
|
84
|
+
email_verified=str(data.get("email_verified", "false")).lower() == "true",
|
|
85
|
+
full_name=full_name,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def _client_secret(self) -> str:
|
|
89
|
+
"""JWT ES256 di breve durata richiesto da /auth/token e /auth/revoke."""
|
|
90
|
+
if not self.team_id or not self.key_id or self.private_key_loader is None:
|
|
91
|
+
raise ProviderNotConfigured("Sign in with Apple: team_id, key_id o chiave privata mancanti")
|
|
92
|
+
if self._private_key is None:
|
|
93
|
+
self._private_key = self.private_key_loader()
|
|
94
|
+
now = int(time())
|
|
95
|
+
payload = {"iss": self.team_id, "iat": now, "exp": now + 300, "aud": ISSUER, "sub": self.bundle_id}
|
|
96
|
+
return jwt.encode(payload, self._private_key, algorithm="ES256", headers={"kid": self.key_id})
|
|
97
|
+
|
|
98
|
+
async def exchange_authorization_code(self, authorization_code: str) -> AppleTokens:
|
|
99
|
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
|
100
|
+
response = await client.post(TOKEN_URL, data={
|
|
101
|
+
"client_id": self.bundle_id,
|
|
102
|
+
"client_secret": self._client_secret(),
|
|
103
|
+
"code": authorization_code,
|
|
104
|
+
"grant_type": "authorization_code",
|
|
105
|
+
}, headers={"Content-Type": "application/x-www-form-urlencoded"})
|
|
106
|
+
if response.status_code != 200:
|
|
107
|
+
raise OAuthError(f"scambio del codice Apple rifiutato: {response.status_code} {response.text}")
|
|
108
|
+
data = response.json()
|
|
109
|
+
return AppleTokens(data["access_token"], data["refresh_token"], data["id_token"], data["expires_in"])
|
|
110
|
+
|
|
111
|
+
async def revoke_refresh_token(self, refresh_token: str) -> None:
|
|
112
|
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
|
113
|
+
response = await client.post(REVOKE_URL, data={
|
|
114
|
+
"client_id": self.bundle_id,
|
|
115
|
+
"client_secret": self._client_secret(),
|
|
116
|
+
"token": refresh_token,
|
|
117
|
+
"token_type_hint": "refresh_token",
|
|
118
|
+
}, headers={"Content-Type": "application/x-www-form-urlencoded"})
|
|
119
|
+
if response.status_code != 200:
|
|
120
|
+
raise OAuthError(f"revoca del token Apple rifiutata: {response.status_code} {response.text}")
|