diff --git a/backend/config.py b/backend/config.py index e672251..3acb6e6 100644 --- a/backend/config.py +++ b/backend/config.py @@ -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 " + # 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 diff --git a/backend/csms.py b/backend/csms.py index aec4008..0eb07dd 100644 --- a/backend/csms.py +++ b/backend/csms.py @@ -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..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:: 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, diff --git a/backend/routes.py b/backend/routes.py index 3cec6cf..95863c5 100644 --- a/backend/routes.py +++ b/backend/routes.py @@ -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) diff --git a/wiki/concepts/authorization.md b/wiki/concepts/authorization.md index 6918dad..ee98cd7 100644 --- a/wiki/concepts/authorization.md +++ b/wiki/concepts/authorization.md @@ -56,7 +56,7 @@ A mobile-friendly web control panel (no app store): The [[backend]] now has real multi-user authorization on top of the three methods above, because not every household member may control everything. Requirement (owner, 2026-07-11): some users control gun 1 only, some gun 2, some only certain [[wifi-relays|relays]]. -- **Users** live in the `settings` table of `backend.db`: username + PBKDF2 password hash + scope list + a personal `id_tag` (`app-`) used for their remote starts, so charging sessions are **attributable per person**. +- **Users** live in the `settings` table of `backend.db`: username + PBKDF2 password hash + scope list + a personal `id_tag` (`app-`) used for their remote starts, so charging sessions are **attributable per person**. The app idTag is NOT an allowlist entry (2026-07-12): `decide()` validates it against the user record directly and enforces the user's gun scopes; the Cards page shows only physical cards. - **Login**: `POST /api/login` (username/password) → 30-day HMAC-signed session, delivered as an HttpOnly cookie (for the PWA) and as a bearer token (for curl). Stateless — survives backend restarts; deleting a user kills their sessions. - **Scopes** (fnmatch wildcards work): diff --git a/wiki/entities/backend.md b/wiki/entities/backend.md index fe63822..97e2a12 100644 --- a/wiki/entities/backend.md +++ b/wiki/entities/backend.md @@ -43,7 +43,7 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root) - 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, and 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. +- Remote starts run under the calling user's own idTag (`app-`) → per-person session attribution. Since 2026-07-12 these tags are **validated directly against the user record** (never enrolled in the allowlist — the old synthetic "app token of " entries are auto-dropped on startup), and the charger-side gate enforces the user's `charger::` scopes too. - **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `backend.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. - Relay calls are blocking tinytuya I/O, run via `asyncio.to_thread` so the OCPP socket never stalls. - Venv at repo root (`../venv/`, Python 3.13); deps pinned in `backend/requirements.txt` (fastapi, uvicorn, websockets, ocpp, tinytuya) — the auth system added none. diff --git a/wiki/log.md b/wiki/log.md index 4cb99bc..4c6fa24 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -95,3 +95,7 @@ Owner (testing on the phone, second user created): (1) transactions are now PRIV ## [2026-07-12] meta | Live telemetry on the gun cards: SoC battery gauge + kW/V/A/delivered Owner wants meter values visible per gun in Control. Backend: latest Sample.Periodic per active tx kept in memory (ACTIVE_TX telemetry) and shipped with /api/status (Transaction.Begin snapshots skipped — taken before the car's BMS is read). Also this morning's finding filed: begin/end snapshots are legitimately 0 A/0 V, and a 42 s session never gets a periodic sample. Frontend: battery gauge with red->blue->green SoC gradient + big kW readout + Delivered/Voltage/Current rows on charging bays; earlier commit added voltage_v/current_a/context columns to samples. Smoke: 60 checks. Updated [[frontend]], [[backend]] implicitly via log. + +## [2026-07-12] meta | User app idTags no longer pollute the allowlist + +Owner: "why do we need this app token of X? We just need the user." Agreed — decide() now validates a user's app idTag directly against the user record (and enforces their charger:: scopes at the charger-side gate too); charger_start no longer auto-enrolls; enrolling a user's tag via the allowlist API returns 400; existing "app token of " entries are auto-dropped at startup. Open-mode bootstrap: "app-remote" authorizes with zero users configured. Session method audit: user tags -> "app". Smoke: 63 checks. Updated [[backend]], [[authorization]].