Skip to content

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

Strict connection timeout settings (#14148)

Tomasz Szymański4a0bcd768f6d
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index 0f3ce560f8..3375bc9a5d 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -30,7 +30,6 @@ from .manifest_validations import clean_manifest_data
from .models import App, AppExtension, AppInstallation
from .types import AppExtensionTarget, AppType
-REQUEST_TIMEOUT = 20
MAX_ICON_FILE_SIZE = 1024 * 1024 * 10 # 10MB
logger = logging.getLogger(__name__)
@@ -70,14 +69,16 @@ def send_app_token(target_url: str, token: str):
target_url,
json=json_data,
headers=headers,
- timeout=REQUEST_TIMEOUT,
allow_redirects=False,
)
validate_app_install_response(response)
def fetch_icon_image(
- url: str, *, max_file_size=MAX_ICON_FILE_SIZE, timeout=REQUEST_TIMEOUT
+ url: str,
+ *,
+ max_file_size=MAX_ICON_FILE_SIZE,
+ timeout=settings.COMMON_REQUESTS_TIMEOUT
) -> File:
filename = get_filename_from_url(url)
size_error_msg = f"File too big. Maximal icon image file size is {max_file_size}."
@@ -101,7 +102,8 @@ def fetch_icon_image(
content.write(chunk)
if content.tell() > max_file_size:
raise ValidationError(size_error_msg, code=code)
- if (time.monotonic() - fetch_start) > timeout:
+ timeout_in_secs = sum(timeout)
+ if (time.monotonic() - fetch_start) > timeout_in_secs:
raise ValidationError(
"Timeout occurred while reading image file.",
code=AppErrorCode.MANIFEST_URL_CANT_CONNECT.value,
@@ -116,7 +118,7 @@ def fetch_icon_image(
return image_file
-def fetch_brand_data(manifest_data, timeout=REQUEST_TIMEOUT):
+def fetch_brand_data(manifest_data, timeout=settings.COMMON_REQUESTS_TIMEOUT):
brand_data = manifest_data.get("brand")
if not brand_data:
return None
@@ -190,7 +192,7 @@ def fetch_brand_data_async(
)
-def fetch_manifest(manifest_url: str, timeout=REQUEST_TIMEOUT):
+def fetch_manifest(manifest_url: str, timeout=settings.COMMON_REQUESTS_TIMEOUT):
headers = {AppHeaders.SCHEMA_VERSION: schema_version}
response = HTTPClient.send_request(
"GET", manifest_url, headers=headers, timeout=timeout, allow_redirects=False
diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.py
index 8155b0c502..5607c06d37 100644
--- a/saleor/app/management/commands/create_app.py
+++ b/saleor/app/management/commands/create_app.py
@@ -56,7 +56,6 @@ class Command(BaseCommand):
target_url,
json=data,
headers=headers,
- timeout=15,
allow_redirects=False,
)
except RequestException as e:
diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.py
index 7ec4469876..89eb868ea3 100644
--- a/saleor/app/tests/test_app_commands.py
+++ b/saleor/app/tests/test_app_commands.py
@@ -87,7 +87,6 @@ def test_creates_app_from_manifest_sends_token(monkeypatch, app_manifest):
"Saleor-Schema-Version": schema_version,
},
json={"auth_token": ANY},
- timeout=ANY,
allow_redirects=False,
)
@@ -155,6 +154,5 @@ def test_sends_data_to_target_url(monkeypatch):
"Saleor-Schema-Version": schema_version,
},
json={"auth_token": ANY},
- timeout=ANY,
allow_redirects=False,
)
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index 77873d0c49..20459170a4 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -96,7 +96,6 @@ def test_install_app_created_app(
"Saleor-Schema-Version": schema_version,
},
json={"auth_token": ANY},
- timeout=ANY,
allow_redirects=False,
)
assert App.objects.get().id == app.id
diff --git a/saleor/core/http_client.py b/saleor/core/http_client.py
index e919f2e2f2..b1c7a3e3cb 100644
--- a/saleor/core/http_client.py
+++ b/saleor/core/http_client.py
@@ -5,7 +5,7 @@ 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),
+ default_timeout=settings.COMMON_REQUESTS_TIMEOUT,
)
HTTPClient = requests_hardened.Manager(HTTPConfig)
diff --git a/saleor/graphql/app/mutations/app_fetch_manifest.py b/saleor/graphql/app/mutations/app_fetch_manifest.py
index 7298ee6b3b..1008c2ad0f 100644
--- a/saleor/graphql/app/mutations/app_fetch_manifest.py
+++ b/saleor/graphql/app/mutations/app_fetch_manifest.py
@@ -1,5 +1,6 @@
import graphene
import requests
+from django.conf import settings
from django.core.exceptions import ValidationError
from ....app.error_codes import AppErrorCode
@@ -13,8 +14,6 @@ from ...core.mutations import BaseMutation
from ...core.types import AppError
from ..types import Manifest
-FETCH_BRAND_DATA_TIMEOUT = 5
-
class AppFetchManifest(BaseMutation):
manifest = graphene.Field(Manifest, description="The validated manifest.")
@@ -83,8 +82,10 @@ class AppFetchManifest(BaseMutation):
@classmethod
def clean_manifest_data(cls, info, manifest_data):
clean_manifest_data(manifest_data)
+ # Brand data is not essential for the mutation, so there is a short,
+ # custom timeout instead of Saleor's default.
manifest_data["brand"] = fetch_brand_data(
- manifest_data, timeout=FETCH_BRAND_DATA_TIMEOUT
+ manifest_data, timeout=(settings.REQUESTS_CONN_EST_TIMEOUT, 5)
)
manifest_data["permissions"] = [
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 79d9838880..f5f416ad38 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -12,7 +12,6 @@ from .....app.error_codes import AppErrorCode
from .....thumbnail import IconThumbnailFormat
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import AppExtensionMountEnum, AppExtensionTargetEnum
-from ...mutations.app_fetch_manifest import FETCH_BRAND_DATA_TIMEOUT
APP_FETCH_MANIFEST_MUTATION = """
mutation AppFetchManifest(
@@ -818,9 +817,7 @@ def test_app_fetch_manifest_with_brand_data(
)
# then
- mock_fetch_icon_image.assert_called_once_with(
- logo_url, timeout=FETCH_BRAND_DATA_TIMEOUT
- )
+ mock_fetch_icon_image.assert_called_once_with(logo_url, timeout=ANY)
content = get_graphql_content(response)
manifest = content["data"]["appFetchManifest"]["manifest"]
assert len(content["data"]["appFetchManifest"]["errors"]) == 0
diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.py
index c993245544..318b65981c 100644
--- a/saleor/graphql/core/validators/file.py
+++ b/saleor/graphql/core/validators/file.py
@@ -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 = HTTPClient.send_request("HEAD", url, timeout=30, allow_redirects=False)
+ head = HTTPClient.send_request("HEAD", url, 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/mutations/product/product_media_create.py b/saleor/graphql/product/mutations/product/product_media_create.py
index 87776ba857..eebde0fa8b 100644
--- a/saleor/graphql/product/mutations/product/product_media_create.py
+++ b/saleor/graphql/product/mutations/product/product_media_create.py
@@ -111,7 +111,7 @@ class ProductMediaCreate(BaseMutation):
)
filename = get_filename_from_url(media_url)
image_data = HTTPClient.send_request(
- "GET", media_url, stream=True, timeout=30, allow_redirects=False
+ "GET", media_url, stream=True, allow_redirects=False
)
image_file = File(image_data.raw, filename)
media = product.media.create(
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 80b3fcb504..5f073e1894 100644
--- a/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
+++ b/saleor/payment/gateways/adyen/tests/utils/test_apple_pay.py
@@ -116,7 +116,6 @@ def test_initialize_payment_for_apple_pay(mocked_request, mocked_tmp_file):
validation_url,
json=expected_data,
cert=mocked_cert_file_name,
- timeout=30,
allow_redirects=False,
)
diff --git a/saleor/payment/gateways/adyen/utils/apple_pay.py b/saleor/payment/gateways/adyen/utils/apple_pay.py
index 83f1f05a25..66fc666fb6 100644
--- a/saleor/payment/gateways/adyen/utils/apple_pay.py
+++ b/saleor/payment/gateways/adyen/utils/apple_pay.py
@@ -107,7 +107,6 @@ def make_request_to_initialize_apple_pay(
validation_url,
json=request_data,
cert=f.name,
- timeout=30,
allow_redirects=False,
)
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index e926f152cc..0dfdd74817 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -40,7 +40,10 @@ logger = logging.getLogger(__name__)
FAILED_STATUSES = ["refused", "error", "cancelled"]
PENDING_STATUSES = ["pending", "received"]
AUTH_STATUS = "authorised"
-HTTP_TIMEOUT = 20 # in seconds
+
+# we'd like shorter timeout than default 30s for Adyen client,
+# library doesn't allow to set connection establ. timeout
+HTTP_TIMEOUT = 20
def initialize_adyen_client(config: GatewayConfig) -> Adyen.Adyen:
diff --git a/saleor/payment/gateways/authorize_net/__init__.py b/saleor/payment/gateways/authorize_net/__init__.py
index 1ede39b1f9..a8ebd514ad 100644
--- a/saleor/payment/gateways/authorize_net/__init__.py
+++ b/saleor/payment/gateways/authorize_net/__init__.py
@@ -43,7 +43,6 @@ def authenticate_test(
url,
json=data,
headers={"content-type": "application/json"},
- timeout=30,
allow_redirects=False,
)
# Response content is utf-8-sig, which requires usage of json.loads
diff --git a/saleor/payment/gateways/np_atobarai/api_helpers.py b/saleor/payment/gateways/np_atobarai/api_helpers.py
index b17003ca83..e27734c8c7 100644
--- a/saleor/payment/gateways/np_atobarai/api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -3,6 +3,7 @@ from decimal import Decimal
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
import requests
+from django.conf import settings
from django.utils import timezone
from posuto import Posuto
from requests.auth import HTTPBasicAuth
@@ -54,7 +55,7 @@ def _request(
response = HTTPClient.send_request(
method,
get_url(config, path),
- timeout=REQUEST_TIMEOUT,
+ timeout=(settings.REQUESTS_CONN_EST_TIMEOUT, REQUEST_TIMEOUT),
json=json or {},
auth=HTTPBasicAuth(config.merchant_code, config.sp_code),
headers={"X-NP-Terminal-Id": config.terminal_id},
diff --git a/saleor/payment/gateways/np_atobarai/const.py b/saleor/payment/gateways/np_atobarai/const.py
index 5a8197315a..cd940f3dc3 100644
--- a/saleor/payment/gateways/np_atobarai/const.py
+++ b/saleor/payment/gateways/np_atobarai/const.py
@@ -1,8 +1,8 @@
-# This integration is currently supporting the settlement type 02 - NP Atobarai
+# This integration is currently supporting the settlement type 02 - NP Atobarai.
NP_ATOBARAI = "02"
NP_ATOBARAI_WIZ = "03"
-# NetProtections recommends a timeout of around 30s
+# Custom timeout, as NetProtections recommends a timeout of around 30s.
REQUEST_TIMEOUT = 30
NP_PLUGIN_ID = "saleor.payments.np-atobarai"
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index f8d25a2ac1..4d89214a86 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -39,7 +39,6 @@ CACHE_TIME = 60 * 60 # 1 hour
TAX_CODES_CACHE_TIME = 60 * 60 * 24 * 7 # 7 days
CACHE_KEY = "avatax_request_id_"
TAX_CODES_CACHE_KEY = "avatax_tax_codes_cache_key"
-TIMEOUT = 10 # API HTTP Requests Timeout
# Common discount code use to apply discount on order
COMMON_DISCOUNT_VOUCHER_CODE = "OD010000"
@@ -103,7 +102,6 @@ def api_post_request(
url,
auth=auth,
data=json.dumps(data),
- timeout=TIMEOUT,
allow_redirects=False,
)
logger.debug("Hit to Avatax to calculate taxes %s", url)
@@ -131,9 +129,7 @@ def api_get_request(
response = None
try:
auth = HTTPBasicAuth(username_or_account, password_or_license)
- response = HTTPClient.send_request(
- "GET", url, auth=auth, timeout=TIMEOUT, allow_redirects=False
- )
+ response = HTTPClient.send_request("GET", url, auth=auth, allow_redirects=False)
json_response = response.json()
logger.debug("[GET] Hit to %s", url)
if "error" in json_response:
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index 0c293c6717..5872626287 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -50,8 +50,6 @@ JWKS_KEY = "oauth_jwks"
JWKS_CACHE_TIME = 60 * 60 # 1 hour
USER_INFO_DEFAULT_CACHE_TIME = 60 * 60 # 1 hour
-REQUEST_TIMEOUT = 5
-
OAUTH_TOKEN_REFRESH_FIELD = "oauth_refresh_token"
CSRF_FIELD = "csrf_token"
@@ -69,9 +67,7 @@ def fetch_jwks(jwks_url) -> Optional[dict]:
"""
response = None
try:
- response = HTTPClient.send_request(
- "GET", jwks_url, timeout=REQUEST_TIMEOUT, allow_redirects=False
- )
+ response = HTTPClient.send_request("GET", jwks_url, allow_redirects=False)
response.raise_for_status()
jwks = response.json()
except requests.exceptions.RequestException:
@@ -127,7 +123,6 @@ def get_user_info(user_info_url, access_token) -> Optional[dict]:
"GET",
user_info_url,
headers={"Authorization": f"Bearer {access_token}"},
- timeout=REQUEST_TIMEOUT,
allow_redirects=False,
)
response.raise_for_status()
diff --git a/saleor/settings.py b/saleor/settings.py
index 6054ae282c..d99bfb6cfe 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -738,10 +738,16 @@ for entry_point in installed_plugins:
PLUGINS = BUILTIN_PLUGINS + EXTERNAL_PLUGINS
+# Default timeout (sec) for establishing a connection when performing external requests.
+REQUESTS_CONN_EST_TIMEOUT = 2
+
+# Default timeout for external requests.
+COMMON_REQUESTS_TIMEOUT = (REQUESTS_CONN_EST_TIMEOUT, 18)
+
# Timeouts for webhook requests. Sync webhooks (eg. payment webhook) need more time
# for getting response from the server.
WEBHOOK_TIMEOUT = 10
-WEBHOOK_SYNC_TIMEOUT = 20
+WEBHOOK_SYNC_TIMEOUT = COMMON_REQUESTS_TIMEOUT
# 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