BlueGit

ict rusty-teams

fix(security): check URL hosts with a parser and route opened links through one gate

- session::trusted_url: host checks on url::Url (https, no user info, no port), used for link preview, AMS, calling, inline video and origin checks
- Session::batch and the skype-token transport only attach credentials for Microsoft hosts
- app_base::open_link: one allowlist for every URL handed to the OS; a test rejects raw cx.open_url
- Video embed: Microsoft hosts only, no external app launch, only user-initiated new windows
- Calls: both mic tracks follow the initial mute and stay off during setup; hold silences restarted software audio
- Credential allowlist includes the Defender for Cloud Apps proxy (mcas.ms); origin checks use App::is_app_url
- cargo fmt on three unrelated files

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-29 · 2 days ago

Hash
6f1532871f5f41aa6478627d0a10ac3a151b9016
Parent
d5f922eb
45 files changed +575 −149
Cargo.lock +2 −0
@@ -340,6 +340,7 @@ dependencies = [
340 340 "tempfile",
341 341 "tokio",
342 342 "tray-icon",
343 "url",
343 344 "wayland-client",
344 345 "wayland-protocols",
345 346 "windows 0.62.2",
@@ -1236,6 +1237,7 @@ dependencies = [
1236 1237 "thiserror 2.0.21",
1237 1238 "tokio",
1238 1239 "tract-onnx",
1240 "url",
1239 1241 "uuid",
1240 1242 "webrtc-sys",
1241 1243 "webview",
@@ -340,6 +340,7 @@ dependencies = [
340 "tempfile",
340 "tempfile",
341 "tokio",
341 "tokio",
342 "tray-icon",
342 "tray-icon",
343 "url",
343 "wayland-client",
344 "wayland-client",
344 "wayland-protocols",
345 "wayland-protocols",
345 "windows 0.62.2",
346 "windows 0.62.2",
@@ -1236,6 +1237,7 @@ dependencies = [
1236 "thiserror 2.0.21",
1237 "thiserror 2.0.21",
1237 "tokio",
1238 "tokio",
1238 "tract-onnx",
1239 "tract-onnx",
1240 "url",
1239 "uuid",
1241 "uuid",
1240 "webrtc-sys",
1242 "webrtc-sys",
1241 "webview",
1243 "webview",
crates/app-base/Cargo.toml +1 −0
@@ -26,6 +26,7 @@ session.workspace = true
26 26 store.workspace = true
27 27 teams-core.workspace = true
28 28 tokio.workspace = true
29 url.workspace = true
29 30 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
30 31 raw-window-handle = "0.6"
31 32 sha2 = "0.10"
@@ -26,6 +26,7 @@ session.workspace = true
26store.workspace = true
26store.workspace = true
27teams-core.workspace = true
27teams-core.workspace = true
28tokio.workspace = true
28tokio.workspace = true
29url.workspace = true
29image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
30image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
30raw-window-handle = "0.6"
31raw-window-handle = "0.6"
31sha2 = "0.10"
32sha2 = "0.10"
crates/app-base/src/lib.rs +1 −0
@@ -30,6 +30,7 @@ pub mod linux_fonts;
30 30 mod linux_idle;
31 31 pub mod native_dumps;
32 32 pub mod notify;
33 pub mod open_link;
33 34 pub mod orgs;
34 35 pub mod presence_link;
35 36 pub mod read_state;
@@ -30,6 +30,7 @@ pub mod linux_fonts;
30mod linux_idle;
30mod linux_idle;
31pub mod native_dumps;
31pub mod native_dumps;
32pub mod notify;
32pub mod notify;
33pub mod open_link;
33pub mod orgs;
34pub mod orgs;
34pub mod presence_link;
35pub mod presence_link;
35pub mod read_state;
36pub mod read_state;
crates/app-base/src/release_feed.rs +5 −3
@@ -288,9 +288,11 @@ pub fn find_release(
288 288 let releases: Vec<Release> =
289 289 serde_json::from_slice(&get(&client, RELEASES_URL, None).await?)
290 290 .map_err(|error| error.to_string())?;
291 Ok(newest_release(running_tag, &releases).map(|release| TaggedRelease {
292 tag: release.tag_name.clone(),
293 }))
291 Ok(
292 newest_release(running_tag, &releases).map(|release| TaggedRelease {
293 tag: release.tag_name.clone(),
294 }),
295 )
294 296 })
295 297 }
296 298
@@ -288,9 +288,11 @@ pub fn find_release(
288 let releases: Vec<Release> =
288 let releases: Vec<Release> =
289 serde_json::from_slice(&get(&client, RELEASES_URL, None).await?)
289 serde_json::from_slice(&get(&client, RELEASES_URL, None).await?)
290 .map_err(|error| error.to_string())?;
290 .map_err(|error| error.to_string())?;
291 Ok(newest_release(running_tag, &releases).map(|release| TaggedRelease {
291 Ok(
292 tag: release.tag_name.clone(),
292 newest_release(running_tag, &releases).map(|release| TaggedRelease {
293 }))
293 tag: release.tag_name.clone(),
294 }),
295 )
294 })
296 })
295}
297}
296
298
crates/app-state/src/call/actions.rs +1 −1
@@ -549,7 +549,7 @@ impl AppState {
549 549 return;
550 550 }
551 551 CallUpdate::WhiteboardUrl(url) => {
552 cx.open_url(&url);
552 app_base::open_link::open_url(cx, &url);
553 553 return;
554 554 }
555 555 CallUpdate::BreakoutMove(moved) => {
@@ -549,7 +549,7 @@ impl AppState {
549 return;
549 return;
550 }
550 }
551 CallUpdate::WhiteboardUrl(url) => {
551 CallUpdate::WhiteboardUrl(url) => {
552 cx.open_url(&url);
552 app_base::open_link::open_url(cx, &url);
553 return;
553 return;
554 }
554 }
555 CallUpdate::BreakoutMove(moved) => {
555 CallUpdate::BreakoutMove(moved) => {
crates/app-state/src/call/features.rs +1 −1
@@ -169,7 +169,7 @@ impl AppState {
169 169 return;
170 170 };
171 171 if let Some(url) = call.model.whiteboard_url() {
172 cx.open_url(url);
172 app_base::open_link::open_url(cx, url);
173 173 return;
174 174 }
175 175 let title = call.model.title.clone();
@@ -169,7 +169,7 @@ impl AppState {
169 return;
169 return;
170 };
170 };
171 if let Some(url) = call.model.whiteboard_url() {
171 if let Some(url) = call.model.whiteboard_url() {
172 cx.open_url(url);
172 app_base::open_link::open_url(cx, url);
173 return;
173 return;
174 }
174 }
175 let title = call.model.title.clone();
175 let title = call.model.title.clone();
crates/app-state/src/card_inputs.rs +1 −1
@@ -429,7 +429,7 @@ impl AppState {
429 429 cx: &mut Context<Self>,
430 430 ) {
431 431 match &action.kind {
432 CardActionKind::OpenUrl(url) => cx.open_url(url),
432 CardActionKind::OpenUrl(url) => app_base::open_link::open_url(cx, url),
433 433 _ => self.run_card_action(
434 434 scope.clone(),
435 435 action_key,
@@ -429,7 +429,7 @@ impl AppState {
429 cx: &mut Context<Self>,
429 cx: &mut Context<Self>,
430 ) {
430 ) {
431 match &action.kind {
431 match &action.kind {
432 CardActionKind::OpenUrl(url) => cx.open_url(url),
432 CardActionKind::OpenUrl(url) => app_base::open_link::open_url(cx, url),
433 _ => self.run_card_action(
433 _ => self.run_card_action(
434 scope.clone(),
434 scope.clone(),
435 action_key,
435 action_key,
crates/app-state/src/channel_menu.rs +1 −1
@@ -395,7 +395,7 @@ impl AppState {
395 395 cx.write_to_clipboard(ClipboardItem::new_string(link));
396 396 self.raise_notice(COPIED_TO_CLIPBOARD.to_owned(), None, cx);
397 397 }
398 LinkUse::OpenInBrowser => cx.open_url(&link),
398 LinkUse::OpenInBrowser => app_base::open_link::open_url(cx, &link),
399 399 }
400 400 }
401 401
@@ -395,7 +395,7 @@ impl AppState {
395 cx.write_to_clipboard(ClipboardItem::new_string(link));
395 cx.write_to_clipboard(ClipboardItem::new_string(link));
396 self.raise_notice(COPIED_TO_CLIPBOARD.to_owned(), None, cx);
396 self.raise_notice(COPIED_TO_CLIPBOARD.to_owned(), None, cx);
397 }
397 }
398 LinkUse::OpenInBrowser => cx.open_url(&link),
398 LinkUse::OpenInBrowser => app_base::open_link::open_url(cx, &link),
399 }
399 }
400 }
400 }
401
401
crates/app-state/src/external_browser.rs +7 −2
@@ -49,14 +49,19 @@ pub fn save(store: &Store, browser: &ExternalBrowser) {
49 49 }
50 50
51 51 pub fn open_url(cx: &mut App, store: &Store, url: &str) {
52 let Some(url) = app_base::open_link::openable_url(url) else {
53 app_base::open_link::open_url(cx, url);
54 return;
55 };
56 let url = url.as_str();
52 57 match load(store) {
53 ExternalBrowser::System => cx.open_url(url),
58 ExternalBrowser::System => app_base::open_link::open_url(cx, url),
54 59 ExternalBrowser::Program(program) => {
55 60 let known = available_choices()
56 61 .iter()
57 62 .any(|choice| choice.id == program);
58 63 if !known || launch_program(&program, url).is_err() {
59 cx.open_url(url);
64 app_base::open_link::open_url(cx, url);
60 65 }
61 66 }
62 67 }
@@ -49,14 +49,19 @@ pub fn save(store: &Store, browser: &ExternalBrowser) {
49}
49}
50
50
51pub fn open_url(cx: &mut App, store: &Store, url: &str) {
51pub fn open_url(cx: &mut App, store: &Store, url: &str) {
52 let Some(url) = app_base::open_link::openable_url(url) else {
53 app_base::open_link::open_url(cx, url);
54 return;
55 };
56 let url = url.as_str();
52 match load(store) {
57 match load(store) {
53 ExternalBrowser::System => cx.open_url(url),
58 ExternalBrowser::System => app_base::open_link::open_url(cx, url),
54 ExternalBrowser::Program(program) => {
59 ExternalBrowser::Program(program) => {
55 let known = available_choices()
60 let known = available_choices()
56 .iter()
61 .iter()
57 .any(|choice| choice.id == program);
62 .any(|choice| choice.id == program);
58 if !known || launch_program(&program, url).is_err() {
63 if !known || launch_program(&program, url).is_err() {
59 cx.open_url(url);
64 app_base::open_link::open_url(cx, url);
60 }
65 }
61 }
66 }
62 }
67 }
crates/app-state/src/share_outlook.rs +8 −2
@@ -58,7 +58,10 @@ impl AppState {
58 58 if self.mode.demo {
59 59 let link = teams_core::chat_message_link(conversation_id, message_id, None);
60 60 let body = share_body(&record, Some(&link));
61 cx.open_url(&teams_core::outlook_compose_link(&subject, &body));
61 app_base::open_link::open_url(
62 cx,
63 &teams_core::outlook_compose_link(&subject, &body),
64 );
62 65 }
63 66 return;
64 67 };
@@ -76,7 +79,10 @@ impl AppState {
76 79 state.raise_notice(format!("No link to the message: {reason}"), None, cx);
77 80 }
78 81 let body = share_body(&record, link.as_deref().ok());
79 cx.open_url(&teams_core::outlook_compose_link(&subject, &body));
82 app_base::open_link::open_url(
83 cx,
84 &teams_core::outlook_compose_link(&subject, &body),
85 );
80 86 })
81 87 .ok();
82 88 })
@@ -58,7 +58,10 @@ impl AppState {
58 if self.mode.demo {
58 if self.mode.demo {
59 let link = teams_core::chat_message_link(conversation_id, message_id, None);
59 let link = teams_core::chat_message_link(conversation_id, message_id, None);
60 let body = share_body(&record, Some(&link));
60 let body = share_body(&record, Some(&link));
61 cx.open_url(&teams_core::outlook_compose_link(&subject, &body));
61 app_base::open_link::open_url(
62 cx,
63 &teams_core::outlook_compose_link(&subject, &body),
64 );
62 }
65 }
63 return;
66 return;
64 };
67 };
@@ -76,7 +79,10 @@ impl AppState {
76 state.raise_notice(format!("No link to the message: {reason}"), None, cx);
79 state.raise_notice(format!("No link to the message: {reason}"), None, cx);
77 }
80 }
78 let body = share_body(&record, link.as_deref().ok());
81 let body = share_body(&record, link.as_deref().ok());
79 cx.open_url(&teams_core::outlook_compose_link(&subject, &body));
82 app_base::open_link::open_url(
83 cx,
84 &teams_core::outlook_compose_link(&subject, &body),
85 );
80 })
86 })
81 .ok();
87 .ok();
82 })
88 })
crates/app-state/src/task_dialog.rs +1 −1
@@ -45,5 +45,5 @@ pub fn open_url_dialog(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut
45 45
46 46 #[cfg(not(windows))]
47 47 pub fn open_url_dialog(dialog: UrlDialog, _engine: Option<Arc<Engine>>, cx: &mut App) {
48 cx.open_url(&dialog.fallback_url);
48 app_base::open_link::open_url(cx, &dialog.fallback_url);
49 49 }
@@ -45,5 +45,5 @@ pub fn open_url_dialog(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut
45
45
46#[cfg(not(windows))]
46#[cfg(not(windows))]
47pub fn open_url_dialog(dialog: UrlDialog, _engine: Option<Arc<Engine>>, cx: &mut App) {
47pub fn open_url_dialog(dialog: UrlDialog, _engine: Option<Arc<Engine>>, cx: &mut App) {
48 cx.open_url(&dialog.fallback_url);
48 app_base::open_link::open_url(cx, &dialog.fallback_url);
49}
49}
crates/app-state/src/task_dialog/hosted.rs +2 −2
@@ -19,7 +19,7 @@ pub fn install_host(transport: Arc<WebViewTransport>) {
19 19
20 20 pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
21 21 let Some(host) = HOST.get().cloned() else {
22 cx.open_url(&dialog.fallback_url);
22 app_base::open_link::open_url(cx, &dialog.fallback_url);
23 23 return;
24 24 };
25 25 let state = cx.global::<AppHandle>().0.clone();
@@ -105,7 +105,7 @@ async fn apply(
105 105 match effect {
106 106 Effect::Resize { width, height } => handle.resize(width, height),
107 107 Effect::OpenLink(link) => {
108 cx.update(|cx| cx.open_url(&link));
108 cx.update(|cx| app_base::open_link::open_url(cx, &link));
109 109 }
110 110 Effect::Submit(result) => {
111 111 let scope = dialog.scope.clone();
@@ -19,7 +19,7 @@ pub fn install_host(transport: Arc<WebViewTransport>) {
19
19
20pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
20pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
21 let Some(host) = HOST.get().cloned() else {
21 let Some(host) = HOST.get().cloned() else {
22 cx.open_url(&dialog.fallback_url);
22 app_base::open_link::open_url(cx, &dialog.fallback_url);
23 return;
23 return;
24 };
24 };
25 let state = cx.global::<AppHandle>().0.clone();
25 let state = cx.global::<AppHandle>().0.clone();
@@ -105,7 +105,7 @@ async fn apply(
105 match effect {
105 match effect {
106 Effect::Resize { width, height } => handle.resize(width, height),
106 Effect::Resize { width, height } => handle.resize(width, height),
107 Effect::OpenLink(link) => {
107 Effect::OpenLink(link) => {
108 cx.update(|cx| cx.open_url(&link));
108 cx.update(|cx| app_base::open_link::open_url(cx, &link));
109 }
109 }
110 Effect::Submit(result) => {
110 Effect::Submit(result) => {
111 let scope = dialog.scope.clone();
111 let scope = dialog.scope.clone();
crates/app-ui-kit/src/render/blocks.rs +3 −1
@@ -141,7 +141,9 @@ impl Inline {
141 141 pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {
142 142 let mut padded = self.clone();
143 143 padded.push(
144 &super::selectable::TIME_ROOM.to_string().repeat(width_in_spaces),
144 &super::selectable::TIME_ROOM
145 .to_string()
146 .repeat(width_in_spaces),
145 147 StyleFlags::default(),
146 148 None,
147 149 );
@@ -141,7 +141,9 @@ impl Inline {
141 pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {
141 pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {
142 let mut padded = self.clone();
142 let mut padded = self.clone();
143 padded.push(
143 padded.push(
144 &super::selectable::TIME_ROOM.to_string().repeat(width_in_spaces),
144 &super::selectable::TIME_ROOM
145 .to_string()
146 .repeat(width_in_spaces),
145 StyleFlags::default(),
147 StyleFlags::default(),
146 None,
148 None,
147 );
149 );
crates/app-ui-kit/src/render/flow_text.rs +1 −1
@@ -977,7 +977,7 @@ mod tests {
977 977 cx.opened_url().is_some()
978 978 });
979 979 assert!(link_x.is_some());
980 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
980 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/"));
981 981 }
982 982
983 983 struct Links {
@@ -977,7 +977,7 @@ mod tests {
977 cx.opened_url().is_some()
977 cx.opened_url().is_some()
978 });
978 });
979 assert!(link_x.is_some());
979 assert!(link_x.is_some());
980 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
980 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/"));
981 }
981 }
982
982
983 struct Links {
983 struct Links {
crates/app-ui-kit/src/render/hooks.rs +2 −24
@@ -17,30 +17,8 @@ pub fn open_profile_link(url: &str, position: Point<Pixels>, cx: &mut App) -> bo
17 17 }
18 18 }
19 19
20 const OPENABLE_SCHEMES: [&str; 16] = [
21 "https://",
22 "http://",
23 "mailto:",
24 "tel:",
25 "sip:",
26 "callto:",
27 "msteams:",
28 "onenote:",
29 "ms-word:",
30 "ms-excel:",
31 "ms-powerpoint:",
32 "ms-visio:",
33 "ms-access:",
34 "ms-project:",
35 "ms-publisher:",
36 "ms-infopath:",
37 ];
38
39 20 pub fn is_openable_link(url: &str) -> bool {
40 let lower = url.trim_start().to_ascii_lowercase();
41 OPENABLE_SCHEMES
42 .iter()
43 .any(|scheme| lower.starts_with(scheme))
21 app_base::open_link::is_openable_url(url)
44 22 }
45 23
46 24 pub fn open_link(url: &str, cx: &mut App) {
@@ -49,7 +27,7 @@ pub fn open_link(url: &str, cx: &mut App) {
49 27 }
50 28 match cx.try_global::<RenderHooks>().copied() {
51 29 Some(hooks) => (hooks.open_link)(url, cx),
52 None => cx.open_url(url),
30 None => app_base::open_link::open_url(cx, url),
53 31 }
54 32 }
55 33
@@ -17,30 +17,8 @@ pub fn open_profile_link(url: &str, position: Point<Pixels>, cx: &mut App) -> bo
17 }
17 }
18}
18}
19
19
20const OPENABLE_SCHEMES: [&str; 16] = [
21 "https://",
22 "http://",
23 "mailto:",
24 "tel:",
25 "sip:",
26 "callto:",
27 "msteams:",
28 "onenote:",
29 "ms-word:",
30 "ms-excel:",
31 "ms-powerpoint:",
32 "ms-visio:",
33 "ms-access:",
34 "ms-project:",
35 "ms-publisher:",
36 "ms-infopath:",
37];
38
39pub fn is_openable_link(url: &str) -> bool {
20pub fn is_openable_link(url: &str) -> bool {
40 let lower = url.trim_start().to_ascii_lowercase();
21 app_base::open_link::is_openable_url(url)
41 OPENABLE_SCHEMES
42 .iter()
43 .any(|scheme| lower.starts_with(scheme))
44}
22}
45
23
46pub fn open_link(url: &str, cx: &mut App) {
24pub fn open_link(url: &str, cx: &mut App) {
@@ -49,7 +27,7 @@ pub fn open_link(url: &str, cx: &mut App) {
49 }
27 }
50 match cx.try_global::<RenderHooks>().copied() {
28 match cx.try_global::<RenderHooks>().copied() {
51 Some(hooks) => (hooks.open_link)(url, cx),
29 Some(hooks) => (hooks.open_link)(url, cx),
52 None => cx.open_url(url),
30 None => app_base::open_link::open_url(cx, url),
53 }
31 }
54}
32}
55
33
crates/app-ui-kit/src/render/selectable.rs +1 −1
@@ -515,7 +515,7 @@ mod tests {
515 515 cx.opened_url().is_some()
516 516 });
517 517 assert!(link_x.is_some());
518 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
518 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/"));
519 519 }
520 520
521 521 #[test]
@@ -515,7 +515,7 @@ mod tests {
515 cx.opened_url().is_some()
515 cx.opened_url().is_some()
516 });
516 });
517 assert!(link_x.is_some());
517 assert!(link_x.is_some());
518 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
518 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/"));
519 }
519 }
520
520
521 #[test]
521 #[test]
crates/app/src/inline_video.rs +16 −5
@@ -2,6 +2,7 @@ use std::cell::Cell;
2 2 use std::rc::Rc;
3 3
4 4 use gpui_kit::*;
5 use session::trusted_url::{HostRule, trusted_https_url};
5 6
6 7 #[cfg(windows)]
7 8 mod native_windows;
@@ -17,18 +18,20 @@ pub use native::available;
17 18 #[cfg(windows)]
18 19 pub use native::configure;
19 20
21 const SHAREPOINT_DOMAIN: &str = "sharepoint.com";
22 const SHAREPOINT_HOSTS: [HostRule; 1] = [HostRule::Domain(SHAREPOINT_DOMAIN)];
20 23 const PERSONAL_SITE: &str = "/personal/";
21 24 const TEAM_SITES: [&str; 2] = ["/sites/", "/teams/"];
22 25 const PLAYER_OPTIONS: &str = "%7B%22ust%22%3Atrue%2C%22hv%22%3A%22CopyEmbedCode%22%7D";
23 26
24 27 /// SharePoint's embeddable player for a video stored in OneDrive or a team site.
25 28 pub fn player_url(content_url: &str) -> Option<String> {
26 let rest = content_url.strip_prefix("https://")?;
27 let (host, path) = rest.split_once('/')?;
28 if !host.ends_with(".sharepoint.com") {
29 let parsed = trusted_https_url(content_url, &SHAREPOINT_HOSTS)?;
30 let host = parsed.host_str()?;
31 if host == SHAREPOINT_DOMAIN {
29 32 return None;
30 33 }
31 let path = format!("/{}", path.split(['?', '#']).next()?);
34 let path = parsed.path();
32 35 let site_prefix = std::iter::once(PERSONAL_SITE)
33 36 .chain(TEAM_SITES)
34 37 .find(|prefix| path.starts_with(prefix))?;
@@ -67,7 +70,7 @@ pub fn play(key: SharedString, content_url: &str, window: &mut Window, cx: &mut
67 70 };
68 71 cx.spawn(async move |cx| {
69 72 while let Some(target) = new_windows.recv().await {
70 cx.update(|cx| cx.open_url(&target));
73 cx.update(|cx| app_base::open_link::open_url(cx, &target));
71 74 }
72 75 })
73 76 .detach();
@@ -188,6 +191,14 @@ mod tests {
188 191 #[test]
189 192 fn other_hosts_have_no_inline_player() {
190 193 assert_eq!(player_url("https://example.com/personal/a/clip.mp4"), None);
194 assert_eq!(
195 player_url("https://evil.example?a.sharepoint.com/personal/x/y.mp4"),
196 None
197 );
198 assert_eq!(
199 player_url("https://evil.example\\.sharepoint.com/personal/x/y.mp4"),
200 None
201 );
191 202 assert_eq!(player_url("https://contoso.sharepoint.com/clip.mp4"), None);
192 203 assert_eq!(
193 204 player_url("https://contoso-my.sharepoint.com/personal/"),
@@ -2,6 +2,7 @@ use std::cell::Cell;
2use std::rc::Rc;
2use std::rc::Rc;
3
3
4use gpui_kit::*;
4use gpui_kit::*;
5use session::trusted_url::{HostRule, trusted_https_url};
5
6
6#[cfg(windows)]
7#[cfg(windows)]
7mod native_windows;
8mod native_windows;
@@ -17,18 +18,20 @@ pub use native::available;
17#[cfg(windows)]
18#[cfg(windows)]
18pub use native::configure;
19pub use native::configure;
19
20
21const SHAREPOINT_DOMAIN: &str = "sharepoint.com";
22const SHAREPOINT_HOSTS: [HostRule; 1] = [HostRule::Domain(SHAREPOINT_DOMAIN)];
20const PERSONAL_SITE: &str = "/personal/";
23const PERSONAL_SITE: &str = "/personal/";
21const TEAM_SITES: [&str; 2] = ["/sites/", "/teams/"];
24const TEAM_SITES: [&str; 2] = ["/sites/", "/teams/"];
22const PLAYER_OPTIONS: &str = "%7B%22ust%22%3Atrue%2C%22hv%22%3A%22CopyEmbedCode%22%7D";
25const PLAYER_OPTIONS: &str = "%7B%22ust%22%3Atrue%2C%22hv%22%3A%22CopyEmbedCode%22%7D";
23
26
24/// SharePoint's embeddable player for a video stored in OneDrive or a team site.
27/// SharePoint's embeddable player for a video stored in OneDrive or a team site.
25pub fn player_url(content_url: &str) -> Option<String> {
28pub fn player_url(content_url: &str) -> Option<String> {
26 let rest = content_url.strip_prefix("https://")?;
29 let parsed = trusted_https_url(content_url, &SHAREPOINT_HOSTS)?;
27 let (host, path) = rest.split_once('/')?;
30 let host = parsed.host_str()?;
28 if !host.ends_with(".sharepoint.com") {
31 if host == SHAREPOINT_DOMAIN {
29 return None;
32 return None;
30 }
33 }
31 let path = format!("/{}", path.split(['?', '#']).next()?);
34 let path = parsed.path();
32 let site_prefix = std::iter::once(PERSONAL_SITE)
35 let site_prefix = std::iter::once(PERSONAL_SITE)
33 .chain(TEAM_SITES)
36 .chain(TEAM_SITES)
34 .find(|prefix| path.starts_with(prefix))?;
37 .find(|prefix| path.starts_with(prefix))?;
@@ -67,7 +70,7 @@ pub fn play(key: SharedString, content_url: &str, window: &mut Window, cx: &mut
67 };
70 };
68 cx.spawn(async move |cx| {
71 cx.spawn(async move |cx| {
69 while let Some(target) = new_windows.recv().await {
72 while let Some(target) = new_windows.recv().await {
70 cx.update(|cx| cx.open_url(&target));
73 cx.update(|cx| app_base::open_link::open_url(cx, &target));
71 }
74 }
72 })
75 })
73 .detach();
76 .detach();
@@ -188,6 +191,14 @@ mod tests {
188 #[test]
191 #[test]
189 fn other_hosts_have_no_inline_player() {
192 fn other_hosts_have_no_inline_player() {
190 assert_eq!(player_url("https://example.com/personal/a/clip.mp4"), None);
193 assert_eq!(player_url("https://example.com/personal/a/clip.mp4"), None);
194 assert_eq!(
195 player_url("https://evil.example?a.sharepoint.com/personal/x/y.mp4"),
196 None
197 );
198 assert_eq!(
199 player_url("https://evil.example\\.sharepoint.com/personal/x/y.mp4"),
200 None
201 );
191 assert_eq!(player_url("https://contoso.sharepoint.com/clip.mp4"), None);
202 assert_eq!(player_url("https://contoso.sharepoint.com/clip.mp4"), None);
192 assert_eq!(
203 assert_eq!(
193 player_url("https://contoso-my.sharepoint.com/personal/"),
204 player_url("https://contoso-my.sharepoint.com/personal/"),
crates/app/src/linux_update.rs +1 −1
@@ -469,7 +469,7 @@ fn build_dialog(dialog: Dialog, cx: &App) -> Dialog {
469 469 decline(&open, cx);
470 470 set_stage(Stage::Idle, cx);
471 471 close_dialog(window, cx);
472 cx.open_url(&url);
472 app_base::open_link::open_url(cx, &url);
473 473 }),
474 474 ),
475 475 )
@@ -469,7 +469,7 @@ fn build_dialog(dialog: Dialog, cx: &App) -> Dialog {
469 decline(&open, cx);
469 decline(&open, cx);
470 set_stage(Stage::Idle, cx);
470 set_stage(Stage::Idle, cx);
471 close_dialog(window, cx);
471 close_dialog(window, cx);
472 cx.open_url(&url);
472 app_base::open_link::open_url(cx, &url);
473 }),
473 }),
474 ),
474 ),
475 )
475 )
crates/app/src/settings/mcp.rs +3 −1
@@ -335,7 +335,9 @@ impl McpView {
335 335 this.update(cx, |this, cx| {
336 336 this.install_busy = None;
337 337 match result {
338 Ok(Some(InstallReport::OpenUrl(url))) => cx.open_url(&url),
338 Ok(Some(InstallReport::OpenUrl(url))) => {
339 app_base::open_link::open_url(cx, &url)
340 }
339 341 Ok(_) => {}
340 342 Err(error) => {
341 343 this.install_errors.insert(target, error.to_string());
@@ -335,7 +335,9 @@ impl McpView {
335 this.update(cx, |this, cx| {
335 this.update(cx, |this, cx| {
336 this.install_busy = None;
336 this.install_busy = None;
337 match result {
337 match result {
338 Ok(Some(InstallReport::OpenUrl(url))) => cx.open_url(&url),
338 Ok(Some(InstallReport::OpenUrl(url))) => {
339 app_base::open_link::open_url(cx, &url)
340 }
339 Ok(_) => {}
341 Ok(_) => {}
340 Err(error) => {
342 Err(error) => {
341 this.install_errors.insert(target, error.to_string());
343 this.install_errors.insert(target, error.to_string());
crates/app/src/views/adaptive_card.rs +1 −1
@@ -906,7 +906,7 @@ fn click_handler(
906 906 match &action.kind {
907 907 CardActionKind::OpenUrl(url) => {
908 908 let url = url.clone();
909 Some(Rc::new(move |cx| cx.open_url(&url)))
909 Some(Rc::new(move |cx| app_base::open_link::open_url(cx, &url)))
910 910 }
911 911 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
912 912 let action = action.clone();
@@ -906,7 +906,7 @@ fn click_handler(
906 match &action.kind {
906 match &action.kind {
907 CardActionKind::OpenUrl(url) => {
907 CardActionKind::OpenUrl(url) => {
908 let url = url.clone();
908 let url = url.clone();
909 Some(Rc::new(move |cx| cx.open_url(&url)))
909 Some(Rc::new(move |cx| app_base::open_link::open_url(cx, &url)))
910 }
910 }
911 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
911 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
912 let action = action.clone();
912 let action = action.clone();
crates/app/src/views/attachments.rs +1 −1
@@ -438,7 +438,7 @@ fn file_view(
438 438 .bg(theme::accent()),
439 439 )
440 440 })
441 .on_click(move |_, _, cx| cx.open_url(&url))
441 .on_click(move |_, _, cx| app_base::open_link::open_url(cx, &url))
442 442 .into_any_element()
443 443 }
444 444
@@ -438,7 +438,7 @@ fn file_view(
438 .bg(theme::accent()),
438 .bg(theme::accent()),
439 )
439 )
440 })
440 })
441 .on_click(move |_, _, cx| cx.open_url(&url))
441 .on_click(move |_, _, cx| app_base::open_link::open_url(cx, &url))
442 .into_any_element()
442 .into_any_element()
443}
443}
444
444
crates/app/src/views/card_media.rs +1 −1
@@ -49,7 +49,7 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
49 49 })
50 50 .on_click(move |_, _, cx| {
51 51 cx.stop_propagation();
52 cx.open_url(&source_url);
52 app_base::open_link::open_url(cx, &source_url);
53 53 })
54 54 .child(poster)
55 55 .child(
@@ -49,7 +49,7 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
49 })
49 })
50 .on_click(move |_, _, cx| {
50 .on_click(move |_, _, cx| {
51 cx.stop_propagation();
51 cx.stop_propagation();
52 cx.open_url(&source_url);
52 app_base::open_link::open_url(cx, &source_url);
53 })
53 })
54 .child(poster)
54 .child(poster)
55 .child(
55 .child(
crates/app/src/views/conversation/recap.rs +2 −2
@@ -274,7 +274,7 @@ impl ConversationView {
274 274 self.select_occurrence(index, cx);
275 275 }
276 276 }
277 (_, Some(url)) => cx.open_url(url),
277 (_, Some(url)) => app_base::open_link::open_url(cx, url),
278 278 (_, None) => {}
279 279 }
280 280 }
@@ -478,7 +478,7 @@ impl ConversationView {
478 478 RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),
479 479 RecapCommand::Play => {
480 480 if let Some(occurrence) = self.selected_occurrence() {
481 cx.open_url(&occurrence.recording_url);
481 app_base::open_link::open_url(cx, &occurrence.recording_url);
482 482 }
483 483 }
484 484 RecapCommand::Download(download) => self.pick_save_target(download, cx),
@@ -274,7 +274,7 @@ impl ConversationView {
274 self.select_occurrence(index, cx);
274 self.select_occurrence(index, cx);
275 }
275 }
276 }
276 }
277 (_, Some(url)) => cx.open_url(url),
277 (_, Some(url)) => app_base::open_link::open_url(cx, url),
278 (_, None) => {}
278 (_, None) => {}
279 }
279 }
280 }
280 }
@@ -478,7 +478,7 @@ impl ConversationView {
478 RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),
478 RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),
479 RecapCommand::Play => {
479 RecapCommand::Play => {
480 if let Some(occurrence) = self.selected_occurrence() {
480 if let Some(occurrence) = self.selected_occurrence() {
481 cx.open_url(&occurrence.recording_url);
481 app_base::open_link::open_url(cx, &occurrence.recording_url);
482 }
482 }
483 }
483 }
484 RecapCommand::Download(download) => self.pick_save_target(download, cx),
484 RecapCommand::Download(download) => self.pick_save_target(download, cx),
crates/app/src/views/conversation/shared.rs +6 −6
@@ -146,7 +146,7 @@ impl ConversationView {
146 146 };
147 147 let resolved = self.tab_links.get(&tab.tab_id).map(String::as_str);
148 148 match tab_action(&tab, resolved) {
149 TabAction::Browser(url) => cx.open_url(&url),
149 TabAction::Browser(url) => app_base::open_link::open_url(cx, &url),
150 150 TabAction::ResolveLink => self.resolve_tab_link(tab, channel_id, cx),
151 151 }
152 152 }
@@ -161,7 +161,7 @@ impl ConversationView {
161 161 let state = self.app.read(cx);
162 162 let engine = state.engine.clone().filter(|_| !state.mode.demo);
163 163 let Some(engine) = engine else {
164 cx.open_url(&fallback);
164 app_base::open_link::open_url(cx, &fallback);
165 165 return;
166 166 };
167 167 let tab_id = tab.tab_id;
@@ -179,7 +179,7 @@ impl ConversationView {
179 179 }
180 180 None => fallback,
181 181 };
182 cx.open_url(&target);
182 app_base::open_link::open_url(cx, &target);
183 183 })
184 184 .ok();
185 185 })
@@ -341,7 +341,7 @@ impl ConversationView {
341 341 }
342 342 SharedCommand::OpenInBrowser(index) => {
343 343 if let Some(entry) = self.library_entry(index) {
344 cx.open_url(&entry.web_url);
344 app_base::open_link::open_url(cx, &entry.web_url);
345 345 }
346 346 }
347 347 SharedCommand::Download(index) => {
@@ -362,7 +362,7 @@ impl ConversationView {
362 362 SharedCommand::Upload => self.pick_upload(cx),
363 363 SharedCommand::OpenSharePoint => {
364 364 if let Some(path) = &self.shared.path {
365 cx.open_url(path.current_web_url());
365 app_base::open_link::open_url(cx, path.current_web_url());
366 366 }
367 367 }
368 368 SharedCommand::OpenItem(index) => {
@@ -377,7 +377,7 @@ impl ConversationView {
377 377 DownloadSource::Share,
378 378 cx,
379 379 ),
380 SharedContent::Link(url) => cx.open_url(&url),
380 SharedContent::Link(url) => app_base::open_link::open_url(cx, &url),
381 381 }
382 382 }
383 383 SharedCommand::JumpToPost(index) => {
@@ -146,7 +146,7 @@ impl ConversationView {
146 };
146 };
147 let resolved = self.tab_links.get(&tab.tab_id).map(String::as_str);
147 let resolved = self.tab_links.get(&tab.tab_id).map(String::as_str);
148 match tab_action(&tab, resolved) {
148 match tab_action(&tab, resolved) {
149 TabAction::Browser(url) => cx.open_url(&url),
149 TabAction::Browser(url) => app_base::open_link::open_url(cx, &url),
150 TabAction::ResolveLink => self.resolve_tab_link(tab, channel_id, cx),
150 TabAction::ResolveLink => self.resolve_tab_link(tab, channel_id, cx),
151 }
151 }
152 }
152 }
@@ -161,7 +161,7 @@ impl ConversationView {
161 let state = self.app.read(cx);
161 let state = self.app.read(cx);
162 let engine = state.engine.clone().filter(|_| !state.mode.demo);
162 let engine = state.engine.clone().filter(|_| !state.mode.demo);
163 let Some(engine) = engine else {
163 let Some(engine) = engine else {
164 cx.open_url(&fallback);
164 app_base::open_link::open_url(cx, &fallback);
165 return;
165 return;
166 };
166 };
167 let tab_id = tab.tab_id;
167 let tab_id = tab.tab_id;
@@ -179,7 +179,7 @@ impl ConversationView {
179 }
179 }
180 None => fallback,
180 None => fallback,
181 };
181 };
182 cx.open_url(&target);
182 app_base::open_link::open_url(cx, &target);
183 })
183 })
184 .ok();
184 .ok();
185 })
185 })
@@ -341,7 +341,7 @@ impl ConversationView {
341 }
341 }
342 SharedCommand::OpenInBrowser(index) => {
342 SharedCommand::OpenInBrowser(index) => {
343 if let Some(entry) = self.library_entry(index) {
343 if let Some(entry) = self.library_entry(index) {
344 cx.open_url(&entry.web_url);
344 app_base::open_link::open_url(cx, &entry.web_url);
345 }
345 }
346 }
346 }
347 SharedCommand::Download(index) => {
347 SharedCommand::Download(index) => {
@@ -362,7 +362,7 @@ impl ConversationView {
362 SharedCommand::Upload => self.pick_upload(cx),
362 SharedCommand::Upload => self.pick_upload(cx),
363 SharedCommand::OpenSharePoint => {
363 SharedCommand::OpenSharePoint => {
364 if let Some(path) = &self.shared.path {
364 if let Some(path) = &self.shared.path {
365 cx.open_url(path.current_web_url());
365 app_base::open_link::open_url(cx, path.current_web_url());
366 }
366 }
367 }
367 }
368 SharedCommand::OpenItem(index) => {
368 SharedCommand::OpenItem(index) => {
@@ -377,7 +377,7 @@ impl ConversationView {
377 DownloadSource::Share,
377 DownloadSource::Share,
378 cx,
378 cx,
379 ),
379 ),
380 SharedContent::Link(url) => cx.open_url(&url),
380 SharedContent::Link(url) => app_base::open_link::open_url(cx, &url),
381 }
381 }
382 }
382 }
383 SharedCommand::JumpToPost(index) => {
383 SharedCommand::JumpToPost(index) => {
crates/app/src/views/profile_card.rs +1 −1
@@ -358,7 +358,7 @@ impl ProfileCard {
358 358 row.child(
359 359 icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
360 360 cx.listener(move |_, _, _, cx| {
361 cx.open_url(&mailto_url(&address));
361 app_base::open_link::open_url(cx, &mailto_url(&address));
362 362 cx.emit(ProfileCardEvent::Close);
363 363 }),
364 364 ),
@@ -358,7 +358,7 @@ impl ProfileCard {
358 row.child(
358 row.child(
359 icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
359 icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
360 cx.listener(move |_, _, _, cx| {
360 cx.listener(move |_, _, _, cx| {
361 cx.open_url(&mailto_url(&address));
361 app_base::open_link::open_url(cx, &mailto_url(&address));
362 cx.emit(ProfileCardEvent::Close);
362 cx.emit(ProfileCardEvent::Close);
363 }),
363 }),
364 ),
364 ),
crates/app/src/views/shell.rs +2 −2
@@ -108,7 +108,7 @@ fn open_link(url: &str, cx: &mut App) {
108 108 .clone()
109 109 .update(cx, |state, cx| state.raise_notice(text, None, cx));
110 110 }
111 cx.open_url(url);
111 app_base::open_link::open_url(cx, url);
112 112 }
113 113
114 114 fn opening_link_text(url: &str) -> String {
@@ -308,7 +308,7 @@ impl AppShell {
308 308 if !this.open_message(conversation_id, message_id, cx)
309 309 && let Some(link) = link
310 310 {
311 cx.open_url(link);
311 app_base::open_link::open_url(cx, link);
312 312 }
313 313 }
314 314 },
@@ -108,7 +108,7 @@ fn open_link(url: &str, cx: &mut App) {
108 .clone()
108 .clone()
109 .update(cx, |state, cx| state.raise_notice(text, None, cx));
109 .update(cx, |state, cx| state.raise_notice(text, None, cx));
110 }
110 }
111 cx.open_url(url);
111 app_base::open_link::open_url(cx, url);
112}
112}
113
113
114fn opening_link_text(url: &str) -> String {
114fn opening_link_text(url: &str) -> String {
@@ -308,7 +308,7 @@ impl AppShell {
308 if !this.open_message(conversation_id, message_id, cx)
308 if !this.open_message(conversation_id, message_id, cx)
309 && let Some(link) = link
309 && let Some(link) = link
310 {
310 {
311 cx.open_url(link);
311 app_base::open_link::open_url(cx, link);
312 }
312 }
313 }
313 }
314 },
314 },
crates/app/src/views/status_menu.rs +1 −1
@@ -172,7 +172,7 @@ fn header(context: &MenuContext, cx: &App) -> Div {
172 172 .hover(|link| link.text_color(theme::accent_text()))
173 173 .child(tr("status_menu.view_account"))
174 174 .child(menu_icon(IconName::ExternalLink).size(px(12.)))
175 .on_click(|_, _, cx| cx.open_url(VIEW_ACCOUNT_URL)),
175 .on_click(|_, _, cx| app_base::open_link::open_url(cx, VIEW_ACCOUNT_URL)),
176 176 )
177 177 .children(
178 178 context
@@ -172,7 +172,7 @@ fn header(context: &MenuContext, cx: &App) -> Div {
172 .hover(|link| link.text_color(theme::accent_text()))
172 .hover(|link| link.text_color(theme::accent_text()))
173 .child(tr("status_menu.view_account"))
173 .child(tr("status_menu.view_account"))
174 .child(menu_icon(IconName::ExternalLink).size(px(12.)))
174 .child(menu_icon(IconName::ExternalLink).size(px(12.)))
175 .on_click(|_, _, cx| cx.open_url(VIEW_ACCOUNT_URL)),
175 .on_click(|_, _, cx| app_base::open_link::open_url(cx, VIEW_ACCOUNT_URL)),
176 )
176 )
177 .children(
177 .children(
178 context
178 context
crates/calling/Cargo.toml +1 −0
@@ -23,6 +23,7 @@ serde.workspace = true
23 23 webrtc-sys = "=0.3.48"
24 24 serde_json.workspace = true
25 25 session.workspace = true
26 url.workspace = true
26 27 thiserror.workspace = true
27 28 tract-onnx = "0.23"
28 29 tokio.workspace = true
@@ -23,6 +23,7 @@ serde.workspace = true
23webrtc-sys = "=0.3.48"
23webrtc-sys = "=0.3.48"
24serde_json.workspace = true
24serde_json.workspace = true
25session.workspace = true
25session.workspace = true
26url.workspace = true
26thiserror.workspace = true
27thiserror.workspace = true
27tract-onnx = "0.23"
28tract-onnx = "0.23"
28tokio.workspace = true
29tokio.workspace = true
crates/calling/src/call/mod.rs +14 −14
@@ -584,6 +584,7 @@ async fn drive(
584 584 let mut input = options.input.clone();
585 585 let mut output = options.output.clone();
586 586 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
587 audio.set_device_tracks_enabled(false);
587 588 control.send(CallUpdate::ListenOnly(audio.listen_only));
588 589 let mut device_lists = devices::list_devices(&factory);
589 590 let mut applied_input = devices::applied_device(
@@ -898,8 +899,7 @@ async fn drive(
898 899 live.audio
899 900 .as_ref()
900 901 .expect("audio set above")
901 .track
902 .set_enabled(initial.track_enabled);
902 .set_device_tracks_enabled(initial.track_enabled);
903 903 if muted {
904 904 control.send(CallUpdate::Muted(true));
905 905 }
@@ -1099,7 +1099,7 @@ async fn drive(
1099 1099 &factory,
1100 1100 options,
1101 1101 &input,
1102 muted,
1102 muted || local_hold,
1103 1103 remote_audio.clone(),
1104 1104 &current.peer,
1105 1105 &track,
@@ -1369,7 +1369,7 @@ async fn drive(
1369 1369 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1370 1370 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1371 1371 local_video.stop_share();
1372 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
1372 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
1373 1373 clear_share(control);
1374 1374 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1375 1375 }
@@ -2025,7 +2025,7 @@ async fn drive(
2025 2025 timeline.record("remote audio track", "receiving");
2026 2026 let had_far_end = remote_audio.replace(remote_track.clone()).is_some();
2027 2027 if !had_far_end && software_audio.is_some() {
2028 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2028 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2029 2029 }
2030 2030 if options.record_remote {
2031 2031 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
@@ -2099,7 +2099,7 @@ async fn drive(
2099 2099 let audio = live.audio.as_ref().expect("audio set above");
2100 2100 muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
2101 2101 audio_disabled = true;
2102 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2102 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2103 2103 if audio.uses_devices() {
2104 2104 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2105 2105 factory.set_adm_recording_enabled(false);
@@ -2116,7 +2116,7 @@ async fn drive(
2116 2116 input = choice;
2117 2117 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2118 2118 if software_audio.is_some() {
2119 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2119 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2120 2120 }
2121 2121 }
2122 2122 Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
@@ -2126,7 +2126,7 @@ async fn drive(
2126 2126 if let Some(audio) = live.audio.as_ref() {
2127 2127 track = audio.device_track(mic_settings).clone();
2128 2128 }
2129 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);
2129 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);
2130 2130 }
2131 2131 Some(CallCommand::SetMicSettings(settings)) => {
2132 2132 mic_settings = settings;
@@ -2334,7 +2334,7 @@ async fn drive(
2334 2334 match local_video.start_share(&source) {
2335 2335 Ok(()) => {
2336 2336 announce_share(control, &source);
2337 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2337 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2338 2338 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2339 2339 Ok((browser_offer, signaled, reply_tags)) => {
2340 2340 timeline.record_sdp("local offer", &signaled.sdp);
@@ -2377,7 +2377,7 @@ async fn drive(
2377 2377 &mut media_description_request,
2378 2378 timeline,
2379 2379 );
2380 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2380 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2381 2381 }
2382 2382 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2383 2383 }
@@ -2394,7 +2394,7 @@ async fn drive(
2394 2394 } else if direct && local_video.sharing() {
2395 2395 local_video.stop_share();
2396 2396 clear_share(control);
2397 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2397 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2398 2398 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2399 2399 Ok((browser_offer, signaled, reply_tags)) => {
2400 2400 timeline.record_sdp("local offer", &signaled.sdp);
@@ -2406,7 +2406,7 @@ async fn drive(
2406 2406 }
2407 2407 } else if local_video.sharing() {
2408 2408 local_video.stop_share();
2409 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2409 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2410 2410 clear_share(control);
2411 2411 tell_media_descriptions(
2412 2412 &remote,
@@ -2422,7 +2422,7 @@ async fn drive(
2422 2422 }
2423 2423 Some(CallCommand::SetShareSound(on)) => {
2424 2424 share_sound_wanted = on;
2425 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2425 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2426 2426 }
2427 2427 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2428 2428 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
@@ -2972,7 +2972,7 @@ async fn drive(
2972 2972 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2973 2973 }
2974 2974 if input_changed && software_audio.is_some() {
2975 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2975 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2976 2976 }
2977 2977 }
2978 2978 }
@@ -584,6 +584,7 @@ async fn drive(
584 let mut input = options.input.clone();
584 let mut input = options.input.clone();
585 let mut output = options.output.clone();
585 let mut output = options.output.clone();
586 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
586 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
587 audio.set_device_tracks_enabled(false);
587 control.send(CallUpdate::ListenOnly(audio.listen_only));
588 control.send(CallUpdate::ListenOnly(audio.listen_only));
588 let mut device_lists = devices::list_devices(&factory);
589 let mut device_lists = devices::list_devices(&factory);
589 let mut applied_input = devices::applied_device(
590 let mut applied_input = devices::applied_device(
@@ -898,8 +899,7 @@ async fn drive(
898 live.audio
899 live.audio
899 .as_ref()
900 .as_ref()
900 .expect("audio set above")
901 .expect("audio set above")
901 .track
902 .set_device_tracks_enabled(initial.track_enabled);
902 .set_enabled(initial.track_enabled);
903 if muted {
903 if muted {
904 control.send(CallUpdate::Muted(true));
904 control.send(CallUpdate::Muted(true));
905 }
905 }
@@ -1099,7 +1099,7 @@ async fn drive(
1099 &factory,
1099 &factory,
1100 options,
1100 options,
1101 &input,
1101 &input,
1102 muted,
1102 muted || local_hold,
1103 remote_audio.clone(),
1103 remote_audio.clone(),
1104 &current.peer,
1104 &current.peer,
1105 &track,
1105 &track,
@@ -1369,7 +1369,7 @@ async fn drive(
1369 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1369 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1370 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1370 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1371 local_video.stop_share();
1371 local_video.stop_share();
1372 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
1372 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
1373 clear_share(control);
1373 clear_share(control);
1374 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1374 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1375 }
1375 }
@@ -2025,7 +2025,7 @@ async fn drive(
2025 timeline.record("remote audio track", "receiving");
2025 timeline.record("remote audio track", "receiving");
2026 let had_far_end = remote_audio.replace(remote_track.clone()).is_some();
2026 let had_far_end = remote_audio.replace(remote_track.clone()).is_some();
2027 if !had_far_end && software_audio.is_some() {
2027 if !had_far_end && software_audio.is_some() {
2028 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2028 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2029 }
2029 }
2030 if options.record_remote {
2030 if options.record_remote {
2031 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
2031 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
@@ -2099,7 +2099,7 @@ async fn drive(
2099 let audio = live.audio.as_ref().expect("audio set above");
2099 let audio = live.audio.as_ref().expect("audio set above");
2100 muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
2100 muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
2101 audio_disabled = true;
2101 audio_disabled = true;
2102 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2102 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2103 if audio.uses_devices() {
2103 if audio.uses_devices() {
2104 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2104 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2105 factory.set_adm_recording_enabled(false);
2105 factory.set_adm_recording_enabled(false);
@@ -2116,7 +2116,7 @@ async fn drive(
2116 input = choice;
2116 input = choice;
2117 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2117 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2118 if software_audio.is_some() {
2118 if software_audio.is_some() {
2119 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2119 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2120 }
2120 }
2121 }
2121 }
2122 Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
2122 Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
@@ -2126,7 +2126,7 @@ async fn drive(
2126 if let Some(audio) = live.audio.as_ref() {
2126 if let Some(audio) = live.audio.as_ref() {
2127 track = audio.device_track(mic_settings).clone();
2127 track = audio.device_track(mic_settings).clone();
2128 }
2128 }
2129 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);
2129 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);
2130 }
2130 }
2131 Some(CallCommand::SetMicSettings(settings)) => {
2131 Some(CallCommand::SetMicSettings(settings)) => {
2132 mic_settings = settings;
2132 mic_settings = settings;
@@ -2334,7 +2334,7 @@ async fn drive(
2334 match local_video.start_share(&source) {
2334 match local_video.start_share(&source) {
2335 Ok(()) => {
2335 Ok(()) => {
2336 announce_share(control, &source);
2336 announce_share(control, &source);
2337 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2337 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2338 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2338 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2339 Ok((browser_offer, signaled, reply_tags)) => {
2339 Ok((browser_offer, signaled, reply_tags)) => {
2340 timeline.record_sdp("local offer", &signaled.sdp);
2340 timeline.record_sdp("local offer", &signaled.sdp);
@@ -2377,7 +2377,7 @@ async fn drive(
2377 &mut media_description_request,
2377 &mut media_description_request,
2378 timeline,
2378 timeline,
2379 );
2379 );
2380 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2380 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2381 }
2381 }
2382 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2382 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2383 }
2383 }
@@ -2394,7 +2394,7 @@ async fn drive(
2394 } else if direct && local_video.sharing() {
2394 } else if direct && local_video.sharing() {
2395 local_video.stop_share();
2395 local_video.stop_share();
2396 clear_share(control);
2396 clear_share(control);
2397 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2397 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2398 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2398 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2399 Ok((browser_offer, signaled, reply_tags)) => {
2399 Ok((browser_offer, signaled, reply_tags)) => {
2400 timeline.record_sdp("local offer", &signaled.sdp);
2400 timeline.record_sdp("local offer", &signaled.sdp);
@@ -2406,7 +2406,7 @@ async fn drive(
2406 }
2406 }
2407 } else if local_video.sharing() {
2407 } else if local_video.sharing() {
2408 local_video.stop_share();
2408 local_video.stop_share();
2409 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2409 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2410 clear_share(control);
2410 clear_share(control);
2411 tell_media_descriptions(
2411 tell_media_descriptions(
2412 &remote,
2412 &remote,
@@ -2422,7 +2422,7 @@ async fn drive(
2422 }
2422 }
2423 Some(CallCommand::SetShareSound(on)) => {
2423 Some(CallCommand::SetShareSound(on)) => {
2424 share_sound_wanted = on;
2424 share_sound_wanted = on;
2425 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2425 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2426 }
2426 }
2427 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2427 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2428 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
2428 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
@@ -2972,7 +2972,7 @@ async fn drive(
2972 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2972 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2973 }
2973 }
2974 if input_changed && software_audio.is_some() {
2974 if input_changed && software_audio.is_some() {
2975 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2975 sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2976 }
2976 }
2977 }
2977 }
2978 }
2978 }
crates/calling/src/signaling.rs +45 −26
@@ -1,7 +1,9 @@
1 1 use std::collections::BTreeMap;
2 2
3 3 use serde_json::{Map, Value, json};
4 use session::trusted_url::{HostRule, trusted_https_url};
4 5 use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};
6 use url::{Position, Url};
5 7
6 8 use crate::captions::{self, BotAction};
7 9 use crate::error::{Error, Result};
@@ -25,8 +27,7 @@ const ENDPOINT_CAPABILITIES: u64 = 73463;
25 27 const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";
26 28 const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";
27 29 const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
28 const ALLOWED_HOST_SUFFIXES: [&str; 2] =
29 [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
30 const TEAMS_HOSTS: [HostRule; 1] = [HostRule::Domain("teams.microsoft.com")];
30 31 const BACKEND_SUFFIX: &str = ".skype.com";
31 32 const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";
32 33 const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
@@ -143,25 +144,32 @@ impl Conversation {
143 144 }
144 145 }
145 146
146 fn host_of(url: &str) -> Result<&str> {
147 url.strip_prefix("https://")
148 .and_then(|rest| rest.split(['/', '?']).next())
149 .map(|authority| authority.split(':').next().unwrap_or(authority))
150 .ok_or_else(|| Error::Signaling("link is not https".into()))
147 fn plain_https(url: &str) -> Result<Url> {
148 Url::parse(url)
149 .ok()
150 .filter(|parsed| {
151 parsed.scheme() == "https"
152 && parsed.username().is_empty()
153 && parsed.password().is_none()
154 && parsed.port().is_none()
155 && parsed.host_str().is_some()
156 })
157 .ok_or_else(|| Error::Signaling("link is not plain https".into()))
151 158 }
152 159
153 160 /// Bearer requests only go to Teams hosts; links come from server answers.
154 161 pub fn ensure_teams_url(url: &str) -> Result<()> {
155 let host = host_of(url)?;
156 if ALLOWED_HOST_SUFFIXES
157 .iter()
158 .any(|suffix| host.ends_with(suffix))
159 || host == "teams.microsoft.com"
160 {
161 Ok(())
162 } else {
163 Err(Error::Signaling(format!("refusing link to host {host}")))
164 }
162 trusted_teams_url(url).map(|_| ())
163 }
164
165 fn trusted_teams_url(url: &str) -> Result<Url> {
166 trusted_https_url(url, &TEAMS_HOSTS).ok_or_else(|| {
167 let host = Url::parse(url)
168 .ok()
169 .and_then(|parsed| parsed.host_str().map(str::to_owned))
170 .unwrap_or_default();
171 Error::Signaling(format!("refusing link to host {host}"))
172 })
165 173 }
166 174
167 175 fn is_backend_host(host: &str) -> bool {
@@ -176,15 +184,12 @@ fn is_backend_host(host: &str) -> bool {
176 184
177 185 /// Push links may name a backend host directly; the browser always reaches those through flightproxy.
178 186 pub fn routed_url(url: &str) -> Result<String> {
179 let host = host_of(url)?;
187 let parsed = plain_https(url)?;
188 let host = parsed.host_str().unwrap_or_default();
180 189 if !is_backend_host(host) {
181 ensure_teams_url(url)?;
182 return Ok(url.to_owned());
190 return Ok(trusted_teams_url(url)?.into());
183 191 }
184 let rest = &url["https://".len()..];
185 let path = rest
186 .find(['/', '?'])
187 .map_or("", |position| &rest[position..]);
192 let path = &parsed[Position::BeforePath..];
188 193 Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
189 194 }
190 195
@@ -797,8 +802,9 @@ impl Signaling {
797 802 }
798 803
799 804 async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {
805 let command_url = trusted_teams_url(command_url)?;
800 806 let arguments = json!({
801 "url": command_url,
807 "url": command_url.as_str(),
802 808 "body": body,
803 809 "recorderResource": captions::RECORDER_RESOURCE,
804 810 "recorderScope": captions::RECORDER_SCOPE,
@@ -1651,6 +1657,14 @@ mod tests {
1651 1657 assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
1652 1658 assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
1653 1659 assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
1660 for bypass in [
1661 "https://evil.example\\.teams.microsoft.com/x",
1662 "https://evil.example#.teams.microsoft.com/x",
1663 "https://a.teams.microsoft.com:x@evil.example/",
1664 ] {
1665 assert!(ensure_teams_url(bypass).is_err(), "{bypass}");
1666 assert!(routed_url(bypass).is_err(), "{bypass}");
1667 }
1654 1668 }
1655 1669
1656 1670 #[test]
@@ -1665,7 +1679,12 @@ mod tests {
1665 1679 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
1666 1680 );
1667 1681 assert!(routed_url("https://evil.skype.com.example/x").is_err());
1668 assert!(routed_url("https://Evil.skype.com/x").is_err());
1682 assert_eq!(
1683 routed_url("https://CC.skype.com/x").unwrap(),
1684 format!("{FLIGHTPROXY_EP}/cc.skype.com/x")
1685 );
1686 assert!(routed_url("https://cc.skype.com:x@evil.example/x").is_err());
1687 assert!(routed_url("https://evil.example\\.cc.skype.com/x").is_err());
1669 1688 assert!(routed_url("https://user@cc.skype.com/x").is_err());
1670 1689 assert!(routed_url("http://cc.skype.com/x").is_err());
1671 1690 assert!(routed_url("https://.skype.com/x").is_err());
@@ -1,7 +1,9 @@
1use std::collections::BTreeMap;
1use std::collections::BTreeMap;
2
2
3use serde_json::{Map, Value, json};
3use serde_json::{Map, Value, json};
4use session::trusted_url::{HostRule, trusted_https_url};
4use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};
5use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};
6use url::{Position, Url};
5
7
6use crate::captions::{self, BotAction};
8use crate::captions::{self, BotAction};
7use crate::error::{Error, Result};
9use crate::error::{Error, Result};
@@ -25,8 +27,7 @@ const ENDPOINT_CAPABILITIES: u64 = 73463;
25const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";
27const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";
26const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";
28const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";
27const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
29const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
28const ALLOWED_HOST_SUFFIXES: [&str; 2] =
30const TEAMS_HOSTS: [HostRule; 1] = [HostRule::Domain("teams.microsoft.com")];
29 [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
30const BACKEND_SUFFIX: &str = ".skype.com";
31const BACKEND_SUFFIX: &str = ".skype.com";
31const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";
32const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";
32const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
33const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
@@ -143,25 +144,32 @@ impl Conversation {
143 }
144 }
144}
145}
145
146
146fn host_of(url: &str) -> Result<&str> {
147fn plain_https(url: &str) -> Result<Url> {
147 url.strip_prefix("https://")
148 Url::parse(url)
148 .and_then(|rest| rest.split(['/', '?']).next())
149 .ok()
149 .map(|authority| authority.split(':').next().unwrap_or(authority))
150 .filter(|parsed| {
150 .ok_or_else(|| Error::Signaling("link is not https".into()))
151 parsed.scheme() == "https"
152 && parsed.username().is_empty()
153 && parsed.password().is_none()
154 && parsed.port().is_none()
155 && parsed.host_str().is_some()
156 })
157 .ok_or_else(|| Error::Signaling("link is not plain https".into()))
151}
158}
152
159
153/// Bearer requests only go to Teams hosts; links come from server answers.
160/// Bearer requests only go to Teams hosts; links come from server answers.
154pub fn ensure_teams_url(url: &str) -> Result<()> {
161pub fn ensure_teams_url(url: &str) -> Result<()> {
155 let host = host_of(url)?;
162 trusted_teams_url(url).map(|_| ())
156 if ALLOWED_HOST_SUFFIXES
163}
157 .iter()
164
158 .any(|suffix| host.ends_with(suffix))
165fn trusted_teams_url(url: &str) -> Result<Url> {
159 || host == "teams.microsoft.com"
166 trusted_https_url(url, &TEAMS_HOSTS).ok_or_else(|| {
160 {
167 let host = Url::parse(url)
161 Ok(())
168 .ok()
162 } else {
169 .and_then(|parsed| parsed.host_str().map(str::to_owned))
163 Err(Error::Signaling(format!("refusing link to host {host}")))
170 .unwrap_or_default();
164 }
171 Error::Signaling(format!("refusing link to host {host}"))
172 })
165}
173}
166
174
167fn is_backend_host(host: &str) -> bool {
175fn is_backend_host(host: &str) -> bool {
@@ -176,15 +184,12 @@ fn is_backend_host(host: &str) -> bool {
176
184
177/// Push links may name a backend host directly; the browser always reaches those through flightproxy.
185/// Push links may name a backend host directly; the browser always reaches those through flightproxy.
178pub fn routed_url(url: &str) -> Result<String> {
186pub fn routed_url(url: &str) -> Result<String> {
179 let host = host_of(url)?;
187 let parsed = plain_https(url)?;
188 let host = parsed.host_str().unwrap_or_default();
180 if !is_backend_host(host) {
189 if !is_backend_host(host) {
181 ensure_teams_url(url)?;
190 return Ok(trusted_teams_url(url)?.into());
182 return Ok(url.to_owned());
183 }
191 }
184 let rest = &url["https://".len()..];
192 let path = &parsed[Position::BeforePath..];
185 let path = rest
186 .find(['/', '?'])
187 .map_or("", |position| &rest[position..]);
188 Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
193 Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
189}
194}
190
195
@@ -797,8 +802,9 @@ impl Signaling {
797 }
802 }
798
803
799 async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {
804 async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {
805 let command_url = trusted_teams_url(command_url)?;
800 let arguments = json!({
806 let arguments = json!({
801 "url": command_url,
807 "url": command_url.as_str(),
802 "body": body,
808 "body": body,
803 "recorderResource": captions::RECORDER_RESOURCE,
809 "recorderResource": captions::RECORDER_RESOURCE,
804 "recorderScope": captions::RECORDER_SCOPE,
810 "recorderScope": captions::RECORDER_SCOPE,
@@ -1651,6 +1657,14 @@ mod tests {
1651 assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
1657 assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
1652 assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
1658 assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
1653 assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
1659 assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
1660 for bypass in [
1661 "https://evil.example\\.teams.microsoft.com/x",
1662 "https://evil.example#.teams.microsoft.com/x",
1663 "https://a.teams.microsoft.com:x@evil.example/",
1664 ] {
1665 assert!(ensure_teams_url(bypass).is_err(), "{bypass}");
1666 assert!(routed_url(bypass).is_err(), "{bypass}");
1667 }
1654 }
1668 }
1655
1669
1656 #[test]
1670 #[test]
@@ -1665,7 +1679,12 @@ mod tests {
1665 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
1679 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
1666 );
1680 );
1667 assert!(routed_url("https://evil.skype.com.example/x").is_err());
1681 assert!(routed_url("https://evil.skype.com.example/x").is_err());
1668 assert!(routed_url("https://Evil.skype.com/x").is_err());
1682 assert_eq!(
1683 routed_url("https://CC.skype.com/x").unwrap(),
1684 format!("{FLIGHTPROXY_EP}/cc.skype.com/x")
1685 );
1686 assert!(routed_url("https://cc.skype.com:x@evil.example/x").is_err());
1687 assert!(routed_url("https://evil.example\\.cc.skype.com/x").is_err());
1669 assert!(routed_url("https://user@cc.skype.com/x").is_err());
1688 assert!(routed_url("https://user@cc.skype.com/x").is_err());
1670 assert!(routed_url("http://cc.skype.com/x").is_err());
1689 assert!(routed_url("http://cc.skype.com/x").is_err());
1671 assert!(routed_url("https://.skype.com/x").is_err());
1690 assert!(routed_url("https://.skype.com/x").is_err());
crates/chatsvc/src/ams.rs +7 −2
@@ -4,7 +4,7 @@ use serde_json::{Value, json};
4 4 use session::{App, Scope, Session};
5 5
6 6 use crate::error::{Error, Result};
7 use crate::links::{LinkImage, decoded_image};
7 use crate::links::{LinkImage, decoded_image, trusted_ams_image_url};
8 8 use crate::messages::ensure_success;
9 9 use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};
10 10
@@ -87,13 +87,18 @@ impl Ams {
87 87
88 88 /// Reads an AMS image view such as `.../v1/objects/{id}/views/imgo` with the Skype token.
89 89 pub async fn download_image(&self, url: &str) -> Result<LinkImage> {
90 let Some(url) = trusted_ams_image_url(url) else {
91 return Err(Error::UnexpectedAnswer(format!(
92 "not an AMS image url: {url}"
93 )));
94 };
90 95 let answer = self
91 96 .session
92 97 .run_with_token(
93 98 App::Teams,
94 99 &Scope::new(CSA_RESOURCE, CSA_SCOPE),
95 100 DOWNLOAD_BODY,
96 &json!({ "url": url }),
101 &json!({ "url": url.as_str() }),
97 102 false,
98 103 )
99 104 .await?;
@@ -4,7 +4,7 @@ use serde_json::{Value, json};
4use session::{App, Scope, Session};
4use session::{App, Scope, Session};
5
5
6use crate::error::{Error, Result};
6use crate::error::{Error, Result};
7use crate::links::{LinkImage, decoded_image};
7use crate::links::{LinkImage, decoded_image, trusted_ams_image_url};
8use crate::messages::ensure_success;
8use crate::messages::ensure_success;
9use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};
9use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};
10
10
@@ -87,13 +87,18 @@ impl Ams {
87
87
88 /// Reads an AMS image view such as `.../v1/objects/{id}/views/imgo` with the Skype token.
88 /// Reads an AMS image view such as `.../v1/objects/{id}/views/imgo` with the Skype token.
89 pub async fn download_image(&self, url: &str) -> Result<LinkImage> {
89 pub async fn download_image(&self, url: &str) -> Result<LinkImage> {
90 let Some(url) = trusted_ams_image_url(url) else {
91 return Err(Error::UnexpectedAnswer(format!(
92 "not an AMS image url: {url}"
93 )));
94 };
90 let answer = self
95 let answer = self
91 .session
96 .session
92 .run_with_token(
97 .run_with_token(
93 App::Teams,
98 App::Teams,
94 &Scope::new(CSA_RESOURCE, CSA_SCOPE),
99 &Scope::new(CSA_RESOURCE, CSA_SCOPE),
95 DOWNLOAD_BODY,
100 DOWNLOAD_BODY,
96 &json!({ "url": url }),
101 &json!({ "url": url.as_str() }),
97 false,
102 false,
98 )
103 )
99 .await?;
104 .await?;
crates/chatsvc/src/pins/transport.rs +8 −1
@@ -1,7 +1,8 @@
1 1 use serde_json::{Value, json};
2 use session::trusted_url::may_carry_credentials;
2 3 use session::{ApiResponse, App, Request, Scope, Session};
3 4
4 use crate::error::Result;
5 use crate::error::{Error, Result};
5 6
6 7 pub const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";
7 8 pub const CSA_SCOPE: &str = "user_impersonation";
@@ -86,6 +87,12 @@ pub fn skype_fetch_answer(answer: Value) -> ApiResponse {
86 87
87 88 impl CsaTransport for SkypeTokenTransport {
88 89 async fn send(&self, request: Request) -> Result<ApiResponse> {
90 if !may_carry_credentials(&request.url) {
91 return Err(Error::UnexpectedAnswer(format!(
92 "refusing skype token request to {}",
93 request.url
94 )));
95 }
89 96 let answer = self
90 97 .session
91 98 .run_with_token(
@@ -1,7 +1,8 @@
1use serde_json::{Value, json};
1use serde_json::{Value, json};
2use session::trusted_url::may_carry_credentials;
2use session::{ApiResponse, App, Request, Scope, Session};
3use session::{ApiResponse, App, Request, Scope, Session};
3
4
4use crate::error::Result;
5use crate::error::{Error, Result};
5
6
6pub const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";
7pub const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";
7pub const CSA_SCOPE: &str = "user_impersonation";
8pub const CSA_SCOPE: &str = "user_impersonation";
@@ -86,6 +87,12 @@ pub fn skype_fetch_answer(answer: Value) -> ApiResponse {
86
87
87impl CsaTransport for SkypeTokenTransport {
88impl CsaTransport for SkypeTokenTransport {
88 async fn send(&self, request: Request) -> Result<ApiResponse> {
89 async fn send(&self, request: Request) -> Result<ApiResponse> {
90 if !may_carry_credentials(&request.url) {
91 return Err(Error::UnexpectedAnswer(format!(
92 "refusing skype token request to {}",
93 request.url
94 )));
95 }
89 let answer = self
96 let answer = self
90 .session
97 .session
91 .run_with_token(
98 .run_with_token(
crates/chatsvc/src/substrate_search/tests.rs +1 −1
@@ -1,7 +1,7 @@
1 1 use std::collections::VecDeque;
2 2 use std::sync::Mutex;
3 3
4 use serde_json::{json, Value};
4 use serde_json::{Value, json};
5 5 use session::{ApiResponse, Method, Request};
6 6
7 7 use super::*;
@@ -1,7 +1,7 @@
1use std::collections::VecDeque;
1use std::collections::VecDeque;
2use std::sync::Mutex;
2use std::sync::Mutex;
3
3
4use serde_json::{json, Value};
4use serde_json::{Value, json};
5use session::{ApiResponse, Method, Request};
5use session::{ApiResponse, Method, Request};
6
6
7use super::*;
7use super::*;
crates/core/src/draft.rs +11 −3
@@ -896,7 +896,8 @@ impl Draft {
896 896 LineKind::Text => {
897 897 let language = fence_language(&self.text[content.clone()])?;
898 898 self.splice(content.clone(), "", &[]);
899 let cursor = self.set_line_kind(index, LineKind::Code(language), None, content.start);
899 let cursor =
900 self.set_line_kind(index, LineKind::Code(language), None, content.start);
900 901 Some(self.repair(cursor))
901 902 }
902 903 LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,
@@ -3184,7 +3185,10 @@ mod tests {
3184 3185 LineKind::Code(None),
3185 3186 ]
3186 3187 );
3187 assert_eq!(draft.code_block_at(draft.text().find('b').unwrap()), Some(0..2));
3188 assert_eq!(
3189 draft.code_block_at(draft.text().find('b').unwrap()),
3190 Some(0..2)
3191 );
3188 3192 assert_eq!(draft.code_block_at(draft.text().len() - 1), Some(3..4));
3189 3193 draft.set_code_language(draft.text().find('x').unwrap(), Some("c".into()));
3190 3194 assert_eq!(draft.lines()[2], LineKind::Text);
@@ -3214,7 +3218,11 @@ mod tests {
3214 3218 content: "FROM x".into(),
3215 3219 marks: Vec::new(),
3216 3220 }]);
3217 assert!(docker.to_html().starts_with("<pre class=\"language-dockerFile "));
3221 assert!(
3222 docker
3223 .to_html()
3224 .starts_with("<pre class=\"language-dockerFile ")
3225 );
3218 3226 }
3219 3227
3220 3228 #[test]
@@ -896,7 +896,8 @@ impl Draft {
896 LineKind::Text => {
896 LineKind::Text => {
897 let language = fence_language(&self.text[content.clone()])?;
897 let language = fence_language(&self.text[content.clone()])?;
898 self.splice(content.clone(), "", &[]);
898 self.splice(content.clone(), "", &[]);
899 let cursor = self.set_line_kind(index, LineKind::Code(language), None, content.start);
899 let cursor =
900 self.set_line_kind(index, LineKind::Code(language), None, content.start);
900 Some(self.repair(cursor))
901 Some(self.repair(cursor))
901 }
902 }
902 LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,
903 LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,
@@ -3184,7 +3185,10 @@ mod tests {
3184 LineKind::Code(None),
3185 LineKind::Code(None),
3185 ]
3186 ]
3186 );
3187 );
3187 assert_eq!(draft.code_block_at(draft.text().find('b').unwrap()), Some(0..2));
3188 assert_eq!(
3189 draft.code_block_at(draft.text().find('b').unwrap()),
3190 Some(0..2)
3191 );
3188 assert_eq!(draft.code_block_at(draft.text().len() - 1), Some(3..4));
3192 assert_eq!(draft.code_block_at(draft.text().len() - 1), Some(3..4));
3189 draft.set_code_language(draft.text().find('x').unwrap(), Some("c".into()));
3193 draft.set_code_language(draft.text().find('x').unwrap(), Some("c".into()));
3190 assert_eq!(draft.lines()[2], LineKind::Text);
3194 assert_eq!(draft.lines()[2], LineKind::Text);
@@ -3214,7 +3218,11 @@ mod tests {
3214 content: "FROM x".into(),
3218 content: "FROM x".into(),
3215 marks: Vec::new(),
3219 marks: Vec::new(),
3216 }]);
3220 }]);
3217 assert!(docker.to_html().starts_with("<pre class=\"language-dockerFile "));
3221 assert!(
3222 docker
3223 .to_html()
3224 .starts_with("<pre class=\"language-dockerFile ")
3225 );
3218 }
3226 }
3219
3227
3220 #[test]
3228 #[test]
crates/session/src/app.rs +12 −1
@@ -105,7 +105,12 @@ pub fn find_app_tab(targets: &[Target], app: App) -> Option<&Target> {
105 105 }
106 106
107 107 pub fn is_login_url(url: &str) -> bool {
108 LOGIN_ORIGINS.iter().any(|origin| url.starts_with(origin))
108 LOGIN_ORIGINS.iter().any(|origin| is_on_origin(url, origin))
109 }
110
111 pub(crate) fn is_on_origin(url: &str, origin: &str) -> bool {
112 url.strip_prefix(origin)
113 .is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
109 114 }
110 115
111 116 pub fn has_login_tab(targets: &[Target]) -> bool {
@@ -189,6 +194,12 @@ mod tests {
189 194 assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft.mcas.ms/v2/"));
190 195 }
191 196
197 #[test]
198 fn a_lookalike_host_is_not_the_login_page() {
199 assert!(is_login_url("https://login.live.com/oauth"));
200 assert!(!is_login_url("https://login.live.com.evil.example/"));
201 }
202
192 203 #[test]
193 204 fn app_urls_need_an_exact_host() {
194 205 for url in [
@@ -105,7 +105,12 @@ pub fn find_app_tab(targets: &[Target], app: App) -> Option<&Target> {
105}
105}
106
106
107pub fn is_login_url(url: &str) -> bool {
107pub fn is_login_url(url: &str) -> bool {
108 LOGIN_ORIGINS.iter().any(|origin| url.starts_with(origin))
108 LOGIN_ORIGINS.iter().any(|origin| is_on_origin(url, origin))
109}
110
111pub(crate) fn is_on_origin(url: &str, origin: &str) -> bool {
112 url.strip_prefix(origin)
113 .is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
109}
114}
110
115
111pub fn has_login_tab(targets: &[Target]) -> bool {
116pub fn has_login_tab(targets: &[Target]) -> bool {
@@ -189,6 +194,12 @@ mod tests {
189 assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft.mcas.ms/v2/"));
194 assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft.mcas.ms/v2/"));
190 }
195 }
191
196
197 #[test]
198 fn a_lookalike_host_is_not_the_login_page() {
199 assert!(is_login_url("https://login.live.com/oauth"));
200 assert!(!is_login_url("https://login.live.com.evil.example/"));
201 }
202
192 #[test]
203 #[test]
193 fn app_urls_need_an_exact_host() {
204 fn app_urls_need_an_exact_host() {
194 for url in [
205 for url in [
crates/session/src/lib.rs +1 −0
@@ -9,6 +9,7 @@ mod request;
9 9 mod scope;
10 10 mod session;
11 11 mod transport;
12 pub mod trusted_url;
12 13
13 14 pub use app::{App, MCAS_SUFFIX, Target, find_app_tab, has_login_tab, is_login_url, is_mcas_url};
14 15 pub use error::{Error, Result};
@@ -9,6 +9,7 @@ mod request;
9mod scope;
9mod scope;
10mod session;
10mod session;
11mod transport;
11mod transport;
12pub mod trusted_url;
12
13
13pub use app::{App, MCAS_SUFFIX, Target, find_app_tab, has_login_tab, is_login_url, is_mcas_url};
14pub use app::{App, MCAS_SUFFIX, Target, find_app_tab, has_login_tab, is_login_url, is_mcas_url};
14pub use error::{Error, Result};
15pub use error::{Error, Result};
crates/session/src/native.rs +2 −7
@@ -7,7 +7,7 @@ use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
7 7 use futures_util::future::join_all;
8 8 use serde_json::{Value, json};
9 9
10 use crate::app::App;
10 use crate::app::{App, is_on_origin};
11 11 use crate::request::{ApiResponse, Method, Request};
12 12 use crate::scope::Scope;
13 13 use crate::session::Session;
@@ -249,7 +249,7 @@ fn eligible(request: &Request) -> bool {
249 249 fn needs_page_cookies(url: &str) -> bool {
250 250 App::ALL.iter().any(|&app| {
251 251 app.origins().iter().any(|origin| {
252 same_origin(url, origin)
252 is_on_origin(url, origin)
253 253 && !(app == App::Teams
254 254 && TEAMS_BEARER_PATHS
255 255 .iter()
@@ -258,11 +258,6 @@ fn needs_page_cookies(url: &str) -> bool {
258 258 })
259 259 }
260 260
261 fn same_origin(url: &str, origin: &str) -> bool {
262 url.strip_prefix(origin)
263 .is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
264 }
265
266 261 fn method(method: Method) -> reqwest::Method {
267 262 match method {
268 263 Method::Get => reqwest::Method::GET,
@@ -7,7 +7,7 @@ use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
7use futures_util::future::join_all;
7use futures_util::future::join_all;
8use serde_json::{Value, json};
8use serde_json::{Value, json};
9
9
10use crate::app::App;
10use crate::app::{App, is_on_origin};
11use crate::request::{ApiResponse, Method, Request};
11use crate::request::{ApiResponse, Method, Request};
12use crate::scope::Scope;
12use crate::scope::Scope;
13use crate::session::Session;
13use crate::session::Session;
@@ -249,7 +249,7 @@ fn eligible(request: &Request) -> bool {
249fn needs_page_cookies(url: &str) -> bool {
249fn needs_page_cookies(url: &str) -> bool {
250 App::ALL.iter().any(|&app| {
250 App::ALL.iter().any(|&app| {
251 app.origins().iter().any(|origin| {
251 app.origins().iter().any(|origin| {
252 same_origin(url, origin)
252 is_on_origin(url, origin)
253 && !(app == App::Teams
253 && !(app == App::Teams
254 && TEAMS_BEARER_PATHS
254 && TEAMS_BEARER_PATHS
255 .iter()
255 .iter()
@@ -258,11 +258,6 @@ fn needs_page_cookies(url: &str) -> bool {
258 })
258 })
259}
259}
260
260
261fn same_origin(url: &str, origin: &str) -> bool {
262 url.strip_prefix(origin)
263 .is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
264}
265
266fn method(method: Method) -> reqwest::Method {
261fn method(method: Method) -> reqwest::Method {
267 match method {
262 match method {
268 Method::Get => reqwest::Method::GET,
263 Method::Get => reqwest::Method::GET,
crates/session/src/session.rs +39 −1
@@ -14,6 +14,7 @@ use crate::native::NativeHttp;
14 14 use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};
15 15 use crate::scope::Scope;
16 16 use crate::transport::{CdpTransport, Transport};
17 use crate::trusted_url::may_carry_credentials;
17 18
18 19 pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";
19 20 pub const UNSEAL_SCRIPT: &str = include_str!("../assets/unseal.js");
@@ -148,11 +149,22 @@ impl Session {
148 149 Ok(response)
149 150 }
150 151
152 /// Requests with credentials to a host outside [`crate::trusted_url::MICROSOFT_HOSTS`] answer status 0 and are never sent.
151 153 pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> {
152 154 let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()];
153 let mut pending: Vec<usize> = (0..requests.len()).collect();
155 let mut pending: Vec<usize> = Vec::with_capacity(requests.len());
156 for (index, request) in requests.iter().enumerate() {
157 if request.anonymous || may_carry_credentials(&request.url) {
158 pending.push(index);
159 } else {
160 results[index] = Some(refused_untrusted_host());
161 }
162 }
154 163 let mut forced_here = false;
155 164 for attempt in 0..=self.config.max_throttle_retries {
165 if pending.is_empty() {
166 break;
167 }
156 168 let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect();
157 169 let answers = match self.run_with_fresh_token(&batch, scope).await {
158 170 Ok(answers) => answers,
@@ -434,6 +446,14 @@ impl Drop for TabHold {
434 446 }
435 447 }
436 448
449 fn refused_untrusted_host() -> ApiResponse {
450 ApiResponse {
451 status: 0,
452 body: Value::String("refused: credentials only go to Microsoft hosts over https".into()),
453 retry_after: None,
454 }
455 }
456
437 457 fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
438 458 config
439 459 .native_http
@@ -483,6 +503,24 @@ mod tests {
483 503 }
484 504 }
485 505
506 #[tokio::test]
507 async fn credentials_never_leave_for_a_foreign_host() {
508 let session =
509 Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())
510 .await
511 .unwrap();
512 let answers = session
513 .batch(
514 &[Request::binary_get(
515 "https://evil.com\\.asyncgw.teams.microsoft.com/x",
516 )],
517 &Scope::graph("x"),
518 )
519 .await
520 .unwrap();
521 assert_eq!(answers[0].status, 0);
522 }
523
486 524 #[tokio::test]
487 525 async fn tab_hold_releases_the_tab_when_dropped() {
488 526 let recorder = Arc::new(HoldRecorder::default());
@@ -14,6 +14,7 @@ use crate::native::NativeHttp;
14use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};
14use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};
15use crate::scope::Scope;
15use crate::scope::Scope;
16use crate::transport::{CdpTransport, Transport};
16use crate::transport::{CdpTransport, Transport};
17use crate::trusted_url::may_carry_credentials;
17
18
18pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";
19pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";
19pub const UNSEAL_SCRIPT: &str = include_str!("../assets/unseal.js");
20pub const UNSEAL_SCRIPT: &str = include_str!("../assets/unseal.js");
@@ -148,11 +149,22 @@ impl Session {
148 Ok(response)
149 Ok(response)
149 }
150 }
150
151
152 /// Requests with credentials to a host outside [`crate::trusted_url::MICROSOFT_HOSTS`] answer status 0 and are never sent.
151 pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> {
153 pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> {
152 let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()];
154 let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()];
153 let mut pending: Vec<usize> = (0..requests.len()).collect();
155 let mut pending: Vec<usize> = Vec::with_capacity(requests.len());
156 for (index, request) in requests.iter().enumerate() {
157 if request.anonymous || may_carry_credentials(&request.url) {
158 pending.push(index);
159 } else {
160 results[index] = Some(refused_untrusted_host());
161 }
162 }
154 let mut forced_here = false;
163 let mut forced_here = false;
155 for attempt in 0..=self.config.max_throttle_retries {
164 for attempt in 0..=self.config.max_throttle_retries {
165 if pending.is_empty() {
166 break;
167 }
156 let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect();
168 let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect();
157 let answers = match self.run_with_fresh_token(&batch, scope).await {
169 let answers = match self.run_with_fresh_token(&batch, scope).await {
158 Ok(answers) => answers,
170 Ok(answers) => answers,
@@ -434,6 +446,14 @@ impl Drop for TabHold {
434 }
446 }
435}
447}
436
448
449fn refused_untrusted_host() -> ApiResponse {
450 ApiResponse {
451 status: 0,
452 body: Value::String("refused: credentials only go to Microsoft hosts over https".into()),
453 retry_after: None,
454 }
455}
456
437fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
457fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
438 config
458 config
439 .native_http
459 .native_http
@@ -483,6 +503,24 @@ mod tests {
483 }
503 }
484 }
504 }
485
505
506 #[tokio::test]
507 async fn credentials_never_leave_for_a_foreign_host() {
508 let session =
509 Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())
510 .await
511 .unwrap();
512 let answers = session
513 .batch(
514 &[Request::binary_get(
515 "https://evil.com\\.asyncgw.teams.microsoft.com/x",
516 )],
517 &Scope::graph("x"),
518 )
519 .await
520 .unwrap();
521 assert_eq!(answers[0].status, 0);
522 }
523
486 #[tokio::test]
524 #[tokio::test]
487 async fn tab_hold_releases_the_tab_when_dropped() {
525 async fn tab_hold_releases_the_tab_when_dropped() {
488 let recorder = Arc::new(HoldRecorder::default());
526 let recorder = Arc::new(HoldRecorder::default());
crates/session/src/trusted_url.rs added +145 −0
@@ -0,0 +1,145 @@
1 use url::Url;
2
3 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4 pub enum HostRule {
5 Exact(&'static str),
6 Domain(&'static str),
7 }
8
9 impl HostRule {
10 fn allows(self, host: &str) -> bool {
11 match self {
12 HostRule::Exact(name) => host == name,
13 HostRule::Domain(domain) => {
14 host == domain
15 || host
16 .strip_suffix(domain)
17 .is_some_and(|prefix| prefix.len() > 1 && prefix.ends_with('.'))
18 }
19 }
20 }
21 }
22
23 pub const MICROSOFT_HOSTS: [HostRule; 12] = [
24 HostRule::Domain("microsoft.com"),
25 HostRule::Domain("cloud.microsoft"),
26 HostRule::Domain("microsoft365.com"),
27 HostRule::Domain("microsoftonline.com"),
28 HostRule::Domain("office.com"),
29 HostRule::Domain("office.net"),
30 HostRule::Domain("office365.com"),
31 HostRule::Domain("skype.com"),
32 HostRule::Domain("sharepoint.com"),
33 HostRule::Domain("onedrive.com"),
34 HostRule::Domain("live.com"),
35 HostRule::Domain("mcas.ms"),
36 ];
37
38 /// The parsed URL when `raw` is plain HTTPS to a host one of `rules` allows: no user info, no explicit port.
39 /// Callers send the returned URL, never `raw`, so the host that was checked is the host that is contacted.
40 pub fn trusted_https_url(raw: &str, rules: &[HostRule]) -> Option<Url> {
41 let url = Url::parse(raw).ok()?;
42 let host = url.host_str()?;
43 let plain = url.scheme() == "https"
44 && url.username().is_empty()
45 && url.password().is_none()
46 && url.port().is_none();
47 (plain && rules.iter().any(|rule| rule.allows(host))).then_some(url)
48 }
49
50 pub fn is_trusted_https_url(raw: &str, rules: &[HostRule]) -> bool {
51 trusted_https_url(raw, rules).is_some()
52 }
53
54 pub fn may_carry_credentials(raw: &str) -> bool {
55 is_trusted_https_url(raw, &MICROSOFT_HOSTS) || is_websocket_to(raw, &MICROSOFT_HOSTS)
56 }
57
58 fn is_websocket_to(raw: &str, rules: &[HostRule]) -> bool {
59 Url::parse(raw).ok().is_some_and(|url| {
60 url.scheme() == "wss"
61 && url.username().is_empty()
62 && url.password().is_none()
63 && url.port().is_none()
64 && url
65 .host_str()
66 .is_some_and(|host| rules.iter().any(|rule| rule.allows(host)))
67 })
68 }
69
70 #[cfg(test)]
71 mod tests {
72 use super::*;
73
74 const AMS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")];
75
76 #[test]
77 fn plain_https_to_an_allowed_host_passes() {
78 let url = trusted_https_url("https://eu-api.asm.skype.com/v1/objects/a", &AMS).unwrap();
79 assert_eq!(url.host_str(), Some("eu-api.asm.skype.com"));
80 assert!(is_trusted_https_url("https://asm.skype.com/x", &AMS));
81 assert!(is_trusted_https_url("https://EU.ASM.Skype.com/x", &AMS));
82 }
83
84 #[test]
85 fn separator_tricks_do_not_pass() {
86 for raw in [
87 "https://evil.example\\.asm.skype.com/v1/objects/a",
88 "https://evil.example#.asm.skype.com/v1/objects/a",
89 "https://evil.example?.asm.skype.com/v1/objects/a",
90 "https://evil.example/.asm.skype.com/v1/objects/a",
91 "https://a.asm.skype.com:x@evil.example/",
92 "https://a.asm.skype.com@evil.example/",
93 "https://user@a.asm.skype.com/",
94 "https://a.asm.skype.com:8443/",
95 "https://evilasm.skype.com/",
96 "https://asm.skype.com.evil.example/",
97 "https://.asm.skype.com/",
98 "http://a.asm.skype.com/",
99 "//a.asm.skype.com/",
100 "javascript:alert(1)//a.asm.skype.com",
101 "not a url",
102 ] {
103 assert!(!is_trusted_https_url(raw, &AMS), "{raw}");
104 }
105 }
106
107 #[test]
108 fn the_checked_host_is_the_host_that_gets_contacted() {
109 let url = trusted_https_url("https://a.asm.skype.com/x?y#z", &AMS).unwrap();
110 assert_eq!(url.as_str(), "https://a.asm.skype.com/x?y#z");
111 }
112
113 #[test]
114 fn exact_rules_match_only_that_host() {
115 let rules = [HostRule::Exact("teams.microsoft.com")];
116 assert!(is_trusted_https_url(
117 "https://teams.microsoft.com/x",
118 &rules
119 ));
120 assert!(!is_trusted_https_url(
121 "https://a.teams.microsoft.com/x",
122 &rules
123 ));
124 }
125
126 #[test]
127 fn credentials_go_only_to_microsoft_hosts() {
128 assert!(may_carry_credentials("https://graph.microsoft.com/v1.0/me"));
129 assert!(may_carry_credentials(
130 "https://teams.cloud.microsoft/api/mt/emea/beta/users"
131 ));
132 assert!(may_carry_credentials("https://contoso.sharepoint.com/x"));
133 assert!(may_carry_credentials(
134 "wss://go.trouter.teams.microsoft.com/v4"
135 ));
136 assert!(may_carry_credentials(
137 "https://teams.cloud.microsoft.mcas.ms/api/mt/emea/beta/users"
138 ));
139 assert!(!may_carry_credentials("https://evil.com\\.microsoft.com/"));
140 assert!(!may_carry_credentials("https://microsoft.com.evil.com/"));
141 assert!(!may_carry_credentials("https://evil.com/"));
142 assert!(!may_carry_credentials("http://graph.microsoft.com/v1.0/me"));
143 assert!(!may_carry_credentials("wss://evil.com/"));
144 }
145 }
@@ -0,0 +1,145 @@
1use url::Url;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum HostRule {
5 Exact(&'static str),
6 Domain(&'static str),
7}
8
9impl HostRule {
10 fn allows(self, host: &str) -> bool {
11 match self {
12 HostRule::Exact(name) => host == name,
13 HostRule::Domain(domain) => {
14 host == domain
15 || host
16 .strip_suffix(domain)
17 .is_some_and(|prefix| prefix.len() > 1 && prefix.ends_with('.'))
18 }
19 }
20 }
21}
22
23pub const MICROSOFT_HOSTS: [HostRule; 12] = [
24 HostRule::Domain("microsoft.com"),
25 HostRule::Domain("cloud.microsoft"),
26 HostRule::Domain("microsoft365.com"),
27 HostRule::Domain("microsoftonline.com"),
28 HostRule::Domain("office.com"),
29 HostRule::Domain("office.net"),
30 HostRule::Domain("office365.com"),
31 HostRule::Domain("skype.com"),
32 HostRule::Domain("sharepoint.com"),
33 HostRule::Domain("onedrive.com"),
34 HostRule::Domain("live.com"),
35 HostRule::Domain("mcas.ms"),
36];
37
38/// The parsed URL when `raw` is plain HTTPS to a host one of `rules` allows: no user info, no explicit port.
39/// Callers send the returned URL, never `raw`, so the host that was checked is the host that is contacted.
40pub fn trusted_https_url(raw: &str, rules: &[HostRule]) -> Option<Url> {
41 let url = Url::parse(raw).ok()?;
42 let host = url.host_str()?;
43 let plain = url.scheme() == "https"
44 && url.username().is_empty()
45 && url.password().is_none()
46 && url.port().is_none();
47 (plain && rules.iter().any(|rule| rule.allows(host))).then_some(url)
48}
49
50pub fn is_trusted_https_url(raw: &str, rules: &[HostRule]) -> bool {
51 trusted_https_url(raw, rules).is_some()
52}
53
54pub fn may_carry_credentials(raw: &str) -> bool {
55 is_trusted_https_url(raw, &MICROSOFT_HOSTS) || is_websocket_to(raw, &MICROSOFT_HOSTS)
56}
57
58fn is_websocket_to(raw: &str, rules: &[HostRule]) -> bool {
59 Url::parse(raw).ok().is_some_and(|url| {
60 url.scheme() == "wss"
61 && url.username().is_empty()
62 && url.password().is_none()
63 && url.port().is_none()
64 && url
65 .host_str()
66 .is_some_and(|host| rules.iter().any(|rule| rule.allows(host)))
67 })
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73
74 const AMS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")];
75
76 #[test]
77 fn plain_https_to_an_allowed_host_passes() {
78 let url = trusted_https_url("https://eu-api.asm.skype.com/v1/objects/a", &AMS).unwrap();
79 assert_eq!(url.host_str(), Some("eu-api.asm.skype.com"));
80 assert!(is_trusted_https_url("https://asm.skype.com/x", &AMS));
81 assert!(is_trusted_https_url("https://EU.ASM.Skype.com/x", &AMS));
82 }
83
84 #[test]
85 fn separator_tricks_do_not_pass() {
86 for raw in [
87 "https://evil.example\\.asm.skype.com/v1/objects/a",
88 "https://evil.example#.asm.skype.com/v1/objects/a",
89 "https://evil.example?.asm.skype.com/v1/objects/a",
90 "https://evil.example/.asm.skype.com/v1/objects/a",
91 "https://a.asm.skype.com:x@evil.example/",
92 "https://a.asm.skype.com@evil.example/",
93 "https://user@a.asm.skype.com/",
94 "https://a.asm.skype.com:8443/",
95 "https://evilasm.skype.com/",
96 "https://asm.skype.com.evil.example/",
97 "https://.asm.skype.com/",
98 "http://a.asm.skype.com/",
99 "//a.asm.skype.com/",
100 "javascript:alert(1)//a.asm.skype.com",
101 "not a url",
102 ] {
103 assert!(!is_trusted_https_url(raw, &AMS), "{raw}");
104 }
105 }
106
107 #[test]
108 fn the_checked_host_is_the_host_that_gets_contacted() {
109 let url = trusted_https_url("https://a.asm.skype.com/x?y#z", &AMS).unwrap();
110 assert_eq!(url.as_str(), "https://a.asm.skype.com/x?y#z");
111 }
112
113 #[test]
114 fn exact_rules_match_only_that_host() {
115 let rules = [HostRule::Exact("teams.microsoft.com")];
116 assert!(is_trusted_https_url(
117 "https://teams.microsoft.com/x",
118 &rules
119 ));
120 assert!(!is_trusted_https_url(
121 "https://a.teams.microsoft.com/x",
122 &rules
123 ));
124 }
125
126 #[test]
127 fn credentials_go_only_to_microsoft_hosts() {
128 assert!(may_carry_credentials("https://graph.microsoft.com/v1.0/me"));
129 assert!(may_carry_credentials(
130 "https://teams.cloud.microsoft/api/mt/emea/beta/users"
131 ));
132 assert!(may_carry_credentials("https://contoso.sharepoint.com/x"));
133 assert!(may_carry_credentials(
134 "wss://go.trouter.teams.microsoft.com/v4"
135 ));
136 assert!(may_carry_credentials(
137 "https://teams.cloud.microsoft.mcas.ms/api/mt/emea/beta/users"
138 ));
139 assert!(!may_carry_credentials("https://evil.com\\.microsoft.com/"));
140 assert!(!may_carry_credentials("https://microsoft.com.evil.com/"));
141 assert!(!may_carry_credentials("https://evil.com/"));
142 assert!(!may_carry_credentials("http://graph.microsoft.com/v1.0/me"));
143 assert!(!may_carry_credentials("wss://evil.com/"));
144 }
145}
crates/webview/src/cdp_failure.rs +1 −1
@@ -9,7 +9,7 @@ pub(crate) fn tab_state(app: App, url: &str) -> &'static str {
9 9 "parked"
10 10 } else if is_login_url(url) {
11 11 "login"
12 } else if app.origins().iter().any(|origin| url.starts_with(origin)) {
12 } else if app.is_app_url(url) {
13 13 "app"
14 14 } else if url.starts_with("about:") {
15 15 "about"
@@ -9,7 +9,7 @@ pub(crate) fn tab_state(app: App, url: &str) -> &'static str {
9 "parked"
9 "parked"
10 } else if is_login_url(url) {
10 } else if is_login_url(url) {
11 "login"
11 "login"
12 } else if app.origins().iter().any(|origin| url.starts_with(origin)) {
12 } else if app.is_app_url(url) {
13 "app"
13 "app"
14 } else if url.starts_with("about:") {
14 } else if url.starts_with("about:") {
15 "about"
15 "about"
crates/webview/src/host.rs +2 −2
@@ -333,7 +333,7 @@ fn watch_loads(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {
333 333 }
334 334
335 335 fn is_running_app(app: App, url: &str) -> bool {
336 app.origins().iter().any(|origin| url.starts_with(origin)) && !app.is_park_url(url)
336 app.is_app_url(url) && !app.is_park_url(url)
337 337 }
338 338
339 339 fn park(shared: &Shared, app: App) {
@@ -443,7 +443,7 @@ fn source_of(webview: &ICoreWebView2) -> String {
443 443 fn on_source_changed(shared: &Shared, app: App, url: String) {
444 444 let window = shared.windows[&app];
445 445 let login = is_login_url(&url);
446 let on_app = app.origins().iter().any(|origin| url.starts_with(origin));
446 let on_app = app.is_app_url(&url);
447 447 shared.state.send_modify(|state| {
448 448 state.urls.insert(app, url);
449 449 });
@@ -333,7 +333,7 @@ fn watch_loads(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {
333}
333}
334
334
335fn is_running_app(app: App, url: &str) -> bool {
335fn is_running_app(app: App, url: &str) -> bool {
336 app.origins().iter().any(|origin| url.starts_with(origin)) && !app.is_park_url(url)
336 app.is_app_url(url) && !app.is_park_url(url)
337}
337}
338
338
339fn park(shared: &Shared, app: App) {
339fn park(shared: &Shared, app: App) {
@@ -443,7 +443,7 @@ fn source_of(webview: &ICoreWebView2) -> String {
443fn on_source_changed(shared: &Shared, app: App, url: String) {
443fn on_source_changed(shared: &Shared, app: App, url: String) {
444 let window = shared.windows[&app];
444 let window = shared.windows[&app];
445 let login = is_login_url(&url);
445 let login = is_login_url(&url);
446 let on_app = app.origins().iter().any(|origin| url.starts_with(origin));
446 let on_app = app.is_app_url(&url);
447 shared.state.send_modify(|state| {
447 shared.state.send_modify(|state| {
448 state.urls.insert(app, url);
448 state.urls.insert(app, url);
449 });
449 });
crates/webview/src/host_dialog.rs +1 −1
@@ -444,7 +444,7 @@ fn shadow_calls(webview: &ICoreWebView2) -> windows::core::Result<()> {
444 444 }
445 445 }
446 446
447 fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {
447 pub(crate) fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {
448 448 let Ok(webview) = webview.cast::<ICoreWebView2_18>() else {
449 449 return Ok(());
450 450 };
@@ -444,7 +444,7 @@ fn shadow_calls(webview: &ICoreWebView2) -> windows::core::Result<()> {
444 }
444 }
445}
445}
446
446
447fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {
447pub(crate) fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {
448 let Ok(webview) = webview.cast::<ICoreWebView2_18>() else {
448 let Ok(webview) = webview.cast::<ICoreWebView2_18>() else {
449 return Ok(());
449 return Ok(());
450 };
450 };
crates/webview/src/main_embed.rs +30 −4
@@ -3,12 +3,13 @@ use std::path::PathBuf;
3 3 use std::rc::{Rc, Weak};
4 4 use std::sync::Once;
5 5
6 use session::trusted_url::{MICROSOFT_HOSTS, is_trusted_https_url};
6 7 use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
7 8 use webview2_com::Microsoft::Web::WebView2::Win32::*;
8 9 use webview2_com::{
9 10 CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,
10 NavigationCompletedEventHandler, NewWindowRequestedEventHandler, SourceChangedEventHandler,
11 take_pwstr,
11 NavigationCompletedEventHandler, NavigationStartingEventHandler,
12 NewWindowRequestedEventHandler, SourceChangedEventHandler, take_pwstr,
12 13 };
13 14 use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
14 15 use windows::Win32::Graphics::Gdi::{
@@ -18,11 +19,12 @@ use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
18 19 use windows::Win32::System::LibraryLoader::GetModuleHandleW;
19 20 use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};
20 21 use windows::Win32::UI::WindowsAndMessaging::*;
21 use windows::core::{HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};
22 use windows::core::{BOOL, HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};
22 23
23 24 use crate::embed::{EmbedEvent, EmbedSpec};
24 25 use crate::geometry::{EmbedBounds, local_cutouts};
25 26 use crate::host::environment_options;
27 use crate::host_dialog::block_app_launch;
26 28
27 29 const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");
28 30 const OWNER_SUBCLASS_ID: usize = 0x5254_4542;
@@ -243,6 +245,8 @@ fn attach(embed: &SharedEmbed, controller: ICoreWebView2Controller) -> windows::
243 245 })?;
244 246 webview.Settings()?.SetIsStatusBarEnabled(false)?;
245 247 }
248 keep_on_microsoft_hosts(&webview)?;
249 block_app_launch(&webview)?;
246 250 watch_source(&webview, events.clone())?;
247 251 watch_loaded(&webview, events.clone())?;
248 252 forward_new_windows(&webview, events)?;
@@ -441,6 +445,23 @@ fn watch_source(
441 445 unsafe { webview.add_SourceChanged(&handler, &mut token) }
442 446 }
443 447
448 /// The embed shares the Teams profile and its single sign-on, so it may only show Microsoft pages.
449 fn keep_on_microsoft_hosts(webview: &ICoreWebView2) -> windows::core::Result<()> {
450 let handler = NavigationStartingEventHandler::create(Box::new(|_, arguments| {
451 let Some(arguments) = arguments else {
452 return Ok(());
453 };
454 let mut target = PWSTR::null();
455 unsafe { arguments.Uri(&mut target) }?;
456 if !is_trusted_https_url(&take_pwstr(target), &MICROSOFT_HOSTS) {
457 unsafe { arguments.SetCancel(true) }?;
458 }
459 Ok(())
460 }));
461 let mut token = 0;
462 unsafe { webview.add_NavigationStarting(&handler, &mut token) }
463 }
464
444 465 fn watch_loaded(
445 466 webview: &ICoreWebView2,
446 467 events: UnboundedSender<EmbedEvent>,
@@ -462,11 +483,16 @@ fn forward_new_windows(
462 483 return Ok(());
463 484 };
464 485 let mut target = PWSTR::null();
486 let mut user_initiated = BOOL::default();
465 487 unsafe {
466 488 arguments.Uri(&mut target)?;
489 arguments.IsUserInitiated(&mut user_initiated)?;
467 490 arguments.SetHandled(true)?;
468 491 }
469 let _ = events.send(EmbedEvent::NewWindow(take_pwstr(target)));
492 let target = take_pwstr(target);
493 if user_initiated.as_bool() {
494 let _ = events.send(EmbedEvent::NewWindow(target));
495 }
470 496 Ok(())
471 497 }));
472 498 let mut token = 0;
@@ -3,12 +3,13 @@ use std::path::PathBuf;
3use std::rc::{Rc, Weak};
3use std::rc::{Rc, Weak};
4use std::sync::Once;
4use std::sync::Once;
5
5
6use session::trusted_url::{MICROSOFT_HOSTS, is_trusted_https_url};
6use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
7use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
7use webview2_com::Microsoft::Web::WebView2::Win32::*;
8use webview2_com::Microsoft::Web::WebView2::Win32::*;
8use webview2_com::{
9use webview2_com::{
9 CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,
10 CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,
10 NavigationCompletedEventHandler, NewWindowRequestedEventHandler, SourceChangedEventHandler,
11 NavigationCompletedEventHandler, NavigationStartingEventHandler,
11 take_pwstr,
12 NewWindowRequestedEventHandler, SourceChangedEventHandler, take_pwstr,
12};
13};
13use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
14use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
14use windows::Win32::Graphics::Gdi::{
15use windows::Win32::Graphics::Gdi::{
@@ -18,11 +19,12 @@ use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
18use windows::Win32::System::LibraryLoader::GetModuleHandleW;
19use windows::Win32::System::LibraryLoader::GetModuleHandleW;
19use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};
20use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};
20use windows::Win32::UI::WindowsAndMessaging::*;
21use windows::Win32::UI::WindowsAndMessaging::*;
21use windows::core::{HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};
22use windows::core::{BOOL, HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};
22
23
23use crate::embed::{EmbedEvent, EmbedSpec};
24use crate::embed::{EmbedEvent, EmbedSpec};
24use crate::geometry::{EmbedBounds, local_cutouts};
25use crate::geometry::{EmbedBounds, local_cutouts};
25use crate::host::environment_options;
26use crate::host::environment_options;
27use crate::host_dialog::block_app_launch;
26
28
27const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");
29const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");
28const OWNER_SUBCLASS_ID: usize = 0x5254_4542;
30const OWNER_SUBCLASS_ID: usize = 0x5254_4542;
@@ -243,6 +245,8 @@ fn attach(embed: &SharedEmbed, controller: ICoreWebView2Controller) -> windows::
243 })?;
245 })?;
244 webview.Settings()?.SetIsStatusBarEnabled(false)?;
246 webview.Settings()?.SetIsStatusBarEnabled(false)?;
245 }
247 }
248 keep_on_microsoft_hosts(&webview)?;
249 block_app_launch(&webview)?;
246 watch_source(&webview, events.clone())?;
250 watch_source(&webview, events.clone())?;
247 watch_loaded(&webview, events.clone())?;
251 watch_loaded(&webview, events.clone())?;
248 forward_new_windows(&webview, events)?;
252 forward_new_windows(&webview, events)?;
@@ -441,6 +445,23 @@ fn watch_source(
441 unsafe { webview.add_SourceChanged(&handler, &mut token) }
445 unsafe { webview.add_SourceChanged(&handler, &mut token) }
442}
446}
443
447
448/// The embed shares the Teams profile and its single sign-on, so it may only show Microsoft pages.
449fn keep_on_microsoft_hosts(webview: &ICoreWebView2) -> windows::core::Result<()> {
450 let handler = NavigationStartingEventHandler::create(Box::new(|_, arguments| {
451 let Some(arguments) = arguments else {
452 return Ok(());
453 };
454 let mut target = PWSTR::null();
455 unsafe { arguments.Uri(&mut target) }?;
456 if !is_trusted_https_url(&take_pwstr(target), &MICROSOFT_HOSTS) {
457 unsafe { arguments.SetCancel(true) }?;
458 }
459 Ok(())
460 }));
461 let mut token = 0;
462 unsafe { webview.add_NavigationStarting(&handler, &mut token) }
463}
464
444fn watch_loaded(
465fn watch_loaded(
445 webview: &ICoreWebView2,
466 webview: &ICoreWebView2,
446 events: UnboundedSender<EmbedEvent>,
467 events: UnboundedSender<EmbedEvent>,
@@ -462,11 +483,16 @@ fn forward_new_windows(
462 return Ok(());
483 return Ok(());
463 };
484 };
464 let mut target = PWSTR::null();
485 let mut target = PWSTR::null();
486 let mut user_initiated = BOOL::default();
465 unsafe {
487 unsafe {
466 arguments.Uri(&mut target)?;
488 arguments.Uri(&mut target)?;
489 arguments.IsUserInitiated(&mut user_initiated)?;
467 arguments.SetHandled(true)?;
490 arguments.SetHandled(true)?;
468 }
491 }
469 let _ = events.send(EmbedEvent::NewWindow(take_pwstr(target)));
492 let target = take_pwstr(target);
493 if user_initiated.as_bool() {
494 let _ = events.send(EmbedEvent::NewWindow(target));
495 }
470 Ok(())
496 Ok(())
471 }));
497 }));
472 let mut token = 0;
498 let mut token = 0;