|
| 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