Skip to main content

livekit_api/
access_token.rs

1// Copyright 2025 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
15use std::{
16    collections::HashMap,
17    env,
18    fmt::Debug,
19    ops::Add,
20    time::{Duration, SystemTime, UNIX_EPOCH},
21};
22
23use jsonwebtoken::{self, DecodingKey, EncodingKey, Header};
24use serde::{Deserialize, Serialize};
25use thiserror::Error;
26
27use crate::get_env_keys;
28
29pub const DEFAULT_TTL: Duration = Duration::from_secs(3600 * 6); // 6 hours
30
31#[derive(Debug, Error)]
32pub enum AccessTokenError {
33    #[error("Invalid API Key or Secret Key")]
34    InvalidKeys,
35    #[error("Invalid environment")]
36    InvalidEnv(#[from] env::VarError),
37    #[error("invalid claims: {0}")]
38    InvalidClaims(&'static str),
39    #[error("failed to encode jwt")]
40    Encoding(#[from] jsonwebtoken::errors::Error),
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
44#[serde(rename_all = "camelCase")]
45pub struct VideoGrants {
46    // actions on rooms
47    #[serde(default)]
48    pub room_create: bool,
49    #[serde(default)]
50    pub room_list: bool,
51    #[serde(default)]
52    pub room_record: bool,
53
54    // actions on a particular room
55    #[serde(default)]
56    pub room_admin: bool,
57    #[serde(default)]
58    pub room_join: bool,
59    #[serde(default)]
60    pub room: String,
61    #[serde(default)]
62    pub destination_room: String,
63
64    // permissions within a room
65    #[serde(default = "default_true")]
66    pub can_publish: bool,
67    #[serde(default = "default_true")]
68    pub can_subscribe: bool,
69    #[serde(default = "default_true")]
70    pub can_publish_data: bool,
71
72    // TrackSource types that a participant may publish.
73    // When set, it supercedes CanPublish. Only sources explicitly set here can be published
74    #[serde(default)]
75    pub can_publish_sources: Vec<String>, // keys keep track of each source
76
77    // by default, a participant is not allowed to update its own metadata
78    #[serde(default)]
79    pub can_update_own_metadata: bool,
80
81    // actions on ingresses
82    #[serde(default)]
83    pub ingress_admin: bool, // applies to all ingress
84
85    // participant is not visible to other participants (useful when making bots)
86    #[serde(default)]
87    pub hidden: bool,
88
89    // indicates to the room that current participant is a recorder
90    #[serde(default)]
91    pub recorder: bool,
92}
93
94/// Used for fields that default to true instead of using the `Default` trait.
95fn default_true() -> bool {
96    true
97}
98
99impl Default for VideoGrants {
100    fn default() -> Self {
101        Self {
102            room_create: false,
103            room_list: false,
104            room_record: false,
105            room_admin: false,
106            room_join: false,
107            room: "".to_string(),
108            destination_room: "".to_string(),
109            can_publish: true,
110            can_subscribe: true,
111            can_publish_data: true,
112            can_publish_sources: Vec::default(),
113            can_update_own_metadata: false,
114            ingress_admin: false,
115            hidden: false,
116            recorder: false,
117        }
118    }
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
122#[serde(rename_all = "camelCase")]
123pub struct SIPGrants {
124    // manage sip resources
125    pub admin: bool,
126    // make outbound calls
127    pub call: bool,
128}
129
130impl Default for SIPGrants {
131    fn default() -> Self {
132        Self { admin: false, call: false }
133    }
134}
135
136#[derive(Debug, Clone, Serialize, Default, Deserialize, PartialEq)]
137#[serde(default)]
138#[serde(rename_all = "camelCase")]
139pub struct Claims {
140    pub exp: usize,  // Expiration
141    pub iss: String, // ApiKey
142    pub nbf: usize,
143    pub sub: String, // Identity
144
145    pub name: String,
146    pub video: VideoGrants,
147    pub sip: SIPGrants,
148    pub sha256: String, // Used to verify the integrity of the message body
149    pub metadata: String,
150    pub attributes: HashMap<String, String>,
151    pub room_config: Option<livekit_protocol::RoomConfiguration>,
152}
153
154impl Claims {
155    pub fn from_unverified(token: &str) -> Result<Self, AccessTokenError> {
156        crate::jwt_provider::ensure_installed();
157        let token = jsonwebtoken::dangerous::insecure_decode::<Claims>(token)?;
158        Ok(token.claims)
159    }
160}
161
162#[derive(Clone)]
163pub struct AccessToken {
164    api_key: String,
165    api_secret: String,
166    claims: Claims,
167}
168
169impl Debug for AccessToken {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        // Don't show api_secret here
172        f.debug_struct("AccessToken")
173            .field("api_key", &self.api_key)
174            .field("claims", &self.claims)
175            .finish()
176    }
177}
178
179impl AccessToken {
180    pub fn with_api_key(api_key: &str, api_secret: &str) -> Self {
181        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
182        Self {
183            api_key: api_key.to_owned(),
184            api_secret: api_secret.to_owned(),
185            claims: Claims {
186                exp: now.add(DEFAULT_TTL).as_secs() as usize,
187                iss: api_key.to_owned(),
188                nbf: now.as_secs() as usize,
189                sub: Default::default(),
190                name: Default::default(),
191                video: VideoGrants::default(),
192                sip: SIPGrants::default(),
193                sha256: Default::default(),
194                metadata: Default::default(),
195                attributes: HashMap::new(),
196                room_config: Default::default(),
197            },
198        }
199    }
200
201    #[cfg(test)]
202    pub fn from_parts(api_key: &str, api_secret: &str, claims: Claims) -> Self {
203        Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned(), claims }
204    }
205
206    pub fn new() -> Result<Self, AccessTokenError> {
207        // Try to get the API Key and the Secret Key from the environment
208        let (api_key, api_secret) = get_env_keys()?;
209        Ok(Self::with_api_key(&api_key, &api_secret))
210    }
211
212    pub fn with_ttl(mut self, ttl: Duration) -> Self {
213        let time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + ttl;
214        self.claims.exp = time.as_secs() as usize;
215        self
216    }
217
218    pub fn with_grants(mut self, grants: VideoGrants) -> Self {
219        self.claims.video = grants;
220        self
221    }
222
223    pub fn with_sip_grants(mut self, grants: SIPGrants) -> Self {
224        self.claims.sip = grants;
225        self
226    }
227
228    pub fn with_identity(mut self, identity: &str) -> Self {
229        self.claims.sub = identity.to_owned();
230        self
231    }
232
233    pub fn with_name(mut self, name: &str) -> Self {
234        self.claims.name = name.to_owned();
235        self
236    }
237
238    pub fn with_metadata(mut self, metadata: &str) -> Self {
239        self.claims.metadata = metadata.to_owned();
240        self
241    }
242
243    pub fn with_attributes<I, K, V>(mut self, attributes: I) -> Self
244    where
245        I: IntoIterator<Item = (K, V)>,
246        K: Into<String>,
247        V: Into<String>,
248    {
249        self.claims.attributes =
250            attributes.into_iter().map(|(k, v)| (k.into(), v.into())).collect::<HashMap<_, _>>();
251        self
252    }
253
254    pub fn with_sha256(mut self, sha256: &str) -> Self {
255        self.claims.sha256 = sha256.to_owned();
256        self
257    }
258
259    pub fn with_room_config(mut self, config: livekit_protocol::RoomConfiguration) -> Self {
260        self.claims.room_config = Some(config);
261        self
262    }
263
264    pub fn to_jwt(self) -> Result<String, AccessTokenError> {
265        crate::jwt_provider::ensure_installed();
266        if self.api_key.is_empty() || self.api_secret.is_empty() {
267            return Err(AccessTokenError::InvalidKeys);
268        }
269
270        if self.claims.video.room_join
271            && (self.claims.sub.is_empty() || self.claims.video.room.is_empty())
272        {
273            return Err(AccessTokenError::InvalidClaims(
274                "token grants room_join but doesn't have an identity or room",
275            ));
276        }
277
278        Ok(jsonwebtoken::encode(
279            &Header::new(jsonwebtoken::Algorithm::HS256),
280            &self.claims,
281            &EncodingKey::from_secret(self.api_secret.as_ref()),
282        )?)
283    }
284}
285
286#[derive(Clone)]
287pub struct TokenVerifier {
288    api_key: String,
289    api_secret: String,
290}
291
292impl Debug for TokenVerifier {
293    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294        f.debug_struct("TokenVerifier").field("api_key", &self.api_key).finish()
295    }
296}
297
298impl TokenVerifier {
299    pub fn with_api_key(api_key: &str, api_secret: &str) -> Self {
300        Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned() }
301    }
302
303    pub fn new() -> Result<Self, AccessTokenError> {
304        let (api_key, api_secret) = get_env_keys()?;
305        Ok(Self::with_api_key(&api_key, &api_secret))
306    }
307
308    pub fn verify(&self, token: &str) -> Result<Claims, AccessTokenError> {
309        crate::jwt_provider::ensure_installed();
310        let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::HS256);
311        validation.validate_exp = true;
312        validation.validate_nbf = true;
313        validation.set_issuer(&[&self.api_key]);
314
315        let token = jsonwebtoken::decode::<Claims>(
316            token,
317            &DecodingKey::from_secret(self.api_secret.as_ref()),
318            &validation,
319        )?;
320
321        Ok(token.claims)
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use std::time::Duration;
328
329    use super::{AccessToken, Claims, TokenVerifier, VideoGrants};
330
331    const TEST_API_KEY: &str = "myapikey";
332    const TEST_API_SECRET: &str = "thiskeyistotallyunsafe";
333    const TEST_TOKEN: &str = include_str!("test_token.txt");
334
335    #[test]
336    fn test_access_token() {
337        let room_config = livekit_protocol::RoomConfiguration {
338            name: "name".to_string(),
339            agents: vec![livekit_protocol::RoomAgentDispatch {
340                agent_name: "test-agent".to_string(),
341                metadata: "test-metadata".to_string(),
342                ..Default::default()
343            }],
344            ..Default::default()
345        };
346
347        let token = AccessToken::with_api_key(TEST_API_KEY, TEST_API_SECRET)
348            .with_ttl(Duration::from_secs(60))
349            .with_identity("test")
350            .with_name("test")
351            .with_grants(VideoGrants::default())
352            .with_room_config(room_config.clone())
353            .to_jwt()
354            .unwrap();
355
356        let verifier = TokenVerifier::with_api_key(TEST_API_KEY, TEST_API_SECRET);
357        let claims = verifier.verify(&token).unwrap();
358
359        assert_eq!(claims.sub, "test");
360        assert_eq!(claims.name, "test");
361        assert_eq!(claims.iss, TEST_API_KEY);
362        assert_eq!(claims.room_config, Some(room_config));
363
364        let incorrect_issuer = TokenVerifier::with_api_key("incorrect", TEST_API_SECRET);
365        assert!(incorrect_issuer.verify(&token).is_err());
366
367        let incorrect_token = TokenVerifier::with_api_key(TEST_API_KEY, "incorrect");
368        assert!(incorrect_token.verify(&token).is_err());
369    }
370
371    #[test]
372    fn test_verify_token_with_room_config() {
373        let verifier = TokenVerifier::with_api_key(TEST_API_KEY, TEST_API_SECRET);
374        // This token was generated using the Python SDK.
375        let claims = verifier.verify(TEST_TOKEN).expect("Failed to verify token.");
376
377        assert_eq!(
378            super::Claims {
379                sub: "identity".to_string(),
380                name: "name".to_string(),
381                room_config: Some(livekit_protocol::RoomConfiguration {
382                    agents: vec![livekit_protocol::RoomAgentDispatch {
383                        agent_name: "test-agent".to_string(),
384                        metadata: "test-metadata".to_string(),
385                        ..Default::default()
386                    }],
387                    ..Default::default()
388                }),
389                ..claims.clone()
390            },
391            claims
392        );
393    }
394
395    #[test]
396    fn test_unverified_token() {
397        let claims = Claims::from_unverified(TEST_TOKEN).expect("Failed to parse token");
398
399        assert_eq!(claims.sub, "identity");
400        assert_eq!(claims.name, "name");
401        assert_eq!(claims.iss, TEST_API_KEY);
402        assert_eq!(
403            claims.room_config,
404            Some(livekit_protocol::RoomConfiguration {
405                agents: vec![livekit_protocol::RoomAgentDispatch {
406                    agent_name: "test-agent".to_string(),
407                    metadata: "test-metadata".to_string(),
408                    ..Default::default()
409                }],
410                ..Default::default()
411            })
412        );
413
414        let token = AccessToken::with_api_key(TEST_API_KEY, TEST_API_SECRET)
415            .with_ttl(Duration::from_secs(60))
416            .with_identity("test")
417            .with_name("test")
418            .with_grants(VideoGrants {
419                room_join: true,
420                room: "test-room".to_string(),
421                ..Default::default()
422            })
423            .to_jwt()
424            .unwrap();
425
426        let claims = Claims::from_unverified(&token).expect("Failed to parse fresh token");
427        assert_eq!(claims.sub, "test");
428        assert_eq!(claims.name, "test");
429        assert_eq!(claims.video.room, "test-room");
430        assert!(claims.video.room_join);
431
432        let parts: Vec<&str> = token.split('.').collect();
433        let malformed_token = format!("{}.{}.wrongsignature", parts[0], parts[1]);
434
435        let claims = Claims::from_unverified(&malformed_token)
436            .expect("Failed to parse token with wrong signature");
437        assert_eq!(claims.sub, "test");
438        assert_eq!(claims.name, "test");
439    }
440}