feat: Add superuser action to reset all wallet keys (#4320)
What changed, and why it matters
This commit adds a recovery feature that lets the LNbits superuser instantly replace every wallet's secret keys, including keys for deleted wallets, and clear any cached copies of the old keys. The vendor says this is needed because of a recent security incident where wallet keys may have been exposed; without rotation, attackers could still spend or steal funds even after the server is upgraded. The change itself is a defensive control, not an attack, but it confirms the underlying incident is serious and affects all versions before 1.7.0.
Operators running LNbits versions before 1.7.0 should upgrade immediately and then use the new superuser 'Reset Wallet Keys' action to rotate all wallet keys and clear cached credentials, as instructed by the vendor. Review access logs for unauthorized use of wallet keys before rotating.
Security signals we found
Vendor describes the change as a recovery control for a security incident involving exposed wallet credentials
Vendor states all versions before 1.7.0 are affected and funds are at risk of theft
New superuser-only endpoint can rotate every wallet's admin and invoice keys, including deleted wallets
Old cached keys are explicitly invalidated during rotation
Tests confirm old keys return 404 after rotation and deleted-wallet restoration does not restore compromised keys
UI button is gated on superuser status and requires explicit confirmation
Evidence from the diff
The patch introduces reset_all_wallet_keys() in lnbits/core/crud/wallets.py, which iterates all wallet rows in 1000-row batches, regenerates adminkey and inkey as UUID4 hex strings, updates each wallet, and calls clear_wallet_cache() to remove cached auth entries. A new superuser-only endpoint POST /admin/api/v1/wallets/reset-keys is added in lnbits/core/views/admin_api.py. The admin UI adds a ‘Reset Wallet Keys’ button gated by isSuperUser. Tests verify that only superusers can invoke it, that old keys become invalid (HTTP 404), that deleted wallets’ old keys also become invalid upon restoration, that cache is cleared, that partial failures do not leave rotated wallets with stale cache, and that batches of 1000 are processed correctly. The vendor references frame this as a recovery action for a pre-1.7.0 credential-exposure incident that puts funds at risk.
Changed components
lnbits/core/crud/wallets.pylnbits/core/views/admin_api.pylnbits/static/js/components/admin/lnbits-admin-users.jslnbits/templates/components/admin/users.vuelnbits/templates/pages/admin.vueInspect captured patch +523 / −5
### lnbits/core/crud/wallets.py
@@ -77,6 +77,30 @@ async def update_wallet(
return wallet
+async def reset_all_wallet_keys(conn: Connection | None = None) -> int:
+ last_id = ""
+ count = 0
+ while settings.lnbits_running:
+ wallets = await (conn or db).fetchall(
+ """
+ SELECT * FROM wallets WHERE id > :last_id
+ ORDER BY id LIMIT 1000
+ """,
+ {"last_id": last_id},
+ model=Wallet,
+ )
+ if not wallets:
+ return count
+ for wallet in wallets:
+ clear_wallet_cache(wallet)
+ wallet.adminkey = uuid4().hex
+ wallet.inkey = uuid4().hex
+ await update_wallet(wallet, conn)
+ count += 1
+ last_id = wallets[-1].id
+ raise RuntimeError("Wallet key reset interrupted by shutdown.")
+
+
async def delete_wallet(
user_id: str,
wallet_id: str,
@@ -614,7 +638,7 @@ def clear_wallet_id_cache(wallet_id: str):
cache.pop(f"auth:x-api-key:{cached_wallet.inkey}")
-def clear_wallet_cache(wallet: Wallet):
+def clear_wallet_cache(wallet: BaseWallet):
cache.pop(f"auth:wallet:{wallet.id}")
cache.pop(f"auth:x-api-key:{wallet.adminkey}")
cache.pop(f"auth:x-api-key:{wallet.inkey}")
### lnbits/core/views/admin_api.py
@@ -16,6 +16,7 @@
from sqlalchemy.exc import ArgumentError
from starlette.concurrency import run_in_threadpool
+from lnbits.core.crud.wallets import reset_all_wallet_keys
from lnbits.core.models.notifications import NotificationType
from lnbits.core.models.users import AccessTokenPayload, Account
from lnbits.core.services import (
@@ -53,6 +54,20 @@
file_upload = File(...)
+@admin_router.post(
+ "/api/v1/wallets/reset-keys", dependencies=[Depends(check_super_user)]
+)
+async def api_reset_all_wallet_keys() -> dict[str, int]:
+ try:
+ count = await reset_all_wallet_keys()
+ except Exception as exc:
+ logger.warning(exc)
+ raise HTTPException(
+ HTTPStatus.INTERNAL_SERVER_ERROR, "Could not reset wallet keys."
+ ) from None
+ return {"wallets_updated": count}
+
+
@admin_router.get(
"/api/v1/audit",
name="Audit",
### lnbits/static/bundle-components.min.js
[binary or diff unavailable]
### lnbits/static/js/components/admin/lnbits-admin-users.js
@@ -1,15 +1,58 @@
window.app.component('lnbits-admin-users', {
- props: ['form-data'],
+ props: ['form-data', 'is-super-user'],
template: '#lnbits-admin-users',
data() {
return {
formAddUser: '',
formAddAdmin: '',
formAddActivationCode: '',
- showReusableActivationCode: false
+ showReusableActivationCode: false,
+ resettingWalletKeys: false
}
},
methods: {
+ resetWalletKeys() {
+ if (!this.isSuperUser || this.resettingWalletKeys) return
+ LNbits.utils
+ .confirmDialog(
+ 'Reset the admin and invoice keys for ALL wallets, including deleted wallets? ' +
+ 'Existing keys will stop working. Integrations must be updated with the new keys, ' +
+ 'and open wallet pages will need to be reloaded.'
+ )
+ .onOk(async () => {
+ if (this.resettingWalletKeys) return
+ this.resettingWalletKeys = true
+ try {
+ const {data} = await LNbits.api.request(
+ 'POST',
+ '/admin/api/v1/wallets/reset-keys'
+ )
+ Quasar.Notify.create({
+ type: 'positive',
+ message: `Keys reset for ${data.wallets_updated} wallets.`
+ })
+ try {
+ const response = await LNbits.api.getAuthUser()
+ this.g.user = LNbits.map.user(response.data)
+ if (this.g.wallet) {
+ this.g.wallet = this.g.user.wallets.find(
+ wallet => wallet.id === this.g.wallet.id
+ )
+ }
+ } catch {
+ Quasar.Notify.create({
+ type: 'warning',
+ message:
+ 'Wallet keys were reset. Reload this page to refresh your wallets.'
+ })
+ }
+ } catch (error) {
+ LNbits.utils.notifyApiError(error)
+ } finally {
+ this.resettingWalletKeys = false
+ }
+ })
+ },
addAllowedUser() {
let addUser = this.formAddUser
let allowed_users = this.formData.lnbits_allowed_users
### lnbits/templates/components/admin/users.vue
@@ -1,5 +1,15 @@
<template id="lnbits-admin-users">
<q-card-section class="q-pa-none">
+ <q-btn
+ v-if="isSuperUser"
+ class="q-mb-md"
+ color="negative"
+ outline
+ icon="refresh"
+ label="Reset Wallet Keys"
+ :loading="resettingWalletKeys"
+ @click="resetWalletKeys"
+ ></q-btn>
<h6 class="q-my-none q-mb-sm">
<span v-text="$t('user_management')"></span>
</h6>
### lnbits/templates/pages/admin.vue
@@ -225,7 +225,10 @@
<lnbits-admin-fiat-providers :form-data="formData" />
</q-tab-panel>
<q-tab-panel name="users" class="q-pa-md">
- <lnbits-admin-users :form-data="formData" />
+ <lnbits-admin-users
+ :form-data="formData"
+ :is-super-user="isSuperUser"
+ />
</q-tab-panel>
<q-tab-panel name="server" class="q-pa-md">
<lnbits-admin-server
### tests/api/test_wallet_key_reset.py
@@ -0,0 +1,264 @@
+from uuid import UUID, uuid4
+
+import pytest
+
+from lnbits.core.crud.wallets import (
+ clear_wallet_cache,
+ create_wallet,
+ delete_wallet,
+ force_delete_wallet,
+ reset_all_wallet_keys,
+)
+from lnbits.core.db import db
+from lnbits.core.models.wallets import (
+ BaseWallet,
+ BaseWalletTypeInfo,
+ KeyType,
+ WalletType,
+)
+from lnbits.helpers import create_access_token
+from lnbits.utils.cache import cache
+
+RESET_URL = "/admin/api/v1/wallets/reset-keys"
+
+
+@pytest.fixture
+async def superuser_wallet(http_client, settings):
+ wallet = await create_wallet(user_id=settings.super_user)
+ try:
+ yield wallet
+ finally:
+ await force_delete_wallet(wallet.id)
+
+
+@pytest.fixture
+async def reset_wallets(http_client, from_user, admin_user, settings, request):
+ created = []
+ owners = [from_user.id, admin_user.id, settings.super_user]
+ for deleted in (False, True):
+ for index, wallet_type in enumerate(WalletType):
+ wallet = await create_wallet(
+ user_id=owners[index % len(owners)],
+ wallet_type=wallet_type,
+ shared_wallet_id=(
+ created[0].id
+ if wallet_type == WalletType.LIGHTNING_SHARED
+ else None
+ ),
+ )
+ created.append(wallet)
+ if deleted:
+ await delete_wallet(wallet.user, wallet.id)
+
+ for _ in range(getattr(request, "param", 0)):
+ created.append(await create_wallet(user_id=from_user.id))
+
+ before = await db.fetchall("SELECT * FROM wallets ORDER BY id")
+ try:
+ yield before, created
+ finally:
+ # Other API tests retain session-scoped wallet objects and their keys.
+ current = await db.fetchall("SELECT * FROM wallets", model=BaseWallet)
+ for wallet in current:
+ clear_wallet_cache(wallet)
+ for row in before:
+ await db.execute(
+ f"""UPDATE wallets SET adminkey = :adminkey, inkey = :inkey,
+ updated_at = {db.timestamp_placeholder('updated_at')}
+ WHERE id = :id""", # noqa: S608
+ {key: row[key] for key in ("id", "adminkey", "inkey", "updated_at")},
+ )
+ for wallet in created:
+ await force_delete_wallet(wallet.id)
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "auth",
+ ["anonymous", "invalid", "user", "admin", "adminkey", "inkey", "superkey"],
+)
+async def test_bulk_key_reset_requires_superuser(
+ http_client,
+ auth,
+ user_headers_from,
+ admin_user,
+ from_wallet,
+ superuser_wallet,
+ mocker,
+):
+ reset = mocker.patch(
+ "lnbits.core.views.admin_api.reset_all_wallet_keys",
+ new_callable=mocker.AsyncMock,
+ )
+ headers = {}
+ if auth == "invalid":
+ headers = {"Authorization": "Bearer invalid"}
+ elif auth == "user":
+ headers = user_headers_from
+ elif auth == "admin":
+ token = create_access_token({"sub": admin_user.username, "usr": admin_user.id})
+ headers = {"Authorization": f"Bearer {token}"}
+ elif auth in ("adminkey", "inkey"):
+ headers = {"X-Api-Key": getattr(from_wallet, auth)}
+ elif auth == "superkey":
+ headers = {"X-Api-Key": superuser_wallet.adminkey}
+
+ response = await http_client.post(RESET_URL, headers=headers)
+ assert response.status_code == (403 if auth in ("user", "admin") else 401)
+ reset.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("token_source", ["header", "cookie"])
+async def test_bulk_key_reset_rotates_every_wallet(
+ http_client, superuser_token, reset_wallets, settings, token_source
+):
+ before, created = reset_wallets
+ settings.auth_authentication_cache_minutes = 1
+ active = created[: len(WalletType)]
+ balances = await db.fetchall("SELECT * FROM balances ORDER BY wallet_id")
+ for wallet in active:
+ for key in (wallet.adminkey, wallet.inkey):
+ response = await http_client.get(
+ "/api/v1/payments", headers={"X-Api-Key": key}
+ )
+ assert response.status_code == 200
+ assert cache.get(f"auth:x-api-key:{key}") is not None
+
+ headers = {}
+ if token_source == "header":
+ headers = {"Authorization": f"Bearer {superuser_token}"}
+ else:
+ http_client.cookies.set("cookie_access_token", superuser_token)
+ response = await http_client.post(RESET_URL, headers=headers)
+ assert response.status_code == 200
+ assert response.json() == {"wallets_updated": len(before)}
+
+ after = await db.fetchall("SELECT * FROM wallets ORDER BY id")
+ old_keys = {row[field] for row in before for field in ("adminkey", "inkey")}
+ new_keys = {row[field] for row in after for field in ("adminkey", "inkey")}
+ assert len(new_keys) == len(after) * 2
+ assert old_keys.isdisjoint(new_keys)
+ for key in new_keys:
+ assert UUID(hex=key).version == 4
+ assert len(key) == 32
+ for old, new in zip(before, after, strict=True):
+ assert {
+ k: v for k, v in old.items() if k not in ("adminkey", "inkey", "updated_at")
+ } == {
+ k: v for k, v in new.items() if k not in ("adminkey", "inkey", "updated_at")
+ }
+ assert await db.fetchall("SELECT * FROM balances ORDER BY wallet_id") == balances
+
+ for wallet in active:
+ assert cache.get(f"auth:wallet:{wallet.id}") is None
+ for key in (wallet.adminkey, wallet.inkey):
+ assert cache.get(f"auth:x-api-key:{key}") is None
+ response = await http_client.get(
+ "/api/v1/payments", headers={"X-Api-Key": key}
+ )
+ assert response.status_code == 404
+ new = next(row for row in after if row["id"] == wallet.id)
+ for field in ("adminkey", "inkey"):
+ response = await http_client.get(
+ "/api/v1/payments", headers={"X-Api-Key": new[field]}
+ )
+ assert response.status_code == 200
+
+ # Restoring a deleted wallet must not restore its compromised keys.
+ deleted_wallet = created[len(WalletType)]
+ await delete_wallet(deleted_wallet.user, deleted_wallet.id, deleted=False)
+ try:
+ for key in (deleted_wallet.adminkey, deleted_wallet.inkey):
+ response = await http_client.get(
+ "/api/v1/wallet", headers={"X-Api-Key": key}
+ )
+ assert response.status_code == 404
+ finally:
+ await delete_wallet(deleted_wallet.user, deleted_wallet.id)
+
+ # The superuser session still retrieves fresh wallet credentials.
+ response = await http_client.get("/api/v1/auth", headers=headers)
+ assert response.status_code == 200
+ assert all(wallet["adminkey"] in new_keys for wallet in response.json()["wallets"])
+
+
+@pytest.mark.anyio
+async def test_bulk_key_reset_failure_clears_rotated_wallet_cache(
+ http_client, superuser_token, reset_wallets, monkeypatch, mocker
+):
+ before, _ = reset_wallets
+ calls = 0
+ error = RuntimeError("database update failed")
+ warning = mocker.patch("lnbits.core.views.admin_api.logger.warning")
+ for row in before:
+ wallet = BaseWallet(**row)
+ cache.set(f"auth:wallet:{wallet.id}", wallet, expiry=60)
+ for key, key_type in (
+ (wallet.adminkey, KeyType.admin),
+ (wallet.inkey, KeyType.invoice),
+ ):
+ cache.set(
+ f"auth:x-api-key:{key}", BaseWalletTypeInfo(key_type, wallet), expiry=60
+ )
+
+ def fail_after_first_wallet():
+ nonlocal calls
+ calls += 1
+ if calls == 3:
+ raise error
+ return uuid4()
+
+ with monkeypatch.context() as patch:
+ patch.setattr("lnbits.core.crud.wallets.uuid4", fail_after_first_wallet)
+ response = await http_client.post(
+ RESET_URL, headers={"Authorization": f"Bearer {superuser_token}"}
+ )
+ assert calls == 3
+ assert response.status_code == 500
+ assert response.json() == {"detail": "Could not reset wallet keys."}
+ warning.assert_called_once_with(error)
+ after = await db.fetchall("SELECT * FROM wallets ORDER BY id")
+ rotated = []
+ for old, new in zip(before, after, strict=True):
+ if old["adminkey"] == new["adminkey"]:
+ assert new == old
+ continue
+ rotated.append(old["id"])
+ assert old["inkey"] != new["inkey"]
+ assert cache.get(f"auth:wallet:{old['id']}") is None
+ for field in ("adminkey", "inkey"):
+ assert cache.get(f"auth:x-api-key:{old[field]}") is None
+ assert len(rotated) == 1
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("reset_wallets", [1000], indirect=True)
+async def test_bulk_key_reset_fetches_batches_of_1000(reset_wallets, mocker):
+ before, _ = reset_wallets
+ fetch = mocker.spy(db, "fetchall")
+
+ assert await reset_all_wallet_keys() == len(before)
+ assert [len(batch) for batch in fetch.spy_return_list] == [
+ 1000,
+ len(before) - 1000,
+ 0,
+ ]
+ after = await db.fetchall("SELECT * FROM wallets ORDER BY id")
+ for old, new in zip(before, after, strict=True):
+ assert old["id"] == new["id"]
+ assert old["adminkey"] != new["adminkey"]
+ assert old["inkey"] != new["inkey"]
+
+
+@pytest.mark.anyio
+async def test_bulk_key_reset_shutdown_is_not_reported_as_success(
+ http_client, superuser_token, reset_wallets, mocker
+):
+ before, _ = reset_wallets
+ mocker.patch("lnbits.core.crud.wallets.settings", lnbits_running=False)
+ response = await http_client.post(
+ RESET_URL, headers={"Authorization": f"Bearer {superuser_token}"}
+ )
+ assert response.status_code == 500
+ assert await db.fetchall("SELECT * FROM wallets ORDER BY id") == before
### tests/unit/admin-wallet-key-reset.test.cjs
@@ -0,0 +1,159 @@
+const assert = require('node:assert/strict')
+const {readFileSync} = require('node:fs')
+const {resolve} = require('node:path')
+const {test} = require('node:test')
+const vm = require('node:vm')
+const {createSSRApp, h} = require('vue')
+const {renderToString} = require('vue/server-renderer')
+
+function harness() {
+ let component
+ let confirm
+ const requests = []
+ const notices = []
+ const errors = []
+ const freshUser = {
+ wallets: [{id: 'wallet', adminkey: 'new', inkey: 'new-in'}]
+ }
+ const api = {
+ async request(...args) {
+ requests.push(args)
+ return {data: {wallets_updated: 42}}
+ },
+ async getAuthUser() {
+ return {data: freshUser}
+ }
+ }
+ vm.runInNewContext(
+ readFileSync(
+ resolve(
+ __dirname,
+ '../../lnbits/static/js/components/admin/lnbits-admin-users.js'
+ ),
+ 'utf8'
+ ),
+ {
+ window: {app: {component: (_, value) => (component = value)}},
+ LNbits: {
+ api,
+ map: {user: value => value},
+ utils: {
+ confirmDialog: () => ({onOk: callback => (confirm = callback)}),
+ notifyApiError: error => errors.push(error)
+ }
+ },
+ Quasar: {Notify: {create: notice => notices.push(notice)}}
+ }
+ )
+ const instance = {
+ ...component.data(),
+ isSuperUser: true,
+ g: {
+ user: {wallets: [{id: 'wallet', adminkey: 'old'}]},
+ wallet: {id: 'wallet', adminkey: 'old'}
+ }
+ }
+ for (const [name, method] of Object.entries(component.methods)) {
+ instance[name] = method.bind(instance)
+ }
+ return {
+ component,
+ instance,
+ api,
+ requests,
+ notices,
+ errors,
+ freshUser,
+ confirm: () => confirm?.()
+ }
+}
+
+test('the reset button is rendered only for the superuser', async () => {
+ const {component} = harness()
+ const template = readFileSync(
+ resolve(__dirname, '../../lnbits/templates/components/admin/users.vue'),
+ 'utf8'
+ )
+ .replace(/^<template[^>]*>/, '')
+ .replace(/<\/template>\s*$/, '')
+ for (const isSuperUser of [false, true]) {
+ const app = createSSRApp(
+ {...component, template},
+ {formData: {}, isSuperUser}
+ )
+ app.config.globalProperties.$t = key => key
+ app.directive('ripple', {})
+ for (const [, name] of template.matchAll(/<(q-[\w-]+)/g)) {
+ if (app.component(name)) continue
+ app.component(name, {
+ props: ['label'],
+ setup:
+ (props, {slots}) =>
+ () =>
+ h(name === 'q-btn' ? 'button' : 'div', [
+ props.label,
+ slots.default?.()
+ ])
+ })
+ }
+ const html = await renderToString(app)
+ assert.equal(html.includes('Reset Wallet Keys'), isSuperUser)
+ }
+})
+
+test('reset requires both the superuser and confirmation', async () => {
+ const h = harness()
+ h.instance.isSuperUser = false
+ h.instance.resetWalletKeys()
+ await h.confirm()
+ assert.equal(h.requests.length, 0)
+ h.instance.isSuperUser = true
+ h.instance.resetWalletKeys()
+ // Dismissing the dialog never calls its onOk callback.
+ assert.equal(h.requests.length, 0)
+})
+
+test('confirmed reset prevents duplicate requests and refreshes wallet keys', async () => {
+ const h = harness()
+ h.instance.resetWalletKeys()
+ const pending = h.confirm()
+ assert.equal(h.instance.resettingWalletKeys, true)
+ await h.confirm()
+ await pending
+ assert.deepEqual(h.requests, [['POST', '/admin/api/v1/wallets/reset-keys']])
+ assert.equal(h.instance.resettingWalletKeys, false)
+ assert.equal(h.instance.g.user, h.freshUser)
+ assert.equal(h.instance.g.wallet, h.freshUser.wallets[0])
+ assert.equal(h.notices[0].message, 'Keys reset for 42 wallets.')
+ assert.equal(h.errors.length, 0)
+})
+
+test('reset failure preserves local keys and allows retry', async () => {
+ const h = harness()
+ const error = new Error('request failed')
+ h.api.request = async () => {
+ throw error
+ }
+ h.instance.resetWalletKeys()
+ await h.confirm()
+ assert.equal(h.instance.resettingWalletKeys, false)
+ assert.equal(h.instance.g.wallet.adminkey, 'old')
+ assert.deepEqual(h.errors, [error])
+ assert.equal(h.notices.length, 0)
+})
+
+test('refresh failure still reports the completed reset and asks for reload', async () => {
+ const h = harness()
+ h.api.getAuthUser = async () => {
+ throw new Error('refresh failed')
+ }
+ h.instance.resetWalletKeys()
+ await h.confirm()
+ assert.equal(h.instance.resettingWalletKeys, false)
+ assert.deepEqual(
+ h.notices.map(notice => notice.type),
+ ['positive', 'warning']
+ )
+ assert.match(h.notices[1].message, /Reload/)
+ assert.equal(h.errors.length, 0)
+})Why this scored 100/100
Evidence and disclosure record
Verified links used to place this patch in context. External claims remain attributed to their publishers.
Add superuser recovery action to reset every wallet key
Recovery control added for the incident: a superuser can rotate admin and invoice keys for all wallets, including deleted wallets, and invalidate cached old keys. LNbits' operator guidance requires this step because exposed credentials may remain usable after upgrading.
LNbits 1.7.0 security update and recovery guidance
The vendor says every version before 1.7.0 is affected, funds are at risk of theft, and exposed credentials may remain usable after an upgrade. It requires key and secret rotation in addition to updating.
LNbits v1.7.0 urgent security update
The first stable release containing the November incident fixes and recovery controls. LNbits instructs all operators to update immediately.
LNbits v1.7.0 security release announcement
Official announcement that v1.7.0 is released and operators should follow the linked upgrade guidance.
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.