Skip to content
Open
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
20 changes: 9 additions & 11 deletions gcs/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,15 @@ def rest_media(self, request, delay=time.sleep):
if range_header is not None and begin >= length:
testbench.error.range_not_satisfiable()

headers = {}
headers = {
"Content-Security-Policy": "default-src 'none'; sandbox",
"X-Content-Type-Options": "nosniff",
# GCS json defaults to application/octet-stream if the object
# doesn't specify its content-type
"Content-Type": self.metadata.content_type or "application/octet-stream",
}
if self.metadata.content_disposition:
headers["Content-Disposition"] = self.metadata.content_disposition
content_range = "bytes %d-%d/%d" % (begin, end - 1, length)

instructions = testbench.common.extract_instruction(request, None)
Expand Down Expand Up @@ -630,13 +638,6 @@ def streamer():
headers["x-goog-metageneration"] = self.metadata.metageneration
headers["x-goog-storage-class"] = self.metadata.storage_class

if self.metadata.content_type:
headers["Content-Type"] = self.metadata.content_type
else:
# GCS json defaults to application/octet-stream if the object
# doesn't specify its content-type
headers["Content-Type"] = "application/octet-stream"

headers["x-goog-stored-content-length"] = self.metadata.size
headers["Content-Length"] = len(response_payload)

Expand All @@ -647,9 +648,6 @@ def streamer():
if not is_decompressive_transcode:
headers["Content-Encoding"] = self.metadata.content_encoding

if self.metadata.content_disposition:
headers["Content-Disposition"] = self.metadata.content_disposition

# Return status code 206 if a valid range request header is included.
if range_header and not is_decompressive_transcode:
return flask.Response(streamer(), status=206, headers=headers)
Expand Down
67 changes: 67 additions & 0 deletions testbench/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from grpc import StatusCode
from requests_toolbelt import MultipartDecoder
from requests_toolbelt.multipart.decoder import ImproperBodyPartContentException
from werkzeug.wsgi import get_host

import testbench
from google.storage.v2 import storage_pb2
Expand Down Expand Up @@ -1214,6 +1215,72 @@ def consume_expect_redirect_token(db, context, method, routing_token):
db.dequeue_next_instruction(test_id, method)


_ALLOWED_SEC_FETCH_SITES = frozenset({"same-origin", "none"})
_DISALLOWED_JSON_CONTENT_TYPES = frozenset(
{
"text/plain",
"application/x-www-form-urlencoded",
"multipart/form-data",
}
)


def _is_allowed_request_origin(environ):
"""Return whether Origin and Sec-Fetch-Site headers match the server origin."""
sec_fetch_site = environ.get("HTTP_SEC_FETCH_SITE", "").strip().lower()
if sec_fetch_site and sec_fetch_site not in _ALLOWED_SEC_FETCH_SITES:
return False

origin = environ.get("HTTP_ORIGIN", "").strip()
if not origin:
return True

host = get_host(environ)
if not host:
return False
request_origin = f"{environ['wsgi.url_scheme']}://{host}"
return origin.lower() == request_origin.lower()


class RequestOriginMiddleware:
"""WSGI middleware enforcing same-origin request headers."""

def __init__(self, app):
"""Initialize the middleware wrapping the target WSGI app."""
self._app = app

def __call__(self, environ, start_response):
if not _is_allowed_request_origin(environ):
body = json.dumps(
{"error": {"code": 403, "message": "Forbidden request origin"}}
).encode("utf-8")
start_response(
"403 Forbidden",
[
("Content-Type", "application/json"),
("Content-Length", str(len(body))),
],
)
if environ.get("REQUEST_METHOD") == "HEAD":
return [b""]
return [body]
return self._app(environ, start_response)


def validate_json_content_type(request):
"""Reject form and plain-text Content-Types on non-empty JSON POST endpoints."""
if request.method == "POST" and request.mimetype in _DISALLOWED_JSON_CONTENT_TYPES:
has_body = (
request.content_length > 0
if request.content_length is not None
else bool(request.get_data())
)
if has_body:
raise testbench.error.RestException(
"Unsupported Content-Type for JSON endpoint", 415
)


def handle_gzip_request(request):
"""
Handle gzip compressed JSON payloads when Content-Encoding: gzip is present on metadata requests.
Expand Down
28 changes: 18 additions & 10 deletions testbench/rest_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ def list_retry_tests():

@root.route("/retry_test", methods=["POST"])
def create_retry_test():
testbench.common.validate_json_content_type(flask.request)
payload = json.loads(flask.request.data)
test_instruction_set = payload.get("instructions", None)
if not test_instruction_set:
Expand Down Expand Up @@ -224,6 +225,11 @@ def start_grpc():
gcs.register_error_handler(Exception, testbench.error.RestException.handler)


@gcs.before_request
def validate_content_type():
testbench.common.validate_json_content_type(flask.request)


@gcs.before_request
def handle_gzip_compressed_request():
return testbench.common.handle_gzip_request(flask.request)
Expand Down Expand Up @@ -1292,16 +1298,18 @@ def delete_resumable_upload(bucket_name):
server = flask.Flask(__name__)
server.debug = False
server.register_error_handler(Exception, testbench.error.RestException.handler)
server.wsgi_app = DispatcherMiddleware(
root,
{
"/httpbin": echo.app(),
GCS_HANDLER_PATH: gcs,
DOWNLOAD_HANDLER_PATH: download,
UPLOAD_HANDLER_PATH: upload,
PROJECTS_HANDLER_PATH: projects_app,
IAM_HANDLER_PATH: iam_app,
},
server.wsgi_app = testbench.common.RequestOriginMiddleware(
DispatcherMiddleware(
root,
{
"/httpbin": echo.app(),
GCS_HANDLER_PATH: gcs,
DOWNLOAD_HANDLER_PATH: download,
UPLOAD_HANDLER_PATH: upload,
PROJECTS_HANDLER_PATH: projects_app,
IAM_HANDLER_PATH: iam_app,
},
)
)


Expand Down
6 changes: 6 additions & 0 deletions testbench/servers/iam_rest_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import flask

import testbench.common
import testbench.error

_IAM_HANDLER_PATH = "/iamapi"
Expand All @@ -28,6 +29,11 @@
_iam.register_error_handler(Exception, testbench.error.RestException.handler)


@_iam.before_request
def validate_content_type():
testbench.common.validate_json_content_type(flask.request)


@_iam.before_request
def handle_gzip_compressed_request():
return testbench.common.handle_gzip_request(flask.request)
Expand Down
4 changes: 4 additions & 0 deletions testbench/servers/projects_rest_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ def get_projects_app(db):
projects.debug = False
projects.register_error_handler(Exception, testbench.error.RestException.handler)

@projects.before_request
def validate_content_type():
testbench.common.validate_json_content_type(flask.request)

@projects.before_request
def handle_gzip_compressed_request():
return testbench.common.handle_gzip_request(flask.request)
Expand Down
74 changes: 74 additions & 0 deletions tests/test_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -1039,6 +1039,80 @@ def test_stall_always(self):
self.assertEqual(response.data, b"How vexingly quick daft zebras jump!")
mock_sleep.assert_called_once_with(10)

def test_rest_media_response_headers(self):
boundary, payload = format_multipart_upload(
{
"name": "page.html",
"contentType": "text/html",
"contentDisposition": 'inline; filename="page.html"',
},
media="<p>hello</p>",
content_type="text/html",
)
upload_request = testbench.common.FakeRequest(
args={},
headers={"content-type": "multipart/related; boundary=" + boundary},
data=payload.encode("utf-8"),
environ={},
)
blob, _ = gcs.object.Object.init_multipart(upload_request, self.bucket.metadata)

cases = [
("full", {}, "text/html", 200, "text/html"),
("range", {"range": "bytes=0-2"}, "text/html", 206, "text/html"),
(
"retry-instruction",
{
"x-goog-testbench-instructions": "return-503-after-256K/retry-3",
"range": "bytes=2-",
},
"text/html",
200,
"text/html",
),
(
"retry-instruction-empty-content-type",
{
"x-goog-testbench-instructions": "return-503-after-256K/retry-3",
"range": "bytes=2-",
},
"",
200,
"application/octet-stream",
),
]
for (
label,
req_headers,
metadata_content_type,
expected_status,
expected_content_type,
) in cases:
with self.subTest(case=label):
blob.metadata.content_type = metadata_content_type
request = Request(
create_environ(
base_url="http://localhost:8080",
headers=req_headers,
)
)
response = blob.rest_media(request)
self.assertEqual(response.status_code, expected_status)
self.assertEqual(
response.headers.get("Content-Security-Policy"),
"default-src 'none'; sandbox",
)
self.assertEqual(
response.headers.get("X-Content-Type-Options"), "nosniff"
)
self.assertEqual(
response.headers.get("Content-Type"), expected_content_type
)
self.assertEqual(
response.headers.get("Content-Disposition"),
'inline; filename="page.html"',
)

def _assert_valid_custom_context_value(self, blob, key, expected_value):
self.assertIn(key, blob.metadata.contexts.custom)
self.assertEqual(blob.metadata.contexts.custom[key].value, expected_value)
Expand Down
Loading
Loading