What changed, and why it matters
This commit adds a user-interface setting for a 'credentials update threshold' and, more importantly, fixes a security gap in the authentication cache. Previously, when a user's login was cached for performance, API-token permissions were not re-checked on every request. That meant a cached session could continue using an API token even after the token had been deleted or its permissions had been reduced. The patch now re-validates the API token's permissions on each cached request and adds tests to prove it.
Review the new _check_account_api_access call for correct exception handling and ensure the auth_credetials_update_threshold setting is enforced server-side (the UI field alone does not prove enforcement). Consider whether the cache invalidation logic covers all credential-update paths, and run the new tests to confirm the fix.
Security signals we found
Cached authentication bypassed API-token permission re-validation
Added per-request API-token ACL re-check inside the auth cache fast-path
New test demonstrates cached token is rejected after ACL removal and after permission narrowing
New admin UI field for credentials-update threshold suggests related security policy work
Evidence from the diff
In lnbits/decorators.py the cached-account lookup path now decodes the access token and calls _check_account_api_access(…) before relying on the cached account_id. A new helper _decode_access_token(…) separates JWT decoding from account lookup. The Vue admin security panel adds an input for auth_credetials_update_threshold (note the typo ‘credetials’ in the variable name). Tests in tests/api/test_auth.py are added/extended to verify that cached API-token access is revalidated after ACL changes and token deletion, and that expired tokens are rejected even when present in cache.
Changed components
lnbits/decorators.pylnbits/templates/components/admin/security.vuetests/api/test_auth.pyInspect captured patch +183 / −44
diff --git a/lnbits/decorators.py b/lnbits/decorators.py
index da7c627..62d99da 100644
--- a/lnbits/decorators.py
+++ b/lnbits/decorators.py
@@ -248,6 +248,15 @@ async def check_account_id_exists(
if cache_key and settings.auth_authentication_cache_minutes > 0:
account_id = cache.get(cache_key)
if account_id:
+ payload = _decode_access_token(access_token) if access_token else None
+ if payload and payload.api_token_id:
+ await _check_account_api_access(
+ account_id.id,
+ payload.api_token_id,
+ r["path"],
+ r["method"],
+ conn=conn,
+ )
r.scope["user_id"] = account_id.id
await _check_user_access(r, account_id.id, conn=conn)
return account_id
@@ -469,11 +478,14 @@ def _extension_id_from_request_path(path: str) -> str:
async def _get_account_from_token(
access_token: str, path: str, method: str, conn: Connection | None = None
) -> Account | None:
+ payload = _decode_access_token(access_token)
+ return await _get_account_from_jwt_payload(payload, path, method, conn=conn)
+
+
+def _decode_access_token(access_token: str) -> AccessTokenPayload:
try:
payload: dict = jwt.decode(access_token, settings.auth_secret_key, ["HS256"])
- return await _get_account_from_jwt_payload(
- AccessTokenPayload(**payload), path, method, conn=conn
- )
+ return AccessTokenPayload(**payload)
except jwt.ExpiredSignatureError as exc:
raise HTTPException(
diff --git a/lnbits/templates/components/admin/security.vue b/lnbits/templates/components/admin/security.vue
index d5e9382..19a3b72 100644
--- a/lnbits/templates/components/admin/security.vue
+++ b/lnbits/templates/components/admin/security.vue
@@ -17,7 +17,7 @@
<span v-text="$t('authentication')"></span>
</h6>
<div class="row q-col-gutter-sm q-mb-md">
- <div class="col-12 col-md-6">
+ <div class="col-12 col-md-4">
<q-input
filled
v-model="formData.auth_token_expire_minutes"
@@ -27,7 +27,7 @@
>
</q-input>
</div>
- <div class="col-12 col-md-6">
+ <div class="col-12 col-md-4">
<q-input
filled
v-model="formData.auth_authentication_cache_minutes"
@@ -37,7 +37,17 @@
>
</q-input>
</div>
- <div class="col-12 col-md-6">
+ <div class="col-12 col-md-4">
+ <q-input
+ filled
+ v-model="formData.auth_credetials_update_threshold"
+ type="number"
+ label="Credentials update threshold (seconds)"
+ hint="Maximum authentication age allowed when updating credentials"
+ >
+ </q-input>
+ </div>
+ <div class="col-12 col-md-12">
<q-select
filled
v-model="formData.auth_allowed_methods"
diff --git a/tests/api/test_auth.py b/tests/api/test_auth.py
index e8998a2..4aca157 100644
--- a/tests/api/test_auth.py
+++ b/tests/api/test_auth.py
@@ -11,6 +11,7 @@ from coincurve import PrivateKey
from httpx import AsyncClient
from lnbits.core.crud.users import (
+ delete_account,
get_user_access_control_lists,
update_user_access_control_list,
)
@@ -19,6 +20,7 @@ from lnbits.core.models.misc import SimpleItem
from lnbits.core.models.users import (
AccessControlList,
Account,
+ AccountId,
ApiTokenRequest,
DeleteTokenRequest,
EndpointAccess,
@@ -31,7 +33,7 @@ from lnbits.core.models.users import (
from lnbits.core.services.users import create_user_account
from lnbits.core.views import auth_api
from lnbits.core.views.user_api import api_users_reset_password
-from lnbits.helpers import create_access_token
+from lnbits.helpers import create_access_token, sha256s
from lnbits.settings import AuthMethods, Settings
from lnbits.utils.cache import cache
from lnbits.utils.nostr import hex_to_npub, sign_event
@@ -1855,6 +1857,50 @@ async def test_api_create_user_api_token_success(
assert abs(stored_token.expires_at - expiration_time) <= 1
+@pytest.mark.anyio
+async def test_api_create_user_api_token_invalid_password(http_client: AsyncClient):
+ # Register a new user
+ tiny_id = shortuuid.uuid()[:8]
+ response = await http_client.post(
+ "/api/v1/auth/register",
+ json={
+ "username": f"u21.{tiny_id}",
+ "password": "secret1234",
+ "password_repeat": "secret1234",
+ "email": f"u21.{tiny_id}@lnbits.com",
+ },
+ )
+ assert response.status_code == 200, "User created."
+ access_token = response.json().get("access_token")
+ assert access_token is not None
+
+ # Create a new ACL
+ acl_data = UpdateAccessControlList(
+ password="secret1234", id="", name="Test ACL", endpoints=[]
+ )
+ response = await http_client.put(
+ "/api/v1/auth/acl",
+ headers={"Authorization": f"Bearer {access_token}"},
+ json=acl_data.dict(),
+ )
+ assert response.status_code == 200, "ACL created."
+ acl_id = response.json()["access_control_list"][0]["id"]
+
+ # Create API token with invalid password
+ token_request = ApiTokenRequest(
+ acl_id=acl_id,
+ token_name="Test Token",
+ expiration_time_minutes=60,
+ password="wrongpassword",
+ )
+ response = await http_client.post(
+ "/api/v1/auth/acl/token",
+ headers={"Authorization": f"Bearer {access_token}"},
+ json=token_request.dict(),
+ )
+ assert response.status_code == 401, "Invalid credentials."
+
+
@pytest.mark.anyio
async def test_acl_api_token_access(user_alan: User, http_client: AsyncClient):
user_acls = await get_user_access_control_lists(user_alan.id)
@@ -1932,47 +1978,118 @@ async def test_acl_api_token_access(user_alan: User, http_client: AsyncClient):
@pytest.mark.anyio
-async def test_api_create_user_api_token_invalid_password(http_client: AsyncClient):
- # Register a new user
- tiny_id = shortuuid.uuid()[:8]
- response = await http_client.post(
- "/api/v1/auth/register",
- json={
- "username": f"u21.{tiny_id}",
- "password": "secret1234",
- "password_repeat": "secret1234",
- "email": f"u21.{tiny_id}@lnbits.com",
- },
- )
- assert response.status_code == 200, "User created."
- access_token = response.json().get("access_token")
- assert access_token is not None
+async def test_cached_acl_api_token_access_is_revalidated(
+ http_client: AsyncClient, settings: Settings
+):
+ assert settings.auth_authentication_cache_minutes > 0
- # Create a new ACL
- acl_data = UpdateAccessControlList(
- password="secret1234", id="", name="Test ACL", endpoints=[]
- )
- response = await http_client.put(
- "/api/v1/auth/acl",
- headers={"Authorization": f"Bearer {access_token}"},
- json=acl_data.dict(),
+ username = f"ct{uuid4().hex[:8]}"
+ account = Account(
+ id=uuid4().hex,
+ username=username,
+ email=f"{username}@lnbits.com",
)
- assert response.status_code == 200, "ACL created."
- acl_id = response.json()["access_control_list"][0]["id"]
+ account.hash_password("secret1234")
+ user = await create_user_account(account)
- # Create API token with invalid password
- token_request = ApiTokenRequest(
- acl_id=acl_id,
- token_name="Test Token",
- expiration_time_minutes=60,
- password="wrongpassword",
+ user_acls = await get_user_access_control_lists(user.id)
+ acl = AccessControlList(
+ id=uuid4().hex,
+ name="Cached Token ACL",
+ endpoints=[EndpointAccess(path="/api/v1/status", name="Status", read=True)],
)
- response = await http_client.post(
- "/api/v1/auth/acl/token",
- headers={"Authorization": f"Bearer {access_token}"},
- json=token_request.dict(),
- )
- assert response.status_code == 401, "Invalid credentials."
+ user_acls.access_control_list = [acl]
+
+ cache_keys: list[str] = []
+ try:
+ api_token_id = uuid4().hex
+ api_token = create_access_token(
+ data=AccessTokenPayload(
+ sub=username,
+ api_token_id=api_token_id,
+ auth_time=int(time.time()),
+ ).dict(),
+ token_expire_minutes=10,
+ )
+ acl.token_id_list.append(SimpleItem(id=api_token_id, name="Status Token"))
+ await update_user_access_control_list(user_acls)
+
+ headers = {"Authorization": f"Bearer {api_token}"}
+ cache_keys.append(f"auth:access_token:{sha256s(api_token)}")
+
+ response = await http_client.get("/api/v1/wallet/paginated", headers=headers)
+ assert response.status_code == 403
+ assert response.json()["detail"] == "Path not allowed."
+
+ response = await http_client.get("/api/v1/status", headers=headers)
+ assert response.status_code == 200
+
+ response = await http_client.get("/api/v1/wallet/paginated", headers=headers)
+ assert response.status_code == 403
+ assert response.json()["detail"] == "Path not allowed."
+
+ acl.delete_token_by_id(api_token_id)
+ await update_user_access_control_list(user_acls)
+ response = await http_client.get("/api/v1/status", headers=headers)
+ assert response.status_code == 403
+ assert response.json()["detail"] == "Invalid token id."
+
+ api_token_id = uuid4().hex
+ api_token = create_access_token(
+ data=AccessTokenPayload(
+ sub=username,
+ api_token_id=api_token_id,
+ auth_time=int(time.time()),
+ ).dict(),
+ token_expire_minutes=10,
+ )
+ acl.endpoints = [
+ EndpointAccess(path="/api/v1/wallet", name="Wallets", read=True)
+ ]
+ acl.token_id_list = [SimpleItem(id=api_token_id, name="Read-only Token")]
+ await update_user_access_control_list(user_acls)
+
+ headers = {"Authorization": f"Bearer {api_token}"}
+ cache_keys.append(f"auth:access_token:{sha256s(api_token)}")
+ response = await http_client.get("/api/v1/wallet/paginated", headers=headers)
+ assert response.status_code == 200
+
+ response = await http_client.delete(
+ f"/api/v1/wallet/{uuid4().hex}", headers=headers
+ )
+ assert response.status_code == 403
+ assert response.json()["detail"] == "Method not allowed."
+
+ expired_token_id = uuid4().hex
+ expired_token = jwt.encode(
+ {
+ "sub": username,
+ "api_token_id": expired_token_id,
+ "auth_time": int(time.time()),
+ "exp": int(time.time()) - 1,
+ },
+ settings.auth_secret_key,
+ "HS256",
+ )
+ expired_cache_key = f"auth:access_token:{sha256s(expired_token)}"
+ cache_keys.append(expired_cache_key)
+ cache.set(
+ expired_cache_key,
+ AccountId(id=user.id),
+ expiry=settings.auth_authentication_cache_minutes * 60,
+ )
+
+ response = await http_client.get(
+ "/api/v1/status",
+ headers={"Authorization": f"Bearer {expired_token}"},
+ )
+ assert response.status_code == 401
+ assert response.json()["detail"] == "Session expired."
+ finally:
+ for cache_key in cache_keys:
+ cache.pop(cache_key)
+ cache.pop(f"auth:user:cache_key:{sha256s(user.id)}")
+ await delete_account(user.id)
@pytest.mark.anyio
Why this scored 45/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.