Les requêtes sont acceptées avec ou sans le préfixe (Caddy peut le retirer ou non). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
194 lignes
7.8 KiB
Python
194 lignes
7.8 KiB
Python
"""« Se connecter avec Gastinel » : client OAuth 2 (code + PKCE S256) vers le Hub. Bibliothèque standard seulement.
|
|
|
|
Contrat du Hub (Plan-connexion-Gastinel.md) :
|
|
GET {hub}/oauth/autoriser?response_type=code&client_id&redirect_uri&state&code_challenge&code_challenge_method=S256
|
|
POST {hub}/oauth/jeton (formulaire) grant_type=authorization_code, code, redirect_uri, client_id, code_verifier[, client_secret]
|
|
-> {"access_token", "token_type": "Bearer", "expires_in": 3600} ; erreurs {"error"} en 400/401/429
|
|
GET {hub}/oauth/moi (Authorization: Bearer <jeton>) -> {"id": "<uuid>", "pseudo": "..."} ; sinon 401 {"error": "invalid_token"}
|
|
|
|
Le forum ne voit jamais le mot de passe ni l'e-mail : seulement l'identifiant et le pseudo.
|
|
"""
|
|
import base64
|
|
import hashlib
|
|
import ipaddress
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
REPONSE_MAX = 64 * 1024 # réponse du Hub lue au plus (octets)
|
|
DELAI = 10 # secondes
|
|
ID_HUB_OK = re.compile(r"^[A-Za-z0-9_.:@-]{1,64}$")
|
|
LOCALES = [ipaddress.ip_network(n) for n in ("127.0.0.0/8", "10.0.0.0/8", "192.168.0.0/16", "::1/128")]
|
|
|
|
|
|
class ErreurHub(Exception):
|
|
"""Le Hub a refusé ou n'a pas répondu correctement."""
|
|
|
|
|
|
def _bool(v):
|
|
return str(v or "").strip() == "1"
|
|
|
|
|
|
PREFIXE_OK = re.compile(r"^(/[A-Za-z0-9._~-]+)+$")
|
|
|
|
|
|
def normaliser_prefixe(p):
|
|
"""« forum », « /forum/ » -> « /forum » ; vide -> « ». Refuse tout caractère douteux (injection dans les liens)."""
|
|
p = (p or "").strip().strip("/")
|
|
if not p:
|
|
return ""
|
|
p = "/" + p
|
|
if not PREFIXE_OK.match(p):
|
|
raise ValueError("FORUM_PREFIXE invalide : lettres, chiffres, . _ ~ - et / seulement")
|
|
return p
|
|
|
|
|
|
class Reglages:
|
|
"""Configuration de la connexion. En production : depuis les variables d'environnement (depuis_env)."""
|
|
|
|
def __init__(self, hub_url="", client_id="forum-vercors",
|
|
redirect_uri=None, client_secret="",
|
|
mode_test=False, relais=("127.0.0.1", "::1"), prefixe=""):
|
|
self.prefixe = normaliser_prefixe(prefixe)
|
|
self.hub_url = (hub_url or "").rstrip("/")
|
|
if self.hub_url:
|
|
u = urllib.parse.urlparse(self.hub_url)
|
|
local = u.hostname in ("127.0.0.1", "localhost", "::1")
|
|
if u.scheme != "https" and not (u.scheme == "http" and local):
|
|
raise ValueError("FORUM_HUB_URL doit être en https (http seulement en local)")
|
|
self.client_id = client_id
|
|
self.redirect_uri = redirect_uri or "https://vercors.me%s/connexion/retour" % self.prefixe
|
|
self.client_secret = client_secret
|
|
self.mode_test = bool(mode_test)
|
|
self.relais = frozenset(relais)
|
|
|
|
@property
|
|
def configuree(self):
|
|
return bool(self.hub_url and self.client_id and self.redirect_uri)
|
|
|
|
@classmethod
|
|
def depuis_env(cls, env=None):
|
|
env = os.environ if env is None else env
|
|
secret = ""
|
|
fichier = env.get("FORUM_OAUTH_SECRET_FILE")
|
|
if fichier:
|
|
with open(fichier, encoding="utf-8") as fh:
|
|
secret = fh.read().strip()
|
|
else:
|
|
secret = env.get("FORUM_OAUTH_SECRET", "")
|
|
relais = ("127.0.0.1", "::1") + tuple(x.strip() for x in env.get("FORUM_RELAIS", "").split(",") if x.strip())
|
|
return cls(hub_url=env.get("FORUM_HUB_URL", ""),
|
|
client_id=env.get("FORUM_CLIENT_ID", "forum-vercors"),
|
|
redirect_uri=env.get("FORUM_REDIRECT_URI") or None,
|
|
prefixe=env.get("FORUM_PREFIXE", ""),
|
|
client_secret=secret,
|
|
mode_test=_bool(env.get("FORUM_MODE_TEST")),
|
|
relais=relais)
|
|
|
|
|
|
# --- PKCE et adresse d'autorisation ------------------------------------------
|
|
def _b64(octets):
|
|
return base64.urlsafe_b64encode(octets).rstrip(b"=").decode("ascii")
|
|
|
|
|
|
def pkce():
|
|
"""Retourne (code_verifier, code_challenge S256)."""
|
|
verifier = secrets.token_urlsafe(48) # 64 caractères (RFC 7636 : 43 à 128)
|
|
return verifier, _b64(hashlib.sha256(verifier.encode("ascii")).digest())
|
|
|
|
|
|
def nouvel_etat():
|
|
return secrets.token_urlsafe(32)
|
|
|
|
|
|
def url_autorisation(r, etat, challenge):
|
|
q = urllib.parse.urlencode({"response_type": "code", "client_id": r.client_id, "redirect_uri": r.redirect_uri,
|
|
"state": etat, "code_challenge": challenge, "code_challenge_method": "S256"})
|
|
return "%s/oauth/autoriser?%s" % (r.hub_url, q)
|
|
|
|
|
|
# --- appels serveur à serveur ------------------------------------------------
|
|
class _SansRedirection(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, *a, **k): # un code ou un jeton ne suit jamais une redirection
|
|
return None
|
|
|
|
|
|
_OUVREUR = urllib.request.build_opener(urllib.request.ProxyHandler({}), _SansRedirection())
|
|
|
|
|
|
def _json(req):
|
|
try:
|
|
with _OUVREUR.open(req, timeout=DELAI) as rep:
|
|
brut = rep.read(REPONSE_MAX + 1)
|
|
except urllib.error.HTTPError as ex:
|
|
raise ErreurHub("le Hub a répondu %d" % ex.code)
|
|
except (urllib.error.URLError, OSError) as ex:
|
|
raise ErreurHub("Hub injoignable (%s)" % ex.__class__.__name__)
|
|
if len(brut) > REPONSE_MAX:
|
|
raise ErreurHub("réponse du Hub trop longue")
|
|
try:
|
|
d = json.loads(brut.decode("utf-8"))
|
|
except ValueError:
|
|
raise ErreurHub("réponse du Hub illisible")
|
|
if not isinstance(d, dict):
|
|
raise ErreurHub("réponse du Hub inattendue")
|
|
return d
|
|
|
|
|
|
def echanger_code(r, code, verifier):
|
|
"""Échange le code contre un jeton d'accès (POST /oauth/jeton)."""
|
|
champs = {"grant_type": "authorization_code", "code": code, "redirect_uri": r.redirect_uri,
|
|
"client_id": r.client_id, "code_verifier": verifier}
|
|
if r.client_secret:
|
|
champs["client_secret"] = r.client_secret
|
|
req = urllib.request.Request(r.hub_url + "/oauth/jeton", data=urllib.parse.urlencode(champs).encode("ascii"),
|
|
headers={"Content-Type": "application/x-www-form-urlencoded",
|
|
"Accept": "application/json"}, method="POST")
|
|
jeton = _json(req).get("access_token")
|
|
if not isinstance(jeton, str) or not jeton or len(jeton) > 4096:
|
|
raise ErreurHub("jeton absent")
|
|
return jeton
|
|
|
|
|
|
def lire_profil(r, jeton):
|
|
"""GET /oauth/moi -> (id Gastinel, pseudo)."""
|
|
req = urllib.request.Request(r.hub_url + "/oauth/moi",
|
|
headers={"Authorization": "Bearer " + jeton, "Accept": "application/json"})
|
|
d = _json(req)
|
|
ident = d.get("id", d.get("sub"))
|
|
if isinstance(ident, bool) or not isinstance(ident, (str, int)):
|
|
raise ErreurHub("identifiant absent")
|
|
ident = str(ident)
|
|
if not ID_HUB_OK.match(ident) or ident == "systeme":
|
|
raise ErreurHub("identifiant invalide")
|
|
pseudo = d.get("pseudo")
|
|
pseudo = "".join(c for c in pseudo if c.isprintable()).strip()[:60] if isinstance(pseudo, str) else ""
|
|
return ident, pseudo or "Membre"
|
|
|
|
|
|
# --- adresse du client --------------------------------------------------------
|
|
def ip_client(directe, xff, relais=("127.0.0.1", "::1")):
|
|
"""Adresse réelle du visiteur. X-Forwarded-For n'est cru que si la requête vient d'un relais de confiance
|
|
(Caddy en local) ; on prend alors la dernière adresse, celle que le relais a vue."""
|
|
if directe in relais and xff:
|
|
derniere = xff.split(",")[-1].strip()
|
|
try:
|
|
return str(ipaddress.ip_address(derniere))
|
|
except ValueError:
|
|
return directe
|
|
return directe
|
|
|
|
|
|
def est_locale(ip):
|
|
try:
|
|
a = ipaddress.ip_address(ip)
|
|
except ValueError:
|
|
return False
|
|
if getattr(a, "ipv4_mapped", None):
|
|
a = a.ipv4_mapped
|
|
return any(a.version == n.version and a in n for n in LOCALES)
|