| 1 | use serde_json::{Value, json}; |
| 2 | use session::{Method, Request, SPACES, Scope, Session}; |
| 3 | |
| 4 | use crate::error::Result; |
| 5 | use crate::language_settings::with_headers; |
| 6 | use crate::messages::{encode, ensure_success}; |
| 7 | use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport}; |
| 8 | |
| 9 | const SKYPE_SCOPE: &str = "user_impersonation"; |
| 10 | const ORGID_PREFIX: &str = "8:orgid:"; |
| 11 | const LIVE_PREFIX: &str = "8:live:"; |
| 12 | const PROFILE_QUERY: &str = |
| 13 | "isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true"; |
| 14 | const PROFILES_PER_REQUEST: usize = 100; |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct UserProfile { |
| 18 | pub user_id: String, |
| 19 | pub display_name: Option<String>, |
| 20 | pub email: Option<String>, |
| 21 | pub user_principal_name: Option<String>, |
| 22 | pub job_title: Option<String>, |
| 23 | pub department: Option<String>, |
| 24 | pub tenant_name: Option<String>, |
| 25 | } |
| 26 | |
| 27 | pub struct UserProfiles<T: CsaTransport = SessionTransport> { |
| 28 | transport: T, |
| 29 | users_url: String, |
| 30 | } |
| 31 | |
| 32 | impl UserProfiles<SessionTransport> { |
| 33 | pub fn new(session: &Session) -> Self { |
| 34 | let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE)); |
| 35 | UserProfiles::with_transport(transport, DEFAULT_REGION) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | impl<T: CsaTransport> UserProfiles<T> { |
| 40 | pub fn with_transport(transport: T, region: &str) -> Self { |
| 41 | UserProfiles { |
| 42 | transport, |
| 43 | users_url: format!("https://teams.cloud.microsoft/api/mt/{region}/beta/users"), |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | pub async fn fetch(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> { |
| 48 | self.post_mris( |
| 49 | &format!("{}/fetchShortProfile?{PROFILE_QUERY}", self.users_url), |
| 50 | user_ids, |
| 51 | ) |
| 52 | .await |
| 53 | } |
| 54 | |
| 55 | /// People of other organizations; the short profile lookup answers nothing for them. |
| 56 | pub async fn fetch_federated(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> { |
| 57 | self.post_mris(&format!("{}/fetchFederated", self.users_url), user_ids) |
| 58 | .await |
| 59 | } |
| 60 | |
| 61 | /// Teams finds a person of another organization only by the full email address. |
| 62 | pub async fn search_external(&self, email: &str) -> Result<Vec<UserProfile>> { |
| 63 | let answer = self |
| 64 | .transport |
| 65 | .send(with_headers(Request::get(format!( |
| 66 | "{}/{}/externalsearchv3?includeTFLUsers=true&includeEDUsers=true", |
| 67 | self.users_url, |
| 68 | encode(email.trim()) |
| 69 | )))) |
| 70 | .await?; |
| 71 | ensure_success(&answer)?; |
| 72 | Ok(parse_user_profiles(&answer.body)) |
| 73 | } |
| 74 | |
| 75 | async fn post_mris(&self, url: &str, user_ids: &[String]) -> Result<Vec<UserProfile>> { |
| 76 | let mut profiles = Vec::new(); |
| 77 | for chunk in user_ids.chunks(PROFILES_PER_REQUEST) { |
| 78 | let mris: Vec<Value> = chunk |
| 79 | .iter() |
| 80 | .map(|user_id| json!(format!("{ORGID_PREFIX}{user_id}"))) |
| 81 | .collect(); |
| 82 | let answer = self |
| 83 | .transport |
| 84 | .send(with_headers(Request::with_body( |
| 85 | Method::Post, |
| 86 | url.to_owned(), |
| 87 | Value::Array(mris), |
| 88 | ))) |
| 89 | .await?; |
| 90 | ensure_success(&answer)?; |
| 91 | profiles.extend(parse_user_profiles(&answer.body)); |
| 92 | } |
| 93 | Ok(profiles) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | fn profile_items(body: &Value) -> Vec<&Value> { |
| 98 | match body { |
| 99 | Value::Array(items) => items.iter().collect(), |
| 100 | Value::Object(_) => { |
| 101 | if let Some(items) = body.get("value").and_then(Value::as_array) { |
| 102 | return items.iter().collect(); |
| 103 | } |
| 104 | if let Some(profile) = body.get("value").filter(|value| value.is_object()) { |
| 105 | return vec![profile]; |
| 106 | } |
| 107 | if body.get("mri").is_some() || body.get("objectId").is_some() { |
| 108 | return vec![body]; |
| 109 | } |
| 110 | Vec::new() |
| 111 | } |
| 112 | _ => Vec::new(), |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> { |
| 117 | profile_items(body) |
| 118 | .into_iter() |
| 119 | .filter_map(|profile| { |
| 120 | let user_id = profile_user_id(profile)?; |
| 121 | Some(UserProfile { |
| 122 | user_id, |
| 123 | display_name: text(profile, "displayName"), |
| 124 | email: text(profile, "email") |
| 125 | .or_else(|| text(profile, "mail")) |
| 126 | .or_else(|| email_from_info(profile)) |
| 127 | .or_else(|| text(profile, "userPrincipalName")), |
| 128 | user_principal_name: text(profile, "userPrincipalName"), |
| 129 | job_title: text(profile, "jobTitle"), |
| 130 | department: text(profile, "department"), |
| 131 | tenant_name: text(profile, "tenantName"), |
| 132 | }) |
| 133 | }) |
| 134 | .collect() |
| 135 | } |
| 136 | |
| 137 | fn profile_user_id(profile: &Value) -> Option<String> { |
| 138 | if let Some(id) = text(profile, "objectId") { |
| 139 | return Some(id); |
| 140 | } |
| 141 | let mri = profile.get("mri").and_then(Value::as_str)?; |
| 142 | if let Some(id) = mri.strip_prefix(ORGID_PREFIX).filter(|id| !id.is_empty()) { |
| 143 | return Some(id.to_owned()); |
| 144 | } |
| 145 | mri.starts_with(LIVE_PREFIX) |
| 146 | .then(|| mri.to_owned()) |
| 147 | .filter(|id| id.len() > LIVE_PREFIX.len()) |
| 148 | } |
| 149 | |
| 150 | fn email_from_info(profile: &Value) -> Option<String> { |
| 151 | match profile.get("emailsInfo")? { |
| 152 | Value::String(value) => text_value(value), |
| 153 | Value::Array(items) => items.iter().find_map(email_info_item), |
| 154 | Value::Object(_) => email_info_item(profile.get("emailsInfo")?), |
| 155 | _ => None, |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | fn email_info_item(item: &Value) -> Option<String> { |
| 160 | text(item, "address") |
| 161 | .or_else(|| text(item, "email")) |
| 162 | .or_else(|| text(item, "smtp")) |
| 163 | .or_else(|| item.as_str().and_then(text_value)) |
| 164 | } |
| 165 | |
| 166 | fn text_value(value: &str) -> Option<String> { |
| 167 | let value = value.trim(); |
| 168 | (!value.is_empty()).then(|| value.to_owned()) |
| 169 | } |
| 170 | |
| 171 | fn text(profile: &Value, key: &str) -> Option<String> { |
| 172 | profile |
| 173 | .get(key) |
| 174 | .and_then(Value::as_str) |
| 175 | .map(str::trim) |
| 176 | .filter(|text| !text.is_empty()) |
| 177 | .map(str::to_owned) |
| 178 | } |
| 179 | |
| 180 | #[cfg(test)] |
| 181 | mod tests { |
| 182 | use std::sync::Mutex; |
| 183 | |
| 184 | use session::ApiResponse; |
| 185 | |
| 186 | use super::*; |
| 187 | |
| 188 | struct Canned { |
| 189 | requests: Mutex<Vec<Request>>, |
| 190 | } |
| 191 | |
| 192 | impl CsaTransport for &Canned { |
| 193 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 194 | self.requests.lock().unwrap().push(request); |
| 195 | Ok(ApiResponse { |
| 196 | status: 200, |
| 197 | body: json!({"value": [ |
| 198 | {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann Example", "email": "ann@example.com"}, |
| 199 | {"mri": "8:orgid:bob", "displayName": " "}, |
| 200 | ]}), |
| 201 | retry_after: None, |
| 202 | }) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | #[tokio::test] |
| 207 | async fn profiles_post_mris_and_read_names() { |
| 208 | let canned = Canned { |
| 209 | requests: Mutex::new(Vec::new()), |
| 210 | }; |
| 211 | let profiles = UserProfiles::with_transport(&canned, "emea") |
| 212 | .fetch(&["ann".into(), "bob".into()]) |
| 213 | .await |
| 214 | .unwrap(); |
| 215 | assert_eq!(profiles[0].display_name.as_deref(), Some("Ann Example")); |
| 216 | assert_eq!(profiles[0].email.as_deref(), Some("ann@example.com")); |
| 217 | assert_eq!(profiles[1].user_id, "bob"); |
| 218 | assert_eq!(profiles[1].display_name, None); |
| 219 | let requests = canned.requests.lock().unwrap(); |
| 220 | assert_eq!( |
| 221 | requests[0].body, |
| 222 | Some(json!(["8:orgid:ann", "8:orgid:bob"])) |
| 223 | ); |
| 224 | assert!(requests[0].url.contains("/users/fetchShortProfile?")); |
| 225 | } |
| 226 | |
| 227 | #[tokio::test] |
| 228 | async fn people_of_other_organizations_come_from_the_federated_lookup() { |
| 229 | let canned = Canned { |
| 230 | requests: Mutex::new(Vec::new()), |
| 231 | }; |
| 232 | UserProfiles::with_transport(&canned, "emea") |
| 233 | .fetch_federated(&["ann".into()]) |
| 234 | .await |
| 235 | .unwrap(); |
| 236 | let requests = canned.requests.lock().unwrap(); |
| 237 | assert!(requests[0].url.ends_with("/emea/beta/users/fetchFederated")); |
| 238 | assert_eq!(requests[0].body, Some(json!(["8:orgid:ann"]))); |
| 239 | } |
| 240 | |
| 241 | #[tokio::test] |
| 242 | async fn external_search_includes_federated_work_accounts() { |
| 243 | let canned = Canned { |
| 244 | requests: Mutex::new(Vec::new()), |
| 245 | }; |
| 246 | UserProfiles::with_transport(&canned, "emea") |
| 247 | .search_external("ada@other.example") |
| 248 | .await |
| 249 | .unwrap(); |
| 250 | let requests = canned.requests.lock().unwrap(); |
| 251 | assert!(requests[0].url.contains("includeTFLUsers=true")); |
| 252 | assert!(requests[0].url.contains("includeEDUsers=true")); |
| 253 | assert!( |
| 254 | requests[0].url.contains("ada%40other.example") |
| 255 | || requests[0].url.contains("ada@other.example") |
| 256 | ); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn an_external_profile_reads_mail_or_the_principal_name() { |
| 261 | let from_mail = parse_user_profiles(&json!( |
| 262 | {"mri": "8:orgid:ada", "displayName": "Ada", "mail": "ada@other.example"} |
| 263 | )); |
| 264 | assert_eq!(from_mail[0].email.as_deref(), Some("ada@other.example")); |
| 265 | let from_upn = parse_user_profiles(&json!({"value": { |
| 266 | "objectId": "bea", |
| 267 | "displayName": "Bea", |
| 268 | "userPrincipalName": "bea@other.example" |
| 269 | }})); |
| 270 | assert_eq!(from_upn[0].user_id, "bea"); |
| 271 | assert_eq!(from_upn[0].email.as_deref(), Some("bea@other.example")); |
| 272 | } |
| 273 | |
| 274 | #[test] |
| 275 | fn a_personal_account_keeps_its_live_mri_and_email() { |
| 276 | let profiles = parse_user_profiles(&json!([{ |
| 277 | "mri": "8:live:cid", |
| 278 | "displayName": "Joe", |
| 279 | "userPrincipalName": "live.cid", |
| 280 | "emailsInfo": [{"address": "joe@example.net"}], |
| 281 | "skypeId": "x", |
| 282 | "type": "TflUser" |
| 283 | }])); |
| 284 | assert_eq!(profiles.len(), 1); |
| 285 | assert_eq!(profiles[0].user_id, "8:live:cid"); |
| 286 | assert_eq!(profiles[0].email.as_deref(), Some("joe@example.net")); |
| 287 | assert_eq!(profiles[0].display_name.as_deref(), Some("Joe")); |
| 288 | } |
| 289 | |
| 290 | #[test] |
| 291 | fn a_federated_profile_carries_its_organization() { |
| 292 | let profiles = parse_user_profiles(&json!({"value": [ |
| 293 | {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann", "tenantName": "Example Corp"}, |
| 294 | ]})); |
| 295 | assert_eq!(profiles[0].tenant_name.as_deref(), Some("Example Corp")); |
| 296 | } |
| 297 | } |