fix: reject user ID authentication for password accounts (#4340)
What changed, and why it matters
This commit fixes an authentication bypass in LNbits. Previously, an account that had been created without a password could still be logged into using only the user ID even after a password was later added. An attacker who knew (or guessed) the user's ID could access the account and wallets without needing the password. The patch now rejects user-ID-only login for any account that has a password set.
Deploy this patch promptly. Review any accounts that were upgraded from passwordless to password-protected and verify that no unauthorized access occurred via user-ID-only authentication before the patch. Consider disabling user-ID-only authentication unless it is strictly required.
Security signals we found
Authentication bypass via user ID for password-protected accounts
Stale authentication cache could grant access after password upgrade
New guard `check_passwordless_account` enforces password requirement
User-ID authentication cache key removed to force fresh account lookup
Tests explicitly model the bypass scenario and its fix
Evidence from the diff
The change adds a check_passwordless_account guard that raises HTTP 403 when user-ID-only authentication is attempted on an Account where has_password is true. It is enforced in both the explicit /api/v1/auth/usr login endpoint and in the request decorator path that validates usr query parameters. The patch also removes user-ID-based authentication caching in check_account_id_exists so that a stale cache entry created before a password was set cannot grant access. Tests confirm that adding a password revokes prior user-ID access, that cached sessions cannot bypass the requirement, and that password-based sessions still work normally.
Changed components
lnbits/core/views/auth_api.pylnbits/decorators.pytests/api/test_auth.pytests/api/test_two_factor.pytests/api/test_user_id_auth.pytests/api/test_users.pytests/api/test_wallet_key_access.pytests/unit/test_decorators.pyInspect captured patch +196 / −44
### lnbits/core/views/auth_api.py
@@ -44,6 +44,7 @@
check_account_exists,
check_admin,
check_api_write_access,
+ check_passwordless_account,
check_user_exists,
optional_user_id,
)
@@ -195,6 +196,7 @@ async def login_usr(data: LoginUsr) -> JSONResponse:
raise HTTPException(
HTTPStatus.FORBIDDEN, "Admin users cannot login with user id only."
)
+ check_passwordless_account(account)
return await _login_response(account)
### lnbits/decorators.py
@@ -264,8 +264,7 @@ async def check_account_id_exists(
cache_key: str | None = None
if access_token:
cache_key = f"auth:access_token:{sha256s(access_token)}"
- elif usr:
- cache_key = f"auth:user_id:{sha256s(usr.hex)}"
+ # User-ID authentication must see newly configured passwords on every request.
async with db.connect() as conn:
if cache_key and settings.auth_authentication_cache_minutes > 0:
@@ -301,6 +300,13 @@ async def check_account_id_exists(
return account_id
+def check_passwordless_account(account: Account) -> None:
+ if account.has_password:
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN, "This account requires password login."
+ )
+
+
async def check_account_exists(
r: Request,
access_token: Annotated[str | None, Depends(check_access_token)],
@@ -333,6 +339,8 @@ async def _check_account_exists(
raise HTTPException(
HTTPStatus.FORBIDDEN, "User id only access for admins is forbidden."
)
+ if account:
+ check_passwordless_account(account)
else:
raise HTTPException(
HTTPStatus.UNAUTHORIZED, "Missing user ID or access token."
### tests/api/test_auth.py
@@ -67,22 +67,15 @@ async def test_login_bad_user(http_client: AsyncClient):
@pytest.mark.anyio
-async def test_login_alan_usr(user_alan: User, http_client: AsyncClient):
+async def test_login_usr_rejects_password_account(
+ user_alan: User, http_client: AsyncClient
+):
response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
- assert response.status_code == 200, "Alan logs in OK."
- access_token = response.json().get("access_token")
- assert access_token is not None, "Expected access token after login."
-
- response = await http_client.get(
- "/api/v1/auth", headers={"Authorization": f"Bearer {access_token}"}
- )
-
- assert response.status_code == 200, "Alan logs in OK."
- alan = response.json()
- assert alan["id"] == user_alan.id
- assert alan["username"] == user_alan.username
- assert alan["email"] == user_alan.email
+ assert response.status_code == 403
+ assert response.json()["detail"] == "This account requires password login."
+ assert "access_token" not in response.json()
+ assert "cookie_access_token" not in response.cookies
@pytest.mark.anyio
@@ -133,20 +126,19 @@ async def test_login_usr_not_allowed_for_admin_without_credentials(
@pytest.mark.anyio
-async def test_login_usr_not_allowed(
- user_alan: User, http_client: AsyncClient, settings: Settings
-):
+async def test_login_usr_not_allowed(http_client: AsyncClient, settings: Settings):
+ user = await create_user_account()
# exclude 'user_id_only'
settings.auth_allowed_methods = [AuthMethods.username_and_password.value]
- response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
+ response = await http_client.post("/api/v1/auth/usr", json={"usr": user.id})
assert response.status_code == 403, "Login method not allowed."
assert response.json().get("detail") == "Login by 'User ID' not allowed."
settings.auth_allowed_methods = AuthMethods.all()
- response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
+ response = await http_client.post("/api/v1/auth/usr", json={"usr": user.id})
assert response.status_code == 200, "Login with 'usr' allowed."
assert (
response.json().get("access_token") is not None
@@ -784,7 +776,9 @@ async def test_change_password_not_authenticated(http_client: AsyncClient):
@pytest.mark.anyio
async def test_alan_change_password_old_nok(user_alan: User, http_client: AsyncClient):
- response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
+ response = await http_client.post(
+ "/api/v1/auth", json={"username": user_alan.username, "password": "secret1234"}
+ )
assert response.status_code == 200, "Alan logs in OK."
access_token = response.json().get("access_token")
@@ -810,7 +804,9 @@ async def test_alan_change_password_old_nok(user_alan: User, http_client: AsyncC
async def test_alan_change_password_different_user(
user_alan: User, http_client: AsyncClient
):
- response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
+ response = await http_client.post(
+ "/api/v1/auth", json={"username": user_alan.username, "password": "secret1234"}
+ )
assert response.status_code == 200, "Alan logs in OK."
access_token = response.json().get("access_token")
@@ -837,7 +833,9 @@ async def test_alan_change_password_auth_threshold_expired(
user_alan: User, http_client: AsyncClient, settings: Settings
):
- response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
+ response = await http_client.post(
+ "/api/v1/auth", json={"username": user_alan.username, "password": "secret1234"}
+ )
assert response.status_code == 200, "Alan logs in OK."
access_token = response.json().get("access_token")
@@ -1207,7 +1205,9 @@ async def test_change_pubkey_not_authenticated(
@pytest.mark.anyio
async def test_change_pubkey_other_user(http_client: AsyncClient, user_alan: User):
- response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
+ response = await http_client.post(
+ "/api/v1/auth", json={"username": user_alan.username, "password": "secret1234"}
+ )
assert response.status_code == 200, "Alan logs in OK."
access_token = response.json().get("access_token")
@@ -1230,7 +1230,9 @@ async def test_alan_change_pubkey_auth_threshold_expired(
user_alan: User, http_client: AsyncClient, settings: Settings
):
- response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
+ response = await http_client.post(
+ "/api/v1/auth", json={"username": user_alan.username, "password": "secret1234"}
+ )
assert response.status_code == 200, "Alan logs in OK."
access_token = response.json().get("access_token")
### tests/api/test_two_factor.py
@@ -180,11 +180,34 @@ async def test_two_factor_user_id_and_cached_session_cannot_bypass(
http_client.cookies.clear()
assert (
await http_client.get("/api/v1/auth", params={"usr": factor_account.id})
- ).status_code == 401
+ ).status_code == 403
response = await http_client.post(
"/api/v1/auth/usr", json={"usr": factor_account.id}
)
+ assert response.status_code == 403
+ assert response.json()["detail"] == "This account requires password login."
+
+
+async def test_two_factor_passwordless_user_id_requires_factor(http_client, settings):
+ settings.totp_encryption_key = uuid4().hex
+ settings.lnbits_two_factor_enabled = True
+ user = await create_user_account()
+ response = await http_client.post("/api/v1/auth/usr", json={"usr": user.id})
+ assert response.status_code == 200
+ setup = await http_client.post("/api/v1/auth/2fa/setup")
+ assert setup.status_code == 200
+ secret = base64.b32decode(setup.json()["secret"])
+ response = await http_client.post(
+ "/api/v1/auth/2fa/confirm",
+ json={"code": totp(secret).generate(int(time())).decode()},
+ )
+ assert response.status_code == 200
+ http_client.cookies.clear()
+ response = await http_client.get("/api/v1/wallets", params={"usr": user.id})
+ assert response.status_code == 401
+ response = await http_client.post("/api/v1/auth/usr", json={"usr": user.id})
assert response.json()["two_factor_required"]
+ assert "access_token" not in response.json()
@pytest.mark.parametrize("operation", ["password", "reset"])
### tests/api/test_user_id_auth.py
@@ -0,0 +1,114 @@
+from uuid import uuid4
+
+import pytest
+
+from lnbits.core.crud.wallets import get_wallet
+from lnbits.core.models.users import Account, AccountId
+from lnbits.core.services.users import create_user_account
+from lnbits.helpers import sha256s
+from lnbits.settings import AuthMethods
+from lnbits.utils.cache import cache
+
+pytestmark = pytest.mark.anyio
+
+
+@pytest.mark.parametrize("cache_minutes", [0, 5])
+@pytest.mark.parametrize("with_username", [False, True])
+async def test_password_accounts_reject_user_id_authentication(
+ http_client, settings, cache_minutes, with_username
+):
+ settings.auth_authentication_cache_minutes = cache_minutes
+ settings.auth_allowed_methods = [
+ AuthMethods.username_and_password.value,
+ AuthMethods.user_id_only.value,
+ ]
+ account = Account(
+ id=uuid4().hex,
+ username=f"password_{uuid4().hex[:8]}" if with_username else None,
+ )
+ account.hash_password("secret1234")
+ user = await create_user_account(account)
+ wallet = user.wallets[0]
+ # A cache entry created before the account had a password must not grant access.
+ cache_key = f"auth:user_id:{sha256s(user.id)}"
+ cache.set(cache_key, AccountId(id=user.id))
+ try:
+ response = await http_client.post("/api/v1/auth/usr", json={"usr": user.id})
+ assert response.status_code == 403
+ assert response.json()["detail"] == "This account requires password login."
+ assert "access_token" not in response.json()
+ assert "cookie_access_token" not in response.cookies
+
+ for method, path in (
+ ("GET", "/api/v1/auth"),
+ ("GET", "/api/v1/wallets"),
+ ("GET", "/api/v1/status"),
+ ("PUT", f"/api/v1/wallet/reset/{wallet.id}"),
+ ):
+ response = await http_client.request(method, path, params={"usr": user.id})
+ assert response.status_code == 403
+ assert response.json()["detail"] == "This account requires password login."
+ stored = await get_wallet(wallet.id)
+ assert stored
+ assert (stored.adminkey, stored.inkey) == (wallet.adminkey, wallet.inkey)
+ finally:
+ cache.pop(cache_key)
+
+
+@pytest.mark.parametrize("token_source", ["cookie", "header"])
+async def test_password_login_session_allows_user_id_query(http_client, token_source):
+ account = Account(id=uuid4().hex, username=f"session_{uuid4().hex[:8]}")
+ account.hash_password("secret1234")
+ user = await create_user_account(account)
+ response = await http_client.post(
+ "/api/v1/auth", json={"username": user.username, "password": "secret1234"}
+ )
+ assert response.status_code == 200
+ headers = {}
+ if token_source == "header":
+ headers = {"Authorization": f"Bearer {response.json()['access_token']}"}
+ http_client.cookies.clear()
+ response = await http_client.get(
+ "/api/v1/wallets", params={"usr": user.id}, headers=headers
+ )
+ assert response.status_code == 200
+ wallets = {wallet["id"]: wallet for wallet in response.json()}
+ wallet = user.wallets[0]
+ assert wallets[wallet.id]["adminkey"] == wallet.adminkey
+ assert wallets[wallet.id]["inkey"] == wallet.inkey
+
+
+@pytest.mark.parametrize("cache_minutes", [0, 5])
+async def test_adding_password_revokes_user_id_access(
+ http_client, settings, cache_minutes
+):
+ settings.auth_authentication_cache_minutes = cache_minutes
+ user = await create_user_account()
+ for path in ("/api/v1/wallets", "/api/v1/status"):
+ response = await http_client.get(path, params={"usr": user.id})
+ assert response.status_code == 200
+ response = await http_client.post("/api/v1/auth/usr", json={"usr": user.id})
+ assert response.status_code == 200
+ # Populate the session cache as well before adding credentials.
+ assert (await http_client.get("/api/v1/status")).status_code == 200
+ response = await http_client.put(
+ "/api/v1/auth/password",
+ json={
+ "user_id": user.id,
+ "username": f"new_pass_{uuid4().hex[:8]}",
+ "password": "secret1234",
+ "password_repeat": "secret1234",
+ },
+ )
+ assert response.status_code == 200
+ http_client.cookies.clear()
+ response = await http_client.post("/api/v1/auth/usr", json={"usr": user.id})
+ assert response.status_code == 403
+ for method, path in (
+ ("GET", "/api/v1/wallets"),
+ ("GET", "/api/v1/status"),
+ ("PUT", f"/api/v1/wallet/reset/{user.wallets[0].id}"),
+ ):
+ response = await http_client.request(method, path, params={"usr": user.id})
+ assert response.status_code == 403
+ assert response.json()["detail"] == "This account requires password login."
### tests/api/test_users.py
@@ -367,7 +367,9 @@ async def test_update_user_invalid_username(http_client: AsyncClient, superuser_
async def test_update_superuser_only_allowed_by_superuser(
http_client: AsyncClient, user_alan: User, settings: Settings
):
- response = await http_client.post("/api/v1/auth/usr", json={"usr": user_alan.id})
+ response = await http_client.post(
+ "/api/v1/auth", json={"username": user_alan.username, "password": "secret1234"}
+ )
assert response.status_code == 200, "Alan logs in OK."
alan_access_token = response.json().get("access_token")
### tests/api/test_wallet_key_access.py
@@ -161,22 +161,23 @@ async def test_wallet_keys_require_current_endpoint_write_access(
@pytest.mark.anyio
async def test_wallet_keys_with_user_id_authentication(
http_client: AsyncClient,
- wallet_key_user: User,
settings: Settings,
):
+ user = await create_user_account()
+ user.wallets.append(await create_wallet(user_id=user.id, wallet_name="Second"))
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})
+ response = await http_client.get(path, params={"usr": 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"])
+ stored = user.get_wallet(wallet["id"])
assert stored
assert wallet["adminkey"] == stored.adminkey
assert wallet["inkey"] == stored.inkey
### tests/unit/test_decorators.py
@@ -109,11 +109,11 @@ async def test_check_user_exists_with_missing_access_token():
@pytest.mark.anyio
-async def test_check_user_exists_with_valid_user_id(user_alan: User):
+async def test_check_user_exists_with_valid_user_id(from_user: User):
request = Request({"type": "http", "path": "/some/path", "method": "GET"})
- user = await check_user_exists(request, access_token=None, usr=UUID(user_alan.id))
+ user = await check_user_exists(request, access_token=None, usr=UUID(from_user.id))
- assert user.id == user_alan.id
+ assert user.id == from_user.id
@pytest.mark.anyio
@@ -126,12 +126,12 @@ async def test_check_user_exists_with_invalid_user_id():
@pytest.mark.anyio
-async def test_check_user_exists_with_user_not_allowed(user_alan: User):
+async def test_check_user_exists_with_user_not_allowed(from_user: User):
settings.lnbits_admin_users = []
request = Request({"type": "http", "path": "/some/path", "method": "GET"})
settings.lnbits_allowed_users = ["only_this_user_id"]
with pytest.raises(HTTPException) as exc_info:
- await check_user_exists(request, access_token=None, usr=UUID(user_alan.id))
+ await check_user_exists(request, access_token=None, usr=UUID(from_user.id))
assert exc_info.value.status_code == 403
assert exc_info.value.detail == "User not allowed."
@@ -174,13 +174,13 @@ async def test_check_user_exists_after_user_deletion(http_client: AsyncClient):
@pytest.mark.anyio
async def test_check_user_exists_with_user_id_only_allowed(
- user_alan: User, settings: Settings
+ from_user: User, settings: Settings
):
settings.auth_allowed_methods = [AuthMethods.user_id_only.value]
request = Request({"type": "http", "path": "/some/path", "method": "GET"})
- user = await check_user_exists(request, access_token=None, usr=UUID(user_alan.id))
+ user = await check_user_exists(request, access_token=None, usr=UUID(from_user.id))
- assert user.id == user_alan.id
+ assert user.id == from_user.id
assert request.scope["user_id"] == user.id
@@ -266,19 +266,19 @@ async def test_check_api_write_access(mocker: MockerFixture, write: bool | None)
@pytest.mark.anyio
async def test_optional_user_id_uses_user_id_or_access_token(
- user_alan: User, settings: Settings
+ from_user: User, settings: Settings
):
settings.auth_allowed_methods = [AuthMethods.user_id_only.value]
request = Request({"type": "http", "path": "/wallet", "method": "GET"})
assert (
- await optional_user_id(request, access_token=None, usr=UUID(user_alan.id))
- == user_alan.id
+ await optional_user_id(request, access_token=None, usr=UUID(from_user.id))
+ == from_user.id
)
settings.auth_allowed_methods = []
- token = create_access_token({"sub": user_alan.username, "usr": user_alan.id})
- assert await optional_user_id(request, access_token=token, usr=None) == user_alan.id
+ token = create_access_token({"sub": from_user.username or "", "usr": from_user.id})
+ assert await optional_user_id(request, access_token=token, usr=None) == from_user.id
assert await optional_user_id(request, access_token=None, usr=None) is None
Why this scored 81/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.