use axum::http::HeaderValue;
use axum::response::{IntoResponse, Response};
use larust_core::AppError;
pub fn route(name: &str) -> Result<String, AppError> {
let path = resolve_route_path(name)?;
let (path, unresolved) = substitute_params(&path, &[]);
reject_if_unresolved(name, &path, unresolved)?;
Ok(path)
}
pub fn route_with(name: &str, params: &[(&str, &str)]) -> Result<String, AppError> {
let path = resolve_route_path(name)?;
let (path, unresolved) = substitute_params(&path, params);
reject_if_unresolved(name, &path, unresolved)?;
Ok(path)
}
fn resolve_route_path(name: &str) -> Result<String, AppError> {
larust_http::resolve_route_name(name).ok_or_else(|| {
AppError::Internal(Box::new(std::io::Error::other(format!(
"no route named `{name}` is registered"
))))
})
}
fn substitute_params(path: &str, params: &[(&str, &str)]) -> (String, bool) {
let mut result = String::with_capacity(path.len());
let mut unresolved = false;
let mut rest = path;
while let Some(start) = rest.find('{') {
result.push_str(&rest[..start]);
let after_open = &rest[start + 1..];
match after_open.find('}') {
Some(end) => {
let key = &after_open[..end];
match params.iter().find(|(param_key, _)| *param_key == key) {
Some((_, value)) => result.push_str(value),
None => {
result.push('{');
result.push_str(key);
result.push('}');
unresolved = true;
}
}
rest = &after_open[end + 1..];
}
None => {
result.push_str(&rest[start..]);
rest = "";
}
}
}
result.push_str(rest);
(result, unresolved)
}
fn reject_if_unresolved(name: &str, path: &str, unresolved: bool) -> Result<(), AppError> {
if !unresolved {
return Ok(());
}
Err(AppError::Internal(Box::new(std::io::Error::other(
format!(
"route `{name}` resolves to `{path}`, which still has an unfilled \
`{{param}}` placeholder - pass the right params via \
route_with(\"{name}\", &[...])"
),
))))
}
pub fn redirect() -> RedirectBuilder {
RedirectBuilder
}
pub struct RedirectBuilder;
impl RedirectBuilder {
pub fn to(self, path: &str) -> Result<Redirect, AppError> {
checked_redirect(path)
}
pub fn route(self, name: &str) -> Result<Redirect, AppError> {
checked_redirect(&route(name)?)
}
pub fn back(
self,
headers: &axum::http::HeaderMap,
fallback: &str,
) -> Result<Redirect, AppError> {
let path = headers
.get(axum::http::header::REFERER)
.and_then(|value| value.to_str().ok())
.and_then(path_from_referer)
.unwrap_or(fallback);
checked_redirect(path)
}
}
fn path_from_referer(referer: &str) -> Option<&str> {
let after_scheme = referer.split_once("://").map_or(referer, |(_, rest)| rest);
let path_start = after_scheme.find('/')?;
Some(&after_scheme[path_start..])
}
fn checked_redirect(path: &str) -> Result<Redirect, AppError> {
HeaderValue::from_str(path).map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(Redirect(axum::response::Redirect::to(path)))
}
#[must_use]
pub struct Redirect(axum::response::Redirect);
impl Redirect {
pub async fn with(
self,
session: &larust_http::session::Session,
key: &str,
value: impl Into<String>,
) -> Self {
if let Err(error) = session.insert(key, value.into()).await {
tracing::warn!(%error, key, "failed to flash value to session");
}
self
}
}
impl IntoResponse for Redirect {
fn into_response(self) -> Response {
self.0.into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::{HeaderMap, HeaderValue};
#[test]
fn path_from_referer_strips_scheme_and_host() {
assert_eq!(
path_from_referer("http://127.0.0.1:34187/posts/5?tab=comments"),
Some("/posts/5?tab=comments")
);
}
#[test]
fn path_from_referer_accepts_a_bare_path_with_no_scheme() {
assert_eq!(path_from_referer("/posts"), Some("/posts"));
}
#[test]
fn path_from_referer_returns_none_when_there_is_no_path_at_all() {
assert_eq!(path_from_referer("http://example.test"), None);
}
#[test]
fn back_redirects_to_the_referers_own_path_discarding_its_origin() {
let mut headers = HeaderMap::new();
headers.insert(
axum::http::header::REFERER,
HeaderValue::from_static("https://not-this-server.test/profile"),
);
let redirect = redirect().back(&headers, "/posts").unwrap();
let response = redirect.into_response();
assert_eq!(
response
.headers()
.get(axum::http::header::LOCATION)
.unwrap(),
"/profile",
"only the path should survive - never the attacker-controlled host"
);
}
#[test]
fn back_falls_back_when_there_is_no_referer_header() {
let redirect = redirect().back(&HeaderMap::new(), "/posts").unwrap();
let response = redirect.into_response();
assert_eq!(
response
.headers()
.get(axum::http::header::LOCATION)
.unwrap(),
"/posts"
);
}
#[test]
fn substitute_params_replaces_a_single_placeholder() {
assert_eq!(
substitute_params("/posts/{post}", &[("post", "42")]),
("/posts/42".to_string(), false)
);
}
#[test]
fn substitute_params_replaces_multiple_placeholders() {
assert_eq!(
substitute_params("/{a}/nested/{b}", &[("a", "1"), ("b", "2")]),
("/1/nested/2".to_string(), false)
);
}
#[test]
fn substitute_params_leaves_a_placeholder_with_no_matching_param_untouched_and_flags_it() {
assert_eq!(
substitute_params("/posts/{post}", &[("wrong_name", "42")]),
("/posts/{post}".to_string(), true)
);
}
#[test]
fn substitute_params_never_reinterprets_an_inserted_value_as_a_later_placeholder() {
assert_eq!(
substitute_params(
"/users/{id}/reset/{token}",
&[("id", "{token}"), ("token", "super-secret")]
),
("/users/{token}/reset/super-secret".to_string(), false)
);
}
#[test]
fn substitute_params_keeps_an_unterminated_placeholder_literal_without_duplicating_it() {
assert_eq!(
substitute_params("/foo/{bar", &[]),
("/foo/{bar".to_string(), false)
);
}
#[test]
fn substitute_params_keeps_an_unterminated_placeholder_literal_after_a_resolved_one() {
assert_eq!(
substitute_params("/a/{id}/b/{unclosed", &[("id", "X")]),
("/a/X/b/{unclosed".to_string(), false)
);
}
#[test]
fn reject_if_unresolved_passes_when_nothing_was_left_unresolved() {
assert!(reject_if_unresolved("posts.show", "/posts/42", false).is_ok());
}
#[test]
fn reject_if_unresolved_errors_when_something_was_left_unresolved() {
let err = reject_if_unresolved("posts.show", "/posts/{post}", true).unwrap_err();
let message = err.to_string();
assert!(message.contains("posts.show"), "message was: {message}");
assert!(message.contains("route_with"), "message was: {message}");
}
#[test]
fn reject_if_unresolved_does_not_flag_brace_characters_that_came_from_a_param_value() {
let (path, unresolved) =
substitute_params("/search/{query}", &[("query", "{not a placeholder}")]);
assert!(!unresolved);
assert!(reject_if_unresolved("search", &path, unresolved).is_ok());
}
}