Archived
feat: add device passkeys for operator access (Closes #485)
This commit is contained in:
1 parent
131848cc43
commit
ced644b275
15 files changed
+1228
-33
No files matched your search
+306
-1
@@ -21,7 +21,7 @@ from fastapi.responses import JSONResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field, PositiveInt, field_validator, model_validator
|
||||
|
||||
from src import dashboard_auth, gitea_proxy
|
||||
from src import dashboard_auth, gitea_proxy, passkeys
|
||||
from src.available_issue_snapshot_store import AvailableIssueSnapshotStore
|
||||
from src.compression import NegotiatedGZipMiddleware
|
||||
from src.gitea_proxy import (
|
||||
@@ -40,6 +40,7 @@ from src.idempotency import IdempotencyLedger, IdempotencyLedgerBusy
|
||||
from src.login_attempt_store import LoginAttemptStore, LoginAttemptStoreError, client_source
|
||||
from src.live_snapshot_store import LiveSnapshotState, LiveSnapshotStore, RefreshLeaseLost
|
||||
from src.models import Issue, Milestone, PullRequest, Repo, User
|
||||
from src.passkey_store import PasskeyStore
|
||||
from src.request_boundary import RequestBodyLimitMiddleware, request_body_limit
|
||||
from src.suggestion_engine import compute
|
||||
from src.later_store import LaterStore
|
||||
@@ -199,12 +200,57 @@ class DashboardSignIn(BaseModel):
|
||||
|
||||
class FreshAuthorization(BaseModel):
|
||||
access_token: str = Field(min_length=1, max_length=1_024)
|
||||
action: Literal[
|
||||
"merge_pull",
|
||||
"close_issue",
|
||||
"revoke_device",
|
||||
"revoke_all_sessions",
|
||||
"enroll_passkey",
|
||||
]
|
||||
target: str = Field(min_length=1, max_length=255)
|
||||
|
||||
|
||||
class PasskeyCeremony(BaseModel):
|
||||
challenge: str = Field(min_length=20, max_length=200)
|
||||
credential: dict = Field()
|
||||
|
||||
|
||||
class PasskeyAuthentication(PasskeyCeremony):
|
||||
device_label: str = Field(default="This device", min_length=1, max_length=64)
|
||||
action: Literal[
|
||||
"sign_in", "merge_pull", "close_issue", "revoke_device", "revoke_all_sessions"
|
||||
] = "sign_in"
|
||||
target: str = Field(default="dashboard", min_length=1, max_length=255)
|
||||
|
||||
|
||||
class PasskeyAuthorizationTarget(BaseModel):
|
||||
action: Literal[
|
||||
"merge_pull", "close_issue", "revoke_device", "revoke_all_sessions"
|
||||
]
|
||||
target: str = Field(min_length=1, max_length=255)
|
||||
|
||||
|
||||
class PasskeyAuthorization(PasskeyCeremony, PasskeyAuthorizationTarget):
|
||||
pass
|
||||
|
||||
|
||||
def _passkey_store() -> PasskeyStore:
|
||||
state_dir = os.getenv("STACKCHAIN_STATE_DIR", ".stackchain-state")
|
||||
database = os.getenv(
|
||||
"STACKCHAIN_SESSION_DB", os.path.join(state_dir, "sessions.sqlite3")
|
||||
)
|
||||
return PasskeyStore(database, clock=time.time)
|
||||
|
||||
|
||||
def _passkey_relying_party(request: Request) -> tuple[str, str]:
|
||||
rp_id = os.getenv("STACKCHAIN_PASSKEY_RP_ID", request.url.hostname or "")
|
||||
origin = os.getenv(
|
||||
"STACKCHAIN_PASSKEY_ORIGIN",
|
||||
f"{request.url.scheme}://{request.url.netloc}",
|
||||
)
|
||||
return rp_id, origin
|
||||
|
||||
|
||||
def _login_attempt_store() -> LoginAttemptStore:
|
||||
state_dir = os.getenv("STACKCHAIN_STATE_DIR", ".stackchain-state")
|
||||
return LoginAttemptStore(
|
||||
@@ -696,6 +742,13 @@ async def require_operator_session(request: Request, call_next):
|
||||
}
|
||||
or path.startswith("/static/")
|
||||
or (path == "/api/v1/session" and request.method == "POST")
|
||||
or (
|
||||
path in {
|
||||
"/api/v1/passkeys/authentication/options",
|
||||
"/api/v1/passkeys/authentication/verify",
|
||||
}
|
||||
and request.method == "POST"
|
||||
)
|
||||
)
|
||||
session = None
|
||||
session_reason = None
|
||||
@@ -969,6 +1022,256 @@ async def fresh_authorization(payload: FreshAuthorization, request: Request):
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/passkeys/registration/options", status_code=201)
|
||||
async def create_passkey_registration_options(
|
||||
request: Request,
|
||||
step_up_grant: str | None = Header(
|
||||
default=None, alias="X-Step-Up-Grant", max_length=128
|
||||
),
|
||||
):
|
||||
await _require_step_up(
|
||||
request,
|
||||
step_up_grant,
|
||||
action="enroll_passkey",
|
||||
target="current_device",
|
||||
)
|
||||
rp_id, _origin = _passkey_relying_party(request)
|
||||
store = _passkey_store()
|
||||
existing = await asyncio.to_thread(store.all)
|
||||
options, challenge = passkeys.registration_options(
|
||||
rp_id=rp_id,
|
||||
excluded=[item.credential_id for item in existing],
|
||||
)
|
||||
await asyncio.to_thread(
|
||||
store.issue_challenge,
|
||||
challenge,
|
||||
session_id=request.state.dashboard_session.session_id,
|
||||
purpose="registration",
|
||||
action="enroll_passkey",
|
||||
target="current_device",
|
||||
)
|
||||
return JSONResponse(
|
||||
options,
|
||||
status_code=201,
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/passkeys/registration/verify", status_code=201)
|
||||
async def verify_passkey_registration(payload: PasskeyCeremony, request: Request):
|
||||
try:
|
||||
challenge = passkeys.decode(payload.challenge)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(status_code=400, detail="Invalid passkey ceremony")
|
||||
store = _passkey_store()
|
||||
valid = await asyncio.to_thread(
|
||||
store.consume_challenge,
|
||||
challenge,
|
||||
session_id=request.state.dashboard_session.session_id,
|
||||
purpose="registration",
|
||||
action="enroll_passkey",
|
||||
target="current_device",
|
||||
)
|
||||
if not valid:
|
||||
raise HTTPException(status_code=409, detail="Passkey challenge expired or already used")
|
||||
rp_id, origin = _passkey_relying_party(request)
|
||||
try:
|
||||
verified = await asyncio.to_thread(
|
||||
passkeys.verify_registration,
|
||||
credential=payload.credential,
|
||||
challenge=challenge,
|
||||
rp_id=rp_id,
|
||||
origin=origin,
|
||||
)
|
||||
devices = await dashboard_auth.active_devices(request.state.dashboard_session)
|
||||
current = next(device for device in devices if device.current)
|
||||
await asyncio.to_thread(
|
||||
store.register,
|
||||
credential_id=verified.credential_id,
|
||||
public_key=verified.credential_public_key,
|
||||
sign_count=verified.sign_count,
|
||||
device_label=current.device_label,
|
||||
management_id=current.management_id,
|
||||
)
|
||||
except dashboard_auth.SessionStoreError:
|
||||
raise HTTPException(status_code=503, detail="Passkey registry is temporarily unavailable")
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail="Passkey verification failed") from exc
|
||||
return JSONResponse(
|
||||
{"enrolled": True}, status_code=201, headers={"Cache-Control": "no-store"}
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/passkeys/authentication/options")
|
||||
async def create_passkey_authentication_options(request: Request):
|
||||
store = _passkey_store()
|
||||
credentials = await asyncio.to_thread(store.all)
|
||||
if not credentials:
|
||||
raise HTTPException(status_code=404, detail="No passkeys enrolled")
|
||||
rp_id, _origin = _passkey_relying_party(request)
|
||||
options, challenge = passkeys.authentication_options(
|
||||
rp_id=rp_id,
|
||||
credentials=[item.credential_id for item in credentials],
|
||||
)
|
||||
await asyncio.to_thread(
|
||||
store.issue_challenge,
|
||||
challenge,
|
||||
session_id=None,
|
||||
purpose="authentication",
|
||||
action="sign_in",
|
||||
target="dashboard",
|
||||
)
|
||||
return JSONResponse(options, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.post("/api/v1/passkeys/authorization/options")
|
||||
async def create_passkey_authorization_options(
|
||||
payload: PasskeyAuthorizationTarget, request: Request
|
||||
):
|
||||
store = _passkey_store()
|
||||
credentials = await asyncio.to_thread(store.all)
|
||||
if not credentials:
|
||||
raise HTTPException(status_code=404, detail="No passkeys enrolled")
|
||||
rp_id, _origin = _passkey_relying_party(request)
|
||||
options, challenge = passkeys.authentication_options(
|
||||
rp_id=rp_id,
|
||||
credentials=[item.credential_id for item in credentials],
|
||||
)
|
||||
await asyncio.to_thread(
|
||||
store.issue_challenge,
|
||||
challenge,
|
||||
session_id=request.state.dashboard_session.session_id,
|
||||
purpose="authorization",
|
||||
action=payload.action,
|
||||
target=payload.target,
|
||||
)
|
||||
return JSONResponse(options, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.post("/api/v1/passkeys/authorization/verify", status_code=201)
|
||||
async def verify_passkey_authorization(
|
||||
payload: PasskeyAuthorization, request: Request
|
||||
):
|
||||
try:
|
||||
challenge = passkeys.decode(payload.challenge)
|
||||
credential_id = passkeys.decode(str(payload.credential.get("id", "")))
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(status_code=400, detail="Invalid passkey ceremony")
|
||||
store = _passkey_store()
|
||||
valid = await asyncio.to_thread(
|
||||
store.consume_challenge,
|
||||
challenge,
|
||||
session_id=request.state.dashboard_session.session_id,
|
||||
purpose="authorization",
|
||||
action=payload.action,
|
||||
target=payload.target,
|
||||
)
|
||||
stored = await asyncio.to_thread(store.get, credential_id)
|
||||
if not valid or stored is None:
|
||||
raise HTTPException(status_code=409, detail="Passkey challenge expired or already used")
|
||||
rp_id, origin = _passkey_relying_party(request)
|
||||
try:
|
||||
verified = await asyncio.to_thread(
|
||||
passkeys.verify_authentication,
|
||||
credential=payload.credential,
|
||||
challenge=challenge,
|
||||
rp_id=rp_id,
|
||||
origin=origin,
|
||||
stored=stored,
|
||||
)
|
||||
updated = await asyncio.to_thread(
|
||||
store.update_counter, stored.credential_id, verified.new_sign_count
|
||||
)
|
||||
if not updated:
|
||||
raise ValueError("stale passkey counter")
|
||||
grant = await dashboard_auth.issue_step_up(
|
||||
request.state.dashboard_session,
|
||||
action=payload.action,
|
||||
target=payload.target,
|
||||
)
|
||||
except dashboard_auth.SessionStoreError:
|
||||
raise HTTPException(status_code=503, detail="Passkey registry is temporarily unavailable")
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=401, detail="Passkey authorization failed") from exc
|
||||
return JSONResponse(
|
||||
{"grant": grant, "expires_in": dashboard_auth.STEP_UP_TTL_SECONDS},
|
||||
status_code=201,
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/passkeys/authentication/verify")
|
||||
async def verify_passkey_authentication(
|
||||
payload: PasskeyAuthentication, request: Request, response: Response
|
||||
):
|
||||
if payload.action != "sign_in" or payload.target != "dashboard":
|
||||
raise HTTPException(status_code=400, detail="Invalid passkey sign-in target")
|
||||
try:
|
||||
challenge = passkeys.decode(payload.challenge)
|
||||
credential_id = passkeys.decode(str(payload.credential.get("id", "")))
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(status_code=400, detail="Invalid passkey ceremony")
|
||||
store = _passkey_store()
|
||||
valid = await asyncio.to_thread(
|
||||
store.consume_challenge,
|
||||
challenge,
|
||||
session_id=None,
|
||||
purpose="authentication",
|
||||
action="sign_in",
|
||||
target="dashboard",
|
||||
)
|
||||
stored = await asyncio.to_thread(store.get, credential_id)
|
||||
if not valid or stored is None:
|
||||
raise HTTPException(status_code=401, detail="Passkey sign-in failed")
|
||||
rp_id, origin = _passkey_relying_party(request)
|
||||
try:
|
||||
verified = await asyncio.to_thread(
|
||||
passkeys.verify_authentication,
|
||||
credential=payload.credential,
|
||||
challenge=challenge,
|
||||
rp_id=rp_id,
|
||||
origin=origin,
|
||||
stored=stored,
|
||||
)
|
||||
updated = await asyncio.to_thread(
|
||||
store.update_counter, stored.credential_id, verified.new_sign_count
|
||||
)
|
||||
if not updated:
|
||||
raise ValueError("stale passkey counter")
|
||||
await dashboard_auth.revoke_managed_session(stored.management_id)
|
||||
signed, session = await asyncio.to_thread(
|
||||
dashboard_auth.issue_session,
|
||||
device_label=stored.device_label,
|
||||
management_id=stored.management_id,
|
||||
)
|
||||
except dashboard_auth.SessionStoreError:
|
||||
raise HTTPException(status_code=503, detail="Passkey registry is temporarily unavailable")
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=401, detail="Passkey sign-in failed") from exc
|
||||
path = dashboard_auth.cookie_path(request)
|
||||
max_age = max(1, session.expires_at - int(time.time()))
|
||||
response.set_cookie(
|
||||
dashboard_auth.SESSION_COOKIE,
|
||||
signed,
|
||||
max_age=max_age,
|
||||
path=path,
|
||||
secure=True,
|
||||
httponly=True,
|
||||
samesite="strict",
|
||||
)
|
||||
response.set_cookie(
|
||||
dashboard_auth.CSRF_COOKIE,
|
||||
session.csrf,
|
||||
max_age=max_age,
|
||||
path=path,
|
||||
secure=True,
|
||||
httponly=False,
|
||||
samesite="strict",
|
||||
)
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return {"authenticated": True, "method": "passkey"}
|
||||
|
||||
|
||||
@app.get("/api/v1/session")
|
||||
async def session_status(request: Request):
|
||||
session = request.state.dashboard_session
|
||||
@@ -1196,6 +1499,7 @@ async def revoke_active_device(
|
||||
target = next(
|
||||
(device for device in devices if device.management_id == management_id), None
|
||||
)
|
||||
await asyncio.to_thread(_passkey_store().revoke_management_id, management_id)
|
||||
revoked = await dashboard_auth.revoke_managed_session(management_id)
|
||||
except dashboard_auth.SessionStoreError:
|
||||
return JSONResponse(
|
||||
@@ -1223,6 +1527,7 @@ async def sign_out_all_devices(
|
||||
target="all",
|
||||
)
|
||||
try:
|
||||
await asyncio.to_thread(_passkey_store().revoke_all)
|
||||
await dashboard_auth.revoke_all_sessions()
|
||||
except dashboard_auth.SessionStoreError:
|
||||
return JSONResponse(
|
||||
|
||||
Reference in new issue
Block a user