Files
xenia-pos-local/local_backend/core/errors.py
T
bonaminandClaude Opus 5.5 3a522e457d feat(backend): support access by offline challenge codes replaces the master account
Platform v2 step 1.10 (APPS_PLATFORM D-16, section 6.5).
- POST /api/auth/support/challenge (public): an 8-character challenge, stored 15 min
  (support_challenges, revision 0009; at most 5 open). POST /api/auth/support/verify
  {challenge, code}: code = base32(HMAC(SUPPORT_SECRET, site_id + challenge))[:10];
  single use, 5 wrong codes burn the challenge. Opens a 4 h support session
  (client=support, synthetic superadmin) with a hard end: sessions.expires_at.
- core/support_codes.py (stdlib only) is the derivation; tools/support_code.py
  (--init, --site-secret <SITE_ID>, <SITE_ID> <CHALLENGE>) uses it on the builder's
  machine with the master key in %USERPROFILE%/.xenia/support_master_key.txt.
- MASTER_USERNAME/MASTER_PASSWORD removed (config, login, docker-compose.yml,
  .env.example); SUPPORT_SECRET added; install.sh asks for it.
- e2e: backends get SUPPORT_SECRET from a test master key and log in with challenge
  codes (lib/support.mjs, license_e2e.py); install.mjs expects the new prompt.
- Pack rule CS-15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:52:16 +02:00

156 lines
8.3 KiB
Python

"""API errors as stable codes (APPS_PLATFORM D-12, §3.2).
Every error response has this shape:
{"error": {"code": "order.not_found", "params": {"order_id": 7}, "message": "Order 7 not found."},
"detail": "Order 7 not found."}
- code: stable identifier; frontends translate it (i18n key `errors.<code>`).
- params: values the translated text can use.
- message: English, for logs, curl and un-migrated screens.
- detail: kept for frontends written before v2 (they read `detail`).
New and converted code raises XeniaError:
raise XeniaError("order.not_found", order_id=order_id)
The status comes from the registry below; pass status= only to override it.
Plain HTTPException (still in most v1 routers; converted gradually, plan step 6.x)
is wrapped as code "http.<status>" with its original `detail` untouched.
Request validation errors become "validation.invalid" with the field errors in params.
Unhandled exceptions become "internal.error" (500) with the request id in params.
Agent notes:
- Add every new code to CODES with its HTTP status and English message (str.format
placeholders from params). tests/test_errors.py fails on a raised code that
isn't registered (via XeniaError's constructor).
- Codes are part of the API contract: never rename one; add a new one instead.
"""
from __future__ import annotations
import logging
from http import HTTPStatus
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
logger = logging.getLogger("xenia.errors")
# code -> (HTTP status, English message)
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.override_invalid": (403, "This approval isn't valid any more. Ask a manager again."),
"access.not_overridable": (422, "{key} can't be approved by a manager."),
"access.approver_lacks_key": (403, "That account can't approve this ({key})."),
"access.override_rate_limited": (429, "Too many wrong PINs. Wait a few minutes and try again."),
"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}."),
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
"license.limit_reached": (402, "License limit reached for {module} {limit} ({max})."),
"license.expired": (402, "The license has expired."),
"license.history_limited": (402, "This license shows only the last {days} days of history ({module})."),
# identity
"auth.invalid_credentials": (401, "Wrong username or password."),
"auth.session_ended": (401, "Your session has ended. Please log in again."),
"auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."),
"auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."),
"auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."),
"auth.username_required": (422, "Enter your username."),
"auth.client_not_allowed": (403, "This account can't use the {client} app."),
"auth.session_not_found": (404, "Session not found."),
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
"device.revoked": (401, "This device was removed. Pair it again."),
"device.not_paired": (401, "This device isn't paired with the venue."),
"device.out_of_scope": (403, "A {app} device can't do this ({key})."),
"device.required": (401, "This login belongs to a paired device. Use it from that device."),
"device.not_found": (404, "Device {device_id} not found."),
"device.pair_code_invalid": (404, "That pairing code is wrong or has expired."),
"device.pair_rate_limited": (429, "Too many pairing requests. Wait a few minutes and try again."),
"device.not_an_app": (422, "{app} is not an app that runs on a device."),
"device.login_mode_invalid": (422, "A {app} device can't use the login mode {mode}."),
"device.link_invalid": (422, "Device {device_id} can't be linked to this device."),
# validation
"validation.invalid": (422, "Some fields are invalid."),
"validation.unknown_language": (422, "Unsupported language: {language}."),
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
# server
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
# domain
"order.not_found": (404, "Order {order_id} not found."),
}
class XeniaError(Exception):
"""An API error with a registered code. raise XeniaError("order.not_found", order_id=5)."""
def __init__(self, code: str, status: int | None = None, **params):
if code not in CODES:
raise KeyError(f"unregistered error code {code!r}: add it to core/errors.py CODES")
default_status, template = CODES[code]
self.code = code
self.status = status or default_status
self.params = params
try:
self.message = template.format(**params)
except (KeyError, IndexError):
self.message = template
super().__init__(self.message)
def error_body(code: str, message: str, params: dict | None = None, detail=None) -> dict:
return {"error": {"code": code, "params": params or {}, "message": message},
"detail": message if detail is None else detail}
async def _xenia_error_handler(request: Request, exc: XeniaError):
return JSONResponse(error_body(exc.code, exc.message, exc.params), status_code=exc.status)
async def _http_exception_handler(request: Request, exc: StarletteHTTPException):
detail = exc.detail
if isinstance(detail, str):
message = detail
elif isinstance(detail, dict) and isinstance(detail.get("message"), str):
message = detail["message"]
else:
try:
message = HTTPStatus(exc.status_code).phrase
except ValueError:
message = "Error"
return JSONResponse(error_body(f"http.{exc.status_code}", message, detail=detail),
status_code=exc.status_code, headers=getattr(exc, "headers", None))
async def _validation_handler(request: Request, exc: RequestValidationError):
errors = [{"field": ".".join(str(p) for p in e.get("loc", ())[1:]) or None,
"type": e.get("type"), "message": e.get("msg")} for e in exc.errors()]
# `detail` stays FastAPI's usual list, so existing frontends keep working
return JSONResponse(error_body("validation.invalid", CODES["validation.invalid"][1],
{"errors": jsonable_encoder(errors)}, detail=jsonable_encoder(exc.errors())),
status_code=422)
async def _unhandled_handler(request: Request, exc: Exception):
"""Last resort: a bug. Logged with the traceback; the client gets the request id
(also in the X-Request-ID header) so support can find the log lines."""
from core.logging import current_request_id
rid = getattr(request.state, "request_id", None) or current_request_id() or "-"
logger.exception("http.unhandled_error request_id=%s path=%s", rid, request.url.path)
err = XeniaError("internal.error", request_id=rid)
return JSONResponse(error_body(err.code, err.message, err.params), status_code=500,
headers={"X-Request-ID": rid})
def install_error_handlers(app: FastAPI) -> None:
app.add_exception_handler(Exception, _unhandled_handler)
app.add_exception_handler(XeniaError, _xenia_error_handler)
app.add_exception_handler(StarletteHTTPException, _http_exception_handler)
app.add_exception_handler(RequestValidationError, _validation_handler)