Skip to content

Commit 007a0e8

Browse files
author
Nick Ashley
authored
Use 308 instead of 301 for trailing slash redirects (#682)
* Use 308 status instead of 301 when redirecting For redirects resulting from requests to paths with a trailing slash, use 308 instead of 301 to prevent non-GET requests (POST, PUT, etc) from being changed to GET. For example, (assuming a route for /path is defined)... - Old behavior results in: POST /path/ -> GET /path - New behavior results in: POST /path/ -> POST /path Fixes #681 * Add deprecation notice to found() Deprecates found() due to its use of HTTP 302 * rustfmt * Use dedicated redirect method Use Redirect::permanent instead of re-implementing its functionality * Remove deprecated method from example Replace usages of Redirect:found with Redirect::to and Redirect::temporary as appropriate * Fix panic in oauth example Previously the example would panic if a request was made without the `Cookie` header. Now the user is redirected to the login page as expected. * Update CHANGELOG * Revert pub TypedheaderRejection fields * Fix clippy lint * cargo fmt * Fix CHANGELOG link * Adhere to implicit line length limit
1 parent 5512ebc commit 007a0e8

File tree

6 files changed

+71
-34
lines changed

6 files changed

+71
-34
lines changed

axum/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
- **fixed:** Fix using incorrect path prefix when nesting `Router`s at `/` ([#691])
1111
- **fixed:** Make `nest("", service)` work and mean the same as `nest("/", service)` ([#691])
12+
- **fixed:** Replace response code `301` with `308` for trailing slash redirects. Also deprecates
13+
`Redirect::found` (`302`) in favor of `Redirect::temporary` (`307`) or `Redirect::to` (`303`).
14+
This is to prevent clients from changing non-`GET` requests to `GET` requests ([#682])
1215

1316
[#691]: https://github.com/tokio-rs/axum/pull/691
17+
[#682]: https://github.com/tokio-rs/axum/pull/682
1418

1519
# 0.4.3 (21. December, 2021)
1620

axum/src/response/redirect.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ impl Redirect {
3333
/// This redirect instructs the client to change the method to GET for the subsequent request
3434
/// to the given `uri`, which is useful after successful form submission, file upload or when
3535
/// you generally don't want the redirected-to page to observe the original request method and
36-
/// body (if non-empty).
36+
/// body (if non-empty). If you want to preserve the request method and body,
37+
/// [`Redirect::temporary`] should be used instead.
3738
///
3839
/// # Panics
3940
///
@@ -71,16 +72,21 @@ impl Redirect {
7172

7273
/// Create a new [`Redirect`] that uses a [`302 Found`][mdn] status code.
7374
///
74-
/// This is the same as [`Redirect::temporary`], except the status code is older and thus
75-
/// supported by some legacy applications that doesn't understand the newer one, but some of
76-
/// those applications wrongly apply [`Redirect::to`] (`303 See Other`) semantics for this
77-
/// status code. It should be avoided where possible.
75+
/// This is the same as [`Redirect::temporary`] ([`307 Temporary Redirect`][mdn307]) except
76+
/// this status code is older and thus supported by some legacy clients that don't understand
77+
/// the newer one. Many clients wrongly apply [`Redirect::to`] ([`303 See Other`][mdn303])
78+
/// semantics for this status code, so it should be avoided where possible.
7879
///
7980
/// # Panics
8081
///
8182
/// If `uri` isn't a valid [`HeaderValue`].
8283
///
8384
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302
85+
/// [mdn307]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307
86+
/// [mdn303]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303
87+
#[deprecated(
88+
note = "This results in different behavior between clients, so Redirect::temporary or Redirect::to should be used instead"
89+
)]
8490
pub fn found(uri: Uri) -> Self {
8591
Self::with_status_code(StatusCode::FOUND, uri)
8692
}

axum/src/routing/mod.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@ use crate::{
77
connect_info::{Connected, IntoMakeServiceWithConnectInfo},
88
MatchedPath, OriginalUri,
99
},
10+
response::IntoResponse,
11+
response::Redirect,
1012
response::Response,
1113
routing::strip_prefix::StripPrefix,
1214
util::{try_downcast, ByteStr, PercentDecodedByteStr},
1315
BoxError,
1416
};
15-
use http::{Request, StatusCode, Uri};
17+
use http::{Request, Uri};
1618
use std::{
1719
borrow::Cow,
1820
collections::HashMap,
@@ -490,12 +492,8 @@ where
490492
} else {
491493
with_path(req.uri(), &format!("{}/", path))
492494
};
493-
let res = Response::builder()
494-
.status(StatusCode::MOVED_PERMANENTLY)
495-
.header(http::header::LOCATION, redirect_to.to_string())
496-
.body(crate::body::empty())
497-
.unwrap();
498-
RouterFuture::from_response(res)
495+
let res = Redirect::permanent(redirect_to);
496+
RouterFuture::from_response(res.into_response())
499497
} else {
500498
match &self.fallback {
501499
Fallback::Default(inner) => {

axum/src/routing/tests/mod.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,30 @@ async fn with_and_without_trailing_slash() {
354354
assert_eq!(res.text().await, "without tsr");
355355
}
356356

357+
// for https://github.com/tokio-rs/axum/issues/681
358+
#[tokio::test]
359+
async fn with_trailing_slash_post() {
360+
let app = Router::new().route("/foo", post(|| async {}));
361+
362+
let client = TestClient::new(app);
363+
364+
// `TestClient` automatically follows redirects
365+
let res = client.post("/foo/").send().await;
366+
assert_eq!(res.status(), StatusCode::OK);
367+
}
368+
369+
// for https://github.com/tokio-rs/axum/issues/681
370+
#[tokio::test]
371+
async fn without_trailing_slash_post() {
372+
let app = Router::new().route("/foo/", post(|| async {}));
373+
374+
let client = TestClient::new(app);
375+
376+
// `TestClient` automatically follows redirects
377+
let res = client.post("/foo").send().await;
378+
assert_eq!(res.status(), StatusCode::OK);
379+
}
380+
357381
// for https://github.com/tokio-rs/axum/issues/420
358382
#[tokio::test]
359383
async fn wildcard_with_trailing_slash() {
@@ -381,7 +405,7 @@ async fn wildcard_with_trailing_slash() {
381405
)
382406
.await
383407
.unwrap();
384-
assert_eq!(res.status(), StatusCode::MOVED_PERMANENTLY);
408+
assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
385409
assert_eq!(res.headers()["location"], "/user1/repo1/tree/");
386410

387411
// check that the params are deserialized correctly

examples/oauth/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,4 @@ serde = { version = "1.0", features = ["derive"] }
1515
# Use Rustls because it makes it easier to cross-compile on CI
1616
reqwest = { version = "0.11", default-features = false, features = ["rustls-tls", "json"] }
1717
headers = "0.3"
18+
http = "0.2"

examples/oauth/src/main.rs

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,33 @@
11
//! Example OAuth (Discord) implementation.
22
//!
3-
//! Run with
4-
//!
3+
//! 1) Create a new application at <https://discord.com/developers/applications>
4+
//! 2) Visit the OAuth2 tab to get your CLIENT_ID and CLIENT_SECRET
5+
//! 3) Add a new redirect URI (for this example: `http://127.0.0.1:3000/auth/authorized`)
6+
//! 4) Run with the following (replacing values appropriately):
57
//! ```not_rust
6-
//! CLIENT_ID=123 CLIENT_SECRET=secret cargo run -p example-oauth
8+
//! CLIENT_ID=REPLACE_ME CLIENT_SECRET=REPLACE_ME cargo run -p example-oauth
79
//! ```
810
911
use async_session::{MemoryStore, Session, SessionStore};
1012
use axum::{
1113
async_trait,
12-
extract::{Extension, FromRequest, Query, RequestParts, TypedHeader},
14+
extract::{
15+
rejection::TypedHeaderRejectionReason, Extension, FromRequest, Query, RequestParts,
16+
TypedHeader,
17+
},
1318
http::{header::SET_COOKIE, HeaderMap},
1419
response::{IntoResponse, Redirect, Response},
1520
routing::get,
1621
AddExtensionLayer, Router,
1722
};
23+
use http::header;
1824
use oauth2::{
1925
basic::BasicClient, reqwest::async_http_client, AuthUrl, AuthorizationCode, ClientId,
2026
ClientSecret, CsrfToken, RedirectUrl, Scope, TokenResponse, TokenUrl,
2127
};
2228
use serde::{Deserialize, Serialize};
2329
use std::{env, net::SocketAddr};
2430

25-
// Quick instructions:
26-
// 1) create a new application at https://discord.com/developers/applications
27-
// 2) visit the OAuth2 tab to get your CLIENT_ID and CLIENT_SECRET
28-
// 3) add a new redirect URI (For this example: http://localhost:3000/auth/authorized)
29-
// 4) AUTH_URL and TOKEN_URL may stay the same for discord.
30-
// More information: https://discord.com/developers/applications/792730475856527411/oauth2
31-
3231
static COOKIE_NAME: &str = "SESSION";
3332

3433
#[tokio::main]
@@ -39,7 +38,7 @@ async fn main() {
3938
}
4039
tracing_subscriber::fmt::init();
4140

42-
// `MemoryStore` just used as an example. Don't use this in production.
41+
// `MemoryStore` is just used as an example. Don't use this in production.
4342
let store = MemoryStore::new();
4443

4544
let oauth_client = oauth_client();
@@ -64,8 +63,8 @@ async fn main() {
6463

6564
fn oauth_client() -> BasicClient {
6665
// Environment variables (* = required):
67-
// *"CLIENT_ID" "123456789123456789";
68-
// *"CLIENT_SECRET" "rAn60Mch4ra-CTErsSf-r04utHcLienT";
66+
// *"CLIENT_ID" "REPLACE_ME";
67+
// *"CLIENT_SECRET" "REPLACE_ME";
6968
// "REDIRECT_URL" "http://127.0.0.1:3000/auth/authorized";
7069
// "AUTH_URL" "https://discord.com/api/oauth2/authorize?response_type=code";
7170
// "TOKEN_URL" "https://discord.com/api/oauth2/token";
@@ -119,7 +118,7 @@ async fn discord_auth(Extension(client): Extension<BasicClient>) -> impl IntoRes
119118
.url();
120119

121120
// Redirect to Discord's oauth service
122-
Redirect::found(auth_url.to_string().parse().unwrap())
121+
Redirect::to(auth_url.to_string().parse().unwrap())
123122
}
124123

125124
// Valid user session required. If there is none, redirect to the auth page
@@ -138,12 +137,12 @@ async fn logout(
138137
let session = match store.load_session(cookie.to_string()).await.unwrap() {
139138
Some(s) => s,
140139
// No session active, just redirect
141-
None => return Redirect::found("/".parse().unwrap()),
140+
None => return Redirect::to("/".parse().unwrap()),
142141
};
143142

144143
store.destroy_session(session).await.unwrap();
145144

146-
Redirect::found("/".parse().unwrap())
145+
Redirect::to("/".parse().unwrap())
147146
}
148147

149148
#[derive(Debug, Deserialize)]
@@ -192,14 +191,14 @@ async fn login_authorized(
192191
let mut headers = HeaderMap::new();
193192
headers.insert(SET_COOKIE, cookie.parse().unwrap());
194193

195-
(headers, Redirect::found("/".parse().unwrap()))
194+
(headers, Redirect::to("/".parse().unwrap()))
196195
}
197196

198197
struct AuthRedirect;
199198

200199
impl IntoResponse for AuthRedirect {
201200
fn into_response(self) -> Response {
202-
Redirect::found("/auth/discord".parse().unwrap()).into_response()
201+
Redirect::temporary("/auth/discord".parse().unwrap()).into_response()
203202
}
204203
}
205204

@@ -218,8 +217,13 @@ where
218217

219218
let cookies = TypedHeader::<headers::Cookie>::from_request(req)
220219
.await
221-
.expect("could not get cookies");
222-
220+
.map_err(|e| match *e.name() {
221+
header::COOKIE => match e.reason() {
222+
TypedHeaderRejectionReason::Missing => AuthRedirect,
223+
_ => panic!("unexpected error getting Cookie header(s): {}", e),
224+
},
225+
_ => panic!("unexpected error getting cookies: {}", e),
226+
})?;
223227
let session_cookie = cookies.get(COOKIE_NAME).ok_or(AuthRedirect)?;
224228

225229
let session = store

0 commit comments

Comments
 (0)