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

Set a Path on the CSRF cookie #944

Merged
merged 1 commit into from
Jan 4, 2025
Merged
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
21 changes: 20 additions & 1 deletion poem/src/middleware/csrf.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{sync::Arc, time::Duration};
use std::{borrow::Cow, sync::Arc, time::Duration};

use base64::{engine::general_purpose::STANDARD, Engine};
use libcsrf::{
Expand Down Expand Up @@ -83,6 +83,10 @@ pub struct Csrf {
http_only: bool,
same_site: Option<SameSite>,
ttl: Duration,
// Using Arc<Cow<'static, _>> here because the path is most likely going
// to be a static str, and if it's not, we don't want to have to copy it
// into every endpoint.
path: Arc<Cow<'static, str>>,
}

impl Default for Csrf {
Expand All @@ -94,6 +98,7 @@ impl Default for Csrf {
http_only: true,
same_site: Some(SameSite::Strict),
ttl: Duration::from_secs(24 * 60 * 60),
path: Arc::new(Cow::Borrowed("/")),
}
}
}
Expand Down Expand Up @@ -147,6 +152,17 @@ impl Csrf {
}
}

/// Set the path for which the CSRF cookie should be set.
///
/// By default, this is `"/"`.
#[must_use]
pub fn path(self, value: impl Into<Cow<'static, str>>) -> Self {
Self {
path: Arc::new(value.into()),
..self
}
}

/// Sets the protection ttl. This will be used for both the cookie
/// expiry and the time window over which CSRF tokens are considered
/// valid.
Expand All @@ -170,6 +186,7 @@ impl<E: Endpoint> Middleware<E> for Csrf {
http_only: self.http_only,
same_site: self.same_site,
ttl: self.ttl,
path: Arc::clone(&self.path),
})
}
}
Expand All @@ -184,6 +201,7 @@ pub struct CsrfEndpoint<E> {
http_only: bool,
same_site: Option<SameSite>,
ttl: Duration,
path: Arc<Cow<'static, str>>,
}

impl<E> CsrfEndpoint<E> {
Expand Down Expand Up @@ -226,6 +244,7 @@ impl<E: Endpoint> Endpoint for CsrfEndpoint<E> {
cookie.set_http_only(self.http_only);
cookie.set_same_site(self.same_site);
cookie.set_max_age(self.ttl);
cookie.set_path(&**self.path);
cookie
};

Expand Down
Loading