rahim237cm Claude Opus 5 commited on
Commit
56362b9
·
1 Parent(s): dfc6e36

fix(laws): le telechargement rend le document, et un seul chemin le resout

Browse files

Le bouton "Telecharger" du front appelait window.print() : ce n'est pas un
telechargement mais l'impression de la page telle qu'affichee. Comme la page ne
monte qu'UN article a la fois et qu'aucune feuille @media print n'existe, le PDF
obtenu contenait le fil d'Ariane, le sommaire, l'en-tete et l'unique article lu.
Le document d'origine n'etait jamais en jeu. GET /laws/{id}/download servait
pourtant le bon fichier depuis toujours, sans qu'aucun code du front ne l'appelle.

Cote API, deux corrections. content_disposition_type passe de "inline" a
"attachment" : un bouton nomme "Telecharger" doit enregistrer le fichier, pas
l'afficher dans l'onglet. Et les CINQ endpoints qui servent un PDF (/download,
/pdf-data, /pdf-stream, /pdf-info, /page/{n}) partagent desormais _law_file_path,
qui delegue a resolve_upload_path. Chacun reconstruisait le chemin a la main,
avec un repli joignant law.file_id au repertoire d'upload sans motif, sans
resolve() ni confinement — cinq copies exactes de la faiblesse que
resolve_upload_path avait ete ecrite pour fermer, et elle n'etait utilisee que
par les routes OCR. Un file_id malforme donne maintenant 404 partout, la ou le
repli tentait une jointure de chemin arbitraire.

Neuf tests : le fichier servi est l'original octet pour octet (comparaison
sha256), l'en-tete annonce attachment avec le nom d'origine, une loi sans
fichier et une loi inexistante donnent 404, et quatre formes de file_id
malforme ("../../../etc/passwd", chemin avec separateur, trop court, vide)
donnent 404 et non 500 sur les trois endpoints principaux.

Le PDF de test est ecrit par pypdf plutot qu'a la main : un squelette sans table
xref faisait echouer PdfReader, et le test aurait mesure la qualite de sa propre
doublure.

Suite : 580 passants, 9 ignores, 0 echec.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

app/api/routes/laws.py CHANGED
@@ -14,6 +14,7 @@ Date: 2026-01-11
14
 
15
  import logging
16
  import time
 
17
  from typing import List, Optional, cast
18
 
19
  from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, status
@@ -33,6 +34,7 @@ from app.schemas.law import (
33
  LawUpdate,
34
  )
35
  from app.services.file_upload_service import get_upload_service
 
36
  from app.services.search_service import invalidate_search_cache
37
  from app.tasks.process_law import delete_from_search_index
38
 
@@ -189,6 +191,34 @@ async def get_law(
189
  )
190
 
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  @router.get("/{law_id}/download")
193
  async def download_law_file(
194
  law_id: int,
@@ -205,34 +235,15 @@ async def download_law_file(
205
  if not law.file_id:
206
  raise HTTPException(status_code=404, detail="No source file found for this law")
207
 
208
- upload_service = get_upload_service()
209
-
210
- # Try to find file with extension
211
- file_path = None
212
- # Use stored filename or construct one
213
- filename = law.original_filename or f"{law.reference}.pdf"
214
-
215
- # Check for PDF or DOCX using file_id
216
- for ext in [".pdf", ".docx"]:
217
- p = upload_service.storage_path / f"{law.file_id}{ext}"
218
- if p.exists():
219
- file_path = p
220
- break
221
-
222
- if not file_path:
223
- # Fallback: maybe file_id IS the filename (legacy behavior?)
224
- # Or maybe stored without extension?
225
- p = upload_service.storage_path / law.file_id
226
- if p.exists():
227
- file_path = p
228
- else:
229
- raise HTTPException(status_code=404, detail="File not found on server")
230
 
231
  return FileResponse(
232
  path=str(file_path),
233
  filename=str(cast(str, law.original_filename) or file_path.name),
234
  media_type="application/pdf" if file_path.suffix == ".pdf" else "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
235
- content_disposition_type="inline"
 
 
236
  )
237
 
238
 
@@ -258,22 +269,7 @@ async def get_law_pdf_data(
258
  raise HTTPException(status_code=404, detail="No source file found for this law")
259
 
260
  from app.services.file_upload_service import get_upload_service
261
- upload_service = get_upload_service()
262
-
263
- # Find the file
264
- file_path = None
265
- for ext in [".pdf", ".docx"]:
266
- p = upload_service.storage_path / f"{law.file_id}{ext}"
267
- if p.exists():
268
- file_path = p
269
- break
270
-
271
- if not file_path:
272
- p = upload_service.storage_path / law.file_id
273
- if p.exists():
274
- file_path = p
275
- else:
276
- raise HTTPException(status_code=404, detail="File not found on server")
277
 
278
  # Read file and encode to Base64
279
  with open(str(file_path), "rb") as f:
@@ -315,22 +311,7 @@ async def get_law_pdf_stream(
315
  raise HTTPException(status_code=404, detail="No source file found for this law")
316
 
317
  from app.services.file_upload_service import get_upload_service
318
- upload_service = get_upload_service()
319
-
320
- # Find the file
321
- file_path = None
322
- for ext in [".pdf", ".docx"]:
323
- p = upload_service.storage_path / f"{law.file_id}{ext}"
324
- if p.exists():
325
- file_path = p
326
- break
327
-
328
- if not file_path:
329
- p = upload_service.storage_path / law.file_id
330
- if p.exists():
331
- file_path = p
332
- else:
333
- raise HTTPException(status_code=404, detail="File not found on server")
334
 
335
  # Read file content
336
  with open(str(file_path), "rb") as f:
@@ -372,22 +353,7 @@ async def get_law_pdf_info(
372
  raise HTTPException(status_code=404, detail="No source file found for this law")
373
 
374
  from app.services.file_upload_service import get_upload_service
375
- upload_service = get_upload_service()
376
-
377
- # Find the file
378
- file_path = None
379
- for ext in [".pdf", ".docx"]:
380
- p = upload_service.storage_path / f"{law.file_id}{ext}"
381
- if p.exists():
382
- file_path = p
383
- break
384
-
385
- if not file_path:
386
- p = upload_service.storage_path / law.file_id
387
- if p.exists():
388
- file_path = p
389
- else:
390
- raise HTTPException(status_code=404, detail="File not found on server")
391
 
392
  # Get page count
393
  try:
@@ -438,22 +404,7 @@ async def get_law_pdf_page_image(
438
  raise HTTPException(status_code=404, detail="No source file found for this law")
439
 
440
  from app.services.file_upload_service import get_upload_service
441
- upload_service = get_upload_service()
442
-
443
- # Find the file
444
- file_path = None
445
- for ext in [".pdf", ".docx"]:
446
- p = upload_service.storage_path / f"{law.file_id}{ext}"
447
- if p.exists():
448
- file_path = p
449
- break
450
-
451
- if not file_path:
452
- p = upload_service.storage_path / law.file_id
453
- if p.exists():
454
- file_path = p
455
- else:
456
- raise HTTPException(status_code=404, detail="File not found on server")
457
 
458
  # Convert page to image using Poppler
459
  try:
 
14
 
15
  import logging
16
  import time
17
+ from pathlib import Path
18
  from typing import List, Optional, cast
19
 
20
  from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, status
 
34
  LawUpdate,
35
  )
36
  from app.services.file_upload_service import get_upload_service
37
+ from app.utils.file_utils import resolve_upload_path
38
  from app.services.search_service import invalidate_search_cache
39
  from app.tasks.process_law import delete_from_search_index
40
 
 
191
  )
192
 
193
 
194
+ def _law_file_path(law: Law) -> Path:
195
+ """
196
+ Chemin du fichier d'origine d'une loi, resolu UNE seule fois.
197
+
198
+ Les cinq endpoints qui servent un PDF repetaient la meme construction a la
199
+ main, avec un repli qui joignait `law.file_id` au repertoire d'upload sans
200
+ aucune verification : ni motif, ni resolve(), ni confinement. Ce n'etait pas
201
+ exploitable — la valeur vient de la base et non de la requete — mais c'etait
202
+ cinq copies de la faiblesse que resolve_upload_path a ete ecrite pour
203
+ fermer, et elle n'etait utilisee que par les routes OCR.
204
+
205
+ Raises:
206
+ HTTPException: 404 si la loi n'a pas de fichier, si l'identifiant ne
207
+ respecte pas le motif, ou si le fichier est absent du disque.
208
+ """
209
+ if not law.file_id:
210
+ raise HTTPException(status_code=404, detail="No source file found for this law")
211
+
212
+ try:
213
+ return resolve_upload_path(law.file_id)
214
+ except ValueError as exc:
215
+ # Identifiant hors motif ou chemin sortant du repertoire d'upload.
216
+ logger.warning(f"⚠️ file_id invalide pour la loi {law.id}: {exc}")
217
+ raise HTTPException(status_code=404, detail="File not found on server") from exc
218
+ except FileNotFoundError as exc:
219
+ raise HTTPException(status_code=404, detail="File not found on server") from exc
220
+
221
+
222
  @router.get("/{law_id}/download")
223
  async def download_law_file(
224
  law_id: int,
 
235
  if not law.file_id:
236
  raise HTTPException(status_code=404, detail="No source file found for this law")
237
 
238
+ file_path = _law_file_path(law)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
  return FileResponse(
241
  path=str(file_path),
242
  filename=str(cast(str, law.original_filename) or file_path.name),
243
  media_type="application/pdf" if file_path.suffix == ".pdf" else "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
244
+ # attachment et non inline : un bouton nomme "Telecharger" doit
245
+ # enregistrer le fichier, pas l'afficher dans l'onglet.
246
+ content_disposition_type="attachment"
247
  )
248
 
249
 
 
269
  raise HTTPException(status_code=404, detail="No source file found for this law")
270
 
271
  from app.services.file_upload_service import get_upload_service
272
+ file_path = _law_file_path(law)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
274
  # Read file and encode to Base64
275
  with open(str(file_path), "rb") as f:
 
311
  raise HTTPException(status_code=404, detail="No source file found for this law")
312
 
313
  from app.services.file_upload_service import get_upload_service
314
+ file_path = _law_file_path(law)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
 
316
  # Read file content
317
  with open(str(file_path), "rb") as f:
 
353
  raise HTTPException(status_code=404, detail="No source file found for this law")
354
 
355
  from app.services.file_upload_service import get_upload_service
356
+ file_path = _law_file_path(law)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
 
358
  # Get page count
359
  try:
 
404
  raise HTTPException(status_code=404, detail="No source file found for this law")
405
 
406
  from app.services.file_upload_service import get_upload_service
407
+ file_path = _law_file_path(law)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408
 
409
  # Convert page to image using Poppler
410
  try:
tests/test_api/test_law_files.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests des endpoints qui servent le fichier d'origine d'une loi.
3
+
4
+ Le bouton "Telecharger" du front appelait window.print(), qui imprime la page
5
+ affichee — donc l'unique article lu, jamais le document. L'endpoint qui sert le
6
+ vrai fichier existait mais n'etait appele par personne. Ces tests fixent son
7
+ contrat : le fichier rendu est l'ORIGINAL, octet pour octet, et il est propose
8
+ en telechargement et non affiche dans l'onglet.
9
+
10
+ Ils couvrent aussi la resolution du chemin, qui etait recopiee a la main dans
11
+ cinq endpoints avec un repli joignant la valeur de base au repertoire d'upload
12
+ sans aucune verification.
13
+ """
14
+
15
+ import hashlib
16
+
17
+ import pytest
18
+
19
+ from app.models.law import Law
20
+ from app.services.file_upload_service import get_upload_service
21
+
22
+
23
+ def _valid_pdf_bytes() -> bytes:
24
+ """
25
+ PDF d'une page, REELLEMENT valide.
26
+
27
+ Ecrit par pypdf plutot qu'a la main : /pdf-info ouvre le fichier avec
28
+ PdfReader, et un squelette PDF sans table xref le fait echouer — le test
29
+ mesurerait alors la qualite de sa propre doublure.
30
+ """
31
+ import io
32
+
33
+ from pypdf import PdfWriter
34
+
35
+ writer = PdfWriter()
36
+ writer.add_blank_page(width=612, height=792)
37
+ buffer = io.BytesIO()
38
+ writer.write(buffer)
39
+ return buffer.getvalue()
40
+
41
+
42
+ MINIMAL_PDF = _valid_pdf_bytes()
43
+
44
+
45
+ @pytest.fixture
46
+ async def law_with_file(db_session):
47
+ """Une loi dont le PDF est reellement pose dans le repertoire d'upload."""
48
+ file_id = "testfileid0001abcd"
49
+ storage = get_upload_service().storage_path
50
+ storage.mkdir(parents=True, exist_ok=True)
51
+ path = storage / f"{file_id}.pdf"
52
+ path.write_bytes(MINIMAL_PDF)
53
+
54
+ law = Law(
55
+ reference="PRC-TEST-FILE",
56
+ title="Décret de test avec fichier",
57
+ content="Article 1. Contenu de test.",
58
+ type="décret",
59
+ language="fr",
60
+ status="published",
61
+ file_id=file_id,
62
+ original_filename="decret-original.pdf",
63
+ )
64
+ db_session.add(law)
65
+ await db_session.commit()
66
+ await db_session.refresh(law)
67
+
68
+ yield law
69
+
70
+ path.unlink(missing_ok=True)
71
+
72
+
73
+ class TestDownload:
74
+
75
+ @pytest.mark.asyncio
76
+ async def test_serves_the_original_bytes(self, client, law_with_file):
77
+ response = await client.get(f"/api/v1/laws/{law_with_file.id}/download")
78
+
79
+ assert response.status_code == 200
80
+ assert response.content == MINIMAL_PDF
81
+ assert hashlib.sha256(response.content).hexdigest() == (
82
+ hashlib.sha256(MINIMAL_PDF).hexdigest()
83
+ )
84
+
85
+ @pytest.mark.asyncio
86
+ async def test_is_offered_as_a_download_not_displayed(self, client, law_with_file):
87
+ """
88
+ attachment et non inline : un bouton nomme "Telecharger" doit
89
+ enregistrer le fichier, pas l'ouvrir dans l'onglet.
90
+ """
91
+ response = await client.get(f"/api/v1/laws/{law_with_file.id}/download")
92
+
93
+ disposition = response.headers["content-disposition"]
94
+ assert disposition.startswith("attachment")
95
+ assert "decret-original.pdf" in disposition
96
+ assert response.headers["content-type"] == "application/pdf"
97
+
98
+ @pytest.mark.asyncio
99
+ async def test_law_without_file_gives_404(self, client, db_session):
100
+ law = Law(
101
+ reference="PRC-TEST-NOFILE",
102
+ title="Loi créée sans téléversement",
103
+ content="Article 1. Contenu.",
104
+ type="loi",
105
+ language="fr",
106
+ status="published",
107
+ )
108
+ db_session.add(law)
109
+ await db_session.commit()
110
+ await db_session.refresh(law)
111
+
112
+ response = await client.get(f"/api/v1/laws/{law.id}/download")
113
+
114
+ assert response.status_code == 404
115
+
116
+ @pytest.mark.asyncio
117
+ async def test_unknown_law_gives_404(self, client):
118
+ assert (await client.get("/api/v1/laws/999999/download")).status_code == 404
119
+
120
+
121
+ class TestPathResolution:
122
+ """
123
+ Le chemin passe par resolve_upload_path, qui refuse tout identifiant hors
124
+ motif. Le repli precedent joignait la valeur brute au repertoire d'upload,
125
+ sans motif ni confinement — cinq fois, une par endpoint.
126
+ """
127
+
128
+ @pytest.mark.parametrize("bad_file_id", [
129
+ "../../../etc/passwd",
130
+ "sous/dossier/fichier",
131
+ "court",
132
+ "",
133
+ ])
134
+ @pytest.mark.asyncio
135
+ async def test_malformed_file_id_gives_404_not_500(
136
+ self, client, db_session, bad_file_id
137
+ ):
138
+ law = Law(
139
+ reference=f"PRC-BAD-{abs(hash(bad_file_id)) % 10000}",
140
+ title="Loi au file_id douteux",
141
+ content="Article 1. Contenu.",
142
+ type="loi",
143
+ language="fr",
144
+ status="published",
145
+ file_id=bad_file_id or None,
146
+ )
147
+ db_session.add(law)
148
+ await db_session.commit()
149
+ await db_session.refresh(law)
150
+
151
+ for endpoint in ("download", "pdf-data", "pdf-info"):
152
+ response = await client.get(f"/api/v1/laws/{law.id}/{endpoint}")
153
+ assert response.status_code == 404, (
154
+ f"{endpoint} devrait repondre 404 pour file_id={bad_file_id!r}, "
155
+ f"pas {response.status_code}"
156
+ )
157
+
158
+ @pytest.mark.asyncio
159
+ async def test_all_file_endpoints_agree_on_the_same_file(self, client, law_with_file):
160
+ """Les cinq endpoints resolvent le meme chemin, donc le meme fichier."""
161
+ download = await client.get(f"/api/v1/laws/{law_with_file.id}/download")
162
+ info = await client.get(f"/api/v1/laws/{law_with_file.id}/pdf-info")
163
+
164
+ assert download.status_code == 200
165
+ assert info.status_code == 200
166
+ assert info.json()["filename"] == "decret-original.pdf"