diff --git a/backend/decorators/auth.py b/backend/decorators/auth.py index 7b0de7e63..628bc9ce5 100644 --- a/backend/decorators/auth.py +++ b/backend/decorators/auth.py @@ -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] diff --git a/backend/endpoints/client_tokens.py b/backend/endpoints/client_tokens.py index c7f671c03..5bdb9c82e 100644 --- a/backend/endpoints/client_tokens.py +++ b/backend/endpoints/client_tokens.py @@ -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 ) diff --git a/backend/endpoints/device/auth.py b/backend/endpoints/device/auth.py index 2baad6ed5..349e604cf 100644 --- a/backend/endpoints/device/auth.py +++ b/backend/endpoints/device/auth.py @@ -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", [])), diff --git a/backend/endpoints/responses/device/auth.py b/backend/endpoints/responses/device/auth.py index 079462476..17d7d803f 100644 --- a/backend/endpoints/responses/device/auth.py +++ b/backend/endpoints/responses/device/auth.py @@ -75,6 +75,7 @@ class DeviceAuthTokenPayload(BaseModel): class DeviceAuthTokenResponse(BaseModel): + id: int access_token: str device_id: str scopes: list[str] diff --git a/backend/tests/endpoints/device/test_auth.py b/backend/tests/endpoints/device/test_auth.py index 0d80ca8cb..8919e1715 100644 --- a/backend/tests/endpoints/device/test_auth.py +++ b/backend/tests/endpoints/device/test_auth.py @@ -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 ): diff --git a/backend/tests/endpoints/test_client_tokens.py b/backend/tests/endpoints/test_client_tokens.py index 4388d0933..41d8f2bbe 100644 --- a/backend/tests/endpoints/test_client_tokens.py +++ b/backend/tests/endpoints/test_client_tokens.py @@ -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 diff --git a/backend/utils/auth.py b/backend/utils/auth.py index 8581f0528..163654806 100644 --- a/backend/utils/auth.py +++ b/backend/utils/auth.py @@ -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") diff --git a/backend/utils/device_auth.py b/backend/utils/device_auth.py index 078d5626a..e57e1ae63 100644 --- a/backend/utils/device_auth.py +++ b/backend/utils/device_auth.py @@ -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, diff --git a/frontend/src/__generated__/models/DeviceAuthTokenResponse.ts b/frontend/src/__generated__/models/DeviceAuthTokenResponse.ts index 99bd2bb4a..d3e599fa2 100644 --- a/frontend/src/__generated__/models/DeviceAuthTokenResponse.ts +++ b/frontend/src/__generated__/models/DeviceAuthTokenResponse.ts @@ -3,6 +3,7 @@ /* tslint:disable */ /* eslint-disable */ export type DeviceAuthTokenResponse = { + id: number; access_token: string; device_id: string; scopes: Array;