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(
|
||||
|
||||
Reference in new issue
Block a user