Skip to content

Commit b52d4b9

Browse files
authored
rename TokenSource -> TokenProvider to avoid confusion (#949)
1 parent 1ea463e commit b52d4b9

5 files changed

Lines changed: 161 additions & 19 deletions

File tree

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,9 @@
4444
TwirpErrorCode,
4545
)
4646
from .livekit_api import LiveKitAPI
47-
from ._service import TokenSource
47+
from ._service import TokenProvider
4848
from .access_token import (
49+
TokenGrants,
4950
InferenceGrants,
5051
ObservabilityGrants,
5152
AgentGrants,
@@ -62,7 +63,8 @@
6263

6364
__all__ = [
6465
"LiveKitAPI",
65-
"TokenSource",
66+
"TokenProvider",
67+
"TokenGrants",
6668
"room_service",
6769
"egress_service",
6870
"ingress_service",

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

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44
from abc import ABC
55
from typing import Awaitable, Callable
66
from .twirp_client import TwirpClient
7-
from .access_token import AccessToken, Claims, VideoGrants, SIPGrants
7+
from .access_token import AccessToken, Claims, TokenGrants, VideoGrants, SIPGrants
88

99
AUTHORIZATION = "authorization"
1010

11-
TokenSource = Callable[[Claims], Awaitable[str]]
12-
"""Returns a token that carries the given claims.
11+
TokenProvider = Callable[[TokenGrants], Awaitable[str]]
12+
"""Returns a token that carries the given grants.
1313
1414
`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.
15+
key and secret, with the grants that request needs. It may cache tokens.
1616
"""
1717

1818

@@ -32,7 +32,7 @@ def __init__(
3232
# skipping per-call signing. Per-service constructors stay key/secret-only.
3333
self._token: str | None = None
3434
# Set by LiveKitAPI to get a token per call in place of signing one.
35-
self._token_source: TokenSource | None = None
35+
self._token_provider: TokenProvider | None = None
3636

3737
async def _auth_header(
3838
self, grants: VideoGrants | None, sip: SIPGrants | None = None
@@ -41,8 +41,8 @@ async def _auth_header(
4141
if self._token:
4242
return {AUTHORIZATION: "Bearer {}".format(self._token)}
4343

44-
if self._token_source is not None:
45-
token = await self._token_source(Claims(video=grants, sip=sip))
44+
if self._token_provider is not None:
45+
token = await self._token_provider(Claims(video=grants, sip=sip))
4646
return {AUTHORIZATION: "Bearer {}".format(token)}
4747

4848
tok = AccessToken(self.api_key, self.api_secret)

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,13 @@ def asdict(self) -> dict:
178178
return claims
179179

180180

181+
# The grants that a `TokenProvider` is asked for. Today these are v1 claims
182+
# (`Claims`). Grants v2 will be accepted here too. The provider does not convert
183+
# between the two: it passes the grants on as they are, and the server that
184+
# signs the token converts them to the format of its key.
185+
TokenGrants = Claims
186+
187+
181188
class AccessToken:
182189
ParticipantKind = Literal["standard", "egress", "ingress", "sip", "agent"]
183190

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

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +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
9+
from ._service import TokenProvider
1010
from typing import Any, Optional
1111

1212

@@ -31,7 +31,7 @@ def __init__(
3131
api_secret: Optional[str] = None,
3232
*,
3333
token: Optional[str] = None,
34-
token_source: Optional[TokenSource] = None,
34+
token_provider: Optional[TokenProvider] = None,
3535
timeout: Optional[aiohttp.ClientTimeout] = None,
3636
session: Optional[aiohttp.ClientSession] = None,
3737
failover: bool = True,
@@ -47,7 +47,7 @@ def __init__(
4747
api_key: API key (read from `LIVEKIT_API_KEY` environment variable if not provided)
4848
api_secret: API secret (read from `LIVEKIT_API_SECRET` environment variable if not provided)
4949
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,
50+
token_provider: Async callable that returns a token for the grants of each call,
5151
in place of signing one with api_key and api_secret
5252
timeout: Request timeout (default: 10 seconds)
5353
session: aiohttp.ClientSession instance to use for requests, if not provided, a new one will be created
@@ -57,19 +57,19 @@ def __init__(
5757
# Only fall back to environment credentials when none were provided
5858
# explicitly, so an ambient LIVEKIT_TOKEN can't silently override an
5959
# explicit api_key/secret (or vice versa).
60-
if not token and not token_source and not api_key and not api_secret:
60+
if not token and not token_provider and not api_key and not api_secret:
6161
token = os.getenv("LIVEKIT_TOKEN")
62-
if not token and not token_source and not api_key and not api_secret:
62+
if not token and not token_provider and not api_key and not api_secret:
6363
api_key = os.getenv("LIVEKIT_API_KEY")
6464
api_secret = os.getenv("LIVEKIT_API_SECRET")
6565

6666
if not url:
6767
raise ValueError("url must be set")
6868

69-
if token and token_source:
70-
raise ValueError("token and token_source cannot both be set")
69+
if token and token_provider:
70+
raise ValueError("token and token_provider cannot both be set")
7171

72-
if not token and not token_source and (not api_key or not api_secret):
72+
if not token and not token_provider and (not api_key or not api_secret):
7373
raise ValueError("either token, or api_key and api_secret, must be set")
7474

7575
self._custom_session = True
@@ -91,7 +91,7 @@ def __init__(
9191
self._agent_dispatch = AgentDispatchService(self._session, url, key, secret, failover)
9292
self._connector = ConnectorService(self._session, url, key, secret, failover)
9393

94-
if token or token_source:
94+
if token or token_provider:
9595
for svc in (
9696
self._room,
9797
self._ingress,
@@ -101,7 +101,7 @@ def __init__(
101101
self._connector,
102102
):
103103
svc._token = token
104-
svc._token_source = token_source
104+
svc._token_provider = token_provider
105105

106106
@classmethod
107107
def with_token(

‎tests/api/test_token_provider.py‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
# Copyright 2026 LiveKit, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""How LiveKitAPI authenticates each call: with a token provider, an API key and
16+
secret, or a static token. A recording session stands in for the server."""
17+
18+
import asyncio
19+
from typing import Dict, List
20+
21+
import jwt
22+
import pytest
23+
24+
from livekit import api
25+
from livekit.api.access_token import Claims
26+
from livekit.protocol.room import ListParticipantsRequest, ListParticipantsResponse
27+
28+
URL = "http://localhost:7880"
29+
KEY, SECRET = "devkey", "thiskeyistotallyunsafe-but-32-bytes-long"
30+
31+
32+
class _Response:
33+
status = 200
34+
35+
async def read(self) -> bytes:
36+
return ListParticipantsResponse().SerializeToString()
37+
38+
39+
class _Post:
40+
async def __aenter__(self) -> _Response:
41+
return _Response()
42+
43+
async def __aexit__(self, *exc) -> None:
44+
return None
45+
46+
47+
class _RecordingSession:
48+
timeout = None
49+
50+
def __init__(self) -> None:
51+
self.headers: List[Dict[str, str]] = []
52+
53+
def post(self, url: str, *, headers: Dict[str, str], **kwargs) -> _Post:
54+
self.headers.append(headers)
55+
return _Post()
56+
57+
58+
def _bearer(session: _RecordingSession) -> str:
59+
return session.headers[-1]["authorization"].removeprefix("Bearer ")
60+
61+
62+
async def _list_participants(lk: api.LiveKitAPI) -> None:
63+
await lk.room.list_participants(ListParticipantsRequest(room="test-room"))
64+
65+
66+
def test_token_provider_gets_the_grants_of_each_call() -> None:
67+
async def run() -> None:
68+
requested: List[api.TokenGrants] = []
69+
70+
async def token_provider(grants: api.TokenGrants) -> str:
71+
requested.append(grants)
72+
return f"provider-token-{len(requested)}"
73+
74+
session = _RecordingSession()
75+
lk = api.LiveKitAPI(URL, token_provider=token_provider, session=session) # type: ignore[arg-type]
76+
77+
await _list_participants(lk)
78+
assert requested == [Claims(video=api.VideoGrants(room_admin=True, room="test-room"))]
79+
assert _bearer(session) == "provider-token-1"
80+
81+
await lk.sip.list_inbound_trunk(api.ListSIPInboundTrunkRequest())
82+
assert requested[-1] == Claims(video=api.VideoGrants(), sip=api.SIPGrants(admin=True))
83+
assert _bearer(session) == "provider-token-2"
84+
85+
asyncio.run(run())
86+
87+
88+
def test_token_provider_takes_precedence_over_env(monkeypatch: pytest.MonkeyPatch) -> None:
89+
async def run() -> None:
90+
monkeypatch.setenv("LIVEKIT_TOKEN", "env-token")
91+
monkeypatch.setenv("LIVEKIT_API_KEY", KEY)
92+
monkeypatch.setenv("LIVEKIT_API_SECRET", SECRET)
93+
94+
async def token_provider(grants: api.TokenGrants) -> str:
95+
return "provider-token"
96+
97+
session = _RecordingSession()
98+
lk = api.LiveKitAPI(URL, token_provider=token_provider, session=session) # type: ignore[arg-type]
99+
await _list_participants(lk)
100+
assert _bearer(session) == "provider-token"
101+
102+
asyncio.run(run())
103+
104+
105+
def test_token_and_token_provider_are_exclusive() -> None:
106+
async def token_provider(grants: api.TokenGrants) -> str:
107+
return "provider-token"
108+
109+
with pytest.raises(ValueError, match="cannot both be set"):
110+
api.LiveKitAPI(URL, token="static", token_provider=token_provider)
111+
112+
113+
def test_key_and_secret_sign_each_call() -> None:
114+
async def run() -> None:
115+
session = _RecordingSession()
116+
lk = api.LiveKitAPI(URL, KEY, SECRET, session=session) # type: ignore[arg-type]
117+
await _list_participants(lk)
118+
119+
claims = api.TokenVerifier(KEY, SECRET).verify(_bearer(session))
120+
assert claims.video == api.VideoGrants(room_admin=True, room="test-room")
121+
assert jwt.decode(_bearer(session), options={"verify_signature": False})["iss"] == KEY
122+
123+
asyncio.run(run())
124+
125+
126+
def test_static_token_is_sent_verbatim() -> None:
127+
async def run() -> None:
128+
session = _RecordingSession()
129+
lk = api.LiveKitAPI.with_token("static-token", URL, session=session) # type: ignore[arg-type]
130+
await _list_participants(lk)
131+
assert _bearer(session) == "static-token"
132+
133+
asyncio.run(run())

0 commit comments

Comments
 (0)