Compare commits
212
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3047f53e8 | ||
|
|
ec63798807 | ||
|
|
1e168ef03e | ||
|
|
ddf7e17788 | ||
|
|
56e8f95729 | ||
|
|
91d435748c | ||
|
|
0b41580310 | ||
|
|
e3d436ea53 | ||
|
|
c453700b13 | ||
|
|
f427f8a8f3 | ||
|
|
7be8a44e89 | ||
|
|
2095ad6bd3 | ||
|
|
fb06bf0062 | ||
|
|
e27142c7db | ||
|
|
77feabcbad | ||
|
|
18a4be6e38 | ||
|
|
12fb8860d1 | ||
|
|
7c2936f2ef | ||
|
|
297d85a0ca | ||
|
|
af58172742 | ||
|
|
b433e01fa8 | ||
|
|
5eb74aa64a | ||
|
|
cc0a58ac4c | ||
|
|
2400b6f05e | ||
|
|
9e33c276d6 | ||
|
|
6cb9ac00cb | ||
|
|
c1f63889c1 | ||
|
|
5875e8c239 | ||
|
|
c8383014a8 | ||
|
|
3cf9194d4c | ||
|
|
8def1e23af | ||
|
|
56c134beb0 | ||
|
|
8fb5ab9f65 | ||
|
|
e22feac2c4 | ||
|
|
5581cb1ef3 | ||
|
|
1d8c986386 | ||
|
|
85cb7c9eeb | ||
|
|
39b1d28ead | ||
|
|
5394257855 | ||
|
|
c741ffc827 | ||
|
|
d7f775f9f7 | ||
|
|
e381e0de09 | ||
|
|
7674955637 | ||
|
|
19cfac1cff | ||
|
|
1fce577a78 | ||
|
|
063092f2c7 | ||
|
|
1afaee069f | ||
|
|
7bc9a09489 | ||
|
|
921da48eb1 | ||
|
|
4ee2109628 | ||
|
|
ec1c05ad54 | ||
|
|
334ca5982b | ||
|
|
2465021d61 | ||
|
|
278299c2b1 | ||
|
|
4f69199734 | ||
|
|
1cca4f130c | ||
|
|
016f226fdb | ||
|
|
88f4f9a601 | ||
|
|
ed7311d4ef | ||
|
|
ff68a51424 | ||
|
|
11f9b1bcd5 | ||
|
|
41c18a3bb1 | ||
|
|
00ef725249 | ||
|
|
34f35f3ca0 | ||
|
|
f5cac1c2a8 | ||
|
|
8e07168a5e | ||
|
|
916b5d246a | ||
|
|
d167b64188 | ||
|
|
7913518c4b | ||
|
|
2ad7692f1c | ||
|
|
a158d6f84c | ||
|
|
7dfd7a7e74 | ||
|
|
8d28113f03 | ||
|
|
62932e57c3 | ||
|
|
cd4fd962be | ||
|
|
517144f7e5 | ||
|
|
cc7ca2d359 | ||
|
|
bbafe7d119 | ||
|
|
9c78c6dc38 | ||
|
|
9161b74874 | ||
|
|
6798d35572 | ||
|
|
f03dce5fe3 | ||
|
|
74ac1b4577 | ||
|
|
ebb72fb399 | ||
|
|
b2d52823ba | ||
|
|
fcbfcc8eb2 | ||
|
|
3692d486c6 | ||
|
|
24bf8bf4b9 | ||
|
|
9f465538bf | ||
|
|
515a92b395 | ||
|
|
0174272bdd | ||
|
|
c740b61b24 | ||
|
|
5669cd63ec | ||
|
|
2f97e4d434 | ||
|
|
07ea8d21dc | ||
|
|
06cb60463c | ||
|
|
1c6b6105bd | ||
|
|
77440281f8 | ||
|
|
63ee79cf32 | ||
|
|
76fa90dfcb | ||
|
|
6ecec1afef | ||
|
|
e13096c62a | ||
|
|
970a4a50b8 | ||
|
|
3fb907d6f6 | ||
|
|
c7490d01b3 | ||
|
|
523b623dc1 | ||
|
|
61e031fc16 | ||
|
|
781644b28e | ||
|
|
1654e4dd81 | ||
|
|
e50921c907 | ||
|
|
56f7211f0b | ||
|
|
730adb69b1 | ||
|
|
f43c9f76a0 | ||
|
|
c83fd889b8 | ||
|
|
04e4913952 | ||
|
|
cf22b2ae55 | ||
|
|
12c5cf87ad | ||
|
|
7b076171d2 | ||
|
|
ad149db0cb | ||
|
|
50dcb4de32 | ||
|
|
d25e544db6 | ||
|
|
d1e4d8cfa0 | ||
|
|
22ff1d93f4 | ||
|
|
1f0eb410eb | ||
|
|
078983a41d | ||
|
|
d632af57b8 | ||
|
|
596cf43eda | ||
|
|
fabd073aaf | ||
|
|
31a9cb109f | ||
|
|
50dddf952b | ||
|
|
fc6600aeaf | ||
|
|
1325a75e9a | ||
|
|
16a0cc4d3b | ||
|
|
11baea7117 | ||
|
|
5e7cb005ac | ||
|
|
3347fa5bdb | ||
|
|
da481d7485 | ||
|
|
344f82fcdd | ||
|
|
61b3494d12 | ||
|
|
44468e85d7 | ||
|
|
580da72eff | ||
|
|
e85c83972a | ||
|
|
da97e6aa8b | ||
|
|
0259f66b62 | ||
|
|
7b9406965e | ||
|
|
881f503f1a | ||
|
|
918bd971da | ||
|
|
6c1f86b4ce | ||
|
|
3eb5a0e8dc | ||
|
|
c733ccfc62 | ||
|
|
b5cffbf56f | ||
|
|
cdef30736a | ||
|
|
e3e0e843d0 | ||
|
|
3ef7de5baa | ||
|
|
c3b7c818aa | ||
|
|
ff6e3c288c | ||
|
|
935782bbca | ||
|
|
c04ce9a9ae | ||
|
|
128133761f | ||
|
|
b032f084fc | ||
|
|
2390e58f78 | ||
|
|
b300be5186 | ||
|
|
b8f806518f | ||
|
|
6c4684a4f6 | ||
|
|
bfbd9ee2cc | ||
|
|
3b7383697e | ||
|
|
c60081a5ac | ||
|
|
cb2ac8c2c2 | ||
|
|
83392c7ff4 | ||
|
|
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 | ||
|
|
6bc2c3793f | ||
|
|
49f46978b0 | ||
|
|
f4d05a8ca9 | ||
|
|
20e7374d90 | ||
|
|
351e928309 | ||
|
|
91f4f007d3 | ||
|
|
4de5fb0935 | ||
|
|
6161a432c3 | ||
|
|
26704831e4 | ||
|
|
56118f45b9 |
@@ -0,0 +1,27 @@
|
|||||||
|
# Dépendances (réinstallées dans l'image)
|
||||||
|
node_modules/
|
||||||
|
vendor/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
# Git et IDE
|
||||||
|
.git/
|
||||||
|
.gitignore
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
|
||||||
|
# Fichiers de build locaux
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Secrets et config locale (CRITIQUE : risque d'exfiltration)
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
secrets/
|
||||||
|
.npmrc
|
||||||
|
.pypirc
|
||||||
|
kubeconfig
|
||||||
@@ -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,40 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
# Frontend — npm
|
||||||
|
- package-ecosystem: "npm"
|
||||||
|
directory: "/apps/frontend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
frontend-dependencies:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
# Backend — uv (lit pyproject.toml / uv.lock)
|
||||||
|
- package-ecosystem: "uv"
|
||||||
|
directory: "/apps/backend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
backend-dependencies:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
# Les workflows GitHub Actions eux-mêmes ont aussi des dépendances à jour
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|
||||||
|
# Si un Dockerfile existe pour le backend
|
||||||
|
- package-ecosystem: "docker"
|
||||||
|
directory: "/apps/backend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|
||||||
|
- package-ecosystem: "docker"
|
||||||
|
directory: "/apps/frontend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
security-audit:
|
||||||
|
name: Audit des dépendances
|
||||||
|
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
|
||||||
|
|
||||||
|
# L'audit porte sur le verrou, pas sur l'environnement : sinon pip-audit auditerait
|
||||||
|
# aussi les paquets que son propre `--with` injecte, hors dépendances du projet.
|
||||||
|
- name: Audite les dépendances livrées
|
||||||
|
# Piège : sans `shell: bash`, un échec de `uv export` serait masqué par le pipe.
|
||||||
|
shell: bash
|
||||||
|
run: uv export --frozen --no-dev --no-emit-project --no-hashes | uvx pip-audit --requirement /dev/stdin --no-deps
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
name: Frontend
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "apps/frontend/**"
|
||||||
|
- ".github/workflows/frontend.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "apps/frontend/**"
|
||||||
|
- ".github/workflows/frontend.yml"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
|
||||||
|
- run: npm ci
|
||||||
|
working-directory: apps/frontend
|
||||||
|
- run: npm run build
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
security-audit:
|
||||||
|
name: Audit des dépendances
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
# Seuil high : une vulnérabilité moderate de devDependency ne doit pas bloquer une livraison.
|
||||||
|
- run: npm audit --audit-level=high --package-lock-only
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
test:
|
||||||
|
needs: build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- name : Installation des dépendances (Front)
|
||||||
|
run: npm ci
|
||||||
|
working-directory: apps/frontend
|
||||||
|
- name : Lancement des tests et génénration du rapport de couverture (Front)
|
||||||
|
run: npm test --watch=false --code-coverage --coverageReporters=lcov
|
||||||
|
working-directory: apps/frontend
|
||||||
|
- name: Upload coverage
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: frontend-coverage
|
||||||
|
path: apps/frontend/coverage/frontend/lcov.info
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
name: ML
|
||||||
|
|
||||||
|
# Piège : la version de Python vient de ml/.python-version, et doit rester en 3.14 (cf.
|
||||||
|
# .github/workflows/backend.yml, même contrainte).
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "ml/**"
|
||||||
|
- ".github/workflows/ml.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "ml/**"
|
||||||
|
- ".github/workflows/ml.yml"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ml-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verification:
|
||||||
|
name: Lint, typage et tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ml
|
||||||
|
|
||||||
|
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: ml/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 enervision_ml tests
|
||||||
|
|
||||||
|
# Aucun test ne touche PostgreSQL ni MLflow distant : tout tourne sur donnees
|
||||||
|
# synthetiques ou un magasin SQLite local jetable (cf. ml/tests/test_train.py).
|
||||||
|
- name: Tests
|
||||||
|
run: uv run pytest
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
name: SonarQube
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "apps/frontend/**"
|
||||||
|
- "apps/backend/**"
|
||||||
|
- ".github/workflows/sonarqube.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "apps/frontend/**"
|
||||||
|
- "apps/backend/**"
|
||||||
|
- ".github/workflows/sonarqube.yml"
|
||||||
|
|
||||||
|
|
||||||
|
# Build l'ensemble du projet, puis lance les tests
|
||||||
|
# Génère les rapports de couverture, puis lance l'analyse SonarQube
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-front:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
|
||||||
|
- run: npm ci
|
||||||
|
working-directory: apps/frontend
|
||||||
|
- run: npm run build
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
test-front:
|
||||||
|
needs: build-front
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
|
||||||
|
- name : Installation des dépendances (Front)
|
||||||
|
run: npm ci
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
- name : Lancement des tests et génénration du rapport de couverture (Front)
|
||||||
|
run: npm test --watch=false --code-coverage --coverageReporters=lcov
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
- name: Upload coverage
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: frontend-coverage
|
||||||
|
path: apps/frontend/coverage/frontend/lcov.info
|
||||||
|
|
||||||
|
build-back:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- 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
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Vérifie le formatage
|
||||||
|
run: uv run ruff format --check .
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Analyse statique
|
||||||
|
run: uv run ruff check --output-format=github .
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Typage
|
||||||
|
run: uv run mypy app
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
|
||||||
|
test-back:
|
||||||
|
needs: build-back
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
|
||||||
|
- name : Lancement des tests et génénration du rapport de couverture (Back)
|
||||||
|
run: uv run pytest --cov-fail-under=85 --cov-report=xml
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Upload coverage
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: backend-coverage
|
||||||
|
path: apps/backend/coverage.xml
|
||||||
|
|
||||||
|
sonarqube:
|
||||||
|
needs: [build-front, build-back, test-front, test-back]
|
||||||
|
name: SonarQube
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Téléchargement du rapport de couverture (Front)
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: frontend-coverage
|
||||||
|
path: apps/frontend/coverage/frontend
|
||||||
|
- name: Téléchargement du rapport de couverture (Back)
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: backend-coverage
|
||||||
|
path: apps/backend
|
||||||
|
- name: SonarQube Scan
|
||||||
|
uses: SonarSource/sonarqube-scan-action@v8
|
||||||
|
env:
|
||||||
|
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
# 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/raw/*
|
||||||
|
!data/raw/.gitkeep
|
||||||
|
*.sqlite3
|
||||||
|
monitoring/grafana/data/
|
||||||
|
monitoring/prometheus/data/
|
||||||
|
|
||||||
|
# ML : jeu de donnees, modeles entraines et suivi MLflow local, tous generes/volumineux
|
||||||
|
ml/data/
|
||||||
|
ml/models/*
|
||||||
|
!ml/models/.gitkeep
|
||||||
|
ml/mlruns/
|
||||||
|
ml/mlartifacts/
|
||||||
|
ml/mlflow.db
|
||||||
|
|
||||||
|
# IDE et OS
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
Generated
-23
@@ -1,23 +0,0 @@
|
|||||||
# This file is maintained automatically by "terraform init".
|
|
||||||
# Manual edits may be lost in future updates.
|
|
||||||
|
|
||||||
provider "registry.terraform.io/kreuzwerker/docker" {
|
|
||||||
version = "3.9.0"
|
|
||||||
constraints = "~> 3.0"
|
|
||||||
hashes = [
|
|
||||||
"h1:MmhVJBgNpE2Fbksv/XObZJncwm4th4mFE7Ai+6LiIy4=",
|
|
||||||
"zh:0ead8281830e9b9496651282235d9a139ba1b1b6ff79e395eb8c78658dc446b9",
|
|
||||||
"zh:0f17d37d8d3872df3fb75c68b5272e0c981343f53b506a9675b4405191edd3ef",
|
|
||||||
"zh:11d50b37323874427c6d2a08b737d3c7707c8301fdd236c94485cf2828d0b14b",
|
|
||||||
"zh:32f6f9b847446054e2db3d72886ef2f1d1aa51a6d0dac42340b07dad18e3f28f",
|
|
||||||
"zh:5ea5c67668b5dcbda560dc6104b788a9bfc974d52f02f7886889b77cc0e5d248",
|
|
||||||
"zh:5fb19a0b07edc344cd3ddeeb9cfb3d183089deb7a6a94a7b22a583aa1712596b",
|
|
||||||
"zh:602a7ece444e2a142ec5245abb98e7a1a990a68afae2df63b6c85ec084f0c5d7",
|
|
||||||
"zh:693dce278524ad8a6d6c9dd7a01bcd63bb85189639198f8d0b044ab0e5099401",
|
|
||||||
"zh:72e9911568103576c6a78fa38841cfd45eeb88ad22a2c649eb140a377a5b3c26",
|
|
||||||
"zh:956b62b6857cbb467b50158601f01b1203daa34cbd447dcc7f044c327e878b68",
|
|
||||||
"zh:9d372bac0d4479868b34485fb4966ba7bb525938f818b6a625f4977004ea83f9",
|
|
||||||
"zh:e06658a51427f9f53dbdb06263406fc1bc56d1a4fb5e7eb660d7cdfc22f596bd",
|
|
||||||
"zh:eee38dadf672b946419af25160eae7c03fc2afbb14f39f2f1d2a7404d647e2f7",
|
|
||||||
]
|
|
||||||
}
|
|
||||||
-870
@@ -1,870 +0,0 @@
|
|||||||
|
|
||||||
<a name="v3.9.0"></a>
|
|
||||||
## [v3.9.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.8.0...v3.9.0) (2025-11-09)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Add file requested by hashicorp ([#813](https://github.com/kreuzwerker/terraform-provider-docker/issues/813))
|
|
||||||
* Prepare release v3.8.0 ([#806](https://github.com/kreuzwerker/terraform-provider-docker/issues/806))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implement caching of docker provider ([#808](https://github.com/kreuzwerker/terraform-provider-docker/issues/808))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* test attribute of docker_service healthcheck is not required ([#815](https://github.com/kreuzwerker/terraform-provider-docker/issues/815))
|
|
||||||
* docker_service label can be updated without recreate ([#814](https://github.com/kreuzwerker/terraform-provider-docker/issues/814))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.8.0"></a>
|
|
||||||
## [v3.8.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.7.0...v3.8.0) (2025-10-08)
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Add build attribute for docker_registry_image ([#805](https://github.com/kreuzwerker/terraform-provider-docker/issues/805))
|
|
||||||
* Add build option for additional contexts ([#798](https://github.com/kreuzwerker/terraform-provider-docker/issues/798))
|
|
||||||
* implement mac_address for networks_advanced ([#794](https://github.com/kreuzwerker/terraform-provider-docker/issues/794))
|
|
||||||
* Implement docker cluster volume ([#793](https://github.com/kreuzwerker/terraform-provider-docker/issues/793))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.7.0"></a>
|
|
||||||
## [v3.7.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.6.2...v3.7.0) (2025-08-19)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.7.0 ([#774](https://github.com/kreuzwerker/terraform-provider-docker/issues/774))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implement memory_reservation and network_mode enhancements ([#773](https://github.com/kreuzwerker/terraform-provider-docker/issues/773))
|
|
||||||
* Implement cache_from and cache_to for docker_image ([#772](https://github.com/kreuzwerker/terraform-provider-docker/issues/772))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Correctly get and set nanoCPUs for docker_container ([#771](https://github.com/kreuzwerker/terraform-provider-docker/issues/771))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.6.2"></a>
|
|
||||||
## [v3.6.2](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.6.1...v3.6.2) (2025-06-13)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.6.2 ([#750](https://github.com/kreuzwerker/terraform-provider-docker/issues/750))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Allow digest in image name ([#744](https://github.com/kreuzwerker/terraform-provider-docker/issues/744))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Remove wrong buildkit version assignment ([#747](https://github.com/kreuzwerker/terraform-provider-docker/issues/747))
|
|
||||||
* Reading non existant volume should recreate ([#749](https://github.com/kreuzwerker/terraform-provider-docker/issues/749))
|
|
||||||
* Typo in cgroup_parent handling ([#746](https://github.com/kreuzwerker/terraform-provider-docker/issues/746))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.6.1"></a>
|
|
||||||
## [v3.6.1](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.6.0...v3.6.1) (2025-06-05)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.6.1 ([#743](https://github.com/kreuzwerker/terraform-provider-docker/issues/743))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* allow to set the cgroup parent for container ([#609](https://github.com/kreuzwerker/terraform-provider-docker/issues/609))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.6.0"></a>
|
|
||||||
## [v3.6.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.5.0...v3.6.0) (2025-05-25)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.6.0 ([#735](https://github.com/kreuzwerker/terraform-provider-docker/issues/735))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implement correct cpu scheduler settings ([#732](https://github.com/kreuzwerker/terraform-provider-docker/issues/732))
|
|
||||||
* Add implementaion of capabilities in docker servic ([#727](https://github.com/kreuzwerker/terraform-provider-docker/issues/727))
|
|
||||||
* implement Buildx builder resource ([#724](https://github.com/kreuzwerker/terraform-provider-docker/issues/724))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Implement buildx fixes for general buildkit support and platform handling ([#734](https://github.com/kreuzwerker/terraform-provider-docker/issues/734))
|
|
||||||
* Make endpoint validation less strict ([#733](https://github.com/kreuzwerker/terraform-provider-docker/issues/733))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.5.0"></a>
|
|
||||||
## [v3.5.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.4.0...v3.5.0) (2025-05-06)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.5.0 ([#721](https://github.com/kreuzwerker/terraform-provider-docker/issues/721))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implement using of buildx for docker_image ([#717](https://github.com/kreuzwerker/terraform-provider-docker/issues/717))
|
|
||||||
* Support registries that return empty auth scope [#646](https://github.com/kreuzwerker/terraform-provider-docker/issues/646)
|
|
||||||
* Implement registry_image_manifests data source ([#714](https://github.com/kreuzwerker/terraform-provider-docker/issues/714))
|
|
||||||
* Implement healthcheck start interval ([#713](https://github.com/kreuzwerker/terraform-provider-docker/issues/713))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.4.0"></a>
|
|
||||||
## [v3.4.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.3.0...v3.4.0) (2025-04-25)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.4.0 ([#712](https://github.com/kreuzwerker/terraform-provider-docker/issues/712))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implement volume_options subpath ([#710](https://github.com/kreuzwerker/terraform-provider-docker/issues/710))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Prevent recreation of image name is intentionally set to a fixed value ([#711](https://github.com/kreuzwerker/terraform-provider-docker/issues/711))
|
|
||||||
* Improve container wait handling ([#709](https://github.com/kreuzwerker/terraform-provider-docker/issues/709))
|
|
||||||
* Use auth_config block also for registry_image delete functionality ([#708](https://github.com/kreuzwerker/terraform-provider-docker/issues/708))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.3.0"></a>
|
|
||||||
## [v3.3.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.2.0...v3.3.0) (2025-04-19)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.3.0 ([#705](https://github.com/kreuzwerker/terraform-provider-docker/issues/705))
|
|
||||||
* Update terraform-plugin-sdk/v2 dependency ([#699](https://github.com/kreuzwerker/terraform-provider-docker/issues/699))
|
|
||||||
* Update docker/docker and docker/cli to newest stable ([#695](https://github.com/kreuzwerker/terraform-provider-docker/issues/695))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implement support for docker context ([#704](https://github.com/kreuzwerker/terraform-provider-docker/issues/704))
|
|
||||||
* disable_docker_daemon_check for provider ([#703](https://github.com/kreuzwerker/terraform-provider-docker/issues/703))
|
|
||||||
* Implement tag triggers for docker_tag resource ([#702](https://github.com/kreuzwerker/terraform-provider-docker/issues/702))
|
|
||||||
* Implement auth_config for docker_registry_image ([#701](https://github.com/kreuzwerker/terraform-provider-docker/issues/701))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Store correctly ports from server ([#698](https://github.com/kreuzwerker/terraform-provider-docker/issues/698))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.2.0"></a>
|
|
||||||
## [v3.2.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.1.2...v3.2.0) (2025-04-16)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.2.0 ([#694](https://github.com/kreuzwerker/terraform-provider-docker/issues/694))
|
|
||||||
* Upgrade golangci-lint to next major version ([#686](https://github.com/kreuzwerker/terraform-provider-docker/issues/686))
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* Consolidated update of docs from several PRs ([#691](https://github.com/kreuzwerker/terraform-provider-docker/issues/691))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implement upload permissions in docker_container resource ([#693](https://github.com/kreuzwerker/terraform-provider-docker/issues/693))
|
|
||||||
* Implement docker_image timeouts ([#692](https://github.com/kreuzwerker/terraform-provider-docker/issues/692))
|
|
||||||
* Add support for build-secrets ([#604](https://github.com/kreuzwerker/terraform-provider-docker/issues/604))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Authentication to ECR public ([#690](https://github.com/kreuzwerker/terraform-provider-docker/issues/690))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.1.2"></a>
|
|
||||||
## [v3.1.2](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.1.1...v3.1.2) (2025-04-15)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* prepare release 3.1.2 ([#688](https://github.com/kreuzwerker/terraform-provider-docker/issues/688))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.1.1"></a>
|
|
||||||
## [v3.1.1](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.1.0...v3.1.1) (2025-04-14)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release 3.1.1 ([#687](https://github.com/kreuzwerker/terraform-provider-docker/issues/687))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.1.0"></a>
|
|
||||||
## [v3.1.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.0.2...v3.1.0) (2025-04-14)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release 3.1.0 ([#685](https://github.com/kreuzwerker/terraform-provider-docker/issues/685))
|
|
||||||
* update Go version to 1.22 for consistency across workflows, jo… ([#613](https://github.com/kreuzwerker/terraform-provider-docker/issues/613))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* support setting cpu shares ([#575](https://github.com/kreuzwerker/terraform-provider-docker/issues/575))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Use build_args everywhere and update documentation ([#681](https://github.com/kreuzwerker/terraform-provider-docker/issues/681))
|
|
||||||
* Compress build context before sending it to Docker ([#461](https://github.com/kreuzwerker/terraform-provider-docker/issues/461))
|
|
||||||
* Set correct default network driver and fix a test ([#677](https://github.com/kreuzwerker/terraform-provider-docker/issues/677))
|
|
||||||
|
|
||||||
### Typo
|
|
||||||
|
|
||||||
* s/presend/present/ ([#606](https://github.com/kreuzwerker/terraform-provider-docker/issues/606))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.0.2"></a>
|
|
||||||
## [v3.0.2](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.0.1...v3.0.2) (2023-03-17)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.0.2
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* correct spelling of "networks_advanced" ([#517](https://github.com/kreuzwerker/terraform-provider-docker/issues/517))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Implement proxy support. ([#529](https://github.com/kreuzwerker/terraform-provider-docker/issues/529))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.0.1"></a>
|
|
||||||
## [v3.0.1](https://github.com/kreuzwerker/terraform-provider-docker/compare/v3.0.0...v3.0.1) (2023-01-13)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.0.1
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Access health of container correctly. ([#506](https://github.com/kreuzwerker/terraform-provider-docker/issues/506))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v3.0.0"></a>
|
|
||||||
## [v3.0.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.25.0...v3.0.0) (2023-01-13)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v3.0.0
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* Update documentation.
|
|
||||||
* Add migration guide and update README ([#502](https://github.com/kreuzwerker/terraform-provider-docker/issues/502))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Prepare v3 release ([#503](https://github.com/kreuzwerker/terraform-provider-docker/issues/503))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.25.0"></a>
|
|
||||||
## [v2.25.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.24.0...v2.25.0) (2023-01-05)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.25.0
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* Add documentation of remote hosts. ([#498](https://github.com/kreuzwerker/terraform-provider-docker/issues/498))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Migrate build block to `docker_image` ([#501](https://github.com/kreuzwerker/terraform-provider-docker/issues/501))
|
|
||||||
* Add platform attribute to docker_image resource ([#500](https://github.com/kreuzwerker/terraform-provider-docker/issues/500))
|
|
||||||
* Add sysctl implementation to container of docker_service. ([#499](https://github.com/kreuzwerker/terraform-provider-docker/issues/499))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.24.0"></a>
|
|
||||||
## [v2.24.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.23.1...v2.24.0) (2022-12-23)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.24.0
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* Fix generated website.
|
|
||||||
* Update command typo ([#487](https://github.com/kreuzwerker/terraform-provider-docker/issues/487))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* cgroupns support ([#497](https://github.com/kreuzwerker/terraform-provider-docker/issues/497))
|
|
||||||
* Add triggers attribute to docker_registry_image ([#496](https://github.com/kreuzwerker/terraform-provider-docker/issues/496))
|
|
||||||
* Support registries with disabled auth ([#494](https://github.com/kreuzwerker/terraform-provider-docker/issues/494))
|
|
||||||
* add IPAM options block for docker networks ([#491](https://github.com/kreuzwerker/terraform-provider-docker/issues/491))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Pin data source specific tag test to older tag.
|
|
||||||
|
|
||||||
### Tests
|
|
||||||
|
|
||||||
* Add test for parsing auth headers.
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.23.1"></a>
|
|
||||||
## [v2.23.1](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.23.0...v2.23.1) (2022-11-23)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.23.1
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Update shasum of busybox:1.35.0 tag in test.
|
|
||||||
* Handle Auth Header Scopes ([#482](https://github.com/kreuzwerker/terraform-provider-docker/issues/482))
|
|
||||||
* Set OS_ARCH from GOHOSTOS and GOHOSTARCH ([#477](https://github.com/kreuzwerker/terraform-provider-docker/issues/477))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.23.0"></a>
|
|
||||||
## [v2.23.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.22.0...v2.23.0) (2022-11-02)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.23.0
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* wait container healthy state ([#467](https://github.com/kreuzwerker/terraform-provider-docker/issues/467))
|
|
||||||
* add docker logs data source ([#471](https://github.com/kreuzwerker/terraform-provider-docker/issues/471))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Update shasum of busybox:1.35.0 tag in test.
|
|
||||||
* Update shasum of busybox:1.35.0 tag
|
|
||||||
* Correct provider name to match the public registry ([#462](https://github.com/kreuzwerker/terraform-provider-docker/issues/462))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.22.0"></a>
|
|
||||||
## [v2.22.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.21.0...v2.22.0) (2022-09-20)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.22.0
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Configurable timeout for docker_container resource stateChangeConf ([#454](https://github.com/kreuzwerker/terraform-provider-docker/issues/454))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* oauth authorization support for azurecr ([#451](https://github.com/kreuzwerker/terraform-provider-docker/issues/451))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.21.0"></a>
|
|
||||||
## [v2.21.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.20.3...v2.21.0) (2022-09-05)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.21.0
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* Fix docker config example.
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Add image_id attribute to docker_image resource. ([#450](https://github.com/kreuzwerker/terraform-provider-docker/issues/450))
|
|
||||||
* Update used goversion to 1.18. ([#449](https://github.com/kreuzwerker/terraform-provider-docker/issues/449))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Replace deprecated .latest attribute with new image_id. ([#453](https://github.com/kreuzwerker/terraform-provider-docker/issues/453))
|
|
||||||
* Remove reading part of docker_tag resource. ([#448](https://github.com/kreuzwerker/terraform-provider-docker/issues/448))
|
|
||||||
* Fix repo_digest value for DockerImageDatasource test.
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.20.3"></a>
|
|
||||||
## [v2.20.3](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.20.2...v2.20.3) (2022-08-31)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.20.3
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Docker Registry Image data source use HEAD request to query image digest ([#433](https://github.com/kreuzwerker/terraform-provider-docker/issues/433))
|
|
||||||
* Adding Support for Windows Paths in Bash ([#438](https://github.com/kreuzwerker/terraform-provider-docker/issues/438))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.20.2"></a>
|
|
||||||
## [v2.20.2](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.20.1...v2.20.2) (2022-08-10)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.20.2
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Check the operating system for determining the default Docker socket ([#427](https://github.com/kreuzwerker/terraform-provider-docker/issues/427))
|
|
||||||
|
|
||||||
### Reverts
|
|
||||||
|
|
||||||
* fix(deps): update module github.com/golangci/golangci-lint to v1.48.0 ([#423](https://github.com/kreuzwerker/terraform-provider-docker/issues/423))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.20.1"></a>
|
|
||||||
## [v2.20.1](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.20.0...v2.20.1) (2022-08-10)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.20.1
|
|
||||||
* Reduce time to setup AccTests ([#430](https://github.com/kreuzwerker/terraform-provider-docker/issues/430))
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* Improve docker network usage documentation [skip-ci]
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implement triggers attribute for docker_image. ([#425](https://github.com/kreuzwerker/terraform-provider-docker/issues/425))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Add ForceTrue to docker_image name attribute. ([#421](https://github.com/kreuzwerker/terraform-provider-docker/issues/421))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.20.0"></a>
|
|
||||||
## [v2.20.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.19.0...v2.20.0) (2022-07-28)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.20.0
|
|
||||||
* Fix release targets in Makefile.
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Implementation of `docker_tag` resource. ([#418](https://github.com/kreuzwerker/terraform-provider-docker/issues/418))
|
|
||||||
* Implement support for insecure registries ([#414](https://github.com/kreuzwerker/terraform-provider-docker/issues/414))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.19.0"></a>
|
|
||||||
## [v2.19.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.18.1...v2.19.0) (2022-07-15)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.19.0
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* Add gpu flag to docker_container resource ([#405](https://github.com/kreuzwerker/terraform-provider-docker/issues/405))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Enable authentication to multiple registries again. ([#400](https://github.com/kreuzwerker/terraform-provider-docker/issues/400))
|
|
||||||
* ECR authentication ([#409](https://github.com/kreuzwerker/terraform-provider-docker/issues/409))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.18.1"></a>
|
|
||||||
## [v2.18.1](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.18.0...v2.18.1) (2022-07-14)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* Prepare release v2.18.1
|
|
||||||
* Automate changelog generation [skip ci]
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Improve searchLocalImages error handling. ([#407](https://github.com/kreuzwerker/terraform-provider-docker/issues/407))
|
|
||||||
* Throw errors when any part of docker config file handling goes wrong. ([#406](https://github.com/kreuzwerker/terraform-provider-docker/issues/406))
|
|
||||||
* Enables having a Dockerfile outside the context ([#402](https://github.com/kreuzwerker/terraform-provider-docker/issues/402))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.18.0"></a>
|
|
||||||
## [v2.18.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.17.0...v2.18.0) (2022-07-11)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* prepare release v2.18.0
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* add runtime, stop_signal and stop_timeout properties to the docker_container resource ([#364](https://github.com/kreuzwerker/terraform-provider-docker/issues/364))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Correctly handle build files and context for docker_registry_image ([#398](https://github.com/kreuzwerker/terraform-provider-docker/issues/398))
|
|
||||||
* Switch to proper go tools mechanism to fix website-* workflows. ([#399](https://github.com/kreuzwerker/terraform-provider-docker/issues/399))
|
|
||||||
* compare relative paths when excluding, fixes kreuzwerker[#280](https://github.com/kreuzwerker/terraform-provider-docker/issues/280) ([#397](https://github.com/kreuzwerker/terraform-provider-docker/issues/397))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.17.0"></a>
|
|
||||||
## [v2.17.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.16.0...v2.17.0) (2022-06-23)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* prepare release v2.17.0
|
|
||||||
* Exclude examples directory from renovate.
|
|
||||||
* remove the workflow to close stale issues and pull requests ([#371](https://github.com/kreuzwerker/terraform-provider-docker/issues/371))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* update go package files directly on master to fix build.
|
|
||||||
* correct authentication for ghcr.io registry([#349](https://github.com/kreuzwerker/terraform-provider-docker/issues/349))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.16.0"></a>
|
|
||||||
## [v2.16.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.15.0...v2.16.0) (2022-01-24)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* prepare release v2.16.0
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* fix service options ([#337](https://github.com/kreuzwerker/terraform-provider-docker/issues/337))
|
|
||||||
* update registry_image.md ([#321](https://github.com/kreuzwerker/terraform-provider-docker/issues/321))
|
|
||||||
* fix r/registry_image truncated docs ([#304](https://github.com/kreuzwerker/terraform-provider-docker/issues/304))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* add parameter for SSH options ([#335](https://github.com/kreuzwerker/terraform-provider-docker/issues/335))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* pass container rm flag ([#322](https://github.com/kreuzwerker/terraform-provider-docker/issues/322))
|
|
||||||
* add nil check of DriverConfig ([#315](https://github.com/kreuzwerker/terraform-provider-docker/issues/315))
|
|
||||||
* fmt of go files for go 1.17
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.15.0"></a>
|
|
||||||
## [v2.15.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.14.0...v2.15.0) (2021-08-11)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* prepare release v2.15.0
|
|
||||||
* re go gets terraform-plugin-docs
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* corrects authentication misspell. Closes [#264](https://github.com/kreuzwerker/terraform-provider-docker/issues/264)
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* add container storage opts ([#258](https://github.com/kreuzwerker/terraform-provider-docker/issues/258))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* add current timestamp for file upload to container ([#259](https://github.com/kreuzwerker/terraform-provider-docker/issues/259))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.14.0"></a>
|
|
||||||
## [v2.14.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.13.0...v2.14.0) (2021-07-09)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* prepare release v2.14.0
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* update to absolute path for registry image context ([#246](https://github.com/kreuzwerker/terraform-provider-docker/issues/246))
|
|
||||||
* update readme with logos and subsections ([#235](https://github.com/kreuzwerker/terraform-provider-docker/issues/235))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* support terraform v1 ([#242](https://github.com/kreuzwerker/terraform-provider-docker/issues/242))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* Update the URL of the docker hub registry ([#230](https://github.com/kreuzwerker/terraform-provider-docker/issues/230))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.13.0"></a>
|
|
||||||
## [v2.13.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.12.2...v2.13.0) (2021-06-22)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* prepare release v2.13.0
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* fix a few typos ([#216](https://github.com/kreuzwerker/terraform-provider-docker/issues/216))
|
|
||||||
* fix typos in docker_image example usage ([#213](https://github.com/kreuzwerker/terraform-provider-docker/issues/213))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.12.2"></a>
|
|
||||||
## [v2.12.2](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.12.1...v2.12.2) (2021-05-26)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* prepare release v2.12.2
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.12.1"></a>
|
|
||||||
## [v2.12.1](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.12.0...v2.12.1) (2021-05-26)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* update changelog for v2.12.1
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* add service host flattener with space split ([#205](https://github.com/kreuzwerker/terraform-provider-docker/issues/205))
|
|
||||||
* service state upgradeV2 for empty auth
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.12.0"></a>
|
|
||||||
## [v2.12.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.11.0...v2.12.0) (2021-05-23)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* update changelog for v2.12.0
|
|
||||||
* ignore dist folder
|
|
||||||
* configure actions/stale ([#157](https://github.com/kreuzwerker/terraform-provider-docker/issues/157))
|
|
||||||
* add the guide about Terraform Configuration in Bug Report ([#139](https://github.com/kreuzwerker/terraform-provider-docker/issues/139))
|
|
||||||
* bump docker dependency to v20.10.5 ([#119](https://github.com/kreuzwerker/terraform-provider-docker/issues/119))
|
|
||||||
|
|
||||||
### Ci
|
|
||||||
|
|
||||||
* run acceptance tests with multiple Terraform versions ([#129](https://github.com/kreuzwerker/terraform-provider-docker/issues/129))
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* update for v2.12.0
|
|
||||||
* add releasing steps
|
|
||||||
* format `Guide of Bug report` ([#159](https://github.com/kreuzwerker/terraform-provider-docker/issues/159))
|
|
||||||
* add an example to build an image with docker_image ([#158](https://github.com/kreuzwerker/terraform-provider-docker/issues/158))
|
|
||||||
* add a guide about writing issues to CONTRIBUTING.md ([#149](https://github.com/kreuzwerker/terraform-provider-docker/issues/149))
|
|
||||||
* fix Github repository URL in README ([#136](https://github.com/kreuzwerker/terraform-provider-docker/issues/136))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* support darwin arm builds and golang 1.16 ([#140](https://github.com/kreuzwerker/terraform-provider-docker/issues/140))
|
|
||||||
* migrate to terraform-sdk v2 ([#102](https://github.com/kreuzwerker/terraform-provider-docker/issues/102))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* rewriting tar header fields ([#198](https://github.com/kreuzwerker/terraform-provider-docker/issues/198))
|
|
||||||
* test spaces for windows ([#190](https://github.com/kreuzwerker/terraform-provider-docker/issues/190))
|
|
||||||
* replace for loops with StateChangeConf ([#182](https://github.com/kreuzwerker/terraform-provider-docker/issues/182))
|
|
||||||
* skip sign on compile action
|
|
||||||
* assign map to rawState when it is nil to prevent panic ([#180](https://github.com/kreuzwerker/terraform-provider-docker/issues/180))
|
|
||||||
* search local images with Docker image ID ([#151](https://github.com/kreuzwerker/terraform-provider-docker/issues/151))
|
|
||||||
* set "ForceNew: true" to labelSchema ([#152](https://github.com/kreuzwerker/terraform-provider-docker/issues/152))
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.11.0"></a>
|
|
||||||
## [v2.11.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.10.0...v2.11.0) (2021-01-22)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* update changelog for v2.11.0
|
|
||||||
* updates changelog for v2.10.0
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* fix legacy configuration style ([#126](https://github.com/kreuzwerker/terraform-provider-docker/issues/126))
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* add properties -it (tty and stdin_opn) to docker container
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.10.0"></a>
|
|
||||||
## [v2.10.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.9.0...v2.10.0) (2021-01-08)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* updates changelog for 2.10.0
|
|
||||||
* ignores testing folders
|
|
||||||
* adds separate bug and ft req templates
|
|
||||||
|
|
||||||
### Ci
|
|
||||||
|
|
||||||
* bumps to docker version 20.10.1
|
|
||||||
* pins workflows to ubuntu:20.04 image
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* add labels to arguments of docker_service ([#105](https://github.com/kreuzwerker/terraform-provider-docker/issues/105))
|
|
||||||
* cleans readme
|
|
||||||
* adds coc and contributing
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* supports Docker plugin ([#35](https://github.com/kreuzwerker/terraform-provider-docker/issues/35))
|
|
||||||
* support max replicas of Docker Service Task Spec ([#112](https://github.com/kreuzwerker/terraform-provider-docker/issues/112))
|
|
||||||
* add force_remove option to r/image ([#104](https://github.com/kreuzwerker/terraform-provider-docker/issues/104))
|
|
||||||
* add local semantic commit validation ([#99](https://github.com/kreuzwerker/terraform-provider-docker/issues/99))
|
|
||||||
* add ability to lint/check of links in documentation locally ([#98](https://github.com/kreuzwerker/terraform-provider-docker/issues/98))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* set "latest" to tag when tag isn't specified ([#117](https://github.com/kreuzwerker/terraform-provider-docker/issues/117))
|
|
||||||
* image label for workflows
|
|
||||||
* remove all azure cps
|
|
||||||
|
|
||||||
### Pull Requests
|
|
||||||
|
|
||||||
* Merge pull request [#38](https://github.com/kreuzwerker/terraform-provider-docker/issues/38) from kreuzwerker/ci-ubuntu2004-workflow
|
|
||||||
* Merge pull request [#36](https://github.com/kreuzwerker/terraform-provider-docker/issues/36) from kreuzwerker/chore-gh-issue-tpl
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.9.0"></a>
|
|
||||||
## [v2.9.0](https://github.com/kreuzwerker/terraform-provider-docker/compare/v2.8.0...v2.9.0) (2020-12-25)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* updates changelog for 2.9.0
|
|
||||||
* update changelog 2.8.0 release date
|
|
||||||
* introduces golangci-lint ([#32](https://github.com/kreuzwerker/terraform-provider-docker/issues/32))
|
|
||||||
* fix changelog links
|
|
||||||
|
|
||||||
### Ci
|
|
||||||
|
|
||||||
* add gofmt's '-s' option
|
|
||||||
* remove unneeded make tasks
|
|
||||||
* fix test of website
|
|
||||||
|
|
||||||
### Doc
|
|
||||||
|
|
||||||
* devices is a block, not a boolean
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* adds support for OCI manifests ([#316](https://github.com/kreuzwerker/terraform-provider-docker/issues/316))
|
|
||||||
* adds security_opts to container config. ([#308](https://github.com/kreuzwerker/terraform-provider-docker/issues/308))
|
|
||||||
* adds support for init process injection for containers. ([#300](https://github.com/kreuzwerker/terraform-provider-docker/issues/300))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* changing mounts requires ForceNew ([#314](https://github.com/kreuzwerker/terraform-provider-docker/issues/314))
|
|
||||||
* allow healthcheck to be computed as container can specify ([#312](https://github.com/kreuzwerker/terraform-provider-docker/issues/312))
|
|
||||||
* treat null user as a no-op ([#318](https://github.com/kreuzwerker/terraform-provider-docker/issues/318))
|
|
||||||
* workdir null behavior ([#320](https://github.com/kreuzwerker/terraform-provider-docker/issues/320))
|
|
||||||
|
|
||||||
### Style
|
|
||||||
|
|
||||||
* format with gofumpt
|
|
||||||
|
|
||||||
### Pull Requests
|
|
||||||
|
|
||||||
* Merge pull request [#33](https://github.com/kreuzwerker/terraform-provider-docker/issues/33) from brandonros/patch-1
|
|
||||||
* Merge pull request [#11](https://github.com/kreuzwerker/terraform-provider-docker/issues/11) from suzuki-shunsuke/format-with-gofumpt
|
|
||||||
* Merge pull request [#26](https://github.com/kreuzwerker/terraform-provider-docker/issues/26) from kreuzwerker/ci/fix-website-ci
|
|
||||||
* Merge pull request [#8](https://github.com/kreuzwerker/terraform-provider-docker/issues/8) from dubo-dubon-duponey/patch1
|
|
||||||
|
|
||||||
|
|
||||||
<a name="v2.8.0"></a>
|
|
||||||
## v2.8.0 (2020-11-11)
|
|
||||||
|
|
||||||
### Chore
|
|
||||||
|
|
||||||
* updates changelog for 2.8.0
|
|
||||||
* removes travis.yml
|
|
||||||
* deactivates travis
|
|
||||||
* removes vendor dir ([#298](https://github.com/kreuzwerker/terraform-provider-docker/issues/298))
|
|
||||||
* bump go 115 ([#297](https://github.com/kreuzwerker/terraform-provider-docker/issues/297))
|
|
||||||
* documentation updates ([#286](https://github.com/kreuzwerker/terraform-provider-docker/issues/286))
|
|
||||||
* updates link syntax ([#287](https://github.com/kreuzwerker/terraform-provider-docker/issues/287))
|
|
||||||
* fix typo ([#292](https://github.com/kreuzwerker/terraform-provider-docker/issues/292))
|
|
||||||
|
|
||||||
### Ci
|
|
||||||
|
|
||||||
* reactivats all workflows
|
|
||||||
* fix website
|
|
||||||
* only run website workflow
|
|
||||||
* exports gopath manually
|
|
||||||
* fix absolute gopath for website
|
|
||||||
* make website check separate workflow
|
|
||||||
* fix workflow names
|
|
||||||
* adds website test to unit test
|
|
||||||
* adds acc test
|
|
||||||
* adds compile
|
|
||||||
* adds go version and goproxy env
|
|
||||||
* enables unit tests for master branch
|
|
||||||
* adds unit test workflow
|
|
||||||
* adds goreleaser and gh action
|
|
||||||
* bumps docker and ubuntu versions ([#241](https://github.com/kreuzwerker/terraform-provider-docker/issues/241))
|
|
||||||
* removes debug option from acc tests
|
|
||||||
* skips test which is flaky only on travis
|
|
||||||
|
|
||||||
### Deps
|
|
||||||
|
|
||||||
* github.com/hashicorp/terraform[@sdk](https://github.com/sdk)-v0.11-with-go-modules Updated via: go get github.com/hashicorp/terraform[@sdk](https://github.com/sdk)-v0.11-with-go-modules and go mod tidy
|
|
||||||
* use go modules for dep mgmt run go mod tidy remove govendor from makefile and travis config set appropriate env vars for go modules
|
|
||||||
|
|
||||||
### Docker
|
|
||||||
|
|
||||||
* improve validation of runtime constraints
|
|
||||||
|
|
||||||
### Docs
|
|
||||||
|
|
||||||
* update container.html.markdown ([#278](https://github.com/kreuzwerker/terraform-provider-docker/issues/278))
|
|
||||||
* update service.html.markdown ([#281](https://github.com/kreuzwerker/terraform-provider-docker/issues/281))
|
|
||||||
* update restart_policy for service. Closes [#228](https://github.com/kreuzwerker/terraform-provider-docker/issues/228)
|
|
||||||
* adds new label structure. Closes [#214](https://github.com/kreuzwerker/terraform-provider-docker/issues/214)
|
|
||||||
* update anchors with -1 suffix ([#178](https://github.com/kreuzwerker/terraform-provider-docker/issues/178))
|
|
||||||
* Fix misspelled words
|
|
||||||
* Fix exported attribute name in docker_registry_image
|
|
||||||
* Fix example for docker_registry_image ([#8308](https://github.com/kreuzwerker/terraform-provider-docker/issues/8308))
|
|
||||||
* provider/docker - network settings attrs
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
* conditionally adding port binding ([#293](https://github.com/kreuzwerker/terraform-provider-docker/issues/293)).
|
|
||||||
* adds docker Image build feature ([#283](https://github.com/kreuzwerker/terraform-provider-docker/issues/283))
|
|
||||||
* adds complete support for Docker credential helpers ([#253](https://github.com/kreuzwerker/terraform-provider-docker/issues/253))
|
|
||||||
* Expose IPv6 properties as attributes
|
|
||||||
* allow use of source file instead of content / content_base64 ([#240](https://github.com/kreuzwerker/terraform-provider-docker/issues/240))
|
|
||||||
* supports to update docker_container ([#236](https://github.com/kreuzwerker/terraform-provider-docker/issues/236))
|
|
||||||
* support to import some docker_container's attributes ([#234](https://github.com/kreuzwerker/terraform-provider-docker/issues/234))
|
|
||||||
* adds config file content as plain string ([#232](https://github.com/kreuzwerker/terraform-provider-docker/issues/232))
|
|
||||||
* make UID, GID, & mode for secrets and configs configurable ([#231](https://github.com/kreuzwerker/terraform-provider-docker/issues/231))
|
|
||||||
* adds import for resources ([#196](https://github.com/kreuzwerker/terraform-provider-docker/issues/196))
|
|
||||||
* add container ipc mode. ([#182](https://github.com/kreuzwerker/terraform-provider-docker/issues/182))
|
|
||||||
* adds container working dir ([#181](https://github.com/kreuzwerker/terraform-provider-docker/issues/181))
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
* ignores 'remove_volumes' on container import
|
|
||||||
* duplicated buildImage function
|
|
||||||
* port objects with the same internal port but different protocol trigger recreation of container ([#274](https://github.com/kreuzwerker/terraform-provider-docker/issues/274))
|
|
||||||
* panic to migrate schema of docker_container from v1 to v2 ([#271](https://github.com/kreuzwerker/terraform-provider-docker/issues/271)). Closes [#264](https://github.com/kreuzwerker/terraform-provider-docker/issues/264)
|
|
||||||
* pins docker registry for tests to v2.7.0
|
|
||||||
* prevent force recreate of container about some attributes ([#269](https://github.com/kreuzwerker/terraform-provider-docker/issues/269))
|
|
||||||
* service endpoint spec flattening
|
|
||||||
* corrects IPAM config read on the data provider ([#229](https://github.com/kreuzwerker/terraform-provider-docker/issues/229))
|
|
||||||
* replica to 0 in current schema. Closes [#221](https://github.com/kreuzwerker/terraform-provider-docker/issues/221)
|
|
||||||
* label for network and volume after improt
|
|
||||||
* binary upload as base 64 content ([#194](https://github.com/kreuzwerker/terraform-provider-docker/issues/194))
|
|
||||||
* service env truncation for multiple delimiters ([#193](https://github.com/kreuzwerker/terraform-provider-docker/issues/193))
|
|
||||||
* destroy_grace_seconds are considered ([#179](https://github.com/kreuzwerker/terraform-provider-docker/issues/179))
|
|
||||||
|
|
||||||
### Make
|
|
||||||
|
|
||||||
* Add website + website-test targets
|
|
||||||
|
|
||||||
### Provider
|
|
||||||
|
|
||||||
* Ensured Go 1.11 in TravisCI and README provider: Run go fix provider: Run go fmt provider: Encode go version 1.11.5 to .go-version file
|
|
||||||
* Require Go 1.11 in TravisCI and README provider: Run go fix provider: Run go fmt
|
|
||||||
|
|
||||||
### Tests
|
|
||||||
|
|
||||||
* Skip test if swap limit isn't available ([#136](https://github.com/kreuzwerker/terraform-provider-docker/issues/136))
|
|
||||||
* Simplify Dockerfile(s)
|
|
||||||
|
|
||||||
### Vendor
|
|
||||||
|
|
||||||
* github.com/hashicorp/terraform/...[@v0](https://github.com/v0).10.0
|
|
||||||
* Ignore github.com/hashicorp/terraform/backend
|
|
||||||
|
|
||||||
### Website
|
|
||||||
|
|
||||||
* Docs sweep for lists & maps
|
|
||||||
* note on docker
|
|
||||||
* docker docs
|
|
||||||
|
|
||||||
### Pull Requests
|
|
||||||
|
|
||||||
* Merge pull request [#134](https://github.com/kreuzwerker/terraform-provider-docker/issues/134) from terraform-providers/go-modules-2019-03-01
|
|
||||||
* Merge pull request [#135](https://github.com/kreuzwerker/terraform-provider-docker/issues/135) from terraform-providers/t-simplify-dockerfile
|
|
||||||
* Merge pull request [#47](https://github.com/kreuzwerker/terraform-provider-docker/issues/47) from captn3m0/docker-link-warning
|
|
||||||
* Merge pull request [#60](https://github.com/kreuzwerker/terraform-provider-docker/issues/60) from terraform-providers/f-make-website
|
|
||||||
* Merge pull request [#23](https://github.com/kreuzwerker/terraform-provider-docker/issues/23) from JamesLaverack/patch-1
|
|
||||||
* Merge pull request [#18](https://github.com/kreuzwerker/terraform-provider-docker/issues/18) from terraform-providers/vendor-tf-0.10
|
|
||||||
* Merge pull request [#5046](https://github.com/kreuzwerker/terraform-provider-docker/issues/5046) from tpounds/use-built-in-schema-string-hash
|
|
||||||
* Merge pull request [#3761](https://github.com/kreuzwerker/terraform-provider-docker/issues/3761) from ryane/f-provider-docker-improvements
|
|
||||||
* Merge pull request [#3383](https://github.com/kreuzwerker/terraform-provider-docker/issues/3383) from apparentlymart/docker-container-command-docs
|
|
||||||
* Merge pull request [#1564](https://github.com/kreuzwerker/terraform-provider-docker/issues/1564) from nickryand/docker_links
|
|
||||||
|
|
||||||
-373
@@ -1,373 +0,0 @@
|
|||||||
Mozilla Public License Version 2.0
|
|
||||||
==================================
|
|
||||||
|
|
||||||
1. Definitions
|
|
||||||
--------------
|
|
||||||
|
|
||||||
1.1. "Contributor"
|
|
||||||
means each individual or legal entity that creates, contributes to
|
|
||||||
the creation of, or owns Covered Software.
|
|
||||||
|
|
||||||
1.2. "Contributor Version"
|
|
||||||
means the combination of the Contributions of others (if any) used
|
|
||||||
by a Contributor and that particular Contributor's Contribution.
|
|
||||||
|
|
||||||
1.3. "Contribution"
|
|
||||||
means Covered Software of a particular Contributor.
|
|
||||||
|
|
||||||
1.4. "Covered Software"
|
|
||||||
means Source Code Form to which the initial Contributor has attached
|
|
||||||
the notice in Exhibit A, the Executable Form of such Source Code
|
|
||||||
Form, and Modifications of such Source Code Form, in each case
|
|
||||||
including portions thereof.
|
|
||||||
|
|
||||||
1.5. "Incompatible With Secondary Licenses"
|
|
||||||
means
|
|
||||||
|
|
||||||
(a) that the initial Contributor has attached the notice described
|
|
||||||
in Exhibit B to the Covered Software; or
|
|
||||||
|
|
||||||
(b) that the Covered Software was made available under the terms of
|
|
||||||
version 1.1 or earlier of the License, but not also under the
|
|
||||||
terms of a Secondary License.
|
|
||||||
|
|
||||||
1.6. "Executable Form"
|
|
||||||
means any form of the work other than Source Code Form.
|
|
||||||
|
|
||||||
1.7. "Larger Work"
|
|
||||||
means a work that combines Covered Software with other material, in
|
|
||||||
a separate file or files, that is not Covered Software.
|
|
||||||
|
|
||||||
1.8. "License"
|
|
||||||
means this document.
|
|
||||||
|
|
||||||
1.9. "Licensable"
|
|
||||||
means having the right to grant, to the maximum extent possible,
|
|
||||||
whether at the time of the initial grant or subsequently, any and
|
|
||||||
all of the rights conveyed by this License.
|
|
||||||
|
|
||||||
1.10. "Modifications"
|
|
||||||
means any of the following:
|
|
||||||
|
|
||||||
(a) any file in Source Code Form that results from an addition to,
|
|
||||||
deletion from, or modification of the contents of Covered
|
|
||||||
Software; or
|
|
||||||
|
|
||||||
(b) any new file in Source Code Form that contains any Covered
|
|
||||||
Software.
|
|
||||||
|
|
||||||
1.11. "Patent Claims" of a Contributor
|
|
||||||
means any patent claim(s), including without limitation, method,
|
|
||||||
process, and apparatus claims, in any patent Licensable by such
|
|
||||||
Contributor that would be infringed, but for the grant of the
|
|
||||||
License, by the making, using, selling, offering for sale, having
|
|
||||||
made, import, or transfer of either its Contributions or its
|
|
||||||
Contributor Version.
|
|
||||||
|
|
||||||
1.12. "Secondary License"
|
|
||||||
means either the GNU General Public License, Version 2.0, the GNU
|
|
||||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
|
||||||
Public License, Version 3.0, or any later versions of those
|
|
||||||
licenses.
|
|
||||||
|
|
||||||
1.13. "Source Code Form"
|
|
||||||
means the form of the work preferred for making modifications.
|
|
||||||
|
|
||||||
1.14. "You" (or "Your")
|
|
||||||
means an individual or a legal entity exercising rights under this
|
|
||||||
License. For legal entities, "You" includes any entity that
|
|
||||||
controls, is controlled by, or is under common control with You. For
|
|
||||||
purposes of this definition, "control" means (a) the power, direct
|
|
||||||
or indirect, to cause the direction or management of such entity,
|
|
||||||
whether by contract or otherwise, or (b) ownership of more than
|
|
||||||
fifty percent (50%) of the outstanding shares or beneficial
|
|
||||||
ownership of such entity.
|
|
||||||
|
|
||||||
2. License Grants and Conditions
|
|
||||||
--------------------------------
|
|
||||||
|
|
||||||
2.1. Grants
|
|
||||||
|
|
||||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
|
||||||
non-exclusive license:
|
|
||||||
|
|
||||||
(a) under intellectual property rights (other than patent or trademark)
|
|
||||||
Licensable by such Contributor to use, reproduce, make available,
|
|
||||||
modify, display, perform, distribute, and otherwise exploit its
|
|
||||||
Contributions, either on an unmodified basis, with Modifications, or
|
|
||||||
as part of a Larger Work; and
|
|
||||||
|
|
||||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
|
||||||
for sale, have made, import, and otherwise transfer either its
|
|
||||||
Contributions or its Contributor Version.
|
|
||||||
|
|
||||||
2.2. Effective Date
|
|
||||||
|
|
||||||
The licenses granted in Section 2.1 with respect to any Contribution
|
|
||||||
become effective for each Contribution on the date the Contributor first
|
|
||||||
distributes such Contribution.
|
|
||||||
|
|
||||||
2.3. Limitations on Grant Scope
|
|
||||||
|
|
||||||
The licenses granted in this Section 2 are the only rights granted under
|
|
||||||
this License. No additional rights or licenses will be implied from the
|
|
||||||
distribution or licensing of Covered Software under this License.
|
|
||||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
|
||||||
Contributor:
|
|
||||||
|
|
||||||
(a) for any code that a Contributor has removed from Covered Software;
|
|
||||||
or
|
|
||||||
|
|
||||||
(b) for infringements caused by: (i) Your and any other third party's
|
|
||||||
modifications of Covered Software, or (ii) the combination of its
|
|
||||||
Contributions with other software (except as part of its Contributor
|
|
||||||
Version); or
|
|
||||||
|
|
||||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
|
||||||
its Contributions.
|
|
||||||
|
|
||||||
This License does not grant any rights in the trademarks, service marks,
|
|
||||||
or logos of any Contributor (except as may be necessary to comply with
|
|
||||||
the notice requirements in Section 3.4).
|
|
||||||
|
|
||||||
2.4. Subsequent Licenses
|
|
||||||
|
|
||||||
No Contributor makes additional grants as a result of Your choice to
|
|
||||||
distribute the Covered Software under a subsequent version of this
|
|
||||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
|
||||||
permitted under the terms of Section 3.3).
|
|
||||||
|
|
||||||
2.5. Representation
|
|
||||||
|
|
||||||
Each Contributor represents that the Contributor believes its
|
|
||||||
Contributions are its original creation(s) or it has sufficient rights
|
|
||||||
to grant the rights to its Contributions conveyed by this License.
|
|
||||||
|
|
||||||
2.6. Fair Use
|
|
||||||
|
|
||||||
This License is not intended to limit any rights You have under
|
|
||||||
applicable copyright doctrines of fair use, fair dealing, or other
|
|
||||||
equivalents.
|
|
||||||
|
|
||||||
2.7. Conditions
|
|
||||||
|
|
||||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
|
||||||
in Section 2.1.
|
|
||||||
|
|
||||||
3. Responsibilities
|
|
||||||
-------------------
|
|
||||||
|
|
||||||
3.1. Distribution of Source Form
|
|
||||||
|
|
||||||
All distribution of Covered Software in Source Code Form, including any
|
|
||||||
Modifications that You create or to which You contribute, must be under
|
|
||||||
the terms of this License. You must inform recipients that the Source
|
|
||||||
Code Form of the Covered Software is governed by the terms of this
|
|
||||||
License, and how they can obtain a copy of this License. You may not
|
|
||||||
attempt to alter or restrict the recipients' rights in the Source Code
|
|
||||||
Form.
|
|
||||||
|
|
||||||
3.2. Distribution of Executable Form
|
|
||||||
|
|
||||||
If You distribute Covered Software in Executable Form then:
|
|
||||||
|
|
||||||
(a) such Covered Software must also be made available in Source Code
|
|
||||||
Form, as described in Section 3.1, and You must inform recipients of
|
|
||||||
the Executable Form how they can obtain a copy of such Source Code
|
|
||||||
Form by reasonable means in a timely manner, at a charge no more
|
|
||||||
than the cost of distribution to the recipient; and
|
|
||||||
|
|
||||||
(b) You may distribute such Executable Form under the terms of this
|
|
||||||
License, or sublicense it under different terms, provided that the
|
|
||||||
license for the Executable Form does not attempt to limit or alter
|
|
||||||
the recipients' rights in the Source Code Form under this License.
|
|
||||||
|
|
||||||
3.3. Distribution of a Larger Work
|
|
||||||
|
|
||||||
You may create and distribute a Larger Work under terms of Your choice,
|
|
||||||
provided that You also comply with the requirements of this License for
|
|
||||||
the Covered Software. If the Larger Work is a combination of Covered
|
|
||||||
Software with a work governed by one or more Secondary Licenses, and the
|
|
||||||
Covered Software is not Incompatible With Secondary Licenses, this
|
|
||||||
License permits You to additionally distribute such Covered Software
|
|
||||||
under the terms of such Secondary License(s), so that the recipient of
|
|
||||||
the Larger Work may, at their option, further distribute the Covered
|
|
||||||
Software under the terms of either this License or such Secondary
|
|
||||||
License(s).
|
|
||||||
|
|
||||||
3.4. Notices
|
|
||||||
|
|
||||||
You may not remove or alter the substance of any license notices
|
|
||||||
(including copyright notices, patent notices, disclaimers of warranty,
|
|
||||||
or limitations of liability) contained within the Source Code Form of
|
|
||||||
the Covered Software, except that You may alter any license notices to
|
|
||||||
the extent required to remedy known factual inaccuracies.
|
|
||||||
|
|
||||||
3.5. Application of Additional Terms
|
|
||||||
|
|
||||||
You may choose to offer, and to charge a fee for, warranty, support,
|
|
||||||
indemnity or liability obligations to one or more recipients of Covered
|
|
||||||
Software. However, You may do so only on Your own behalf, and not on
|
|
||||||
behalf of any Contributor. You must make it absolutely clear that any
|
|
||||||
such warranty, support, indemnity, or liability obligation is offered by
|
|
||||||
You alone, and You hereby agree to indemnify every Contributor for any
|
|
||||||
liability incurred by such Contributor as a result of warranty, support,
|
|
||||||
indemnity or liability terms You offer. You may include additional
|
|
||||||
disclaimers of warranty and limitations of liability specific to any
|
|
||||||
jurisdiction.
|
|
||||||
|
|
||||||
4. Inability to Comply Due to Statute or Regulation
|
|
||||||
---------------------------------------------------
|
|
||||||
|
|
||||||
If it is impossible for You to comply with any of the terms of this
|
|
||||||
License with respect to some or all of the Covered Software due to
|
|
||||||
statute, judicial order, or regulation then You must: (a) comply with
|
|
||||||
the terms of this License to the maximum extent possible; and (b)
|
|
||||||
describe the limitations and the code they affect. Such description must
|
|
||||||
be placed in a text file included with all distributions of the Covered
|
|
||||||
Software under this License. Except to the extent prohibited by statute
|
|
||||||
or regulation, such description must be sufficiently detailed for a
|
|
||||||
recipient of ordinary skill to be able to understand it.
|
|
||||||
|
|
||||||
5. Termination
|
|
||||||
--------------
|
|
||||||
|
|
||||||
5.1. The rights granted under this License will terminate automatically
|
|
||||||
if You fail to comply with any of its terms. However, if You become
|
|
||||||
compliant, then the rights granted under this License from a particular
|
|
||||||
Contributor are reinstated (a) provisionally, unless and until such
|
|
||||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
|
||||||
ongoing basis, if such Contributor fails to notify You of the
|
|
||||||
non-compliance by some reasonable means prior to 60 days after You have
|
|
||||||
come back into compliance. Moreover, Your grants from a particular
|
|
||||||
Contributor are reinstated on an ongoing basis if such Contributor
|
|
||||||
notifies You of the non-compliance by some reasonable means, this is the
|
|
||||||
first time You have received notice of non-compliance with this License
|
|
||||||
from such Contributor, and You become compliant prior to 30 days after
|
|
||||||
Your receipt of the notice.
|
|
||||||
|
|
||||||
5.2. If You initiate litigation against any entity by asserting a patent
|
|
||||||
infringement claim (excluding declaratory judgment actions,
|
|
||||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
|
||||||
directly or indirectly infringes any patent, then the rights granted to
|
|
||||||
You by any and all Contributors for the Covered Software under Section
|
|
||||||
2.1 of this License shall terminate.
|
|
||||||
|
|
||||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
|
||||||
end user license agreements (excluding distributors and resellers) which
|
|
||||||
have been validly granted by You or Your distributors under this License
|
|
||||||
prior to termination shall survive termination.
|
|
||||||
|
|
||||||
************************************************************************
|
|
||||||
* *
|
|
||||||
* 6. Disclaimer of Warranty *
|
|
||||||
* ------------------------- *
|
|
||||||
* *
|
|
||||||
* Covered Software is provided under this License on an "as is" *
|
|
||||||
* basis, without warranty of any kind, either expressed, implied, or *
|
|
||||||
* statutory, including, without limitation, warranties that the *
|
|
||||||
* Covered Software is free of defects, merchantable, fit for a *
|
|
||||||
* particular purpose or non-infringing. The entire risk as to the *
|
|
||||||
* quality and performance of the Covered Software is with You. *
|
|
||||||
* Should any Covered Software prove defective in any respect, You *
|
|
||||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
|
||||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
|
||||||
* essential part of this License. No use of any Covered Software is *
|
|
||||||
* authorized under this License except under this disclaimer. *
|
|
||||||
* *
|
|
||||||
************************************************************************
|
|
||||||
|
|
||||||
************************************************************************
|
|
||||||
* *
|
|
||||||
* 7. Limitation of Liability *
|
|
||||||
* -------------------------- *
|
|
||||||
* *
|
|
||||||
* Under no circumstances and under no legal theory, whether tort *
|
|
||||||
* (including negligence), contract, or otherwise, shall any *
|
|
||||||
* Contributor, or anyone who distributes Covered Software as *
|
|
||||||
* permitted above, be liable to You for any direct, indirect, *
|
|
||||||
* special, incidental, or consequential damages of any character *
|
|
||||||
* including, without limitation, damages for lost profits, loss of *
|
|
||||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
|
||||||
* and all other commercial damages or losses, even if such party *
|
|
||||||
* shall have been informed of the possibility of such damages. This *
|
|
||||||
* limitation of liability shall not apply to liability for death or *
|
|
||||||
* personal injury resulting from such party's negligence to the *
|
|
||||||
* extent applicable law prohibits such limitation. Some *
|
|
||||||
* jurisdictions do not allow the exclusion or limitation of *
|
|
||||||
* incidental or consequential damages, so this exclusion and *
|
|
||||||
* limitation may not apply to You. *
|
|
||||||
* *
|
|
||||||
************************************************************************
|
|
||||||
|
|
||||||
8. Litigation
|
|
||||||
-------------
|
|
||||||
|
|
||||||
Any litigation relating to this License may be brought only in the
|
|
||||||
courts of a jurisdiction where the defendant maintains its principal
|
|
||||||
place of business and such litigation shall be governed by laws of that
|
|
||||||
jurisdiction, without reference to its conflict-of-law provisions.
|
|
||||||
Nothing in this Section shall prevent a party's ability to bring
|
|
||||||
cross-claims or counter-claims.
|
|
||||||
|
|
||||||
9. Miscellaneous
|
|
||||||
----------------
|
|
||||||
|
|
||||||
This License represents the complete agreement concerning the subject
|
|
||||||
matter hereof. If any provision of this License is held to be
|
|
||||||
unenforceable, such provision shall be reformed only to the extent
|
|
||||||
necessary to make it enforceable. Any law or regulation which provides
|
|
||||||
that the language of a contract shall be construed against the drafter
|
|
||||||
shall not be used to construe this License against a Contributor.
|
|
||||||
|
|
||||||
10. Versions of the License
|
|
||||||
---------------------------
|
|
||||||
|
|
||||||
10.1. New Versions
|
|
||||||
|
|
||||||
Mozilla Foundation is the license steward. Except as provided in Section
|
|
||||||
10.3, no one other than the license steward has the right to modify or
|
|
||||||
publish new versions of this License. Each version will be given a
|
|
||||||
distinguishing version number.
|
|
||||||
|
|
||||||
10.2. Effect of New Versions
|
|
||||||
|
|
||||||
You may distribute the Covered Software under the terms of the version
|
|
||||||
of the License under which You originally received the Covered Software,
|
|
||||||
or under the terms of any subsequent version published by the license
|
|
||||||
steward.
|
|
||||||
|
|
||||||
10.3. Modified Versions
|
|
||||||
|
|
||||||
If you create software not governed by this License, and you want to
|
|
||||||
create a new license for such software, you may create and use a
|
|
||||||
modified version of this License if you rename the license and remove
|
|
||||||
any references to the name of the license steward (except to note that
|
|
||||||
such modified license differs from this License).
|
|
||||||
|
|
||||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
|
||||||
Licenses
|
|
||||||
|
|
||||||
If You choose to distribute Source Code Form that is Incompatible With
|
|
||||||
Secondary Licenses under the terms of this version of the License, the
|
|
||||||
notice described in Exhibit B of this License must be attached.
|
|
||||||
|
|
||||||
Exhibit A - Source Code Form License Notice
|
|
||||||
-------------------------------------------
|
|
||||||
|
|
||||||
This Source Code Form is subject to the terms of the Mozilla Public
|
|
||||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
||||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
||||||
|
|
||||||
If it is not possible or desirable to put the notice in a particular
|
|
||||||
file, then You may include the notice in a location (such as a LICENSE
|
|
||||||
file in a relevant directory) where a recipient would be likely to look
|
|
||||||
for such a notice.
|
|
||||||
|
|
||||||
You may add additional accurate notices of copyright ownership.
|
|
||||||
|
|
||||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
|
||||||
---------------------------------------------------------
|
|
||||||
|
|
||||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
|
||||||
defined by the Mozilla Public License, v. 2.0.
|
|
||||||
-117
@@ -1,117 +0,0 @@
|
|||||||
<a href="https://docker.com">
|
|
||||||
<img src="https://raw.githubusercontent.com/kreuzwerker/terraform-provider-docker/master/assets/docker-logo.png" alt="Docker logo" title="Docker" align="right" height="100" />
|
|
||||||
</a>
|
|
||||||
<a href="https://terraform.io">
|
|
||||||
<img src="https://raw.githubusercontent.com/kreuzwerker/terraform-provider-docker/master/assets/terraform-logo.png" alt="Terraform logo" title="Terraform" align="right" height="100" />
|
|
||||||
</a>
|
|
||||||
<a href="https://kreuzwerker.de">
|
|
||||||
<img src="https://raw.githubusercontent.com/kreuzwerker/terraform-provider-docker/master/assets/xw-logo.png" alt="Kreuzwerker logo" title="Kreuzwerker" align="right" height="100" />
|
|
||||||
</a>
|
|
||||||
|
|
||||||
# Terraform Provider for Docker
|
|
||||||
|
|
||||||
[](https://github.com/kreuzwerker/terraform-provider-docker/releases)
|
|
||||||
[](https://registry.terraform.io/providers/kreuzwerker/docker)
|
|
||||||
[](https://registry.terraform.io/providers/kreuzwerker/docker/latest/docs)
|
|
||||||
[](https://github.com/kreuzwerker/terraform-provider-docker/blob/main/LICENSE)
|
|
||||||
[](https://github.com/kreuzwerker/terraform-provider-docker/actions)
|
|
||||||
[](https://github.com/kreuzwerker/terraform-provider-docker/actions)
|
|
||||||
[](https://goreportcard.com/report/github.com/kreuzwerker/terraform-provider-docker)
|
|
||||||
|
|
||||||
## Documentation
|
|
||||||
|
|
||||||
The documentation for the provider is available on the [Terraform Registry](https://registry.terraform.io/providers/kreuzwerker/docker/latest/docs).
|
|
||||||
|
|
||||||
Do you want to migrate from `v2.x` to `v3.x`? Please read the [migration guide](docs/v2_v3_migration.md)
|
|
||||||
|
|
||||||
## Example usage
|
|
||||||
|
|
||||||
Take a look at the examples in the [documentation](https://registry.terraform.io/providers/kreuzwerker/docker/3.9.0/docs) of the registry
|
|
||||||
or use the following example:
|
|
||||||
|
|
||||||
|
|
||||||
```hcl
|
|
||||||
# Set the required provider and versions
|
|
||||||
terraform {
|
|
||||||
required_providers {
|
|
||||||
# We recommend pinning to the specific version of the Docker Provider you're using
|
|
||||||
# since new versions are released frequently
|
|
||||||
docker = {
|
|
||||||
source = "kreuzwerker/docker"
|
|
||||||
version = "3.9.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Configure the docker provider
|
|
||||||
provider "docker" {
|
|
||||||
}
|
|
||||||
|
|
||||||
# Create a docker image resource
|
|
||||||
# -> docker pull nginx:latest
|
|
||||||
resource "docker_image" "nginx" {
|
|
||||||
name = "nginx:latest"
|
|
||||||
keep_locally = true
|
|
||||||
}
|
|
||||||
|
|
||||||
# Create a docker container resource
|
|
||||||
# -> same as 'docker run --name nginx -p8080:80 -d nginx:latest'
|
|
||||||
resource "docker_container" "nginx" {
|
|
||||||
name = "nginx"
|
|
||||||
image = docker_image.nginx.image_id
|
|
||||||
|
|
||||||
ports {
|
|
||||||
external = 8080
|
|
||||||
internal = 80
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Or create a service resource
|
|
||||||
# -> same as 'docker service create -d -p 8081:80 --name nginx-service --replicas 2 nginx:latest'
|
|
||||||
resource "docker_service" "nginx_service" {
|
|
||||||
name = "nginx-service"
|
|
||||||
task_spec {
|
|
||||||
container_spec {
|
|
||||||
image = docker_image.nginx.repo_digest
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mode {
|
|
||||||
replicated {
|
|
||||||
replicas = 2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
endpoint_spec {
|
|
||||||
ports {
|
|
||||||
published_port = 8081
|
|
||||||
target_port = 80
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Building The Provider
|
|
||||||
|
|
||||||
[Go](https://golang.org/doc/install) 1.18.x (to build the provider plugin)
|
|
||||||
|
|
||||||
|
|
||||||
```sh
|
|
||||||
$ git clone git@github.com:kreuzwerker/terraform-provider-docker
|
|
||||||
$ make build
|
|
||||||
```
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
The Terraform Docker Provider is the work of many of contributors. We appreciate your help!
|
|
||||||
|
|
||||||
To contribute, please read the contribution guidelines: [Contributing to Terraform - Docker Provider](CONTRIBUTING.md)
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
The Terraform Provider Docker is available to everyone under the terms of the Mozilla Public License Version 2.0. [Take a look the LICENSE file](LICENSE).
|
|
||||||
|
|
||||||
|
|
||||||
## Stargazers over time
|
|
||||||
|
|
||||||
[](https://starchart.cc/kreuzwerker/terraform-provider-docker)
|
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
BACKEND := apps/backend
|
||||||
|
FRONTEND := apps/frontend
|
||||||
|
ML := ml
|
||||||
|
|
||||||
|
.DEFAULT_GOAL := help
|
||||||
|
.PHONY: help install install-backend install-frontend install-ml 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 \
|
||||||
|
ml-lint ml-typecheck ml-test ml-check ml-train
|
||||||
|
|
||||||
|
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 install-ml ## Installe les dépendances backend, frontend et ML
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
install-ml: ## Installe les dépendances du pipeline ML
|
||||||
|
cd $(ML) && uv sync --all-groups
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
ml-lint: ## Analyse statique du pipeline ML
|
||||||
|
cd $(ML) && uv run ruff check .
|
||||||
|
|
||||||
|
ml-typecheck: ## Vérifie le typage du pipeline ML
|
||||||
|
cd $(ML) && uv run mypy enervision_ml tests
|
||||||
|
|
||||||
|
ml-test: ## Exécute les tests du pipeline ML (donnees synthetiques, sans base ni serveur MLflow)
|
||||||
|
cd $(ML) && uv run pytest
|
||||||
|
|
||||||
|
ml-check: ml-lint ml-typecheck ml-test ## Chaîne de vérification complète du pipeline ML
|
||||||
|
|
||||||
|
ml-train: ## Entraine le modele LightGBM. CSV=chemin optionnel, sinon lit ML_DATABASE_URL
|
||||||
|
cd $(ML) && uv run python -m enervision_ml.train $(if $(CSV),--csv $(CSV),)
|
||||||
|
|
||||||
|
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,106 @@
|
|||||||
# 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 |
|
||||||
|
| ML | LightGBM, MLflow | `ml` | Entrainement initialise |
|
||||||
|
|
||||||
|
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
|
||||||
|
├── ml/ Pipeline d'entrainement LightGBM, suivi MLflow
|
||||||
|
├── 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,20 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
# Mot de passe oublié : lien à usage unique valable 15 minutes par défaut.
|
||||||
|
APP_FRONTEND_RESET_PASSWORD_URL=http://localhost:4200/reset-password
|
||||||
|
|
||||||
|
# SMTP local de dev (Mailpit, cf. docker-compose.yml) : aucune authentification, aucun TLS.
|
||||||
|
# À remplacer par un vrai relais en staging/prod.
|
||||||
|
APP_SMTP_HOST=localhost
|
||||||
|
APP_SMTP_PORT=1025
|
||||||
|
APP_SMTP_USE_TLS=false
|
||||||
|
APP_SMTP_FROM_ADDRESS=no-reply@enervision.fr
|
||||||
@@ -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,158 @@
|
|||||||
|
# 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/forgot-password` | Demande un lien de réinitialisation par email | public |
|
||||||
|
| `/api/v1/auth/reset-password` | Choisit un nouveau mot de passe depuis ce lien | public |
|
||||||
|
| `/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,96 @@
|
|||||||
|
"""jetons et tentatives de reinitialisation de mot de passe
|
||||||
|
|
||||||
|
Revision ID: c0adab96238c
|
||||||
|
Revises: e6d2026091501
|
||||||
|
Create Date: 2026-09-17 10:37:12.571314
|
||||||
|
|
||||||
|
Meme schema que `refresh_token` pour `password_reset_token` : seule l'empreinte SHA-256 du
|
||||||
|
jeton est stockee, jamais le jeton lui-meme, pour la meme raison (revocation en cascade,
|
||||||
|
aucune session utilisable dans un pg_dump qui fuiterait).
|
||||||
|
|
||||||
|
`password_reset_attempt` vit hors de `audit_log`, comme `login_attempt`, car son volume est
|
||||||
|
pilote par l'attaquant : une campagne de demandes y ecrirait des lignes que l'audit, en ajout
|
||||||
|
seul, ne devrait jamais purger.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "c0adab96238c"
|
||||||
|
down_revision: str | Sequence[str] | None = "e6d2026091501"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
JETONS_VIVANTS = "consumed_at is null"
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"password_reset_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.PrimaryKeyConstraint("id", name="pk_password_reset_attempt"),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_password_reset_attempt_email_date",
|
||||||
|
"password_reset_attempt",
|
||||||
|
["email_tried", "occurred_at"],
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_password_reset_attempt_ip_date", "password_reset_attempt", ["client_ip", "occurred_at"]
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"password_reset_token",
|
||||||
|
sa.Column("id", sa.UUID(), server_default=sa.text("gen_random_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("consumed_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("client_ip", postgresql.INET(), nullable=True),
|
||||||
|
sa.Column("user_agent", sa.Text(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["app_user.id"],
|
||||||
|
name="fk_password_reset_token_user",
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name="pk_password_reset_token"),
|
||||||
|
sa.UniqueConstraint("token_hash", name="uq_password_reset_token_hash"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_password_reset_token_user", "password_reset_token", ["user_id"])
|
||||||
|
op.create_index(
|
||||||
|
"ix_password_reset_token_vivants",
|
||||||
|
"password_reset_token",
|
||||||
|
["user_id"],
|
||||||
|
postgresql_where=JETONS_VIVANTS,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(
|
||||||
|
"ix_password_reset_token_vivants",
|
||||||
|
table_name="password_reset_token",
|
||||||
|
postgresql_where=JETONS_VIVANTS,
|
||||||
|
)
|
||||||
|
op.drop_index("ix_password_reset_token_user", table_name="password_reset_token")
|
||||||
|
op.drop_table("password_reset_token")
|
||||||
|
op.drop_index("ix_password_reset_attempt_ip_date", table_name="password_reset_attempt")
|
||||||
|
op.drop_index("ix_password_reset_attempt_email_date", table_name="password_reset_attempt")
|
||||||
|
op.drop_table("password_reset_attempt")
|
||||||
@@ -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,278 @@
|
|||||||
|
# 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.mailer import Mailer, SmtpConfig
|
||||||
|
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.password_reset_attempt import PasswordResetAttemptRepository
|
||||||
|
from app.repositories.password_reset_token import PasswordResetTokenRepository
|
||||||
|
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, PasswordResetPolicy
|
||||||
|
from app.services.reading import ReadingService
|
||||||
|
from app.services.recommendation import RecommendationService
|
||||||
|
from app.services.sensor import SensorService
|
||||||
|
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_mailer(settings: SettingsDep) -> Mailer:
|
||||||
|
return Mailer(
|
||||||
|
SmtpConfig(
|
||||||
|
host=settings.smtp_host,
|
||||||
|
port=settings.smtp_port,
|
||||||
|
username=settings.smtp_username,
|
||||||
|
password=(
|
||||||
|
settings.smtp_password.get_secret_value() if settings.smtp_password else None
|
||||||
|
),
|
||||||
|
use_tls=settings.smtp_use_tls,
|
||||||
|
from_address=settings.smtp_from_address,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_auth_service(
|
||||||
|
session: SessionDep,
|
||||||
|
settings: SettingsDep,
|
||||||
|
hasher: Annotated[Argon2Hasher, Depends(get_hasher)],
|
||||||
|
token_policy: Annotated[TokenPolicy, Depends(get_token_policy)],
|
||||||
|
mailer: Annotated[Mailer, Depends(get_mailer)],
|
||||||
|
) -> 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),
|
||||||
|
reset_tokens=PasswordResetTokenRepository(session),
|
||||||
|
reset_attempts=PasswordResetAttemptRepository(session),
|
||||||
|
reset_policy=PasswordResetPolicy(
|
||||||
|
window_seconds=settings.password_reset_window_seconds,
|
||||||
|
max_requests_per_identifier=settings.password_reset_max_requests_per_identifier,
|
||||||
|
max_requests_per_ip=settings.password_reset_max_requests_per_ip,
|
||||||
|
token_ttl=timedelta(seconds=settings.password_reset_ttl_seconds),
|
||||||
|
frontend_reset_url=settings.frontend_reset_password_url,
|
||||||
|
),
|
||||||
|
mailer=mailer,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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), readings=ReadingRepository(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)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_reading_service(session: SessionDep) -> ReadingService:
|
||||||
|
return ReadingService(readings=ReadingRepository(session))
|
||||||
|
|
||||||
|
|
||||||
|
ReadingServiceDep = Annotated[ReadingService, Depends(get_reading_service)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_sensor_service(session: SessionDep) -> SensorService:
|
||||||
|
return SensorService(sites=SiteRepository(session), readings=ReadingRepository(session))
|
||||||
|
|
||||||
|
|
||||||
|
SensorServiceDep = Annotated[SensorService, Depends(get_sensor_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,179 @@
|
|||||||
|
# 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`.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "readings",
|
||||||
|
"description": (
|
||||||
|
"Historique des lectures de consommation. Fenêtre temporelle plafonnée à 90 jours, "
|
||||||
|
"24 dernières heures par défaut si `start`/`end` sont omis. Accessible à partir du "
|
||||||
|
"rôle `lecteur`."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "sensors",
|
||||||
|
"description": "État de santé des capteurs par site. Réservé au rôle `admin`.",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
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`).",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSE_LIMITE: Final[Reponses] = {
|
||||||
|
429: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": "Trop de demandes sur cette fenêtre glissante.",
|
||||||
|
"headers": {
|
||||||
|
"Retry-After": {
|
||||||
|
"description": "Secondes à attendre avant une nouvelle tentative.",
|
||||||
|
"schema": {"type": "integer"},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -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,365 @@
|
|||||||
|
# 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, BackgroundTasks, 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_LIMITE,
|
||||||
|
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 (
|
||||||
|
ForgotPasswordRequest,
|
||||||
|
LoginRequest,
|
||||||
|
PasswordChangeRequest,
|
||||||
|
PrincipalResponse,
|
||||||
|
ResetPasswordRequest,
|
||||||
|
ResetTokenValidationResponse,
|
||||||
|
TokenResponse,
|
||||||
|
)
|
||||||
|
from app.schemas.errors import ErrorResponse
|
||||||
|
from app.services.auth import (
|
||||||
|
AuthenticatedSession,
|
||||||
|
InvalidCredentialsError,
|
||||||
|
InvalidOrExpiredResetTokenError,
|
||||||
|
RateLimitedError,
|
||||||
|
SessionRejectedError,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
DETAIL_IDENTIFIANTS = "Identifiants invalides"
|
||||||
|
DETAIL_SESSION = "Session invalide"
|
||||||
|
DETAIL_LIEN_RESET = "Lien invalide ou expiré"
|
||||||
|
|
||||||
|
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.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSES_FORGOT_PASSWORD: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
**REPONSE_LIMITE,
|
||||||
|
}
|
||||||
|
|
||||||
|
REPONSES_RESET_PASSWORD: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
**REPONSE_ORIGINE_REFUSEE,
|
||||||
|
400: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": "Lien invalide, déjà utilisé, ou expiré (durée de vie : 15 minutes).",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/forgot-password",
|
||||||
|
status_code=status.HTTP_202_ACCEPTED,
|
||||||
|
summary="Demande un lien de réinitialisation par email",
|
||||||
|
responses=REPONSES_FORGOT_PASSWORD,
|
||||||
|
)
|
||||||
|
async def forgot_password(
|
||||||
|
payload: ForgotPasswordRequest,
|
||||||
|
request: Request,
|
||||||
|
response: Response,
|
||||||
|
service: AuthServiceDep,
|
||||||
|
background_tasks: BackgroundTasks,
|
||||||
|
client_ip: str | None = Depends(get_client_ip),
|
||||||
|
) -> None:
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
|
||||||
|
try:
|
||||||
|
await service.request_password_reset(
|
||||||
|
email=payload.email,
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=request.headers.get("user-agent"),
|
||||||
|
background_tasks=background_tasks,
|
||||||
|
)
|
||||||
|
except RateLimitedError as erreur:
|
||||||
|
logger.warning("auth.password_reset.rate_limited ip=%s", client_ip)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||||
|
detail="Trop de demandes, réessayez plus tard",
|
||||||
|
headers={"Retry-After": str(erreur.retry_after)},
|
||||||
|
) from erreur
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/reset-password/validate",
|
||||||
|
response_model=ResetTokenValidationResponse,
|
||||||
|
summary="Vérifie sans le consommer si un lien de réinitialisation est encore valide",
|
||||||
|
responses=REPONSE_VALIDATION,
|
||||||
|
)
|
||||||
|
async def validate_reset_token(token: str, service: AuthServiceDep) -> ResetTokenValidationResponse:
|
||||||
|
return ResetTokenValidationResponse(valid=await service.is_reset_token_valid(token=token))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/reset-password",
|
||||||
|
response_model=TokenResponse,
|
||||||
|
summary="Choisit un nouveau mot de passe depuis un lien reçu par email",
|
||||||
|
dependencies=[Depends(require_trusted_origin)],
|
||||||
|
responses=REPONSES_RESET_PASSWORD,
|
||||||
|
)
|
||||||
|
async def reset_password(
|
||||||
|
payload: ResetPasswordRequest,
|
||||||
|
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.confirm_password_reset(
|
||||||
|
token=payload.token,
|
||||||
|
new_password=payload.new_password,
|
||||||
|
client_ip=client_ip,
|
||||||
|
user_agent=request.headers.get("user-agent"),
|
||||||
|
)
|
||||||
|
except InvalidOrExpiredResetTokenError as erreur:
|
||||||
|
logger.warning("auth.password_reset.invalid_token ip=%s", client_ip)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST, detail=DETAIL_LIEN_RESET
|
||||||
|
) from erreur
|
||||||
|
|
||||||
|
logger.info("auth.password_reset.success user_id=%s", session.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,54 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query, status
|
||||||
|
|
||||||
|
from app.api.deps import LecteurDep, ReadingServiceDep
|
||||||
|
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||||
|
from app.schemas.errors import ErrorResponse
|
||||||
|
from app.schemas.reading import ReadingResponse
|
||||||
|
from app.services.reading import FenetreInverseeError, FenetreTropLargeError
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
REPONSES_FENETRE: Reponses = {
|
||||||
|
**REPONSE_VALIDATION,
|
||||||
|
400: {
|
||||||
|
"model": ErrorResponse,
|
||||||
|
"description": (
|
||||||
|
"Fenêtre temporelle invalide : `start` postérieur ou égal à `end`, ou écart entre "
|
||||||
|
"les deux supérieur à 90 jours."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"",
|
||||||
|
response_model=list[ReadingResponse],
|
||||||
|
summary="Liste l'historique des lectures",
|
||||||
|
responses=REPONSES_FENETRE,
|
||||||
|
)
|
||||||
|
async def list_readings(
|
||||||
|
_: LecteurDep,
|
||||||
|
service: ReadingServiceDep,
|
||||||
|
site_id: str | None = None,
|
||||||
|
start: datetime | None = None,
|
||||||
|
end: datetime | None = None,
|
||||||
|
limit: int = Query(500, ge=1, le=2000),
|
||||||
|
offset: int = Query(0, ge=0),
|
||||||
|
) -> list[ReadingResponse]:
|
||||||
|
try:
|
||||||
|
lectures = await service.list_history(
|
||||||
|
site_id=site_id, start=start, end=end, limit=limit, offset=offset
|
||||||
|
)
|
||||||
|
except FenetreInverseeError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="`start` doit être strictement antérieur à `end`",
|
||||||
|
) from erreur
|
||||||
|
except FenetreTropLargeError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="L'écart entre `start` et `end` ne peut pas dépasser 90 jours",
|
||||||
|
) from erreur
|
||||||
|
return [ReadingResponse.model_validate(lecture) for lecture in lectures]
|
||||||
@@ -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,16 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.deps import AdminDep, SensorServiceDep
|
||||||
|
from app.schemas.sensor import SensorStatusResponse
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/status",
|
||||||
|
response_model=SensorStatusResponse,
|
||||||
|
summary="État de santé des capteurs par site",
|
||||||
|
)
|
||||||
|
async def get_status(_: AdminDep, service: SensorServiceDep) -> SensorStatusResponse:
|
||||||
|
etat = await service.status()
|
||||||
|
return SensorStatusResponse.model_validate(etat)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
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 SiteCurrentResponse, 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)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{site_id}/current",
|
||||||
|
response_model=SiteCurrentResponse,
|
||||||
|
summary="Dernière mesure d'un site",
|
||||||
|
responses=REPONSES_INTROUVABLE,
|
||||||
|
)
|
||||||
|
async def get_current(site_id: str, _: LecteurDep, service: SiteServiceDep) -> SiteCurrentResponse:
|
||||||
|
try:
|
||||||
|
actuel = await service.current(site_id)
|
||||||
|
except SiteNotFoundError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
||||||
|
) from erreur
|
||||||
|
return SiteCurrentResponse.model_validate(actuel)
|
||||||
@@ -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,36 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.openapi import REPONSE_SERVEUR, REPONSES_ADMIN, REPONSES_LECTEUR
|
||||||
|
from app.api.v1.endpoints import (
|
||||||
|
alerts,
|
||||||
|
auth,
|
||||||
|
health,
|
||||||
|
readings,
|
||||||
|
recommendations,
|
||||||
|
sensors,
|
||||||
|
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)
|
||||||
|
api_router.include_router(
|
||||||
|
readings.router, prefix="/readings", tags=["readings"], responses=REPONSES_LECTEUR
|
||||||
|
)
|
||||||
|
api_router.include_router(
|
||||||
|
sensors.router, prefix="/sensors", tags=["sensors"], responses=REPONSES_ADMIN
|
||||||
|
)
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
# 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 string
|
||||||
|
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
|
||||||
|
from app.schemas.auth import PASSWORD_MIN_LENGTH, SPECIAL_CHARACTERS, valide_complexite
|
||||||
|
|
||||||
|
LONGUEUR_MOT_DE_PASSE_GENERE = 24
|
||||||
|
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 genere_mot_de_passe() -> str:
|
||||||
|
tirage = secrets.SystemRandom()
|
||||||
|
classes = [
|
||||||
|
string.ascii_uppercase,
|
||||||
|
string.ascii_lowercase,
|
||||||
|
string.digits,
|
||||||
|
SPECIAL_CHARACTERS,
|
||||||
|
]
|
||||||
|
reste = LONGUEUR_MOT_DE_PASSE_GENERE - len(classes)
|
||||||
|
caracteres = [tirage.choice(classe) for classe in classes]
|
||||||
|
caracteres += [tirage.choice("".join(classes)) for _ in range(reste)]
|
||||||
|
tirage.shuffle(caracteres)
|
||||||
|
return "".join(caracteres)
|
||||||
|
|
||||||
|
|
||||||
|
def read_password(*, generate: bool) -> str:
|
||||||
|
if generate:
|
||||||
|
mot_de_passe = genere_mot_de_passe()
|
||||||
|
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) < PASSWORD_MIN_LENGTH:
|
||||||
|
raise SystemExit(f"Le mot de passe doit faire au moins {PASSWORD_MIN_LENGTH} caractères")
|
||||||
|
try:
|
||||||
|
valide_complexite(mot_de_passe)
|
||||||
|
except ValueError as erreur:
|
||||||
|
raise SystemExit(str(erreur)) from erreur
|
||||||
|
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,123 @@
|
|||||||
|
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)
|
||||||
|
|
||||||
|
password_reset_ttl_seconds: int = Field(default=900, ge=60, le=3600)
|
||||||
|
password_reset_window_seconds: int = Field(default=900, ge=60)
|
||||||
|
password_reset_max_requests_per_identifier: int = Field(default=3, ge=1)
|
||||||
|
password_reset_max_requests_per_ip: int = Field(default=10, ge=1)
|
||||||
|
|
||||||
|
smtp_host: str = "localhost"
|
||||||
|
smtp_port: int = Field(default=587, ge=1, le=65535)
|
||||||
|
smtp_username: str | None = None
|
||||||
|
smtp_password: SecretStr | None = None
|
||||||
|
smtp_use_tls: bool = False
|
||||||
|
smtp_from_address: str = "no-reply@enervision.fr"
|
||||||
|
frontend_reset_password_url: str = "http://localhost:4200/reset-password" # noqa: S105
|
||||||
|
|
||||||
|
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,48 @@
|
|||||||
|
# Piège : l'URL de réinitialisation porte le jeton en clair. Ne jamais la journaliser :
|
||||||
|
# `send_password_reset_email()` ne logue que le destinataire, jamais `reset_url`.
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from email.message import EmailMessage
|
||||||
|
|
||||||
|
import aiosmtplib
|
||||||
|
|
||||||
|
from app.core.logging import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SmtpConfig:
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
username: str | None
|
||||||
|
password: str | None
|
||||||
|
use_tls: bool
|
||||||
|
from_address: str
|
||||||
|
|
||||||
|
|
||||||
|
class Mailer:
|
||||||
|
def __init__(self, config: SmtpConfig) -> None:
|
||||||
|
self._config = config
|
||||||
|
|
||||||
|
async def send_password_reset_email(self, *, to: str, reset_url: str) -> None:
|
||||||
|
message = EmailMessage()
|
||||||
|
message["From"] = self._config.from_address
|
||||||
|
message["To"] = to
|
||||||
|
message["Subject"] = "Réinitialisation de votre mot de passe EnerVision"
|
||||||
|
message.set_content(
|
||||||
|
"Une réinitialisation de mot de passe a été demandée pour ce compte.\n\n"
|
||||||
|
f"Ouvrez ce lien dans les 15 minutes pour choisir un nouveau mot de passe : "
|
||||||
|
f"{reset_url}\n\n"
|
||||||
|
"Si vous n'êtes pas à l'origine de cette demande, ignorez cet email."
|
||||||
|
)
|
||||||
|
|
||||||
|
_, message_recu = await aiosmtplib.send(
|
||||||
|
message,
|
||||||
|
hostname=self._config.host,
|
||||||
|
port=self._config.port,
|
||||||
|
username=self._config.username,
|
||||||
|
password=self._config.password,
|
||||||
|
use_tls=self._config.use_tls,
|
||||||
|
)
|
||||||
|
logger.info("mailer.password_reset_sent to=%s smtp_response=%s", to, message_recu)
|
||||||
@@ -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,621 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
|
||||||
|
|
||||||
|
from app.core.config import get_settings
|
||||||
|
|
||||||
|
REQUIRED_COLUMNS = {
|
||||||
|
"timestamp",
|
||||||
|
"site_id",
|
||||||
|
"site_type",
|
||||||
|
"site_name",
|
||||||
|
"consumption_kwh",
|
||||||
|
"consumption_euros",
|
||||||
|
"temperature_celsius",
|
||||||
|
"humidity_percent",
|
||||||
|
"solar_irradiance_wm2",
|
||||||
|
"hour",
|
||||||
|
"day_of_week",
|
||||||
|
"day_name",
|
||||||
|
"month",
|
||||||
|
"is_weekend",
|
||||||
|
"is_working_hours",
|
||||||
|
}
|
||||||
|
|
||||||
|
MEASURE_COLUMNS = [
|
||||||
|
"consumption_kwh",
|
||||||
|
"consumption_euros",
|
||||||
|
"temperature_celsius",
|
||||||
|
"humidity_percent",
|
||||||
|
"solar_irradiance_wm2",
|
||||||
|
]
|
||||||
|
|
||||||
|
SOURCE_NAME = "csv"
|
||||||
|
|
||||||
|
|
||||||
|
def compute_sha256(path: Path) -> str:
|
||||||
|
"""Calcule l'empreinte SHA-256 du fichier source."""
|
||||||
|
sha256 = hashlib.sha256()
|
||||||
|
|
||||||
|
with path.open("rb") as source:
|
||||||
|
for block in iter(lambda: source.read(1024 * 1024), b""):
|
||||||
|
sha256.update(block)
|
||||||
|
|
||||||
|
return sha256.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def load_metadata(path: Path) -> dict[str, Any]:
|
||||||
|
"""Charge les métadonnées fournies avec le dataset."""
|
||||||
|
with path.open("r", encoding="utf-8") as source:
|
||||||
|
metadata = json.load(source)
|
||||||
|
|
||||||
|
if not isinstance(metadata, dict):
|
||||||
|
raise ValueError("Le fichier de métadonnées doit contenir un objet JSON.")
|
||||||
|
|
||||||
|
return cast(dict[str, Any], metadata)
|
||||||
|
|
||||||
|
|
||||||
|
def classify_quality(
|
||||||
|
row: dict[str, Any],
|
||||||
|
) -> tuple[str, list[str]]:
|
||||||
|
"""
|
||||||
|
Déduit une qualité technique à partir des champs manquants.
|
||||||
|
|
||||||
|
Les valeurs NULL sont conservées. On ne cherche pas ici à
|
||||||
|
déterminer la cause physique exacte de leur absence.
|
||||||
|
"""
|
||||||
|
missing = [column for column in MEASURE_COLUMNS if pd.isna(row.get(column))]
|
||||||
|
|
||||||
|
if not missing:
|
||||||
|
quality = "good"
|
||||||
|
elif len(missing) == len(MEASURE_COLUMNS):
|
||||||
|
quality = "critical"
|
||||||
|
elif "consumption_kwh" in missing:
|
||||||
|
quality = "degraded"
|
||||||
|
else:
|
||||||
|
quality = "partial"
|
||||||
|
|
||||||
|
reasons = [f"missing:{column}" for column in missing]
|
||||||
|
|
||||||
|
return quality, reasons
|
||||||
|
|
||||||
|
|
||||||
|
def validate_source(
|
||||||
|
frame: pd.DataFrame,
|
||||||
|
metadata: dict[str, Any],
|
||||||
|
) -> None:
|
||||||
|
"""Valide le dataset avant tout chargement en base."""
|
||||||
|
missing_columns = REQUIRED_COLUMNS.difference(frame.columns)
|
||||||
|
|
||||||
|
if missing_columns:
|
||||||
|
raise ValueError(f"Colonnes obligatoires absentes : {sorted(missing_columns)}")
|
||||||
|
|
||||||
|
expected_records = int(metadata["total_records"])
|
||||||
|
|
||||||
|
if len(frame) != expected_records:
|
||||||
|
raise ValueError(f"Nombre de lignes inattendu : {len(frame)} au lieu de {expected_records}")
|
||||||
|
|
||||||
|
expected_sites = set(metadata["sites"].keys())
|
||||||
|
actual_sites = set(frame["site_id"].unique())
|
||||||
|
|
||||||
|
if actual_sites != expected_sites:
|
||||||
|
raise ValueError(
|
||||||
|
f"Sites incohérents. Attendus={sorted(expected_sites)}, trouvés={sorted(actual_sites)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
duplicated = frame.duplicated(subset=["site_id", "timestamp"]).sum()
|
||||||
|
|
||||||
|
if duplicated:
|
||||||
|
raise ValueError(f"{duplicated} doublons (site_id, timestamp) détectés")
|
||||||
|
|
||||||
|
static_variants = frame.groupby("site_id")[["site_type", "site_name"]].nunique()
|
||||||
|
|
||||||
|
if (static_variants > 1).any().any():
|
||||||
|
raise ValueError("Un site possède plusieurs valeurs de site_type ou site_name.")
|
||||||
|
|
||||||
|
# Vérifie également que tous les timestamps
|
||||||
|
# peuvent être interprétés correctement.
|
||||||
|
pd.to_datetime(
|
||||||
|
frame["timestamp"],
|
||||||
|
errors="raise",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_timestamps(
|
||||||
|
frame: pd.DataFrame,
|
||||||
|
source_timezone: str,
|
||||||
|
) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
Normalise les timestamps et leur associe une timezone.
|
||||||
|
|
||||||
|
Les timestamps originaux sont conservés dans une colonne
|
||||||
|
temporaire afin de pouvoir les stocker dans raw_data.
|
||||||
|
"""
|
||||||
|
normalized = frame.copy()
|
||||||
|
|
||||||
|
normalized["_source_timestamp"] = normalized["timestamp"]
|
||||||
|
|
||||||
|
timestamps = pd.to_datetime(
|
||||||
|
normalized["timestamp"],
|
||||||
|
errors="raise",
|
||||||
|
)
|
||||||
|
|
||||||
|
if timestamps.dt.tz is None:
|
||||||
|
timestamps = timestamps.dt.tz_localize(source_timezone)
|
||||||
|
else:
|
||||||
|
timestamps = timestamps.dt.tz_convert(source_timezone)
|
||||||
|
|
||||||
|
normalized["timestamp"] = timestamps
|
||||||
|
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
def to_json_value(value: Any) -> Any:
|
||||||
|
"""
|
||||||
|
Convertit une valeur Pandas/Numpy en valeur
|
||||||
|
compatible JSON.
|
||||||
|
"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
if pd.isna(value):
|
||||||
|
return None
|
||||||
|
except TypeError, ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if isinstance(value, pd.Timestamp):
|
||||||
|
return value.isoformat()
|
||||||
|
|
||||||
|
if hasattr(value, "item"):
|
||||||
|
return value.item()
|
||||||
|
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
async def ensure_dataset(
|
||||||
|
connection: AsyncConnection,
|
||||||
|
metadata: dict[str, Any],
|
||||||
|
sha256: str,
|
||||||
|
source_timezone: str,
|
||||||
|
storage_uri: str,
|
||||||
|
) -> int:
|
||||||
|
"""
|
||||||
|
Crée l'entrée dataset si elle n'existe pas.
|
||||||
|
|
||||||
|
Le SHA-256 permet de reconnaître un fichier déjà importé
|
||||||
|
et participe à l'idempotence et à la traçabilité.
|
||||||
|
"""
|
||||||
|
result = await connection.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
SELECT dataset_id
|
||||||
|
FROM dataset
|
||||||
|
WHERE archive_sha256 = :sha256
|
||||||
|
LIMIT 1
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"sha256": sha256,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
existing = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if existing is not None:
|
||||||
|
return int(existing)
|
||||||
|
|
||||||
|
metadata_summary = {
|
||||||
|
"generator_version": metadata.get("generator_version"),
|
||||||
|
"total_sites": metadata.get("total_sites"),
|
||||||
|
"total_records": metadata.get("total_records"),
|
||||||
|
"date_range": metadata.get("date_range"),
|
||||||
|
"frequency": metadata.get("frequency"),
|
||||||
|
"null_injection_enabled": metadata.get("null_injection_enabled"),
|
||||||
|
"null_strategies": metadata.get("null_strategies"),
|
||||||
|
"importer": "historical_import_v1",
|
||||||
|
}
|
||||||
|
|
||||||
|
result = await connection.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
INSERT INTO dataset (
|
||||||
|
dataset_name,
|
||||||
|
archive_sha256,
|
||||||
|
storage_uri,
|
||||||
|
source_timezone,
|
||||||
|
"metadata"
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
:dataset_name,
|
||||||
|
:archive_sha256,
|
||||||
|
:storage_uri,
|
||||||
|
:source_timezone,
|
||||||
|
CAST(:metadata AS jsonb)
|
||||||
|
)
|
||||||
|
RETURNING dataset_id
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"dataset_name": ("EnerVision historical dataset 2023-2024"),
|
||||||
|
"archive_sha256": sha256,
|
||||||
|
"storage_uri": storage_uri,
|
||||||
|
"source_timezone": source_timezone,
|
||||||
|
"metadata": json.dumps(
|
||||||
|
metadata_summary,
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
return int(result.scalar_one())
|
||||||
|
|
||||||
|
|
||||||
|
async def upsert_sites(
|
||||||
|
connection: AsyncConnection,
|
||||||
|
frame: pd.DataFrame,
|
||||||
|
) -> None:
|
||||||
|
"""Insère ou met à jour les sites du dataset."""
|
||||||
|
sites = cast(
|
||||||
|
list[dict[str, Any]],
|
||||||
|
frame[
|
||||||
|
[
|
||||||
|
"site_id",
|
||||||
|
"site_type",
|
||||||
|
"site_name",
|
||||||
|
]
|
||||||
|
]
|
||||||
|
.drop_duplicates(subset=["site_id"])
|
||||||
|
.to_dict(orient="records"),
|
||||||
|
)
|
||||||
|
|
||||||
|
await connection.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
INSERT INTO site (
|
||||||
|
site_id,
|
||||||
|
site_type,
|
||||||
|
site_name
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
:site_id,
|
||||||
|
:site_type,
|
||||||
|
:site_name
|
||||||
|
)
|
||||||
|
ON CONFLICT (site_id)
|
||||||
|
DO UPDATE SET
|
||||||
|
site_type = EXCLUDED.site_type,
|
||||||
|
site_name = EXCLUDED.site_name
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
sites,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_reading_batch(
|
||||||
|
chunk: pd.DataFrame,
|
||||||
|
dataset_id: int,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Transforme un chunk Pandas en lignes prêtes
|
||||||
|
à être chargées dans la table reading.
|
||||||
|
"""
|
||||||
|
rows: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
records = cast(
|
||||||
|
list[dict[str, Any]],
|
||||||
|
chunk.to_dict(orient="records"),
|
||||||
|
)
|
||||||
|
|
||||||
|
for record in records:
|
||||||
|
quality, reasons = classify_quality(record)
|
||||||
|
|
||||||
|
raw_data = {
|
||||||
|
column: to_json_value(value)
|
||||||
|
for column, value in record.items()
|
||||||
|
if column != "_source_timestamp"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Dans raw_data, on conserve le timestamp
|
||||||
|
# exactement tel qu'il était dans le CSV.
|
||||||
|
raw_data["timestamp"] = to_json_value(record["_source_timestamp"])
|
||||||
|
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"site_id": record["site_id"],
|
||||||
|
"timestamp": record["timestamp"],
|
||||||
|
"source": SOURCE_NAME,
|
||||||
|
"dataset_id": dataset_id,
|
||||||
|
# Non fourni par le dataset historique.
|
||||||
|
"consumption_kw": None,
|
||||||
|
"consumption_kwh": to_json_value(record["consumption_kwh"]),
|
||||||
|
"consumption_euros": to_json_value(record["consumption_euros"]),
|
||||||
|
# Non fournis par le CSV historique.
|
||||||
|
"voltage_v": None,
|
||||||
|
"current_a": None,
|
||||||
|
"power_factor": None,
|
||||||
|
"temperature_celsius": (to_json_value(record["temperature_celsius"])),
|
||||||
|
"humidity_percent": (to_json_value(record["humidity_percent"])),
|
||||||
|
"solar_irradiance_wm2": (to_json_value(record["solar_irradiance_wm2"])),
|
||||||
|
"is_working_hours": bool(record["is_working_hours"]),
|
||||||
|
"data_quality": quality,
|
||||||
|
"null_reasons": reasons,
|
||||||
|
# Aucune imputation pendant l'ingestion RAW.
|
||||||
|
# Les valeurs manquantes sont conservées telles quelles
|
||||||
|
# afin de préserver la donnée source.
|
||||||
|
"imputed_values": None,
|
||||||
|
"imputation_method": None,
|
||||||
|
# Conservation de la donnée source
|
||||||
|
# pour la traçabilité.
|
||||||
|
"raw_data": json.dumps(
|
||||||
|
raw_data,
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
READING_INSERT = text(
|
||||||
|
"""
|
||||||
|
INSERT INTO reading (
|
||||||
|
site_id,
|
||||||
|
timestamp,
|
||||||
|
source,
|
||||||
|
dataset_id,
|
||||||
|
consumption_kw,
|
||||||
|
consumption_kwh,
|
||||||
|
consumption_euros,
|
||||||
|
voltage_v,
|
||||||
|
current_a,
|
||||||
|
power_factor,
|
||||||
|
temperature_celsius,
|
||||||
|
humidity_percent,
|
||||||
|
solar_irradiance_wm2,
|
||||||
|
is_working_hours,
|
||||||
|
data_quality,
|
||||||
|
null_reasons,
|
||||||
|
imputed_values,
|
||||||
|
imputation_method,
|
||||||
|
raw_data
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
:site_id,
|
||||||
|
:timestamp,
|
||||||
|
:source,
|
||||||
|
:dataset_id,
|
||||||
|
:consumption_kw,
|
||||||
|
:consumption_kwh,
|
||||||
|
:consumption_euros,
|
||||||
|
:voltage_v,
|
||||||
|
:current_a,
|
||||||
|
:power_factor,
|
||||||
|
:temperature_celsius,
|
||||||
|
:humidity_percent,
|
||||||
|
:solar_irradiance_wm2,
|
||||||
|
:is_working_hours,
|
||||||
|
:data_quality,
|
||||||
|
:null_reasons,
|
||||||
|
CAST(:imputed_values AS jsonb),
|
||||||
|
:imputation_method,
|
||||||
|
CAST(:raw_data AS jsonb)
|
||||||
|
)
|
||||||
|
ON CONFLICT DO NOTHING
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def import_historical(
|
||||||
|
csv_path: Path,
|
||||||
|
metadata_path: Path,
|
||||||
|
source_timezone: str,
|
||||||
|
batch_size: int,
|
||||||
|
dry_run: bool,
|
||||||
|
storage_uri: str,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Exécute le pipeline ETL historique EnerVision.
|
||||||
|
|
||||||
|
Étapes :
|
||||||
|
1. Extract
|
||||||
|
2. Validate
|
||||||
|
3. Transform
|
||||||
|
4. Load
|
||||||
|
"""
|
||||||
|
metadata = load_metadata(metadata_path)
|
||||||
|
|
||||||
|
frame = pd.read_csv(csv_path)
|
||||||
|
|
||||||
|
validate_source(
|
||||||
|
frame,
|
||||||
|
metadata,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"Lignes : {len(frame)}")
|
||||||
|
print(f"Sites : {frame['site_id'].nunique()}")
|
||||||
|
print(f"Période : {frame['timestamp'].min()} -> {frame['timestamp'].max()}")
|
||||||
|
print(f"Doublons : {frame.duplicated(['site_id', 'timestamp']).sum()}")
|
||||||
|
|
||||||
|
print("\nValeurs NULL :")
|
||||||
|
print(frame[MEASURE_COLUMNS].isna().sum())
|
||||||
|
|
||||||
|
sha256 = compute_sha256(csv_path)
|
||||||
|
|
||||||
|
print(f"\nSHA-256 : {sha256}")
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
print("\nDry-run terminé : aucune donnée écrite.")
|
||||||
|
return
|
||||||
|
|
||||||
|
normalized = normalize_timestamps(
|
||||||
|
frame,
|
||||||
|
source_timezone,
|
||||||
|
)
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
engine = create_async_engine(
|
||||||
|
str(settings.database_url),
|
||||||
|
pool_pre_ping=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with engine.begin() as connection:
|
||||||
|
dataset_id = await ensure_dataset(
|
||||||
|
connection=connection,
|
||||||
|
metadata=metadata,
|
||||||
|
sha256=sha256,
|
||||||
|
source_timezone=source_timezone,
|
||||||
|
storage_uri=storage_uri,
|
||||||
|
)
|
||||||
|
|
||||||
|
await upsert_sites(
|
||||||
|
connection,
|
||||||
|
normalized,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await connection.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM reading
|
||||||
|
WHERE dataset_id = :dataset_id
|
||||||
|
AND source = :source
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"dataset_id": dataset_id,
|
||||||
|
"source": SOURCE_NAME,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
before = int(result.scalar_one())
|
||||||
|
|
||||||
|
for start in range(
|
||||||
|
0,
|
||||||
|
len(normalized),
|
||||||
|
batch_size,
|
||||||
|
):
|
||||||
|
chunk = normalized.iloc[start : start + batch_size]
|
||||||
|
|
||||||
|
rows = build_reading_batch(
|
||||||
|
chunk,
|
||||||
|
dataset_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
await connection.execute(
|
||||||
|
READING_INSERT,
|
||||||
|
rows,
|
||||||
|
)
|
||||||
|
|
||||||
|
loaded = min(
|
||||||
|
start + batch_size,
|
||||||
|
len(normalized),
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"Chargement : {loaded}/{len(normalized)}")
|
||||||
|
|
||||||
|
result = await connection.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM reading
|
||||||
|
WHERE dataset_id = :dataset_id
|
||||||
|
AND source = :source
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"dataset_id": dataset_id,
|
||||||
|
"source": SOURCE_NAME,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
after = int(result.scalar_one())
|
||||||
|
|
||||||
|
print("\nImport terminé.")
|
||||||
|
print(f"dataset_id : {dataset_id}")
|
||||||
|
print(f"lectures avant : {before}")
|
||||||
|
print(f"lectures après : {after}")
|
||||||
|
print(f"nouvelles lectures : {after - before}")
|
||||||
|
|
||||||
|
finally:
|
||||||
|
await engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
"""Définit les arguments CLI de l'import."""
|
||||||
|
parser = argparse.ArgumentParser(description=("Import historique EnerVision"))
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--csv",
|
||||||
|
type=Path,
|
||||||
|
required=True,
|
||||||
|
help="Chemin vers le CSV historique.",
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--metadata",
|
||||||
|
type=Path,
|
||||||
|
required=True,
|
||||||
|
help=("Chemin vers le fichier dataset_metadata.json."),
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--source-timezone",
|
||||||
|
default="UTC",
|
||||||
|
help=("Timezone associée aux timestamps du dataset. Défaut : UTC."),
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--batch-size",
|
||||||
|
type=int,
|
||||||
|
default=1000,
|
||||||
|
help=("Nombre de lignes insérées par batch. Défaut : 1000."),
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--dry-run",
|
||||||
|
action="store_true",
|
||||||
|
help=("Valide les données sans écrire en base."),
|
||||||
|
)
|
||||||
|
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Point d'entrée CLI du pipeline."""
|
||||||
|
args = parse_args()
|
||||||
|
|
||||||
|
if args.batch_size <= 0:
|
||||||
|
raise ValueError("--batch-size doit être strictement supérieur à 0.")
|
||||||
|
|
||||||
|
# resolve() est volontairement exécuté ici,
|
||||||
|
# dans la partie synchrone du programme.
|
||||||
|
# Cela évite une opération filesystem bloquante
|
||||||
|
# à l'intérieur d'une fonction async.
|
||||||
|
storage_uri = args.csv.resolve().as_uri()
|
||||||
|
|
||||||
|
asyncio.run(
|
||||||
|
import_historical(
|
||||||
|
csv_path=args.csv,
|
||||||
|
metadata_path=args.metadata,
|
||||||
|
source_timezone=(args.source_timezone),
|
||||||
|
batch_size=args.batch_size,
|
||||||
|
dry_run=args.dry_run,
|
||||||
|
storage_uri=storage_uri,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import Depends, FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from prometheus_fastapi_instrumentator import Instrumentator
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.responses import HTMLResponse
|
||||||
|
|
||||||
|
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"]
|
||||||
|
STATIC_DIR = Path(__file__).parent / "static"
|
||||||
|
LOGO_URL = "/static/logo-icon.png"
|
||||||
|
|
||||||
|
|
||||||
|
@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=None,
|
||||||
|
redoc_url=None,
|
||||||
|
openapi_url="/openapi.json" if documentee else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
if documentee:
|
||||||
|
application.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||||
|
|
||||||
|
# ReDoc supporte nativement `info.x-logo` (extension Redocly) pour afficher un logo
|
||||||
|
# en en-tête ; Swagger UI n'a pas d'equivalent, il ne reprend que le favicon.
|
||||||
|
openapi_original = application.openapi
|
||||||
|
|
||||||
|
def openapi_avec_logo() -> dict[str, object]:
|
||||||
|
schema = openapi_original()
|
||||||
|
schema["info"]["x-logo"] = {"url": LOGO_URL, "altText": "EnerVision"}
|
||||||
|
return schema
|
||||||
|
|
||||||
|
application.openapi = openapi_avec_logo # type: ignore[method-assign]
|
||||||
|
|
||||||
|
@application.get("/docs", include_in_schema=False)
|
||||||
|
async def docs_swagger(_: Request) -> HTMLResponse:
|
||||||
|
return get_swagger_ui_html(
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
title=f"{application.title} · Swagger UI",
|
||||||
|
swagger_favicon_url=LOGO_URL,
|
||||||
|
)
|
||||||
|
|
||||||
|
@application.get("/redoc", include_in_schema=False)
|
||||||
|
async def docs_redoc(_: Request) -> HTMLResponse:
|
||||||
|
return get_redoc_html(
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
title=f"{application.title} · ReDoc",
|
||||||
|
redoc_favicon_url=LOGO_URL,
|
||||||
|
)
|
||||||
|
|
||||||
|
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,25 @@
|
|||||||
|
# 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.password_reset_attempt import PasswordResetAttempt
|
||||||
|
from app.models.password_reset_token import PasswordResetToken
|
||||||
|
from app.models.refresh_token import RefreshToken
|
||||||
|
from app.models.user import AppUser
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Alert",
|
||||||
|
"AppUser",
|
||||||
|
"AuditLog",
|
||||||
|
"Dataset",
|
||||||
|
"LoginAttempt",
|
||||||
|
"PasswordResetAttempt",
|
||||||
|
"PasswordResetToken",
|
||||||
|
"Prediction",
|
||||||
|
"Reading",
|
||||||
|
"Recommendation",
|
||||||
|
"RefreshToken",
|
||||||
|
"Site",
|
||||||
|
]
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# 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"
|
||||||
|
MOT_DE_PASSE_OUBLIE_DEMANDE = "auth.password_reset_requested"
|
||||||
|
MOT_DE_PASSE_REINITIALISE_PAR_SOI = "auth.password_reset_self_service"
|
||||||
|
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,27 @@
|
|||||||
|
# Pourquoi : même séparation que `login_attempt` par rapport à `audit_log` : ce compteur est
|
||||||
|
# piloté par l'attaquant (une campagne de demandes) et se purge, l'audit log est en ajout seul.
|
||||||
|
# Piège : la tentative est enregistrée même quand l'email est inconnu, sinon le 429 apprendrait
|
||||||
|
# qu'un compte existe.
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, DateTime, Identity, Index, String, func
|
||||||
|
from sqlalchemy.dialects.postgresql import INET
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetAttempt(Base):
|
||||||
|
__tablename__ = "password_reset_attempt"
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_password_reset_attempt_email_date", "email_tried", "occurred_at"),
|
||||||
|
Index("ix_password_reset_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)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Pourquoi : même schéma que `refresh_token` (chaîne opaque, jamais un JWT) pour la même
|
||||||
|
# raison : un jeton de réinitialisation doit être révocable d'un coup, et un JWT ne figure
|
||||||
|
# dans aucune ligne à invalider.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import 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 PasswordResetToken(Base):
|
||||||
|
__tablename__ = "password_reset_token"
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_password_reset_token_user", "user_id"),
|
||||||
|
Index(
|
||||||
|
"ix_password_reset_token_vivants",
|
||||||
|
"user_id",
|
||||||
|
postgresql_where="consumed_at is null",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PG_UUID(as_uuid=True), primary_key=True, server_default=func.gen_random_uuid()
|
||||||
|
)
|
||||||
|
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)
|
||||||
|
consumed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=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,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,42 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.password_reset_attempt import PasswordResetAttempt
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ResetRequestCounts:
|
||||||
|
per_identifier: int
|
||||||
|
per_ip: int
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetAttemptRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def record(self, *, email: str, client_ip: str | None) -> None:
|
||||||
|
self._session.add(
|
||||||
|
PasswordResetAttempt(email_tried=email.strip().lower(), client_ip=client_ip)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def count_recent(
|
||||||
|
self, *, email: str, client_ip: str | None, window_seconds: int
|
||||||
|
) -> ResetRequestCounts:
|
||||||
|
identifiant = email.strip().lower()
|
||||||
|
meme_email = PasswordResetAttempt.email_tried == identifiant
|
||||||
|
meme_ip = PasswordResetAttempt.client_ip == client_ip
|
||||||
|
|
||||||
|
requete = select(
|
||||||
|
func.count().filter(meme_email),
|
||||||
|
func.count().filter(meme_ip),
|
||||||
|
).where(
|
||||||
|
PasswordResetAttempt.occurred_at
|
||||||
|
> datetime.now(UTC) - timedelta(seconds=window_seconds),
|
||||||
|
meme_email | meme_ip,
|
||||||
|
)
|
||||||
|
|
||||||
|
par_identifiant, par_ip = (await self._session.execute(requete)).one()
|
||||||
|
return ResetRequestCounts(per_identifier=par_identifiant, per_ip=par_ip)
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# Piège : `consume()` est une seule instruction, sur le modèle de `claim_for_rotation()` du
|
||||||
|
# jeton de rafraîchissement. Un SELECT puis un UPDATE laisseraient une fenêtre où deux
|
||||||
|
# soumissions concurrentes du même lien réussiraient toutes les deux.
|
||||||
|
|
||||||
|
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.password_reset_token import PasswordResetToken
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ConsumedResetToken:
|
||||||
|
id: UUID
|
||||||
|
user_id: UUID
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetTokenRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def create(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
user_id: UUID,
|
||||||
|
token_hash: bytes,
|
||||||
|
expires_at: datetime,
|
||||||
|
client_ip: str | None,
|
||||||
|
user_agent: str | None,
|
||||||
|
) -> PasswordResetToken:
|
||||||
|
jeton = PasswordResetToken(
|
||||||
|
user_id=user_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 consume(self, token_hash: bytes) -> ConsumedResetToken | None:
|
||||||
|
requete = (
|
||||||
|
update(PasswordResetToken)
|
||||||
|
.where(
|
||||||
|
PasswordResetToken.token_hash == token_hash,
|
||||||
|
PasswordResetToken.consumed_at.is_(None),
|
||||||
|
PasswordResetToken.expires_at > func.clock_timestamp(),
|
||||||
|
)
|
||||||
|
.values(consumed_at=func.clock_timestamp())
|
||||||
|
.returning(PasswordResetToken.id, PasswordResetToken.user_id)
|
||||||
|
)
|
||||||
|
ligne = (await self._session.execute(requete)).one_or_none()
|
||||||
|
if ligne is None:
|
||||||
|
return None
|
||||||
|
return ConsumedResetToken(id=ligne.id, user_id=ligne.user_id)
|
||||||
|
|
||||||
|
# Piège : simple SELECT, volontairement pas atomique avec la consommation. Sert seulement
|
||||||
|
# au feedback UX (jeton encore valide ?) ; `consume()` reste la seule source de vérité.
|
||||||
|
async def exists_valid(self, token_hash: bytes) -> bool:
|
||||||
|
requete = select(PasswordResetToken.id).where(
|
||||||
|
PasswordResetToken.token_hash == token_hash,
|
||||||
|
PasswordResetToken.consumed_at.is_(None),
|
||||||
|
PasswordResetToken.expires_at > func.clock_timestamp(),
|
||||||
|
)
|
||||||
|
return (await self._session.execute(requete)).first() is not None
|
||||||
|
|
||||||
|
async def invalidate_all_for_user(self, user_id: UUID) -> int:
|
||||||
|
resultat = await self._session.execute(
|
||||||
|
update(PasswordResetToken)
|
||||||
|
.where(PasswordResetToken.user_id == user_id, PasswordResetToken.consumed_at.is_(None))
|
||||||
|
.values(consumed_at=func.clock_timestamp())
|
||||||
|
.returning(PasswordResetToken.id)
|
||||||
|
)
|
||||||
|
return len(resultat.all())
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
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. `reading_id` départage
|
||||||
|
# les égalités de timestamp, que `uq_reading_source` autorise à `source` différente.
|
||||||
|
requete = (
|
||||||
|
select(Reading)
|
||||||
|
.distinct(Reading.site_id)
|
||||||
|
.order_by(Reading.site_id, Reading.timestamp.desc(), Reading.reading_id.desc())
|
||||||
|
)
|
||||||
|
return (await self._session.execute(requete)).scalars().all()
|
||||||
|
|
||||||
|
async def latest_for_site(self, site_id: str) -> Reading | None:
|
||||||
|
# Piège : `uq_reading_source` autorise deux lignes au même `site_id`+`timestamp` quand la
|
||||||
|
# `source` diffère. Sans `reading_id` en départage, le `LIMIT 1` renverrait au hasard.
|
||||||
|
requete = (
|
||||||
|
select(Reading)
|
||||||
|
.where(Reading.site_id == site_id)
|
||||||
|
.order_by(Reading.timestamp.desc(), Reading.reading_id.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
lecture: Reading | None = await self._session.scalar(requete)
|
||||||
|
return lecture
|
||||||
|
|
||||||
|
async def list_history(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
start: datetime,
|
||||||
|
end: datetime,
|
||||||
|
site_id: str | None = None,
|
||||||
|
limit: int,
|
||||||
|
offset: int,
|
||||||
|
) -> Sequence[Reading]:
|
||||||
|
requete = (
|
||||||
|
select(Reading)
|
||||||
|
.where(Reading.timestamp >= start, Reading.timestamp < end)
|
||||||
|
.order_by(Reading.timestamp.desc(), Reading.reading_id.desc())
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset)
|
||||||
|
)
|
||||||
|
if site_id is not None:
|
||||||
|
requete = requete.where(Reading.site_id == site_id)
|
||||||
|
return (await self._session.scalars(requete)).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,95 @@
|
|||||||
|
# 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.
|
||||||
|
# Contrainte : `SPECIAL_CHARACTERS` doit rester identique à `password.validator.ts` côté
|
||||||
|
# frontend. `\w`/`\d` divergent entre Python (Unicode) et JavaScript (ASCII) : une classe
|
||||||
|
# explicite, plutôt qu'une négation, évite qu'un mot de passe soit accepté d'un côté et
|
||||||
|
# rejeté de l'autre (ex. "Sécurité1", où "é" comptait comme "spécial" pour Python seul).
|
||||||
|
|
||||||
|
import re
|
||||||
|
from typing import Literal, Self
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator
|
||||||
|
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
|
||||||
|
PASSWORD_MIN_LENGTH = 8
|
||||||
|
PASSWORD_MAX_LENGTH = 128
|
||||||
|
|
||||||
|
SPECIAL_CHARACTERS = "!@#$%^&*()-_=+[]{};:,.?"
|
||||||
|
|
||||||
|
_MAJUSCULE = re.compile(r"[A-ZÀ-ÖØ-Þ]")
|
||||||
|
_MINUSCULE = re.compile(r"[a-zà-öø-þ]")
|
||||||
|
_CHIFFRE = re.compile(r"[0-9]")
|
||||||
|
_SPECIAL = re.compile(r"[" + re.escape(SPECIAL_CHARACTERS) + r"]")
|
||||||
|
|
||||||
|
|
||||||
|
def valide_complexite(mot_de_passe: str) -> str:
|
||||||
|
manquants = [
|
||||||
|
nom
|
||||||
|
for nom, motif in (
|
||||||
|
("une majuscule", _MAJUSCULE),
|
||||||
|
("une minuscule", _MINUSCULE),
|
||||||
|
("un chiffre", _CHIFFRE),
|
||||||
|
("un caractère spécial", _SPECIAL),
|
||||||
|
)
|
||||||
|
if not motif.search(mot_de_passe)
|
||||||
|
]
|
||||||
|
if manquants:
|
||||||
|
raise ValueError(f"Le mot de passe doit contenir au moins {', '.join(manquants)}")
|
||||||
|
return mot_de_passe
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
@field_validator("new_password")
|
||||||
|
@classmethod
|
||||||
|
def _new_password_est_complexe(cls, valeur: str) -> str:
|
||||||
|
return valide_complexite(valeur)
|
||||||
|
|
||||||
|
|
||||||
|
class ForgotPasswordRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
|
||||||
|
|
||||||
|
class ResetPasswordRequest(BaseModel):
|
||||||
|
token: str = Field(min_length=1)
|
||||||
|
new_password: str = Field(min_length=PASSWORD_MIN_LENGTH, max_length=PASSWORD_MAX_LENGTH)
|
||||||
|
|
||||||
|
@field_validator("new_password")
|
||||||
|
@classmethod
|
||||||
|
def _new_password_est_complexe(cls, valeur: str) -> str:
|
||||||
|
return valide_complexite(valeur)
|
||||||
|
|
||||||
|
|
||||||
|
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 ResetTokenValidationResponse(BaseModel):
|
||||||
|
valid: bool
|
||||||
|
|
||||||
|
|
||||||
|
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,45 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingSource(StrEnum):
|
||||||
|
CSV = "csv"
|
||||||
|
API_CURRENT = "api_current"
|
||||||
|
API_HISTORY = "api_history"
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingDataQuality(StrEnum):
|
||||||
|
GOOD = "good"
|
||||||
|
PARTIAL = "partial"
|
||||||
|
DEGRADED = "degraded"
|
||||||
|
CRITICAL = "critical"
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
reading_id: int
|
||||||
|
site_id: str
|
||||||
|
timestamp: datetime
|
||||||
|
source: ReadingSource
|
||||||
|
consumption_kw: float | None
|
||||||
|
consumption_kwh: float | None
|
||||||
|
# Piège : `Decimal` (miroir de `Numeric(14, 2)` en base, pour ne pas arrondir un montant)
|
||||||
|
# sérialise en chaîne dans le JSON, pas en nombre — un consommateur qui ferait un `parseFloat`
|
||||||
|
# naïf perdrait la précision que ce choix visait à garder.
|
||||||
|
consumption_euros: Decimal | None
|
||||||
|
voltage_v: float | None
|
||||||
|
current_a: float | None
|
||||||
|
power_factor: float | None
|
||||||
|
temperature_celsius: float | None
|
||||||
|
humidity_percent: float | None
|
||||||
|
solar_irradiance_wm2: float | None
|
||||||
|
is_working_hours: bool | None
|
||||||
|
data_quality: ReadingDataQuality | None
|
||||||
|
null_reasons: list[str] | None
|
||||||
|
imputed_values: dict[str, Any] | None
|
||||||
|
imputation_method: str | None
|
||||||
@@ -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,42 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
|
||||||
|
class SensorDiagnosticResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
status: Literal["ok", "failing"]
|
||||||
|
since: datetime | None = Field(
|
||||||
|
description=(
|
||||||
|
"Horodatage de la dernière lecture reçue pour ce site. Ce n'est pas le début de la "
|
||||||
|
"panne : l'historique ne permet pas de le dater sans requête supplémentaire."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SiteSensorsResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
consumption: SensorDiagnosticResponse
|
||||||
|
electrical: SensorDiagnosticResponse
|
||||||
|
temperature: SensorDiagnosticResponse
|
||||||
|
humidity: SensorDiagnosticResponse
|
||||||
|
network: SensorDiagnosticResponse
|
||||||
|
|
||||||
|
|
||||||
|
class SiteSensorStatusResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
site_id: str
|
||||||
|
site_name: str
|
||||||
|
sensors: SiteSensorsResponse
|
||||||
|
overall: Literal["ok", "degraded", "critical"]
|
||||||
|
|
||||||
|
|
||||||
|
class SensorStatusResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
timestamp: datetime
|
||||||
|
sites: list[SiteSensorStatusResponse]
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class SiteCurrentResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
timestamp: datetime | None
|
||||||
|
site_id: str
|
||||||
|
site_type: str
|
||||||
|
consumption_kw: float | None
|
||||||
|
consumption_kwh: float | None
|
||||||
|
voltage_v: float | None
|
||||||
|
current_a: float | None
|
||||||
|
power_factor: float | None
|
||||||
|
temperature_celsius: float | None
|
||||||
|
humidity_percent: float | None
|
||||||
|
null_reasons: list[str]
|
||||||
|
data_quality: Literal["good", "partial", "degraded", "critical"]
|
||||||
@@ -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
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user