Skip to main content

blitz_script/
fetch.rs

1//! Synchronous fetching of external script sources (`<script src="...">`)
2
3use std::fmt;
4use std::io::Read;
5use std::path::PathBuf;
6
7use url::Url;
8
9pub(crate) const MAX_SCRIPT_BYTES: usize = 16 * 1024 * 1024;
10
11#[derive(Debug)]
12pub enum FetchError {
13    UnsupportedScheme(String),
14    Io(std::io::Error),
15    InvalidData(String),
16}
17
18impl fmt::Display for FetchError {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::UnsupportedScheme(scheme) => {
22                write!(f, "unsupported URL scheme for script: {scheme}")
23            }
24            Self::Io(error) => write!(f, "IO error fetching script: {error}"),
25            Self::InvalidData(msg) => write!(f, "invalid script data: {msg}"),
26        }
27    }
28}
29
30impl std::error::Error for FetchError {}
31
32/// Trait for synchronously fetching external script sources.
33///
34/// Scripts are fetched synchronously because the HTML spec requires classic
35/// scripts to execute in document order, blocking parsing. Implementations
36/// should provide [`Self::fetch`]. The default [`Self::fetch_for_document`]
37/// applies file-URL authorization and the source-size limit before returning
38/// source text. An override of `fetch_for_document` is responsible for
39/// preserving those checks (and any additional policy required by its host).
40pub trait ScriptFetcher: 'static {
41    fn fetch(&self, url: &Url) -> Result<String, FetchError>;
42
43    fn fetch_for_document(
44        &self,
45        url: &Url,
46        document_url: Option<&Url>,
47    ) -> Result<String, FetchError> {
48        // Keep policy checks at the boundary used by document script loading;
49        // custom implementations overriding this method must preserve them.
50        authorize_script_url(url, document_url)?;
51        let source = self.fetch(url)?;
52        if source.len() > MAX_SCRIPT_BYTES {
53            return Err(FetchError::InvalidData(format!(
54                "script source exceeds {MAX_SCRIPT_BYTES} bytes"
55            )));
56        }
57        Ok(source)
58    }
59}
60
61/// The default [`ScriptFetcher`]: supports `file:` and `data:` URLs.
62pub struct DefaultScriptFetcher;
63
64impl ScriptFetcher for DefaultScriptFetcher {
65    fn fetch(&self, url: &Url) -> Result<String, FetchError> {
66        match url.scheme() {
67            "file" => Err(FetchError::InvalidData(
68                "file script fetch requires document authority".to_string(),
69            )),
70            "data" => decode_data_url(url),
71            scheme => Err(FetchError::UnsupportedScheme(scheme.to_string())),
72        }
73    }
74
75    fn fetch_for_document(
76        &self,
77        url: &Url,
78        document_url: Option<&Url>,
79    ) -> Result<String, FetchError> {
80        if url.scheme() == "file" {
81            let path = authorized_file_path(url, document_url)?;
82            read_script_file(path)
83        } else {
84            self.fetch(url)
85        }
86    }
87}
88
89pub(crate) fn authorize_script_url(
90    url: &Url,
91    document_url: Option<&Url>,
92) -> Result<(), FetchError> {
93    if url.scheme() != "file" {
94        return Ok(());
95    }
96    authorized_file_path(url, document_url).map(|_| ())
97}
98
99fn file_url_path(url: &Url) -> Result<PathBuf, FetchError> {
100    if url.host_str().is_some_and(|host| host != "localhost") {
101        return Err(FetchError::InvalidData(format!(
102            "unsupported authority in file URL: {url}"
103        )));
104    }
105    url.to_file_path()
106        .map_err(|_| FetchError::InvalidData(format!("invalid file URL: {url}")))
107}
108
109fn require_regular_file(path: &std::path::Path, role: &str) -> Result<(), FetchError> {
110    let metadata = std::fs::metadata(path).map_err(FetchError::Io)?;
111    if !metadata.is_file() {
112        return Err(FetchError::InvalidData(format!(
113            "{role} is not a regular file"
114        )));
115    }
116    Ok(())
117}
118
119fn authorized_file_path(url: &Url, document_url: Option<&Url>) -> Result<PathBuf, FetchError> {
120    let document_url = document_url.ok_or_else(|| {
121        FetchError::InvalidData("file script access requires a file document URL".to_string())
122    })?;
123    if document_url.scheme() != "file" {
124        return Err(FetchError::InvalidData(
125            "file script access requires a file document URL".to_string(),
126        ));
127    }
128
129    let document_path = file_url_path(document_url)?;
130    let requested_path = file_url_path(url)?;
131    let canonical_document = std::fs::canonicalize(document_path).map_err(FetchError::Io)?;
132    require_regular_file(&canonical_document, "document")?;
133    let root = canonical_document.parent().ok_or_else(|| {
134        FetchError::InvalidData("document file has no parent directory".to_string())
135    })?;
136
137    let canonical_requested = std::fs::canonicalize(requested_path).map_err(FetchError::Io)?;
138    if !canonical_requested.starts_with(root) {
139        return Err(FetchError::InvalidData(format!(
140            "script file is outside the document directory: {url}"
141        )));
142    }
143    require_regular_file(&canonical_requested, "script")?;
144    Ok(canonical_requested)
145}
146
147fn read_script_file(path: PathBuf) -> Result<String, FetchError> {
148    let before_open = std::fs::metadata(&path).map_err(FetchError::Io)?;
149    if !before_open.is_file() {
150        return Err(FetchError::InvalidData(
151            "script is not a regular file".to_string(),
152        ));
153    }
154    if before_open.len() > MAX_SCRIPT_BYTES as u64 {
155        return Err(FetchError::InvalidData(format!(
156            "script source exceeds {MAX_SCRIPT_BYTES} bytes"
157        )));
158    }
159
160    let file = std::fs::File::open(path).map_err(FetchError::Io)?;
161    let opened_metadata = file.metadata().map_err(FetchError::Io)?;
162    if !opened_metadata.is_file() {
163        return Err(FetchError::InvalidData(
164            "script is not a regular file".to_string(),
165        ));
166    }
167    if opened_metadata.len() > MAX_SCRIPT_BYTES as u64 {
168        return Err(FetchError::InvalidData(format!(
169            "script source exceeds {MAX_SCRIPT_BYTES} bytes"
170        )));
171    }
172
173    let mut bytes = Vec::new();
174    file.take(MAX_SCRIPT_BYTES as u64 + 1)
175        .read_to_end(&mut bytes)
176        .map_err(FetchError::Io)?;
177    if bytes.len() > MAX_SCRIPT_BYTES {
178        return Err(FetchError::InvalidData(format!(
179            "script source exceeds {MAX_SCRIPT_BYTES} bytes"
180        )));
181    }
182    String::from_utf8(bytes).map_err(|error| FetchError::InvalidData(format!("{error:?}")))
183}
184
185fn decode_data_url(url: &Url) -> Result<String, FetchError> {
186    let data_url = data_url::DataUrl::process(url.as_str())
187        .map_err(|error| FetchError::InvalidData(format!("{error:?}")))?;
188    let mut bytes = Vec::new();
189    data_url
190        .decode(|chunk| {
191            if chunk.len() > MAX_SCRIPT_BYTES.saturating_sub(bytes.len()) {
192                return Err(FetchError::InvalidData(format!(
193                    "script source exceeds {MAX_SCRIPT_BYTES} bytes"
194                )));
195            }
196            bytes.extend_from_slice(chunk);
197            Ok::<(), FetchError>(())
198        })
199        .map_err(|error| match error {
200            data_url::forgiving_base64::DecodeError::WriteError(error) => error,
201            data_url::forgiving_base64::DecodeError::InvalidBase64(error) => {
202                FetchError::InvalidData(format!("{error:?}"))
203            }
204        })?;
205    String::from_utf8(bytes).map_err(|error| FetchError::InvalidData(format!("{error:?}")))
206}