Skip to content

Commit 2d36826

Browse files
committed
fix(traces): quote a record's download name and keep its characters
A record's download wrote its file name between quotes as it was. A name with a quote, a backslash or a control character broke the header, and a name outside ASCII had no portable form. The name now has its control characters removed and is quoted, with an ASCII fallback, and a name outside ASCII is also sent as UTF-8 (filename*).
1 parent 7bd87f1 commit 2d36826

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

‎app/ui_tests/test_trial_records.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import tempfile
99
import unittest
1010
from urllib.parse import quote
11+
from werkzeug.http import parse_options_header
1112
from contextlib import ExitStack
1213
from unittest.mock import patch
1314

@@ -83,6 +84,23 @@ def test_a_declared_record_is_read_and_downloaded_by_its_key(self):
8384
self.assertEqual((got.status_code, got.headers["Content-Disposition"]), (200, 'attachment; filename="brief.md"'))
8485
self.assertEqual(got.get_data(as_text=True), "Set the field, then press Apply.\n")
8586

87+
def test_download_names_are_quoted_without_controls_and_keep_unicode(self):
88+
for name, clean in [('a"quoted\\name.txt', 'a"quoted\\name.txt'),
89+
('résumé-文件.txt', 'résumé-文件.txt')]:
90+
with self.subTest(name=name):
91+
with open(os.path.join(self.root, "t1", "verifier", "own", name), "w") as handle:
92+
handle.write("record")
93+
response = self.get(f"/trial/{self.job.job_id}/t1/artifact/{quote('r1-' + name, safe='')}/download")
94+
self.assertEqual(response.status_code, 200)
95+
header = response.headers["Content-Disposition"]
96+
self.assertTrue(header.startswith('attachment; filename="'))
97+
self.assertFalse(any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in header))
98+
self.assertEqual(parse_options_header(header), ("attachment", {"filename": clean}))
99+
if not clean.isascii():
100+
self.assertIn("filename*=UTF-8''", header)
101+
self.assertTrue(header.isascii())
102+
self.assertEqual(response.get_data(as_text=True), "record")
103+
86104
def test_a_key_outside_the_declaration_or_of_a_name_not_printable_is_not_found(self):
87105
own = os.fsencode(os.path.join(self.root, "t1", "verifier", "own"))
88106
for name in (b"bad-\xff.txt", b"line\nbreak\r\t\x01\x7f\x85.txt"):

‎app/web/traces.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@
66
import os
77
import re
88
import threading
9+
import unicodedata
910
from collections import OrderedDict
11+
from urllib.parse import quote
1012
from flask import abort, flash, g, jsonify, redirect, render_template, request, url_for
1113
from markupsafe import Markup, escape
14+
from werkzeug.http import quote_header_value
1215
from nullius.traces import behavior, charts, conversation, trace, trajectory
1316
from nullius.runs import artifacts, attempts as task_attempts, parse
1417
from nullius import importers as harnesses
@@ -192,13 +195,17 @@ def artifact_download(job_id, trial_name, key):
192195
text, truncated = artifacts.whole(trial.dir, key, declared)
193196
except (LookupError, OSError):
194197
abort(404)
195-
name = os.path.basename(artifacts.describe(key, declared)[1])
198+
name = re.sub(r"[\x00-\x1f\x7f-\x9f]", "", os.path.basename(artifacts.describe(key, declared)[1]))
196199
if truncated:
197200
stem, ext = os.path.splitext(name)
198201
name = f"{stem}.partial{ext}"
199202
response = app.response_class(text, mimetype="application/json" if name.endswith(".json") else "text/plain")
200203
if not request.args.get("inline"):
201-
response.headers["Content-Disposition"] = f'attachment; filename="{name}"'
204+
fallback = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode("ascii")
205+
disposition = f'attachment; filename={quote_header_value(fallback, allow_token=False)}'
206+
if not name.isascii():
207+
disposition += "; filename*=UTF-8''" + quote(name, safe="")
208+
response.headers["Content-Disposition"] = disposition
202209
response.headers["Cache-Control"] = "no-store"
203210
response.headers["X-Content-Type-Options"] = "nosniff" # a run's own text, shown as text whatever it holds
204211
return response

0 commit comments

Comments
 (0)