fix: centralize SSRF protection and block self-targeted requests (#4310)
What changed, and why it matters
This is a major security patch for LNbits released after a November incident. It fixes two broad weaknesses: attackers could trick the server into making requests to itself or to internal/cloud services (SSRF), and new user accounts could be created too freely, letting attackers sign up and abuse those features. The patch centralizes outbound-request protections, blocks self-targeted requests, disables public registration by default, and adds activation/invitation requirements. The vendor explicitly says every version before 1.7.0 is affected and funds are at risk of theft.
Upgrade to LNbits v1.7.0 or later immediately. After upgrading, rotate all API keys, wallet keys, admin secrets, and any credentials that may have been exposed, because the vendor warns that exposed credentials could remain usable. Review the Security settings page to confirm outbound protection status and supply LNBITS_OUTBOUND_HOST_IPS for any public NAT/origin addresses not visible locally. Keep public registration disabled unless explicitly required, and use invitation/activation codes if it is enabled. Run the provided Docker launcher so container deployments receive host interface addresses.
Security signals we found
New centralized SafeHttpClient with DNS pinning, redirect limits, and destination validation
New outbound.py blocks requests to the instance hostname and locally assigned/supplied IP addresses
SSRF protection applied to LNURL, NIP-05, webhooks, WASM extension HTTP, and WebSockets
Private/internal/cloud metadata addresses blocked by default; administrator opt-in retained but scoped
Public registration disabled by default; anonymous account creation gated by settings
Username/password registration requires activation/invitation when configured
Migration m056 disables public registration on existing databases
Service-fee helper now only credits confirmed outgoing payments
Vendor advisory states pre-1.7.0 versions affected, funds at risk of theft, and credentials may remain usable after upgrade
Evidence from the diff
The commit centralizes SSRF protection in new utilities (lnbits/utils/safe_http.py and outbound.py) and applies them to LNURL fetching, NIP-05 lookups, payment webhooks, WASM extension HTTP, and WebSockets. It pins DNS to IP before connecting, blocks private/special addresses by default, blocks the instance hostname and locally assigned/supplied IPs, limits redirects, and prevents user-controlled requests from looping back to the LNbits server. It also hardens registration: public registration now defaults to false, anonymous /api/v1/account creation requires explicit opt-in, and username/password registration requires activation/invitation when configured. A migration disables public registration on existing installs. A service-fee accounting guard prevents crediting fees for failed/non-outgoing payments.
Changed components
lnbits/utils/safe_http.pylnbits/utils/outbound.pylnbits/core/services/lnurl.pylnbits/core/services/nostr.pylnbits/core/services/notifications.pylnbits/core/services/payments.pylnbits/core/services/users.pylnbits/core/views/api.pylnbits/core/views/auth_api.pylnbits/core/wasm_ext/client/http.pylnbits/settings.pylnbits/core/migrations.pylnbits/app.pylnbits/core/models/misc.pylnbits/templates/components/admin/security.vuetools/docker-run.shInspect captured patch +2076 / −303
### .env.example
@@ -14,6 +14,12 @@
# When enabled (recommended), auth cookies require HTTPS and SSO will reject insecure HTTP.
AUTH_HTTPS_ONLY=true
+# Additional addresses belonging to this deployment (comma-separated IPv4/IPv6).
+# Assigned interface addresses and LNBITS_BASEURL's hostname are blocked automatically
+# for user-controlled outbound requests. tools/docker-run.sh supplies Docker host IPs.
+# Supply any additional public NAT/origin addresses that are not visible locally.
+LNBITS_OUTBOUND_HOST_IPS=[]
+
# === Logging and Development ===
DEBUG=False
@@ -371,8 +377,9 @@ LNBITS_USER_DEFAULT_EXTENSIONS="lnurlp"
# Start LNbits core only. The extensions are not loaded.
# LNBITS_EXTENSIONS_DEACTIVATE_ALL=true
-# Disable account creation for new users
-# LNBITS_ALLOW_NEW_ACCOUNTS=false
+# Public registration is disabled by default. Prefer the superuser creating
+# users and inviting them individually. Explicitly opt in to public registration.
+LNBITS_ALLOW_NEW_ACCOUNTS=false
# Enable Node Management without activating the LNBITS Admin GUI
# by setting the following variables to true.
### docs/guide/installation.md
@@ -302,6 +302,44 @@ LNBITS_ADMIN_UI=true AUTH_HTTPS_ONLY=false ./result/bin/lnbits --port 9000 --hos
<details>
<summary><strong>Show Docker instructions</strong> (official image, volumes, extensions)</summary>
+### Automatic outbound protection in Docker
+
+On Linux, use the launcher below in place of `docker run`. It supplies the host's
+current interface addresses to LNbits, preventing user-controlled requests from
+looping back to services on the Docker host. It does not require privileged mode
+or mounting the Docker socket inside the container.
+
+```sh
+wget https://raw.githubusercontent.com/lnbits/lnbits/main/tools/docker-run.sh -O lnbits-docker-run.sh
+# Review the script before running it.
+bash lnbits-docker-run.sh --detach --publish 5000:5000 --name lnbits \
+ --volume ${PWD}/.env:/app/.env \
+ --volume ${PWD}/data/:/app/data \
+ lnbits/lnbits
+```
+
+Use it when creating or recreating a container; existing containers need to be
+recreated to receive the host addresses. Recreate it after host addresses change.
+The image must contain the outbound protection utility and the
+`LNBITS_OUTBOUND_HOST_IPS` setting.
+
+Native installations detect addresses assigned to the machine automatically.
+Containers detect only their own addresses unless the host supplies its addresses.
+Neither method can reliably discover a public address hidden by cloud NAT or a
+router. For those deployments, set `LNBITS_OUTBOUND_HOST_IPS` in the host shell
+before running the launcher (or in LNbits' `.env` for native installations).
+The launcher preserves these extra addresses as well as adding interface addresses.
+A CDN's shared IP addresses are not automatically blocked; the saved LNbits
+hostname itself is blocked. Keep `LNBITS_BASEURL` set to the canonical instance URL.
+
+The superuser's Security settings show the protection status. This policy applies
+to user-controlled destinations, including redirects; trusted funding-source
+connections retain their existing configuration. Known same-instance LNURL payment
+and withdrawal endpoints run inside LNbits without connecting to the host. Other
+self-directed webhooks and URL downloads are rejected, including alternate ports.
+Custom same-instance LNURL endpoints need explicit support in the internal dispatcher.
+Private-address opt-ins do not override the self-target protection.
+
**Use latest image**
```sh
### lnbits/app.py
@@ -225,6 +225,7 @@ def create_app() -> FastAPI:
if settings.profiler:
add_profiler_middleware(app)
+ core_app_extra.local_lnurl_app = app
return app
### lnbits/core/migrations.py
@@ -1019,3 +1019,24 @@ async def m055_create_scheduled_job_runs(db: Connection):
CREATE INDEX idx_scheduled_job_runs_status
ON scheduled_job_runs (status, started_at)
""")
+
+
+async def m056_disable_public_registration(db: Connection):
+ # Only initialise this field for existing admin settings. An otherwise empty
+ # settings table must stay empty so first-start superuser setup still runs.
+ await db.execute("""
+ INSERT INTO system_settings (id, value, tag)
+ SELECT 'lnbits_allow_new_accounts', 'false', 'core'
+ WHERE EXISTS (
+ SELECT 1 FROM system_settings WHERE id = 'super_user' AND tag = 'core'
+ )
+ ON CONFLICT (id, tag) DO UPDATE SET value = 'false'
+ """)
+ await db.execute("""
+ UPDATE system_settings SET value = 'false'
+ WHERE id = 'lnbits_allow_new_accounts' AND tag = 'core'
+ """)
+ # Apply the one-time reset before first-start settings are persisted, too.
+ from lnbits.settings import settings
+
+ settings.lnbits_allow_new_accounts = False
### lnbits/core/models/misc.py
@@ -5,13 +5,15 @@
from typing import Any
from pydantic import BaseModel
+from starlette.types import ASGIApp
def _do_nothing(*_):
pass
class CoreAppExtra:
+ local_lnurl_app: ASGIApp | None = None
register_new_ext_routes: Callable = _do_nothing
register_new_wasm_ext_routes: Callable = _do_nothing
unregister_wasm_ext_routes: Callable = _do_nothing
### lnbits/core/services/lnurl.py
@@ -34,12 +34,14 @@
from pydantic import TypeAdapter, ValidationError
from lnbits.core.crud import update_wallet
+from lnbits.core.db import core_app_extra
from lnbits.core.models import CreateLnurlPayment, Wallet
from lnbits.core.models.lnurl import StoredPayLink
from lnbits.helpers import check_callback_url
from lnbits.settings import settings
from lnbits.utils.exchange_rates import fiat_amount_as_satoshis
from lnbits.utils.network import is_global_address
+from lnbits.utils.outbound import check_outbound_addresses, check_outbound_hostname
LNURL_MAX_REDIRECTS = 3
LNURL_MAX_RESPONSE_BYTES = 262_144
@@ -237,6 +239,19 @@ async def fetch_lnurl_pay_request(
return data.res, res2
+async def request_lnurl_json(
+ url: str, *, params: dict[str, str | int] | None = None, timeout: int = 5
+) -> dict[str, Any]:
+ """Fetch LNURL JSON with the core destination and redirect policy."""
+ return await _request_lnurl_json(
+ url,
+ params=params,
+ timeout=timeout,
+ user_agent=settings.user_agent,
+ tor_socks=None,
+ )
+
+
async def _get(
url: str,
*,
@@ -384,15 +399,8 @@ async def _request_lnurl_json(
raise LnurlResponseException("Invalid LNURL request URL.") from exc
for redirect_count in range(LNURL_MAX_REDIRECTS + 1):
- addresses, proxy = await _validate_lnurl_request_url(
- current_url, tor_socks=tor_socks
- )
- status_code, headers, body = await _send_lnurl_request(
- current_url,
- addresses=addresses,
- proxy=proxy,
- user_agent=user_agent,
- timeout=timeout,
+ status_code, headers, body = await _fetch_lnurl_response(
+ current_url, tor_socks=tor_socks, user_agent=user_agent, timeout=timeout
)
if status_code in {301, 302, 303, 307, 308}:
@@ -437,6 +445,7 @@ async def _validate_lnurl_request_url(
is_onion = host.endswith(".onion")
if parsed.scheme not in {"http", "https"}:
raise LnurlResponseException("LNURL request URL scheme must be HTTP or HTTPS.")
+ await _check_lnurl_self_target(host, [])
if is_onion:
return [], tor_socks or LNURL_TOR_SOCKS
@@ -458,6 +467,7 @@ async def _validate_lnurl_request_url(
raise LnurlResponseException(
"LNURL request target resolves to a private or non-global IP address."
)
+ await _check_lnurl_self_target(host, addresses)
return addresses, None
@@ -536,3 +546,77 @@ def _check_lnurl_redirect_rule(url: httpx.URL) -> None:
except re.error:
logger.warning(f"Invalid LNURL redirect URL rule: '{rule}'.")
raise LnurlResponseException("LNURL redirect was not allowed.")
+
+
+def _is_local_lnurl_url(url: httpx.URL) -> bool:
+ base = httpx.URL(settings.lnbits_baseurl)
+ if (
+ url.userinfo
+ or base.userinfo
+ or url.scheme not in {"http", "https"}
+ or (url.scheme, url.host, url.port) != (base.scheme, base.host, base.port)
+ or b"%" in url.raw_path.split(b"?", 1)[0]
+ ):
+ return False
+ # Only these public LNURL endpoints may run in-process. No arbitrary path,
+ # credentials, alternative port or network connection is permitted.
+ return any(
+ re.fullmatch(pattern, url.path)
+ for pattern in (
+ r"/\.well-known/lnurlp/[A-Za-z0-9_.-]+",
+ r"/api/v1/lnurl/wallet/[A-Za-z0-9_.-]+/cb",
+ r"/lnurlp/[A-Za-z0-9_-]+",
+ r"/lnurlp/api/v1/lnurl/(?:cb/)?[A-Za-z0-9_-]+",
+ r"/lnurlp/api/v1/well-known/[A-Za-z0-9_.-]+",
+ r"/withdraw/api/v1/lnurl/[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)?",
+ )
+ )
+
+
+async def _send_local_lnurl_request(
+ url: httpx.URL, *, timeout: int | None
+) -> tuple[int, dict[str, str], bytes]:
+ app = core_app_extra.local_lnurl_app
+ if app is None:
+ raise LnurlResponseException("Local LNURL service is unavailable.")
+
+ async def request() -> tuple[int, dict[str, str], bytes]:
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app),
+ follow_redirects=False,
+ trust_env=False,
+ ) as client:
+ async with client.stream("GET", url) as response:
+ body = await _read_limited_lnurl_response(response)
+ return response.status_code, dict(response.headers), body
+
+ try:
+ return await asyncio.wait_for(request(), timeout=timeout or 5)
+ except (asyncio.TimeoutError, httpx.RequestError) as exc:
+ raise LnurlResponseException("Local LNURL request failed.") from exc
+
+
+async def _check_lnurl_self_target(
+ host: str, addresses: list[ipaddress.IPv4Address | ipaddress.IPv6Address]
+) -> None:
+ try:
+ check_outbound_hostname(host)
+ if addresses:
+ await check_outbound_addresses(addresses)
+ except ValueError as exc:
+ raise LnurlResponseException(str(exc)) from exc
+
+
+async def _fetch_lnurl_response(
+ url: httpx.URL,
+ *,
+ tor_socks: str | None,
+ user_agent: str | None,
+ timeout: int | None,
+) -> tuple[int, dict[str, str], bytes]:
+ if _is_local_lnurl_url(url):
+ return await _send_local_lnurl_request(url, timeout=timeout)
+ addresses, proxy = await _validate_lnurl_request_url(url, tor_socks=tor_socks)
+ return await _send_lnurl_request(
+ url, addresses=addresses, proxy=proxy, user_agent=user_agent, timeout=timeout
+ )
### lnbits/core/services/nostr.py
@@ -1,7 +1,6 @@
import asyncio
from datetime import timedelta
-import httpx
from loguru import logger
from nostr_sdk import (
Client,
@@ -22,6 +21,7 @@
validate_identifier,
validate_pub_key,
)
+from lnbits.utils.safe_http import SafeHttpClient
async def send_nostr_dm(
@@ -92,7 +92,7 @@ async def fetch_nip5_details(identifier: str) -> tuple[str, list[str]]:
validate_identifier(identifier)
url = f"https://{domain}/.well-known/nostr.json?name={identifier}"
- async with httpx.AsyncClient() as client:
+ async with SafeHttpClient(timeout=5, apply_callback_rules=False) as client:
resp = await client.get(url)
resp.raise_for_status()
data = resp.json()
### lnbits/core/services/notifications.py
@@ -1,13 +1,10 @@
import asyncio
-import ipaddress
import json
import smtplib
-import socket
from asyncio.tasks import create_task
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from http import HTTPStatus
-from urllib.parse import urlparse
import httpx
from loguru import logger
@@ -36,8 +33,8 @@
from lnbits.core.services.websockets import websocket_manager
from lnbits.helpers import check_callback_url, is_valid_email_address
from lnbits.settings import settings
-from lnbits.utils.network import is_global_address
from lnbits.utils.nostr import normalize_private_key
+from lnbits.utils.safe_http import SafeHttpClient
notifications_queue: asyncio.Queue[NotificationMessage] = asyncio.Queue()
@@ -486,64 +483,20 @@ async def _post_webhook(payment: Payment) -> int:
if not payment.webhook:
raise ValueError("Webhook URL is missing.")
- url = httpx.URL(payment.webhook)
- parsed = urlparse(str(url))
- if not parsed.hostname:
- raise ValueError("Webhook URL host is missing.")
-
- addresses = await _resolve_webhook_host(parsed.hostname, parsed.port)
- if not settings.lnbits_callback_allow_private_ips and any(
- not is_global_address(address) for address in addresses
- ):
- raise ValueError("Webhook target IP address is not allowed.")
-
- request_url = url.copy_with(host=str(addresses[0]))
- headers = {
- "Host": parsed.netloc,
- "User-Agent": settings.user_agent,
- }
- async with httpx.AsyncClient(
- follow_redirects=False,
- trust_env=False,
+ async with SafeHttpClient(
+ timeout=40,
+ read_body=False,
+ allow_private_ips=settings.lnbits_callback_allow_private_ips,
) as client:
response = await client.post(
- request_url,
- headers=headers,
- extensions={"sni_hostname": parsed.hostname},
+ payment.webhook,
+ headers={"User-Agent": settings.user_agent},
json=payment.model_dump_json(),
- timeout=40,
)
response.raise_for_status()
return response.status_code
-async def _resolve_webhook_host(
- host: str, port: int | None
-) -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]:
- try:
- return [ipaddress.ip_address(host)]
- except ValueError:
- pass
-
- def resolve() -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]:
- try:
- infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
- except socket.gaierror as exc:
- raise ValueError("Webhook target could not be resolved.") from exc
-
- addresses: list[ipaddress.IPv4Address | ipaddress.IPv6Address] = []
- for info in infos:
- address = ipaddress.ip_address(info[4][0])
- if address not in addresses:
- addresses.append(address)
- return addresses
-
- addresses = await asyncio.to_thread(resolve)
- if not addresses:
- raise ValueError("Webhook target could not be resolved.")
- return addresses
-
-
def _telegram_error_message(error: Exception) -> str:
if isinstance(error, httpx.HTTPStatusError):
response = error.response
### lnbits/core/services/payments.py
@@ -1189,6 +1189,8 @@ def _validate_payment_request(
async def _credit_service_fee_wallet(
payment: Payment, wallet: Wallet | None = None, conn: Connection | None = None
):
+ if not payment.success or not payment.is_out:
+ return
if not wallet:
wallet = await get_wallet(payment.wallet_id, deleted=None, conn=conn)
if not wallet:
### lnbits/core/services/users.py
@@ -9,6 +9,7 @@
from lnbits.core.models.users import RegisterUser
from lnbits.db import Connection
from lnbits.settings import (
+ AuthMethods,
EditableSettings,
SuperSettings,
settings,
@@ -41,10 +42,19 @@
async def create_user_account(
- account: Account | None = None, wallet_name: str | None = None
+ account: Account | None = None,
+ wallet_name: str | None = None,
+ *,
+ activation_verified: bool = False,
) -> User:
if not settings.new_accounts_allowed:
raise ValueError("Account creation is disabled.")
+ if account is None and not settings.is_auth_method_allowed(
+ AuthMethods.user_id_only
+ ):
+ raise ValueError("Account creation by user ID is disabled.")
+ if settings.lnbits_require_user_activation and not activation_verified:
+ raise ValueError("Account creation requires an invitation or activation.")
return await create_user_account_no_ckeck(account, wallet_name)
### lnbits/core/views/api.py
@@ -4,7 +4,7 @@
from typing import Any
import pyqrcode
-from fastapi import APIRouter, Depends
+from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from lnbits.core.models import (
@@ -81,6 +81,12 @@ async def api_wallets(
@api_router.post("/api/v1/account", response_model=None)
async def api_create_account(data: CreateWallet):
+ if not settings.anonimous_account_creation_allowed:
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN,
+ "Anonymous account creation is disabled. Contact the administrator "
+ "for an invitation.",
+ )
user = await create_user_account(wallet_name=data.name)
if settings.lnbits_two_factor_enabled and settings.lnbits_two_factor_mandatory:
from lnbits.core.crud.users import get_account
### lnbits/core/views/auth_api.py
@@ -459,6 +459,8 @@ async def logout() -> JSONResponse:
@auth_router.post("/register")
async def register(data: RegisterUser) -> JSONResponse:
+ if not settings.new_accounts_allowed:
+ raise HTTPException(HTTPStatus.FORBIDDEN, "Account creation is disabled.")
if not settings.is_auth_method_allowed(AuthMethods.username_and_password):
raise HTTPException(
HTTPStatus.FORBIDDEN,
@@ -487,7 +489,7 @@ async def register(data: RegisterUser) -> JSONResponse:
username=data.username,
)
account.hash_password(data.password)
- await create_user_account(account)
+ await create_user_account(account, activation_verified=True)
return await _login_response(account)
### lnbits/core/views/generic.py
@@ -24,6 +24,7 @@
)
from lnbits.helpers import check_callback_url, template_renderer
from lnbits.settings import settings
+from lnbits.utils.outbound import outbound_protection_status
from ..crud import get_user
@@ -212,6 +213,9 @@ async def index(
"base.html",
{
"user": user.model_dump_json(),
+ "outbound_protection": (
+ outbound_protection_status() if user.super_user else None
+ ),
},
)
### lnbits/core/wasm_ext/client/http.py
@@ -1,13 +1,11 @@
from __future__ import annotations
-import ipaddress
-import socket
from typing import Any
from urllib.parse import urlparse
import httpx
-from lnbits.utils.network import is_global_address
+from lnbits.utils.safe_http import SafeHttpClient, UnsafeHttpDestinationError
from ..api.models import HttpRequest, HttpResponse
@@ -45,17 +43,15 @@ async def send_extension_http_request(
f"Extension '{extension_id}' is not allowed to request '{origin}'."
)
- await _reject_internal_host(request.url)
headers = _request_headers(request.headers)
body = request.body.encode() if request.body is not None else b""
if len(body) > 65_536:
raise ValueError("HTTP request body is too large.")
try:
- async with httpx.AsyncClient(
- follow_redirects=False,
+ async with SafeHttpClient(
timeout=_timeout_seconds(timeout_ms, HTTP_REQUEST_TIMEOUT_SECONDS),
- trust_env=False,
+ apply_callback_rules=False,
) as client:
async with client.stream(
request.method,
@@ -72,6 +68,8 @@ async def send_extension_http_request(
headers=_response_headers(dict(response.headers)),
body=response_body.decode(response.encoding or "utf-8", "replace"),
)
+ except (UnsafeHttpDestinationError, httpx.InvalidURL) as exc:
+ raise PermissionError("HTTP request target is not allowed.") from exc
except httpx.RequestError as exc:
raise ValueError("HTTP request failed.") from exc
@@ -114,52 +112,6 @@ def _url_port(parsed: Any) -> int | None:
raise PermissionError("HTTP request URL has an invalid port.") from exc
-async def _reject_internal_host(url: str) -> None:
- parsed = urlparse(url)
- hostname = parsed.hostname
- if not hostname:
- raise PermissionError("HTTP requests require a hostname.")
- if hostname == "localhost" or hostname.endswith(".localhost"):
- raise PermissionError("HTTP requests cannot target localhost.")
-
- try:
- address = ipaddress.ip_address(hostname)
- _reject_internal_address(address)
- return
- except ValueError:
- pass
-
- for address in await _resolve_host(hostname):
- _reject_internal_address(address)
-
-
-async def _resolve_host(
- hostname: str,
-) -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]:
- import asyncio
-
- def resolve() -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]:
- try:
- infos = socket.getaddrinfo(hostname, None, type=socket.SOCK_STREAM)
- except socket.gaierror as exc:
- raise PermissionError("HTTP request host could not be resolved.") from exc
-
- addresses: list[ipaddress.IPv4Address | ipaddress.IPv6Address] = []
- for info in infos:
- sockaddr = info[4]
- addresses.append(ipaddress.ip_address(sockaddr[0]))
- return addresses
-
- return await asyncio.to_thread(resolve)
-
-
-def _reject_internal_address(
- address: ipaddress.IPv4Address | ipaddress.IPv6Address,
-) -> None:
- if not is_global_address(address):
- raise PermissionError("HTTP requests cannot target internal network addresses.")
-
-
def _request_headers(headers: dict[str, str]) -> dict[str, str]:
clean: dict[str, str] = {}
for key, value in headers.items():
### lnbits/settings.py
@@ -2,6 +2,7 @@
import importlib
import importlib.metadata
+import ipaddress
import json
import os
import re
@@ -53,7 +54,7 @@ def validate_list(cls, val):
class UsersSettings(LNbitsSettings):
lnbits_admin_users: list[str] = Field(default=[])
lnbits_allowed_users: list[str] = Field(default=[])
- lnbits_allow_new_accounts: bool = Field(default=True)
+ lnbits_allow_new_accounts: bool = Field(default=False)
lnbits_ln_address_mode: Literal[
"core_first", "extension_first", "extension_only"
@@ -1197,6 +1198,8 @@ class EnvSettings(LNbitsSettings):
host: str = Field(default="127.0.0.1")
port: int = Field(default=5000, gt=0)
forwarded_allow_ips: str = Field(default="*")
+ # Deployment-supplied addresses hidden by container networking or NAT.
+ lnbits_outbound_host_ips: list[str] = Field(default=[])
lnbits_title: str = Field(default="LNbits API")
lnbits_path: str = Field(default=".")
lnbits_extensions_path: str = Field(default="lnbits")
@@ -1217,6 +1220,11 @@ class EnvSettings(LNbitsSettings):
task_heart_beat_verbose: bool = Field(default=False)
task_heart_beat_interval: int = Field(default=30)
+ @field_validator("lnbits_outbound_host_ips")
+ @classmethod
+ def validate_outbound_host_ips(cls, values: list[str]) -> list[str]:
+ return list(dict.fromkeys(str(ipaddress.ip_address(value)) for value in values))
+
@property
def has_default_extension_path(self) -> bool:
return self.lnbits_extensions_path == "lnbits"
@@ -1406,6 +1414,14 @@ def decode_env_values(cls, value: Any, info: ValidationInfo) -> Any:
return list_parse_fallback(value)
return value
+ @property
+ def anonimous_account_creation_allowed(self) -> bool:
+ return (
+ self.new_accounts_allowed
+ and self.is_auth_method_allowed(AuthMethods.user_id_only)
+ and not self.lnbits_require_user_activation
+ )
+
def is_user_allowed(self, user_id: str) -> bool:
return (
len(self.lnbits_allowed_users) == 0
### lnbits/templates/components/admin/security.vue
@@ -13,6 +13,29 @@
></q-input>
</div>
</div>
+ {% if outbound_protection %}
+ <q-banner class="q-mt-md rounded-borders bg-grey-9 text-white">
+ <div class="text-weight-bold">Outbound request protection</div>
+ User-supplied destinations cannot target this machine's assigned addresses
+ or the saved instance hostname ({{ outbound_protection.hostname }}). {% if
+ outbound_protection.container_without_host_ips %}
+ <p class="q-mt-sm q-mb-none">
+ Container host addresses have not been supplied. Use the Docker launcher
+ in the installation guide to include the host automatically.
+ </p>
+ {% elif outbound_protection.host_ip_count %}
+ <p class="q-mt-sm q-mb-none">
+ Deployment-supplied host addresses are also protected.
+ </p>
+ {% endif %}
+ <p class="q-mt-sm q-mb-none">
+ If a router or cloud NAT gives this server another public address, your
+ deployment must supply it using LNBITS_OUTBOUND_HOST_IPS. Addresses
+ hidden from this machine cannot be discovered reliably. Reload after
+ saving the base URL to refresh this status.
+ </p>
+ </q-banner>
+ {% endif %}
<q-separator class="q-mb-lg q-mt-md"></q-separator>
<h6 class="q-my-none q-mb-sm">
<span v-text="$t('authentication')"></span>
@@ -459,6 +482,12 @@
</div>
<div class="col-12 col-md-6">
<q-item tag="label" v-ripple>
+ <q-tooltip>
+ Not recommended. Enabling private-IP callbacks can let users
+ probe internal services and cloud metadata endpoints (SSRF).
+ Keep this disabled unless you have restricted callbacks to
+ trusted destinations.
+ </q-tooltip>
<q-item-section>
<q-item-label
v-text="$t('callback_allow_private_ips')"
### lnbits/templates/components/admin/users.vue
@@ -69,6 +69,12 @@
caption
v-text="$t('allow_creation_user_desc')"
></q-item-label>
+ <q-item-label caption>
+ Public registration is disabled by default. Prefer the superuser
+ creating users on the Users page and explicitly inviting them
+ individually. If you enable public registration, require
+ activation with one-time invitation codes.
+ </q-item-label>
</q-item-section>
<q-item-section avatar>
<q-toggle
### lnbits/utils/outbound.py
@@ -0,0 +1,83 @@
+"""Reject user-controlled requests back to the deployment itself."""
+
+import asyncio
+import errno
+import ipaddress
+import socket
+from pathlib import Path
+
+import httpx
+
+from lnbits.settings import settings
+
+IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
+
+
+def instance_hostname() -> str:
+ return (
+ httpx.URL(settings.lnbits_baseurl).raw_host.decode("ascii").lower().rstrip(".")
+ )
+
+
+def check_outbound_hostname(host: str) -> None:
+ hostname = httpx.URL(scheme="https", host=host).raw_host.decode("ascii")
+ if hostname.lower().rstrip(".") == instance_hostname():
+ raise ValueError("Requests to this server are not allowed.")
+
+
+async def check_outbound_addresses(addresses: list[IPAddress]) -> None:
+ # Check each request against current interfaces: do not cache stale addresses.
+ # Binding a UDP socket sends no packets and works without enumerating interfaces
+ # or adding a platform-specific dependency. Run OS operations off the event loop.
+ await asyncio.to_thread(_check_addresses, addresses)
+
+
+def outbound_protection_status() -> dict:
+ container = Path("/.dockerenv").exists() or Path("/run/.containerenv").exists()
+ return {
+ "hostname": instance_hostname(),
+ "container_without_host_ips": container
+ and not settings.lnbits_outbound_host_ips,
+ "host_ip_count": len(settings.lnbits_outbound_host_ips),
+ }
+
+
+def _check_addresses(addresses: list[IPAddress]) -> None:
+ supplied = {
+ address
+ for ip in settings.lnbits_outbound_host_ips
+ for address in _embedded_addresses(ipaddress.ip_address(ip))
+ }
+ for address in addresses:
+ for candidate in _embedded_addresses(address):
+ if candidate in supplied or _is_assigned(candidate):
+ raise ValueError("Requests to this server are not allowed.")
+
+
+def _embedded_addresses(address: IPAddress) -> list[IPAddress]:
+ result = [address]
+ if isinstance(address, ipaddress.IPv6Address):
+ if address.ipv4_mapped:
+ result.append(address.ipv4_mapped)
+ if address.sixtofour:
+ result.append(address.sixtofour)
+ if address.teredo:
+ result.extend(address.teredo)
+ if address in ipaddress.IPv6Network(
+ "64:ff9b::/96"
+ ) or address in ipaddress.IPv6Network("::/96"):
+ result.append(ipaddress.IPv4Address(address.packed[-4:]))
+ return result
+
+
+def _is_assigned(address: IPAddress) -> bool:
+ family = socket.AF_INET if address.version == 4 else socket.AF_INET6
+ try:
+ with socket.socket(family, socket.SOCK_DGRAM) as sock:
+ sock.bind((str(address), 0))
+ return True
+ except OSError as exc:
+ if exc.errno in {errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT}:
+ return False
+ # Unexpected errors (e.g. exhausted descriptors) must not disable protection.
+ raise ValueError("Cannot validate the outbound destination.") from exc
### lnbits/utils/safe_http.py
@@ -0,0 +1,296 @@
+"""Restricted HTTP transport for user-controlled destinations.
+
+Core and extensions use this client for arbitrary URLs supplied by users. By
+default it requires public destinations and applies administrator callback rules.
+Non-callback protocols can disable those rules while retaining destination checks.
+Trusted internal integrations have separate connection requirements. An explicit
+private_endpoint supplied by trusted administrator configuration permits LAN/ULA
+and loopback destinations only within that origin/path; public self-addresses,
+metadata addresses and redirects remain blocked.
+
+Core webhooks may explicitly retain the administrator's legacy private-IP opt-in
+with allow_private_ips. This does not bypass callback rules or self-target checks.
+"""
+
+import asyncio
+import ipaddress
+import socket
+from contextlib import asynccontextmanager
+
+import httpx
+from websockets.asyncio.client import connect
+
+from lnbits.helpers import check_callback_url
+from lnbits.settings import settings
+from lnbits.utils.outbound import check_outbound_addresses, check_outbound_hostname
+
+
+class UnsafeHttpDestinationError(ValueError):
+ """The request destination failed validation before connecting."""
+
+
+class SafeHttpClient:
+ def __init__(
+ self,
+ *,
+ timeout: float | httpx.Timeout | None = 10,
+ follow_redirects=False,
+ read_body=True,
+ private_endpoint=None,
+ apply_callback_rules: bool = True,
+ allow_private_ips: bool = False,
+ ):
+ # Only trusted administrator configuration may provide this exception.
+ # It is confined to one origin/path and never permits redirects.
+ if private_endpoint is not None and follow_redirects:
+ raise ValueError("Private endpoint redirects are not allowed.")
+ if allow_private_ips and (follow_redirects or private_endpoint is not None):
+ raise ValueError(
+ "Private callback access cannot use redirects or endpoints."
+ )
+ self.private_endpoint = private_endpoint
+ self.follow_redirects = follow_redirects
+ self.read_body = read_body
+ self.apply_callback_rules = apply_callback_rules
+ self.allow_private_ips = allow_private_ips
+ self.client = httpx.AsyncClient(
+ timeout=timeout, follow_redirects=False, trust_env=False
+ )
+
+ async def __aenter__(self):
+ await self.client.__aenter__()
+ return self
+
+ async def __aexit__(self, *args):
+ return await self.client.__aexit__(*args)
+
+ async def get(self, url, **kwargs):
+ return await self.request("GET", url, **kwargs)
+
+ async def post(self, url, **kwargs):
+ return await self.request("POST", url, **kwargs)
+
+ async def put(self, url, **kwargs):
+ return await self.request("PUT", url, **kwargs)
+
+ async def delete(self, url, **kwargs):
+ return await self.request("DELETE", url, **kwargs)
+
+ async def request(self, method, url, **kwargs):
+ async with self.stream(method, url, **kwargs) as response:
+ body = bytearray()
+ if self.read_body:
+ async for chunk in response.aiter_bytes(chunk_size=65536):
+ body.extend(chunk)
+ if len(body) > 1048576:
+ raise ValueError("HTTP response is too large.")
+ # The streaming response is closed here; return a buffered response.
+ headers = response.headers.copy()
+ headers.pop("content-encoding", None)
+ headers.pop("content-length", None)
+ return httpx.Response(
+ response.status_code,
+ headers=headers,
+ content=bytes(body),
+ request=response.request,
+ )
+
+ @asynccontextmanager
+ async def stream(self, method, url, **kwargs):
+ request = self.client.build_request(method, url, **kwargs)
+ for redirect in range(4):
+ try:
+ addresses = await validate_url(
+ request.url,
+ private_endpoint=self.private_endpoint,
+ apply_callback_rules=self.apply_callback_rules,
+ allow_private_ips=self.allow_private_ips,
+ )
+ except (ValueError, httpx.InvalidURL) as exc:
+ raise UnsafeHttpDestinationError(str(exc)) from exc
+ response = await self._send(request, addresses)
+ try:
+ if not self.follow_redirects or not response.has_redirect_location:
+ yield response
+ return
+ if redirect == 3:
+ raise ValueError("Too many HTTP redirects.")
+ # Only read-only downloads follow redirects. Never replay payments
+ # or webhook credentials/bodies to a destination chosen by a server.
+ if request.method not in {"GET", "HEAD"}:
+ raise ValueError("Redirect for this HTTP method is not allowed.")
+ target = request.url.join(response.headers["location"])
+ if request.url.scheme == "https" and target.scheme != "https":
+ raise ValueError("HTTPS downgrade is not allowed.")
+ headers = request.headers.copy()
+ if _origin(target) != _origin(request.url):
+ headers = httpx.Headers()
+ headers.pop("host", None)
+ # Do not carry cookies collected by the underlying client.
+ request = httpx.Request(request.method, target, headers=headers)
+ finally:
+ await response.aclose()
+ raise ValueError("HTTP request could not be completed.")
+
+ async def _send(self, request, addresses):
+ for index, address in enumerate(addresses):
+ pinned = httpx.Request(
+ request.method,
+ request.url.copy_with(host=address),
+ headers=request.headers,
+ content=request.content,
+ extensions={**request.extensions, "sni_hostname": request.url.host},
+ )
+ # Use the validated URL's hostname for HTTP routing and TLS verification.
+ pinned.headers["Host"] = request.url.netloc.decode("ascii")
+ # An IP-keyed pool must not reuse TLS verified for a different host.
+ pinned.headers["Connection"] = "close"
+ try:
+ return await self.client.send(pinned, stream=True)
+ except (httpx.ConnectError, httpx.ConnectTimeout):
+ if index == len(addresses) - 1:
+ raise
+ raise ValueError("HTTP target could not be resolved.")
+
+
+async def validate_url(
+ value, *, private_endpoint=None, apply_callback_rules=True, allow_private_ips=False
+) -> list[str]:
+ url = httpx.URL(value)
+ _check_http_url(url)
+ # Other protocols (e.g. WASM HTTP) enforce their own origin permissions.
+ if apply_callback_rules:
+ check_callback_url(str(url))
+ if private_endpoint is None:
+ check_outbound_hostname(url.host)
+ else:
+ _check_endpoint_scope(url, httpx.URL(private_endpoint))
+ try:
+ infos = await asyncio.wait_for(
+ asyncio.get_running_loop().getaddrinfo(
+ url.host,
+ url.port or (443 if url.scheme == "https" else 80),
+ type=socket.SOCK_STREAM,
+ ),
+ timeout=5,
+ )
+ addresses = list(dict.fromkeys(ipaddress.ip_address(i[4][0]) for i in infos))
+ except (OSError, ValueError, asyncio.TimeoutError) as exc:
+ raise ValueError("HTTP target could not be resolved.") from exc
+ await _check_addresses(
+ url,
+ addresses,
+ private_endpoint=private_endpoint,
+ allow_private_ips=allow_private_ips,
+ )
+ return [str(address) for address in addresses]
+
+
+@asynccontextmanager
+async def safe_websocket(url, *, private_endpoint=None):
+ """Connect to a validated, pinned WebSocket target without redirects or proxies."""
+ target = httpx.URL(url)
+ if target.scheme not in {"ws", "wss"}:
+ raise ValueError("WebSocket target is not allowed.")
+ http_url = target.copy_with(scheme="https" if target.scheme == "wss" else "http")
+ addresses = await validate_url(http_url, private_endpoint=private_endpoint)
+ for index, address in enumerate(addresses):
+ connected = False
+ try:
+ async with _NoRedirectConnect(
+ str(target),
+ host=address,
+ port=target.port or (443 if target.scheme == "wss" else 80),
+ proxy=None,
+ open_timeout=5,
+ close_timeout=1,
+ max_size=1048576,
+ ) as websocket:
+ connected = True
+ yield websocket
+ return
+ except (OSError, asyncio.TimeoutError):
+ if connected or index == len(addresses) - 1:
+ raise
+
+
+class _NoRedirectConnect(connect):
+ def process_redirect(self, exc):
+ return exc
+
+
+def _check_http_url(url):
+ if (
+ url.scheme not in {"http", "https"}
+ or not url.host
+ or url.userinfo
+ or "%" in url.host
+ ):
+ raise ValueError("HTTP target is not allowed.")
+
+
+def _check_endpoint_scope(url, endpoint):
+ _check_http_url(endpoint)
+ if (
+ endpoint.query
+ or endpoint.fragment
+ or _origin(url) != _origin(endpoint)
+ or not (
+ url.path == endpoint.path
+ or url.path.startswith(endpoint.path.rstrip("/") + "/")
+ )
+ or b"%" in url.raw_path.split(b"?", 1)[0]
+ ):
+ raise ValueError("Request is outside the configured private endpoint.")
+
+
+async def _check_addresses(
+ url, addresses, *, private_endpoint, allow_private_ips=False
+):
+ if (
+ addresses
+ and private_endpoint is not None
+ and all(_is_private_service_address(address) for address in addresses)
+ ):
+ if _origin(url) == _origin(httpx.URL(settings.lnbits_baseurl)):
+ raise ValueError("Requests to this server are not allowed.")
+ return
+ if not addresses or (
+ not allow_private_ips and any(not _is_public(address) for address in addresses)
+ ):
+ raise ValueError("HTTP target must resolve only to public addresses.")
+ check_outbound_hostname(url.host)
+ await check_outbound_addresses(addresses)
+
+
+def _is_private_service_address(address):
+ # Explicit private services may use LAN/ULA or loopback addresses, never
+ # cloud metadata/link-local, multicast, unspecified or transition addresses.
+ networks = (
+ ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8")
+ if address.version == 4
+ else ("fc00::/7", "::1/128")
+ )
+ return any(address in ipaddress.ip_network(network) for network in networks)
+
+
+def _origin(url):
+ return url.scheme, url.host, url.port
+
+
+def _is_public(address):
+ if not address.is_global or address.is_multicast or address.is_reserved:
+ return False
+ if isinstance(address, ipaddress.IPv4Address):
+ return True
+ if address.ipv4_mapped:
+ return _is_public(address.ipv4_mapped)
+ if address.sixtofour:
+ return _is_public(address.sixtofour)
+ if address.teredo:
+ return all(_is_public(ip) for ip in address.teredo)
+ if address in ipaddress.IPv6Network("64:ff9b:1::/48"):
+ return False
+ if address in ipaddress.IPv6Network("64:ff9b::/96"):
+ return _is_public(ipaddress.IPv4Address(address.packed[-4:]))
+ return True
### tests/api/test_api.py
@@ -37,8 +37,11 @@ async def test_create_account(client, settings: Settings):
settings.lnbits_allow_new_accounts = False
response = await client.post("/api/v1/account", json={"name": "test"})
- assert response.status_code == 400
- assert response.json().get("detail") == "Account creation is disabled."
+ assert response.status_code == 403
+ assert response.json().get("detail") == (
+ "Anonymous account creation is disabled. Contact the administrator "
+ "for an invitation."
+ )
settings.lnbits_allow_new_accounts = True
response = await client.post("/api/v1/account", json={"name": "test"})
### tests/conftest.py
@@ -122,6 +122,8 @@ async def app(
)
)
+ # Apply the test policy after migrations, before session user fixtures run.
+ _settings_cleanup(settings)
yield manager.app
### tests/unit/conftest.py
@@ -0,0 +1,28 @@
+import asyncio
+import socket
+from unittest.mock import AsyncMock, Mock
+
+import httpx
+import pytest
+
+from lnbits.utils.safe_http import SafeHttpClient
+
+
+@pytest.fixture
+async def safe_http_mock(monkeypatch):
+ """Exercise destination validation and pinning without making network requests."""
+ resolver = AsyncMock(
+ return_value=[
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443))
+ ]
+ )
+ monkeypatch.setattr(asyncio.get_running_loop(), "getaddrinfo", resolver)
+ handler = Mock(side_effect=lambda request: httpx.Response(200, json={}))
+ original_init = SafeHttpClient.__init__
+
+ def init(client, **kwargs):
+ original_init(client, **kwargs)
+ client.client._transport = httpx.MockTransport(handler)
+
+ monkeypatch.setattr(SafeHttpClient, "__init__", init)
+ return resolver, handler
### tests/unit/onchain/test_migrations.py
@@ -22,6 +22,11 @@ async def test_onchain_schema_uses_wallets_and_addresses(
try:
async with db.connect() as conn:
await migrations.m000_create_migrations_table(conn)
+ await conn.execute("""
+ CREATE TABLE system_settings (
+ id TEXT, value TEXT, tag TEXT, UNIQUE(id, tag)
+ )
+ """)
await conn.execute("""
CREATE TABLE wallets (
id TEXT PRIMARY KEY,
### tests/unit/test_outbound.py
@@ -0,0 +1,365 @@
+import asyncio
+import errno
+import ipaddress
+import os
+import socket
+import subprocess
+from datetime import datetime, timezone
+from pathlib import Path
+from shutil import which
+from unittest.mock import AsyncMock, Mock
+
+import httpx
+import pytest
+from fastapi import FastAPI, Request
+from fastapi.responses import StreamingResponse
+from lnurl import LnurlResponseException
+from pydantic import ValidationError
+
+from lnbits.core.db import core_app_extra
+from lnbits.core.models import User
+from lnbits.core.services import lnurl
+from lnbits.settings import Settings, settings
+from lnbits.utils import outbound, safe_http
+
+
+@pytest.fixture(autouse=True)
+def policy(monkeypatch):
+ monkeypatch.setattr(settings, "lnbits_baseurl", "https://instance.example/")
+ monkeypatch.setattr(settings, "lnbits_outbound_host_ips", [])
+ monkeypatch.setattr(settings, "lnbits_callback_url_rules", [])
+ monkeypatch.setattr(settings, "lnbits_lnurl_redirect_url_rules", [])
+ monkeypatch.setattr(outbound, "_is_assigned", lambda ip: False)
+
+
+def dns(monkeypatch, addresses):
+ resolver = AsyncMock(
+ return_value=[
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, 443)) for ip in addresses
+ ]
+ )
+ monkeypatch.setattr(asyncio.get_running_loop(), "getaddrinfo", resolver)
+ return resolver
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("target", ["instance.example", "INSTANCE.EXAMPLE."])
+async def test_hostname_blocked_before_dns_at_any_port(monkeypatch, target):
+ resolver = dns(monkeypatch, ["8.8.8.8"])
+ with pytest.raises(ValueError, match="this server"):
+ await safe_http.validate_url(f"https://{target}:8443/secrets")
+ resolver.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("kind", ["assigned", "supplied"])
+@pytest.mark.parametrize("target", ["8.8.8.8", "2001:4860:4860::8888"])
+async def test_public_self_ip_and_dns_alias_never_connect(monkeypatch, kind, target):
+ if kind == "assigned":
+ monkeypatch.setattr(outbound, "_is_assigned", lambda ip: str(ip) == target)
+ else:
+ monkeypatch.setattr(settings, "lnbits_outbound_host_ips", [target])
+ dns(monkeypatch, [target])
+ async with safe_http.SafeHttpClient() as client:
+ send = AsyncMock()
+ monkeypatch.setattr(client.client, "send", send)
+ for url in [
+ httpx.URL("https://alias.example"),
+ httpx.URL("https://x").copy_with(host=target),
+ ]:
+ with pytest.raises(ValueError, match="this server"):
+ await client.get(url)
+ send.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "target", ["::ffff:8.8.8.8", "64:ff9b::808:808", "2002:0808:0808::"]
+)
+async def test_embedded_self_ip_is_blocked(monkeypatch, target):
+ monkeypatch.setattr(settings, "lnbits_outbound_host_ips", ["8.8.8.8"])
+ with pytest.raises(ValueError, match="this server"):
+ await outbound.check_outbound_addresses([ipaddress.ip_address(target)])
+
+
+@pytest.mark.anyio
+async def test_mixed_answers_and_interface_changes_are_rechecked(monkeypatch):
+ dns(monkeypatch, ["8.8.8.8", "1.1.1.1"])
+ assert len(await safe_http.validate_url("https://public.example")) == 2
+ monkeypatch.setattr(outbound, "_is_assigned", lambda ip: str(ip) == "1.1.1.1")
+ with pytest.raises(ValueError, match="this server"):
+ await safe_http.validate_url("https://public.example")
+
+
+@pytest.mark.anyio
+async def test_redirect_to_self_never_connects(monkeypatch):
+ dns(monkeypatch, ["8.8.8.8"])
+ async with safe_http.SafeHttpClient(follow_redirects=True) as client:
+ send = AsyncMock(
+ return_value=httpx.Response(
+ 302, headers={"location": "https://instance.example:8443/secret"}
+ )
+ )
+ monkeypatch.setattr(client, "_send", send)
+ with pytest.raises(ValueError, match="this server"):
+ await client.get("https://public.example")
+ send.assert_awaited_once()
+
+
+@pytest.mark.anyio
+async def test_lnurl_public_self_ip_cannot_use_private_opt_in(monkeypatch):
+ monkeypatch.setattr(settings, "lnbits_lnurl_allow_private_ips", True)
+ monkeypatch.setattr(settings, "lnbits_outbound_host_ips", ["8.8.8.8"])
+ with pytest.raises(LnurlResponseException, match="this server"):
+ await lnurl._validate_lnurl_request_url(
+ httpx.URL("https://8.8.8.8:8443/"), tor_socks=None
+ )
+
+
+@pytest.mark.anyio
+async def test_local_payment_metadata_and_callback_use_no_network(monkeypatch):
+ app = FastAPI()
+ calls = []
+
+ @app.get("/.well-known/lnurlp/alice")
+ async def metadata(request: Request):
+ calls.append(request)
+ return {"callback": "https://instance.example/api/v1/lnurl/wallet/alice/cb"}
+
+ @app.get("/api/v1/lnurl/wallet/alice/cb")
+ async def callback(request: Request, amount: int):
+ calls.append(request)
+ return {"pr": "test-invoice", "amount": amount}
+
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", app)
+ send = AsyncMock(side_effect=AssertionError("Must not connect to the host"))
+ monkeypatch.setattr(lnurl, "_send_lnurl_request", send)
+ resolver = dns(monkeypatch, [])
+ data = await lnurl.request_lnurl_json(
+ "https://instance.example/.well-known/lnurlp/alice"
+ )
+ result = await lnurl.request_lnurl_json(data["callback"], params={"amount": 123000})
+ assert result == {"pr": "test-invoice", "amount": 123000}
+ assert all(
+ "authorization" not in r.headers and "cookie" not in r.headers for r in calls
+ )
+ send.assert_not_awaited()
+ resolver.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("phase", ["response", "body"])
+async def test_local_lnurl_timeout_cancels_stalled_request(monkeypatch, phase):
+ app = FastAPI()
+ started = asyncio.Event()
+ cancelled = asyncio.Event()
+
+ async def stall():
+ started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ cancelled.set()
+
+ @app.get("/.well-known/lnurlp/alice")
+ async def metadata():
+ if phase == "response":
+ await stall()
+ return {}
+
+ async def body():
+ yield b"{"
+ await stall()
+
+ return StreamingResponse(body(), media_type="application/json")
+
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", app)
+ with pytest.raises(
+ LnurlResponseException, match="Local LNURL request failed"
+ ) as exc:
+ await lnurl.request_lnurl_json(
+ "https://instance.example/.well-known/lnurlp/alice", timeout=1
+ )
+ assert started.is_set()
+ assert cancelled.is_set()
+ assert isinstance(exc.value.__cause__, asyncio.TimeoutError)
+
+
+@pytest.mark.parametrize(
+ "path",
+ [
+ "/lnurlp/abc",
+ "/lnurlp/api/v1/lnurl/abc",
+ "/lnurlp/api/v1/lnurl/cb/abc",
+ "/lnurlp/api/v1/well-known/alice",
+ "/withdraw/api/v1/lnurl/abc",
+ "/withdraw/api/v1/lnurl/cb/abc",
+ "/withdraw/api/v1/lnurl/abc/unique",
+ ],
+)
+def test_known_extension_lnurls_have_an_internal_path(path):
+ assert lnurl._is_local_lnurl_url(httpx.URL("https://instance.example" + path))
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "url",
+ [
+ "https://instance.example/admin/api/v1/settings",
+ "https://instance.example:8443/.well-known/lnurlp/alice",
+ "http://instance.example/.well-known/lnurlp/alice",
+ "https://user:secret@instance.example/.well-known/lnurlp/alice",
+ "https://instance.example/.well-known/lnurlp/%61lice",
+ "https://instance.example/lnurlp/abc/../../admin",
+ ],
+)
+async def test_internal_dispatch_does_not_allow_arbitrary_self_requests(
+ monkeypatch, url
+):
+ send = AsyncMock()
+ monkeypatch.setattr(lnurl, "_send_lnurl_request", send)
+ assert not lnurl._is_local_lnurl_url(httpx.URL(url))
+ with pytest.raises(LnurlResponseException):
+ await lnurl.request_lnurl_json(url)
+ send.assert_not_awaited()
+
+
+@pytest.mark.anyio
+async def test_internal_redirect_is_checked_and_missing_app_fails_closed(monkeypatch):
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", None)
+ with pytest.raises(LnurlResponseException, match="unavailable"):
+ await lnurl.request_lnurl_json("https://instance.example/lnurlp/abc")
+ app = FastAPI()
+
+ @app.get("/lnurlp/abc")
+ async def redirect():
+ from fastapi.responses import RedirectResponse
+
+ return RedirectResponse("https://instance.example:8443/secret")
+
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", app)
+ monkeypatch.setattr(settings, "lnbits_lnurl_redirect_url_rules", [".*"])
+ with pytest.raises(LnurlResponseException, match="this server"):
+ await lnurl.request_lnurl_json("https://instance.example/lnurlp/abc")
+
+
+def test_environment_addresses_are_validated_and_readonly():
+ configured = Settings(
+ _env_file=None, # pyright: ignore[reportCallIssue]
+ lnbits_outbound_host_ips="8.8.8.8,2001:4860:4860::8888,8.8.8.8",
+ )
+ assert configured.lnbits_outbound_host_ips == ["8.8.8.8", "2001:4860:4860::8888"]
+ assert "lnbits_outbound_host_ips" in Settings.readonly_fields()
+ with pytest.raises(ValidationError):
+ Settings(
+ _env_file=None, # pyright: ignore[reportCallIssue]
+ lnbits_outbound_host_ips=["attacker.example"],
+ )
+
+
+def test_bind_detection_sends_no_packets_and_fails_closed(monkeypatch):
+ # Restore the real function replaced by the fixture.
+ assigned = REAL_IS_ASSIGNED
+ sock = Mock()
+ sock.__enter__ = Mock(return_value=sock)
+ sock.__exit__ = Mock(return_value=False)
+ monkeypatch.setattr(outbound.socket, "socket", Mock(return_value=sock))
+ assert assigned(ipaddress.ip_address("8.8.8.8"))
+ sock.bind.assert_called_once_with(("8.8.8.8", 0))
+ sock.send.assert_not_called()
+ sock.connect.assert_not_called()
+ sock.bind.side_effect = OSError(errno.EADDRNOTAVAIL, "not assigned")
+ assert not assigned(ipaddress.ip_address("8.8.8.8"))
+ sock.bind.side_effect = OSError(errno.EMFILE, "resource exhaustion")
+ with pytest.raises(ValueError, match="Cannot validate"):
+ assigned(ipaddress.ip_address("8.8.8.8"))
+
+
+def test_real_loopback_bind_detection():
+ assert REAL_IS_ASSIGNED(ipaddress.ip_address("127.0.0.1"))
+
+
+def test_docker_launcher_supplies_host_and_extra_addresses(tmp_path):
+ bash = which("bash")
+ sh = which("sh")
+ assert bash and sh
+ hostname = tmp_path / "hostname"
+ hostname.write_text(f"#!{sh}\nprintf '8.8.8.8 2001:4860:4860::8888 \\n'\n")
+ hostname.chmod(0o700)
+ docker = tmp_path / "docker"
+ docker.write_text(f"#!{sh}\nprintf '%s\\n' \"$@\"\n")
+ docker.chmod(0o700)
+ env = {
+ **os.environ,
+ "PATH": f"{tmp_path}:/usr/bin:/bin",
+ "LNBITS_OUTBOUND_HOST_IPS": "1.1.1.1",
+ }
+ result = subprocess.run( # noqa: S603 - fixed local script, stubbed docker
+ [
+ bash,
+ str(Path("tools/docker-run.sh").resolve()),
+ "--name",
+ "test instance",
+ "lnbits/test",
+ ],
+ env=env,
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ assert result.stdout.splitlines() == [
+ "run",
+ "--env",
+ "LNBITS_OUTBOUND_HOST_IPS=8.8.8.8,2001:4860:4860::8888,1.1.1.1",
+ "--name",
+ "test instance",
+ "lnbits/test",
+ ]
+ hostname.write_text(f"#!{sh}\nexit 1\n")
+ result = subprocess.run( # noqa: S603 - fixed local script, stubbed docker
+ [bash, str(Path("tools/docker-run.sh").resolve()), "lnbits/test"],
+ env=env,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode != 0
+ assert not result.stdout
+
+
+REAL_IS_ASSIGNED = outbound._is_assigned
+
+
+@pytest.mark.anyio
+async def test_deployment_mapped_ipv4_address_also_blocks_plain_ipv4(monkeypatch):
+ monkeypatch.setattr(settings, "lnbits_outbound_host_ips", ["::ffff:8.8.8.8"])
+ with pytest.raises(ValueError, match="this server"):
+ await outbound.check_outbound_addresses([ipaddress.ip_address("8.8.8.8")])
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("super_user", [False, True])
+async def test_security_status_only_rendered_for_superuser(monkeypatch, super_user):
+ from lnbits.core.views import generic
+
+ renderer = Mock()
+ monkeypatch.setattr(generic, "template_renderer", lambda: renderer)
+ now = datetime.now(timezone.utc)
+ user = User(id="a" * 32, created_at=now, updated_at=now, super_user=super_user)
+ await generic.index(Request({"type": "http"}), user=user)
+ context = renderer.TemplateResponse.call_args.args[2]
+ assert bool(context["outbound_protection"]) is super_user
+
+
+def test_container_gap_is_reported_until_host_addresses_supplied(monkeypatch):
+ monkeypatch.setattr(outbound.Path, "exists", lambda _: True)
+ assert outbound.outbound_protection_status()["container_without_host_ips"]
+ monkeypatch.setattr(settings, "lnbits_outbound_host_ips", ["8.8.8.8"])
+ assert not outbound.outbound_protection_status()["container_without_host_ips"]
+
+
+@pytest.mark.parametrize("target", ["bücher.example", "xn--bcher-kva.example"])
+def test_hostname_guard_normalizes_international_names(monkeypatch, target):
+ monkeypatch.setattr(settings, "lnbits_baseurl", "https://bücher.example/")
+ with pytest.raises(ValueError, match="this server"):
+ outbound.check_outbound_hostname(target)
### tests/unit/test_registration_security.py
@@ -0,0 +1,127 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+from fastapi import FastAPI, HTTPException
+
+from lnbits.core.models import Account
+from lnbits.core.models.users import RegisterUser
+from lnbits.core.services import users
+from lnbits.core.views import api, auth_api
+from lnbits.settings import AuthMethods, UsersSettings
+
+
+def test_public_registration_defaults_to_disabled():
+ assert UsersSettings.model_fields["lnbits_allow_new_accounts"].default is False
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "restriction", ["closed", "auth_method", "activation", "allowlist"]
+)
+async def test_anonymous_account_endpoint_rejects_restricted_registration(
+ settings, monkeypatch, restriction
+):
+ if restriction == "closed":
+ settings.lnbits_allow_new_accounts = False
+ elif restriction == "auth_method":
+ settings.auth_allowed_methods = [AuthMethods.username_and_password.value]
+ elif restriction == "activation":
+ settings.lnbits_require_user_activation = True
+ settings.lnbits_user_activation_by_invitation_code = True
+ else:
+ settings.lnbits_allowed_users = ["existing-user"]
+ create = AsyncMock()
+ monkeypatch.setattr(api, "create_user_account", create)
+ app = FastAPI()
+ app.include_router(api.api_router)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.post("/api/v1/account", json={"name": "wallet"})
+ assert response.status_code == 403
+ create.assert_not_awaited()
+
+
+@pytest.mark.anyio
+async def test_anonymous_account_endpoint_explicit_opt_in(settings, monkeypatch):
+ settings.lnbits_allow_new_accounts = True
+ settings.auth_allowed_methods = [AuthMethods.user_id_only.value]
+ monkeypatch.setattr(
+ users,
+ "create_user_account_no_ckeck",
+ AsyncMock(return_value=SimpleNamespace(wallets=[{"id": "new-wallet"}])),
+ )
+ app = FastAPI()
+ app.include_router(api.api_router)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.post("/api/v1/account", json={"name": "wallet"})
+ assert response.status_code == 200
+ assert response.json()["id"] == "new-wallet"
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("account", [None, Account(id="a" * 32, username="newuser")])
+async def test_shared_account_creation_requires_activation(
+ settings, monkeypatch, account
+):
+ settings.lnbits_require_user_activation = True
+ create = AsyncMock()
+ monkeypatch.setattr(users, "create_user_account_no_ckeck", create)
+ with pytest.raises(ValueError, match="invitation or activation"):
+ await users.create_user_account(account)
+ create.assert_not_awaited()
+
+
+@pytest.mark.anyio
+async def test_closed_registration_does_not_consume_invitation(settings, monkeypatch):
+ settings.lnbits_allow_new_accounts = False
+ settings.lnbits_register_one_time_activation_codes = ["one-use"]
+ check = AsyncMock()
+ monkeypatch.setattr(auth_api, "check_register_activation_settings", check)
+ with pytest.raises(HTTPException) as exc:
+ await auth_api.register(_registration("one-use"))
+ assert exc.value.status_code == 403
+ assert settings.lnbits_register_one_time_activation_codes == ["one-use"]
+ check.assert_not_awaited()
+
+
+@pytest.mark.anyio
+async def test_registration_consumes_valid_invitation_once(settings, monkeypatch):
+ settings.lnbits_require_user_activation = True
+ settings.lnbits_user_activation_by_invitation_code = True
+ settings.lnbits_register_one_time_activation_codes = ["one-use"]
+ monkeypatch.setattr(
+ auth_api, "get_account_by_username", AsyncMock(return_value=None)
+ )
+ persist = AsyncMock()
+ monkeypatch.setattr(users, "set_settings_field", persist)
+ create = AsyncMock()
+ monkeypatch.setattr(users, "create_user_account_no_ckeck", create)
+ login = AsyncMock()
+ monkeypatch.setattr(auth_api, "_login_response", login)
+
+ for code in (None, "invalid"):
+ with pytest.raises(ValueError, match="[Ii]nvitation"):
+ await auth_api.register(_registration(code))
+ create.assert_not_awaited()
+ await auth_api.register(_registration("one-use"))
+ create.assert_awaited_once()
+ login.assert_awaited_once()
+ assert settings.lnbits_register_one_time_activation_codes == []
+ persist.assert_awaited_once_with("lnbits_register_one_time_activation_codes", [])
+ with pytest.raises(ValueError, match="Invalid invitation"):
+ await auth_api.register(_registration("one-use"))
+ assert create.await_count == 1
+
+
+def _registration(code):
+ return RegisterUser(
+ username="newuser",
+ password="password123",
+ password_repeat="password123",
+ invitation_code=code,
+ )
### tests/unit/test_safe_http.py
@@ -0,0 +1,433 @@
+import asyncio
+import socket
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+
+from lnbits.settings import settings
+from lnbits.utils import safe_http
+
+
+@pytest.fixture
+def anyio_backend():
+ return "asyncio"
+
+
+@pytest.fixture(autouse=True)
+def policy(monkeypatch):
+ monkeypatch.setattr(settings, "lnbits_callback_url_rules", [])
+
+
+def resolve(monkeypatch, addresses):
+ dns = AsyncMock(
+ return_value=[
+ (
+ socket.AF_INET6 if ":" in ip else socket.AF_INET,
+ socket.SOCK_STREAM,
+ 6,
+ "",
+ (ip, 443),
+ )
+ for ip in addresses
+ ]
+ )
+ monkeypatch.setattr(asyncio.get_running_loop(), "getaddrinfo", dns)
+ return dns
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "url",
+ [
+ "file:///tmp/server-key",
+ "ftp://public.example/file",
+ "gopher://public.example/",
+ "https://user:secret@public.example/",
+ "https://[fe80::1%25eth0]/",
+ ],
+)
+async def test_unsafe_scheme_or_authority_never_connects(monkeypatch, url):
+ dns = resolve(monkeypatch, ["93.184.216.34"])
+ async with safe_http.SafeHttpClient() as client:
+ send = AsyncMock()
+ monkeypatch.setattr(client.client, "send", send)
+ with pytest.raises((ValueError, httpx.InvalidURL)):
+ await client.get(url)
+ send.assert_not_awaited()
+ dns.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "ip",
+ [
+ "127.0.0.1",
+ "10.0.0.1",
+ "172.16.1.2",
+ "192.168.1.1",
+ "169.254.169.254",
+ "100.64.0.1",
+ "0.0.0.0", # noqa: S104 - rejected destination, not a listening address
+ "224.0.0.1",
+ "::1",
+ "::",
+ "fc00::1",
+ "fe80::1",
+ "ff02::1",
+ "::ffff:127.0.0.1",
+ "64:ff9b::7f00:1",
+ "64:ff9b:1::a00:1",
+ "2002:7f00:1::",
+ "2001:0:4136:e378:8000:63bf:3fff:fdd2",
+ ],
+)
+async def test_nonpublic_and_embedded_addresses_never_connect(monkeypatch, ip):
+ resolve(monkeypatch, [ip])
+ async with safe_http.SafeHttpClient() as client:
+ send = AsyncMock()
+ monkeypatch.setattr(client.client, "send", send)
+ with pytest.raises(ValueError):
+ await client.get("https://public.example/")
+ send.assert_not_awaited()
+
+
+@pytest.mark.anyio
+async def test_mixed_dns_answers_fail_closed(monkeypatch):
+ resolve(monkeypatch, ["93.184.216.34", "127.0.0.1"])
+ async with safe_http.SafeHttpClient() as client:
+ send = AsyncMock()
+ monkeypatch.setattr(client.client, "send", send)
+ with pytest.raises(ValueError):
+ await client.get("https://public.example/")
+ send.assert_not_awaited()
+
+
+@pytest.mark.anyio
+async def test_pins_ip_preserves_host_tls_body_and_headers(monkeypatch):
+ dns = resolve(monkeypatch, ["93.184.216.34"])
+ seen = []
+
+ def handler(request):
+ seen.append(request)
+ return httpx.Response(200, json={"ok": True})
+
+ async with safe_http.SafeHttpClient() as client:
+ client.client._transport = httpx.MockTransport(handler)
+ result = await client.post(
+ "https://public.example:8443/hook?token=abc",
+ json={"amount": 7},
+ headers={"Host": "localhost", "X-API-KEY": "secret"},
+ )
+ assert result.json() == {"ok": True}
+ assert dns.await_count == 1
+ assert seen[0].url.host == "93.184.216.34"
+ assert seen[0].headers["host"] == "public.example:8443"
+ assert seen[0].extensions["sni_hostname"] == "public.example"
+ assert seen[0].headers["X-API-KEY"] == "secret"
+ assert seen[0].content == b'{"amount": 7}'
+ assert seen[0].url.query == b"token=abc"
+
+
+@pytest.mark.anyio
+async def test_redirect_revalidates_and_drops_credentials(monkeypatch):
+ dns = resolve(monkeypatch, ["93.184.216.34"])
+ seen = []
+
+ def handler(request):
+ seen.append(request)
+ if len(seen) == 1:
+ return httpx.Response(
+ 302,
+ headers={
+ "location": "https://cdn.example/file",
+ "set-cookie": "key=secret",
+ },
+ )
+ return httpx.Response(200, content=b"download")
+
+ async with safe_http.SafeHttpClient(follow_redirects=True) as client:
+ client.client._transport = httpx.MockTransport(handler)
+ response = await client.get(
+ "https://public.example/file",
+ headers={
+ "Authorization": "secret",
+ "X-API-KEY": "secret",
+ "Cookie": "secret",
+ },
+ )
+ assert response.content == b"download"
+ assert dns.await_count == 2
+ assert seen[1].headers["host"] == "cdn.example"
+ assert all(
+ header not in seen[1].headers
+ for header in ["authorization", "x-api-key", "cookie"]
+ )
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("target", ["file:///tmp/key", "https://internal.example/key"])
+async def test_redirect_cannot_reach_files_or_private_dns(monkeypatch, target):
+ dns = resolve(monkeypatch, ["93.184.216.34"])
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ dns.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 443))
+ ]
+ return httpx.Response(302, headers={"location": target})
+
+ async with safe_http.SafeHttpClient(follow_redirects=True) as client:
+ client.client._transport = httpx.MockTransport(handler)
+ with pytest.raises(ValueError):
+ await client.get("https://public.example/")
+ assert len(calls) == 1
+
+
+@pytest.mark.anyio
+async def test_webhooks_do_not_follow_redirects_or_read_response(monkeypatch):
+ resolve(monkeypatch, ["93.184.216.34"])
+
+ class UnreadableBody(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ raise AssertionError("Webhook response body must not be read")
+ yield b""
+
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(
+ 302, headers={"location": "http://127.0.0.1/"}, stream=UnreadableBody()
+ )
+
+ async with safe_http.SafeHttpClient(read_body=False) as client:
+ client.client._transport = httpx.MockTransport(handler)
+ result = await client.post("https://public.example/hook", json={"paid": True})
+ assert result.status_code == 302
+ assert result.content == b""
+ assert len(calls) == 1
+
+
+@pytest.mark.anyio
+async def test_response_size_and_redirect_count_are_bounded(monkeypatch):
+ resolve(monkeypatch, ["93.184.216.34"])
+ async with safe_http.SafeHttpClient() as client:
+ client.client._transport = httpx.MockTransport(
+ lambda r: httpx.Response(200, content=b"x" * 1048577)
+ )
+ with pytest.raises(ValueError, match="too large"):
+ await client.get("https://public.example/")
+ async with safe_http.SafeHttpClient(follow_redirects=True) as client:
+ client.client._transport = httpx.MockTransport(
+ lambda r: httpx.Response(302, headers={"location": "/again"})
+ )
+ with pytest.raises(ValueError, match="Too many"):
+ await client.get("https://public.example/")
+
+
+@pytest.mark.anyio
+async def test_dns_failure_and_admin_rules_fail_closed(monkeypatch):
+ dns = resolve(monkeypatch, [])
+ with pytest.raises(ValueError):
+ await safe_http.validate_url("https://public.example/")
+ dns.side_effect = socket.gaierror()
+ with pytest.raises(ValueError):
+ await safe_http.validate_url("https://public.example/")
+ dns.reset_mock()
+ monkeypatch.setattr(
+ settings, "lnbits_callback_url_rules", [r"https://allowed\.example"]
+ )
+ with pytest.raises(ValueError):
+ await safe_http.validate_url("https://public.example/")
+ dns.assert_not_awaited()
+
+
+@pytest.mark.anyio
+async def test_noncallback_requests_keep_destination_checks(monkeypatch):
+ dns = resolve(monkeypatch, ["93.184.216.34"])
+ monkeypatch.setattr(
+ settings, "lnbits_callback_url_rules", [r"https://allowed\.example"]
+ )
+ async with safe_http.SafeHttpClient(apply_callback_rules=False) as client:
+ client.client._transport = httpx.MockTransport(
+ lambda request: httpx.Response(200)
+ )
+ assert (await client.get("https://public.example/")).status_code == 200
+ dns.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 443))
+ ]
+ with pytest.raises(safe_http.UnsafeHttpDestinationError):
+ await client.get("https://public.example/")
+ with pytest.raises(safe_http.UnsafeHttpDestinationError):
+ await client.get("file:///tmp/key")
+
+
+@pytest.mark.parametrize(
+ "options",
+ [{"follow_redirects": True}, {"private_endpoint": "http://mempool.example"}],
+)
+def test_private_callback_opt_in_cannot_enable_redirects_or_endpoint_exceptions(
+ options,
+):
+ with pytest.raises(ValueError, match="Private callback access"):
+ safe_http.SafeHttpClient(allow_private_ips=True, **options)
+
+
+@pytest.mark.anyio
+async def test_pinned_connection_falls_back_without_resolving_again(monkeypatch):
+ dns = resolve(monkeypatch, ["93.184.216.34", "1.1.1.1"])
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ if len(calls) == 1:
+ raise httpx.ConnectError("unreachable")
+ return httpx.Response(200)
+
+ async with safe_http.SafeHttpClient() as client:
+ client.client._transport = httpx.MockTransport(handler)
+ assert (await client.get("https://public.example/")).status_code == 200
+ dns.assert_awaited_once()
+ assert [request.url.host for request in calls] == ["93.184.216.34", "1.1.1.1"]
+ assert all(request.headers["host"] == "public.example" for request in calls)
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "address", ["127.0.0.1", "10.2.3.4", "172.20.0.2", "192.168.1.2", "::1", "fd00::1"]
+)
+async def test_private_endpoint_opt_in_is_scoped_and_pinned(monkeypatch, address):
+ resolve(monkeypatch, [address])
+ async with safe_http.SafeHttpClient(
+ private_endpoint="http://mempool.example:3006/testnet"
+ ) as client:
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ return httpx.Response(200, json=[])
+
+ client.client._transport = httpx.MockTransport(handler)
+ result = await client.get(
+ "http://mempool.example:3006/testnet/api/address/address/txs"
+ )
+ assert result.json() == []
+ assert requests[0].url.host == address
+ assert requests[0].headers["host"] == "mempool.example:3006"
+ for url in [
+ "http://other.example:3006/testnet/api",
+ "http://mempool.example:3007/testnet/api",
+ "http://mempool.example:3006/admin",
+ "http://mempool.example:3006/testnet/%2e%2e/admin",
+ ]:
+ with pytest.raises(ValueError):
+ await client.get(url)
+ assert len(requests) == 1
+ with pytest.raises(ValueError):
+ await safe_http.validate_url("http://mempool.example:3006/testnet/api")
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "address",
+ [
+ "169.254.169.254",
+ "169.254.170.2",
+ "0.0.0.0", # noqa: S104 - rejected destination, not a listening address
+ "224.0.0.1",
+ "::",
+ "fe80::1",
+ "ff02::1",
+ "::ffff:127.0.0.1",
+ "64:ff9b::7f00:1",
+ "100.100.100.200",
+ ],
+)
+async def test_private_opt_in_never_allows_metadata_or_special_addresses(
+ monkeypatch, address
+):
+ resolve(monkeypatch, [address])
+ with pytest.raises(ValueError):
+ await safe_http.validate_url(
+ "http://mempool.example/api", private_endpoint="http://mempool.example"
+ )
+
+
+@pytest.mark.anyio
+async def test_private_opt_in_keeps_public_self_and_mixed_dns_blocked(monkeypatch):
+ monkeypatch.setattr(settings, "lnbits_outbound_host_ips", ["8.8.8.8"])
+ resolve(monkeypatch, ["8.8.8.8"])
+ with pytest.raises(ValueError, match="this server"):
+ await safe_http.validate_url(
+ "https://alias.example/api", private_endpoint="https://alias.example"
+ )
+ resolve(monkeypatch, ["8.8.8.8", "10.0.0.2"])
+ with pytest.raises(ValueError):
+ await safe_http.validate_url(
+ "https://alias.example/api", private_endpoint="https://alias.example"
+ )
+ monkeypatch.setattr(settings, "lnbits_baseurl", "http://mempool.example:3006/")
+ resolve(monkeypatch, ["127.0.0.1"])
+ with pytest.raises(ValueError, match="this server"):
+ await safe_http.validate_url(
+ "http://mempool.example:3006/api",
+ private_endpoint="http://mempool.example:3006",
+ )
+
+
+def test_private_endpoint_cannot_enable_redirects():
+ with pytest.raises(ValueError, match="redirects"):
+ safe_http.SafeHttpClient(
+ private_endpoint="http://mempool.example", follow_redirects=True
+ )
+
+
+@pytest.mark.anyio
+async def test_websocket_pins_ip_preserving_origin_and_disables_proxy(monkeypatch):
+ from unittest.mock import Mock
+
+ resolve(monkeypatch, ["93.184.216.34"])
+ connection = AsyncMock()
+ factory = Mock(return_value=connection)
+ monkeypatch.setattr(safe_http, "_NoRedirectConnect", factory)
+ async with safe_http.safe_websocket("wss://mempool.example/api/v1/ws") as websocket:
+ assert websocket is connection.__aenter__.return_value
+ args, kwargs = factory.call_args
+ assert args == ("wss://mempool.example/api/v1/ws",)
+ assert kwargs["host"] == "93.184.216.34"
+ assert kwargs["port"] == 443 and kwargs["proxy"] is None
+ connection.__aexit__.assert_awaited_once()
+
+
+@pytest.mark.anyio
+async def test_websocket_rejects_private_without_opt_in(monkeypatch):
+ from unittest.mock import Mock
+
+ resolve(monkeypatch, ["127.0.0.1"])
+ factory = Mock(return_value=AsyncMock())
+ monkeypatch.setattr(safe_http, "_NoRedirectConnect", factory)
+ with pytest.raises(ValueError):
+ async with safe_http.safe_websocket("ws://mempool.example:3006/api/v1/ws"):
+ pytest.fail("connected")
+ factory.assert_not_called()
+ async with safe_http.safe_websocket(
+ "ws://mempool.example:3006/api/v1/ws",
+ private_endpoint="http://mempool.example:3006",
+ ):
+ pass
+ assert factory.call_args.kwargs["host"] == "127.0.0.1"
+
+
+def test_websocket_redirect_is_never_followed():
+ from websockets.datastructures import Headers
+ from websockets.exceptions import InvalidStatus
+ from websockets.http11 import Response
+
+ connection = safe_http._NoRedirectConnect(
+ "wss://mempool.example/api/v1/ws", proxy=None
+ )
+ for location in ["/admin", "ws://169.254.169.254/", "wss://other.example/"]:
+ error = InvalidStatus(Response(302, "Found", Headers({"Location": location})))
+ assert connection.process_redirect(error) is error
### tests/unit/test_security_accounting.py
@@ -0,0 +1,173 @@
+from importlib import import_module
+from unittest.mock import AsyncMock
+
+import pytest
+
+from lnbits.core import migrations
+from lnbits.core.crud.payments import (
+ create_payment,
+ get_payment,
+ get_standalone_payment,
+)
+from lnbits.core.crud.wallets import create_wallet, get_wallet
+from lnbits.core.helpers import run_migration
+from lnbits.core.models import Account, CreatePayment, PaymentState
+from lnbits.core.models.users import CreateUser
+from lnbits.core.services import payments, users
+from lnbits.core.views import user_api
+from lnbits.db import DB_TYPE, SQLITE, Database
+from lnbits.exceptions import PaymentError
+from lnbits.wallets.base import (
+ PaymentFailedStatus,
+ PaymentResponse,
+ PaymentSuccessStatus,
+)
+
+
+@pytest.fixture
+async def security_db(tmp_path, settings, monkeypatch):
+ if DB_TYPE != SQLITE:
+ pytest.skip("temporary accounting database is SQLite-only")
+ monkeypatch.setattr(settings, "lnbits_data_folder", str(tmp_path))
+ monkeypatch.setattr(settings, "lnbits_user_default_extensions", [])
+ db = Database("security_accounting")
+ for name in (
+ "crud.users",
+ "crud.wallets",
+ "crud.payments",
+ "crud.settings",
+ "crud.extensions",
+ "services.users",
+ "services.payments",
+ ):
+ monkeypatch.setattr(import_module(f"lnbits.core.{name}"), "db", db)
+ try:
+ async with db.connect() as conn:
+ await run_migration(conn, migrations, "core")
+ yield db
+ finally:
+ await db.engine.dispose()
+
+
+@pytest.mark.anyio
+async def test_closed_registration_allows_bootstrap_and_admin_invitation(
+ security_db, settings
+):
+ assert settings.lnbits_allow_new_accounts is False
+ initial = await users.init_admin_settings()
+ assert initial.super_user
+ assert initial.lnbits_allow_new_accounts is False
+ # The admin-only provisioning handler remains usable with public registration off.
+ created = await user_api.api_create_user(CreateUser(username="invited"))
+ assert created.id
+ assert created.password
+ with pytest.raises(ValueError, match="Account creation is disabled"):
+ await users.create_user_account(Account(id="b" * 32, username="uninvited"))
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("later_failure", [False, True])
+async def test_failed_withdrawal_releases_reserve_and_never_credits_service_fee(
+ security_db, settings, monkeypatch, later_failure
+):
+ wallet, fee_wallet, payment = await _funded_withdrawal(settings)
+ wallet = await get_wallet(wallet.id)
+ assert wallet is not None
+ assert wallet.balance_msat == 880000
+ if later_failure:
+ pending = await payments._handle_external_payment_response(
+ payment, PaymentResponse(ok=None)
+ )
+ assert pending.pending
+ fee_wallet = await get_wallet(fee_wallet.id)
+ assert fee_wallet is not None
+ assert fee_wallet.balance_msat == 0
+ monkeypatch.setattr(
+ payments,
+ "check_payment_status",
+ AsyncMock(return_value=PaymentFailedStatus()),
+ )
+ await payments.update_pending_payment(pending)
+ else:
+ with pytest.raises(PaymentError):
+ await payments._handle_external_payment_response(
+ payment, PaymentResponse(ok=False)
+ )
+ assert (await get_payment(payment.checking_id)).failed
+ wallet = await get_wallet(wallet.id)
+ fee_wallet = await get_wallet(fee_wallet.id)
+ assert wallet is not None
+ assert fee_wallet is not None
+ assert wallet.balance_msat == 1000000
+ assert fee_wallet.balance_msat == 0
+ assert await get_standalone_payment(f"service_fee_{payment.payment_hash}") is None
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("state", [PaymentState.PENDING, PaymentState.FAILED])
+async def test_service_fee_helper_rejects_unconfirmed_payment(
+ security_db, settings, state
+):
+ _, fee_wallet, payment = await _funded_withdrawal(settings)
+ payment.status = state
+ await payments._credit_service_fee_wallet(payment)
+ fee_wallet = await get_wallet(fee_wallet.id)
+ assert fee_wallet is not None
+ assert fee_wallet.balance_msat == 0
+ assert await get_standalone_payment(f"service_fee_{payment.payment_hash}") is None
+
+
+@pytest.mark.anyio
+async def test_confirmed_withdrawal_credits_service_fee_only_once(
+ security_db, settings, monkeypatch
+):
+ wallet, fee_wallet, payment = await _funded_withdrawal(settings)
+ monkeypatch.setattr(
+ payments, "send_payment_notification_in_background", lambda *_: None
+ )
+ for _ in range(2):
+ await payments.update_payment_success_status(
+ payment, PaymentSuccessStatus(fee_msat=2000)
+ )
+ fee_wallet = await get_wallet(fee_wallet.id)
+ wallet = await get_wallet(wallet.id)
+ assert fee_wallet is not None
+ assert wallet is not None
+ assert fee_wallet.balance_msat == 1000
+ assert wallet.balance_msat == 897000
+ fee_payment = await get_standalone_payment(f"service_fee_{payment.payment_hash}")
+ assert fee_payment is not None
+ assert fee_payment.success
+ assert fee_payment.amount == 1000
+
+
+async def _funded_withdrawal(settings):
+ wallet = await create_wallet(user_id="owner")
+ fee_wallet = await create_wallet(user_id="fee-owner")
+ settings.lnbits_service_fee_wallet = fee_wallet.id
+ settings.lnbits_service_fee = 1
+ settings.lnbits_service_fee_max = 0
+ await create_payment(
+ checking_id="funding",
+ data=CreatePayment(
+ wallet_id=wallet.id,
+ payment_hash="f" * 64,
+ bolt11="funding",
+ memo="Test funding",
+ amount_msat=1000000,
+ ),
+ status=PaymentState.SUCCESS,
+ )
+ payment = await create_payment(
+ checking_id="withdrawal",
+ data=CreatePayment(
+ wallet_id=wallet.id,
+ payment_hash="a" * 64,
+ bolt11="withdrawal",
+ memo="Test withdrawal",
+ amount_msat=-100000,
+ fee=-20000,
+ ),
+ status=PaymentState.PENDING,
+ )
+ return wallet, fee_wallet, payment
### tests/unit/test_services_lnurl.py
@@ -79,22 +79,26 @@ async def test_lnurl_requests_reject_private_ips_by_default(
)
settings.lnbits_lnurl_allow_private_ips = True
- addresses, proxy = await lnurl_service._validate_lnurl_request_url(
- target_url, tor_socks=None
- )
- assert addresses == [ipaddress.ip_address(target_ip)]
- assert proxy is None
+ if target_ip == "64:ff9b::127.0.0.1":
+ with pytest.raises(LnurlResponseException, match="this server"):
+ await lnurl_service._validate_lnurl_request_url(target_url, tor_socks=None)
+ else:
+ addresses, proxy = await lnurl_service._validate_lnurl_request_url(
+ target_url, tor_socks=None
+ )
+ assert addresses == [ipaddress.ip_address(target_ip)]
+ assert proxy is None
with pytest.raises(LnurlResponseException, match="not allowed over HTTP"):
await lnurl_service._validate_lnurl_request_url(
httpx.URL("http://93.184.216.34/lnurl"), tor_socks=None
)
- addresses, proxy = await lnurl_service._validate_lnurl_request_url(
- httpx.URL("http://127.0.0.1:8080/lnurl"), tor_socks=None
- )
- assert addresses == [ipaddress.ip_address("127.0.0.1")]
- assert proxy is None
+ # Private destination opt-in cannot allow arbitrary requests back to this server.
+ with pytest.raises(LnurlResponseException, match="this server"):
+ await lnurl_service._validate_lnurl_request_url(
+ httpx.URL("http://127.0.0.1:8080/lnurl"), tor_socks=None
+ )
@pytest.mark.anyio
### tests/unit/test_services_nostr.py
@@ -1,7 +1,9 @@
import asyncio
import json
+import socket
import time
+import httpx
import pytest
from nostr_sdk import (
Client,
@@ -109,7 +111,7 @@ async def test_fetch_nip5_details_returns_pubkey_and_relays(mocker: MockerFixtur
mocker.patch("lnbits.core.services.nostr.is_valid_url", return_value=True)
validate_identifier = mocker.patch("lnbits.core.services.nostr.validate_identifier")
validate_pub_key = mocker.patch("lnbits.core.services.nostr.validate_pub_key")
- mocker.patch("lnbits.core.services.nostr.httpx.AsyncClient", return_value=client)
+ mocker.patch("lnbits.core.services.nostr.SafeHttpClient", return_value=client)
pubkey, relays = await fetch_nip5_details("alice@example.com")
@@ -131,11 +133,75 @@ async def test_fetch_nip5_details_rejects_invalid_values(mocker: MockerFixture):
mocker.patch("lnbits.core.services.nostr.is_valid_url", return_value=True)
client = MockHTTPClient(MockHTTPResponse({"names": {}}))
- mocker.patch("lnbits.core.services.nostr.httpx.AsyncClient", return_value=client)
+ mocker.patch("lnbits.core.services.nostr.SafeHttpClient", return_value=client)
with pytest.raises(ValueError, match="NIP5 not name found"):
await fetch_nip5_details("alice@example.com")
+@pytest.mark.anyio
+async def test_nip05_pins_public_host_without_applying_webhook_rules(
+ safe_http_mock, settings
+):
+ resolver, handler = safe_http_mock
+ settings.lnbits_callback_url_rules = [r"https://webhooks\.example"]
+ pubkey = Keys.generate().public_key().to_hex()
+ handler.side_effect = lambda request: httpx.Response(
+ 200, json={"names": {"alice": pubkey}}
+ )
+
+ assert await fetch_nip5_details("alice@example.com") == (pubkey, [])
+
+ resolver.assert_awaited_once()
+ request = handler.call_args.args[0]
+ assert str(request.url) == "https://93.184.216.34/.well-known/nostr.json?name=alice"
+ assert request.headers["host"] == "example.com"
+ assert request.extensions["sni_hostname"] == "example.com"
+ assert request.extensions["timeout"]["read"] == 5
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "address",
+ ["127.0.0.1", "10.0.0.2", "169.254.169.254", "64:ff9b::7f00:1", "8.8.8.8"],
+)
+async def test_nip05_rejects_private_and_self_addresses(
+ safe_http_mock, settings, address
+):
+ resolver, handler = safe_http_mock
+ settings.lnbits_callback_allow_private_ips = True
+ settings.lnbits_outbound_host_ips = ["8.8.8.8"]
+ resolver.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, 443))
+ ]
+ with pytest.raises(ValueError):
+ await fetch_nip5_details("alice@example.com")
+ handler.assert_not_called()
+
+
+@pytest.mark.anyio
+async def test_nip05_rejects_instance_hostname_before_dns(safe_http_mock, settings):
+ resolver, handler = safe_http_mock
+ settings.lnbits_baseurl = "https://example.com"
+ with pytest.raises(ValueError, match="this server"):
+ await fetch_nip5_details("alice@example.com")
+ resolver.assert_not_awaited()
+ handler.assert_not_called()
+
+
+@pytest.mark.anyio
+async def test_nip05_bounds_response_and_does_not_follow_redirects(safe_http_mock):
+ _, handler = safe_http_mock
+ handler.side_effect = lambda request: httpx.Response(
+ 302, headers={"location": "http://127.0.0.1/"}
+ )
+ with pytest.raises(httpx.HTTPStatusError):
+ await fetch_nip5_details("alice@example.com")
+ handler.assert_called_once()
+ handler.side_effect = lambda request: httpx.Response(200, content=b"x" * 1048577)
+ with pytest.raises(ValueError, match="too large"):
+ await fetch_nip5_details("alice@example.com")
+
+
@pytest.mark.parametrize("local_part", ["alice", "john-doe", "a.b_c-d", "Bob-42"])
def test_validate_identifier_accepts_nip05_characters(local_part: str):
validate_identifier(local_part)
### tests/unit/test_services_notifications.py
@@ -1,6 +1,6 @@
import asyncio
-import ipaddress
import json
+import socket
from http import HTTPStatus
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -581,27 +581,22 @@ async def test_dispatch_webhook_marks_missing_invalid_and_failed_requests(
side_effect=ValueError("blocked"),
)
mocker.patch(
- "lnbits.core.services.notifications.httpx.AsyncClient",
+ "lnbits.core.services.notifications.SafeHttpClient",
return_value=invalid_client,
)
await dispatch_webhook(invalid_payment)
assert (await get_payment(invalid_payment.checking_id)).webhook_status == "-1"
assert invalid_client.posts == []
- mocker.patch(
- "lnbits.core.services.notifications._resolve_webhook_host",
- mocker.AsyncMock(return_value=[ipaddress.ip_address("93.184.216.34")]),
- )
-
error_payment = await _create_payment(wallet, webhook="https://error.example")
assert error_payment.webhook is not None
mocker.patch(
"lnbits.core.services.notifications.check_callback_url",
return_value=None,
)
mocker.patch(
- "lnbits.core.services.notifications.httpx.AsyncClient",
+ "lnbits.core.services.notifications.SafeHttpClient",
return_value=MockHTTPClient(
post_response=httpx.Response(
500,
@@ -616,7 +611,7 @@ async def test_dispatch_webhook_marks_missing_invalid_and_failed_requests(
request_payment = await _create_payment(wallet, webhook="https://request.example")
assert request_payment.webhook is not None
mocker.patch(
- "lnbits.core.services.notifications.httpx.AsyncClient",
+ "lnbits.core.services.notifications.SafeHttpClient",
return_value=MockHTTPClient(
post_exception=httpx.RequestError(
"boom",
@@ -662,93 +657,130 @@ async def test_dispatch_webhook_status_is_scoped_to_payment(
@pytest.mark.anyio
@pytest.mark.parametrize(
- "target_ip", ["169.254.169.254", "64:ff9b::127.0.0.1", "64:ff9b::a9fe:a9fe"]
+ "target_ip",
+ ["10.0.0.2", "169.254.169.254", "64:ff9b::127.0.0.1", "64:ff9b::a9fe:a9fe"],
)
async def test_dispatch_webhook_blocks_private_targets(
- settings: Settings, mocker: MockerFixture, target_ip: str
+ settings: Settings, safe_http_mock, target_ip: str
):
+ resolver, handler = safe_http_mock
settings.lnbits_callback_url_rules = []
+ resolver.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", (target_ip, 80))
+ ]
target_url = httpx.URL("http://metadata.internal/metadata").copy_with(
host=target_ip
)
wallet = await _create_wallet()
- response = httpx.Response(
- 200,
- request=httpx.Request("POST", "http://169.254.169.254/metadata"),
- )
- client = MockHTTPClient(post_response=response)
- mocker.patch(
- "lnbits.core.services.notifications.httpx.AsyncClient",
- return_value=client,
- )
-
direct_payment = await _create_payment(wallet, webhook=str(target_url))
await dispatch_webhook(direct_payment)
-
assert (await get_payment(direct_payment.checking_id)).webhook_status == "-1"
- assert client.posts == []
+ handler.assert_not_called()
- resolver = mocker.patch(
- "lnbits.core.services.notifications._resolve_webhook_host",
- mocker.AsyncMock(
- return_value=[
- ipaddress.ip_address("93.184.216.34"),
- ipaddress.ip_address(target_ip),
- ]
- ),
+ resolver.return_value.insert(
+ 0, (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443))
)
dns_payment = await _create_payment(
wallet, webhook="https://attacker.example/internal"
)
await dispatch_webhook(dns_payment)
-
assert (await get_payment(dns_payment.checking_id)).webhook_status == "-1"
- assert client.posts == []
+ handler.assert_not_called()
settings.lnbits_callback_allow_private_ips = True
- resolver.return_value = [ipaddress.ip_address(target_ip)]
+ resolver.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", (target_ip, 443))
+ ]
allowed_payment = await _create_payment(
wallet, webhook="https://attacker.example/internal"
)
await dispatch_webhook(allowed_payment)
-
- assert (await get_payment(allowed_payment.checking_id)).webhook_status == "200"
- assert client.posts[0][0] == httpx.URL(
- "https://attacker.example/internal"
- ).copy_with(host=str(ipaddress.ip_address(target_ip)))
+ # The administrator's opt-in retains private access, but never self-targets.
+ expected = "-1" if target_ip == "64:ff9b::127.0.0.1" else "200"
+ assert (await get_payment(allowed_payment.checking_id)).webhook_status == expected
+ if expected == "200":
+ assert handler.call_args.args[0].url == httpx.URL(
+ "https://attacker.example/internal"
+ ).copy_with(host=target_ip)
+ else:
+ handler.assert_not_called()
@pytest.mark.anyio
+@pytest.mark.parametrize("status_code", [200, 302])
async def test_dispatch_webhook_pins_allowed_target(
- settings: Settings, mocker: MockerFixture
+ settings: Settings, safe_http_mock, status_code
):
+ resolver, handler = safe_http_mock
settings.lnbits_callback_url_rules = []
wallet = await _create_wallet()
payment = await _create_payment(
wallet, webhook="https://callback.example:8443/paid"
)
- client = MockHTTPClient(
- post_response=httpx.Response(
- 200,
- request=httpx.Request("POST", "https://93.184.216.34:8443/paid"),
- )
- )
- mocker.patch(
- "lnbits.core.services.notifications._resolve_webhook_host",
- mocker.AsyncMock(return_value=[ipaddress.ip_address("93.184.216.34")]),
- )
- client_factory = mocker.patch(
- "lnbits.core.services.notifications.httpx.AsyncClient",
- return_value=client,
+ expected_body = payment.model_dump_json()
+
+ class UnreadableBody(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ raise AssertionError("Webhook response body must not be read")
+ yield b""
+
+ handler.side_effect = lambda request: httpx.Response(
+ status_code, headers={"location": "http://127.0.0.1/"}, stream=UnreadableBody()
)
+ await dispatch_webhook(payment)
+
+ assert (await get_payment(payment.checking_id)).webhook_status == str(status_code)
+ resolver.assert_awaited_once()
+ handler.assert_called_once()
+ request = handler.call_args.args[0]
+ assert str(request.url) == "https://93.184.216.34:8443/paid"
+ assert request.headers["host"] == "callback.example:8443"
+ assert request.headers["user-agent"] == settings.user_agent
+ assert request.extensions["sni_hostname"] == "callback.example"
+ assert request.extensions["timeout"]["read"] == 40
+ assert request.method == "POST"
+ assert json.loads(request.content) == expected_body
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("allow_private", [False, True])
+@pytest.mark.parametrize("kind", ["hostname", "supplied", "assigned"])
+async def test_dispatch_webhook_blocks_self_targets(
+ settings: Settings, safe_http_mock, monkeypatch, allow_private, kind
+):
+ from lnbits.utils import outbound
+
+ _, handler = safe_http_mock
+ settings.lnbits_callback_url_rules = []
+ settings.lnbits_callback_allow_private_ips = allow_private
+ settings.lnbits_baseurl = "https://instance.example/"
+ if kind == "supplied":
+ settings.lnbits_outbound_host_ips = ["93.184.216.34"]
+ elif kind == "assigned":
+ monkeypatch.setattr(
+ outbound, "_is_assigned", lambda address: str(address) == "93.184.216.34"
+ )
+ target = "instance.example" if kind == "hostname" else "alias.example"
+ wallet = await _create_wallet()
+ payment = await _create_payment(wallet, webhook=f"https://{target}:8443/paid")
await dispatch_webhook(payment)
+ assert (await get_payment(payment.checking_id)).webhook_status == "-1"
+ handler.assert_not_called()
+
- assert (await get_payment(payment.checking_id)).webhook_status == "200"
- assert str(client.posts[0][0]) == "https://93.184.216.34:8443/paid"
- assert client.posts[0][1]["headers"]["Host"] == "callback.example:8443"
- assert client.posts[0][1]["extensions"] == {"sni_hostname": "callback.example"}
- client_factory.assert_called_once_with(follow_redirects=False, trust_env=False)
+@pytest.mark.anyio
+async def test_dispatch_webhook_keeps_callback_rules_with_private_opt_in(
+ settings: Settings, safe_http_mock
+):
+ resolver, handler = safe_http_mock
+ settings.lnbits_callback_allow_private_ips = True
+ settings.lnbits_callback_url_rules = [r"https://allowed\.example"]
+ wallet = await _create_wallet()
+ payment = await _create_payment(wallet, webhook="https://blocked.example/paid")
+ await dispatch_webhook(payment)
+ assert (await get_payment(payment.checking_id)).webhook_status == "-1"
+ resolver.assert_not_awaited()
+ handler.assert_not_called()
@pytest.mark.anyio
### tests/unit/test_wasm_extension_http.py
@@ -1,9 +1,7 @@
-import ipaddress
-from typing import cast
+import socket
import httpx
import pytest
-from pytest_mock.plugin import MockerFixture
from lnbits.core.wasm_ext.api.models import HttpRequest
from lnbits.core.wasm_ext.client import http as wasm_http
@@ -30,22 +28,41 @@ def test_wasm_http_origin_normalization_and_url_rejections():
@pytest.mark.anyio
@pytest.mark.parametrize(
- "target_ip", ["127.0.0.1", "64:ff9b::127.0.0.1", "64:ff9b::a9fe:a9fe"]
+ "target_ip",
+ ["127.0.0.1", "10.0.0.2", "64:ff9b::127.0.0.1", "64:ff9b::a9fe:a9fe", "8.8.8.8"],
)
-async def test_wasm_http_rejects_internal_hosts(mocker: MockerFixture, target_ip: str):
- with pytest.raises(PermissionError, match="localhost"):
- await wasm_http._reject_internal_host("https://localhost/api")
+async def test_wasm_http_rejects_internal_and_self_hosts(
+ safe_http_mock, settings, target_ip
+):
+ resolver, handler = safe_http_mock
+ settings.lnbits_callback_allow_private_ips = True
+ settings.lnbits_outbound_host_ips = ["8.8.8.8"]
+ resolver.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", (target_ip, 443))
+ ]
+ for url in (
+ "https://api.example.com",
+ str(httpx.URL("https://example.com").copy_with(host=target_ip)),
+ ):
+ with pytest.raises(PermissionError, match="target is not allowed"):
+ await wasm_http.send_extension_http_request(
+ "demoext", [url], HttpRequest(url=url, body=None)
+ )
+ handler.assert_not_called()
- with pytest.raises(PermissionError, match="internal network"):
- url = httpx.URL("https://api.example.com/api").copy_with(host=target_ip)
- await wasm_http._reject_internal_host(str(url))
- mocker.patch(
- "lnbits.core.wasm_ext.client.http._resolve_host",
- mocker.AsyncMock(return_value=[ipaddress.ip_address(target_ip)]),
- )
- with pytest.raises(PermissionError, match="internal network"):
- await wasm_http._reject_internal_host("https://api.example.com")
+@pytest.mark.anyio
+async def test_wasm_http_rejects_self_hostname_before_dns(safe_http_mock, settings):
+ resolver, handler = safe_http_mock
+ settings.lnbits_baseurl = "https://api.example.com"
+ with pytest.raises(PermissionError, match="target is not allowed"):
+ await wasm_http.send_extension_http_request(
+ "demoext",
+ ["https://api.example.com"],
+ HttpRequest(url="https://api.example.com", body=None),
+ )
+ resolver.assert_not_awaited()
+ handler.assert_not_called()
def test_wasm_http_strips_forbidden_headers_and_normalizes_timeout():
@@ -70,62 +87,65 @@ def test_wasm_http_strips_forbidden_headers_and_normalizes_timeout():
@pytest.mark.anyio
-async def test_wasm_http_request_enforces_policies_and_response_bounds(
- mocker: MockerFixture,
+async def test_wasm_http_request_enforces_policies_and_pins_dns(
+ safe_http_mock, settings
):
- mocker.patch(
- "lnbits.core.wasm_ext.client.http._reject_internal_host",
- mocker.AsyncMock(),
- )
- client = _FakeAsyncClient(
- _FakeStreamResponse(
- status_code=201,
+ resolver, handler = safe_http_mock
+ settings.lnbits_callback_url_rules = [r"https://webhooks\.example"]
+
+ def respond(request):
+ # A later resolution would reach loopback, but the request is already pinned.
+ resolver.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 443))
+ ]
+ return httpx.Response(
+ 201,
headers={
"content-type": "application/json",
"set-cookie": "session=secret",
},
- chunks=[b'{"ok":true}'],
+ content=b'{"ok":true}',
)
- )
- mocker.patch("lnbits.core.wasm_ext.client.http.httpx.AsyncClient", client.factory)
+ handler.side_effect = respond
response = await wasm_http.send_extension_http_request(
"demoext",
[{"host": "https://api.example.com"}],
HttpRequest(
method="POST",
url="https://api.example.com/path",
- headers={"Host": "evil.example", "X-Test": "yes"},
+ headers={"Host": "evil.example", "Cookie": "secret", "X-Test": "yes"},
body="{}",
),
timeout_ms=500,
max_response_bytes=100,
)
-
assert response.status_code == 201
assert response.body == '{"ok":true}'
assert response.headers == {"content-type": "application/json"}
- assert client.kwargs["follow_redirects"] is False
- assert client.kwargs["trust_env"] is False
- assert client.kwargs["timeout"] == 0.5
- assert client.stream_kwargs["headers"] == {"X-Test": "yes"}
+ resolver.assert_awaited_once()
+ request = handler.call_args.args[0]
+ assert str(request.url) == "https://93.184.216.34/path"
+ assert request.headers["host"] == "api.example.com"
+ assert request.headers["x-test"] == "yes"
+ assert "cookie" not in request.headers
+ assert request.content == b"{}"
+ assert request.extensions["sni_hostname"] == "api.example.com"
+ assert request.extensions["timeout"]["read"] == 0.5
with pytest.raises(PermissionError, match="not allowed"):
await wasm_http.send_extension_http_request(
"demoext",
[{"host": "https://api.example.com"}],
HttpRequest(url="https://other.example.com/path", body=None),
)
+ resolver.assert_awaited_once()
+ handler.assert_called_once()
@pytest.mark.anyio
-async def test_wasm_http_request_rejects_oversized_bodies_and_responses(
- mocker: MockerFixture,
-):
- mocker.patch(
- "lnbits.core.wasm_ext.client.http._reject_internal_host",
- mocker.AsyncMock(),
- )
+async def test_wasm_http_request_rejects_oversized_bodies_and_responses(safe_http_mock):
+ resolver, handler = safe_http_mock
with pytest.raises(ValueError, match="body is too large"):
await wasm_http.send_extension_http_request(
"demoext",
@@ -137,82 +157,63 @@ async def test_wasm_http_request_rejects_oversized_bodies_and_responses(
body="x" * 65_537,
),
)
-
+ resolver.assert_not_awaited()
+ handler.assert_not_called()
+ handler.side_effect = lambda request: httpx.Response(200, content=b"123456789")
with pytest.raises(ValueError, match="response is too large"):
- await wasm_http._read_limited_response(
- cast(httpx.Response, _FakeStreamResponse(chunks=[b"12345", b"67890"])),
+ await wasm_http.send_extension_http_request(
+ "demoext",
+ ["https://api.example.com"],
+ HttpRequest(url="https://api.example.com", body=None),
max_response_bytes=8,
)
+ handler.side_effect = lambda request: httpx.Response(
+ 200, content=b"x" * (wasm_http.HTTP_MAX_RESPONSE_BYTES + 1)
+ )
+ with pytest.raises(ValueError, match="response is too large"):
+ await wasm_http.send_extension_http_request(
+ "demoext",
+ ["https://api.example.com"],
+ HttpRequest(url="https://api.example.com", body=None),
+ )
@pytest.mark.anyio
-async def test_wasm_http_request_hides_transport_errors(mocker: MockerFixture):
- mocker.patch(
- "lnbits.core.wasm_ext.client.http._reject_internal_host",
- mocker.AsyncMock(),
+async def test_wasm_http_preserves_disabled_limits_and_does_not_follow_redirects(
+ safe_http_mock,
+):
+ _, handler = safe_http_mock
+ body = b"x" * 1048577
+ handler.side_effect = lambda request: httpx.Response(200, content=body)
+ response = await wasm_http.send_extension_http_request(
+ "demoext",
+ ["https://api.example.com"],
+ HttpRequest(url="https://api.example.com", body=None),
+ timeout_ms=0,
+ max_response_bytes=0,
)
- client = _FakeAsyncClient(_FakeStreamError())
- mocker.patch("lnbits.core.wasm_ext.client.http.httpx.AsyncClient", client.factory)
+ assert response.body == body.decode()
+ assert handler.call_args.args[0].extensions["timeout"]["read"] is None
+ handler.reset_mock()
+ handler.side_effect = lambda request: httpx.Response(
+ 302, headers={"location": "https://other.example.com"}
+ )
+ response = await wasm_http.send_extension_http_request(
+ "demoext",
+ ["https://api.example.com"],
+ HttpRequest(url="https://api.example.com", body=None),
+ )
+ assert response.status_code == 302
+ handler.assert_called_once()
+
- with pytest.raises(ValueError, match="HTTP request failed"):
+@pytest.mark.anyio
+async def test_wasm_http_request_hides_transport_errors(safe_http_mock):
+ _, handler = safe_http_mock
+ handler.side_effect = httpx.ConnectError("sensitive transport detail")
+ with pytest.raises(ValueError, match=r"^HTTP request failed\.$"):
await wasm_http.send_extension_http_request(
"demoext",
[{"host": "https://api.example.com"}],
HttpRequest(url="https://api.example.com/path", body=None),
)
-
-
-class _FakeAsyncClient:
- def __init__(self, response):
- self.response = response
- self.kwargs = {}
- self.stream_kwargs = {}
-
- def factory(self, **kwargs):
- self.kwargs = kwargs
- return self
-
- async def __aenter__(self):
- return self
-
- async def __aexit__(self, *_args):
- return False
-
- def stream(self, method, url, **kwargs):
- self.stream_kwargs = {"method": method, "url": url, **kwargs}
- return self.response
-
-
-class _FakeStreamResponse:
- def __init__(
- self,
- *,
- status_code: int = 200,
- headers: dict[str, str] | None = None,
- chunks: list[bytes] | None = None,
- ):
- self.status_code = status_code
- self.headers = headers or {}
- self.encoding = "utf-8"
- self._chunks = chunks or []
-
- async def __aenter__(self):
- return self
-
- async def __aexit__(self, *_args):
- return False
-
- async def aiter_bytes(self):
- for chunk in self._chunks:
- yield chunk
-
-
-class _FakeStreamError:
- async def __aenter__(self):
- raise httpx.RequestError(
- "network failed",
- request=httpx.Request("GET", "https://api.example.com"),
- )
-
- async def __aexit__(self, *_args):
- return False
### tools/docker-run.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Linux Docker launcher: forward host addresses without giving containers host access.
+set -euo pipefail
+
+if [[ $# -eq 0 ]]; then
+ echo 'Usage: bash tools/docker-run.sh [docker run options] IMAGE [COMMAND...]' >&2
+ exit 2
+fi
+
+# hostname -I reads assigned interfaces; it does not contact an external IP service.
+host_addresses=$(hostname -I)
+read -r -a host_ips <<< "$host_addresses"
+if [[ ${#host_ips[@]} -eq 0 ]]; then
+ echo 'Could not detect host addresses; container was not started.' >&2
+ exit 1
+fi
+joined_ips=$(IFS=,; echo "${host_ips[*]}")
+extra_ips=${LNBITS_OUTBOUND_HOST_IPS:-}
+if [[ -n $extra_ips && $extra_ips != "[]" ]]; then
+ joined_ips="$joined_ips,$extra_ips"
+fi
+exec docker run --env "LNBITS_OUTBOUND_HOST_IPS=$joined_ips" "$@"Why this scored 90/100
Evidence and disclosure record
Verified links used to place this patch in context. External claims remain attributed to their publishers.
Centralize SSRF protection and block self-targeted requests
Incident-response change centralizing outbound-request validation and blocking requests that resolve to the LNbits server itself. The pull request was opened hours after the November 8 shutdown warning and merged into v1.7.0.
LNbits 1.7.0 security update and recovery guidance
The vendor says every version before 1.7.0 is affected, funds are at risk of theft, and exposed credentials may remain usable after an upgrade. It requires key and secret rotation in addition to updating.
LNbits v1.7.0 urgent security update
The first stable release containing the November incident fixes and recovery controls. LNbits instructs all operators to update immediately.
LNbits v1.7.0 security release announcement
Official announcement that v1.7.0 is released and operators should follow the linked upgrade guidance.
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.