diff --git a/Makefile b/Makefile index bf45b61..7035680 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ BACKEND := apps/backend .DEFAULT_GOAL := help .PHONY: help install dev lint format typecheck test test-cov test-integration check \ - docker-build db-up db-down db-reset db-logs db-psql migrate bootstrap-admin + openapi docker-build db-up db-down db-reset db-logs db-psql migrate bootstrap-admin help: ## Liste les cibles disponibles @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-16s\033[0m %s\n", $$1, $$2}' @@ -34,6 +34,9 @@ test-integration: ## Exécute les tests exigeant une base joignable check: lint typecheck test ## Chaîne de vérification complète +openapi: ## Régénère apps/backend/openapi.json depuis les routes déclarées + cd $(BACKEND) && uv run python -m app.cli export-openapi + docker-build: ## Construit l'image du backend docker build -t enervision-backend:local $(BACKEND) diff --git a/apps/backend/app/cli.py b/apps/backend/app/cli.py index 74d7a50..37e94fd 100644 --- a/apps/backend/app/cli.py +++ b/apps/backend/app/cli.py @@ -7,18 +7,25 @@ import argparse import asyncio +import json import secrets import sys from getpass import getpass +from pathlib import Path +from typing import Any + +from pydantic import SecretStr from app.core.config import Settings, get_settings from app.core.hashing import build_hasher from app.core.roles import Role from app.db.session import get_session_factory +from app.main import create_app from app.repositories.user import UserRepository LONGUEUR_MOT_DE_PASSE_GENERE = 24 LONGUEUR_MINIMALE = 12 +CHEMIN_CONTRAT = Path(__file__).resolve().parent.parent / "openapi.json" async def create_admin( @@ -55,6 +62,35 @@ async def create_admin( ) +# Piège : le schéma ne doit dépendre ni du `.env` du poste ni des variables `APP_*`, sinon le +# fichier versionné changerait de machine en machine et le test de dérive deviendrait un oracle +# de configuration locale. Tout ce qui atteint le schéma est donc posé ici, `_env_file` compris. +def settings_du_contrat() -> Settings: + return Settings( + _env_file=None, + name="EnerVision API", + version="0.1.0", + env="local", + api_prefix="/api/v1", + secret_key=SecretStr("contrat-openapi-sans-effet-sur-le-schema"), + database_url="postgresql+asyncpg://openapi:contrat@localhost:5432/enervision", + ) + + +def schema_du_contrat() -> dict[str, Any]: + schema: dict[str, Any] = create_app(settings_du_contrat()).openapi() + return schema + + +def rend_le_contrat() -> str: + return json.dumps(schema_du_contrat(), indent=2, ensure_ascii=False) + "\n" + + +def export_openapi(destination: Path) -> str: + destination.write_text(rend_le_contrat(), encoding="utf-8") + return f"Contrat OpenAPI écrit dans {destination}" + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="python -m app.cli", description="Outils EnerVision") sous_commandes = parser.add_subparsers(dest="commande", required=True) @@ -67,6 +103,11 @@ def build_parser() -> argparse.ArgumentParser: admin.add_argument( "--force", action="store_true", help="Crée le compte même si un administrateur existe" ) + + contrat = sous_commandes.add_parser( + "export-openapi", help="Écrit le contrat OpenAPI sur disque" + ) + contrat.add_argument("--output", default=str(CHEMIN_CONTRAT)) return parser @@ -86,6 +127,11 @@ def read_password(*, generate: bool) -> str: def main(argv: list[str] | None = None) -> int: arguments = build_parser().parse_args(argv) + + if arguments.commande == "export-openapi": + print(export_openapi(Path(arguments.output))) + return 0 + mot_de_passe = read_password(generate=arguments.generate) succes, message = asyncio.run( diff --git a/apps/backend/openapi.json b/apps/backend/openapi.json new file mode 100644 index 0000000..8462c4d --- /dev/null +++ b/apps/backend/openapi.json @@ -0,0 +1,1150 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "EnerVision API", + "summary": "Collecte, analyse et restitution de séries temporelles énergétiques.", + "description": "\nToutes les routes sont préfixées par `/api/v1`.\n\n**Authentification.** Le jeton d'accès se présente dans l'en-tête `Authorization: Bearer ...`.\nLe jeton de rafraîchissement est un cookie `HttpOnly` que le code client ne voit jamais : il\nsuffit d'émettre les requêtes avec les identifiants de session. `POST /auth/refresh` rend un\nnouveau jeton d'accès et fait tourner le cookie.\n\n**Rôles.** `lecteur`, puis `operateur`, puis `admin`. Chaque rôle couvre les droits du\nprécédent.\n\n**Erreurs.** Le corps porte toujours une clé `detail`. Un `403` dont le `detail` vaut\n`password_change_required` n'est pas un refus de droits : il exige le changement du mot de passe\nprovisoire avant toute autre action.\n\nLe parcours de session complet est décrit dans\n`docs/architecture/31-contrat-authentification.md`.\n", + "version": "0.1.0" + }, + "paths": { + "/api/v1/health/live": { + "get": { + "tags": [ + "health" + ], + "summary": "Sonde de vivacité", + "operationId": "liveness_api_v1_health_live_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LivenessStatus" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + } + } + } + }, + "/api/v1/health/ready": { + "get": { + "tags": [ + "health" + ], + "summary": "Sonde de disponibilité", + "operationId": "readiness_api_v1_health_ready_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadinessStatus" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "503": { + "description": "Base injoignable, ou extension TimescaleDB absente de la base.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/api/v1/auth/login": { + "post": { + "tags": [ + "auth" + ], + "summary": "Ouvre une session", + "operationId": "login_api_v1_auth_login_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenResponse" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "422": { + "description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorResponse" + } + } + } + }, + "401": { + "description": "Identifiants faux, compte inconnu ou compte désactivé. Le message est le même dans les trois cas, et n'apprend donc rien sur l'existence du compte.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "429": { + "description": "Trop de tentatives sur cette fenêtre glissante.", + "headers": { + "Retry-After": { + "description": "Secondes à attendre avant une nouvelle tentative.", + "schema": { + "type": "integer" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/api/v1/auth/refresh": { + "post": { + "tags": [ + "auth" + ], + "summary": "Fait tourner la session", + "operationId": "refresh_api_v1_auth_refresh_post", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenResponse" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "401": { + "description": "Cookie absent, session expirée, révoquée, ou jeton déjà tourné. Dans ce dernier cas toute la famille de sessions est révoquée et le cookie est effacé avec la réponse.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "Cookie de rafraîchissement": [] + } + ] + } + }, + "/api/v1/auth/logout": { + "post": { + "tags": [ + "auth" + ], + "summary": "Ferme la session courante", + "operationId": "logout_api_v1_auth_logout_post", + "responses": { + "204": { + "description": "Successful Response" + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + } + }, + "security": [ + { + "Cookie de rafraîchissement": [] + } + ] + } + }, + "/api/v1/auth/logout-all": { + "post": { + "tags": [ + "auth" + ], + "summary": "Ferme toutes les sessions du compte", + "operationId": "logout_all_api_v1_auth_logout_all_post", + "responses": { + "204": { + "description": "Successful Response" + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "401": { + "description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "Jeton d'accès": [] + } + ] + } + }, + "/api/v1/auth/me": { + "get": { + "tags": [ + "auth" + ], + "summary": "Décrit le compte connecté", + "operationId": "me_api_v1_auth_me_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PrincipalResponse" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "401": { + "description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "Jeton d'accès": [] + } + ] + } + }, + "/api/v1/auth/password": { + "post": { + "tags": [ + "auth" + ], + "summary": "Change son propre mot de passe", + "operationId": "change_password_api_v1_auth_password_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PasswordChangeRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenResponse" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "422": { + "description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorResponse" + } + } + } + }, + "401": { + "description": "Jeton d'accès invalide, ou mot de passe courant faux.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "Jeton d'accès": [] + } + ] + } + }, + "/api/v1/users": { + "get": { + "tags": [ + "users" + ], + "summary": "Liste les comptes", + "operationId": "list_users_api_v1_users_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/UserResponse" + }, + "type": "array", + "title": "Response List Users Api V1 Users Get" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "401": { + "description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "403": { + "description": "Droits insuffisants, ou mot de passe provisoire à changer quand `detail` vaut `password_change_required`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "Jeton d'accès": [] + } + ] + }, + "post": { + "tags": [ + "users" + ], + "summary": "Crée un compte avec un mot de passe provisoire", + "operationId": "create_user_api_v1_users_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserCreateRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TemporaryPasswordResponse" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "401": { + "description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "403": { + "description": "Droits insuffisants, ou mot de passe provisoire à changer quand `detail` vaut `password_change_required`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "422": { + "description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorResponse" + } + } + } + }, + "409": { + "description": "Adresse déjà portée par un autre compte.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "Jeton d'accès": [] + } + ] + } + }, + "/api/v1/users/{user_id}": { + "patch": { + "tags": [ + "users" + ], + "summary": "Change le rôle ou l'activation", + "operationId": "update_user_api_v1_users__user_id__patch", + "security": [ + { + "Jeton d'accès": [] + } + ], + "parameters": [ + { + "name": "user_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid", + "title": "User Id" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserUpdateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserResponse" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "401": { + "description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "403": { + "description": "Droits insuffisants, ou mot de passe provisoire à changer quand `detail` vaut `password_change_required`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "422": { + "description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorResponse" + } + } + } + }, + "404": { + "description": "Aucun compte ne porte cet identifiant.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "400": { + "description": "Corps vide, aucune modification demandée.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "409": { + "description": "L'opération laisserait la plateforme sans administrateur actif, qu'il s'agisse de rétrograder le dernier ou de le désactiver.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/api/v1/users/{user_id}/password-reset": { + "post": { + "tags": [ + "users" + ], + "summary": "Réinitialise le mot de passe et ferme les sessions", + "operationId": "reset_password_api_v1_users__user_id__password_reset_post", + "security": [ + { + "Jeton d'accès": [] + } + ], + "parameters": [ + { + "name": "user_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid", + "title": "User Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TemporaryPasswordResponse" + } + } + } + }, + "500": { + "description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorResponse" + } + } + } + }, + "401": { + "description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "403": { + "description": "Droits insuffisants, ou mot de passe provisoire à changer quand `detail` vaut `password_change_required`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "422": { + "description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorResponse" + } + } + } + }, + "404": { + "description": "Aucun compte ne porte cet identifiant.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "AccountKind": { + "type": "string", + "enum": [ + "human", + "service" + ], + "title": "AccountKind" + }, + "ErrorResponse": { + "properties": { + "detail": { + "type": "string", + "title": "Detail" + } + }, + "type": "object", + "required": [ + "detail" + ], + "title": "ErrorResponse" + }, + "FieldError": { + "properties": { + "champ": { + "type": "string", + "title": "Champ" + }, + "type": { + "type": "string", + "title": "Type" + } + }, + "type": "object", + "required": [ + "champ", + "type" + ], + "title": "FieldError" + }, + "InternalErrorResponse": { + "properties": { + "detail": { + "type": "string", + "title": "Detail" + }, + "correlation": { + "type": "string", + "title": "Correlation" + } + }, + "type": "object", + "required": [ + "detail", + "correlation" + ], + "title": "InternalErrorResponse" + }, + "LivenessStatus": { + "properties": { + "status": { + "type": "string", + "const": "ok", + "title": "Status" + }, + "service": { + "type": "string", + "title": "Service" + }, + "version": { + "type": "string", + "title": "Version" + }, + "environment": { + "type": "string", + "title": "Environment" + } + }, + "type": "object", + "required": [ + "status", + "service", + "version", + "environment" + ], + "title": "LivenessStatus" + }, + "LoginRequest": { + "properties": { + "email": { + "type": "string", + "format": "email", + "title": "Email" + }, + "password": { + "type": "string", + "maxLength": 128, + "minLength": 1, + "title": "Password" + } + }, + "type": "object", + "required": [ + "email", + "password" + ], + "title": "LoginRequest" + }, + "PasswordChangeRequest": { + "properties": { + "current_password": { + "type": "string", + "maxLength": 128, + "minLength": 1, + "title": "Current Password" + }, + "new_password": { + "type": "string", + "maxLength": 128, + "minLength": 12, + "title": "New Password" + } + }, + "type": "object", + "required": [ + "current_password", + "new_password" + ], + "title": "PasswordChangeRequest" + }, + "PrincipalResponse": { + "properties": { + "id": { + "type": "string", + "format": "uuid", + "title": "Id" + }, + "email": { + "type": "string", + "title": "Email" + }, + "role": { + "$ref": "#/components/schemas/Role" + }, + "kind": { + "$ref": "#/components/schemas/AccountKind" + }, + "must_change_password": { + "type": "boolean", + "title": "Must Change Password" + } + }, + "type": "object", + "required": [ + "id", + "email", + "role", + "kind", + "must_change_password" + ], + "title": "PrincipalResponse" + }, + "ReadinessStatus": { + "properties": { + "status": { + "type": "string", + "const": "ready", + "title": "Status" + }, + "database": { + "type": "string", + "const": "reachable", + "title": "Database" + }, + "timescaledb": { + "type": "string", + "const": "loaded", + "title": "Timescaledb" + } + }, + "type": "object", + "required": [ + "status", + "database", + "timescaledb" + ], + "title": "ReadinessStatus" + }, + "Role": { + "type": "string", + "enum": [ + "lecteur", + "operateur", + "admin" + ], + "title": "Role" + }, + "TemporaryPasswordResponse": { + "properties": { + "user": { + "$ref": "#/components/schemas/UserResponse" + }, + "temporary_password": { + "type": "string", + "title": "Temporary Password" + } + }, + "type": "object", + "required": [ + "user", + "temporary_password" + ], + "title": "TemporaryPasswordResponse" + }, + "TokenResponse": { + "properties": { + "access_token": { + "type": "string", + "title": "Access Token" + }, + "token_type": { + "type": "string", + "const": "bearer", + "title": "Token Type", + "default": "bearer" + }, + "expires_in": { + "type": "integer", + "title": "Expires In" + }, + "principal": { + "$ref": "#/components/schemas/PrincipalResponse" + } + }, + "type": "object", + "required": [ + "access_token", + "expires_in", + "principal" + ], + "title": "TokenResponse" + }, + "UserCreateRequest": { + "properties": { + "email": { + "type": "string", + "format": "email", + "title": "Email" + }, + "role": { + "$ref": "#/components/schemas/Role" + }, + "full_name": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ], + "title": "Full Name" + } + }, + "type": "object", + "required": [ + "email", + "role" + ], + "title": "UserCreateRequest" + }, + "UserResponse": { + "properties": { + "id": { + "type": "string", + "format": "uuid", + "title": "Id" + }, + "email": { + "type": "string", + "title": "Email" + }, + "role": { + "$ref": "#/components/schemas/Role" + }, + "kind": { + "$ref": "#/components/schemas/AccountKind" + }, + "is_active": { + "type": "boolean", + "title": "Is Active" + }, + "must_change_password": { + "type": "boolean", + "title": "Must Change Password" + }, + "full_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Full Name" + }, + "last_login_at": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ], + "title": "Last Login At" + }, + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + } + }, + "type": "object", + "required": [ + "id", + "email", + "role", + "kind", + "is_active", + "must_change_password", + "full_name", + "last_login_at", + "created_at" + ], + "title": "UserResponse" + }, + "UserUpdateRequest": { + "properties": { + "role": { + "anyOf": [ + { + "$ref": "#/components/schemas/Role" + }, + { + "type": "null" + } + ] + }, + "is_active": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Is Active" + } + }, + "type": "object", + "title": "UserUpdateRequest" + }, + "ValidationErrorResponse": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/FieldError" + }, + "type": "array", + "title": "Detail" + } + }, + "type": "object", + "required": [ + "detail" + ], + "title": "ValidationErrorResponse" + } + }, + "securitySchemes": { + "Cookie de rafraîchissement": { + "type": "apiKey", + "description": "Cookie `HttpOnly` posé par `/auth/login` et tourné par `/auth/refresh`. Il prend le préfixe `__Secure-` dès que l'API tourne derrière TLS, et n'est émis que vers `/api/v1/auth`.", + "in": "cookie", + "name": "ev_refresh" + }, + "Jeton d'accès": { + "type": "http", + "scheme": "bearer" + } + } + }, + "tags": [ + { + "name": "health", + "description": "Sondes d'infrastructure, publiques. `live` prouve que le processus répond, `ready` que la base répond et que l'extension TimescaleDB est chargée." + }, + { + "name": "auth", + "description": "Ouverture, rotation et fermeture de session, et changement de son propre mot de passe." + }, + { + "name": "users", + "description": "Administration des comptes. Réservé au rôle `admin`." + } + ] +} diff --git a/apps/backend/tests/api/test_openapi.py b/apps/backend/tests/api/test_openapi.py new file mode 100644 index 0000000..ca979d5 --- /dev/null +++ b/apps/backend/tests/api/test_openapi.py @@ -0,0 +1,91 @@ +# Pourquoi : `openapi.json` est versionné, donc une route qui change son contrat public le montre +# dans la diff d'une pull request. `test_the_committed_contract_matches_the_generated_one` est ce +# qui empêche le fichier de dériver du code sans que personne ne le voie. + +import json +from typing import Any + +import pytest + +from app import cli + +METHODES = {"get", "post", "patch", "put", "delete"} + +# `/auth/logout` lit le cookie mais ne le réclame pas : sans session elle répond 204, et un 401 +# documenté y serait faux. +SANS_REFUS = {("POST", "/api/v1/auth/logout")} + + +@pytest.fixture(scope="module") +def schema() -> dict[str, Any]: + return cli.schema_du_contrat() + + +def operations(schema: dict[str, Any]) -> list[tuple[str, str, dict[str, Any]]]: + return [ + (methode.upper(), chemin, operation) + for chemin, operations_du_chemin in schema["paths"].items() + for methode, operation in operations_du_chemin.items() + if methode in METHODES + ] + + +def test_the_committed_contract_matches_the_generated_one(schema: dict[str, Any]) -> None: + publie = json.loads(cli.CHEMIN_CONTRAT.read_text(encoding="utf-8")) + + assert publie == schema, "lancer `make openapi` et versionner le fichier obtenu" + + +def test_every_route_demanding_an_identity_says_how_it_refuses(schema: dict[str, Any]) -> None: + muettes = [ + (methode, chemin) + for methode, chemin, operation in operations(schema) + if operation.get("security") + and (methode, chemin) not in SANS_REFUS + and "401" not in operation["responses"] + ] + + assert muettes == [] + + +def test_every_administration_route_documents_the_role_refusal(schema: dict[str, Any]) -> None: + sans_403 = [ + (methode, chemin) + for methode, chemin, operation in operations(schema) + if "users" in operation.get("tags", []) and "403" not in operation["responses"] + ] + + assert sans_403 == [] + + +def test_the_validation_model_matches_what_the_handler_returns(schema: dict[str, Any]) -> None: + modeles = { + operation["responses"]["422"]["content"]["application/json"]["schema"]["$ref"] + for _, _, operation in operations(schema) + if "422" in operation["responses"] + } + + assert modeles == {"#/components/schemas/ValidationErrorResponse"} + assert "HTTPValidationError" not in schema["components"]["schemas"] + + +def test_the_rate_limit_documents_the_delay_header(schema: dict[str, Any]) -> None: + trop_de_tentatives = schema["paths"]["/api/v1/auth/login"]["post"]["responses"]["429"] + + assert "Retry-After" in trop_de_tentatives["headers"] + + +def test_the_refresh_cookie_appears_in_the_security_schemes(schema: dict[str, Any]) -> None: + schemes = schema["components"]["securitySchemes"] + + assert schemes["Cookie de rafraîchissement"]["in"] == "cookie" + assert schemes["Cookie de rafraîchissement"]["name"] == "ev_refresh" + + +def test_each_tag_used_by_a_route_is_described(schema: dict[str, Any]) -> None: + decrits = {tag["name"] for tag in schema["tags"]} + + for methode, chemin, operation in operations(schema): + poses = operation.get("tags", []) + assert len(poses) == len(set(poses)), f"tag en double sur {methode} {chemin}" + assert set(poses) <= decrits, f"tag non décrit sur {methode} {chemin}" diff --git a/apps/backend/tests/test_cli.py b/apps/backend/tests/test_cli.py index d8465b5..40b8317 100644 --- a/apps/backend/tests/test_cli.py +++ b/apps/backend/tests/test_cli.py @@ -1,3 +1,6 @@ +import json +from pathlib import Path + import pytest from app import cli @@ -55,3 +58,52 @@ def test_read_password_refuses_two_different_entries(monkeypatch: pytest.MonkeyP with pytest.raises(SystemExit): cli.read_password(generate=False) + + +def test_build_parser_reads_the_export_openapi_arguments() -> None: + arguments = cli.build_parser().parse_args( + ["export-openapi", "--output", "ailleurs/contrat.json"] + ) + + assert arguments.commande == "export-openapi" + assert arguments.output == "ailleurs/contrat.json" + + +def test_build_parser_defaults_the_export_to_the_versioned_contract() -> None: + arguments = cli.build_parser().parse_args(["export-openapi"]) + + assert arguments.output == str(cli.CHEMIN_CONTRAT) + + +def test_settings_of_the_contract_ignore_the_local_environment( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("APP_API_PREFIX", "/api/v9") + monkeypatch.setenv("APP_NAME", "API du poste de Johan") + + settings = cli.settings_du_contrat() + + assert settings.api_prefix == "/api/v1" + assert settings.name == "EnerVision API" + + +def test_export_openapi_writes_a_readable_schema_where_asked(tmp_path: Path) -> None: + destination = tmp_path / "contrat.json" + + cli.export_openapi(destination) + + assert json.loads(destination.read_text(encoding="utf-8"))["openapi"].startswith("3.") + + +# Piège : `main()` réclamait un mot de passe avant de lire la commande. Sans le branchement, +# l'export resterait bloqué sur `getpass` et aucune CI ne pourrait le rejouer. +def test_main_exports_the_contract_without_asking_for_a_password( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + destination = tmp_path / "contrat.json" + + code = cli.main(["export-openapi", "--output", str(destination)]) + + assert code == 0 + assert destination.exists() + assert str(destination) in capsys.readouterr().out