From 70c2fe1210220e6fe551f48b2d853fd20536872c Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Sat, 11 Jul 2026 20:03:36 +0200 Subject: [PATCH] feat(backend): link cards to users; charger-qualified gun restrictions; config-driven gun labels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Allowlist entries take "user": — sessions started with that card attribute to the person, and the owner sees their card's history even without gun-wide permissions (ownership looked up live) - "guns": ["eu092025:2"] (fnmatch) replaces the charger-blind "connectors": [2] restriction — safe with multiple chargers - New "chargers" config section provides per-charger/per-gun display names; the panel no longer hardcodes the Anfu gun labels - Panel admin tab: owner dropdown + guns field on card entries - Smoke test: 42 checks, incl. retroactive history visibility after linking a card and rejection of links to unknown users --- backend/config.example.json | 19 +++++++++++++++---- backend/config.py | 4 +++- backend/csms.py | 34 +++++++++++++++++++++------------- backend/routes.py | 22 +++++++++++++++------- backend/static/index.html | 31 +++++++++++++++++++------------ wiki/concepts/authorization.md | 7 ++++++- wiki/entities/backend.md | 3 ++- wiki/log.md | 4 ++++ 8 files changed, 85 insertions(+), 39 deletions(-) diff --git a/backend/config.example.json b/backend/config.example.json index 6ea3244..f8687a6 100644 --- a/backend/config.example.json +++ b/backend/config.example.json @@ -19,14 +19,25 @@ } }, "authorized": { - "1000000000000000": { "name": "Example RFID card, works on both guns", "kind": "card" }, - "1000000000000001": { - "name": "Example RFID card restricted to gun 2", + "1000000000000000": { + "name": "Card linked to a user, works everywhere", "kind": "card", - "connectors": [2] + "user": "admin-user" + }, + "1000000000000001": { + "name": "Card restricted to gun 2 of one charger", + "kind": "card", + "user": "gun1-only-user", + "guns": ["eu092025:2"] }, "app-remote": { "name": "Web/app remote start token", "kind": "app" } }, + "chargers": { + "eu092025": { + "label": "Anfu 60kW", + "guns": { "1": "Gun 1 · EU (CCS)", "2": "Gun 2 · GB/T" } + } + }, "relays": { "example-relay": { "id": "", diff --git a/backend/config.py b/backend/config.py index 6822ef9..d3e5c04 100644 --- a/backend/config.py +++ b/backend/config.py @@ -17,8 +17,10 @@ CONFIG_PATH = HERE / "config.json" DEFAULTS = { "learn_mode": True, "users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...} - "authorized": {}, # idTag -> {"name", "kind": "card|app|car", optional "connectors": [1]} + "authorized": {}, # idTag -> {"name", "kind": "card|app|car", + # optional "user": owner, "guns": ["eu092025:2"]} "relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"} + "chargers": {}, # cp_id -> {"label", "guns": {"1": "display name", ...}} (UI only) } diff --git a/backend/csms.py b/backend/csms.py index 4ebab78..5705152 100644 --- a/backend/csms.py +++ b/backend/csms.py @@ -10,6 +10,7 @@ import asyncio import json import logging from collections import deque +from fnmatch import fnmatch from typing import Optional from fastapi import WebSocket, WebSocketDisconnect @@ -46,21 +47,24 @@ TRIGGERABLE = { } -def decide(id_tag: str, context: str, connector: Optional[int] = None) -> AuthorizationStatus: +def decide(id_tag: str, context: str, connector: Optional[int] = None, + cp: Optional[str] = None) -> AuthorizationStatus: """The one gate every auth method flows through: is this idTag allowed? - An allowlist entry may carry "connectors": [1] to restrict a card to - specific guns. Only StartTransaction knows the connector, so the per-gun - check fires there; a plain Authorize (card tap) still accepts a known card - — which matches this charger, since AuthorizeRemoteTxRequests=false means + An allowlist entry may carry "guns": ["eu092025:2"] to restrict a card to + specific guns of specific chargers (fnmatch patterns, so "eu092025:*" + works). Only StartTransaction knows the connector, so the per-gun check + fires there; a plain Authorize (card tap) still accepts a known card — + which matches this charger, since AuthorizeRemoteTxRequests=false means StartTransaction is the decisive call anyway. """ entry = CONFIG["authorized"].get(id_tag) known = entry is not None - if known and connector is not None and entry.get("connectors") \ - and connector not in entry["connectors"]: - log.warning("[NO] REJECTED idTag=%r (%s) not allowed on connector %s (allowed: %s)", - id_tag, entry.get("name", "?"), connector, entry["connectors"]) + 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"]): + log.warning("[NO] REJECTED idTag=%r (%s) not allowed on %s (allowed: %s)", + id_tag, entry.get("name", "?"), gun, entry["guns"]) status = AuthorizationStatus.invalid elif known: name = entry.get("name", "?") @@ -82,10 +86,14 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None) -> Author def resolve_who(id_tag: str) -> str: - """Human label for a session: allowlist entry name, username, or the raw tag.""" + """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.""" entry = CONFIG["authorized"].get(id_tag) - if entry and entry.get("name"): - return entry["name"] + if entry: + if entry.get("user"): + return entry["user"] + if entry.get("name"): + return entry["name"] for username, user in CONFIG["users"].items(): if user.get("id_tag") == id_tag: return username @@ -125,7 +133,7 @@ class ChargePoint(OcppChargePoint): @on(Action.start_transaction) async def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs): status = decide(id_tag, f"StartTransaction (connector {connector_id})", - connector=connector_id) + connector=connector_id, cp=self.id) if status == AuthorizationStatus.accepted: _tx_counter["n"] += 1 tx = _tx_counter["n"] diff --git a/backend/routes.py b/backend/routes.py index 7b9e89b..73a2220 100644 --- a/backend/routes.py +++ b/backend/routes.py @@ -119,6 +119,7 @@ async def api_status(user: dict = Depends(current_user)): "active_transactions": csms.ACTIVE_TX, "recent_auth_events": list(csms.AUTH_EVENTS), "relays": _visible_relays(user), + "chargers": CONFIG["chargers"], # display labels for the panel } @@ -197,11 +198,15 @@ async def charger_probe(cp: Optional[str] = None, user: dict = Depends(current_u # ---- session history: who charged when and how many kWh ---- def _may_see_session(user: dict, s: dict) -> bool: - """Own sessions, sessions on guns you control, or everything for admin.""" - return ( - s["id_tag"] == user.get("id_tag") - or users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}") - ) + """Own sessions (own app starts or own cards), sessions on guns you + control, or everything for admin. Card ownership is looked up live, so + linking a card to a user retroactively shows them its history.""" + if users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}"): + return True + if s["id_tag"] == user.get("id_tag"): + return True + entry = CONFIG["authorized"].get(s["id_tag"]) + return bool(entry and entry.get("user") == user["name"]) @router.get("/sessions") @@ -225,8 +230,9 @@ async def session_samples(tx: int, user: dict = Depends(current_user)): # ---- allowlist management (admin) ---- class AllowlistEntry(BaseModel): name: str - kind: str = "card" # card | app | car - connectors: Optional[list[int]] = None # e.g. [2] = this card only works on gun 2 + kind: str = "card" # card | app | car + user: Optional[str] = None # owning username -> sessions attribute to them + guns: Optional[list[str]] = None # e.g. ["eu092025:2"]; fnmatch, empty = all guns @router.get("/allowlist") @@ -243,6 +249,8 @@ async def allowlist_get(user: dict = Depends(current_user)): async def allowlist_put(id_tag: str, entry: AllowlistEntry, user: dict = Depends(current_user)): 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}") CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True) save() log.info("allowlist: added/updated %r (%s)", id_tag, entry.name) diff --git a/backend/static/index.html b/backend/static/index.html index 485c710..aa43828 100644 --- a/backend/static/index.html +++ b/backend/static/index.html @@ -143,22 +143,23 @@
-

Allowlist

+

Cards & tags

- +
idTagNameGuns
idTagNameUserGuns
- +
- - + +
+
@@ -308,8 +309,10 @@ function renderGuns() { .sort((a, b) => a.conn - b.conn); if (!conns.length) html += `
${esc(cp)} connected — no gun status yet
`; + const cpCfg = (status.chargers || {})[cp] || {}; for (const { conn, st } of conns) { - const gunName = conn === 1 ? "Gun 1 · EU (CCS)" : conn === 2 ? "Gun 2 · GB/T" : `Gun ${conn}`; + let gunName = (cpCfg.guns || {})[conn] || `Gun ${conn}`; + if (cps.length > 1) gunName = `${cpCfg.label || cp} · ${gunName}`; const active = txByGun[`${cp}/${conn}`]; const may = scopeOk(`charger:${cp}:${conn}`); const canStart = may && !active && (st === "Preparing" || st === "Available"); @@ -408,22 +411,24 @@ async function loadSessions() { // ---- admin tab ---- async function loadAdmin() { try { - const al = await api("/allowlist"); + const [al, users] = await Promise.all([api("/allowlist"), api("/users")]); $("mode-label").textContent = al.learn_mode ? "Learn mode" : "Enforcing allowlist"; $("mode-btn").textContent = al.learn_mode ? "Enforce" : "Back to learn"; $("mode-btn").dataset.learn = al.learn_mode; $("allowlist").innerHTML = Object.entries(al.authorized).map(([tag, e]) => ` ${esc(tag)}${esc(e.name)} - ${e.connectors ? e.connectors.join(",") : "all"} + ${e.user ? esc(e.user) : '—'} + ${e.guns ? esc(e.guns.join(", ")) : "all"} `).join(""); + $("a-user").innerHTML = `` + + users.map(u => ``).join(""); const seen = Object.entries(al.seen || {}).filter(([tag]) => !(tag in al.authorized)); $("seen-tags").innerHTML = seen.length ? `
Seen but not enrolled:
` + seen.map(([tag, s]) => `
${esc(tag)} (×${s.count})
`).join("") : ""; - const users = await api("/users"); $("users").innerHTML = users.map(u => ` ${esc(u.name)}${esc(u.scopes.join(" "))} @@ -441,12 +446,14 @@ async function toggleMode() { async function addAllowlist(ev) { ev.preventDefault(); const body = { name: $("a-name").value.trim(), kind: $("a-kind").value }; - const conns = $("a-conn").value.trim(); - if (conns) body.connectors = conns.split(",").map(s => +s.trim()).filter(Boolean); + if ($("a-user").value) body.user = $("a-user").value; + const guns = $("a-guns").value.trim(); + if (guns) body.guns = guns.split(",").map(s => s.trim()).filter(Boolean); try { await api(`/allowlist/${encodeURIComponent($("a-tag").value.trim())}`, { method: "PUT", body: JSON.stringify(body) }); - $("a-tag").value = $("a-name").value = $("a-conn").value = ""; + $("a-tag").value = $("a-name").value = $("a-guns").value = ""; + $("a-user").value = ""; loadAdmin(); } catch (e) { toast(e.message); } return false; diff --git a/wiki/concepts/authorization.md b/wiki/concepts/authorization.md index 7fcd104..33916ff 100644 --- a/wiki/concepts/authorization.md +++ b/wiki/concepts/authorization.md @@ -17,7 +17,12 @@ First card tapped on the real charger: idTag `1000000000000393` → Authorize Flow for each new card: tap once in learn mode → harvest its idTag from `seen_tags.json` / `GET /api/allowlist` → add to `authorized` with a name (`kind: "card"`). -Since 2026-07-11 a card can be **restricted per gun**: an optional `"connectors": [2]` on its allowlist entry makes `decide()` reject it on any other connector. The check fires at `StartTransaction` (the only message that carries the connector); the preceding `Authorize` (tap) still says Accepted — harmless on this charger, because `AuthorizeRemoteTxRequests=false` makes `StartTransaction` the decisive call anyway (see the probe facts below). ✅ verified with a fake charge point: gun-2-only card → `Invalid`/tx 0 on gun 1, Accepted on gun 2. +Since 2026-07-11 a card can be **linked to a user and restricted per gun**: + +- `"user": "julian"` on the allowlist entry ties the card to a user account — sessions started with it attribute to that person in the history, and the owner sees their card's sessions even without gun-wide permissions (ownership is looked up live, so linking is retroactive for history visibility). +- `"guns": ["eu092025:2"]` restricts the card to specific guns, **charger-qualified** (fnmatch patterns, so `"eu092025:*"` = all guns of one charger) — multi-charger-safe by construction. The check fires at `StartTransaction` (the only message that carries the connector); the preceding `Authorize` (tap) still says Accepted — harmless on this charger, because `AuthorizeRemoteTxRequests=false` makes `StartTransaction` the decisive call anyway (see the probe facts below). ✅ verified with a fake charge point: gun-2-only card → `Invalid`/tx 0 on gun 1, Accepted on gun 2. + +Both are editable from the panel's Admin tab (owner dropdown + guns field). ## 2. By vehicle / chassis — ❌ CLOSED: not supported (2026-07-09) diff --git a/wiki/entities/backend.md b/wiki/entities/backend.md index 9dcec93..4d017da 100644 --- a/wiki/entities/backend.md +++ b/wiki/entities/backend.md @@ -40,7 +40,8 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root) ## Design facts -- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with optional per-gun card restriction (`"connectors": [2]`) — the `_WSAdapter` WebSocket bridge, learn mode, the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]). +- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with card→user linking (`"user"`) and charger-qualified gun restriction (`"guns": ["eu092025:2"]`, fnmatch) — the `_WSAdapter` WebSocket bridge, learn mode, the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]). +- **Multi-charger by design**: a second charger only needs the same URL with a unique ChargerID; scopes, sessions, card restrictions, and the panel are all keyed by charger id. Gun display names come from the `"chargers"` config section (not hardcoded). - **Multi-user auth** (2026-07-11, replaced the interim `api_token`): username/password users with permission scopes — `charger::`, `relay:`, `admin` — full model in [[authorization]]. Stdlib crypto only (PBKDF2 + HMAC sessions). Zero users = open API (startup warns); bootstrap via `python -m backend.users add --scopes admin`. - Remote starts run under the calling user's own idTag (`app-`, auto-enrolled) → per-person session attribution. - **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `sessions.db` with a resolved "who" (allowlist name or username); `StopTransaction` closes it and computes Wh from the meter diff; `MeterValues` rows land in a `samples` table (energy/power/SoC, kW→W normalized). Transaction ids continue from `MAX(tx)` across restarts, and stop-by-tx falls back to the store so sessions running through a backend restart stay stoppable. diff --git a/wiki/log.md b/wiki/log.md index 91d461e..23b5932 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -71,3 +71,7 @@ Owner requirement: per-user permissions (gun 1 vs gun 2 of eu092025, per-relay o ## [2026-07-11] meta | Consumption tracking (SQLite) + the PWA control panel Owner requirement: button-push start when a gun is ready (and permitted) + "who charged when and how many kWh". Built store.py (sessions.db: sessions with resolved who/started/ended/Wh + per-minute samples energy/power/SoC; tx ids survive restarts; stop falls back to store after restart), /api/sessions with visibility rules (own + in-scope guns; admin all), and the phase-3 web panel in backend/static/ (vanilla JS PWA at /: login, gun cards with scope- and readiness-gated Start/Stop, relay toggles, history tab, admin tab with allowlist/users/mode). Fixed a sqlite connection leak (with-connect commits but never closes). Smoke test 28 -> 37 checks, all passing. Updated [[backend]], [[architecture-plan]] (phases 1-3 all done), [[overview]], [[index]]. + +## [2026-07-11] meta | Cards linked to users; multi-charger gaps closed + +Owner requirements: cards must belong to a person (not float around as "RFID card A (tapped first...)"), and adding a second charger must be clean. Allowlist entries now take "user" (sessions attribute to the person; owner sees their card's history) and charger-qualified "guns": ["eu092025:2"] (fnmatch; replaces the charger-blind "connectors" field). Gun display names moved from hardcoded panel JS to a "chargers" config section served via /api/status. Adding a charger = point it at the same URL with a unique ChargerID + grant charger:: scopes. Panel admin tab: owner dropdown + guns field. Smoke test 37 -> 42 checks. Updated [[authorization]], [[backend]].