What changed, and why it matters
This commit fixes a security gap in LNbits' on-chain (Bitcoin) wallet feature. Previously, a wallet owner could point their wallet at any Mempool-style block explorer URL, including internal or attacker-controlled addresses. The server would then make HTTP requests to that URL, which could leak data, reach internal services, or be tricked by redirects. The patch introduces an administrator-controlled 'approved explorer URL' list, validates URLs strictly, blocks unapproved endpoints before any network request, and disables HTTP redirects. It also lets users see and pick only approved URLs in the wallet settings screen.
Treat this as a security fix and include it in the next release. Operators should review lnbits_onchain_explorer_urls in admin settings, ensure only trusted Mempool endpoints are listed, and advise users with unapproved saved endpoints to select an approved one. No CVE is referenced in the commit; consider requesting one if the project tracks SSRF fixes.
Security signals we found
Server-Side Request Forgery (SSRF) mitigation: unapproved mempool endpoints are rejected before httpx.AsyncClient is instantiated
Open redirect / redirect-to-attacker mitigation: follow_redirects=False on mempool requests
Input validation: Pydantic validator strips paths, rejects credentials, fragments, query strings, control chars, backslashes, and invalid ports
Authorization boundary: only server admins can modify approved explorer URLs; wallet owners cannot bypass via UI or API
Defense in depth: endpoint re-validated on every request, so revoking approval blocks ongoing scans
Error-message hygiene: unapproved endpoint errors are surfaced to user; other failures are generic to avoid leaking URLs/credentials
Evidence from the diff
The change adds a new setting lnbits_onchain_explorer_urls (default [“https://mempool.space”]) with a Pydantic validator that rejects non-HTTP(S) schemes, credentials, query strings, fragments, control characters, backslashes, and malformed ports. A new validate_mempool_endpoint() helper raises ExplorerNotAllowedError if a wallet’s mempool_endpoint is not in the approved list. MempoolExplorer now validates the endpoint in init and on every _request(), preventing client creation and blocking long-running scans if an admin later revokes approval. API endpoints return HTTP 403 for ExplorerNotAllowedError and 400 when saving an unapproved config. The UI replaces the free-text mempool endpoint field with a dropdown of approved URLs and warns when a saved URL is no longer approved. Tests cover SSRF-like targets (169.254.169.254, dotted decimal, ::ffff:127.0.0.1, host variants, ports, paths), redirect blocking, and admin-only approval changes.
Changed components
lnbits/core/services/blockexplorer.pylnbits/core/services/onchain.pylnbits/core/views/onchain_api.pylnbits/core/views/wallet_api.pylnbits/settings.pylnbits/core/models/wallets.pylnbits/templates/components/admin/blockexplorer.vuelnbits/templates/components/onchain/wallet-config.vueInspect captured patch +354 / −22
### lnbits/core/models/wallets.py
@@ -353,6 +353,7 @@ class OnchainWalletConfigResponse(OnchainConfig):
network: Literal["Mainnet", "Testnet", "Testnet4"] = "Mainnet"
lnbits_explorer_network: str | None = None
explorer_url: str
+ approved_mempool_endpoints: list[str]
class NewHotWallet(BaseModel):
### lnbits/core/services/blockexplorer.py
@@ -215,13 +215,23 @@ async def broadcast(self, raw: str) -> str:
return await self.client.broadcast(raw)
+class ExplorerNotAllowedError(ValueError):
+ def __init__(self):
+ super().__init__(
+ "Explorer URL is not approved. Select an approved explorer in wallet "
+ "settings or ask a server administrator to approve this URL."
+ )
+
+
class MempoolExplorer:
def __init__(
self,
config: OnchainConfig,
network: str,
client: httpx.AsyncClient | None = None,
):
+ self.endpoint = config.mempool_endpoint.rstrip("/")
+ validate_mempool_endpoint(self.endpoint)
self.client = client or httpx.AsyncClient(
base_url=mempool_url(config, network) + "/",
timeout=15,
@@ -237,13 +247,13 @@ async def __aexit__(self, *args):
await self.client.__aexit__(*args)
async def checkpoint(self) -> ScanCheckpoint:
- response = await self.client.get("api/blocks/tip/height")
+ response = await self._request("GET", "api/blocks/tip/height")
response.raise_for_status()
height = int(response.text)
return ScanCheckpoint(height=height, block_hash=await self.block_hash(height))
async def block_hash(self, height: int) -> str:
- response = await self.client.get(f"api/block-height/{height}")
+ response = await self._request("GET", f"api/block-height/{height}")
response.raise_for_status()
block_hash = response.text.strip()
if not TXID.fullmatch(block_hash):
@@ -264,7 +274,7 @@ async def history(
and tx["status"]["confirmed"]
and tx["status"]["block_height"] <= checkpoint.height
}
- response = await self.client.get(f"api/address/{address}/txs")
+ response = await self._request("GET", f"api/address/{address}/txs")
response.raise_for_status()
page = response.json()
result: dict[str, dict] = {}
@@ -294,7 +304,9 @@ async def history(
if last in seen or not TXID.fullmatch(last):
raise ValueError("Invalid explorer pagination")
seen.add(last)
- response = await self.client.get(f"api/address/{address}/txs/chain/{last}")
+ response = await self._request(
+ "GET", f"api/address/{address}/txs/chain/{last}"
+ )
response.raise_for_status()
page = response.json()
else:
@@ -309,32 +321,41 @@ async def _check_missing_pending(self, previous: list[dict], result: dict) -> No
for tx in previous:
if tx["txid"] in result:
continue
- response = await self.client.get(f"api/tx/{tx['txid']}/status")
+ response = await self._request("GET", f"api/tx/{tx['txid']}/status")
if response.status_code == 404:
continue
response.raise_for_status()
result[tx["txid"]] = {**tx, "status": response.json()}
async def utxos(self, address: str) -> list[dict]:
- response = await self.client.get(f"api/address/{address}/utxo")
+ response = await self._request("GET", f"api/address/{address}/utxo")
response.raise_for_status()
return response.json()
async def fees(self) -> dict:
- response = await self.client.get("api/v1/fees/recommended")
+ response = await self._request("GET", "api/v1/fees/recommended")
response.raise_for_status()
return response.json()
async def raw_transaction(self, txid: str) -> str:
- response = await self.client.get(f"api/tx/{txid}/hex")
+ response = await self._request("GET", f"api/tx/{txid}/hex")
response.raise_for_status()
return response.text.strip()
async def broadcast(self, raw: str) -> str:
- response = await self.client.post("api/tx", content=raw)
+ response = await self._request("POST", "api/tx", content=raw)
response.raise_for_status()
return response.text.strip()
+ async def _request(
+ self, method: str, path: str, *, content: str | None = None
+ ) -> httpx.Response:
+ # Recheck long-running scans when an administrator revokes approval.
+ validate_mempool_endpoint(self.endpoint)
+ return await self.client.request(
+ method, path, content=content, follow_redirects=False
+ )
+
class LnbitsExplorer(BlockExplorerWalletSession):
def __init__(self, network: str):
@@ -480,6 +501,12 @@ def explorer_client(config: OnchainConfig, network: str) -> Explorer:
return MempoolExplorer(config, network)
+def validate_mempool_endpoint(endpoint: str) -> None:
+ # Exact base URLs only: approving a host does not approve other ports or paths.
+ if endpoint.rstrip("/") not in settings.lnbits_onchain_explorer_urls:
+ raise ExplorerNotAllowedError()
+
+
def _client() -> ElectrumClient:
return ElectrumClient(
settings.lnbits_blockexplorer_electrum_url,
### lnbits/core/services/onchain.py
@@ -48,7 +48,12 @@
Snapshot,
)
from lnbits.core.models.wallets import OnchainMeta, OnchainWallet
-from lnbits.core.services.blockexplorer import TXID, Explorer, explorer_client
+from lnbits.core.services.blockexplorer import (
+ TXID,
+ Explorer,
+ ExplorerNotAllowedError,
+ explorer_client,
+)
from lnbits.core.services.wallets import get_wallet_addresses
from lnbits.db import Connection
from lnbits.settings import settings
@@ -654,7 +659,11 @@ async def _scan_with_lease(wallet_id: str, *, max_age: int | None = None) -> Non
outcome = "failed"
reason = type(exc).__name__
# Never return credentials, explorer URLs, raw responses or stack traces.
- error = "Blockchain update failed. Previous balances and history are retained."
+ error = (
+ str(exc)
+ if isinstance(exc, ExplorerNotAllowedError)
+ else "Blockchain update failed. Previous balances and history are retained."
+ )
finally:
try:
saved = await _finish_scan(wallet_id, lease, error, checkpoint=checkpoint)
### lnbits/core/views/onchain_api.py
@@ -25,7 +25,11 @@
SignedTransaction,
)
from lnbits.core.models.wallets import NewHotWallet, OnchainMeta, OnchainWallet
-from lnbits.core.services.blockexplorer import TXID, explorer_client
+from lnbits.core.services.blockexplorer import (
+ TXID,
+ ExplorerNotAllowedError,
+ explorer_client,
+)
from lnbits.core.services.onchain import (
decrypt_wallet_mnemonic,
encrypt_wallet_mnemonic,
@@ -202,6 +206,8 @@ async def api_tx_broadcast(
raise ValueError("Invalid broadcast response")
request_scan(auth.wallet_id)
return tx_id
+ except ExplorerNotAllowedError as exc:
+ raise HTTPException(HTTPStatus.FORBIDDEN, str(exc)) from exc
except Exception as exc:
raise HTTPException(
400, "Broadcast failed. Check the transaction status before retrying."
@@ -354,6 +360,8 @@ async def sign_hot_wallet_payment(
):
raise ValueError("Inputs have changed")
return await run_in_threadpool(sign_payment, wallet, encrypted, data)
+ except ExplorerNotAllowedError as exc:
+ raise HTTPException(HTTPStatus.FORBIDDEN, str(exc)) from exc
except Exception as exc:
# Native library/encryption errors must not disclose key material.
raise HTTPException(
@@ -393,6 +401,8 @@ async def fee_estimates(auth: OnchainAuth = Depends(require_onchain_read)):
wallet.onchain_config, wallet.onchain_network or "Mainnet"
) as client:
return await client.fees()
+ except ExplorerNotAllowedError as exc:
+ raise HTTPException(HTTPStatus.FORBIDDEN, str(exc)) from exc
except Exception as exc:
raise HTTPException(503, "Fee estimates are unavailable") from exc
@@ -414,6 +424,8 @@ async def previous_transaction(
if len(raw) > 8_000_000 or not re.fullmatch(r"[0-9a-fA-F]+", raw):
raise ValueError("Invalid transaction")
return raw
+ except ExplorerNotAllowedError as exc:
+ raise HTTPException(HTTPStatus.FORBIDDEN, str(exc)) from exc
except Exception as exc:
raise HTTPException(503, "Previous transaction is unavailable") from exc
### lnbits/core/views/wallet_api.py
@@ -33,9 +33,11 @@
WalletType,
)
from lnbits.core.services.blockexplorer import (
+ ExplorerNotAllowedError,
explorer_url,
local_explorer_network,
provider_name,
+ validate_mempool_endpoint,
)
from lnbits.core.services.lightning_address import set_wallet_lightning_address
from lnbits.core.services.onchain import request_scan
@@ -353,6 +355,11 @@ async def api_update_config(
HTTPStatus.CONFLICT,
"Create another LNbits wallet to use a different Bitcoin network",
)
+ if provider_name(data, network) == "mempool":
+ try:
+ validate_mempool_endpoint(data.mempool_endpoint)
+ except ExplorerNotAllowedError as exc:
+ raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
await update_onchain_wallet_config(data, wallet_id=auth.wallet_id, network=network)
request_scan(auth.wallet_id)
response_data = data.model_dump()
@@ -362,6 +369,7 @@ async def api_update_config(
**response_data,
lnbits_explorer_network=local_explorer_network(),
explorer_url=explorer_url(data, network),
+ approved_mempool_endpoints=settings.lnbits_onchain_explorer_urls,
)
@@ -381,4 +389,5 @@ async def api_get_config(
**data,
lnbits_explorer_network=local_explorer_network(),
explorer_url=explorer_url(config, network),
+ approved_mempool_endpoints=settings.lnbits_onchain_explorer_urls,
)
### lnbits/settings.py
@@ -11,6 +11,7 @@
from pathlib import Path
from time import gmtime, strftime, time
from typing import Any, Literal, get_args, get_origin
+from urllib.parse import urlsplit
from uuid import uuid4
from loguru import logger
@@ -915,6 +916,7 @@ class NodeUISettings(LNbitsSettings):
class BlockExplorerSettings(LNbitsSettings):
+ lnbits_onchain_explorer_urls: list[str] = Field(default=["https://mempool.space"])
lnbits_blockexplorer_enabled: bool = Field(default=True)
lnbits_blockexplorer_public_api: bool = Field(default=False)
lnbits_blockexplorer_in_user_menu: bool = Field(default=True)
@@ -924,6 +926,29 @@ class BlockExplorerSettings(LNbitsSettings):
# one of: main, test, test4, regtest, signet
lnbits_blockexplorer_network: str = Field(default="main")
+ @field_validator("lnbits_onchain_explorer_urls")
+ @classmethod
+ def validate_onchain_explorer_urls(cls, values: list[str]) -> list[str]:
+ for value in values:
+ url = urlsplit(value)
+ if (
+ url.scheme not in ("http", "https")
+ or not url.hostname
+ or url.username is not None
+ or url.password is not None
+ or url.query
+ or url.fragment
+ or any(c.isspace() or ord(c) < 32 for c in value)
+ or "\\" in value
+ ):
+ raise ValueError(
+ "Enter HTTP(S) explorer URLs without credentials, "
+ "queries or fragments"
+ )
+ # Accessing port also rejects malformed or out-of-range ports.
+ _ = url.port
+ return list(dict.fromkeys(value.rstrip("/") for value in values))
+
class AuthMethods(Enum):
user_id_only = "user-id-only"
### lnbits/templates/components/admin/blockexplorer.vue
@@ -131,5 +131,23 @@
></q-btn>
</div>
</div>
+ <q-separator class="q-mb-lg q-mt-md"></q-separator>
+ <h6 class="q-my-none q-mb-sm">Approved onchain wallet explorers</h6>
+ <p>
+ Wallet users can select only these Mempool-compatible HTTP(S) URLs. Adding
+ a local or private URL allows wallets to contact that service. Removing a
+ URL blocks wallets using it until they select another approved explorer.
+ </p>
+ <q-select
+ filled
+ dense
+ multiple
+ use-input
+ use-chips
+ new-value-mode="add-unique"
+ v-model="formData.lnbits_onchain_explorer_urls"
+ label="Approved explorer URLs"
+ hint="Type a URL and press Enter. Custom URLs must include the network path; mempool.space selects it automatically. An empty list disables external explorers."
+ ></q-select>
</q-card-section>
</template>
### lnbits/templates/components/onchain/wallet-config.vue
@@ -4,6 +4,17 @@
>Could not load onchain settings.<template v-slot:action
><q-btn flat label="Retry" @click="getConfig"></q-btn></template
></q-banner>
+ <q-banner
+ v-if="
+ config.explorer_provider === 'mempool' &&
+ !config.approved_mempool_endpoints?.includes(config.mempool_endpoint)
+ "
+ class="q-mb-md"
+ >
+ This wallet's explorer URL is not approved. Select an approved explorer in
+ Blockchain settings or ask a server administrator to approve the current
+ URL.
+ </q-banner>
<q-card-section>
<div class="row items-center no-wrap">
<div class="col row items-center q-gutter-sm">
@@ -35,16 +46,22 @@
:options="explorerOptions"
label="Block explorer"
></q-select>
- <q-input
+ <q-select
v-if="config.explorer_provider === 'mempool'"
filled
dense
- v-model.trim="config.mempool_endpoint"
- hint="Use mempool.space or your own Mempool server URL for this network."
- type="text"
+ v-model="config.mempool_endpoint"
+ :options="config.approved_mempool_endpoints"
+ hint="Choose an explorer approved by a server administrator."
+ :error="
+ !config.approved_mempool_endpoints?.includes(
+ config.mempool_endpoint
+ )
+ "
+ error-message="Select an approved explorer."
:label="$t('onchain.mempool_endpoint')"
>
- </q-input>
+ </q-select>
<q-input
filled
@@ -92,7 +109,9 @@
color="primary"
:disable="
config.explorer_provider === 'mempool' &&
- !config.mempool_endpoint
+ !config.approved_mempool_endpoints?.includes(
+ config.mempool_endpoint
+ )
"
type="submit"
:label="$t('onchain.update')"
### tests/api/test_admin_api.py
@@ -66,6 +66,41 @@ async def test_admin_nostr_notification_protocol(client, superuser_token, settin
assert settings.lnbits_nostr_notifications_protocol == "nip17"
+@pytest.mark.anyio
+async def test_explorer_approval_requires_server_admin(
+ client, admin_user, user_headers_from, adminkey_headers_from, settings
+):
+ field = "lnbits_onchain_explorer_urls"
+ approved = ["https://mempool.space", "http://127.0.0.1:3006/testnet4"]
+ for headers in (user_headers_from, adminkey_headers_from):
+ rejected = await client.put(
+ "/admin/api/v1/settings", json={field: approved}, headers=headers
+ )
+ assert rejected.status_code in (401, 403)
+ assert settings.lnbits_onchain_explorer_urls == ["https://mempool.space"]
+
+ assert admin_user.id != settings.super_user
+ # The fixture grants admin access in memory; settings updates reload the DB.
+ await set_settings_field("lnbits_admin_users", settings.lnbits_admin_users)
+ login = await client.post(
+ "/api/v1/auth",
+ json={"username": admin_user.username, "password": "secret1234"},
+ )
+ assert login.status_code == 200
+ client.cookies.clear()
+ headers = {"Authorization": f"Bearer {login.json()['access_token']}"}
+ response = await client.put(
+ "/admin/api/v1/settings", json={field: approved}, headers=headers
+ )
+ assert response.status_code == 200, response.text
+ assert settings.lnbits_onchain_explorer_urls == approved
+ stored = await get_settings_field(field)
+ assert stored and stored.value == approved
+ loaded = await client.get("/admin/api/v1/settings", headers=headers)
+ assert loaded.status_code == 200
+ assert loaded.json()[field] == approved
+
+
@pytest.mark.anyio
async def test_admin_update_noneditable_settings(
client: AsyncClient,
### tests/api/test_onchain_wallet.py
@@ -1062,6 +1062,7 @@ async def test_onchain_explorer_selection_defaults_and_persists(
assert config["explorer_provider"] == "lnbits"
assert config["explorer_url"] == "/blockexplorer"
assert config["lnbits_explorer_network"] == "Testnet4"
+ assert config["approved_mempool_endpoints"] == ["https://mempool.space"]
config.update(
explorer_provider="mempool", mempool_endpoint="https://example.com/testnet4"
)
@@ -1076,6 +1077,12 @@ async def test_onchain_explorer_selection_defaults_and_persists(
path, headers={"X-API-KEY": wallet.inkey}, params=params, json=config
)
assert forbidden.status_code == 403
+ rejected = await http_client.put(path, headers=headers, params=params, json=config)
+ assert rejected.status_code == 400
+ assert "not approved" in rejected.json()["detail"]
+ monkeypatch.setattr(
+ settings, "lnbits_onchain_explorer_urls", ["https://example.com/testnet4"]
+ )
saved = await http_client.put(path, headers=headers, params=params, json=config)
assert saved.status_code == 200, saved.text
assert saved.json()["network"] == "Testnet4"
@@ -1097,6 +1104,63 @@ async def test_onchain_explorer_selection_defaults_and_persists(
assert rejected.status_code == 400
+@pytest.mark.anyio
+async def test_saved_unapproved_explorer_is_blocked_and_can_be_replaced(
+ http_client, onchain_wallet, monkeypatch
+):
+ from lnbits.core.services import blockexplorer
+
+ wallet, _, headers = onchain_wallet
+ await add_watch(http_client, headers)
+ stored = await get_onchain_wallet(wallet.id)
+ assert stored
+ stored.onchain_config.explorer_provider = "mempool"
+ stored.onchain_config.mempool_endpoint = "http://127.0.0.1:3006"
+ # Simulate a configuration saved before the approval requirement existed.
+ await update_onchain_wallet_config(stored.onchain_config, wallet.id)
+
+ def unexpected_client(**_kwargs):
+ pytest.fail("Saved unapproved explorers must not create an HTTP client")
+
+ monkeypatch.setattr(blockexplorer.httpx, "AsyncClient", unexpected_client)
+ path = "/api/v1/wallet/onchain/config"
+ config_response = await http_client.get(path, headers=headers)
+ assert config_response.status_code == 200
+ config = config_response.json()
+ assert config["mempool_endpoint"] == "http://127.0.0.1:3006"
+ assert config["explorer_provider"] == "mempool"
+ assert config["approved_mempool_endpoints"] == ["https://mempool.space"]
+ for method, url, kwargs in [
+ ("GET", "/api/v1/onchain/fees", {}),
+ ("GET", "/api/v1/onchain/tx/" + "a" * 64 + "/hex", {}),
+ ("POST", "/api/v1/onchain/tx", {"json": {"tx_hex": "deadbeef"}}),
+ ]:
+ response = await http_client.request(method, url, headers=headers, **kwargs)
+ assert response.status_code == 403
+ assert "not approved" in response.json()["detail"]
+ assert "127.0.0.1" not in response.json()["detail"]
+
+ await onchain.scan_wallet(wallet.id)
+ stored = await get_onchain_wallet(wallet.id)
+ assert stored and "not approved" in (stored.onchain_meta.sync_error or "")
+ assert stored.onchain_config.mempool_endpoint == "http://127.0.0.1:3006"
+
+ # A wallet owner cannot approve a URL by changing the returned choices.
+ config["approved_mempool_endpoints"] = [config["mempool_endpoint"]]
+ rejected = await http_client.put(
+ path, headers=headers, params={"network": "Testnet4"}, json=config
+ )
+ assert rejected.status_code == 400
+ assert settings.lnbits_onchain_explorer_urls == ["https://mempool.space"]
+
+ config["mempool_endpoint"] = "https://mempool.space"
+ saved = await http_client.put(
+ path, headers=headers, params={"network": "Testnet4"}, json=config
+ )
+ assert saved.status_code == 200
+ assert saved.json()["explorer_url"] == "https://mempool.space/testnet4"
+
+
@pytest.mark.anyio
async def test_onchain_local_explorer_used_for_fees_raw_tx_and_broadcast(
http_client, onchain_wallet, monkeypatch
### tests/unit/onchain/test_explorer.py
@@ -62,7 +62,7 @@ def test_custom_mempool_url_is_specific_to_network():
"http://[::1]:8080",
],
)
-async def test_local_mempool_urls_are_allowed(monkeypatch, url):
+async def test_local_mempool_urls_require_admin_approval(settings, monkeypatch, url):
real_client = httpx.AsyncClient
requests = []
@@ -74,13 +74,87 @@ def client(**kwargs):
return real_client(**kwargs, transport=httpx.MockTransport(response))
monkeypatch.setattr(blockexplorer.httpx, "AsyncClient", client)
- async with blockexplorer.MempoolExplorer(
- OnchainConfig(mempool_endpoint=url), "Mainnet"
- ) as provider:
+ config = OnchainConfig(mempool_endpoint=url)
+ with pytest.raises(blockexplorer.ExplorerNotAllowedError, match="not approved"):
+ blockexplorer.MempoolExplorer(config, "Mainnet")
+ assert requests == []
+ settings.lnbits_onchain_explorer_urls = [url]
+ async with blockexplorer.MempoolExplorer(config, "Mainnet") as provider:
assert await provider.fees() == {"fastestFee": 1}
assert str(requests[0].url) == url + "/api/v1/fees/recommended"
+@pytest.mark.parametrize(
+ "url",
+ [
+ "http://169.254.169.254",
+ "http://2130706433",
+ "http://[::ffff:127.0.0.1]",
+ "https://unapproved.example",
+ "https://mempool.space.evil.example",
+ "https://mempool.space:8443",
+ "http://mempool.space",
+ "https://mempool.space/custom",
+ "https://mempool.space/testnet4/../custom",
+ "https://mempool.space/%2e%2e/custom",
+ ],
+)
+def test_unapproved_explorer_is_rejected_before_client_creation(monkeypatch, url):
+ def unexpected_client(**_kwargs):
+ pytest.fail("Unapproved explorer must not create an HTTP client")
+
+ monkeypatch.setattr(blockexplorer.httpx, "AsyncClient", unexpected_client)
+ with pytest.raises(blockexplorer.ExplorerNotAllowedError):
+ blockexplorer.MempoolExplorer(OnchainConfig(mempool_endpoint=url), "Mainnet")
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ ("method", "args"),
+ [
+ ("checkpoint", []),
+ ("block_hash", [1]),
+ ("fees", []),
+ ("history", ["address"]),
+ ("utxos", ["address"]),
+ ("raw_transaction", ["a" * 64]),
+ ("broadcast", ["raw"]),
+ ],
+)
+async def test_revoked_explorer_blocks_every_operation(settings, method, args):
+ def unexpected_request(_request):
+ pytest.fail("A revoked explorer must not receive requests")
+
+ client = httpx.AsyncClient(
+ base_url="https://mempool.space/",
+ transport=httpx.MockTransport(unexpected_request),
+ )
+ async with blockexplorer.MempoolExplorer(OnchainConfig(), "Mainnet", client) as p:
+ settings.lnbits_onchain_explorer_urls = []
+ with pytest.raises(blockexplorer.ExplorerNotAllowedError):
+ await getattr(p, method)(*args)
+
+
+@pytest.mark.anyio
+async def test_approved_explorer_cannot_redirect_to_another_destination():
+ requests = []
+
+ def redirect(request):
+ requests.append(request)
+ return httpx.Response(302, headers={"Location": "http://127.0.0.1/private"})
+
+ client = httpx.AsyncClient(
+ base_url="https://mempool.space/",
+ follow_redirects=True,
+ transport=httpx.MockTransport(redirect),
+ )
+ async with blockexplorer.MempoolExplorer(OnchainConfig(), "Mainnet", client) as p:
+ with pytest.raises(httpx.HTTPStatusError):
+ await p.fees()
+ assert len(requests) == 1
+ assert requests[0].url.host == "mempool.space"
+
+
@pytest.mark.anyio
async def test_local_explorer_history_coins_fees_and_broadcast(settings, monkeypatch):
settings.lnbits_blockexplorer_enabled = True
### tests/unit/test_settings.py
@@ -8,6 +8,7 @@
from lnbits.settings import (
DEFAULT_WASM_MANIFESTS,
AssetSettings,
+ BlockExplorerSettings,
ExchangeRateProvider,
InstalledExtensionsSettings,
NotificationsSettings,
@@ -21,6 +22,44 @@
)
+@pytest.mark.parametrize(
+ "url",
+ [
+ "file:///etc/passwd",
+ "https://",
+ "https://user:password@example.com",
+ "https://example.com?key=value",
+ "https://example.com#fragment",
+ "https://example.com:99999",
+ "https://example.com\n",
+ "https://example.com\\private",
+ ],
+)
+def test_approved_explorer_urls_reject_invalid_endpoints(url):
+ with pytest.raises(ValueError):
+ BlockExplorerSettings(lnbits_onchain_explorer_urls=[url])
+
+
+def test_approved_explorer_urls_are_normalized_and_can_be_empty():
+ approved = BlockExplorerSettings(
+ lnbits_onchain_explorer_urls=[
+ "https://mempool.space/",
+ "https://mempool.space",
+ "http://[::1]:3006/testnet4/",
+ ]
+ )
+ assert approved.lnbits_onchain_explorer_urls == [
+ "https://mempool.space",
+ "http://[::1]:3006/testnet4",
+ ]
+ assert (
+ BlockExplorerSettings(
+ lnbits_onchain_explorer_urls=[]
+ ).lnbits_onchain_explorer_urls
+ == []
+ )
+
+
@pytest.mark.parametrize("admins", ['["alice", "bob"]', "alice,bob"])
def test_settings_load_env_collections_and_ignore_unrelated_dotenv_values(
monkeypatch, tmp_path, adminsWhy this scored 79/100
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.