Files
xenia-pos-local/local_backend/core/access/override.py
T
bonaminandClaude Opus 5.5 650fee7873 feat(backend): manager override with one-time PIN approval for cancel, price change, over-limit discount
Platform v2 step 1.9 (APPS_PLATFORM D-10).
- Perm(..., overridable=True). check() answers access.override_possible (not
  access.denied) for such keys, and consumes an X-Xenia-Override token for them.
- POST /api/access/override {key, username, pin}: the approver must hold the key
  (module effective); returns a token valid 60 s, once, for that key and the
  requesting session only (sha256 stored). Wrong PINs throttled per session.
  GET /api/access/overrides: audit list (core.staff.manage).
- access_overrides table (revision 0008): who asked, session, who approved, device,
  key, created/expires/used, target. The revision also grants core.devices.manage and
  the new pricing.discounts.over_limit to existing owners/store managers.
- Overridable: ordering.orders.cancel (the three cancel endpoints; the order audit log
  notes "override #n approved by user m"), ordering.prices.modify (price adjust), and
  new pricing.discounts.over_limit (waiter discounts beyond their limits; the reason
  goes in params). The venue switch discounts.enabled is never overridable.
- /orders/cancel-permissions adds override_possible; permission catalogues expose
  `overridable`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:57:37 +02:00

138 lines
6.0 KiB
Python

"""Manager override (APPS_PLATFORM D-10, plan step 1.9).
Flow
1. A user calls an action they lack an *overridable* key for (Perm(..., overridable=True))
-> 403 `access.override_possible` {key}.
2. The client asks for a manager's username + PIN and calls
POST /api/access/override {key, username, pin} with the user's own session.
grant() checks the PIN and that the approver may use the key (module effective + holds
it) and returns a token valid for TOKEN_TTL_S, once, for that key and that session.
3. The client retries the action with header X-Xenia-Override: <token>. check() (for
require() routes) or require_override() (for checks inside an endpoint) consumes it.
Agent notes:
- consume() commits at once, so a token can't be used twice even if the action then fails.
A token for another key or another session is refused WITHOUT being burned.
- Only the sha256 of the token is stored. Every approval is a row in access_overrides
(who asked, who approved, key, when used, target); failures are logged, not stored.
- PIN guessing is throttled per requesting session (MAX_FAILURES in FAILURE_WINDOW_S).
- Endpoints whose own rule is more than "holds key" (e.g. cancelling also needs the
venue setting orders.waiter_cancellations_allowed) call require_override() directly
when their rule says no; pass `target` ("order:12") so the audit row says what it was for.
"""
from __future__ import annotations
import logging
import secrets
import threading
import time
from collections import deque
from datetime import timedelta
from core.errors import XeniaError
from core.timeutil import utcnow
logger = logging.getLogger("xenia.access")
HEADER = "X-Xenia-Override"
TOKEN_TTL_S = 60
MAX_FAILURES = 5
FAILURE_WINDOW_S = 300
_lock = threading.Lock()
_failures: dict[str, deque] = {}
def reset_throttle() -> None:
with _lock:
_failures.clear()
def is_overridable(key: str) -> bool:
from core.modules.registry import all_permissions
entry = all_permissions().get(key)
return bool(entry and entry[0].overridable)
def _throttled(who: str) -> bool:
now = time.monotonic()
with _lock:
q = _failures.setdefault(who, deque())
while q and now - q[0] > FAILURE_WINDOW_S:
q.popleft()
return len(q) >= MAX_FAILURES
def _fail(who: str) -> None:
with _lock:
_failures.setdefault(who, deque()).append(time.monotonic())
def grant(db, *, key: str, username: str, pin: str, requester, sid: str | None, device=None):
"""Check the approver and create a one-time token. Returns (token, AccessOverride row)."""
import bcrypt
from core.access.check import can
from core.access.context import hash_token
from core.modules.registry import all_permissions
from models.access_override import AccessOverride
from models.user import User
if key not in all_permissions():
raise XeniaError("access.unknown_key", key=key)
if not is_overridable(key):
raise XeniaError("access.not_overridable", key=key)
who = sid or f"user:{getattr(requester, 'id', None)}"
if _throttled(who):
raise XeniaError("access.override_rate_limited")
approver = db.query(User).filter(User.username == username, User.is_active == True).first() # noqa: E712
if approver is None or not pin or not approver.pin_hash or \
not bcrypt.checkpw(pin.encode(), approver.pin_hash.encode()):
_fail(who)
logger.warning("override.denied reason=credentials key=%s requester=%s approver=%s",
key, getattr(requester, "id", None), username)
raise XeniaError("auth.invalid_credentials")
if not can(approver, key, db):
logger.warning("override.denied reason=approver_lacks_key key=%s requester=%s approver=%s",
key, getattr(requester, "id", None), approver.id)
raise XeniaError("access.approver_lacks_key", key=key)
token = secrets.token_urlsafe(24)
now = utcnow()
row = AccessOverride(key=key, token_hash=hash_token(token), requested_by=getattr(requester, "id", None) or None,
requested_session=sid, approved_by=approver.id,
device_id=getattr(device, "id", None), created_at=now,
expires_at=now + timedelta(seconds=TOKEN_TTL_S))
db.add(row)
db.commit()
logger.info("override.granted id=%s key=%s requester=%s approver=%s", row.id, key, row.requested_by, approver.id)
return token, row
def consume(db, token: str, key: str, sid: str | None, target: str | None = None):
"""Use a token for `key` in session `sid`. Returns the AccessOverride row (approved_by
says who approved). Raises access.override_invalid."""
from core.access.context import hash_token
from models.access_override import AccessOverride
row = db.query(AccessOverride).filter(AccessOverride.token_hash == hash_token(token)).first()
now = utcnow()
reason = ("unknown" if row is None else "used" if row.used_at is not None else
"expired" if row.expires_at < now else "wrong_key" if row.key != key else
"wrong_session" if row.requested_session != sid else None)
if reason:
logger.warning("override.refused reason=%s key=%s id=%s", reason, key, getattr(row, "id", None))
raise XeniaError("access.override_invalid")
row.used_at = now
row.target = (target or "")[:200] or None
db.commit()
logger.info("override.used id=%s key=%s target=%s approver=%s", row.id, key, row.target, row.approved_by)
return row
def require_override(request, db, key: str, target: str | None = None, **params):
"""Inside an endpoint whose own rule said no: accept a valid override token for `key`,
otherwise raise access.override_possible (params go along, e.g. reason=...)."""
token = request.headers.get(HEADER)
if not token:
raise XeniaError("access.override_possible", key=key, **params)
return consume(db, token, key, getattr(request.state, "xenia_sid", None),
target or f"{request.method} {request.url.path}")