Courrier v1.5 (tt-2026-11-068) : telechargement securise des pieces jointes depuis le panneau de lecture
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XGaEeWkqZYNP6Wn3mGQsrL
This commit is contained in:
1 parent
a9fbd45081
commit
ce10cae840
7 files changed
+176
-10
No files matched your search
+47
-1
@@ -1,8 +1,11 @@
|
||||
import base64
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from urllib.parse import quote
|
||||
from typing import Optional, List, Dict, Any
|
||||
from pathlib import Path
|
||||
from fastapi import FastAPI, APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -198,6 +201,20 @@ def get_mails_periode(jours: int = 7):
|
||||
|
||||
# --- Lecture d'un mail (texte seul, lecture seule) ---
|
||||
MAX_CORPS_LECTURE = 200_000
|
||||
MAX_PIECE = 25 * 1024 * 1024
|
||||
# Extensions exécutables ou actives : jamais servies (le mail est un contenu non fiable).
|
||||
EXT_REFUSEES = {"exe", "msi", "bat", "cmd", "com", "scr", "pif", "vbs", "vbe", "js", "jse", "wsf", "wsh", "ps1", "psm1",
|
||||
"jar", "lnk", "hta", "cpl", "reg", "dll", "sys", "iso", "img", "html", "htm", "xhtml", "svg",
|
||||
"docm", "xlsm", "pptm", "dotm", "xlam", "appx", "apk", "sh", "py", "app", "dmg", "chm"}
|
||||
|
||||
|
||||
def _extension(nom: str) -> str:
|
||||
return nom.rsplit(".", 1)[-1].lower().strip() if "." in nom else ""
|
||||
|
||||
|
||||
def _nom_sur(nom: str) -> str:
|
||||
nom = re.sub(r"[\\/\x00-\x1f\x7f\"]", "_", nom.replace("\\", "/").split("/")[-1]).strip(" .")
|
||||
return (nom or "piece-jointe")[:150]
|
||||
|
||||
|
||||
def _entete(en_tetes: Dict[str, Any], nom: str) -> str:
|
||||
@@ -227,6 +244,7 @@ def lire_mail(id: str = Query(..., min_length=1, max_length=400)):
|
||||
"nom": str(p.get("filename") or p.get("nom") or "(sans nom)"),
|
||||
"type": str(p.get("content_type") or p.get("type") or ""),
|
||||
"taille": int(p.get("size") or p.get("taille") or 0),
|
||||
"bloquee": _extension(str(p.get("filename") or p.get("nom") or "")) in EXT_REFUSEES,
|
||||
})
|
||||
return {
|
||||
"message_id": d.get("message_id") or id,
|
||||
@@ -238,6 +256,34 @@ def lire_mail(id: str = Query(..., min_length=1, max_length=400)):
|
||||
}
|
||||
|
||||
|
||||
@api.get("/mail/piece")
|
||||
def telecharger_piece(id: str = Query(..., min_length=1, max_length=400), nom: str = Query(..., min_length=1, max_length=260)):
|
||||
"""Télécharge une pièce jointe : toujours en téléchargement (jamais affichée), extensions actives refusées,
|
||||
plafond de taille, aucune écriture, aucun contenu dans les journaux."""
|
||||
if _extension(nom) in EXT_REFUSEES:
|
||||
raise HTTPException(status_code=403, detail="Type de fichier bloqué par sécurité.")
|
||||
try:
|
||||
res = mirror_client.get_attachment(id, nom)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="Pièce jointe indisponible : miroir injoignable.")
|
||||
d = res.get("donnees") if isinstance(res, dict) else None
|
||||
b64 = d.get("contenu_base64") if isinstance(d, dict) else None
|
||||
if not b64:
|
||||
raise HTTPException(status_code=404, detail="Pièce jointe introuvable.")
|
||||
if len(b64) * 3 // 4 > MAX_PIECE or int(d.get("taille") or 0) > MAX_PIECE:
|
||||
raise HTTPException(status_code=413, detail="Pièce jointe trop volumineuse (25 Mo maximum).")
|
||||
try:
|
||||
brut = base64.b64decode(b64)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="Pièce jointe illisible.")
|
||||
propre = _nom_sur(nom)
|
||||
ascii_nom = propre.encode("ascii", "replace").decode().replace("?", "_")
|
||||
return Response(content=brut, media_type="application/octet-stream", headers={
|
||||
"Content-Disposition": f"attachment; filename=\"{ascii_nom}\"; filename*=UTF-8''{quote(propre)}",
|
||||
"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
|
||||
})
|
||||
|
||||
|
||||
# --- Classements ---
|
||||
@api.get("/classements")
|
||||
def get_classements(
|
||||
|
||||
@@ -283,6 +283,11 @@ class MirrorClient:
|
||||
pass # le miroir reste lisible sur les 100 derniers même si la recherche échoue
|
||||
return out
|
||||
|
||||
def get_attachment(self, message_id: str, filename: str) -> Dict[str, Any]:
|
||||
"""Pièce jointe d'un mail (mirror_mail_attachment), jamais mise en cache (contenu volumineux)."""
|
||||
res = self.call_tool("mirror_mail_attachment", {"message_id": message_id, "filename": filename}, use_cache=False)
|
||||
return res if isinstance(res, dict) else {"raw": res}
|
||||
|
||||
def get_mails_for_day(self, date_str: str, max_items: int = 50) -> List[Dict[str, Any]]:
|
||||
"""Mails d'un jour donné (AAAA-MM-JJ)."""
|
||||
if not date_str:
|
||||
|
||||
@@ -264,3 +264,10 @@ h1, h2, h3, p { margin: 0; }
|
||||
.lect-meta { grid-template-columns: minmax(0, 1fr); gap: 0; }
|
||||
.lect-meta dt { margin-top: var(--ny-e2); font-size: 13px; line-height: 18px; }
|
||||
}
|
||||
|
||||
/* Pièces jointes : téléchargement */
|
||||
.lect-pj li .btn-icone { flex: none; }
|
||||
.lect-pj .info.bloquee { color: var(--ny-erreur, var(--ny-encre-2)); font-weight: 600; }
|
||||
.lect-sig { margin-top: var(--ny-e4); }
|
||||
.lect-sig ul { list-style: none; margin: var(--ny-e2) 0 0; padding: 0; display: grid; gap: var(--ny-e2); }
|
||||
.lect-sig li { display: flex; align-items: center; gap: var(--ny-e3); min-height: var(--ny-cible); padding: 6px var(--ny-e3); color: var(--ny-encre-2); }
|
||||
+41
-6
@@ -14,7 +14,7 @@
|
||||
suivi: 'M12 6v6l4 2|M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0',
|
||||
pj: 'm21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48',
|
||||
groupes: 'M3 7h7v7H3z|M14 7h7v7h-7z|M3 17h18',
|
||||
fermer: 'M18 6 6 18|m6 6 12 12', gauche: 'm15 18-6-6 6-6', droite: 'm9 18 6-6-6-6', bas: 'm6 9 6 6 6-6', fleche: 'M5 12h14|m12 5 7 7-7 7'
|
||||
telecharger: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4|m7 10 5 5 5-5|M12 15V3', fermer: 'M18 6 6 18|m6 6 12 12', gauche: 'm15 18-6-6 6-6', droite: 'm9 18 6-6-6-6', bas: 'm6 9 6 6 6-6', fleche: 'M5 12h14|m12 5 7 7-7 7'
|
||||
};
|
||||
var NAV = [
|
||||
['tri', 'Tri du jour', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['regles', 'Règles', true],
|
||||
@@ -378,6 +378,28 @@
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(iso)) return String(v || '');
|
||||
return nomJour(iso).toLowerCase() + ' ' + fr(iso) + ' à ' + heureTunis(v);
|
||||
}
|
||||
function estSignature(p) {
|
||||
return /^image\//.test(p.type || '') && Number(p.taille) < 20480 && !p.bloquee;
|
||||
}
|
||||
function telechargerPiece(id, p, bt) {
|
||||
bt.disabled = true; annoncer('Téléchargement de ' + p.nom + ' en cours');
|
||||
fetch(API + '/mail/piece?id=' + encodeURIComponent(id) + '&nom=' + encodeURIComponent(p.nom), { credentials: 'same-origin', redirect: 'manual' })
|
||||
.then(function (rep) {
|
||||
if (rep.type === 'opaqueredirect') { sessionExpiree(); throw new Error('session'); }
|
||||
if (rep.status === 403) throw new Error('Ce type de fichier est bloqué par sécurité.');
|
||||
if (rep.status === 413) throw new Error('Pièce jointe trop volumineuse (25 Mo maximum).');
|
||||
if (!rep.ok) throw new Error('Pièce jointe indisponible pour le moment.');
|
||||
return rep.blob();
|
||||
})
|
||||
.then(function (blob) {
|
||||
var url = URL.createObjectURL(blob), a = document.createElement('a');
|
||||
a.href = url; a.download = p.nom; document.body.appendChild(a); a.click(); a.remove();
|
||||
setTimeout(function () { URL.revokeObjectURL(url); }, 4000);
|
||||
annoncer(p.nom + ' téléchargé');
|
||||
})
|
||||
.catch(function (e) { if (e.message !== 'session') annoncer(e.message); })
|
||||
.then(function () { bt.disabled = false; });
|
||||
}
|
||||
function afficherMail(cont, m, r, c) {
|
||||
var badges = h('div', { class: 'lect-badges' }, h('span', { class: 'lect-cat' }, pastille(couleur(m.cat, c && c.id)), m.cat));
|
||||
(m.etiquettes || []).forEach(function (t) { badges.appendChild(h('span', { class: 'etq', text: t })); });
|
||||
@@ -398,14 +420,27 @@
|
||||
}
|
||||
if (r.tronque) cont.appendChild(h('p', { class: 'lect-note', text: 'Le texte est très long : seul le début est affiché.' }));
|
||||
var pj = r.pieces_jointes || [];
|
||||
if (pj.length) {
|
||||
var signature = pj.filter(estSignature), utiles = pj.filter(function (p) { return !estSignature(p); });
|
||||
function extDe(p) { var e = String(p.nom || '').indexOf('.') > -1 ? String(p.nom).split('.').pop().toUpperCase() : ''; return e && e.length <= 5 ? e + ' · ' : ''; }
|
||||
if (utiles.length) {
|
||||
var ul = h('ul');
|
||||
pj.forEach(function (p) {
|
||||
var ext = String(p.nom || '').indexOf('.') > -1 ? String(p.nom).split('.').pop().toUpperCase() : '';
|
||||
utiles.forEach(function (p) {
|
||||
var action;
|
||||
if (p.bloquee) action = h('span', { class: 'info bloquee', text: 'Bloquée par sécurité' });
|
||||
else {
|
||||
var bt = h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Télécharger ' + p.nom, title: 'Télécharger' }, icone('telecharger'));
|
||||
bt.addEventListener('click', function () { telechargerPiece(r.message_id || m.id, p, bt); });
|
||||
action = bt;
|
||||
}
|
||||
ul.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }),
|
||||
h('span', { class: 'info', text: (ext && ext.length <= 5 ? ext + ' · ' : '') + tailleLisible(p.taille) })));
|
||||
h('span', { class: 'info', text: extDe(p) + tailleLisible(p.taille) }), action));
|
||||
});
|
||||
cont.appendChild(h('section', { class: 'lect-pj', 'aria-labelledby': 'lect-pj-t' }, h('h3', { id: 'lect-pj-t', text: 'Pièces jointes (' + pj.length + ')' }), ul));
|
||||
cont.appendChild(h('section', { class: 'lect-pj', 'aria-labelledby': 'lect-pj-t' }, h('h3', { id: 'lect-pj-t', text: 'Pièces jointes (' + utiles.length + ')' }), ul));
|
||||
}
|
||||
if (signature.length) {
|
||||
var us = h('ul');
|
||||
signature.forEach(function (p) { us.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }), h('span', { class: 'info', text: tailleLisible(p.taille) }))); });
|
||||
cont.appendChild(h('details', { class: 'lect-histo lect-sig' }, h('summary', null, 'Images intégrées au message (' + signature.length + ')'), us));
|
||||
}
|
||||
cont.appendChild(h('p', { class: 'lect-note', text: 'Lecture seule : le mail n\'est pas modifié dans votre messagerie.' }));
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<link rel="stylesheet" href="/static/fonts.css">
|
||||
<link rel="stylesheet" href="/static/nyora.css">
|
||||
<link rel="stylesheet" href="/static/app.css?v=20261117g">
|
||||
<link rel="stylesheet" href="/static/app.css?v=20261118a">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" class="coque">
|
||||
@@ -20,6 +20,6 @@
|
||||
</div>
|
||||
<div id="calque"></div>
|
||||
<div id="annonce" class="sr" role="status" aria-live="polite"></div>
|
||||
<script src="/static/app.js?v=20261117g"></script>
|
||||
<script src="/static/app.js?v=20261118a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -28,7 +28,7 @@ def test_lecture_renvoie_les_champs_utiles(client, monkeypatch):
|
||||
j = r.json()
|
||||
assert j["de"].startswith("Ali Ben Salah") and "autre@exemple.tn" in j["a"] and j["cc"] == "copie@exemple.tn"
|
||||
assert j["objet"] == "Demande de prix" and j["corps"].startswith("Bonjour,") and j["tronque"] is False
|
||||
assert j["pieces_jointes"] == [{"nom": "offre.pdf", "type": "application/pdf", "taille": 20480}]
|
||||
assert j["pieces_jointes"] == [{"nom": "offre.pdf", "type": "application/pdf", "taille": 20480, "bloquee": False}]
|
||||
|
||||
|
||||
def test_lecture_plafonne_un_corps_tres_long(client, monkeypatch):
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app, mirror_client, MAX_PIECE, _nom_sur
|
||||
|
||||
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||
|
||||
|
||||
def fausse(contenu=b"%PDF-1.4 test", nom="offre.pdf", taille=None):
|
||||
return lambda mid, f: {"donnees": {"message_id": mid, "nom": nom, "type_mime": "application/pdf",
|
||||
"taille": taille if taille is not None else len(contenu),
|
||||
"encodage": "base64", "contenu_base64": base64.b64encode(contenu).decode()}}
|
||||
|
||||
|
||||
def test_piece_exige_le_jeton():
|
||||
assert TestClient(app).get("/api/v1/mail/piece?id=m-1&nom=offre.pdf").status_code == 401
|
||||
|
||||
|
||||
def test_piece_telechargee_toujours_en_piece_jointe(client, monkeypatch):
|
||||
monkeypatch.setattr(mirror_client, "get_attachment", fausse())
|
||||
r = client.get("/api/v1/mail/piece?id=m-1&nom=offre.pdf")
|
||||
assert r.status_code == 200 and r.content == b"%PDF-1.4 test"
|
||||
assert r.headers["content-type"].startswith("application/octet-stream")
|
||||
assert r.headers["content-disposition"].startswith("attachment;")
|
||||
assert r.headers["x-content-type-options"] == "nosniff" and r.headers["cache-control"] == "no-store"
|
||||
|
||||
|
||||
def test_piece_nom_accentue_dans_l_entete(client, monkeypatch):
|
||||
monkeypatch.setattr(mirror_client, "get_attachment", fausse(nom="Offre financière.pdf"))
|
||||
r = client.get("/api/v1/mail/piece", params={"id": "m-1", "nom": "Offre financière.pdf"})
|
||||
assert "filename*=UTF-8''Offre%20financi%C3%A8re.pdf" in r.headers["content-disposition"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nom", ["setup.exe", "page.HTML", "macro.xlsm", "script.js", "image.svg", "a.b.bat"])
|
||||
def test_extensions_actives_refusees_sans_appel_miroir(client, monkeypatch, nom):
|
||||
def boom(*a): raise AssertionError("le miroir ne doit pas etre appele")
|
||||
monkeypatch.setattr(mirror_client, "get_attachment", boom)
|
||||
assert client.get("/api/v1/mail/piece", params={"id": "m-1", "nom": nom}).status_code == 403
|
||||
|
||||
|
||||
def test_piece_trop_volumineuse(client, monkeypatch):
|
||||
monkeypatch.setattr(mirror_client, "get_attachment", fausse(taille=MAX_PIECE + 1))
|
||||
assert client.get("/api/v1/mail/piece?id=m-1&nom=gros.pdf").status_code == 413
|
||||
|
||||
|
||||
def test_piece_introuvable_et_miroir_indisponible(client, monkeypatch):
|
||||
monkeypatch.setattr(mirror_client, "get_attachment", lambda mid, f: {"donnees": {}})
|
||||
assert client.get("/api/v1/mail/piece?id=m-1&nom=x.pdf").status_code == 404
|
||||
def casse(mid, f): raise ConnectionError("x")
|
||||
monkeypatch.setattr(mirror_client, "get_attachment", casse)
|
||||
assert client.get("/api/v1/mail/piece?id=m-1&nom=x.pdf").status_code == 502
|
||||
|
||||
|
||||
def test_nom_nettoye():
|
||||
assert _nom_sur('../../etc/pass"wd.pdf') == "pass_wd.pdf"
|
||||
assert _nom_sur("..") == "piece-jointe"
|
||||
|
||||
|
||||
def test_indicateur_bloquee_dans_la_lecture(client, monkeypatch):
|
||||
d = {"message_id": "m-1", "en_tetes": {}, "corps_texte": "x",
|
||||
"pieces_jointes": [{"filename": "a.exe", "content_type": "application/x", "size": 5},
|
||||
{"filename": "b.pdf", "content_type": "application/pdf", "size": 5}]}
|
||||
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": d})
|
||||
pj = client.get("/api/v1/mail?id=m-1").json()["pieces_jointes"]
|
||||
assert [p["bloquee"] for p in pj] == [True, False]
|
||||
|
||||
|
||||
def test_interface_telechargement_sans_innerhtml():
|
||||
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||
assert "telechargerPiece" in js and "/mail/piece?id=" in js and "innerHTML" not in js
|
||||
Reference in new issue
Block a user