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>
This commit is contained in:
+4
-3
@@ -15,9 +15,10 @@ LICENSE_GRACE_HOURS=24
|
|||||||
# the router's DHCP.
|
# the router's DHCP.
|
||||||
HOST_IP=
|
HOST_IP=
|
||||||
|
|
||||||
# Break-glass support account (leave blank to disable)
|
# Support access (challenge codes, works offline). The builder makes this value with
|
||||||
MASTER_USERNAME=
|
# python tools/support_code.py --site-secret <SITE_ID>
|
||||||
MASTER_PASSWORD=
|
# Blank = no support access on this site.
|
||||||
|
SUPPORT_SECRET=
|
||||||
|
|
||||||
# Volumes — absolute paths on the client machine
|
# Volumes — absolute paths on the client machine
|
||||||
DATA_PATH=/opt/xenia/data
|
DATA_PATH=/opt/xenia/data
|
||||||
|
|||||||
+1
-2
@@ -14,8 +14,7 @@ services:
|
|||||||
- HOST_IP=${HOST_IP:-}
|
- HOST_IP=${HOST_IP:-}
|
||||||
- TLS_PORT=${TLS_PORT:-8443} # published port of the proxy's TLS entry (advertised to the app)
|
- TLS_PORT=${TLS_PORT:-8443} # published port of the proxy's TLS entry (advertised to the app)
|
||||||
- HTTP_PORT=${HTTP_PORT:-80} # published plain-HTTP LAN port (app downloads UI bundles from it)
|
- HTTP_PORT=${HTTP_PORT:-80} # published plain-HTTP LAN port (app downloads UI bundles from it)
|
||||||
- MASTER_USERNAME=${MASTER_USERNAME:-}
|
- SUPPORT_SECRET=${SUPPORT_SECRET:-}
|
||||||
- MASTER_PASSWORD=${MASTER_PASSWORD:-}
|
|
||||||
volumes:
|
volumes:
|
||||||
- ${DATA_PATH}:/app/data
|
- ${DATA_PATH}:/app/data
|
||||||
- ${LOGO_PATH}:/app/logo.png:ro
|
- ${LOGO_PATH}:/app/logo.png:ro
|
||||||
|
|||||||
@@ -154,6 +154,9 @@ Use `core.access.deps.require("<module>.<area>.<action>")` (or `require_any`, `p
|
|||||||
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>`; a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
|
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>`; a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
|
||||||
Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent).
|
Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent).
|
||||||
|
|
||||||
|
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
|
||||||
|
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
|
||||||
|
|
||||||
Everything else still needs manual checks before committing:
|
Everything else still needs manual checks before committing:
|
||||||
- the backend starts cleanly against an **existing** `pos.db` (this catches missing migrations)
|
- the backend starts cleanly against an **existing** `pos.db` (this catches missing migrations)
|
||||||
- `npm run build` passes for any frontend you touched
|
- `npm run build` passes for any frontend you touched
|
||||||
|
|||||||
@@ -71,6 +71,8 @@ if [ ! -f "$SCRIPT_DIR/.env" ]; then
|
|||||||
DETECTED_IP=$(detect_host_ip)
|
DETECTED_IP=$(detect_host_ip)
|
||||||
read -rp " Enter this machine's LAN IP [${DETECTED_IP}]: " INPUT_HOST_IP
|
read -rp " Enter this machine's LAN IP [${DETECTED_IP}]: " INPUT_HOST_IP
|
||||||
INPUT_HOST_IP=${INPUT_HOST_IP:-$DETECTED_IP}
|
INPUT_HOST_IP=${INPUT_HOST_IP:-$DETECTED_IP}
|
||||||
|
echo " Support access: the builder runs python tools/support_code.py --site-secret <SITE_ID>"
|
||||||
|
read -rp " Enter SUPPORT_SECRET (blank = no support access): " INPUT_SUPPORT_SECRET
|
||||||
|
|
||||||
if [ -z "$INPUT_SECRET_KEY" ]; then
|
if [ -z "$INPUT_SECRET_KEY" ]; then
|
||||||
INPUT_SECRET_KEY=$(openssl rand -hex 32)
|
INPUT_SECRET_KEY=$(openssl rand -hex 32)
|
||||||
@@ -81,6 +83,7 @@ if [ ! -f "$SCRIPT_DIR/.env" ]; then
|
|||||||
sed -i "s/^SITE_KEY=.*/SITE_KEY=${INPUT_SITE_KEY}/" "$SCRIPT_DIR/.env"
|
sed -i "s/^SITE_KEY=.*/SITE_KEY=${INPUT_SITE_KEY}/" "$SCRIPT_DIR/.env"
|
||||||
sed -i "s/^SECRET_KEY=.*/SECRET_KEY=${INPUT_SECRET_KEY}/" "$SCRIPT_DIR/.env"
|
sed -i "s/^SECRET_KEY=.*/SECRET_KEY=${INPUT_SECRET_KEY}/" "$SCRIPT_DIR/.env"
|
||||||
sed -i "s/^HOST_IP=.*/HOST_IP=${INPUT_HOST_IP}/" "$SCRIPT_DIR/.env"
|
sed -i "s/^HOST_IP=.*/HOST_IP=${INPUT_HOST_IP}/" "$SCRIPT_DIR/.env"
|
||||||
|
sed -i "s/^SUPPORT_SECRET=.*/SUPPORT_SECRET=${INPUT_SUPPORT_SECRET}/" "$SCRIPT_DIR/.env"
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo " .env written. Review it at: $SCRIPT_DIR/.env"
|
echo " .env written. Review it at: $SCRIPT_DIR/.env"
|
||||||
|
|||||||
@@ -26,9 +26,9 @@ class Settings(BaseSettings):
|
|||||||
# machines and test suites (docker-compose.dev.yml, tests/e2e). Never on a site.
|
# machines and test suites (docker-compose.dev.yml, tests/e2e). Never on a site.
|
||||||
LICENSE_MODE: str = "enforced"
|
LICENSE_MODE: str = "enforced"
|
||||||
|
|
||||||
# Break-glass master account — lives only in env vars, never in the DB
|
# Support access (APPS_PLATFORM D-16): this site's secret, made by the builder with
|
||||||
MASTER_USERNAME: str = ""
|
# tools/support_code.py --site-secret <SITE_ID>. Empty = no support access.
|
||||||
MASTER_PASSWORD: str = ""
|
SUPPORT_SECRET: str = ""
|
||||||
|
|
||||||
model_config = {"env_file": str(_HERE / ".env"), "env_file_encoding": "utf-8"}
|
model_config = {"env_file": str(_HERE / ".env"), "env_file_encoding": "utf-8"}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from core.modules.registry import all_permissions
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class AccessContext:
|
class AccessContext:
|
||||||
user: Any = None # User row, or the support ghost (step 1.10); None for device-only calls
|
user: Any = None # User row, or the support account (routers.deps.make_support_user); None for device-only calls
|
||||||
session: Any = None # session id (sid) of the user's login
|
session: Any = None # session id (sid) of the user's login
|
||||||
device: Any = None # Device row when the call comes from a paired device (D-8)
|
device: Any = None # Device row when the call comes from a paired device (D-8)
|
||||||
override_token: Optional[str] = None # X-Xenia-Override (D-10); consumed by check() when needed
|
override_token: Optional[str] = None # X-Xenia-Override (D-10); consumed by check() when needed
|
||||||
|
|||||||
@@ -62,6 +62,9 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"auth.username_required": (422, "Enter your username."),
|
"auth.username_required": (422, "Enter your username."),
|
||||||
"auth.client_not_allowed": (403, "This account can't use the {client} app."),
|
"auth.client_not_allowed": (403, "This account can't use the {client} app."),
|
||||||
"auth.session_not_found": (404, "Session not found."),
|
"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.revoked": (401, "This device was removed. Pair it again."),
|
||||||
"device.not_paired": (401, "This device isn't paired with the venue."),
|
"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.out_of_scope": (403, "A {app} device can't do this ({key})."),
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ class Active(NamedTuple):
|
|||||||
"""What validate() knows about an active session."""
|
"""What validate() knows about an active session."""
|
||||||
user_id: Optional[int] # None = the support account
|
user_id: Optional[int] # None = the support account
|
||||||
device_id: Optional[int] # set for terminal sessions: the device they belong to
|
device_id: Optional[int] # set for terminal sessions: the device they belong to
|
||||||
|
expires_at: Optional[object] = None # hard end (support sessions); None = none
|
||||||
|
|
||||||
|
|
||||||
_cache: dict[str, tuple[float, Active]] = {} # sid -> (checked_at monotonic, info) for ACTIVE sessions
|
_cache: dict[str, tuple[float, Active]] = {} # sid -> (checked_at monotonic, info) for ACTIVE sessions
|
||||||
@@ -61,8 +62,8 @@ def single_session_rule(db, client: str) -> str:
|
|||||||
|
|
||||||
# ── lifecycle ────────────────────────────────────────────────────────────────
|
# ── lifecycle ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def start(db, user, client: str, request=None, *, legacy_manager: bool = False, device=None):
|
def start(db, user, client: str, request=None, *, legacy_manager: bool = False, device=None, expires_at=None):
|
||||||
"""Create a session for user (None user_id for the support ghost). Commits.
|
"""Create a session for user (None user_id for the support account). Commits.
|
||||||
`device`: the paired device of a terminal login; its previous sessions are replaced
|
`device`: the paired device of a terminal login; its previous sessions are replaced
|
||||||
(a shared screen shows one user at a time)."""
|
(a shared screen shows one user at a time)."""
|
||||||
from models.session import LoginSession
|
from models.session import LoginSession
|
||||||
@@ -86,7 +87,7 @@ def start(db, user, client: str, request=None, *, legacy_manager: bool = False,
|
|||||||
_end_row(s, "replaced")
|
_end_row(s, "replaced")
|
||||||
now = utcnow()
|
now = utcnow()
|
||||||
row = LoginSession(id=uuid.uuid4().hex, user_id=user_id, client=client, created_at=now, last_seen_at=now,
|
row = LoginSession(id=uuid.uuid4().hex, user_id=user_id, client=client, created_at=now, last_seen_at=now,
|
||||||
device_id=(device.id if device is not None else None),
|
device_id=(device.id if device is not None else None), expires_at=expires_at,
|
||||||
ip=(request.client.host if request is not None and request.client else None),
|
ip=(request.client.host if request is not None and request.client else None),
|
||||||
user_agent=(request.headers.get("user-agent", "")[:300] if request is not None else None))
|
user_agent=(request.headers.get("user-agent", "")[:300] if request is not None else None))
|
||||||
db.add(row)
|
db.add(row)
|
||||||
@@ -138,7 +139,7 @@ def validate(sid: str | None, db=None) -> Active:
|
|||||||
now_m = time.monotonic()
|
now_m = time.monotonic()
|
||||||
with _lock:
|
with _lock:
|
||||||
hit = _cache.get(sid)
|
hit = _cache.get(sid)
|
||||||
if hit and now_m - hit[0] < CACHE_TTL_S:
|
if hit and now_m - hit[0] < CACHE_TTL_S and not (hit[1].expires_at and hit[1].expires_at <= utcnow()):
|
||||||
return hit[1]
|
return hit[1]
|
||||||
from models.session import LoginSession
|
from models.session import LoginSession
|
||||||
own = db is None
|
own = db is None
|
||||||
@@ -147,11 +148,14 @@ def validate(sid: str | None, db=None) -> Active:
|
|||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
try:
|
try:
|
||||||
row = db.get(LoginSession, sid)
|
row = db.get(LoginSession, sid)
|
||||||
|
if row is not None and row.ended_at is None and row.expires_at is not None and row.expires_at <= utcnow():
|
||||||
|
_end_row(row, "expired")
|
||||||
|
db.commit()
|
||||||
if row is None or row.ended_at is not None:
|
if row is None or row.ended_at is not None:
|
||||||
with _lock:
|
with _lock:
|
||||||
_cache.pop(sid, None)
|
_cache.pop(sid, None)
|
||||||
raise XeniaError("auth.session_ended")
|
raise XeniaError("auth.session_ended")
|
||||||
info = Active(row.user_id, row.device_id)
|
info = Active(row.user_id, row.device_id, row.expires_at)
|
||||||
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
||||||
finally:
|
finally:
|
||||||
if own:
|
if own:
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""Support access codes (APPS_PLATFORM D-16, plan step 1.10). Standard library only.
|
||||||
|
|
||||||
|
Used by the backend (routers/auth.py) AND by the builder's tool tools/support_code.py,
|
||||||
|
which loads this file by path, so keep it free of backend imports.
|
||||||
|
|
||||||
|
master key (builder only, %USERPROFILE%\\.xenia\\support_master_key.txt)
|
||||||
|
└─ site secret = HMAC-SHA256(master, "xenia-support-site:" + site_id) -> hex, in the site .env as SUPPORT_SECRET
|
||||||
|
└─ code = base32(HMAC-SHA256(site secret, "xenia-support:" + site_id + ":" + challenge))[:10]
|
||||||
|
|
||||||
|
The site shows a random 8-character challenge (stored server-side for 15 min, single use);
|
||||||
|
the builder runs the tool with the site id and the challenge and reads back the code.
|
||||||
|
Works offline at the site: nothing but the two HMACs is needed. A code made for another
|
||||||
|
site never verifies (different secret, and the site id is in the message).
|
||||||
|
The test suite and tests/e2e (JS) re-implement these two functions; tests/test_support.py
|
||||||
|
pins a known vector so the implementations can't drift apart.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
CHALLENGE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # read aloud / typed: no 0/O, 1/I
|
||||||
|
CHALLENGE_LEN = 8
|
||||||
|
CODE_LEN = 10
|
||||||
|
|
||||||
|
|
||||||
|
def site_secret(master_key: str, site_id: str) -> str:
|
||||||
|
return hmac.new(master_key.strip().encode(), f"xenia-support-site:{site_id}".encode(), hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_challenge(challenge: str) -> str:
|
||||||
|
return "".join(ch for ch in challenge.upper() if ch.isalnum())
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_code(code: str) -> str:
|
||||||
|
# base32 (A-Z, 2-7): people read 0 as O, 1 as I and 8 as B
|
||||||
|
s = "".join(ch for ch in code.upper() if ch.isalnum())
|
||||||
|
return s.translate(str.maketrans({"0": "O", "1": "I", "8": "B"}))
|
||||||
|
|
||||||
|
|
||||||
|
def code_for(secret: str, site_id: str, challenge: str) -> str:
|
||||||
|
msg = f"xenia-support:{site_id}:{normalize_challenge(challenge)}".encode()
|
||||||
|
digest = hmac.new(secret.strip().encode(), msg, hashlib.sha256).digest()
|
||||||
|
return base64.b32encode(digest).decode()[:CODE_LEN]
|
||||||
|
|
||||||
|
|
||||||
|
def new_challenge() -> str:
|
||||||
|
return "".join(secrets.choice(CHALLENGE_ALPHABET) for _ in range(CHALLENGE_LEN))
|
||||||
|
|
||||||
|
|
||||||
|
def group(s: str, size: int) -> str:
|
||||||
|
""""ABCDEFGH" -> "ABCD-EFGH" (for display; input is normalized anyway)."""
|
||||||
|
return "-".join(s[i:i + size] for i in range(0, len(s), size))
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""support_challenges + sessions.expires_at (support access)
|
||||||
|
|
||||||
|
Revision ID: 0009_support_access
|
||||||
|
Revises: 0008_access_overrides
|
||||||
|
Create Date: 2026-11-13 10:47:20.516800
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0009_support_access'
|
||||||
|
down_revision = '0008_access_overrides'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('support_challenges',
|
||||||
|
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column('challenge', sa.String(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('expires_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('attempts', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('used_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('session_id', sa.String(), nullable=True),
|
||||||
|
sa.Column('ip', sa.String(), nullable=True),
|
||||||
|
sa.Column('user_agent', sa.String(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('challenge'),
|
||||||
|
sqlite_autoincrement=True
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('support_challenges', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_support_challenges_expires_at'), ['expires_at'], unique=False)
|
||||||
|
|
||||||
|
with op.batch_alter_table('sessions', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('expires_at', UTCDateTime(), nullable=True))
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('sessions', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('expires_at')
|
||||||
|
|
||||||
|
with op.batch_alter_table('support_challenges', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_support_challenges_expires_at'))
|
||||||
|
|
||||||
|
op.drop_table('support_challenges')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -32,3 +32,4 @@ import models.user_permission # noqa: F401 UserPermission (permission keys, st
|
|||||||
import models.session # noqa: F401 LoginSession (step 1.6)
|
import models.session # noqa: F401 LoginSession (step 1.6)
|
||||||
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
|
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
|
||||||
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
|
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
|
||||||
|
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ class LoginSession(Base):
|
|||||||
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
last_seen_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
last_seen_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
ended_at = Column(UTCDateTime, nullable=True, index=True)
|
ended_at = Column(UTCDateTime, nullable=True, index=True)
|
||||||
end_reason = Column(String, nullable=True) # logout | replaced | ended_by_manager | user_blocked | refreshed | device_revoked | device_reassigned
|
expires_at = Column(UTCDateTime, nullable=True) # hard end (support sessions: 4 h); NULL = none
|
||||||
|
end_reason = Column(String, nullable=True) # logout | replaced | ended_by_manager | user_blocked | refreshed | device_revoked | device_reassigned | expired
|
||||||
ip = Column(String, nullable=True)
|
ip = Column(String, nullable=True)
|
||||||
user_agent = Column(String, nullable=True)
|
user_agent = Column(String, nullable=True)
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""Support access challenges (APPS_PLATFORM D-16, §6.5, plan step 1.10).
|
||||||
|
|
||||||
|
One row per challenge shown on a login screen ("Support access"). It is valid for 15 min,
|
||||||
|
once, with a few wrong tries. A used row is the audit record of a support login: when,
|
||||||
|
from where and which session it opened. Rows are never deleted.
|
||||||
|
Written through routers/auth.py (support endpoints) only.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import Column, Integer, String
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class SupportChallenge(Base):
|
||||||
|
__tablename__ = "support_challenges"
|
||||||
|
__table_args__ = {"sqlite_autoincrement": True}
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
challenge = Column(String, nullable=False, unique=True) # normalized, 8 chars
|
||||||
|
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
|
expires_at = Column(UTCDateTime, nullable=False, index=True)
|
||||||
|
attempts = Column(Integer, nullable=False, default=0) # wrong codes entered
|
||||||
|
used_at = Column(UTCDateTime, nullable=True)
|
||||||
|
session_id = Column(String, nullable=True) # the support session it opened
|
||||||
|
ip = Column(String, nullable=True)
|
||||||
|
user_agent = Column(String, nullable=True)
|
||||||
@@ -23,7 +23,7 @@ class LoginByIdRequest(_PydanticBase):
|
|||||||
pin: str
|
pin: str
|
||||||
from schemas.user import UserOut
|
from schemas.user import UserOut
|
||||||
from core.i18n import normalize_language
|
from core.i18n import normalize_language
|
||||||
from routers.deps import bearer, get_current_user, make_token, decode_token, _make_ghost_superadmin
|
from routers.deps import bearer, get_current_user, make_token, decode_token, make_support_user
|
||||||
from core import sessions
|
from core import sessions
|
||||||
from core.access.deps import require
|
from core.access.deps import require
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
@@ -54,14 +54,6 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
|
|||||||
if client == "terminal":
|
if client == "terminal":
|
||||||
return _terminal_login(db, request, username=username, user_id=user_id, pin=pin, password=password)
|
return _terminal_login(db, request, username=username, user_id=user_id, pin=pin, password=password)
|
||||||
|
|
||||||
# Support access (synthetic superadmin). >>> replaced by challenge codes in step 1.10
|
|
||||||
if (client == "manager" and settings.MASTER_USERNAME and settings.MASTER_PASSWORD
|
|
||||||
and username == settings.MASTER_USERNAME and password == settings.MASTER_PASSWORD):
|
|
||||||
_logger.warning("MASTER LOGIN USED from username=%s", username)
|
|
||||||
ghost = _make_ghost_superadmin()
|
|
||||||
row = sessions.start(db, ghost, "support", request)
|
|
||||||
return TokenResponse(access_token=make_token(ghost, row.id), user=UserOut.model_validate(ghost))
|
|
||||||
|
|
||||||
if client == "manager":
|
if client == "manager":
|
||||||
mode = sessions.manager_login_mode(db)
|
mode = sessions.manager_login_mode(db)
|
||||||
if not legacy: # the current manager UI (no `client`) keeps v1 behaviour: pin or password
|
if not legacy: # the current manager UI (no `client`) keeps v1 behaviour: pin or password
|
||||||
@@ -165,6 +157,84 @@ def logout(credentials: Optional[HTTPAuthorizationCredentials] = Depends(_option
|
|||||||
return {"status": "logged out"}
|
return {"status": "logged out"}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Support access (D-16, §6.5) ─────────────────────────────────────────────
|
||||||
|
# The login screen's "Support access" asks for a challenge, the builder answers with
|
||||||
|
# tools/support_code.py <SITE_ID> <challenge>, and verify opens a 4 h support session
|
||||||
|
# (synthetic superadmin). Works offline. Replaces the MASTER_USERNAME/PASSWORD account.
|
||||||
|
|
||||||
|
SUPPORT_CHALLENGE_TTL_MIN = 15
|
||||||
|
SUPPORT_SESSION_HOURS = 4
|
||||||
|
SUPPORT_MAX_ATTEMPTS = 5 # wrong codes per challenge
|
||||||
|
SUPPORT_MAX_OPEN = 5 # unexpired, unused challenges at once
|
||||||
|
|
||||||
|
|
||||||
|
class SupportVerifyRequest(_PydanticBase):
|
||||||
|
challenge: str
|
||||||
|
code: str
|
||||||
|
|
||||||
|
|
||||||
|
def _support_configured() -> None:
|
||||||
|
if not (settings.SUPPORT_SECRET and settings.SITE_ID):
|
||||||
|
raise XeniaError("auth.support_not_configured")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/support/challenge", status_code=201, dependencies=[Depends(public())])
|
||||||
|
def support_challenge(request: Request, db: Session = Depends(get_db)):
|
||||||
|
"""A new challenge to read to the builder: {challenge: "ABCD-EFGH", site_id, expires_at}."""
|
||||||
|
from datetime import timedelta
|
||||||
|
from core import support_codes
|
||||||
|
from core.timeutil import utcnow
|
||||||
|
from models.support_challenge import SupportChallenge
|
||||||
|
_support_configured()
|
||||||
|
now = utcnow()
|
||||||
|
open_now = db.query(SupportChallenge).filter(SupportChallenge.used_at.is_(None), SupportChallenge.expires_at > now,
|
||||||
|
SupportChallenge.attempts < SUPPORT_MAX_ATTEMPTS).count()
|
||||||
|
if open_now >= SUPPORT_MAX_OPEN:
|
||||||
|
raise XeniaError("auth.support_rate_limited")
|
||||||
|
while True:
|
||||||
|
ch = support_codes.new_challenge()
|
||||||
|
if not db.query(SupportChallenge).filter(SupportChallenge.challenge == ch).first():
|
||||||
|
break
|
||||||
|
row = SupportChallenge(challenge=ch, created_at=now, expires_at=now + timedelta(minutes=SUPPORT_CHALLENGE_TTL_MIN),
|
||||||
|
ip=request.headers.get("x-real-ip") or (request.client.host if request.client else None),
|
||||||
|
user_agent=request.headers.get("user-agent", "")[:300])
|
||||||
|
db.add(row)
|
||||||
|
db.commit()
|
||||||
|
_logger.info("support.challenge id=%s", row.id)
|
||||||
|
return {"challenge": support_codes.group(ch, 4), "site_id": settings.SITE_ID, "expires_at": iso_z(row.expires_at)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/support/verify", response_model=TokenResponse, dependencies=[Depends(public())])
|
||||||
|
def support_verify(body: SupportVerifyRequest, request: Request, db: Session = Depends(get_db)):
|
||||||
|
"""The builder's code for a challenge -> a support session (4 h, single use per challenge)."""
|
||||||
|
import hmac as _hmac
|
||||||
|
from datetime import timedelta
|
||||||
|
from core import support_codes
|
||||||
|
from core.timeutil import utcnow
|
||||||
|
from models.support_challenge import SupportChallenge
|
||||||
|
_support_configured()
|
||||||
|
now = utcnow()
|
||||||
|
row = db.query(SupportChallenge).filter(
|
||||||
|
SupportChallenge.challenge == support_codes.normalize_challenge(body.challenge)).first()
|
||||||
|
if row is None or row.used_at is not None or row.expires_at <= now or row.attempts >= SUPPORT_MAX_ATTEMPTS:
|
||||||
|
raise XeniaError("auth.support_code_invalid")
|
||||||
|
expected = support_codes.code_for(settings.SUPPORT_SECRET, settings.SITE_ID, row.challenge)
|
||||||
|
if not _hmac.compare_digest(expected, support_codes.normalize_code(body.code)):
|
||||||
|
row.attempts += 1
|
||||||
|
db.commit()
|
||||||
|
_logger.warning("support.code_wrong challenge=%s attempts=%s", row.id, row.attempts)
|
||||||
|
raise XeniaError("auth.support_code_invalid")
|
||||||
|
support = make_support_user()
|
||||||
|
session = sessions.start(db, support, "support", request, expires_at=now + timedelta(hours=SUPPORT_SESSION_HOURS))
|
||||||
|
row.used_at = now
|
||||||
|
row.session_id = session.id
|
||||||
|
db.commit()
|
||||||
|
_logger.warning("support.access_used challenge=%s sid=%s ip=%s", row.id, session.id[:8], session.ip)
|
||||||
|
# >>> step 1.11: notify owners (support.access_used)
|
||||||
|
return TokenResponse(access_token=make_token(support, session.id, hours=SUPPORT_SESSION_HOURS),
|
||||||
|
user=UserOut.model_validate(support))
|
||||||
|
|
||||||
|
|
||||||
# ── Sessions (D-9): who is logged in where ─────────────────────────────────
|
# ── Sessions (D-9): who is logged in where ─────────────────────────────────
|
||||||
|
|
||||||
def _session_out(s, users: dict) -> dict:
|
def _session_out(s, users: dict) -> dict:
|
||||||
|
|||||||
@@ -17,15 +17,16 @@ bearer = HTTPBearer()
|
|||||||
TOKEN_EXPIRY_HOURS = 8
|
TOKEN_EXPIRY_HOURS = 8
|
||||||
|
|
||||||
|
|
||||||
MASTER_USER_ID = 0 # sentinel — never a real DB row
|
SUPPORT_USER_ID = 0 # sentinel — never a real DB row
|
||||||
|
|
||||||
|
|
||||||
def _make_ghost_superadmin():
|
def make_support_user():
|
||||||
"""Synthetic in-memory superadmin — plain namespace, never touches SQLAlchemy."""
|
"""The support account (D-16): a synthetic superadmin, never a DB row. Its sessions have
|
||||||
|
client="support" and user_id NULL; it only exists through POST /api/auth/support/verify."""
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
return SimpleNamespace(
|
return SimpleNamespace(
|
||||||
id=MASTER_USER_ID,
|
id=SUPPORT_USER_ID,
|
||||||
username=settings.MASTER_USERNAME,
|
username="support",
|
||||||
full_name="Xenia Support",
|
full_name="Xenia Support",
|
||||||
role="superadmin",
|
role="superadmin",
|
||||||
is_active=True,
|
is_active=True,
|
||||||
@@ -44,14 +45,14 @@ def _make_ghost_superadmin():
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def make_token(user: User, sid: str) -> str:
|
def make_token(user: User, sid: str, hours: float = TOKEN_EXPIRY_HOURS) -> str:
|
||||||
"""JWT for an existing session row (core.sessions.start). `sid` is what makes it revocable."""
|
"""JWT for an existing session row (core.sessions.start). `sid` is what makes it revocable."""
|
||||||
payload = {
|
payload = {
|
||||||
"sub": str(user.id),
|
"sub": str(user.id),
|
||||||
"sid": sid,
|
"sid": sid,
|
||||||
"username": user.username,
|
"username": user.username,
|
||||||
"role": user.role,
|
"role": user.role,
|
||||||
"exp": utcnow() + timedelta(hours=TOKEN_EXPIRY_HOURS),
|
"exp": utcnow() + timedelta(hours=hours),
|
||||||
}
|
}
|
||||||
return jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")
|
return jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")
|
||||||
|
|
||||||
@@ -87,9 +88,9 @@ def user_from_token(token: str, request: Request, db: Session):
|
|||||||
dev = current_device(request, db)
|
dev = current_device(request, db)
|
||||||
if dev is None or dev.id != info.device_id:
|
if dev is None or dev.id != info.device_id:
|
||||||
raise XeniaError("device.required")
|
raise XeniaError("device.required")
|
||||||
if int(payload["sub"]) == MASTER_USER_ID and payload.get("role") == "superadmin":
|
if info.user_id is None: # only support sessions have no user (core/sessions.py)
|
||||||
set_log_context(user="support")
|
set_log_context(user="support")
|
||||||
return _make_ghost_superadmin(), payload.get("sid")
|
return make_support_user(), payload.get("sid")
|
||||||
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
|
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
|
||||||
if not user:
|
if not user:
|
||||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
||||||
|
|||||||
@@ -37,8 +37,7 @@ _TMP = Path(tempfile.mkdtemp(prefix="xenia-tests-"))
|
|||||||
os.environ["DATABASE_URL"] = f"sqlite:///{(_TMP / 'test.db').as_posix()}"
|
os.environ["DATABASE_URL"] = f"sqlite:///{(_TMP / 'test.db').as_posix()}"
|
||||||
os.environ["LOG_DIR"] = str(_TMP / "logs")
|
os.environ["LOG_DIR"] = str(_TMP / "logs")
|
||||||
os.environ["TLS_DIR"] = str(_TMP / "tls")
|
os.environ["TLS_DIR"] = str(_TMP / "tls")
|
||||||
os.environ.setdefault("MASTER_USERNAME", "")
|
os.environ.setdefault("SUPPORT_SECRET", "")
|
||||||
os.environ.setdefault("MASTER_PASSWORD", "")
|
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""Support access (plan step 1.10, APPS_PLATFORM D-16, §6.5)."""
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from datetime import timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from core import support_codes as C
|
||||||
|
|
||||||
|
MASTER = "test-master-key-0123456789abcdef"
|
||||||
|
TOOL = Path(__file__).resolve().parents[2] / "tools" / "support_code.py"
|
||||||
|
|
||||||
|
|
||||||
|
def err(r):
|
||||||
|
return r.json()["error"]["code"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def site(monkeypatch):
|
||||||
|
from config import settings
|
||||||
|
monkeypatch.setattr(settings, "SITE_ID", "site-A")
|
||||||
|
monkeypatch.setattr(settings, "SUPPORT_SECRET", C.site_secret(MASTER, "site-A"))
|
||||||
|
return settings
|
||||||
|
|
||||||
|
|
||||||
|
def challenge(client):
|
||||||
|
r = client.post("/api/auth/support/challenge")
|
||||||
|
assert r.status_code == 201, r.text
|
||||||
|
return r.json()["challenge"]
|
||||||
|
|
||||||
|
|
||||||
|
def verify(client, ch, code):
|
||||||
|
return client.post("/api/auth/support/verify", json={"challenge": ch, "code": code})
|
||||||
|
|
||||||
|
|
||||||
|
# ── the derivation ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_known_vector(): # pins the algorithm; tests/e2e/lib (JS) must give the same values
|
||||||
|
secret = C.site_secret(MASTER, "site-A")
|
||||||
|
assert secret == "058ec8ca09a653f82d1d4f546fbb2c03ababe6d6830079c75a564675ceb6fcfe"
|
||||||
|
assert C.code_for(secret, "site-A", "ABCD-EFGH") == "E4MYPVWT3M"
|
||||||
|
assert C.code_for(secret, "site-A", "abcd efgh") == "E4MYPVWT3M" # challenge typed loosely
|
||||||
|
assert C.normalize_code("e4myp-vwt3m") == "E4MYPVWT3M"
|
||||||
|
|
||||||
|
|
||||||
|
def test_tool_round_trip(client, site, tmp_path): # "done when": a code made by the tool works, once
|
||||||
|
key = tmp_path / "master.txt"
|
||||||
|
env = {"XENIA_SUPPORT_MASTER_KEY_FILE": str(key), "SYSTEMROOT": "C:\\Windows", "PATH": ""}
|
||||||
|
|
||||||
|
def tool(*args):
|
||||||
|
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True, env=env, check=True).stdout.strip()
|
||||||
|
|
||||||
|
assert "Created" in tool("--init")
|
||||||
|
assert "already exists" in tool("--init") # never overwrites
|
||||||
|
site.SUPPORT_SECRET = tool("--site-secret", "site-A")
|
||||||
|
ch = challenge(client)
|
||||||
|
code = tool("site-A", ch)
|
||||||
|
assert len(code) == 11 and code[5] == "-"
|
||||||
|
|
||||||
|
r = verify(client, ch, code)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
h = {"Authorization": f"Bearer {r.json()['access_token']}"}
|
||||||
|
me = client.get("/api/auth/me", headers=h).json()
|
||||||
|
assert me["role"] == "superadmin" and me["username"] == "support"
|
||||||
|
assert client.get("/api/settings/", headers=h).status_code == 200 # full access
|
||||||
|
# single use
|
||||||
|
assert err(verify(client, ch, code)) == "auth.support_code_invalid"
|
||||||
|
|
||||||
|
|
||||||
|
def test_code_for_another_site_is_refused(client, site):
|
||||||
|
ch = challenge(client)
|
||||||
|
other = C.code_for(C.site_secret(MASTER, "site-B"), "site-B", ch)
|
||||||
|
assert err(verify(client, ch, other)) == "auth.support_code_invalid"
|
||||||
|
# a different master key doesn't work either
|
||||||
|
assert err(verify(client, ch, C.code_for(C.site_secret("x" * 32, "site-A"), "site-A", ch))) == "auth.support_code_invalid"
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrong_codes_burn_the_challenge(client, site):
|
||||||
|
from routers.auth import SUPPORT_MAX_ATTEMPTS
|
||||||
|
ch = challenge(client)
|
||||||
|
for _ in range(SUPPORT_MAX_ATTEMPTS):
|
||||||
|
assert err(verify(client, ch, "AAAAA-AAAAA")) == "auth.support_code_invalid"
|
||||||
|
right = C.code_for(site.SUPPORT_SECRET, "site-A", ch)
|
||||||
|
assert err(verify(client, ch, right)) == "auth.support_code_invalid"
|
||||||
|
|
||||||
|
|
||||||
|
def test_challenge_expires(client, db, site):
|
||||||
|
from models.support_challenge import SupportChallenge
|
||||||
|
ch = challenge(client)
|
||||||
|
row = db.query(SupportChallenge).filter(SupportChallenge.challenge == C.normalize_challenge(ch)).one()
|
||||||
|
row.expires_at = row.created_at - timedelta(seconds=1)
|
||||||
|
db.commit()
|
||||||
|
assert err(verify(client, ch, C.code_for(site.SUPPORT_SECRET, "site-A", ch))) == "auth.support_code_invalid"
|
||||||
|
|
||||||
|
|
||||||
|
def test_support_session_has_a_hard_end(client, db, site):
|
||||||
|
from core import sessions
|
||||||
|
from models.session import LoginSession
|
||||||
|
from models.support_challenge import SupportChallenge
|
||||||
|
ch = challenge(client)
|
||||||
|
r = verify(client, ch, C.code_for(site.SUPPORT_SECRET, "site-A", ch))
|
||||||
|
h = {"Authorization": f"Bearer {r.json()['access_token']}"}
|
||||||
|
audit = db.query(SupportChallenge).filter(SupportChallenge.challenge == C.normalize_challenge(ch)).one()
|
||||||
|
s = db.get(LoginSession, audit.session_id)
|
||||||
|
assert s.client == "support" and s.user_id is None
|
||||||
|
assert timedelta(hours=3, minutes=59) < s.expires_at - s.created_at <= timedelta(hours=4)
|
||||||
|
s.expires_at = s.created_at
|
||||||
|
db.commit()
|
||||||
|
sessions.clear_cache()
|
||||||
|
assert err(client.get("/api/auth/me", headers=h)) == "auth.session_ended"
|
||||||
|
db.refresh(s)
|
||||||
|
assert s.end_reason == "expired"
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_challenges_are_capped(client, site):
|
||||||
|
from routers.auth import SUPPORT_MAX_OPEN
|
||||||
|
for _ in range(SUPPORT_MAX_OPEN):
|
||||||
|
challenge(client)
|
||||||
|
r = client.post("/api/auth/support/challenge")
|
||||||
|
assert r.status_code == 429 and err(r) == "auth.support_rate_limited"
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_configured(client, monkeypatch):
|
||||||
|
from config import settings
|
||||||
|
monkeypatch.setattr(settings, "SUPPORT_SECRET", "")
|
||||||
|
r = client.post("/api/auth/support/challenge")
|
||||||
|
assert r.status_code == 503 and err(r) == "auth.support_not_configured"
|
||||||
|
|
||||||
|
|
||||||
|
def test_master_account_is_gone(): # "done when": the env vars are gone
|
||||||
|
from config import Settings
|
||||||
|
assert not {"MASTER_USERNAME", "MASTER_PASSWORD"} & set(Settings.model_fields)
|
||||||
@@ -39,8 +39,8 @@ host eth0; DEFAULT_ROUTE=""; echo "DETECT no-d
|
|||||||
host wlan0; DEFAULT_ROUTE="default via 192.168.1.1 dev wlan0"; echo "DETECT wifi-only=$(detect_host_ip)"
|
host wlan0; DEFAULT_ROUTE="default via 192.168.1.1 dev wlan0"; echo "DETECT wifi-only=$(detect_host_ip)"
|
||||||
# full install.sh flows (real ip/hostname again, docker stubbed)
|
# full install.sh flows (real ip/hostname again, docker stubbed)
|
||||||
rm /stub/ip /stub/hostname; unset XENIA_SYS_NET
|
rm /stub/ip /stub/hostname; unset XENIA_SYS_NET
|
||||||
cp -r /t /a && cd /a && printf 'site-123\\nkey-abc\\n\\n\\n' | bash install.sh >/dev/null
|
cp -r /t /a && cd /a && printf 'site-123\\nkey-abc\\n\\n\\nsupp-0123abcd\\n' | bash install.sh >/dev/null
|
||||||
echo "FRESH env=$(grep -cE '^(SITE_ID=site-123|SITE_KEY=key-abc|HOST_IP=.+)$' .env) cert=$(test -s certs/cert.pem && echo yes) keymode=$(stat -c %a certs/key.pem) conf=$(test -s nginx-proxy/nginx.conf && echo yes)"
|
echo "FRESH env=$(grep -cE '^(SITE_ID=site-123|SITE_KEY=key-abc|HOST_IP=.+|SUPPORT_SECRET=supp-0123abcd)$' .env) cert=$(test -s certs/cert.pem && echo yes) keymode=$(stat -c %a certs/key.pem) conf=$(test -s nginx-proxy/nginx.conf && echo yes)"
|
||||||
cp -r /t /b && cd /b && mkdir -p certs && cp /a/certs/* certs/ && grep -v '^HOST_IP' .env.example > .env
|
cp -r /t /b && cd /b && mkdir -p certs && cp /a/certs/* certs/ && grep -v '^HOST_IP' .env.example > .env
|
||||||
bash install.sh >/dev/null; echo "UPGRADE hostip=$(grep -c '^HOST_IP=.\\+' .env)"
|
bash install.sh >/dev/null; echo "UPGRADE hostip=$(grep -c '^HOST_IP=.\\+' .env)"
|
||||||
bash install.sh >/dev/null; echo "RERUN hostip_lines=$(grep -c '^HOST_IP=' .env)"
|
bash install.sh >/dev/null; echo "RERUN hostip_lines=$(grep -c '^HOST_IP=' .env)"
|
||||||
@@ -54,7 +54,7 @@ r.check('HOST_IP: WireGuard full tunnel → physical NIC', val('DETECT wg-full-t
|
|||||||
r.check('HOST_IP: tunnel owns the default route → physical NIC', val('DETECT tunnel-owns-default') === '10.98.20.70')
|
r.check('HOST_IP: tunnel owns the default route → physical NIC', val('DETECT tunnel-owns-default') === '10.98.20.70')
|
||||||
r.check('HOST_IP: no default route → physical NIC', val('DETECT no-default-route') === '10.98.20.70')
|
r.check('HOST_IP: no default route → physical NIC', val('DETECT no-default-route') === '10.98.20.70')
|
||||||
r.check('HOST_IP: WiFi-only server', val('DETECT wifi-only') === '192.168.1.44')
|
r.check('HOST_IP: WiFi-only server', val('DETECT wifi-only') === '192.168.1.44')
|
||||||
r.check('fresh install: .env filled (SITE_ID, SITE_KEY, HOST_IP)', val('env') === '3')
|
r.check('fresh install: .env filled (SITE_ID, SITE_KEY, HOST_IP, SUPPORT_SECRET)', val('env') === '4')
|
||||||
r.check('fresh install: self-signed cert, key 600, proxy config written', val('cert') === 'yes' && val('keymode') === '600' && val('conf') === 'yes')
|
r.check('fresh install: self-signed cert, key 600, proxy config written', val('cert') === 'yes' && val('keymode') === '600' && val('conf') === 'yes')
|
||||||
r.check('upgrade: missing HOST_IP backfilled', val('UPGRADE hostip') === '1')
|
r.check('upgrade: missing HOST_IP backfilled', val('UPGRADE hostip') === '1')
|
||||||
r.check('re-run: HOST_IP not duplicated', val('RERUN hostip_lines') === '1')
|
r.check('re-run: HOST_IP not duplicated', val('RERUN hostip_lines') === '1')
|
||||||
|
|||||||
@@ -18,8 +18,6 @@ mkdirSync(OUT, { recursive: true })
|
|||||||
export const PYTHON = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3')
|
export const PYTHON = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3')
|
||||||
// Playwright browser: system Edge by default; BROWSER_CHANNEL= (empty) uses Playwright's own Chromium
|
// Playwright browser: system Edge by default; BROWSER_CHANNEL= (empty) uses Playwright's own Chromium
|
||||||
export const BROWSER_CHANNEL = process.env.BROWSER_CHANNEL ?? 'msedge'
|
export const BROWSER_CHANNEL = process.env.BROWSER_CHANNEL ?? 'msedge'
|
||||||
// Break-glass login the test backends are started with (never a real account)
|
|
||||||
export const MASTER = { username: 'e2e', password: 'e2e-pass-123' }
|
|
||||||
// The Android emulator reaches the host machine at this address
|
// The Android emulator reaches the host machine at this address
|
||||||
export const EMULATOR_HOST = '10.0.2.2'
|
export const EMULATOR_HOST = '10.0.2.2'
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,8 @@
|
|||||||
import { execFileSync, spawn } from 'node:child_process'
|
import { execFileSync, spawn } from 'node:child_process'
|
||||||
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
import { BACKEND, CS, MASTER, OUT, PYTHON, WAITER, sleep } from './env.mjs'
|
import { BACKEND, CS, OUT, PYTHON, WAITER, sleep } from './env.mjs'
|
||||||
|
import { SUPPORT_MASTER, siteSecret, supportLogin } from './support.mjs'
|
||||||
|
|
||||||
/** Kill a process and its children (npx/shell wrappers on Windows). */
|
/** Kill a process and its children (npx/shell wrappers on Windows). */
|
||||||
export function killTree(child) {
|
export function killTree(child) {
|
||||||
@@ -66,7 +67,7 @@ export async function startBackend({ port = 8055, siteId = 'test-site-1', siteKe
|
|||||||
SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret',
|
SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret',
|
||||||
// No cloud = a test backend: licensing off (every module). The license suite passes a cloudUrl.
|
// No cloud = a test backend: licensing off (every module). The license suite passes a cloudUrl.
|
||||||
LICENSE_MODE: cloudUrl ? 'enforced' : 'off',
|
LICENSE_MODE: cloudUrl ? 'enforced' : 'off',
|
||||||
MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password, ...env,
|
SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId), ...env,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
const url = `http://127.0.0.1:${port}`
|
const url = `http://127.0.0.1:${port}`
|
||||||
@@ -74,12 +75,8 @@ export async function startBackend({ port = 8055, siteId = 'test-site-1', siteKe
|
|||||||
return { url, dataDir, child, stop: async () => { killTree(child); await waitHttp(`${url}/api/system/health`, false).catch(() => {}) } }
|
return { url, dataDir, child, stop: async () => { killTree(child); await waitHttp(`${url}/api/system/health`, false).catch(() => {}) } }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function login(baseUrl) {
|
/** A superadmin token for a test backend, through support access (challenge code). */
|
||||||
const r = await fetch(`${baseUrl}/api/auth/login`, {
|
export const login = baseUrl => supportLogin(baseUrl)
|
||||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(MASTER),
|
|
||||||
})
|
|
||||||
return (await r.json()).access_token
|
|
||||||
}
|
|
||||||
|
|
||||||
/** nginx:alpine serving a waiter build (`dist`) with the waiter's own nginx.conf, /api → host backend. */
|
/** nginx:alpine serving a waiter build (`dist`) with the waiter's own nginx.conf, /api → host backend. */
|
||||||
export async function serveWaiterBuild({ name, port, dist = path.join(WAITER, 'dist'), backendPort = 8055 }) {
|
export async function serveWaiterBuild({ name, port, dist = path.join(WAITER, 'dist'), backendPort = 8055 }) {
|
||||||
@@ -121,7 +118,7 @@ export function composeStack({ project, version, siteId, http, https, manager, e
|
|||||||
writeFileSync(envFile, Object.entries({
|
writeFileSync(envFile, Object.entries({
|
||||||
REGISTRY: 'e2e', VERSION: version, SITE_ID: siteId, SITE_KEY: 'x', CLOUD_URL: '', SECRET_KEY: 'e2e-secret',
|
REGISTRY: 'e2e', VERSION: version, SITE_ID: siteId, SITE_KEY: 'x', CLOUD_URL: '', SECRET_KEY: 'e2e-secret',
|
||||||
LICENSE_MODE: 'off',
|
LICENSE_MODE: 'off',
|
||||||
HOST_IP: '10.0.2.2', TLS_PORT: https, HTTP_PORT: http, MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password,
|
HOST_IP: '10.0.2.2', TLS_PORT: https, HTTP_PORT: http, SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId),
|
||||||
DATA_PATH: fwd(path.join(dir, 'data')), LOGO_PATH: fwd(path.join(dir, 'logo.png')), FISCAL_PATH: fwd(path.join(dir, 'fiscal')),
|
DATA_PATH: fwd(path.join(dir, 'data')), LOGO_PATH: fwd(path.join(dir, 'logo.png')), FISCAL_PATH: fwd(path.join(dir, 'fiscal')),
|
||||||
...extraEnv,
|
...extraEnv,
|
||||||
}).map(([k, v]) => `${k}=${v}`).join('\n') + '\n')
|
}).map(([k, v]) => `${k}=${v}`).join('\n') + '\n')
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
// Support access for the test backends (APPS_PLATFORM D-16): the suites log in the way
|
||||||
|
// the builder would, with a challenge code. Same algorithm as
|
||||||
|
// local_backend/core/support_codes.py; local_backend/tests/test_support.py pins a known
|
||||||
|
// vector (master "test-master-key-0123456789abcdef", site "site-A", challenge
|
||||||
|
// "ABCD-EFGH" -> "E4MYPVWT3M"), checked here by selfCheck().
|
||||||
|
import { createHmac } from 'node:crypto'
|
||||||
|
|
||||||
|
// The test master key the e2e backends' SUPPORT_SECRET is derived from (never a real key)
|
||||||
|
export const SUPPORT_MASTER = 'e2e-support-master-key-0000000000'
|
||||||
|
|
||||||
|
const B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
||||||
|
|
||||||
|
function base32(buf) {
|
||||||
|
let bits = 0, value = 0, out = ''
|
||||||
|
for (const byte of buf) {
|
||||||
|
value = (value << 8) | byte
|
||||||
|
bits += 8
|
||||||
|
while (bits >= 5) { out += B32[(value >>> (bits - 5)) & 31]; bits -= 5 }
|
||||||
|
}
|
||||||
|
if (bits > 0) out += B32[(value << (5 - bits)) & 31]
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
export const siteSecret = (master, siteId) =>
|
||||||
|
createHmac('sha256', master.trim()).update(`xenia-support-site:${siteId}`).digest('hex')
|
||||||
|
|
||||||
|
export function codeFor(secret, siteId, challenge) {
|
||||||
|
const ch = challenge.toUpperCase().replace(/[^A-Z0-9]/g, '')
|
||||||
|
return base32(createHmac('sha256', secret.trim()).update(`xenia-support:${siteId}:${ch}`).digest()).slice(0, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selfCheck() {
|
||||||
|
const s = siteSecret('test-master-key-0123456789abcdef', 'site-A')
|
||||||
|
if (codeFor(s, 'site-A', 'ABCD-EFGH') !== 'E4MYPVWT3M') throw new Error('support code algorithm drifted from core/support_codes.py')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A support session on a test backend: challenge -> code -> token. */
|
||||||
|
export async function supportLogin(baseUrl, master = SUPPORT_MASTER) {
|
||||||
|
selfCheck()
|
||||||
|
const c = await (await fetch(`${baseUrl}/api/auth/support/challenge`, { method: 'POST' })).json()
|
||||||
|
if (!c.challenge) throw new Error(`support challenge failed: ${JSON.stringify(c)}`)
|
||||||
|
const code = codeFor(siteSecret(master, c.site_id), c.site_id, c.challenge)
|
||||||
|
const r = await fetch(`${baseUrl}/api/auth/support/verify`, {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ challenge: c.challenge, code }),
|
||||||
|
})
|
||||||
|
const body = await r.json()
|
||||||
|
if (!body.access_token) throw new Error(`support verify failed: ${JSON.stringify(body)}`)
|
||||||
|
return body.access_token
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ Starts the cloud on :8101 and the site on :8055, on throwaway databases.
|
|||||||
python license_e2e.py
|
python license_e2e.py
|
||||||
"""
|
"""
|
||||||
import base64
|
import base64
|
||||||
|
import importlib.util
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
@@ -33,7 +34,12 @@ BACKEND = CS / "local_backend"
|
|||||||
CLOUD = Path(os.environ.get("CLOUD_DIR", CS.parent / "cloud-service" / "cloud_backend"))
|
CLOUD = Path(os.environ.get("CLOUD_DIR", CS.parent / "cloud-service" / "cloud_backend"))
|
||||||
OUT = E2E / "out"
|
OUT = E2E / "out"
|
||||||
CLOUD_URL, SITE_URL = "http://127.0.0.1:8101", "http://127.0.0.1:8055"
|
CLOUD_URL, SITE_URL = "http://127.0.0.1:8101", "http://127.0.0.1:8055"
|
||||||
MASTER = {"username": "e2e", "password": "e2e-pass-123"}
|
# Support access (D-16): the site gets a SUPPORT_SECRET derived from this test master key,
|
||||||
|
# and the suite logs in with a challenge code, the way the builder would.
|
||||||
|
SUPPORT_MASTER = "e2e-support-master-key-0000000000"
|
||||||
|
_spec = importlib.util.spec_from_file_location("support_codes", BACKEND / "core" / "support_codes.py")
|
||||||
|
codes = importlib.util.module_from_spec(_spec)
|
||||||
|
_spec.loader.exec_module(codes)
|
||||||
|
|
||||||
key = Ed25519PrivateKey.generate()
|
key = Ed25519PrivateKey.generate()
|
||||||
PRIV = base64.b64encode(key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())).decode()
|
PRIV = base64.b64encode(key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())).decode()
|
||||||
@@ -116,7 +122,7 @@ def start_cloud():
|
|||||||
def start_site(site_id, site_key):
|
def start_site(site_id, site_key):
|
||||||
env = {**os.environ, "DATABASE_URL": f"sqlite:///{(tmp / 'data' / 'pos.db').as_posix()}", "CLOUD_URL": CLOUD_URL,
|
env = {**os.environ, "DATABASE_URL": f"sqlite:///{(tmp / 'data' / 'pos.db').as_posix()}", "CLOUD_URL": CLOUD_URL,
|
||||||
"SITE_ID": site_id, "SITE_KEY": site_key, "SECRET_KEY": "e2e-site", "LICENSE_MODE": "enforced",
|
"SITE_ID": site_id, "SITE_KEY": site_key, "SECRET_KEY": "e2e-site", "LICENSE_MODE": "enforced",
|
||||||
"MASTER_USERNAME": MASTER["username"], "MASTER_PASSWORD": MASTER["password"]}
|
"SUPPORT_SECRET": codes.site_secret(SUPPORT_MASTER, site_id)}
|
||||||
launcher = (f"import services.license as L; L.LICENSE_PUBLIC_KEY = {PUB!r}; "
|
launcher = (f"import services.license as L; L.LICENSE_PUBLIC_KEY = {PUB!r}; "
|
||||||
"import uvicorn; uvicorn.run('main:app', host='127.0.0.1', port=8055)")
|
"import uvicorn; uvicorn.run('main:app', host='127.0.0.1', port=8055)")
|
||||||
procs["site"] = subprocess.Popen([sys.executable, "-c", launcher], cwd=BACKEND, env=env,
|
procs["site"] = subprocess.Popen([sys.executable, "-c", launcher], cwd=BACKEND, env=env,
|
||||||
@@ -133,7 +139,9 @@ def stop(name):
|
|||||||
|
|
||||||
|
|
||||||
def status():
|
def status():
|
||||||
_, tok = call(SITE_URL, "POST", "/api/auth/login", MASTER)
|
_, ch = call(SITE_URL, "POST", "/api/auth/support/challenge", {})
|
||||||
|
code = codes.code_for(codes.site_secret(SUPPORT_MASTER, ch["site_id"]), ch["site_id"], ch["challenge"])
|
||||||
|
_, tok = call(SITE_URL, "POST", "/api/auth/support/verify", {"challenge": ch["challenge"], "code": code})
|
||||||
return call(SITE_URL, "GET", "/api/system/status", token=tok["access_token"])[1], tok["access_token"]
|
return call(SITE_URL, "GET", "/api/system/status", token=tok["access_token"])[1], tok["access_token"]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""Support access codes for Xenia sites (APPS_PLATFORM D-16). Run on the BUILDER's machine.
|
||||||
|
|
||||||
|
python tools/support_code.py --init create the master key (once; never overwrites)
|
||||||
|
python tools/support_code.py --site-secret <SITE_ID> the SUPPORT_SECRET value for that site's .env
|
||||||
|
python tools/support_code.py <SITE_ID> <CHALLENGE> the response code for a challenge the site shows
|
||||||
|
|
||||||
|
The master key lives in %USERPROFILE%\\.xenia\\support_master_key.txt (XENIA_SUPPORT_MASTER_KEY_FILE
|
||||||
|
overrides the path). It is outside the repo: back it up. Losing it means every site's
|
||||||
|
SUPPORT_SECRET has to be replaced; leaking it gives support access to every site.
|
||||||
|
The derivation is local_backend/core/support_codes.py (loaded by path; stdlib only).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_HERE = Path(__file__).resolve().parent
|
||||||
|
_spec = importlib.util.spec_from_file_location("support_codes", _HERE.parent / "local_backend" / "core" / "support_codes.py")
|
||||||
|
codes = importlib.util.module_from_spec(_spec)
|
||||||
|
_spec.loader.exec_module(codes)
|
||||||
|
|
||||||
|
|
||||||
|
def key_file() -> Path:
|
||||||
|
return Path(os.environ.get("XENIA_SUPPORT_MASTER_KEY_FILE") or Path.home() / ".xenia" / "support_master_key.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def master_key() -> str:
|
||||||
|
p = key_file()
|
||||||
|
if not p.exists():
|
||||||
|
sys.exit(f"No master key at {p}. Create it once with: python tools/support_code.py --init")
|
||||||
|
key = p.read_text(encoding="utf-8").strip()
|
||||||
|
if len(key) < 32:
|
||||||
|
sys.exit(f"{p} looks wrong (too short).")
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str]) -> int:
|
||||||
|
if argv == ["--init"]:
|
||||||
|
p = key_file()
|
||||||
|
if p.exists():
|
||||||
|
print(f"Master key already exists at {p}; not touching it.")
|
||||||
|
return 0
|
||||||
|
p.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
p.write_text(secrets.token_hex(32) + "\n", encoding="utf-8")
|
||||||
|
print(f"Created {p}. Back it up somewhere safe.")
|
||||||
|
return 0
|
||||||
|
if len(argv) == 2 and argv[0] == "--site-secret":
|
||||||
|
print(codes.site_secret(master_key(), argv[1]))
|
||||||
|
return 0
|
||||||
|
if len(argv) == 2 and not argv[0].startswith("-"):
|
||||||
|
site_id, challenge = argv
|
||||||
|
secret = codes.site_secret(master_key(), site_id)
|
||||||
|
print(codes.group(codes.code_for(secret, site_id, challenge), 5))
|
||||||
|
return 0
|
||||||
|
print(__doc__)
|
||||||
|
return 2
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv[1:]))
|
||||||
Reference in New Issue
Block a user