Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/token-source.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions livekit-api/livekit/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
TwirpErrorCode,
)
from .livekit_api import LiveKitAPI
from ._service import TokenSource
from .access_token import (
InferenceGrants,
ObservabilityGrants,
Expand All @@ -61,6 +62,7 @@

__all__ = [
"LiveKitAPI",
"TokenSource",
"room_service",
"egress_service",
"ingress_service",
Expand Down
18 changes: 16 additions & 2 deletions livekit-api/livekit/api/_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__(
Expand All @@ -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)
Expand Down
28 changes: 20 additions & 8 deletions livekit-api/livekit/api/access_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import calendar
import re
import datetime
import json
import os
import jwt
import dataclasses
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
8 changes: 4 additions & 4 deletions livekit-api/livekit/api/agent_dispatch_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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)
Expand All @@ -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:
Expand Down
10 changes: 5 additions & 5 deletions livekit-api/livekit/api/connector_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand Down Expand Up @@ -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,
)
Expand All @@ -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,
)
20 changes: 10 additions & 10 deletions livekit-api/livekit/api/egress_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)
8 changes: 4 additions & 4 deletions livekit-api/livekit/api/ingress_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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,
)
16 changes: 12 additions & 4 deletions livekit-api/livekit/api/livekit_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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,
Expand All @@ -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
"""
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -94,6 +101,7 @@ def __init__(
self._connector,
):
svc._token = token
svc._token_source = token_source

@classmethod
def with_token(
Expand Down
Loading
Loading