From 1637187c7638e5a782f3799c9ea2e4ec2793a7de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 19 Apr 2018 13:10:41 +0200 Subject: [PATCH] Extend URL test to also allow whitelist/blacklist check for the returned content type --- docs/api/util.rst | 6 +++ src/octoprint/server/api/__init__.py | 65 +++++++++++++++++++--------- src/octoprint/util/__init__.py | 32 ++++++++++++++ 3 files changed, 83 insertions(+), 20 deletions(-) diff --git a/docs/api/util.rst b/docs/api/util.rst index ca1e46333..dde6d5100 100644 --- a/docs/api/util.rst +++ b/docs/api/util.rst @@ -65,6 +65,12 @@ Test paths or URLs from the URL check will be returned as part of the check result as well. ``json`` will attempt to parse the response as json and return the parsed result. ``true`` or ``bytes`` will base64 encode the body and return that. + * ``content_type_whitelist``: Optional array of supported content types. If set and the URL returns a content + type not included in this list, the test will fail. E.g. ``["image/*", "text/plain"]``. + * ``content_type_blacklist``: Optional array of unsupported content types. If set and the URL returns a content + type included in this list, the test wil fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist`` + to further limit broader content type definition, e.g. by putting ``image/*`` into the whitelist, but disallowing + PNG by including ``image/png`` on the blacklist. The ``url`` command returns :http:statuscode:`200` with a :ref:`URL test result ` when the test could be performed. The status code of the response does NOT reflect the diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 37de67a79..f577a624c 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -339,6 +339,8 @@ def utilTestPath(): timeout = 3.0 valid_ssl = True check_status = [status_ranges["normal"]] + content_type_whitelist = None + content_type_blacklist = None if "timeout" in data: try: @@ -366,34 +368,57 @@ def utilTestPath(): if code is not None: check_status.append([code]) + if "content_type_whitelist" in data: + if not isinstance(data["content_type_whitelist"], (list, tuple)): + return make_response("content_type_whitelist must be a list of mime types") + content_type_whitelist = map(util.parse_mime_type, data["content_type_whitelist"]) + if "content_type_blacklist" in data: + if not isinstance(data["content_type_whitelist"], (list, tuple)): + return make_response("content_type_blacklist must be a list of mime types") + content_type_blacklist = map(util.parse_mime_type, data["content_type_blacklist"]) + + response_result = None + outcome = True + status = 0 try: - response = requests.request(method=method, url=url, timeout=timeout, verify=valid_ssl) - status = response.status_code + with requests.request(method=method, url=url, timeout=timeout, verify=valid_ssl, stream=True) as response: + status = response.status_code + outcome = outcome and any(map(lambda x: status in x, check_status)) + content_type = response.headers.get("content-type") + + response_result = dict(headers=dict(response.headers), + content_type=content_type) + + parsed_content_type = util.parse_mime_type(content_type) + in_whitelist = content_type_whitelist is None or any(map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_whitelist)) + in_blacklist = content_type_blacklist is not None and any(map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_blacklist)) + + if not in_whitelist or in_blacklist: + # we don't support this content type + response.close() + outcome = False + + elif "response" in data and (data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes")): + if data["response"] == "json": + content = response.json() + + else: + import base64 + content = base64.standard_b64encode(response.content) + + response_result["content"] = content except: - status = 0 + logging.getLogger(__name__).exception("Error while running a test {} request on {}".format(method, url)) + outcome = False result = dict( url=url, status=status, - result=any(map(lambda x: status in x, check_status)) + result=outcome ) + if response_result: + result["response"] = response_result - if "response" in data and (data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes")): - - import base64 - content = base64.standard_b64encode(response.content) - - if data["response"] == "json": - try: - content = response.json() - except: - logging.getLogger(__name__).exception("Couldn't convert response to json") - result["result"] = False - - result["response"] = dict( - headers=dict(response.headers), - content=content - ) return jsonify(**result) elif command == "server": diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 7a2467044..4fe60fa21 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -849,6 +849,38 @@ def server_reachable(host, port, timeout=3.05, proto="tcp", source=None): except: return False +def parse_mime_type(mime): + import cgi + + if not mime or not isinstance(mime, basestring): + raise ValueError("mime must be a non empty str or unicode") + + mime, params = cgi.parse_header(mime) + + if mime == "*": + mime = "*/*" + + parts = mime.split("/") if "/" in mime else None + if not parts or len(parts) != 2: + raise ValueError("mime must be a mime type of format type/subtype") + + mime_type, mime_subtype = parts + return mime_type.strip(), mime_subtype.strip(), params + +def mime_type_matches(mime, other): + if not isinstance(mime, tuple): + mime = parse_mime_type(mime) + if not isinstance(other, tuple): + other = parse_mime_type(other) + + mime_type, mime_subtype, _ = mime + other_type, other_subtype, _ = other + + type_matches = (mime_type == other_type or mime_type == "*" or other_type == "*") + subtype_matches = (mime_subtype == other_subtype or mime_subtype == "*" or other_subtype == "*") + + return type_matches and subtype_matches + @contextlib.contextmanager def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777): if os.path.exists(filename):