fix(beta): neutralise les caracteres de controle dans les sorties terminal
co-authored below Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Cette révision appartient à :
1 Parent
6a7872b09b
révision
1fffd39e5c
2 fichiers modifiés
+63
-7
Aucun fichier ne correspond à votre recherche
+14
-7
@@ -15,6 +15,7 @@ import csv
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
import unicodedata
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -22,6 +23,12 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|||||||
import db # noqa: E402
|
import db # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def propre(v):
|
||||||
|
"""Remplace tout caractère de contrôle (catégorie Unicode C*) : un testeur ne doit
|
||||||
|
pas pouvoir injecter de séquence d'échappement dans le terminal."""
|
||||||
|
return "".join(" " if unicodedata.category(ch)[0] == "C" else ch for ch in str(v if v is not None else ""))
|
||||||
|
|
||||||
|
|
||||||
def fmt(ts):
|
def fmt(ts):
|
||||||
return datetime.fromtimestamp(ts).strftime("%d/%m/%Y %H:%M") if ts else "-"
|
return datetime.fromtimestamp(ts).strftime("%d/%m/%Y %H:%M") if ts else "-"
|
||||||
|
|
||||||
@@ -58,7 +65,7 @@ def main(argv=None):
|
|||||||
label = a.label if a.nombre == 1 else f"{a.label} {i + 1}"
|
label = a.label if a.nombre == 1 else f"{a.label} {i + 1}"
|
||||||
cid, code = db.creer_code(c, label, a.jours, a.sessions)
|
cid, code = db.creer_code(c, label, a.jours, a.sessions)
|
||||||
lignes.append((cid, label, code))
|
lignes.append((cid, label, code))
|
||||||
print(f"#{cid} {label} {code}")
|
print(f"#{cid} {propre(label)} {code}")
|
||||||
if a.csv:
|
if a.csv:
|
||||||
f_ = db.DATA / "codes-emis.csv"
|
f_ = db.DATA / "codes-emis.csv"
|
||||||
neuf = not f_.exists()
|
neuf = not f_.exists()
|
||||||
@@ -71,7 +78,7 @@ def main(argv=None):
|
|||||||
print(f"(écrit dans {f_} : hors git, à supprimer après envoi)")
|
print(f"(écrit dans {f_} : hors git, à supprimer après envoi)")
|
||||||
elif a.cmd == "liste":
|
elif a.cmd == "liste":
|
||||||
for r_ in c.execute("SELECT * FROM codes ORDER BY id"):
|
for r_ in c.execute("SELECT * FROM codes ORDER BY id"):
|
||||||
print(f"#{r_['id']:<3} {etat(r_):<8} {r_['label']:<24} créé {fmt(r_['created_at'])} expire {fmt(r_['expires_at'])} "
|
print(f"#{r_['id']:<3} {etat(r_):<8} {propre(r_['label']):<24} créé {fmt(r_['created_at'])} expire {fmt(r_['expires_at'])} "
|
||||||
f"usages {r_['uses']} dernier {fmt(r_['last_used_at'])}")
|
f"usages {r_['uses']} dernier {fmt(r_['last_used_at'])}")
|
||||||
elif a.cmd == "revoquer":
|
elif a.cmd == "revoquer":
|
||||||
c.execute("UPDATE codes SET revoked_at=? WHERE id=? AND revoked_at IS NULL", (time.time(), a.id))
|
c.execute("UPDATE codes SET revoked_at=? WHERE id=? AND revoked_at IS NULL", (time.time(), a.id))
|
||||||
@@ -90,15 +97,15 @@ def main(argv=None):
|
|||||||
print("Prolongé.")
|
print("Prolongé.")
|
||||||
elif a.cmd == "journal":
|
elif a.cmd == "journal":
|
||||||
for r_ in c.execute("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (a.n,)):
|
for r_ in c.execute("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (a.n,)):
|
||||||
print(f"{fmt(r_['ts'])} {r_['event']:<16} code={r_['code_id'] or '-'} ip={r_['ip_hash'] or '-'} {r_['detail'] or ''}")
|
print(f"{fmt(r_['ts'])} {propre(r_['event']):<16} code={r_['code_id'] or '-'} ip={propre(r_['ip_hash']) or '-'} {propre(r_['detail'])}")
|
||||||
elif a.cmd == "retours":
|
elif a.cmd == "retours":
|
||||||
for r_ in c.execute("SELECT f.*, c.label FROM feedback f LEFT JOIN codes c ON c.id=f.code_id ORDER BY f.id DESC LIMIT ?", (a.n,)):
|
for r_ in c.execute("SELECT f.*, c.label FROM feedback f LEFT JOIN codes c ON c.id=f.code_id ORDER BY f.id DESC LIMIT ?", (a.n,)):
|
||||||
print(f"#{r_['id']} {fmt(r_['ts'])} [{r_['kind']}] {r_['label']} sur {r_['page']} ({r_['viewport']})"
|
print(f"#{r_['id']} {fmt(r_['ts'])} [{propre(r_['kind'])}] {propre(r_['label'])} sur {propre(r_['page'])} ({propre(r_['viewport'])})"
|
||||||
f"{' capture: ' + r_['shot'] if r_['shot'] else ''}\n {r_['text']}")
|
f"{' capture: ' + propre(r_['shot']) if r_['shot'] else ''}\n {propre(r_['text'])}")
|
||||||
elif a.cmd == "testeurs":
|
elif a.cmd == "testeurs":
|
||||||
for r_ in c.execute("SELECT * FROM testers ORDER BY id"):
|
for r_ in c.execute("SELECT * FROM testers ORDER BY id"):
|
||||||
print(f"#{r_['id']} {r_['prenom']} {r_['nom']} <{r_['email']}> {r_['tel']} "
|
print(f"#{r_['id']} {propre(r_['prenom'])} {propre(r_['nom'])} <{propre(r_['email'])}> {propre(r_['tel'])} "
|
||||||
f"{'MINEUR (parent: ' + str(r_['parent_nom']) + ')' if r_['mineur'] else 'majeur'} reseaux={r_['suivi_reseaux']}")
|
f"{'MINEUR (parent: ' + propre(r_['parent_nom']) + ')' if r_['mineur'] else 'majeur'} reseaux={r_['suivi_reseaux']}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import io, os, sys, tempfile, unittest
|
||||||
|
from contextlib import redirect_stdout
|
||||||
|
from pathlib import Path
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
os.environ["BETA_DATA"] = str(Path(tempfile.mkdtemp()) / "data")
|
||||||
|
import db, codes, server # noqa: E402
|
||||||
|
|
||||||
|
ESC = "\x1b[2J\x1b]0;pwn\x07"
|
||||||
|
|
||||||
|
|
||||||
|
def sortie(*args):
|
||||||
|
b = io.StringIO()
|
||||||
|
with redirect_stdout(b):
|
||||||
|
codes.main(list(args))
|
||||||
|
return b.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
class T(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.c = db.connect()
|
||||||
|
|
||||||
|
def test_propre(self):
|
||||||
|
self.assertEqual(codes.propre("a\x1bb\nc\x07"), "a b c ")
|
||||||
|
self.assertEqual(codes.propre(None), "")
|
||||||
|
|
||||||
|
def test_retours(self):
|
||||||
|
self.c.execute("INSERT INTO feedback(ts,text,page,viewport,kind) VALUES(1,?,?,?,?)", (ESC + "x", ESC, ESC, ESC)); self.c.commit()
|
||||||
|
self.assertNotIn("\x1b", sortie("retours"))
|
||||||
|
|
||||||
|
def test_testeurs(self):
|
||||||
|
self.c.execute("INSERT INTO testers(ts,nom,prenom,email,tel,mineur,parent_nom) VALUES(1,?,?,?,?,1,?)", (ESC,) * 4 + (ESC,)); self.c.commit()
|
||||||
|
self.assertNotIn("\x1b", sortie("testeurs"))
|
||||||
|
|
||||||
|
def test_liste_et_journal(self):
|
||||||
|
db.creer_code(self.c, ESC + "etiquette", 1)
|
||||||
|
db.journal(self.c, ESC, None, ESC, ESC)
|
||||||
|
self.assertNotIn("\x1b", sortie("liste"))
|
||||||
|
self.assertNotIn("\x1b", sortie("journal"))
|
||||||
|
|
||||||
|
def test_generer(self):
|
||||||
|
self.assertNotIn("\x1b", sortie("generer", "--label", ESC))
|
||||||
|
|
||||||
|
def test_serveur_refuse_controle(self):
|
||||||
|
self.assertTrue(server.a_controle("Jean\x1b[2J"))
|
||||||
|
self.assertFalse(server.a_controle("Éloïse-Marie"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Référencer dans un nouveau ticket
Bloquer un utilisateur