- WebSocket: credentials may come in the first frame ({cursor, token?, device?}).
A device token alone connects a paired screen (login-none apps get every event, a
sign-in app only events addressed to it); a terminal session's JWT needs its own
device, as over HTTP. Refusals send {type: refused, data: {code}} + close 4001/4003.
- ws_bus: registry of open sockets by user, session and device. Ending a session
closes its sockets (session.ended); revoke/reassign close the device's sockets
(device.revoked / device.updated); edits and module on/off send device.updated.
Events can target devices (device_ids=..., sync_events.target_device_ids, rev 0014).
Pushes go through each socket's own loop (call_soon_threadsafe).
- Device config: DeviceApp.config = typed ConfigFields, validated on pair/edit/
reassign (validation.device_config), effective values (defaults filled) in both
device views and the module catalogue. First field: auto_sign_out_minutes (KDS, POS).
- Manager: DeviceConfigFields renders an app's fields in the pair and edit dialogs.
- @xenia/api createLiveClient: `credentials` and `onRefused` options.
- Tests: tests/test_live.py (11), module texts for config fields, live client,
devices logic, manager.mjs device setting + live socket checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
310 lines
16 KiB
Python
310 lines
16 KiB
Python
"""Devices, pairing, device tokens, limits, scope (plan step 1.8, APPS_PLATFORM D-8, §6.3)."""
|
|
from datetime import datetime, timezone
|
|
|
|
import pytest
|
|
|
|
from conftest import TEST_PIN
|
|
from core.modules import entitlements as E
|
|
|
|
NOW = datetime(2026, 11, 12, 12, tzinfo=timezone.utc)
|
|
|
|
|
|
def install(**modules):
|
|
"""Licensed with exactly these modules (+ core/free tier)."""
|
|
E.set_current(E.compute({"v": 2, "site_id": "site-A", "modules": modules}, True, False, NOW, False), notify=False)
|
|
|
|
|
|
def err(r):
|
|
return r.json()["error"]["code"]
|
|
|
|
|
|
@pytest.fixture
|
|
def owner_h(make_user, login):
|
|
return login(make_user(role="owner"))
|
|
|
|
|
|
@pytest.fixture
|
|
def pair(client, owner_h):
|
|
"""pair(app_key, name=..., **fields) -> (device_token, device json from the manager API)."""
|
|
def _pair(app_key, name=None, **fields):
|
|
req = client.post("/api/devices/pair-request")
|
|
assert req.status_code == 201, req.text
|
|
code, secret = req.json()["code"], req.json()["secret"]
|
|
r = client.post("/api/devices", headers=owner_h,
|
|
json={"code": code, "app_key": app_key, "name": name or f"{app_key} screen", **fields})
|
|
if r.status_code != 201:
|
|
return None, r
|
|
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
|
|
assert poll.status_code == 200 and poll.json()["status"] == "paired", poll.text
|
|
return poll.json()["device_token"], r
|
|
return _pair
|
|
|
|
|
|
def dev_h(token, extra=None):
|
|
return {"X-Xenia-Device": token, **(extra or {})}
|
|
|
|
|
|
# ── pairing flow ─────────────────────────────────────────────────────────────
|
|
|
|
def test_pairing_flow(client, owner_h):
|
|
req = client.post("/api/devices/pair-request", headers={"User-Agent": "KDS-Box"})
|
|
assert req.status_code == 201
|
|
body = req.json()
|
|
code, secret = body["code"], body["secret"]
|
|
assert len(code) == 6 and set(code) <= set("ABCDEFGHJKLMNPQRSTUVWXYZ23456789")
|
|
|
|
# only the requester (who holds the secret) may poll
|
|
assert err(client.get(f"/api/devices/pair-request/{code}")) == "device.pair_code_invalid"
|
|
assert err(client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": "nope"})) \
|
|
== "device.pair_code_invalid"
|
|
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
|
|
assert poll.json()["status"] == "pending"
|
|
|
|
# the manager types the code (case and dashes don't matter)
|
|
typed = f"{code[:3].lower()}-{code[3:]}"
|
|
r = client.post("/api/devices", headers=owner_h,
|
|
json={"code": typed, "app_key": "kds", "name": "Bar KDS", "config": {"auto_sign_out_minutes": 5}})
|
|
assert r.status_code == 201, r.text
|
|
d = r.json()
|
|
assert d["claimed"] is False and d["user_agent"] == "KDS-Box" and d["effective_login_mode"] == "pin"
|
|
# a code is used once
|
|
assert err(client.post("/api/devices", headers=owner_h, json={"code": code, "app_key": "kds", "name": "x"})) \
|
|
== "device.pair_code_invalid"
|
|
|
|
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
|
|
assert poll.status_code == 200
|
|
token = poll.json()["device_token"]
|
|
assert poll.json()["device"]["config"] == {"auto_sign_out_minutes": 5} and poll.json()["device"]["app_status"] == "ok"
|
|
# the token is handed out exactly once
|
|
assert err(client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})) \
|
|
== "device.pair_code_invalid"
|
|
|
|
me = client.get("/api/devices/me", headers=dev_h(token))
|
|
assert me.status_code == 200 and me.json()["name"] == "Bar KDS" and me.json()["app_key"] == "kds"
|
|
listed = client.get("/api/devices", headers=owner_h).json()
|
|
assert [x["name"] for x in listed] == ["Bar KDS"] and listed[0]["claimed"] and listed[0]["last_seen_at"]
|
|
|
|
|
|
def test_unknown_token_and_no_token(client):
|
|
assert err(client.get("/api/devices/me")) == "device.not_paired"
|
|
assert err(client.get("/api/devices/me", headers=dev_h("forged"))) == "device.not_paired"
|
|
|
|
|
|
def test_pair_request_rate_limited(client):
|
|
from routers import devices
|
|
for _ in range(devices.RATE_PER_IP):
|
|
assert client.post("/api/devices/pair-request").status_code == 201
|
|
r = client.post("/api/devices/pair-request")
|
|
assert r.status_code == 429 and err(r) == "device.pair_rate_limited"
|
|
|
|
|
|
def test_device_management_needs_key(client, make_user, login):
|
|
chef_h = login(make_user(role="chef"))
|
|
assert err(client.get("/api/devices", headers=chef_h)) == "access.denied"
|
|
|
|
|
|
def test_approve_validation(client, owner_h, pair):
|
|
_, r = pair("reports")
|
|
assert err(r) == "device.not_an_app"
|
|
_, r = pair("signage", login_mode="pin")
|
|
assert err(r) == "device.login_mode_invalid"
|
|
_, r = pair("kds", linked_device_id=999)
|
|
assert err(r) == "device.link_invalid"
|
|
|
|
|
|
def test_rename_mode_link(client, owner_h, pair):
|
|
_, pos = pair("pos_counter", "Counter 1")
|
|
_, disp = pair("customer_display", "Counter 1 display")
|
|
pid, did = pos.json()["id"], disp.json()["id"]
|
|
r = client.patch(f"/api/devices/{did}", headers=owner_h, json={"linked_device_id": pid, "name": "Front display"})
|
|
assert r.status_code == 200 and r.json()["linked_device_id"] == pid and r.json()["name"] == "Front display"
|
|
assert err(client.patch(f"/api/devices/{did}", headers=owner_h, json={"linked_device_id": did})) == "device.link_invalid"
|
|
r = client.patch(f"/api/devices/{pid}", headers=owner_h, json={"login_mode": "tap"})
|
|
assert r.json()["login_mode"] == "tap" and r.json()["effective_login_mode"] == "tap"
|
|
r = client.patch(f"/api/devices/{pid}", headers=owner_h, json={"login_mode": ""})
|
|
assert r.json()["login_mode"] is None and r.json()["effective_login_mode"] == "pin"
|
|
assert client.get(f"/api/devices/{did}", headers=owner_h).json()["effective_login_mode"] == "none"
|
|
assert err(client.get("/api/devices/4242", headers=owner_h)) == "device.not_found"
|
|
|
|
|
|
# ── limits (D-6) ─────────────────────────────────────────────────────────────
|
|
|
|
def test_third_kds_refused_with_limit_two(client, owner_h, pair): # "done when" 1
|
|
install(ordering={}, kds={"limits": {"devices": 2}})
|
|
t1, _ = pair("kds", "KDS 1")
|
|
t2, _ = pair("kds", "KDS 2")
|
|
assert t1 and t2
|
|
_, r = pair("kds", "KDS 3")
|
|
assert r.status_code == 402
|
|
assert r.json()["error"] == {"code": "license.limit_reached",
|
|
"params": {"module": "kds", "limit": "devices", "max": 2},
|
|
"message": "License limit reached for kds devices (2)."}
|
|
# revoking one frees its place
|
|
first = client.get("/api/devices", headers=owner_h).json()[0]["id"]
|
|
client.post(f"/api/devices/{first}/revoke", headers=owner_h)
|
|
t3, r = pair("kds", "KDS 3")
|
|
assert t3, r.text
|
|
|
|
|
|
def test_downgrade_blocks_newest_devices(client, owner_h, pair):
|
|
install(ordering={}, kds={"limits": {"devices": 3}})
|
|
tokens = [pair("kds", f"KDS {i}")[0] for i in range(3)]
|
|
install(ordering={}, kds={"limits": {"devices": 2}})
|
|
assert client.get("/api/devices/me", headers=dev_h(tokens[1])).status_code == 200
|
|
r = client.get("/api/devices/me", headers=dev_h(tokens[2]))
|
|
assert r.status_code == 402 and err(r) == "license.limit_reached"
|
|
|
|
|
|
def test_unlicensed_app_cannot_be_paired(client, pair):
|
|
install(ordering={})
|
|
_, r = pair("kds")
|
|
assert r.status_code == 402 and r.json()["error"]["params"] == {"module": "kds"}
|
|
|
|
|
|
def test_disabled_app_reports_status_on_me(client, owner_h, pair, make_user, login):
|
|
token, _ = pair("kds")
|
|
admin_h = login(make_user(role="superadmin"))
|
|
assert client.put("/api/platform/modules/kds", headers=admin_h, json={"enabled": False}).status_code == 200
|
|
me = client.get("/api/devices/me", headers=dev_h(token))
|
|
assert me.status_code == 200 and me.json()["app_status"] == "module.disabled"
|
|
|
|
|
|
# ── revoke ───────────────────────────────────────────────────────────────────
|
|
|
|
def test_revoked_device_next_call_fails(client, owner_h, pair, make_user): # "done when" 2
|
|
token, r = pair("kds")
|
|
chef = make_user(role="chef")
|
|
s = client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id, "pin": TEST_PIN})
|
|
user_h = {"Authorization": f"Bearer {s.json()['access_token']}"}
|
|
assert client.get("/api/kds/orders", headers=dev_h(token, user_h)).status_code == 200
|
|
|
|
assert client.post(f"/api/devices/{r.json()['id']}/revoke", headers=owner_h).json()["revoked_at"]
|
|
for resp in (client.get("/api/devices/me", headers=dev_h(token)),
|
|
client.get("/api/kds/orders", headers=dev_h(token, user_h))):
|
|
assert resp.status_code == 401 and err(resp) == "device.revoked"
|
|
# its user session ended too, and it's gone from the default list
|
|
assert err(client.get("/api/auth/me", headers=user_h)) == "auth.session_ended"
|
|
assert client.get("/api/devices", headers=owner_h).json() == []
|
|
assert len(client.get("/api/devices?include_revoked=true", headers=owner_h).json()) == 1
|
|
|
|
|
|
def test_reassign_checks_limit_and_ends_sessions(client, owner_h, pair, make_user):
|
|
install(ordering={}, kds={"limits": {"devices": 1}}, pos_counter={"limits": {"devices": 1}})
|
|
k_token, k = pair("kds")
|
|
_, p = pair("pos_counter")
|
|
r = client.post(f"/api/devices/{p.json()['id']}/reassign", headers=owner_h, json={"app_key": "kds"})
|
|
assert err(r) == "license.limit_reached"
|
|
|
|
chef = make_user(role="chef")
|
|
s = client.post("/api/auth/login", headers=dev_h(k_token), json={"client": "terminal", "user_id": chef.id, "pin": TEST_PIN})
|
|
user_h = {"Authorization": f"Bearer {s.json()['access_token']}"}
|
|
client.post(f"/api/devices/{p.json()['id']}/revoke", headers=owner_h)
|
|
r = client.post(f"/api/devices/{k.json()['id']}/reassign", headers=owner_h, json={"app_key": "pos_counter"})
|
|
assert r.status_code == 200 and r.json()["app_key"] == "pos_counter"
|
|
assert err(client.get("/api/auth/me", headers=dev_h(k_token, user_h))) == "auth.session_ended"
|
|
assert client.get("/api/devices/me", headers=dev_h(k_token)).json()["app_key"] == "pos_counter"
|
|
|
|
|
|
# ── scope (D-8) ──────────────────────────────────────────────────────────────
|
|
|
|
def test_signage_token_cannot_call_orders(client, owner_h, pair): # "done when" 3
|
|
token, _ = pair("signage")
|
|
assert client.get("/api/orders/", headers=owner_h).status_code == 200 # control: no device
|
|
r = client.get("/api/orders/", headers=dev_h(token, owner_h))
|
|
assert r.status_code == 403 and r.json()["error"]["params"] == {"app": "signage", "key": "ordering"}
|
|
r = client.get("/api/orders/", headers=dev_h(token))
|
|
assert r.status_code == 403 and err(r) == "device.out_of_scope"
|
|
|
|
|
|
def test_keyed_core_route_out_of_device_scope(client, owner_h, pair):
|
|
token, _ = pair("kds")
|
|
assert client.get("/api/auth/sessions", headers=owner_h).status_code == 200
|
|
r = client.get("/api/auth/sessions", headers=dev_h(token, owner_h))
|
|
assert r.status_code == 403 and r.json()["error"]["params"] == {"app": "kds", "key": "core.staff.manage"}
|
|
assert client.get("/api/auth/me", headers=dev_h(token, owner_h)).status_code == 200 # core basics stay
|
|
|
|
|
|
def test_require_device_with_app():
|
|
from core.access.context import in_scope, module_in_scope
|
|
assert in_scope("kds", "kds.bump") and not in_scope("kds", "ordering.orders.cancel")
|
|
assert in_scope("pos_counter", "ordering.orders.cancel") and module_in_scope("pos_counter", "ordering")
|
|
assert not module_in_scope("signage", "ordering") and module_in_scope("signage", "signage")
|
|
|
|
|
|
# ── device login ─────────────────────────────────────────────────────────────
|
|
|
|
def test_terminal_login_needs_a_device(client, make_user): # tap without a device is refused
|
|
chef = make_user(role="chef")
|
|
r = client.post("/api/auth/login", json={"client": "terminal", "user_id": chef.id})
|
|
assert r.status_code == 401 and err(r) == "device.not_paired"
|
|
r = client.post("/api/auth/login", headers=dev_h("forged"), json={"client": "terminal", "user_id": chef.id})
|
|
assert err(r) == "device.not_paired"
|
|
|
|
|
|
def test_terminal_modes(client, owner_h, pair, make_user):
|
|
token, r = pair("kds", login_mode="tap")
|
|
chef, waiter = make_user(role="chef"), make_user(role="waiter")
|
|
s = client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id})
|
|
assert s.status_code == 200, s.text
|
|
assert err(client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": waiter.id})) \
|
|
== "auth.client_not_allowed"
|
|
|
|
client.patch(f"/api/devices/{r.json()['id']}", headers=owner_h, json={"login_mode": "pin"})
|
|
assert err(client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id})) \
|
|
== "auth.login_mode_not_allowed"
|
|
r2 = client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id, "pin": "0000"})
|
|
assert err(r2) == "auth.invalid_credentials"
|
|
|
|
sig, _ = pair("signage")
|
|
r3 = client.post("/api/auth/login", headers=dev_h(sig), json={"client": "terminal", "user_id": chef.id})
|
|
assert r3.json()["error"] == {"code": "auth.login_mode_not_allowed", "params": {"mode": "none"},
|
|
"message": "This way of logging in isn't enabled (none)."}
|
|
|
|
users = client.get("/api/devices/me/users", headers=dev_h(token)).json()
|
|
assert chef.id in {u["id"] for u in users} and waiter.id not in {u["id"] for u in users}
|
|
assert client.get("/api/devices/me/users", headers=dev_h(sig)).json() == []
|
|
|
|
|
|
def test_site_default_login_mode(client, owner_h, pair, make_user, login):
|
|
admin_h = login(make_user(role="superadmin"))
|
|
assert client.put("/api/settings/auth.default_login_mode", headers=admin_h, json={"value": "tap"}).status_code == 200
|
|
token, r = pair("kds")
|
|
assert r.json()["effective_login_mode"] == "tap"
|
|
chef = make_user(role="chef")
|
|
assert client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id}).status_code == 200
|
|
|
|
|
|
def test_terminal_session_bound_to_device(client, pair, make_user):
|
|
token, _ = pair("kds")
|
|
other, _ = pair("kds", "other")
|
|
chef = make_user(role="chef")
|
|
s = client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id, "pin": TEST_PIN})
|
|
user_h = {"Authorization": f"Bearer {s.json()['access_token']}"}
|
|
assert client.get("/api/kds/orders", headers=dev_h(token, user_h)).status_code == 200
|
|
r = client.get("/api/kds/orders", headers=user_h) # header dropped
|
|
assert r.status_code == 401 and err(r) == "device.required"
|
|
assert err(client.get("/api/kds/orders", headers=dev_h(other, user_h))) == "device.required" # another device
|
|
|
|
# a new login on the same device replaces the previous user
|
|
chef2 = make_user(role="chef")
|
|
client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef2.id, "pin": TEST_PIN})
|
|
assert err(client.get("/api/auth/me", headers=dev_h(token, user_h))) == "auth.session_ended"
|
|
|
|
|
|
def test_waiter_tap_still_needs_device(client, make_user, login):
|
|
admin_h = login(make_user(role="superadmin"))
|
|
client.put("/api/settings/auth.waiter_login_mode", headers=admin_h, json={"value": "tap"})
|
|
w = make_user(role="waiter")
|
|
assert err(client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id})) == "auth.mode_needs_device"
|
|
|
|
|
|
def test_sessions_list_names_the_device_and_the_callers_own(client, owner_h, pair, make_user): # 2.6e
|
|
token, _ = pair("kds", "Kitchen")
|
|
chef = make_user(role="chef")
|
|
client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id, "pin": TEST_PIN})
|
|
rows = client.get("/api/auth/sessions", headers=owner_h).json()
|
|
term = next(s for s in rows if s["user_id"] == chef.id)
|
|
assert term["client"] == "terminal" and term["device_name"] == "Kitchen" and term["device_app"] == "kds"
|
|
assert term["current"] is False
|
|
assert [s["current"] for s in rows].count(True) == 1 # the owner's own session
|