feat(backend): permission keys replace the 13 perm_* columns
Platform v2 step 1.5 (APPS_PLATFORM D-7, D-17, §3, §6.1).
- user_permissions(user_id, key); revision 0005 copies existing v1 flags into
keys (frozen mapping) and drops the perm_* columns; can_cancel_orders gone
- core/access: check() = module effective + key held (superadmin implicit,
override keys wired for 1.9); holds()/can(); markers require/require_any/
public/require_device; role templates from manifests; queries.holders_filter
replaces User.perm_x == True; legacy.py projects/accepts the v1 booleans
for the current manager/waiter UIs only (§3.3, temporary)
- routers.deps: require_manager/... are now aliases of require("<key>");
history endpoints use history.view; superadmin-only = core.system.admin;
get_current_user carries the "signed_in" marker
- every inline perm_* read in routers/services converted to holds()
- staff API: permission catalogue by module with role templates, get/set a
user's keys, reset to role template; legacy flag toggles still work; a
non-superadmin can only grant keys they hold (access.cannot_grant)
- setup wizard creates the first account as owner (v1: store_manager, who
couldn't change settings); demo/seed manager is owner
- roles.py keeps only the role list and labels
- guards: every route has an access marker (19 open routes marked public()
on purpose; /waiters/roles now needs sign-in), no perm_* attribute reads
- tests: check matrix, templates, projection, staff permission API, grant
guard, 0005 data copy; pack rule CS-14
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
"""Access control (APPS_PLATFORM §3, D-7, D-8, D-17).
|
||||
|
||||
allowed(key) = module_of(key) is effective (licence ∪ free) ∩ enabled
|
||||
AND (no device OR key in the device app's scope) step 1.8
|
||||
AND (user is superadmin OR user holds key user_permissions
|
||||
OR a valid manager-override token for key) step 1.9
|
||||
|
||||
Use it through the route markers in core/access/deps.py:
|
||||
require("ordering.orders.cancel") one key (returns the user)
|
||||
require_any("a.b", "c.d") any of several keys
|
||||
signed_in any logged-in user (routers.deps.get_current_user)
|
||||
public() deliberately open (health, login, pairing...)
|
||||
require_device("kds") device-only endpoints (step 1.8)
|
||||
and inside code with can(user, key) for conditional behaviour (e.g. managers see all orders).
|
||||
|
||||
Every route must carry one of these markers somewhere in its dependencies; the guard
|
||||
tests/guards/test_route_access.py fails otherwise.
|
||||
|
||||
Files: templates.py (role templates from manifests), check.py (the decision),
|
||||
deps.py (route markers), legacy.py (temporary v1 perm_* projection for the current
|
||||
frontends, §3.3), queries.py (find users holding a key).
|
||||
"""
|
||||
@@ -0,0 +1,55 @@
|
||||
"""The one access decision (APPS_PLATFORM §3.1)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional
|
||||
|
||||
from core.errors import XeniaError
|
||||
from core.modules.registry import all_permissions
|
||||
|
||||
|
||||
@dataclass
|
||||
class AccessContext:
|
||||
user: Any = None # User row, or the support ghost (step 1.10); None for device-only calls
|
||||
session: Any = None # step 1.6
|
||||
device: Any = None # step 1.8
|
||||
override_keys: frozenset = frozenset() # step 1.9
|
||||
|
||||
|
||||
def module_of(key: str) -> str:
|
||||
try:
|
||||
return all_permissions()[key][1]
|
||||
except KeyError:
|
||||
raise ValueError(f"unknown permission key {key!r}: declare it in a module manifest") from None
|
||||
|
||||
|
||||
def holds(user, key: str) -> bool:
|
||||
"""Does the user have the key (ignoring modules)? Superadmin has every key (D-7)."""
|
||||
if user is None:
|
||||
return False
|
||||
if getattr(user, "role", None) == "superadmin":
|
||||
return True
|
||||
return key in user_keys(user)
|
||||
|
||||
|
||||
def user_keys(user) -> frozenset[str]:
|
||||
rows = getattr(user, "permission_rows", None) or []
|
||||
return frozenset(r.key for r in rows)
|
||||
|
||||
|
||||
def can(user, key: str, db=None) -> bool:
|
||||
"""Full check without raising: module effective AND user holds the key."""
|
||||
from core.modules.state import is_effective
|
||||
return is_effective(module_of(key), db) and holds(user, key)
|
||||
|
||||
|
||||
def check(ctx: AccessContext, key: str, db=None) -> None:
|
||||
"""Raise the right XeniaError unless `key` is allowed for this request."""
|
||||
from core.modules.state import blocked_error, is_effective
|
||||
module = module_of(key)
|
||||
if not is_effective(module, db):
|
||||
raise blocked_error(module, db)
|
||||
# device scope: step 1.8
|
||||
if holds(ctx.user, key) or key in ctx.override_keys:
|
||||
return
|
||||
raise XeniaError("access.denied", key=key)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Route access markers (APPS_PLATFORM §3.1, D-17).
|
||||
|
||||
Each marker is a FastAPI dependency with an `__xenia_access__` attribute. The route
|
||||
guard (tests/guards/test_route_access.py) walks every route's dependency tree and fails
|
||||
any route without a marker, so "forgot to protect" can't ship.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.access.check import AccessContext, check
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
|
||||
|
||||
def _mark(fn, *marker):
|
||||
fn.__xenia_access__ = marker
|
||||
return fn
|
||||
|
||||
|
||||
def require(key: str):
|
||||
"""The user must hold `key`, and its module must be effective. Returns the user."""
|
||||
# Keys are not validated here (routers are imported while the registry loads);
|
||||
# tests/guards/test_route_access.py checks every marker's key exists.
|
||||
from routers.deps import get_current_user
|
||||
|
||||
def _dep(user=Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
check(AccessContext(user=user), key, db)
|
||||
return user
|
||||
|
||||
_dep.__name__ = f"require_{key.replace('.', '_')}"
|
||||
return _mark(_dep, "require", key)
|
||||
|
||||
|
||||
def require_any(*keys: str):
|
||||
"""The user must hold at least one of `keys` (in an effective module). Returns the user."""
|
||||
from routers.deps import get_current_user
|
||||
|
||||
def _dep(user=Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
last = None
|
||||
for k in keys:
|
||||
try:
|
||||
check(AccessContext(user=user), k, db)
|
||||
return user
|
||||
except XeniaError as e:
|
||||
last = e
|
||||
raise last
|
||||
|
||||
_dep.__name__ = "require_any_" + "_".join(k.replace(".", "_") for k in keys)
|
||||
return _mark(_dep, "require_any", *keys)
|
||||
|
||||
|
||||
def public():
|
||||
"""Deliberately open endpoint (health, identity, login, pairing request...)."""
|
||||
def _dep():
|
||||
return None
|
||||
return _mark(_dep, "public")
|
||||
|
||||
|
||||
def require_device(app_key: str):
|
||||
"""Device-only endpoint for paired devices running `app_key` (implemented in step 1.8)."""
|
||||
def _dep():
|
||||
raise XeniaError("device.not_paired")
|
||||
return _mark(_dep, "require_device", app_key)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""TEMPORARY v1 projection (APPS_PLATFORM §3.3). Delete with the last frontend that reads it.
|
||||
|
||||
The current manager dashboard and waiter app still read and write 13 boolean fields
|
||||
(perm_access_dashboard ...). This file is the ONLY place that knows them:
|
||||
- project(user): booleans computed from the user's keys, for UserOut
|
||||
- apply_booleans(user, {field: bool}): a frontend toggled a boolean -> grant/revoke keys
|
||||
Not for deployed v1 sites (D-21): it only keeps our own unconverted screens usable on
|
||||
the branch. Plan: removed when the manager (phase 2/6) and waiter app (phase 4) use keys.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from core.access.check import holds, user_keys
|
||||
|
||||
# boolean -> keys it stands for. Projection: True if the user holds the FIRST key.
|
||||
LEGACY_MAP: dict[str, tuple[str, ...]] = {
|
||||
"perm_access_dashboard": ("core.dashboard.access",),
|
||||
"perm_access_waiter_app": ("waiter_app.access",),
|
||||
"perm_access_kds": ("kds.access", "kds.bump"),
|
||||
"perm_cancel_orders": ("ordering.orders.cancel",),
|
||||
"perm_apply_discounts": ("pricing.discounts.apply",),
|
||||
"perm_modify_prices": ("ordering.prices.modify",),
|
||||
"perm_open_orders": ("ordering.orders.open",),
|
||||
"perm_close_orders": ("ordering.orders.close",),
|
||||
"perm_view_reports": ("reports.view", "history.view"),
|
||||
"perm_manage_staff": ("core.staff.manage",),
|
||||
"perm_manage_tables": ("catalog.tables.manage",),
|
||||
"perm_manage_menu": ("catalog.menu.manage",),
|
||||
"perm_manage_settings": ("core.settings.manage",),
|
||||
}
|
||||
LEGACY_FIELDS = tuple(LEGACY_MAP)
|
||||
|
||||
|
||||
def project(user) -> dict[str, bool]:
|
||||
return {field: holds(user, keys[0]) for field, keys in LEGACY_MAP.items()}
|
||||
|
||||
|
||||
def apply_booleans(user, values: dict) -> None:
|
||||
"""Grant/revoke the keys behind each boolean present in `values` (None = untouched)."""
|
||||
from core.access.templates import set_user_keys
|
||||
keys = set(user_keys(user))
|
||||
for field, val in values.items():
|
||||
if field not in LEGACY_MAP or val is None:
|
||||
continue
|
||||
if val:
|
||||
keys |= set(LEGACY_MAP[field])
|
||||
else:
|
||||
keys -= set(LEGACY_MAP[field])
|
||||
set_user_keys(user, keys)
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Find users by permission key (replaces v1 filters like User.perm_access_dashboard == True)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
|
||||
|
||||
def holders_filter(key: str):
|
||||
"""SQLAlchemy filter: superadmins, or users with a grant for `key`."""
|
||||
from models.user import User
|
||||
from models.user_permission import UserPermission
|
||||
return or_(User.role == "superadmin",
|
||||
User.id.in_(select(UserPermission.user_id).where(UserPermission.key == key)))
|
||||
|
||||
|
||||
def users_with_key(db, key: str, active_only: bool = True):
|
||||
"""Query of users holding `key` (superadmins included)."""
|
||||
from models.user import User
|
||||
q = db.query(User).filter(holders_filter(key))
|
||||
if active_only:
|
||||
q = q.filter(User.is_active == True) # noqa: E712
|
||||
return q
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Role templates (D-7): the default keys of each role, read from the module manifests.
|
||||
|
||||
A role is a label plus a template. The template is copied into user_permissions when a
|
||||
user is created and on "reset to role defaults"; after that the user's keys are theirs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from core.modules.registry import all_permissions
|
||||
|
||||
|
||||
def role_template(role: str) -> set[str]:
|
||||
"""Keys a new user with this role gets. Superadmin: none stored (implicit-all)."""
|
||||
if role == "superadmin":
|
||||
return set()
|
||||
return {k for k, (p, _m) in all_permissions().items() if role in p.roles}
|
||||
|
||||
|
||||
def set_user_keys(user, keys) -> None:
|
||||
"""Replace a user's grants with `keys` (validated against the catalogue)."""
|
||||
from models.user_permission import UserPermission
|
||||
catalogue = all_permissions()
|
||||
unknown = set(keys) - set(catalogue)
|
||||
if unknown:
|
||||
from core.errors import XeniaError
|
||||
raise XeniaError("access.unknown_key", key=sorted(unknown)[0])
|
||||
wanted = set(keys)
|
||||
user.permission_rows = [r for r in user.permission_rows if r.key in wanted] + \
|
||||
[UserPermission(key=k) for k in sorted(wanted - {r.key for r in user.permission_rows})]
|
||||
|
||||
|
||||
def apply_role_template(user) -> None:
|
||||
set_user_keys(user, role_template(user.role))
|
||||
@@ -40,6 +40,8 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
# access / licensing / modules (filled in by steps 1.3-1.9)
|
||||
"access.denied": (403, "You don't have permission to do this ({key})."),
|
||||
"access.override_possible": (403, "A manager can approve this ({key})."),
|
||||
"access.unknown_key": (422, "There is no permission {key}."),
|
||||
"access.cannot_grant": (403, "You can only give permissions you have yourself ({key})."),
|
||||
"module.disabled": (403, "The {module} module is turned off."),
|
||||
"module.not_licensed": (402, "This site's license doesn't include {module}."),
|
||||
"module.unknown": (404, "There is no module {module}."),
|
||||
|
||||
@@ -16,6 +16,8 @@ Agent notes:
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from core.access.deps import public
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
@@ -71,7 +73,7 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/bootstrap")
|
||||
@router.get("/bootstrap", dependencies=[Depends(public())])
|
||||
def bootstrap(
|
||||
db: Session = Depends(get_db),
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer),
|
||||
|
||||
Reference in New Issue
Block a user