diff --git a/api/app/settings/common.py b/api/app/settings/common.py index 3f6248bea5a2..abbd9a1cb700 100644 --- a/api/app/settings/common.py +++ b/api/app/settings/common.py @@ -75,6 +75,8 @@ CSRF_TRUSTED_ORIGINS: list[str] = env.list("DJANGO_CSRF_TRUSTED_ORIGINS", default=[]) +SSRF_ALLOWED_HOSTS: list[str] = env.list("SSRF_ALLOWED_HOSTS", default=[]) + INTERNAL_IPS = ["127.0.0.1"] # Application definition diff --git a/api/core/validators.py b/api/core/validators.py index 8a4d973e021a..24d903d43616 100644 --- a/api/core/validators.py +++ b/api/core/validators.py @@ -1,6 +1,8 @@ from urllib.parse import urlparse +from django.conf import settings from django.core.exceptions import ValidationError +from django.http.request import validate_host from core.network import is_internal_address @@ -19,12 +21,24 @@ def validate_http_url_scheme(value: str) -> None: raise ValidationError("Enter a valid http(s) URL.", code="invalid") +def _normalise_allowed_host(pattern: str) -> str: + if pattern.startswith("*."): + pattern = pattern[1:] + return pattern.strip("[]") + + def validate_no_internal_address(value: str) -> None: """ Reject URLs that target, or resolve to, an internal or private network address, preventing Server-Side Request Forgery (SSRF). + + Hosts in `settings.SSRF_ALLOWED_HOSTS` are exempt. """ - if is_internal_address(urlparse(value).hostname or ""): + hostname = urlparse(value).hostname or "" + allowed_hosts = map(_normalise_allowed_host, settings.SSRF_ALLOWED_HOSTS) + if validate_host(hostname, allowed_hosts): + return + if is_internal_address(hostname): raise ValidationError( "URLs must not target internal or private network addresses.", code="internal_address", diff --git a/api/tests/unit/core/test_validators.py b/api/tests/unit/core/test_validators.py new file mode 100644 index 000000000000..5eafb0306bda --- /dev/null +++ b/api/tests/unit/core/test_validators.py @@ -0,0 +1,57 @@ +import socket + +import pytest +from django.core.exceptions import ValidationError +from pytest_django.fixtures import SettingsWrapper +from pytest_mock import MockerFixture + +from core.validators import validate_no_internal_address + + +@pytest.mark.parametrize( + "url, allowed_host", + [ + ("http://hooks.internal.example.com/", "hooks.internal.example.com"), + ("http://hooks.internal.example.com/", ".internal.example.com"), + ("http://hooks.internal.example.com/", "*.internal.example.com"), + ("http://10.0.0.5/", "10.0.0.5"), + ("http://[fd00::1]/", "[fd00::1]"), + ("http://127.0.0.1/", "*"), + ], +) +def test_validate_no_internal_address__host_allowed__does_not_raise( + settings: SettingsWrapper, + mocker: MockerFixture, + url: str, + allowed_host: str, +) -> None: + # Given + settings.SSRF_ALLOWED_HOSTS = [allowed_host] + mocker.patch( + "core.network.socket.getaddrinfo", + return_value=[(socket.AF_INET, None, None, None, ("10.0.0.5", 0))], + ) + + # When / Then + validate_no_internal_address(url) + + +@pytest.mark.parametrize("allowed_hosts", [[], ["other.example.com"]]) +def test_validate_no_internal_address__host_not_allowed__raises_validation_error( + settings: SettingsWrapper, + mocker: MockerFixture, + allowed_hosts: list[str], +) -> None: + # Given + settings.SSRF_ALLOWED_HOSTS = allowed_hosts + mocker.patch( + "core.network.socket.getaddrinfo", + return_value=[(socket.AF_INET, None, None, None, ("10.0.0.5", 0))], + ) + + # When + with pytest.raises(ValidationError) as exc_info: + validate_no_internal_address("http://hooks.internal.example.com/") + + # Then + assert exc_info.value.code == "internal_address" diff --git a/api/tests/unit/integrations/webhook/test_unit_webhook_views.py b/api/tests/unit/integrations/webhook/test_unit_webhook_views.py index 64bda29e22da..fd06d87d1a06 100644 --- a/api/tests/unit/integrations/webhook/test_unit_webhook_views.py +++ b/api/tests/unit/integrations/webhook/test_unit_webhook_views.py @@ -1,8 +1,11 @@ import json from django.urls import reverse +from pytest_django.fixtures import SettingsWrapper from rest_framework import status +from rest_framework.test import APIClient +from environments.models import Environment from integrations.webhook.models import WebhookConfiguration valid_webhook_url = "http://my.webhook.com/webhooks" @@ -138,3 +141,28 @@ def test_create_webhook_config__private_ip_url__returns_400( # type: ignore[no- # Then assert response.status_code == status.HTTP_400_BAD_REQUEST assert not WebhookConfiguration.objects.filter(environment=environment).exists() + + +def test_create_webhook_config__private_ip_in_ssrf_allowed_hosts__returns_201( + admin_client: APIClient, + environment: Environment, + settings: SettingsWrapper, +) -> None: + # Given + settings.SSRF_ALLOWED_HOSTS = ["127.0.0.1"] + url = reverse( + "api-v1:environments:integrations-webhook-list", + args=[environment.api_key], + ) + data = {"url": "http://127.0.0.1/webhooks", "secret": "random_secret"} + + # When + response = admin_client.post( + url, + data=json.dumps(data), + content_type="application/json", + ) + + # Then + assert response.status_code == status.HTTP_201_CREATED + assert WebhookConfiguration.objects.filter(environment=environment).exists() diff --git a/docs/docs/deployment-self-hosting/core-configuration/environment-variables.md b/docs/docs/deployment-self-hosting/core-configuration/environment-variables.md index 51c0e63d2e44..8a5f8f4d3164 100644 --- a/docs/docs/deployment-self-hosting/core-configuration/environment-variables.md +++ b/docs/docs/deployment-self-hosting/core-configuration/environment-variables.md @@ -13,6 +13,8 @@ relevant section below for more details. ## API Environment Variables - `DJANGO_ALLOWED_HOSTS`: Comma-separated list of domains that can access the API. Alternatively `*` to allow any. +- `SSRF_ALLOWED_HOSTS`: Comma-separated list of trusted hosts that webhook and integration URLs can target, even if they + resolve to a private network address, e.g. `.internal.example.com`. - `DATABASE_URL`: The URL of your PostgreSQL database. Both `postgres://` and `postgresql://` schemas are supported. - `DJANGO_DB_CONN_MAX_AGE`: Lifetime of a database connection, in seconds. Defaults to `60`. Set to `-1` to close the connection at the end of each request (Django's default behaviour). See