larust_support/redirect.rs
1use axum::http::HeaderValue;
2use axum::response::{IntoResponse, Response};
3use larust_core::AppError;
4
5/// Resolves a named route to its declared path (Laravel's `route($name)`).
6/// Fails if no route with that name was registered, **or** if the resolved
7/// path still has an unsubstituted `{param}` placeholder - this function
8/// takes no parameters, so a route that needs one (`/posts/{post}`) must be
9/// resolved via [`route_with`] instead; erroring here (rather than
10/// returning the literal, broken `/posts/{post}` string) is what steers a
11/// caller toward the right function instead of shipping a dead link.
12///
13/// A missing route name is a developer misconfiguration (a typo in a
14/// hardcoded name), not something to expose to the client - the detail
15/// goes through `AppError::Internal` (logged, generic message to the
16/// client), not `AppError::Http` (client-visible message).
17pub fn route(name: &str) -> Result<String, AppError> {
18 let path = resolve_route_path(name)?;
19 let (path, unresolved) = substitute_params(&path, &[]);
20 reject_if_unresolved(name, &path, unresolved)?;
21 Ok(path)
22}
23
24/// Resolves a named route, substituting each `{key}` placeholder in its
25/// declared path with the matching value from `params` (Laravel's
26/// `route($name, $params)`, minus the array/positional-value flexibility -
27/// `params` is explicit `(name, value)` pairs here, matching this
28/// codebase's existing "explicit, never inferred" stance for anything with
29/// this shape, e.g. `#[belongs_to_many(...)]`'s `related_pivot_key` or
30/// `Route::resource`'s `param` argument).
31///
32/// Fails if the route doesn't exist, or if any `{param}` placeholder
33/// remains after applying every given pair - a wrong param name or a
34/// missing one, caught here rather than silently producing a broken URL.
35pub fn route_with(name: &str, params: &[(&str, &str)]) -> Result<String, AppError> {
36 let path = resolve_route_path(name)?;
37 let (path, unresolved) = substitute_params(&path, params);
38 reject_if_unresolved(name, &path, unresolved)?;
39 Ok(path)
40}
41
42fn resolve_route_path(name: &str) -> Result<String, AppError> {
43 larust_http::resolve_route_name(name).ok_or_else(|| {
44 AppError::Internal(Box::new(std::io::Error::other(format!(
45 "no route named `{name}` is registered"
46 ))))
47 })
48}
49
50/// Replaces each `{key}` in `path` with its matching value from `params`,
51/// in a single left-to-right pass over the *original* `path` - factored
52/// out from `route_with` so it's testable without touching
53/// `larust_http::resolve_route_name`'s process-wide route registry (only
54/// set once per process, by whichever `Router::into_axum_router()` call
55/// happens to run first - not practical to exercise per-test-case here).
56///
57/// Deliberately never re-scans the string it's building: an earlier
58/// `String::replace(...)`-per-key approach re-scanned the *entire,
59/// already-substituted* output on every subsequent key, so a param value
60/// that happened to contain literal `{other_key}` text got swept up and
61/// replaced again - leaking one param's value into a position a *later*
62/// param controlled. Because inserted values are pushed straight into
63/// `result` and only `rest` (the untouched remainder of the original
64/// `path`) is ever searched for the next `{`, an inserted value can never
65/// be reinterpreted as a placeholder, however it's shaped.
66///
67/// Returns whether any `{...}` placeholder in `path` had no matching
68/// entry in `params` - computed here, during the single parse, rather
69/// than by re-inspecting the output for leftover braces afterward (which
70/// can't tell a genuinely unfilled placeholder apart from a param value
71/// that simply contains brace characters of its own).
72fn substitute_params(path: &str, params: &[(&str, &str)]) -> (String, bool) {
73 let mut result = String::with_capacity(path.len());
74 let mut unresolved = false;
75 let mut rest = path;
76 while let Some(start) = rest.find('{') {
77 result.push_str(&rest[..start]);
78 let after_open = &rest[start + 1..];
79 match after_open.find('}') {
80 Some(end) => {
81 let key = &after_open[..end];
82 match params.iter().find(|(param_key, _)| *param_key == key) {
83 Some((_, value)) => result.push_str(value),
84 None => {
85 result.push('{');
86 result.push_str(key);
87 result.push('}');
88 unresolved = true;
89 }
90 }
91 rest = &after_open[end + 1..];
92 }
93 // A stray `{` with no closing brace isn't a well-formed
94 // placeholder to substitute or to flag as unresolved - keep
95 // it (and everything after it) literal. Push from `start`,
96 // not from the top of `rest` - the prefix before `start` was
97 // already pushed on line above; pushing all of `rest` here
98 // would duplicate it.
99 None => {
100 result.push_str(&rest[start..]);
101 rest = "";
102 }
103 }
104 }
105 result.push_str(rest);
106 (result, unresolved)
107}
108
109fn reject_if_unresolved(name: &str, path: &str, unresolved: bool) -> Result<(), AppError> {
110 if !unresolved {
111 return Ok(());
112 }
113 Err(AppError::Internal(Box::new(std::io::Error::other(
114 format!(
115 "route `{name}` resolves to `{path}`, which still has an unfilled \
116 `{{param}}` placeholder - pass the right params via \
117 route_with(\"{name}\", &[...])"
118 ),
119 ))))
120}
121
122/// Entry point for Laravel's `redirect()` helper.
123pub fn redirect() -> RedirectBuilder {
124 RedirectBuilder
125}
126
127pub struct RedirectBuilder;
128
129impl RedirectBuilder {
130 /// Redirects to a literal path.
131 ///
132 /// Fails rather than panics if `path` can't be represented as a
133 /// `Location` header value (axum's own `Redirect::to` panics on this,
134 /// which is unsafe to expose to paths built from request data such as
135 /// a `?next=` query parameter).
136 pub fn to(self, path: &str) -> Result<Redirect, AppError> {
137 checked_redirect(path)
138 }
139
140 /// Redirects to a named route (Laravel's `redirect()->route($name)`).
141 pub fn route(self, name: &str) -> Result<Redirect, AppError> {
142 checked_redirect(&route(name)?)
143 }
144
145 /// Redirects back to wherever the request came from (Laravel's
146 /// `redirect()->back()`), read from the `Referer` header - for a
147 /// handler that does something (change a preference, submit a small
148 /// form) from more than one page and should return the visitor to
149 /// whichever one they were actually on, rather than a single
150 /// hardcoded destination.
151 ///
152 /// Only the path (plus any query/fragment) is ever taken from
153 /// `Referer` - the scheme and host are discarded unconditionally, so
154 /// a header a client fully controls can never redirect anywhere but
155 /// this same origin. Falls back to `fallback` when there's no
156 /// `Referer` header at all, or it has no path component to extract
157 /// (e.g. `http://example.test` with nothing after the host).
158 pub fn back(
159 self,
160 headers: &axum::http::HeaderMap,
161 fallback: &str,
162 ) -> Result<Redirect, AppError> {
163 let path = headers
164 .get(axum::http::header::REFERER)
165 .and_then(|value| value.to_str().ok())
166 .and_then(path_from_referer)
167 .unwrap_or(fallback);
168 checked_redirect(path)
169 }
170}
171
172/// Extracts the path (plus query/fragment) from a `Referer` header value,
173/// discarding its scheme and host - see [`RedirectBuilder::back`]'s own
174/// doc comment for why that's a deliberate safety property, not an
175/// oversight. Also tolerates a `referer` that's already just a path (no
176/// `://` at all) unchanged, rather than requiring a full URL - defensive,
177/// since nothing about `Referer` is guaranteed to be well-formed.
178fn path_from_referer(referer: &str) -> Option<&str> {
179 let after_scheme = referer.split_once("://").map_or(referer, |(_, rest)| rest);
180 let path_start = after_scheme.find('/')?;
181 Some(&after_scheme[path_start..])
182}
183
184fn checked_redirect(path: &str) -> Result<Redirect, AppError> {
185 HeaderValue::from_str(path).map_err(|source| AppError::Internal(Box::new(source)))?;
186 Ok(Redirect(axum::response::Redirect::to(path)))
187}
188
189#[must_use]
190pub struct Redirect(axum::response::Redirect);
191
192impl Redirect {
193 /// Flashes a value into the session, readable on the very next request
194 /// via `session.remove(key)` (Laravel's `redirect()->with($key, $value)` -
195 /// a one-hop flash, not persistent storage). Takes `&Session`
196 /// explicitly rather than reaching for an ambient/global session,
197 /// matching this framework's "no implicit request-scoped state"
198 /// design.
199 pub async fn with(
200 self,
201 session: &larust_http::session::Session,
202 key: &str,
203 value: impl Into<String>,
204 ) -> Self {
205 // Best-effort: a failed session write means the flash message is
206 // lost, not that the redirect itself should fail - the user still
207 // gets redirected to the right place.
208 if let Err(error) = session.insert(key, value.into()).await {
209 tracing::warn!(%error, key, "failed to flash value to session");
210 }
211 self
212 }
213}
214
215impl IntoResponse for Redirect {
216 fn into_response(self) -> Response {
217 self.0.into_response()
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224 use axum::http::{HeaderMap, HeaderValue};
225
226 #[test]
227 fn path_from_referer_strips_scheme_and_host() {
228 assert_eq!(
229 path_from_referer("http://127.0.0.1:34187/posts/5?tab=comments"),
230 Some("/posts/5?tab=comments")
231 );
232 }
233
234 #[test]
235 fn path_from_referer_accepts_a_bare_path_with_no_scheme() {
236 assert_eq!(path_from_referer("/posts"), Some("/posts"));
237 }
238
239 #[test]
240 fn path_from_referer_returns_none_when_there_is_no_path_at_all() {
241 assert_eq!(path_from_referer("http://example.test"), None);
242 }
243
244 #[test]
245 fn back_redirects_to_the_referers_own_path_discarding_its_origin() {
246 let mut headers = HeaderMap::new();
247 headers.insert(
248 axum::http::header::REFERER,
249 HeaderValue::from_static("https://not-this-server.test/profile"),
250 );
251 let redirect = redirect().back(&headers, "/posts").unwrap();
252 let response = redirect.into_response();
253 assert_eq!(
254 response
255 .headers()
256 .get(axum::http::header::LOCATION)
257 .unwrap(),
258 "/profile",
259 "only the path should survive - never the attacker-controlled host"
260 );
261 }
262
263 #[test]
264 fn back_falls_back_when_there_is_no_referer_header() {
265 let redirect = redirect().back(&HeaderMap::new(), "/posts").unwrap();
266 let response = redirect.into_response();
267 assert_eq!(
268 response
269 .headers()
270 .get(axum::http::header::LOCATION)
271 .unwrap(),
272 "/posts"
273 );
274 }
275
276 #[test]
277 fn substitute_params_replaces_a_single_placeholder() {
278 assert_eq!(
279 substitute_params("/posts/{post}", &[("post", "42")]),
280 ("/posts/42".to_string(), false)
281 );
282 }
283
284 #[test]
285 fn substitute_params_replaces_multiple_placeholders() {
286 assert_eq!(
287 substitute_params("/{a}/nested/{b}", &[("a", "1"), ("b", "2")]),
288 ("/1/nested/2".to_string(), false)
289 );
290 }
291
292 #[test]
293 fn substitute_params_leaves_a_placeholder_with_no_matching_param_untouched_and_flags_it() {
294 assert_eq!(
295 substitute_params("/posts/{post}", &[("wrong_name", "42")]),
296 ("/posts/{post}".to_string(), true)
297 );
298 }
299
300 #[test]
301 fn substitute_params_never_reinterprets_an_inserted_value_as_a_later_placeholder() {
302 // Regression test: an earlier implementation used
303 // `String::replace(...)` once per key against a single growing
304 // buffer, so an `id` value that happened to spell out `{token}`
305 // got swept up by the *next* `.replace("{token}", ...)` call and
306 // silently overwritten with the real token - leaking a sensitive
307 // param into a position the caller never put it in. Single-pass
308 // substitution over the original path (never over `result`) must
309 // not exhibit this: the literal text `{token}` arriving *as a
310 // param value* has to survive untouched in the output.
311 assert_eq!(
312 substitute_params(
313 "/users/{id}/reset/{token}",
314 &[("id", "{token}"), ("token", "super-secret")]
315 ),
316 ("/users/{token}/reset/super-secret".to_string(), false)
317 );
318 }
319
320 #[test]
321 fn substitute_params_keeps_an_unterminated_placeholder_literal_without_duplicating_it() {
322 // Regression test: the `None` arm (no closing `}`) originally
323 // pushed all of `rest`, but the prefix before the stray `{` had
324 // already been pushed on the line above - duplicating that
325 // prefix in the output instead of leaving the tail literal once.
326 assert_eq!(
327 substitute_params("/foo/{bar", &[]),
328 ("/foo/{bar".to_string(), false)
329 );
330 }
331
332 #[test]
333 fn substitute_params_keeps_an_unterminated_placeholder_literal_after_a_resolved_one() {
334 assert_eq!(
335 substitute_params("/a/{id}/b/{unclosed", &[("id", "X")]),
336 ("/a/X/b/{unclosed".to_string(), false)
337 );
338 }
339
340 #[test]
341 fn reject_if_unresolved_passes_when_nothing_was_left_unresolved() {
342 assert!(reject_if_unresolved("posts.show", "/posts/42", false).is_ok());
343 }
344
345 #[test]
346 fn reject_if_unresolved_errors_when_something_was_left_unresolved() {
347 let err = reject_if_unresolved("posts.show", "/posts/{post}", true).unwrap_err();
348 let message = err.to_string();
349 assert!(message.contains("posts.show"), "message was: {message}");
350 assert!(message.contains("route_with"), "message was: {message}");
351 }
352
353 #[test]
354 fn reject_if_unresolved_does_not_flag_brace_characters_that_came_from_a_param_value() {
355 // A param value containing `{`/`}` of its own (e.g. free-form user
356 // text) is not evidence of an unfilled route placeholder - only
357 // `substitute_params`'s own `unresolved` flag, computed during the
358 // single parse of the *declared* route path, decides that.
359 let (path, unresolved) =
360 substitute_params("/search/{query}", &[("query", "{not a placeholder}")]);
361 assert!(!unresolved);
362 assert!(reject_if_unresolved("search", &path, unresolved).is_ok());
363 }
364}