Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(content-type): add warning if a pac file is found but the content-type is invalid #79

Merged
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
5 changes: 5 additions & 0 deletions pypac/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
These are the most commonly used components of PyPAC.
"""
import os
import logging
from contextlib import contextmanager

import requests
Expand All @@ -18,6 +19,7 @@
)
from pypac.wpad import proxy_urls_from_dns

logger = logging.getLogger(__name__)

def get_pac(
url=None,
Expand Down Expand Up @@ -157,6 +159,9 @@ def download_pac(candidate_urls, timeout=1, allowed_content_types=None, session=
resp = sess.get(pac_url, timeout=timeout)
content_type = resp.headers.get("content-type", "").lower()
if content_type and True not in [allowed_type in content_type for allowed_type in allowed_content_types]:
logger.warning(
f"{pac_url} available but content-type {content_type} is not allowed. Only {','.join(allowed_content_types)} are allowed."
)
continue
if resp.ok:
return resp.text
Expand Down
8 changes: 7 additions & 1 deletion tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import os
import sys

Expand Down Expand Up @@ -78,12 +79,17 @@ def test_download_pac_not_ok(self):
({"content-type": "text/plain"}, ["text/plain"], direct_pac_js),
],
)
def test_download_pac_content_type(self, headers, allowed_content_types, expected_value):
def test_download_pac_content_type(self, headers, allowed_content_types, expected_value, caplog):
"""Test acceptance/rejection of obtained PAC based on Content-Type header."""
mock_pac_response = Mock(spec=requests.Response, ok=True, headers=headers, text=direct_pac_js)
with _patch_request_base(mock_pac_response):
result = download_pac([arbitrary_pac_url], allowed_content_types=allowed_content_types)
assert result == expected_value
if expected_value is None:
ex_warn = "available but content-type {} is not allowed".format(headers["content-type"])
log = caplog.records[0]
assert log.levelno == logging.WARNING
assert ex_warn in log.msg

def test_registry_filesystem_path(self):
"""
Expand Down
Loading