Skip to main content

sui_core/
url_opener.rs

1use std::{cell::RefCell, fmt, rc::Rc};
2
3/// Driver behind a [`UrlOpener`] handle that hands a URL to the platform.
4///
5/// The default [`LocalUrlOpenerBackend`] opens nothing, so links stay inert
6/// in tests and headless runs. Platforms install a native implementation at
7/// startup that opens the default browser, mail client, or whichever app the
8/// system registers for the URL's scheme.
9pub trait UrlOpenerBackend {
10    /// Hand `url` to the platform, returning whether a handler accepted it.
11    /// A handler can still fail after accepting it.
12    fn open(&mut self, url: &str) -> bool;
13}
14
15/// Records URLs instead of opening them; used when no platform backend is
16/// installed.
17///
18/// Clones share one record, so a test can install a clone and read back
19/// what widgets asked to open.
20#[derive(Debug, Default, Clone)]
21pub struct LocalUrlOpenerBackend {
22    opened: Rc<RefCell<Vec<String>>>,
23}
24
25impl LocalUrlOpenerBackend {
26    pub fn new() -> Self {
27        Self::default()
28    }
29
30    /// URLs handed to this backend, oldest first.
31    pub fn opened(&self) -> Vec<String> {
32        self.opened.borrow().clone()
33    }
34}
35
36impl UrlOpenerBackend for LocalUrlOpenerBackend {
37    fn open(&mut self, url: &str) -> bool {
38        self.opened.borrow_mut().push(url.to_string());
39        false
40    }
41}
42
43/// Decides which URLs a [`UrlOpener`] hands to the platform.
44///
45/// The default, [`UrlPolicy::allows_by_default`], lets through only absolute
46/// `http`, `https`, and `mailto` URLs without control characters, so links in
47/// untrusted content, such as Markdown from the network or a model, cannot
48/// launch local files, scripts, or arbitrary protocol handlers. An app that
49/// needs more registers its own check with [`UrlPolicy::new`], or turns the
50/// check off with [`UrlPolicy::allow_all`].
51#[derive(Clone)]
52pub struct UrlPolicy {
53    allows: Rc<dyn Fn(&str) -> bool>,
54}
55
56impl UrlPolicy {
57    /// A policy that lets through the URLs `allows` returns `true` for. Call
58    /// [`Self::allows_by_default`] from it to extend the default instead of
59    /// replacing it:
60    ///
61    /// ```ignore
62    /// let policy = UrlPolicy::new(|url| {
63    ///     url.starts_with("myapp:") || UrlPolicy::allows_by_default(url)
64    /// });
65    /// ```
66    pub fn new(allows: impl Fn(&str) -> bool + 'static) -> Self {
67        Self {
68            allows: Rc::new(allows),
69        }
70    }
71
72    /// A policy that lets every URL through. Use it only when the app trusts
73    /// every URL it opens.
74    pub fn allow_all() -> Self {
75        Self::new(|_| true)
76    }
77
78    /// Whether this policy lets `url` through.
79    pub fn allows(&self, url: &str) -> bool {
80        (self.allows)(url)
81    }
82
83    /// The default check: whether `url` is an absolute `http`, `https`, or
84    /// `mailto` URL without control characters. Relative URLs never pass.
85    pub fn allows_by_default(url: &str) -> bool {
86        !url.chars().any(char::is_control)
87            && url_scheme(url).is_some_and(|scheme| {
88                ["http", "https", "mailto"]
89                    .iter()
90                    .any(|allowed| allowed.eq_ignore_ascii_case(scheme))
91            })
92    }
93}
94
95impl Default for UrlPolicy {
96    fn default() -> Self {
97        Self::new(Self::allows_by_default)
98    }
99}
100
101impl fmt::Debug for UrlPolicy {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.debug_struct("UrlPolicy").finish_non_exhaustive()
104    }
105}
106
107/// The scheme of an absolute URL, or `None` for a relative one.
108fn url_scheme(url: &str) -> Option<&str> {
109    let (scheme, rest) = url.split_once(':')?;
110    let mut chars = scheme.chars();
111    let starts_with_letter = chars.next().is_some_and(|c| c.is_ascii_alphabetic());
112    let valid = starts_with_letter
113        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
114    (valid && !rest.is_empty()).then_some(scheme)
115}
116
117/// Shared handle to the URL-opening service.
118///
119/// The handle trims a URL and hands it to its backend only when its
120/// [`UrlPolicy`] allows it. Cloning is cheap and every clone refers to the
121/// same backend and policy, so a backend or policy installed through one
122/// handle applies to all of them.
123#[derive(Clone)]
124pub struct UrlOpener {
125    inner: Rc<RefCell<UrlOpenerState>>,
126}
127
128struct UrlOpenerState {
129    backend: Box<dyn UrlOpenerBackend>,
130    policy: UrlPolicy,
131}
132
133impl UrlOpener {
134    pub fn new() -> Self {
135        Self::with_backend(LocalUrlOpenerBackend::new())
136    }
137
138    pub fn with_backend(backend: impl UrlOpenerBackend + 'static) -> Self {
139        Self {
140            inner: Rc::new(RefCell::new(UrlOpenerState {
141                backend: Box::new(backend),
142                policy: UrlPolicy::default(),
143            })),
144        }
145    }
146
147    /// Replace the driver while keeping every existing handle valid.
148    pub fn set_backend(&self, backend: impl UrlOpenerBackend + 'static) {
149        self.inner.borrow_mut().backend = Box::new(backend);
150    }
151
152    pub fn policy(&self) -> UrlPolicy {
153        self.inner.borrow().policy.clone()
154    }
155
156    /// Decide which URLs open with `policy`; [`UrlPolicy::default`] restores
157    /// the default.
158    pub fn set_policy(&self, policy: UrlPolicy) {
159        self.inner.borrow_mut().policy = policy;
160    }
161
162    /// Whether [`Self::open`] would hand `url` to the backend.
163    pub fn allows(&self, url: &str) -> bool {
164        // The policy runs unborrowed, so it may use this opener itself.
165        self.policy().allows(url.trim())
166    }
167
168    /// Hand `url` to the platform when the policy allows it, returning
169    /// whether a handler accepted it.
170    pub fn open(&self, url: impl AsRef<str>) -> bool {
171        let url = url.as_ref().trim();
172        self.allows(url) && self.inner.borrow_mut().backend.open(url)
173    }
174}
175
176impl Default for UrlOpener {
177    fn default() -> Self {
178        Self::new()
179    }
180}
181
182impl fmt::Debug for UrlOpener {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        f.debug_struct("UrlOpener").finish_non_exhaustive()
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    struct AcceptingBackend(LocalUrlOpenerBackend);
193
194    impl UrlOpenerBackend for AcceptingBackend {
195        fn open(&mut self, url: &str) -> bool {
196            self.0.open(url);
197            true
198        }
199    }
200
201    #[test]
202    fn default_policy_allows_web_and_mail_links_only() {
203        let policy = UrlPolicy::default();
204        assert!(policy.allows("https://example.com/docs"));
205        assert!(policy.allows("HTTP://example.com"));
206        assert!(policy.allows("mailto:team@example.com"));
207
208        assert!(!policy.allows("file:///etc/passwd"));
209        assert!(!policy.allows("javascript:alert(1)"));
210        assert!(!policy.allows("ms-msdt:/id"));
211        assert!(!policy.allows("C:\\Windows\\notepad.exe"));
212        assert!(!policy.allows("/docs/intro"));
213        assert!(!policy.allows("docs/intro.md"));
214        assert!(!policy.allows("https:"));
215        assert!(!policy.allows("https://example.com/\nmalicious"));
216    }
217
218    #[test]
219    fn custom_policies_can_extend_or_turn_off_the_default() {
220        let extended =
221            UrlPolicy::new(|url| url.starts_with("myapp:") || UrlPolicy::allows_by_default(url));
222        assert!(extended.allows("myapp://settings"));
223        assert!(extended.allows("https://example.com"));
224        assert!(!extended.allows("file:///etc/passwd"));
225
226        let all = UrlPolicy::allow_all();
227        assert!(all.allows("file:///etc/passwd"));
228        assert!(all.allows("docs/intro.md"));
229    }
230
231    #[test]
232    fn opener_hands_only_allowed_trimmed_urls_to_its_backend() {
233        let record = LocalUrlOpenerBackend::new();
234        let opener = UrlOpener::with_backend(AcceptingBackend(record.clone()));
235
236        assert!(opener.open("  https://example.com  "));
237        assert!(!opener.open("file:///etc/passwd"));
238        assert_eq!(record.opened(), vec!["https://example.com".to_string()]);
239
240        opener.set_policy(UrlPolicy::allow_all());
241        assert!(opener.open("file:///etc/passwd"));
242        opener.set_policy(UrlPolicy::default());
243        assert!(!opener.open("file:///etc/passwd"));
244        assert_eq!(
245            record.opened(),
246            vec![
247                "https://example.com".to_string(),
248                "file:///etc/passwd".to_string()
249            ]
250        );
251    }
252
253    #[test]
254    fn local_backend_records_without_accepting() {
255        let record = LocalUrlOpenerBackend::new();
256        let opener = UrlOpener::new();
257        opener.set_backend(record.clone());
258
259        assert!(!opener.open("https://example.com"));
260        assert_eq!(record.opened(), vec!["https://example.com".to_string()]);
261    }
262
263    #[test]
264    fn clones_share_backend_and_policy() {
265        let record = LocalUrlOpenerBackend::new();
266        let opener = UrlOpener::new();
267        let clone = opener.clone();
268        clone.set_backend(record.clone());
269        clone.set_policy(UrlPolicy::new(|url| url.starts_with("myapp:")));
270
271        opener.open("myapp://settings");
272        opener.open("https://example.com");
273        assert_eq!(record.opened(), vec!["myapp://settings".to_string()]);
274    }
275
276    #[test]
277    fn a_policy_may_change_its_own_opener() {
278        let record = LocalUrlOpenerBackend::new();
279        let opener = UrlOpener::with_backend(record.clone());
280        let inner = opener.clone();
281        // Lets one URL through, then restores the default.
282        opener.set_policy(UrlPolicy::new(move |_| {
283            inner.set_policy(UrlPolicy::default());
284            true
285        }));
286        opener.open("file:///tmp/once");
287        opener.open("file:///tmp/twice");
288        assert_eq!(record.opened(), vec!["file:///tmp/once".to_string()]);
289    }
290}