feat: auth fail-closed, regles par defaut idempotentes et conteneur non root (tt-2026-11-061)
This commit is contained in:
1 parent
b51a8bba69
commit
6aef9e83e7
11 files changed
+424
-95
No files matched your search
+8
-1
@@ -4,8 +4,9 @@ import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
import jwt
|
||||
|
||||
# Configure test environment variables before importing app
|
||||
# Configuration impérative de l'environnement de test avant l'importation de l'application
|
||||
TEST_SECRET = "secret-test-courrier-tt-2026-11-059"
|
||||
os.environ["ENV"] = "test"
|
||||
os.environ["CF_TEST_SECRET"] = TEST_SECRET
|
||||
os.environ["CF_ACCESS_AUD"] = "courrier-test-aud"
|
||||
|
||||
@@ -39,6 +40,12 @@ def client(valid_jwt_token, temp_db, monkeypatch):
|
||||
"""Client de test FastAPI avec injecteur d'en-tête Cloudflare Access et DB isolée."""
|
||||
monkeypatch.setattr("app.config.DB_PATH", temp_db)
|
||||
monkeypatch.setattr("app.db.DB_PATH", temp_db)
|
||||
monkeypatch.setattr("app.config.ENV", "test")
|
||||
monkeypatch.setattr("app.auth.ENV", "test")
|
||||
monkeypatch.setattr("app.config.CF_TEST_SECRET", TEST_SECRET)
|
||||
monkeypatch.setattr("app.auth.CF_TEST_SECRET", TEST_SECRET)
|
||||
monkeypatch.setattr("app.config.CF_ACCESS_AUD", "courrier-test-aud")
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "courrier-test-aud")
|
||||
init_db(temp_db)
|
||||
with TestClient(app) as c:
|
||||
c.headers.update({"Cf-Access-Jwt-Assertion": valid_jwt_token})
|
||||
|
||||
+127
-4
@@ -1,8 +1,11 @@
|
||||
import pytest
|
||||
import jwt
|
||||
from fastapi.testclient import TestClient
|
||||
from app.main import app
|
||||
from tests.conftest import TEST_SECRET
|
||||
|
||||
def test_health_endpoint_no_auth_required():
|
||||
"""/health reste public et répond 200 avec l'horodatage de Tunis."""
|
||||
client = TestClient(app)
|
||||
resp = client.get("/health")
|
||||
assert resp.status_code == 200
|
||||
@@ -11,22 +14,142 @@ def test_health_endpoint_no_auth_required():
|
||||
assert data["service"] == "courrier"
|
||||
assert "+01:00" in data["horodatage"]
|
||||
|
||||
def test_missing_cf_access_jwt_returns_401():
|
||||
def test_missing_cf_access_jwt_returns_401(monkeypatch):
|
||||
"""Une requête API sans en-tête JWT est rejetée en 401."""
|
||||
monkeypatch.setattr("app.auth.ENV", "test")
|
||||
monkeypatch.setattr("app.auth.CF_TEST_SECRET", TEST_SECRET)
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "courrier-test-aud")
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/v1/categories")
|
||||
assert resp.status_code == 401
|
||||
assert "Cf-Access-Jwt-Assertion manquant" in resp.json()["detail"]
|
||||
assert "manquant" in resp.json()["detail"]
|
||||
|
||||
def test_invalid_cf_access_jwt_returns_401():
|
||||
def test_invalid_cf_access_jwt_returns_401(monkeypatch):
|
||||
"""Un jeton malformé est rejeté en 401."""
|
||||
monkeypatch.setattr("app.auth.ENV", "test")
|
||||
monkeypatch.setattr("app.auth.CF_TEST_SECRET", TEST_SECRET)
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "courrier-test-aud")
|
||||
client = TestClient(app)
|
||||
# Token malformé
|
||||
resp = client.get(
|
||||
"/api/v1/categories",
|
||||
headers={"Cf-Access-Jwt-Assertion": "ceci.n-est-pas.un-jwt-valide"}
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
|
||||
def test_forged_alg_none_jwt_returns_401(monkeypatch):
|
||||
"""
|
||||
Preuve T1 : Un jeton forgé avec l'algorithme 'none' est formellement
|
||||
rejeté en 401 (aucun décodage non vérifié permis).
|
||||
"""
|
||||
monkeypatch.setattr("app.auth.ENV", "test")
|
||||
monkeypatch.setattr("app.auth.CF_TEST_SECRET", TEST_SECRET)
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "courrier-test-aud")
|
||||
|
||||
payload = {
|
||||
"sub": "hacker@evil.com",
|
||||
"email": "hacker@evil.com",
|
||||
"aud": "courrier-test-aud",
|
||||
"exp": 9999999999
|
||||
}
|
||||
# Jeton non signé (alg: none)
|
||||
forged_token = jwt.encode(payload, key="", algorithm="none")
|
||||
|
||||
client = TestClient(app)
|
||||
resp = client.get(
|
||||
"/api/v1/categories",
|
||||
headers={"Cf-Access-Jwt-Assertion": forged_token}
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
assert "signature non vérifiée" in resp.json()["detail"].lower() or "invalide" in resp.json()["detail"].lower()
|
||||
|
||||
def test_forged_bad_signature_jwt_returns_401(monkeypatch):
|
||||
"""
|
||||
Preuve T1 : Un jeton signé avec une fausse clé secrète est formellement
|
||||
rejeté en 401.
|
||||
"""
|
||||
monkeypatch.setattr("app.auth.ENV", "test")
|
||||
monkeypatch.setattr("app.auth.CF_TEST_SECRET", TEST_SECRET)
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "courrier-test-aud")
|
||||
|
||||
payload = {
|
||||
"sub": "hacker@evil.com",
|
||||
"email": "hacker@evil.com",
|
||||
"aud": "courrier-test-aud",
|
||||
"exp": 9999999999
|
||||
}
|
||||
# Signé avec une clé pirate différente
|
||||
forged_token = jwt.encode(payload, "mauvaise-cle-pirate-123-longueur-securisee-32-bytes", algorithm="HS256")
|
||||
|
||||
client = TestClient(app)
|
||||
resp = client.get(
|
||||
"/api/v1/categories",
|
||||
headers={"Cf-Access-Jwt-Assertion": forged_token}
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
|
||||
def test_bad_audience_jwt_returns_401(monkeypatch):
|
||||
"""Un jeton portant un audience différent de CF_ACCESS_AUD est rejeté en 401."""
|
||||
monkeypatch.setattr("app.auth.ENV", "test")
|
||||
monkeypatch.setattr("app.auth.CF_TEST_SECRET", TEST_SECRET)
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "courrier-test-aud")
|
||||
|
||||
payload = {
|
||||
"sub": "user@example.com",
|
||||
"aud": "autre-audience-invalide",
|
||||
"exp": 9999999999
|
||||
}
|
||||
token = jwt.encode(payload, TEST_SECRET, algorithm="HS256")
|
||||
|
||||
client = TestClient(app)
|
||||
resp = client.get(
|
||||
"/api/v1/categories",
|
||||
headers={"Cf-Access-Jwt-Assertion": token}
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
|
||||
def test_valid_cf_access_jwt_returns_200(client):
|
||||
"""Un jeton correctement signé en environnement de test donne accès en 200."""
|
||||
resp = client.get("/api/v1/categories")
|
||||
assert resp.status_code == 200
|
||||
assert "categories" in resp.json()
|
||||
|
||||
def test_unconfigured_auth_returns_503_on_api_and_200_on_health(monkeypatch):
|
||||
"""
|
||||
Preuve T1 : En production (ENV!=test) sans CF_ACCESS_CERTS_URL et CF_ACCESS_AUD,
|
||||
toutes les routes /api répondent 503 tandis que /health reste 200.
|
||||
"""
|
||||
monkeypatch.setattr("app.auth.ENV", "production")
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_CERTS_URL", "")
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "")
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
# 1. /health reste fonctionnel en 200
|
||||
r_health = client.get("/health")
|
||||
assert r_health.status_code == 200
|
||||
|
||||
# 2. Les routes /api renvoient 503 Fail-Closed
|
||||
r_api = client.get(
|
||||
"/api/v1/categories",
|
||||
headers={"Cf-Access-Jwt-Assertion": "dummy.token"}
|
||||
)
|
||||
assert r_api.status_code == 503
|
||||
assert "obligatoires" in r_api.json()["detail"]
|
||||
|
||||
def test_cf_test_secret_ignored_when_not_in_test_env(monkeypatch):
|
||||
"""
|
||||
Preuve T1 : Le mode CF_TEST_SECRET n'existe que si ENV=test.
|
||||
Si ENV=production, CF_TEST_SECRET est strictement ignoré et le service
|
||||
répond 503 si les clés JWKS de production ne sont pas configurées.
|
||||
"""
|
||||
monkeypatch.setattr("app.auth.ENV", "production")
|
||||
monkeypatch.setattr("app.auth.CF_TEST_SECRET", TEST_SECRET)
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_CERTS_URL", "")
|
||||
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "")
|
||||
|
||||
client = TestClient(app)
|
||||
r = client.get(
|
||||
"/api/v1/categories",
|
||||
headers={"Cf-Access-Jwt-Assertion": "token"}
|
||||
)
|
||||
assert r.status_code == 503
|
||||
@@ -11,6 +11,7 @@ from app.classifier import (
|
||||
classify_mail,
|
||||
manual_classify_and_propose,
|
||||
confirm_and_apply_rule,
|
||||
reclassify_all_non_manual,
|
||||
extract_keywords
|
||||
)
|
||||
|
||||
@@ -132,3 +133,46 @@ def test_confirm_proposed_rule_applies_to_non_manual_mails_only(temp_db):
|
||||
c1_after = get_classement(mid1, db_path=temp_db)
|
||||
assert c1_after["categorie"] == "Tunis"
|
||||
assert c1_after["source"] == "manuel"
|
||||
|
||||
def test_reclassify_preserves_manual_and_uses_non_default_category(temp_db):
|
||||
"""
|
||||
Preuve T2 : Au moins une catégorie autre que 'À classer' est utilisée sur les mails du jour,
|
||||
et les classements manuels ne sont JAMAIS écrasés.
|
||||
"""
|
||||
# Mail A avec étiquette 'tunis'
|
||||
mail_a = {
|
||||
"message_id": "<mail-tunis-01@domain.tn>",
|
||||
"expediteur": "contact@tunis.tn",
|
||||
"objet": "Point d'avancement",
|
||||
"date": "2026-11-17",
|
||||
"etiquettes": ["tunis"]
|
||||
}
|
||||
cA = classify_mail(mail_a, db_path=temp_db)
|
||||
assert cA["categorie"] == "Tunis", "L'étiquette 'tunis' doit classer en 'Tunis'"
|
||||
assert cA["source"] == "regle"
|
||||
|
||||
# Mail B classé manuellement en 'CI'
|
||||
mail_b = {
|
||||
"message_id": "<mail-manual-01@domain.tn>",
|
||||
"expediteur": "contact@autre.tn",
|
||||
"objet": "Point sans objet",
|
||||
"date": "2026-11-17",
|
||||
"etiquettes": ["sans_objet"]
|
||||
}
|
||||
cB_manual = save_classement_manuel(
|
||||
message_id=mail_b["message_id"],
|
||||
categorie="CI",
|
||||
db_path=temp_db
|
||||
)
|
||||
assert cB_manual["categorie"] == "CI"
|
||||
assert cB_manual["source"] == "manuel"
|
||||
|
||||
# Reclassement général
|
||||
reclassify_all_non_manual(db_path=temp_db)
|
||||
|
||||
# Vérifications :
|
||||
# 1. Le mail A est resté 'Tunis'
|
||||
assert get_classement(mail_a["message_id"], db_path=temp_db)["categorie"] == "Tunis"
|
||||
# 2. Le mail B manuel n'a JAMAIS été écrasé vers 'Sans objet'
|
||||
assert get_classement(mail_b["message_id"], db_path=temp_db)["categorie"] == "CI"
|
||||
assert get_classement(mail_b["message_id"], db_path=temp_db)["source"] == "manuel"
|
||||
+33
-3
@@ -1,5 +1,6 @@
|
||||
import pytest
|
||||
from app.db import (
|
||||
init_db,
|
||||
list_categories,
|
||||
add_category,
|
||||
update_category,
|
||||
@@ -20,6 +21,33 @@ def test_init_db_creates_tables_and_default_categories(temp_db):
|
||||
expected = ["Tunis", "Demande FB", "CI", "Câbles", "Sans objet", "À classer"]
|
||||
assert cat_names == expected, f"Catégories par défaut attendues: {expected}, obtenu: {cat_names}"
|
||||
|
||||
def test_init_db_creates_default_rules_idempotently(temp_db):
|
||||
"""
|
||||
Preuve T2 : Les règles de départ sont créées à partir des étiquettes miroir
|
||||
(sans_objet, tunis, courses) et catégories (Demande FB, CI, Câbles) de façon idempotente.
|
||||
"""
|
||||
rules_initial = list_regles(statut="active", db_path=temp_db)
|
||||
assert len(rules_initial) >= 6
|
||||
|
||||
# Vérification des règles sur étiquettes miroir
|
||||
tags = {r["etiquette_miroir"] for r in rules_initial if r["etiquette_miroir"]}
|
||||
assert "sans_objet" in tags
|
||||
assert "tunis" in tags
|
||||
assert "courses" in tags
|
||||
|
||||
# Vérification des catégories cibles
|
||||
rule_cats = {r["categorie"] for r in rules_initial}
|
||||
assert "Sans objet" in rule_cats
|
||||
assert "Tunis" in rule_cats
|
||||
assert "Demande FB" in rule_cats
|
||||
assert "CI" in rule_cats
|
||||
assert "Câbles" in rule_cats
|
||||
|
||||
# Idempotence : un second init_db ne doit pas créer de doublons
|
||||
init_db(temp_db)
|
||||
rules_after = list_regles(statut="active", db_path=temp_db)
|
||||
assert len(rules_after) == len(rules_initial)
|
||||
|
||||
def test_crud_categories(temp_db):
|
||||
# Création
|
||||
new_cat = add_category("Factures", db_path=temp_db)
|
||||
@@ -40,6 +68,8 @@ def test_crud_categories(temp_db):
|
||||
assert not any(c["name"] == "Factures Fournisseurs" for c in cats_after)
|
||||
|
||||
def test_crud_regles(temp_db):
|
||||
initial_count = len(list_regles(db_path=temp_db))
|
||||
|
||||
# Création
|
||||
rule = add_regle(
|
||||
categorie="Tunis",
|
||||
@@ -59,12 +89,12 @@ def test_crud_regles(temp_db):
|
||||
|
||||
# Liste
|
||||
rules = list_regles(statut="active", db_path=temp_db)
|
||||
assert len(rules) == 1
|
||||
assert rules[0]["categorie"] == "Demande FB"
|
||||
assert len(rules) == initial_count + 1
|
||||
assert any(r["id"] == rule["id"] and r["categorie"] == "Demande FB" for r in rules)
|
||||
|
||||
# Suppression
|
||||
assert delete_regle(rule["id"], db_path=temp_db) is True
|
||||
assert len(list_regles(db_path=temp_db)) == 0
|
||||
assert len(list_regles(db_path=temp_db)) == initial_count
|
||||
|
||||
def test_manual_classification_persistence(temp_db):
|
||||
mid = "<msg-001@domain.com>"
|
||||
|
||||
Reference in new issue
Block a user