refactor(backend): user app idTags validated against the user record, not the allowlist
'app token of <name>' synthetic allowlist entries are gone: decide() recognizes a user's personal idTag directly, enforces the user's own charger:<cp>:<gun> scopes at the charger-side gate, and attributes the session (who=user, method=app). charger_start no longer auto-enrolls; PUT /api/allowlist/<user-tag> returns 400; stale entries auto-drop at startup. Zero-user open mode still authorizes 'app-remote' for bootstrap. Smoke: 63 checks.
This commit is contained in:
@@ -54,6 +54,12 @@ def _load() -> dict:
|
||||
for key, default in DEFAULTS.items():
|
||||
cfg.setdefault(key, default if not isinstance(default, dict) else dict(default))
|
||||
cfg.pop("learn_mode", None) # superseded by the pending-cards workflow
|
||||
# users' app idTags used to be auto-enrolled as "app token of <name>"
|
||||
# allowlist entries; they now authorize via the user record directly
|
||||
user_tags = {u.get("id_tag") for u in cfg["users"].values()}
|
||||
for tag in [t for t in cfg["authorized"] if t in user_tags]:
|
||||
del cfg["authorized"][tag]
|
||||
log.info("dropped redundant allowlist entry %r (a user's app token)", tag)
|
||||
if not cfg.get("session_secret"):
|
||||
cfg["session_secret"] = secrets.token_hex(32)
|
||||
return cfg
|
||||
|
||||
+37
-4
@@ -26,7 +26,7 @@ from ocpp.v16.enums import (
|
||||
RegistrationStatus,
|
||||
)
|
||||
|
||||
from . import store
|
||||
from . import store, users
|
||||
from .config import CONFIG, HERE, save
|
||||
from .journal import now, record_event
|
||||
|
||||
@@ -68,11 +68,16 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
|
||||
which matches this charger, since AuthorizeRemoteTxRequests=false means
|
||||
StartTransaction is the decisive call anyway.
|
||||
|
||||
A user's app idTag (users.<name>.id_tag, used for their in-app starts) is
|
||||
validated directly against the user record — it is NOT an allowlist entry,
|
||||
and it must satisfy the user's own charger:<cp>:<gun> scopes.
|
||||
|
||||
Unknown idTags are always refused: silently if the admin already rejected
|
||||
the card, otherwise they land in pending_cards for the admin to decide.
|
||||
"""
|
||||
entry = CONFIG["authorized"].get(id_tag)
|
||||
known = entry is not None
|
||||
app_user = user_for_tag(id_tag)
|
||||
gun = f"{cp}:{connector}" if cp and connector is not None else None
|
||||
if known and gun and entry.get("guns") \
|
||||
and not any(fnmatch(gun, pat) for pat in entry["guns"]):
|
||||
@@ -83,6 +88,20 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
|
||||
name = entry.get("name", "?")
|
||||
log.info("[OK] AUTHORIZED idTag=%r (%s) via %s", id_tag, name, context)
|
||||
status = AuthorizationStatus.accepted
|
||||
elif app_user is not None:
|
||||
known = True
|
||||
scopes = CONFIG["users"][app_user].get("scopes", [])
|
||||
if gun and not users.allowed(scopes, f"charger:{cp}:{connector}"):
|
||||
log.warning("[NO] REJECTED app idTag of %r on %s (no permission)",
|
||||
app_user, gun)
|
||||
status = AuthorizationStatus.invalid
|
||||
else:
|
||||
log.info("[OK] AUTHORIZED app start by user %r via %s", app_user, context)
|
||||
status = AuthorizationStatus.accepted
|
||||
elif id_tag == "app-remote" and not CONFIG["users"]:
|
||||
# bootstrap: with zero users the API is open and starts run as "app-remote"
|
||||
log.info("[OK] AUTHORIZED app-remote (open mode, no users yet)")
|
||||
status = AuthorizationStatus.accepted
|
||||
elif id_tag in CONFIG["denied_cards"]:
|
||||
log.warning("[NO] DENIED idTag=%r (admin-rejected card) via %s", id_tag, context)
|
||||
status = AuthorizationStatus.invalid
|
||||
@@ -98,6 +117,14 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
|
||||
return status
|
||||
|
||||
|
||||
def user_for_tag(id_tag: str) -> Optional[str]:
|
||||
"""Username whose personal app idTag this is, if any."""
|
||||
for username, user in CONFIG["users"].items():
|
||||
if user.get("id_tag") == id_tag:
|
||||
return username
|
||||
return None
|
||||
|
||||
|
||||
def resolve_who(id_tag: str) -> str:
|
||||
"""Human label for a session: the card's owning user, the allowlist entry
|
||||
name, the username behind an app idTag, or the raw tag — in that order."""
|
||||
@@ -151,9 +178,15 @@ class ChargePoint(OcppChargePoint):
|
||||
_tx_counter["n"] += 1
|
||||
tx = _tx_counter["n"]
|
||||
who = resolve_who(id_tag)
|
||||
# audit: HOW was this session authorized? kind of the allowlist
|
||||
# entry -> "card" (physical tap) or "app" (in-app button press)
|
||||
method = CONFIG["authorized"].get(id_tag, {}).get("kind", "unknown")
|
||||
# audit: HOW was this session authorized? allowlist kind ->
|
||||
# "card" (physical tap); a user's app idTag -> "app" (in-app button)
|
||||
entry = CONFIG["authorized"].get(id_tag)
|
||||
if entry is not None:
|
||||
method = entry.get("kind", "unknown")
|
||||
elif user_for_tag(id_tag) or id_tag == "app-remote":
|
||||
method = "app"
|
||||
else:
|
||||
method = "unknown"
|
||||
ACTIVE_TX[tx] = {
|
||||
"cp": self.id, "connector": connector_id, "id_tag": id_tag,
|
||||
"who": who, "method": method,
|
||||
|
||||
+5
-4
@@ -159,11 +159,9 @@ async def charger_start(connector: int = 1, cp: Optional[str] = None,
|
||||
user: dict = Depends(current_user)):
|
||||
target = _cp(cp)
|
||||
need(user, f"charger:{target.id}:{connector}")
|
||||
# remote starts run under the caller's own idTag so sessions are attributable
|
||||
# remote starts run under the caller's own idTag so sessions are
|
||||
# attributable; decide() validates it directly against the user record
|
||||
id_tag = user.get("id_tag") or f"app-{user['name']}"
|
||||
if id_tag not in CONFIG["authorized"]:
|
||||
CONFIG["authorized"][id_tag] = {"name": f"app token of {user['name']}", "kind": "app"}
|
||||
save()
|
||||
status = await _ocpp(csms.remote_start(target.id, id_tag, connector))
|
||||
return {"remote_start": status, "id_tag": id_tag}
|
||||
|
||||
@@ -272,6 +270,9 @@ async def allowlist_put(id_tag: str, entry: AllowlistEntry,
|
||||
need(user, "admin")
|
||||
if entry.user is not None and entry.user not in CONFIG["users"]:
|
||||
raise HTTPException(400, f"cannot link card to unknown user {entry.user!r}")
|
||||
if csms.user_for_tag(id_tag) is not None:
|
||||
raise HTTPException(400, f"{id_tag!r} is a user's app token — it authorizes "
|
||||
"through the user's own permissions, not the allowlist")
|
||||
CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True)
|
||||
save()
|
||||
log.info("allowlist: added/updated %r (%s)", id_tag, entry.name)
|
||||
|
||||
Reference in New Issue
Block a user