BlueGit

ict rusty-teams

fix(calendar): address Copilot review on event peek

Sanitize agenda HTML hrefs and Google descriptions, fully percent-encode
mailto subjects, localize the primary calendar fallback, and pick the
richest event copy in one pass.

metis Joachim Mild · pushed by metis

Authored 2026-11-13 · 2 weeks ago

Hash
1cb5a2c525271f8a104b18229805589777eb98e7
Parent
9fa73c38
4 files changed +149 −41
crates/app-state/src/google_calendar_sync.rs +4 −1
@@ -34,7 +34,10 @@ pub async fn fetch_google_events(
34 34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
35 35 .collect();
36 36 let calendars = if calendars.is_empty() {
37 vec![("primary".to_owned(), "Primary".to_owned())]
37 vec![(
38 "primary".to_owned(),
39 app_base::ui_locale::tr("settings.calendar.primary"),
40 )]
38 41 } else {
39 42 calendars
40 43 };
@@ -34,7 +34,10 @@ pub async fn fetch_google_events(
34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
35 .collect();
35 .collect();
36 let calendars = if calendars.is_empty() {
36 let calendars = if calendars.is_empty() {
37 vec![("primary".to_owned(), "Primary".to_owned())]
37 vec![(
38 "primary".to_owned(),
39 app_base::ui_locale::tr("settings.calendar.primary"),
40 )]
38 } else {
41 } else {
39 calendars
42 calendars
40 };
43 };
crates/app/src/views/calendar_event_dialog.rs +25 −23
@@ -115,13 +115,6 @@ impl EventPeek {
115 115 fn pull_event(&mut self, cx: &mut Context<Self>) {
116 116 let key = self.event.object_id.clone();
117 117 let app = self.state.read(cx);
118 let best = app
119 .calendar_week
120 .events
121 .iter()
122 .chain(app.calendar_events.iter())
123 .find(|event| event.object_id == key)
124 .cloned();
125 118 let best = app
126 119 .calendar_week
127 120 .events
@@ -129,13 +122,12 @@ impl EventPeek {
129 122 .chain(app.calendar_events.iter())
130 123 .filter(|event| event.object_id == key)
131 124 .cloned()
132 .fold(best, |best, candidate| {
133 Some(match best {
134 Some(current) if event_detail_score(&current) >= event_detail_score(&candidate) => {
135 current
136 }
137 _ => candidate,
138 })
125 .reduce(|best, candidate| {
126 if event_detail_score(&candidate) > event_detail_score(&best) {
127 candidate
128 } else {
129 best
130 }
139 131 });
140 132 if let Some(event) = best {
141 133 self.event = event;
@@ -522,15 +514,10 @@ impl EventPeek {
522 514 if !addresses.is_empty() {
523 515 let mut mailto = format!("mailto:{}", addresses.join(","));
524 516 if !self.event.subject.is_empty() {
525 let subject = self
526 .event
527 .subject
528 .replace('%', "%25")
529 .replace(' ', "%20")
530 .replace('&', "%26")
531 .replace('?', "%3F")
532 .replace('#', "%23");
533 mailto = format!("{mailto}?subject={subject}");
517 mailto = format!(
518 "{mailto}?subject={}",
519 percent_encode_query(&self.event.subject)
520 );
534 521 }
535 522 buttons.push(
536 523 Button::new("calendar-peek-email-guests")
@@ -962,6 +949,21 @@ fn group_label(group: ResponseType) -> String {
962 949 }
963 950 }
964 951
952 /// Percent-encode a mailto `subject` query value (UTF-8, RFC 3986).
953 fn percent_encode_query(value: &str) -> String {
954 let mut out = String::with_capacity(value.len() * 3);
955 for byte in value.as_bytes() {
956 match *byte {
957 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
958 out.push(*byte as char);
959 }
960 b' ' => out.push_str("%20"),
961 _ => out.push_str(&format!("%{byte:02X}")),
962 }
963 }
964 out
965 }
966
965 967 fn is_teams_url(url: &str) -> bool {
966 968 url.contains("teams.microsoft.com")
967 969 }
@@ -115,13 +115,6 @@ impl EventPeek {
115 fn pull_event(&mut self, cx: &mut Context<Self>) {
115 fn pull_event(&mut self, cx: &mut Context<Self>) {
116 let key = self.event.object_id.clone();
116 let key = self.event.object_id.clone();
117 let app = self.state.read(cx);
117 let app = self.state.read(cx);
118 let best = app
119 .calendar_week
120 .events
121 .iter()
122 .chain(app.calendar_events.iter())
123 .find(|event| event.object_id == key)
124 .cloned();
125 let best = app
118 let best = app
126 .calendar_week
119 .calendar_week
127 .events
120 .events
@@ -129,13 +122,12 @@ impl EventPeek {
129 .chain(app.calendar_events.iter())
122 .chain(app.calendar_events.iter())
130 .filter(|event| event.object_id == key)
123 .filter(|event| event.object_id == key)
131 .cloned()
124 .cloned()
132 .fold(best, |best, candidate| {
125 .reduce(|best, candidate| {
133 Some(match best {
126 if event_detail_score(&candidate) > event_detail_score(&best) {
134 Some(current) if event_detail_score(&current) >= event_detail_score(&candidate) => {
127 candidate
135 current
128 } else {
136 }
129 best
137 _ => candidate,
130 }
138 })
139 });
131 });
140 if let Some(event) = best {
132 if let Some(event) = best {
141 self.event = event;
133 self.event = event;
@@ -522,15 +514,10 @@ impl EventPeek {
522 if !addresses.is_empty() {
514 if !addresses.is_empty() {
523 let mut mailto = format!("mailto:{}", addresses.join(","));
515 let mut mailto = format!("mailto:{}", addresses.join(","));
524 if !self.event.subject.is_empty() {
516 if !self.event.subject.is_empty() {
525 let subject = self
517 mailto = format!(
526 .event
518 "{mailto}?subject={}",
527 .subject
519 percent_encode_query(&self.event.subject)
528 .replace('%', "%25")
520 );
529 .replace(' ', "%20")
530 .replace('&', "%26")
531 .replace('?', "%3F")
532 .replace('#', "%23");
533 mailto = format!("{mailto}?subject={subject}");
534 }
521 }
535 buttons.push(
522 buttons.push(
536 Button::new("calendar-peek-email-guests")
523 Button::new("calendar-peek-email-guests")
@@ -962,6 +949,21 @@ fn group_label(group: ResponseType) -> String {
962 }
949 }
963}
950}
964
951
952/// Percent-encode a mailto `subject` query value (UTF-8, RFC 3986).
953fn percent_encode_query(value: &str) -> String {
954 let mut out = String::with_capacity(value.len() * 3);
955 for byte in value.as_bytes() {
956 match *byte {
957 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
958 out.push(*byte as char);
959 }
960 b' ' => out.push_str("%20"),
961 _ => out.push_str(&format!("%{byte:02X}")),
962 }
963 }
964 out
965}
966
965fn is_teams_url(url: &str) -> bool {
967fn is_teams_url(url: &str) -> bool {
966 url.contains("teams.microsoft.com")
968 url.contains("teams.microsoft.com")
967}
969}
crates/chatsvc/src/calendar.rs +87 −1
@@ -428,10 +428,53 @@ fn body_html_text(entry: &Value) -> Option<String> {
428 428 .replace('<', "&lt;")
429 429 .replace('>', "&gt;")
430 430 .replace("\r\n", "\n")
431 .replace('\r', "\n")
431 432 .replace('\n', "<br>");
432 433 return Some(escaped);
433 434 }
434 Some(content)
435 // Drop non-http(s)/mailto hrefs so the agenda renderer cannot open them.
436 Some(sanitize_html_hrefs(&content))
437 }
438
439 fn sanitize_html_hrefs(html: &str) -> String {
440 let mut out = String::with_capacity(html.len());
441 let mut rest = html;
442 while let Some(start) = rest.find("href=") {
443 out.push_str(&rest[..start]);
444 rest = &rest[start..];
445 let quote = rest.as_bytes().get(5).copied();
446 let (quote_char, after_quote) = match quote {
447 Some(b'"') | Some(b'\'') => (quote.unwrap() as char, &rest[6..]),
448 _ => {
449 out.push_str("href=");
450 rest = &rest[5..];
451 continue;
452 }
453 };
454 let Some(end) = after_quote.find(quote_char) else {
455 out.push_str(rest);
456 return out;
457 };
458 let url = &after_quote[..end];
459 let safe = url_is_safe_href(url);
460 out.push_str("href=");
461 out.push(quote_char);
462 if safe {
463 out.push_str(url);
464 }
465 out.push(quote_char);
466 rest = &after_quote[end + 1..];
467 }
468 out.push_str(rest);
469 out
470 }
471
472 fn url_is_safe_href(url: &str) -> bool {
473 let trimmed = url.trim();
474 let lower = trimmed.to_ascii_lowercase();
475 lower.starts_with("https://")
476 || lower.starts_with("http://")
477 || lower.starts_with("mailto:")
435 478 }
436 479
437 480 fn attendee_response(label: &str) -> ResponseType {
@@ -842,6 +885,49 @@ mod tests {
842 885 );
843 886 }
844 887
888 #[test]
889 fn text_body_normalizes_lone_carriage_returns() {
890 let mut event = CalendarEvent {
891 object_id: "cr".into(),
892 start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(),
893 end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(),
894 ..Default::default()
895 };
896 apply_event_details(
897 &mut event,
898 &serde_json::json!({
899 "body": {"contentType": "text", "content": "Line1\rLine2\r\nLine3"}
900 }),
901 );
902 assert_eq!(
903 event.body_html.as_deref(),
904 Some("Line1<br>Line2<br>Line3")
905 );
906 }
907
908 #[test]
909 fn html_body_drops_javascript_hrefs() {
910 let mut event = CalendarEvent {
911 object_id: "js".into(),
912 start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(),
913 end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(),
914 ..Default::default()
915 };
916 apply_event_details(
917 &mut event,
918 &serde_json::json!({
919 "body": {
920 "contentType": "html",
921 "content": r#"<p><a href="javascript:alert(1)">x</a> <a href='https://ok.example'>y</a></p>"#
922 }
923 }),
924 );
925 let html = event.body_html.as_deref().expect("html");
926 assert!(!html.to_ascii_lowercase().contains("javascript:"));
927 assert!(html.contains(r#"href="""#) || html.contains("href=''"));
928 assert!(html.contains(r#"href='https://ok.example'"#));
929 }
930
845 931 #[test]
846 932 fn apply_event_details_uses_body_content_when_preview_missing() {
847 933 let mut event = CalendarEvent {
@@ -428,10 +428,53 @@ fn body_html_text(entry: &Value) -> Option<String> {
428 .replace('<', "&lt;")
428 .replace('<', "&lt;")
429 .replace('>', "&gt;")
429 .replace('>', "&gt;")
430 .replace("\r\n", "\n")
430 .replace("\r\n", "\n")
431 .replace('\r', "\n")
431 .replace('\n', "<br>");
432 .replace('\n', "<br>");
432 return Some(escaped);
433 return Some(escaped);
433 }
434 }
434 Some(content)
435 // Drop non-http(s)/mailto hrefs so the agenda renderer cannot open them.
436 Some(sanitize_html_hrefs(&content))
437}
438
439fn sanitize_html_hrefs(html: &str) -> String {
440 let mut out = String::with_capacity(html.len());
441 let mut rest = html;
442 while let Some(start) = rest.find("href=") {
443 out.push_str(&rest[..start]);
444 rest = &rest[start..];
445 let quote = rest.as_bytes().get(5).copied();
446 let (quote_char, after_quote) = match quote {
447 Some(b'"') | Some(b'\'') => (quote.unwrap() as char, &rest[6..]),
448 _ => {
449 out.push_str("href=");
450 rest = &rest[5..];
451 continue;
452 }
453 };
454 let Some(end) = after_quote.find(quote_char) else {
455 out.push_str(rest);
456 return out;
457 };
458 let url = &after_quote[..end];
459 let safe = url_is_safe_href(url);
460 out.push_str("href=");
461 out.push(quote_char);
462 if safe {
463 out.push_str(url);
464 }
465 out.push(quote_char);
466 rest = &after_quote[end + 1..];
467 }
468 out.push_str(rest);
469 out
470}
471
472fn url_is_safe_href(url: &str) -> bool {
473 let trimmed = url.trim();
474 let lower = trimmed.to_ascii_lowercase();
475 lower.starts_with("https://")
476 || lower.starts_with("http://")
477 || lower.starts_with("mailto:")
435}
478}
436
479
437fn attendee_response(label: &str) -> ResponseType {
480fn attendee_response(label: &str) -> ResponseType {
@@ -842,6 +885,49 @@ mod tests {
842 );
885 );
843 }
886 }
844
887
888 #[test]
889 fn text_body_normalizes_lone_carriage_returns() {
890 let mut event = CalendarEvent {
891 object_id: "cr".into(),
892 start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(),
893 end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(),
894 ..Default::default()
895 };
896 apply_event_details(
897 &mut event,
898 &serde_json::json!({
899 "body": {"contentType": "text", "content": "Line1\rLine2\r\nLine3"}
900 }),
901 );
902 assert_eq!(
903 event.body_html.as_deref(),
904 Some("Line1<br>Line2<br>Line3")
905 );
906 }
907
908 #[test]
909 fn html_body_drops_javascript_hrefs() {
910 let mut event = CalendarEvent {
911 object_id: "js".into(),
912 start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(),
913 end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(),
914 ..Default::default()
915 };
916 apply_event_details(
917 &mut event,
918 &serde_json::json!({
919 "body": {
920 "contentType": "html",
921 "content": r#"<p><a href="javascript:alert(1)">x</a> <a href='https://ok.example'>y</a></p>"#
922 }
923 }),
924 );
925 let html = event.body_html.as_deref().expect("html");
926 assert!(!html.to_ascii_lowercase().contains("javascript:"));
927 assert!(html.contains(r#"href="""#) || html.contains("href=''"));
928 assert!(html.contains(r#"href='https://ok.example'"#));
929 }
930
845 #[test]
931 #[test]
846 fn apply_event_details_uses_body_content_when_preview_missing() {
932 fn apply_event_details_uses_body_content_when_preview_missing() {
847 let mut event = CalendarEvent {
933 let mut event = CalendarEvent {
crates/chatsvc/src/google_calendar/parse.rs +33 −16
@@ -122,13 +122,16 @@ fn parse_event(
122 122 })
123 123 }
124 124
125 /// Plain Google descriptions become escaped HTML with links and line breaks.
126 /// Descriptions that already look like HTML are kept as-is.
125 /// Google descriptions become escaped HTML with http(s) links and line breaks.
126 /// Existing markup is flattened first so untrusted schemes (e.g. `javascript:`)
127 /// cannot become clickable `href`s through the message HTML pipeline.
127 128 pub fn description_html(text: &str) -> String {
128 if looks_like_html(text) {
129 return text.to_owned();
130 }
131 let escaped = text
129 let plain = if looks_like_html(text) {
130 strip_html(text)
131 } else {
132 text.to_owned()
133 };
134 let escaped = plain
132 135 .replace('&', "&amp;")
133 136 .replace('<', "&lt;")
134 137 .replace('>', "&gt;");
@@ -141,15 +144,17 @@ pub fn description_html(text: &str) -> String {
141 144
142 145 fn looks_like_html(text: &str) -> bool {
143 146 let lower = text.to_ascii_lowercase();
144 lower.contains("<br")
145 || lower.contains("<p")
146 || lower.contains("<div")
147 || lower.contains("<a ")
148 || lower.contains("<b>")
149 || lower.contains("<i>")
150 || lower.contains("<ul")
151 || lower.contains("<ol")
152 || lower.contains("<li")
147 lower.contains('<')
148 && (lower.contains("<br")
149 || lower.contains("<p")
150 || lower.contains("<div")
151 || lower.contains("<a ")
152 || lower.contains("<b>")
153 || lower.contains("<i>")
154 || lower.contains("<ul")
155 || lower.contains("<ol")
156 || lower.contains("<li")
157 || lower.contains("<span"))
153 158 }
154 159
155 160 fn linkify_escaped(text: &str) -> String {
@@ -424,10 +429,22 @@ mod tests {
424 429 );
425 430 assert_eq!(
426 431 events[0].body_html.as_deref(),
427 Some("<b>Agenda</b><br> Item&nbsp;1 &amp; notes")
432 Some("Agenda Item 1 &amp; notes")
428 433 );
429 434 }
430 435
436 #[test]
437 fn html_description_strips_javascript_hrefs() {
438 let html = description_html(
439 r#"Click <a href="javascript:alert(1)">here</a> or https://safe.example/x"#,
440 );
441 assert!(!html.to_ascii_lowercase().contains("javascript:"));
442 assert!(html.contains(
443 r#"<a href="https://safe.example/x">https://safe.example/x</a>"#
444 ));
445 assert!(html.contains("Click here or"));
446 }
447
431 448 #[test]
432 449 fn plain_description_keeps_breaks_and_links() {
433 450 let html = description_html(
@@ -122,13 +122,16 @@ fn parse_event(
122 })
122 })
123}
123}
124
124
125/// Plain Google descriptions become escaped HTML with links and line breaks.
125/// Google descriptions become escaped HTML with http(s) links and line breaks.
126/// Descriptions that already look like HTML are kept as-is.
126/// Existing markup is flattened first so untrusted schemes (e.g. `javascript:`)
127/// cannot become clickable `href`s through the message HTML pipeline.
127pub fn description_html(text: &str) -> String {
128pub fn description_html(text: &str) -> String {
128 if looks_like_html(text) {
129 let plain = if looks_like_html(text) {
129 return text.to_owned();
130 strip_html(text)
130 }
131 } else {
131 let escaped = text
132 text.to_owned()
133 };
134 let escaped = plain
132 .replace('&', "&amp;")
135 .replace('&', "&amp;")
133 .replace('<', "&lt;")
136 .replace('<', "&lt;")
134 .replace('>', "&gt;");
137 .replace('>', "&gt;");
@@ -141,15 +144,17 @@ pub fn description_html(text: &str) -> String {
141
144
142fn looks_like_html(text: &str) -> bool {
145fn looks_like_html(text: &str) -> bool {
143 let lower = text.to_ascii_lowercase();
146 let lower = text.to_ascii_lowercase();
144 lower.contains("<br")
147 lower.contains('<')
145 || lower.contains("<p")
148 && (lower.contains("<br")
146 || lower.contains("<div")
149 || lower.contains("<p")
147 || lower.contains("<a ")
150 || lower.contains("<div")
148 || lower.contains("<b>")
151 || lower.contains("<a ")
149 || lower.contains("<i>")
152 || lower.contains("<b>")
150 || lower.contains("<ul")
153 || lower.contains("<i>")
151 || lower.contains("<ol")
154 || lower.contains("<ul")
152 || lower.contains("<li")
155 || lower.contains("<ol")
156 || lower.contains("<li")
157 || lower.contains("<span"))
153}
158}
154
159
155fn linkify_escaped(text: &str) -> String {
160fn linkify_escaped(text: &str) -> String {
@@ -424,10 +429,22 @@ mod tests {
424 );
429 );
425 assert_eq!(
430 assert_eq!(
426 events[0].body_html.as_deref(),
431 events[0].body_html.as_deref(),
427 Some("<b>Agenda</b><br> Item&nbsp;1 &amp; notes")
432 Some("Agenda Item 1 &amp; notes")
428 );
433 );
429 }
434 }
430
435
436 #[test]
437 fn html_description_strips_javascript_hrefs() {
438 let html = description_html(
439 r#"Click <a href="javascript:alert(1)">here</a> or https://safe.example/x"#,
440 );
441 assert!(!html.to_ascii_lowercase().contains("javascript:"));
442 assert!(html.contains(
443 r#"<a href="https://safe.example/x">https://safe.example/x</a>"#
444 ));
445 assert!(html.contains("Click here or"));
446 }
447
431 #[test]
448 #[test]
432 fn plain_description_keeps_breaks_and_links() {
449 fn plain_description_keeps_breaks_and_links() {
433 let html = description_html(
450 let html = description_html(