securite: #87 T6-T8 fin dette — deps qualifiées, semgrep, Secure auto, CORS
This commit is contained in:
+80
-1
@@ -402,4 +402,83 @@ class TestAvatar:
|
||||
"username": "admin", "password": "chab30",
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["user"]["avatar"] == TINY_PNG
|
||||
assert resp.json()["user"]["avatar"] == TINY_PNG
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
# Secure cookies (#87 T8)
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSecureCookies:
|
||||
"""`Secure` auto par défaut : https → flag, http → pas de flag
|
||||
(les navigateurs jettent les cookies Secure sur http)."""
|
||||
|
||||
@staticmethod
|
||||
def _req(scheme="http", forwarded_proto=None):
|
||||
from types import SimpleNamespace
|
||||
headers = {}
|
||||
if forwarded_proto is not None:
|
||||
headers["x-forwarded-proto"] = forwarded_proto
|
||||
return SimpleNamespace(
|
||||
url=SimpleNamespace(scheme=scheme),
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
def test_forced_true(self, monkeypatch):
|
||||
from backend.auth.router import is_secure_cookies
|
||||
monkeypatch.setenv("OBSIGATE_SECURE_COOKIES", "true")
|
||||
assert is_secure_cookies(self._req("http")) is True
|
||||
|
||||
def test_forced_false(self, monkeypatch):
|
||||
from backend.auth.router import is_secure_cookies
|
||||
monkeypatch.setenv("OBSIGATE_SECURE_COOKIES", "false")
|
||||
assert is_secure_cookies(self._req("https")) is False
|
||||
|
||||
def test_auto_http(self, monkeypatch):
|
||||
from backend.auth.router import is_secure_cookies
|
||||
monkeypatch.delenv("OBSIGATE_SECURE_COOKIES", raising=False)
|
||||
assert is_secure_cookies(self._req("http")) is False
|
||||
|
||||
def test_auto_https(self, monkeypatch):
|
||||
from backend.auth.router import is_secure_cookies
|
||||
monkeypatch.delenv("OBSIGATE_SECURE_COOKIES", raising=False)
|
||||
assert is_secure_cookies(self._req("https")) is True
|
||||
|
||||
def test_auto_forwarded_proto_trusted(self, monkeypatch):
|
||||
from backend.auth.router import is_secure_cookies
|
||||
monkeypatch.delenv("OBSIGATE_SECURE_COOKIES", raising=False)
|
||||
monkeypatch.setenv("OBSIGATE_TRUST_PROXY", "true")
|
||||
assert is_secure_cookies(self._req("http", "https")) is True
|
||||
|
||||
def test_auto_forwarded_proto_untrusted(self, monkeypatch):
|
||||
from backend.auth.router import is_secure_cookies
|
||||
monkeypatch.delenv("OBSIGATE_SECURE_COOKIES", raising=False)
|
||||
monkeypatch.delenv("OBSIGATE_TRUST_PROXY", raising=False)
|
||||
assert is_secure_cookies(self._req("http", "https")) is False
|
||||
|
||||
def test_login_http_sets_cookie_without_secure(self, auth_client, monkeypatch):
|
||||
monkeypatch.delenv("OBSIGATE_SECURE_COOKIES", raising=False)
|
||||
resp = auth_client.post("/api/auth/login", json={
|
||||
"username": "admin", "password": "chab30",
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
set_cookie = resp.headers.get("set-cookie", "")
|
||||
assert "access_token" in set_cookie
|
||||
assert "secure" not in set_cookie.lower()
|
||||
|
||||
def test_login_https_sets_secure_cookie(self, auth_client, monkeypatch):
|
||||
"""Même app servie en https → flag Secure présent."""
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
monkeypatch.delenv("OBSIGATE_SECURE_COOKIES", raising=False)
|
||||
https_client = TestClient(app, base_url="https://testserver",
|
||||
raise_server_exceptions=False)
|
||||
try:
|
||||
resp = https_client.post("/api/auth/login", json={
|
||||
"username": "admin", "password": "chab30",
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
assert "secure" in resp.headers.get("set-cookie", "").lower()
|
||||
finally:
|
||||
if hasattr(https_client, "close"):
|
||||
https_client.close()
|
||||
@@ -61,6 +61,17 @@ class TestRunnerProofScripts:
|
||||
)
|
||||
|
||||
|
||||
class TestSemgrepStep:
|
||||
def test_semgrep_local_rules_enforced(self):
|
||||
"""#87 T7 : semgrep bloquant sur règles locales (aucun registre)."""
|
||||
text = CI_YML.read_text(encoding="utf-8")
|
||||
assert "semgrep --config semgrep-rules/ backend/" in text, (
|
||||
"#87 T7 : étape semgrep locale attendue dans le job security"
|
||||
)
|
||||
rules = REPO_ROOT / "semgrep-rules" / "obsigate-python.yaml"
|
||||
assert rules.exists(), "ruleset semgrep manquant"
|
||||
|
||||
|
||||
class TestFrontendStepsHaveTheirDeps:
|
||||
@staticmethod
|
||||
def _root_step_files() -> list[str]:
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Parité i18n FR/EN des locales du frontend (#87 T9).
|
||||
|
||||
`frontend/locales/fr.json` et `en.json` doivent exposer exactement les mêmes
|
||||
clés (comparaison profonde) : toute clé manquante fait afficher la clé brute
|
||||
dans l'UI au lieu du libellé.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
LOCALES = Path(__file__).resolve().parent.parent / "frontend" / "locales"
|
||||
|
||||
|
||||
def _flat(d: dict, prefix: str = "") -> set[str]:
|
||||
keys = set()
|
||||
for k, v in d.items():
|
||||
name = f"{prefix}.{k}" if prefix else str(k)
|
||||
if isinstance(v, dict):
|
||||
keys |= _flat(v, name)
|
||||
else:
|
||||
keys.add(name)
|
||||
return keys
|
||||
|
||||
|
||||
def _load(lang: str) -> set[str]:
|
||||
return _flat(json.loads((LOCALES / f"{lang}.json").read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
class TestI18nParity:
|
||||
def test_fr_en_same_keys(self):
|
||||
fr, en = _load("fr"), _load("en")
|
||||
assert not (fr - en), f"clés sans traduction EN : {sorted(fr - en)[:10]}"
|
||||
assert not (en - fr), f"clés sans traduction FR : {sorted(en - fr)[:10]}"
|
||||
@@ -1,31 +1,34 @@
|
||||
"""Tests — cookies Secure, CORS same-origin implicite, avertissement bind (ROADMAP #87 T3).
|
||||
"""Tests — cookies Secure, CORS same-origin explicite, avertissement bind (ROADMAP #87 T3/T8).
|
||||
|
||||
- `is_secure_cookies()` suit `OBSIGATE_SECURE_COOKIES` (défaut `false` :
|
||||
compatibilité logins en HTTP local — les navigateurs ignorent les cookies
|
||||
`Secure` en clair).
|
||||
- Aucun en-tête CORS permissif n'est émis : sans `CORSMiddleware`, les
|
||||
navigateurs appliquent le same-origin par défaut (politique explicite par
|
||||
l'absence — vérifiée ici pour qu'un ajout futur de CORS soit conscient).
|
||||
- `is_secure_cookies()` : `OBSIGATE_SECURE_COOKIES=true|false|auto` (défaut
|
||||
`auto` : Secure si la requête arrive en https, sinon pas de flag — les
|
||||
navigateurs ignorent les cookies `Secure` en clair).
|
||||
- CORS same-origin EXPLICITE : `CORSMiddleware(allow_origins=[])` — aucun
|
||||
`Access-Control-Allow-*` n'est émis même avec un `Origin` cross-origin,
|
||||
et les preflights sont rejetés (400).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_secure_cookies_default_false(monkeypatch):
|
||||
"""Défaut `false` (logins HTTP locaux préservés)."""
|
||||
def test_secure_cookies_default_auto(monkeypatch):
|
||||
"""Défaut `auto` : sans requête → pas de flag (logins HTTP locaux préservés)."""
|
||||
from backend.auth.router import is_secure_cookies
|
||||
|
||||
monkeypatch.delenv("OBSIGATE_SECURE_COOKIES", raising=False)
|
||||
assert is_secure_cookies() is False
|
||||
|
||||
|
||||
def test_secure_cookies_opt_in(monkeypatch):
|
||||
"""`OBSIGATE_SECURE_COOKIES=true` → flag actif (insensible à la casse)."""
|
||||
def test_secure_cookies_forced_values(monkeypatch):
|
||||
"""`true`/`1`/`yes` → flag ; `false`/`0`/`no` → pas de flag (insensible à la casse)."""
|
||||
from backend.auth.router import is_secure_cookies
|
||||
|
||||
for value in ("true", "True", "TRUE", "1", "yes"):
|
||||
for value in ("true", "True", "TRUE", "1", "yes", "on"):
|
||||
monkeypatch.setenv("OBSIGATE_SECURE_COOKIES", value)
|
||||
assert is_secure_cookies() is (value.lower() == "true")
|
||||
assert is_secure_cookies() is True
|
||||
for value in ("false", "False", "FALSE", "0", "no", "off"):
|
||||
monkeypatch.setenv("OBSIGATE_SECURE_COOKIES", value)
|
||||
assert is_secure_cookies() is False
|
||||
|
||||
|
||||
def test_no_cors_headers_on_api(client):
|
||||
@@ -42,6 +45,25 @@ def test_no_cors_headers_on_public_share(client):
|
||||
assert "access-control-allow-origin" not in {k.lower() for k in resp.headers}
|
||||
|
||||
|
||||
def test_cross_origin_get_emits_no_acao(client):
|
||||
"""#87 T8 : même avec un `Origin` cross-origin, aucun ACAO (refus explicite)."""
|
||||
resp = client.get("/api/health", headers={"Origin": "http://evil.example"})
|
||||
assert resp.status_code == 200
|
||||
assert "access-control-allow-origin" not in {k.lower() for k in resp.headers}
|
||||
|
||||
|
||||
def test_cross_origin_preflight_rejected(client):
|
||||
"""#87 T8 : preflight cross-origin → 400 (origine non autorisée)."""
|
||||
resp = client.options(
|
||||
"/api/health",
|
||||
headers={
|
||||
"Origin": "http://evil.example",
|
||||
"Access-Control-Request-Method": "GET",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_security_headers_present(client):
|
||||
"""En-têtes de durcissement posés par le middleware (non-régression)."""
|
||||
resp = client.get("/api/health")
|
||||
|
||||
Reference in New Issue
Block a user