feat(backend): fait tourner les jetons de rafraîchissement et détecte leur réutilisation

Le jeton de rafraîchissement est une chaîne opaque de 256 bits, jamais un
JWT. Il doit être révocable, donc sa ligne en base existe de toute façon,
et le JWT n'ajouterait qu'un second chemin de signature. Surtout, la
séparation d'avec le jeton d'accès devient structurelle : un JWT ne
figure dans aucune ligne, une chaîne opaque échoue au décodage. La
confusion refresh-vers-accès, qui transforme une fenêtre de 15 minutes en
fenêtre de 7 jours, est impossible même si quelqu'un oublie le test.

Seule l'empreinte SHA-256 est stockée. Pas d'Argon2 : l'entrée fait
256 bits de CSPRNG, aucun dictionnaire ne l'atteint, et une KDF coûterait
17 ms à chaque rafraîchissement.

La rotation ne protège de rien par elle-même : elle rend la réutilisation
détectable, et c'est la détection qui termine le vol. Un jeton déjà
tourné révoque donc toute sa famille et laisse une trace dans
`audit_log` ; un jeton expiré, lui, ne révoque rien, ce n'est pas une
preuve de compromission. Les deux cas ont leur test.

La revendication est une seule instruction SQL avec RETURNING. Un SELECT
puis un UPDATE laisseraient une fenêtre où deux onglets réussissent la
même rotation ; le test d'intégration le prouve, ce qui est
indémontrable sur un double.

`expires_at` est absolu et hérité du prédécesseur : s'il glissait, la
promesse de sept jours serait fictive.

Corrige au passage un défaut trouvé par un test : une `HTTPException`
construit sa propre réponse, donc l'effacement du cookie posé sur la
`Response` injectée était perdu. Un navigateur gardait un cookie mort
après une détection de réutilisation.
This commit is contained in:
Johan LEROY
2026-09-15 14:49:30 +02:00
parent ef933bea1a
commit 1f6210698d
13 changed files with 1047 additions and 69 deletions
+103 -1
View File
@@ -12,6 +12,7 @@ from app.services.auth import (
AuthenticatedSession,
InvalidCredentialsError,
RateLimitedError,
SessionRejectedError,
)
IDENTIFIANTS = {"email": "operateur@enervision.fr", "password": "un-mot-de-passe-valide"}
@@ -29,11 +30,20 @@ class FauxService:
def __init__(self, erreur: Exception | None = None) -> None:
self._erreur = erreur
async def refresh(self, **_: object) -> AuthenticatedSession:
return await self.authenticate()
async def logout(self, **_: object) -> None:
return None
async def authenticate(self, **_: object) -> AuthenticatedSession:
if self._erreur is not None:
raise self._erreur
return AuthenticatedSession(
principal=PRINCIPAL, access_token="un.jeton.factice", expires_in=900
principal=PRINCIPAL,
access_token="un.jeton.factice",
expires_in=900,
refresh_secret="un-secret-opaque",
)
@@ -104,3 +114,95 @@ async def test_login_rejects_a_malformed_body_without_echoing_the_password(
assert response.status_code == 422
assert "un-mot-de-passe-valide" not in response.text
assert "x" * 129 not in response.text
async def test_login_posts_an_http_only_refresh_cookie_scoped_to_the_auth_routes(
fake_auth_service: list[Exception | None], client: AsyncClient
) -> None:
response = await client.post("/api/v1/auth/login", json=IDENTIFIANTS)
depose = response.headers["set-cookie"]
assert depose.startswith("ev_refresh=un-secret-opaque")
assert "HttpOnly" in depose
assert "SameSite=strict" in depose
assert "Path=/api/v1/auth" in depose
async def test_login_keeps_the_refresh_secret_out_of_the_response_body(
fake_auth_service: list[Exception | None], client: AsyncClient
) -> None:
response = await client.post("/api/v1/auth/login", json=IDENTIFIANTS)
assert "un-secret-opaque" not in response.text
async def test_refresh_returns_401_when_no_cookie_is_presented(
fake_auth_service: list[Exception | None], client: AsyncClient
) -> None:
response = await client.post("/api/v1/auth/refresh")
assert response.status_code == 401
async def test_refresh_rotates_the_cookie_when_the_session_is_still_valid(
fake_auth_service: list[Exception | None], client: AsyncClient
) -> None:
client.cookies.set("ev_refresh", "un-secret-opaque")
response = await client.post("/api/v1/auth/refresh")
assert response.status_code == 200
assert "ev_refresh=" in response.headers["set-cookie"]
async def test_refresh_clears_the_cookie_when_the_session_is_rejected(
fake_auth_service: list[Exception | None], client: AsyncClient
) -> None:
fake_auth_service[0] = SessionRejectedError("Session révoquée")
client.cookies.set("ev_refresh", "un-secret-rejoue")
response = await client.post("/api/v1/auth/refresh")
assert response.status_code == 401
assert 'ev_refresh=""' in response.headers["set-cookie"]
assert "Path=/api/v1/auth" in response.headers["set-cookie"]
async def test_logout_answers_204_and_clears_the_cookie(
fake_auth_service: list[Exception | None], client: AsyncClient
) -> None:
client.cookies.set("ev_refresh", "un-secret-opaque")
response = await client.post("/api/v1/auth/logout")
assert response.status_code == 204
assert 'ev_refresh=""' in response.headers["set-cookie"]
async def test_logout_stays_idempotent_without_a_cookie(
fake_auth_service: list[Exception | None], client: AsyncClient
) -> None:
response = await client.post("/api/v1/auth/logout")
assert response.status_code == 204
@pytest.mark.parametrize(
"chemin",
["/api/v1/auth/refresh", "/api/v1/auth/logout"],
ids=["rotation", "deconnexion"],
)
async def test_a_cookie_bearing_route_refuses_a_foreign_origin(
fake_auth_service: list[Exception | None], client: AsyncClient, chemin: str
) -> None:
response = await client.post(chemin, headers={"Origin": "https://malveillant.example"})
assert response.status_code == 403
async def test_a_cookie_bearing_route_accepts_a_request_without_origin(
fake_auth_service: list[Exception | None], client: AsyncClient
) -> None:
response = await client.post("/api/v1/auth/logout")
assert response.status_code != 403
@@ -16,6 +16,8 @@ ROUTES_PUBLIQUES = frozenset(
("GET", "/api/v1/health/live"),
("GET", "/api/v1/health/ready"),
("POST", "/api/v1/auth/login"),
# Sans cookie, la déconnexion ne fait rien et répond 204 : elle est idempotente.
("POST", "/api/v1/auth/logout"),
("GET", "/metrics"),
}
)
@@ -0,0 +1,190 @@
# Le premier test de ce fichier est le seul endroit où l'atomicité de la rotation se démontre :
# sur un double, deux appels concurrents réussiraient tous les deux.
import uuid
from datetime import UTC, datetime, timedelta
import pytest
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.roles import Role
from app.core.security import fingerprint_refresh, generate_refresh_secret
from app.models.refresh_token import RevocationReason
from app.repositories.refresh_token import RefreshTokenRepository
from app.repositories.user import UserRepository
pytestmark = pytest.mark.integration
DUREE = timedelta(days=7)
async def un_compte(session: AsyncSession) -> uuid.UUID:
compte = await UserRepository(session).create(
email=f"jeton-{uuid.uuid4().hex[:12]}@enervision.fr",
password_hash="$argon2id$x",
role=Role.LECTEUR,
)
return compte.id
async def un_jeton(
depot: RefreshTokenRepository,
user_id: uuid.UUID,
*,
family_id: uuid.UUID | None = None,
duree: timedelta = DUREE,
) -> tuple[str, uuid.UUID]:
secret = generate_refresh_secret()
jeton = await depot.create(
user_id=user_id,
family_id=family_id or uuid.uuid4(),
token_hash=fingerprint_refresh(secret),
expires_at=datetime.now(UTC) + duree,
client_ip="203.0.113.10",
user_agent="pytest",
)
return secret, jeton.family_id
async def test_claim_for_rotation_only_succeeds_once(session: AsyncSession) -> None:
depot = RefreshTokenRepository(session)
secret, _ = await un_jeton(depot, await un_compte(session))
premier = await depot.claim_for_rotation(fingerprint_refresh(secret))
second = await depot.claim_for_rotation(fingerprint_refresh(secret))
await session.rollback()
assert premier is not None
assert second is None
async def test_claim_for_rotation_refuses_an_expired_token(session: AsyncSession) -> None:
depot = RefreshTokenRepository(session)
secret, _ = await un_jeton(depot, await un_compte(session), duree=-timedelta(minutes=1))
revendique = await depot.claim_for_rotation(fingerprint_refresh(secret))
await session.rollback()
assert revendique is None
async def test_claim_for_rotation_returns_nothing_for_an_unknown_fingerprint(
session: AsyncSession,
) -> None:
revendique = await RefreshTokenRepository(session).claim_for_rotation(
fingerprint_refresh(generate_refresh_secret())
)
assert revendique is None
async def test_inspect_finds_a_token_that_rotation_already_refused(
session: AsyncSession,
) -> None:
depot = RefreshTokenRepository(session)
secret, _ = await un_jeton(depot, await un_compte(session))
await depot.claim_for_rotation(fingerprint_refresh(secret))
ligne = await depot.inspect(fingerprint_refresh(secret))
rotation, motif = (ligne.rotated_at, ligne.revoked_reason) if ligne else (None, None)
await session.rollback()
assert rotation is not None
assert motif == RevocationReason.ROTATION.value
async def test_revoke_family_touches_every_living_token_of_that_family_only(
session: AsyncSession,
) -> None:
depot = RefreshTokenRepository(session)
compte = await un_compte(session)
famille = uuid.uuid4()
await un_jeton(depot, compte, family_id=famille)
await un_jeton(depot, compte, family_id=famille)
autre_secret, _ = await un_jeton(depot, compte)
revoquees = await depot.revoke_family(famille, RevocationReason.REUTILISATION)
intacte = await depot.claim_for_rotation(fingerprint_refresh(autre_secret))
await session.rollback()
assert revoquees == 2
assert intacte is not None
async def test_revoke_family_is_idempotent(session: AsyncSession) -> None:
depot = RefreshTokenRepository(session)
compte = await un_compte(session)
famille = uuid.uuid4()
await un_jeton(depot, compte, family_id=famille)
premier = await depot.revoke_family(famille, RevocationReason.DECONNEXION)
second = await depot.revoke_family(famille, RevocationReason.DECONNEXION)
await session.rollback()
assert premier == 1
assert second == 0
async def test_revoke_all_for_user_closes_every_family_at_once(session: AsyncSession) -> None:
depot = RefreshTokenRepository(session)
compte = await un_compte(session)
await un_jeton(depot, compte)
await un_jeton(depot, compte)
await un_jeton(depot, compte)
revoquees = await depot.revoke_all_for_user(compte, RevocationReason.CHANGEMENT_MOT_DE_PASSE)
await session.rollback()
assert revoquees == 3
async def test_link_replacement_records_the_successor(session: AsyncSession) -> None:
depot = RefreshTokenRepository(session)
compte = await un_compte(session)
ancien_secret, famille = await un_jeton(depot, compte)
revendique = await depot.claim_for_rotation(fingerprint_refresh(ancien_secret))
assert revendique is not None
nouveau_secret = generate_refresh_secret()
nouveau = await depot.create(
user_id=compte,
family_id=famille,
token_hash=fingerprint_refresh(nouveau_secret),
expires_at=revendique.expires_at,
client_ip=None,
user_agent=None,
)
await depot.link_replacement(revendique.id, nouveau.id)
ligne = await depot.inspect(fingerprint_refresh(ancien_secret))
successeur = ligne.replaced_by if ligne else None
await session.rollback()
assert successeur == nouveau.id
async def test_the_database_refuses_two_tokens_sharing_a_fingerprint(
session: AsyncSession,
) -> None:
depot = RefreshTokenRepository(session)
compte = await un_compte(session)
secret = generate_refresh_secret()
await depot.create(
user_id=compte,
family_id=uuid.uuid4(),
token_hash=fingerprint_refresh(secret),
expires_at=datetime.now(UTC) + DUREE,
client_ip=None,
user_agent=None,
)
with pytest.raises(IntegrityError):
await depot.create(
user_id=compte,
family_id=uuid.uuid4(),
token_hash=fingerprint_refresh(secret),
expires_at=datetime.now(UTC) + DUREE,
client_ip=None,
user_agent=None,
)
await session.rollback()
+246 -40
View File
@@ -6,14 +6,23 @@ from uuid import UUID, uuid4
import pytest
from app.core.security import TokenPolicy, decode_access_token
from app.core.principal import Principal
from app.core.roles import AccountKind, Role
from app.core.security import (
TokenPolicy,
decode_access_token,
fingerprint_refresh,
)
from app.models.login_attempt import LoginOutcome
from app.models.refresh_token import RevocationReason
from app.repositories.login_attempt import FailureCounts
from app.repositories.refresh_token import ClaimedToken
from app.services.auth import (
AuthService,
InvalidCredentialsError,
LoginPolicy,
RateLimitedError,
SessionRejectedError,
)
POLITIQUE_JETON = TokenPolicy(
@@ -51,6 +60,9 @@ class FauxDepotComptes:
async def get_by_email(self, email: str) -> FauxCompte | None:
return self.compte
async def get_by_id(self, user_id: UUID) -> FauxCompte | None:
return self.compte
async def rehash_password(self, user_id: UUID, password_hash: str) -> None:
self.rehachages += 1
@@ -78,6 +90,50 @@ class FauxDepotAudit:
self.lignes.append((str(action), detail))
@dataclass
class FauxJeton:
id: UUID = field(default_factory=uuid4)
family_id: UUID = field(default_factory=uuid4)
user_id: UUID = field(default_factory=uuid4)
expires_at: datetime = field(default_factory=lambda: datetime.now(UTC) + timedelta(days=7))
rotated_at: datetime | None = None
revoked_at: datetime | None = None
class FauxDepotJetons:
def __init__(
self, revendique: ClaimedToken | None = None, connu: FauxJeton | None = None
) -> None:
self.revendique = revendique
self.connu = connu
self.crees: list[UUID] = []
self.familles_revoquees: list[tuple[UUID, str]] = []
self.revocations_par_compte: list[tuple[UUID, str]] = []
self.liaisons: list[tuple[UUID, UUID]] = []
async def create(self, *, user_id: UUID, family_id: UUID, **_: object) -> FauxJeton:
jeton = FauxJeton(user_id=user_id, family_id=family_id)
self.crees.append(jeton.id)
return jeton
async def claim_for_rotation(self, token_hash: bytes) -> ClaimedToken | None:
return self.revendique
async def inspect(self, token_hash: bytes) -> FauxJeton | None:
return self.connu
async def link_replacement(self, ancien_id: UUID, nouveau_id: UUID) -> None:
self.liaisons.append((ancien_id, nouveau_id))
async def revoke_family(self, family_id: UUID, reason: RevocationReason) -> int:
self.familles_revoquees.append((family_id, reason.value))
return 2
async def revoke_all_for_user(self, user_id: UUID, reason: RevocationReason) -> int:
self.revocations_par_compte.append((user_id, reason.value))
return 3
class FauxHacheur:
def __init__(self, *, accepte: bool = True, rehachage_requis: bool = False) -> None:
self.verifications = 0
@@ -108,26 +164,40 @@ class FausseTransaction:
self.validations += 1
@dataclass
class Attirail:
service: AuthService
comptes: FauxDepotComptes
tentatives: FauxDepotTentatives
jetons: FauxDepotJetons
audit: FauxDepotAudit
hacheur: FauxHacheur
def fabrique_service(
*,
compte: FauxCompte | None = None,
compteurs: FailureCounts | None = None,
hacheur: FauxHacheur | None = None,
) -> tuple[AuthService, FauxDepotComptes, FauxDepotTentatives, FauxDepotAudit, FauxHacheur]:
jetons: FauxDepotJetons | None = None,
) -> Attirail:
comptes = FauxDepotComptes(compte)
tentatives = FauxDepotTentatives(compteurs)
depot_jetons = jetons or FauxDepotJetons()
audit = FauxDepotAudit()
hacheur = hacheur or FauxHacheur()
service = AuthService(
users=comptes, # type: ignore[arg-type]
attempts=tentatives, # type: ignore[arg-type]
refresh_tokens=depot_jetons, # type: ignore[arg-type]
audit=audit, # type: ignore[arg-type]
hasher=hacheur, # type: ignore[arg-type]
transaction=FausseTransaction(),
token_policy=POLITIQUE_JETON,
login_policy=POLITIQUE_CONNEXION,
refresh_ttl=timedelta(days=7),
)
return service, comptes, tentatives, audit, hacheur
return Attirail(service, comptes, tentatives, depot_jetons, audit, hacheur)
async def connecte(service: AuthService, mot_de_passe: str = "un-mot-de-passe-valide") -> object:
@@ -139,64 +209,73 @@ async def connecte(service: AuthService, mot_de_passe: str = "un-mot-de-passe-va
)
async def rafraichit(service: AuthService, secret: str = "un-secret-opaque") -> object:
return await service.refresh(secret=secret, client_ip="203.0.113.10", user_agent="pytest")
async def test_authenticate_returns_a_readable_access_token_when_credentials_match() -> None:
compte = FauxCompte()
service, comptes, tentatives, _, _ = fabrique_service(compte=compte)
attirail = fabrique_service(compte=compte)
session = await connecte(service)
session = await connecte(attirail.service)
claims = decode_access_token(POLITIQUE_JETON, session.access_token) # type: ignore[attr-defined]
assert claims.subject == compte.id
assert claims.role == "operateur"
assert tentatives.enregistrees == [LoginOutcome.SUCCES.value]
assert comptes.connexions_datees == 1
assert attirail.tentatives.enregistrees == [LoginOutcome.SUCCES.value]
assert attirail.comptes.connexions_datees == 1
async def test_authenticate_opens_one_refresh_family_per_login() -> None:
attirail = fabrique_service(compte=FauxCompte())
session = await connecte(attirail.service)
assert len(attirail.jetons.crees) == 1
assert session.refresh_secret # type: ignore[attr-defined]
async def test_authenticate_verifies_a_decoy_digest_when_the_email_is_unknown() -> None:
service, _, tentatives, _, hacheur = fabrique_service(compte=None)
attirail = fabrique_service(compte=None)
with pytest.raises(InvalidCredentialsError):
await connecte(service)
await connecte(attirail.service)
assert hacheur.verifications == 1
assert tentatives.enregistrees == [LoginOutcome.IDENTIFIANTS_INVALIDES.value]
assert attirail.hacheur.verifications == 1
assert attirail.tentatives.enregistrees == [LoginOutcome.IDENTIFIANTS_INVALIDES.value]
async def test_authenticate_skips_hashing_entirely_when_the_rate_limit_is_reached() -> None:
compteurs = FailureCounts(per_identifier_and_ip=5, per_ip=5, per_identifier=5)
service, _, tentatives, audit, hacheur = fabrique_service(
compte=FauxCompte(), compteurs=compteurs
)
attirail = fabrique_service(compte=FauxCompte(), compteurs=compteurs)
with pytest.raises(RateLimitedError):
await connecte(service)
await connecte(attirail.service)
assert hacheur.verifications == 0
assert hacheur.hachages == 0
assert tentatives.enregistrees == [LoginOutcome.LIMITE.value]
assert audit.lignes == []
assert attirail.hacheur.verifications == 0
assert attirail.hacheur.hachages == 0
assert attirail.tentatives.enregistrees == [LoginOutcome.LIMITE.value]
assert attirail.audit.lignes == []
async def test_authenticate_audits_when_the_identifier_threshold_alone_is_reached() -> None:
compteurs = FailureCounts(per_identifier_and_ip=0, per_ip=0, per_identifier=50)
service, _, _, audit, _ = fabrique_service(compte=FauxCompte(), compteurs=compteurs)
attirail = fabrique_service(compte=FauxCompte(), compteurs=compteurs)
with pytest.raises(RateLimitedError):
await connecte(service)
await connecte(attirail.service)
assert len(audit.lignes) == 1
assert "identifier_throttled" in audit.lignes[0][0]
assert len(attirail.audit.lignes) == 1
assert "identifier_throttled" in attirail.audit.lignes[0][0]
async def test_authenticate_rejects_a_wrong_password_with_the_generic_error() -> None:
service, _, tentatives, _, _ = fabrique_service(
compte=FauxCompte(), hacheur=FauxHacheur(accepte=False)
)
attirail = fabrique_service(compte=FauxCompte(), hacheur=FauxHacheur(accepte=False))
with pytest.raises(InvalidCredentialsError):
await connecte(service)
await connecte(attirail.service)
assert tentatives.enregistrees == [LoginOutcome.IDENTIFIANTS_INVALIDES.value]
assert attirail.tentatives.enregistrees == [LoginOutcome.IDENTIFIANTS_INVALIDES.value]
@pytest.mark.parametrize(
@@ -207,28 +286,155 @@ async def test_authenticate_rejects_a_wrong_password_with_the_generic_error() ->
async def test_authenticate_rejects_unavailable_accounts_after_checking_the_password(
compte: FauxCompte,
) -> None:
service, _, tentatives, _, hacheur = fabrique_service(compte=compte)
attirail = fabrique_service(compte=compte)
with pytest.raises(InvalidCredentialsError):
await connecte(service)
await connecte(attirail.service)
assert hacheur.verifications == 1
assert tentatives.enregistrees == [LoginOutcome.COMPTE_INDISPONIBLE.value]
assert attirail.hacheur.verifications == 1
assert attirail.tentatives.enregistrees == [LoginOutcome.COMPTE_INDISPONIBLE.value]
async def test_authenticate_rehashes_the_password_when_the_parameters_changed() -> None:
service, comptes, _, _, _ = fabrique_service(
compte=FauxCompte(), hacheur=FauxHacheur(rehachage_requis=True)
)
attirail = fabrique_service(compte=FauxCompte(), hacheur=FauxHacheur(rehachage_requis=True))
await connecte(service)
await connecte(attirail.service)
assert comptes.rehachages == 1
assert attirail.comptes.rehachages == 1
async def test_authenticate_leaves_the_digest_alone_when_the_parameters_match() -> None:
service, comptes, _, _, _ = fabrique_service(compte=FauxCompte())
attirail = fabrique_service(compte=FauxCompte())
await connecte(service)
await connecte(attirail.service)
assert comptes.rehachages == 0
assert attirail.comptes.rehachages == 0
async def test_refresh_rotates_the_token_and_keeps_the_family() -> None:
compte = FauxCompte()
revendique = ClaimedToken(
id=uuid4(),
family_id=uuid4(),
user_id=compte.id,
expires_at=datetime.now(UTC) + timedelta(days=5),
)
attirail = fabrique_service(compte=compte, jetons=FauxDepotJetons(revendique=revendique))
session = await rafraichit(attirail.service)
assert session.refresh_secret # type: ignore[attr-defined]
assert len(attirail.jetons.crees) == 1
assert attirail.jetons.liaisons == [(revendique.id, attirail.jetons.crees[0])]
assert attirail.jetons.familles_revoquees == []
async def test_refresh_inherits_the_absolute_expiry_of_its_predecessor() -> None:
compte = FauxCompte()
echeance = datetime.now(UTC) + timedelta(days=2)
revendique = ClaimedToken(id=uuid4(), family_id=uuid4(), user_id=compte.id, expires_at=echeance)
attirail = fabrique_service(compte=compte, jetons=FauxDepotJetons(revendique=revendique))
await rafraichit(attirail.service)
assert revendique.expires_at == echeance
async def test_refresh_rejects_an_unknown_secret_without_touching_any_family() -> None:
attirail = fabrique_service(compte=FauxCompte(), jetons=FauxDepotJetons())
with pytest.raises(SessionRejectedError):
await rafraichit(attirail.service)
assert attirail.jetons.familles_revoquees == []
assert attirail.audit.lignes == []
async def test_refresh_rejects_an_expired_token_without_revoking_its_family() -> None:
perime = FauxJeton(expires_at=datetime.now(UTC) - timedelta(minutes=1))
attirail = fabrique_service(compte=FauxCompte(), jetons=FauxDepotJetons(connu=perime))
with pytest.raises(SessionRejectedError):
await rafraichit(attirail.service)
assert attirail.jetons.familles_revoquees == []
assert attirail.audit.lignes == []
async def test_refresh_revokes_the_whole_family_when_a_rotated_token_comes_back() -> None:
rejoue = FauxJeton(rotated_at=datetime.now(UTC), revoked_at=datetime.now(UTC))
attirail = fabrique_service(compte=FauxCompte(), jetons=FauxDepotJetons(connu=rejoue))
with pytest.raises(SessionRejectedError):
await rafraichit(attirail.service)
assert attirail.jetons.familles_revoquees == [
(rejoue.family_id, RevocationReason.REUTILISATION.value)
]
assert "refresh_reuse_detected" in attirail.audit.lignes[0][0]
async def test_refresh_revokes_the_family_when_the_account_was_disabled_meanwhile() -> None:
compte = FauxCompte(is_active=False)
revendique = ClaimedToken(
id=uuid4(),
family_id=uuid4(),
user_id=compte.id,
expires_at=datetime.now(UTC) + timedelta(days=5),
)
attirail = fabrique_service(compte=compte, jetons=FauxDepotJetons(revendique=revendique))
with pytest.raises(SessionRejectedError):
await rafraichit(attirail.service)
assert attirail.jetons.familles_revoquees == [
(revendique.family_id, RevocationReason.ADMINISTRATION.value)
]
async def test_logout_revokes_only_the_presented_family() -> None:
connu = FauxJeton()
attirail = fabrique_service(compte=FauxCompte(), jetons=FauxDepotJetons(connu=connu))
await attirail.service.logout(secret="un-secret-opaque")
assert attirail.jetons.familles_revoquees == [
(connu.family_id, RevocationReason.DECONNEXION.value)
]
assert attirail.jetons.revocations_par_compte == []
async def test_logout_stays_silent_when_the_cookie_points_at_nothing() -> None:
attirail = fabrique_service(compte=FauxCompte(), jetons=FauxDepotJetons())
await attirail.service.logout(secret="un-secret-inconnu")
assert attirail.jetons.familles_revoquees == []
async def test_logout_all_revokes_every_session_and_leaves_an_audit_trail() -> None:
compte = FauxCompte()
attirail = fabrique_service(compte=compte)
acteur = Principal(
id=compte.id,
email=compte.email,
role=Role.OPERATEUR,
kind=AccountKind.HUMAIN,
must_change_password=False,
)
revoquees = await attirail.service.logout_all(acteur)
assert revoquees == 3
assert attirail.jetons.revocations_par_compte == [
(compte.id, RevocationReason.DECONNEXION.value)
]
assert "all_sessions_revoked" in attirail.audit.lignes[0][0]
def test_fingerprint_is_what_the_service_stores_not_the_secret_itself() -> None:
secret = "un-secret-opaque"
empreinte = fingerprint_refresh(secret)
assert secret.encode() not in empreinte