from datetime import datetime, timedelta, timezone
import psycopg
import pytest
from fastapi.testclient import TestClient
from shortstats.config import WebConfig
from shortstats.web.app import create_app
from shortstats.web.auth import hash_password
ORIGIN = "http://testserver"
CH = "UC" + "a" * 22
OTHER = "UC" + "b" * 22
PASSWORD = "un-mot-de-passe-solide"
@pytest.fixture()
def users_file(tmp_path):
path = tmp_path / "users.txt"
path.write_text(f"# comptes\nalice:{hash_password(PASSWORD)}\nligne invalide\n")
return path
@pytest.fixture()
def app_client(clean_db, users_file):
cfg = WebConfig(database_url=clean_db["web"], secret_key="x" * 40, users_file=str(users_file),
session_max_age_s=3600, cookie_secure=False, login_max_failures=3, login_lock_minutes=15)
with TestClient(create_app(cfg), base_url=ORIGIN) as client:
yield client
def login(client, password=PASSWORD, origin=ORIGIN):
return client.post("/login", data={"username": "alice", "password": password},
headers={"Origin": origin}, follow_redirects=False)
def seed_videos(owner_url, n=30):
base = datetime(2026, 9, 1, 17, 0, tzinfo=timezone.utc)
with psycopg.connect(owner_url, autocommit=True) as conn:
conn.execute("""INSERT INTO shortstats.channel (channel_id, author_channel_id, youtube_title)
VALUES (%s, %s, 'Ma chaîne') ON CONFLICT DO NOTHING""", (CH, CH))
for i in range(n):
text = ["Apothecary Diaries saison 2", "une applepie", "rien"][i % 3]
conn.execute(
"""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, collected_at, title,
duration_s, view_count, like_count, comment_count, author_comment_status,
author_comment_text, author_comment_likes, author_comment_rank)
VALUES (%s, %s, %s, 'collected', now(), %s, %s, %s, %s, %s, 'found', %s, %s, 1)""",
(f"vid{i:08d}", CH, base + timedelta(days=i, hours=i % 5), f"Short {i}",
30 + i, 1000 * (i + 1), 40 * (i + 1), 5 + i, text, i * 2),
)
def test_pages_require_login(app_client):
r = app_client.get("/", follow_redirects=False)
assert r.status_code == 303 and r.headers["location"] == "/login"
assert app_client.get("/api/charts").status_code == 401
assert app_client.get("/videos", follow_redirects=False).status_code == 303
def test_healthz_and_security_headers(app_client):
r = app_client.get("/healthz")
assert r.json() == {"status": "ok"}
r = app_client.get("/login")
assert "script-src 'self'" in r.headers["content-security-policy"]
assert r.headers["x-frame-options"] == "DENY"
assert r.headers["cache-control"] == "no-store"
def test_login_logout_flow(app_client):
assert "incorrect" in login(app_client, password="mauvais").text
r = login(app_client)
assert r.status_code == 303 and r.headers["location"] == "/"
cookie = r.headers["set-cookie"].lower()
assert "httponly" in cookie and "samesite=strict" in cookie
assert app_client.get("/").status_code == 200
app_client.post("/logout", headers={"Origin": ORIGIN})
assert app_client.get("/api/charts").status_code == 401
def test_login_rejects_foreign_origin(app_client):
r = login(app_client, origin="https://evil.example")
assert r.status_code == 403
def test_throttle_after_failures(app_client):
for _ in range(3):
login(app_client, password="mauvais")
r = login(app_client) # bon mot de passe, mais compte bloqué
assert "Trop d'essais" in r.text
def test_removing_user_revokes_session(app_client, users_file):
login(app_client)
assert app_client.get("/api/charts").status_code == 200
users_file.write_text("# plus personne\n")
import os
os.utime(users_file, (1, 1)) # forcer une date de modification différente
assert app_client.get("/api/charts").status_code == 401
def test_chart_crud_and_render(app_client, clean_db):
seed_videos(clean_db["owner"])
login(app_client)
h = {"Origin": ORIGIN}
cfg = {"x": "weekday", "y": "views", "type": "auto", "agg": "auto", "color": None, "scale": "auto", "title": ""}
r = app_client.post("/api/charts", json={"config": cfg}, headers=h)
assert r.status_code == 201
chart_id = r.json()["id"]
r2 = app_client.post("/api/charts", json={"config": {**cfg, "x": "theme", "y": "count"}}, headers=h)
second = r2.json()["id"]
out = app_client.get(f"/api/charts/{chart_id}/render").json()
assert out["n"] == 30 and out["spec"]["mark"]["type"] in {"boxplot", "bar"}
themes = {v["x"] for v in app_client.get(f"/api/charts/{second}/render").json()["spec"]["data"]["values"]}
assert themes == {"Apothecary Diaries", "applepie", "Aucun thème"}
assert app_client.post(f"/api/charts/{second}/move", json={"direction": -1}, headers=h).status_code == 204
assert [c["id"] for c in app_client.get("/api/charts").json()] == [second, chart_id]
r = app_client.put(f"/api/charts/{chart_id}", json={"config": {**cfg, "type": "heatmap", "y": "count"}}, headers=h)
assert r.status_code == 400 and "impossible" in r.json()["error"]
assert app_client.delete(f"/api/charts/{chart_id}", headers=h).status_code == 204
assert app_client.delete(f"/api/charts/{chart_id}", headers=h).status_code == 404
def test_api_requires_json_and_same_origin(app_client):
login(app_client)
cfg = {"x": "views", "y": "likes"}
assert app_client.post("/api/charts", json={"config": cfg}).status_code == 403 # sans Origin
r = app_client.post("/api/charts", data={"config": "x"}, headers={"Origin": ORIGIN})
assert r.status_code == 400
def test_preview_and_compat(app_client, clean_db):
seed_videos(clean_db["owner"])
login(app_client)
r = app_client.post("/api/preview", json={"config": {"x": "views", "y": "likes"}}, headers={"Origin": ORIGIN})
assert r.json()["resolved"]["type"] == "scatter"
compat = app_client.get("/api/compat?x=views&y=count").json()
assert compat["histogram"] is None and compat["scatter"]
def test_themes_page_and_crud(app_client, clean_db):
seed_videos(clean_db["owner"])
login(app_client)
h = {"Origin": ORIGIN}
r = app_client.post("/themes", data={"name": "Saison", "keywords": "saison 2, saison deux"}, headers=h,
follow_redirects=False)
assert r.headers["location"] == "/themes?msg=created"
page = app_client.get("/themes").text
assert "Saison" in page and "saison 2, saison deux" in page
r = app_client.post("/themes", data={"name": "Saison", "keywords": "x"}, headers=h, follow_redirects=False)
assert r.headers["location"] == "/themes?msg=duplicate"
r = app_client.post("/themes", data={"name": "", "keywords": "x"}, headers=h, follow_redirects=False)
assert r.headers["location"] == "/themes?msg=invalid"
def test_video_titles_are_escaped(app_client, clean_db):
seed_videos(clean_db["owner"], n=3)
login(app_client)
html = app_client.get("/videos").text
assert "<b>Short 0</b>" in html and "Short 0" not in html
def channels_in_db(owner_url):
with psycopg.connect(owner_url) as conn:
return {r[0]: r[1:] for r in conn.execute(
"SELECT channel_id, author_channel_id, active, author_title, checked_at FROM shortstats.channel")}
def test_channel_management(app_client, clean_db):
login(app_client)
h = {"Origin": ORIGIN}
def post(path, data):
return app_client.post(path, data=data, headers=h, follow_redirects=False).headers["location"]
third = "UC" + "c" * 22
# L'utilisateur A est obligatoire : jamais de propriétaire implicite
assert post("/channels", {"channel": CH, "author": ""}) == "/channels?msg=missing_author"
assert post("/channels", {"channel": CH, "author": " "}) == "/channels?msg=missing_author"
assert channels_in_db(clean_db["owner"]) == {}
# Ajout avec une autre personne comme utilisateur A
assert post("/channels", {"channel": CH, "author": OTHER}) == "/channels?msg=created"
# Ajout à partir d'URL, l'utilisateur A étant ici le propriétaire (saisi explicitement)
assert post("/channels", {"channel": f"https://www.youtube.com/channel/{third}/shorts",
"author": f"https://youtube.com/channel/{third}"}) == "/channels?msg=created"
# Une même personne peut être l'utilisateur A de plusieurs chaînes
fourth = "UC" + "e" * 22
assert post("/channels", {"channel": fourth, "author": OTHER}) == "/channels?msg=created"
rows = channels_in_db(clean_db["owner"])
assert (rows[CH][:2], rows[third][:2], rows[fourth][:2]) == ((OTHER, True), (third, True), (OTHER, True))
post(f"/channels/{fourth}/delete", {})
# Erreurs de saisie
assert post("/channels", {"channel": CH, "author": OTHER}) == "/channels?msg=duplicate"
assert post("/channels", {"channel": "@machaine", "author": OTHER}) == "/channels?msg=handle"
assert post("/channels", {"channel": "https://www.youtube.com/@machaine", "author": OTHER}) == "/channels?msg=handle"
assert post("/channels", {"channel": "UC123", "author": OTHER}) == "/channels?msg=invalid_channel"
assert post("/channels", {"channel": "UC" + "d" * 22, "author": "pas un id"}) == "/channels?msg=invalid_author"
assert post("/channels", {"channel": "UC" + "d" * 22, "author": "@quelquun"}) == "/channels?msg=invalid_author"
# Changer l'utilisateur A remet sa vérification à zéro ; mettre en pause ne la touche pas
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
conn.execute("UPDATE shortstats.channel SET checked_at = now(), author_title = 'Ancien A'")
# Vider le champ à la modification est refusé (et ne change rien)
assert post(f"/channels/{CH}", {"author": "", "active": "on"}) == "/channels?msg=missing_author"
assert channels_in_db(clean_db["owner"])[CH][0] == OTHER
# Passer de l'autre personne au propriétaire, puis du propriétaire à l'autre personne
assert post(f"/channels/{CH}", {"author": CH, "active": "on"}) == "/channels?msg=updated"
assert post(f"/channels/{third}", {"author": OTHER, "active": "on"}) == "/channels?msg=updated"
rows = channels_in_db(clean_db["owner"])
assert rows[CH] == (CH, True, None, None) and rows[third] == (OTHER, True, None, None)
# Mise en pause sans changer l'utilisateur A : la vérification est conservée
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
conn.execute("UPDATE shortstats.channel SET checked_at = now(), author_title = 'Ancien A'")
assert post(f"/channels/{third}", {"author": OTHER}) == "/channels?msg=updated" # case décochée
rows = channels_in_db(clean_db["owner"])
assert rows[third][:3] == (OTHER, False, "Ancien A") and rows[third][3] is not None
# Réactiver une chaîne relance sa vérification
post(f"/channels/{third}", {"author": OTHER, "active": "on"})
assert channels_in_db(clean_db["owner"])[third][3] is None
# Page : identifiants et état affichés, champ toujours rempli avec l'identifiant de A
page = app_client.get("/channels").text
assert third in page and "vérification en cours" in page
assert "Utilisateur A" not in page and "utilisateur A" not in page
assert "Auteur du commentaire épinglé" in page
# liens vers la chaîne (onglet Shorts) et vers la page de l'auteur
assert f'href="https://www.youtube.com/channel/{third}/shorts"' in page
assert f'href="https://www.youtube.com/channel/{OTHER}"' in page
assert f'value="{OTHER}"' in page and f'value="{CH}"' in page
assert "propriétaire de la chaîne" in page
# Suppression : refusée si des vidéos existent, acceptée sinon
seed_videos(clean_db["owner"], n=2)
assert post(f"/channels/{CH}/delete", {}) == "/channels?msg=has_videos"
assert post(f"/channels/{third}/delete", {}) == "/channels?msg=deleted"
assert post("/channels/pas-un-id/delete", {}) == "/channels?msg=missing"
assert set(channels_in_db(clean_db["owner"])) == {CH}
def test_channel_field_in_charts_and_dashboard_banner(app_client, clean_db):
login(app_client)
assert "Aucune chaîne suivie" in app_client.get("/").text
seed_videos(clean_db["owner"], n=6)
out = app_client.post("/api/preview", json={"config": {"x": "channel", "y": "views"}},
headers={"Origin": ORIGIN}).json()
assert {v["x"] for v in out["spec"]["data"]["values"]} == {"Ma chaîne"}
assert "Aucune chaîne suivie" not in app_client.get("/").text
# -- v1.1.0 : changement de mot de passe -----------------------------------------
NEW_PASSWORD = "un-autre-mot-de-passe-long"
def change(client, current, new, confirm=None):
r = client.post("/account/password", headers={"Origin": ORIGIN}, follow_redirects=False,
data={"current": current, "new": new, "confirm": new if confirm is None else confirm})
return r.headers["location"]
def test_account_page_requires_login(app_client):
assert app_client.get("/account", follow_redirects=False).headers["location"] == "/login"
r = app_client.post("/account/password", headers={"Origin": ORIGIN},
data={"current": PASSWORD, "new": NEW_PASSWORD, "confirm": NEW_PASSWORD},
follow_redirects=False)
assert r.headers["location"] == "/login"
def test_change_password_validation(app_client):
login(app_client)
assert "Changer de mot de passe" in app_client.get("/account").text
assert change(app_client, "mauvais", NEW_PASSWORD) == "/account?msg=wrong_current"
assert change(app_client, PASSWORD, "court") == "/account?msg=too_short"
assert change(app_client, PASSWORD, NEW_PASSWORD, confirm="autre-chose-long") == "/account?msg=mismatch"
assert change(app_client, PASSWORD, PASSWORD) == "/account?msg=unchanged"
# Aucune de ces tentatives n'a changé le mot de passe.
app_client.post("/logout", headers={"Origin": ORIGIN})
assert login(app_client).headers["location"] == "/"
def test_change_password_flow(app_client, clean_db, users_file):
other = TestClient(app_client.app, base_url=ORIGIN) # 2e navigateur de la même personne
login(app_client)
login(other)
assert other.get("/api/charts").status_code == 200
assert change(app_client, PASSWORD, NEW_PASSWORD) == "/account?msg=changed"
# La session courante reste ouverte, l'autre est fermée.
assert app_client.get("/api/charts").status_code == 200
assert other.get("/api/charts").status_code == 401
# Ancien mot de passe refusé, nouveau accepté.
assert "incorrect" in login(other, password=PASSWORD).text
assert login(other, password=NEW_PASSWORD).headers["location"] == "/"
# Le haché est en base, users.txt n'a pas été modifié.
with psycopg.connect(clean_db["owner"]) as conn:
row = conn.execute("SELECT password_hash FROM shortstats.user_password WHERE username = 'alice'").fetchone()
assert row and row[0].startswith("$argon2id$")
assert "alice:" in users_file.read_text() and row[0] not in users_file.read_text()
def test_admin_reset_in_file_overrides_changed_password(app_client, users_file):
"""Mot de passe oublié : l'administrateur remplace la ligne de users.txt, qui reprend la main."""
import os
login(app_client)
assert change(app_client, PASSWORD, NEW_PASSWORD) == "/account?msg=changed"
reset = "mot-de-passe-de-secours"
users_file.write_text(f"alice:{hash_password(reset)}\n")
os.utime(users_file, (2, 2))
assert app_client.get("/api/charts").status_code == 401 # sessions fermées
assert "incorrect" in login(app_client, password=NEW_PASSWORD).text
assert login(app_client, password=reset).headers["location"] == "/"
def test_removed_user_cannot_use_changed_password(app_client, users_file):
import os
login(app_client)
change(app_client, PASSWORD, NEW_PASSWORD)
users_file.write_text("# plus personne\n")
os.utime(users_file, (3, 3))
assert app_client.get("/api/charts").status_code == 401
assert "incorrect" in login(app_client, password=NEW_PASSWORD).text
def test_change_password_is_throttled(app_client):
login(app_client)
for _ in range(3): # LOGIN_MAX_FAILURES = 3 dans la fixture
change(app_client, "mauvais", NEW_PASSWORD)
assert change(app_client, PASSWORD, NEW_PASSWORD) == "/account?msg=throttled"
def test_change_password_rejects_foreign_origin(app_client):
login(app_client)
r = app_client.post("/account/password", headers={"Origin": "https://evil.example"},
data={"current": PASSWORD, "new": NEW_PASSWORD, "confirm": NEW_PASSWORD})
assert r.status_code == 403