Skip to content

Commit 03ef74b

Browse files
fix: sanitize mime_type and filename to prevent HTTP header injection in resumable upload
Sanitize user-supplied mime_type and filename values before they are interpolated into HTTP request headers in prepare_resumable_upload(). CR and LF characters in these values are stripped to prevent potential HTTP header injection. Added a _sanitize_header_value() helper that is applied to both the X-Goog-Upload-Header-Content-Type and X-Goog-Upload-File-Name headers.
1 parent cce5398 commit 03ef74b

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

google/genai/_extra_utils.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@
5252
McpClientSession = None
5353
McpTool = None
5454

55+
def _sanitize_header_value(value: str) -> str:
56+
"""Strips CR and LF characters to prevent HTTP header injection."""
57+
return value.replace('\r', '').replace('\n', '')
58+
59+
5560
_DEFAULT_MAX_REMOTE_CALLS_AFC = 10
5661

5762
logger = logging.getLogger('google_genai.models')
@@ -659,7 +664,7 @@ def prepare_resumable_upload(
659664
'X-Goog-Upload-Protocol': 'resumable',
660665
'X-Goog-Upload-Command': 'start',
661666
'X-Goog-Upload-Header-Content-Length': f'{size_bytes}',
662-
'X-Goog-Upload-Header-Content-Type': f'{mime_type}',
667+
'X-Goog-Upload-Header-Content-Type': _sanitize_header_value(mime_type),
663668
}
664669
else:
665670
http_options = types.HttpOptions(
@@ -669,11 +674,11 @@ def prepare_resumable_upload(
669674
'X-Goog-Upload-Protocol': 'resumable',
670675
'X-Goog-Upload-Command': 'start',
671676
'X-Goog-Upload-Header-Content-Length': f'{size_bytes}',
672-
'X-Goog-Upload-Header-Content-Type': f'{mime_type}',
677+
'X-Goog-Upload-Header-Content-Type': _sanitize_header_value(mime_type),
673678
},
674679
)
675680
if isinstance(file, (str, os.PathLike)):
676681
if http_options.headers is None:
677682
http_options.headers = {}
678-
http_options.headers['X-Goog-Upload-File-Name'] = os.path.basename(file)
683+
http_options.headers['X-Goog-Upload-File-Name'] = _sanitize_header_value(os.path.basename(str(file)))
679684
return http_options, size_bytes, mime_type

0 commit comments

Comments
 (0)