Skip to content

Commit 67d7dc9

Browse files
authored
fix: removing admin tokens when deleted (#1728)
1 parent 4fca64f commit 67d7dc9

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

packages/ns-api/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ define Package/ns-api/install
194194
$(INSTALL_BIN) ./files/post-commit/restart-cron.py $(1)/usr/libexec/ns-api/post-commit
195195
$(INSTALL_BIN) ./files/post-commit/update-timezone.py $(1)/usr/libexec/ns-api/post-commit
196196
$(INSTALL_BIN) ./files/post-commit/restart-wireguard.py $(1)/usr/libexec/ns-api/post-commit
197+
$(INSTALL_BIN) ./files/post-commit/clear-user-tokens.py $(1)/usr/libexec/ns-api/post-commit
197198
$(INSTALL_BIN) ./files/pre-commit/clean-network.py $(1)/usr/libexec/ns-api/pre-commit
198199
$(INSTALL_BIN) ./files/remove-pppoe-keepalive $(1)/usr/share/ns-api
199200
$(INSTALL_DIR) $(1)/etc/uci-defaults
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/python3
2+
3+
#
4+
# Copyright (C) 2026 Nethesis S.r.l.
5+
# SPDX-License-Identifier: GPL-2.0-only
6+
#
7+
8+
# Log out users that have been deleted or demoted from the admin role:
9+
# remove their token store so the API server invalidates all their sessions.
10+
# Only admins (rpcd login sections) can authenticate against the API, so any
11+
# token file whose username is no longer an admin is stale and must be purged.
12+
13+
import glob
14+
import os
15+
16+
from euci import EUci
17+
from nethsec import utils
18+
19+
TOKENS_DIR = "/var/run/ns-api-server/tokens"
20+
21+
# Admin role changes are tracked in the rpcd configuration.
22+
# `changes` is injected by ns.commit when the hook is exec'd.
23+
if "rpcd" in changes and os.path.isdir(TOKENS_DIR): # noqa: F821
24+
u = EUci()
25+
admins = set()
26+
for login in (utils.get_all_by_type(u, "rpcd", "login") or {}).values():
27+
username = login.get("username")
28+
if username:
29+
admins.add(username)
30+
31+
for token_file in glob.glob(os.path.join(TOKENS_DIR, "*")):
32+
username = os.path.basename(token_file)
33+
if username not in admins:
34+
try:
35+
os.remove(token_file)
36+
except OSError:
37+
pass

0 commit comments

Comments
 (0)