From 487432869f983b1aa0c5733b0d8e2d478d343e76 Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Sun, 2 Dec 2018 18:02:24 +0200 Subject: [PATCH 01/11] Added travis --- .tavis.yml | 9 +++++++++ tests/px_proxy_handler.py | 8 ++------ 2 files changed, 11 insertions(+), 6 deletions(-) create mode 100644 .tavis.yml diff --git a/.tavis.yml b/.tavis.yml new file mode 100644 index 0000000..1a5e1cd --- /dev/null +++ b/.tavis.yml @@ -0,0 +1,9 @@ +language: python +python: + - "2.7" +# command to install dependencies +install: + - pip install -r requirements.txt +# command to run tests +script: + - python -m unittest discover -s ./tests -p 'px*' \ No newline at end of file diff --git a/tests/px_proxy_handler.py b/tests/px_proxy_handler.py index c5e7bd9..92bce42 100644 --- a/tests/px_proxy_handler.py +++ b/tests/px_proxy_handler.py @@ -60,17 +60,13 @@ def test_send_reverse_captcha_request(self, mock): def test_send_reverse_xhr_request(self, mock): content = 'captcha content' config = PxConfig({'app_id': 'PXfake_app_id'}) - ctx = PxContext({'PATH_INFO': '/fake_app_id/init.js', + ctx = PxContext({'PATH_INFO': '/fake_app_id/xhr/api/v1/collector', 'HTTP_X_FORWARDED_FOR': '127.0.0.1', 'ip': '127.0.0.1'}, PxConfig({'app_id': 'fake_app_id'})) - ctx = {'uri': '/fake_app_id/xhr/api/v1/collector', - 'headers': {'X-FORWARDED-FOR': '127.0.0.1'}, - 'ip': '127.0.0.1', - 'REQUEST_METHOD': 'POST'} headers = {'host': config.collector_host, px_constants.FIRST_PARTY_HEADER: '1', - px_constants.ENFORCER_TRUE_IP_HEADER: ctx.get('ip'), + px_constants.ENFORCER_TRUE_IP_HEADER: ctx.ip, px_constants.FIRST_PARTY_FORWARDED_FOR: '127.0.0.1'} mock.post(url='https://collector-pxfake_app_id.perimeterx.net/api/v1/collector', text=content, request_headers=headers, status_code=200, reason='OK') From 54b925ee22076e26a39321ae135f4564543b5d65 Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Sun, 2 Dec 2018 18:06:36 +0200 Subject: [PATCH 02/11] Added travis --- .tavis.yml => .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename .tavis.yml => .travis.yml (73%) diff --git a/.tavis.yml b/.travis.yml similarity index 73% rename from .tavis.yml rename to .travis.yml index 1a5e1cd..7b5b817 100644 --- a/.tavis.yml +++ b/.travis.yml @@ -6,4 +6,4 @@ install: - pip install -r requirements.txt # command to run tests script: - - python -m unittest discover -s ./tests -p 'px*' \ No newline at end of file + - python -m unittest discover -s ./tests -p 'px*' From b65640c8872c49f2a1ee6c3dd0ac9d09dc3d32f3 Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Mon, 3 Dec 2018 10:04:25 +0200 Subject: [PATCH 03/11] tests --- .../px_blocking_messages/blocking.txt | 0 .../px_blocking_messages/ratelimit.txt | 0 .../test_px_activities_client.py | 0 tests/px_api.py => test/test_px_api.py | 24 ++++++++++++++++++- .../px_blocker.py => test/test_px_blocker.py | 0 test/test_px_config.py | 12 ++++++++++ tests/px_config.py => test/test_px_context.py | 0 tests/px_cookie.py => test/test_px_cookie.py | 0 .../test_px_cookie_validator.py | 0 tests/px_httpc.py => test/test_px_httpc.py | 0 .../test_px_proxy_handler.py | 0 tests/px_context.py | 0 12 files changed, 35 insertions(+), 1 deletion(-) rename {tests => test}/px_blocking_messages/blocking.txt (100%) rename {tests => test}/px_blocking_messages/ratelimit.txt (100%) rename tests/px_activities_client.py => test/test_px_activities_client.py (100%) rename tests/px_api.py => test/test_px_api.py (51%) rename tests/px_blocker.py => test/test_px_blocker.py (100%) create mode 100644 test/test_px_config.py rename tests/px_config.py => test/test_px_context.py (100%) rename tests/px_cookie.py => test/test_px_cookie.py (100%) rename tests/px_cookie_validator.py => test/test_px_cookie_validator.py (100%) rename tests/px_httpc.py => test/test_px_httpc.py (100%) rename tests/px_proxy_handler.py => test/test_px_proxy_handler.py (100%) delete mode 100644 tests/px_context.py diff --git a/tests/px_blocking_messages/blocking.txt b/test/px_blocking_messages/blocking.txt similarity index 100% rename from tests/px_blocking_messages/blocking.txt rename to test/px_blocking_messages/blocking.txt diff --git a/tests/px_blocking_messages/ratelimit.txt b/test/px_blocking_messages/ratelimit.txt similarity index 100% rename from tests/px_blocking_messages/ratelimit.txt rename to test/px_blocking_messages/ratelimit.txt diff --git a/tests/px_activities_client.py b/test/test_px_activities_client.py similarity index 100% rename from tests/px_activities_client.py rename to test/test_px_activities_client.py diff --git a/tests/px_api.py b/test/test_px_api.py similarity index 51% rename from tests/px_api.py rename to test/test_px_api.py index d7d53e7..fe56440 100644 --- a/tests/px_api.py +++ b/test/test_px_api.py @@ -2,9 +2,14 @@ from perimeterx import px_api from perimeterx.px_config import PxConfig from perimeterx.px_context import PxContext +import mock +import uuid +import json class Test_PXApi(unittest.TestCase): + + def enrich_custom_parameters(self, params): params['custom_param1'] = '1' params['custom_param2'] = '5' @@ -19,4 +24,21 @@ def test_prepare_risk_body(self): self.assertEqual(body['additional'].get('custom_param1'), '1') self.assertEqual(body['additional'].get('custom_param2'), '5') self.assertFalse(body['additional'].get('custom')) - print + + def test_send_risk_request(self): + config = PxConfig({'app_id': 'app_id', + 'enrich_custom_parameters': self.enrich_custom_parameters, + 'auth_token': 'auth'}) + ctx = PxContext({'PATH_INFO': '/test_path'}, config) + uuid_val = str(uuid.uuid4()) + response = ResponseMock({'score': 100, 'uuid': uuid_val, 'action': 'c'}) + with mock.patch('perimeterx.px_httpc.send', return_value=response): + response = px_api.send_risk_request(ctx, config) + self.assertEqual({'action': 'c', 'score': 100, 'uuid': uuid_val}, response) + + + +class ResponseMock(object): + def __init__(self, dict): + self.content = json.dumps(dict) + diff --git a/tests/px_blocker.py b/test/test_px_blocker.py similarity index 100% rename from tests/px_blocker.py rename to test/test_px_blocker.py diff --git a/test/test_px_config.py b/test/test_px_config.py new file mode 100644 index 0000000..6116cdc --- /dev/null +++ b/test/test_px_config.py @@ -0,0 +1,12 @@ +from perimeterx.px_config import PxConfig +import unittest +from perimeterx import px_constants +class TestPXConfig(unittest.TestCase): + + def test_constructor(self): + config_dict = {'app_id': 'PXfake_app_id', 'debug_mode': True, 'module_mode': px_constants.MODULE_MODE_BLOCKING} + config = PxConfig(config_dict) + self.assertEqual(config._monitor_mode, 1) + self.assertEqual(config.debug_mode, True) + self.assertEqual(config.server_host, 'sapi-pxfake_app_id.perimeterx.net') + self.assertEqual(config.collector_host, 'collector-pxfake_app_id.perimeterx.net') \ No newline at end of file diff --git a/tests/px_config.py b/test/test_px_context.py similarity index 100% rename from tests/px_config.py rename to test/test_px_context.py diff --git a/tests/px_cookie.py b/test/test_px_cookie.py similarity index 100% rename from tests/px_cookie.py rename to test/test_px_cookie.py diff --git a/tests/px_cookie_validator.py b/test/test_px_cookie_validator.py similarity index 100% rename from tests/px_cookie_validator.py rename to test/test_px_cookie_validator.py diff --git a/tests/px_httpc.py b/test/test_px_httpc.py similarity index 100% rename from tests/px_httpc.py rename to test/test_px_httpc.py diff --git a/tests/px_proxy_handler.py b/test/test_px_proxy_handler.py similarity index 100% rename from tests/px_proxy_handler.py rename to test/test_px_proxy_handler.py diff --git a/tests/px_context.py b/tests/px_context.py deleted file mode 100644 index e69de29..0000000 From 5ea7e6a649af7e00900f54de61cf1556bbf182f7 Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Mon, 3 Dec 2018 10:58:48 +0200 Subject: [PATCH 04/11] FixedTests --- perimeterx/px_context.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/perimeterx/px_context.py b/perimeterx/px_context.py index d37e818..7e91a3b 100644 --- a/perimeterx/px_context.py +++ b/perimeterx/px_context.py @@ -34,8 +34,6 @@ def __init__(self, environ, config): http_version = protocol_split[1] if key == 'CONTENT_TYPE' or key == 'CONTENT_LENGTH': headers[key.replace('_', '-').lower()] = environ.get(key) - if key == 'HTTP_' + MOBILE_SDK_HEADER.replace('-', '_').upper(): - headers[MOBILE_SDK_HEADER] = environ.get(key, '') mobile_header = headers.get(MOBILE_SDK_HEADER) original_token = '' From 869c956830ea6c63c5ea9cb8133ab45c0d052448 Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Mon, 3 Dec 2018 10:59:54 +0200 Subject: [PATCH 05/11] FixedTests --- .travis.yml | 2 +- perimeterx/middleware.py | 2 +- perimeterx/px_httpc.py | 2 +- perimeterx/px_original_token_validator.py | 2 +- .../{px_proxy_handler.py => px_proxy.py} | 1 - perimeterx/px_token_v1.py | 32 --------------- perimeterx/px_token_v3.py | 37 ----------------- test/__init__.py | 0 test/test_px_httpc.py | 1 + test/test_px_original_token_validator.py | 41 +++++++++++++++++++ ...t_px_proxy_handler.py => test_px_proxy.py} | 2 +- tests/px_utils.py => test/test_px_utils.py | 0 12 files changed, 47 insertions(+), 75 deletions(-) rename perimeterx/{px_proxy_handler.py => px_proxy.py} (99%) delete mode 100644 perimeterx/px_token_v1.py delete mode 100644 perimeterx/px_token_v3.py create mode 100644 test/__init__.py create mode 100644 test/test_px_original_token_validator.py rename test/{test_px_proxy_handler.py => test_px_proxy.py} (98%) rename tests/px_utils.py => test/test_px_utils.py (100%) diff --git a/.travis.yml b/.travis.yml index 7b5b817..19458cf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,4 +6,4 @@ install: - pip install -r requirements.txt # command to run tests script: - - python -m unittest discover -s ./tests -p 'px*' + - python -m unittest discover -s ./test -p 'test*' diff --git a/perimeterx/middleware.py b/perimeterx/middleware.py index bc7171c..ee3b816 100644 --- a/perimeterx/middleware.py +++ b/perimeterx/middleware.py @@ -5,7 +5,7 @@ import px_api import px_constants import px_utils -from perimeterx.px_proxy_handler import PXProxy +from perimeterx.px_proxy import PXProxy from px_config import PxConfig diff --git a/perimeterx/px_httpc.py b/perimeterx/px_httpc.py index 81e7e68..28e92d9 100644 --- a/perimeterx/px_httpc.py +++ b/perimeterx/px_httpc.py @@ -17,6 +17,6 @@ def send(full_url, body, headers, config, method): logger.debug('PerimeterX server call took ' + str(time.time() - start) + 'ms') return response - except requests.exceptions as e: + except requests.exceptions.RequestException as e: logger.debug('Received RequestException, message: ' + e.message) return False diff --git a/perimeterx/px_original_token_validator.py b/perimeterx/px_original_token_validator.py index c49e8d0..84a17f9 100644 --- a/perimeterx/px_original_token_validator.py +++ b/perimeterx/px_original_token_validator.py @@ -17,7 +17,7 @@ def verify(ctx, config): original_token = ctx.original_token version, no_version_token = original_token.split(':', 1) px_cookie_builder = PxCookie(config) - px_cookie = px_cookie_builder.build_px_cookie({version: no_version_token},'') + px_cookie = px_cookie_builder.build_px_cookie({version: no_version_token}, '') if not px_cookie.deserialize(): logger.error('Original token decryption failed, value:' + px_cookie.raw_cookie) diff --git a/perimeterx/px_proxy_handler.py b/perimeterx/px_proxy.py similarity index 99% rename from perimeterx/px_proxy_handler.py rename to perimeterx/px_proxy.py index 8f58988..f0d31af 100644 --- a/perimeterx/px_proxy_handler.py +++ b/perimeterx/px_proxy.py @@ -1,5 +1,4 @@ import px_constants -import px_logger import px_httpc import px_utils import base64 diff --git a/perimeterx/px_token_v1.py b/perimeterx/px_token_v1.py deleted file mode 100644 index 182f195..0000000 --- a/perimeterx/px_token_v1.py +++ /dev/null @@ -1,32 +0,0 @@ -from px_cookie import PxCookie - - -class PxTokenV1(PxCookie): - - def __init__(self, config, token): - self._config = config - self._logger = config.logger - self.raw_cookie = token - - def get_score(self): - return self.decoded_cookie['s']['b'] - - def get_hmac(self): - return self.decoded_cookie['h'] - - def get_action(self): - return 'c' - - def is_cookie_format_valid(self): - c = self.decoded_cookie - return 't' in c and 'v' in c and 'u' in c and "s" in c and 'a' in c['s'] and 'h' in c - - def is_secured(self, ip): - c = self.decoded_cookie - base_hmac = str(self.get_timestamp()) + str(c['s']['a']) + str(self.get_score()) + self.get_uuid() + self.get_vid() - hmac_with_ip = base_hmac + ip - hmac_without_ip = base_hmac - - return self.is_cookie_valid(hmac_without_ip) or self.is_cookie_valid(hmac_with_ip) - - diff --git a/perimeterx/px_token_v3.py b/perimeterx/px_token_v3.py deleted file mode 100644 index 057e2e3..0000000 --- a/perimeterx/px_token_v3.py +++ /dev/null @@ -1,37 +0,0 @@ -from px_cookie import PxCookie -from px_constants import * - - -class PxTokenV3(PxCookie): - - def __init__(self, config, token): - - self._config = config - self._logger = config.logger - spliced_cookie = token.split(":", 1) - - print ("Count: " + str(len(spliced_cookie))) - - if len(spliced_cookie) > 1: - self.hmac = spliced_cookie[0] - self.raw_cookie = spliced_cookie[1] - else: - self.raw_cookie = token - - - def get_score(self): - return self.decoded_cookie['s'] - - def get_hmac(self): - return self.hmac - - def get_action(self): - return self.decoded_cookie['a'] - - def is_cookie_format_valid(self): - c = self.decoded_cookie; - return 't' in c and 'v' in c and 'u' in c and 's' in c and 'a' in c - - def is_secured(self): - return self.is_cookie_valid(self.raw_cookie) - diff --git a/test/__init__.py b/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/test_px_httpc.py b/test/test_px_httpc.py index 69ff055..9083463 100644 --- a/test/test_px_httpc.py +++ b/test/test_px_httpc.py @@ -3,6 +3,7 @@ import requests_mock from perimeterx.px_config import PxConfig + class TestPXHttpc(unittest.TestCase): def test_send(self): with requests_mock.mock() as m: diff --git a/test/test_px_original_token_validator.py b/test/test_px_original_token_validator.py new file mode 100644 index 0000000..8524c94 --- /dev/null +++ b/test/test_px_original_token_validator.py @@ -0,0 +1,41 @@ +import unittest +from perimeterx import px_original_token_validator +from perimeterx.px_config import PxConfig +from perimeterx.px_context import PxContext +from perimeterx import px_constants +class TestPXOriginalTokenValidator(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.cookie_key = 'Pyth0nS3crE7K3Y' + cls.config = PxConfig({'app_id': 'app_id', + 'cookie_key': cls.cookie_key}) + def test_verify(self): + token = '3:bd078865fa9627f626d6f7d6828ab595028d2c0974065ab6f6c5a9f80c4593cd:OCIluokZHHvqrWyu8zrWSH8Vu7AefCjrd4CMx/NXsX58LzeV40EZIlPG4gsNMoAYzH88s/GoZwv+DpQa76C21A==:1000:zwT+Rht/YGDNWKkzHtJAB7IiI00u4fOePL/3xWMs1nZ93lzW1XvAMGR2hLlHBmOv8O0CpylEQOZZTK1uQMls6O28Y8aQnTo5DETLkrbhpwCVeNjOcf8GVKTckITwuHfXbEcfHbdtb68s1+jHv1+vt/w/6HZqTzanaIsvFVp8vmA=' + + context = PxContext({'HTTP_' + px_constants.MOBILE_SDK_ORIGINAL_HEADER.replace('-', '_').upper(): token, + 'HTTP_' + px_constants.MOBILE_SDK_HEADER.replace('-', '_').upper(): '2'}, self.config) + verified = px_original_token_validator.verify(context, self.config) + self.assertTrue(verified) + self.assertEqual(context.vid, 'ce305f10-f17e-11e8-90f2-e7a14f96c498') + self.assertEqual(context.decoded_original_token, {'a': 'a', 's': 0, 'u': 'ce308620-f17e-11e8-90f2-e7a14f96c498', 't': 1663653730456, 'v': 'ce305f10-f17e-11e8-90f2-e7a14f96c498'}) + self.assertEqual(context.original_uuid, 'ce308620-f17e-11e8-90f2-e7a14f96c498') + self.assertEqual(context.original_token_error, '') + + def test_decryption_error_token(self): + token = '3:bd078865fa9627f626d6f7d6828ab595028d2c0974065ab6f6c5a9f80c4593cd:OCIluokZHHvqrWyu8zrWSH8Vu7AefCjrd4CMx/NXsX58LzeV40EZIlPG4gsNMoAYzH88s/GoZwv+DpQa76C21A==:1000:zwT+Rht/YGDNWKkzHtJAB7IiI00asfafu4fOePL/3xWMs1nZ93lzW1XvAMGR2hLlHBmOv8O0CpylEQOZZTK1uQMls6O28Y8aQnTo5DETLkrbhpwCVeNjOcf8GVKTckITwuHfXbEcfHbdtb68s1+jHv1+vt/w/6HZqTzanaIsvFVp8vmA=' + + context = PxContext({'HTTP_' + px_constants.MOBILE_SDK_ORIGINAL_HEADER.replace('-', '_').upper(): token, + 'HTTP_' + px_constants.MOBILE_SDK_HEADER.replace('-', '_').upper(): '2'}, self.config) + verified = px_original_token_validator.verify(context, self.config) + self.assertFalse(verified) + self.assertEqual(context.original_token_error, 'decryption_failed') + + def test_validation_error_token(self): + token = '3:bd078865fa9627f626d6f7d6828ab595028d2c0974ds065ab6f6c5afsaa9f80c4593cd:OCIluokZHHvqrWyu8zrWSH8Vu7AefCjrd4CMx/NXsX58LzeV40EZIlPG4gsNMoAYzH88s/GoZwv+DpQa76C21A==:1000:zwT+Rht/YGDNWKkzHtJAB7IiI00u4fOePL/3xWMs1nZ93lzW1XvAMGR2hLlHBmOv8O0CpylEQOZZTK1uQMls6O28Y8aQnTo5DETLkrbhpwCVeNjOcf8GVKTckITwuHfXbEcfHbdtb68s1+jHv1+vt/w/6HZqTzanaIsvFVp8vmA=' + + context = PxContext({'HTTP_' + px_constants.MOBILE_SDK_ORIGINAL_HEADER.replace('-', '_').upper(): token, + 'HTTP_' + px_constants.MOBILE_SDK_HEADER.replace('-', '_').upper(): '2'}, self.config) + verified = px_original_token_validator.verify(context, self.config) + self.assertFalse(verified) + self.assertEqual(context.original_token_error, 'validation_failed') diff --git a/test/test_px_proxy_handler.py b/test/test_px_proxy.py similarity index 98% rename from test/test_px_proxy_handler.py rename to test/test_px_proxy.py index 92bce42..f2bd9db 100644 --- a/test/test_px_proxy_handler.py +++ b/test/test_px_proxy.py @@ -1,6 +1,6 @@ import unittest import requests_mock -from perimeterx.px_proxy_handler import PXProxy +from perimeterx.px_proxy import PXProxy from perimeterx.px_config import PxConfig from perimeterx import px_constants from perimeterx.px_context import PxContext diff --git a/tests/px_utils.py b/test/test_px_utils.py similarity index 100% rename from tests/px_utils.py rename to test/test_px_utils.py From 5ba02eef42fe0fb494d6069c9628d0d418ea62f7 Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Mon, 3 Dec 2018 11:41:37 +0200 Subject: [PATCH 06/11] Fxied Tests --- perimeterx/px_context.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/perimeterx/px_context.py b/perimeterx/px_context.py index 7e91a3b..dd4e76d 100644 --- a/perimeterx/px_context.py +++ b/perimeterx/px_context.py @@ -34,9 +34,11 @@ def __init__(self, environ, config): http_version = protocol_split[1] if key == 'CONTENT_TYPE' or key == 'CONTENT_LENGTH': headers[key.replace('_', '-').lower()] = environ.get(key) + if key == 'HTTP_' + MOBILE_SDK_HEADER.replace('-', '_').upper(): + headers[MOBILE_SDK_HEADER] = environ.get(key, '') - mobile_header = headers.get(MOBILE_SDK_HEADER) original_token = '' + mobile_header = headers.get(MOBILE_SDK_HEADER) if mobile_header is None: cookies = Cookie.SimpleCookie(environ.get('HTTP_COOKIE', '')) cookie_keys = cookies.keys() From 4aced94a7603537cf5af3d1c7a1ec616f22386d4 Mon Sep 17 00:00:00 2001 From: Yaron Schwimmer Date: Mon, 3 Dec 2018 13:16:29 +0200 Subject: [PATCH 07/11] added lint --- .pylintrc | 549 +++++++++++++++++++++++++++++++++++++++++++++++ .travis.yml | 1 + requirements.txt | 3 +- 3 files changed, 552 insertions(+), 1 deletion(-) create mode 100644 .pylintrc diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..19f6c38 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,549 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code +extension-pkg-whitelist= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. +jobs=1 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once).You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use"--disable=all --enable=classes +# --disable=W" +disable=print-statement, + parameter-unpacking, + unpacking-in-except, + old-raise-syntax, + backtick, + long-suffix, + old-ne-operator, + old-octal-literal, + import-star-module-level, + non-ascii-bytes-literal, + invalid-unicode-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + locally-enabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + apply-builtin, + basestring-builtin, + buffer-builtin, + cmp-builtin, + coerce-builtin, + execfile-builtin, + file-builtin, + long-builtin, + raw_input-builtin, + reduce-builtin, + standarderror-builtin, + unicode-builtin, + xrange-builtin, + coerce-method, + delslice-method, + getslice-method, + setslice-method, + no-absolute-import, + old-division, + dict-iter-method, + dict-view-method, + next-method-called, + metaclass-assignment, + indexing-exception, + raising-string, + reload-builtin, + oct-method, + hex-method, + nonzero-method, + cmp-method, + input-builtin, + round-builtin, + intern-builtin, + unichr-builtin, + map-builtin-not-iterating, + zip-builtin-not-iterating, + range-builtin-not-iterating, + filter-builtin-not-iterating, + using-cmp-argument, + eq-without-hash, + div-method, + idiv-method, + rdiv-method, + exception-message-attribute, + invalid-str-codec, + sys-max-int, + bad-python3-import, + deprecated-string-function, + deprecated-str-translate-call, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio).You can also give a reporter class, eg +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=optparse.Values,sys.exit + + +[LOGGING] + +# Logging modules to check that the string format arguments are in logging +# function parameter format +logging-modules=logging + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members=raw_cookie,get_hmac,get_score,is_cookie_format_valid + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expectedly +# not used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,io,builtins + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[BASIC] + +# Naming style matching correct argument names +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style +#argument-rgx= + +# Naming style matching correct attribute names +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style +#class-attribute-rgx= + +# Naming style matching correct class names +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming-style +#class-rgx= + +# Naming style matching correct constant names +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma +good-names=i, + j, + k, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name +include-naming-hint=no + +# Naming style matching correct inline iteration names +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style +#inlinevar-rgx= + +# Naming style matching correct method names +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style +#method-rgx= + +# Naming style matching correct module names +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style +#variable-rgx= + + +[DESIGN] + +# Maximum number of arguments for function / method +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in a if statement +max-bool-expr=5 + +# Maximum number of branch for function / method body +max-branches=12 + +# Maximum number of locals for function / method body +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body +max-returns=6 + +# Maximum number of statements in function / method body +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[IMPORTS] + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=regsub, + TERMIOS, + Bastion, + rexec + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled) +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled) +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception" +overgeneral-exceptions=Exception diff --git a/.travis.yml b/.travis.yml index 19458cf..15ca9ae 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,3 +7,4 @@ install: # command to run tests script: - python -m unittest discover -s ./test -p 'test*' + - pylint -E perimeterx/ diff --git a/requirements.txt b/requirements.txt index 23ee4f9..ad3d2c3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,5 @@ requests==2.20.1 setuptools==40.6.2 requests_mock==1.5.2 pycrypto==2.6.1 -webapp2==2.5.2 +iwebapp2==2.5.2 +pylint From b282268b64b57a66ca6cd830324f971f3ea95039 Mon Sep 17 00:00:00 2001 From: Yaron Schwimmer Date: Mon, 3 Dec 2018 13:20:45 +0200 Subject: [PATCH 08/11] fixed dependency name --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index ad3d2c3..b8d57dd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,5 +3,5 @@ requests==2.20.1 setuptools==40.6.2 requests_mock==1.5.2 pycrypto==2.6.1 -iwebapp2==2.5.2 +webapp2==2.5.2 pylint From 630f070215141f7aed18a9f3a7ccb3d3704f2aee Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Mon, 3 Dec 2018 14:37:10 +0200 Subject: [PATCH 09/11] Somehow mobile flow was not included :\ --- perimeterx/px_blocker.py | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/perimeterx/px_blocker.py b/perimeterx/px_blocker.py index 315b78a..db40051 100644 --- a/perimeterx/px_blocker.py +++ b/perimeterx/px_blocker.py @@ -2,6 +2,7 @@ import px_template import px_constants import json +import base64 class PXBlocker(object): @@ -31,9 +32,23 @@ def handle_blocking(self, ctx, config): blocking_props = self.prepare_properties(ctx, config) blocking_response = self.mustache_renderer.render(px_template.get_template(px_constants.BLOCK_TEMPLATE), blocking_props) + + if ctx.is_mobile: + blocking_response = json.dumps({ + 'action': parse_action(ctx.block_action), + 'uuid': ctx.uuid, + 'vid': ctx.vid, + 'appId': config.app_id, + 'page': base64.b64encode(blocking_response), + 'collectorURL': 'https://' + config.collector_host + }) + return blocking_response, headers, status + if is_json_response: blocking_response = json.dumps(blocking_props) - return str(blocking_response), headers, status + + blocking_response = str(blocking_response) + return blocking_response, headers, status def prepare_properties(self, ctx, config): app_id = config.app_id @@ -78,3 +93,14 @@ def is_json_response(self, ctx): if header_item.strip() == 'application/json': return True return False + + +def parse_action(action): + if 'b' == action: + return 'block' + elif 'j' == action: + return 'challege' + elif 'r' == action: + return 'ratelimit' + else: + return 'captcha' From 24725a84b5edfc8c90ee2c7950034927def4851e Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Mon, 3 Dec 2018 14:39:20 +0200 Subject: [PATCH 10/11] Fixed README according to Sara's review --- README.md | 95 +++++++++++++------------------------------------------ 1 file changed, 22 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index 3b781cf..1a24f6e 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,15 @@ [![Build Status](https://travis-ci.org/PerimeterX/perimeterx-python-wsgi.svg?branch=master)](https://travis-ci.org/PerimeterX/perimeterx-python-wsgi) - ![image](https://s.perimeterx.net/logo.png) - [PerimeterX](http://www.perimeterx.com) Python Middleware ============================================================= - > Latest stable version: [v2.0.0](link to package) - Table of Contents ----------------- - [Installation](#installation) -- [Basic Usage Example](#basic_usage) +- [Required Configuration](#required_config) +- [Upgrading](#upgrading) - [Advanced Blocking Response](#advanced_blocking_response) -- [Advanced Configuration Options](#configuration) +- [Optional Configuration](#configuration) * [Module Enabled](#module_enabled) * [Module Mode](#module_mode) * [Blocking Score](#blocking_score) @@ -22,45 +19,34 @@ Table of Contents * [Whitelist Routes](#whitelist_routes) * [Sensitive Headers](#sensitive_headers) * [IP Headers](#ip_headers) - * [First Party Enabled](#first_party_enabled) + * [First-Party Enabled](#first_party_enabled) * [Custom Request Handler](#custom_request_handler) * [Additional Activity Handler](#additional_activity_handler) - ## Installation -PerimeterX python middleware is installed via PIP: +PerimeterX Python middleware is installed via PIP: `$ pip install perimeterx-python-wsgi` - -## Basic Usage Example +## Upgrading +Contact [PerimeterX Support](mailto: support@perimeterx.com) for details. +## Required Configurations To use PerimeterX middleware on a specific route follow this example: - ```python px_config = { 'app_id': 'APP_ID', 'cookie_key': 'COOKIE_KEY', 'auth_token': 'AUTH_TOKEN', } - application = get_wsgi_application() application = PerimeterX(application, px_config) - -**Note:** app id, cookie secret and auth token are required fields. - - ``` - - - +- The PerimeterX **Application ID** / **AppId** and PerimeterX **Token** / **Auth Token** can be found in the Portal, in [Applications](https://console.perimeterx.com/#/app/applicationsmgmt). +- PerimeterX **Risk Cookie** / **Cookie Key** can be found in the portal, in [Policies](https://console.perimeterx.com/#/app/policiesmgmt). +The Policy from where the **Risk Cookie** / **Cookie Key** is taken must correspond with the Application from where the **Application ID** / **AppId** and PerimeterX **Token** / **Auth Token**. For details on how to create a custom Captcha page, refer to the [documentation](https://console.perimeterx.com/docs/server_integration_new.html#custom-captcha-section) - -## Advanced Configuration Options - -In addition to the basic installation configuration [above](#basicUsage), the following configurations options are available: - +## Optional Configuration +In addition to the basic installation configuration [above](#required_config), the following configurations options are available: #### Module Enabled A boolean flag to enable/disable the PerimeterX Enforcer. - **Default:** true - ```python config = { ... @@ -68,17 +54,12 @@ config = { ... } ``` - #### Module Mode Sets the working mode of the Enforcer. - Possible values: - * `active_blocking` - Blocking Mode * `monitor` - Monitoring Mode - **Default:** `monitor` - Monitor Mode - ```python config = { ... @@ -86,16 +67,11 @@ config = { ... } ``` - #### Blocking Score Sets the minimum blocking score of a request. - Possible values: - * Any integer between 0 and 100. - **Default:** 100 - ```python config = { ... @@ -103,13 +79,10 @@ config = { ... } ``` - #### Send Page Activities -A boolean flag to enable/disable sending activities and metrics to PerimeterX with each request.
+Enable/disable sending activities and metrics to PerimeterX with each request.
Enabling this feature allows data to populate the PerimeterX Portal with valuable information, such as the number of requests blocked and additional API usage statistics. - **Default:** true - ```python config = { ... @@ -117,13 +90,9 @@ config = { ... } ``` - - #### Debug Mode -A boolean flag to enable/disable the debug log messages. - +Enable/disable the debug log messages. **Default:** False - ```python config = { ... @@ -131,12 +100,9 @@ config = { ... } ``` - #### Sensitive Routes An array of route prefixes that trigger a server call to PerimeterX servers every time the page is viewed, regardless of viewing history. - **Default:** Empty - ```python const config = { ... @@ -144,12 +110,9 @@ const config = { ... } ``` - #### Whitelist Routes An array of route prefixes which will bypass enforcement (will never get scored). - **Default:** Empty - ```python config = { ... @@ -157,12 +120,9 @@ config = { ... } ``` - #### Sensitive Headers An array of headers that are not sent to PerimeterX servers on API calls. - **Default:** ['cookie', 'cookies'] - ```python config = { ... @@ -170,12 +130,9 @@ config = { ... } ``` - #### IP Headers An array of trusted headers that specify an IP to be extracted. - **Default:** Empty - ```python config = { ... @@ -183,12 +140,9 @@ config = { ... } ``` - -#### First Party Enabled -A boolean flag to enable/disable first party mode. - +#### First-Party Enabled +Enable/disable First-Party mode. **Default:** True - ```python const pxConfig = { ... @@ -196,14 +150,12 @@ const pxConfig = { ... } ``` - #### Custom Request Handler -A Python function that adds a custom response handler to the request. -Do not forget to declare the function before using it in the config. -Custom request handler is triggered after PerimeterX's verification. -The custom function should handle the response (probably create a new one) +A Python function that adds a custom response handler to the request.
+You must declare the function before using it in the config.
+The Custom Request Handler is triggered after PerimeterX's verification. +The custom function should handle the response (most likely it will create a new response) **Default:** Empty - ```python config = { ... @@ -211,16 +163,13 @@ config = { ... } ``` - #### Additional Activity Handler A Python function that allows interaction with the request data collected by PerimeterX before the data is returned to the PerimeterX servers. Does not alter the response. - **Default:** Empty - ```python config = { ... additional_activity_handler: additional_activity_handler_function, ... } -``` +``` \ No newline at end of file From 70f8f2220518ed7f7b10636d617e23da2935b93b Mon Sep 17 00:00:00 2001 From: Alex Bluvstein Date: Mon, 3 Dec 2018 14:47:09 +0200 Subject: [PATCH 11/11] Changed naming --- perimeterx/px_blocker.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/perimeterx/px_blocker.py b/perimeterx/px_blocker.py index db40051..40388b3 100644 --- a/perimeterx/px_blocker.py +++ b/perimeterx/px_blocker.py @@ -34,7 +34,7 @@ def handle_blocking(self, ctx, config): blocking_props) if ctx.is_mobile: - blocking_response = json.dumps({ + page_response = json.dumps({ 'action': parse_action(ctx.block_action), 'uuid': ctx.uuid, 'vid': ctx.vid, @@ -42,7 +42,7 @@ def handle_blocking(self, ctx, config): 'page': base64.b64encode(blocking_response), 'collectorURL': 'https://' + config.collector_host }) - return blocking_response, headers, status + return page_response, headers, status if is_json_response: blocking_response = json.dumps(blocking_props)