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>
@@ -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",@@ -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 = true26
store.workspace = true26
store.workspace = true27
teams-core.workspace = true27
teams-core.workspace = true28
tokio.workspace = true28
tokio.workspace = true29
url.workspace = true29
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }30
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }30
raw-window-handle = "0.6"31
raw-window-handle = "0.6"31
sha2 = "0.10"32
sha2 = "0.10"@@ -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;30
mod linux_idle;30
mod linux_idle;31
pub mod native_dumps;31
pub mod native_dumps;32
pub mod notify;32
pub mod notify;33
pub mod open_link;33
pub mod orgs;34
pub mod orgs;34
pub mod presence_link;35
pub mod presence_link;35
pub mod read_state;36
pub mod read_state;@@ -0,0 +1,138 @@
1
use gpui_kit::App;
2
use url::Url;
3
4
const WEB_SCHEMES: [&str; 2] = ["https", "http"];
5
const PLAIN_SCHEMES: [&str; 5] = ["mailto", "tel", "sip", "callto", "msteams"];
6
const OFFICE_SCHEMES: [&str; 8] = [
7
"ms-word",
8
"ms-excel",
9
"ms-powerpoint",
10
"ms-visio",
11
"ms-access",
12
"ms-project",
13
"ms-publisher",
14
"ms-infopath",
15
];
16
17
pub fn openable_url(raw: &str) -> Option<String> {
18
let url = Url::parse(raw.trim()).ok()?;
19
let scheme = url.scheme();
20
let allowed = if WEB_SCHEMES.contains(&scheme) {
21
url.host_str().is_some_and(|host| !host.is_empty())
22
} else if PLAIN_SCHEMES.contains(&scheme) {
23
url.host().is_none() && !url.path().contains('\\')
24
} else if scheme == "onenote" {
25
web_document(url.path()).is_some()
26
} else if OFFICE_SCHEMES.contains(&scheme) {
27
url.path()
28
.rsplit('|')
29
.next()
30
.and_then(web_document)
31
.is_some()
32
} else {
33
false
34
};
35
allowed.then(|| url.into())
36
}
37
38
fn web_document(document: &str) -> Option<Url> {
39
let document = Url::parse(document).ok()?;
40
(document.scheme() == "https" && document.host_str().is_some()).then_some(document)
41
}
42
43
pub fn is_openable_url(raw: &str) -> bool {
44
openable_url(raw).is_some()
45
}
46
47
pub fn open_url(cx: &mut App, raw: &str) {
48
match openable_url(raw) {
49
Some(url) => cx.open_url(&url),
50
None => crate::diagnostics::record(format!("refused to open a link: {}", scheme_of(raw))),
51
}
52
}
53
54
fn scheme_of(raw: &str) -> &str {
55
raw.trim()
56
.split_once(':')
57
.map_or("no scheme", |(scheme, _)| scheme)
58
}
59
60
#[cfg(test)]
61
mod tests {
62
use super::*;
63
64
#[test]
65
fn web_mail_and_teams_links_open() {
66
for url in [
67
"https://contoso.sharepoint.com/x.pdf",
68
"http://intranet.example/x",
69
"mailto:someone@example.com",
70
"tel:+491234",
71
"msteams:/l/chat/0/0",
72
"onenote:https://contoso.sharepoint.com/n.one",
73
"ms-word:ofe|u|https://contoso.sharepoint.com/a.docx",
74
] {
75
assert!(is_openable_url(url), "{url}");
76
}
77
}
78
79
#[test]
80
fn files_shares_and_local_handlers_do_not_open() {
81
for url in [
82
"\\\\203.0.113.5\\s\\x.lnk",
83
"file:///C:/Windows/System32/calc.exe",
84
"file://203.0.113.5/s/x.lnk",
85
"search-ms:query=x&crumb=location:\\\\203.0.113.5\\s",
86
"javascript:alert(1)",
87
"ms-msdt:/id x",
88
"ms-word:ofe|u|\\\\203.0.113.5\\s\\a.docx",
89
"ms-word:ofe|u|file:///C:/a.docx",
90
"ms-word:ofe|u|http://203.0.113.5/a.docx",
91
"mailto:\\\\203.0.113.5\\s",
92
"onenote:\\\\203.0.113.5\\s\\n.one",
93
"onenote://203.0.113.5/s/n.one",
94
"onenote:file:///C:/n.one",
95
"C:\\Windows\\System32\\calc.exe",
96
"",
97
] {
98
assert!(!is_openable_url(url), "{url}");
99
}
100
}
101
102
#[test]
103
fn every_url_the_app_opens_goes_through_this_module() {
104
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
105
let mut offenders = Vec::new();
106
visit(&crates, &mut offenders);
107
assert!(
108
offenders.is_empty(),
109
"use app_base::open_link::open_url instead of cx.open_url: {offenders:#?}"
110
);
111
}
112
113
fn visit(directory: &std::path::Path, offenders: &mut Vec<String>) {
114
let Ok(entries) = std::fs::read_dir(directory) else {
115
return;
116
};
117
for entry in entries.flatten() {
118
let path = entry.path();
119
if path.is_dir() {
120
if path.file_name().is_some_and(|name| name != "target") {
121
visit(&path, offenders);
122
}
123
continue;
124
}
125
if path.extension().is_none_or(|extension| extension != "rs")
126
|| path.ends_with("app-base/src/open_link.rs")
127
{
128
continue;
129
}
130
let text = std::fs::read_to_string(&path).unwrap_or_default();
131
for (number, line) in text.lines().enumerate() {
132
if line.contains("cx.open_url(") {
133
offenders.push(format!("{}:{}", path.display(), number + 1));
134
}
135
}
136
}
137
}
138
}
@@ -0,0 +1,138 @@1
use gpui_kit::App;2
use url::Url;3
4
const WEB_SCHEMES: [&str; 2] = ["https", "http"];5
const PLAIN_SCHEMES: [&str; 5] = ["mailto", "tel", "sip", "callto", "msteams"];6
const OFFICE_SCHEMES: [&str; 8] = [7
"ms-word",8
"ms-excel",9
"ms-powerpoint",10
"ms-visio",11
"ms-access",12
"ms-project",13
"ms-publisher",14
"ms-infopath",15
];16
17
pub fn openable_url(raw: &str) -> Option<String> {18
let url = Url::parse(raw.trim()).ok()?;19
let scheme = url.scheme();20
let allowed = if WEB_SCHEMES.contains(&scheme) {21
url.host_str().is_some_and(|host| !host.is_empty())22
} else if PLAIN_SCHEMES.contains(&scheme) {23
url.host().is_none() && !url.path().contains('\\')24
} else if scheme == "onenote" {25
web_document(url.path()).is_some()26
} else if OFFICE_SCHEMES.contains(&scheme) {27
url.path()28
.rsplit('|')29
.next()30
.and_then(web_document)31
.is_some()32
} else {33
false34
};35
allowed.then(|| url.into())36
}37
38
fn web_document(document: &str) -> Option<Url> {39
let document = Url::parse(document).ok()?;40
(document.scheme() == "https" && document.host_str().is_some()).then_some(document)41
}42
43
pub fn is_openable_url(raw: &str) -> bool {44
openable_url(raw).is_some()45
}46
47
pub fn open_url(cx: &mut App, raw: &str) {48
match openable_url(raw) {49
Some(url) => cx.open_url(&url),50
None => crate::diagnostics::record(format!("refused to open a link: {}", scheme_of(raw))),51
}52
}53
54
fn scheme_of(raw: &str) -> &str {55
raw.trim()56
.split_once(':')57
.map_or("no scheme", |(scheme, _)| scheme)58
}59
60
#[cfg(test)]61
mod tests {62
use super::*;63
64
#[test]65
fn web_mail_and_teams_links_open() {66
for url in [67
"https://contoso.sharepoint.com/x.pdf",68
"http://intranet.example/x",69
"mailto:someone@example.com",70
"tel:+491234",71
"msteams:/l/chat/0/0",72
"onenote:https://contoso.sharepoint.com/n.one",73
"ms-word:ofe|u|https://contoso.sharepoint.com/a.docx",74
] {75
assert!(is_openable_url(url), "{url}");76
}77
}78
79
#[test]80
fn files_shares_and_local_handlers_do_not_open() {81
for url in [82
"\\\\203.0.113.5\\s\\x.lnk",83
"file:///C:/Windows/System32/calc.exe",84
"file://203.0.113.5/s/x.lnk",85
"search-ms:query=x&crumb=location:\\\\203.0.113.5\\s",86
"javascript:alert(1)",87
"ms-msdt:/id x",88
"ms-word:ofe|u|\\\\203.0.113.5\\s\\a.docx",89
"ms-word:ofe|u|file:///C:/a.docx",90
"ms-word:ofe|u|http://203.0.113.5/a.docx",91
"mailto:\\\\203.0.113.5\\s",92
"onenote:\\\\203.0.113.5\\s\\n.one",93
"onenote://203.0.113.5/s/n.one",94
"onenote:file:///C:/n.one",95
"C:\\Windows\\System32\\calc.exe",96
"",97
] {98
assert!(!is_openable_url(url), "{url}");99
}100
}101
102
#[test]103
fn every_url_the_app_opens_goes_through_this_module() {104
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");105
let mut offenders = Vec::new();106
visit(&crates, &mut offenders);107
assert!(108
offenders.is_empty(),109
"use app_base::open_link::open_url instead of cx.open_url: {offenders:#?}"110
);111
}112
113
fn visit(directory: &std::path::Path, offenders: &mut Vec<String>) {114
let Ok(entries) = std::fs::read_dir(directory) else {115
return;116
};117
for entry in entries.flatten() {118
let path = entry.path();119
if path.is_dir() {120
if path.file_name().is_some_and(|name| name != "target") {121
visit(&path, offenders);122
}123
continue;124
}125
if path.extension().is_none_or(|extension| extension != "rs")126
|| path.ends_with("app-base/src/open_link.rs")127
{128
continue;129
}130
let text = std::fs::read_to_string(&path).unwrap_or_default();131
for (number, line) in text.lines().enumerate() {132
if line.contains("cx.open_url(") {133
offenders.push(format!("{}:{}", path.display(), number + 1));134
}135
}136
}137
}138
}@@ -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
@@ -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) => {@@ -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();@@ -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,@@ -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
51
pub fn open_url(cx: &mut App, store: &Store, url: &str) {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
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
}@@ -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: &mut45
45
46
#[cfg(not(windows))]46
#[cfg(not(windows))]47
pub fn open_url_dialog(dialog: UrlDialog, _engine: Option<Arc<Engine>>, cx: &mut App) {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
}@@ -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
20
pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {20
pub 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();@@ -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_ROOM145
.to_string()146
.repeat(width_in_spaces),145
StyleFlags::default(),147
StyleFlags::default(),146
None,148
None,147
);149
);@@ -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 {@@ -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) -> bo17
}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
pub fn is_openable_link(url: &str) -> bool {20
pub 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_SCHEMES42
.iter()43
.any(|scheme| lower.starts_with(scheme))44
}22
}45
23
46
pub fn open_link(url: &str, cx: &mut App) {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
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
@@ -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]@@ -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;2
use std::rc::Rc;2
use std::rc::Rc;3
3
4
use gpui_kit::*;4
use gpui_kit::*;5
use session::trusted_url::{HostRule, trusted_https_url};5
6
6
#[cfg(windows)]7
#[cfg(windows)]7
mod native_windows;8
mod native_windows;@@ -17,18 +18,20 @@ pub use native::available;17
#[cfg(windows)]18
#[cfg(windows)]18
pub use native::configure;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
const PERSONAL_SITE: &str = "/personal/";23
const PERSONAL_SITE: &str = "/personal/";21
const TEAM_SITES: [&str; 2] = ["/sites/", "/teams/"];24
const TEAM_SITES: [&str; 2] = ["/sites/", "/teams/"];22
const PLAYER_OPTIONS: &str = "%7B%22ust%22%3Atrue%2C%22hv%22%3A%22CopyEmbedCode%22%7D";25
const 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.25
pub fn player_url(content_url: &str) -> Option<String> {28
pub 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: &mut67
};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
None197
);198
assert_eq!(199
player_url("https://evil.example\\.sharepoint.com/personal/x/y.mp4"),200
None201
);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/"),@@ -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
)@@ -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());@@ -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();@@ -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
@@ -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(@@ -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),@@ -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
),@@ -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
114
fn opening_link_text(url: &str) -> String {114
fn 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) = link309
&& let Some(link) = link310
{310
{311
cx.open_url(link);311
app_base::open_link::open_url(cx, link);312
}312
}313
}313
}314
},314
},@@ -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 = true23
webrtc-sys = "=0.3.48"23
webrtc-sys = "=0.3.48"24
serde_json.workspace = true24
serde_json.workspace = true25
session.workspace = true25
session.workspace = true26
url.workspace = true26
thiserror.workspace = true27
thiserror.workspace = true27
tract-onnx = "0.23"28
tract-onnx = "0.23"28
tokio.workspace = true29
tokio.workspace = true@@ -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
¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2102
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(¤t.peer, ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(¤t.peer, ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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.audio899
live.audio899
.as_ref()900
.as_ref()900
.expect("audio set above")901
.expect("audio set above")901
.track902
.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
¤t.peer,1104
¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);2102
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(¤t.peer, ¤t.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(¤t.peer, ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(¤t.peer, ¤t.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(¤t.peer, ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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(), ¤t.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
}@@ -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 @@1
use std::collections::BTreeMap;1
use std::collections::BTreeMap;2
2
3
use serde_json::{Map, Value, json};3
use serde_json::{Map, Value, json};4
use session::trusted_url::{HostRule, trusted_https_url};4
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};5
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};6
use url::{Position, Url};5
7
6
use crate::captions::{self, BotAction};8
use crate::captions::{self, BotAction};7
use crate::error::{Error, Result};9
use crate::error::{Error, Result};@@ -25,8 +27,7 @@ const ENDPOINT_CAPABILITIES: u64 = 73463;25
const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";27
const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";26
const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";28
const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";27
const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;29
const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;28
const ALLOWED_HOST_SUFFIXES: [&str; 2] =30
const TEAMS_HOSTS: [HostRule; 1] = [HostRule::Domain("teams.microsoft.com")];29
[".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];30
const BACKEND_SUFFIX: &str = ".skype.com";31
const BACKEND_SUFFIX: &str = ".skype.com";31
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";32
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";32
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";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
fn 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.154
pub fn ensure_teams_url(url: &str) -> Result<()> {161
pub fn ensure_teams_url(url: &str) -> Result<()> {155
let host = host_of(url)?;162
trusted_teams_url(url).map(|_| ())156
if ALLOWED_HOST_SUFFIXES163
}157
.iter()164
158
.any(|suffix| host.ends_with(suffix))165
fn 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
167
fn is_backend_host(host: &str) -> bool {175
fn 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.178
pub fn routed_url(url: &str) -> Result<String> {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
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 = rest186
.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());@@ -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};4
use session::{App, Scope, Session};4
use session::{App, Scope, Session};5
5
6
use crate::error::{Error, Result};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
use crate::messages::ensure_success;8
use crate::messages::ensure_success;9
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};9
use 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 = self95
let answer = self91
.session96
.session92
.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?;@@ -1,7 +1,9 @@
1
1
use base64::Engine as _;
2
2
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
3
3
use serde_json::{Value, json};
4
use session::trusted_url::{HostRule, trusted_https_url};
4
5
use session::{Method, Request};
6
use url::Url;
5
7
6
8
use crate::error::{Error, Result};
7
9
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};
@@ -11,7 +13,10 @@ pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
11
13
const LIST_VIEW: &str = "msnp24Equivalent";
12
14
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";
13
15
const HOSTED_URL_KEY: &str = ",url=";
14
const AMS_HOST_SUFFIX: &str = ".asm.skype.com";
16
const LINK_PROXY_HOSTS: [HostRule; 1] = [HostRule::Domain("asyncgw.teams.microsoft.com")];
17
const AMS_HOSTS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")];
18
const AMS_OBJECT_HOSTS: [HostRule; 2] = [AMS_HOSTS[0], LINK_PROXY_HOSTS[0]];
19
const OBJECTS_PATH: &str = "/v1/objects/";
15
20
const VIEWS_SEGMENT: &str = "/views/";
16
21
const FULL_SIZE_VIEW_PREFIX: &str = "imgpsh_fullsize";
17
22
/// The view Teams opens in its image viewer; `_anim` keeps animated GIFs moving.
@@ -41,9 +46,7 @@ pub struct LinkImage {
41
46
}
42
47
43
48
pub fn is_link_image_url(url: &str) -> bool {
44
url.strip_prefix("https://")
45
.and_then(|rest| rest.split(['/', '?', '#']).next())
46
.is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))
49
trusted_https_url(url, &LINK_PROXY_HOSTS).is_some()
47
50
}
48
51
49
52
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.
@@ -56,16 +59,19 @@ pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
56
59
.ok()?;
57
60
let decoded = String::from_utf8(bytes).ok()?;
58
61
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;
59
(is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned())
62
(is_link_image_url(url) || is_ams_image_url(url))
63
.then(|| Url::parse(url).ok())
64
.flatten()
65
.map(String::from)
60
66
}
61
67
62
68
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.
63
69
pub fn is_ams_image_url(url: &str) -> bool {
64
url.strip_prefix("https://")
65
.and_then(|rest| rest.split_once('/'))
66
.is_some_and(|(host, path)| {
67
host.ends_with(AMS_HOST_SUFFIX) && path.starts_with("v1/objects/")
68
})
70
trusted_ams_image_url(url).is_some()
71
}
72
73
pub fn trusted_ams_image_url(url: &str) -> Option<Url> {
74
trusted_https_url(url, &AMS_HOSTS).filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))
69
75
}
70
76
71
77
/// The full-resolution view of the AMS image at `url` (a plain AMS view or a Graph `hostedContents` link to one).
@@ -74,15 +80,9 @@ pub fn is_ams_image_url(url: &str) -> bool {
74
80
pub fn ams_full_size_url(url: &str) -> Option<String> {
75
81
let decoded = hosted_content_image_url(url);
76
82
let url = decoded.as_deref().unwrap_or(url);
77
let is_object = |host: &str, path: &str| {
78
path.starts_with("v1/objects/")
79
&& (host.ends_with(AMS_HOST_SUFFIX) || host.ends_with(LINK_PROXY_HOST_SUFFIX))
80
};
81
let (host, path) = url.strip_prefix("https://")?.split_once('/')?;
82
if !is_object(host, path) {
83
return None;
84
}
85
let (object, view) = url.rsplit_once(VIEWS_SEGMENT)?;
83
let parsed = trusted_https_url(url, &AMS_OBJECT_HOSTS)
84
.filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))?;
85
let (object, view) = parsed.as_str().rsplit_once(VIEWS_SEGMENT)?;
86
86
let still_picture = view.starts_with("img") && !view.contains(['/', '?', '#']);
87
87
(still_picture && !view.starts_with(FULL_SIZE_VIEW_PREFIX))
88
88
.then(|| format!("{object}{VIEWS_SEGMENT}{FULL_SIZE_VIEW}"))
@@ -177,12 +177,15 @@ impl<T: MessageTransport> Messages<T> {
177
177
}
178
178
179
179
pub async fn link_image(&self, url: &str) -> Result<LinkImage> {
180
if !is_link_image_url(url) {
180
let Some(url) = trusted_https_url(url, &LINK_PROXY_HOSTS) else {
181
181
return Err(Error::UnexpectedAnswer(format!(
182
182
"not a link preview image url: {url}"
183
183
)));
184
}
185
let answer = self.transport.send(Request::binary_get(url)).await?;
184
};
185
let answer = self
186
.transport
187
.send(Request::binary_get(url.as_str()))
188
.await?;
186
189
ensure_success(&answer)?;
187
190
decoded_image(&answer.body)
188
191
}
@@ -359,5 +362,24 @@ mod tests {
359
362
assert!(!is_link_image_url(
360
363
"http://de-prod.asyncgw.teams.microsoft.com/x"
361
364
));
365
for bypass in [
366
"https://evil.example\\.asyncgw.teams.microsoft.com/x",
367
"https://de-prod.asyncgw.teams.microsoft.com:x@evil.example/",
368
] {
369
assert!(!is_link_image_url(bypass), "{bypass}");
370
}
371
}
372
373
#[test]
374
fn ams_checks_see_the_host_the_request_goes_to() {
375
for bypass in [
376
"https://evil.example#.asm.skype.com/v1/objects/a",
377
"https://evil.example?.asm.skype.com/v1/objects/a",
378
"https://evil.example\\.asm.skype.com/v1/objects/a",
379
"https://eu-api.asm.skype.com@evil.example/v1/objects/a",
380
] {
381
assert!(!is_ams_image_url(bypass), "{bypass}");
382
assert_eq!(ams_full_size_url(&format!("{bypass}/views/imgo")), None);
383
}
362
384
}
363
385
}
@@ -1,7 +1,9 @@1
use base64::Engine as _;1
use base64::Engine as _;2
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};2
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};3
use serde_json::{Value, json};3
use serde_json::{Value, json};4
use session::trusted_url::{HostRule, trusted_https_url};4
use session::{Method, Request};5
use session::{Method, Request};6
use url::Url;5
7
6
use crate::error::{Error, Result};8
use crate::error::{Error, Result};7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};9
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};@@ -11,7 +13,10 @@ pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";11
const LIST_VIEW: &str = "msnp24Equivalent";13
const LIST_VIEW: &str = "msnp24Equivalent";12
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";14
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";13
const HOSTED_URL_KEY: &str = ",url=";15
const HOSTED_URL_KEY: &str = ",url=";14
const AMS_HOST_SUFFIX: &str = ".asm.skype.com";16
const LINK_PROXY_HOSTS: [HostRule; 1] = [HostRule::Domain("asyncgw.teams.microsoft.com")];17
const AMS_HOSTS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")];18
const AMS_OBJECT_HOSTS: [HostRule; 2] = [AMS_HOSTS[0], LINK_PROXY_HOSTS[0]];19
const OBJECTS_PATH: &str = "/v1/objects/";15
const VIEWS_SEGMENT: &str = "/views/";20
const VIEWS_SEGMENT: &str = "/views/";16
const FULL_SIZE_VIEW_PREFIX: &str = "imgpsh_fullsize";21
const FULL_SIZE_VIEW_PREFIX: &str = "imgpsh_fullsize";17
/// The view Teams opens in its image viewer; `_anim` keeps animated GIFs moving.22
/// The view Teams opens in its image viewer; `_anim` keeps animated GIFs moving.@@ -41,9 +46,7 @@ pub struct LinkImage {41
}46
}42
47
43
pub fn is_link_image_url(url: &str) -> bool {48
pub fn is_link_image_url(url: &str) -> bool {44
url.strip_prefix("https://")49
trusted_https_url(url, &LINK_PROXY_HOSTS).is_some()45
.and_then(|rest| rest.split(['/', '?', '#']).next())46
.is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))47
}50
}48
51
49
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.52
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.@@ -56,16 +59,19 @@ pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {56
.ok()?;59
.ok()?;57
let decoded = String::from_utf8(bytes).ok()?;60
let decoded = String::from_utf8(bytes).ok()?;58
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;61
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;59
(is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned())62
(is_link_image_url(url) || is_ams_image_url(url))63
.then(|| Url::parse(url).ok())64
.flatten()65
.map(String::from)60
}66
}61
67
62
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.68
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.63
pub fn is_ams_image_url(url: &str) -> bool {69
pub fn is_ams_image_url(url: &str) -> bool {64
url.strip_prefix("https://")70
trusted_ams_image_url(url).is_some()65
.and_then(|rest| rest.split_once('/'))71
}66
.is_some_and(|(host, path)| {72
67
host.ends_with(AMS_HOST_SUFFIX) && path.starts_with("v1/objects/")73
pub fn trusted_ams_image_url(url: &str) -> Option<Url> {68
})74
trusted_https_url(url, &AMS_HOSTS).filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))69
}75
}70
76
71
/// The full-resolution view of the AMS image at `url` (a plain AMS view or a Graph `hostedContents` link to one).77
/// The full-resolution view of the AMS image at `url` (a plain AMS view or a Graph `hostedContents` link to one).@@ -74,15 +80,9 @@ pub fn is_ams_image_url(url: &str) -> bool {74
pub fn ams_full_size_url(url: &str) -> Option<String> {80
pub fn ams_full_size_url(url: &str) -> Option<String> {75
let decoded = hosted_content_image_url(url);81
let decoded = hosted_content_image_url(url);76
let url = decoded.as_deref().unwrap_or(url);82
let url = decoded.as_deref().unwrap_or(url);77
let is_object = |host: &str, path: &str| {83
let parsed = trusted_https_url(url, &AMS_OBJECT_HOSTS)78
path.starts_with("v1/objects/")84
.filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))?;79
&& (host.ends_with(AMS_HOST_SUFFIX) || host.ends_with(LINK_PROXY_HOST_SUFFIX))85
let (object, view) = parsed.as_str().rsplit_once(VIEWS_SEGMENT)?;80
};81
let (host, path) = url.strip_prefix("https://")?.split_once('/')?;82
if !is_object(host, path) {83
return None;84
}85
let (object, view) = url.rsplit_once(VIEWS_SEGMENT)?;86
let still_picture = view.starts_with("img") && !view.contains(['/', '?', '#']);86
let still_picture = view.starts_with("img") && !view.contains(['/', '?', '#']);87
(still_picture && !view.starts_with(FULL_SIZE_VIEW_PREFIX))87
(still_picture && !view.starts_with(FULL_SIZE_VIEW_PREFIX))88
.then(|| format!("{object}{VIEWS_SEGMENT}{FULL_SIZE_VIEW}"))88
.then(|| format!("{object}{VIEWS_SEGMENT}{FULL_SIZE_VIEW}"))@@ -177,12 +177,15 @@ impl<T: MessageTransport> Messages<T> {177
}177
}178
178
179
pub async fn link_image(&self, url: &str) -> Result<LinkImage> {179
pub async fn link_image(&self, url: &str) -> Result<LinkImage> {180
if !is_link_image_url(url) {180
let Some(url) = trusted_https_url(url, &LINK_PROXY_HOSTS) else {181
return Err(Error::UnexpectedAnswer(format!(181
return Err(Error::UnexpectedAnswer(format!(182
"not a link preview image url: {url}"182
"not a link preview image url: {url}"183
)));183
)));184
}184
};185
let answer = self.transport.send(Request::binary_get(url)).await?;185
let answer = self186
.transport187
.send(Request::binary_get(url.as_str()))188
.await?;186
ensure_success(&answer)?;189
ensure_success(&answer)?;187
decoded_image(&answer.body)190
decoded_image(&answer.body)188
}191
}@@ -359,5 +362,24 @@ mod tests {359
assert!(!is_link_image_url(362
assert!(!is_link_image_url(360
"http://de-prod.asyncgw.teams.microsoft.com/x"363
"http://de-prod.asyncgw.teams.microsoft.com/x"361
));364
));365
for bypass in [366
"https://evil.example\\.asyncgw.teams.microsoft.com/x",367
"https://de-prod.asyncgw.teams.microsoft.com:x@evil.example/",368
] {369
assert!(!is_link_image_url(bypass), "{bypass}");370
}371
}372
373
#[test]374
fn ams_checks_see_the_host_the_request_goes_to() {375
for bypass in [376
"https://evil.example#.asm.skype.com/v1/objects/a",377
"https://evil.example?.asm.skype.com/v1/objects/a",378
"https://evil.example\\.asm.skype.com/v1/objects/a",379
"https://eu-api.asm.skype.com@evil.example/v1/objects/a",380
] {381
assert!(!is_ams_image_url(bypass), "{bypass}");382
assert_eq!(ams_full_size_url(&format!("{bypass}/views/imgo")), None);383
}362
}384
}363
}385
}@@ -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 @@1
use serde_json::{Value, json};1
use serde_json::{Value, json};2
use session::trusted_url::may_carry_credentials;2
use session::{ApiResponse, App, Request, Scope, Session};3
use session::{ApiResponse, App, Request, Scope, Session};3
4
4
use crate::error::Result;5
use crate::error::{Error, Result};5
6
6
pub const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";7
pub const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";7
pub const CSA_SCOPE: &str = "user_impersonation";8
pub const CSA_SCOPE: &str = "user_impersonation";@@ -86,6 +87,12 @@ pub fn skype_fetch_answer(answer: Value) -> ApiResponse {86
87
87
impl CsaTransport for SkypeTokenTransport {88
impl 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.url94
)));95
}89
let answer = self96
let answer = self90
.session97
.session91
.run_with_token(98
.run_with_token(@@ -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 @@1
use std::collections::VecDeque;1
use std::collections::VecDeque;2
use std::sync::Mutex;2
use std::sync::Mutex;3
3
4
use serde_json::{json, Value};4
use serde_json::{Value, json};5
use session::{ApiResponse, Method, Request};5
use session::{ApiResponse, Method, Request};6
6
7
use super::*;7
use super::*;@@ -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
docker3223
.to_html()3224
.starts_with("<pre class=\"language-dockerFile ")3225
);3218
}3226
}3219
3227
3220
#[test]3228
#[test]@@ -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
107
pub fn is_login_url(url: &str) -> bool {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
pub fn has_login_tab(targets: &[Target]) -> bool {116
pub 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 [@@ -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;9
mod scope;9
mod scope;10
mod session;10
mod session;11
mod transport;11
mod transport;12
pub mod trusted_url;12
13
13
pub use app::{App, MCAS_SUFFIX, Target, find_app_tab, has_login_tab, is_login_url, is_mcas_url};14
pub use app::{App, MCAS_SUFFIX, Target, find_app_tab, has_login_tab, is_login_url, is_mcas_url};14
pub use error::{Error, Result};15
pub use error::{Error, Result};@@ -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};7
use futures_util::future::join_all;7
use futures_util::future::join_all;8
use serde_json::{Value, json};8
use serde_json::{Value, json};9
9
10
use crate::app::App;10
use crate::app::{App, is_on_origin};11
use crate::request::{ApiResponse, Method, Request};11
use crate::request::{ApiResponse, Method, Request};12
use crate::scope::Scope;12
use crate::scope::Scope;13
use crate::session::Session;13
use crate::session::Session;@@ -249,7 +249,7 @@ fn eligible(request: &Request) -> bool {249
fn needs_page_cookies(url: &str) -> bool {249
fn 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::Teams253
&& !(app == App::Teams254
&& TEAMS_BEARER_PATHS254
&& TEAMS_BEARER_PATHS255
.iter()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
fn method(method: Method) -> reqwest::Method {261
fn method(method: Method) -> reqwest::Method {267
match method {262
match method {268
Method::Get => reqwest::Method::GET,263
Method::Get => reqwest::Method::GET,@@ -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;14
use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};14
use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};15
use crate::scope::Scope;15
use crate::scope::Scope;16
use crate::transport::{CdpTransport, Transport};16
use crate::transport::{CdpTransport, Transport};17
use crate::trusted_url::may_carry_credentials;17
18
18
pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";19
pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";19
pub const UNSEAL_SCRIPT: &str = include_str!("../assets/unseal.js");20
pub 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
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
fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {457
fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {438
config458
config439
.native_http459
.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
.await511
.unwrap();512
let answers = session513
.batch(514
&[Request::binary_get(515
"https://evil.com\\.asyncgw.teams.microsoft.com/x",516
)],517
&Scope::graph("x"),518
)519
.await520
.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());@@ -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 @@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 == domain15
|| host16
.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
&& url65
.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
&rules119
));120
assert!(!is_trusted_https_url(121
"https://a.teams.microsoft.com/x",122
&rules123
));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
}@@ -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"@@ -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
335
fn is_running_app(app: App, url: &str) -> bool {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
fn park(shared: &Shared, app: App) {339
fn park(shared: &Shared, app: App) {@@ -443,7 +443,7 @@ fn source_of(webview: &ICoreWebView2) -> String {443
fn on_source_changed(shared: &Shared, app: App, url: String) {443
fn 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
});@@ -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
447
fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {447
pub(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
};@@ -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;3
use std::rc::{Rc, Weak};3
use std::rc::{Rc, Weak};4
use std::sync::Once;4
use std::sync::Once;5
5
6
use session::trusted_url::{MICROSOFT_HOSTS, is_trusted_https_url};6
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};7
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};7
use webview2_com::Microsoft::Web::WebView2::Win32::*;8
use webview2_com::Microsoft::Web::WebView2::Win32::*;8
use webview2_com::{9
use 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
};13
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};14
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};14
use windows::Win32::Graphics::Gdi::{15
use windows::Win32::Graphics::Gdi::{@@ -18,11 +19,12 @@ use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};18
use windows::Win32::System::LibraryLoader::GetModuleHandleW;19
use windows::Win32::System::LibraryLoader::GetModuleHandleW;19
use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};20
use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};20
use windows::Win32::UI::WindowsAndMessaging::*;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
use crate::embed::{EmbedEvent, EmbedSpec};24
use crate::embed::{EmbedEvent, EmbedSpec};24
use crate::geometry::{EmbedBounds, local_cutouts};25
use crate::geometry::{EmbedBounds, local_cutouts};25
use crate::host::environment_options;26
use crate::host::environment_options;27
use crate::host_dialog::block_app_launch;26
28
27
const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");29
const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");28
const OWNER_SUBCLASS_ID: usize = 0x5254_4542;30
const 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.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
fn watch_loaded(465
fn 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;