fix: respect shared wallet permissions for payment updates (#4338)
What changed, and why it matters
This commit fixes a permission bug in LNbits where users of shared wallets could update or settle/cancel payments even when they only had view-only access. It also adds a check so that settle/cancel actions only work on special 'hold invoices,' preventing them from being misused on regular payments. The change is a security fix for access control.
Review shared-wallet permission model for other mutating endpoints; ensure can_update_payments() is consistently applied; deploy the patch promptly for instances using shared wallets.
Security signals we found
Access-control bypass fix for shared wallet payment updates
New permission check can_update_payments() tied to shared wallet receive/send permissions
New hold_invoice guard on settle/cancel endpoints
Regression tests added for unauthorized shared-wallet actions and non-hold-invoice actions
Evidence from the diff
The patch adds a for_update flag to get_standalone_payment() that enforces write permissions on shared wallets via a new can_update_payments() helper. api_update_payment_labels, api_update_payment_extra, api_payments_settle, and api_payments_cancel now pass for_update=True. Additionally, settle and cancel endpoints now reject non-hold-invoice payments. Tests cover shared-wallet permission boundaries and hold-invoice validation.
Changed components
lnbits/core/crud/payments.pylnbits/core/models/wallets.pylnbits/core/views/payment_api.pytests/api/test_payment_api.pyInspect captured patch +154 / −6
### lnbits/core/crud/payments.py
@@ -39,6 +39,7 @@ async def get_standalone_payment(
incoming: bool | None = False,
wallet_id: str | None = None,
conn: Connection | None = None,
+ for_update: bool = False, # Check shared-wallet write permissions.
) -> Payment | None:
clause: str = "checking_id = :checking_id OR payment_hash = :hash"
values = {
@@ -52,6 +53,8 @@ async def get_standalone_payment(
wallet = await get_wallet(wallet_id, conn=conn)
if not wallet or not wallet.can_view_payments:
return None
+ if for_update and not wallet.can_update_payments():
+ return None
values["wallet_id"] = wallet.source_wallet_id
clause = f"({clause}) AND wallet_id = :wallet_id"
### lnbits/core/models/wallets.py
@@ -196,6 +196,13 @@ def has_permission(self, permission: WalletPermission) -> bool:
return False
+ def can_update_payments(self) -> bool:
+ return (
+ not self.is_lightning_shared_wallet
+ or self.can_receive_payments
+ or self.can_send_payments
+ )
+
@property
def source_wallet_id(self) -> str:
"""For shared wallets return the original wallet ID, else return own ID."""
### lnbits/core/views/payment_api.py
@@ -341,7 +341,9 @@ async def api_update_payment_labels(
data: UpdatePaymentLabels,
key_type: BaseWalletTypeInfo = Depends(require_base_admin_key),
) -> SimpleStatus:
- payment = await get_standalone_payment(payment_hash, wallet_id=key_type.wallet.id)
+ payment = await get_standalone_payment(
+ payment_hash, wallet_id=key_type.wallet.id, for_update=True
+ )
if payment is None:
raise HTTPException(HTTPStatus.NOT_FOUND, "Payment does not exist.")
account = await get_account(key_type.wallet.user)
@@ -381,7 +383,7 @@ async def api_update_payment_extra(
key_type: WalletTypeInfo = Depends(require_admin_key),
) -> Payment:
payment = await get_standalone_payment(
- data.payment_hash, wallet_id=key_type.wallet.id
+ data.payment_hash, wallet_id=key_type.wallet.id, for_update=True
)
if payment is None:
raise HTTPException(HTTPStatus.NOT_FOUND, "Payment does not exist.")
@@ -567,13 +569,15 @@ async def api_payments_settle(
) -> InvoiceResponse:
payment_hash = sha256(bytes.fromhex(data.preimage)).hexdigest()
payment = await get_standalone_payment(
- payment_hash, incoming=True, wallet_id=key_type.wallet.id
+ payment_hash, incoming=True, wallet_id=key_type.wallet.id, for_update=True
)
if not payment:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Payment does not exist or does not belong to this wallet.",
)
+ if not payment.extra.get("hold_invoice"):
+ raise HTTPException(HTTPStatus.BAD_REQUEST, "Payment is not a hold invoice.")
return await settle_hold_invoice(payment, data.preimage)
@@ -582,13 +586,15 @@ async def api_payments_cancel(
data: CancelInvoice, key_type: WalletTypeInfo = Depends(require_admin_key)
) -> InvoiceResponse:
payment = await get_standalone_payment(
- data.payment_hash, incoming=True, wallet_id=key_type.wallet.id
+ data.payment_hash, incoming=True, wallet_id=key_type.wallet.id, for_update=True
)
if not payment:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Payment does not exist or does not belong to this wallet.",
)
+ if not payment.extra.get("hold_invoice"):
+ raise HTTPException(HTTPStatus.BAD_REQUEST, "Payment is not a hold invoice.")
return await cancel_hold_invoice(payment)
### tests/api/test_payment_api.py
@@ -10,12 +10,22 @@
create_payment,
get_payment,
get_payments,
+ get_standalone_payment,
update_payment,
)
+from lnbits.core.crud.wallets import create_wallet, update_wallet
from lnbits.core.models import Account, CreateInvoice, PaymentFilters, PaymentState
from lnbits.core.models.payments import CancelInvoice, CreatePayment, SettleInvoice
from lnbits.core.models.users import AccountId
-from lnbits.core.models.wallets import BaseWalletTypeInfo, KeyType, WalletTypeInfo
+from lnbits.core.models.wallets import (
+ BaseWalletTypeInfo,
+ KeyType,
+ WalletPermission,
+ WalletSharePermission,
+ WalletShareStatus,
+ WalletType,
+ WalletTypeInfo,
+)
from lnbits.core.services.payments import create_wallet_invoice
from lnbits.core.services.users import create_user_account
from lnbits.core.views.payment_api import (
@@ -244,6 +254,7 @@ async def test_payment_api_fee_reserve_and_hold_invoice_actions(mocker):
amount_msat=1_000,
payment_hash=payment_hash,
status=PaymentState.PENDING,
+ extra={"hold_invoice": True},
)
settle_mock = mocker.patch(
"lnbits.core.views.payment_api.settle_hold_invoice",
@@ -269,6 +280,7 @@ async def test_payment_api_fee_reserve_and_hold_invoice_actions(mocker):
amount_msat=2_000,
payment_hash=cancel_hash,
status=PaymentState.PENDING,
+ extra={"hold_invoice": True},
)
cancel_mock = mocker.patch(
"lnbits.core.views.payment_api.cancel_hold_invoice",
@@ -289,6 +301,123 @@ async def test_payment_api_fee_reserve_and_hold_invoice_actions(mocker):
cancel_mock.assert_awaited_once()
+@pytest.mark.anyio
+@pytest.mark.parametrize("action", ["cancel", "settle", "labels", "extra"])
+@pytest.mark.parametrize(
+ "permission",
+ [
+ None,
+ WalletPermission.VIEW_PAYMENTS,
+ WalletPermission.RECEIVE_PAYMENTS,
+ WalletPermission.SEND_PAYMENTS,
+ ],
+)
+async def test_payment_updates_require_shared_wallet_write_permission(
+ client, to_wallet, from_wallet, mocker, action, permission
+):
+ wallet = await create_wallet(user_id=to_wallet.user)
+ request_wallet = wallet
+ if permission is not None:
+ request_wallet = await create_wallet(
+ user_id=from_wallet.user,
+ wallet_type=WalletType.LIGHTNING_SHARED,
+ shared_wallet_id=wallet.id,
+ )
+ wallet.extra.shared_with.append(
+ WalletSharePermission(
+ username="shared-user",
+ shared_with_wallet_id=request_wallet.id,
+ permissions=list({WalletPermission.VIEW_PAYMENTS, permission}),
+ status=WalletShareStatus.APPROVED,
+ )
+ )
+ await update_wallet(wallet)
+
+ preimage = uuid4().hex * 2
+ payment_hash = sha256(bytes.fromhex(preimage)).hexdigest()
+ is_hold_action = action in ("cancel", "settle")
+ checking_id = await _create_payment(
+ wallet.id,
+ amount_msat=1_000,
+ payment_hash=payment_hash,
+ status=PaymentState.PENDING if is_hold_action else PaymentState.SUCCESS,
+ extra={"hold_invoice": True} if is_hold_action else {},
+ )
+ original = await get_standalone_payment(payment_hash, wallet_id=request_wallet.id)
+ assert original is not None
+ assert original.wallet_id == wallet.id
+ hold_actions = {
+ name: mocker.patch(
+ f"lnbits.core.views.payment_api.{name}_hold_invoice",
+ new=mocker.AsyncMock(return_value=InvoiceResponse(ok=True)),
+ )
+ for name in ("cancel", "settle")
+ }
+ method, path, data = {
+ "cancel": ("POST", "/cancel", {"payment_hash": payment_hash}),
+ "settle": ("POST", "/settle", {"preimage": preimage}),
+ "labels": ("PUT", f"/{payment_hash}/labels", {"labels": ["updated"]}),
+ "extra": (
+ "PATCH",
+ "/extra",
+ {"payment_hash": payment_hash, "extra": {"note": "updated"}},
+ ),
+ }[action]
+ response = await client.request(
+ method,
+ f"/api/v1/payments{path}",
+ json=data,
+ headers={"X-Api-Key": request_wallet.adminkey},
+ )
+ payment = await get_payment(checking_id)
+ if permission == WalletPermission.VIEW_PAYMENTS:
+ assert response.status_code == 404
+ for hold_action in hold_actions.values():
+ hold_action.assert_not_awaited()
+ assert payment == original
+ else:
+ assert response.status_code == 200
+ if is_hold_action:
+ hold_actions[action].assert_awaited_once()
+ elif action == "labels":
+ assert payment.labels == ["updated"]
+ else:
+ assert payment.extra == {"note": "updated"}
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("action", ["cancel", "settle"])
+async def test_hold_invoice_actions_reject_regular_payments(
+ client, to_wallet, mocker, action
+):
+ preimage = uuid4().hex * 2
+ payment_hash = sha256(bytes.fromhex(preimage)).hexdigest()
+ checking_id = await _create_payment(
+ to_wallet.id,
+ amount_msat=1_000,
+ payment_hash=payment_hash,
+ status=PaymentState.PENDING,
+ )
+ original = await get_payment(checking_id)
+ hold_action = mocker.patch(
+ f"lnbits.core.views.payment_api.{action}_hold_invoice",
+ new=mocker.AsyncMock(return_value=InvoiceResponse(ok=True)),
+ )
+ response = await client.post(
+ f"/api/v1/payments/{action}",
+ headers={"X-Api-Key": to_wallet.adminkey},
+ json=(
+ {"preimage": preimage}
+ if action == "settle"
+ else {"payment_hash": payment_hash}
+ ),
+ )
+ assert response.status_code == 400
+ assert response.json()["detail"] == "Payment is not a hold invoice."
+ hold_action.assert_not_awaited()
+ assert await get_payment(checking_id) == original
+
+
@pytest.mark.anyio
async def test_payment_extra_update_appends_new_keys(
client,
@@ -448,11 +577,14 @@ async def test_payment_extra_update_requires_successful_payment(
@pytest.mark.anyio
+@pytest.mark.parametrize("wallet_type", [WalletType.LIGHTNING, WalletType.FIAT])
async def test_api_update_payment_labels(
client,
to_wallet,
- adminkey_headers_to,
+ wallet_type,
):
+ to_wallet = await create_wallet(user_id=to_wallet.user, wallet_type=wallet_type)
+ adminkey_headers_to = {"X-Api-Key": to_wallet.adminkey}
payment_hash = uuid4().hex
checking_id = await _create_payment(
to_wallet.id,Why this scored 67/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.