Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add IP filter for HTTP requests (#13891)

Mikail806684c30f15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c90d0acd2d..605bc0a6ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,13 @@ All notable, unreleased changes to this project will be documented in this file.
in 3.17. Use `PaymentSettings.defaultTransactionFlowStrategy` instead.
- Change in the CSV export. It will now use empty string for empty attribute values instead of a single whitespace value.
+- Add IP filter feature to backend HTTP requests - #13891 by @NyanKiyoshi
+
+ This rejects server-side HTTP requests (webhooks, OIDC, etc.) if they try to communicate
+ with private or loopback IP addresses, to change the default behavior,
+ refer to `HTTP_IP_FILTER_ENABLED`, and `HTTP_IP_FILTER_ALLOW_LOOPBACK_IPS` settings
+ for more details.
+
### GraphQL API
- Add `customerIpAddress` to `transactionInitialize` and `transactionProcess` mutations - #13718 by @korycins
diff --git a/poetry.lock b/poetry.lock
index 15b2d70e8d..ffd7225b8f 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -1,4 +1,4 @@
-# This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand.
+# This file is automatically @generated by Poetry 1.5.1 and should not be changed by hand.
[[package]]
name = "adyen"
@@ -3700,6 +3700,7 @@ files = [
{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938"},
{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d"},
{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515"},
+ {file = "PyYAML-6.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:326c013efe8048858a6d312ddd31d56e468118ad4cdeda36c719bf5bb6192290"},
{file = "PyYAML-6.0.1-cp310-cp310-win32.whl", hash = "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924"},
{file = "PyYAML-6.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d"},
{file = "PyYAML-6.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007"},
@@ -3707,8 +3708,15 @@ files = [
{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d"},
{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc"},
{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673"},
+ {file = "PyYAML-6.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e7d73685e87afe9f3b36c799222440d6cf362062f78be1013661b00c5c6f678b"},
{file = "PyYAML-6.0.1-cp311-cp311-win32.whl", hash = "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741"},
{file = "PyYAML-6.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34"},
+ {file = "PyYAML-6.0.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:855fb52b0dc35af121542a76b9a84f8d1cd886ea97c84703eaa6d88e37a2ad28"},
+ {file = "PyYAML-6.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:40df9b996c2b73138957fe23a16a4f0ba614f4c0efce1e9406a184b6d07fa3a9"},
+ {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c22bec3fbe2524cde73d7ada88f6566758a8f7227bfbf93a408a9d86bcc12a0"},
+ {file = "PyYAML-6.0.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8d4e9c88387b0f5c7d5f281e55304de64cf7f9c0021a3525bd3b1c542da3b0e4"},
+ {file = "PyYAML-6.0.1-cp312-cp312-win32.whl", hash = "sha256:d483d2cdf104e7c9fa60c544d92981f12ad66a457afae824d146093b8c294c54"},
+ {file = "PyYAML-6.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:0d3304d8c0adc42be59c5f8a4d9e3d7379e6955ad754aa9d6ab7a398b59dd1df"},
{file = "PyYAML-6.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47"},
{file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98"},
{file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c"},
@@ -3725,6 +3733,7 @@ files = [
{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5"},
{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696"},
{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735"},
+ {file = "PyYAML-6.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:49a183be227561de579b4a36efbb21b3eab9651dd81b1858589f796549873dd6"},
{file = "PyYAML-6.0.1-cp38-cp38-win32.whl", hash = "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206"},
{file = "PyYAML-6.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62"},
{file = "PyYAML-6.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8"},
@@ -3732,6 +3741,7 @@ files = [
{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6"},
{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0"},
{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c"},
+ {file = "PyYAML-6.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:04ac92ad1925b2cff1db0cfebffb6ffc43457495c9b3c39d3fcae417d7125dc5"},
{file = "PyYAML-6.0.1-cp39-cp39-win32.whl", hash = "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c"},
{file = "PyYAML-6.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486"},
{file = "PyYAML-6.0.1.tar.gz", hash = "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43"},
@@ -3790,6 +3800,22 @@ urllib3 = ">=1.21.1,<3"
socks = ["PySocks (>=1.5.6,!=1.5.7)"]
use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"]
+[[package]]
+name = "requests-hardened"
+version = "1.0.0b0"
+description = "A library that overrides the default behaviors of the ``requests`` library, and adds new security features."
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "requests-hardened-1.0.0b0.tar.gz", hash = "sha256:7c8934bb3918235ecaba14f7890d678fe556584c154a1ab511838897649e10c9"},
+]
+
+[package.dependencies]
+requests = ">=2.0.1,<3.0.0"
+
+[package.extras]
+dev = ["mypy (>=1.5.1,<1.6.0)", "pytest (>=7.4.0,<7.5.0)", "trustme (>=1.1.0,<2.0.0)", "types-requests (>=2.0.1,<3.0.0)"]
+
[[package]]
name = "rsa"
version = "4.9"
@@ -4869,4 +4895,4 @@ test = ["pytest"]
[metadata]
lock-version = "2.0"
python-versions = "~3.9"
-content-hash = "82b793737993b89baabafebcb72a58fb993196d13530c247e889ba9b3f450a99"
+content-hash = "fe41089a647dfcc895c7960f07ae18604490f4327b84f06122caa041053c6dda"
diff --git a/pyproject.toml b/pyproject.toml
index 502c0b9703..1f2f293a5d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -71,6 +71,7 @@ documentation = "https://docs.saleor.io/"
Authlib = "^1.0.0"
pillow-avif-plugin = "^1.3.1"
semantic-version = "^2.10.0"
+ requests-hardened = "1.0.0b0"
[tool.poetry.dependencies.celery]
version = ">=4.4.5,<6.0.0"
diff --git a/requirements.txt b/requirements.txt
index 6c36295bc0..a550ab6c87 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -128,6 +128,7 @@ pyxb==1.2.5 ; python_version >= "3.9" and python_version < "3.10"
pyyaml==6.0.1 ; python_version >= "3.9" and python_version < "3.10"
razorpay==1.4.1 ; python_version >= "3.9" and python_version < "3.10"
redis==4.6.0 ; python_version >= "3.9" and python_version < "3.10"
+requests-hardened==1.0.0b0 ; python_version >= "3.9" and python_version < "3.10"
requests==2.31.0 ; python_version >= "3.9" and python_version < "3.10"
rsa==4.9 ; python_version >= "3.9" and python_version < "3.10"
rx==1.6.3 ; python_version >= "3.9" and python_version < "3.10"
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 4d81fd78a8..d6409f3d6e 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -182,6 +182,7 @@ pyxb==1.2.5 ; python_version >= "3.9" and python_version < "3.10"
pyyaml==6.0.1 ; python_version >= "3.9" and python_version < "3.10"
razorpay==1.4.1 ; python_version >= "3.9" and python_version < "3.10"
redis==4.6.0 ; python_version >= "3.9" and python_version < "3.10"
+requests-hardened==1.0.0b0 ; python_version >= "3.9" and python_version < "3.10"
requests==2.31.0 ; python_version >= "3.9" and python_version < "3.10"
rsa==4.9 ; python_version >= "3.9" and python_version < "3.10"
rx==1.6.3 ; python_version >= "3.9" and python_version < "3.10"
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index ac38f353f0..18eca43dd9 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -18,6 +18,7 @@ from requests import HTTPError, Response
from .. import schema_version
from ..app.headers import AppHeaders, DeprecatedAppHeaders
from ..celeryconf import app
+from ..core.http_client import HTTPClient
from ..core.utils import build_absolute_uri
from ..permission.enums import get_permission_names
from ..plugins.manager import PluginsManager
@@ -63,7 +64,8 @@ def send_app_token(target_url: str, token: str):
AppHeaders.SCHEMA_VERSION: schema_version,
}
json_data = {"auth_token": token}
- response = requests.post(
+ response = HTTPClient.send_request(
+ "POST",
target_url,
json=json_data,
headers=headers,
@@ -81,8 +83,8 @@ def fetch_icon_image(
code = AppErrorCode.INVALID.value
fetch_start = time.monotonic()
try:
- with requests.get(
- url, stream=True, timeout=timeout, allow_redirects=False
+ with HTTPClient.send_request(
+ "GET", url, stream=True, timeout=timeout, allow_redirects=False
) as res:
res.raise_for_status()
content_type = res.headers.get("content-type")
@@ -189,8 +191,8 @@ def fetch_brand_data_async(
def fetch_manifest(manifest_url: str, timeout=REQUEST_TIMEOUT):
headers = {AppHeaders.SCHEMA_VERSION: schema_version}
- response = requests.get(
- manifest_url, headers=headers, timeout=timeout, allow_redirects=False
+ response = HTTPClient.send_request(
+ "GET", manifest_url, headers=headers, timeout=timeout, allow_redirects=False
)
response.raise_for_status()
return response.json()
diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.py
index ff1759a485..ba8178e338 100644
--- a/saleor/app/management/commands/create_app.py
+++ b/saleor/app/management/commands/create_app.py
@@ -1,7 +1,6 @@
import json
from typing import Any, Dict, Optional
-import requests
from django.contrib.sites.models import Site
from django.core.management import BaseCommand, CommandError
from django.core.management.base import CommandParser
@@ -10,6 +9,7 @@ from requests.exceptions import RequestException
from .... import schema_version
from ....app.headers import AppHeaders, DeprecatedAppHeaders
+from ....core.http_client import HTTPClient
from ....core.utils import build_absolute_uri
from ...models import App
from .utils import clean_permissions
@@ -52,7 +52,8 @@ class Command(BaseCommand):
AppHeaders.SCHEMA_VERSION: schema_version,
}
try:
- response = requests.post(
+ response = HTTPClient.send_request(
+ "POST",
target_url,
json=data,
headers=headers,
diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.py
index 6f46211d8c..7ec4469876 100644
--- a/saleor/app/tests/test_app_commands.py
+++ b/saleor/app/tests/test_app_commands.py
@@ -1,8 +1,8 @@
from unittest.mock import ANY, Mock, call
import pytest
-import requests
from django.core.management import call_command
+from requests_hardened import HTTPSession
from ... import schema_version
from ...core import JobStatus
@@ -53,13 +53,22 @@ def test_creates_app_from_manifest_sends_token(monkeypatch, app_manifest):
mocked_post = Mock(return_value=Mock())
mocked_post.return_value.status_code = 200
- monkeypatch.setattr(requests, "get", mocked_get)
- monkeypatch.setattr(requests, "post", mocked_post)
+ def _side_effect(_self, method, *args, **kwargs):
+ if method == "GET":
+ func = mocked_get
+ elif method == "POST":
+ func = mocked_post
+ else:
+ raise NotImplementedError("Method not implemented", method)
+ return func(method, *args, **kwargs)
+
+ monkeypatch.setattr(HTTPSession, "request", _side_effect)
manifest_url = "http://localhost:3000/manifest"
call_command("install_app", manifest_url)
get_call = call(
+ "GET",
manifest_url,
headers={"Saleor-Schema-Version": schema_version},
timeout=ANY,
@@ -67,6 +76,7 @@ def test_creates_app_from_manifest_sends_token(monkeypatch, app_manifest):
)
mocked_get.assert_has_calls([get_call, get_call])
mocked_post.assert_called_once_with(
+ "POST",
app_manifest["tokenTargetUrl"],
headers={
"Content-Type": "application/json",
@@ -126,7 +136,7 @@ def test_sends_data_to_target_url(monkeypatch):
mocked_response.status_code = 200
mocked_post = Mock(return_value=mocked_response)
- monkeypatch.setattr(requests, "post", mocked_post)
+ monkeypatch.setattr(HTTPSession, "request", mocked_post)
name = "Single App"
target_url = "https://ss.shop.com/register"
@@ -135,6 +145,7 @@ def test_sends_data_to_target_url(monkeypatch):
call_command("create_app", name, permission=permissions, target_url=target_url)
mocked_post.assert_called_once_with(
+ "POST",
target_url,
headers={
# X- headers will be deprecated in Saleor 4.0, proper headers are without X-
diff --git a/saleor/app/tests/test_app_tasks.py b/saleor/app/tests/test_app_tasks.py
index 1ed15a11dc..cd2bb5b82a 100644
--- a/saleor/app/tests/test_app_tasks.py
+++ b/saleor/app/tests/test_app_tasks.py
@@ -2,6 +2,7 @@ from unittest.mock import Mock
import pytest
from requests import RequestException
+from requests_hardened import HTTPSession
from ...core import JobStatus
from ..installation_utils import AppInstallationError
@@ -35,7 +36,7 @@ def test_install_app_task_wrong_format_of_target_token_url():
@pytest.mark.vcr
def test_install_app_task_request_timeout(monkeypatch, app_installation):
mocked_post = Mock(side_effect=RequestException("Timeout"))
- monkeypatch.setattr("saleor.app.installation_utils.requests.post", mocked_post)
+ monkeypatch.setattr(HTTPSession, "request", mocked_post)
install_app_task(app_installation.pk, activate=True)
app_installation.refresh_from_db()
@@ -53,14 +54,7 @@ def test_install_app_task_wrong_response_code(monkeypatch):
app_name="External App",
manifest_url="http://localhost:3000/manifest-wrong1",
)
- response_status_code = 404
- mocked_post = Mock()
- mocked_post.status_code = response_status_code
- monkeypatch.setattr("saleor.app.installation_utils.requests.post", mocked_post)
- message = (
- f"App internal error ({response_status_code}). "
- "Try later or contact with app support."
- )
+ message = "App internal error (404). Try later or contact with app support."
install_app_task(app_installation.pk, activate=True)
app_installation.refresh_from_db()
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index f5c10dc8ce..876f5247a7 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -10,6 +10,7 @@ from django.core.files import File
from django.core.files.base import ContentFile
from django.db import DatabaseError
from freezegun import freeze_time
+from requests_hardened import HTTPSession
from ... import __version__, schema_version
from ...core.utils.json_serializer import CustomJsonEncoder
@@ -56,10 +57,18 @@ def test_install_app_created_app(
app_manifest["permissions"] = ["MANAGE_PRODUCTS"]
mocked_get = Mock(return_value=Mock())
mocked_get.return_value.json = Mock(return_value=app_manifest)
-
- monkeypatch.setattr(requests, "get", mocked_get)
mocked_post = Mock()
- monkeypatch.setattr(requests, "post", mocked_post)
+
+ def _side_effect(_self, method, *args, **kwargs):
+ if method == "GET":
+ func = mocked_get
+ elif method == "POST":
+ func = mocked_post
+ else:
+ raise NotImplementedError("Method not implemented", method)
+ return func(method, *args, **kwargs)
+
+ monkeypatch.setattr(HTTPSession, "request", _side_effect)
app_installation.permissions.set([permission_manage_products])
@@ -68,12 +77,14 @@ def test_install_app_created_app(
# then
mocked_get.assert_called_once_with(
+ "GET",
app_installation.manifest_url,
headers={"Saleor-Schema-Version": schema_version},
timeout=ANY,
allow_redirects=False,
)
mocked_post.assert_called_once_with(
+ "POST",
app_manifest["tokenTargetUrl"],
headers={
"Content-Type": "application/json",
@@ -101,7 +112,7 @@ def test_install_app_created_app_with_audience(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when
@@ -118,7 +129,7 @@ def test_install_app_with_required_saleor_version(
app_manifest["requiredSaleorVersion"] = f"^{__version__}"
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when
@@ -135,7 +146,7 @@ def test_install_app_when_saleor_version_unsupported(
app_manifest["requiredSaleorVersion"] = "<3.11"
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when
@@ -153,7 +164,7 @@ def test_install_app_with_author(app_manifest, app_installation, monkeypatch):
app_manifest["author"] = "Acme Ltd"
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when
@@ -169,7 +180,7 @@ def test_install_app_with_empty_author(app_manifest, app_installation, monkeypat
app_manifest["author"] = " "
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when
@@ -188,7 +199,7 @@ def test_install_app_with_brand_data(app_manifest, app_installation, monkeypatch
app_manifest["brand"] = brand_data
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
mocked_fetch_brand_data_task = Mock()
monkeypatch.setattr(
@@ -226,7 +237,7 @@ def test_install_app_created_app_trigger_webhook(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
app_installation.permissions.set([permission_manage_products])
@@ -274,7 +285,7 @@ def test_install_app_with_extension(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
app_installation.permissions.set(
@@ -325,7 +336,7 @@ def test_install_app_extension_permission_out_of_scope(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when & then
@@ -361,7 +372,7 @@ def test_install_app_extension_incorrect_url(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when & then
@@ -392,7 +403,7 @@ def test_install_app_extension_invalid_permission(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when & then
@@ -432,7 +443,7 @@ def test_install_app_extension_incorrect_values(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when & then
@@ -450,7 +461,7 @@ def test_install_app_with_webhook(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when
@@ -479,7 +490,7 @@ def test_install_app_webhook_incorrect_url(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when & then
with pytest.raises(ValidationError) as excinfo:
@@ -500,7 +511,7 @@ def test_install_app_with_webhook_is_active(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
# when
@@ -520,7 +531,7 @@ def test_install_app_with_webhook_incorrect_is_active_value(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when & then
with pytest.raises(ValidationError) as excinfo:
@@ -554,7 +565,7 @@ def test_install_app_webhook_incorrect_query(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when & then
with pytest.raises(ValidationError) as excinfo:
@@ -575,7 +586,7 @@ def test_install_app_webhook_incorrect_custom_headers(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when & then
with pytest.raises(ValidationError) as excinfo:
@@ -599,7 +610,7 @@ def test_install_app_lack_of_token_target_url_in_manifest_data(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
mocked_post = Mock()
monkeypatch.setattr(requests, "post", mocked_post)
@@ -629,7 +640,7 @@ def image_response_mock():
@patch("saleor.app.installation_utils.validate_icon_image")
-@patch("saleor.app.installation_utils.requests.get")
[email protected](HTTPSession, "request")
def test_fetch_icon_image(
mock_get_request, mock_validate_icon_image, image_response_mock
):
@@ -643,7 +654,7 @@ def test_fetch_icon_image(
# then
mock_get_request.assert_called_once_with(
- image_url, stream=True, timeout=ANY, allow_redirects=False
+ "GET", image_url, stream=True, timeout=ANY, allow_redirects=False
)
mock_validate_icon_image.assert_called_once_with(image_file, ANY)
assert isinstance(image_file, File)
@@ -652,7 +663,7 @@ def test_fetch_icon_image(
@patch("saleor.app.installation_utils.validate_icon_image")
-@patch("saleor.app.installation_utils.requests.get")
[email protected](HTTPSession, "request")
def test_fetch_icon_image_invalid_type(
mock_get_request, mock_validate_icon_image, image_response_mock
):
@@ -665,7 +676,7 @@ def test_fetch_icon_image_invalid_type(
mock_validate_icon_image.assert_not_called()
-@patch("saleor.app.installation_utils.requests.get")
[email protected](HTTPSession, "request")
def test_fetch_icon_image_content_length(mock_get_request, image_response_mock):
mock_get_request.return_value.__enter__.return_value = image_response_mock
image_response_mock.headers["content-length"] = MAX_ICON_FILE_SIZE + 1
@@ -676,7 +687,7 @@ def test_fetch_icon_image_content_length(mock_get_request, image_response_mock):
assert "File too big. Maximal icon image file size is" in error.value.message
-@patch("saleor.app.installation_utils.requests.get")
[email protected](HTTPSession, "request")
def test_fetch_icon_image_file_too_big(mock_get_request, image_response_mock):
def content_chunks():
while True:
@@ -691,7 +702,7 @@ def test_fetch_icon_image_file_too_big(mock_get_request, image_response_mock):
assert "File too big. Maximal icon image file size is" in error.value.message
-@patch("saleor.app.installation_utils.requests.get")
[email protected](HTTPSession, "request")
def test_fetch_icon_image_network_error(mock_get_request):
mock_get_request.side_effect = requests.RequestException
with pytest.raises(ValidationError) as error:
diff --git a/saleor/core/http_client.py b/saleor/core/http_client.py
new file mode 100644
index 0000000000..e919f2e2f2
--- /dev/null
+++ b/saleor/core/http_client.py
@@ -0,0 +1,11 @@
+import requests_hardened
+from django.conf import settings
+
+HTTPConfig = requests_hardened.Config(
+ ip_filter_enable=settings.HTTP_IP_FILTER_ENABLED,
+ ip_filter_allow_localhost=settings.HTTP_IP_FILTER_ALLOW_LOOPBACK_IPS,
+ never_allow_redirects=True,
+ default_timeout=(2, 10),
+)
+
+HTTPClient = requests_hardened.Manager(HTTPConfig)
diff --git a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
index b7931f8e06..79d9838880 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -5,6 +5,7 @@ from unittest.mock import ANY, Mock
import pytest
import requests
from PIL import Image
+from requests_hardened import HTTPSession
from ..... import schema_version
from .....app.error_codes import AppErrorCode
@@ -109,7 +110,7 @@ def test_app_fetch_manifest_custom_saleor_headers(
mocked_get = Mock(return_value=Mock())
mocked_get.return_value.json = Mock(return_value=app_manifest)
- monkeypatch.setattr(requests, "get", mocked_get)
+ monkeypatch.setattr(HTTPSession, "request", mocked_get)
query = APP_FETCH_MANIFEST_MUTATION
manifest_url = "http://localhost:3000/configuration/manifest"
variables = {"manifest_url": manifest_url}
@@ -121,6 +122,7 @@ def test_app_fetch_manifest_custom_saleor_headers(
# then
mocked_get.assert_called_once_with(
+ "GET",
manifest_url,
headers={"Saleor-Schema-Version": schema_version},
timeout=ANY,
@@ -218,9 +220,7 @@ def test_app_fetch_manifest_timeout(
):
mocked_request = Mock()
mocked_request.side_effect = requests.Timeout()
- monkeypatch.setattr(
- "saleor.graphql.app.mutations.app_fetch_manifest.requests.get", mocked_request
- )
+ monkeypatch.setattr(HTTPSession, "request", mocked_request)
manifest_url = "http://localhost:3000/manifest-doesnt-exist"
query = APP_FETCH_MANIFEST_MUTATION
variables = {
@@ -273,7 +273,7 @@ def test_app_fetch_manifest_handle_exception(
mocked_get = Mock()
mocked_get.side_effect = Exception()
- monkeypatch.setattr(requests, "get", mocked_get)
+ monkeypatch.setattr(HTTPSession, "request", mocked_get)
manifest_url = "http://localhost:3000/manifest-wrong-format"
query = APP_FETCH_MANIFEST_MUTATION
variables = {
@@ -311,7 +311,7 @@ def test_app_fetch_manifest_missing_fields(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
query = APP_FETCH_MANIFEST_MUTATION
manifest_url = "http://localhost:3000/configuration/manifest"
variables = {
@@ -359,7 +359,7 @@ def test_app_fetch_manifest_missing_extension_fields(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
query = APP_FETCH_MANIFEST_MUTATION
manifest_url = "http://localhost:3000/configuration/manifest"
variables = {
@@ -404,7 +404,7 @@ def test_app_fetch_manifest_extensions_incorrect_enum_values(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
query = APP_FETCH_MANIFEST_MUTATION
manifest_url = "http://localhost:3000/configuration/manifest"
variables = {
@@ -464,7 +464,7 @@ def test_app_fetch_manifest_extensions_correct_url(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
query = APP_FETCH_MANIFEST_MUTATION
manifest_url = "http://localhost:3000/configuration/manifest"
variables = {
@@ -511,7 +511,7 @@ def test_app_fetch_manifest_extensions_incorrect_url(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
query = APP_FETCH_MANIFEST_MUTATION
manifest_url = "http://localhost:3000/configuration/manifest"
variables = {
@@ -564,7 +564,7 @@ def test_app_fetch_manifest_extensions_permission_out_of_scope(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
query = APP_FETCH_MANIFEST_MUTATION
manifest_url = "http://localhost:3000/configuration/manifest"
variables = {
@@ -605,7 +605,7 @@ def test_app_fetch_manifest_extensions_invalid_permission(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
query = APP_FETCH_MANIFEST_MUTATION
manifest_url = "http://localhost:3000/configuration/manifest"
variables = {
@@ -647,7 +647,7 @@ def test_app_fetch_manifest_with_extensions(
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
query = APP_FETCH_MANIFEST_MUTATION
variables = {
@@ -686,7 +686,7 @@ def test_app_fetch_manifest_with_required_saleor_version(
app_manifest["requiredSaleorVersion"] = required_saleor_version
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when
response = staff_api_client.post_graphql(
@@ -713,7 +713,7 @@ def test_app_fetch_manifest_with_invalid_required_saleor_version(
app_manifest["requiredSaleorVersion"] = required_saleor_version
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when
response = staff_api_client.post_graphql(
@@ -737,7 +737,7 @@ def test_app_fetch_manifest_with_author(
app_manifest["author"] = "Acme Ltd"
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when
response = staff_api_client.post_graphql(
@@ -760,7 +760,7 @@ def test_app_fetch_manifest_with_empty_author(
app_manifest["author"] = " "
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when
response = staff_api_client.post_graphql(
@@ -800,7 +800,7 @@ def test_app_fetch_manifest_with_brand_data(
app_manifest["brand"] = {"logo": {"default": logo_url}}
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
mock_fetch_icon_image = Mock(return_value=icon_image)
monkeypatch.setattr(
"saleor.app.installation_utils.fetch_icon_image", mock_fetch_icon_image
@@ -839,7 +839,7 @@ def test_app_fetch_manifest_with_invalid_brand_data(
app_manifest["brand"] = {"logo": {"default": "wrong-url.png"}}
mocked_get_response = Mock()
mocked_get_response.json.return_value = app_manifest
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))
# when
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.py
index 83867980b7..b2f95c66a0 100644
--- a/saleor/graphql/core/tests/test_file_validation.py
+++ b/saleor/graphql/core/tests/test_file_validation.py
@@ -5,6 +5,7 @@ import pytest
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image
+from requests_hardened import HTTPSession
from ....product.error_codes import ProductErrorCode
from ..validators.file import (
@@ -64,7 +65,8 @@ def test_validate_image_url_valid_image_response(monkeypatch):
valid_image_response_mock = Mock()
valid_image_response_mock.headers = {"content-type": "image/jpeg"}
monkeypatch.setattr(
- "saleor.graphql.core.validators.file.requests.head",
+ HTTPSession,
+ "request",
Mock(return_value=valid_image_response_mock),
)
field = "image"
@@ -85,7 +87,8 @@ def test_validate_image_url_invalid_mimetype_response(monkeypatch):
invalid_response_mock = Mock()
invalid_response_mock.headers = {"content-type": "application/json"}
monkeypatch.setattr(
- "saleor.graphql.core.validators.file.requests.head",
+ HTTPSession,
+ "request",
Mock(return_value=invalid_response_mock),
)
field = "image"
@@ -108,7 +111,8 @@ def test_validate_image_url_response_without_content_headers(monkeypatch):
invalid_response_mock = Mock()
invalid_response_mock.headers = {}
monkeypatch.setattr(
- "saleor.graphql.core.validators.file.requests.head",
+ HTTPSession,
+ "request",
Mock(return_value=invalid_response_mock),
)
field = "image"
diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.py
index e54aa53c51..c993245544 100644
--- a/saleor/graphql/core/validators/file.py
+++ b/saleor/graphql/core/validators/file.py
@@ -1,10 +1,10 @@
import mimetypes
import os
-import requests
from django.core.exceptions import ValidationError
from PIL import Image, UnidentifiedImageError
+from ....core.http_client import HTTPClient
from ....thumbnail import MIME_TYPE_TO_PIL_IDENTIFIER
from ..utils import add_hash_to_file_name
@@ -40,7 +40,7 @@ def validate_image_url(url: str, field_name: str, error_code: str) -> None:
Instead of the whole file, only the headers are fetched.
"""
- head = requests.head(url, timeout=30, allow_redirects=False)
+ head = HTTPClient.send_request("HEAD", url, timeout=30, allow_redirects=False)
header = head.headers
content_type = header.get("content-type")
if content_type is None or not is_supported_image_mimetype(content_type):
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index f208a5ea8c..f3e53ae62d 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -3,7 +3,6 @@ from datetime import datetime
import graphene
import pytz
-import requests
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db.models import F
@@ -11,6 +10,7 @@ from django.utils.text import slugify
from graphene.utils.str_converters import to_camel_case
from text_unidecode import unidecode
+from ....core.http_client import HTTPClient
from ....core.tracing import traced_atomic_transaction
from ....core.utils import prepare_unique_slug
from ....core.utils.editorjs import clean_editor_js
@@ -802,8 +802,8 @@ class ProductBulkCreate(BaseMutation):
media_url, "media_url", ProductBulkCreateErrorCode.INVALID.value
)
filename = get_filename_from_url(media_url)
- image_data = requests.get(
- media_url, stream=True, timeout=30, allow_redirects=False
+ image_data = HTTPClient.send_request(
+ "GET", media_url, stream=True, timeout=30, allow_redirects=False
)
image_data = File(image_data.raw, filename)
media_to_create.append(
diff --git a/saleor/graphql/product/mutations/product/product_media_create.py b/saleor/graphql/product/mutations/product/product_media_create.py
index 539c035da8..87776ba857 100644
--- a/saleor/graphql/product/mutations/product/product_media_create.py
+++ b/saleor/graphql/product/mutations/product/product_media_create.py
@@ -1,8 +1,8 @@
import graphene
-import requests
from django.core.exceptions import ValidationError
from django.core.files import File
+from .....core.http_client import HTTPClient
from .....core.utils.validators import get_oembed_data
from .....permission.enums import ProductPermissions
from .....product import ProductMediaTypes, models
@@ -110,8 +110,8 @@ class ProductMediaCreate(BaseMutation):
media_url, "media_url", ProductErrorCode.INVALID.value
)
filename = get_filename_from_url(media_url)
- image_data = requests.get(
- media_url, stream=True, timeout=30, allow_redirects=False
+ image_data = HTTPClient.send_request(
+ "GET", media_url, stream=True, timeout=30, allow_redirects=False
)
image_file = File(image_data.raw, filename)
media = product.media.create(
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index ba875b5863..38095663e3 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -17,6 +17,7 @@ from graphql import GraphQLDocument, get_default_backend
from graphql.error import GraphQLError, GraphQLSyntaxError
from graphql.execution import ExecutionResult
from jwt.exceptions import PyJWTError
+from requests_hardened.ip_filter import InvalidIPAddress
from .. import __version__ as saleor_version
from ..core.exceptions import PermissionDenied, ReadOnlyException
@@ -59,7 +60,13 @@ class GraphQLView(View):
middleware = None
root_value = None
- HANDLED_EXCEPTIONS = (GraphQLError, PyJWTError, ReadOnlyException, PermissionDenied)
+ HANDLED_EXCEPTIONS = (
+ GraphQLError,
+ PyJWTError,
+ ReadOnlyException,
+ PermissionDenied,
+ InvalidIPAddress,
+ )
def __init__(
self,
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
index efdcdda36d..dbe30b6c6e 100644
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py
@@ -6,6 +6,7 @@ import Adyen
import pytest
from django.core.exceptions import ValidationError
from requests.exceptions import ConnectTimeout, RequestException, SSLError
+from requests_hardened import HTTPSession
from .....plugins.models import PluginConfiguration
from .... import PaymentError, TransactionKind
@@ -604,7 +605,7 @@ def test_capture_payment(
assert response.transaction_id == "852610007697063J" # ID returned by Adyen
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.requests.post")
[email protected](HTTPSession, "request")
def test_validate_plugin_configuration_incorrect_certificate(
mocked_request, adyen_plugin
):
@@ -615,7 +616,7 @@ def test_validate_plugin_configuration_incorrect_certificate(
plugin.validate_plugin_configuration(configuration)
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.requests.post")
[email protected](HTTPSession, "request")
def test_validate_plugin_configuration_correct_cert(mocked_request, adyen_plugin):
plugin = adyen_plugin(apple_pay_cert="correct_cert")
mocked_request.side_effect = RequestException()
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py b/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
index 6b8e6f9b76..80b3fcb504 100644
--- a/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
+++ b/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
@@ -1,6 +1,7 @@
from unittest import mock
import pytest
+from requests_hardened import HTTPSession
from saleor.payment import PaymentError
from saleor.payment.gateways.adyen.utils.apple_pay import (
@@ -72,7 +73,7 @@ def test_validate_payment_data_for_apple_pay():
@mock.patch("saleor.payment.gateways.adyen.utils.apple_pay.NamedTemporaryFile")
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.requests.post")
[email protected](HTTPSession, "request")
def test_initialize_payment_for_apple_pay(mocked_request, mocked_tmp_file):
mocked_cert_file_name = "cert-file-name"
mocked_file = mock.MagicMock()
@@ -111,6 +112,7 @@ def test_initialize_payment_for_apple_pay(mocked_request, mocked_tmp_file):
}
mocked_request.assert_called_with(
+ "POST",
validation_url,
json=expected_data,
cert=mocked_cert_file_name,
@@ -119,7 +121,7 @@ def test_initialize_payment_for_apple_pay(mocked_request, mocked_tmp_file):
)
[email protected]("saleor.payment.gateways.adyen.utils.apple_pay.requests.post")
[email protected](HTTPSession, "request")
def test_initialize_payment_for_apple_pay_request_failed(mocked_request):
mocked_response = mock.Mock()
mocked_response.ok = False
diff --git a/saleor/payment/gateways/adyen/utils/apple_pay.py b/saleor/payment/gateways/adyen/utils/apple_pay.py
index fb4223dc68..83f1f05a25 100644
--- a/saleor/payment/gateways/adyen/utils/apple_pay.py
+++ b/saleor/payment/gateways/adyen/utils/apple_pay.py
@@ -5,6 +5,7 @@ from urllib.parse import urlsplit
import requests
+from .....core.http_client import HTTPClient
from .... import PaymentError
# https://developer.apple.com/documentation/apple_pay_on_the_web/
@@ -101,7 +102,8 @@ def make_request_to_initialize_apple_pay(
with NamedTemporaryFile() as f:
f.write(certificate.encode())
f.flush() # ensure all data written
- return requests.post(
+ return HTTPClient.send_request(
+ "POST",
validation_url,
json=request_data,
cert=f.name,
diff --git a/saleor/payment/gateways/authorize_net/__init__.py b/saleor/payment/gateways/authorize_net/__init__.py
index 027c49f948..1ede39b1f9 100644
--- a/saleor/payment/gateways/authorize_net/__init__.py
+++ b/saleor/payment/gateways/authorize_net/__init__.py
@@ -1,7 +1,6 @@
import json
from typing import Any, Dict, List, Optional, Tuple, Union
-import requests
from authorizenet import apicontractsv1
from authorizenet.apicontrollers import (
constants,
@@ -11,6 +10,7 @@ from authorizenet.apicontrollers import (
from lxml import etree
from lxml.objectify import ObjectifiedElement
+from ....core.http_client import HTTPClient
from ... import TransactionKind
from ...interface import (
CustomerSource,
@@ -38,7 +38,8 @@ def authenticate_test(
"merchantAuthentication": {"name": name, "transactionKey": transaction_key}
}
}
- response = requests.post(
+ response = HTTPClient.send_request(
+ "POST",
url,
json=data,
headers={"content-type": "application/json"},
diff --git a/saleor/payment/gateways/np_atobarai/api_helpers.py b/saleor/payment/gateways/np_atobarai/api_helpers.py
index aea54366f2..04d45fee6e 100644
--- a/saleor/payment/gateways/np_atobarai/api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -7,6 +7,7 @@ from django.utils import timezone
from posuto import Posuto
from requests.auth import HTTPBasicAuth
+from ....core.http_client import HTTPClient
from ....order.models import Order
from ... import PaymentError
from ...interface import AddressData, PaymentData, PaymentLineData, RefundData
@@ -50,9 +51,9 @@ def _request(
) -> requests.Response:
trace_name = f"np-atobarai.request.{path.lstrip('/')}"
with np_atobarai_opentracing_trace(trace_name):
- response = requests.request(
- method=method,
- url=get_url(config, path),
+ response = HTTPClient.send_request(
+ method,
+ get_url(config, path),
timeout=REQUEST_TIMEOUT,
json=json or {},
auth=HTTPBasicAuth(config.merchant_code, config.sp_code),
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api.py b/saleor/payment/gateways/np_atobarai/tests/test_api.py
index f6f140145f..633056237f 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_api.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api.py
@@ -5,6 +5,7 @@ from unittest.mock import ANY, Mock, patch
import pytest
import requests
from graphene import Node
+from requests_hardened import HTTPSession
from .... import PaymentError
from .. import PaymentStatus, api, const
@@ -19,7 +20,7 @@ from ..errors import (
from ..plugin import NPAtobaraiGatewayPlugin
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_refund_payment(
mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy
):
@@ -79,7 +80,7 @@ def test_refund_payment_payment_not_created(
assert not gateway_response.is_success
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_refund_payment_np_errors(
mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy
):
@@ -122,7 +123,7 @@ def test_refund_payment_no_payment(
assert excinfo.value.message == f"Payment with id {payment_id} does not exist."
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_refund_payment_partial_refund_change_transaction(
mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy
):
@@ -157,7 +158,7 @@ def test_refund_payment_partial_refund_change_transaction(
@patch("saleor.payment.gateways.np_atobarai.api.change_transaction")
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_refund_payment_partial_refund_reregister_transaction(
mocked_request,
mocked_change_transaction,
@@ -203,7 +204,7 @@ def test_refund_payment_partial_refund_reregister_transaction(
assert gateway_response.psp_reference == new_psp_reference
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_report_fulfillment(mocked_request, config, fulfillment, payment_dummy):
# given
psp_reference = "18121200001"
@@ -288,7 +289,7 @@ def test_report_fulfillment_no_tracking_number(
assert errors == [f"FR#{NO_TRACKING_NUMBER}"]
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_report_fulfillment_np_errors(
mocked_request, config, fulfillment, payment_dummy
):
@@ -314,7 +315,7 @@ def test_report_fulfillment_np_errors(
assert errors == [f"FR#{code}" for code in error_codes]
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_report_fulfillment_connection_errors(
mocked_request, config, fulfillment, payment_dummy, caplog
):
@@ -341,7 +342,7 @@ def test_report_fulfillment_connection_errors(
]
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_report_fulfillment_already_captured(
mocked_request, config, fulfillment, payment_dummy
):
@@ -490,7 +491,7 @@ def test_tracking_number_updated_no_payments(
assert caplog.records[0].message == ("No active payments for this order")
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_change_transaction_success(
mocked_request, config, payment_dummy, np_payment_data
):
@@ -521,7 +522,7 @@ def test_change_transaction_success(
@patch("saleor.payment.gateways.np_atobarai.api.cancel")
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_change_transaction_pending(
mocked_request, mocked_cancel, config, payment_dummy, np_payment_data
):
@@ -557,7 +558,7 @@ def test_change_transaction_pending(
assert payment_response.status == PaymentStatus.FAILED
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_change_transaction_post_fulfillment(
mocked_request, config, payment_dummy, np_payment_data
):
@@ -578,7 +579,7 @@ def test_change_transaction_post_fulfillment(
assert payment_response.status == PaymentStatus.FOR_REREGISTRATION
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_change_transaction_failed(
mocked_request, config, payment_dummy, np_payment_data
):
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
index 6f56f00289..7a385c420f 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
@@ -3,9 +3,10 @@ from unittest.mock import Mock, patch
import pytest
import requests
+from requests_hardened import HTTPSession
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_process_payment_authorized(
mocked_request, np_atobarai_plugin, np_payment_data
):
@@ -38,7 +39,7 @@ def test_process_payment_authorized(
assert not gateway_response.error
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_process_payment_refused(mocked_request, np_atobarai_plugin, np_payment_data):
# given
plugin = np_atobarai_plugin()
@@ -68,7 +69,7 @@ def test_process_payment_refused(mocked_request, np_atobarai_plugin, np_payment_
assert not gateway_response.is_success
-@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
def test_process_payment_error(mocked_request, np_atobarai_plugin, np_payment_data):
# given
plugin = np_atobarai_plugin()
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
index b5fa3be723..6408e063ba 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
@@ -4,11 +4,12 @@ from unittest.mock import Mock
import pytest
import requests
from django.core.exceptions import ValidationError
+from requests_hardened import HTTPSession
from ..plugin import NPAtobaraiGatewayPlugin
[email protected]("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
@pytest.mark.parametrize("status_code", [200, 400])
def test_validate_plugin_configuration_valid_credentials(
mocked_request, np_atobarai_plugin, status_code
@@ -22,7 +23,7 @@ def test_validate_plugin_configuration_valid_credentials(
# then: no exception
[email protected]("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
[email protected](HTTPSession, "request")
@pytest.mark.parametrize("status_code", [401, 403])
def test_validate_plugin_configuration_invalid_credentials(
mocked_request, np_atobarai_plugin, status_code
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index a193c32638..f8d25a2ac1 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -15,6 +15,7 @@ from requests.auth import HTTPBasicAuth
from ...account.models import Address
from ...checkout import base_calculations
from ...checkout.utils import is_shipping_required
+from ...core.http_client import HTTPClient
from ...core.taxes import TaxError
from ...discount import DiscountType, VoucherType
from ...order import base_calculations as base_order_calculations
@@ -97,7 +98,8 @@ def api_post_request(
response = None
try:
auth = HTTPBasicAuth(config.username_or_account, config.password_or_license)
- response = requests.post(
+ response = HTTPClient.send_request(
+ "POST",
url,
auth=auth,
data=json.dumps(data),
@@ -106,7 +108,7 @@ def api_post_request(
)
logger.debug("Hit to Avatax to calculate taxes %s", url)
json_response = response.json()
- if "error" in response: # type: ignore
+ if "error" in response:
logger.exception("Avatax response contains errors %s", json_response)
return json_response
except requests.exceptions.RequestException:
@@ -129,7 +131,9 @@ def api_get_request(
response = None
try:
auth = HTTPBasicAuth(username_or_account, password_or_license)
- response = requests.get(url, auth=auth, timeout=TIMEOUT, allow_redirects=False)
+ response = HTTPClient.send_request(
+ "GET", url, auth=auth, timeout=TIMEOUT, allow_redirects=False
+ )
json_response = response.json()
logger.debug("[GET] Hit to %s", url)
if "error" in json_response:
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index ef8c6ecf26..4d8001ac51 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -8,6 +8,7 @@ from django.core.exceptions import ValidationError
from django.test import override_settings
from prices import Money, TaxedMoney
from requests import RequestException
+from requests_hardened import HTTPSession
from ....account.models import Address
from ....checkout.fetch import (
@@ -4243,7 +4244,7 @@ def test_get_tax_code_from_object_meta(product, settings, plugin_configuration):
def test_api_get_request_handles_request_errors(product, monkeypatch, avatax_config):
mocked_response = Mock(side_effect=RequestException())
- monkeypatch.setattr("saleor.plugins.avatax.requests.get", mocked_response)
+ monkeypatch.setattr(HTTPSession, "request", mocked_response)
config = avatax_config
url = "https://www.avatax.api.com/some-get-path"
@@ -4258,7 +4259,7 @@ def test_api_get_request_handles_request_errors(product, monkeypatch, avatax_con
def test_api_get_request_handles_json_errors(product, monkeypatch, avatax_config):
mocked_response = Mock(side_effect=JSONDecodeError("", "", 0))
- monkeypatch.setattr("saleor.plugins.avatax.requests.get", mocked_response)
+ monkeypatch.setattr(HTTPSession, "request", mocked_response)
config = avatax_config
url = "https://www.avatax.api.com/some-get-path"
@@ -4273,7 +4274,7 @@ def test_api_get_request_handles_json_errors(product, monkeypatch, avatax_config
def test_api_post_request_handles_request_errors(product, monkeypatch, avatax_config):
mocked_response = Mock(side_effect=RequestException())
- monkeypatch.setattr("saleor.plugins.avatax.requests.post", mocked_response)
+ monkeypatch.setattr(HTTPSession, "request", mocked_response)
config = avatax_config
url = "https://www.avatax.api.com/some-get-path"
@@ -4286,7 +4287,7 @@ def test_api_post_request_handles_request_errors(product, monkeypatch, avatax_co
def test_api_post_request_handles_json_errors(product, monkeypatch, avatax_config):
mocked_response = Mock(side_effect=JSONDecodeError("", "", 0))
- monkeypatch.setattr("saleor.plugins.avatax.requests.post", mocked_response)
+ monkeypatch.setattr(HTTPSession, "request", mocked_response)
config = avatax_config
url = "https://www.avatax.api.com/some-get-path"
diff --git a/saleor/plugins/openid_connect/client.py b/saleor/plugins/openid_connect/client.py
new file mode 100644
index 0000000000..fc36048f13
--- /dev/null
+++ b/saleor/plugins/openid_connect/client.py
@@ -0,0 +1,12 @@
+from authlib.integrations import requests_client
+from requests_hardened import HTTPSession
+
+from ...core.http_client import HTTPConfig
+
+
+class OAuth2Client(HTTPSession, requests_client.OAuth2Session):
+ """Override the 3rd party OAuth client with our custom HTTP client."""
+
+ def __init__(self, **kwargs):
+ kwargs.setdefault("config", HTTPConfig)
+ super().__init__(**kwargs)
diff --git a/saleor/plugins/openid_connect/plugin.py b/saleor/plugins/openid_connect/plugin.py
index 91ff4858fc..9c5259d787 100644
--- a/saleor/plugins/openid_connect/plugin.py
+++ b/saleor/plugins/openid_connect/plugin.py
@@ -2,7 +2,6 @@ import logging
from typing import Optional, Tuple
from authlib.common.errors import AuthlibBaseError
-from authlib.integrations.requests_client import OAuth2Session
from django.core import signing
from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
@@ -24,6 +23,7 @@ from ..base_plugin import BasePlugin, ConfigurationTypeField, ExternalAccessToke
from ..error_codes import PluginErrorCode
from ..models import PluginConfiguration
from . import PLUGIN_ID
+from .client import OAuth2Client
from .const import SALEOR_STAFF_PERMISSION
from .dataclasses import OpenIDConnectConfig
from .exceptions import AuthenticationError
@@ -226,7 +226,7 @@ class OpenIDConnectPlugin(BasePlugin):
scope += f" {scope_permissions}"
if self.config.enable_refresh_token:
scope += " offline_access"
- return OAuth2Session(
+ return OAuth2Client(
client_id=self.config.client_id,
client_secret=self.config.client_secret,
scope=scope,
diff --git a/saleor/plugins/openid_connect/tests/test_ip_filtering.py b/saleor/plugins/openid_connect/tests/test_ip_filtering.py
new file mode 100644
index 0000000000..fc699528c0
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/test_ip_filtering.py
@@ -0,0 +1,22 @@
+import pytest
+from django.core import signing
+from requests_hardened.ip_filter import InvalidIPAddress
+
+from ....core.http_client import HTTPClient
+
+
+def test_rejects_private_ips(openid_plugin, id_token, rf, monkeypatch):
+ """
+ Ensure non-public IP addresses are rejected in HTTP calls in the OAuth plugin.
+ """
+ monkeypatch.setattr(HTTPClient.config, "ip_filter_enable", True)
+
+ plugin = openid_plugin(oauth_token_url="https://0.0.0.0")
+ oauth_payload = {
+ "code": 123,
+ "state": signing.dumps({"redirectUri": "https://example.com"}),
+ }
+
+ # Should reject the ip address used for the HTTP request.
+ with pytest.raises(InvalidIPAddress):
+ plugin.external_obtain_access_tokens(oauth_payload, rf.request(), None)
diff --git a/saleor/plugins/openid_connect/tests/test_plugin.py b/saleor/plugins/openid_connect/tests/test_plugin.py
index 13384fcc05..042a2c9f42 100644
--- a/saleor/plugins/openid_connect/tests/test_plugin.py
+++ b/saleor/plugins/openid_connect/tests/test_plugin.py
@@ -112,7 +112,7 @@ def test_external_refresh_from_cookie(
}
mocked_refresh_token = Mock(return_value=oauth_payload)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.refresh_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.refresh_token",
mocked_refresh_token,
)
@@ -165,7 +165,7 @@ def test_external_refresh_from_input(
}
mocked_refresh_token = Mock(return_value=oauth_payload)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.refresh_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.refresh_token",
mocked_refresh_token,
)
@@ -225,7 +225,7 @@ def test_external_refresh_with_scope_permissions(
}
mocked_refresh_token = Mock(return_value=oauth_payload)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.refresh_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.refresh_token",
mocked_refresh_token,
)
@@ -287,7 +287,7 @@ def test_external_refresh_raises_error_when_token_is_invalid(
}
mocked_refresh_token = Mock(return_value=oauth_payload)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.refresh_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.refresh_token",
mocked_refresh_token,
)
@@ -386,7 +386,7 @@ def test_external_obtain_access_tokens(
}
mocked_fetch_token = Mock(return_value=oauth_payload)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.fetch_token",
mocked_fetch_token,
)
redirect_uri = "http://localhost:3000/used-logged-in"
@@ -447,7 +447,7 @@ def test_external_obtain_access_tokens_with_permissions(
}
mocked_fetch_token = Mock(return_value=oauth_payload)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.fetch_token",
mocked_fetch_token,
)
redirect_uri = "http://localhost:3000/used-logged-in"
@@ -516,7 +516,7 @@ def test_external_obtain_access_tokens_with_saleor_staff(
}
mocked_fetch_token = Mock(return_value=oauth_payload)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.fetch_token",
mocked_fetch_token,
)
redirect_uri = "http://localhost:3000/used-logged-in"
@@ -587,7 +587,7 @@ def test_external_obtain_access_tokens_user_which_is_no_more_staff(
}
mocked_fetch_token = Mock(return_value=oauth_payload)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.fetch_token",
mocked_fetch_token,
)
redirect_uri = "http://localhost:3000/used-logged-in"
@@ -678,7 +678,7 @@ def test_external_obtain_access_tokens_fetch_token_raises_error(
plugin = openid_plugin(use_oauth_scope_permissions=True)
monkeypatch.setattr(
- "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ "saleor.plugins.openid_connect.client.OAuth2Client.fetch_token",
Mock(side_effect=OAuthError()),
)
diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.py
index 5c09ed8aea..ee7621f027 100644
--- a/saleor/plugins/openid_connect/tests/test_utils.py
+++ b/saleor/plugins/openid_connect/tests/test_utils.py
@@ -13,6 +13,7 @@ from django.core.exceptions import ValidationError
from django.utils import timezone
from freezegun import freeze_time
from requests import Response
+from requests_hardened import HTTPSession
from ....account.models import Group, User
from ....core.jwt import (
@@ -54,7 +55,7 @@ def test_fetch_jwks_raises_error(monkeypatch, error):
mocked_get = Mock()
mocked_get.side_effect = error
jwks_url = "http://localhost:3000/"
- monkeypatch.setattr("saleor.plugins.openid_connect.utils.requests.get", mocked_get)
+ monkeypatch.setattr(HTTPSession, "request", mocked_get)
with pytest.raises(AuthenticationError):
fetch_jwks(jwks_url)
@@ -196,9 +197,7 @@ def test_get_saleor_permissions_from_scope():
def test_get_user_info_raises_decode_error(monkeypatch):
response = Response()
response.status_code = 200
- monkeypatch.setattr(
- "saleor.plugins.openid_connect.utils.requests.get", Mock(return_value=response)
- )
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=response))
user_info = get_user_info("https://saleor.io/userinfo", "access_token")
assert user_info is None
@@ -207,9 +206,7 @@ def test_get_user_info_raises_decode_error(monkeypatch):
def test_get_user_info_raises_http_error(monkeypatch):
response = Response()
response.status_code = 500
- monkeypatch.setattr(
- "saleor.plugins.openid_connect.utils.requests.get", Mock(return_value=response)
- )
+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=response))
user_info = get_user_info("https://saleor.io/userinfo", "access_token")
assert user_info is None
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index 13c122c071..8761c81696 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -18,6 +18,7 @@ from jwt import PyJWTError
from ...account.models import Group, User
from ...account.utils import get_user_groups_permissions
+from ...core.http_client import HTTPClient
from ...core.jwt import (
JWT_ACCESS_TYPE,
JWT_OWNER_FIELD,
@@ -67,8 +68,8 @@ def fetch_jwks(jwks_url) -> Optional[dict]:
"""
response = None
try:
- response = requests.get(
- jwks_url, timeout=REQUEST_TIMEOUT, allow_redirects=False
+ response = HTTPClient.send_request(
+ "GET", jwks_url, timeout=REQUEST_TIMEOUT, allow_redirects=False
)
response.raise_for_status()
jwks = response.json()
@@ -121,7 +122,8 @@ def get_user_info_from_cache_or_fetch(
def get_user_info(user_info_url, access_token) -> Optional[dict]:
try:
- response = requests.get(
+ response = HTTPClient.send_request(
+ "GET",
user_info_url,
headers={"Authorization": f"Bearer {access_token}"},
timeout=REQUEST_TIMEOUT,
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index 9e1db7b41c..d48296db18 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -7,7 +7,6 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Ty
from urllib.parse import unquote, urlparse, urlunparse
import boto3
-import requests
from botocore.exceptions import ClientError
from celery import group
from celery.exceptions import MaxRetriesExceededError, Retry
@@ -17,10 +16,12 @@ from django.core.cache import cache
from django.urls import reverse
from google.cloud import pubsub_v1
from requests.exceptions import RequestException
+from requests_hardened.ip_filter import InvalidIPAddress
from ...app.headers import AppHeaders, DeprecatedAppHeaders
from ...celeryconf import app
from ...core import EventDeliveryStatus
+from ...core.http_client import HTTPClient
from ...core.models import EventDelivery, EventPayload
from ...core.tracing import webhooks_opentracing_trace
from ...core.utils import build_absolute_uri
@@ -406,7 +407,8 @@ def send_webhook_using_http(
headers.update(custom_headers)
try:
- response = requests.post(
+ response = HTTPClient.send_request(
+ "POST",
target_url,
data=message,
headers=headers,
@@ -415,19 +417,23 @@ def send_webhook_using_http(
)
except RequestException as e:
if e.response:
- result = WebhookResponse(
+ return WebhookResponse(
content=e.response.text,
status=EventDeliveryStatus.FAILED,
request_headers=headers,
response_headers=dict(e.response.headers),
response_status_code=e.response.status_code,
)
+
+ if isinstance(e, InvalidIPAddress):
+ message = "Invalid IP address"
else:
- result = WebhookResponse(
- content=str(e),
- status=EventDeliveryStatus.FAILED,
- request_headers=headers,
- )
+ message = str(e)
+ result = WebhookResponse(
+ content=message,
+ status=EventDeliveryStatus.FAILED,
+ request_headers=headers,
+ )
return result
return WebhookResponse(
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index e769dba422..5db6d899c9 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py
@@ -7,6 +7,7 @@ import pytest
from django.conf import settings
from django.contrib.sites.models import Site
from requests import RequestException, TooManyRedirects
+from requests_hardened import HTTPSession
from ....app.models import App
from ....core import EventDeliveryStatus
@@ -80,7 +81,7 @@ def test_trigger_webhook_sync_with_subscription(
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_send_webhook_request_sync_failed_attempt(
mock_post, mock_observability, app, event_delivery
):
@@ -112,7 +113,7 @@ def test_send_webhook_request_sync_failed_attempt(
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
@mock.patch("saleor.plugins.webhook.tasks.clear_successful_delivery")
def test_send_webhook_request_sync_successful_attempt(
mock_clear_delivery, mock_post, mock_observability, app, event_delivery
@@ -147,7 +148,7 @@ def test_send_webhook_request_sync_successful_attempt(
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.requests.post", side_effect=RequestException)
[email protected](HTTPSession, "request", side_effect=RequestException)
def test_send_webhook_request_sync_request_exception(
mock_post, mock_observability, app, event_delivery
):
@@ -179,7 +180,7 @@ def test_send_webhook_request_sync_request_exception(
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_send_webhook_request_sync_when_exception_with_response(
mock_post, mock_observability, app, event_delivery
):
@@ -200,7 +201,7 @@ def test_send_webhook_request_sync_when_exception_with_response(
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_send_webhook_request_sync_json_parsing_error(
mock_post, mock_observability, app, event_delivery
):
@@ -231,7 +232,7 @@ def test_send_webhook_request_sync_json_parsing_error(
mock_observability.assert_called_once_with(attempt)
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_send_webhook_request_with_proper_timeout(mock_post, event_delivery, app):
mock_post().text = '{"key": "response_text"}'
mock_post().headers = {"header_key": "header_val"}
diff --git a/saleor/plugins/webhook/tests/test_tasks.py b/saleor/plugins/webhook/tests/test_tasks.py
index 53a5a51c89..c9aec7df42 100644
--- a/saleor/plugins/webhook/tests/test_tasks.py
+++ b/saleor/plugins/webhook/tests/test_tasks.py
@@ -6,6 +6,7 @@ import pytest
from django.utils import timezone
from freezegun import freeze_time
from graphene import Node
+from requests_hardened import HTTPSession
from ....core import EventDeliveryStatus
from ....core.models import EventDelivery, EventPayload
@@ -162,7 +163,7 @@ def test_trigger_transaction_request_with_webhook_subscription(
@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_handle_transaction_request_task_with_only_psp_reference(
mocked_post_request,
transaction_item_generator,
@@ -217,6 +218,7 @@ def test_handle_transaction_request_task_with_only_psp_reference(
event.refresh_from_db()
assert event.psp_reference == expected_psp_reference
mocked_post_request.assert_called_once_with(
+ "POST",
target_url,
data=payload.encode("utf-8"),
headers=mock.ANY,
@@ -228,7 +230,7 @@ def test_handle_transaction_request_task_with_only_psp_reference(
@pytest.mark.parametrize("status_code", [500, 501, 510])
@freeze_time("2022-06-11 12:50")
@mock.patch("saleor.plugins.webhook.tasks.handle_webhook_retry")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_handle_transaction_request_task_with_server_error(
mocked_post_request,
mocked_webhook_retry,
@@ -284,7 +286,7 @@ def test_handle_transaction_request_task_with_server_error(
@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_handle_transaction_request_task_with_missing_psp_reference(
mocked_post_request,
transaction_item_created_by_app,
@@ -353,6 +355,7 @@ def test_handle_transaction_request_task_with_missing_psp_reference(
assert failure_event.amount_value == event.amount_value
assert failure_event.transaction_id == event.transaction_id
mocked_post_request.assert_called_once_with(
+ "POST",
target_url,
data=payload.encode("utf-8"),
headers=mock.ANY,
@@ -362,7 +365,7 @@ def test_handle_transaction_request_task_with_missing_psp_reference(
@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_handle_transaction_request_task_with_missing_required_event_field(
mocked_post_request,
transaction_item_created_by_app,
@@ -436,6 +439,7 @@ def test_handle_transaction_request_task_with_missing_required_event_field(
assert failure_event.amount_value == event.amount_value
assert failure_event.transaction_id == event.transaction_id
mocked_post_request.assert_called_once_with(
+ "POST",
target_url,
data=payload.encode("utf-8"),
headers=mock.ANY,
@@ -445,7 +449,7 @@ def test_handle_transaction_request_task_with_missing_required_event_field(
@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_handle_transaction_request_task_with_result_event(
mocked_post_request,
transaction_item_generator,
@@ -534,6 +538,7 @@ def test_handle_transaction_request_task_with_result_event(
assert success_event.message == event_cause
mocked_post_request.assert_called_once_with(
+ "POST",
target_url,
data=payload.encode("utf-8"),
headers=mock.ANY,
@@ -543,7 +548,7 @@ def test_handle_transaction_request_task_with_result_event(
@freeze_time("2022-06-11T17:50:00+00:00")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_handle_transaction_request_task_with_only_required_fields_for_result_event(
mocked_post_request,
transaction_item_generator,
@@ -626,6 +631,7 @@ def test_handle_transaction_request_task_with_only_required_fields_for_result_ev
assert success_event.message == ""
mocked_post_request.assert_called_once_with(
+ "POST",
target_url,
data=payload.encode("utf-8"),
headers=mock.ANY,
@@ -639,7 +645,7 @@ def test_handle_transaction_request_task_with_only_required_fields_for_result_ev
"saleor.payment.utils.recalculate_transaction_amounts",
wraps=recalculate_transaction_amounts,
)
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_handle_transaction_request_task_calls_recalculation_of_amounts(
mocked_post_request,
mocked_recalculation,
@@ -709,7 +715,7 @@ def test_handle_transaction_request_task_calls_recalculation_of_amounts(
@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_handle_transaction_request_task_with_available_actions(
mocked_post_request,
transaction_item_generator,
@@ -799,6 +805,7 @@ def test_handle_transaction_request_task_with_available_actions(
)
mocked_post_request.assert_called_once_with(
+ "POST",
target_url,
allow_redirects=False,
data=payload.encode("utf-8"),
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 5a5342526c..b2b2c8f5ce 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -18,6 +18,7 @@ from django.utils import timezone
from freezegun import freeze_time
from kombu.asynchronous.aws.sqs.connection import AsyncSQSConnection
from requests import RequestException
+from requests_hardened import HTTPSession
from .... import __version__
from ....account.notifications import (
@@ -1976,7 +1977,7 @@ def test_send_webhook_request_async_when_delivery_attempt_failed(
mocked_observability.assert_called_once_with(attempt, None)
[email protected]("saleor.plugins.webhook.tasks.requests.post", side_effect=RequestException)
[email protected](HTTPSession, "request", side_effect=RequestException)
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
def test_send_webhook_request_async_with_request_exception(
mocked_observability, mocked_post, event_delivery, webhook_response_failed
diff --git a/saleor/plugins/webhook/tests/test_webhook_ip_filtering.py b/saleor/plugins/webhook/tests/test_webhook_ip_filtering.py
new file mode 100644
index 0000000000..e9948a20bb
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_webhook_ip_filtering.py
@@ -0,0 +1,28 @@
+from ....core.http_client import HTTPClient
+from ....core.models import EventDeliveryAttempt
+from ..tasks import trigger_webhooks_async
+
+
+def test_rejects_private_ips(webhook, monkeypatch):
+ """
+ Ensure non-public IP addresses are rejected in HTTP calls in the webhook plugin.
+ """
+
+ # Enable IP filter
+ monkeypatch.setattr(HTTPClient.config, "ip_filter_enable", True)
+
+ # Configure webhook
+ webhook.target_url = "https://10.0.0.0/test"
+ webhook.save(update_fields=["target_url"])
+
+ assert (
+ not EventDeliveryAttempt.objects.exists()
+ ), "should not have any pre-existing attempts"
+
+ # Trigger the webhook
+ trigger_webhooks_async(data="", event_type="test", webhooks=[webhook])
+
+ # Should have rejected the ip address used in all attempts.
+ statuses = list(EventDeliveryAttempt.objects.values_list("status", "response"))
+ assert len(statuses) > 0
+ assert statuses == [("failed", "Invalid IP address")] * len(statuses)
diff --git a/saleor/plugins/webhook/tests/test_webhook_protocols.py b/saleor/plugins/webhook/tests/test_webhook_protocols.py
index 62678b59e2..85b379ee18 100644
--- a/saleor/plugins/webhook/tests/test_webhook_protocols.py
+++ b/saleor/plugins/webhook/tests/test_webhook_protocols.py
@@ -6,6 +6,7 @@ import jwt
import pytest
from django.core.serializers import serialize
from google.cloud.pubsub_v1 import PublisherClient
+from requests_hardened import HTTPSession
from ....webhook.event_types import WebhookEventAsyncType
from ...webhook import signature_for_payload
@@ -212,7 +213,7 @@ def test_trigger_webhooks_with_google_pub_sub_and_secret_key(
)
-@patch("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_trigger_webhooks_with_http(
mock_request,
webhook,
@@ -254,6 +255,7 @@ def test_trigger_webhooks_with_http(
}
mock_request.assert_called_once_with(
+ "POST",
webhook.target_url,
data=bytes(expected_data, "utf-8"),
headers=expected_headers,
@@ -262,7 +264,7 @@ def test_trigger_webhooks_with_http(
)
-@patch("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_trigger_webhooks_with_http_and_secret_key(
mock_request, webhook, order_with_lines, permission_manage_orders
):
@@ -299,6 +301,7 @@ def test_trigger_webhooks_with_http_and_secret_key(
}
mock_request.assert_called_once_with(
+ "POST",
webhook.target_url,
data=bytes(expected_data, "utf-8"),
headers=expected_headers,
@@ -307,7 +310,7 @@ def test_trigger_webhooks_with_http_and_secret_key(
)
-@patch("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_trigger_webhooks_with_http_and_secret_key_as_empty_string(
mock_request, webhook, order_with_lines, permission_manage_orders
):
@@ -348,6 +351,7 @@ def test_trigger_webhooks_with_http_and_secret_key_as_empty_string(
assert signature_headers["alg"] == "RS256"
mock_request.assert_called_once_with(
+ "POST",
webhook.target_url,
data=bytes(expected_data, "utf-8"),
headers=expected_headers,
@@ -356,7 +360,7 @@ def test_trigger_webhooks_with_http_and_secret_key_as_empty_string(
)
-@patch("saleor.plugins.webhook.tasks.requests.post")
[email protected](HTTPSession, "request")
def test_trigger_webhooks_with_http_and_custom_headers(
mock_request, webhook, order_with_lines, permission_manage_orders
):
diff --git a/saleor/settings.py b/saleor/settings.py
index 6bfdcb4d55..e054806d42 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -735,6 +735,17 @@ PLUGINS = BUILTIN_PLUGINS + EXTERNAL_PLUGINS
WEBHOOK_TIMEOUT = 10
WEBHOOK_SYNC_TIMEOUT = 20
+# When `True`, HTTP requests made from arbitrary URLs will be rejected (e.g., webhooks).
+# if they try to access private IP address ranges, and loopback ranges (unless
+# `HTTP_IP_FILTER_ALLOW_LOOPBACK_IPS=False`).
+HTTP_IP_FILTER_ENABLED: bool = get_bool_from_env("HTTP_IP_FILTER_ENABLED", True)
+
+# When `False` it rejects loopback IPs during external calls.
+# Refer to `HTTP_IP_FILTER_ENABLED` for more details.
+HTTP_IP_FILTER_ALLOW_LOOPBACK_IPS: bool = get_bool_from_env(
+ "HTTP_IP_FILTER_ALLOW_LOOPBACK_IPS", False
+)
+
# Since we split checkout complete logic into two separate transactions, in order to
# mimic stock lock, we apply short reservation for the stocks. The value represents
# time of the reservation in seconds.
diff --git a/saleor/tests/settings.py b/saleor/tests/settings.py
index 24711dedf3..21b3cf816d 100644
--- a/saleor/tests/settings.py
+++ b/saleor/tests/settings.py
@@ -85,3 +85,6 @@ FdkAmFzQhgLtnEtnb+eBI7DNOJEuPLD52Jwnq2pGnJ/LxlqjjWJ5FsQQVSoDHGfM
-----END RSA PRIVATE KEY-----"""
DATABASE_CONNECTION_REPLICA_NAME = DATABASE_CONNECTION_DEFAULT_NAME # noqa: F405
+
+HTTP_IP_FILTER_ENABLED = False
+HTTP_IP_FILTER_ALLOW_LOOPBACK_IPS = True
diff --git a/setup.cfg b/setup.cfg
index 47acf2c4f9..39e35ac7a4 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -60,6 +60,8 @@ ignore_missing_imports = True
pretty = True
show_column_numbers = True
show_error_codes = True
+show_error_context = True
+show_traceback = True
warn_redundant_casts = True
warn_unused_ignores = True