1use 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); #[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 #[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 #[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 #[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 #[serde(default)]
75 pub can_publish_sources: Vec<String>, #[serde(default)]
79 pub can_update_own_metadata: bool,
80
81 #[serde(default)]
83 pub ingress_admin: bool, #[serde(default)]
87 pub hidden: bool,
88
89 #[serde(default)]
91 pub recorder: bool,
92}
93
94fn 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 pub admin: bool,
126 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, pub iss: String, pub nbf: usize,
143 pub sub: String, pub name: String,
146 pub video: VideoGrants,
147 pub sip: SIPGrants,
148 pub sha256: String, 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 let token = jsonwebtoken::dangerous::insecure_decode::<Claims>(token)?;
157 Ok(token.claims)
158 }
159}
160
161#[derive(Clone)]
162pub struct AccessToken {
163 api_key: String,
164 api_secret: String,
165 claims: Claims,
166}
167
168impl Debug for AccessToken {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 f.debug_struct("AccessToken")
172 .field("api_key", &self.api_key)
173 .field("claims", &self.claims)
174 .finish()
175 }
176}
177
178impl AccessToken {
179 pub fn with_api_key(api_key: &str, api_secret: &str) -> Self {
180 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
181 Self {
182 api_key: api_key.to_owned(),
183 api_secret: api_secret.to_owned(),
184 claims: Claims {
185 exp: now.add(DEFAULT_TTL).as_secs() as usize,
186 iss: api_key.to_owned(),
187 nbf: now.as_secs() as usize,
188 sub: Default::default(),
189 name: Default::default(),
190 video: VideoGrants::default(),
191 sip: SIPGrants::default(),
192 sha256: Default::default(),
193 metadata: Default::default(),
194 attributes: HashMap::new(),
195 room_config: Default::default(),
196 },
197 }
198 }
199
200 #[cfg(test)]
201 pub fn from_parts(api_key: &str, api_secret: &str, claims: Claims) -> Self {
202 Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned(), claims }
203 }
204
205 pub fn new() -> Result<Self, AccessTokenError> {
206 let (api_key, api_secret) = get_env_keys()?;
208 Ok(Self::with_api_key(&api_key, &api_secret))
209 }
210
211 pub fn with_ttl(mut self, ttl: Duration) -> Self {
212 let time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + ttl;
213 self.claims.exp = time.as_secs() as usize;
214 self
215 }
216
217 pub fn with_grants(mut self, grants: VideoGrants) -> Self {
218 self.claims.video = grants;
219 self
220 }
221
222 pub fn with_sip_grants(mut self, grants: SIPGrants) -> Self {
223 self.claims.sip = grants;
224 self
225 }
226
227 pub fn with_identity(mut self, identity: &str) -> Self {
228 self.claims.sub = identity.to_owned();
229 self
230 }
231
232 pub fn with_name(mut self, name: &str) -> Self {
233 self.claims.name = name.to_owned();
234 self
235 }
236
237 pub fn with_metadata(mut self, metadata: &str) -> Self {
238 self.claims.metadata = metadata.to_owned();
239 self
240 }
241
242 pub fn with_attributes<I, K, V>(mut self, attributes: I) -> Self
243 where
244 I: IntoIterator<Item = (K, V)>,
245 K: Into<String>,
246 V: Into<String>,
247 {
248 self.claims.attributes =
249 attributes.into_iter().map(|(k, v)| (k.into(), v.into())).collect::<HashMap<_, _>>();
250 self
251 }
252
253 pub fn with_sha256(mut self, sha256: &str) -> Self {
254 self.claims.sha256 = sha256.to_owned();
255 self
256 }
257
258 pub fn with_room_config(mut self, config: livekit_protocol::RoomConfiguration) -> Self {
259 self.claims.room_config = Some(config);
260 self
261 }
262
263 pub fn to_jwt(self) -> Result<String, AccessTokenError> {
264 if self.api_key.is_empty() || self.api_secret.is_empty() {
265 return Err(AccessTokenError::InvalidKeys);
266 }
267
268 if self.claims.video.room_join
269 && (self.claims.sub.is_empty() || self.claims.video.room.is_empty())
270 {
271 return Err(AccessTokenError::InvalidClaims(
272 "token grants room_join but doesn't have an identity or room",
273 ));
274 }
275
276 Ok(jsonwebtoken::encode(
277 &Header::new(jsonwebtoken::Algorithm::HS256),
278 &self.claims,
279 &EncodingKey::from_secret(self.api_secret.as_ref()),
280 )?)
281 }
282}
283
284#[derive(Clone)]
285pub struct TokenVerifier {
286 api_key: String,
287 api_secret: String,
288}
289
290impl Debug for TokenVerifier {
291 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
292 f.debug_struct("TokenVerifier").field("api_key", &self.api_key).finish()
293 }
294}
295
296impl TokenVerifier {
297 pub fn with_api_key(api_key: &str, api_secret: &str) -> Self {
298 Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned() }
299 }
300
301 pub fn new() -> Result<Self, AccessTokenError> {
302 let (api_key, api_secret) = get_env_keys()?;
303 Ok(Self::with_api_key(&api_key, &api_secret))
304 }
305
306 pub fn verify(&self, token: &str) -> Result<Claims, AccessTokenError> {
307 let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::HS256);
308 validation.validate_exp = true;
309 validation.validate_nbf = true;
310 validation.set_issuer(&[&self.api_key]);
311
312 let token = jsonwebtoken::decode::<Claims>(
313 token,
314 &DecodingKey::from_secret(self.api_secret.as_ref()),
315 &validation,
316 )?;
317
318 Ok(token.claims)
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use std::time::Duration;
325
326 use super::{AccessToken, Claims, TokenVerifier, VideoGrants};
327
328 const TEST_API_KEY: &str = "myapikey";
329 const TEST_API_SECRET: &str = "thiskeyistotallyunsafe";
330 const TEST_TOKEN: &str = include_str!("test_token.txt");
331
332 #[test]
333 fn test_access_token() {
334 let room_config = livekit_protocol::RoomConfiguration {
335 name: "name".to_string(),
336 agents: vec![livekit_protocol::RoomAgentDispatch {
337 agent_name: "test-agent".to_string(),
338 metadata: "test-metadata".to_string(),
339 }],
340 ..Default::default()
341 };
342
343 let token = AccessToken::with_api_key(TEST_API_KEY, TEST_API_SECRET)
344 .with_ttl(Duration::from_secs(60))
345 .with_identity("test")
346 .with_name("test")
347 .with_grants(VideoGrants::default())
348 .with_room_config(room_config.clone())
349 .to_jwt()
350 .unwrap();
351
352 let verifier = TokenVerifier::with_api_key(TEST_API_KEY, TEST_API_SECRET);
353 let claims = verifier.verify(&token).unwrap();
354
355 assert_eq!(claims.sub, "test");
356 assert_eq!(claims.name, "test");
357 assert_eq!(claims.iss, TEST_API_KEY);
358 assert_eq!(claims.room_config, Some(room_config));
359
360 let incorrect_issuer = TokenVerifier::with_api_key("incorrect", TEST_API_SECRET);
361 assert!(incorrect_issuer.verify(&token).is_err());
362
363 let incorrect_token = TokenVerifier::with_api_key(TEST_API_KEY, "incorrect");
364 assert!(incorrect_token.verify(&token).is_err());
365 }
366
367 #[test]
368 fn test_verify_token_with_room_config() {
369 let verifier = TokenVerifier::with_api_key(TEST_API_KEY, TEST_API_SECRET);
370 let claims = verifier.verify(TEST_TOKEN).expect("Failed to verify token.");
372
373 assert_eq!(
374 super::Claims {
375 sub: "identity".to_string(),
376 name: "name".to_string(),
377 room_config: Some(livekit_protocol::RoomConfiguration {
378 agents: vec![livekit_protocol::RoomAgentDispatch {
379 agent_name: "test-agent".to_string(),
380 metadata: "test-metadata".to_string(),
381 }],
382 ..Default::default()
383 }),
384 ..claims.clone()
385 },
386 claims
387 );
388 }
389
390 #[test]
391 fn test_unverified_token() {
392 let claims = Claims::from_unverified(TEST_TOKEN).expect("Failed to parse token");
393
394 assert_eq!(claims.sub, "identity");
395 assert_eq!(claims.name, "name");
396 assert_eq!(claims.iss, TEST_API_KEY);
397 assert_eq!(
398 claims.room_config,
399 Some(livekit_protocol::RoomConfiguration {
400 agents: vec![livekit_protocol::RoomAgentDispatch {
401 agent_name: "test-agent".to_string(),
402 metadata: "test-metadata".to_string(),
403 }],
404 ..Default::default()
405 })
406 );
407
408 let token = AccessToken::with_api_key(TEST_API_KEY, TEST_API_SECRET)
409 .with_ttl(Duration::from_secs(60))
410 .with_identity("test")
411 .with_name("test")
412 .with_grants(VideoGrants {
413 room_join: true,
414 room: "test-room".to_string(),
415 ..Default::default()
416 })
417 .to_jwt()
418 .unwrap();
419
420 let claims = Claims::from_unverified(&token).expect("Failed to parse fresh token");
421 assert_eq!(claims.sub, "test");
422 assert_eq!(claims.name, "test");
423 assert_eq!(claims.video.room, "test-room");
424 assert!(claims.video.room_join);
425
426 let parts: Vec<&str> = token.split('.').collect();
427 let malformed_token = format!("{}.{}.wrongsignature", parts[0], parts[1]);
428
429 let claims = Claims::from_unverified(&malformed_token)
430 .expect("Failed to parse token with wrong signature");
431 assert_eq!(claims.sub, "test");
432 assert_eq!(claims.name, "test");
433 }
434}