| 1 | use std::fmt; |
| 2 | use std::time::{Duration, Instant}; |
| 3 | |
| 4 | use libwebrtc::peer_connection_factory::IceServer; |
| 5 | use serde::Deserialize; |
| 6 | use session::{IC3, Request, Scope, Session}; |
| 7 | |
| 8 | use crate::error::{Error, Result}; |
| 9 | |
| 10 | pub const TOKENS_URL: &str = "https://teams.microsoft.com/trap/tokens"; |
| 11 | pub const DEFAULT_RELAY_HOST: &str = "gateway-eu.az.relay.teams.cloud.microsoft"; |
| 12 | |
| 13 | pub fn ic3_scope() -> Scope { |
| 14 | Scope::new(IC3, "Teams.AccessAsUser.All") |
| 15 | } |
| 16 | |
| 17 | #[derive(Clone, Deserialize)] |
| 18 | pub struct RelayCredentials { |
| 19 | #[serde(default)] |
| 20 | pub realm: String, |
| 21 | pub username: String, |
| 22 | pub password: String, |
| 23 | } |
| 24 | |
| 25 | impl fmt::Debug for RelayCredentials { |
| 26 | fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 27 | formatter |
| 28 | .debug_struct("RelayCredentials") |
| 29 | .field("realm", &self.realm) |
| 30 | .finish_non_exhaustive() |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | #[derive(Deserialize)] |
| 35 | struct TokensAnswer { |
| 36 | tokens: Vec<RelayCredentials>, |
| 37 | #[serde(default)] |
| 38 | expires: u64, |
| 39 | } |
| 40 | |
| 41 | #[derive(Debug, Clone)] |
| 42 | pub struct RelayGrant { |
| 43 | pub credentials: RelayCredentials, |
| 44 | pub expires_in_seconds: u64, |
| 45 | } |
| 46 | |
| 47 | impl RelayGrant { |
| 48 | pub fn ice_server(&self, relay_host: &str) -> IceServer { |
| 49 | IceServer { |
| 50 | urls: vec![ |
| 51 | format!("turn:{relay_host}:3478?transport=udp"), |
| 52 | format!("turn:{relay_host}:443?transport=tcp"), |
| 53 | format!("turns:{relay_host}:443"), |
| 54 | ], |
| 55 | username: self.credentials.username.clone(), |
| 56 | password: self.credentials.password.clone(), |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | pub async fn fetch_relay_grant(session: &Session) -> Result<RelayGrant> { |
| 62 | let mut request = Request::get(TOKENS_URL); |
| 63 | request.headers = vec![ |
| 64 | ("api-version".into(), "2".into()), |
| 65 | ("X-MS-Migration".into(), "True".into()), |
| 66 | ("Accept".into(), "application/json, text/javascript".into()), |
| 67 | ]; |
| 68 | let response = session.send(request, &ic3_scope()).await?; |
| 69 | let answer: TokensAnswer = serde_json::from_value(response.body) |
| 70 | .map_err(|error| Error::Signaling(format!("trap/tokens answer: {error}")))?; |
| 71 | let credentials = answer |
| 72 | .tokens |
| 73 | .into_iter() |
| 74 | .next() |
| 75 | .ok_or_else(|| Error::Signaling("trap/tokens returned no relay token".into()))?; |
| 76 | Ok(RelayGrant { |
| 77 | credentials, |
| 78 | expires_in_seconds: answer.expires, |
| 79 | }) |
| 80 | } |
| 81 | |
| 82 | const MAX_REFRESH_MARGIN: Duration = Duration::from_secs(3600); |
| 83 | |
| 84 | /// One relay grant per engine, fetched once and reused while it stays valid. |
| 85 | #[derive(Default)] |
| 86 | pub struct RelayCache { |
| 87 | cached: tokio::sync::Mutex<Option<(RelayGrant, Instant)>>, |
| 88 | } |
| 89 | |
| 90 | impl RelayCache { |
| 91 | pub async fn grant(&self, session: &Session) -> Result<RelayGrant> { |
| 92 | let mut cached = self.cached.lock().await; |
| 93 | if let Some((grant, fetched)) = cached.as_ref() |
| 94 | && still_fresh(grant.expires_in_seconds, fetched.elapsed()) |
| 95 | { |
| 96 | return Ok(grant.clone()); |
| 97 | } |
| 98 | let grant = fetch_relay_grant(session).await?; |
| 99 | *cached = Some((grant.clone(), Instant::now())); |
| 100 | Ok(grant) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | fn still_fresh(expires_in_seconds: u64, age: Duration) -> bool { |
| 105 | let lifetime = Duration::from_secs(expires_in_seconds); |
| 106 | age + (lifetime / 2).min(MAX_REFRESH_MARGIN) < lifetime |
| 107 | } |
| 108 | |
| 109 | #[cfg(test)] |
| 110 | mod tests { |
| 111 | use super::*; |
| 112 | |
| 113 | #[test] |
| 114 | fn a_grant_is_reused_until_an_hour_before_it_expires() { |
| 115 | let week = 604_800; |
| 116 | assert!(still_fresh(week, Duration::from_secs(60))); |
| 117 | assert!(still_fresh(week, Duration::from_secs(week - 3601))); |
| 118 | assert!(!still_fresh(week, Duration::from_secs(week - 3600))); |
| 119 | assert!(still_fresh(600, Duration::from_secs(200))); |
| 120 | assert!(!still_fresh(600, Duration::from_secs(300))); |
| 121 | assert!(!still_fresh(0, Duration::ZERO)); |
| 122 | } |
| 123 | |
| 124 | #[test] |
| 125 | fn debug_never_shows_secrets() { |
| 126 | let credentials = RelayCredentials { |
| 127 | realm: "rtcmedia".into(), |
| 128 | username: "user-secret".into(), |
| 129 | password: "pass-secret".into(), |
| 130 | }; |
| 131 | let text = format!("{credentials:?}"); |
| 132 | assert!(text.contains("rtcmedia") && !text.contains("secret")); |
| 133 | } |
| 134 | |
| 135 | #[test] |
| 136 | fn ice_server_lists_udp_tcp_and_tls() { |
| 137 | let grant = RelayGrant { |
| 138 | credentials: RelayCredentials { |
| 139 | realm: String::new(), |
| 140 | username: "u".into(), |
| 141 | password: "p".into(), |
| 142 | }, |
| 143 | expires_in_seconds: 604800, |
| 144 | }; |
| 145 | let server = grant.ice_server(DEFAULT_RELAY_HOST); |
| 146 | assert_eq!(server.urls.len(), 3); |
| 147 | assert!(server.urls[2].starts_with("turns:")); |
| 148 | } |
| 149 | } |