livekit_api/
access_token.rs

1// Copyright 2023 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
154#[derive(Clone)]
155pub struct AccessToken {
156    api_key: String,
157    api_secret: String,
158    claims: Claims,
159}
160
161impl Debug for AccessToken {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        // Don't show api_secret here
164        f.debug_struct("AccessToken")
165            .field("api_key", &self.api_key)
166            .field("claims", &self.claims)
167            .finish()
168    }
169}
170
171impl AccessToken {
172    pub fn with_api_key(api_key: &str, api_secret: &str) -> Self {
173        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
174        Self {
175            api_key: api_key.to_owned(),
176            api_secret: api_secret.to_owned(),
177            claims: Claims {
178                exp: now.add(DEFAULT_TTL).as_secs() as usize,
179                iss: api_key.to_owned(),
180                nbf: now.as_secs() as usize,
181                sub: Default::default(),
182                name: Default::default(),
183                video: VideoGrants::default(),
184                sip: SIPGrants::default(),
185                sha256: Default::default(),
186                metadata: Default::default(),
187                attributes: HashMap::new(),
188                room_config: Default::default(),
189            },
190        }
191    }
192
193    #[cfg(test)]
194    pub fn from_parts(api_key: &str, api_secret: &str, claims: Claims) -> Self {
195        Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned(), claims }
196    }
197
198    pub fn new() -> Result<Self, AccessTokenError> {
199        // Try to get the API Key and the Secret Key from the environment
200        let (api_key, api_secret) = get_env_keys()?;
201        Ok(Self::with_api_key(&api_key, &api_secret))
202    }
203
204    pub fn with_ttl(mut self, ttl: Duration) -> Self {
205        let time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + ttl;
206        self.claims.exp = time.as_secs() as usize;
207        self
208    }
209
210    pub fn with_grants(mut self, grants: VideoGrants) -> Self {
211        self.claims.video = grants;
212        self
213    }
214
215    pub fn with_sip_grants(mut self, grants: SIPGrants) -> Self {
216        self.claims.sip = grants;
217        self
218    }
219
220    pub fn with_identity(mut self, identity: &str) -> Self {
221        self.claims.sub = identity.to_owned();
222        self
223    }
224
225    pub fn with_name(mut self, name: &str) -> Self {
226        self.claims.name = name.to_owned();
227        self
228    }
229
230    pub fn with_metadata(mut self, metadata: &str) -> Self {
231        self.claims.metadata = metadata.to_owned();
232        self
233    }
234
235    pub fn with_attributes<I, K, V>(mut self, attributes: I) -> Self
236    where
237        I: IntoIterator<Item = (K, V)>,
238        K: Into<String>,
239        V: Into<String>,
240    {
241        self.claims.attributes =
242            attributes.into_iter().map(|(k, v)| (k.into(), v.into())).collect::<HashMap<_, _>>();
243        self
244    }
245
246    pub fn with_sha256(mut self, sha256: &str) -> Self {
247        self.claims.sha256 = sha256.to_owned();
248        self
249    }
250
251    pub fn with_room_config(mut self, config: livekit_protocol::RoomConfiguration) -> Self {
252        self.claims.room_config = Some(config);
253        self
254    }
255
256    pub fn to_jwt(self) -> Result<String, AccessTokenError> {
257        if self.api_key.is_empty() || self.api_secret.is_empty() {
258            return Err(AccessTokenError::InvalidKeys);
259        }
260
261        if self.claims.video.room_join
262            && (self.claims.sub.is_empty() || self.claims.video.room.is_empty())
263        {
264            return Err(AccessTokenError::InvalidClaims(
265                "token grants room_join but doesn't have an identity or room",
266            ));
267        }
268
269        Ok(jsonwebtoken::encode(
270            &Header::new(jsonwebtoken::Algorithm::HS256),
271            &self.claims,
272            &EncodingKey::from_secret(self.api_secret.as_ref()),
273        )?)
274    }
275}
276
277#[derive(Clone)]
278pub struct TokenVerifier {
279    api_key: String,
280    api_secret: String,
281}
282
283impl Debug for TokenVerifier {
284    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285        f.debug_struct("TokenVerifier").field("api_key", &self.api_key).finish()
286    }
287}
288
289impl TokenVerifier {
290    pub fn with_api_key(api_key: &str, api_secret: &str) -> Self {
291        Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned() }
292    }
293
294    pub fn new() -> Result<Self, AccessTokenError> {
295        let (api_key, api_secret) = get_env_keys()?;
296        Ok(Self::with_api_key(&api_key, &api_secret))
297    }
298
299    pub fn verify(&self, token: &str) -> Result<Claims, AccessTokenError> {
300        let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::HS256);
301        validation.validate_exp = true;
302        #[cfg(test)] // FIXME: TEST_TOKEN is expired, TODO: generate TEST_TOKEN at test runtime
303        {
304            validation.validate_exp = false;
305        }
306        validation.validate_nbf = true;
307        validation.set_issuer(&[&self.api_key]);
308
309        let token = jsonwebtoken::decode::<Claims>(
310            token,
311            &DecodingKey::from_secret(self.api_secret.as_ref()),
312            &validation,
313        )?;
314
315        Ok(token.claims)
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use std::time::Duration;
322
323    use super::{AccessToken, TokenVerifier, VideoGrants};
324
325    const TEST_API_KEY: &str = "myapikey";
326    const TEST_API_SECRET: &str = "thiskeyistotallyunsafe";
327    const TEST_TOKEN: &str = include_str!("test_token.txt");
328
329    #[test]
330    fn test_access_token() {
331        let room_config = livekit_protocol::RoomConfiguration {
332            name: "name".to_string(),
333            agents: vec![livekit_protocol::RoomAgentDispatch {
334                agent_name: "test-agent".to_string(),
335                metadata: "test-metadata".to_string(),
336            }],
337            ..Default::default()
338        };
339
340        let token = AccessToken::with_api_key(TEST_API_KEY, TEST_API_SECRET)
341            .with_ttl(Duration::from_secs(60))
342            .with_identity("test")
343            .with_name("test")
344            .with_grants(VideoGrants::default())
345            .with_room_config(room_config.clone())
346            .to_jwt()
347            .unwrap();
348
349        let verifier = TokenVerifier::with_api_key(TEST_API_KEY, TEST_API_SECRET);
350        let claims = verifier.verify(&token).unwrap();
351
352        assert_eq!(claims.sub, "test");
353        assert_eq!(claims.name, "test");
354        assert_eq!(claims.iss, TEST_API_KEY);
355        assert_eq!(claims.room_config, Some(room_config));
356
357        let incorrect_issuer = TokenVerifier::with_api_key("incorrect", TEST_API_SECRET);
358        assert!(incorrect_issuer.verify(&token).is_err());
359
360        let incorrect_token = TokenVerifier::with_api_key(TEST_API_KEY, "incorrect");
361        assert!(incorrect_token.verify(&token).is_err());
362    }
363
364    #[test]
365    fn test_verify_token_with_room_config() {
366        let verifier = TokenVerifier::with_api_key(TEST_API_KEY, TEST_API_SECRET);
367        // This token was generated using the Python SDK.
368        let claims = verifier.verify(TEST_TOKEN).expect("Failed to verify token.");
369
370        assert_eq!(
371            super::Claims {
372                sub: "identity".to_string(),
373                name: "name".to_string(),
374                room_config: Some(livekit_protocol::RoomConfiguration {
375                    agents: vec![livekit_protocol::RoomAgentDispatch {
376                        agent_name: "test-agent".to_string(),
377                        metadata: "test-metadata".to_string(),
378                    }],
379                    ..Default::default()
380                }),
381                ..claims.clone()
382            },
383            claims
384        );
385    }
386}