mirror of
https://github.com/rommapp/romm.git
synced 2026-12-05 05:07:31 +01:00
fix(client-tokens): let a client token revoke itself without me.write (#5419)
* fix(client-tokens): let a client token revoke itself without me.write
A device that signs out or re-pairs had no way to revoke its own token
unless it held me.write, which also lets it mint tokens and approve
pairings. DELETE /api/client-tokens/{id} now skips the me.write check
when the id is the token authenticating the request.
Fixes #5274
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(client-tokens): code-review pass on self-revoke
Annotate raise_auth_error as NoReturn, trim the delete_token docstring, and
cover a me.write token revoking a sibling, the revoked token failing to
authenticate, and socket closure on self-revoke.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(client-tokens): revoke the calling token through DELETE /current
Self-revoke moves to an id-less route so a device never needs to know its
token id, and DELETE /{token_id} keeps me.write in its decorator and in
OpenAPI. The device-authorization token response now also returns token_id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(client-tokens): simplify pass, reuse raise_auth_error for /current
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* revert(client-tokens): drop DELETE /current and the device-flow token_id
Self-revoke stays on DELETE /{token_id} with the in-handler check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(device-auth): return the issued token's id from the device token poll
A device paired through the device-authorization flow can now revoke its
own token with DELETE /api/client-tokens/{id}, as tokens from /exchange can.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Update docs/BACKEND_ARCHITECTURE.md
* docs: format client tokens table
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
committed by
GitHub
parent
f10efbc625
commit
0f75e6aaf4
@@ -1,7 +1,7 @@
|
||||
import functools
|
||||
import inspect
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from typing import Any, NoReturn
|
||||
|
||||
from authlib.integrations.starlette_client import OAuth
|
||||
from authlib.oidc.discovery import get_well_known_url
|
||||
@@ -79,7 +79,7 @@ oauth.register(
|
||||
)
|
||||
|
||||
|
||||
def _raise_auth_error(request: Request) -> None:
|
||||
def raise_auth_error(request: Request) -> NoReturn:
|
||||
"""Raise the status matching the caller's auth state.
|
||||
|
||||
401 tells the client it has no valid credentials (so it can redirect to
|
||||
@@ -120,7 +120,7 @@ def _requires_scopes(
|
||||
request = kwargs.get("request", args[idx] if idx < len(args) else None)
|
||||
assert isinstance(request, Request)
|
||||
if not has_required_scope(request, scopes):
|
||||
_raise_auth_error(request)
|
||||
raise_auth_error(request)
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
return async_wrapper # type: ignore[return-value]
|
||||
@@ -130,7 +130,7 @@ def _requires_scopes(
|
||||
request = kwargs.get("request", args[idx] if idx < len(args) else None)
|
||||
assert isinstance(request, Request)
|
||||
if not has_required_scope(request, scopes):
|
||||
_raise_auth_error(request)
|
||||
raise_auth_error(request)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return sync_wrapper # type: ignore[return-value]
|
||||
|
||||
@@ -3,7 +3,7 @@ import json
|
||||
from fastapi import HTTPException, Request, status
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from decorators.auth import protected_route, raise_auth_error
|
||||
from endpoints.responses.client_token import (
|
||||
ClientTokenAdminSchema,
|
||||
ClientTokenCreateSchema,
|
||||
@@ -19,6 +19,7 @@ from handler.redis_handler import sync_cache
|
||||
from handler.socket_handler import close_client_token_sockets
|
||||
from models.audit_event import AuditAction, AuditTargetType
|
||||
from models.client_token import ClientToken
|
||||
from utils.auth import request_client_token_id
|
||||
from utils.client_tokens import (
|
||||
PAIR_CODE_TTL_SECONDS,
|
||||
build_admin_schema,
|
||||
@@ -97,8 +98,13 @@ def list_tokens(request: Request) -> list[ClientTokenSchema]:
|
||||
return [build_schema(t) for t in tokens]
|
||||
|
||||
|
||||
@protected_route(router.delete, "/{token_id}", [Scope.ME_WRITE])
|
||||
@protected_route(router.delete, "/{token_id}")
|
||||
async def delete_token(request: Request, token_id: int) -> None:
|
||||
"""Revoke one of the caller's tokens; a client token can always revoke itself."""
|
||||
is_self_revoke = token_id == request_client_token_id(request)
|
||||
if not is_self_revoke and Scope.ME_WRITE not in request.auth.scopes:
|
||||
raise_auth_error(request)
|
||||
|
||||
token = db_client_token_handler.get_token(
|
||||
token_id=token_id, user_id=request.user.id
|
||||
)
|
||||
|
||||
@@ -244,6 +244,7 @@ def approve(
|
||||
mark_approved(
|
||||
device_code,
|
||||
raw_token=raw_token,
|
||||
token_id=token.id,
|
||||
device_id=device.id,
|
||||
scopes=sorted(approved_set),
|
||||
expires_at=token.expires_at,
|
||||
@@ -345,6 +346,7 @@ def token(request: Request, payload: DeviceAuthTokenPayload) -> DeviceAuthTokenR
|
||||
f"device_code_prefix={_device_code_prefix(payload.device_code)}"
|
||||
)
|
||||
return DeviceAuthTokenResponse(
|
||||
id=approved["token_id"],
|
||||
access_token=approved["raw_token"],
|
||||
device_id=approved["device_id"],
|
||||
scopes=list(approved.get("scopes", [])),
|
||||
|
||||
@@ -75,6 +75,7 @@ class DeviceAuthTokenPayload(BaseModel):
|
||||
|
||||
|
||||
class DeviceAuthTokenResponse(BaseModel):
|
||||
id: int
|
||||
access_token: str
|
||||
device_id: str
|
||||
scopes: list[str]
|
||||
|
||||
@@ -533,8 +533,23 @@ class TestToken:
|
||||
data = resp.json()
|
||||
assert data["access_token"].startswith("rmm_")
|
||||
assert data["device_id"] == approve.json()["device_id"]
|
||||
token = db_client_token_handler.get_token(token_id=data["id"])
|
||||
assert token is not None
|
||||
assert token.device_id == data["device_id"]
|
||||
assert set(data["scopes"]) == {"roms.read", "roms.user.write"}
|
||||
|
||||
def test_issued_token_revokes_itself_by_id(self, client, access_token: str):
|
||||
body = _authorize(client)
|
||||
_approve(client, access_token, body["user_code"], approved_scopes=["roms.read"])
|
||||
creds = _poll_token(client, body["device_code"]).json()
|
||||
|
||||
resp = client.delete(
|
||||
f"/api/client-tokens/{creds['id']}",
|
||||
headers={"Authorization": f"Bearer {creds['access_token']}"},
|
||||
)
|
||||
assert resp.status_code == status.HTTP_200_OK
|
||||
assert db_client_token_handler.get_token(token_id=creds["id"]) is None
|
||||
|
||||
def test_one_shot_second_poll_returns_expired_token(
|
||||
self, client, access_token: str
|
||||
):
|
||||
|
||||
@@ -410,6 +410,49 @@ class TestClientTokenScopeCeiling:
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
|
||||
class TestClientTokenSelfRevoke:
|
||||
def test_a_token_revokes_itself_without_me_write(self, client, admin_user):
|
||||
token, raw = make_device_token(admin_user, None, scopes="roms.read")
|
||||
|
||||
response = client.delete(
|
||||
f"/api/client-tokens/{token.id}",
|
||||
headers={"Authorization": f"Bearer {raw}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert db_client_token_handler.get_token(token_id=token.id) is None
|
||||
after = client.get("/api/platforms", headers={"Authorization": f"Bearer {raw}"})
|
||||
assert after.status_code == status.HTTP_401_UNAUTHORIZED
|
||||
|
||||
def test_a_token_with_me_write_revokes_a_sibling(self, client, admin_user):
|
||||
_, raw = make_device_token(admin_user, None, scopes="me.write roms.read")
|
||||
sibling, _ = make_device_token(admin_user, None, scopes="roms.read")
|
||||
|
||||
response = client.delete(
|
||||
f"/api/client-tokens/{sibling.id}",
|
||||
headers={"Authorization": f"Bearer {raw}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert db_client_token_handler.get_token(token_id=sibling.id) is None
|
||||
|
||||
def test_a_token_cannot_revoke_a_sibling_without_me_write(self, client, admin_user):
|
||||
_, raw = make_device_token(admin_user, None, scopes="roms.read")
|
||||
sibling, _ = make_device_token(admin_user, None, scopes="roms.read")
|
||||
|
||||
response = client.delete(
|
||||
f"/api/client-tokens/{sibling.id}",
|
||||
headers={"Authorization": f"Bearer {raw}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert db_client_token_handler.get_token(token_id=sibling.id)
|
||||
|
||||
def test_an_anonymous_caller_is_unauthorized(self, client, admin_user):
|
||||
token, _ = make_device_token(admin_user, None, scopes="roms.read")
|
||||
|
||||
response = client.delete(f"/api/client-tokens/{token.id}")
|
||||
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
||||
assert db_client_token_handler.get_token(token_id=token.id)
|
||||
|
||||
|
||||
class TestClientTokenUserIsolation:
|
||||
def test_list_only_own_tokens(
|
||||
self,
|
||||
@@ -841,6 +884,17 @@ class TestRevocationClosesDeviceSockets:
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
close.assert_awaited_once_with([token_id])
|
||||
|
||||
def test_a_token_revoking_itself(self, client, admin_user, close):
|
||||
token, raw = make_device_token(admin_user, None, scopes="devices.read")
|
||||
|
||||
response = client.delete(
|
||||
f"/api/client-tokens/{token.id}",
|
||||
headers={"Authorization": f"Bearer {raw}"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
close.assert_awaited_once_with([token.id])
|
||||
|
||||
def test_regenerating_a_token(self, client, headers, token_id, close):
|
||||
response = client.put(
|
||||
f"/api/client-tokens/{token_id}/regenerate", headers=headers
|
||||
|
||||
@@ -24,6 +24,11 @@ def token_device_id(conn: HTTPConnection) -> str | None:
|
||||
return getattr(conn.state, "device_id", None)
|
||||
|
||||
|
||||
def request_client_token_id(conn: HTTPConnection) -> int | None:
|
||||
"""The id of the client token that authenticated the request, if any."""
|
||||
return getattr(conn.state, "client_token_id", None)
|
||||
|
||||
|
||||
def current_device_id(conn: HTTPConnection) -> str | None:
|
||||
"""The device a request comes from: its client token's, else its web session's."""
|
||||
return token_device_id(conn) or (conn.scope.get("session") or {}).get("device_id")
|
||||
|
||||
@@ -149,6 +149,7 @@ def mark_approved(
|
||||
device_code: str,
|
||||
*,
|
||||
raw_token: str,
|
||||
token_id: int,
|
||||
device_id: str,
|
||||
scopes: list[str],
|
||||
expires_at: datetime | None,
|
||||
@@ -160,6 +161,7 @@ def mark_approved(
|
||||
approved = {
|
||||
"status": FlowStatus.APPROVED,
|
||||
"raw_token": raw_token,
|
||||
"token_id": token_id,
|
||||
"device_id": device_id,
|
||||
"scopes": scopes,
|
||||
"expires_at": expires_at.isoformat() if expires_at else None,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type DeviceAuthTokenResponse = {
|
||||
id: number;
|
||||
access_token: string;
|
||||
device_id: string;
|
||||
scopes: Array<string>;
|
||||
|
||||
Reference in New Issue
Block a user