Compare commits
98
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
692ec436a5 | ||
|
|
a3d32a6fb1 | ||
|
|
63ee79cf32 | ||
|
|
76fa90dfcb | ||
|
|
e13096c62a | ||
|
|
3fb907d6f6 | ||
|
|
c7490d01b3 | ||
|
|
523b623dc1 | ||
|
|
61e031fc16 | ||
|
|
781644b28e | ||
|
|
1654e4dd81 | ||
|
|
e50921c907 | ||
|
|
56f7211f0b | ||
|
|
c83fd889b8 | ||
|
|
cf22b2ae55 | ||
|
|
12c5cf87ad | ||
|
|
7b076171d2 | ||
|
|
ad149db0cb | ||
|
|
50dcb4de32 | ||
|
|
d25e544db6 | ||
|
|
22ff1d93f4 | ||
|
|
d632af57b8 | ||
|
|
fabd073aaf | ||
|
|
31a9cb109f | ||
|
|
50dddf952b | ||
|
|
fc6600aeaf | ||
|
|
1325a75e9a | ||
|
|
16a0cc4d3b | ||
|
|
5e7cb005ac | ||
|
|
3347fa5bdb | ||
|
|
da481d7485 | ||
|
|
344f82fcdd | ||
|
|
44468e85d7 | ||
|
|
580da72eff | ||
|
|
e85c83972a | ||
|
|
da97e6aa8b | ||
|
|
0259f66b62 | ||
|
|
7b9406965e | ||
|
|
881f503f1a | ||
|
|
918bd971da | ||
|
|
6c1f86b4ce | ||
|
|
3eb5a0e8dc | ||
|
|
c733ccfc62 | ||
|
|
cdef30736a | ||
|
|
e3e0e843d0 | ||
|
|
c3b7c818aa | ||
|
|
935782bbca | ||
|
|
c04ce9a9ae | ||
|
|
128133761f | ||
|
|
b032f084fc | ||
|
|
6c4684a4f6 | ||
|
|
bfbd9ee2cc | ||
|
|
3b7383697e | ||
|
|
c60081a5ac | ||
|
|
cb2ac8c2c2 | ||
|
|
e8f22bf427 | ||
|
|
7fdd6513ca | ||
|
|
cf9c707592 | ||
|
|
1f6210698d | ||
|
|
ef933bea1a | ||
|
|
a8f59e6e76 | ||
|
|
53af7a76d8 | ||
|
|
008cf581a7 | ||
|
|
e4d1b43a44 | ||
|
|
dcdee8fc6e | ||
|
|
e47235bd7f | ||
|
|
4c72fbbb69 | ||
|
|
57c16c77f7 | ||
|
|
1103c6e1a6 | ||
|
|
b910e747ec | ||
|
|
4692f1d604 | ||
|
|
239efc8ee6 | ||
|
|
0ca429ff3d | ||
|
|
a2727f9b5a | ||
|
|
6aeaca8ed1 | ||
|
|
08ad3bbe34 | ||
|
|
50dfa72c9d | ||
|
|
d58647cad4 | ||
|
|
d14b3afc8e | ||
|
|
c95f4d3851 | ||
|
|
8f237f6d6f | ||
|
|
3db4419bdf | ||
|
|
3ca1866e93 | ||
|
|
98ec01c847 | ||
|
|
552391c9bd | ||
|
|
34890b2b04 | ||
|
|
06a8ae42d2 | ||
|
|
1fbacf2fa3 | ||
|
|
0be2418e02 | ||
|
|
6bc2c3793f | ||
|
|
49f46978b0 | ||
|
|
f4d05a8ca9 | ||
|
|
20e7374d90 | ||
|
|
351e928309 | ||
|
|
91f4f007d3 | ||
|
|
4de5fb0935 | ||
|
|
6161a432c3 | ||
|
|
26704831e4 |
@@ -0,0 +1,22 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
[*.py]
|
||||||
|
indent_size = 4
|
||||||
|
max_line_length = 100
|
||||||
|
|
||||||
|
[*.{tf,tfvars}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
[Makefile]
|
||||||
|
indent_style = tab
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
trim_trailing_whitespace = false
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Variables lues par docker-compose.yml à la racine.
|
||||||
|
# Le backend lancé hors conteneur (`make dev`) lit apps/backend/.env, pas ce fichier.
|
||||||
|
|
||||||
|
POSTGRES_USER=enervision
|
||||||
|
POSTGRES_PASSWORD=change_me
|
||||||
|
POSTGRES_DB=enervision
|
||||||
|
# 5432 est souvent déjà pris par une autre base du poste.
|
||||||
|
POSTGRES_PORT=5433
|
||||||
|
# `basic` renvoie des statistiques d'usage à Timescale.
|
||||||
|
TIMESCALEDB_TELEMETRY=off
|
||||||
|
|
||||||
|
APP_ENV=local
|
||||||
|
APP_DEBUG=false
|
||||||
|
APP_LOG_LEVEL=INFO
|
||||||
|
# L'API refuse de démarrer tant que cette valeur reste un exemple ou fait moins de
|
||||||
|
# 32 caractères. Générer la vôtre : python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||||
|
APP_SECRET_KEY=change_me
|
||||||
|
APP_CORS_ORIGINS=http://localhost:4200
|
||||||
|
BACKEND_PORT=8000
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
name: Backend
|
||||||
|
|
||||||
|
# Piège : la version de Python vient de apps/backend/.python-version, et elle doit rester
|
||||||
|
# en 3.14. Le code utilise le PEP 758, qu'un interpréteur 3.13 refuse de compiler.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "apps/backend/**"
|
||||||
|
- ".github/workflows/backend.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "apps/backend/**"
|
||||||
|
- ".github/workflows/backend.yml"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: backend-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verification:
|
||||||
|
name: Lint, typage et tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
|
||||||
|
- name: Installe l'interpréteur déclaré par .python-version
|
||||||
|
run: uv python install
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
|
||||||
|
- name: Vérifie le formatage
|
||||||
|
run: uv run ruff format --check .
|
||||||
|
|
||||||
|
- name: Analyse statique
|
||||||
|
run: uv run ruff check --output-format=github .
|
||||||
|
|
||||||
|
- name: Typage
|
||||||
|
run: uv run mypy app
|
||||||
|
|
||||||
|
# Le marqueur `integration` est exclu par défaut, donc aucune base n'est nécessaire ici.
|
||||||
|
- name: Tests et couverture
|
||||||
|
run: uv run pytest --cov-fail-under=85
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
coverage.xml
|
||||||
|
htmlcov/
|
||||||
|
test-results/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.egg-info/
|
||||||
|
|
||||||
|
# Node / Angular
|
||||||
|
node_modules/
|
||||||
|
.angular/
|
||||||
|
apps/frontend/dist/
|
||||||
|
apps/frontend/.angular/
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# Terraform
|
||||||
|
.terraform/
|
||||||
|
# .terraform.lock.hcl est versionne (pas ignore) pour figer les versions de provider entre contributeurs/CI
|
||||||
|
*.tfstate
|
||||||
|
*.tfstate.*
|
||||||
|
*.tfplan
|
||||||
|
crash.log
|
||||||
|
override.tf
|
||||||
|
override.tf.json
|
||||||
|
*_override.tf
|
||||||
|
*_override.tf.json
|
||||||
|
*.tfvars
|
||||||
|
!*.tfvars.example
|
||||||
|
kubeconfig
|
||||||
|
|
||||||
|
# Airflow
|
||||||
|
etl/airflow/logs/
|
||||||
|
airflow.db
|
||||||
|
airflow-webserver.pid
|
||||||
|
standalone_admin_password.txt
|
||||||
|
|
||||||
|
# Environnement et secrets
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
secrets/
|
||||||
|
|
||||||
|
# Donnees locales
|
||||||
|
data/
|
||||||
|
*.sqlite3
|
||||||
|
monitoring/grafana/data/
|
||||||
|
monitoring/prometheus/data/
|
||||||
|
|
||||||
|
# IDE et OS
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
BACKEND := apps/backend
|
||||||
|
FRONTEND := apps/frontend
|
||||||
|
|
||||||
|
.DEFAULT_GOAL := help
|
||||||
|
.PHONY: help install install-backend install-frontend dev dev-backend dev-frontend \
|
||||||
|
lint format typecheck test test-cov test-integration check \
|
||||||
|
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}'
|
||||||
|
|
||||||
|
install: install-backend install-frontend ## Installe les dépendances backend et frontend
|
||||||
|
|
||||||
|
install-backend: ## Installe les dépendances du backend
|
||||||
|
cd $(BACKEND) && uv sync --all-groups
|
||||||
|
|
||||||
|
install-frontend: ## Installe les dépendances du frontend
|
||||||
|
cd $(FRONTEND) && npm ci
|
||||||
|
|
||||||
|
dev: ## Lance toute la stack (backend + frontend) en rechargement à chaud
|
||||||
|
@trap 'kill 0' EXIT INT TERM; \
|
||||||
|
$(MAKE) --no-print-directory dev-backend & \
|
||||||
|
$(MAKE) --no-print-directory dev-frontend & \
|
||||||
|
wait
|
||||||
|
|
||||||
|
dev-backend: ## Lance l'API seule en rechargement à chaud
|
||||||
|
@echo "backend -> http://localhost:8000 (docs sur /docs)"
|
||||||
|
cd $(BACKEND) && uv run uvicorn app.main:create_app --factory --reload --host 0.0.0.0 --port 8000
|
||||||
|
|
||||||
|
dev-frontend: ## Lance le frontend seul en rechargement à chaud
|
||||||
|
@echo "frontend -> http://localhost:4200"
|
||||||
|
cd $(FRONTEND) && npm start
|
||||||
|
|
||||||
|
lint: ## Analyse statique du backend
|
||||||
|
cd $(BACKEND) && uv run ruff check .
|
||||||
|
|
||||||
|
format: ## Formate et corrige le backend
|
||||||
|
cd $(BACKEND) && uv run ruff format . && uv run ruff check --fix .
|
||||||
|
|
||||||
|
typecheck: ## Vérifie le typage du backend
|
||||||
|
cd $(BACKEND) && uv run mypy app
|
||||||
|
|
||||||
|
test: ## Exécute les tests backend ne demandant pas de base
|
||||||
|
cd $(BACKEND) && uv run pytest --cov-fail-under=85
|
||||||
|
|
||||||
|
test-cov: ## Rapports de couverture HTML et XML, plus les résultats au format JUnit
|
||||||
|
cd $(BACKEND) && uv run pytest --cov-fail-under=85 --cov-report=html \
|
||||||
|
--cov-report=xml --junitxml=test-results/junit.xml
|
||||||
|
|
||||||
|
test-integration: ## Exécute les tests exigeant une base joignable
|
||||||
|
cd $(BACKEND) && uv run pytest -m integration
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
db-up: ## Démarre la base PostgreSQL TimescaleDB
|
||||||
|
docker compose up -d db
|
||||||
|
|
||||||
|
db-down: ## Arrête la base en conservant ses données
|
||||||
|
docker compose stop db
|
||||||
|
|
||||||
|
db-reset: ## Détruit la base et rejoue db/init
|
||||||
|
docker compose down -v && docker compose up -d db
|
||||||
|
|
||||||
|
db-logs: ## Suit les journaux de la base
|
||||||
|
docker compose logs -f db
|
||||||
|
|
||||||
|
db-psql: ## Ouvre une session psql sur la base applicative
|
||||||
|
docker compose exec db psql -U $${POSTGRES_USER:-enervision} -d $${POSTGRES_DB:-enervision}
|
||||||
|
|
||||||
|
migrate: ## Applique les migrations Alembic
|
||||||
|
cd $(BACKEND) && uv run alembic upgrade head
|
||||||
|
|
||||||
|
bootstrap-admin: ## Crée le premier administrateur, mot de passe saisi au clavier
|
||||||
|
cd $(BACKEND) && uv run python -m app.cli create-admin --email $${EMAIL:?EMAIL=... requis}
|
||||||
@@ -1 +1,104 @@
|
|||||||
# ProjetPiscine_EnerVision
|
# EnerVision
|
||||||
|
|
||||||
|
Monorepo de la plateforme EnerVision : collecte, stockage, analyse et restitution de
|
||||||
|
series temporelles energetiques, deployee sur une machine on-premise.
|
||||||
|
|
||||||
|
## Jalons
|
||||||
|
|
||||||
|
| Jalon | Intitulé |
|
||||||
|
|-------|----------------------------------------------------------|
|
||||||
|
| J1 | Valider la préparation de l'environnement et du repo |
|
||||||
|
| J2 | Valider le périmètre retenu et les choix technologiques |
|
||||||
|
| J3 | Valider l'architecture et la gestion de la sécurité |
|
||||||
|
| J4 | Valider la robustesse et assurer les livrables |
|
||||||
|
|
||||||
|
Ce que la documentation apporte à chacun : [docs/architecture/00-vue-ensemble.md](docs/architecture/00-vue-ensemble.md).
|
||||||
|
|
||||||
|
## Stack cible
|
||||||
|
|
||||||
|
| Domaine | Technologie | Emplacement | Etat |
|
||||||
|
|------------|-------------------------------------|---------------------|---------------|
|
||||||
|
| Backend | FastAPI, Python 3.14 | `apps/backend` | Initialise |
|
||||||
|
| Frontend | Angular 22, Node 24 LTS | `apps/frontend` | Tableau de bord |
|
||||||
|
| Base | PostgreSQL 17 + TimescaleDB | `db` | Initialise |
|
||||||
|
| ETL | Apache Airflow | `etl/airflow` | A initialiser |
|
||||||
|
| Infra | Terraform (k3s single-node) | `infra/terraform` | Initialise |
|
||||||
|
| CI/CD | GitHub Actions | `.github/workflows` | Backend en place |
|
||||||
|
| Monitoring | Prometheus, Grafana, Alertmanager | `monitoring` | A initialiser |
|
||||||
|
|
||||||
|
Le backend, la base et l'infrastructure (Terraform/k3s) sont initialises a ce stade. Le frontend
|
||||||
|
sert un tableau de bord sur `/dashboard`, dont les données proviennent de fixtures : les endpoints
|
||||||
|
correspondants restent à écrire côté API. Les autres dossiers portent l'arborescence et un README
|
||||||
|
de cadrage, leur contenu fait l'objet d'un ticket dedie.
|
||||||
|
|
||||||
|
L'etat detaille de chaque brique et les vues d'architecture sont dans
|
||||||
|
[docs/architecture](docs/architecture/README.md).
|
||||||
|
|
||||||
|
## Arborescence
|
||||||
|
|
||||||
|
```
|
||||||
|
.
|
||||||
|
├── apps/
|
||||||
|
│ ├── backend/ API FastAPI
|
||||||
|
│ └── frontend/ Application Angular
|
||||||
|
├── db/
|
||||||
|
│ ├── init/ Bootstrap PostgreSQL + TimescaleDB
|
||||||
|
│ ├── migrations/ Migrations SQL versionnees
|
||||||
|
│ └── seeds/ Jeux de donnees de reference
|
||||||
|
├── etl/airflow/
|
||||||
|
│ ├── dags/ DAGs d'ingestion et d'agregation
|
||||||
|
│ ├── plugins/ Operateurs et hooks maison
|
||||||
|
│ ├── include/ Requetes SQL et ressources des DAGs
|
||||||
|
│ └── tests/ Tests d'integrite des DAGs
|
||||||
|
├── infra/terraform/
|
||||||
|
│ ├── modules/ Modules reutilisables
|
||||||
|
│ └── environments/ Racines Terraform, une par environnement
|
||||||
|
├── monitoring/
|
||||||
|
│ ├── prometheus/ Collecte et regles d'alerte
|
||||||
|
│ ├── grafana/ Provisioning et dashboards
|
||||||
|
│ └── alertmanager/ Routage des alertes
|
||||||
|
├── docs/ ADR et vues d'architecture
|
||||||
|
└── scripts/ Outillage local
|
||||||
|
```
|
||||||
|
|
||||||
|
## Demarrage
|
||||||
|
|
||||||
|
Prerequis : uv, Docker, Node 24 LTS (npm fourni). Le poste doit disposer de Python 3.14, que
|
||||||
|
`uv` installe seul.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env # variables de docker-compose
|
||||||
|
cp apps/backend/.env.example apps/backend/.env # variables du backend hors conteneur
|
||||||
|
|
||||||
|
make db-up # PostgreSQL + TimescaleDB, publie sur le port 5433
|
||||||
|
make install # dependances du backend et du frontend
|
||||||
|
make migrate # applique les migrations Alembic
|
||||||
|
make dev # backend sur http://localhost:8000 (docs sur /docs), frontend sur http://localhost:4200
|
||||||
|
make check # lint + typage + tests
|
||||||
|
```
|
||||||
|
|
||||||
|
`make help` liste les cibles disponibles.
|
||||||
|
|
||||||
|
Deux fichiers d'environnement, deux usages : `.env` a la racine alimente `docker-compose.yml`,
|
||||||
|
`apps/backend/.env` alimente le backend lance sur le poste. Le port 5433 est publie plutot que
|
||||||
|
5432, souvent deja pris par une autre base.
|
||||||
|
|
||||||
|
La boucle de developpement est `make db-up` puis `make dev` : seule la base tourne en
|
||||||
|
conteneur, le backend et le frontend tournent tous les deux sur le poste, lances ensemble par
|
||||||
|
`make dev` (logs entrelaces dans le meme terminal, Ctrl+C arrete les deux). `make dev-backend`
|
||||||
|
et `make dev-frontend` restent disponibles pour lancer un seul des deux. Le service `backend`
|
||||||
|
du `docker-compose.yml` sert la stack complete et la recette, et n'embarque pas le source, donc
|
||||||
|
toute modification y demande un `docker compose up -d --build backend`.
|
||||||
|
|
||||||
|
Verifier que la base repond et que l'extension est chargee :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s localhost:8000/api/v1/health/ready
|
||||||
|
```
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Branches : `feat/`, `fix/`, `chore/`, `docs/`, `test/` suivi d'un libelle court.
|
||||||
|
- Commits : Conventional Commits, portee = dossier de premier niveau concerne.
|
||||||
|
- Toute decision structurante donne lieu a un ADR dans `docs/adr`.
|
||||||
|
- Toute PR qui change un composant met a jour sa vue dans `docs/architecture`, dans la meme PR.
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
coverage.xml
|
||||||
|
htmlcov/
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
tests/
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
|
README.md
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
APP_ENV=local
|
||||||
|
APP_DEBUG=false
|
||||||
|
APP_LOG_LEVEL=INFO
|
||||||
|
|
||||||
|
# L'API refuse de démarrer tant que cette valeur reste un exemple ou fait moins de
|
||||||
|
# 32 caractères. Générer la vôtre : python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||||
|
APP_SECRET_KEY=change_me
|
||||||
|
|
||||||
|
APP_CORS_ORIGINS=http://localhost:4200
|
||||||
|
DATABASE_URL=postgresql+asyncpg://enervision:change_me@localhost:5433/enervision
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
3.14
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
FROM python:3.14-slim AS builder
|
||||||
|
|
||||||
|
COPY --from=ghcr.io/astral-sh/uv:0.11.26 /uv /uvx /bin/
|
||||||
|
|
||||||
|
ENV UV_COMPILE_BYTECODE=1 \
|
||||||
|
UV_LINK_MODE=copy \
|
||||||
|
UV_PYTHON_DOWNLOADS=never
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
|
--mount=type=bind,source=uv.lock,target=uv.lock \
|
||||||
|
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
|
||||||
|
uv sync --locked --no-install-project --no-dev
|
||||||
|
|
||||||
|
COPY . /app
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
|
uv sync --locked --no-dev
|
||||||
|
|
||||||
|
|
||||||
|
FROM python:3.14-slim AS runtime
|
||||||
|
|
||||||
|
RUN groupadd --system --gid 1001 app \
|
||||||
|
&& useradd --system --uid 1001 --gid app --create-home app
|
||||||
|
|
||||||
|
ENV PATH="/app/.venv/bin:${PATH}" \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PYTHONDONTWRITEBYTECODE=1
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=builder --chown=app:app /app /app
|
||||||
|
|
||||||
|
USER app
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||||
|
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/v1/health/live')"
|
||||||
|
|
||||||
|
CMD ["uvicorn", "app.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
# Backend EnerVision
|
||||||
|
|
||||||
|
API FastAPI exposant les series temporelles energetiques.
|
||||||
|
|
||||||
|
| Element | Choix |
|
||||||
|
|-------------|--------------------------------------------|
|
||||||
|
| Python | 3.14 |
|
||||||
|
| Gestionnaire| uv (`uv.lock` fait foi) |
|
||||||
|
| Framework | FastAPI + Uvicorn |
|
||||||
|
| Persistance | SQLAlchemy 2 async + asyncpg + Alembic |
|
||||||
|
| Lint/format | ruff |
|
||||||
|
| Typage | mypy en mode strict |
|
||||||
|
| Tests | pytest + pytest-asyncio + httpx |
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
uv sync --all-groups
|
||||||
|
```
|
||||||
|
|
||||||
|
`APP_SECRET_KEY` et `DATABASE_URL` n'ont pas de valeur par defaut : l'application refuse
|
||||||
|
de demarrer sans elles.
|
||||||
|
|
||||||
|
`DATABASE_URL` pointe sur `localhost:5433`, le port publie par le service `db` du
|
||||||
|
`docker-compose.yml` racine. Demarrer la base depuis la racine avec `make db-up`.
|
||||||
|
|
||||||
|
## Commandes
|
||||||
|
|
||||||
|
Depuis la racine du monorepo, via le `Makefile` : `make install`, `make dev`, `make lint`,
|
||||||
|
`make format`, `make typecheck`, `make test`, `make check`, `make openapi`, `make docker-build`.
|
||||||
|
|
||||||
|
Directement depuis ce dossier :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run uvicorn app.main:create_app --factory --reload --port 8000
|
||||||
|
uv run ruff check . # lint
|
||||||
|
uv run ruff format . # format
|
||||||
|
uv run mypy app # typage strict
|
||||||
|
uv run pytest # tests + couverture
|
||||||
|
uv run pytest -m integration # tests exigeant une base joignable
|
||||||
|
uv run python -m app.cli export-openapi # régénère openapi.json
|
||||||
|
```
|
||||||
|
|
||||||
|
`openapi.json` est versionné : `tests/api/test_openapi.py` échoue si le fichier ne correspond
|
||||||
|
plus aux routes déclarées. Toute PR qui change une route le régénère dans le même commit.
|
||||||
|
|
||||||
|
Les conventions de tests, les gabarits et le detail des marqueurs sont dans
|
||||||
|
[`TESTING.md`](TESTING.md).
|
||||||
|
|
||||||
|
`pytest` ecarte par defaut les tests marques `integration`, pour que `make check` reste
|
||||||
|
jouable sans Docker. Ces tests visent la base `enervision_test`, creee par
|
||||||
|
`db/init/110-test-database.sql` au premier demarrage du conteneur.
|
||||||
|
|
||||||
|
L'application est exposee par une factory (`create_app`) et non par un objet module :
|
||||||
|
aucune configuration n'est lue a l'import, ce qui rend les tests et les migrations
|
||||||
|
independants de l'environnement.
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── api/
|
||||||
|
│ ├── deps.py Dépendances partagées : session, settings, principal, gardes de rôle
|
||||||
|
│ ├── errors.py Gestionnaires 422 et 500
|
||||||
|
│ ├── middleware.py En-têtes de sécurité
|
||||||
|
│ ├── security.py Garde du point /metrics
|
||||||
|
│ └── v1/
|
||||||
|
│ ├── router.py Agrégation des routes de la version 1
|
||||||
|
│ └── endpoints/ Un module par ressource exposée
|
||||||
|
├── core/
|
||||||
|
│ ├── config.py Settings Pydantic, source unique de configuration
|
||||||
|
│ ├── cookies.py Attributs du cookie de rafraîchissement
|
||||||
|
│ ├── hashing.py Argon2id, poussé dans un fil sous limiteur
|
||||||
|
│ ├── logging.py Journalisation console en local, JSON en production
|
||||||
|
│ ├── principal.py L'identité que voit le code métier
|
||||||
|
│ ├── roles.py Rôles ordonnés
|
||||||
|
│ └── security.py Encodage et décodage des jetons d'accès
|
||||||
|
├── db/
|
||||||
|
│ ├── base.py Base declarative SQLAlchemy
|
||||||
|
│ └── session.py Engine et sessions asynchrones
|
||||||
|
├── models/ Modeles SQLAlchemy
|
||||||
|
├── schemas/ Modeles Pydantic d'entree et de sortie
|
||||||
|
├── repositories/ Acces aux donnees, une classe par agregat
|
||||||
|
├── services/ Regles metier, orchestrent les repositories
|
||||||
|
├── cli.py Commandes hors HTTP, dont l'amorcage du premier admin
|
||||||
|
└── main.py Factory applicative
|
||||||
|
tests/ Miroir de app/
|
||||||
|
alembic/ Migrations du schema applicatif
|
||||||
|
```
|
||||||
|
|
||||||
|
Le sens de dependance est unique : `endpoints` vers `services` vers `repositories` vers
|
||||||
|
`models`. Un endpoint ne touche jamais une session directement.
|
||||||
|
|
||||||
|
## Routes
|
||||||
|
|
||||||
|
| Route | Rôle | Accès |
|
||||||
|
|---|---|---|
|
||||||
|
| `/api/v1/health/live` | Sonde de vivacité, aucune dépendance externe | public |
|
||||||
|
| `/api/v1/health/ready` | Sonde de disponibilité, vérifie la base et TimescaleDB | public |
|
||||||
|
| `/api/v1/auth/login` | Ouvre une session | public |
|
||||||
|
| `/api/v1/auth/refresh` | Fait tourner la session | cookie |
|
||||||
|
| `/api/v1/auth/logout` | Ferme la session courante | cookie, idempotente |
|
||||||
|
| `/api/v1/auth/logout-all` | Ferme toutes les sessions du compte | jeton |
|
||||||
|
| `/api/v1/auth/password` | Change son propre mot de passe | jeton |
|
||||||
|
| `/api/v1/auth/me` | Décrit le compte connecté | jeton |
|
||||||
|
| `/api/v1/users` | Liste et crée des comptes | `admin` |
|
||||||
|
| `/api/v1/users/{id}` | Change le rôle ou l'activation | `admin` |
|
||||||
|
| `/api/v1/users/{id}/password-reset` | Réinitialise et ferme les sessions | `admin` |
|
||||||
|
| `/api/v1/sites` | Liste les sites | `lecteur` |
|
||||||
|
| `/api/v1/sites/{site_id}` | Décrit un site | `lecteur` |
|
||||||
|
| `/api/v1/recommendations` | Liste les recommandations | `lecteur` |
|
||||||
|
| `/api/v1/recommendations/{recommendation_id}` | Décrit une recommandation | `lecteur` |
|
||||||
|
| `/metrics` | Métriques au format Prometheus | jeton si `APP_METRICS_TOKEN` |
|
||||||
|
| `/docs`, `/openapi.json` | Documentation, fermée en `staging` et `prod` | public sinon |
|
||||||
|
|
||||||
|
Le contrat détaillé pour le frontend est dans
|
||||||
|
[`docs/architecture/31-contrat-authentification.md`](../../docs/architecture/31-contrat-authentification.md).
|
||||||
|
|
||||||
|
## Premier administrateur
|
||||||
|
|
||||||
|
Aucun compte n'existe après les migrations. Il s'en crée un en ligne de commande :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make bootstrap-admin EMAIL=prenom.nom@enervision.fr # mot de passe saisi au clavier
|
||||||
|
# ou, depuis apps/backend :
|
||||||
|
uv run python -m app.cli create-admin --email prenom.nom@enervision.fr --generate
|
||||||
|
```
|
||||||
|
|
||||||
|
Le compte est créé avec `must_change_password`, donc la première connexion ne donne accès qu'à
|
||||||
|
`/auth/me` et `/auth/password` jusqu'au changement. Le mot de passe ne transite jamais par
|
||||||
|
`argv`, visible de tout `ps`, et aucune révision Alembic n'insère de compte : son empreinte
|
||||||
|
resterait dans Git pour toujours.
|
||||||
|
|
||||||
|
## Migrations
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run alembic revision --autogenerate -m "libelle"
|
||||||
|
uv run alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
L'URL de connexion vient de `DATABASE_URL`, pas de `alembic.ini`.
|
||||||
|
|
||||||
|
La premiere revision ne cree aucune table : elle refuse de s'appliquer si l'extension
|
||||||
|
TimescaleDB manque, ce qui arrive quand `db/init` n'a pas ete joue. Le DDL propre a
|
||||||
|
TimescaleDB qui ne depend pas du schema applicatif vit dans `db/`, pas ici.
|
||||||
|
|
||||||
|
## Image Docker
|
||||||
|
|
||||||
|
Build multi-stage, dependances resolues par uv depuis `uv.lock`, execution sous un
|
||||||
|
utilisateur non root, sonde de sante integree.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -t enervision-backend:local .
|
||||||
|
docker run --rm -p 8000:8000 --env-file .env enervision-backend:local
|
||||||
|
```
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
# Conventions de tests unitaires : Backend
|
||||||
|
|
||||||
|
## Outil
|
||||||
|
|
||||||
|
pytest, avec pytest-asyncio en mode `auto` : un `async def test_*` est collecte sans
|
||||||
|
decorateur. Les appels HTTP passent par httpx sur `ASGITransport`, qui parle a
|
||||||
|
l'application en memoire, sans serveur ni port ouvert.
|
||||||
|
|
||||||
|
## Ou ecrire les tests
|
||||||
|
|
||||||
|
`tests/` est le miroir de `app/` : un test de `app/services/consumption.py` va dans
|
||||||
|
`tests/services/test_consumption.py`. Les paquets `core`, `db`, `services` et
|
||||||
|
`repositories` existent deja, vides, pour cette raison.
|
||||||
|
|
||||||
|
## Nommage
|
||||||
|
|
||||||
|
- Fonctions en anglais : `test_<sujet>_<comportement>_when_<condition>`.
|
||||||
|
- `ids=` de `parametrize` en francais : `ids=["erreur_sqlalchemy", "erreur_reseau"]`.
|
||||||
|
- Pas de docstring : le nom porte l'intention.
|
||||||
|
|
||||||
|
## Structure attendue (Arrange / Act / Assert)
|
||||||
|
|
||||||
|
Une ligne vide separe les trois temps, sans commentaire pour les annoncer.
|
||||||
|
|
||||||
|
```python
|
||||||
|
async def test_readiness_returns_503_when_the_extension_is_missing(
|
||||||
|
fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=None)
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/health/ready")
|
||||||
|
|
||||||
|
assert response.status_code == 503
|
||||||
|
assert response.json()["detail"] == "Extension TimescaleDB absente"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Ce qui doit etre teste en priorite
|
||||||
|
|
||||||
|
Le sens de dependance du backend est `endpoints -> services -> repositories -> models`.
|
||||||
|
|
||||||
|
| Couche | Ce qu'on teste |
|
||||||
|
|---|---|
|
||||||
|
| `services/` | La logique metier, cas nominal et cas d'erreur. C'est la priorite. |
|
||||||
|
| `repositories/` | Chaque branche de decision, sous le marqueur `integration`. |
|
||||||
|
| `endpoints/` | Le code de statut et la forme de la reponse, pas la logique metier. |
|
||||||
|
| `schemas/` | Rien, sauf si le schema porte une validation ecrite a la main. |
|
||||||
|
|
||||||
|
## Doubles
|
||||||
|
|
||||||
|
On remplace une dependance FastAPI par `app.dependency_overrides`, jamais par
|
||||||
|
`unittest.mock`. `tests/factories.py` fournit le necessaire.
|
||||||
|
|
||||||
|
- `fake_session(result=...)` : la session repond `result`.
|
||||||
|
- `fake_session(failure=...)` : la session leve l'exception.
|
||||||
|
- `make_settings(**overrides)` : fabrique une `Settings`, dont les valeurs priment sur
|
||||||
|
l'environnement et sur `.env`. C'est le moyen de tester `create_app` en `prod`.
|
||||||
|
|
||||||
|
## Gabarit : un endpoint
|
||||||
|
|
||||||
|
```python
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
|
||||||
|
async def test_endpoint_returns_the_expected_payload(
|
||||||
|
fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=42)
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/...")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"valeur": 42}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Gabarit : un service avec repository factice
|
||||||
|
|
||||||
|
Un service ne connait que son repository : on lui en passe un faux, sans base ni session.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from app.services.consumption import ConsumptionService
|
||||||
|
|
||||||
|
|
||||||
|
class FakeRepository:
|
||||||
|
async def total_for(self, site_id: int) -> float:
|
||||||
|
return 12.5
|
||||||
|
|
||||||
|
|
||||||
|
async def test_service_converts_the_total_to_kilowatt_hours() -> None:
|
||||||
|
service = ConsumptionService(FakeRepository())
|
||||||
|
|
||||||
|
total = await service.total_kwh(site_id=1)
|
||||||
|
|
||||||
|
assert total == 12.5
|
||||||
|
```
|
||||||
|
|
||||||
|
## Gabarit : un repository sur la vraie base
|
||||||
|
|
||||||
|
Un repository parle du SQL : le tester sur un double ne prouve rien. Il porte donc le
|
||||||
|
marqueur `integration`, ecarte par defaut.
|
||||||
|
|
||||||
|
```python
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.site import Site
|
||||||
|
from app.repositories.site import SiteRepository
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_repository_reads_back_what_it_wrote(session: AsyncSession) -> None:
|
||||||
|
repository = SiteRepository(session)
|
||||||
|
|
||||||
|
await repository.add(Site(name="Toulouse"))
|
||||||
|
|
||||||
|
assert await repository.by_name("Toulouse") is not None
|
||||||
|
```
|
||||||
|
|
||||||
|
## Marqueurs
|
||||||
|
|
||||||
|
`integration` designe tout test exigeant une base joignable. `pytest` les ecarte par
|
||||||
|
defaut, ce qui garde `make check` jouable sans Docker. Tout autre marqueur doit etre
|
||||||
|
declare dans `pyproject.toml` : `--strict-markers` refuse les marqueurs inconnus.
|
||||||
|
|
||||||
|
## Couverture
|
||||||
|
|
||||||
|
Les branches sont mesurees, pas seulement les lignes. Le seuil de 85 % ne s'applique
|
||||||
|
qu'aux cibles qui jouent toute la suite, `make test` et `make test-cov` : un fichier
|
||||||
|
joue seul affiche sa couverture sans jamais echouer dessus. Le detail se lit dans
|
||||||
|
`htmlcov/index.html` apres `make test-cov`.
|
||||||
|
|
||||||
|
## Lancer les tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test # suite unitaire, sans base
|
||||||
|
make test-cov # idem, plus les rapports HTML, XML et JUnit
|
||||||
|
make db-up && make test-integration # tests exigeant une base, demande Docker
|
||||||
|
make check # lint + typage + suite unitaire
|
||||||
|
|
||||||
|
uv run pytest tests/api/test_health.py # un seul fichier
|
||||||
|
uv run pytest -k readiness # par motif de nom
|
||||||
|
```
|
||||||
|
|
||||||
|
## Trois fichiers à connaître avant de toucher à l'authentification
|
||||||
|
|
||||||
|
`tests/api/test_route_protection.py` interroge réellement chaque route sans identifiant et
|
||||||
|
échoue si l'une d'elles répond autre chose qu'un 401 ou un 403. Il n'inspecte pas l'arbre de
|
||||||
|
dépendances : celui-ci n'est accessible que par l'API privée de FastAPI, et surtout une route
|
||||||
|
peut porter la bonne dépendance tout en répondant quand même. **Rendre une route publique impose
|
||||||
|
donc de modifier la liste `ROUTES_PUBLIQUES` de ce fichier**, ce qui apparaît en clair dans la
|
||||||
|
diff d'une pull request.
|
||||||
|
|
||||||
|
`tests/services/test_auth.py` donne au faux hacheur un **compteur d'appels**. C'est ce qui rend
|
||||||
|
possibles les deux assertions qui prouvent la conception, et qu'aucune autre forme de test
|
||||||
|
n'atteint :
|
||||||
|
|
||||||
|
- adresse inconnue → le compteur vaut 1, donc le haché leurre a bien été vérifié et il n'y a pas
|
||||||
|
d'oracle temporel ;
|
||||||
|
- limite de débit atteinte → le compteur vaut 0, donc la limite est évaluée avant Argon2.
|
||||||
|
|
||||||
|
`tests/api/test_parcours_authentification.py` joue six parcours complets contre la vraie base,
|
||||||
|
sous le marqueur `integration`, sans serveur ni port ouvert. C'est là que se démontrent
|
||||||
|
l'atomicité de la rotation, la mort de la famille au rejeu d'un cookie déjà tourné, et la
|
||||||
|
révocation immédiate d'un compte désactivé.
|
||||||
|
|
||||||
|
## Deux pièges d'écriture de test
|
||||||
|
|
||||||
|
**Lire les attributs avant le `rollback`.** Un `session.rollback()` périme les attributs chargés,
|
||||||
|
et les relire déclenche une entrée-sortie hors du contexte greenlet, donc un `MissingGreenlet`.
|
||||||
|
On capture la valeur dans une variable locale avant d'annuler.
|
||||||
|
|
||||||
|
**`audit_log` ne se nettoie pas.** La table est en ajout seul, garanti par déclencheur : un test
|
||||||
|
ne peut pas effacer ce qu'il y écrit, et les lignes d'une exécution précédente sont encore là.
|
||||||
|
Chaque test filtre donc sur son propre `target_id` plutôt que de supposer une table vide.
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts.
|
||||||
|
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||||
|
# format, relative to the token %(here)s which refers to the location of this
|
||||||
|
# ini file
|
||||||
|
script_location = %(here)s/alembic
|
||||||
|
|
||||||
|
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||||
|
# Uncomment the line below if you want the files to be prepended with date and time
|
||||||
|
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||||
|
# for all available tokens
|
||||||
|
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||||
|
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||||
|
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory. for multiple paths, the path separator
|
||||||
|
# is defined by "path_separator" below.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the tzdata library which can be installed by adding
|
||||||
|
# `alembic[tz]` to the pip requirements.
|
||||||
|
# string value is passed to ZoneInfo()
|
||||||
|
# leave blank for localtime
|
||||||
|
# timezone =
|
||||||
|
|
||||||
|
# max length of characters to apply to the "slug" field
|
||||||
|
# truncate_slug_length = 40
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
# set to 'true' to allow .pyc and .pyo files without
|
||||||
|
# a source .py file to be detected as revisions in the
|
||||||
|
# versions/ directory
|
||||||
|
# sourceless = false
|
||||||
|
|
||||||
|
# version location specification; This defaults
|
||||||
|
# to <script_location>/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path.
|
||||||
|
# The path separator used here should be the separator specified by "path_separator"
|
||||||
|
# below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||||
|
|
||||||
|
# path_separator; This indicates what character is used to split lists of file
|
||||||
|
# paths, including version_locations and prepend_sys_path within configparser
|
||||||
|
# files such as alembic.ini.
|
||||||
|
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||||
|
# to provide os-dependent path splitting.
|
||||||
|
#
|
||||||
|
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||||
|
# take place if path_separator is not present in alembic.ini. If this
|
||||||
|
# option is omitted entirely, fallback logic is as follows:
|
||||||
|
#
|
||||||
|
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||||
|
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||||
|
# behavior of splitting on spaces and/or commas.
|
||||||
|
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||||
|
# behavior of splitting on spaces, commas, or colons.
|
||||||
|
#
|
||||||
|
# Valid values for path_separator are:
|
||||||
|
#
|
||||||
|
# path_separator = :
|
||||||
|
# path_separator = ;
|
||||||
|
# path_separator = space
|
||||||
|
# path_separator = newline
|
||||||
|
#
|
||||||
|
# Use os.pathsep. Default configuration used for new projects.
|
||||||
|
path_separator = os
|
||||||
|
|
||||||
|
|
||||||
|
# set to 'true' to search source files recursively
|
||||||
|
# in each "version_locations" directory
|
||||||
|
# new in Alembic version 1.10
|
||||||
|
# recursive_version_locations = false
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
# database URL. This is consumed by the user-maintained env.py script only.
|
||||||
|
# other means of configuring database URLs may be customized within the env.py
|
||||||
|
# file.
|
||||||
|
# L'URL est injectee par alembic/env.py depuis app.core.config.
|
||||||
|
sqlalchemy.url =
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = module
|
||||||
|
# ruff.module = ruff
|
||||||
|
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = exec
|
||||||
|
# ruff.executable = ruff
|
||||||
|
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration. This is also consumed by the user-maintained
|
||||||
|
# env.py script only.
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARNING
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARNING
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration with an async dbapi.
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import asyncio
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy import pool
|
||||||
|
from sqlalchemy.engine import Connection
|
||||||
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
||||||
|
|
||||||
|
import app.models # noqa: F401
|
||||||
|
from app.core.config import get_settings
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
config.set_main_option("sqlalchemy.url", get_settings().database_url.replace("%", "%%"))
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def do_run_migrations(connection: Connection) -> None:
|
||||||
|
context.configure(connection=connection, target_metadata=target_metadata)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
async def run_async_migrations() -> None:
|
||||||
|
"""In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
connectable = async_engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
async with connectable.connect() as connection:
|
||||||
|
await connection.run_sync(do_run_migrations)
|
||||||
|
|
||||||
|
await connectable.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Run migrations in 'online' mode."""
|
||||||
|
|
||||||
|
asyncio.run(run_async_migrations())
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
"""Upgrade schema."""
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
"""Downgrade schema."""
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
+119
@@ -0,0 +1,119 @@
|
|||||||
|
"""tentatives de connexion et journal d audit
|
||||||
|
|
||||||
|
Revision ID: 517053a3c044
|
||||||
|
Revises: b1a7c3d9e240
|
||||||
|
Create Date: 2026-09-15 14:31:07.966180
|
||||||
|
|
||||||
|
Deux tables aux vocations opposees. `login_attempt` est le compteur de la limitation
|
||||||
|
de debit : son volume est pilote par l'attaquant, donc elle se purge. `audit_log` est
|
||||||
|
en ajout seul, garanti par deux declencheurs.
|
||||||
|
|
||||||
|
Le declencheur TRUNCATE n'est pas redondant : TRUNCATE ne passe pas par les
|
||||||
|
declencheurs de ligne. Et RAISE EXCEPTION plutot qu'un RETURN NULL, qui annulerait
|
||||||
|
l'operation silencieusement.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "517053a3c044"
|
||||||
|
down_revision: str | Sequence[str] | None = "b1a7c3d9e240"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
FONCTION_AJOUT_SEUL = """
|
||||||
|
CREATE FUNCTION audit_log_append_only() RETURNS trigger AS $$
|
||||||
|
BEGIN
|
||||||
|
RAISE EXCEPTION 'audit_log est en ajout seul : % interdit', TG_OP;
|
||||||
|
END
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
"""
|
||||||
|
|
||||||
|
DECLENCHEUR_LIGNE = """
|
||||||
|
CREATE TRIGGER audit_log_no_update_delete
|
||||||
|
BEFORE UPDATE OR DELETE ON audit_log
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION audit_log_append_only();
|
||||||
|
"""
|
||||||
|
|
||||||
|
DECLENCHEUR_TRUNCATE = """
|
||||||
|
CREATE TRIGGER audit_log_no_truncate
|
||||||
|
BEFORE TRUNCATE ON audit_log
|
||||||
|
FOR EACH STATEMENT EXECUTE FUNCTION audit_log_append_only();
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"login_attempt",
|
||||||
|
sa.Column("id", sa.BigInteger(), sa.Identity(always=True), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"occurred_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("email_tried", sa.String(length=320), nullable=False),
|
||||||
|
sa.Column("client_ip", postgresql.INET(), nullable=True),
|
||||||
|
sa.Column("outcome", sa.Text(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.UUID(), nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"outcome in ('success', 'bad_credentials', 'throttled', 'inactive')",
|
||||||
|
name="ck_login_attempt_outcome",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name="pk_login_attempt"),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_login_attempt_email_date", "login_attempt", ["email_tried", "occurred_at"]
|
||||||
|
)
|
||||||
|
op.create_index("ix_login_attempt_ip_date", "login_attempt", ["client_ip", "occurred_at"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"audit_log",
|
||||||
|
sa.Column("id", sa.BigInteger(), sa.Identity(always=True), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"occurred_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("actor_id", sa.UUID(), nullable=True),
|
||||||
|
sa.Column("actor_email", sa.Text(), nullable=True),
|
||||||
|
sa.Column("actor_role", sa.Text(), nullable=True),
|
||||||
|
sa.Column("action", sa.Text(), nullable=False),
|
||||||
|
sa.Column("target_type", sa.Text(), nullable=True),
|
||||||
|
sa.Column("target_id", sa.Text(), nullable=True),
|
||||||
|
sa.Column("outcome", sa.Text(), nullable=False),
|
||||||
|
sa.Column("client_ip", postgresql.INET(), nullable=True),
|
||||||
|
sa.Column("user_agent", sa.Text(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"detail",
|
||||||
|
postgresql.JSONB(astext_type=sa.Text()),
|
||||||
|
server_default=sa.text("jsonb_build_object()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("outcome in ('success', 'failure')", name="ck_audit_log_outcome"),
|
||||||
|
sa.PrimaryKeyConstraint("id", name="pk_audit_log"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_audit_log_date", "audit_log", ["occurred_at"])
|
||||||
|
op.create_index("ix_audit_log_action_date", "audit_log", ["action", "occurred_at"])
|
||||||
|
|
||||||
|
op.execute(FONCTION_AJOUT_SEUL)
|
||||||
|
op.execute(DECLENCHEUR_LIGNE)
|
||||||
|
op.execute(DECLENCHEUR_TRUNCATE)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute("DROP TRIGGER IF EXISTS audit_log_no_truncate ON audit_log;")
|
||||||
|
op.execute("DROP TRIGGER IF EXISTS audit_log_no_update_delete ON audit_log;")
|
||||||
|
op.execute("DROP FUNCTION IF EXISTS audit_log_append_only();")
|
||||||
|
|
||||||
|
op.drop_index("ix_audit_log_action_date", table_name="audit_log")
|
||||||
|
op.drop_index("ix_audit_log_date", table_name="audit_log")
|
||||||
|
op.drop_table("audit_log")
|
||||||
|
|
||||||
|
op.drop_index("ix_login_attempt_ip_date", table_name="login_attempt")
|
||||||
|
op.drop_index("ix_login_attempt_email_date", table_name="login_attempt")
|
||||||
|
op.drop_table("login_attempt")
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""socle garde extension timescaledb
|
||||||
|
|
||||||
|
Revision ID: 5353c0e4f094
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-09-14 14:17:17.556764
|
||||||
|
|
||||||
|
Premiere revision du schema applicatif. Elle ne cree aucune table : elle etablit
|
||||||
|
alembic_version et refuse de s'appliquer sur une base ou l'extension TimescaleDB
|
||||||
|
manque, cas qui se produit quand db/init n'a pas ete joue.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "5353c0e4f094"
|
||||||
|
down_revision: str | Sequence[str] | None = None
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
GARDE_EXTENSION = """
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'timescaledb') THEN
|
||||||
|
RAISE EXCEPTION 'extension timescaledb absente, voir db/init et db/README.md';
|
||||||
|
END IF;
|
||||||
|
END
|
||||||
|
$$;
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.execute(GARDE_EXTENSION)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
"""jetons de rafraichissement
|
||||||
|
|
||||||
|
Revision ID: 821f71be74c0
|
||||||
|
Revises: 517053a3c044
|
||||||
|
Create Date: 2026-09-15 14:42:09.757949
|
||||||
|
|
||||||
|
Le jeton lui-meme n'est jamais stocke : seule son empreinte SHA-256 l'est, dans
|
||||||
|
`token_hash`. Un pg_dump qui fuiterait ne livrerait donc aucune session utilisable.
|
||||||
|
|
||||||
|
L'index partiel `ix_refresh_token_vivants` sert la revocation en cascade et la
|
||||||
|
recherche des sessions actives, qui ne regardent jamais les lignes deja tournees.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "821f71be74c0"
|
||||||
|
down_revision: str | Sequence[str] | None = "517053a3c044"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
MOTIFS = "'logout', 'rotation', 'reuse_detected', 'password_change', 'admin'"
|
||||||
|
JETONS_VIVANTS = "revoked_at is null and rotated_at is null"
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"refresh_token",
|
||||||
|
sa.Column(
|
||||||
|
"id", sa.UUID(), server_default=sa.text("gen_random_uuid()"), nullable=False
|
||||||
|
),
|
||||||
|
sa.Column("family_id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("token_hash", sa.LargeBinary(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"issued_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("rotated_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("revoked_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("revoked_reason", sa.Text(), nullable=True),
|
||||||
|
sa.Column("replaced_by", sa.UUID(), nullable=True),
|
||||||
|
sa.Column("client_ip", postgresql.INET(), nullable=True),
|
||||||
|
sa.Column("user_agent", sa.Text(), nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
f"revoked_reason is null or revoked_reason in ({MOTIFS})",
|
||||||
|
name="ck_refresh_token_revoked_reason",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"], ["app_user.id"], name="fk_refresh_token_user", ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name="pk_refresh_token"),
|
||||||
|
sa.UniqueConstraint("token_hash", name="uq_refresh_token_hash"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_refresh_token_family", "refresh_token", ["family_id"])
|
||||||
|
op.create_index("ix_refresh_token_user", "refresh_token", ["user_id"])
|
||||||
|
op.create_index(
|
||||||
|
"ix_refresh_token_vivants",
|
||||||
|
"refresh_token",
|
||||||
|
["user_id"],
|
||||||
|
postgresql_where=JETONS_VIVANTS,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(
|
||||||
|
"ix_refresh_token_vivants", table_name="refresh_token", postgresql_where=JETONS_VIVANTS
|
||||||
|
)
|
||||||
|
op.drop_index("ix_refresh_token_user", table_name="refresh_token")
|
||||||
|
op.drop_index("ix_refresh_token_family", table_name="refresh_token")
|
||||||
|
op.drop_table("refresh_token")
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""comptes applicatifs
|
||||||
|
|
||||||
|
Revision ID: b1a7c3d9e240
|
||||||
|
Revises: 5353c0e4f094
|
||||||
|
Create Date: 2026-09-15 14:40:00.000000
|
||||||
|
|
||||||
|
Cree `app_user`, la table des comptes humains et de service. Le nom evite `user`,
|
||||||
|
mot reserve de PostgreSQL. `gen_random_uuid()` est au coeur de PG17, aucune
|
||||||
|
extension n'est necessaire.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "b1a7c3d9e240"
|
||||||
|
down_revision: str | Sequence[str] | None = "5353c0e4f094"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"app_user",
|
||||||
|
sa.Column(
|
||||||
|
"id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
server_default=sa.text("gen_random_uuid()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("email", sa.String(length=320), nullable=False),
|
||||||
|
sa.Column("password_hash", sa.Text(), nullable=False),
|
||||||
|
sa.Column("role", sa.Text(), nullable=False),
|
||||||
|
sa.Column("kind", sa.Text(), server_default=sa.text("'human'"), nullable=False),
|
||||||
|
sa.Column("is_active", sa.Boolean(), server_default=sa.text("true"), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"must_change_password", sa.Boolean(), server_default=sa.text("false"), nullable=False
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"credentials_changed_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("last_login_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("full_name", sa.Text(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"updated_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("email = lower(email)", name="ck_app_user_email_minuscule"),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"role in ('lecteur', 'operateur', 'admin')", name="ck_app_user_role"
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("kind in ('human', 'service')", name="ck_app_user_kind"),
|
||||||
|
sa.PrimaryKeyConstraint("id", name="pk_app_user"),
|
||||||
|
sa.UniqueConstraint("email", name="uq_app_user_email"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("app_user")
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
"""Création des six tables Data et de l'hypertable reading.
|
||||||
|
|
||||||
|
Revision ID: e6d2026091501
|
||||||
|
Revises: 821f71be74c0
|
||||||
|
"""
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision = "e6d2026091501"
|
||||||
|
down_revision = "821f71be74c0"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table(
|
||||||
|
"dataset",
|
||||||
|
sa.Column("dataset_id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("dataset_name", sa.Text(), nullable=False),
|
||||||
|
sa.Column("archive_sha256", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("storage_uri", sa.Text(), nullable=False),
|
||||||
|
sa.Column("source_timezone", sa.Text(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"metadata", postgresql.JSONB(none_as_null=True, astext_type=sa.Text()), nullable=False
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("dataset_id > 0", name="ck_dataset_positive_id"),
|
||||||
|
sa.PrimaryKeyConstraint("dataset_id"),
|
||||||
|
sa.UniqueConstraint("archive_sha256", name="uq_dataset_archive_sha256"),
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"site",
|
||||||
|
sa.Column("site_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column("site_name", sa.Text(), nullable=False),
|
||||||
|
sa.Column("site_type", sa.Text(), nullable=False),
|
||||||
|
sa.Column("location", sa.Text(), nullable=True),
|
||||||
|
sa.Column("capacity_kw", sa.Double(), nullable=True),
|
||||||
|
sa.Column("status", sa.Text(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("site_id"),
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"prediction",
|
||||||
|
sa.Column("prediction_id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("site_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("target_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("target_metric", sa.Text(), nullable=False),
|
||||||
|
sa.Column("period_minutes", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("predicted_value", sa.Double(), nullable=True),
|
||||||
|
sa.Column("model_reference", sa.Text(), nullable=False),
|
||||||
|
sa.Column("status", sa.Text(), nullable=False),
|
||||||
|
sa.Column("failure_reason", sa.Text(), nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"(status = 'available' AND predicted_value IS NOT NULL AND failure_reason IS NULL) OR (status IN ('insufficient_data', 'error') AND predicted_value IS NULL AND failure_reason IS NOT NULL)",
|
||||||
|
name="ck_prediction_status",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"target_metric <> 'consumption_kwh' OR period_minutes IS NOT NULL",
|
||||||
|
name="ck_prediction_energy_period",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"target_metric IN ('consumption_kwh', 'consumption_kw')", name="ck_prediction_metric"
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"period_minutes IS NULL OR period_minutes > 0", name="ck_prediction_period"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["site_id"], ["site.site_id"], name="fk_prediction_site", ondelete="RESTRICT"
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("prediction_id"),
|
||||||
|
sa.UniqueConstraint("prediction_id", "site_id", name="uq_prediction_id_site"),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_prediction_site_target", "prediction", ["site_id", "target_at"], unique=False
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"reading",
|
||||||
|
sa.Column("reading_id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("site_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column("timestamp", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("source", sa.Text(), nullable=False),
|
||||||
|
sa.Column("dataset_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("consumption_kw", sa.Double(), nullable=True),
|
||||||
|
sa.Column("consumption_kwh", sa.Double(), nullable=True),
|
||||||
|
sa.Column("consumption_euros", sa.Numeric(precision=14, scale=2), nullable=True),
|
||||||
|
sa.Column("voltage_v", sa.Double(), nullable=True),
|
||||||
|
sa.Column("current_a", sa.Double(), nullable=True),
|
||||||
|
sa.Column("power_factor", sa.Double(), nullable=True),
|
||||||
|
sa.Column("temperature_celsius", sa.Double(), nullable=True),
|
||||||
|
sa.Column("humidity_percent", sa.Double(), nullable=True),
|
||||||
|
sa.Column("solar_irradiance_wm2", sa.Double(), nullable=True),
|
||||||
|
sa.Column("is_working_hours", sa.Boolean(), nullable=True),
|
||||||
|
sa.Column("data_quality", sa.Text(), nullable=True),
|
||||||
|
sa.Column("null_reasons", postgresql.ARRAY(sa.Text()), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"imputed_values", postgresql.JSONB(none_as_null=True, astext_type=sa.Text()), nullable=True
|
||||||
|
),
|
||||||
|
sa.Column("imputation_method", sa.Text(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"ingested_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"raw_data", postgresql.JSONB(none_as_null=True, astext_type=sa.Text()), nullable=False
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"(source = 'csv' AND dataset_id IS NOT NULL) OR (source IN ('api_current', 'api_history') AND dataset_id IS NULL)",
|
||||||
|
name="ck_reading_dataset_source",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"data_quality IS NULL OR data_quality IN ('good', 'partial', 'degraded', 'critical')",
|
||||||
|
name="ck_reading_quality",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"source IN ('csv', 'api_current', 'api_history')", name="ck_reading_source"
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"(imputed_values IS NULL AND imputation_method IS NULL) OR (imputed_values IS NOT NULL AND imputation_method IS NOT NULL)",
|
||||||
|
name="ck_reading_imputation",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["dataset_id"], ["dataset.dataset_id"], name="fk_reading_dataset", ondelete="RESTRICT"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["site_id"], ["site.site_id"], name="fk_reading_site", ondelete="RESTRICT"
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("reading_id", "timestamp"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_reading_dataset_id", "reading", ["dataset_id"], unique=False)
|
||||||
|
op.create_index(
|
||||||
|
"ix_reading_site_timestamp", "reading", ["site_id", "timestamp"], unique=False
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"uq_reading_source",
|
||||||
|
"reading",
|
||||||
|
["site_id", "timestamp", "source", sa.literal_column("coalesce(dataset_id, 0)")],
|
||||||
|
unique=True,
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
"SELECT create_hypertable('reading', by_range('timestamp'), create_default_indexes => FALSE)"
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"alert",
|
||||||
|
sa.Column("alert_id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("source_alert_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column("site_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column("source", sa.Text(), nullable=False),
|
||||||
|
sa.Column("timestamp", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("type", sa.Text(), nullable=False),
|
||||||
|
sa.Column("severity", sa.Text(), nullable=False),
|
||||||
|
sa.Column("message", sa.Text(), nullable=False),
|
||||||
|
sa.Column("value", sa.Double(), nullable=True),
|
||||||
|
sa.Column("threshold", sa.Double(), nullable=True),
|
||||||
|
sa.Column("metric", sa.Text(), nullable=True),
|
||||||
|
sa.Column("prediction_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"raw_data", postgresql.JSONB(none_as_null=True, astext_type=sa.Text()), nullable=False
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"severity IN ('low', 'medium', 'high', 'critical')", name="ck_alert_severity"
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("source IN ('api_mock', 'enervision')", name="ck_alert_source"),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"type IN ('spike', 'threshold', 'anomaly', 'outage', 'sensor')", name="ck_alert_type"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["prediction_id", "site_id"],
|
||||||
|
["prediction.prediction_id", "prediction.site_id"],
|
||||||
|
name="fk_alert_prediction_site",
|
||||||
|
ondelete="RESTRICT",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["site_id"], ["site.site_id"], name="fk_alert_site", ondelete="RESTRICT"
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("alert_id"),
|
||||||
|
sa.UniqueConstraint(
|
||||||
|
"source", "site_id", "source_alert_id", name="uq_alert_source_reference"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.create_index("ix_alert_site_timestamp", "alert", ["site_id", "timestamp"], unique=False)
|
||||||
|
op.create_table(
|
||||||
|
"recommendation",
|
||||||
|
sa.Column("recommendation_id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("alert_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("action", sa.Text(), nullable=False),
|
||||||
|
sa.Column("explanation", sa.Text(), nullable=False),
|
||||||
|
sa.Column("rule_reference", sa.Text(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["alert_id"], ["alert.alert_id"], name="fk_recommendation_alert", ondelete="RESTRICT"
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("recommendation_id"),
|
||||||
|
sa.UniqueConstraint("alert_id", "rule_reference", name="uq_recommendation_alert_rule"),
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("recommendation")
|
||||||
|
op.drop_table("alert")
|
||||||
|
op.drop_table("reading")
|
||||||
|
op.drop_table("prediction")
|
||||||
|
op.drop_table("site")
|
||||||
|
op.drop_table("dataset")
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
# Piège : `get_current_principal()` relit le compte en base à chaque requête au lieu de faire
|
||||||
|
# confiance aux claims. C'est le renoncement assumé à la propriété « sans état » : sur un seul
|
||||||
|
# service et une seule base, elle n'achetait rien, et la lecture par clé primaire coûte moins
|
||||||
|
# d'un pour cent du budget d'une requête. Ce qu'elle achète, c'est la révocation immédiate.
|
||||||
|
# Piège : le `Principal` est construit depuis la ligne, jamais depuis le claim `role`. Un claim
|
||||||
|
# périmé ne peut donc pas provoquer d'élévation de privilège.
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from datetime import timedelta
|
||||||
|
from functools import lru_cache
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException, Request, status
|
||||||
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.core.config import Settings, get_settings
|
||||||
|
from app.core.hashing import Argon2Hasher, build_hasher
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role, has_at_least
|
||||||
|
from app.core.security import TokenExpiredError, TokenInvalidError, TokenPolicy
|
||||||
|
from app.core.security import decode_access_token as decode_token
|
||||||
|
from app.db.session import get_session
|
||||||
|
from app.repositories.alert import AlertRepository
|
||||||
|
from app.repositories.audit_log import AuditLogRepository
|
||||||
|
from app.repositories.login_attempt import LoginAttemptRepository
|
||||||
|
from app.repositories.reading import ReadingRepository
|
||||||
|
from app.repositories.recommendation import RecommendationRepository
|
||||||
|
from app.repositories.refresh_token import RefreshTokenRepository
|
||||||
|
from app.repositories.site import SiteRepository
|
||||||
|
from app.repositories.user import UserRepository
|
||||||
|
from app.services.alert import AlertService
|
||||||
|
from app.services.auth import AuthService, LoginPolicy
|
||||||
|
from app.services.recommendation import RecommendationService
|
||||||
|
from app.services.site import SiteService
|
||||||
|
from app.services.stats import StatsService
|
||||||
|
from app.services.user import UserService
|
||||||
|
|
||||||
|
SessionDep = Annotated[AsyncSession, Depends(get_session)]
|
||||||
|
SettingsDep = Annotated[Settings, Depends(get_settings)]
|
||||||
|
|
||||||
|
CODE_CHANGEMENT_REQUIS = "password_change_required"
|
||||||
|
|
||||||
|
_porteur = HTTPBearer(auto_error=False, scheme_name="Jeton d'accès")
|
||||||
|
CredentialsDep = Annotated[HTTPAuthorizationCredentials | None, Depends(_porteur)]
|
||||||
|
|
||||||
|
|
||||||
|
def _non_authentifie(description: str) -> HTTPException:
|
||||||
|
return HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Authentification requise",
|
||||||
|
headers={"WWW-Authenticate": f'Bearer error="{description}"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_token_policy(settings: SettingsDep) -> TokenPolicy:
|
||||||
|
return TokenPolicy(
|
||||||
|
secret=settings.secret_key.get_secret_value(),
|
||||||
|
issuer=settings.jwt_issuer,
|
||||||
|
audience=settings.jwt_audience,
|
||||||
|
access_ttl=timedelta(seconds=settings.access_token_ttl_seconds),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Construire un `Argon2Hasher` calcule un haché leurre, donc 17 ms : il est mis en cache sur
|
||||||
|
# les paramètres plutôt que reconstruit à chaque requête.
|
||||||
|
@lru_cache
|
||||||
|
def _hasher_cache(
|
||||||
|
time_cost: int, memory_cost_kib: int, parallelism: int, max_concurrency: int
|
||||||
|
) -> Argon2Hasher:
|
||||||
|
return build_hasher(
|
||||||
|
time_cost=time_cost,
|
||||||
|
memory_cost_kib=memory_cost_kib,
|
||||||
|
parallelism=parallelism,
|
||||||
|
max_concurrency=max_concurrency,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_hasher(settings: SettingsDep) -> Argon2Hasher:
|
||||||
|
return _hasher_cache(
|
||||||
|
settings.argon2_time_cost,
|
||||||
|
settings.argon2_memory_cost_kib,
|
||||||
|
settings.argon2_parallelism,
|
||||||
|
settings.argon2_max_concurrency,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_client_ip(request: Request, settings: SettingsDep) -> str | None:
|
||||||
|
# Derrière un proxy, `request.client.host` vaut l'IP du proxy : le compteur par IP
|
||||||
|
# deviendrait global, donc un déni de service auto-infligé. Le dernier élément est le seul
|
||||||
|
# qu'un proxy de confiance ait écrit, les précédents sont fournis par le client.
|
||||||
|
if settings.trust_proxy_headers:
|
||||||
|
transmis = request.headers.get("x-forwarded-for")
|
||||||
|
if transmis:
|
||||||
|
return transmis.split(",")[-1].strip()
|
||||||
|
return request.client.host if request.client else None
|
||||||
|
|
||||||
|
|
||||||
|
def get_auth_service(
|
||||||
|
session: SessionDep,
|
||||||
|
settings: SettingsDep,
|
||||||
|
hasher: Annotated[Argon2Hasher, Depends(get_hasher)],
|
||||||
|
token_policy: Annotated[TokenPolicy, Depends(get_token_policy)],
|
||||||
|
) -> AuthService:
|
||||||
|
return AuthService(
|
||||||
|
users=UserRepository(session),
|
||||||
|
attempts=LoginAttemptRepository(session),
|
||||||
|
refresh_tokens=RefreshTokenRepository(session),
|
||||||
|
audit=AuditLogRepository(session),
|
||||||
|
hasher=hasher,
|
||||||
|
transaction=session,
|
||||||
|
token_policy=token_policy,
|
||||||
|
login_policy=LoginPolicy(
|
||||||
|
window_seconds=settings.login_window_seconds,
|
||||||
|
max_failures_per_identifier_and_ip=(settings.login_max_failures_per_identifier_and_ip),
|
||||||
|
max_failures_per_ip=settings.login_max_failures_per_ip,
|
||||||
|
max_failures_per_identifier=settings.login_max_failures_per_identifier,
|
||||||
|
),
|
||||||
|
refresh_ttl=timedelta(seconds=settings.refresh_token_ttl_seconds),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
AuthServiceDep = Annotated[AuthService, Depends(get_auth_service)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_service(
|
||||||
|
session: SessionDep,
|
||||||
|
hasher: Annotated[Argon2Hasher, Depends(get_hasher)],
|
||||||
|
) -> UserService:
|
||||||
|
return UserService(
|
||||||
|
users=UserRepository(session),
|
||||||
|
refresh_tokens=RefreshTokenRepository(session),
|
||||||
|
audit=AuditLogRepository(session),
|
||||||
|
hasher=hasher,
|
||||||
|
transaction=session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_site_service(session: SessionDep) -> SiteService:
|
||||||
|
return SiteService(sites=SiteRepository(session))
|
||||||
|
|
||||||
|
|
||||||
|
SiteServiceDep = Annotated[SiteService, Depends(get_site_service)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_alert_service(session: SessionDep) -> AlertService:
|
||||||
|
return AlertService(alerts=AlertRepository(session))
|
||||||
|
|
||||||
|
|
||||||
|
AlertServiceDep = Annotated[AlertService, Depends(get_alert_service)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_recommendation_service(session: SessionDep) -> RecommendationService:
|
||||||
|
return RecommendationService(recommendations=RecommendationRepository(session))
|
||||||
|
|
||||||
|
|
||||||
|
RecommendationServiceDep = Annotated[RecommendationService, Depends(get_recommendation_service)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_stats_service(session: SessionDep) -> StatsService:
|
||||||
|
return StatsService(sites=SiteRepository(session), readings=ReadingRepository(session))
|
||||||
|
|
||||||
|
|
||||||
|
StatsServiceDep = Annotated[StatsService, Depends(get_stats_service)]
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_principal(
|
||||||
|
credentials: CredentialsDep,
|
||||||
|
session: SessionDep,
|
||||||
|
token_policy: Annotated[TokenPolicy, Depends(get_token_policy)],
|
||||||
|
) -> Principal:
|
||||||
|
if credentials is None:
|
||||||
|
raise _non_authentifie("invalid_request")
|
||||||
|
|
||||||
|
try:
|
||||||
|
claims = decode_token(token_policy, credentials.credentials)
|
||||||
|
except TokenExpiredError as erreur:
|
||||||
|
raise _non_authentifie("expired") from erreur
|
||||||
|
except TokenInvalidError as erreur:
|
||||||
|
raise _non_authentifie("invalid_token") from erreur
|
||||||
|
|
||||||
|
compte = await UserRepository(session).get_by_id(claims.subject)
|
||||||
|
if compte is None or not compte.is_active:
|
||||||
|
raise _non_authentifie("invalid_token")
|
||||||
|
# Piège : `iat` est une date JWT, donc en secondes entières. Comparer sans tronquer le
|
||||||
|
# marqueur rejetterait tout jeton émis dans la même seconde que le changement, c'est-à-dire
|
||||||
|
# celui que `/auth/password` vient de rendre pour garder l'appareil courant connecté.
|
||||||
|
if int(claims.issued_at.timestamp()) < int(compte.credentials_changed_at.timestamp()):
|
||||||
|
raise _non_authentifie("token_stale")
|
||||||
|
if claims.role != compte.role:
|
||||||
|
raise _non_authentifie("token_stale")
|
||||||
|
|
||||||
|
return Principal(
|
||||||
|
id=compte.id,
|
||||||
|
email=compte.email,
|
||||||
|
role=Role(compte.role),
|
||||||
|
kind=AccountKind(compte.kind),
|
||||||
|
must_change_password=compte.must_change_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
CurrentPrincipalDep = Annotated[Principal, Depends(get_current_principal)]
|
||||||
|
|
||||||
|
|
||||||
|
def require_role(minimum: Role) -> Callable[[Principal], Principal]:
|
||||||
|
def garde(principal: CurrentPrincipalDep) -> Principal:
|
||||||
|
if principal.must_change_password:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN, detail=CODE_CHANGEMENT_REQUIS
|
||||||
|
)
|
||||||
|
if not has_at_least(principal.role, minimum):
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Droits insuffisants")
|
||||||
|
return principal
|
||||||
|
|
||||||
|
return garde
|
||||||
|
|
||||||
|
|
||||||
|
LecteurDep = Annotated[Principal, Depends(require_role(Role.LECTEUR))]
|
||||||
|
OperateurDep = Annotated[Principal, Depends(require_role(Role.OPERATEUR))]
|
||||||
|
AdminDep = Annotated[Principal, Depends(require_role(Role.ADMIN))]
|
||||||
|
|
||||||
|
|
||||||
|
def require_trusted_origin(request: Request, settings: SettingsDep) -> None:
|
||||||
|
# Un navigateur envoie toujours `Origin` sur une requête non sûre. Son absence signale un
|
||||||
|
# client hors navigateur, qui ne détient aucun cookie de victime : rien à protéger.
|
||||||
|
origine = request.headers.get("origin")
|
||||||
|
if origine is None:
|
||||||
|
return
|
||||||
|
if origine not in settings.allowed_origins:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Origine refusée")
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Piège : la réponse 422 par défaut de FastAPI contient la clé `input`, c'est-à-dire la valeur
|
||||||
|
# rejetée. Sur `/auth/login`, un corps malformé renverrait donc le mot de passe au client et le
|
||||||
|
# déposerait dans les journaux d'erreur. `validation_error_handler()` ne laisse passer que le
|
||||||
|
# champ fautif et le type d'erreur.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request, status
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
from app.core.logging import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def validation_error_handler(_: Request, exception: RequestValidationError) -> JSONResponse:
|
||||||
|
champs: list[dict[str, Any]] = [
|
||||||
|
{
|
||||||
|
"champ": ".".join(str(element) for element in erreur["loc"]),
|
||||||
|
"type": erreur["type"],
|
||||||
|
}
|
||||||
|
for erreur in exception.errors()
|
||||||
|
]
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, content={"detail": champs}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def unhandled_error_handler(request: Request, exception: Exception) -> JSONResponse:
|
||||||
|
correlation = uuid.uuid4().hex
|
||||||
|
logger.exception(
|
||||||
|
"erreur non gérée correlation=%s methode=%s chemin=%s",
|
||||||
|
correlation,
|
||||||
|
request.method,
|
||||||
|
request.url.path,
|
||||||
|
)
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
|
content={"detail": "Erreur interne", "correlation": correlation},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def register_error_handlers(application: FastAPI) -> None:
|
||||||
|
application.add_exception_handler(RequestValidationError, validation_error_handler) # type: ignore[arg-type]
|
||||||
|
application.add_exception_handler(Exception, unhandled_error_handler)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Pourquoi : `SecurityHeadersMiddleware` ne pose ni HSTS ni CSP, et c'est délibéré.
|
||||||
|
# L'application ignore si TLS termine devant elle, donc elle ne peut pas décider d'un HSTS ;
|
||||||
|
# et une CSP sur une API JSON ne protège presque rien, celle qui compte protège la page
|
||||||
|
# Angular. Les deux appartiennent au terminateur TLS.
|
||||||
|
# Contrainte : `/docs` charge Swagger depuis un CDN, une CSP stricte ici casserait la
|
||||||
|
# documentation sans rien sécuriser.
|
||||||
|
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.responses import Response
|
||||||
|
|
||||||
|
EN_TETES: Final[dict[str, str]] = {
|
||||||
|
"X-Content-Type-Options": "nosniff",
|
||||||
|
"X-Frame-Options": "DENY",
|
||||||
|
"Referrer-Policy": "no-referrer",
|
||||||
|
}
|
||||||
|
|
||||||
|
PREFIXE_AUTHENTIFICATION: Final = "/auth"
|
||||||
|
|
||||||
|
|
||||||
|
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(
|
||||||
|
self, request: Request, call_next: Callable[[Request], Awaitable[Response]]
|
||||||
|
) -> Response:
|
||||||
|
response = await call_next(request)
|
||||||
|
for nom, valeur in EN_TETES.items():
|
||||||
|
response.headers.setdefault(nom, valeur)
|
||||||
|
|
||||||
|
# Une réponse d'authentification ne doit jamais être conservée par un intermédiaire.
|
||||||
|
if PREFIXE_AUTHENTIFICATION in request.url.path:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
return response
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
# Piège : `cookie_de_rafraichissement` est purement documentaire, d'où son `auto_error=False`.
|
||||||
|
# Avec la valeur par défaut, FastAPI répondrait 403 avant d'atteindre `lit_le_cookie()`, et
|
||||||
|
# `/auth/refresh` cesserait de rendre le 401 que le frontend attend.
|
||||||
|
|
||||||
|
from typing import Any, Final
|
||||||
|
|
||||||
|
from fastapi.security import APIKeyCookie
|
||||||
|
|
||||||
|
from app.core.config import REFRESH_COOKIE_DEFAUT
|
||||||
|
from app.schemas.errors import ErrorResponse, InternalErrorResponse, ValidationErrorResponse
|
||||||
|
|
||||||
|
Reponses = dict[int | str, dict[str, Any]]
|
||||||
|
|
||||||
|
SUMMARY: Final = "Collecte, analyse et restitution de séries temporelles énergétiques."
|
||||||
|
|
||||||
|
DESCRIPTION: Final = """
|
||||||
|
Toutes les routes sont préfixées par `/api/v1`.
|
||||||
|
|
||||||
|
**Authentification.** Le jeton d'accès se présente dans l'en-tête `Authorization: Bearer ...`.
|
||||||
|
Le jeton de rafraîchissement est un cookie `HttpOnly` que le code client ne voit jamais : il
|
||||||
|
suffit d'émettre les requêtes avec les identifiants de session. `POST /auth/refresh` rend un
|
||||||
|
nouveau jeton d'accès et fait tourner le cookie.
|
||||||
|
|
||||||
|
**Rôles.** `lecteur`, puis `operateur`, puis `admin`. Chaque rôle couvre les droits du
|
||||||
|
précédent.
|
||||||
|
|
||||||
|
**Erreurs.** Le corps porte toujours une clé `detail`. Un `403` dont le `detail` vaut
|
||||||
|
`password_change_required` n'est pas un refus de droits : il exige le changement du mot de passe
|
||||||
|
provisoire avant toute autre action.
|
||||||
|
|
||||||
|
Le parcours de session complet est décrit dans
|
||||||
|
`docs/architecture/31-contrat-authentification.md`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
TAGS: Final[list[dict[str, Any]]] = [
|
||||||
|
{
|
||||||
|
"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`.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "sites",
|
||||||
|
"description": "Consultation du parc de sites. Accessible à partir du rôle `lecteur`.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "alerts",
|
||||||
|
"description": "Consultation des alertes de consommation. Accessible à partir du rôle "
|
||||||
|
"`lecteur`.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "recommendations",
|
||||||
|
"description": (
|
||||||
|
"Consultation des recommandations issues des alertes. Accessible à partir du rôle "
|
||||||
|
"`lecteur`."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "stats",
|
||||||
|
"description": "Statistiques agrégées de consommation. Accessible à partir du rôle "
|
||||||
|
"`lecteur`.",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
cookie_de_rafraichissement = APIKeyCookie(
|
||||||
|
name=REFRESH_COOKIE_DEFAUT,
|
||||||
|
scheme_name="Cookie de rafraîchissement",
|
||||||
|
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`."
|
||||||
|
),
|
||||||
|
auto_error=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Le 422 n'est déclaré que sur les routes qui acceptent un corps ou un paramètre : ailleurs,
|
||||||
|
# aucune validation ne peut échouer et l'annoncer serait faux.
|
||||||
|
REPONSE_VALIDATION: Final[Reponses] = {
|
||||||
|
422: {
|
||||||
|
"model": ValidationErrorResponse,
|
||||||
|
"description": (
|
||||||
|
"Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la "
|
||||||
|
"valeur envoyée."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSE_SERVEUR: Final[Reponses] = {
|
||||||
|
500: {
|
||||||
|
"model": InternalErrorResponse,
|
||||||
|
"description": (
|
||||||
|
"Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas "
|
||||||
|
"renvoyée au client."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSE_INDISPONIBLE: Final[Reponses] = {
|
||||||
|
503: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": "Base injoignable, ou extension TimescaleDB absente de la base.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSES_AUTHENTIFIEES: Final[Reponses] = {
|
||||||
|
401: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"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=`."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSES_ADMIN: Final[Reponses] = {
|
||||||
|
**REPONSES_AUTHENTIFIEES,
|
||||||
|
403: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": (
|
||||||
|
"Droits insuffisants, ou mot de passe provisoire à changer quand `detail` vaut "
|
||||||
|
"`password_change_required`."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
# `lecteur` est le rôle minimum : `require_role` n'y refuse jamais un 403 pour droits
|
||||||
|
# insuffisants, seulement pour le mot de passe provisoire.
|
||||||
|
REPONSES_LECTEUR: Final[Reponses] = {
|
||||||
|
**REPONSES_AUTHENTIFIEES,
|
||||||
|
403: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": (
|
||||||
|
"Mot de passe provisoire à changer (`detail` vaut `password_change_required`)."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSE_ORIGINE_REFUSEE: Final[Reponses] = {
|
||||||
|
403: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": "Origine non autorisée (protection CSRF de `require_trusted_origin`).",
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Pourquoi : `/metrics` est protégé par un jeton statique et non par un rôle applicatif. Coupler
|
||||||
|
# la supervision au modèle d'utilisateurs casserait la collecte à chaque panne
|
||||||
|
# d'authentification, c'est-à-dire précisément quand on a besoin des métriques. Le vrai contrôle
|
||||||
|
# reste le réseau : Prometheus scrute sur le réseau interne et `/metrics` ne sort pas.
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from fastapi import HTTPException, Request, status
|
||||||
|
|
||||||
|
from app.api.deps import SettingsDep
|
||||||
|
|
||||||
|
|
||||||
|
def require_metrics_token(request: Request, settings: SettingsDep) -> None:
|
||||||
|
attendu = settings.metrics_token
|
||||||
|
if attendu is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
presente = request.headers.get("authorization", "")
|
||||||
|
prefixe = "Bearer "
|
||||||
|
if not presente.startswith(prefixe) or not secrets.compare_digest(
|
||||||
|
presente[len(prefixe) :], attendu.get_secret_value()
|
||||||
|
):
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Jeton requis")
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.deps import AlertServiceDep, LecteurDep
|
||||||
|
from app.api.openapi import REPONSE_VALIDATION
|
||||||
|
from app.schemas.alert import AlertResponse, AlertSeverity
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"",
|
||||||
|
response_model=list[AlertResponse],
|
||||||
|
summary="Liste les alertes",
|
||||||
|
responses=REPONSE_VALIDATION,
|
||||||
|
)
|
||||||
|
async def list_alerts(
|
||||||
|
_: LecteurDep,
|
||||||
|
service: AlertServiceDep,
|
||||||
|
site_id: str | None = None,
|
||||||
|
severity: AlertSeverity | None = None,
|
||||||
|
) -> list[AlertResponse]:
|
||||||
|
alertes = await service.list_all(site_id=site_id, severity=severity)
|
||||||
|
return [AlertResponse.model_validate(alerte) for alerte in alertes]
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
# Piège : le jeton de rafraîchissement ne quitte jamais le cookie httpOnly, et le jeton
|
||||||
|
# d'accès ne va jamais dans un cookie. C'est ce qui réduit la surface CSRF aux trois routes de
|
||||||
|
# ce module : partout ailleurs, le navigateur n'attache rien de lui-même.
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||||
|
|
||||||
|
from app.api.deps import (
|
||||||
|
AuthServiceDep,
|
||||||
|
CurrentPrincipalDep,
|
||||||
|
SettingsDep,
|
||||||
|
get_client_ip,
|
||||||
|
require_trusted_origin,
|
||||||
|
)
|
||||||
|
from app.api.openapi import (
|
||||||
|
REPONSE_ORIGINE_REFUSEE,
|
||||||
|
REPONSE_VALIDATION,
|
||||||
|
REPONSES_AUTHENTIFIEES,
|
||||||
|
Reponses,
|
||||||
|
cookie_de_rafraichissement,
|
||||||
|
)
|
||||||
|
from app.core.cookies import RefreshCookie, cookie_name
|
||||||
|
from app.core.logging import get_logger
|
||||||
|
from app.schemas.auth import (
|
||||||
|
LoginRequest,
|
||||||
|
PasswordChangeRequest,
|
||||||
|
PrincipalResponse,
|
||||||
|
TokenResponse,
|
||||||
|
)
|
||||||
|
from app.schemas.errors import ErrorResponse
|
||||||
|
from app.services.auth import (
|
||||||
|
AuthenticatedSession,
|
||||||
|
InvalidCredentialsError,
|
||||||
|
RateLimitedError,
|
||||||
|
SessionRejectedError,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
DETAIL_IDENTIFIANTS = "Identifiants invalides"
|
||||||
|
DETAIL_SESSION = "Session invalide"
|
||||||
|
|
||||||
|
REPONSES_LOGIN: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
401: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"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."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
429: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": "Trop de tentatives sur cette fenêtre glissante.",
|
||||||
|
"headers": {
|
||||||
|
"Retry-After": {
|
||||||
|
"description": "Secondes à attendre avant une nouvelle tentative.",
|
||||||
|
"schema": {"type": "integer"},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSES_REFRESH: Reponses = {
|
||||||
|
**REPONSE_ORIGINE_REFUSEE,
|
||||||
|
401: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"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."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSES_LOGOUT: Reponses = {**REPONSE_ORIGINE_REFUSEE}
|
||||||
|
|
||||||
|
REPONSES_LOGOUT_ALL: Reponses = {**REPONSES_AUTHENTIFIEES, **REPONSE_ORIGINE_REFUSEE}
|
||||||
|
|
||||||
|
REPONSES_MOT_DE_PASSE: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
**REPONSE_ORIGINE_REFUSEE,
|
||||||
|
401: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": "Jeton d'accès invalide, ou mot de passe courant faux.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def repond(
|
||||||
|
response: Response, settings: SettingsDep, session: AuthenticatedSession
|
||||||
|
) -> TokenResponse:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
response.set_cookie(**RefreshCookie.build(settings, session.refresh_secret).as_kwargs())
|
||||||
|
return TokenResponse(
|
||||||
|
access_token=session.access_token,
|
||||||
|
expires_in=session.expires_in,
|
||||||
|
principal=PrincipalResponse.from_principal(session.principal),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Piège : une `HTTPException` construit sa propre réponse, donc tout en-tête posé sur la
|
||||||
|
# `Response` injectée est perdu. L'effacement du cookie doit voyager avec l'exception,
|
||||||
|
# sans quoi un navigateur garderait un cookie mort après une détection de réutilisation.
|
||||||
|
def entete_de_suppression(settings: SettingsDep) -> str:
|
||||||
|
temoin = Response()
|
||||||
|
temoin.delete_cookie(**RefreshCookie.expired(settings).as_deletion_kwargs())
|
||||||
|
return temoin.headers["set-cookie"]
|
||||||
|
|
||||||
|
|
||||||
|
def lit_le_cookie(request: Request, settings: SettingsDep) -> str:
|
||||||
|
secret = request.cookies.get(cookie_name(settings))
|
||||||
|
if not secret:
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=DETAIL_SESSION)
|
||||||
|
return secret
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/login",
|
||||||
|
response_model=TokenResponse,
|
||||||
|
summary="Ouvre une session",
|
||||||
|
responses=REPONSES_LOGIN,
|
||||||
|
)
|
||||||
|
async def login(
|
||||||
|
payload: LoginRequest,
|
||||||
|
request: Request,
|
||||||
|
response: Response,
|
||||||
|
settings: SettingsDep,
|
||||||
|
service: AuthServiceDep,
|
||||||
|
client_ip: str | None = Depends(get_client_ip),
|
||||||
|
) -> TokenResponse:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
agent = request.headers.get("user-agent")
|
||||||
|
|
||||||
|
try:
|
||||||
|
session = await service.authenticate(
|
||||||
|
email=payload.email, password=payload.password, client_ip=client_ip, user_agent=agent
|
||||||
|
)
|
||||||
|
except RateLimitedError as erreur:
|
||||||
|
logger.warning("auth.rate_limited email=%s ip=%s", payload.email, client_ip)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||||
|
detail="Trop de tentatives, réessayez plus tard",
|
||||||
|
headers={"Retry-After": str(erreur.retry_after)},
|
||||||
|
) from erreur
|
||||||
|
except InvalidCredentialsError as erreur:
|
||||||
|
logger.warning("auth.login.failure email=%s ip=%s", payload.email, client_ip)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED, detail=DETAIL_IDENTIFIANTS
|
||||||
|
) from erreur
|
||||||
|
|
||||||
|
logger.info("auth.login.success user_id=%s ip=%s", session.principal.id, client_ip)
|
||||||
|
return repond(response, settings, session)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/refresh",
|
||||||
|
response_model=TokenResponse,
|
||||||
|
summary="Fait tourner la session",
|
||||||
|
dependencies=[Depends(require_trusted_origin), Depends(cookie_de_rafraichissement)],
|
||||||
|
responses=REPONSES_REFRESH,
|
||||||
|
)
|
||||||
|
async def refresh(
|
||||||
|
request: Request,
|
||||||
|
response: Response,
|
||||||
|
settings: SettingsDep,
|
||||||
|
service: AuthServiceDep,
|
||||||
|
client_ip: str | None = Depends(get_client_ip),
|
||||||
|
) -> TokenResponse:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
|
||||||
|
try:
|
||||||
|
session = await service.refresh(
|
||||||
|
secret=lit_le_cookie(request, settings),
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=request.headers.get("user-agent"),
|
||||||
|
)
|
||||||
|
except SessionRejectedError as erreur:
|
||||||
|
logger.warning("auth.refresh.rejected ip=%s", client_ip)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail=DETAIL_SESSION,
|
||||||
|
headers={
|
||||||
|
"Set-Cookie": entete_de_suppression(settings),
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
},
|
||||||
|
) from erreur
|
||||||
|
|
||||||
|
return repond(response, settings, session)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/logout",
|
||||||
|
status_code=status.HTTP_204_NO_CONTENT,
|
||||||
|
summary="Ferme la session courante",
|
||||||
|
dependencies=[Depends(require_trusted_origin), Depends(cookie_de_rafraichissement)],
|
||||||
|
responses=REPONSES_LOGOUT,
|
||||||
|
)
|
||||||
|
async def logout(
|
||||||
|
request: Request, response: Response, settings: SettingsDep, service: AuthServiceDep
|
||||||
|
) -> None:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
secret = request.cookies.get(cookie_name(settings))
|
||||||
|
if secret:
|
||||||
|
await service.logout(secret=secret)
|
||||||
|
response.delete_cookie(**RefreshCookie.expired(settings).as_deletion_kwargs())
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/logout-all",
|
||||||
|
status_code=status.HTTP_204_NO_CONTENT,
|
||||||
|
summary="Ferme toutes les sessions du compte",
|
||||||
|
dependencies=[Depends(require_trusted_origin)],
|
||||||
|
responses=REPONSES_LOGOUT_ALL,
|
||||||
|
)
|
||||||
|
async def logout_all(
|
||||||
|
principal: CurrentPrincipalDep,
|
||||||
|
response: Response,
|
||||||
|
settings: SettingsDep,
|
||||||
|
service: AuthServiceDep,
|
||||||
|
) -> None:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
revoquees = await service.logout_all(principal)
|
||||||
|
logger.info("auth.logout_all user_id=%s sessions=%s", principal.id, revoquees)
|
||||||
|
response.delete_cookie(**RefreshCookie.expired(settings).as_deletion_kwargs())
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/me",
|
||||||
|
response_model=PrincipalResponse,
|
||||||
|
summary="Décrit le compte connecté",
|
||||||
|
responses=REPONSES_AUTHENTIFIEES,
|
||||||
|
)
|
||||||
|
async def me(principal: CurrentPrincipalDep) -> PrincipalResponse:
|
||||||
|
return PrincipalResponse.from_principal(principal)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/password",
|
||||||
|
response_model=TokenResponse,
|
||||||
|
summary="Change son propre mot de passe",
|
||||||
|
dependencies=[Depends(require_trusted_origin)],
|
||||||
|
responses=REPONSES_MOT_DE_PASSE,
|
||||||
|
)
|
||||||
|
async def change_password(
|
||||||
|
payload: PasswordChangeRequest,
|
||||||
|
principal: CurrentPrincipalDep,
|
||||||
|
request: Request,
|
||||||
|
response: Response,
|
||||||
|
settings: SettingsDep,
|
||||||
|
service: AuthServiceDep,
|
||||||
|
client_ip: str | None = Depends(get_client_ip),
|
||||||
|
) -> TokenResponse:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
|
||||||
|
try:
|
||||||
|
session = await service.change_password(
|
||||||
|
principal=principal,
|
||||||
|
current_password=payload.current_password,
|
||||||
|
new_password=payload.new_password,
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=request.headers.get("user-agent"),
|
||||||
|
)
|
||||||
|
except InvalidCredentialsError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED, detail=DETAIL_IDENTIFIANTS
|
||||||
|
) from erreur
|
||||||
|
|
||||||
|
logger.info("auth.password_changed user_id=%s", principal.id)
|
||||||
|
return repond(response, settings, session)
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException, status
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
|
|
||||||
|
from app.api.deps import SessionDep, SettingsDep
|
||||||
|
from app.api.openapi import REPONSE_INDISPONIBLE
|
||||||
|
from app.core.logging import get_logger
|
||||||
|
from app.schemas.health import LivenessStatus, ReadinessStatus
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
TIMESCALEDB_VERSION = text("SELECT extversion FROM pg_extension WHERE extname = 'timescaledb'")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/live", summary="Sonde de vivacité")
|
||||||
|
async def liveness(settings: SettingsDep) -> LivenessStatus:
|
||||||
|
return LivenessStatus(
|
||||||
|
status="ok",
|
||||||
|
service=settings.name,
|
||||||
|
version=settings.version,
|
||||||
|
environment=settings.env,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/ready", summary="Sonde de disponibilité", responses=REPONSE_INDISPONIBLE)
|
||||||
|
async def readiness(session: SessionDep) -> ReadinessStatus:
|
||||||
|
try:
|
||||||
|
version: str | None = await session.scalar(TIMESCALEDB_VERSION)
|
||||||
|
# `# fmt: skip` contourne un bug de ruff format 0.16.7 : il retire les parenthèses de ce
|
||||||
|
# `except` à deux types, ce qui produit une syntaxe invalide (`except A, B:`).
|
||||||
|
except (SQLAlchemyError, OSError): # fmt: skip
|
||||||
|
logger.exception("Base de données injoignable")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Base de données injoignable",
|
||||||
|
) from None
|
||||||
|
|
||||||
|
if version is None:
|
||||||
|
logger.error("Extension TimescaleDB absente de la base")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Extension TimescaleDB absente",
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug("Extension TimescaleDB en version %s", version)
|
||||||
|
return ReadinessStatus(status="ready", database="reachable", timescaledb="loaded")
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException, status
|
||||||
|
|
||||||
|
from app.api.deps import LecteurDep, RecommendationServiceDep
|
||||||
|
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||||
|
from app.schemas.errors import ErrorResponse
|
||||||
|
from app.schemas.recommendation import RecommendationResponse
|
||||||
|
from app.services.recommendation import RecommendationNotFoundError
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
REPONSES_INTROUVABLE: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
404: {"model": ErrorResponse, "description": "Aucune recommandation ne porte cet identifiant."},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[RecommendationResponse], summary="Liste les recommandations")
|
||||||
|
async def list_recommendations(
|
||||||
|
_: LecteurDep, service: RecommendationServiceDep
|
||||||
|
) -> list[RecommendationResponse]:
|
||||||
|
recommendations = await service.list_all()
|
||||||
|
return [RecommendationResponse.model_validate(r) for r in recommendations]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{recommendation_id}",
|
||||||
|
response_model=RecommendationResponse,
|
||||||
|
summary="Décrit une recommandation",
|
||||||
|
responses=REPONSES_INTROUVABLE,
|
||||||
|
)
|
||||||
|
async def get_recommendation(
|
||||||
|
recommendation_id: int, _: LecteurDep, service: RecommendationServiceDep
|
||||||
|
) -> RecommendationResponse:
|
||||||
|
try:
|
||||||
|
recommendation = await service.get_by_id(recommendation_id)
|
||||||
|
except RecommendationNotFoundError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="Recommandation introuvable"
|
||||||
|
) from erreur
|
||||||
|
return RecommendationResponse.model_validate(recommendation)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException, status
|
||||||
|
|
||||||
|
from app.api.deps import LecteurDep, SiteServiceDep
|
||||||
|
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||||
|
from app.schemas.errors import ErrorResponse
|
||||||
|
from app.schemas.site import SiteResponse
|
||||||
|
from app.services.site import SiteNotFoundError
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
REPONSES_INTROUVABLE: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
404: {"model": ErrorResponse, "description": "Aucun site ne porte cet identifiant."},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[SiteResponse], summary="Liste les sites")
|
||||||
|
async def list_sites(_: LecteurDep, service: SiteServiceDep) -> list[SiteResponse]:
|
||||||
|
sites = await service.list_all()
|
||||||
|
return [SiteResponse.model_validate(site) for site in sites]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{site_id}",
|
||||||
|
response_model=SiteResponse,
|
||||||
|
summary="Décrit un site",
|
||||||
|
responses=REPONSES_INTROUVABLE,
|
||||||
|
)
|
||||||
|
async def get_site(site_id: str, _: LecteurDep, service: SiteServiceDep) -> SiteResponse:
|
||||||
|
try:
|
||||||
|
site = await service.get_by_id(site_id)
|
||||||
|
except SiteNotFoundError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
||||||
|
) from erreur
|
||||||
|
return SiteResponse.model_validate(site)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.deps import LecteurDep, StatsServiceDep
|
||||||
|
from app.schemas.stats import StatsSummaryResponse
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/summary",
|
||||||
|
response_model=StatsSummaryResponse,
|
||||||
|
summary="Résume la consommation instantanée du parc",
|
||||||
|
)
|
||||||
|
async def get_summary(_: LecteurDep, service: StatsServiceDep) -> StatsSummaryResponse:
|
||||||
|
resume = await service.summary()
|
||||||
|
return StatsSummaryResponse.model_validate(resume)
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Response, status
|
||||||
|
|
||||||
|
from app.api.deps import AdminDep, UserServiceDep
|
||||||
|
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||||
|
from app.core.logging import get_logger
|
||||||
|
from app.schemas.errors import ErrorResponse
|
||||||
|
from app.schemas.user import (
|
||||||
|
TemporaryPasswordResponse,
|
||||||
|
UserCreateRequest,
|
||||||
|
UserResponse,
|
||||||
|
UserUpdateRequest,
|
||||||
|
)
|
||||||
|
from app.services.user import EmailAlreadyUsedError, LastAdminError, UserNotFoundError
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
REPONSES_CREATION: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
409: {"model": ErrorResponse, "description": "Adresse déjà portée par un autre compte."},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSES_INTROUVABLE: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
404: {"model": ErrorResponse, "description": "Aucun compte ne porte cet identifiant."},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSES_MODIFICATION: Reponses = {
|
||||||
|
**REPONSES_INTROUVABLE,
|
||||||
|
400: {"model": ErrorResponse, "description": "Corps vide, aucune modification demandée."},
|
||||||
|
409: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": (
|
||||||
|
"L'opération laisserait la plateforme sans administrateur actif, qu'il s'agisse de "
|
||||||
|
"rétrograder le dernier ou de le désactiver."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[UserResponse], summary="Liste les comptes")
|
||||||
|
async def list_users(_: AdminDep, service: UserServiceDep) -> list[UserResponse]:
|
||||||
|
comptes = await service.list_all()
|
||||||
|
return [UserResponse.model_validate(compte) for compte in comptes]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"",
|
||||||
|
response_model=TemporaryPasswordResponse,
|
||||||
|
status_code=status.HTTP_201_CREATED,
|
||||||
|
summary="Crée un compte avec un mot de passe provisoire",
|
||||||
|
responses=REPONSES_CREATION,
|
||||||
|
)
|
||||||
|
async def create_user(
|
||||||
|
payload: UserCreateRequest,
|
||||||
|
acteur: AdminDep,
|
||||||
|
service: UserServiceDep,
|
||||||
|
response: Response,
|
||||||
|
) -> TemporaryPasswordResponse:
|
||||||
|
# Le mot de passe provisoire ne doit être conservé par aucun intermédiaire.
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
try:
|
||||||
|
cree = await service.create(
|
||||||
|
actor=acteur,
|
||||||
|
email=payload.email,
|
||||||
|
role=payload.role,
|
||||||
|
full_name=payload.full_name,
|
||||||
|
)
|
||||||
|
except EmailAlreadyUsedError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT, detail="Adresse déjà utilisée"
|
||||||
|
) from erreur
|
||||||
|
|
||||||
|
logger.info("user.created actor=%s target=%s", acteur.id, cree.user.id)
|
||||||
|
return TemporaryPasswordResponse(
|
||||||
|
user=UserResponse.model_validate(cree.user),
|
||||||
|
temporary_password=cree.temporary_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch(
|
||||||
|
"/{user_id}",
|
||||||
|
response_model=UserResponse,
|
||||||
|
summary="Change le rôle ou l'activation",
|
||||||
|
responses=REPONSES_MODIFICATION,
|
||||||
|
)
|
||||||
|
async def update_user(
|
||||||
|
user_id: UUID,
|
||||||
|
payload: UserUpdateRequest,
|
||||||
|
acteur: AdminDep,
|
||||||
|
service: UserServiceDep,
|
||||||
|
) -> UserResponse:
|
||||||
|
compte = None
|
||||||
|
try:
|
||||||
|
if payload.role is not None:
|
||||||
|
compte = await service.change_role(actor=acteur, user_id=user_id, role=payload.role)
|
||||||
|
if payload.is_active is not None:
|
||||||
|
compte = await service.set_active(
|
||||||
|
actor=acteur, user_id=user_id, is_active=payload.is_active
|
||||||
|
)
|
||||||
|
except UserNotFoundError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="Compte introuvable"
|
||||||
|
) from erreur
|
||||||
|
except LastAdminError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="Dernier administrateur actif, l'opération le laisserait sans successeur",
|
||||||
|
) from erreur
|
||||||
|
|
||||||
|
if compte is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST, detail="Aucune modification demandée"
|
||||||
|
)
|
||||||
|
logger.info("user.updated actor=%s target=%s", acteur.id, user_id)
|
||||||
|
return UserResponse.model_validate(compte)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{user_id}/password-reset",
|
||||||
|
response_model=TemporaryPasswordResponse,
|
||||||
|
summary="Réinitialise le mot de passe et ferme les sessions",
|
||||||
|
responses=REPONSES_INTROUVABLE,
|
||||||
|
)
|
||||||
|
async def reset_password(
|
||||||
|
user_id: UUID, acteur: AdminDep, service: UserServiceDep, response: Response
|
||||||
|
) -> TemporaryPasswordResponse:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
try:
|
||||||
|
reinitialise = await service.reset_password(actor=acteur, user_id=user_id)
|
||||||
|
except UserNotFoundError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="Compte introuvable"
|
||||||
|
) from erreur
|
||||||
|
|
||||||
|
logger.info("user.password_reset actor=%s target=%s", acteur.id, user_id)
|
||||||
|
return TemporaryPasswordResponse(
|
||||||
|
user=UserResponse.model_validate(reinitialise.user),
|
||||||
|
temporary_password=reinitialise.temporary_password,
|
||||||
|
)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.openapi import REPONSE_SERVEUR, REPONSES_ADMIN, REPONSES_LECTEUR
|
||||||
|
from app.api.v1.endpoints import alerts, auth, health, recommendations, sites, stats, users
|
||||||
|
|
||||||
|
api_router = APIRouter(responses=REPONSE_SERVEUR)
|
||||||
|
api_router.include_router(health.router, prefix="/health", tags=["health"])
|
||||||
|
api_router.include_router(auth.router, prefix="/auth", tags=["auth"])
|
||||||
|
api_router.include_router(users.router, prefix="/users", tags=["users"], responses=REPONSES_ADMIN)
|
||||||
|
api_router.include_router(sites.router, prefix="/sites", tags=["sites"], responses=REPONSES_LECTEUR)
|
||||||
|
api_router.include_router(
|
||||||
|
alerts.router, prefix="/alerts", tags=["alerts"], responses=REPONSES_LECTEUR
|
||||||
|
)
|
||||||
|
api_router.include_router(
|
||||||
|
recommendations.router,
|
||||||
|
prefix="/recommendations",
|
||||||
|
tags=["recommendations"],
|
||||||
|
responses=REPONSES_LECTEUR,
|
||||||
|
)
|
||||||
|
api_router.include_router(stats.router, prefix="/stats", tags=["stats"], responses=REPONSES_LECTEUR)
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# Pourquoi : `create_admin()` est une commande et non une révision Alembic. Une révision qui
|
||||||
|
# insérerait un compte graverait son empreinte dans Git pour toujours, et son mot de passe
|
||||||
|
# serait connu de quiconque lit le dépôt. L'ADR 0001 pose par ailleurs qu'Alembic porte le
|
||||||
|
# schéma, pas les données.
|
||||||
|
# Piège : le mot de passe ne transite jamais par `argv`, visible de tout `ps`, ni par
|
||||||
|
# l'historique du shell. Il est saisi par `getpass` ou tiré au sort par la commande.
|
||||||
|
|
||||||
|
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(
|
||||||
|
settings: Settings, *, email: str, password: str, force: bool
|
||||||
|
) -> tuple[bool, str]:
|
||||||
|
hacheur = build_hasher(
|
||||||
|
time_cost=settings.argon2_time_cost,
|
||||||
|
memory_cost_kib=settings.argon2_memory_cost_kib,
|
||||||
|
parallelism=settings.argon2_parallelism,
|
||||||
|
max_concurrency=settings.argon2_max_concurrency,
|
||||||
|
)
|
||||||
|
empreinte = await hacheur.hash(password)
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
depot = UserRepository(session)
|
||||||
|
|
||||||
|
if not force and await depot.count_active_admins() > 0:
|
||||||
|
return False, "Un administrateur actif existe déjà, relancer avec --force pour forcer"
|
||||||
|
|
||||||
|
if await depot.get_by_email(email) is not None:
|
||||||
|
return False, f"Le compte {email} existe déjà"
|
||||||
|
|
||||||
|
await depot.create(
|
||||||
|
email=email,
|
||||||
|
password_hash=empreinte,
|
||||||
|
role=Role.ADMIN,
|
||||||
|
must_change_password=True,
|
||||||
|
)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
return (
|
||||||
|
True,
|
||||||
|
f"Administrateur {email.strip().lower()} créé, mot de passe à changer à la connexion",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
admin = sous_commandes.add_parser("create-admin", help="Crée le premier administrateur")
|
||||||
|
admin.add_argument("--email", required=True)
|
||||||
|
admin.add_argument(
|
||||||
|
"--generate", action="store_true", help="Tire un mot de passe au sort et l'affiche une fois"
|
||||||
|
)
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def read_password(*, generate: bool) -> str:
|
||||||
|
if generate:
|
||||||
|
mot_de_passe = secrets.token_urlsafe(LONGUEUR_MOT_DE_PASSE_GENERE)
|
||||||
|
print(f"Mot de passe généré, il ne sera plus affiché : {mot_de_passe}")
|
||||||
|
return mot_de_passe
|
||||||
|
|
||||||
|
mot_de_passe = getpass("Mot de passe : ")
|
||||||
|
if len(mot_de_passe) < LONGUEUR_MINIMALE:
|
||||||
|
raise SystemExit(f"Le mot de passe doit faire au moins {LONGUEUR_MINIMALE} caractères")
|
||||||
|
if mot_de_passe != getpass("Confirmation : "):
|
||||||
|
raise SystemExit("Les deux saisies diffèrent")
|
||||||
|
return mot_de_passe
|
||||||
|
|
||||||
|
|
||||||
|
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(
|
||||||
|
create_admin(
|
||||||
|
get_settings(),
|
||||||
|
email=arguments.email,
|
||||||
|
password=mot_de_passe,
|
||||||
|
force=arguments.force,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
print(message)
|
||||||
|
return 0 if succes else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": # pragma: no cover
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
from functools import lru_cache
|
||||||
|
from typing import Literal, Self
|
||||||
|
|
||||||
|
from pydantic import Field, SecretStr, model_validator
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
Environment = Literal["local", "dev", "staging", "prod"]
|
||||||
|
SameSite = Literal["lax", "strict", "none"]
|
||||||
|
|
||||||
|
SECRET_KEY_MIN_LENGTH = 32
|
||||||
|
REFRESH_COOKIE_DEFAUT = "ev_refresh"
|
||||||
|
SENTINELLES_INTERDITES = frozenset(
|
||||||
|
{"change_me", "changeme", "secret", "secret-de-test", "changez-moi", "todo"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env",
|
||||||
|
env_prefix="APP_",
|
||||||
|
env_file_encoding="utf-8",
|
||||||
|
extra="ignore",
|
||||||
|
)
|
||||||
|
|
||||||
|
name: str = "EnerVision API"
|
||||||
|
version: str = "0.1.0"
|
||||||
|
env: Environment = "local"
|
||||||
|
debug: bool = False
|
||||||
|
log_level: str = "INFO"
|
||||||
|
api_prefix: str = "/api/v1"
|
||||||
|
secret_key: SecretStr
|
||||||
|
cors_origins: str = ""
|
||||||
|
database_url: str = Field(validation_alias="DATABASE_URL")
|
||||||
|
database_pool_size: int = 5
|
||||||
|
database_max_overflow: int = 10
|
||||||
|
|
||||||
|
jwt_issuer: str = "enervision-api"
|
||||||
|
jwt_audience: str = "enervision-web"
|
||||||
|
access_token_ttl_seconds: int = Field(default=900, ge=60, le=3600)
|
||||||
|
refresh_token_ttl_seconds: int = Field(default=604800, ge=3600, le=2592000)
|
||||||
|
|
||||||
|
refresh_cookie_name: str = REFRESH_COOKIE_DEFAUT
|
||||||
|
cookie_path: str = "/api/v1/auth"
|
||||||
|
cookie_samesite: SameSite = "strict"
|
||||||
|
cookie_secure: bool | None = None
|
||||||
|
|
||||||
|
argon2_time_cost: int = Field(default=2, ge=1, le=10)
|
||||||
|
argon2_memory_cost_kib: int = Field(default=19456, ge=8192)
|
||||||
|
argon2_parallelism: int = Field(default=1, ge=1, le=4)
|
||||||
|
argon2_max_concurrency: int = Field(default=4, ge=1, le=32)
|
||||||
|
|
||||||
|
login_window_seconds: int = Field(default=900, ge=60)
|
||||||
|
login_max_failures_per_identifier_and_ip: int = Field(default=5, ge=1)
|
||||||
|
login_max_failures_per_ip: int = Field(default=20, ge=1)
|
||||||
|
login_max_failures_per_identifier: int = Field(default=50, ge=1)
|
||||||
|
|
||||||
|
trust_proxy_headers: bool = False
|
||||||
|
expose_api_docs: bool | None = None
|
||||||
|
metrics_token: SecretStr | None = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def allowed_origins(self) -> list[str]:
|
||||||
|
return [origin.strip() for origin in self.cors_origins.split(",") if origin.strip()]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_production(self) -> bool:
|
||||||
|
return self.env == "prod"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cookies_are_secure(self) -> bool:
|
||||||
|
return self.env != "local" if self.cookie_secure is None else self.cookie_secure
|
||||||
|
|
||||||
|
@property
|
||||||
|
def api_docs_are_exposed(self) -> bool:
|
||||||
|
if self.expose_api_docs is not None:
|
||||||
|
return self.expose_api_docs
|
||||||
|
return self.env not in ("staging", "prod")
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _refuse_les_configurations_dangereuses(self) -> Self:
|
||||||
|
secret = self.secret_key.get_secret_value()
|
||||||
|
if len(secret) < SECRET_KEY_MIN_LENGTH:
|
||||||
|
raise ValueError(
|
||||||
|
f"APP_SECRET_KEY doit faire au moins {SECRET_KEY_MIN_LENGTH} caractères"
|
||||||
|
)
|
||||||
|
if secret.strip().lower() in SENTINELLES_INTERDITES:
|
||||||
|
raise ValueError("APP_SECRET_KEY est une valeur d'exemple, il faut en générer une")
|
||||||
|
|
||||||
|
# Piège : `create_app()` passe `debug` à FastAPI, qui renvoie alors la trace complète
|
||||||
|
# au client, et à l'engine, qui journalise le SQL et ses paramètres.
|
||||||
|
if self.debug and self.env in ("staging", "prod"):
|
||||||
|
raise ValueError("APP_DEBUG doit rester faux hors des environnements locaux")
|
||||||
|
|
||||||
|
if "*" in self.cors_origins:
|
||||||
|
raise ValueError("APP_CORS_ORIGINS n'accepte pas de joker, les origines sont listées")
|
||||||
|
|
||||||
|
# Sans origines, aucun middleware CORS n'est monté et la vérification d'`Origin` des
|
||||||
|
# routes d'authentification n'a plus de référentiel auquel comparer.
|
||||||
|
if self.env != "local" and not self.allowed_origins:
|
||||||
|
raise ValueError("APP_CORS_ORIGINS doit lister au moins une origine hors local")
|
||||||
|
|
||||||
|
if self.cookie_samesite == "none" and not self.cookies_are_secure:
|
||||||
|
raise ValueError("Un cookie SameSite=None est rejeté par les navigateurs sans Secure")
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return Settings()
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# Piège : le cookie de suppression doit reprendre exactement le nom et le `Path` du cookie
|
||||||
|
# posé, sinon le navigateur en garde une copie et la déconnexion n'est que cosmétique.
|
||||||
|
# `RefreshCookie.expired()` existe pour que les deux ne puissent pas diverger.
|
||||||
|
|
||||||
|
from dataclasses import asdict, dataclass
|
||||||
|
from typing import Any, Self
|
||||||
|
|
||||||
|
from app.core.config import SameSite, Settings
|
||||||
|
|
||||||
|
SECURE_PREFIX = "__Secure-"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class RefreshCookie:
|
||||||
|
key: str
|
||||||
|
value: str
|
||||||
|
max_age: int
|
||||||
|
path: str
|
||||||
|
secure: bool
|
||||||
|
httponly: bool
|
||||||
|
samesite: SameSite
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def build(cls, settings: Settings, value: str) -> Self:
|
||||||
|
return cls(
|
||||||
|
key=cookie_name(settings),
|
||||||
|
value=value,
|
||||||
|
max_age=settings.refresh_token_ttl_seconds,
|
||||||
|
path=settings.cookie_path,
|
||||||
|
secure=settings.cookies_are_secure,
|
||||||
|
httponly=True,
|
||||||
|
samesite=settings.cookie_samesite,
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def expired(cls, settings: Settings) -> Self:
|
||||||
|
return cls(
|
||||||
|
key=cookie_name(settings),
|
||||||
|
value="",
|
||||||
|
max_age=0,
|
||||||
|
path=settings.cookie_path,
|
||||||
|
secure=settings.cookies_are_secure,
|
||||||
|
httponly=True,
|
||||||
|
samesite=settings.cookie_samesite,
|
||||||
|
)
|
||||||
|
|
||||||
|
def as_kwargs(self) -> dict[str, Any]:
|
||||||
|
return asdict(self)
|
||||||
|
|
||||||
|
def as_deletion_kwargs(self) -> dict[str, Any]:
|
||||||
|
# `Response.delete_cookie()` n'accepte ni `value` ni `max_age`, mais il exige le même
|
||||||
|
# nom, le même chemin et les mêmes attributs, sinon le navigateur garde le cookie.
|
||||||
|
arguments = asdict(self)
|
||||||
|
del arguments["value"], arguments["max_age"]
|
||||||
|
return arguments
|
||||||
|
|
||||||
|
|
||||||
|
def cookie_name(settings: Settings) -> str:
|
||||||
|
if settings.cookies_are_secure:
|
||||||
|
return f"{SECURE_PREFIX}{settings.refresh_cookie_name}"
|
||||||
|
return settings.refresh_cookie_name
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# Piège : `PasswordHasher.verify()` bloque 17 ms. Appelé tel quel dans un `async def`, il fige
|
||||||
|
# la boucle d'événements et gèle toutes les requêtes en cours, pas seulement la connexion.
|
||||||
|
# `Argon2Hasher` le pousse donc dans un fil, sous un `CapacityLimiter` : le pool par défaut
|
||||||
|
# d'anyio accepte 40 fils, soit 40 x 19 Mio dans le pire cas sur une machine qui héberge aussi
|
||||||
|
# PostgreSQL, Prometheus et Grafana.
|
||||||
|
# Piège : `verify_dummy()` doit être appelé quand l'utilisateur est introuvable. Sans lui,
|
||||||
|
# l'écart entre 2 ms et 17 ms est un oracle d'existence de compte, mesurable à distance.
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
import anyio
|
||||||
|
import anyio.to_thread
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
from argon2.exceptions import Argon2Error, InvalidHashError, VerificationError
|
||||||
|
|
||||||
|
_ERREURS_DE_VERIFICATION = (VerificationError, InvalidHashError, Argon2Error)
|
||||||
|
|
||||||
|
|
||||||
|
class Argon2Hasher:
|
||||||
|
def __init__(self, hasher: PasswordHasher, *, max_concurrency: int) -> None:
|
||||||
|
self._hasher = hasher
|
||||||
|
self._limiter = anyio.CapacityLimiter(max_concurrency)
|
||||||
|
self._leurre = hasher.hash(secrets.token_urlsafe(32))
|
||||||
|
|
||||||
|
async def hash(self, password: str) -> str:
|
||||||
|
return await anyio.to_thread.run_sync(self._hasher.hash, password, limiter=self._limiter)
|
||||||
|
|
||||||
|
async def verify(self, stored: str, password: str) -> bool:
|
||||||
|
return await anyio.to_thread.run_sync(self._verify, stored, password, limiter=self._limiter)
|
||||||
|
|
||||||
|
async def verify_dummy(self) -> None:
|
||||||
|
await self.verify(self._leurre, "")
|
||||||
|
|
||||||
|
def needs_rehash(self, stored: str) -> bool:
|
||||||
|
try:
|
||||||
|
return self._hasher.check_needs_rehash(stored)
|
||||||
|
except _ERREURS_DE_VERIFICATION:
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _verify(self, stored: str, password: str) -> bool:
|
||||||
|
try:
|
||||||
|
return self._hasher.verify(stored, password)
|
||||||
|
except _ERREURS_DE_VERIFICATION:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def build_hasher(
|
||||||
|
*,
|
||||||
|
time_cost: int,
|
||||||
|
memory_cost_kib: int,
|
||||||
|
parallelism: int,
|
||||||
|
max_concurrency: int,
|
||||||
|
) -> Argon2Hasher:
|
||||||
|
return Argon2Hasher(
|
||||||
|
PasswordHasher(
|
||||||
|
time_cost=time_cost,
|
||||||
|
memory_cost=memory_cost_kib,
|
||||||
|
parallelism=parallelism,
|
||||||
|
hash_len=32,
|
||||||
|
salt_len=16,
|
||||||
|
),
|
||||||
|
max_concurrency=max_concurrency,
|
||||||
|
)
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# Pourquoi : `RedactingFilter` est la troisième ligne de défense, pas la première. La première
|
||||||
|
# est de ne jamais passer un secret au logger, la deuxième de ne jamais mettre un jeton dans
|
||||||
|
# une URL, que le journal d'accès enregistrerait de toute façon. Le filtre rattrape l'erreur
|
||||||
|
# que personne n'a relue, notamment l'écho SQL quand `debug` est actif.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from logging.config import dictConfig
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
from app.core.config import Settings
|
||||||
|
|
||||||
|
CAVIARDAGE: Final = "[expurgé]"
|
||||||
|
|
||||||
|
REMPLACEMENTS: Final[tuple[tuple[re.Pattern[str], str], ...]] = (
|
||||||
|
(re.compile(r"Bearer\s+[A-Za-z0-9._~+/-]{20,}=*"), f"Bearer {CAVIARDAGE}"),
|
||||||
|
(re.compile(r"eyJ[A-Za-z0-9._-]{20,}"), CAVIARDAGE),
|
||||||
|
(re.compile(r"\$argon2[a-z0-9]*\$\S+"), CAVIARDAGE),
|
||||||
|
(
|
||||||
|
re.compile(r'("?(?:password|mot_de_passe|secret|token)"?\s*[:=]\s*")[^"]*(")'),
|
||||||
|
rf"\1{CAVIARDAGE}\2",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
re.compile(r"((?:password|mot_de_passe|secret|token)[A-Za-z_]*=)[^&\s;\"]+"),
|
||||||
|
rf"\1{CAVIARDAGE}",
|
||||||
|
),
|
||||||
|
(re.compile(r"(ev_refresh=)[^;\s]+"), rf"\1{CAVIARDAGE}"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def redact(message: str) -> str:
|
||||||
|
for motif, remplacement in REMPLACEMENTS:
|
||||||
|
message = motif.sub(remplacement, message)
|
||||||
|
return message
|
||||||
|
|
||||||
|
|
||||||
|
class RedactingFilter(logging.Filter):
|
||||||
|
def filter(self, record: logging.LogRecord) -> bool:
|
||||||
|
message = record.getMessage()
|
||||||
|
expurge = redact(message)
|
||||||
|
if expurge != message:
|
||||||
|
record.msg = expurge
|
||||||
|
record.args = ()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def configure_logging(settings: Settings) -> None:
|
||||||
|
formatter = "json" if settings.is_production else "console"
|
||||||
|
dictConfig(
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"disable_existing_loggers": False,
|
||||||
|
"filters": {
|
||||||
|
"redaction": {"()": "app.core.logging.RedactingFilter"},
|
||||||
|
},
|
||||||
|
"formatters": {
|
||||||
|
"console": {
|
||||||
|
"format": "%(asctime)s %(levelname)-8s %(name)s %(message)s",
|
||||||
|
},
|
||||||
|
"json": {
|
||||||
|
"()": "pythonjsonlogger.json.JsonFormatter",
|
||||||
|
"format": "%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"handlers": {
|
||||||
|
"default": {
|
||||||
|
"class": "logging.StreamHandler",
|
||||||
|
"formatter": formatter,
|
||||||
|
"filters": ["redaction"],
|
||||||
|
"stream": "ext://sys.stdout",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"root": {"handlers": ["default"], "level": settings.log_level},
|
||||||
|
"loggers": {
|
||||||
|
"uvicorn": {
|
||||||
|
"handlers": ["default"],
|
||||||
|
"level": settings.log_level,
|
||||||
|
"propagate": False,
|
||||||
|
},
|
||||||
|
"uvicorn.access": {
|
||||||
|
"handlers": ["default"],
|
||||||
|
"level": settings.log_level,
|
||||||
|
"propagate": False,
|
||||||
|
},
|
||||||
|
"sqlalchemy.engine": {"level": "WARNING"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_logger(name: str) -> logging.Logger:
|
||||||
|
return logging.getLogger(name)
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Pourquoi : tout le code métier dépend de `Principal` et jamais du modèle ORM ni des claims
|
||||||
|
# du jeton. C'est ce qui garde la bascule vers un fournisseur OIDC locale à
|
||||||
|
# `get_current_principal()` et à `AuthService.authenticate()`, au lieu de la répandre dans
|
||||||
|
# chaque endpoint.
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Principal:
|
||||||
|
id: UUID
|
||||||
|
email: str
|
||||||
|
role: Role
|
||||||
|
kind: AccountKind
|
||||||
|
must_change_password: bool
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from enum import StrEnum
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
|
||||||
|
class Role(StrEnum):
|
||||||
|
# Contrainte : ces valeurs voyagent en base, en JSON et dans les jetons. Elles restent
|
||||||
|
# en ASCII, contrairement au libellé « opérateur » affiché à l'utilisateur.
|
||||||
|
LECTEUR = "lecteur"
|
||||||
|
OPERATEUR = "operateur"
|
||||||
|
ADMIN = "admin"
|
||||||
|
|
||||||
|
|
||||||
|
class AccountKind(StrEnum):
|
||||||
|
HUMAIN = "human"
|
||||||
|
SERVICE = "service"
|
||||||
|
|
||||||
|
|
||||||
|
ROLE_RANK: Final[dict[Role, int]] = {
|
||||||
|
Role.LECTEUR: 0,
|
||||||
|
Role.OPERATEUR: 1,
|
||||||
|
Role.ADMIN: 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def has_at_least(actual: Role, required: Role) -> bool:
|
||||||
|
return ROLE_RANK[actual] >= ROLE_RANK[required]
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# Piège : `decode_access_token()` porte trois barrières indépendantes, et retirer l'une
|
||||||
|
# d'elles ne casse aucun test évident. L'algorithme est épinglé, sinon un jeton forgé en
|
||||||
|
# `alg: none` passerait. L'audience et l'émetteur sont vérifiés, sinon un jeton émis pour
|
||||||
|
# un autre service serait accepté. Le claim `typ` est comparé, sinon un jeton de
|
||||||
|
# rafraîchissement servirait de jeton d'accès, ce qui transformerait une fenêtre de
|
||||||
|
# 15 minutes en fenêtre de 7 jours.
|
||||||
|
# Contrainte : ce module ne lit jamais `get_settings()`, qui est mis en cache par
|
||||||
|
# `lru_cache` et se contaminerait entre tests. Tout paramètre arrive par `TokenPolicy`.
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import secrets
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from typing import Final
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
import jwt
|
||||||
|
|
||||||
|
ACCESS_TOKEN_TYPE: Final = "access" # noqa: S105
|
||||||
|
REFRESH_SECRET_BYTES: Final = 32
|
||||||
|
|
||||||
|
_ALGORITHME: Final = "HS256"
|
||||||
|
_CLAIMS_REQUIS: Final = ["iss", "aud", "sub", "iat", "exp", "jti", "typ", "role", "kind"]
|
||||||
|
|
||||||
|
|
||||||
|
class TokenInvalidError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TokenExpiredError(TokenInvalidError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class TokenPolicy:
|
||||||
|
secret: str
|
||||||
|
issuer: str
|
||||||
|
audience: str
|
||||||
|
access_ttl: timedelta
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class AccessClaims:
|
||||||
|
subject: UUID
|
||||||
|
role: str
|
||||||
|
kind: str
|
||||||
|
token_id: UUID
|
||||||
|
issued_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
def encode_access_token(
|
||||||
|
policy: TokenPolicy,
|
||||||
|
*,
|
||||||
|
subject: UUID,
|
||||||
|
role: str,
|
||||||
|
kind: str,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> str:
|
||||||
|
emis_a = now or datetime.now(UTC)
|
||||||
|
return jwt.encode(
|
||||||
|
{
|
||||||
|
"iss": policy.issuer,
|
||||||
|
"aud": policy.audience,
|
||||||
|
"sub": str(subject),
|
||||||
|
"iat": emis_a,
|
||||||
|
"exp": emis_a + policy.access_ttl,
|
||||||
|
"jti": str(uuid4()),
|
||||||
|
"typ": ACCESS_TOKEN_TYPE,
|
||||||
|
"role": role,
|
||||||
|
"kind": kind,
|
||||||
|
},
|
||||||
|
policy.secret,
|
||||||
|
algorithm=_ALGORITHME,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_access_token(policy: TokenPolicy, token: str) -> AccessClaims:
|
||||||
|
try:
|
||||||
|
charge = jwt.decode(
|
||||||
|
token,
|
||||||
|
policy.secret,
|
||||||
|
algorithms=[_ALGORITHME],
|
||||||
|
audience=policy.audience,
|
||||||
|
issuer=policy.issuer,
|
||||||
|
options={"require": _CLAIMS_REQUIS},
|
||||||
|
)
|
||||||
|
except jwt.ExpiredSignatureError as erreur:
|
||||||
|
raise TokenExpiredError("Jeton expiré") from erreur
|
||||||
|
except jwt.InvalidTokenError as erreur:
|
||||||
|
raise TokenInvalidError("Jeton invalide") from erreur
|
||||||
|
|
||||||
|
if charge["typ"] != ACCESS_TOKEN_TYPE:
|
||||||
|
raise TokenInvalidError("Type de jeton inattendu")
|
||||||
|
|
||||||
|
try:
|
||||||
|
sujet = UUID(charge["sub"])
|
||||||
|
identifiant = UUID(charge["jti"])
|
||||||
|
except (AttributeError, TypeError, ValueError) as erreur:
|
||||||
|
raise TokenInvalidError("Identifiants du jeton illisibles") from erreur
|
||||||
|
|
||||||
|
return AccessClaims(
|
||||||
|
subject=sujet,
|
||||||
|
role=str(charge["role"]),
|
||||||
|
kind=str(charge["kind"]),
|
||||||
|
token_id=identifiant,
|
||||||
|
issued_at=datetime.fromtimestamp(charge["iat"], tz=UTC),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_refresh_secret() -> str:
|
||||||
|
return secrets.token_urlsafe(REFRESH_SECRET_BYTES)
|
||||||
|
|
||||||
|
|
||||||
|
# SHA-256 nu, pas Argon2id : 256 bits de CSPRNG n'ont ni dictionnaire ni préimage atteignable,
|
||||||
|
# et une KDF lente coûterait 17 ms à chaque rafraîchissement pour aucun gain.
|
||||||
|
def fingerprint_refresh(secret: str) -> bytes:
|
||||||
|
return hashlib.sha256(secret.encode("utf-8")).digest()
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
"""Base déclarative commune à tous les modèles."""
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import (
|
||||||
|
AsyncEngine,
|
||||||
|
AsyncSession,
|
||||||
|
async_sessionmaker,
|
||||||
|
create_async_engine,
|
||||||
|
)
|
||||||
|
|
||||||
|
from app.core.config import get_settings
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_engine() -> AsyncEngine:
|
||||||
|
settings = get_settings()
|
||||||
|
return create_async_engine(
|
||||||
|
settings.database_url,
|
||||||
|
echo=settings.debug,
|
||||||
|
pool_pre_ping=True,
|
||||||
|
pool_size=settings.database_pool_size,
|
||||||
|
max_overflow=settings.database_max_overflow,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_session_factory() -> async_sessionmaker[AsyncSession]:
|
||||||
|
return async_sessionmaker(get_engine(), class_=AsyncSession, expire_on_commit=False)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_session() -> AsyncIterator[AsyncSession]:
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
yield session
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import Depends, FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from prometheus_fastapi_instrumentator import Instrumentator
|
||||||
|
|
||||||
|
from app.api.errors import register_error_handlers
|
||||||
|
from app.api.middleware import SecurityHeadersMiddleware
|
||||||
|
from app.api.openapi import DESCRIPTION, SUMMARY, TAGS
|
||||||
|
from app.api.security import require_metrics_token
|
||||||
|
from app.api.v1.router import api_router
|
||||||
|
from app.core.config import Settings, get_settings
|
||||||
|
from app.core.logging import configure_logging, get_logger
|
||||||
|
from app.db.session import get_engine
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
METHODES_AUTORISEES = ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"]
|
||||||
|
EN_TETES_AUTORISES = ["Authorization", "Content-Type"]
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||||
|
settings = get_settings()
|
||||||
|
logger.info(
|
||||||
|
"Démarrage de %s %s en environnement %s", settings.name, settings.version, settings.env
|
||||||
|
)
|
||||||
|
yield
|
||||||
|
await get_engine().dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||||
|
resolved = settings or get_settings()
|
||||||
|
configure_logging(resolved)
|
||||||
|
|
||||||
|
documentee = resolved.api_docs_are_exposed
|
||||||
|
application = FastAPI(
|
||||||
|
title=resolved.name,
|
||||||
|
version=resolved.version,
|
||||||
|
summary=SUMMARY,
|
||||||
|
description=DESCRIPTION,
|
||||||
|
openapi_tags=TAGS,
|
||||||
|
debug=resolved.debug,
|
||||||
|
lifespan=lifespan,
|
||||||
|
docs_url="/docs" if documentee else None,
|
||||||
|
redoc_url="/redoc" if documentee else None,
|
||||||
|
openapi_url="/openapi.json" if documentee else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
application.add_middleware(SecurityHeadersMiddleware)
|
||||||
|
|
||||||
|
if resolved.allowed_origins:
|
||||||
|
# Méthodes et en-têtes listés plutôt que joker : avec `allow_credentials`, la liste
|
||||||
|
# d'origines devient l'unique contrôle, autant documenter le contrat exact.
|
||||||
|
application.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=resolved.allowed_origins,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=METHODES_AUTORISEES,
|
||||||
|
allow_headers=EN_TETES_AUTORISES,
|
||||||
|
expose_headers=["Retry-After"],
|
||||||
|
max_age=600,
|
||||||
|
)
|
||||||
|
|
||||||
|
register_error_handlers(application)
|
||||||
|
|
||||||
|
Instrumentator().instrument(application).expose(
|
||||||
|
application,
|
||||||
|
endpoint="/metrics",
|
||||||
|
include_in_schema=False,
|
||||||
|
dependencies=[Depends(require_metrics_token)],
|
||||||
|
)
|
||||||
|
application.include_router(api_router, prefix=resolved.api_prefix)
|
||||||
|
|
||||||
|
# Piège : sans cette surcharge, une configuration passée à `create_app()` ne piloterait
|
||||||
|
# que la construction, et les dépendances continueraient de lire `get_settings()` depuis
|
||||||
|
# l'environnement. Un test « en production » ne testerait alors pas la production.
|
||||||
|
if settings is not None:
|
||||||
|
application.dependency_overrides[get_settings] = lambda: resolved
|
||||||
|
|
||||||
|
return application
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Piège : tout modèle absent de ce module reste invisible de `alembic revision
|
||||||
|
# --autogenerate`, qui générerait alors un drop de sa table.
|
||||||
|
|
||||||
|
from app.models.audit_log import AuditLog
|
||||||
|
from app.models.energy import Alert, Dataset, Prediction, Reading, Recommendation, Site
|
||||||
|
from app.models.login_attempt import LoginAttempt
|
||||||
|
from app.models.refresh_token import RefreshToken
|
||||||
|
from app.models.user import AppUser
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Alert",
|
||||||
|
"AppUser",
|
||||||
|
"AuditLog",
|
||||||
|
"Dataset",
|
||||||
|
"LoginAttempt",
|
||||||
|
"Prediction",
|
||||||
|
"Reading",
|
||||||
|
"Recommendation",
|
||||||
|
"RefreshToken",
|
||||||
|
"Site",
|
||||||
|
]
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# Pourquoi : `actor_id` ne porte volontairement aucune clé étrangère. Une contrainte
|
||||||
|
# `ON DELETE SET NULL` déclencherait un UPDATE que le déclencheur d'ajout seul refuserait, donc
|
||||||
|
# la suppression d'un compte échouerait ; une contrainte `NO ACTION` interdirait toute
|
||||||
|
# suppression. `actor_email` et `actor_role` sont dénormalisés pour la même raison : le journal
|
||||||
|
# dit ce qui était vrai au moment de l'acte, pas ce qui est vrai aujourd'hui.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, CheckConstraint, DateTime, Identity, Index, Text, func
|
||||||
|
from sqlalchemy.dialects.postgresql import INET, JSONB
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class AuditOutcome(StrEnum):
|
||||||
|
SUCCES = "success"
|
||||||
|
ECHEC = "failure"
|
||||||
|
|
||||||
|
|
||||||
|
class AuditAction(StrEnum):
|
||||||
|
COMPTE_CREE = "user.created"
|
||||||
|
COMPTE_ROLE_CHANGE = "user.role_changed"
|
||||||
|
COMPTE_DESACTIVE = "user.disabled"
|
||||||
|
COMPTE_ACTIVE = "user.enabled"
|
||||||
|
COMPTE_MOT_DE_PASSE_REINITIALISE = "user.password_reset_by_admin"
|
||||||
|
COMPTE_MOT_DE_PASSE_CHANGE = "user.password_changed"
|
||||||
|
REFRESH_REUTILISE = "auth.refresh_reuse_detected"
|
||||||
|
SESSIONS_REVOQUEES = "auth.all_sessions_revoked"
|
||||||
|
LIMITE_PAR_IDENTIFIANT = "auth.identifier_throttled"
|
||||||
|
ADMIN_AMORCE = "bootstrap.admin_created"
|
||||||
|
|
||||||
|
|
||||||
|
ISSUES_AUTORISEES = ", ".join(f"'{issue.value}'" for issue in AuditOutcome)
|
||||||
|
|
||||||
|
|
||||||
|
class AuditLog(Base):
|
||||||
|
__tablename__ = "audit_log"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint(f"outcome in ({ISSUES_AUTORISEES})", name="ck_audit_log_outcome"),
|
||||||
|
Index("ix_audit_log_date", "occurred_at"),
|
||||||
|
Index("ix_audit_log_action_date", "action", "occurred_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, Identity(always=True), primary_key=True)
|
||||||
|
occurred_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
actor_id: Mapped[uuid.UUID | None] = mapped_column(PG_UUID(as_uuid=True), nullable=True)
|
||||||
|
actor_email: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
actor_role: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
action: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
target_type: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
target_id: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
outcome: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
client_ip: Mapped[str | None] = mapped_column(INET, nullable=True)
|
||||||
|
user_agent: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
detail: Mapped[dict[str, Any]] = mapped_column(
|
||||||
|
JSONB, nullable=False, server_default=func.jsonb_build_object()
|
||||||
|
)
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""Tables du modèle de données EnerVision (CSV, API Mock et résultats ML)."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import (
|
||||||
|
BigInteger,
|
||||||
|
Boolean,
|
||||||
|
CheckConstraint,
|
||||||
|
DateTime,
|
||||||
|
Double,
|
||||||
|
ForeignKey,
|
||||||
|
ForeignKeyConstraint,
|
||||||
|
Index,
|
||||||
|
Integer,
|
||||||
|
Numeric,
|
||||||
|
String,
|
||||||
|
Text,
|
||||||
|
UniqueConstraint,
|
||||||
|
func,
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Dataset(Base):
|
||||||
|
__tablename__ = "dataset"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("dataset_id > 0", name="ck_dataset_positive_id"),
|
||||||
|
UniqueConstraint("archive_sha256", name="uq_dataset_archive_sha256"),
|
||||||
|
)
|
||||||
|
|
||||||
|
dataset_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||||
|
dataset_name: Mapped[str] = mapped_column(Text)
|
||||||
|
archive_sha256: Mapped[str] = mapped_column(String(64))
|
||||||
|
storage_uri: Mapped[str] = mapped_column(Text)
|
||||||
|
source_timezone: Mapped[str | None] = mapped_column(Text)
|
||||||
|
# "metadata" est réservé par SQLAlchemy ; le nom SQL reste inchangé.
|
||||||
|
dataset_metadata: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB(none_as_null=True))
|
||||||
|
|
||||||
|
|
||||||
|
class Site(Base):
|
||||||
|
__tablename__ = "site"
|
||||||
|
|
||||||
|
site_id: Mapped[str] = mapped_column(Text, primary_key=True)
|
||||||
|
site_name: Mapped[str] = mapped_column(Text)
|
||||||
|
site_type: Mapped[str] = mapped_column(Text)
|
||||||
|
location: Mapped[str | None] = mapped_column(Text)
|
||||||
|
capacity_kw: Mapped[float | None] = mapped_column(Double)
|
||||||
|
status: Mapped[str | None] = mapped_column(Text)
|
||||||
|
|
||||||
|
|
||||||
|
class Reading(Base):
|
||||||
|
__tablename__ = "reading"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint(
|
||||||
|
"source IN ('csv', 'api_current', 'api_history')", name="ck_reading_source"
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"(source = 'csv' AND dataset_id IS NOT NULL) OR "
|
||||||
|
"(source IN ('api_current', 'api_history') AND dataset_id IS NULL)",
|
||||||
|
name="ck_reading_dataset_source",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"data_quality IS NULL OR data_quality IN ('good', 'partial', 'degraded', 'critical')",
|
||||||
|
name="ck_reading_quality",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"(imputed_values IS NULL AND imputation_method IS NULL) OR "
|
||||||
|
"(imputed_values IS NOT NULL AND imputation_method IS NOT NULL)",
|
||||||
|
name="ck_reading_imputation",
|
||||||
|
),
|
||||||
|
Index("ix_reading_site_timestamp", "site_id", "timestamp"),
|
||||||
|
Index("ix_reading_dataset_id", "dataset_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
reading_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||||
|
site_id: Mapped[str] = mapped_column(
|
||||||
|
Text, ForeignKey("site.site_id", name="fk_reading_site", ondelete="RESTRICT")
|
||||||
|
)
|
||||||
|
timestamp: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True)
|
||||||
|
source: Mapped[str] = mapped_column(Text)
|
||||||
|
dataset_id: Mapped[int | None] = mapped_column(
|
||||||
|
BigInteger,
|
||||||
|
ForeignKey("dataset.dataset_id", name="fk_reading_dataset", ondelete="RESTRICT"),
|
||||||
|
)
|
||||||
|
consumption_kw: Mapped[float | None] = mapped_column(Double)
|
||||||
|
consumption_kwh: Mapped[float | None] = mapped_column(Double)
|
||||||
|
consumption_euros: Mapped[Decimal | None] = mapped_column(Numeric(14, 2))
|
||||||
|
voltage_v: Mapped[float | None] = mapped_column(Double)
|
||||||
|
current_a: Mapped[float | None] = mapped_column(Double)
|
||||||
|
power_factor: Mapped[float | None] = mapped_column(Double)
|
||||||
|
temperature_celsius: Mapped[float | None] = mapped_column(Double)
|
||||||
|
humidity_percent: Mapped[float | None] = mapped_column(Double)
|
||||||
|
solar_irradiance_wm2: Mapped[float | None] = mapped_column(Double)
|
||||||
|
is_working_hours: Mapped[bool | None] = mapped_column(Boolean)
|
||||||
|
data_quality: Mapped[str | None] = mapped_column(Text)
|
||||||
|
null_reasons: Mapped[list[str] | None] = mapped_column(ARRAY(Text))
|
||||||
|
imputed_values: Mapped[dict[str, Any] | None] = mapped_column(JSONB(none_as_null=True))
|
||||||
|
imputation_method: Mapped[str | None] = mapped_column(Text)
|
||||||
|
ingested_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now()
|
||||||
|
)
|
||||||
|
raw_data: Mapped[dict[str, Any]] = mapped_column(JSONB(none_as_null=True))
|
||||||
|
|
||||||
|
|
||||||
|
Index(
|
||||||
|
"uq_reading_source",
|
||||||
|
Reading.site_id,
|
||||||
|
Reading.timestamp,
|
||||||
|
Reading.source,
|
||||||
|
func.coalesce(Reading.dataset_id, text("0")),
|
||||||
|
unique=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Prediction(Base):
|
||||||
|
__tablename__ = "prediction"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("prediction_id", "site_id", name="uq_prediction_id_site"),
|
||||||
|
Index("ix_prediction_site_target", "site_id", "target_at"),
|
||||||
|
CheckConstraint(
|
||||||
|
"target_metric IN ('consumption_kwh', 'consumption_kw')",
|
||||||
|
name="ck_prediction_metric",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"period_minutes IS NULL OR period_minutes > 0", name="ck_prediction_period"
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"target_metric <> 'consumption_kwh' OR period_minutes IS NOT NULL",
|
||||||
|
name="ck_prediction_energy_period",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"(status = 'available' AND predicted_value IS NOT NULL AND failure_reason IS NULL) OR "
|
||||||
|
"(status IN ('insufficient_data', 'error') AND predicted_value IS NULL "
|
||||||
|
"AND failure_reason IS NOT NULL)",
|
||||||
|
name="ck_prediction_status",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
prediction_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||||
|
site_id: Mapped[str] = mapped_column(
|
||||||
|
Text, ForeignKey("site.site_id", name="fk_prediction_site", ondelete="RESTRICT")
|
||||||
|
)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
target_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||||
|
target_metric: Mapped[str] = mapped_column(Text)
|
||||||
|
period_minutes: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
predicted_value: Mapped[float | None] = mapped_column(Double)
|
||||||
|
model_reference: Mapped[str] = mapped_column(Text)
|
||||||
|
status: Mapped[str] = mapped_column(Text)
|
||||||
|
failure_reason: Mapped[str | None] = mapped_column(Text)
|
||||||
|
|
||||||
|
|
||||||
|
class Alert(Base):
|
||||||
|
__tablename__ = "alert"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("source", "site_id", "source_alert_id", name="uq_alert_source_reference"),
|
||||||
|
Index("ix_alert_site_timestamp", "site_id", "timestamp"),
|
||||||
|
ForeignKeyConstraint(
|
||||||
|
["prediction_id", "site_id"],
|
||||||
|
["prediction.prediction_id", "prediction.site_id"],
|
||||||
|
name="fk_alert_prediction_site",
|
||||||
|
ondelete="RESTRICT",
|
||||||
|
),
|
||||||
|
CheckConstraint("source IN ('api_mock', 'enervision')", name="ck_alert_source"),
|
||||||
|
CheckConstraint(
|
||||||
|
"type IN ('spike', 'threshold', 'anomaly', 'outage', 'sensor')", name="ck_alert_type"
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"severity IN ('low', 'medium', 'high', 'critical')", name="ck_alert_severity"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
alert_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||||
|
source_alert_id: Mapped[str] = mapped_column(Text)
|
||||||
|
site_id: Mapped[str] = mapped_column(
|
||||||
|
Text, ForeignKey("site.site_id", name="fk_alert_site", ondelete="RESTRICT")
|
||||||
|
)
|
||||||
|
source: Mapped[str] = mapped_column(Text)
|
||||||
|
timestamp: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||||
|
type: Mapped[str] = mapped_column(Text)
|
||||||
|
severity: Mapped[str] = mapped_column(Text)
|
||||||
|
message: Mapped[str] = mapped_column(Text)
|
||||||
|
value: Mapped[float | None] = mapped_column(Double)
|
||||||
|
threshold: Mapped[float | None] = mapped_column(Double)
|
||||||
|
metric: Mapped[str | None] = mapped_column(Text)
|
||||||
|
prediction_id: Mapped[int | None] = mapped_column(BigInteger)
|
||||||
|
raw_data: Mapped[dict[str, Any]] = mapped_column(JSONB(none_as_null=True))
|
||||||
|
|
||||||
|
|
||||||
|
class Recommendation(Base):
|
||||||
|
__tablename__ = "recommendation"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("alert_id", "rule_reference", name="uq_recommendation_alert_rule"),
|
||||||
|
)
|
||||||
|
|
||||||
|
recommendation_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||||
|
alert_id: Mapped[int] = mapped_column(
|
||||||
|
BigInteger,
|
||||||
|
ForeignKey("alert.alert_id", name="fk_recommendation_alert", ondelete="RESTRICT"),
|
||||||
|
)
|
||||||
|
action: Mapped[str] = mapped_column(Text)
|
||||||
|
explanation: Mapped[str] = mapped_column(Text)
|
||||||
|
rule_reference: Mapped[str] = mapped_column(Text)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Pourquoi : les tentatives vivent ici et non dans `audit_log`, qui est en ajout seul. Leur
|
||||||
|
# volume est piloté par l'attaquant : une force brute y écrirait des millions de lignes
|
||||||
|
# indestructibles. Cette table-ci se purge, et c'est aussi le compteur de la limitation.
|
||||||
|
# Piège : la tentative est enregistrée même quand l'email est inconnu, sinon le 429 dirait
|
||||||
|
# qu'un compte existe.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, CheckConstraint, DateTime, Identity, Index, String, Text, func
|
||||||
|
from sqlalchemy.dialects.postgresql import INET
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class LoginOutcome(StrEnum):
|
||||||
|
SUCCES = "success"
|
||||||
|
IDENTIFIANTS_INVALIDES = "bad_credentials"
|
||||||
|
LIMITE = "throttled"
|
||||||
|
COMPTE_INDISPONIBLE = "inactive"
|
||||||
|
|
||||||
|
|
||||||
|
ISSUES_AUTORISEES = ", ".join(f"'{issue.value}'" for issue in LoginOutcome)
|
||||||
|
|
||||||
|
|
||||||
|
class LoginAttempt(Base):
|
||||||
|
__tablename__ = "login_attempt"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint(f"outcome in ({ISSUES_AUTORISEES})", name="ck_login_attempt_outcome"),
|
||||||
|
Index("ix_login_attempt_email_date", "email_tried", "occurred_at"),
|
||||||
|
Index("ix_login_attempt_ip_date", "client_ip", "occurred_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, Identity(always=True), primary_key=True)
|
||||||
|
occurred_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
email_tried: Mapped[str] = mapped_column(String(320), nullable=False)
|
||||||
|
client_ip: Mapped[str | None] = mapped_column(INET, nullable=True)
|
||||||
|
outcome: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
user_id: Mapped[uuid.UUID | None] = mapped_column(PG_UUID(as_uuid=True), nullable=True)
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# Pourquoi : un jeton de rafraîchissement est une chaîne opaque, jamais un JWT. Il doit être
|
||||||
|
# révocable, donc cette ligne existe de toute façon ; le JWT n'ajouterait qu'un second chemin de
|
||||||
|
# signature. Surtout, la séparation devient structurelle : un JWT ne figure dans aucune ligne,
|
||||||
|
# une chaîne opaque échoue au décodage. Aucune confusion de type n'est possible.
|
||||||
|
# Piège : `expires_at` est absolu et hérité du prédécesseur à chaque rotation. S'il glissait,
|
||||||
|
# la promesse de sept jours serait fictive et une session active ne finirait jamais.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, LargeBinary, Text, func
|
||||||
|
from sqlalchemy.dialects.postgresql import INET
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class RevocationReason(StrEnum):
|
||||||
|
DECONNEXION = "logout"
|
||||||
|
ROTATION = "rotation"
|
||||||
|
REUTILISATION = "reuse_detected"
|
||||||
|
CHANGEMENT_MOT_DE_PASSE = "password_change"
|
||||||
|
ADMINISTRATION = "admin"
|
||||||
|
|
||||||
|
|
||||||
|
MOTIFS_AUTORISES = ", ".join(f"'{motif.value}'" for motif in RevocationReason)
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshToken(Base):
|
||||||
|
__tablename__ = "refresh_token"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint(
|
||||||
|
f"revoked_reason is null or revoked_reason in ({MOTIFS_AUTORISES})",
|
||||||
|
name="ck_refresh_token_revoked_reason",
|
||||||
|
),
|
||||||
|
Index("ix_refresh_token_family", "family_id"),
|
||||||
|
Index("ix_refresh_token_user", "user_id"),
|
||||||
|
Index(
|
||||||
|
"ix_refresh_token_vivants",
|
||||||
|
"user_id",
|
||||||
|
postgresql_where="revoked_at is null and rotated_at is null",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PG_UUID(as_uuid=True), primary_key=True, server_default=func.gen_random_uuid()
|
||||||
|
)
|
||||||
|
family_id: Mapped[uuid.UUID] = mapped_column(PG_UUID(as_uuid=True), nullable=False)
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PG_UUID(as_uuid=True), ForeignKey("app_user.id", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
token_hash: Mapped[bytes] = mapped_column(LargeBinary, nullable=False, unique=True)
|
||||||
|
issued_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
rotated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
revoked_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
replaced_by: Mapped[uuid.UUID | None] = mapped_column(PG_UUID(as_uuid=True), nullable=True)
|
||||||
|
client_ip: Mapped[str | None] = mapped_column(INET, nullable=True)
|
||||||
|
user_agent: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Contrainte : la table s'appelle `app_user` et non `user`, qui est un mot réservé PostgreSQL,
|
||||||
|
# raccourci de `CURRENT_USER`. Le nom rappelle aussi qu'il s'agit d'un compte applicatif, par
|
||||||
|
# opposition au rôle PostgreSQL qui porte, lui, le cantonnement des accès.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import Boolean, CheckConstraint, DateTime, String, Text, func, text
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
ROLES_AUTORISES = ", ".join(f"'{role.value}'" for role in Role)
|
||||||
|
NATURES_AUTORISEES = ", ".join(f"'{nature.value}'" for nature in AccountKind)
|
||||||
|
|
||||||
|
|
||||||
|
class AppUser(Base):
|
||||||
|
__tablename__ = "app_user"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("email = lower(email)", name="ck_app_user_email_minuscule"),
|
||||||
|
CheckConstraint(f"role in ({ROLES_AUTORISES})", name="ck_app_user_role"),
|
||||||
|
CheckConstraint(f"kind in ({NATURES_AUTORISEES})", name="ck_app_user_kind"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PG_UUID(as_uuid=True), primary_key=True, server_default=func.gen_random_uuid()
|
||||||
|
)
|
||||||
|
email: Mapped[str] = mapped_column(String(320), unique=True, nullable=False)
|
||||||
|
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
role: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
kind: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'human'"))
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||||
|
must_change_password: Mapped[bool] = mapped_column(
|
||||||
|
Boolean, nullable=False, server_default=text("false")
|
||||||
|
)
|
||||||
|
# Une seule colonne couvre le changement de mot de passe, le changement de rôle et la
|
||||||
|
# désactivation : tout jeton émis avant cet instant est périmé.
|
||||||
|
credentials_changed_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
full_name: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()
|
||||||
|
)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.energy import Alert
|
||||||
|
|
||||||
|
|
||||||
|
class AlertRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def list_all(
|
||||||
|
self, *, site_id: str | None = None, severity: str | None = None
|
||||||
|
) -> Sequence[Alert]:
|
||||||
|
requete = select(Alert).order_by(Alert.timestamp.desc(), Alert.alert_id.desc())
|
||||||
|
if site_id is not None:
|
||||||
|
requete = requete.where(Alert.site_id == site_id)
|
||||||
|
if severity is not None:
|
||||||
|
requete = requete.where(Alert.severity == severity)
|
||||||
|
return (await self._session.scalars(requete)).all()
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# Piège : `detail` passe par une liste blanche de clés et jamais par un `dict(**kwargs)`. La
|
||||||
|
# table est en ajout seul : une clé inattendue qui porterait un secret ou une donnée
|
||||||
|
# personnelle ne pourrait plus en être retirée.
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.models.audit_log import AuditAction, AuditLog, AuditOutcome
|
||||||
|
|
||||||
|
CLES_DE_DETAIL_AUTORISEES = frozenset(
|
||||||
|
{
|
||||||
|
"email",
|
||||||
|
"role_avant",
|
||||||
|
"role_apres",
|
||||||
|
"famille",
|
||||||
|
"motif",
|
||||||
|
"source",
|
||||||
|
"sessions_revoquees",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def assemble_detail(brut: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||||
|
if not brut:
|
||||||
|
return {}
|
||||||
|
return {cle: valeur for cle, valeur in brut.items() if cle in CLES_DE_DETAIL_AUTORISEES}
|
||||||
|
|
||||||
|
|
||||||
|
class AuditLogRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def record(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
action: AuditAction,
|
||||||
|
outcome: AuditOutcome = AuditOutcome.SUCCES,
|
||||||
|
actor: Principal | None = None,
|
||||||
|
actor_label: str | None = None,
|
||||||
|
target_type: str | None = None,
|
||||||
|
target_id: str | None = None,
|
||||||
|
client_ip: str | None = None,
|
||||||
|
user_agent: str | None = None,
|
||||||
|
detail: Mapping[str, Any] | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._session.add(
|
||||||
|
AuditLog(
|
||||||
|
actor_id=actor.id if actor else None,
|
||||||
|
actor_email=actor.email if actor else actor_label,
|
||||||
|
actor_role=actor.role.value if actor else None,
|
||||||
|
action=action.value,
|
||||||
|
target_type=target_type,
|
||||||
|
target_id=target_id,
|
||||||
|
outcome=outcome.value,
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
detail=assemble_detail(detail),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Pourquoi : les trois compteurs tiennent en une seule requête, grâce aux clauses FILTER de
|
||||||
|
# PostgreSQL. Trois `count(*)` séparés feraient trois allers-retours sur le chemin critique de
|
||||||
|
# la connexion, qui est justement celui qu'un attaquant martèle.
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from sqlalchemy import and_, func, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.login_attempt import LoginAttempt, LoginOutcome
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class FailureCounts:
|
||||||
|
per_identifier_and_ip: int
|
||||||
|
per_ip: int
|
||||||
|
per_identifier: int
|
||||||
|
|
||||||
|
|
||||||
|
class LoginAttemptRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def record(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
email: str,
|
||||||
|
client_ip: str | None,
|
||||||
|
outcome: LoginOutcome,
|
||||||
|
user_id: UUID | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._session.add(
|
||||||
|
LoginAttempt(
|
||||||
|
email_tried=email.strip().lower(),
|
||||||
|
client_ip=client_ip,
|
||||||
|
outcome=outcome.value,
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def count_recent_failures(
|
||||||
|
self, *, email: str, client_ip: str | None, window_seconds: int
|
||||||
|
) -> FailureCounts:
|
||||||
|
identifiant = email.strip().lower()
|
||||||
|
meme_email = LoginAttempt.email_tried == identifiant
|
||||||
|
meme_ip = LoginAttempt.client_ip == client_ip
|
||||||
|
|
||||||
|
requete = select(
|
||||||
|
func.count().filter(and_(meme_email, meme_ip)),
|
||||||
|
func.count().filter(meme_ip),
|
||||||
|
func.count().filter(meme_email),
|
||||||
|
).where(
|
||||||
|
LoginAttempt.outcome != LoginOutcome.SUCCES.value,
|
||||||
|
LoginAttempt.occurred_at > datetime.now(UTC) - timedelta(seconds=window_seconds),
|
||||||
|
meme_email | meme_ip,
|
||||||
|
)
|
||||||
|
|
||||||
|
par_identifiant_et_ip, par_ip, par_identifiant = (
|
||||||
|
await self._session.execute(requete)
|
||||||
|
).one()
|
||||||
|
return FailureCounts(
|
||||||
|
per_identifier_and_ip=par_identifiant_et_ip,
|
||||||
|
per_ip=par_ip,
|
||||||
|
per_identifier=par_identifiant,
|
||||||
|
)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.energy import Reading
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def latest_by_site(self) -> Sequence[Reading]:
|
||||||
|
# `.distinct(site_id)` compile en `DISTINCT ON (site_id)` sous PostgreSQL : une seule
|
||||||
|
# ligne par site, la plus récente grâce à l'ordre composite qui suit.
|
||||||
|
requete = (
|
||||||
|
select(Reading)
|
||||||
|
.distinct(Reading.site_id)
|
||||||
|
.order_by(Reading.site_id, Reading.timestamp.desc())
|
||||||
|
)
|
||||||
|
return (await self._session.execute(requete)).scalars().all()
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.energy import Recommendation
|
||||||
|
|
||||||
|
|
||||||
|
class RecommendationRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def list_all(self) -> Sequence[Recommendation]:
|
||||||
|
requete = select(Recommendation).order_by(Recommendation.recommendation_id)
|
||||||
|
return (await self._session.scalars(requete)).all()
|
||||||
|
|
||||||
|
async def get_by_id(self, recommendation_id: int) -> Recommendation | None:
|
||||||
|
requete = select(Recommendation).where(
|
||||||
|
Recommendation.recommendation_id == recommendation_id
|
||||||
|
)
|
||||||
|
recommendation: Recommendation | None = await self._session.scalar(requete)
|
||||||
|
return recommendation
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# Piège : `claim_for_rotation()` est une seule instruction. Un SELECT puis un UPDATE
|
||||||
|
# laisseraient une fenêtre où deux onglets réussissent la même rotation. Zéro ligne retournée
|
||||||
|
# signifie donc, sans ambiguïté, que le jeton était déjà tourné, révoqué, expiré ou inconnu, et
|
||||||
|
# c'est `inspect()` qui départage ensuite ces cas.
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from sqlalchemy import func, select, update
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.refresh_token import RefreshToken, RevocationReason
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ClaimedToken:
|
||||||
|
id: UUID
|
||||||
|
family_id: UUID
|
||||||
|
user_id: UUID
|
||||||
|
expires_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshTokenRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def create(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
user_id: UUID,
|
||||||
|
family_id: UUID,
|
||||||
|
token_hash: bytes,
|
||||||
|
expires_at: datetime,
|
||||||
|
client_ip: str | None,
|
||||||
|
user_agent: str | None,
|
||||||
|
) -> RefreshToken:
|
||||||
|
jeton = RefreshToken(
|
||||||
|
user_id=user_id,
|
||||||
|
family_id=family_id,
|
||||||
|
token_hash=token_hash,
|
||||||
|
expires_at=expires_at,
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
)
|
||||||
|
self._session.add(jeton)
|
||||||
|
await self._session.flush()
|
||||||
|
return jeton
|
||||||
|
|
||||||
|
async def claim_for_rotation(self, token_hash: bytes) -> ClaimedToken | None:
|
||||||
|
requete = (
|
||||||
|
update(RefreshToken)
|
||||||
|
.where(
|
||||||
|
RefreshToken.token_hash == token_hash,
|
||||||
|
RefreshToken.rotated_at.is_(None),
|
||||||
|
RefreshToken.revoked_at.is_(None),
|
||||||
|
RefreshToken.expires_at > func.clock_timestamp(),
|
||||||
|
)
|
||||||
|
.values(
|
||||||
|
rotated_at=func.clock_timestamp(),
|
||||||
|
revoked_at=func.clock_timestamp(),
|
||||||
|
revoked_reason=RevocationReason.ROTATION.value,
|
||||||
|
)
|
||||||
|
.returning(
|
||||||
|
RefreshToken.id,
|
||||||
|
RefreshToken.family_id,
|
||||||
|
RefreshToken.user_id,
|
||||||
|
RefreshToken.expires_at,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
ligne = (await self._session.execute(requete)).one_or_none()
|
||||||
|
if ligne is None:
|
||||||
|
return None
|
||||||
|
return ClaimedToken(
|
||||||
|
id=ligne.id,
|
||||||
|
family_id=ligne.family_id,
|
||||||
|
user_id=ligne.user_id,
|
||||||
|
expires_at=ligne.expires_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def inspect(self, token_hash: bytes) -> RefreshToken | None:
|
||||||
|
requete = select(RefreshToken).where(RefreshToken.token_hash == token_hash)
|
||||||
|
return (await self._session.execute(requete)).scalar_one_or_none()
|
||||||
|
|
||||||
|
async def link_replacement(self, ancien_id: UUID, nouveau_id: UUID) -> None:
|
||||||
|
await self._session.execute(
|
||||||
|
update(RefreshToken).where(RefreshToken.id == ancien_id).values(replaced_by=nouveau_id)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def revoke_family(self, family_id: UUID, reason: RevocationReason) -> int:
|
||||||
|
resultat = await self._session.execute(
|
||||||
|
update(RefreshToken)
|
||||||
|
.where(RefreshToken.family_id == family_id, RefreshToken.revoked_at.is_(None))
|
||||||
|
.values(revoked_at=func.clock_timestamp(), revoked_reason=reason.value)
|
||||||
|
.returning(RefreshToken.id)
|
||||||
|
)
|
||||||
|
return len(resultat.all())
|
||||||
|
|
||||||
|
async def revoke_all_for_user(self, user_id: UUID, reason: RevocationReason) -> int:
|
||||||
|
resultat = await self._session.execute(
|
||||||
|
update(RefreshToken)
|
||||||
|
.where(RefreshToken.user_id == user_id, RefreshToken.revoked_at.is_(None))
|
||||||
|
.values(revoked_at=func.clock_timestamp(), revoked_reason=reason.value)
|
||||||
|
.returning(RefreshToken.id)
|
||||||
|
)
|
||||||
|
return len(resultat.all())
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.energy import Site
|
||||||
|
|
||||||
|
|
||||||
|
class SiteRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def list_all(self) -> Sequence[Site]:
|
||||||
|
requete = select(Site).order_by(Site.site_id)
|
||||||
|
return (await self._session.scalars(requete)).all()
|
||||||
|
|
||||||
|
async def get_by_id(self, site_id: str) -> Site | None:
|
||||||
|
requete = select(Site).where(Site.site_id == site_id)
|
||||||
|
site: Site | None = await self._session.scalar(requete)
|
||||||
|
return site
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Piège : `set_role()` et `set_active()` avancent `credentials_changed_at`. C'est ce qui rend
|
||||||
|
# un changement de rôle ou une désactivation effectifs à la requête suivante au lieu d'attendre
|
||||||
|
# l'expiration du jeton d'accès. Une mise à jour qui l'oublierait laisserait 15 minutes de
|
||||||
|
# privilèges périmés.
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from sqlalchemy import func, select, update
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.models.user import AppUser
|
||||||
|
|
||||||
|
|
||||||
|
class UserRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def get_by_email(self, email: str) -> AppUser | None:
|
||||||
|
requete = select(AppUser).where(AppUser.email == email.strip().lower())
|
||||||
|
return (await self._session.execute(requete)).scalar_one_or_none()
|
||||||
|
|
||||||
|
async def get_by_id(self, user_id: UUID) -> AppUser | None:
|
||||||
|
return await self._session.get(AppUser, user_id)
|
||||||
|
|
||||||
|
async def list_all(self) -> Sequence[AppUser]:
|
||||||
|
requete = select(AppUser).order_by(AppUser.email)
|
||||||
|
return (await self._session.execute(requete)).scalars().all()
|
||||||
|
|
||||||
|
async def count_active_admins(self) -> int:
|
||||||
|
requete = (
|
||||||
|
select(func.count())
|
||||||
|
.select_from(AppUser)
|
||||||
|
.where(AppUser.role == Role.ADMIN.value, AppUser.is_active.is_(True))
|
||||||
|
)
|
||||||
|
return (await self._session.execute(requete)).scalar_one()
|
||||||
|
|
||||||
|
async def create(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
email: str,
|
||||||
|
password_hash: str,
|
||||||
|
role: Role,
|
||||||
|
kind: AccountKind = AccountKind.HUMAIN,
|
||||||
|
full_name: str | None = None,
|
||||||
|
must_change_password: bool = False,
|
||||||
|
) -> AppUser:
|
||||||
|
compte = AppUser(
|
||||||
|
email=email.strip().lower(),
|
||||||
|
password_hash=password_hash,
|
||||||
|
role=role.value,
|
||||||
|
kind=kind.value,
|
||||||
|
full_name=full_name,
|
||||||
|
must_change_password=must_change_password,
|
||||||
|
)
|
||||||
|
self._session.add(compte)
|
||||||
|
await self._session.flush()
|
||||||
|
return compte
|
||||||
|
|
||||||
|
async def update_password(
|
||||||
|
self, user_id: UUID, password_hash: str, *, must_change_password: bool
|
||||||
|
) -> None:
|
||||||
|
await self._session.execute(
|
||||||
|
update(AppUser)
|
||||||
|
.where(AppUser.id == user_id)
|
||||||
|
.values(
|
||||||
|
password_hash=password_hash,
|
||||||
|
must_change_password=must_change_password,
|
||||||
|
credentials_changed_at=func.clock_timestamp(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def rehash_password(self, user_id: UUID, password_hash: str) -> None:
|
||||||
|
# Un simple recalcul avec des paramètres Argon2 plus récents ne périme aucun jeton.
|
||||||
|
await self._session.execute(
|
||||||
|
update(AppUser).where(AppUser.id == user_id).values(password_hash=password_hash)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def touch_last_login(self, user_id: UUID) -> None:
|
||||||
|
await self._session.execute(
|
||||||
|
update(AppUser).where(AppUser.id == user_id).values(last_login_at=func.now())
|
||||||
|
)
|
||||||
|
|
||||||
|
async def set_role(self, user_id: UUID, role: Role) -> None:
|
||||||
|
await self._session.execute(
|
||||||
|
update(AppUser)
|
||||||
|
.where(AppUser.id == user_id)
|
||||||
|
.values(role=role.value, credentials_changed_at=func.clock_timestamp())
|
||||||
|
)
|
||||||
|
|
||||||
|
async def set_active(self, user_id: UUID, *, is_active: bool) -> None:
|
||||||
|
await self._session.execute(
|
||||||
|
update(AppUser)
|
||||||
|
.where(AppUser.id == user_id)
|
||||||
|
.values(is_active=is_active, credentials_changed_at=func.clock_timestamp())
|
||||||
|
)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from app.schemas.health import LivenessStatus, ReadinessStatus
|
||||||
|
|
||||||
|
__all__ = ["LivenessStatus", "ReadinessStatus"]
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class AlertType(StrEnum):
|
||||||
|
SPIKE = "spike"
|
||||||
|
THRESHOLD = "threshold"
|
||||||
|
ANOMALY = "anomaly"
|
||||||
|
OUTAGE = "outage"
|
||||||
|
SENSOR = "sensor"
|
||||||
|
|
||||||
|
|
||||||
|
class AlertSeverity(StrEnum):
|
||||||
|
LOW = "low"
|
||||||
|
MEDIUM = "medium"
|
||||||
|
HIGH = "high"
|
||||||
|
CRITICAL = "critical"
|
||||||
|
|
||||||
|
|
||||||
|
class AlertResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
alert_id: int
|
||||||
|
site_id: str
|
||||||
|
timestamp: datetime
|
||||||
|
type: AlertType
|
||||||
|
severity: AlertSeverity
|
||||||
|
message: str
|
||||||
|
value: float | None
|
||||||
|
threshold: float | None
|
||||||
|
metric: str | None
|
||||||
|
prediction_id: int | None
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Contrainte : le mot de passe est borné à 128 caractères. Sans plafond, une chaîne de dix
|
||||||
|
# mégaoctets ferait travailler Argon2 gratuitement, à la charge du serveur.
|
||||||
|
|
||||||
|
from typing import Literal, Self
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
||||||
|
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
|
||||||
|
PASSWORD_MIN_LENGTH = 12
|
||||||
|
PASSWORD_MAX_LENGTH = 128
|
||||||
|
|
||||||
|
|
||||||
|
class LoginRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
password: str = Field(min_length=1, max_length=PASSWORD_MAX_LENGTH)
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordChangeRequest(BaseModel):
|
||||||
|
current_password: str = Field(min_length=1, max_length=PASSWORD_MAX_LENGTH)
|
||||||
|
new_password: str = Field(min_length=PASSWORD_MIN_LENGTH, max_length=PASSWORD_MAX_LENGTH)
|
||||||
|
|
||||||
|
|
||||||
|
class PrincipalResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: UUID
|
||||||
|
email: str
|
||||||
|
role: Role
|
||||||
|
kind: AccountKind
|
||||||
|
must_change_password: bool
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_principal(cls, principal: Principal) -> Self:
|
||||||
|
return cls.model_validate(principal)
|
||||||
|
|
||||||
|
|
||||||
|
class TokenResponse(BaseModel):
|
||||||
|
access_token: str
|
||||||
|
token_type: Literal["bearer"] = "bearer" # noqa: S105
|
||||||
|
expires_in: int
|
||||||
|
principal: PrincipalResponse
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Piège : ces modèles ne décrivent rien, ils publient. Ce sont eux que Swagger montre, donc ils
|
||||||
|
# doivent suivre `validation_error_handler()` et `unhandled_error_handler()` d'`app/api/errors.py`
|
||||||
|
# à la lettre. Un champ renommé là-bas sans l'être ici rend la documentation fausse en silence.
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorResponse(BaseModel):
|
||||||
|
detail: str
|
||||||
|
|
||||||
|
|
||||||
|
class FieldError(BaseModel):
|
||||||
|
champ: str
|
||||||
|
type: str
|
||||||
|
|
||||||
|
|
||||||
|
class ValidationErrorResponse(BaseModel):
|
||||||
|
detail: list[FieldError]
|
||||||
|
|
||||||
|
|
||||||
|
class InternalErrorResponse(BaseModel):
|
||||||
|
detail: str
|
||||||
|
correlation: str
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class LivenessStatus(BaseModel):
|
||||||
|
status: Literal["ok"]
|
||||||
|
service: str
|
||||||
|
version: str
|
||||||
|
environment: str
|
||||||
|
|
||||||
|
|
||||||
|
# Contrainte : la sonde ne publie pas la version de TimescaleDB. Une version exacte de
|
||||||
|
# composant, servie sans authentification, est de la reconnaissance gratuite pour qui
|
||||||
|
# cherche une CVE. Elle part dans le journal, où elle sert au diagnostic.
|
||||||
|
class ReadinessStatus(BaseModel):
|
||||||
|
status: Literal["ready"]
|
||||||
|
database: Literal["reachable"]
|
||||||
|
timescaledb: Literal["loaded"]
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class RecommendationResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
recommendation_id: int
|
||||||
|
alert_id: int
|
||||||
|
action: str
|
||||||
|
explanation: str
|
||||||
|
rule_reference: str
|
||||||
|
created_at: datetime
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class SiteResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
site_id: str
|
||||||
|
site_name: str
|
||||||
|
site_type: str
|
||||||
|
location: str | None
|
||||||
|
capacity_kw: float | None
|
||||||
|
status: str | None
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class SiteSummaryResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
site_id: str
|
||||||
|
site_name: str
|
||||||
|
current_consumption_kw: float | None
|
||||||
|
capacity_kw: float
|
||||||
|
load_percent: float | None
|
||||||
|
data_quality: Literal["good", "partial", "degraded", "critical"]
|
||||||
|
|
||||||
|
|
||||||
|
class StatsSummaryResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
timestamp: datetime
|
||||||
|
total_sites: int
|
||||||
|
total_consumption_kw: float
|
||||||
|
total_capacity_kw: float
|
||||||
|
average_load_percent: float
|
||||||
|
sites: list[SiteSummaryResponse]
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Contrainte : les schémas de lecture et d'écriture sont séparés. Un modèle unique laisserait
|
||||||
|
# passer `role` ou `is_active` depuis un corps de requête, et renverrait `password_hash` en
|
||||||
|
# réponse. C'est l'attribution de masse, API3 du top 10 API.
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
||||||
|
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
|
||||||
|
|
||||||
|
class UserCreateRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
role: Role
|
||||||
|
full_name: str | None = Field(default=None, max_length=200)
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdateRequest(BaseModel):
|
||||||
|
role: Role | None = None
|
||||||
|
is_active: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class UserResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: UUID
|
||||||
|
email: str
|
||||||
|
role: Role
|
||||||
|
kind: AccountKind
|
||||||
|
is_active: bool
|
||||||
|
must_change_password: bool
|
||||||
|
full_name: str | None
|
||||||
|
last_login_at: datetime | None
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class TemporaryPasswordResponse(BaseModel):
|
||||||
|
# Affiché une seule fois : l'empreinte seule est conservée côté serveur.
|
||||||
|
user: UserResponse
|
||||||
|
temporary_password: str
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from app.models.energy import Alert
|
||||||
|
from app.repositories.alert import AlertRepository
|
||||||
|
|
||||||
|
|
||||||
|
class AlertService:
|
||||||
|
def __init__(self, *, alerts: AlertRepository) -> None:
|
||||||
|
self._alerts = alerts
|
||||||
|
|
||||||
|
async def list_all(
|
||||||
|
self, *, site_id: str | None = None, severity: str | None = None
|
||||||
|
) -> Sequence[Alert]:
|
||||||
|
return await self._alerts.list_all(site_id=site_id, severity=severity)
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
# Piège : les compteurs de limitation sont lus AVANT le hachage Argon2. Dans l'autre ordre,
|
||||||
|
# chaque requête rejetée coûterait quand même 17 ms de processeur et 19 Mio de mémoire, et la
|
||||||
|
# protection deviendrait l'amplificateur de déni de service qu'elle est censée empêcher.
|
||||||
|
# Piège : quand l'email est inconnu, `verify_dummy()` consomme le même temps qu'une
|
||||||
|
# vérification réelle. Sans lui, l'écart de temps de réponse est un oracle d'existence.
|
||||||
|
# Piège : la tentative échouée est validée en base AVANT que l'erreur ne soit levée.
|
||||||
|
# `get_session()` ne valide pas de lui-même, donc la preuve disparaîtrait avec la transaction.
|
||||||
|
# Piège : dans `refresh()`, un jeton expiré ne révoque PAS la famille, un jeton déjà tourné si.
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from typing import NoReturn, Protocol
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
from app.core.hashing import Argon2Hasher
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.core.security import (
|
||||||
|
TokenPolicy,
|
||||||
|
encode_access_token,
|
||||||
|
fingerprint_refresh,
|
||||||
|
generate_refresh_secret,
|
||||||
|
)
|
||||||
|
from app.models.audit_log import AuditAction, AuditOutcome
|
||||||
|
from app.models.login_attempt import LoginOutcome
|
||||||
|
from app.models.refresh_token import RevocationReason
|
||||||
|
from app.repositories.audit_log import AuditLogRepository
|
||||||
|
from app.repositories.login_attempt import LoginAttemptRepository
|
||||||
|
from app.repositories.refresh_token import RefreshTokenRepository
|
||||||
|
from app.repositories.user import UserRepository
|
||||||
|
|
||||||
|
|
||||||
|
class Transaction(Protocol):
|
||||||
|
async def commit(self) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class AuthError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidCredentialsError(AuthError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class SessionRejectedError(AuthError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class RateLimitedError(AuthError):
|
||||||
|
def __init__(self, retry_after: int) -> None:
|
||||||
|
super().__init__("Trop de tentatives")
|
||||||
|
self.retry_after = retry_after
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class LoginPolicy:
|
||||||
|
window_seconds: int
|
||||||
|
max_failures_per_identifier_and_ip: int
|
||||||
|
max_failures_per_ip: int
|
||||||
|
max_failures_per_identifier: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class AuthenticatedSession:
|
||||||
|
principal: Principal
|
||||||
|
access_token: str
|
||||||
|
expires_in: int
|
||||||
|
refresh_secret: str
|
||||||
|
|
||||||
|
|
||||||
|
class AuthService:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
users: UserRepository,
|
||||||
|
attempts: LoginAttemptRepository,
|
||||||
|
refresh_tokens: RefreshTokenRepository,
|
||||||
|
audit: AuditLogRepository,
|
||||||
|
hasher: Argon2Hasher,
|
||||||
|
transaction: Transaction,
|
||||||
|
token_policy: TokenPolicy,
|
||||||
|
login_policy: LoginPolicy,
|
||||||
|
refresh_ttl: timedelta,
|
||||||
|
) -> None:
|
||||||
|
self._users = users
|
||||||
|
self._attempts = attempts
|
||||||
|
self._refresh = refresh_tokens
|
||||||
|
self._audit = audit
|
||||||
|
self._hasher = hasher
|
||||||
|
self._transaction = transaction
|
||||||
|
self._token_policy = token_policy
|
||||||
|
self._login_policy = login_policy
|
||||||
|
self._refresh_ttl = refresh_ttl
|
||||||
|
|
||||||
|
async def authenticate(
|
||||||
|
self, *, email: str, password: str, client_ip: str | None, user_agent: str | None
|
||||||
|
) -> AuthenticatedSession:
|
||||||
|
await self._refuse_si_limite(email=email, client_ip=client_ip, user_agent=user_agent)
|
||||||
|
|
||||||
|
compte = await self._users.get_by_email(email)
|
||||||
|
if compte is None:
|
||||||
|
await self._hasher.verify_dummy()
|
||||||
|
await self._echoue(email, client_ip, LoginOutcome.IDENTIFIANTS_INVALIDES)
|
||||||
|
|
||||||
|
if not await self._hasher.verify(compte.password_hash, password):
|
||||||
|
await self._echoue(
|
||||||
|
email, client_ip, LoginOutcome.IDENTIFIANTS_INVALIDES, user_id=compte.id
|
||||||
|
)
|
||||||
|
|
||||||
|
if not compte.is_active or compte.kind != AccountKind.HUMAIN.value:
|
||||||
|
await self._echoue(
|
||||||
|
email, client_ip, LoginOutcome.COMPTE_INDISPONIBLE, user_id=compte.id
|
||||||
|
)
|
||||||
|
|
||||||
|
if self._hasher.needs_rehash(compte.password_hash):
|
||||||
|
await self._users.rehash_password(compte.id, await self._hasher.hash(password))
|
||||||
|
|
||||||
|
await self._users.touch_last_login(compte.id)
|
||||||
|
await self._attempts.record(
|
||||||
|
email=email, client_ip=client_ip, outcome=LoginOutcome.SUCCES, user_id=compte.id
|
||||||
|
)
|
||||||
|
secret = await self._ouvre_une_famille(
|
||||||
|
user_id=compte.id, client_ip=client_ip, user_agent=user_agent
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
|
||||||
|
return self._session(self._en_principal(compte), secret)
|
||||||
|
|
||||||
|
async def refresh(
|
||||||
|
self, *, secret: str, client_ip: str | None, user_agent: str | None
|
||||||
|
) -> AuthenticatedSession:
|
||||||
|
empreinte = fingerprint_refresh(secret)
|
||||||
|
revendique = await self._refresh.claim_for_rotation(empreinte)
|
||||||
|
if revendique is None:
|
||||||
|
await self._traite_rotation_refusee(empreinte, client_ip, user_agent)
|
||||||
|
|
||||||
|
compte = await self._users.get_by_id(revendique.user_id)
|
||||||
|
if compte is None or not compte.is_active:
|
||||||
|
await self._refresh.revoke_family(revendique.family_id, RevocationReason.ADMINISTRATION)
|
||||||
|
await self._transaction.commit()
|
||||||
|
raise SessionRejectedError("Session révoquée")
|
||||||
|
|
||||||
|
nouveau_secret = generate_refresh_secret()
|
||||||
|
nouveau = await self._refresh.create(
|
||||||
|
user_id=revendique.user_id,
|
||||||
|
family_id=revendique.family_id,
|
||||||
|
token_hash=fingerprint_refresh(nouveau_secret),
|
||||||
|
expires_at=revendique.expires_at,
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
)
|
||||||
|
await self._refresh.link_replacement(revendique.id, nouveau.id)
|
||||||
|
await self._transaction.commit()
|
||||||
|
|
||||||
|
return self._session(self._en_principal(compte), nouveau_secret)
|
||||||
|
|
||||||
|
async def logout(self, *, secret: str) -> None:
|
||||||
|
ligne = await self._refresh.inspect(fingerprint_refresh(secret))
|
||||||
|
if ligne is not None:
|
||||||
|
await self._refresh.revoke_family(ligne.family_id, RevocationReason.DECONNEXION)
|
||||||
|
await self._transaction.commit()
|
||||||
|
|
||||||
|
async def change_password(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
principal: Principal,
|
||||||
|
current_password: str,
|
||||||
|
new_password: str,
|
||||||
|
client_ip: str | None,
|
||||||
|
user_agent: str | None,
|
||||||
|
) -> AuthenticatedSession:
|
||||||
|
compte = await self._users.get_by_id(principal.id)
|
||||||
|
if compte is None or not await self._hasher.verify(compte.password_hash, current_password):
|
||||||
|
raise InvalidCredentialsError("Identifiants invalides")
|
||||||
|
|
||||||
|
await self._users.update_password(
|
||||||
|
principal.id, await self._hasher.hash(new_password), must_change_password=False
|
||||||
|
)
|
||||||
|
# Toutes les sessions tombent, puis on en rouvre une : l'appareil courant reste
|
||||||
|
# connecté et tous les autres sont déconnectés.
|
||||||
|
revoquees = await self._refresh.revoke_all_for_user(
|
||||||
|
principal.id, RevocationReason.CHANGEMENT_MOT_DE_PASSE
|
||||||
|
)
|
||||||
|
secret = await self._ouvre_une_famille(
|
||||||
|
user_id=principal.id, client_ip=client_ip, user_agent=user_agent
|
||||||
|
)
|
||||||
|
await self._audit.record(
|
||||||
|
action=AuditAction.COMPTE_MOT_DE_PASSE_CHANGE,
|
||||||
|
actor=principal,
|
||||||
|
target_type="app_user",
|
||||||
|
target_id=str(principal.id),
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
detail={"sessions_revoquees": revoquees},
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
|
||||||
|
rafraichi = await self._users.get_by_id(principal.id)
|
||||||
|
return self._session(self._en_principal(rafraichi or compte), secret)
|
||||||
|
|
||||||
|
async def logout_all(self, principal: Principal) -> int:
|
||||||
|
revoquees = await self._refresh.revoke_all_for_user(
|
||||||
|
principal.id, RevocationReason.DECONNEXION
|
||||||
|
)
|
||||||
|
await self._audit.record(
|
||||||
|
action=AuditAction.SESSIONS_REVOQUEES,
|
||||||
|
actor=principal,
|
||||||
|
detail={"sessions_revoquees": revoquees},
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
return revoquees
|
||||||
|
|
||||||
|
def _session(self, principal: Principal, refresh_secret: str) -> AuthenticatedSession:
|
||||||
|
jeton = encode_access_token(
|
||||||
|
self._token_policy,
|
||||||
|
subject=principal.id,
|
||||||
|
role=principal.role.value,
|
||||||
|
kind=principal.kind.value,
|
||||||
|
)
|
||||||
|
return AuthenticatedSession(
|
||||||
|
principal=principal,
|
||||||
|
access_token=jeton,
|
||||||
|
expires_in=int(self._token_policy.access_ttl.total_seconds()),
|
||||||
|
refresh_secret=refresh_secret,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _en_principal(self, compte: object) -> Principal:
|
||||||
|
return Principal(
|
||||||
|
id=compte.id, # type: ignore[attr-defined]
|
||||||
|
email=compte.email, # type: ignore[attr-defined]
|
||||||
|
role=Role(compte.role), # type: ignore[attr-defined]
|
||||||
|
kind=AccountKind(compte.kind), # type: ignore[attr-defined]
|
||||||
|
must_change_password=compte.must_change_password, # type: ignore[attr-defined]
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _ouvre_une_famille(
|
||||||
|
self, *, user_id: UUID, client_ip: str | None, user_agent: str | None
|
||||||
|
) -> str:
|
||||||
|
secret = generate_refresh_secret()
|
||||||
|
await self._refresh.create(
|
||||||
|
user_id=user_id,
|
||||||
|
family_id=uuid4(),
|
||||||
|
token_hash=fingerprint_refresh(secret),
|
||||||
|
expires_at=datetime.now(UTC) + self._refresh_ttl,
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
)
|
||||||
|
return secret
|
||||||
|
|
||||||
|
async def _traite_rotation_refusee(
|
||||||
|
self, empreinte: bytes, client_ip: str | None, user_agent: str | None
|
||||||
|
) -> NoReturn:
|
||||||
|
ligne = await self._refresh.inspect(empreinte)
|
||||||
|
if ligne is None:
|
||||||
|
raise SessionRejectedError("Session inconnue")
|
||||||
|
|
||||||
|
if ligne.expires_at <= datetime.now(UTC):
|
||||||
|
raise SessionRejectedError("Session expirée")
|
||||||
|
|
||||||
|
# Présenter un jeton déjà tourné est une preuve de compromission, pas un accident : toute
|
||||||
|
# la famille tombe, y compris la session encore vivante du voleur ou de la victime.
|
||||||
|
revoquees = await self._refresh.revoke_family(
|
||||||
|
ligne.family_id, RevocationReason.REUTILISATION
|
||||||
|
)
|
||||||
|
await self._audit.record(
|
||||||
|
action=AuditAction.REFRESH_REUTILISE,
|
||||||
|
outcome=AuditOutcome.ECHEC,
|
||||||
|
target_type="refresh_token",
|
||||||
|
target_id=str(ligne.family_id),
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
detail={"famille": str(ligne.family_id), "sessions_revoquees": revoquees},
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
raise SessionRejectedError("Session révoquée")
|
||||||
|
|
||||||
|
async def _refuse_si_limite(
|
||||||
|
self, *, email: str, client_ip: str | None, user_agent: str | None
|
||||||
|
) -> None:
|
||||||
|
politique = self._login_policy
|
||||||
|
compteurs = await self._attempts.count_recent_failures(
|
||||||
|
email=email, client_ip=client_ip, window_seconds=politique.window_seconds
|
||||||
|
)
|
||||||
|
|
||||||
|
depasse = (
|
||||||
|
compteurs.per_identifier_and_ip >= politique.max_failures_per_identifier_and_ip
|
||||||
|
or compteurs.per_ip >= politique.max_failures_per_ip
|
||||||
|
or compteurs.per_identifier >= politique.max_failures_per_identifier
|
||||||
|
)
|
||||||
|
if not depasse:
|
||||||
|
return
|
||||||
|
|
||||||
|
await self._attempts.record(email=email, client_ip=client_ip, outcome=LoginOutcome.LIMITE)
|
||||||
|
# Un blocage déclenché par l'identifiant seul signe une attaque distribuée : lui seul
|
||||||
|
# mérite une trace durable, les échecs ordinaires restent dans `login_attempt`.
|
||||||
|
if compteurs.per_identifier >= politique.max_failures_per_identifier:
|
||||||
|
await self._audit.record(
|
||||||
|
action=AuditAction.LIMITE_PAR_IDENTIFIANT,
|
||||||
|
outcome=AuditOutcome.ECHEC,
|
||||||
|
actor_label=email.strip().lower(),
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
detail={"motif": "seuil par identifiant depasse"},
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
raise RateLimitedError(politique.window_seconds)
|
||||||
|
|
||||||
|
async def _echoue(
|
||||||
|
self,
|
||||||
|
email: str,
|
||||||
|
client_ip: str | None,
|
||||||
|
outcome: LoginOutcome,
|
||||||
|
*,
|
||||||
|
user_id: UUID | None = None,
|
||||||
|
) -> NoReturn:
|
||||||
|
await self._attempts.record(
|
||||||
|
email=email, client_ip=client_ip, outcome=outcome, user_id=user_id
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
raise InvalidCredentialsError("Identifiants invalides")
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from app.models.energy import Recommendation
|
||||||
|
from app.repositories.recommendation import RecommendationRepository
|
||||||
|
|
||||||
|
|
||||||
|
class RecommendationError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class RecommendationNotFoundError(RecommendationError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class RecommendationService:
|
||||||
|
def __init__(self, *, recommendations: RecommendationRepository) -> None:
|
||||||
|
self._recommendations = recommendations
|
||||||
|
|
||||||
|
async def list_all(self) -> Sequence[Recommendation]:
|
||||||
|
return await self._recommendations.list_all()
|
||||||
|
|
||||||
|
async def get_by_id(self, recommendation_id: int) -> Recommendation:
|
||||||
|
recommendation = await self._recommendations.get_by_id(recommendation_id)
|
||||||
|
if recommendation is None:
|
||||||
|
raise RecommendationNotFoundError(recommendation_id)
|
||||||
|
return recommendation
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from app.models.energy import Site
|
||||||
|
from app.repositories.site import SiteRepository
|
||||||
|
|
||||||
|
|
||||||
|
class SiteError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class SiteNotFoundError(SiteError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class SiteService:
|
||||||
|
def __init__(self, *, sites: SiteRepository) -> None:
|
||||||
|
self._sites = sites
|
||||||
|
|
||||||
|
async def list_all(self) -> Sequence[Site]:
|
||||||
|
return await self._sites.list_all()
|
||||||
|
|
||||||
|
async def get_by_id(self, site_id: str) -> Site:
|
||||||
|
site = await self._sites.get_by_id(site_id)
|
||||||
|
if site is None:
|
||||||
|
raise SiteNotFoundError(site_id)
|
||||||
|
return site
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from app.models.energy import Reading, Site
|
||||||
|
from app.repositories.reading import ReadingRepository
|
||||||
|
from app.repositories.site import SiteRepository
|
||||||
|
|
||||||
|
DataQuality = Literal["good", "partial", "degraded", "critical"]
|
||||||
|
|
||||||
|
QUALITES_CONNUES: frozenset[str] = frozenset({"good", "partial", "degraded", "critical"})
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SiteConsumption:
|
||||||
|
site_id: str
|
||||||
|
site_name: str
|
||||||
|
current_consumption_kw: float | None
|
||||||
|
capacity_kw: float
|
||||||
|
load_percent: float | None
|
||||||
|
data_quality: DataQuality
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ConsumptionSummary:
|
||||||
|
timestamp: datetime
|
||||||
|
total_sites: int
|
||||||
|
total_consumption_kw: float
|
||||||
|
total_capacity_kw: float
|
||||||
|
average_load_percent: float
|
||||||
|
sites: list[SiteConsumption]
|
||||||
|
|
||||||
|
|
||||||
|
class StatsService:
|
||||||
|
def __init__(self, sites: SiteRepository, readings: ReadingRepository) -> None:
|
||||||
|
self._sites = sites
|
||||||
|
self._readings = readings
|
||||||
|
|
||||||
|
async def summary(self) -> ConsumptionSummary:
|
||||||
|
sites = await self._sites.list_all()
|
||||||
|
dernieres = {lecture.site_id: lecture for lecture in await self._readings.latest_by_site()}
|
||||||
|
|
||||||
|
resumes = [self._resume_site(site, dernieres.get(site.site_id)) for site in sites]
|
||||||
|
consommation_totale = sum(r.current_consumption_kw or 0 for r in resumes)
|
||||||
|
capacite_totale = sum(r.capacity_kw for r in resumes)
|
||||||
|
|
||||||
|
return ConsumptionSummary(
|
||||||
|
timestamp=datetime.now(UTC),
|
||||||
|
total_sites=len(resumes),
|
||||||
|
total_consumption_kw=consommation_totale,
|
||||||
|
total_capacity_kw=capacite_totale,
|
||||||
|
average_load_percent=(
|
||||||
|
consommation_totale / capacite_totale * 100 if capacite_totale > 0 else 0
|
||||||
|
),
|
||||||
|
sites=resumes,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _resume_site(site: Site, derniere: Reading | None) -> SiteConsumption:
|
||||||
|
capacite = site.capacity_kw or 0
|
||||||
|
# Piège : `data_quality` est nul dès qu'un site n'a jamais reçu de lecture, ou que le
|
||||||
|
# producteur n'a pas su la qualifier. Le contrat frontend n'a pas de valeur pour ce cas,
|
||||||
|
# `critical` est la seule des quatre qui n'induit pas une confiance qu'on n'a pas.
|
||||||
|
qualite: DataQuality = "critical"
|
||||||
|
consommation = None
|
||||||
|
if derniere is not None and derniere.data_quality in QUALITES_CONNUES:
|
||||||
|
qualite = derniere.data_quality # type: ignore[assignment]
|
||||||
|
consommation = derniere.consumption_kw
|
||||||
|
|
||||||
|
charge = (
|
||||||
|
consommation / capacite * 100 if consommation is not None and capacite > 0 else None
|
||||||
|
)
|
||||||
|
|
||||||
|
return SiteConsumption(
|
||||||
|
site_id=site.site_id,
|
||||||
|
site_name=site.site_name,
|
||||||
|
current_consumption_kw=consommation,
|
||||||
|
capacity_kw=capacite,
|
||||||
|
load_percent=charge,
|
||||||
|
data_quality=qualite,
|
||||||
|
)
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
# Piège : `change_role()` et `set_active()` refusent de toucher au dernier administrateur actif.
|
||||||
|
# Sans cette garde, un administrateur peut se rétrograder ou se désactiver lui-même, et plus
|
||||||
|
# personne ne peut administrer la plateforme sans repasser par `psql`.
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Protocol
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from app.core.hashing import Argon2Hasher
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import Role
|
||||||
|
from app.models.audit_log import AuditAction
|
||||||
|
from app.models.refresh_token import RevocationReason
|
||||||
|
from app.models.user import AppUser
|
||||||
|
from app.repositories.audit_log import AuditLogRepository
|
||||||
|
from app.repositories.refresh_token import RefreshTokenRepository
|
||||||
|
from app.repositories.user import UserRepository
|
||||||
|
|
||||||
|
LONGUEUR_MOT_DE_PASSE_TEMPORAIRE = 18
|
||||||
|
|
||||||
|
|
||||||
|
class Transaction(Protocol):
|
||||||
|
async def commit(self) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class UserError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UserNotFoundError(UserError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class EmailAlreadyUsedError(UserError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class LastAdminError(UserError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class CreatedUser:
|
||||||
|
user: AppUser
|
||||||
|
temporary_password: str
|
||||||
|
|
||||||
|
|
||||||
|
class UserService:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
users: UserRepository,
|
||||||
|
refresh_tokens: RefreshTokenRepository,
|
||||||
|
audit: AuditLogRepository,
|
||||||
|
hasher: Argon2Hasher,
|
||||||
|
transaction: Transaction,
|
||||||
|
) -> None:
|
||||||
|
self._users = users
|
||||||
|
self._refresh = refresh_tokens
|
||||||
|
self._audit = audit
|
||||||
|
self._hasher = hasher
|
||||||
|
self._transaction = transaction
|
||||||
|
|
||||||
|
async def list_all(self) -> Sequence[AppUser]:
|
||||||
|
return await self._users.list_all()
|
||||||
|
|
||||||
|
async def create(
|
||||||
|
self, *, actor: Principal, email: str, role: Role, full_name: str | None
|
||||||
|
) -> CreatedUser:
|
||||||
|
if await self._users.get_by_email(email) is not None:
|
||||||
|
raise EmailAlreadyUsedError(email)
|
||||||
|
|
||||||
|
provisoire = secrets.token_urlsafe(LONGUEUR_MOT_DE_PASSE_TEMPORAIRE)
|
||||||
|
compte = await self._users.create(
|
||||||
|
email=email,
|
||||||
|
password_hash=await self._hasher.hash(provisoire),
|
||||||
|
role=role,
|
||||||
|
full_name=full_name,
|
||||||
|
must_change_password=True,
|
||||||
|
)
|
||||||
|
await self._audit.record(
|
||||||
|
action=AuditAction.COMPTE_CREE,
|
||||||
|
actor=actor,
|
||||||
|
target_type="app_user",
|
||||||
|
target_id=str(compte.id),
|
||||||
|
detail={"email": compte.email, "role_apres": role.value},
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
return CreatedUser(user=compte, temporary_password=provisoire)
|
||||||
|
|
||||||
|
async def change_role(self, *, actor: Principal, user_id: UUID, role: Role) -> AppUser:
|
||||||
|
compte = await self._exige(user_id)
|
||||||
|
if compte.role == role.value:
|
||||||
|
return compte
|
||||||
|
|
||||||
|
await self._refuse_si_dernier_admin(compte, futur_role=role, futur_actif=compte.is_active)
|
||||||
|
avant = compte.role
|
||||||
|
await self._users.set_role(user_id, role)
|
||||||
|
await self._refresh.revoke_all_for_user(user_id, RevocationReason.ADMINISTRATION)
|
||||||
|
await self._audit.record(
|
||||||
|
action=AuditAction.COMPTE_ROLE_CHANGE,
|
||||||
|
actor=actor,
|
||||||
|
target_type="app_user",
|
||||||
|
target_id=str(user_id),
|
||||||
|
detail={"role_avant": avant, "role_apres": role.value},
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
return await self._exige(user_id)
|
||||||
|
|
||||||
|
async def set_active(self, *, actor: Principal, user_id: UUID, is_active: bool) -> AppUser:
|
||||||
|
compte = await self._exige(user_id)
|
||||||
|
if compte.is_active == is_active:
|
||||||
|
return compte
|
||||||
|
|
||||||
|
await self._refuse_si_dernier_admin(
|
||||||
|
compte, futur_role=Role(compte.role), futur_actif=is_active
|
||||||
|
)
|
||||||
|
await self._users.set_active(user_id, is_active=is_active)
|
||||||
|
if not is_active:
|
||||||
|
await self._refresh.revoke_all_for_user(user_id, RevocationReason.ADMINISTRATION)
|
||||||
|
await self._audit.record(
|
||||||
|
action=AuditAction.COMPTE_ACTIVE if is_active else AuditAction.COMPTE_DESACTIVE,
|
||||||
|
actor=actor,
|
||||||
|
target_type="app_user",
|
||||||
|
target_id=str(user_id),
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
return await self._exige(user_id)
|
||||||
|
|
||||||
|
async def reset_password(self, *, actor: Principal, user_id: UUID) -> CreatedUser:
|
||||||
|
compte = await self._exige(user_id)
|
||||||
|
provisoire = secrets.token_urlsafe(LONGUEUR_MOT_DE_PASSE_TEMPORAIRE)
|
||||||
|
|
||||||
|
await self._users.update_password(
|
||||||
|
user_id, await self._hasher.hash(provisoire), must_change_password=True
|
||||||
|
)
|
||||||
|
await self._refresh.revoke_all_for_user(user_id, RevocationReason.CHANGEMENT_MOT_DE_PASSE)
|
||||||
|
await self._audit.record(
|
||||||
|
action=AuditAction.COMPTE_MOT_DE_PASSE_REINITIALISE,
|
||||||
|
actor=actor,
|
||||||
|
target_type="app_user",
|
||||||
|
target_id=str(user_id),
|
||||||
|
detail={"email": compte.email},
|
||||||
|
)
|
||||||
|
await self._transaction.commit()
|
||||||
|
return CreatedUser(user=await self._exige(user_id), temporary_password=provisoire)
|
||||||
|
|
||||||
|
async def _exige(self, user_id: UUID) -> AppUser:
|
||||||
|
compte = await self._users.get_by_id(user_id)
|
||||||
|
if compte is None:
|
||||||
|
raise UserNotFoundError(str(user_id))
|
||||||
|
return compte
|
||||||
|
|
||||||
|
async def _refuse_si_dernier_admin(
|
||||||
|
self, compte: AppUser, *, futur_role: Role, futur_actif: bool
|
||||||
|
) -> None:
|
||||||
|
etait_admin = compte.role == Role.ADMIN.value and compte.is_active
|
||||||
|
reste_admin = futur_role is Role.ADMIN and futur_actif
|
||||||
|
if not etait_admin or reste_admin:
|
||||||
|
return
|
||||||
|
if await self._users.count_active_admins() <= 1:
|
||||||
|
raise LastAdminError(str(compte.id))
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,96 @@
|
|||||||
|
[project]
|
||||||
|
name = "enervision-backend"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "API EnerVision : exposition des series temporelles energetiques"
|
||||||
|
requires-python = ">=3.14,<3.15"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.141.1",
|
||||||
|
"uvicorn[standard]>=0.53.0",
|
||||||
|
"pydantic[email]>=2.13.5",
|
||||||
|
"pydantic-settings>=2.15.0",
|
||||||
|
"sqlalchemy[asyncio]>=2.0.52",
|
||||||
|
"asyncpg>=0.31.0",
|
||||||
|
"alembic>=1.20.0",
|
||||||
|
"prometheus-fastapi-instrumentator>=8.1.0",
|
||||||
|
"python-json-logger>=4.2.0",
|
||||||
|
"pyjwt>=2.10",
|
||||||
|
"argon2-cffi>=23.1",
|
||||||
|
"anyio>=4.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependency-groups]
|
||||||
|
dev = [
|
||||||
|
"ruff>=0.16.7",
|
||||||
|
"mypy>=2.3.1",
|
||||||
|
"pytest>=9.1.1",
|
||||||
|
"pytest-asyncio>=1.4.0",
|
||||||
|
"pytest-cov>=7.1.0",
|
||||||
|
"httpx>=0.28.1",
|
||||||
|
]
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["hatchling>=1.32.0"]
|
||||||
|
build-backend = "hatchling.build"
|
||||||
|
|
||||||
|
[tool.hatch.build.targets.wheel]
|
||||||
|
packages = ["app"]
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 100
|
||||||
|
target-version = "py314"
|
||||||
|
src = ["app", "tests"]
|
||||||
|
extend-exclude = ["alembic/versions"]
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = [
|
||||||
|
"E", "W",
|
||||||
|
"F",
|
||||||
|
"I",
|
||||||
|
"N",
|
||||||
|
"UP",
|
||||||
|
"B",
|
||||||
|
"C4",
|
||||||
|
"SIM",
|
||||||
|
"TID",
|
||||||
|
"RUF",
|
||||||
|
"ASYNC",
|
||||||
|
"S",
|
||||||
|
"PT",
|
||||||
|
]
|
||||||
|
ignore = ["B008"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.per-file-ignores]
|
||||||
|
# S105 à S107 signalent les secrets en dur, qui sont justement la matière des tests d'auth.
|
||||||
|
"tests/**/*.py" = ["S101", "S105", "S106", "S107"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.isort]
|
||||||
|
known-first-party = ["app"]
|
||||||
|
|
||||||
|
[tool.ruff.format]
|
||||||
|
quote-style = "double"
|
||||||
|
|
||||||
|
[tool.mypy]
|
||||||
|
python_version = "3.14"
|
||||||
|
strict = true
|
||||||
|
warn_unreachable = true
|
||||||
|
plugins = ["pydantic.mypy"]
|
||||||
|
exclude = ["^alembic/"]
|
||||||
|
|
||||||
|
[[tool.mypy.overrides]]
|
||||||
|
module = ["tests.*"]
|
||||||
|
disallow_untyped_defs = false
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
asyncio_mode = "auto"
|
||||||
|
asyncio_default_fixture_loop_scope = "function"
|
||||||
|
addopts = "-q --strict-markers -m 'not integration' --cov=app --cov-report=term-missing"
|
||||||
|
markers = ["integration: requiert une base PostgreSQL joignable, hors `make test`"]
|
||||||
|
|
||||||
|
[tool.coverage.run]
|
||||||
|
source = ["app"]
|
||||||
|
branch = true
|
||||||
|
omit = ["alembic/*"]
|
||||||
|
|
||||||
|
[tool.coverage.report]
|
||||||
|
show_missing = true
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
from collections.abc import Callable, Iterator
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from app.api.deps import get_alert_service, get_current_principal
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.models.energy import Alert
|
||||||
|
from app.schemas.alert import AlertSeverity
|
||||||
|
|
||||||
|
|
||||||
|
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||||
|
return Principal(
|
||||||
|
id=uuid4(),
|
||||||
|
email=f"{role.value}@enervision.fr",
|
||||||
|
role=role,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def alert(alert_id: int = 1, site_id: str = "site-1", severity: str = "high") -> Alert:
|
||||||
|
return Alert(
|
||||||
|
alert_id=alert_id,
|
||||||
|
source_alert_id=f"ALR-{alert_id}",
|
||||||
|
site_id=site_id,
|
||||||
|
source="enervision",
|
||||||
|
timestamp=datetime(2026, 9, 16, tzinfo=UTC),
|
||||||
|
type="threshold",
|
||||||
|
severity=severity,
|
||||||
|
message="Dépassement du seuil configuré",
|
||||||
|
value=812.5,
|
||||||
|
threshold=720.0,
|
||||||
|
metric="consumption_kw",
|
||||||
|
prediction_id=None,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FauxService:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.alert = alert()
|
||||||
|
self.appels: list[tuple[str | None, str | None]] = []
|
||||||
|
|
||||||
|
async def list_all(
|
||||||
|
self, *, site_id: str | None = None, severity: str | None = None
|
||||||
|
) -> list[Alert]:
|
||||||
|
self.appels.append((site_id, severity))
|
||||||
|
return [self.alert]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: principal()
|
||||||
|
yield
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def servi(app: FastAPI, lecteur_connecte: None) -> Iterator[Callable[[], FauxService]]:
|
||||||
|
def installe() -> FauxService:
|
||||||
|
service = FauxService()
|
||||||
|
app.dependency_overrides[get_alert_service] = lambda: service
|
||||||
|
return service
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_alert_service, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_alerts_returns_the_alerts(
|
||||||
|
servi: Callable[[], FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/alerts")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
corps = response.json()
|
||||||
|
assert corps == [
|
||||||
|
{
|
||||||
|
"alert_id": 1,
|
||||||
|
"site_id": "site-1",
|
||||||
|
"timestamp": "2026-09-16T00:00:00Z",
|
||||||
|
"type": "threshold",
|
||||||
|
"severity": "high",
|
||||||
|
"message": "Dépassement du seuil configuré",
|
||||||
|
"value": 812.5,
|
||||||
|
"threshold": 720.0,
|
||||||
|
"metric": "consumption_kw",
|
||||||
|
"prediction_id": None,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_alerts_transmits_the_site_id_filter(
|
||||||
|
servi: Callable[[], FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
service = servi()
|
||||||
|
|
||||||
|
await client.get("/api/v1/alerts?site_id=site-1")
|
||||||
|
|
||||||
|
assert service.appels == [("site-1", None)]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_alerts_transmits_the_severity_filter(
|
||||||
|
servi: Callable[[], FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
service = servi()
|
||||||
|
|
||||||
|
await client.get("/api/v1/alerts?severity=critical")
|
||||||
|
|
||||||
|
assert service.appels == [(None, AlertSeverity.CRITICAL)]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_alerts_returns_422_for_an_unknown_severity(
|
||||||
|
servi: Callable[[], FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/alerts?severity=invalide")
|
||||||
|
|
||||||
|
assert response.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_alerts_returns_an_empty_list_when_there_is_nothing(
|
||||||
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=[])
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/alerts")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == []
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
from collections.abc import Iterator
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from app.api.deps import get_auth_service
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.services.auth import (
|
||||||
|
AuthenticatedSession,
|
||||||
|
InvalidCredentialsError,
|
||||||
|
RateLimitedError,
|
||||||
|
SessionRejectedError,
|
||||||
|
)
|
||||||
|
|
||||||
|
IDENTIFIANTS = {"email": "operateur@enervision.fr", "password": "un-mot-de-passe-valide"}
|
||||||
|
|
||||||
|
PRINCIPAL = Principal(
|
||||||
|
id=uuid4(),
|
||||||
|
email="operateur@enervision.fr",
|
||||||
|
role=Role.OPERATEUR,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
refresh_secret="un-secret-opaque",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_auth_service(app: FastAPI) -> Iterator[list[Exception | None]]:
|
||||||
|
programme: list[Exception | None] = [None]
|
||||||
|
app.dependency_overrides[get_auth_service] = lambda: FauxService(programme[0])
|
||||||
|
yield programme
|
||||||
|
app.dependency_overrides.pop(get_auth_service, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_returns_the_token_and_the_principal_when_credentials_match(
|
||||||
|
fake_auth_service: list[Exception | None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
response = await client.post("/api/v1/auth/login", json=IDENTIFIANTS)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
corps = response.json()
|
||||||
|
assert corps["access_token"] == "un.jeton.factice"
|
||||||
|
assert corps["token_type"] == "bearer"
|
||||||
|
assert corps["principal"]["role"] == "operateur"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_forbids_intermediaries_from_caching_the_response(
|
||||||
|
fake_auth_service: list[Exception | None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
response = await client.post("/api/v1/auth/login", json=IDENTIFIANTS)
|
||||||
|
|
||||||
|
assert response.headers["cache-control"] == "no-store"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_never_reveals_which_half_of_the_credentials_was_wrong(
|
||||||
|
fake_auth_service: list[Exception | None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_auth_service[0] = InvalidCredentialsError("Identifiants invalides")
|
||||||
|
|
||||||
|
response = await client.post("/api/v1/auth/login", json=IDENTIFIANTS)
|
||||||
|
|
||||||
|
assert response.status_code == 401
|
||||||
|
assert response.json() == {"detail": "Identifiants invalides"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_returns_429_with_a_retry_after_when_the_rate_limit_is_reached(
|
||||||
|
fake_auth_service: list[Exception | None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_auth_service[0] = RateLimitedError(900)
|
||||||
|
|
||||||
|
response = await client.post("/api/v1/auth/login", json=IDENTIFIANTS)
|
||||||
|
|
||||||
|
assert response.status_code == 429
|
||||||
|
assert response.headers["retry-after"] == "900"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"corps",
|
||||||
|
[
|
||||||
|
{"email": "pas-une-adresse", "password": "un-mot-de-passe-valide"},
|
||||||
|
{"email": "operateur@enervision.fr"},
|
||||||
|
{"email": "operateur@enervision.fr", "password": "x" * 129},
|
||||||
|
],
|
||||||
|
ids=["adresse_invalide", "mot_de_passe_absent", "mot_de_passe_trop_long"],
|
||||||
|
)
|
||||||
|
async def test_login_rejects_a_malformed_body_without_echoing_the_password(
|
||||||
|
fake_auth_service: list[Exception | None], client: AsyncClient, corps: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
response = await client.post("/api/v1/auth/login", json=corps)
|
||||||
|
|
||||||
|
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
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
from collections.abc import Callable, Iterator
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from app.api.deps import AdminDep, get_current_principal, require_role
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
|
||||||
|
CHEMIN_ADMIN = "/api/v1/essai-admin"
|
||||||
|
|
||||||
|
|
||||||
|
def principal(role: Role = Role.LECTEUR, *, must_change_password: bool = False) -> Principal:
|
||||||
|
return Principal(
|
||||||
|
id=uuid4(),
|
||||||
|
email=f"{role.value}@enervision.fr",
|
||||||
|
role=role,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=must_change_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def route_admin(app: FastAPI) -> None:
|
||||||
|
@app.get(CHEMIN_ADMIN)
|
||||||
|
async def _reserve_aux_admins(acteur: AdminDep) -> dict[str, str]:
|
||||||
|
return {"email": acteur.email}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def connecte(app: FastAPI) -> Iterator[Callable[[Principal], None]]:
|
||||||
|
def installe(acteur: Principal) -> None:
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: acteur
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_me_returns_401_when_no_credentials_are_sent(client: AsyncClient) -> None:
|
||||||
|
response = await client.get("/api/v1/auth/me")
|
||||||
|
|
||||||
|
assert response.status_code == 401
|
||||||
|
assert "Bearer" in response.headers["www-authenticate"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_me_returns_401_when_the_token_is_not_readable(client: AsyncClient) -> None:
|
||||||
|
response = await client.get(
|
||||||
|
"/api/v1/auth/me", headers={"Authorization": "Bearer nimporte.quoi.ici"}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 401
|
||||||
|
assert 'error="invalid_token"' in response.headers["www-authenticate"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_me_describes_the_connected_account(
|
||||||
|
connecte: Callable[[Principal], None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
acteur = principal(Role.OPERATEUR)
|
||||||
|
connecte(acteur)
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/auth/me")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["email"] == acteur.email
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("role", "attendu"),
|
||||||
|
[(Role.LECTEUR, 403), (Role.OPERATEUR, 403), (Role.ADMIN, 200)],
|
||||||
|
ids=["lecteur_refuse", "operateur_refuse", "admin_accepte"],
|
||||||
|
)
|
||||||
|
async def test_an_admin_route_only_answers_to_an_admin(
|
||||||
|
route_admin: None,
|
||||||
|
connecte: Callable[[Principal], None],
|
||||||
|
client: AsyncClient,
|
||||||
|
role: Role,
|
||||||
|
attendu: int,
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(role))
|
||||||
|
|
||||||
|
response = await client.get(CHEMIN_ADMIN)
|
||||||
|
|
||||||
|
assert response.status_code == attendu
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_pending_password_change_blocks_every_business_route(
|
||||||
|
route_admin: None, connecte: Callable[[Principal], None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(Role.ADMIN, must_change_password=True))
|
||||||
|
|
||||||
|
response = await client.get(CHEMIN_ADMIN)
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
assert response.json()["detail"] == "password_change_required"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_pending_password_change_still_allows_reading_ones_own_account(
|
||||||
|
connecte: Callable[[Principal], None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(Role.LECTEUR, must_change_password=True))
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/auth/me")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["must_change_password"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_require_role_builds_one_guard_per_minimum_level() -> None:
|
||||||
|
garde = require_role(Role.OPERATEUR)
|
||||||
|
|
||||||
|
assert callable(garde)
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import pytest
|
||||||
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
from httpx import Response as HttpResponse
|
||||||
|
|
||||||
|
from app.main import create_app
|
||||||
|
from tests.factories import make_settings
|
||||||
|
|
||||||
|
ORIGINE = "https://enervision.fr"
|
||||||
|
|
||||||
|
|
||||||
|
async def interroge(
|
||||||
|
settings_overrides: dict[str, object], chemin: str, **kwargs: object
|
||||||
|
) -> HttpResponse:
|
||||||
|
application = create_app(make_settings(**settings_overrides))
|
||||||
|
transport = ASGITransport(app=application)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||||
|
return await client.get(chemin, **kwargs) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("entete", "valeur"),
|
||||||
|
[
|
||||||
|
("x-content-type-options", "nosniff"),
|
||||||
|
("x-frame-options", "DENY"),
|
||||||
|
("referrer-policy", "no-referrer"),
|
||||||
|
],
|
||||||
|
ids=["nosniff", "anti_iframe", "referrer"],
|
||||||
|
)
|
||||||
|
async def test_every_response_carries_the_security_headers(
|
||||||
|
client: AsyncClient, entete: str, valeur: str
|
||||||
|
) -> None:
|
||||||
|
response = await client.get("/api/v1/health/live")
|
||||||
|
|
||||||
|
assert response.headers[entete] == valeur
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_application_never_sets_hsts_itself(client: AsyncClient) -> None:
|
||||||
|
response = await client.get("/api/v1/health/live")
|
||||||
|
|
||||||
|
assert "strict-transport-security" not in response.headers
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"env",
|
||||||
|
["staging", "prod"],
|
||||||
|
ids=["preproduction", "production"],
|
||||||
|
)
|
||||||
|
async def test_the_documentation_disappears_outside_development(env: str) -> None:
|
||||||
|
surcharges = {"env": env, "cors_origins": ORIGINE}
|
||||||
|
|
||||||
|
for chemin in ("/docs", "/openapi.json"):
|
||||||
|
assert (await interroge(surcharges, chemin)).status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("env", ["local", "dev"], ids=["local", "developpement"])
|
||||||
|
async def test_the_documentation_stays_available_while_developing(env: str) -> None:
|
||||||
|
surcharges = {"env": env, "cors_origins": ORIGINE}
|
||||||
|
|
||||||
|
assert (await interroge(surcharges, "/openapi.json")).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
async def test_an_explicit_override_can_reopen_the_documentation() -> None:
|
||||||
|
surcharges = {"env": "prod", "cors_origins": ORIGINE, "expose_api_docs": True}
|
||||||
|
|
||||||
|
assert (await interroge(surcharges, "/openapi.json")).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
async def test_metrics_stay_open_when_no_token_is_configured(client: AsyncClient) -> None:
|
||||||
|
response = await client.get("/metrics")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
async def test_metrics_demand_the_token_once_one_is_configured() -> None:
|
||||||
|
surcharges = {"metrics_token": "un-jeton-de-supervision-assez-long"}
|
||||||
|
|
||||||
|
assert (await interroge(surcharges, "/metrics")).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_metrics_answer_to_the_right_token() -> None:
|
||||||
|
surcharges = {"metrics_token": "un-jeton-de-supervision-assez-long"}
|
||||||
|
entetes = {"Authorization": "Bearer un-jeton-de-supervision-assez-long"}
|
||||||
|
|
||||||
|
response = await interroge(surcharges, "/metrics", headers=entetes)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
async def test_metrics_refuse_a_token_that_is_almost_right() -> None:
|
||||||
|
surcharges = {"metrics_token": "un-jeton-de-supervision-assez-long"}
|
||||||
|
entetes = {"Authorization": "Bearer un-jeton-de-supervision-assez-lon"}
|
||||||
|
|
||||||
|
response = await interroge(surcharges, "/metrics", headers=entetes)
|
||||||
|
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_an_unhandled_error_returns_a_correlation_id_and_no_traceback() -> None:
|
||||||
|
application = create_app(make_settings())
|
||||||
|
|
||||||
|
@application.get("/api/v1/essai-panne")
|
||||||
|
async def _casse() -> None:
|
||||||
|
raise RuntimeError("secret interne de la pile")
|
||||||
|
|
||||||
|
transport = ASGITransport(app=application, raise_app_exceptions=False)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||||
|
response = await client.get("/api/v1/essai-panne")
|
||||||
|
|
||||||
|
assert response.status_code == 500
|
||||||
|
assert "secret interne de la pile" not in response.text
|
||||||
|
assert response.json()["correlation"]
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import AsyncClient
|
||||||
|
from sqlalchemy.exc import OperationalError
|
||||||
|
|
||||||
|
|
||||||
|
async def test_liveness_exposes_service_metadata(client: AsyncClient) -> None:
|
||||||
|
response = await client.get("/api/v1/health/live")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {
|
||||||
|
"status": "ok",
|
||||||
|
"service": "EnerVision API",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"environment": "local",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_readiness_confirms_the_extension_without_leaking_its_version(
|
||||||
|
fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result="2.22.1")
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/health/ready")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {
|
||||||
|
"status": "ready",
|
||||||
|
"database": "reachable",
|
||||||
|
"timescaledb": "loaded",
|
||||||
|
}
|
||||||
|
assert "2.22.1" not in response.text
|
||||||
|
|
||||||
|
|
||||||
|
async def test_readiness_returns_503_when_the_extension_is_missing(
|
||||||
|
fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=None)
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/health/ready")
|
||||||
|
|
||||||
|
assert response.status_code == 503
|
||||||
|
assert response.json()["detail"] == "Extension TimescaleDB absente"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"failure",
|
||||||
|
[
|
||||||
|
OperationalError("SELECT 1", {}, Exception("connexion refusee")),
|
||||||
|
ConnectionRefusedError(111, "Connection refused"),
|
||||||
|
],
|
||||||
|
ids=["erreur_sqlalchemy", "erreur_reseau_asyncpg"],
|
||||||
|
)
|
||||||
|
async def test_readiness_returns_503_when_database_is_unreachable(
|
||||||
|
fake_session: Callable[..., None], client: AsyncClient, failure: Exception
|
||||||
|
) -> None:
|
||||||
|
fake_session(failure=failure)
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/health/ready")
|
||||||
|
|
||||||
|
assert response.status_code == 503
|
||||||
|
assert response.json()["detail"] == "Base de données injoignable"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("path", ["/openapi.json", "/metrics"])
|
||||||
|
async def test_technical_endpoints_are_served(client: AsyncClient, path: str) -> None:
|
||||||
|
assert (await client.get(path)).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_readiness_reaches_the_real_database(client: AsyncClient) -> None:
|
||||||
|
response = await client.get("/api/v1/health/ready")
|
||||||
|
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
body = response.json()
|
||||||
|
assert body["status"] == "ready"
|
||||||
|
assert body["database"] == "reachable"
|
||||||
|
assert body["timescaledb"] == "loaded"
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
# 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")}
|
||||||
|
|
||||||
|
ORIGINE_VERIFIEE = {
|
||||||
|
("POST", "/api/v1/auth/refresh"),
|
||||||
|
("POST", "/api/v1/auth/logout"),
|
||||||
|
("POST", "/api/v1/auth/logout-all"),
|
||||||
|
("POST", "/api/v1/auth/password"),
|
||||||
|
}
|
||||||
|
|
||||||
|
# Toute route derrière `require_role` (LecteurDep, OperateurDep, AdminDep) peut rendre 403 pour
|
||||||
|
# `password_change_required`, pas seulement les routes `admin`.
|
||||||
|
ROUTES_A_ROLE = {
|
||||||
|
("GET", "/api/v1/users"),
|
||||||
|
("POST", "/api/v1/users"),
|
||||||
|
("PATCH", "/api/v1/users/{id}"),
|
||||||
|
("POST", "/api/v1/users/{id}/password-reset"),
|
||||||
|
("GET", "/api/v1/sites"),
|
||||||
|
("GET", "/api/v1/sites/{site_id}"),
|
||||||
|
("GET", "/api/v1/alerts"),
|
||||||
|
("GET", "/api/v1/recommendations"),
|
||||||
|
("GET", "/api/v1/recommendations/{recommendation_id}"),
|
||||||
|
("GET", "/api/v1/stats/summary"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@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_role_guarded_route_documents_the_role_refusal(schema: dict[str, Any]) -> None:
|
||||||
|
sans_403 = [
|
||||||
|
(methode, chemin)
|
||||||
|
for methode, chemin, operation in operations(schema)
|
||||||
|
if (methode, chemin) in ROUTES_A_ROLE and "403" not in operation["responses"]
|
||||||
|
]
|
||||||
|
|
||||||
|
assert sans_403 == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_origin_checked_route_documents_the_csrf_refusal(schema: dict[str, Any]) -> None:
|
||||||
|
sans_403 = [
|
||||||
|
(methode, chemin)
|
||||||
|
for methode, chemin, operation in operations(schema)
|
||||||
|
if (methode, chemin) in ORIGINE_VERIFIEE 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}"
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# Parcours complet contre la vraie base, sans serveur ni port ouvert. C'est ce fichier qui
|
||||||
|
# prouve que le câblage tient : la connexion, la rotation, la détection de réutilisation et la
|
||||||
|
# révocation immédiate passent par les vrais dépôts, les vraies transactions et les vrais
|
||||||
|
# déclencheurs PostgreSQL.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from app.core.hashing import build_hasher
|
||||||
|
from app.core.roles import Role
|
||||||
|
from app.db.session import get_session_factory
|
||||||
|
from app.repositories.user import UserRepository
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.integration
|
||||||
|
|
||||||
|
MOT_DE_PASSE = "un-mot-de-passe-de-recette"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def compte_operateur() -> AsyncIterator[str]:
|
||||||
|
email = f"parcours-{uuid.uuid4().hex[:12]}@enervision.fr"
|
||||||
|
hacheur = build_hasher(time_cost=1, memory_cost_kib=8192, parallelism=1, max_concurrency=2)
|
||||||
|
empreinte = await hacheur.hash(MOT_DE_PASSE)
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
await UserRepository(session).create(
|
||||||
|
email=email, password_hash=empreinte, role=Role.OPERATEUR
|
||||||
|
)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
yield email
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
await session.execute(text("delete from app_user where email = :e"), {"e": email})
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def navigateur(app: FastAPI) -> AsyncIterator[AsyncClient]:
|
||||||
|
transport = ASGITransport(app=app)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||||
|
yield client
|
||||||
|
|
||||||
|
|
||||||
|
async def connecte(navigateur: AsyncClient, email: str) -> dict[str, str]:
|
||||||
|
reponse = await navigateur.post(
|
||||||
|
"/api/v1/auth/login", json={"email": email, "password": MOT_DE_PASSE}
|
||||||
|
)
|
||||||
|
assert reponse.status_code == 200, reponse.text
|
||||||
|
return {"Authorization": f"Bearer {reponse.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_full_session_runs_from_login_to_logout(
|
||||||
|
compte_operateur: str, navigateur: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
entetes = await connecte(navigateur, compte_operateur)
|
||||||
|
|
||||||
|
identite = await navigateur.get("/api/v1/auth/me", headers=entetes)
|
||||||
|
rotation = await navigateur.post("/api/v1/auth/refresh")
|
||||||
|
deconnexion = await navigateur.post("/api/v1/auth/logout")
|
||||||
|
|
||||||
|
assert identite.status_code == 200
|
||||||
|
assert identite.json()["role"] == "operateur"
|
||||||
|
assert rotation.status_code == 200
|
||||||
|
assert deconnexion.status_code == 204
|
||||||
|
|
||||||
|
|
||||||
|
async def test_replaying_a_rotated_cookie_kills_the_whole_family(
|
||||||
|
compte_operateur: str, navigateur: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
await connecte(navigateur, compte_operateur)
|
||||||
|
vole = navigateur.cookies["ev_refresh"]
|
||||||
|
premiere_rotation = await navigateur.post("/api/v1/auth/refresh")
|
||||||
|
vivant = navigateur.cookies["ev_refresh"]
|
||||||
|
|
||||||
|
navigateur.cookies.set("ev_refresh", vole)
|
||||||
|
rejeu = await navigateur.post("/api/v1/auth/refresh")
|
||||||
|
|
||||||
|
navigateur.cookies.set("ev_refresh", vivant)
|
||||||
|
apres = await navigateur.post("/api/v1/auth/refresh")
|
||||||
|
|
||||||
|
assert premiere_rotation.status_code == 200
|
||||||
|
assert rejeu.status_code == 401
|
||||||
|
assert apres.status_code == 401, "la session vivante doit tomber avec sa famille"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_reuse_leaves_a_trace_in_the_append_only_audit_log(
|
||||||
|
compte_operateur: str, navigateur: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
await connecte(navigateur, compte_operateur)
|
||||||
|
vole = navigateur.cookies["ev_refresh"]
|
||||||
|
await navigateur.post("/api/v1/auth/refresh")
|
||||||
|
|
||||||
|
navigateur.cookies.set("ev_refresh", vole)
|
||||||
|
await navigateur.post("/api/v1/auth/refresh")
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
traces = await session.scalar(
|
||||||
|
text("select count(*) from audit_log where action = 'auth.refresh_reuse_detected'")
|
||||||
|
)
|
||||||
|
assert traces is not None
|
||||||
|
assert traces >= 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_disabling_an_account_invalidates_its_access_token_at_once(
|
||||||
|
compte_operateur: str, navigateur: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
entetes = await connecte(navigateur, compte_operateur)
|
||||||
|
avant = await navigateur.get("/api/v1/auth/me", headers=entetes)
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
depot = UserRepository(session)
|
||||||
|
compte = await depot.get_by_email(compte_operateur)
|
||||||
|
assert compte is not None
|
||||||
|
await depot.set_active(compte.id, is_active=False)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
apres = await navigateur.get("/api/v1/auth/me", headers=entetes)
|
||||||
|
|
||||||
|
assert avant.status_code == 200
|
||||||
|
assert apres.status_code == 401, "la révocation doit être immédiate, pas dans 15 minutes"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_changing_a_role_invalidates_the_token_that_still_carries_the_old_one(
|
||||||
|
compte_operateur: str, navigateur: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
entetes = await connecte(navigateur, compte_operateur)
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
depot = UserRepository(session)
|
||||||
|
compte = await depot.get_by_email(compte_operateur)
|
||||||
|
assert compte is not None
|
||||||
|
await depot.set_role(compte.id, Role.LECTEUR)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
apres = await navigateur.get("/api/v1/auth/me", headers=entetes)
|
||||||
|
|
||||||
|
assert apres.status_code == 401
|
||||||
|
assert "token_stale" in apres.headers["www-authenticate"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_failed_login_is_recorded_even_for_an_unknown_address(
|
||||||
|
navigateur: AsyncClient,
|
||||||
|
) -> None:
|
||||||
|
inconnu = f"inconnu-{uuid.uuid4().hex[:12]}@enervision.fr"
|
||||||
|
|
||||||
|
reponse = await navigateur.post(
|
||||||
|
"/api/v1/auth/login", json={"email": inconnu, "password": "peu-importe-ici"}
|
||||||
|
)
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
tentatives = await session.scalar(
|
||||||
|
text("select count(*) from login_attempt where email_tried = :e"), {"e": inconnu}
|
||||||
|
)
|
||||||
|
assert reponse.status_code == 401
|
||||||
|
assert reponse.json() == {"detail": "Identifiants invalides"}
|
||||||
|
assert tentatives == 1, "sans cette ligne, le 429 deviendrait un oracle d'existence"
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
from collections.abc import Callable, Iterator
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from app.api.deps import get_current_principal, get_recommendation_service
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.models.energy import Recommendation
|
||||||
|
from app.services.recommendation import RecommendationNotFoundError
|
||||||
|
|
||||||
|
MOMENT = datetime(2024, 1, 1, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||||
|
return Principal(
|
||||||
|
id=uuid4(),
|
||||||
|
email=f"{role.value}@enervision.fr",
|
||||||
|
role=role,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def recommendation(recommendation_id: int = 1) -> Recommendation:
|
||||||
|
return Recommendation(
|
||||||
|
recommendation_id=recommendation_id,
|
||||||
|
alert_id=1,
|
||||||
|
action="Vérifier la consommation",
|
||||||
|
explanation="Pic détecté",
|
||||||
|
rule_reference="spike-v1",
|
||||||
|
created_at=MOMENT,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FauxService:
|
||||||
|
def __init__(self, erreur: Exception | None = None) -> None:
|
||||||
|
self._erreur = erreur
|
||||||
|
self.recommendation = recommendation()
|
||||||
|
|
||||||
|
async def list_all(self) -> list[Recommendation]:
|
||||||
|
return [self.recommendation]
|
||||||
|
|
||||||
|
async def get_by_id(self, recommendation_id: int) -> Recommendation:
|
||||||
|
if self._erreur is not None:
|
||||||
|
raise self._erreur
|
||||||
|
return self.recommendation
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: principal()
|
||||||
|
yield
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def servi(
|
||||||
|
app: FastAPI, lecteur_connecte: None
|
||||||
|
) -> Iterator[Callable[[Exception | None], FauxService]]:
|
||||||
|
def installe(erreur: Exception | None = None) -> FauxService:
|
||||||
|
service = FauxService(erreur)
|
||||||
|
app.dependency_overrides[get_recommendation_service] = lambda: service
|
||||||
|
return service
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_recommendation_service, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_recommendations_returns_the_recommendations(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/recommendations")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
corps = response.json()
|
||||||
|
assert corps == [
|
||||||
|
{
|
||||||
|
"recommendation_id": 1,
|
||||||
|
"alert_id": 1,
|
||||||
|
"action": "Vérifier la consommation",
|
||||||
|
"explanation": "Pic détecté",
|
||||||
|
"rule_reference": "spike-v1",
|
||||||
|
"created_at": "2024-01-01T00:00:00Z",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_recommendation_returns_the_matching_recommendation(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/recommendations/1")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["recommendation_id"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_recommendation_returns_404_for_an_unknown_recommendation(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi(RecommendationNotFoundError(404))
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/recommendations/404")
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_recommendations_reaches_the_repository_through_the_session(
|
||||||
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=[recommendation(1), recommendation(2)])
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/recommendations")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert [r["recommendation_id"] for r in response.json()] == [1, 2]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_recommendation_reaches_the_repository_through_the_session(
|
||||||
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=recommendation(1))
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/recommendations/1")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["recommendation_id"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_recommendation_returns_404_when_the_session_finds_nothing(
|
||||||
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=None)
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/recommendations/404")
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# Ce test est le garde-fou de l'autorisation : rendre une route publique oblige à modifier
|
||||||
|
# `ROUTES_PUBLIQUES` ci-dessous, ce qui apparaît en clair dans la diff d'une pull request et
|
||||||
|
# demande une justification au relecteur.
|
||||||
|
# Pourquoi : il interroge réellement chaque route sans jeton au lieu d'inspecter l'arbre de
|
||||||
|
# dépendances. L'arbre n'est accessible que par l'API privée de FastAPI, et surtout une route
|
||||||
|
# peut porter la bonne dépendance tout en répondant quand même.
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
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"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
VALEURS_DE_SUBSTITUTION = "00000000-0000-0000-0000-000000000000"
|
||||||
|
STATUTS_DE_REFUS = {401, 403}
|
||||||
|
|
||||||
|
|
||||||
|
def routes_declarees(app: FastAPI) -> list[tuple[str, str]]:
|
||||||
|
schema: dict[str, Any] = app.openapi()
|
||||||
|
return [
|
||||||
|
(methode.upper(), chemin)
|
||||||
|
for chemin, operations in schema["paths"].items()
|
||||||
|
for methode in operations
|
||||||
|
if methode.upper() in {"GET", "POST", "PATCH", "PUT", "DELETE"}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def routes_protegees(app: FastAPI) -> list[tuple[str, str]]:
|
||||||
|
return [route for route in routes_declarees(app) if route not in ROUTES_PUBLIQUES]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_public_allow_list_has_no_stale_entry(app: FastAPI) -> None:
|
||||||
|
declarees = set(routes_declarees(app)) | {("GET", "/metrics")}
|
||||||
|
|
||||||
|
inconnues = ROUTES_PUBLIQUES - declarees
|
||||||
|
|
||||||
|
assert inconnues == set()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_every_route_rejects_an_anonymous_caller_unless_explicitly_public(
|
||||||
|
app: FastAPI, client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
ouvertes: list[tuple[str, str, int]] = []
|
||||||
|
|
||||||
|
for methode, chemin in routes_protegees(app):
|
||||||
|
concret = chemin.replace("{user_id}", VALEURS_DE_SUBSTITUTION)
|
||||||
|
response = await client.request(methode, concret, json={})
|
||||||
|
if response.status_code not in STATUTS_DE_REFUS:
|
||||||
|
ouvertes.append((methode, chemin, response.status_code))
|
||||||
|
|
||||||
|
assert ouvertes == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_declared_routes_are_actually_reachable(app: FastAPI) -> None:
|
||||||
|
assert ("POST", "/api/v1/auth/login") in routes_declarees(app)
|
||||||
|
assert ("GET", "/api/v1/auth/me") in routes_declarees(app)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"chemin",
|
||||||
|
["/api/v1/health/live", "/api/v1/health/ready"],
|
||||||
|
ids=["sonde_de_vie", "sonde_de_disponibilite"],
|
||||||
|
)
|
||||||
|
def test_the_health_probes_stay_public(app: FastAPI, chemin: str) -> None:
|
||||||
|
assert ("GET", chemin) in ROUTES_PUBLIQUES
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
from collections.abc import Callable, Iterator
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from app.api.deps import get_current_principal, get_site_service
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.models.energy import Site
|
||||||
|
from app.services.site import SiteNotFoundError
|
||||||
|
|
||||||
|
|
||||||
|
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||||
|
return Principal(
|
||||||
|
id=uuid4(),
|
||||||
|
email=f"{role.value}@enervision.fr",
|
||||||
|
role=role,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def site(site_id: str = "site-1") -> Site:
|
||||||
|
return Site(
|
||||||
|
site_id=site_id,
|
||||||
|
site_name="Site de test",
|
||||||
|
site_type="industriel",
|
||||||
|
location="Toulouse",
|
||||||
|
capacity_kw=42.0,
|
||||||
|
status="actif",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FauxService:
|
||||||
|
def __init__(self, erreur: Exception | None = None) -> None:
|
||||||
|
self._erreur = erreur
|
||||||
|
self.site = site()
|
||||||
|
|
||||||
|
async def list_all(self) -> list[Site]:
|
||||||
|
return [self.site]
|
||||||
|
|
||||||
|
async def get_by_id(self, site_id: str) -> Site:
|
||||||
|
if self._erreur is not None:
|
||||||
|
raise self._erreur
|
||||||
|
return self.site
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: principal()
|
||||||
|
yield
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def servi(
|
||||||
|
app: FastAPI, lecteur_connecte: None
|
||||||
|
) -> Iterator[Callable[[Exception | None], FauxService]]:
|
||||||
|
def installe(erreur: Exception | None = None) -> FauxService:
|
||||||
|
service = FauxService(erreur)
|
||||||
|
app.dependency_overrides[get_site_service] = lambda: service
|
||||||
|
return service
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_site_service, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_sites_returns_the_sites(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
corps = response.json()
|
||||||
|
assert corps == [
|
||||||
|
{
|
||||||
|
"site_id": "site-1",
|
||||||
|
"site_name": "Site de test",
|
||||||
|
"site_type": "industriel",
|
||||||
|
"location": "Toulouse",
|
||||||
|
"capacity_kw": 42.0,
|
||||||
|
"status": "actif",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_site_returns_the_matching_site(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites/site-1")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["site_id"] == "site-1"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_site_returns_404_for_an_unknown_site(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi(SiteNotFoundError("site-inconnu"))
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites/site-inconnu")
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_sites_reaches_the_repository_through_the_session(
|
||||||
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=[site("a"), site("b")])
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert [s["site_id"] for s in response.json()] == ["a", "b"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_site_reaches_the_repository_through_the_session(
|
||||||
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=site("a"))
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites/a")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["site_id"] == "a"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_site_returns_404_when_the_session_finds_nothing(
|
||||||
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
fake_session(result=None)
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites/inconnu")
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
from collections.abc import Callable, Iterator
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from app.api.deps import get_current_principal, get_stats_service
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.services.stats import ConsumptionSummary, SiteConsumption
|
||||||
|
|
||||||
|
|
||||||
|
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||||
|
return Principal(
|
||||||
|
id=uuid4(),
|
||||||
|
email=f"{role.value}@enervision.fr",
|
||||||
|
role=role,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FauxService:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.resume = ConsumptionSummary(
|
||||||
|
timestamp=datetime.now(UTC),
|
||||||
|
total_sites=1,
|
||||||
|
total_consumption_kw=87.34,
|
||||||
|
total_capacity_kw=200,
|
||||||
|
average_load_percent=43.7,
|
||||||
|
sites=[
|
||||||
|
SiteConsumption(
|
||||||
|
site_id="SITE001",
|
||||||
|
site_name="Bureau Paris La Défense",
|
||||||
|
current_consumption_kw=87.34,
|
||||||
|
capacity_kw=200,
|
||||||
|
load_percent=43.7,
|
||||||
|
data_quality="good",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def summary(self) -> ConsumptionSummary:
|
||||||
|
return self.resume
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def servi(app: FastAPI) -> Iterator[Callable[[], FauxService]]:
|
||||||
|
def installe() -> FauxService:
|
||||||
|
service = FauxService()
|
||||||
|
app.dependency_overrides[get_stats_service] = lambda: service
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: principal()
|
||||||
|
return service
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_stats_service, None)
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_summary_returns_the_service_result(
|
||||||
|
servi: Callable[[], FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/stats/summary")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
corps = response.json()
|
||||||
|
assert corps["total_sites"] == 1
|
||||||
|
assert corps["sites"][0]["site_id"] == "SITE001"
|
||||||
|
assert corps["sites"][0]["data_quality"] == "good"
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user