What changed, and why it matters
This commit fixes a privacy and authorization issue in LNbits where wallet secret keys (admin and invoice keys) were being returned to API clients even when the client was authenticated with a restricted access-control token that only had read permission. The change introduces a new helper that masks those keys unless the current request has write access to the endpoint, and applies it to several wallet-listing API responses. It also adds tests confirming the masking behavior.
Review whether any other endpoints return Wallet or User objects containing wallet keys and ensure they also apply copy_with_keys with the correct can_write flag. Verify that the new check_api_write_access decorator correctly handles all authentication paths, including extension-specific endpoints that may return wallet details.
Security signals we found
Sensitive credential disclosure in API responses
Authorization boundary between read-only and write ACL tokens
New access-control check tied to endpoint path and HTTP method
Redaction of adminkey and invoice key in serialized wallet objects
Regression tests for restricted token key exposure
Evidence from the diff
The patch adds Wallet.copy_with_keys(keep=True) to return a copy of a wallet with adminkey/inkey redacted to asterisks when keep=False. It introduces decorators.check_api_write_access and optional_acl_token_payload to determine whether the current request is authenticated via a restricted ACL token and whether that token has write access to the current endpoint. The can_write result is then threaded into api_wallets, get_auth_user, api_get_user, api_users_get_user_wallet, and api_wallets_paginated so that wallet keys are only exposed when the caller has unrestricted session authentication or an ACL token with write access to the specific endpoint. Tests verify that read-only ACL tokens see masked keys, write ACL tokens see real keys, and full session tokens are unaffected.
Changed components
lnbits/core/models/wallets.pylnbits/core/views/api.pylnbits/core/views/auth_api.pylnbits/core/views/user_api.pylnbits/core/views/wallet_api.pylnbits/decorators.pyInspect captured patch +357 / −10
diff --git a/lnbits/core/models/wallets.py b/lnbits/core/models/wallets.py
index 8e62419..61101b2 100644
--- a/lnbits/core/models/wallets.py
+++ b/lnbits/core/models/wallets.py
@@ -137,6 +137,14 @@ class Wallet(BaseWallet):
super().__init__(**data)
self._validate_data()
+ def copy_with_keys(self, keep: bool = True) -> Wallet:
+ """Return a wallet copy, masking its credentials when keep is False."""
+ wallet = self.copy()
+ if not keep:
+ wallet.adminkey = "*" * 32
+ wallet.inkey = "*" * 32
+ return wallet
+
def mirror_shared_wallet(
self,
shared_wallet: Wallet,
diff --git a/lnbits/core/views/api.py b/lnbits/core/views/api.py
index 123776d..2975618 100644
--- a/lnbits/core/views/api.py
+++ b/lnbits/core/views/api.py
@@ -17,6 +17,7 @@ from lnbits.core.models.users import AccountId
from lnbits.decorators import (
check_account_exists,
check_account_id_exists,
+ check_api_write_access,
check_user_exists,
)
from lnbits.settings import settings
@@ -71,8 +72,11 @@ async def health_check(
name="Wallets",
description="Get basic info for all of user's wallets.",
)
-async def api_wallets(user: User = Depends(check_user_exists)) -> list[Wallet]:
- return user.wallets
+async def api_wallets(
+ user: User = Depends(check_user_exists),
+ can_write: bool = Depends(check_api_write_access),
+) -> list[Wallet]:
+ return [wallet.copy_with_keys(keep=can_write) for wallet in user.wallets]
@api_router.post("/api/v1/account")
diff --git a/lnbits/core/views/auth_api.py b/lnbits/core/views/auth_api.py
index be172b4..504bfc5 100644
--- a/lnbits/core/views/auth_api.py
+++ b/lnbits/core/views/auth_api.py
@@ -36,6 +36,7 @@ from lnbits.decorators import (
access_token_payload,
check_account_exists,
check_admin,
+ check_api_write_access,
check_user_exists,
optional_user_id,
)
@@ -128,7 +129,11 @@ def _record_login_failure(cache_key: str) -> None:
@auth_router.get("", description="Get the authenticated user")
-async def get_auth_user(user: User = Depends(check_user_exists)) -> User:
+async def get_auth_user(
+ user: User = Depends(check_user_exists),
+ can_write: bool = Depends(check_api_write_access),
+) -> User:
+ user.wallets = [wallet.copy_with_keys(keep=can_write) for wallet in user.wallets]
return user
diff --git a/lnbits/core/views/user_api.py b/lnbits/core/views/user_api.py
index 28ad4cd..d233634 100644
--- a/lnbits/core/views/user_api.py
+++ b/lnbits/core/views/user_api.py
@@ -43,7 +43,12 @@ from lnbits.core.services import (
)
from lnbits.core.services.lightning_address import set_wallet_lightning_address
from lnbits.db import Filters, Page
-from lnbits.decorators import check_admin, check_super_user, parse_filters
+from lnbits.decorators import (
+ check_admin,
+ check_api_write_access,
+ check_super_user,
+ parse_filters,
+)
from lnbits.helpers import (
encrypt_internal_message,
generate_filter_params_openapi,
@@ -74,10 +79,14 @@ async def api_get_users(
name="Get user",
summary="Get user by Id",
)
-async def api_get_user(user_id: str) -> User:
+async def api_get_user(
+ user_id: str,
+ can_write: bool = Depends(check_api_write_access),
+) -> User:
user = await get_user(user_id, active_only=False)
if not user:
raise HTTPException(HTTPStatus.NOT_FOUND, "User not found.")
+ user.wallets = [wallet.copy_with_keys(keep=can_write) for wallet in user.wallets]
return user
@@ -261,8 +270,12 @@ async def api_users_toggle_activated(
@users_router.get("/user/{user_id}/wallet", name="Get wallets for user")
-async def api_users_get_user_wallet(user_id: str) -> list[Wallet]:
- return await get_wallets(user_id, deleted=None)
+async def api_users_get_user_wallet(
+ user_id: str,
+ can_write: bool = Depends(check_api_write_access),
+) -> list[Wallet]:
+ wallets = await get_wallets(user_id, deleted=None)
+ return [wallet.copy_with_keys(keep=can_write) for wallet in wallets]
@users_router.post("/user/{user_id}/wallet", name="Create a new wallet for user")
diff --git a/lnbits/core/views/wallet_api.py b/lnbits/core/views/wallet_api.py
index 7963632..1c3060c 100644
--- a/lnbits/core/views/wallet_api.py
+++ b/lnbits/core/views/wallet_api.py
@@ -34,6 +34,7 @@ from lnbits.db import Filters, Page
from lnbits.decorators import (
check_account_exists,
check_account_id_exists,
+ check_api_write_access,
parse_filters,
require_admin_key,
require_invoice_key,
@@ -72,12 +73,14 @@ async def api_wallet(key_info: WalletTypeInfo = Depends(require_invoice_key)):
async def api_wallets_paginated(
account_id: AccountId = Depends(check_account_id_exists),
filters: Filters = Depends(parse_filters(WalletsFilters)),
+ can_write: bool = Depends(check_api_write_access),
):
page = await get_wallets_paginated(
user_id=account_id.id,
filters=filters,
)
+ page.data = [wallet.copy_with_keys(keep=can_write) for wallet in page.data]
return page
diff --git a/lnbits/decorators.py b/lnbits/decorators.py
index c847196..2ca70c8 100644
--- a/lnbits/decorators.py
+++ b/lnbits/decorators.py
@@ -29,7 +29,7 @@ from lnbits.core.models import (
User,
WalletTypeInfo,
)
-from lnbits.core.models.users import AccountId
+from lnbits.core.models.users import AccountId, EndpointAccess
from lnbits.core.models.wallets import BaseWallet, BaseWalletTypeInfo
from lnbits.db import Connection, Filter, Filters, TFilterModel
from lnbits.helpers import normalize_path, path_segments, sha256s
@@ -359,6 +359,34 @@ async def access_token_payload(
return AccessTokenPayload(**payload)
+async def optional_acl_token_payload(
+ access_token: Annotated[str | None, Depends(check_access_token)],
+) -> AccessTokenPayload | None:
+ if not access_token:
+ return None
+ payload = _decode_access_token(access_token)
+ return payload if payload.api_token_id else None
+
+
+async def check_api_write_access(
+ request: Request,
+ account_id: Annotated[AccountId, Depends(check_account_id_exists)],
+ acl_token: Annotated[
+ AccessTokenPayload | None, Depends(optional_acl_token_payload)
+ ],
+) -> bool:
+ """Check current endpoint write access, including unrestricted authentication."""
+ if not acl_token or not acl_token.api_token_id:
+ return True
+ endpoint = await _check_account_api_access(
+ account_id.id,
+ acl_token.api_token_id,
+ request["path"],
+ request["method"],
+ )
+ return endpoint.write
+
+
async def check_admin(
account: Annotated[Account, Depends(check_account_exists)],
) -> Account:
@@ -520,7 +548,7 @@ async def _get_account_from_jwt_payload(
async def _check_account_api_access(
user_id: str, token_id: str, path: str, method: str, conn: Connection | None = None
-):
+) -> EndpointAccess:
segments = path.split("/")
if len(segments) < 3:
raise HTTPException(HTTPStatus.FORBIDDEN, "Not an API endpoint.")
@@ -536,6 +564,7 @@ async def _check_account_api_access(
raise HTTPException(HTTPStatus.FORBIDDEN, "Path not allowed.")
if not endpoint.supports_method(method):
raise HTTPException(HTTPStatus.FORBIDDEN, "Method not allowed.")
+ return endpoint
def url_for_interceptor(original_method):
diff --git a/tests/api/test_wallet_key_access.py b/tests/api/test_wallet_key_access.py
new file mode 100644
index 0000000..cb17762
--- /dev/null
+++ b/tests/api/test_wallet_key_access.py
@@ -0,0 +1,203 @@
+from uuid import uuid4
+
+import jwt
+import pytest
+from httpx import AsyncClient
+
+from lnbits.core.crud.users import (
+ delete_account,
+ get_user_access_control_lists,
+ update_user_access_control_list,
+)
+from lnbits.core.crud.wallets import create_wallet, force_delete_wallet, get_wallet
+from lnbits.core.models import AccessTokenPayload, User
+from lnbits.core.models.misc import SimpleItem
+from lnbits.core.models.users import AccessControlList, Account, EndpointAccess
+from lnbits.core.services.users import create_user_account
+from lnbits.helpers import create_access_token
+from lnbits.settings import AuthMethods, Settings
+
+
+@pytest.fixture
+async def wallet_key_user(http_client: AsyncClient):
+ account = Account(id=uuid4().hex, username=f"keys_{uuid4().hex[:8]}")
+ account.hash_password("secret1234")
+ user = await create_user_account(account)
+ user.wallets.append(await create_wallet(user_id=user.id, wallet_name="Second"))
+ try:
+ yield user
+ finally:
+ for wallet in user.wallets:
+ await force_delete_wallet(wallet.id)
+ await delete_account(user.id)
+
+
+@pytest.fixture(
+ params=[
+ ("/api/v1/wallets", "/api/v1/wallets", None),
+ ("/api/v1/wallet/paginated", "/api/v1/wallet", "data"),
+ ("/api/v1/auth", "/api/v1/auth", "wallets"),
+ ("/users/api/v1/user/{user_id}", "/users/api/v1", "wallets"),
+ ("/users/api/v1/user/{user_id}/wallet", "/users/api/v1", None),
+ ]
+)
+def wallet_key_endpoint(request, wallet_key_user: User, settings: Settings):
+ path, acl_path, wallet_field = request.param
+ if path.startswith("/users/"):
+ settings.lnbits_admin_users = [wallet_key_user.id]
+ return path.format(user_id=wallet_key_user.id), acl_path, wallet_field
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("token_source", ["header", "cookie"])
+async def test_wallet_keys_require_current_endpoint_write_access(
+ http_client: AsyncClient,
+ wallet_key_user: User,
+ wallet_key_endpoint: tuple[str, str, str | None],
+ token_source: str,
+ settings: Settings,
+):
+ settings.auth_authentication_cache_minutes = 1
+ path, acl_path, wallet_field = wallet_key_endpoint
+ user = wallet_key_user
+ session_token = create_access_token({"sub": user.username, "usr": user.id})
+ session_headers = {"Authorization": f"Bearer {session_token}"}
+ response = await http_client.get(path, headers=session_headers)
+ assert response.status_code == 200
+ original = response.json()
+ http_client.cookies.set("cookie_access_token", session_token)
+ response = await http_client.get(path)
+ assert response.status_code == 200
+ assert response.json() == original
+ http_client.cookies.clear()
+ original_wallets = original[wallet_field] if wallet_field else original
+ assert len(original_wallets) == 2
+ for wallet in original_wallets:
+ stored = user.get_wallet(wallet["id"])
+ assert stored
+ assert wallet["adminkey"] == stored.adminkey
+ assert wallet["inkey"] == stored.inkey
+
+ token_id = uuid4().hex
+ token = create_access_token(
+ AccessTokenPayload(sub=user.username or "", api_token_id=token_id).dict()
+ )
+ endpoint = EndpointAccess(path=acl_path, name="Wallet response", read=True)
+ acl = AccessControlList(
+ id=uuid4().hex,
+ name="Wallet keys",
+ endpoints=[
+ endpoint,
+ # Write access elsewhere must not grant access to these keys.
+ EndpointAccess(path="/api/v1/payments", name="Payments", write=True),
+ ],
+ token_id_list=[SimpleItem(id=token_id, name="Wallet token")],
+ )
+ acls = await get_user_access_control_lists(user.id)
+ acls.access_control_list = [acl]
+ await update_user_access_control_list(acls)
+
+ headers = {}
+ if token_source == "header":
+ headers = {"Authorization": f"Bearer {token}"}
+ # A full session cookie must not override a restricted bearer token.
+ http_client.cookies.set("cookie_access_token", session_token)
+ else:
+ http_client.cookies.set("cookie_access_token", token)
+
+ # A grant followed by a downgrade exercises previously cached authentication.
+ for write in (False, True, False):
+ endpoint.write = write
+ await update_user_access_control_list(acls)
+ response = await http_client.get(path, headers=headers)
+ assert response.status_code == 200
+ result = response.json()
+ wallets = result[wallet_field] if wallet_field else result
+ assert len(wallets) == 2
+ if wallet_field:
+ # Updating the ACL also updates the account's updated_at timestamp.
+ ignored = {wallet_field, "updated_at"}
+ assert {k: v for k, v in result.items() if k not in ignored} == {
+ k: v for k, v in original.items() if k not in ignored
+ }
+ originals = {wallet["id"]: wallet for wallet in original_wallets}
+ for wallet in wallets:
+ expected = originals[wallet["id"]]
+ if not write:
+ expected = {
+ **expected,
+ "adminkey": "*" * 32,
+ "inkey": "*" * 32,
+ }
+ assert wallet == expected
+
+ # Read access is still required even when write access is granted.
+ endpoint.read = False
+ endpoint.write = True
+ await update_user_access_control_list(acls)
+ response = await http_client.get(path, headers=headers)
+ assert response.status_code == 403
+
+ endpoint.read = True
+ acl.delete_token_by_id(token_id)
+ await update_user_access_control_list(acls)
+ response = await http_client.get(path, headers=headers)
+ assert response.status_code == 403
+ assert response.json()["detail"] == "Invalid token id."
+
+ # Redaction must not alter persisted credentials or unrestricted responses.
+ http_client.cookies.clear()
+ response = await http_client.get(path, headers=session_headers)
+ assert response.status_code == 200
+ restored = response.json()
+ assert (restored[wallet_field] if wallet_field else restored) == original_wallets
+ for wallet in user.wallets:
+ stored = await get_wallet(wallet.id)
+ assert stored
+ assert stored.adminkey == wallet.adminkey
+ assert stored.inkey == wallet.inkey
+
+
+@pytest.mark.anyio
+async def test_wallet_keys_with_user_id_authentication(
+ http_client: AsyncClient,
+ wallet_key_user: User,
+ settings: Settings,
+):
+ settings.auth_allowed_methods = [AuthMethods.user_id_only.value]
+ for path, wallet_field in (
+ ("/api/v1/wallets", None),
+ ("/api/v1/wallet/paginated", "data"),
+ ("/api/v1/auth", "wallets"),
+ ):
+ response = await http_client.get(path, params={"usr": wallet_key_user.id})
+ assert response.status_code == 200
+ result = response.json()
+ wallets = result[wallet_field] if wallet_field else result
+ assert len(wallets) == 2
+ for wallet in wallets:
+ stored = wallet_key_user.get_wallet(wallet["id"])
+ assert stored
+ assert wallet["adminkey"] == stored.adminkey
+ assert wallet["inkey"] == stored.inkey
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("token", [None, "invalid_token", "expired"])
+async def test_wallet_keys_reject_missing_or_invalid_authentication(
+ http_client: AsyncClient,
+ wallet_key_endpoint: tuple[str, str, str | None],
+ token: str | None,
+ wallet_key_user: User,
+ settings: Settings,
+):
+ path, _, _ = wallet_key_endpoint
+ if token == "expired":
+ token = jwt.encode(
+ {"sub": wallet_key_user.username, "api_token_id": uuid4().hex, "exp": 0},
+ settings.auth_secret_key,
+ "HS256",
+ )
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
+ response = await http_client.get(path, headers=headers)
+ assert response.status_code == 401
diff --git a/tests/unit/test_decorators.py b/tests/unit/test_decorators.py
index 7a5da13..e4d0a1c 100644
--- a/tests/unit/test_decorators.py
+++ b/tests/unit/test_decorators.py
@@ -7,18 +7,21 @@ from fastapi import Request
from fastapi.exceptions import HTTPException
from httpx import AsyncClient
from pydantic.types import UUID4
+from pytest_mock import MockerFixture
from lnbits.core.crud.users import delete_account
from lnbits.core.models import User
-from lnbits.core.models.users import AccessTokenPayload
+from lnbits.core.models.users import AccessTokenPayload, AccountId, EndpointAccess
from lnbits.decorators import (
_extension_id_from_request_path,
access_token_payload,
check_access_token,
check_admin_ui,
+ check_api_write_access,
check_extension_builder,
check_first_install,
check_user_exists,
+ optional_acl_token_payload,
optional_user_id,
)
from lnbits.helpers import create_access_token
@@ -169,6 +172,55 @@ async def test_access_token_payload_success_and_missing(settings: Settings):
await access_token_payload(None)
+@pytest.mark.anyio
+async def test_optional_acl_token_payload_distinguishes_session_tokens():
+ assert await optional_acl_token_payload(None) is None
+ session_token = create_access_token({"sub": "alice"})
+ assert await optional_acl_token_payload(session_token) is None
+
+ acl_token = create_access_token({"sub": "alice", "api_token_id": "acl-token"})
+ payload = await optional_acl_token_payload(acl_token)
+ assert payload
+ assert payload.api_token_id == "acl-token"
+
+ with pytest.raises(HTTPException, match="Invalid access token."):
+ await optional_acl_token_payload("invalid_token")
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("write", [None, False, True])
+async def test_check_api_write_access(mocker: MockerFixture, write: bool | None):
+ check_access = mocker.patch(
+ "lnbits.decorators._check_account_api_access",
+ return_value=EndpointAccess(
+ path="/api/v1/wallet", name="Wallet", read=True, write=bool(write)
+ ),
+ )
+
+ request = Request(
+ {
+ "type": "http",
+ "path": "/api/v1/wallet",
+ "method": "GET",
+ }
+ )
+ acl_token = (
+ AccessTokenPayload(sub="alice", api_token_id="acl-token")
+ if write is not None
+ else None
+ )
+ result = await check_api_write_access(
+ request, account_id=AccountId(id="user-id"), acl_token=acl_token
+ )
+ assert result is (write is not False)
+ if write is None:
+ check_access.assert_not_called()
+ else:
+ check_access.assert_awaited_once_with(
+ "user-id", "acl-token", "/api/v1/wallet", "GET"
+ )
+
+
@pytest.mark.anyio
async def test_optional_user_id_uses_user_id_or_access_token(
user_alan: User, settings: Settings
diff --git a/tests/unit/test_models_wallets.py b/tests/unit/test_models_wallets.py
new file mode 100644
index 0000000..5c5e07c
--- /dev/null
+++ b/tests/unit/test_models_wallets.py
@@ -0,0 +1,30 @@
+import json
+
+import pytest
+
+from lnbits.core.models import Wallet
+
+
+@pytest.mark.parametrize("keep", [None, True, False])
+def test_copy_with_keys(keep: bool | None):
+ wallet = Wallet(
+ id="wallet-id",
+ user="user-id",
+ name="Wallet",
+ adminkey="admin-key",
+ inkey="invoice-key",
+ )
+ original = json.loads(wallet.json())
+
+ result = (
+ wallet.copy_with_keys() if keep is None else wallet.copy_with_keys(keep=keep)
+ )
+
+ assert isinstance(result, Wallet)
+ assert result is not wallet
+ assert json.loads(wallet.json()) == original
+ expected = original
+ if keep is False:
+ expected = {**original, "adminkey": "*" * 32, "inkey": "*" * 32}
+ assert json.loads(result.json()) == expected
+ assert Wallet(**result.dict()) == result
Why this scored 64/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.