1use std::{
4 ffi::OsString,
5 fs,
6 io::Write,
7 path::{Path, PathBuf},
8};
9
10use crate::{RenderedDocument, ViewError};
11
12pub const STATIC_OUTPUT_DIR_ENV: &str = "SERENADE_STATIC_OUTPUT_DIR";
14
15#[derive(Clone, Debug, Eq, PartialEq)]
21pub struct StaticDocumentWriter {
22 output_directory: PathBuf,
23}
24
25impl StaticDocumentWriter {
26 #[must_use]
28 pub fn new(output_directory: impl Into<PathBuf>) -> Self {
29 Self {
30 output_directory: output_directory.into(),
31 }
32 }
33
34 pub fn from_env() -> Result<Self, ViewError> {
40 Self::from_environment(std::env::var_os(STATIC_OUTPUT_DIR_ENV))
41 }
42
43 fn from_environment(output_directory: Option<OsString>) -> Result<Self, ViewError> {
44 let output_directory = output_directory
45 .filter(|directory| !directory.is_empty())
46 .ok_or_else(|| {
47 ViewError::msg(format!(
48 "environment variable {STATIC_OUTPUT_DIR_ENV} is not set"
49 ))
50 })?;
51 Ok(Self::new(output_directory))
52 }
53
54 pub fn output_path(&self, route: &str) -> Result<PathBuf, ViewError> {
64 Ok(self.index_path(&route_segments(route)?))
65 }
66
67 pub fn write(&self, route: &str, document: RenderedDocument) -> Result<PathBuf, ViewError> {
82 let segments = route_segments(route)?;
83 let output_path = self.index_path(&segments);
84 let mut directory = fs::create_dir_all(&self.output_directory)
85 .and_then(|()| self.output_directory.canonicalize())
86 .map_err(|error| directory_error(&self.output_directory, &error))?;
87 for segment in segments {
88 directory.push(segment);
89 create_real_directory(&directory)?;
90 }
91 replace_file(&directory, document.into_static_output().as_bytes()).map_err(|error| {
92 ViewError::msg(format!(
93 "failed to write static document {}: {error}",
94 output_path.display()
95 ))
96 })?;
97 Ok(output_path)
98 }
99}
100
101impl StaticDocumentWriter {
102 fn index_path(&self, segments: &[&str]) -> PathBuf {
103 let mut output_path = self.output_directory.clone();
104 output_path.extend(segments);
105 output_path.push(INDEX_FILE);
106 output_path
107 }
108}
109
110const INDEX_FILE: &str = "index.html";
111
112fn route_segments(route: &str) -> Result<Vec<&str>, ViewError> {
113 if !route.starts_with('/') || route.contains(['?', '#', '\\']) || route.contains("//") {
114 return Err(ViewError::msg(format!(
115 "static output route must be a normalized absolute path: `{route}`"
116 )));
117 }
118 let relative = route.trim_start_matches('/');
119 let relative = relative.strip_suffix('/').unwrap_or(relative);
120 if relative.is_empty() {
121 return Ok(Vec::new());
122 }
123 relative
124 .split('/')
125 .map(|segment| {
126 let decoded_dots = segment.to_ascii_lowercase().replace("%2e", ".");
127 if segment.is_empty()
128 || matches!(decoded_dots.as_str(), "." | "..")
129 || decoded_dots.contains("%2f")
130 || decoded_dots.contains("%5c")
131 || segment.contains(':')
132 || segment.chars().any(char::is_control)
133 {
134 Err(ViewError::msg(format!(
135 "unsafe static output route segment in `{route}`"
136 )))
137 } else {
138 Ok(segment)
139 }
140 })
141 .collect()
142}
143
144fn create_real_directory(path: &Path) -> Result<(), ViewError> {
148 match fs::create_dir(path) {
149 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
150 match fs::symlink_metadata(path) {
151 Ok(metadata) if metadata.file_type().is_symlink() => Err(ViewError::msg(format!(
152 "static output directory {} is a symbolic link; refusing to write through it",
153 path.display()
154 ))),
155 Ok(metadata) if metadata.is_dir() => Ok(()),
156 _ => Err(directory_error(
157 path,
158 &std::io::Error::other("not a directory"),
159 )),
160 }
161 }
162 result => result.map_err(|error| directory_error(path, &error)),
163 }
164}
165
166fn directory_error(path: &Path, error: &std::io::Error) -> ViewError {
167 ViewError::msg(format!(
168 "failed to create static output directory {}: {error}",
169 path.display()
170 ))
171}
172
173fn replace_file(directory: &Path, contents: &[u8]) -> std::io::Result<()> {
179 let destination = directory.join(INDEX_FILE);
180 tempfile::Builder::new()
181 .prefix(".index.html.")
182 .suffix(".serenade-tmp")
183 .tempfile_in(directory)
184 .and_then(|mut file| file.write_all(contents).map(|()| file))
185 .and_then(|file| {
186 file.persist(&destination)
187 .map(drop)
188 .or_else(|error| retry_replacement(error, &destination))
189 })
190}
191
192#[cfg(windows)]
197#[allow(clippy::permissions_set_readonly_false)]
199fn retry_replacement(error: tempfile::PersistError, destination: &Path) -> std::io::Result<()> {
200 let tempfile::PersistError { error, file } = error;
201 match fs::symlink_metadata(destination) {
202 Ok(metadata) if metadata.is_file() && metadata.permissions().readonly() => {
203 let mut permissions = metadata.permissions();
204 permissions.set_readonly(false);
205 fs::set_permissions(destination, permissions)?;
206 file.persist(destination)
207 .map(drop)
208 .map_err(|error| error.error)
209 }
210 _ => Err(error),
211 }
212}
213
214#[cfg(not(windows))]
216fn retry_replacement(error: tempfile::PersistError, _destination: &Path) -> std::io::Result<()> {
217 Err(error.error)
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223 use crate::{Document, DocumentParts, DocumentTemplate};
224
225 struct TestTemplate;
226
227 impl DocumentTemplate<&'static str, &'static str> for TestTemplate {
228 fn render(
229 self,
230 parts: DocumentParts<&'static str, &'static str>,
231 ) -> Result<String, ViewError> {
232 Ok(format!(
233 "<!doctype html><html><head>{}</head><body>{}</body></html>",
234 parts.head, parts.body
235 ))
236 }
237 }
238
239 fn document() -> RenderedDocument {
240 Document::new("<title>About</title>", "<main>About page</main>")
241 .render_with(TestTemplate)
242 .expect("render document")
243 }
244
245 #[test]
246 fn maps_routes_to_static_index_documents() {
247 let temp = tempfile::tempdir().expect("temporary directory");
248 let writer = StaticDocumentWriter::new(temp.path());
249
250 assert_eq!(
251 writer.output_path("/").expect("root route"),
252 temp.path().join("index.html")
253 );
254 assert_eq!(
255 writer.output_path("/about").expect("about route"),
256 temp.path().join("about/index.html")
257 );
258 assert_eq!(
259 writer.output_path("/about/").expect("trailing slash route"),
260 temp.path().join("about/index.html")
261 );
262 }
263
264 #[test]
265 fn reads_output_directory_from_environment_value() {
266 assert_eq!(
267 StaticDocumentWriter::from_environment(Some(OsString::from("dist")))
268 .expect("configured output directory"),
269 StaticDocumentWriter::new("dist")
270 );
271 assert!(StaticDocumentWriter::from_environment(None).is_err());
272 assert!(StaticDocumentWriter::from_environment(Some(OsString::new())).is_err());
273
274 let _from_env = StaticDocumentWriter::from_env();
275 }
276
277 #[test]
278 fn writes_complete_documents_and_creates_route_directories() {
279 let temp = tempfile::tempdir().expect("temporary directory");
280 let writer = StaticDocumentWriter::new(temp.path());
281 let output_path = writer.write("/about/", document()).expect("write document");
282
283 assert_eq!(output_path, temp.path().join("about/index.html"));
284 assert_eq!(
285 fs::read_to_string(output_path).expect("read output"),
286 "<!doctype html><html><head><title>About</title></head><body><main>About page</main></body></html>"
287 );
288 }
289
290 #[test]
291 fn reports_static_output_filesystem_errors() {
292 let temp = tempfile::tempdir().expect("temporary directory");
293 let blocked_directory = temp.path().join("blocked");
294 fs::write(&blocked_directory, "not a directory").expect("create blocking file");
295 let error = StaticDocumentWriter::new(blocked_directory)
296 .write("/about", document())
297 .expect_err("creating a route directory beneath a file must fail")
298 .to_string();
299 assert!(error.contains("failed to create static output directory"));
300
301 let temp = tempfile::tempdir().expect("temporary directory");
302 fs::create_dir_all(temp.path().join("about/index.html"))
303 .expect("create directory at document file path");
304 let error = StaticDocumentWriter::new(temp.path())
305 .write("/about", document())
306 .expect_err("writing over a directory must fail")
307 .to_string();
308 assert!(error.contains("failed to write static document"));
309 }
310
311 #[test]
312 fn rejects_route_entries_that_are_files_and_unsafe_routes() {
313 let temp = tempfile::tempdir().expect("temporary directory");
314 fs::write(temp.path().join("about"), "not a directory").expect("blocking file");
315 let writer = StaticDocumentWriter::new(temp.path());
316 let error = writer
317 .write("/about/team", document())
318 .expect_err("a file where a route directory belongs must fail")
319 .to_string();
320 assert!(error.contains("failed to create static output directory"));
321 assert!(error.contains("not a directory"));
322 assert!(writer.write("/../secret", document()).is_err());
323
324 let too_long = format!("/{}", "a".repeat(4096));
325 let error = writer
326 .write(&too_long, document())
327 .expect_err("an uncreatable route directory must fail")
328 .to_string();
329 assert!(error.contains("failed to create static output directory"));
330 }
331
332 fn entries(directory: &Path) -> Vec<String> {
333 let mut names: Vec<String> = fs::read_dir(directory)
334 .expect("read directory")
335 .map(|entry| {
336 entry
337 .expect("entry")
338 .file_name()
339 .to_string_lossy()
340 .into_owned()
341 })
342 .collect();
343 names.sort();
344 names
345 }
346
347 #[test]
348 fn rewrites_existing_documents_without_leaving_temporary_files() {
349 let temp = tempfile::tempdir().expect("temporary directory");
350 let writer = StaticDocumentWriter::new(temp.path());
351 fs::write(temp.path().join(INDEX_FILE), "old").expect("existing document");
352 writer
353 .write("/", document())
354 .expect("rewrite root document");
355 assert!(
356 fs::read_to_string(temp.path().join(INDEX_FILE))
357 .expect("read output")
358 .contains("About page")
359 );
360 assert_eq!(entries(temp.path()), [INDEX_FILE]);
361 }
362
363 #[test]
364 fn rerun_replaces_a_read_only_existing_document() {
365 let temp = tempfile::tempdir().expect("temporary directory");
366 let existing = temp.path().join(INDEX_FILE);
367 fs::write(&existing, "old").expect("existing document");
368 let mut permissions = fs::metadata(&existing).expect("metadata").permissions();
369 permissions.set_readonly(true);
370 fs::set_permissions(&existing, permissions).expect("mark read-only");
371 StaticDocumentWriter::new(temp.path())
372 .write("/", document())
373 .expect("rerun over a read-only document");
374 assert!(
375 fs::read_to_string(&existing)
376 .expect("read output")
377 .contains("About page")
378 );
379 assert_eq!(entries(temp.path()), [INDEX_FILE]);
380 }
381
382 #[test]
383 fn concurrent_writes_of_the_same_route_all_succeed() {
384 let temp = tempfile::tempdir().expect("temporary directory");
385 let writer = StaticDocumentWriter::new(temp.path());
386 std::thread::scope(|scope| {
387 for _ in 0..8 {
388 scope.spawn(|| {
389 for _ in 0..25 {
390 writer
391 .write("/docs/guide/", document())
392 .expect("concurrent write");
393 }
394 });
395 }
396 });
397 let route = temp.path().join("docs/guide");
398 assert_eq!(entries(&route), [INDEX_FILE]);
399 assert!(
400 fs::read_to_string(route.join(INDEX_FILE))
401 .expect("read output")
402 .contains("About page")
403 );
404 }
405
406 #[test]
407 #[cfg(unix)]
408 fn never_writes_through_symbolic_links_out_of_the_output_directory() {
409 use std::os::unix::fs::symlink;
410
411 let outside = tempfile::tempdir().expect("outside directory");
412 let temp = tempfile::tempdir().expect("temporary directory");
413 let writer = StaticDocumentWriter::new(temp.path());
414
415 symlink(outside.path(), temp.path().join("about")).expect("directory symlink");
416 let error = writer
417 .write("/about/team", document())
418 .expect_err("symlinked route directory must be rejected")
419 .to_string();
420 assert!(error.contains("is a symbolic link"));
421 assert!(!outside.path().join("team").exists());
422
423 let victim = outside.path().join("victim.html");
424 fs::write(&victim, "untouched").expect("outside file");
425 symlink(&victim, temp.path().join(INDEX_FILE)).expect("file symlink");
426 writer
427 .write("/", document())
428 .expect("replace symlinked document");
429 assert_eq!(fs::read_to_string(&victim).expect("victim"), "untouched");
430 let written = temp.path().join(INDEX_FILE);
431 assert!(
432 !fs::symlink_metadata(&written)
433 .expect("metadata")
434 .file_type()
435 .is_symlink()
436 );
437 assert!(
438 fs::read_to_string(written)
439 .expect("output")
440 .contains("About page")
441 );
442
443 let linked_root = outside.path().join("linked-output");
444 symlink(temp.path(), &linked_root).expect("output directory symlink");
445 StaticDocumentWriter::new(&linked_root)
446 .write("/", document())
447 .expect("a symlinked output directory itself is the configured root");
448 }
449
450 #[test]
451 fn rejects_non_normalized_and_unsafe_routes() {
452 let writer = StaticDocumentWriter::new("dist");
453 for route in [
454 "about",
455 "/about?tab=details",
456 "/about#details",
457 "/about//team",
458 "/../secret",
459 "/about/%2e%2e/secret",
460 "/about/%2Fsecret",
461 "/about\\secret",
462 "/C:/secret",
463 ] {
464 assert!(
465 writer.output_path(route).is_err(),
466 "route should be rejected: {route}"
467 );
468 }
469 }
470}