Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 40 additions & 8 deletions src/google/appengine/ext/blobstore/blobstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,45 @@
'^%s(?:,%s)+$' % (_RANGE_FORMAT, _RANGE_NUMERIC_FORMAT))
_BYTES_UNIT = 'bytes'

_FILENAME_CONTROL_CHARS_REGEX = re.compile(rb'[\x00-\x1f\x7f]')
_FILENAME_TEXT_CONTROL_CHARS_REGEX = re.compile(r'[\x00-\x1f\x7f-\x9f]')
_FILENAME_QUOTED_UNSAFE_CHARS_REGEX = re.compile(rb'["\\]')


def _format_content_disposition(filename):
"""Builds a Content-Disposition header value for an attachment.

Control characters are removed from the filename. For a `bytes` filename
only ASCII control characters are removed, because its encoding is not
known. In the quoted `filename` parameter, double quotes and backslashes are
replaced with underscores, because not all clients unescape them. A text
filename is also sent percent-encoded in the `filename*` parameter.

Args:
filename: The filename to send, as `bytes` or `str`, or None if there is
no filename.

Returns:
The header value as `bytes`. It has no filename parameter if the filename
is None, or is empty once control characters are removed.
"""
if filename is None:
return b'attachment'
is_text = isinstance(filename, six.text_type)
if is_text:
filename = _FILENAME_TEXT_CONTROL_CHARS_REGEX.sub('', filename)
filename = filename.encode('utf-8')
else:
filename = _FILENAME_CONTROL_CHARS_REGEX.sub(b'', filename)
if not filename:
return b'attachment'
quoted_filename = _FILENAME_QUOTED_UNSAFE_CHARS_REGEX.sub(b'_', filename)
if is_text:
return _CONTENT_DISPOSITION_FORMAT_UTF8 % (
quoted_filename,
urllib.parse.quote(filename, safe='').encode('utf-8'))
return _CONTENT_DISPOSITION_FORMAT % quoted_filename


class BlobInfoParseError(Error):
"""The CGI parameter does not contain a valid `BlobInfo` record."""
Expand Down Expand Up @@ -1446,14 +1485,7 @@ def send_blob(self,
headers['Content-Type'] = content_type

def send_attachment(filename):
if isinstance(filename, six.text_type):
filename_utf8 = filename.encode('utf-8')
headers['Content-Disposition'] = (
_CONTENT_DISPOSITION_FORMAT_UTF8 %
(filename_utf8, urllib.parse.quote(filename_utf8).encode('utf-8')))
else:
headers['Content-Disposition'] = (
_CONTENT_DISPOSITION_FORMAT % filename)
headers['Content-Disposition'] = _format_content_disposition(filename)

if save_as:
if isinstance(save_as, (bytes, six.text_type)):
Expand Down
143 changes: 143 additions & 0 deletions tests/google/appengine/ext/blobstore/blobstore_handlers_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
#!/usr/bin/env python
#
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


"""Tests for the download handler in google.appengine.ext.blobstore."""

import datetime

from google.appengine.ext.blobstore import blobstore
from absl.testing import absltest


class SendBlobContentDispositionTest(absltest.TestCase):
"""Tests the Content-Disposition header set by send_blob."""

def setUp(self):
super().setUp()
self.handler = blobstore.BlobstoreDownloadHandler()

def _create_blob_info(self, filename):
return blobstore.BlobInfo(
blobstore.BlobKey('my blob'),
{
'filename': filename,
'content_type': b'application/pdf',
'size': 1024,
'creation': datetime.datetime(2009, 1, 2, 3, 4, 5),
},
)

def _send_blob(self, blob_key_or_info, save_as):
headers = self.handler.send_blob({}, blob_key_or_info, save_as=save_as)
return headers['Content-Disposition']

def test_bytes_filename(self):
self.assertEqual(
b'attachment; filename="alternate.txt"',
self._send_blob('my blob', b'alternate.txt'),
)

def test_text_filename(self):
self.assertEqual(
b'attachment; filename="alternate.txt"; '
b"filename*=utf-8''alternate.txt",
self._send_blob('my blob', 'alternate.txt'),
)

def test_non_ascii_uploaded_filename(self):
self.assertEqual(
b'attachment; filename="\xe2\x82\xac rates";'
b" filename*=utf-8''%E2%82%AC%20rates",
self._send_blob(self._create_blob_info('\u20ac rates'), True),
)

def test_double_quote_is_replaced(self):
Comment thread
riddhi-shivhare marked this conversation as resolved.
Resolved
self.assertEqual(
b'attachment; filename="a_; filename=_evil.exe"',
self._send_blob('my blob', b'a"; filename="evil.exe'),
)

def test_double_quote_is_replaced_in_text_filename(self):
self.assertEqual(
b'attachment; filename="benign.txt_; filename=_setup.exe"; '
b"filename*=utf-8''benign.txt%22%3B%20filename%3D%22setup.exe",
self._send_blob('my blob', 'benign.txt"; filename="setup.exe'),
)

def test_trailing_backslash_is_replaced(self):
self.assertEqual(
b'attachment; filename="evil_"',
self._send_blob('my blob', b'evil\\'),
)

def test_backslash_is_replaced(self):
self.assertEqual(
b'attachment; filename="a_b.txt"',
self._send_blob('my blob', b'a\\b.txt'),
)

def test_backslash_and_double_quote_are_replaced(self):
self.assertEqual(
b'attachment; filename="a__b"',
self._send_blob('my blob', b'a\\"b'),
)

def test_text_filename_keeps_backslash_in_extended_parameter(self):
self.assertEqual(
b"attachment; filename=\"a_b\"; filename*=utf-8''a%5Cb",
self._send_blob('my blob', 'a\\b'),
)

def test_slash_is_encoded_in_extended_parameter(self):
self.assertEqual(
b'attachment; filename="dir/file.txt"; '
b"filename*=utf-8''dir%2Ffile.txt",
self._send_blob('my blob', 'dir/file.txt'),
)

def test_control_characters_removed_from_text_filename(self):
self.assertEqual(
b'attachment; filename="a_Set-Cookie: x=1"; '
b"filename*=utf-8''a%22Set-Cookie%3A%20x%3D1",
self._send_blob('my blob', 'a"\r\n\x00\t\x7f\x85Set-Cookie: x=1'),
)

def test_control_characters_removed_from_uploaded_filename(self):
self.assertEqual(
b'attachment; filename="x_Location: evil"',
self._send_blob(
self._create_blob_info(b'x"\r\nLocation: evil'), True
),
)

def test_no_filename_when_only_control_characters(self):
self.assertEqual(b'attachment', self._send_blob('my blob', '\r\n'))

def test_no_filename_when_bytes_are_only_control_characters(self):
self.assertEqual(
b'attachment', self._send_blob('my blob', b'\r\n\x00\x7f')
)

def test_no_filename_when_blob_info_has_none(self):
self.assertEqual(
b'attachment', self._send_blob(self._create_blob_info(None), True)
)


if __name__ == '__main__':
absltest.main()
Loading