Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions api/app/settings/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 15 additions & 1 deletion api/core/validators.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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",
Expand Down
57 changes: 57 additions & 0 deletions api/tests/unit/core/test_validators.py
Original file line number Diff line number Diff line change
@@ -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"
28 changes: 28 additions & 0 deletions api/tests/unit/integrations/webhook/test_unit_webhook_views.py
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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()
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Security & Privacy · Quick win

Document the subdomain scope of a leading-dot entry.

A leading dot trusts the domain and all its subdomains. For example, .internal.example.com also trusts every name under internal.example.com. An operator who only intends to trust internal.example.com can therefore trust more hosts than planned. A subdomain under that domain that resolves to a private address can then be used as a webhook or integration target. The practical risk depends on who can create names under the trusted domain.

State this scope in the entry, and show the exact-host form for narrow access. A value without a leading dot matches only that host.

Suggested documentation change

--- "a/docs/docs/deployment-self-hosting/core-configuration/environment-variables.md"
+++ "b/docs/docs/deployment-self-hosting/core-configuration/environment-variables.md"
@@ -14,7 +14,8 @@
 
 - `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`.
+  A leading dot trusts the domain and all its subdomains. To trust only one host, omit the dot, 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

Scope reference: Django validate_host

Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
resolve to a private network address, e.g. `.internal.example.com`.
resolve to a private network address, e.g. `.internal.example.com`.
A leading dot trusts the domain and all its subdomains. To trust only one host, omit the dot, e.g. `internal.example.com`.
Tools

LanguageTool

[typographical] ~17-~17: Two consecutive dots
Context: ...solve to a private network address, e.g. .internal.example.com. - DATABASE_URL: The URL of your Postg...

(DOUBLE_PUNCTUATION)

- `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
Expand Down
Loading