Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement rewrite API #2789

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
101b245
Implement basic rewrite API
the10thWiz May 8, 2024
6b23b49
Fix issues, and clean up implementation
the10thWiz May 10, 2024
5f0164e
Format for style changes
the10thWiz May 10, 2024
86f148b
Make default rewrites public
the10thWiz May 14, 2024
bb47311
Clean up tests and remove unused member
the10thWiz May 18, 2024
13bbfb8
Minor cleanup and adding documentation
the10thWiz May 28, 2024
335e340
Fix doctest
the10thWiz May 28, 2024
7a6c355
Update error message
the10thWiz May 29, 2024
22ed995
Improve API and break backwards-compatibility
the10thWiz May 30, 2024
5b54e8a
Add map_uri function to Redirect
the10thWiz Jun 2, 2024
424aa38
Update Rewriter API based on discussion
the10thWiz Jun 2, 2024
e282abe
Add missing_root, and update docs to include panic
the10thWiz Jun 2, 2024
a37bdbb
Fix doctests
the10thWiz Jun 2, 2024
59e7801
Update tests to use new Rewrite API
the10thWiz Jun 2, 2024
42b799b
Fix test issue on Windows, adjust API
the10thWiz Jun 2, 2024
e8a8c39
Stop using `has_trailing_slash`
the10thWiz Jun 2, 2024
16e2a5a
Update to use tracing macros
the10thWiz Jun 9, 2024
9b23ec0
Update `to_path_buf` to ignore `.`s
the10thWiz Jun 11, 2024
b42dbaf
Update implementation
the10thWiz Jun 11, 2024
e094091
Convert to proper tracing structure
the10thWiz Jun 11, 2024
0c2bafe
Update naming and documentation
the10thWiz Jun 11, 2024
9ead65c
Fix line length
the10thWiz Jun 11, 2024
4d7f98b
Simplify standard rewrites type
the10thWiz Jun 11, 2024
c179f56
changes and improvements to rewrite PR
SergioBenitez Jun 30, 2024
3fbda80
streamline rewriters - use structs for consistency
SergioBenitez Jun 30, 2024
1cfcbf5
Update doc-tests and add small pieces of functionality
the10thWiz Jun 30, 2024
113b79c
Update examples and docs to use the new FileServer api
the10thWiz Jun 30, 2024
482a047
Updates based on PR review
the10thWiz Jul 1, 2024
fb8df12
Clean up docs. Rename 'FileServer::empty()'.
SergioBenitez Jul 6, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions core/http/src/uri/segments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,9 @@ impl<'a> Segments<'a, Path> {
}

/// Creates a `PathBuf` from `self`. The returned `PathBuf` is
/// percent-decoded. If a segment is equal to `..`, the previous segment (if
/// any) is skipped.
/// percent-decoded and guaranteed to be relative. If a segment is equal to
/// `.`, it is skipped. If a segment is equal to `..`, the previous segment
/// (if any) is skipped.
///
/// For security purposes, if a segment meets any of the following
/// conditions, an `Err` is returned indicating the condition met:
Expand All @@ -193,7 +194,7 @@ impl<'a> Segments<'a, Path> {
/// Additionally, if `allow_dotfiles` is `false`, an `Err` is returned if
/// the following condition is met:
///
/// * Decoded segment starts with any of: `.` (except `..`)
/// * Decoded segment starts with any of: `.` (except `..` and `.`)
///
/// As a result of these conditions, a `PathBuf` derived via `FromSegments`
/// is safe to interpolate within, or use as a suffix of, a path without
Expand All @@ -216,7 +217,9 @@ impl<'a> Segments<'a, Path> {
pub fn to_path_buf(&self, allow_dotfiles: bool) -> Result<PathBuf, PathError> {
let mut buf = PathBuf::new();
for segment in self.clone() {
if segment == ".." {
if segment == "." {
continue;
} else if segment == ".." {
buf.pop();
} else if !allow_dotfiles && segment.starts_with('.') {
return Err(PathError::BadStart('.'))
Expand Down
53 changes: 52 additions & 1 deletion core/lib/src/fs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,59 @@ mod named_file;
mod temp_file;
mod file_name;

pub mod rewrite;

pub use server::*;
pub use named_file::*;
pub use temp_file::*;
pub use file_name::*;
pub use server::relative;

crate::export! {
/// Generates a crate-relative version of a path.
///
/// This macro is primarily intended for use with [`FileServer`] to serve
/// files from a path relative to the crate root.
///
/// The macro accepts one parameter, `$path`, an absolute or (preferably)
/// relative path. It returns a path as an `&'static str` prefixed with the
/// path to the crate root. Use `Path::new(relative!($path))` to retrieve an
/// `&'static Path`.
///
/// # Example
///
/// Serve files from the crate-relative `static/` directory:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use rocket::fs::{FileServer, relative};
///
/// #[launch]
/// fn rocket() -> _ {
/// rocket::build().mount("/", FileServer::new(relative!("static")))
/// }
/// ```
///
/// Path equivalences:
///
/// ```rust
/// use std::path::Path;
///
/// use rocket::fs::relative;
///
/// let manual = Path::new(env!("CARGO_MANIFEST_DIR")).join("static");
/// let automatic_1 = Path::new(relative!("static"));
/// let automatic_2 = Path::new(relative!("/static"));
/// assert_eq!(manual, automatic_1);
/// assert_eq!(automatic_1, automatic_2);
/// ```
///
macro_rules! relative {
($path:expr) => {
if cfg!(windows) {
concat!(env!("CARGO_MANIFEST_DIR"), "\\", $path)
} else {
concat!(env!("CARGO_MANIFEST_DIR"), "/", $path)
}
};
}
}
261 changes: 261 additions & 0 deletions core/lib/src/fs/rewrite.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
use std::borrow::Cow;
use std::path::{Path, PathBuf};

use crate::Request;
use crate::http::{ext::IntoOwned, HeaderMap};
use crate::response::Redirect;

/// A file server [`Rewrite`] rewriter.
///
/// A [`FileServer`] is a sequence of [`Rewriter`]s which transform the incoming
/// request path into a [`Rewrite`] or `None`. The first rewriter is called with
/// the request path as a [`Rewrite::File`]. Each `Rewriter` thereafter is
/// called in-turn with the previously returned [`Rewrite`], and the value
/// returned from the last `Rewriter` is used to respond to the request. If the
/// final rewrite is `None` or a nonexistent path or a directory, [`FileServer`]
/// responds with [`Status::NotFound`]. Otherwise it responds with the file
/// contents, if [`Rewrite::File`] is specified, or a redirect, if
/// [`Rewrite::Redirect`] is specified.
///
/// [`FileServer`]: super::FileServer
/// [`Status::NotFound`]: crate::http::Status::NotFound
pub trait Rewriter: Send + Sync + 'static {
/// Alter the [`Rewrite`] as needed.
fn rewrite<'r>(&self, opt: Option<Rewrite<'r>>, req: &'r Request<'_>) -> Option<Rewrite<'r>>;
}

/// A Response from a [`FileServer`](super::FileServer)
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Rewrite<'r> {
/// Return the contents of the specified file.
File(File<'r>),
/// Returns a Redirect.
Redirect(Redirect),
}

/// A File response from a [`FileServer`](super::FileServer) and a rewriter.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct File<'r> {
/// The path to the file that [`FileServer`](super::FileServer) will respond with.
pub path: Cow<'r, Path>,
/// A list of headers to be added to the generated response.
pub headers: HeaderMap<'r>,
}

impl<'r> File<'r> {
/// A new `File`, with not additional headers.
pub fn new(path: impl Into<Cow<'r, Path>>) -> Self {
Self { path: path.into(), headers: HeaderMap::new() }
}

/// A new `File`, with not additional headers.
///
/// # Panics
///
/// Panics if the `path` does not exist.
pub fn checked<P: AsRef<Path>>(path: P) -> Self {
let path = path.as_ref();
if !path.exists() {
let path = path.display();
error!(%path, "FileServer path does not exist.\n\
Panicking to prevent inevitable handler error.");
panic!("missing file {}: refusing to continue", path);
}

Self::new(path.to_path_buf())
}

/// Replace the path in `self` with the result of applying `f` to the path.
pub fn map_path<F, P>(self, f: F) -> Self
where F: FnOnce(Cow<'r, Path>) -> P, P: Into<Cow<'r, Path>>,
{
Self {
path: f(self.path).into(),
headers: self.headers,
}
}

/// Returns `true` if the file is a dotfile. A dotfile is a file whose
/// name or any directory in it's path start with a period (`.`) and is
/// considered hidden.
///
/// # Windows Note
///
/// This does *not* check the file metadata on any platform, so hidden files
/// on Windows will not be detected by this method.
pub fn is_hidden(&self) -> bool {
self.path.iter().any(|s| s.as_encoded_bytes().starts_with(b"."))
}

/// Returns `true` if the file is not hidden. This is the inverse of
/// [`File::is_hidden()`].
pub fn is_visible(&self) -> bool {
!self.is_hidden()
}
}

/// Prefixes all paths with a given path.
///
/// # Example
///
/// ```rust,no_run
/// use rocket::fs::FileServer;
/// use rocket::fs::rewrite::Prefix;
///
/// FileServer::identity()
/// .filter(|f, _| f.is_visible())
/// .rewrite(Prefix::checked("static"));
/// ```
pub struct Prefix(PathBuf);

impl Prefix {
/// Panics if `path` does not exist.
pub fn checked<P: AsRef<Path>>(path: P) -> Self {
let path = path.as_ref();
if !path.is_dir() {
let path = path.display();
error!(%path, "FileServer path is not a directory.");
warn!("Aborting early to prevent inevitable handler error.");
panic!("invalid directory: refusing to continue");
}

Self(path.to_path_buf())
}

/// Creates a new `Prefix` from a path.
pub fn unchecked<P: AsRef<Path>>(path: P) -> Self {
Self(path.as_ref().to_path_buf())
}
}

impl Rewriter for Prefix {
fn rewrite<'r>(&self, opt: Option<Rewrite<'r>>, _: &Request<'_>) -> Option<Rewrite<'r>> {
opt.map(|r| match r {
Rewrite::File(f) => Rewrite::File(f.map_path(|p| self.0.join(p))),
Rewrite::Redirect(r) => Rewrite::Redirect(r),
})
}
}

impl Rewriter for PathBuf {
fn rewrite<'r>(&self, _: Option<Rewrite<'r>>, _: &Request<'_>) -> Option<Rewrite<'r>> {
Some(Rewrite::File(File::new(self.clone())))
}
}

/// Normalize directories to always include a trailing slash by redirecting
/// (with a 302 temporary redirect) requests for directories without a trailing
/// slash to the same path with a trailing slash.
///
/// # Example
///
/// ```rust,no_run
/// use rocket::fs::FileServer;
/// use rocket::fs::rewrite::{Prefix, TrailingDirs};
///
/// FileServer::identity()
/// .filter(|f, _| f.is_visible())
/// .rewrite(TrailingDirs);
/// ```
pub struct TrailingDirs;

impl Rewriter for TrailingDirs {
fn rewrite<'r>(&self, opt: Option<Rewrite<'r>>, req: &Request<'_>) -> Option<Rewrite<'r>> {
if let Some(Rewrite::File(f)) = &opt {
if !req.uri().path().ends_with('/') && f.path.is_dir() {
let uri = req.uri().clone().into_owned();
let uri = uri.map_path(|p| format!("{p}/")).unwrap();
return Some(Rewrite::Redirect(Redirect::temporary(uri)));
}
}

opt
}
}

/// Rewrite a directory to a file inside of that directory.
///
/// # Example
///
/// Rewrites all directory requests to `directory/index.html`.
///
/// ```rust,no_run
/// use rocket::fs::FileServer;
/// use rocket::fs::rewrite::DirIndex;
///
/// FileServer::without_index("static")
/// .rewrite(DirIndex::if_exists("index.htm"))
/// .rewrite(DirIndex::unconditional("index.html"));
/// ```
pub struct DirIndex {
path: PathBuf,
check: bool,
}

impl DirIndex {
/// Appends `path` to every request for a directory.
pub fn unconditional(path: impl AsRef<Path>) -> Self {
Self { path: path.as_ref().to_path_buf(), check: false }
}

/// Only appends `path` to a request for a directory if the file exists.
pub fn if_exists(path: impl AsRef<Path>) -> Self {
Self { path: path.as_ref().to_path_buf(), check: true }
}
}

impl Rewriter for DirIndex {
fn rewrite<'r>(&self, opt: Option<Rewrite<'r>>, _: &Request<'_>) -> Option<Rewrite<'r>> {
match opt? {
Rewrite::File(f) if f.path.is_dir() => {
let candidate = f.path.join(&self.path);
if self.check && !candidate.is_file() {
return Some(Rewrite::File(f));
}

Some(Rewrite::File(f.map_path(|_| candidate)))
}
r => Some(r),
}
}
}

impl<'r> From<File<'r>> for Rewrite<'r> {
fn from(value: File<'r>) -> Self {
Self::File(value)
}
}

impl<'r> From<Redirect> for Rewrite<'r> {
fn from(value: Redirect) -> Self {
Self::Redirect(value)
}
}

impl<F: Send + Sync + 'static> Rewriter for F
where F: for<'r> Fn(Option<Rewrite<'r>>, &Request<'_>) -> Option<Rewrite<'r>>
{
fn rewrite<'r>(&self, f: Option<Rewrite<'r>>, r: &Request<'_>) -> Option<Rewrite<'r>> {
self(f, r)
}
}

impl Rewriter for Rewrite<'static> {
fn rewrite<'r>(&self, _: Option<Rewrite<'r>>, _: &Request<'_>) -> Option<Rewrite<'r>> {
Some(self.clone())
}
}

impl Rewriter for File<'static> {
fn rewrite<'r>(&self, _: Option<Rewrite<'r>>, _: &Request<'_>) -> Option<Rewrite<'r>> {
Some(Rewrite::File(self.clone()))
}
}

impl Rewriter for Redirect {
fn rewrite<'r>(&self, _: Option<Rewrite<'r>>, _: &Request<'_>) -> Option<Rewrite<'r>> {
Some(Rewrite::Redirect(self.clone()))
}
}
Loading
Loading