- removing a passkey ends every session it opened (sessions record the id); - an open Chrome view on the internet address re-checks its session every 5 s and closes when it ends (sign-out, passkey removed, access off); - Sign out there always ends the owner's session unless the guest cookie beside it is a live impersonation — a cookie a guest's *.gabvdl.xyz site planted can no longer turn it into a no-op; - the passkey link and "back on" need Authelia on the admin host, not just "not the internet address": the host token / loopback (what a run started from a stolen session can call) are refused; making a link now pushes; - switching internet access off cancels an open link; - ceremony tickets capped per address (10) so one address can't drain them; - docs: what the off switch can't undo (the owner is a shell). - 13 regression tests (test_remote_access: 51). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
323 lines
15 KiB
Python
323 lines
15 KiB
Python
"""Settings → Security → *Internet access*: what the owner's internet address
|
|
is, who is signed in there, and the switch that shuts it."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hmac
|
|
import secrets
|
|
import threading
|
|
import time
|
|
|
|
from fastapi import APIRouter, HTTPException, Request, Response
|
|
from pydantic import BaseModel, Field
|
|
|
|
import schemas
|
|
from core.http import _r
|
|
from core.i18n import primary_lang, tr
|
|
from core.state import State
|
|
from remoteaccess.sessions import COOKIE, OWNER_SESSION_IDLE_S, OWNER_SESSION_TTL_S
|
|
from remoteaccess.webauthn import (ALGS, WebAuthnError, b64u, unb64u, verify_assertion,
|
|
verify_registration)
|
|
from security import service as security
|
|
from users.caller import OWNER_HOSTS, OWNER_NAME, OwnerDep, on_owner_surface, request_host
|
|
from users.store import _hash
|
|
from workers import guests as worker_guests
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def view(deps, request: Request) -> dict:
|
|
st = deps.security_state.get()
|
|
sessions = deps.owner_sessions.list(request.cookies.get(COOKIE, ""))
|
|
passkeys = [{k: p.get(k) for k in ("id", "name", "created", "lastUsed", "synced")}
|
|
for p in deps.owner_passkeys.all()]
|
|
return {"hosts": sorted(OWNER_HOSTS), "locked": st["remoteLocked"],
|
|
"lockedAt": st["remoteLockedAt"], "sessions": sessions, "passkeys": passkeys,
|
|
"ttlS": OWNER_SESSION_TTL_S, "idleS": OWNER_SESSION_IDLE_S,
|
|
"here": on_owner_surface(request)}
|
|
|
|
|
|
@router.get("/api/remote", responses=_r(schemas.RemoteAccess))
|
|
def remote_state(deps: State, request: Request, _: OwnerDep):
|
|
return view(deps, request)
|
|
|
|
|
|
class RemoteLockBody(BaseModel):
|
|
locked: bool
|
|
|
|
|
|
@router.post("/api/remote/lock", responses=_r(schemas.RemoteAccess))
|
|
def remote_lock(deps: State, request: Request, caller: OwnerDep, body: RemoteLockBody):
|
|
"""Off from anywhere (one tap, even on the internet address itself — that
|
|
signs this browser out too); back on only from the admin host, signed in
|
|
through Authelia, so a session that was dropped (or a run it started)
|
|
can't undo its own cut-off."""
|
|
if not body.locked and not _on_admin_host(request):
|
|
raise HTTPException(403, "switch internet access back on from the admin host")
|
|
security.lock_remote(deps, body.locked)
|
|
return view(deps, request)
|
|
|
|
|
|
@router.delete("/api/remote/sessions/{sid}", responses=_r(schemas.RemoteAccess))
|
|
def remote_sign_out(deps: State, request: Request, _: OwnerDep, sid: str):
|
|
if not deps.owner_sessions.close_id(sid):
|
|
raise HTTPException(404, "no such session")
|
|
security.record(deps, "remote_signed_out", who="owner", request=request,
|
|
detail=f"session {sid} signed out")
|
|
return view(deps, request)
|
|
|
|
|
|
# ── passkeys ─────────────────────────────────────────────────────────────────
|
|
# A ceremony started here and not finished: ticket → {kind, challenge, host,
|
|
# exp, invite}. In memory (a restart only cancels sign-ins in progress),
|
|
# short-lived, bounded — anyone on the internet may start one.
|
|
_pending: dict[str, dict] = {}
|
|
_PENDING_TTL_S = 180
|
|
_PENDING_MAX = 2000
|
|
# One address holds at most this many: a flood from one place evicts its own
|
|
# tickets, never the owner's (a pool shared by everyone could be drained).
|
|
_PENDING_PER_IP = 10
|
|
_plock = threading.Lock()
|
|
# A refused sign-in is logged once per address per quiet window.
|
|
_refused_seen: dict[str, float] = {}
|
|
_REFUSED_QUIET_S = 600
|
|
|
|
|
|
def _on_admin_host(request: Request) -> bool:
|
|
"""Authelia vouched for the owner on this very request (``Remote-User``
|
|
through Traefik): the one proof it comes from the tailnet, past a second
|
|
factor. Not the internet address, and not a host-side caller either (the
|
|
host token, loopback) — a run started from a stolen internet session
|
|
could call those, and give itself a lasting way back in."""
|
|
from core.auth import edge_role, via_edge
|
|
return (not on_owner_surface(request) and via_edge(request)
|
|
and edge_role(request) == "owner")
|
|
|
|
|
|
def _owner_host(request: Request) -> str:
|
|
"""The internet address this request came in on — the RP ID, and
|
|
``https://<it>`` the only origin a passkey ceremony may come from."""
|
|
if not on_owner_surface(request):
|
|
raise HTTPException(404, "not found")
|
|
return request_host(request)
|
|
|
|
|
|
def _guard(deps, request: Request) -> str:
|
|
host = _owner_host(request)
|
|
if deps.security_state.remote_locked():
|
|
raise HTTPException(403, {"message": tr(_lang(request), "internet access is switched off"),
|
|
"kind": "remote_locked"})
|
|
if worker_guests.ip_locked(request):
|
|
raise HTTPException(429, {"message": tr(_lang(request),
|
|
"too many failed sign-ins — try again in an hour"),
|
|
"kind": "ip_locked"})
|
|
return host
|
|
|
|
|
|
def _lang(request: Request) -> str:
|
|
return primary_lang(request.headers.get("accept-language")) or "en"
|
|
|
|
|
|
def _new_ticket(request: Request, kind: str, host: str, **extra) -> tuple[str, bytes]:
|
|
from security.service import client_ip
|
|
ip = client_ip(request)
|
|
now = time.time()
|
|
ticket, challenge = secrets.token_urlsafe(24), secrets.token_bytes(32)
|
|
with _plock:
|
|
for t in [t for t, p in _pending.items() if p["exp"] < now]:
|
|
del _pending[t]
|
|
mine = sorted((p["exp"], t) for t, p in _pending.items() if p["ip"] == ip)
|
|
for _, t in mine[:max(0, len(mine) - _PENDING_PER_IP + 1)]:
|
|
del _pending[t]
|
|
while len(_pending) >= _PENDING_MAX:
|
|
del _pending[min(_pending, key=lambda t: _pending[t]["exp"])]
|
|
_pending[ticket] = {"kind": kind, "challenge": challenge, "host": host, "ip": ip,
|
|
"exp": now + _PENDING_TTL_S, **extra}
|
|
return ticket, challenge
|
|
|
|
|
|
def _take(ticket: str, kind: str, host: str) -> dict | None:
|
|
"""The ceremony ``ticket`` started — once: a second try needs a new one."""
|
|
with _plock:
|
|
p = _pending.pop(ticket or "", None)
|
|
if not p or p["kind"] != kind or p["host"] != host or p["exp"] < time.time():
|
|
return None
|
|
return p
|
|
|
|
|
|
def _refuse(deps, request: Request, why: str, status: int = 401):
|
|
"""A failed passkey ceremony: counted toward this address's lockout, logged."""
|
|
from security.service import client_ip
|
|
worker_guests.bad_token(deps, request, "/api/remote/passkey")
|
|
ip = client_ip(request)
|
|
now = time.time()
|
|
with _plock:
|
|
fresh = now - _refused_seen.get(ip, 0) > _REFUSED_QUIET_S
|
|
if fresh:
|
|
_refused_seen[ip] = now
|
|
if fresh:
|
|
security.record(deps, "owner_login_refused", request=request, detail=why[:200])
|
|
raise HTTPException(status, {"message": tr(_lang(request), "that passkey didn't work here"),
|
|
"kind": "passkey_refused"})
|
|
|
|
|
|
def _sign_in(deps, request: Request, response: Response, passkey: dict, how: str) -> None:
|
|
from security.service import client_ip
|
|
ip, ua = client_ip(request), request.headers.get("user-agent", "")
|
|
deps.owner_sessions.close(request.cookies.get(COOKIE, ""))
|
|
token = deps.owner_sessions.open(ip, ua, f"passkey {passkey.get('name') or ''}".strip(),
|
|
passkey=passkey.get("id"))
|
|
response.set_cookie(COOKIE, token, max_age=OWNER_SESSION_TTL_S, httponly=True,
|
|
secure=True, samesite="strict", path="/")
|
|
security.record(deps, "owner_login", who="owner", request=request,
|
|
detail=f"{how} “{passkey.get('name') or 'passkey'}” · {ip} · {ua[:80]}")
|
|
|
|
|
|
def _b(s: str) -> bytes:
|
|
try:
|
|
return unb64u(s)
|
|
except WebAuthnError:
|
|
raise HTTPException(400, "bad encoding") from None
|
|
|
|
|
|
@router.post("/api/remote/passkey/login/options", responses=_r(schemas.PasskeyOptions))
|
|
def passkey_login_options(deps: State, request: Request):
|
|
host = _guard(deps, request)
|
|
ticket, ch = _new_ticket(request, "login", host)
|
|
# No allowCredentials: the browser offers the owner's passkey for this
|
|
# site (or a phone's, by QR) without the page naming it.
|
|
return {"ticket": ticket, "publicKey": {
|
|
"challenge": b64u(ch), "rpId": host, "timeout": 120000,
|
|
"userVerification": "required", "allowCredentials": []}}
|
|
|
|
|
|
class AssertionBody(BaseModel):
|
|
ticket: str = Field(max_length=64)
|
|
id: str = Field(max_length=2048)
|
|
clientDataJSON: str = Field(max_length=8192)
|
|
authenticatorData: str = Field(max_length=8192)
|
|
signature: str = Field(max_length=2048)
|
|
userHandle: str | None = Field(default=None, max_length=256)
|
|
|
|
|
|
@router.post("/api/remote/passkey/login", responses=_r(schemas.OkResponse))
|
|
def passkey_login(deps: State, request: Request, response: Response, body: AssertionBody):
|
|
host = _guard(deps, request)
|
|
pend = _take(body.ticket, "login", host)
|
|
if pend is None:
|
|
raise HTTPException(409, {"message": tr(_lang(request), "the sign-in took too long — try again"),
|
|
"kind": "expired"})
|
|
cred = deps.owner_passkeys.get(body.id)
|
|
if cred is None:
|
|
_refuse(deps, request, f"unknown passkey {body.id[:24]}")
|
|
if body.userHandle and body.userHandle != deps.owner_passkeys.user_handle:
|
|
_refuse(deps, request, "user handle mismatch")
|
|
try:
|
|
count = verify_assertion(cred=cred, authenticator_data=_b(body.authenticatorData),
|
|
client_data_json=_b(body.clientDataJSON),
|
|
signature=_b(body.signature), challenge=pend["challenge"],
|
|
origin=f"https://{host}", rp_id=host)
|
|
except WebAuthnError as e:
|
|
_refuse(deps, request, f"passkey “{cred.get('name')}”: {e}")
|
|
deps.owner_passkeys.used(cred["id"], count)
|
|
_sign_in(deps, request, response, cred, "passkey")
|
|
return {"ok": True}
|
|
|
|
|
|
class InviteBody(BaseModel):
|
|
invite: str = Field(max_length=128)
|
|
|
|
|
|
@router.post("/api/remote/passkey/add/options", responses=_r(schemas.PasskeyOptions))
|
|
def passkey_add_options(deps: State, request: Request, body: InviteBody):
|
|
host = _guard(deps, request)
|
|
if not deps.owner_passkeys.invite_ok(body.invite):
|
|
worker_guests.bad_token(deps, request, "/api/remote/passkey/add")
|
|
raise HTTPException(410, {"message": tr(_lang(request), "this link has expired or was "
|
|
"already used — make a new one on the admin host"),
|
|
"kind": "invite_expired"})
|
|
ticket, ch = _new_ticket(request, "add", host, invite=_hash(body.invite))
|
|
return {"ticket": ticket, "publicKey": {
|
|
"challenge": b64u(ch), "rp": {"id": host, "name": "ai-agent"},
|
|
"user": {"id": deps.owner_passkeys.user_handle, "name": OWNER_NAME,
|
|
"displayName": OWNER_NAME},
|
|
"pubKeyCredParams": [{"type": "public-key", "alg": a} for a in ALGS],
|
|
"authenticatorSelection": {"residentKey": "required", "requireResidentKey": True,
|
|
"userVerification": "required"},
|
|
"attestation": "none", "timeout": 180000,
|
|
"excludeCredentials": [{"type": "public-key", "id": p["id"]}
|
|
for p in deps.owner_passkeys.all()]}}
|
|
|
|
|
|
class AttestationBody(BaseModel):
|
|
ticket: str = Field(max_length=64)
|
|
invite: str = Field(max_length=128)
|
|
id: str = Field(max_length=2048)
|
|
clientDataJSON: str = Field(max_length=8192)
|
|
attestationObject: str = Field(max_length=32768)
|
|
name: str = Field(default="", max_length=60)
|
|
|
|
|
|
@router.post("/api/remote/passkey/add", responses=_r(schemas.OkResponse))
|
|
def passkey_add(deps: State, request: Request, response: Response, body: AttestationBody):
|
|
host = _guard(deps, request)
|
|
pend = _take(body.ticket, "add", host)
|
|
if pend is None or not hmac.compare_digest(pend.get("invite", ""), _hash(body.invite)):
|
|
raise HTTPException(409, {"message": tr(_lang(request), "that took too long — try again"),
|
|
"kind": "expired"})
|
|
try:
|
|
cred = verify_registration(attestation_object=_b(body.attestationObject),
|
|
client_data_json=_b(body.clientDataJSON),
|
|
challenge=pend["challenge"], origin=f"https://{host}",
|
|
rp_id=host, credential_id=_b(body.id))
|
|
except WebAuthnError as e:
|
|
_refuse(deps, request, f"new passkey: {e}", status=400)
|
|
# Spent only now: a passkey prompt cancelled or refused keeps the link usable.
|
|
if not deps.owner_passkeys.spend_invite(body.invite):
|
|
raise HTTPException(410, {"message": tr(_lang(request), "this link has expired or was "
|
|
"already used — make a new one on the admin host"),
|
|
"kind": "invite_expired"})
|
|
try:
|
|
rec = deps.owner_passkeys.add(cred, body.name)
|
|
except ValueError as e:
|
|
raise HTTPException(409, str(e))
|
|
security.record(deps, "remote_passkey_added", who="owner", request=request,
|
|
detail=f"“{rec['name']}”" + (" (synced)" if rec.get("synced") else ""))
|
|
_sign_in(deps, request, response, rec, "new passkey")
|
|
return {"ok": True}
|
|
|
|
|
|
# ── the owner's side (Settings → Security) ───────────────────────────────────
|
|
@router.post("/api/remote/passkeys/invite", responses=_r(schemas.PasskeyInvite))
|
|
def passkey_invite(deps: State, request: Request, _: OwnerDep):
|
|
"""A one-time link that adds a passkey — made on the admin host only: a
|
|
session on the internet address can't give itself a lasting way back in."""
|
|
if not _on_admin_host(request):
|
|
raise HTTPException(403, "make the link on the admin host")
|
|
if not OWNER_HOSTS:
|
|
raise HTTPException(409, "no internet address set up here (OWNER_HOSTS)")
|
|
token, exp = deps.owner_passkeys.invite()
|
|
security.record(deps, "remote_passkey_invited", who="owner", request=request,
|
|
detail="a link to add a passkey (15 min)")
|
|
return {"url": f"https://{sorted(OWNER_HOSTS)[0]}/remote/add-passkey#{token}",
|
|
"expiresAt": exp}
|
|
|
|
|
|
@router.delete("/api/remote/passkeys/invite", responses=_r(schemas.RemoteAccess))
|
|
def passkey_invite_cancel(deps: State, request: Request, _: OwnerDep):
|
|
deps.owner_passkeys.cancel_invites()
|
|
return view(deps, request)
|
|
|
|
|
|
@router.delete("/api/remote/passkeys/{pid}", responses=_r(schemas.RemoteAccess))
|
|
def passkey_remove(deps: State, request: Request, _: OwnerDep, pid: str):
|
|
p = deps.owner_passkeys.get(pid)
|
|
if p is None or not deps.owner_passkeys.remove(pid):
|
|
raise HTTPException(404, "no such passkey")
|
|
# …and whatever it signed in: a passkey removed because it isn't his
|
|
# must not leave its sessions behind.
|
|
ended = deps.owner_sessions.close_passkey(pid)
|
|
security.record(deps, "remote_passkey_removed", who="owner", request=request,
|
|
detail=f"“{p.get('name')}”" + (f", {ended} session(s) ended" if ended else ""))
|
|
return view(deps, request)
|