Skip to content

Commit 056b376

Browse files
feat: support token source to generate token on the fly (#945)
Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 691e735 commit 056b376

12 files changed

Lines changed: 152 additions & 68 deletions

‎.changeset/token-source.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"livekit-api": minor
3+
---
4+
5+
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.

‎livekit-api/livekit/api/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
TwirpErrorCode,
4545
)
4646
from .livekit_api import LiveKitAPI
47+
from ._service import TokenSource
4748
from .access_token import (
4849
InferenceGrants,
4950
ObservabilityGrants,
@@ -61,6 +62,7 @@
6162

6263
__all__ = [
6364
"LiveKitAPI",
65+
"TokenSource",
6466
"room_service",
6567
"egress_service",
6668
"ingress_service",

‎livekit-api/livekit/api/_service.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,19 @@
22

33
import aiohttp
44
from abc import ABC
5+
from typing import Awaitable, Callable
56
from .twirp_client import TwirpClient
6-
from .access_token import AccessToken, VideoGrants, SIPGrants
7+
from .access_token import AccessToken, Claims, VideoGrants, SIPGrants
78

89
AUTHORIZATION = "authorization"
910

11+
TokenSource = Callable[[Claims], Awaitable[str]]
12+
"""Returns a token that carries the given claims.
13+
14+
`LiveKitAPI` calls it before each request, in place of signing a token with an API
15+
key and secret, with the claims that request needs. It may cache tokens.
16+
"""
17+
1018

1119
class Service(ABC):
1220
def __init__(
@@ -23,14 +31,20 @@ def __init__(
2331
# A pre-signed token set by LiveKitAPI for token auth; sent verbatim,
2432
# skipping per-call signing. Per-service constructors stay key/secret-only.
2533
self._token: str | None = None
34+
# Set by LiveKitAPI to get a token per call in place of signing one.
35+
self._token_source: TokenSource | None = None
2636

27-
def _auth_header(
37+
async def _auth_header(
2838
self, grants: VideoGrants | None, sip: SIPGrants | None = None
2939
) -> dict[str, str]:
3040
# A pre-signed token is sent verbatim; the caller is responsible for its grants.
3141
if self._token:
3242
return {AUTHORIZATION: "Bearer {}".format(self._token)}
3343

44+
if self._token_source is not None:
45+
token = await self._token_source(Claims(video=grants, sip=sip))
46+
return {AUTHORIZATION: "Bearer {}".format(token)}
47+
3448
tok = AccessToken(self.api_key, self.api_secret)
3549
if grants:
3650
tok.with_grants(grants)

‎livekit-api/livekit/api/access_token.py‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import calendar
1616
import re
1717
import datetime
18+
import json
1819
import os
1920
import jwt
2021
import dataclasses
@@ -185,14 +186,9 @@ def __init__(
185186
api_key: Optional[str] = None,
186187
api_secret: Optional[str] = None,
187188
) -> None:
188-
api_key = api_key or os.getenv("LIVEKIT_API_KEY")
189-
api_secret = api_secret or os.getenv("LIVEKIT_API_SECRET")
190-
191-
if not api_key or not api_secret:
192-
raise ValueError("api_key and api_secret must be set")
193-
194-
self.api_key = api_key # iss
195-
self.api_secret = api_secret
189+
# the key and secret are checked in to_jwt, so that to_claims_json works without them
190+
self.api_key = api_key or os.getenv("LIVEKIT_API_KEY") or "" # iss
191+
self.api_secret = api_secret or os.getenv("LIVEKIT_API_SECRET") or ""
196192
self.claims = Claims()
197193

198194
# default jwt claims
@@ -267,7 +263,23 @@ def with_room_config(self, config: RoomConfiguration) -> "AccessToken":
267263
self.claims.room_config = config
268264
return self
269265

266+
def to_claims_json(self) -> str:
267+
"""Returns the claims of this token as JSON, without signing them.
268+
269+
The JSON has the shape of the payload `to_jwt` signs, without the claims the
270+
signer sets (iss, sub, nbf, exp); the identity is in `identity`. It needs no
271+
API key or secret, so a process without them can send it to a server that
272+
signs the token, such as in `CreateJobTokenRequest.claims`.
273+
"""
274+
claims = self.claims.asdict()
275+
if self.identity:
276+
claims["identity"] = self.identity
277+
return json.dumps(claims)
278+
270279
def to_jwt(self) -> str:
280+
if not self.api_key or not self.api_secret:
281+
raise ValueError("api_key and api_secret must be set")
282+
271283
video = self.claims.video
272284
if video and video.room_join and (not self.identity or not video.room):
273285
raise ValueError("identity and room must be set when joining a room")

‎livekit-api/livekit/api/agent_dispatch_service.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ async def create_dispatch(self, req: CreateAgentDispatchRequest) -> AgentDispatc
5353
SVC,
5454
"CreateDispatch",
5555
req,
56-
self._auth_header(VideoGrants(room_admin=True, room=req.room)),
56+
await self._auth_header(VideoGrants(room_admin=True, room=req.room)),
5757
AgentDispatch,
5858
)
5959

@@ -74,7 +74,7 @@ async def delete_dispatch(self, dispatch_id: str, room_name: str) -> AgentDispat
7474
dispatch_id=dispatch_id,
7575
room=room_name,
7676
),
77-
self._auth_header(VideoGrants(room_admin=True, room=room_name)),
77+
await self._auth_header(VideoGrants(room_admin=True, room=room_name)),
7878
AgentDispatch,
7979
)
8080

@@ -91,7 +91,7 @@ async def list_dispatch(self, room_name: str) -> list[AgentDispatch]:
9191
SVC,
9292
"ListDispatch",
9393
ListAgentDispatchRequest(room=room_name),
94-
self._auth_header(VideoGrants(room_admin=True, room=room_name)),
94+
await self._auth_header(VideoGrants(room_admin=True, room=room_name)),
9595
ListAgentDispatchResponse,
9696
)
9797
return list(res.agent_dispatches)
@@ -110,7 +110,7 @@ async def get_dispatch(self, dispatch_id: str, room_name: str) -> Optional[Agent
110110
SVC,
111111
"ListDispatch",
112112
ListAgentDispatchRequest(dispatch_id=dispatch_id, room=room_name),
113-
self._auth_header(VideoGrants(room_admin=True, room=room_name)),
113+
await self._auth_header(VideoGrants(room_admin=True, room=room_name)),
114114
ListAgentDispatchResponse,
115115
)
116116
if len(res.agent_dispatches) > 0:

‎livekit-api/livekit/api/connector_service.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ async def dial_whatsapp_call(
6363
SVC,
6464
"DialWhatsAppCall",
6565
request,
66-
self._auth_header(VideoGrants(room_create=True)),
66+
await self._auth_header(VideoGrants(room_create=True)),
6767
DialWhatsAppCallResponse,
6868
)
6969

@@ -83,7 +83,7 @@ async def disconnect_whatsapp_call(
8383
SVC,
8484
"DisconnectWhatsAppCall",
8585
request,
86-
self._auth_header(VideoGrants(room_create=True)),
86+
await self._auth_header(VideoGrants(room_create=True)),
8787
DisconnectWhatsAppCallResponse,
8888
)
8989

@@ -103,7 +103,7 @@ async def connect_whatsapp_call(
103103
SVC,
104104
"ConnectWhatsAppCall",
105105
request,
106-
self._auth_header(VideoGrants(room_create=True)),
106+
await self._auth_header(VideoGrants(room_create=True)),
107107
ConnectWhatsAppCallResponse,
108108
)
109109

@@ -140,7 +140,7 @@ async def accept_whatsapp_call(
140140
SVC,
141141
"AcceptWhatsAppCall",
142142
request,
143-
self._auth_header(VideoGrants(room_create=True)),
143+
await self._auth_header(VideoGrants(room_create=True)),
144144
AcceptWhatsAppCallResponse,
145145
timeout=client_timeout,
146146
)
@@ -161,6 +161,6 @@ async def connect_twilio_call(
161161
SVC,
162162
"ConnectTwilioCall",
163163
request,
164-
self._auth_header(VideoGrants(room_create=True)),
164+
await self._auth_header(VideoGrants(room_create=True)),
165165
ConnectTwilioCallResponse,
166166
)

‎livekit-api/livekit/api/egress_service.py‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ async def start_room_composite_egress(self, start: RoomCompositeEgressRequest) -
5050
SVC,
5151
"StartRoomCompositeEgress",
5252
start,
53-
self._auth_header(VideoGrants(room_record=True)),
53+
await self._auth_header(VideoGrants(room_record=True)),
5454
EgressInfo,
5555
)
5656

@@ -60,7 +60,7 @@ async def start_web_egress(self, start: WebEgressRequest) -> EgressInfo:
6060
SVC,
6161
"StartWebEgress",
6262
start,
63-
self._auth_header(VideoGrants(room_record=True)),
63+
await self._auth_header(VideoGrants(room_record=True)),
6464
EgressInfo,
6565
)
6666

@@ -70,7 +70,7 @@ async def start_participant_egress(self, start: ParticipantEgressRequest) -> Egr
7070
SVC,
7171
"StartParticipantEgress",
7272
start,
73-
self._auth_header(VideoGrants(room_record=True)),
73+
await self._auth_header(VideoGrants(room_record=True)),
7474
EgressInfo,
7575
)
7676

@@ -80,7 +80,7 @@ async def start_track_composite_egress(self, start: TrackCompositeEgressRequest)
8080
SVC,
8181
"StartTrackCompositeEgress",
8282
start,
83-
self._auth_header(VideoGrants(room_record=True)),
83+
await self._auth_header(VideoGrants(room_record=True)),
8484
EgressInfo,
8585
)
8686

@@ -90,7 +90,7 @@ async def start_track_egress(self, start: TrackEgressRequest) -> EgressInfo:
9090
SVC,
9191
"StartTrackEgress",
9292
start,
93-
self._auth_header(VideoGrants(room_record=True)),
93+
await self._auth_header(VideoGrants(room_record=True)),
9494
EgressInfo,
9595
)
9696

@@ -100,7 +100,7 @@ async def start_egress(self, start: StartEgressRequest) -> EgressInfo:
100100
SVC,
101101
"StartEgress",
102102
start,
103-
self._auth_header(VideoGrants(room_record=True)),
103+
await self._auth_header(VideoGrants(room_record=True)),
104104
EgressInfo,
105105
)
106106

@@ -110,7 +110,7 @@ async def update_layout(self, update: UpdateLayoutRequest) -> EgressInfo:
110110
SVC,
111111
"UpdateLayout",
112112
update,
113-
self._auth_header(VideoGrants(room_record=True)),
113+
await self._auth_header(VideoGrants(room_record=True)),
114114
EgressInfo,
115115
)
116116

@@ -120,7 +120,7 @@ async def update_stream(self, update: UpdateStreamRequest) -> EgressInfo:
120120
SVC,
121121
"UpdateStream",
122122
update,
123-
self._auth_header(VideoGrants(room_record=True)),
123+
await self._auth_header(VideoGrants(room_record=True)),
124124
EgressInfo,
125125
)
126126

@@ -137,7 +137,7 @@ async def list_egress(self, list: ListEgressRequest) -> ListEgressResponse:
137137
SVC,
138138
"ListEgress",
139139
list,
140-
self._auth_header(VideoGrants(room_record=True)),
140+
await self._auth_header(VideoGrants(room_record=True)),
141141
ListEgressResponse,
142142
)
143143

@@ -147,6 +147,6 @@ async def stop_egress(self, stop: StopEgressRequest) -> EgressInfo:
147147
SVC,
148148
"StopEgress",
149149
stop,
150-
self._auth_header(VideoGrants(room_record=True)),
150+
await self._auth_header(VideoGrants(room_record=True)),
151151
EgressInfo,
152152
)

‎livekit-api/livekit/api/ingress_service.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ async def create_ingress(self, create: CreateIngressRequest) -> IngressInfo:
4343
SVC,
4444
"CreateIngress",
4545
create,
46-
self._auth_header(VideoGrants(ingress_admin=True)),
46+
await self._auth_header(VideoGrants(ingress_admin=True)),
4747
IngressInfo,
4848
)
4949

@@ -52,7 +52,7 @@ async def update_ingress(self, update: UpdateIngressRequest) -> IngressInfo:
5252
SVC,
5353
"UpdateIngress",
5454
update,
55-
self._auth_header(VideoGrants(ingress_admin=True)),
55+
await self._auth_header(VideoGrants(ingress_admin=True)),
5656
IngressInfo,
5757
)
5858

@@ -61,7 +61,7 @@ async def list_ingress(self, list: ListIngressRequest) -> ListIngressResponse:
6161
SVC,
6262
"ListIngress",
6363
list,
64-
self._auth_header(VideoGrants(ingress_admin=True)),
64+
await self._auth_header(VideoGrants(ingress_admin=True)),
6565
ListIngressResponse,
6666
)
6767

@@ -70,6 +70,6 @@ async def delete_ingress(self, delete: DeleteIngressRequest) -> IngressInfo:
7070
SVC,
7171
"DeleteIngress",
7272
delete,
73-
self._auth_header(VideoGrants(ingress_admin=True)),
73+
await self._auth_header(VideoGrants(ingress_admin=True)),
7474
IngressInfo,
7575
)

‎livekit-api/livekit/api/livekit_api.py‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from .sip_service import SipService
77
from .agent_dispatch_service import AgentDispatchService
88
from .connector_service import ConnectorService
9+
from ._service import TokenSource
910
from typing import Any, Optional
1011

1112

@@ -30,6 +31,7 @@ def __init__(
3031
api_secret: Optional[str] = None,
3132
*,
3233
token: Optional[str] = None,
34+
token_source: Optional[TokenSource] = None,
3335
timeout: Optional[aiohttp.ClientTimeout] = None,
3436
session: Optional[aiohttp.ClientSession] = None,
3537
failover: bool = True,
@@ -45,6 +47,8 @@ def __init__(
4547
api_key: API key (read from `LIVEKIT_API_KEY` environment variable if not provided)
4648
api_secret: API secret (read from `LIVEKIT_API_SECRET` environment variable if not provided)
4749
token: Pre-signed access token (read from `LIVEKIT_TOKEN` environment variable if not provided)
50+
token_source: Async callable that returns a token for the claims of each call,
51+
in place of signing one with api_key and api_secret
4852
timeout: Request timeout (default: 10 seconds)
4953
session: aiohttp.ClientSession instance to use for requests, if not provided, a new one will be created
5054
"""
@@ -53,16 +57,19 @@ def __init__(
5357
# Only fall back to environment credentials when none were provided
5458
# explicitly, so an ambient LIVEKIT_TOKEN can't silently override an
5559
# explicit api_key/secret (or vice versa).
56-
if not token and not api_key and not api_secret:
60+
if not token and not token_source and not api_key and not api_secret:
5761
token = os.getenv("LIVEKIT_TOKEN")
58-
if not token and not api_key and not api_secret:
62+
if not token and not token_source and not api_key and not api_secret:
5963
api_key = os.getenv("LIVEKIT_API_KEY")
6064
api_secret = os.getenv("LIVEKIT_API_SECRET")
6165

6266
if not url:
6367
raise ValueError("url must be set")
6468

65-
if not token and (not api_key or not api_secret):
69+
if token and token_source:
70+
raise ValueError("token and token_source cannot both be set")
71+
72+
if not token and not token_source and (not api_key or not api_secret):
6673
raise ValueError("either token, or api_key and api_secret, must be set")
6774

6875
self._custom_session = True
@@ -84,7 +91,7 @@ def __init__(
8491
self._agent_dispatch = AgentDispatchService(self._session, url, key, secret, failover)
8592
self._connector = ConnectorService(self._session, url, key, secret, failover)
8693

87-
if token:
94+
if token or token_source:
8895
for svc in (
8996
self._room,
9097
self._ingress,
@@ -94,6 +101,7 @@ def __init__(
94101
self._connector,
95102
):
96103
svc._token = token
104+
svc._token_source = token_source
97105

98106
@classmethod
99107
def with_token(

0 commit comments

Comments
 (0)