fix: harden server-initiated HTTP against SSRF and DNS rebinding (#7914)

Co-authored-by: Michael Genson <genson.michael@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-09-04 14:54:55 -05:00
1 parent cb32b6249f
commit fb221afa25
14 files changed
+769 -185

No files matched your search

@@ -30,6 +30,8 @@
| SECURITY_MAX_LOGIN_ATTEMPTS | 5 | Maximum times a user can provide an invalid password before their account is locked |
| SECURITY_USER_LOCKOUT_TIME | 24 | Time in hours for how long a users account is locked |
| ALLOWED_IFRAME_HOSTS | `""` | Comma-separated extra hostnames allowed as `<iframe>` sources in recipe content. Extends the built-in list of trusted video providers (YouTube, Vimeo). Subdomains are included automatically. Only `https` sources are permitted. Adding hosts here opts into rendering embeds from those origins to all viewers, including the public, so add only origins you trust. |
| HTTP_ALLOW_LIST | `""` | Comma-separated hosts or CIDRs that server-initiated requests (recipe scraping, webhooks, recipe actions, OIDC profile images) may reach even when they resolve to an otherwise-blocked private/internal address. Use to allow a known internal server. |
| HTTP_DISALLOW_LIST | `""` | Comma-separated hosts or CIDRs that server-initiated requests may never reach, even if public. Takes precedence over `HTTP_ALLOW_LIST`. |
### Database
@@ -0,0 +1,88 @@
<template>
<div>
<p>
Mealie now checks where its own outgoing requests are going. Anything the server fetches on your
behalf, such as importing a recipe from a URL, downloading a recipe image, sending a webhook, or
running a recipe action, is only allowed to reach addresses on the public internet.
</p>
<p>
This protects your network: without it, someone could use one of those features to make your Mealie
server reach devices it can see but they can't.
</p>
<div v-if="user?.admin">
<hr class="mt-2 mb-4">
<p>
Webhooks and recipe actions were not checked before, and the checks on recipe imports were
narrower than they are now. If any of these pointed at something on your own network, they will
stop working after this update.
</p>
<div class="mb-2">
<p class="mb-1">
Requests are now refused when the target resolves to:
</p>
<ul class="ml-6">
<li>a private, loopback, or link-local address, including the cloud metadata endpoint</li>
<li>
the carrier-grade NAT range <code>100.64.0.0/10</code>. This one is worth noting, because it
is the range <strong>Tailscale</strong> uses
</li>
<li>the IPv6 equivalents of all of the above</li>
</ul>
</div>
<p>
A hostname is also refused if <em>any</em> of the addresses it resolves to is non-public, not just
the first one. Split-horizon DNS setups are the usual reason this bites.
</p>
<p>
If you need a target on your own network to keep working, allow it explicitly with
<code>HTTP_ALLOW_LIST</code>, which accepts hostnames or CIDRs. To keep a Tailscale host
reachable, for example:
</p>
<p>
<code>HTTP_ALLOW_LIST=100.64.0.0/10</code>
</p>
<p>
There is also <code>HTTP_DISALLOW_LIST</code> for blocking targets that would otherwise be
allowed, including public ones. It takes precedence over the allow list.
</p>
<p>
Notifiers are unaffected. They send through the Apprise library rather than Mealie's own HTTP
client, so they are not covered by these checks.
<br>
<v-btn
class="mt-2"
color="primary"
href="https://docs.mealie.io/documentation/getting-started/installation/backend-config/#security"
target="_blank"
>
Backend Configuration
</v-btn>
</p>
</div>
<div v-else>
<p>
If a webhook or recipe action of yours has stopped working, or a recipe URL that used to import no
longer does, let your server admin know. It may be pointing at an address Mealie no longer reaches
by default, and they can allow it on the server.
</p>
</div>
</div>
</template>
<script setup lang="ts">
import type { AnnouncementMeta } from "~/composables/use-announcements";
const { user } = useMealieAuth();
</script>
<script lang="ts">
export const meta: AnnouncementMeta = {
title: "Outgoing requests are now restricted to public addresses",
};
</script>
<style scoped lang="css">
p {
padding-bottom: 8px;
}
</style>
@@ -1,13 +1,16 @@
from __future__ import annotations
import hashlib
import ipaddress
import shutil
import socket
from datetime import timedelta
from pathlib import Path
from urllib.parse import urljoin, urlparse
from typing import TYPE_CHECKING
from urllib.parse import urlparse
from uuid import uuid4
import requests
if TYPE_CHECKING:
import httpx
from authlib.oidc.core import UserInfo
from pydantic import UUID4
from sqlalchemy.orm.session import Session
@@ -154,15 +157,36 @@ class OpenIDProvider(AuthProvider[UserInfo]):
claims.add(settings.OIDC_GROUPS_CLAIM)
return claims
def _is_safe_picture_url(self, url: str) -> bool:
@staticmethod
def _picture_allow_hosts() -> list[str]:
"""
Vets the picture claim before we make a request to it.
Hosts the avatar fetch may reach even when they resolve to a private address.
The provider's own host is one: Mealie already contacts it on every login, and
self-hosted setups routinely run it on a private network. `HTTP_DISALLOW_LIST` still
wins over this, since `safehttp` checks the deny list first.
"""
settings = get_app_settings()
allow = list(settings.http_allow_list)
if settings.OIDC_CONFIGURATION_URL:
provider_host = urlparse(settings.OIDC_CONFIGURATION_URL).hostname
if provider_host:
allow.append(provider_host)
return allow
def _is_safe_picture_scheme(self, url: str) -> bool:
"""
Vets the picture claim's scheme before we make a request to it.
The claim is not necessarily set by the provider -- IdPs that let users edit their own
profile would otherwise hand any user a request-forgery primitive -- so the URL must use
HTTPS and resolve to a public address. The exception is the provider's own host, which
Mealie already contacts on every login and which self-hosted setups routinely run on a
private network, often over plain HTTP.
HTTPS. The exception is the provider's own host, which self-hosted setups routinely run
over plain HTTP.
Which addresses the URL is allowed to reach is enforced by `safehttp` at connect time,
per redirect hop, rather than here.
"""
settings = get_app_settings()
parsed = urlparse(url)
@@ -177,58 +201,59 @@ class OpenIDProvider(AuthProvider[UserInfo]):
self._logger.warning("[OIDC] refusing to fetch profile image over a non-HTTPS URL")
return False
try:
addresses = {info[4][0] for info in socket.getaddrinfo(host, None)}
except (socket.gaierror, UnicodeError):
# `UnicodeError`, not `gaierror`, is what an unencodable hostname raises.
return False
# `is_global` is false for private, loopback and link-local ranges, so a single check
# covers RFC1918, 127/8, and the 169.254.169.254 cloud metadata endpoint.
if not addresses or any(not ipaddress.ip_address(address).is_global for address in addresses):
self._logger.warning("[OIDC] refusing to fetch profile image from a non-public address")
return False
return True
def _fetch_picture(self, url: str) -> requests.Response:
def _enforce_picture_scheme(self, request: httpx.Request) -> None:
"""
Fetches `url`, following redirects only to hosts that pass the same vetting.
Re-checks the scheme on every hop, including redirects.
`requests` follows redirects itself by default, which would let a vetted URL hand us off
to a host nobody checked -- the validation has to be re-applied per hop, not once up
front. So we follow them ourselves and run every target through `_is_safe_picture_url`
before requesting it.
httpx follows the redirect chain for us, so without this an https URL could hand us off
to a plain-http host and downgrade the fetch.
"""
for _ in range(MAX_PICTURE_REDIRECTS + 1):
response = requests.get(url, timeout=15, stream=True, allow_redirects=False)
if not response.is_redirect:
if not self._is_safe_picture_scheme(str(request.url)):
raise ValueError(f"refusing to fetch profile image from {request.url.scheme} URL")
def _fetch_picture(self, url: str) -> bytes:
"""
Fetches `url` through the SSRF-protected transport and returns the body.
`safehttp` resolves the host, vets every address it resolves to, and then pins the
connection to those addresses, so a rebinding DNS answer cannot redirect us between the
check and the connect. httpx re-enters the transport for each redirect hop, so every hop
is vetted and pinned the same way -- which is why the redirect chain no longer has to be
walked by hand here.
"""
import httpx
from mealie.pkgs import safehttp
settings = get_app_settings()
transport = safehttp.SafeTransport(
log=self._logger,
allow_hosts=self._picture_allow_hosts(),
deny_hosts=settings.http_disallow_list,
timeout=15,
)
with httpx.Client(
transport=transport,
follow_redirects=True,
max_redirects=MAX_PICTURE_REDIRECTS,
event_hooks={"request": [self._enforce_picture_scheme]},
) as client:
with client.stream("GET", url) as response:
response.raise_for_status()
return response
location = response.headers.get("location", "")
# The body is streamed, so an intermediate response holds its connection open.
response.close()
if not location:
raise ValueError("redirect without a Location header")
# A Location may be relative (RFC 9110), so resolve it against the URL we just asked.
url = urljoin(url, location)
if not self._is_safe_picture_url(url):
raise ValueError("refusing to follow redirect to an unvetted host")
raise ValueError(f"profile image exceeded {MAX_PICTURE_REDIRECTS} redirects")
return self._read_capped(response)
@staticmethod
def _read_capped(response: requests.Response) -> bytes:
def _read_capped(response: httpx.Response) -> bytes:
"""Reads the body, refusing anything over `MAX_PICTURE_BYTES`."""
declared_length = response.headers.get("content-length")
if declared_length and declared_length.isdigit() and int(declared_length) > MAX_PICTURE_BYTES:
raise ValueError(f"declared content-length {declared_length} exceeds {MAX_PICTURE_BYTES} bytes")
content = bytearray()
for chunk in response.iter_content(chunk_size=8192):
for chunk in response.iter_bytes(chunk_size=8192):
content.extend(chunk)
# Servers that omit or understate Content-Length are caught by the running total.
if len(content) > MAX_PICTURE_BYTES:
@@ -243,7 +268,7 @@ class OpenIDProvider(AuthProvider[UserInfo]):
# The claim is attacker-controlled on IdPs that let users edit their own profile, and a
# value that trips up parsing or resolution must skip the avatar, never fail the login.
try:
if not self._is_safe_picture_url(picture):
if not self._is_safe_picture_scheme(picture):
return
repos = get_repositories(self.session, group_id=None, household_id=None)
@@ -256,8 +281,7 @@ class OpenIDProvider(AuthProvider[UserInfo]):
if user.external_avatar_hash == picture_hash:
return
response = self._fetch_picture(picture)
content = self._read_capped(response)
content = self._fetch_picture(picture)
with get_temporary_path() as temp_path:
temp_img = Path(temp_path).joinpath(str(uuid4()))
+17
View File
@@ -189,6 +189,23 @@ class AppSettings(AppLoggingSettings):
extra = [host.strip().lower() for host in self.ALLOWED_IFRAME_HOSTS.split(",") if host.strip()]
return list(dict.fromkeys(DEFAULT_ALLOWED_IFRAME_HOSTS + extra))
HTTP_ALLOW_LIST: str = ""
"""Comma-separated hosts or CIDRs that server-initiated requests (recipe scraping, webhooks,
recipe actions) may reach even if they resolve to an otherwise-blocked private/internal address.
Use this to allow a known internal server."""
HTTP_DISALLOW_LIST: str = ""
"""Comma-separated hosts or CIDRs that server-initiated requests may never reach, even if public.
Takes precedence over `HTTP_ALLOW_LIST`."""
@property
def http_allow_list(self) -> list[str]:
return [host.strip() for host in self.HTTP_ALLOW_LIST.split(",") if host.strip()]
@property
def http_disallow_list(self) -> list[str]:
return [host.strip() for host in self.HTTP_DISALLOW_LIST.split(",") if host.strip()]
DAILY_SCHEDULE_TIME: str = "23:45"
"""Local server time, in HH:MM format. See `DAILY_SCHEDULE_TIME_UTC` for the parsed UTC equivalent"""
+11 -1
View File
@@ -5,12 +5,22 @@ from .fetch import (
ForceTimeoutException,
resilient_fetch,
)
from .transport import AsyncSafeTransport, ForcedTimeoutException, InvalidDomainError
from .transport import (
AsyncSafeTransport,
ForcedTimeoutException,
InvalidDomainError,
SafeTransport,
is_blocked_ip,
post,
)
__all__ = [
"AsyncSafeTransport",
"SafeTransport",
"ForcedTimeoutException",
"InvalidDomainError",
"is_blocked_ip",
"post",
"BROWSER_IMPERSONATIONS",
"SCRAPER_TIMEOUT",
"FetchResult",
+6
View File
@@ -96,14 +96,20 @@ def body_indicates_challenge(content: bytes) -> bool:
def _build_transport(impersonate: str, proxy: str | None = None) -> AsyncSafeTransport:
settings = get_app_settings()
kwargs: dict = {
"impersonate": impersonate,
"default_headers": True,
# disable SSL verification since we can handle untrusted data and some sites don't have certs
# (this also covers the proxy connection, so no separate proxy-verify knob is needed)
"verify": False,
"allow_hosts": settings.http_allow_list,
"deny_hosts": settings.http_disallow_list,
}
if proxy:
# The transport still validates the target host, but it cannot pin the connection: curl
# hands the hostname to the proxy, which does its own resolution. Routing egress through a
# proxy is an explicit operator choice, so that trade-off is theirs to make.
kwargs["proxy"] = proxy
return AsyncSafeTransport(**kwargs)
+173 -35
View File
@@ -1,9 +1,19 @@
import ipaddress
import logging
import socket
from collections.abc import Sequence
from typing import Any
import httpx
from httpx_curl_cffi import AsyncCurlTransport
from curl_cffi import CurlOpt
from httpx_curl_cffi import AsyncCurlTransport, CurlTransport
IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
# Carrier-grade NAT. `is_private` does not cover this range on every Python
# version, so we check it explicitly.
CGNAT_NETWORK = ipaddress.ip_network("100.64.0.0/10")
class ForcedTimeoutException(Exception):
@@ -16,61 +26,189 @@ class ForcedTimeoutException(Exception):
class InvalidDomainError(Exception):
"""
Raised when a request is made to a local IP address.
Raised when a request targets a disallowed (e.g. local/internal) address.
"""
...
class AsyncSafeTransport(AsyncCurlTransport):
def _normalize(ip: IPAddress) -> IPAddress:
# Unwrap IPv4-mapped IPv6 (e.g. ::ffff:127.0.0.1) so a mapped address can't
# dodge the IPv4 checks below.
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
return ip.ipv4_mapped
return ip
def is_blocked_ip(ip: IPAddress) -> bool:
"""Return True if connecting to this address should never be allowed by default."""
ip = _normalize(ip)
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified:
return True
return isinstance(ip, ipaddress.IPv4Address) and ip in CGNAT_NETWORK
def _parse_host_list(entries: Sequence[str]) -> tuple[set[str], list[IPNetwork]]:
"""Split configured entries into exact hostnames and IP networks (CIDRs)."""
hosts: set[str] = set()
networks: list[IPNetwork] = []
for entry in entries:
cleaned = entry.strip().lower()
if not cleaned:
continue
try:
networks.append(ipaddress.ip_network(cleaned, strict=False))
except ValueError:
hosts.add(cleaned)
return hosts, networks
def _matches(host: str, ips: Sequence[IPAddress], hosts: set[str], networks: list[IPNetwork]) -> bool:
if host.lower() in hosts:
return True
for ip in ips:
normalized = _normalize(ip)
for network in networks:
if normalized.version == network.version and normalized in network:
return True
return False
class _SafeTransportMixin:
"""
A wrapper around the httpx-curl-cffi transport class that enforces a timeout value
and that the request is not made to a local IP address.
Shared SSRF protection for the sync and async curl transports.
On each request it resolves the host once, validates every resolved address,
and pins the connection to the validated address(es) via curl's RESOLVE option
so curl cannot re-resolve to a different (e.g. rebound) IP.
Not safe for concurrent requests on a single transport instance: the pin is
applied through the shared session. Mealie uses a fresh transport per scrape
and per outbound POST, and redirects are followed sequentially.
"""
timeout: int = 15
# set by the curl transport base class this mixin is combined with
_session: Any
def __init__(self, log: logging.Logger | None = None, **kwargs):
self.timeout = kwargs.pop("timeout", self.timeout)
def __init__(
self,
*,
log: logging.Logger | None = None,
allow_hosts: Sequence[str] = (),
deny_hosts: Sequence[str] = (),
timeout: int | None = None,
**kwargs,
) -> None:
self._log = log
self._allow = _parse_host_list(allow_hosts)
self._deny = _parse_host_list(deny_hosts)
if timeout is not None:
self.timeout = timeout
# httpx-curl-cffi computes a NOPROXY curl option but then hands the session the
# caller's original mapping, so when none is passed the option is dropped. Without it
# curl falls back to ambient HTTP_PROXY/HTTPS_PROXY, and a proxied request is resolved
# by the proxy -- which would make the pin below inert without anything saying so.
# Passing a non-empty mapping keeps the option; the library fills in the right value.
kwargs.setdefault("curl_options", {CurlOpt.NOPROXY: "*"})
super().__init__(**kwargs)
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
# override timeout value for _all_ requests
def _validate(self, request: httpx.Request) -> list[str] | None:
"""Validate the request target. Returns the curl RESOLVE pins, or None for an IP literal."""
# Force our timeout onto every request.
request.extensions["timeout"] = httpx.Timeout(self.timeout, pool=self.timeout).as_dict()
# validate the request is not attempting to connect to a local IP
# This is a security measure to prevent SSRF attacks
host = request.url.host
port = request.url.port or (443 if request.url.scheme == "https" else 80)
ip: ipaddress.IPv4Address | ipaddress.IPv6Address | None = None
netloc = request.url.netloc.decode()
if ":" in netloc: # Either an IP, or a hostname:port combo
netloc_parts = netloc.split(":")
netloc = netloc_parts[0]
try:
literal: IPAddress | None = ipaddress.ip_address(host)
except ValueError:
literal = None
if literal is not None:
ips: list[IPAddress] = [literal]
else:
try:
ip = ipaddress.ip_address(netloc)
except ValueError:
if self._log:
self._log.debug(f"failed to parse ip for {netloc=} falling back to domain resolution")
pass
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
except (socket.gaierror, UnicodeError) as e:
# An unencodable hostname (e.g. an over-long label) raises UnicodeError, not
# gaierror. Either way the host is unusable, so it fails as an invalid domain.
raise InvalidDomainError(f"could not resolve host: {host}") from e
# Request is a domain or a hostname.
if not ip:
if self._log:
self._log.debug(f"resolving IP for domain: {netloc}")
ips = []
seen: set[str] = set()
for info in infos:
addr = str(info[4][0]).split("%")[0] # drop any IPv6 scope id
if addr not in seen:
seen.add(addr)
ips.append(ipaddress.ip_address(addr))
ip_str = socket.gethostbyname(netloc)
ip = ipaddress.ip_address(ip_str)
deny_hosts, deny_networks = self._deny
if _matches(host, ips, deny_hosts, deny_networks):
self._warn(request, "target is on the disallow list")
raise InvalidDomainError(f"request blocked by disallow list: {request.url}")
if self._log:
self._log.debug(f"resolved IP for domain: {netloc} -> {ip}")
allow_hosts, allow_networks = self._allow
if not _matches(host, ips, allow_hosts, allow_networks):
for ip in ips:
if is_blocked_ip(ip):
self._warn(request, f"resolves to non-public address {ip}")
raise InvalidDomainError(f"invalid request on local resource: {request.url} -> {ip}")
if ip.is_private:
if self._log:
self._log.warning(f"invalid request on local resource: {request.url} -> {ip}")
raise InvalidDomainError(f"invalid request on local resource: {request.url} -> {ip}")
if literal is not None:
# curl connects straight to the literal address; nothing to pin.
return None
return [f"{host}:{port}:{ip}" for ip in ips]
def _warn(self, request: httpx.Request, reason: str) -> None:
if self._log:
self._log.warning(f"[safehttp] blocked request to {request.url}: {reason}")
def _apply_pin(self, resolve: list[str] | None) -> None:
# curl_cffi applies the session's curl_options to each request, so setting
# RESOLVE here pins this request to the address we just validated.
options = self._session.curl_options
if resolve:
options[CurlOpt.RESOLVE] = resolve
else:
options.pop(CurlOpt.RESOLVE, None)
class AsyncSafeTransport(_SafeTransportMixin, AsyncCurlTransport):
"""Async curl transport that blocks SSRF and pins the connection to a validated IP."""
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
resolve = self._validate(request)
self._apply_pin(resolve)
return await super().handle_async_request(request)
class SafeTransport(_SafeTransportMixin, CurlTransport):
"""Sync counterpart of AsyncSafeTransport for server-initiated POSTs (webhooks, recipe actions)."""
def handle_request(self, request: httpx.Request) -> httpx.Response:
resolve = self._validate(request)
self._apply_pin(resolve)
return super().handle_request(request)
def post(
url: str,
*,
json=None,
timeout: int = 15,
allow_hosts: Sequence[str] = (),
deny_hosts: Sequence[str] = (),
**kwargs,
) -> httpx.Response:
"""Perform a sync POST through the SSRF-protected transport.
Drop-in for `requests.post(url, json=..., timeout=...)` on server-initiated
requests to user-supplied URLs. Redirects are followed and re-validated per hop.
"""
transport = SafeTransport(allow_hosts=allow_hosts, deny_hosts=deny_hosts, timeout=timeout)
with httpx.Client(transport=transport, follow_redirects=True) as client:
return client.post(url, json=json, timeout=timeout, **kwargs)
@@ -1,11 +1,12 @@
from functools import cached_property
import requests
from fastapi import APIRouter, BackgroundTasks, Body, Depends, HTTPException, status
from fastapi.encoders import jsonable_encoder
from pydantic import UUID4
from mealie.core.config import get_app_settings
from mealie.core.exceptions import NoEntryFound
from mealie.pkgs import safehttp
from mealie.routes._base.base_controllers import BaseUserController
from mealie.routes._base.controller import controller
from mealie.routes._base.mixins import HttpRepo
@@ -79,7 +80,7 @@ class GroupRecipeActionController(BaseUserController):
)
if recipe_action.action_type == GroupRecipeActionType.post.value:
task_action = requests.post
task_action = safehttp.post
else:
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
@@ -95,10 +96,13 @@ class GroupRecipeActionController(BaseUserController):
detail=ErrorResponse.respond(message="Not found."),
) from e
settings = get_app_settings()
payload = GroupRecipeActionPayload(action=recipe_action, content=recipe, recipe_scale=recipe_scale)
bg_tasks.add_task(
task_action,
url=recipe_action.url,
json=jsonable_encoder(payload.model_dump()),
timeout=15,
allow_hosts=settings.http_allow_list,
deny_hosts=settings.http_disallow_list,
)
+10 -2
View File
@@ -42,10 +42,18 @@ class WebhookPublisher:
self.hard_fail = hard_fail
def publish(self, event: Event, notification_urls: list[str]):
import requests
from mealie.core.config import get_app_settings
from mealie.pkgs import safehttp
event_payload = jsonable_encoder(event)
settings = get_app_settings()
for url in notification_urls:
r = requests.post(url, json=event_payload, timeout=15)
r = safehttp.post(
url,
json=event_payload,
timeout=15,
allow_hosts=settings.http_allow_list,
deny_hosts=settings.http_disallow_list,
)
if self.hard_fail:
r.raise_for_status()
@@ -1,9 +1,9 @@
from uuid import UUID, uuid4
import pytest
import requests
from fastapi.testclient import TestClient
from mealie.pkgs import safehttp
from mealie.schema.household.group_recipe_action import (
CreateGroupRecipeAction,
GroupRecipeActionOut,
@@ -17,8 +17,8 @@ from tests.utils.fixture_schemas import TestUser
@pytest.fixture(autouse=True)
def mock_requests_post(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(requests, "post", lambda *args, **kwargs: None)
def mock_outbound_post(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(safehttp, "post", lambda *args, **kwargs: None)
def create_action(action_type: GroupRecipeActionType = GroupRecipeActionType.link) -> CreateGroupRecipeAction:
@@ -91,7 +91,7 @@ def test_delete_webhook(api_client: TestClient, webhook_data, unique_user: TestU
def test_post_test_webhook(
monkeypatch: pytest.MonkeyPatch, api_client: TestClient, unique_user: TestUser, webhook_data
):
# Mock the requests.post to avoid actual HTTP calls
# Mock the outbound post to avoid actual HTTP calls
class MockResponse:
status_code = 200
@@ -101,7 +101,7 @@ def test_post_test_webhook(
mock_calls.append((args, kwargs))
return MockResponse()
monkeypatch.setattr("requests.post", mock_post)
monkeypatch.setattr("mealie.pkgs.safehttp.post", mock_post)
# Create a webhook and post it
response = api_client.post(
@@ -124,7 +124,7 @@ def test_post_test_webhook(
test_message = "This is a test webhook message"
post_test_webhook(webhook, test_message)
# Verify that requests.post was called with the correct parameters
# Verify that the outbound post was called with the correct parameters
assert len(mock_calls) == 1
args, kwargs = mock_calls[0]
@@ -3,10 +3,9 @@ import io
import logging
import socket
from pathlib import Path
from unittest.mock import MagicMock
import httpx
import pytest
import requests
from PIL import Image
from pytest import MonkeyPatch, Session
@@ -14,6 +13,7 @@ from mealie.core.config import get_app_settings
from mealie.core.exceptions import MissingClaimException
from mealie.core.security.providers import openid_provider
from mealie.core.security.providers.openid_provider import OpenIDProvider
from mealie.pkgs.safehttp import transport as safehttp_transport
from mealie.repos.all_repositories import get_repositories
from mealie.schema.user import PrivateUser
from tests.utils.factories import random_email, random_string
@@ -355,29 +355,12 @@ def _png_bytes() -> bytes:
return buffer.getvalue()
class _FakeResponse:
def __init__(self, body: bytes, headers: dict | None = None, status_code: int = 200):
self.headers = headers or {}
self.status_code = status_code
self._body = body
@property
def is_redirect(self) -> bool:
return self.status_code in (301, 302, 303, 307, 308) and "location" in {key.lower() for key in self.headers}
def raise_for_status(self) -> None:
return None
def close(self) -> None:
self.closed = True
def iter_content(self, chunk_size: int = 8192):
for i in range(0, len(self._body), chunk_size):
yield self._body[i : i + chunk_size]
def _response(body: bytes, headers: dict | None = None, status_code: int = 200) -> httpx.Response:
return httpx.Response(status_code, headers=headers or {}, content=body)
def _redirect(location: str, status_code: int = 302) -> _FakeResponse:
return _FakeResponse(b"", headers={"location": location}, status_code=status_code)
def _redirect(location: str, status_code: int = 302) -> httpx.Response:
return _response(b"", headers={"location": location}, status_code=status_code)
def _picture_claims(picture: object = None) -> dict:
@@ -394,31 +377,44 @@ def _picture_claims(picture: object = None) -> dict:
def _resolve_to(monkeypatch: MonkeyPatch, address: str) -> None:
"""Pins DNS resolution so the guard's decision is deterministic and offline."""
monkeypatch.setattr(
openid_provider.socket,
"getaddrinfo",
lambda host, port, *a, **kw: [(None, None, None, "", (address, 0))],
)
_resolve_hosts(monkeypatch, {}, default=address)
def _resolve_hosts(monkeypatch: MonkeyPatch, mapping: dict[str, str], default: str = "93.184.216.34") -> None:
"""Per-host DNS pinning, so a redirect chain can cross from a public host to a private one."""
"""
Per-host DNS pinning, so a redirect chain can cross from a public host to a private one.
The vetting now happens inside `safehttp`, so this patches the resolver that layer uses.
"""
monkeypatch.setattr(
openid_provider.socket,
safehttp_transport.socket,
"getaddrinfo",
lambda host, port, *a, **kw: [(None, None, None, "", (mapping.get(host, default), 0))],
)
def _fake_gets(monkeypatch: MonkeyPatch, responses: list[_FakeResponse]) -> MagicMock:
"""Scripts consecutive `requests.get` calls, so a redirect chain can be walked."""
fake_get = MagicMock(side_effect=responses)
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
return fake_get
def _patch_network(monkeypatch: MonkeyPatch, responses: list) -> list[str]:
"""
Scripts consecutive transport responses and records the URLs actually requested.
This stubs the curl transport underneath `SafeTransport`, so the real SSRF vetting and
connection pinning still run on every hop -- only the socket work is replaced. An entry may
be an exception, which is raised instead of returned.
"""
requested: list[str] = []
queue = list(responses)
def _requested_urls(fake_get: MagicMock) -> list[str]:
return [call.args[0] for call in fake_get.call_args_list]
def fake_handle_request(_self, request: httpx.Request) -> httpx.Response:
requested.append(str(request.url))
if not queue:
raise AssertionError(f"unexpected request to {request.url}")
response = queue.pop(0)
if isinstance(response, Exception):
raise response
return response
monkeypatch.setattr(safehttp_transport.CurlTransport, "handle_request", fake_handle_request)
return requested
@pytest.fixture
@@ -435,14 +431,13 @@ def test_stores_picture_and_rotates_cache_key(_oidc_env, monkeypatch: MonkeyPatc
before = unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
url = "https://cdn.example.com/avatar.png"
fake_get = MagicMock(return_value=_FakeResponse(_png_bytes()))
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
requested = _patch_network(monkeypatch, [_response(_png_bytes())])
data = _picture_claims(url)
data["email"] = unique_user.email
assert OpenIDProvider(unique_user.repos.session, data).authenticate() is not None
fake_get.assert_called_once()
assert requested == [url]
after = unique_user.repos.users.get_one(unique_user.user_id)
assert after is not None
assert (PrivateUser.get_directory(unique_user.user_id) / "profile.webp").is_file()
@@ -458,23 +453,21 @@ def test_unchanged_picture_claim_skips_download(_oidc_env, monkeypatch: MonkeyPa
unique_user.user_id, {"external_avatar_hash": hashlib.sha256(url.encode()).hexdigest()}
)
fake_get = MagicMock(return_value=_FakeResponse(_png_bytes()))
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
requested = _patch_network(monkeypatch, [_response(_png_bytes())])
data = _picture_claims(url)
data["email"] = unique_user.email
assert OpenIDProvider(unique_user.repos.session, data).authenticate() is not None
fake_get.assert_not_called()
assert requested == []
@pytest.mark.parametrize("picture", [None, 123, {"url": PICTURE_URL}, ""])
def test_absent_or_non_string_picture_claim(_oidc_env, monkeypatch: MonkeyPatch, session: Session, picture):
fake_get = MagicMock()
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
requested = _patch_network(monkeypatch, [])
assert OpenIDProvider(session, _picture_claims(picture)).authenticate() is not None
fake_get.assert_not_called()
assert requested == []
@pytest.mark.parametrize(
@@ -488,11 +481,10 @@ def test_absent_or_non_string_picture_claim(_oidc_env, monkeypatch: MonkeyPatch,
)
def test_rejects_urls_that_are_not_https(_oidc_env, monkeypatch: MonkeyPatch, session: Session, url: str):
_resolve_to(monkeypatch, "93.184.216.34")
fake_get = MagicMock()
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
requested = _patch_network(monkeypatch, [])
assert OpenIDProvider(session, _picture_claims(url)).authenticate() is not None
fake_get.assert_not_called()
assert requested == []
@pytest.mark.parametrize(
@@ -502,30 +494,47 @@ def test_rejects_urls_that_are_not_https(_oidc_env, monkeypatch: MonkeyPatch, se
"10.0.0.5", # private
"192.168.1.10", # private
"169.254.169.254", # link-local / cloud metadata
"100.64.0.1", # CGNAT
"::1",
"fd00::1",
"::ffff:127.0.0.1", # IPv4-mapped loopback
],
)
def test_rejects_non_public_addresses(_oidc_env, monkeypatch: MonkeyPatch, session: Session, address: str):
"""No request is made at all -- the guard runs before `requests.get`."""
"""No connection is made at all -- `safehttp` rejects before it reaches the socket."""
_resolve_to(monkeypatch, address)
fake_get = MagicMock()
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
requested = _patch_network(monkeypatch, [])
assert OpenIDProvider(session, _picture_claims("https://cdn.example.com/a.png")).authenticate() is not None
fake_get.assert_not_called()
assert requested == []
def test_unresolvable_host_is_rejected(_oidc_env, monkeypatch: MonkeyPatch, session: Session):
def _boom(*args, **kwargs):
raise socket.gaierror("no such host")
monkeypatch.setattr(openid_provider.socket, "getaddrinfo", _boom)
fake_get = MagicMock()
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
monkeypatch.setattr(safehttp_transport.socket, "getaddrinfo", _boom)
requested = _patch_network(monkeypatch, [])
assert OpenIDProvider(session, _picture_claims("https://nope.example.com/a.png")).authenticate() is not None
fake_get.assert_not_called()
assert requested == []
def test_disallow_list_blocks_a_public_avatar_host(monkeypatch: MonkeyPatch, session: Session):
"""`HTTP_DISALLOW_LIST` reaches the avatar fetch like any other server-initiated request."""
monkeypatch.setenv("OIDC_REQUIRES_EMAIL_VERIFICATION", "true")
monkeypatch.setenv("OIDC_CONFIGURATION_URL", "https://idp.example.com/.well-known/openid-configuration")
monkeypatch.setenv("HTTP_DISALLOW_LIST", "cdn.example.com")
get_app_settings.cache_clear()
try:
_resolve_to(monkeypatch, "93.184.216.34")
requested = _patch_network(monkeypatch, [])
assert OpenIDProvider(session, _picture_claims("https://cdn.example.com/a.png")).authenticate() is not None
assert requested == []
finally:
get_app_settings.cache_clear()
@pytest.mark.parametrize("url", ["https://idp.example.com/pic.png", "http://idp.example.com/pic.png"])
@@ -536,14 +545,13 @@ def test_provider_own_host_is_allowed_on_a_private_network(
_resolve_to(monkeypatch, "192.168.1.10")
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
fake_get = MagicMock(return_value=_FakeResponse(_png_bytes()))
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
requested = _patch_network(monkeypatch, [_response(_png_bytes())])
data = _picture_claims(url)
data["email"] = unique_user.email
assert OpenIDProvider(unique_user.repos.session, data).authenticate() is not None
fake_get.assert_called_once()
assert requested == [url]
def test_oversized_declared_content_length_is_refused(_oidc_env, monkeypatch: MonkeyPatch, unique_user: TestUser):
@@ -551,8 +559,7 @@ def test_oversized_declared_content_length_is_refused(_oidc_env, monkeypatch: Mo
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
too_big = str(openid_provider.MAX_PICTURE_BYTES + 1)
response = _FakeResponse(_png_bytes(), headers={"content-length": too_big})
monkeypatch.setattr(openid_provider.requests, "get", MagicMock(return_value=response))
_patch_network(monkeypatch, [_response(_png_bytes(), headers={"content-length": too_big})])
data = _picture_claims("https://cdn.example.com/huge.png")
data["email"] = unique_user.email
@@ -569,8 +576,7 @@ def test_oversized_stream_is_refused(_oidc_env, monkeypatch: MonkeyPatch, unique
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
body = b"x" * (openid_provider.MAX_PICTURE_BYTES + 1)
response = _FakeResponse(body, headers={"content-length": "10"})
monkeypatch.setattr(openid_provider.requests, "get", MagicMock(return_value=response))
_patch_network(monkeypatch, [_response(body, headers={"content-length": "10"})])
data = _picture_claims("https://cdn.example.com/liar.png")
data["email"] = unique_user.email
@@ -585,7 +591,7 @@ def test_failed_download_does_not_break_login(_oidc_env, monkeypatch: MonkeyPatc
_resolve_to(monkeypatch, "93.184.216.34")
before = unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
monkeypatch.setattr(openid_provider.requests, "get", MagicMock(side_effect=requests.ConnectionError("boom")))
_patch_network(monkeypatch, [httpx.ConnectError("boom")])
data = _picture_claims("https://cdn.example.com/a.png")
data["email"] = unique_user.email
@@ -597,12 +603,27 @@ def test_failed_download_does_not_break_login(_oidc_env, monkeypatch: MonkeyPatc
assert after.external_avatar_hash is None
def test_error_status_does_not_break_login(_oidc_env, monkeypatch: MonkeyPatch, unique_user: TestUser):
"""`raise_for_status` still guards the body, now through httpx."""
_resolve_to(monkeypatch, "93.184.216.34")
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
_patch_network(monkeypatch, [_response(b"nope", status_code=404)])
data = _picture_claims("https://cdn.example.com/a.png")
data["email"] = unique_user.email
assert OpenIDProvider(unique_user.repos.session, data).authenticate() is not None
after = unique_user.repos.users.get_one(unique_user.user_id)
assert after is not None
assert after.external_avatar_hash is None
def test_undecodable_image_does_not_break_login(_oidc_env, monkeypatch: MonkeyPatch, unique_user: TestUser):
_resolve_to(monkeypatch, "93.184.216.34")
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
response = _FakeResponse(b"definitely not a png")
monkeypatch.setattr(openid_provider.requests, "get", MagicMock(return_value=response))
_patch_network(monkeypatch, [_response(b"definitely not a png")])
data = _picture_claims("https://cdn.example.com/a.png")
data["email"] = unique_user.email
@@ -621,20 +642,18 @@ def _authenticate_with_picture(user: TestUser, url: str):
@pytest.mark.parametrize("status_code", [301, 302, 303, 307, 308])
def test_follows_redirect_to_a_vetted_host(_oidc_env, monkeypatch: MonkeyPatch, unique_user: TestUser, status_code):
"""Redirects are followed, but we walk them ourselves so each hop can be checked."""
"""httpx walks the chain, but every hop re-enters the transport and is vetted again."""
_resolve_hosts(monkeypatch, {}) # everything public
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
fake_get = _fake_gets(
requested = _patch_network(
monkeypatch,
[_redirect("https://cdn2.example.com/real.png", status_code), _FakeResponse(_png_bytes())],
[_redirect("https://cdn2.example.com/real.png", status_code), _response(_png_bytes())],
)
assert _authenticate_with_picture(unique_user, "https://cdn.example.com/a.png") is not None
assert _requested_urls(fake_get) == ["https://cdn.example.com/a.png", "https://cdn2.example.com/real.png"]
# requests must never follow on its own -- that would skip our per-hop check.
assert all(call.kwargs["allow_redirects"] is False for call in fake_get.call_args_list)
assert requested == ["https://cdn.example.com/a.png", "https://cdn2.example.com/real.png"]
assert (PrivateUser.get_directory(unique_user.user_id) / "profile.webp").is_file()
@@ -643,26 +662,27 @@ def test_refuses_redirect_to_a_private_address(_oidc_env, monkeypatch: MonkeyPat
_resolve_hosts(monkeypatch, {"metadata.internal": "169.254.169.254"})
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
fake_get = _fake_gets(monkeypatch, [_redirect("https://metadata.internal/latest/meta-data/")])
requested = _patch_network(monkeypatch, [_redirect("https://metadata.internal/latest/meta-data/")])
assert _authenticate_with_picture(unique_user, "https://cdn.example.com/a.png") is not None
# The redirect target is never requested.
assert _requested_urls(fake_get) == ["https://cdn.example.com/a.png"]
# The redirect target is never connected to.
assert requested == ["https://cdn.example.com/a.png"]
after = unique_user.repos.users.get_one(unique_user.user_id)
assert after is not None
assert after.external_avatar_hash is None
def test_refuses_redirect_downgrading_to_http(_oidc_env, monkeypatch: MonkeyPatch, unique_user: TestUser):
"""httpx would follow a downgrade on its own, so the scheme is re-checked per hop."""
_resolve_hosts(monkeypatch, {})
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
fake_get = _fake_gets(monkeypatch, [_redirect("http://cdn2.example.com/a.png")])
requested = _patch_network(monkeypatch, [_redirect("http://cdn2.example.com/a.png")])
assert _authenticate_with_picture(unique_user, "https://cdn.example.com/a.png") is not None
assert len(_requested_urls(fake_get)) == 1
assert requested == ["https://cdn.example.com/a.png"]
after = unique_user.repos.users.get_one(unique_user.user_id)
assert after is not None
assert after.external_avatar_hash is None
@@ -675,11 +695,11 @@ def test_relative_location_is_resolved_against_the_current_url(
_resolve_hosts(monkeypatch, {})
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
fake_get = _fake_gets(monkeypatch, [_redirect("/avatars/real.png"), _FakeResponse(_png_bytes())])
requested = _patch_network(monkeypatch, [_redirect("/avatars/real.png"), _response(_png_bytes())])
assert _authenticate_with_picture(unique_user, "https://cdn.example.com/users/1/a.png") is not None
assert _requested_urls(fake_get) == [
assert requested == [
"https://cdn.example.com/users/1/a.png",
"https://cdn.example.com/avatars/real.png",
]
@@ -691,26 +711,27 @@ def test_redirect_chain_is_capped(_oidc_env, monkeypatch: MonkeyPatch, unique_us
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
hops = openid_provider.MAX_PICTURE_REDIRECTS + 2
fake_get = _fake_gets(monkeypatch, [_redirect(f"https://cdn.example.com/{i}.png") for i in range(hops)])
requested = _patch_network(monkeypatch, [_redirect(f"https://cdn.example.com/{i}.png") for i in range(hops)])
assert _authenticate_with_picture(unique_user, "https://cdn.example.com/a.png") is not None
assert len(_requested_urls(fake_get)) == openid_provider.MAX_PICTURE_REDIRECTS + 1
assert len(requested) == openid_provider.MAX_PICTURE_REDIRECTS + 1
after = unique_user.repos.users.get_one(unique_user.user_id)
assert after is not None
assert after.external_avatar_hash is None
def test_redirect_without_location_is_refused(_oidc_env, monkeypatch: MonkeyPatch, unique_user: TestUser):
"""A 302 whose Location is empty resolves back to itself, so it must hit the cap and stop."""
_resolve_hosts(monkeypatch, {})
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
# A 302 carrying no Location: urljoin would resolve to the same URL and spin until the cap.
fake_get = _fake_gets(monkeypatch, [_FakeResponse(b"", headers={"location": ""}, status_code=302)])
hops = openid_provider.MAX_PICTURE_REDIRECTS + 2
requested = _patch_network(monkeypatch, [_redirect("") for _ in range(hops)])
assert _authenticate_with_picture(unique_user, "https://cdn.example.com/a.png") is not None
assert len(_requested_urls(fake_get)) == 1
assert len(requested) == openid_provider.MAX_PICTURE_REDIRECTS + 1
after = unique_user.repos.users.get_one(unique_user.user_id)
assert after is not None
assert after.external_avatar_hash is None
@@ -728,7 +749,7 @@ def test_temp_file_is_moved_not_left_behind(_oidc_env, monkeypatch: MonkeyPatch,
"move",
lambda src, dst: (moved.append((src, dst)), real_move(src, dst))[1],
)
monkeypatch.setattr(openid_provider.requests, "get", MagicMock(return_value=_FakeResponse(_png_bytes())))
_patch_network(monkeypatch, [_response(_png_bytes())])
data = _picture_claims("https://cdn.example.com/a.png")
data["email"] = unique_user.email
@@ -753,14 +774,13 @@ def test_malformed_picture_claim_does_not_break_login(
"""A claim that trips up parsing or resolution must skip the avatar, not fail the login."""
unique_user.repos.users.patch(unique_user.user_id, {"external_avatar_hash": None})
fake_get = MagicMock()
monkeypatch.setattr(openid_provider.requests, "get", fake_get)
requested = _patch_network(monkeypatch, [])
data = _picture_claims(picture)
data["email"] = unique_user.email
assert OpenIDProvider(unique_user.repos.session, data).authenticate() is not None
fake_get.assert_not_called()
assert requested == []
after = unique_user.repos.users.get_one(unique_user.user_id)
assert after is not None
assert after.external_avatar_hash is None
@@ -416,3 +416,45 @@ async def test_flaresolverr_failure_degrades_gracefully(monkeypatch):
assert result is None
assert len(calls) == 1 # it tried, then gave up cleanly
# ---------------------------------------------------------------------------
# Transport construction
# ---------------------------------------------------------------------------
def test_build_transport_applies_operator_host_lists(monkeypatch):
# The scraper builds its own transports, so the operator's allow/deny lists have to be
# threaded through here or scraping silently loses them.
captured: dict = {}
monkeypatch.setattr(
fetch,
"get_app_settings",
lambda: SimpleNamespace(
http_allow_list=["internal.example"],
http_disallow_list=["blocked.example"],
),
)
monkeypatch.setattr(fetch, "AsyncSafeTransport", lambda **kwargs: captured.update(kwargs))
fetch._build_transport("chrome")
assert captured["allow_hosts"] == ["internal.example"]
assert captured["deny_hosts"] == ["blocked.example"]
assert "proxy" not in captured
def test_build_transport_passes_proxy_through(monkeypatch):
captured: dict = {}
monkeypatch.setattr(
fetch,
"get_app_settings",
lambda: SimpleNamespace(http_allow_list=[], http_disallow_list=[]),
)
monkeypatch.setattr(fetch, "AsyncSafeTransport", lambda **kwargs: captured.update(kwargs))
fetch._build_transport("chrome", "http://proxy:8080")
assert captured["proxy"] == "http://proxy:8080"
assert captured["allow_hosts"] == []
assert captured["deny_hosts"] == []
@@ -0,0 +1,225 @@
import http.server
import ipaddress
import socket
import threading
import httpx
import pytest
from curl_cffi import CurlOpt
from mealie.pkgs import safehttp
from mealie.pkgs.safehttp import transport as safehttp_transport
from mealie.pkgs.safehttp.transport import (
AsyncSafeTransport,
InvalidDomainError,
SafeTransport,
is_blocked_ip,
)
def _request(url: str) -> httpx.Request:
return httpx.Request("GET", url)
def _patch_resolver(monkeypatch, ips: list[str]) -> None:
def fake_getaddrinfo(host, port, *args, **kwargs):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port)) for ip in ips]
monkeypatch.setattr(safehttp_transport.socket, "getaddrinfo", fake_getaddrinfo)
@pytest.mark.parametrize(
("ip", "blocked"),
[
("8.8.8.8", False),
("2606:4700:4700::1111", False),
("10.0.0.1", True),
("172.16.5.5", True),
("192.168.1.1", True),
("127.0.0.1", True),
("169.254.169.254", True), # cloud metadata / link-local
("100.64.0.1", True), # CGNAT, not covered by is_private on all versions
("0.0.0.0", True),
("224.0.0.1", True), # multicast
("::1", True),
("fe80::1", True),
("fc00::1", True),
("::ffff:127.0.0.1", True), # IPv4-mapped loopback
],
)
def test_is_blocked_ip(ip: str, blocked: bool):
assert is_blocked_ip(ipaddress.ip_address(ip)) is blocked
def test_blocks_host_resolving_to_private(monkeypatch):
_patch_resolver(monkeypatch, ["10.0.0.5"])
transport = AsyncSafeTransport()
with pytest.raises(InvalidDomainError):
transport._validate(_request("https://evil.example/"))
def test_allows_public_host_and_returns_pin(monkeypatch):
_patch_resolver(monkeypatch, ["93.184.216.34"])
transport = AsyncSafeTransport()
resolve = transport._validate(_request("https://example.test/path"))
assert resolve == ["example.test:443:93.184.216.34"]
def test_pin_covers_all_resolved_addresses(monkeypatch):
_patch_resolver(monkeypatch, ["93.184.216.34", "93.184.216.35"])
transport = AsyncSafeTransport()
resolve = transport._validate(_request("http://example.test/"))
assert resolve == ["example.test:80:93.184.216.34", "example.test:80:93.184.216.35"]
def test_rejects_when_any_resolved_address_is_unsafe(monkeypatch):
# one public, one private -> reject the whole request
_patch_resolver(monkeypatch, ["93.184.216.34", "127.0.0.1"])
transport = AsyncSafeTransport()
with pytest.raises(InvalidDomainError):
transport._validate(_request("https://mixed.example/"))
def test_ip_literal_public_needs_no_pin():
transport = AsyncSafeTransport()
assert transport._validate(_request("https://93.184.216.34/")) is None
def test_ip_literal_metadata_blocked():
transport = AsyncSafeTransport()
with pytest.raises(InvalidDomainError):
transport._validate(_request("http://169.254.169.254/latest/meta-data/"))
def test_ipv6_resolution_is_validated(monkeypatch):
_patch_resolver(monkeypatch, ["::1"])
transport = AsyncSafeTransport()
with pytest.raises(InvalidDomainError):
transport._validate(_request("https://v6.example/"))
def test_allow_list_bypasses_block(monkeypatch):
_patch_resolver(monkeypatch, ["10.0.0.5"])
transport = AsyncSafeTransport(allow_hosts=["internal.example"])
resolve = transport._validate(_request("https://internal.example/"))
assert resolve == ["internal.example:443:10.0.0.5"]
def test_allow_list_cidr_bypasses_block(monkeypatch):
_patch_resolver(monkeypatch, ["10.1.2.3"])
transport = AsyncSafeTransport(allow_hosts=["10.0.0.0/8"])
assert transport._validate(_request("https://internal.example/")) == ["internal.example:443:10.1.2.3"]
def test_deny_list_overrides_allow(monkeypatch):
_patch_resolver(monkeypatch, ["93.184.216.34"])
transport = AsyncSafeTransport(allow_hosts=["blocked.example"], deny_hosts=["blocked.example"])
with pytest.raises(InvalidDomainError):
transport._validate(_request("https://blocked.example/"))
def test_deny_list_blocks_public_host(monkeypatch):
_patch_resolver(monkeypatch, ["93.184.216.34"])
transport = AsyncSafeTransport(deny_hosts=["93.184.216.0/24"])
with pytest.raises(InvalidDomainError):
transport._validate(_request("https://public.example/"))
def test_unresolvable_host_is_rejected(monkeypatch):
def boom(host, port, *args, **kwargs):
raise socket.gaierror("no such host")
monkeypatch.setattr(safehttp_transport.socket, "getaddrinfo", boom)
transport = AsyncSafeTransport()
with pytest.raises(InvalidDomainError):
transport._validate(_request("https://nope.invalid/"))
class _LocalServer:
def __init__(self):
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"OK")
def do_POST(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"OK")
def log_message(self, *args):
pass
self.server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
self.port = self.server.server_address[1]
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
def __enter__(self):
self.thread.start()
return self
def __exit__(self, *exc):
# `shutdown` only stops the serve_forever loop; without `server_close` the listening
# socket stays open and pytest fails the test on the resulting ResourceWarning.
self.server.shutdown()
self.thread.join()
self.server.server_close()
@pytest.mark.asyncio
async def test_async_transport_pins_connection_to_validated_ip(monkeypatch):
with _LocalServer() as server:
# host does not really resolve to localhost; the resolver + pin make it so
_patch_resolver(monkeypatch, ["127.0.0.1"])
transport = AsyncSafeTransport(allow_hosts=["pinned.example"])
async with httpx.AsyncClient(transport=transport) as client:
resp = await client.get(f"http://pinned.example:{server.port}/")
assert resp.status_code == 200
assert resp.text == "OK"
def test_sync_post_blocks_loopback_by_default():
with _LocalServer() as server:
with pytest.raises(InvalidDomainError):
safehttp.post(f"http://127.0.0.1:{server.port}/", json={"x": 1})
def test_sync_post_allows_configured_host():
with _LocalServer() as server:
resp = safehttp.post(
f"http://127.0.0.1:{server.port}/",
json={"x": 1},
allow_hosts=["127.0.0.1"],
)
assert resp.status_code == 200
# ---------------------------------------------------------------------------
# Proxy handling
# ---------------------------------------------------------------------------
def test_noproxy_is_set_when_no_proxy_is_configured():
"""
Without this, curl silently honors ambient HTTP_PROXY/HTTPS_PROXY -- and a proxied request
is resolved by the proxy, so the connection pin would no longer apply.
"""
transport = SafeTransport()
assert transport._session.curl_options[CurlOpt.NOPROXY] == "*"
def test_noproxy_is_cleared_when_a_proxy_is_configured():
"""An explicitly configured proxy must apply to every host, env vars notwithstanding."""
transport = SafeTransport(proxy="http://proxy:8080")
assert transport._session.curl_options[CurlOpt.NOPROXY] == ""
def test_pin_and_proxy_options_coexist(monkeypatch):
"""Applying the pin must not clobber the proxy option living in the same mapping."""
_patch_resolver(monkeypatch, ["93.184.216.34"])
transport = SafeTransport(proxy="http://proxy:8080")
transport._apply_pin(transport._validate(_request("https://example.test/")))
options = transport._session.curl_options
assert options[CurlOpt.RESOLVE] == ["example.test:443:93.184.216.34"]
assert options[CurlOpt.NOPROXY] == ""