Skip to content

update to tower-sessions #28

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
18 changes: 10 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,18 @@ edition = "2021"
maintenance = { status = "actively-developed" }

[dependencies]
axum = "0.6.16"
axum-core = "0.3.4"
axum-sessions = "0.5.0"
base64 = "0.21.0"
axum = "0.7.3"
base64 = "0.21.5"
rand = "0.8.5"
thiserror = "1.0.40"
tokio = { version = "1.27.0", features = ["macros", "rt", "rt-multi-thread"] }
tower = "0.4.13"
tracing = "0.1.37"
tower-cookies = "0.10.0"
tower-layer = "0.3.2"
tower-service = "0.3.2"
tower-sessions = "0.9.1"
tracing = "0.1.40"

[dev-dependencies]
tokio = { version = "1.27.0", features = ["macros", "rt", "rt-multi-thread"] }
tokio-test = "0.4.2"
tower-http = { version = "0.4.0", features = ["cors"] }
tower = "0.4.13"
tower-http = { version = "0.5.0", features = ["cors"] }
62 changes: 26 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,9 @@ Consider as well to use the [crate unit tests](https://github.com/LeoniePhiline/

This middleware implements token transfer via [custom request headers](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#use-of-custom-request-headers).

The middleware requires and is built upon [`axum_sessions`](https://docs.rs/axum-sessions/), which in turn uses [`async_session`](https://docs.rs/async-session/).
The middleware requires and is built upon [`tower_sessions`](https://docs.rs/tower-sessions/).

The current version is built for and works with `axum 0.6.x`, `axum-sessions 0.5.x` and `async_session 3.x`.

There will be support for `axum 0.7` and later versions.
The current version is built for and works with `axum 0.7.x`, `tower-sessions 0.9.x`.

The [Same Origin Policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) prevents the custom request header to be set by foreign scripts.

Expand Down Expand Up @@ -67,7 +65,7 @@ See ["Our RNGs"](https://rust-random.github.io/book/guide-rngs.html#cryptographi

The security of the underlying session is paramount - the CSRF prevention methods applied can only be as secure as the session carrying the server-side token.

- When creating your [SessionLayer](https://docs.rs/axum-sessions/latest/axum_sessions/struct.SessionLayer.html), make sure to use at least 64 bytes of cryptographically secure randomness.
- When creating your [SessionManagerLayer](https://docs.rs/tower-sessions/latest/tower_sessions/struct.SessionManagerLayer.html)
- Do not lower the secure defaults: Keep the session cookie's `secure` flag **on**.
- Use the strictest possible same-site policy.

Expand Down Expand Up @@ -105,16 +103,12 @@ Configure your session and CSRF protection layer in your backend application:

```rust
use axum::{
body::Body,
http::StatusCode,
routing::{get, Router},
http::{header, StatusCode},
response::IntoResponse,
routing::get,
};
use axum_csrf_sync_pattern::{CsrfLayer, RegenerateToken};
use axum_sessions::{async_session::MemoryStore, SessionLayer};
use rand::RngCore;

let mut secret = [0; 64];
rand::thread_rng().try_fill_bytes(&mut secret).unwrap();
use axum_csrf_sync_pattern::CsrfLayer;
use tower_sessions::{MemoryStore, SessionManagerLayer};

async fn handler() -> StatusCode {
StatusCode::OK
Expand All @@ -136,7 +130,7 @@ let app = Router::new()
// Default: "_csrf_token"
.session_key("_custom_session_key")
)
.layer(SessionLayer::new(MemoryStore::new(), &secret));
.layer(SessionManagerLayer::new(MemoryStore::default()));

// Use hyper to run `app` as service and expose on a local port or socket.
```
Expand Down Expand Up @@ -175,37 +169,33 @@ Configure your CORS layer, session and CSRF protection layer in your backend app

```rust
use axum::{
body::Body,
http::{header, Method, StatusCode},
response::IntoResponse,
routing::{get, Router},
};
use axum_csrf_sync_pattern::{CsrfLayer, RegenerateToken};
use axum_sessions::{async_session::MemoryStore, SessionLayer};
use rand::RngCore;
use axum_csrf_sync_pattern::CsrfLayer;
use tower_http::cors::{AllowOrigin, CorsLayer};

let mut secret = [0; 64];
rand::thread_rng().try_fill_bytes(&mut secret).unwrap();
use tower_sessions::{MemoryStore, SessionManagerLayer};

async fn handler() -> StatusCode {
StatusCode::OK
}

let app = Router::new()
.route("/", get(handler).post(handler))
.layer(
// See example above for custom layer configuration.
CsrfLayer::new()
)
.layer(SessionLayer::new(MemoryStore::new(), &secret))
.layer(
CorsLayer::new()
.allow_origin(AllowOrigin::list(["https://www.example.com".parse().unwrap()]))
.allow_methods([Method::GET, Method::POST])
.allow_headers([header::CONTENT_TYPE, "X-CSRF-TOKEN".parse().unwrap()])
.allow_credentials(true)
.expose_headers(["X-CSRF-TOKEN".parse().unwrap()]),
);
.route("/", get(handler).post(handler))
.layer(
// See example above for custom layer configuration.
CsrfLayer::new()
)
.layer(SessionManagerLayer::new(MemoryStore::default()))
.layer(
CorsLayer::new()
.allow_origin(AllowOrigin::list(["https://www.example.com".parse().rap()]))
.allow_methods([Method::GET, Method::POST])
.allow_headers([header::CONTENT_TYPE, "X-CSRF-TOKEN".parse().unwrap()])
.allow_credentials(true)
.expose_headers(["X-CSRF-TOKEN".parse().unwrap()]),
);

// Use hyper to run `app` as service and expose on a local port or socket.
```
Expand Down
10 changes: 4 additions & 6 deletions examples/cross-site/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@ edition = "2021"
publish = false

[dependencies]
axum = "0.6.16"
axum = "0.7.3"
axum-csrf-sync-pattern = { path = "../../" }
axum-sessions = "0.5.0"
color-eyre = "0.6.2"
rand = "0.8.5"
tokio = { version = "1.27.0", features = ["macros", "rt", "rt-multi-thread"] }
tower = "0.4.13"
tower-http = { version = "0.4.0", features = ["cors"] }
tracing-subscriber = "0.3.16"
tower-http = { version = "0.5.0", features = ["cors"] }
tower-sessions = "0.9.1"
tracing-subscriber = "0.3.18"
18 changes: 6 additions & 12 deletions examples/cross-site/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ use axum::{
http::{header, Method, StatusCode},
response::IntoResponse,
routing::{get, Router},
Server,
};
use axum_csrf_sync_pattern::CsrfLayer;
use axum_sessions::{async_session::MemoryStore, SessionLayer};
use color_eyre::eyre::{self, eyre, WrapErr};
use rand::RngCore;
use tower_http::cors::{AllowOrigin, CorsLayer};
use tower_sessions::{MemoryStore, SessionManagerLayer};

#[tokio::main]
async fn main() -> eyre::Result<()> {
Expand All @@ -33,15 +31,10 @@ async fn main() -> eyre::Result<()> {
};

let backend = async {
let mut secret = [0; 64];
rand::thread_rng()
.try_fill_bytes(&mut secret)
.wrap_err("Failed to generate session seed.")?;

let app = Router::new()
.route("/", get(get_token).post(post_handler))
.layer(CsrfLayer::new())
.layer(SessionLayer::new(MemoryStore::new(), &secret))
.layer(SessionManagerLayer::new(MemoryStore::default()))
.layer(
CorsLayer::new()
.allow_origin(AllowOrigin::list([
Expand Down Expand Up @@ -81,9 +74,10 @@ async fn main() -> eyre::Result<()> {

async fn serve(app: Router, port: u16) -> eyre::Result<()> {
let addr = SocketAddr::from(([127, 0, 0, 1], port));
Server::try_bind(&addr)
.wrap_err("Could not bind to network address.")?
.serve(app.into_make_service())
let listener = tokio::net::TcpListener::bind(addr)
.await
.wrap_err("Could not bind to network address.")?;
axum::serve(listener, app)
.await
.wrap_err("Failed to serve the app.")?;

Expand Down
8 changes: 3 additions & 5 deletions examples/same-site/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@ edition = "2021"
publish = false

[dependencies]
axum = "0.6.16"
axum = "0.7.3"
axum-csrf-sync-pattern = { path = "../../" }
axum-sessions = "0.5.0"
color-eyre = "0.6.2"
rand = "0.8.5"
tokio = { version = "1.27.0", features = ["macros", "rt", "rt-multi-thread"] }
tower = "0.4.13"
tracing-subscriber = "0.3.16"
tower-sessions = "0.9.1"
tracing-subscriber = "0.3.18"
26 changes: 8 additions & 18 deletions examples/same-site/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ use axum::{
http::{header, StatusCode},
response::IntoResponse,
routing::get,
Server,
};
use axum_csrf_sync_pattern::CsrfLayer;
use axum_sessions::{async_session::MemoryStore, SessionLayer};
use color_eyre::eyre::{self, eyre, WrapErr};
use rand::RngCore;
use tower_sessions::{MemoryStore, SessionManagerLayer};

#[tokio::main]
async fn main() -> eyre::Result<()> {
Expand All @@ -20,26 +18,18 @@ async fn main() -> eyre::Result<()> {
.map_err(|e| eyre!(e))
.wrap_err("Failed to initialize tracing-subscriber.")?;

let mut secret = [0; 64];
rand::thread_rng()
.try_fill_bytes(&mut secret)
.wrap_err("Failed to generate session seed.")?;

let app = axum::Router::new()
.route("/", get(index).post(handler))
.layer(CsrfLayer::new())
.layer(SessionLayer::new(MemoryStore::new(), &secret));
.layer(SessionManagerLayer::new(MemoryStore::default()));

// Visit "http://127.0.0.1:3000/" in your browser.
Server::try_bind(
&"0.0.0.0:3000"
.parse()
.wrap_err("Failed to parse socket address.")?,
)
.wrap_err("Could not bind to network address.")?
.serve(app.into_make_service())
.await
.wrap_err("Failed to serve the app.")?;
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.wrap_err("Could not bind to network address.")?;
axum::serve(listener, app)
.await
.wrap_err("Failed to serve the app.")?;

Ok(())
}
Expand Down
Loading