diff --git a/.changeset/token-source.md b/.changeset/token-source.md new file mode 100644 index 00000000..0c726c0a --- /dev/null +++ b/.changeset/token-source.md @@ -0,0 +1,5 @@ +--- +"livekit-api": minor +--- + +Add a `token_source` option on `LiveKitAPI` that supplies a token for the claims of each call, in place of an API key and secret. Add `AccessToken.to_claims_json()`, which returns those claims as JSON. diff --git a/livekit-api/livekit/api/__init__.py b/livekit-api/livekit/api/__init__.py index 0e307fbd..e31f6aeb 100644 --- a/livekit-api/livekit/api/__init__.py +++ b/livekit-api/livekit/api/__init__.py @@ -44,6 +44,7 @@ TwirpErrorCode, ) from .livekit_api import LiveKitAPI +from ._service import TokenSource from .access_token import ( InferenceGrants, ObservabilityGrants, @@ -61,6 +62,7 @@ __all__ = [ "LiveKitAPI", + "TokenSource", "room_service", "egress_service", "ingress_service", diff --git a/livekit-api/livekit/api/_service.py b/livekit-api/livekit/api/_service.py index 6e3394aa..6d63a9db 100644 --- a/livekit-api/livekit/api/_service.py +++ b/livekit-api/livekit/api/_service.py @@ -2,11 +2,19 @@ import aiohttp from abc import ABC +from typing import Awaitable, Callable from .twirp_client import TwirpClient -from .access_token import AccessToken, VideoGrants, SIPGrants +from .access_token import AccessToken, Claims, VideoGrants, SIPGrants AUTHORIZATION = "authorization" +TokenSource = Callable[[Claims], Awaitable[str]] +"""Returns a token that carries the given claims. + +`LiveKitAPI` calls it before each request, in place of signing a token with an API +key and secret, with the claims that request needs. It may cache tokens. +""" + class Service(ABC): def __init__( @@ -23,14 +31,20 @@ def __init__( # A pre-signed token set by LiveKitAPI for token auth; sent verbatim, # skipping per-call signing. Per-service constructors stay key/secret-only. self._token: str | None = None + # Set by LiveKitAPI to get a token per call in place of signing one. + self._token_source: TokenSource | None = None - def _auth_header( + async def _auth_header( self, grants: VideoGrants | None, sip: SIPGrants | None = None ) -> dict[str, str]: # A pre-signed token is sent verbatim; the caller is responsible for its grants. if self._token: return {AUTHORIZATION: "Bearer {}".format(self._token)} + if self._token_source is not None: + token = await self._token_source(Claims(video=grants, sip=sip)) + return {AUTHORIZATION: "Bearer {}".format(token)} + tok = AccessToken(self.api_key, self.api_secret) if grants: tok.with_grants(grants) diff --git a/livekit-api/livekit/api/access_token.py b/livekit-api/livekit/api/access_token.py index d0274f11..22498380 100644 --- a/livekit-api/livekit/api/access_token.py +++ b/livekit-api/livekit/api/access_token.py @@ -15,6 +15,7 @@ import calendar import re import datetime +import json import os import jwt import dataclasses @@ -185,14 +186,9 @@ def __init__( api_key: Optional[str] = None, api_secret: Optional[str] = None, ) -> None: - api_key = api_key or os.getenv("LIVEKIT_API_KEY") - api_secret = api_secret or os.getenv("LIVEKIT_API_SECRET") - - if not api_key or not api_secret: - raise ValueError("api_key and api_secret must be set") - - self.api_key = api_key # iss - self.api_secret = api_secret + # the key and secret are checked in to_jwt, so that to_claims_json works without them + self.api_key = api_key or os.getenv("LIVEKIT_API_KEY") or "" # iss + self.api_secret = api_secret or os.getenv("LIVEKIT_API_SECRET") or "" self.claims = Claims() # default jwt claims @@ -267,7 +263,23 @@ def with_room_config(self, config: RoomConfiguration) -> "AccessToken": self.claims.room_config = config return self + def to_claims_json(self) -> str: + """Returns the claims of this token as JSON, without signing them. + + The JSON has the shape of the payload `to_jwt` signs, without the claims the + signer sets (iss, sub, nbf, exp); the identity is in `identity`. It needs no + API key or secret, so a process without them can send it to a server that + signs the token, such as in `CreateJobTokenRequest.claims`. + """ + claims = self.claims.asdict() + if self.identity: + claims["identity"] = self.identity + return json.dumps(claims) + def to_jwt(self) -> str: + if not self.api_key or not self.api_secret: + raise ValueError("api_key and api_secret must be set") + video = self.claims.video if video and video.room_join and (not self.identity or not video.room): raise ValueError("identity and room must be set when joining a room") diff --git a/livekit-api/livekit/api/agent_dispatch_service.py b/livekit-api/livekit/api/agent_dispatch_service.py index d014e6d0..dfd4dec6 100644 --- a/livekit-api/livekit/api/agent_dispatch_service.py +++ b/livekit-api/livekit/api/agent_dispatch_service.py @@ -53,7 +53,7 @@ async def create_dispatch(self, req: CreateAgentDispatchRequest) -> AgentDispatc SVC, "CreateDispatch", req, - self._auth_header(VideoGrants(room_admin=True, room=req.room)), + await self._auth_header(VideoGrants(room_admin=True, room=req.room)), AgentDispatch, ) @@ -74,7 +74,7 @@ async def delete_dispatch(self, dispatch_id: str, room_name: str) -> AgentDispat dispatch_id=dispatch_id, room=room_name, ), - self._auth_header(VideoGrants(room_admin=True, room=room_name)), + await self._auth_header(VideoGrants(room_admin=True, room=room_name)), AgentDispatch, ) @@ -91,7 +91,7 @@ async def list_dispatch(self, room_name: str) -> list[AgentDispatch]: SVC, "ListDispatch", ListAgentDispatchRequest(room=room_name), - self._auth_header(VideoGrants(room_admin=True, room=room_name)), + await self._auth_header(VideoGrants(room_admin=True, room=room_name)), ListAgentDispatchResponse, ) return list(res.agent_dispatches) @@ -110,7 +110,7 @@ async def get_dispatch(self, dispatch_id: str, room_name: str) -> Optional[Agent SVC, "ListDispatch", ListAgentDispatchRequest(dispatch_id=dispatch_id, room=room_name), - self._auth_header(VideoGrants(room_admin=True, room=room_name)), + await self._auth_header(VideoGrants(room_admin=True, room=room_name)), ListAgentDispatchResponse, ) if len(res.agent_dispatches) > 0: diff --git a/livekit-api/livekit/api/connector_service.py b/livekit-api/livekit/api/connector_service.py index 4f5c09c9..a5ec11d1 100644 --- a/livekit-api/livekit/api/connector_service.py +++ b/livekit-api/livekit/api/connector_service.py @@ -63,7 +63,7 @@ async def dial_whatsapp_call( SVC, "DialWhatsAppCall", request, - self._auth_header(VideoGrants(room_create=True)), + await self._auth_header(VideoGrants(room_create=True)), DialWhatsAppCallResponse, ) @@ -83,7 +83,7 @@ async def disconnect_whatsapp_call( SVC, "DisconnectWhatsAppCall", request, - self._auth_header(VideoGrants(room_create=True)), + await self._auth_header(VideoGrants(room_create=True)), DisconnectWhatsAppCallResponse, ) @@ -103,7 +103,7 @@ async def connect_whatsapp_call( SVC, "ConnectWhatsAppCall", request, - self._auth_header(VideoGrants(room_create=True)), + await self._auth_header(VideoGrants(room_create=True)), ConnectWhatsAppCallResponse, ) @@ -140,7 +140,7 @@ async def accept_whatsapp_call( SVC, "AcceptWhatsAppCall", request, - self._auth_header(VideoGrants(room_create=True)), + await self._auth_header(VideoGrants(room_create=True)), AcceptWhatsAppCallResponse, timeout=client_timeout, ) @@ -161,6 +161,6 @@ async def connect_twilio_call( SVC, "ConnectTwilioCall", request, - self._auth_header(VideoGrants(room_create=True)), + await self._auth_header(VideoGrants(room_create=True)), ConnectTwilioCallResponse, ) diff --git a/livekit-api/livekit/api/egress_service.py b/livekit-api/livekit/api/egress_service.py index 5a3065f2..76dce7f7 100644 --- a/livekit-api/livekit/api/egress_service.py +++ b/livekit-api/livekit/api/egress_service.py @@ -50,7 +50,7 @@ async def start_room_composite_egress(self, start: RoomCompositeEgressRequest) - SVC, "StartRoomCompositeEgress", start, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) @@ -60,7 +60,7 @@ async def start_web_egress(self, start: WebEgressRequest) -> EgressInfo: SVC, "StartWebEgress", start, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) @@ -70,7 +70,7 @@ async def start_participant_egress(self, start: ParticipantEgressRequest) -> Egr SVC, "StartParticipantEgress", start, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) @@ -80,7 +80,7 @@ async def start_track_composite_egress(self, start: TrackCompositeEgressRequest) SVC, "StartTrackCompositeEgress", start, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) @@ -90,7 +90,7 @@ async def start_track_egress(self, start: TrackEgressRequest) -> EgressInfo: SVC, "StartTrackEgress", start, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) @@ -100,7 +100,7 @@ async def start_egress(self, start: StartEgressRequest) -> EgressInfo: SVC, "StartEgress", start, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) @@ -110,7 +110,7 @@ async def update_layout(self, update: UpdateLayoutRequest) -> EgressInfo: SVC, "UpdateLayout", update, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) @@ -120,7 +120,7 @@ async def update_stream(self, update: UpdateStreamRequest) -> EgressInfo: SVC, "UpdateStream", update, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) @@ -137,7 +137,7 @@ async def list_egress(self, list: ListEgressRequest) -> ListEgressResponse: SVC, "ListEgress", list, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), ListEgressResponse, ) @@ -147,6 +147,6 @@ async def stop_egress(self, stop: StopEgressRequest) -> EgressInfo: SVC, "StopEgress", stop, - self._auth_header(VideoGrants(room_record=True)), + await self._auth_header(VideoGrants(room_record=True)), EgressInfo, ) diff --git a/livekit-api/livekit/api/ingress_service.py b/livekit-api/livekit/api/ingress_service.py index b29ce460..40d592b1 100644 --- a/livekit-api/livekit/api/ingress_service.py +++ b/livekit-api/livekit/api/ingress_service.py @@ -43,7 +43,7 @@ async def create_ingress(self, create: CreateIngressRequest) -> IngressInfo: SVC, "CreateIngress", create, - self._auth_header(VideoGrants(ingress_admin=True)), + await self._auth_header(VideoGrants(ingress_admin=True)), IngressInfo, ) @@ -52,7 +52,7 @@ async def update_ingress(self, update: UpdateIngressRequest) -> IngressInfo: SVC, "UpdateIngress", update, - self._auth_header(VideoGrants(ingress_admin=True)), + await self._auth_header(VideoGrants(ingress_admin=True)), IngressInfo, ) @@ -61,7 +61,7 @@ async def list_ingress(self, list: ListIngressRequest) -> ListIngressResponse: SVC, "ListIngress", list, - self._auth_header(VideoGrants(ingress_admin=True)), + await self._auth_header(VideoGrants(ingress_admin=True)), ListIngressResponse, ) @@ -70,6 +70,6 @@ async def delete_ingress(self, delete: DeleteIngressRequest) -> IngressInfo: SVC, "DeleteIngress", delete, - self._auth_header(VideoGrants(ingress_admin=True)), + await self._auth_header(VideoGrants(ingress_admin=True)), IngressInfo, ) diff --git a/livekit-api/livekit/api/livekit_api.py b/livekit-api/livekit/api/livekit_api.py index eec792f9..0eaa22fc 100644 --- a/livekit-api/livekit/api/livekit_api.py +++ b/livekit-api/livekit/api/livekit_api.py @@ -6,6 +6,7 @@ from .sip_service import SipService from .agent_dispatch_service import AgentDispatchService from .connector_service import ConnectorService +from ._service import TokenSource from typing import Any, Optional @@ -30,6 +31,7 @@ def __init__( api_secret: Optional[str] = None, *, token: Optional[str] = None, + token_source: Optional[TokenSource] = None, timeout: Optional[aiohttp.ClientTimeout] = None, session: Optional[aiohttp.ClientSession] = None, failover: bool = True, @@ -45,6 +47,8 @@ def __init__( api_key: API key (read from `LIVEKIT_API_KEY` environment variable if not provided) api_secret: API secret (read from `LIVEKIT_API_SECRET` environment variable if not provided) token: Pre-signed access token (read from `LIVEKIT_TOKEN` environment variable if not provided) + token_source: Async callable that returns a token for the claims of each call, + in place of signing one with api_key and api_secret timeout: Request timeout (default: 10 seconds) session: aiohttp.ClientSession instance to use for requests, if not provided, a new one will be created """ @@ -53,16 +57,19 @@ def __init__( # Only fall back to environment credentials when none were provided # explicitly, so an ambient LIVEKIT_TOKEN can't silently override an # explicit api_key/secret (or vice versa). - if not token and not api_key and not api_secret: + if not token and not token_source and not api_key and not api_secret: token = os.getenv("LIVEKIT_TOKEN") - if not token and not api_key and not api_secret: + if not token and not token_source and not api_key and not api_secret: api_key = os.getenv("LIVEKIT_API_KEY") api_secret = os.getenv("LIVEKIT_API_SECRET") if not url: raise ValueError("url must be set") - if not token and (not api_key or not api_secret): + if token and token_source: + raise ValueError("token and token_source cannot both be set") + + if not token and not token_source and (not api_key or not api_secret): raise ValueError("either token, or api_key and api_secret, must be set") self._custom_session = True @@ -84,7 +91,7 @@ def __init__( self._agent_dispatch = AgentDispatchService(self._session, url, key, secret, failover) self._connector = ConnectorService(self._session, url, key, secret, failover) - if token: + if token or token_source: for svc in ( self._room, self._ingress, @@ -94,6 +101,7 @@ def __init__( self._connector, ): svc._token = token + svc._token_source = token_source @classmethod def with_token( diff --git a/livekit-api/livekit/api/room_service.py b/livekit-api/livekit/api/room_service.py index e3cb7bb6..7981c364 100644 --- a/livekit-api/livekit/api/room_service.py +++ b/livekit-api/livekit/api/room_service.py @@ -79,7 +79,7 @@ async def create_room( SVC, "CreateRoom", create, - self._auth_header(VideoGrants(room_create=True)), + await self._auth_header(VideoGrants(room_create=True)), Room, ) @@ -98,7 +98,7 @@ async def list_rooms(self, list: ListRoomsRequest) -> ListRoomsResponse: SVC, "ListRooms", list, - self._auth_header(VideoGrants(room_list=True)), + await self._auth_header(VideoGrants(room_list=True)), ListRoomsResponse, ) @@ -116,7 +116,7 @@ async def delete_room(self, delete: DeleteRoomRequest) -> DeleteRoomResponse: SVC, "DeleteRoom", delete, - self._auth_header(VideoGrants(room_create=True)), + await self._auth_header(VideoGrants(room_create=True)), DeleteRoomResponse, ) @@ -135,7 +135,7 @@ async def update_room_metadata(self, update: UpdateRoomMetadataRequest) -> Room: SVC, "UpdateRoomMetadata", update, - self._auth_header(VideoGrants(room_admin=True, room=update.room)), + await self._auth_header(VideoGrants(room_admin=True, room=update.room)), Room, ) @@ -154,7 +154,7 @@ async def list_participants(self, list: ListParticipantsRequest) -> ListParticip SVC, "ListParticipants", list, - self._auth_header(VideoGrants(room_admin=True, room=list.room)), + await self._auth_header(VideoGrants(room_admin=True, room=list.room)), ListParticipantsResponse, ) @@ -183,7 +183,7 @@ async def get_participant(self, get: RoomParticipantIdentity) -> ParticipantInfo SVC, "GetParticipant", get, - self._auth_header(VideoGrants(room_admin=True, room=get.room)), + await self._auth_header(VideoGrants(room_admin=True, room=get.room)), ParticipantInfo, ) @@ -204,7 +204,7 @@ async def remove_participant( SVC, "RemoveParticipant", remove, - self._auth_header(VideoGrants(room_admin=True, room=remove.room)), + await self._auth_header(VideoGrants(room_admin=True, room=remove.room)), RemoveParticipantResponse, ) @@ -224,7 +224,7 @@ async def forward_participant(self, forward: ForwardParticipantRequest) -> None: SVC, "ForwardParticipant", forward, - self._auth_header( + await self._auth_header( VideoGrants( room_admin=True, room=forward.room, destination_room=forward.destination_room ) @@ -248,7 +248,7 @@ async def move_participant(self, move: MoveParticipantRequest) -> None: SVC, "MoveParticipant", move, - self._auth_header( + await self._auth_header( VideoGrants( room_admin=True, room=move.room, @@ -279,7 +279,7 @@ async def mute_published_track( SVC, "MutePublishedTrack", update, - self._auth_header(VideoGrants(room_admin=True, room=update.room)), + await self._auth_header(VideoGrants(room_admin=True, room=update.room)), MuteRoomTrackResponse, ) @@ -302,7 +302,7 @@ async def update_participant(self, update: UpdateParticipantRequest) -> Particip SVC, "UpdateParticipant", update, - self._auth_header(VideoGrants(room_admin=True, room=update.room)), + await self._auth_header(VideoGrants(room_admin=True, room=update.room)), ParticipantInfo, ) @@ -326,7 +326,7 @@ async def update_subscriptions( SVC, "UpdateSubscriptions", update, - self._auth_header(VideoGrants(room_admin=True, room=update.room)), + await self._auth_header(VideoGrants(room_admin=True, room=update.room)), UpdateSubscriptionsResponse, ) @@ -350,6 +350,6 @@ async def send_data(self, send: SendDataRequest) -> SendDataResponse: SVC, "SendData", send, - self._auth_header(VideoGrants(room_admin=True, room=send.room)), + await self._auth_header(VideoGrants(room_admin=True, room=send.room)), SendDataResponse, ) diff --git a/livekit-api/livekit/api/sip_service.py b/livekit-api/livekit/api/sip_service.py index c222cdf0..920862c4 100644 --- a/livekit-api/livekit/api/sip_service.py +++ b/livekit-api/livekit/api/sip_service.py @@ -94,7 +94,7 @@ async def create_inbound_trunk( SVC, "CreateSIPInboundTrunk", create, - self._admin_headers(), + await self._admin_headers(), SIPInboundTrunkInfo, ) @@ -140,7 +140,7 @@ async def update_inbound_trunk( sip_trunk_id=trunk_id, replace=trunk, ), - self._admin_headers(), + await self._admin_headers(), SIPInboundTrunkInfo, ) @@ -221,7 +221,7 @@ async def update_inbound_trunk_fields( sip_trunk_id=trunk_id, update=update, ), - self._admin_headers(), + await self._admin_headers(), SIPInboundTrunkInfo, ) @@ -275,7 +275,7 @@ async def create_outbound_trunk( SVC, "CreateSIPOutboundTrunk", create, - self._admin_headers(), + await self._admin_headers(), SIPOutboundTrunkInfo, ) @@ -321,7 +321,7 @@ async def update_outbound_trunk( sip_trunk_id=trunk_id, replace=trunk, ), - self._admin_headers(), + await self._admin_headers(), SIPOutboundTrunkInfo, ) @@ -390,7 +390,7 @@ async def update_outbound_trunk_fields( sip_trunk_id=trunk_id, update=update, ), - self._admin_headers(), + await self._admin_headers(), SIPOutboundTrunkInfo, ) @@ -444,7 +444,7 @@ async def list_inbound_trunk( SVC, "ListSIPInboundTrunk", list, - self._admin_headers(), + await self._admin_headers(), ListSIPInboundTrunkResponse, ) @@ -484,7 +484,7 @@ async def list_outbound_trunk( SVC, "ListSIPOutboundTrunk", list, - self._admin_headers(), + await self._admin_headers(), ListSIPOutboundTrunkResponse, ) @@ -522,7 +522,7 @@ async def delete_trunk(self, delete: DeleteSIPTrunkRequest) -> SIPTrunkInfo: SVC, "DeleteSIPTrunk", delete, - self._admin_headers(), + await self._admin_headers(), SIPTrunkInfo, ) @@ -560,7 +560,7 @@ async def create_dispatch_rule( SVC, "CreateSIPDispatchRule", create, - self._admin_headers(), + await self._admin_headers(), SIPDispatchRuleInfo, ) @@ -603,7 +603,7 @@ async def update_dispatch_rule( SVC, "UpdateSIPDispatchRule", UpdateSIPDispatchRuleRequest(sip_dispatch_rule_id=rule_id, replace=rule), - self._admin_headers(), + await self._admin_headers(), SIPDispatchRuleInfo, ) @@ -663,7 +663,7 @@ async def update_dispatch_rule_fields( SVC, "UpdateSIPDispatchRule", UpdateSIPDispatchRuleRequest(sip_dispatch_rule_id=rule_id, update=update), - self._admin_headers(), + await self._admin_headers(), SIPDispatchRuleInfo, ) @@ -713,7 +713,7 @@ async def list_dispatch_rule( SVC, "ListSIPDispatchRule", list, - self._admin_headers(), + await self._admin_headers(), ListSIPDispatchRuleResponse, ) @@ -753,7 +753,7 @@ async def delete_dispatch_rule( SVC, "DeleteSIPDispatchRule", delete, - self._admin_headers(), + await self._admin_headers(), SIPDispatchRuleInfo, ) @@ -822,7 +822,7 @@ async def create_sip_participant( SVC, "CreateSIPParticipant", create, - self._auth_header(VideoGrants(), sip=SIPGrants(call=True)), + await self._auth_header(VideoGrants(), sip=SIPGrants(call=True)), SIPParticipantInfo, timeout=client_timeout, ) @@ -859,7 +859,7 @@ async def transfer_sip_participant( SVC, "TransferSIPParticipant", transfer, - self._auth_header( + await self._auth_header( VideoGrants( room_admin=True, room=transfer.room_name, @@ -872,5 +872,5 @@ async def transfer_sip_participant( except ServerError as e: raise _as_sip_error(e) from None - def _admin_headers(self) -> dict[str, str]: - return self._auth_header(VideoGrants(), sip=SIPGrants(admin=True)) + async def _admin_headers(self) -> dict[str, str]: + return await self._auth_header(VideoGrants(), sip=SIPGrants(admin=True)) diff --git a/tests/api/test_access_token.py b/tests/api/test_access_token.py index dfd93053..a433dd37 100644 --- a/tests/api/test_access_token.py +++ b/tests/api/test_access_token.py @@ -1,5 +1,6 @@ import calendar import datetime +import json import jwt import pytest @@ -256,3 +257,45 @@ def test_verify_token_with_only_inference_grants() -> None: assert claims.video is None assert claims.sip is None assert claims.observability is None + + +def _claims_token() -> AccessToken: + return ( + AccessToken(TEST_API_KEY, TEST_API_SECRET) + .with_identity("test_identity") + .with_name("test_name") + .with_kind("agent") + .with_metadata("test_metadata") + .with_attributes({"key1": "value1"}) + .with_grants(VideoGrants(room_join=True, room="test_room", can_publish_data=False)) + .with_sip_grants(SIPGrants(call=True)) + .with_room_config(RoomConfiguration(agents=[RoomAgentDispatch(agent_name="test-agent")])) + ) + + +def test_claims_json_matches_signed_payload() -> None: + claims = json.loads(_claims_token().to_claims_json()) + payload = jwt.decode(_claims_token().to_jwt(), options={"verify_signature": False}) + + # the claims the signer sets are left out; the identity is in `identity` + assert claims == {k: v for k, v in payload.items() if k not in ("iss", "sub", "nbf", "exp")} | { + "identity": "test_identity" + } + assert claims["video"] == { + "roomJoin": True, + "room": "test_room", + "canPublish": True, + "canSubscribe": True, + "canPublishData": False, + } + assert claims["kind"] == "agent" + + +def test_claims_json_without_key_or_secret(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("LIVEKIT_API_KEY", raising=False) + monkeypatch.delenv("LIVEKIT_API_SECRET", raising=False) + + token = AccessToken().with_identity("test_identity").with_grants(VideoGrants(room_list=True)) + assert json.loads(token.to_claims_json())["identity"] == "test_identity" + with pytest.raises(ValueError, match="api_key and api_secret must be set"): + token.to_jwt()