1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
//! Defines a session middleware with a pluggable backend.
use std::future::Future;
use std::io;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::panic::RefUnwindSafe;
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use base64::prelude::*;
use cookie::{Cookie, CookieJar};
use futures_util::future::{self, FutureExt, TryFutureExt};
use hyper::header::SET_COOKIE;
use hyper::{Body, Response, StatusCode};
use log::{error, trace, warn};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use super::cookie::CookieParser;
use super::{Middleware, NewMiddleware};
use crate::handler::{HandlerError, HandlerFuture, HandlerResult};
use crate::helpers::http::response::create_empty_response;
use crate::state::{self, FromState, State, StateData};
mod backend;
mod rng;
pub use self::backend::memory::MemoryBackend;
pub use self::backend::{Backend, GetSessionFuture, NewBackend, SetSessionFuture};
const SECURE_COOKIE_PREFIX: &str = "__Secure-";
const HOST_COOKIE_PREFIX: &str = "__Host-";
/// Represents the session identifier which is held in the user agent's session cookie.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct SessionIdentifier {
/// The value which is passed as a cookie, identifying the session.
pub value: String,
}
/// The kind of failure which occurred trying to perform a session operation.
#[derive(Debug)]
#[non_exhaustive]
pub enum SessionError {
/// The backend failed, and the included message describes the problem.
Backend(String),
/// The session was unable to be deserialized.
Deserialize,
}
enum SessionCookieState {
New,
Existing,
}
enum SessionDataState {
Clean,
Dirty,
}
#[derive(Copy, Clone, PartialEq, Debug)]
enum SameSiteEnforcement {
Disabled,
Strict,
Lax,
}
/// Configuration for how the `Set-Cookie` header is generated.
///
/// By default, the cookie has the name "_gotham_session", and the cookie header includes the
/// `secure` flag. `NewSessionMiddleware` provides functions for adjusting the
/// `SessionCookieConfig`.
#[derive(Clone, Debug)]
struct SessionCookieConfig {
// If `Expires` / `Max-Age` are ever added update `reset_session` to allow for them.
name: String,
secure: bool,
http_only: bool,
same_site: SameSiteEnforcement,
path: String,
domain: Option<String>,
}
impl Default for SessionCookieConfig {
fn default() -> SessionCookieConfig {
SessionCookieConfig {
name: "_gotham_session".to_string(),
secure: true,
http_only: true,
same_site: SameSiteEnforcement::Lax,
domain: None,
path: "/".to_string(),
}
}
}
impl SessionCookieConfig {
fn to_cookie_string(&self, value: &str) -> String {
// Ensure this is always enough to prevent re-allocs
let mut cookie_value = String::with_capacity(255);
cookie_value.push_str(&self.name);
cookie_value.push('=');
cookie_value.push_str(value);
if self.secure {
cookie_value.push_str("; Secure")
}
if self.http_only {
cookie_value.push_str("; HttpOnly")
}
match self.same_site {
SameSiteEnforcement::Strict => cookie_value.push_str("; SameSite=Strict"),
SameSiteEnforcement::Lax => cookie_value.push_str("; SameSite=Lax"),
SameSiteEnforcement::Disabled => (),
}
if let Some(ref domain) = self.domain {
cookie_value.push_str("; Domain=");
cookie_value.push_str(domain);
}
cookie_value.push_str("; Path=");
cookie_value.push_str(&self.path);
cookie_value
}
/// Validates cookie attributes if the name includes a Cookie Prefix.
/// see: https://tools.ietf.org/html/draft-west-cookie-prefixes-05
/// Returns an updated `SessionCookieConfig` with any invalid attributes overridden and emits a warning.
fn validate_prefix(self) -> SessionCookieConfig {
if self.invalid_secure_config() {
self.warn_overriding_attrs(SECURE_COOKIE_PREFIX, "Secure");
SessionCookieConfig {
secure: true,
..self
}
} else if self.invalid_host_config() {
if !self.secure {
self.warn_overriding_attrs(HOST_COOKIE_PREFIX, "Secure")
};
if self.domain.is_some() {
self.warn_overriding_attrs(HOST_COOKIE_PREFIX, "Domain")
};
if self.path != "/" {
self.warn_overriding_attrs(HOST_COOKIE_PREFIX, "Path")
};
SessionCookieConfig {
secure: true,
path: "/".to_string(),
domain: None,
..self
}
} else {
self
}
}
fn invalid_secure_config(&self) -> bool {
self.name.starts_with(SECURE_COOKIE_PREFIX) && !self.secure
}
fn invalid_host_config(&self) -> bool {
self.name.starts_with(HOST_COOKIE_PREFIX)
&& (!self.secure || self.domain.is_some() || self.path != "/")
}
fn warn_overriding_attrs(&self, prefix: &str, attribute: &str) {
warn!(
"{} prefix is used for cookie but {} attribute is not set correctly! This will be overridden. Cookie is: {:?}",
prefix, attribute, self
)
}
}
/// The wrapping type for application session data.
///
/// The application will receive a `SessionData<T>` via the `State` container, where `T` is the
/// session type given to `NewSessionMiddleware`.
///
/// ## Examples
///
/// ```rust
/// # use std::sync::Arc;
/// # use std::time::Duration;
/// # use futures_util::future::{self, FutureExt};
/// # use gotham::state::{State, FromState};
/// # use gotham::middleware::{NewMiddleware, Middleware};
/// # use gotham::middleware::session::{SessionData, NewSessionMiddleware, Backend, MemoryBackend,
/// # SessionIdentifier};
/// # use gotham::helpers::http::response::create_response;
/// # use gotham::test::TestServer;
/// # use hyper::{Body, Response, StatusCode};
/// # use hyper::header::COOKIE;
/// # use serde::{Deserialize, Serialize};
/// #[derive(Default, Deserialize, Serialize)]
/// struct MySessionType {
/// items: Vec<String>,
/// }
///
/// fn my_handler(state: State) -> (State, Response<Body>) {
/// // The `Router` has a `NewSessionMiddleware<_, MySessionType>` in a pipeline which is
/// // active for this handler.
/// let body = {
/// let session = SessionData::<MySessionType>::borrow_from(&state);
/// format!("{:?}", session.items)
/// };
///
/// let response = create_response(&state,
/// StatusCode::OK,
/// mime::TEXT_PLAIN,
/// body);
///
/// (state, response)
/// }
/// #
/// # fn main() {
/// # let backend = MemoryBackend::new(Duration::from_secs(1));
/// # let identifier = SessionIdentifier { value: "u0G6KdfckQgkV0qLANZjjNkEHBU".to_owned() };
/// #
/// # State::with_new(|state| {
/// # let session = MySessionType {
/// # items: vec!["a".into(), "b".into(), "c".into()],
/// # };
/// # let bytes = bincode::serialize(&session).unwrap();
/// # futures_executor::block_on(backend.persist_session(
/// # &state,
/// # identifier.clone(),
/// # &bytes[..]
/// # ))
/// # .unwrap();
/// # });
/// #
/// # let nm = NewSessionMiddleware::new(backend).with_session_type::<MySessionType>();
/// # let nm = Arc::new(nm);
/// #
/// # let new_handler = move || {
/// # let nm = nm.clone();
/// #
/// # let handler = move |state| {
/// # let m = nm.new_middleware().unwrap();
/// # let chain = |state| future::ok(my_handler(state)).boxed();
/// #
/// # m.call(state, chain)
/// # };
/// #
/// # Ok(handler)
/// # };
/// #
/// # let test_server = TestServer::new(new_handler).unwrap();
/// # let response = test_server
/// # .client()
/// # .get("http://localhost/")
/// # .with_header(COOKIE, format!("_gotham_session={}", identifier.value.clone()).parse().unwrap())
/// # .perform()
/// # .unwrap();
/// # let response_bytes = response.read_body().unwrap();
/// # assert_eq!(String::from_utf8(response_bytes).unwrap(),
/// # r#"["a", "b", "c"]"#);
/// # }
/// ```
pub struct SessionData<T>
where
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
value: T,
cookie_state: SessionCookieState,
state: SessionDataState,
identifier: SessionIdentifier,
backend: Box<dyn Backend + Send>,
cookie_config: Arc<SessionCookieConfig>,
}
struct SessionDropData {
cookie_config: Arc<SessionCookieConfig>,
}
impl<T> SessionData<T>
where
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
/// Discards the session, invalidating it for future use and removing the data from the
/// `Backend`.
pub fn discard(
self,
state: &mut State,
) -> Pin<Box<dyn Future<Output = Result<(), SessionError>> + Send>> {
state.put(SessionDropData {
cookie_config: self.cookie_config,
});
self.backend.drop_session(state, self.identifier)
}
// Create a new, blank `SessionData<T>`
fn new<B>(middleware: SessionMiddleware<B, T>) -> SessionData<T>
where
B: Backend + Send + 'static,
{
let state = SessionDataState::Dirty; // Always persist a new session
let cookie_state = SessionCookieState::New;
let identifier = middleware.random_identifier();
let value = T::default();
let backend = Box::new(middleware.backend);
let cookie_config = middleware.cookie_config;
trace!(
" no existing session, assigning new identifier ({})",
identifier.value
);
SessionData {
value,
cookie_state,
state,
identifier,
backend,
cookie_config,
}
}
// Load an existing, serialized session into a `SessionData<T>`
fn construct<B>(
middleware: SessionMiddleware<B, T>,
identifier: SessionIdentifier,
val: Option<Vec<u8>>,
) -> SessionData<T>
where
B: Backend + Send + 'static,
{
let cookie_state = SessionCookieState::Existing;
let state = SessionDataState::Clean;
match val {
Some(val) => {
match bincode::deserialize::<T>(&val[..]) {
Ok(value) => {
let backend = Box::new(middleware.backend);
let cookie_config = middleware.cookie_config;
trace!(
" successfully deserialized session data ({})",
identifier.value
);
SessionData {
value,
cookie_state,
state,
identifier,
backend,
cookie_config,
}
}
Err(_) => {
// This is most likely caused by the application changing their session
// struct but the backend not being purged of sessions.
warn!(
" failed to deserialize session data ({}), falling back to new session",
identifier.value
);
SessionData::new(middleware)
}
}
}
None => SessionData::new(middleware),
}
}
}
impl<T> StateData for SessionData<T> where
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static
{
}
impl<T> Deref for SessionData<T>
where
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T> DerefMut for SessionData<T>
where
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
fn deref_mut(&mut self) -> &mut T {
self.state = SessionDataState::Dirty;
&mut self.value
}
}
impl StateData for SessionDropData {}
trait SessionTypePhantom<T>: Send + Sync + RefUnwindSafe
where
T: Send,
{
}
/// Added to a `Pipeline`, this spawns the per-request `SessionMiddleware`
///
/// There are two ways to construct the `NewSessionMiddleware`, but `with_session_type` **must** be
/// called before the middleware is useful:
///
/// 1. Using the `Default` implementation, which sets up an in-memory session store. When
/// constructed this way, sessions are unable to be shared between multiple application servers,
/// and are lost on restart:
///
/// ```rust
/// # extern crate gotham;
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # fn main() {
/// NewSessionMiddleware::default()
/// # ;}
/// ```
///
/// 2. Using the `NewSessionMiddleware::new` function, and providing a backend. The `Default`
/// implementation uses `MemoryBackend`, but this can be changed by providing your own:
///
/// ```rust
/// # extern crate gotham;
/// # use gotham::middleware::session::{MemoryBackend, NewSessionMiddleware};
/// # fn main() {
/// NewSessionMiddleware::new(MemoryBackend::default())
/// # ;}
/// ```
///
/// Before the middleware can be used, it must be associated with a session type provided by the
/// application. This gives type-safe storage for all session data:
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # use serde::{Deserialize, Serialize};
/// #[derive(Default, Serialize, Deserialize)]
/// struct MySessionType {
/// items: Vec<String>,
/// }
///
/// # fn main() {
/// NewSessionMiddleware::default().with_session_type::<MySessionType>()
/// # ;}
/// ```
///
/// For plaintext HTTP servers, the `insecure` method must also be called to instruct the
/// middleware not to set the `secure` flag on the cookie.
pub struct NewSessionMiddleware<B, T>
where
B: NewBackend,
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
new_backend: B,
identifier_rng: Arc<Mutex<rng::SessionIdentifierRng>>,
cookie_config: Arc<SessionCookieConfig>,
phantom: PhantomData<dyn SessionTypePhantom<T>>,
}
/// The per-request value which provides session storage for other middleware and handlers.
///
/// See `NewSessionMiddleware` for usage details.
pub struct SessionMiddleware<B, T>
where
B: Backend,
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
backend: B,
identifier_rng: Arc<Mutex<rng::SessionIdentifierRng>>,
cookie_config: Arc<SessionCookieConfig>,
phantom: PhantomData<T>,
}
impl<B, T> NewMiddleware for NewSessionMiddleware<B, T>
where
B: NewBackend,
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
type Instance = SessionMiddleware<B::Instance, T>;
fn new_middleware(&self) -> anyhow::Result<Self::Instance> {
self.new_backend
.new_backend()
.map(|backend| SessionMiddleware {
backend,
identifier_rng: self.identifier_rng.clone(),
cookie_config: self.cookie_config.clone(),
phantom: PhantomData,
})
}
}
impl<B, T> Clone for NewSessionMiddleware<B, T>
where
B: NewBackend,
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
fn clone(&self) -> Self {
NewSessionMiddleware {
new_backend: self.new_backend.clone(),
identifier_rng: self.identifier_rng.clone(),
cookie_config: self.cookie_config.clone(),
phantom: PhantomData,
}
}
}
impl Default for NewSessionMiddleware<MemoryBackend, ()> {
fn default() -> NewSessionMiddleware<MemoryBackend, ()> {
NewSessionMiddleware::new(MemoryBackend::default())
}
}
impl<B> NewSessionMiddleware<B, ()>
where
B: NewBackend,
{
/// Create a `NewSessionMiddleware` value for the provided backend and with a blank session
/// type. `with_session_type` **must** be called before the result is useful.
pub fn new(b: B) -> NewSessionMiddleware<B, ()> {
NewSessionMiddleware {
new_backend: b,
identifier_rng: Arc::new(Mutex::new(rng::session_identifier_rng())),
cookie_config: Arc::new(SessionCookieConfig::default()),
phantom: PhantomData,
}
}
}
impl<B, T> NewSessionMiddleware<B, T>
where
B: NewBackend,
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
fn rebuild_new_session_middleware(
self,
cookie_config: SessionCookieConfig,
) -> NewSessionMiddleware<B, T> {
NewSessionMiddleware {
cookie_config: Arc::new(cookie_config.validate_prefix()),
..self
}
}
/// Configures the session cookie to be set at a more restrictive path.
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct MySessionType {
/// # items: Vec<String>,
/// # }
/// #
/// # fn main() {
/// NewSessionMiddleware::default()
/// .with_session_type::<MySessionType>()
/// .with_cookie_path("/app".to_string())
/// # ;}
/// ```
pub fn with_cookie_path<P>(self, path: P) -> NewSessionMiddleware<B, T>
where
P: AsRef<str>,
{
let cookie_config = SessionCookieConfig {
path: path.as_ref().to_owned(),
..(*self.cookie_config).clone()
};
self.rebuild_new_session_middleware(cookie_config)
}
/// Configures the `NewSessionMiddleware` not to send the `secure` flag along with the cookie.
/// This is required for plaintext HTTP connections.
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct MySessionType {
/// # items: Vec<String>,
/// # }
/// #
/// # fn main() {
/// NewSessionMiddleware::default()
/// .with_session_type::<MySessionType>()
/// .insecure()
/// # ;}
/// ```
pub fn insecure(self) -> NewSessionMiddleware<B, T> {
let cookie_config = SessionCookieConfig {
secure: false,
..(*self.cookie_config).clone()
};
self.rebuild_new_session_middleware(cookie_config)
}
/// Configures the `NewSessionMiddleware` to use an alternate cookie name. The default cookie
/// name is `_gotham_session`.
///
/// When a cookie name with a [cookie prefix][cookie-prefix] is used, the other options are
/// forced to be correct (ignoring overridden settings from the application). i.e.:
///
/// * For a cookie prefix of `__Secure-`, the cookie attributes will include `Secure`
/// * For a cookie prefix of `__Host-`, the cookie attributes will include `Secure; Path=/` and
/// not include `Domain=`
///
/// If the session cookie configuration set by the application does not match the prefix, a
/// warning will be logged upon startup and the cookie prefix options will override what was
/// provided by the application.
///
/// [cookie-prefix]: https://tools.ietf.org/html/draft-west-cookie-prefixes-05
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct MySessionType {
/// # items: Vec<String>,
/// # }
/// #
/// # fn main() {
/// NewSessionMiddleware::default()
/// .with_session_type::<MySessionType>()
/// .with_cookie_name("_myapp_session")
/// # ;}
/// ```
pub fn with_cookie_name<S>(self, name: S) -> NewSessionMiddleware<B, T>
where
S: AsRef<str>,
{
let cookie_config = SessionCookieConfig {
name: name.as_ref().to_owned(),
..(*self.cookie_config).clone()
};
self.rebuild_new_session_middleware(cookie_config)
}
/// Configures the `NewSessionMiddleware` to use a `Domain` attribute with the provided value.
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct MySessionType {
/// # items: Vec<String>,
/// # }
/// #
/// # fn main() {
/// NewSessionMiddleware::default()
/// .with_session_type::<MySessionType>()
/// .with_cookie_domain("example.com")
/// # ;}
/// ```
pub fn with_cookie_domain<S>(self, domain: S) -> NewSessionMiddleware<B, T>
where
S: AsRef<str>,
{
let cookie_config = SessionCookieConfig {
domain: Some(domain.as_ref().to_owned()),
..(*self.cookie_config).clone()
};
self.rebuild_new_session_middleware(cookie_config)
}
/// Removes the `SameSite` cookie attribute, allowing cross-site requests to include the cookie.
///
/// By default, the session cookie will be set with `SameSite=lax`, which ensures cross-site
/// requests will include the cookie if and only if they are top-level navigations which use a
/// "safe" (in the [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.2.1) sense) HTTP
/// method.
///
/// See: <https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1>
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct MySessionType {
/// # items: Vec<String>,
/// # }
/// #
/// # fn main() {
/// NewSessionMiddleware::default()
/// .with_session_type::<MySessionType>()
/// .allow_cross_site_usage()
/// # ;}
/// ```
pub fn allow_cross_site_usage(self) -> NewSessionMiddleware<B, T> {
let cookie_config = SessionCookieConfig {
same_site: SameSiteEnforcement::Disabled,
..(*self.cookie_config).clone()
};
self.rebuild_new_session_middleware(cookie_config)
}
/// Sets the "SameSite" cookie attribute value to "strict".
///
/// This will ensure that the cookie is never sent for cross-site requests (including top-level
/// navigations).
///
/// By default, the session cookie will be set with "SameSite=lax", which ensures cross-site
/// requests will include the cookie if and only if they are top-level navigations which use a
/// "safe" (in the [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.2.1) sense) HTTP
/// method.
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct MySessionType {
/// # items: Vec<String>,
/// # }
/// #
/// # fn main() {
/// NewSessionMiddleware::default()
/// .with_session_type::<MySessionType>()
/// .with_strict_same_site_enforcement()
/// # ;}
/// ```
pub fn with_strict_same_site_enforcement(self) -> NewSessionMiddleware<B, T> {
let cookie_config = SessionCookieConfig {
same_site: SameSiteEnforcement::Strict,
..(*self.cookie_config).clone()
};
self.rebuild_new_session_middleware(cookie_config)
}
/// Changes the session type to the provided type parameter. This is required to override the
/// default (unusable) session type of `()`.
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// # use serde::{Deserialize, Serialize};
/// #
/// #[derive(Default, Serialize, Deserialize)]
/// struct MySessionType {
/// items: Vec<String>,
/// }
///
/// # fn main() {
/// NewSessionMiddleware::default().with_session_type::<MySessionType>()
/// # ;}
/// ```
pub fn with_session_type<U>(self) -> NewSessionMiddleware<B, U>
where
U: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
NewSessionMiddleware {
new_backend: self.new_backend,
identifier_rng: self.identifier_rng,
cookie_config: self.cookie_config,
phantom: PhantomData,
}
}
}
impl<B, T> Middleware for SessionMiddleware<B, T>
where
B: Backend + Send + 'static,
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
where
Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static,
Self: Sized,
{
// cookies might have been parsed already by middleware
let cookies = CookieJar::try_borrow_from(&state)
.map(ToOwned::to_owned)
.unwrap_or_else(|| CookieParser::from_state(&state));
let session_identifier = cookies
.get(&self.cookie_config.name)
.map(Cookie::value)
.map(|value| SessionIdentifier {
value: value.to_owned(),
});
match session_identifier {
Some(id) => {
trace!(
"[{}] SessionIdentifier {} found in cookie from user-agent",
state::request_id(&state),
id.value
);
self.backend
.read_session(&state, id.clone())
.then(move |r| self.load_session_into_state(state, id, r))
.and_then(chain)
.and_then(persist_session::<T>)
.boxed()
}
None => {
trace!(
"[{}] No SessionIdentifier found in cookie from user-agent",
state::request_id(&state),
);
self.new_session(state)
.boxed()
.and_then(chain)
.and_then(persist_session::<T>)
.boxed()
}
}
}
}
impl<B, T> SessionMiddleware<B, T>
where
B: Backend + 'static,
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
fn random_identifier(&self) -> SessionIdentifier {
let mut bytes = [0u8; 64];
match self.identifier_rng.lock() {
Ok(mut rng) => rng.fill_bytes(&mut bytes),
Err(PoisonError { .. }) => unreachable!("identifier_rng lock poisoned. Rng panicked?"),
};
SessionIdentifier {
value: BASE64_URL_SAFE_NO_PAD.encode(&bytes[..]),
}
}
}
fn persist_session<T>(
(mut state, mut response): (State, Response<Body>),
) -> Pin<Box<dyn Future<Output = HandlerResult> + Send>>
where
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
match state.try_take::<SessionDropData>() {
Some(ref session_drop_data) => {
trace!(
"[{}] SessionDropData found in state, removing session cookie from user agent",
state::request_id(&state)
);
reset_cookie(&mut response, session_drop_data);
return Box::pin(future::ok((state, response)));
}
None => {
trace!(
"[{}] SessionDropData is not present, retaining session cookie",
state::request_id(&state)
);
}
}
match state.try_take::<SessionData<T>>() {
Some(session_data) => {
if let SessionCookieState::New = session_data.cookie_state {
send_cookie(&mut response, &session_data);
}
match session_data.state {
SessionDataState::Dirty => write_session(state, response, session_data),
SessionDataState::Clean => Box::pin(future::ok((state, response))),
}
}
// Session was discarded with `SessionData::discard`, or otherwise removed
None => Box::pin(future::ok((state, response))),
}
}
fn send_cookie<B, T>(response: &mut Response<B>, session_data: &SessionData<T>)
where
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
let cookie_string = session_data
.cookie_config
.to_cookie_string(&session_data.identifier.value);
write_cookie(cookie_string, response);
}
fn reset_cookie<B>(response: &mut Response<B>, session_drop_data: &SessionDropData) {
let cookie_string = session_drop_data
.cookie_config
.to_cookie_string("discarded");
let cookie_string = format!(
"{}; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0",
cookie_string
);
write_cookie(cookie_string, response);
}
fn write_cookie<B>(cookie: String, response: &mut Response<B>) {
response
.headers_mut()
.append(SET_COOKIE, cookie.parse().unwrap());
}
fn write_session<T>(
state: State,
response: Response<Body>,
session_data: SessionData<T>,
) -> Pin<Box<dyn Future<Output = HandlerResult> + Send>>
where
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
let bytes = match bincode::serialize(&session_data.value) {
Ok(bytes) => bytes,
Err(e) => {
error!(
"[{}] failed to serialize session: {:?}",
state::request_id(&state),
e
);
let response = create_empty_response(&state, StatusCode::INTERNAL_SERVER_ERROR);
return Box::pin(future::ok((state, response)));
}
};
let identifier = session_data.identifier;
let slice = &bytes[..];
session_data
.backend
.persist_session(&state, identifier.clone(), slice)
.then(move |result| match result {
Ok(_) => {
trace!(
"[{}] persisted session ({}) successfully",
state::request_id(&state),
identifier.value
);
future::ok((state, response))
}
Err(_) => {
let response = create_empty_response(&state, StatusCode::INTERNAL_SERVER_ERROR);
future::ok((state, response))
}
})
.boxed()
}
impl<B, T> SessionMiddleware<B, T>
where
B: Backend + 'static,
T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
fn load_session_into_state(
self,
mut state: State,
identifier: SessionIdentifier,
result: Result<Option<Vec<u8>>, SessionError>,
) -> impl Future<Output = Result<State, (State, HandlerError)>> {
match result {
Ok(v) => {
trace!(
"[{}] got response for session ({}) from backend, data located: {}",
state::request_id(&state),
identifier.value,
v.is_some()
);
let session_data = SessionData::<T>::construct(self, identifier, v);
state.put(session_data);
future::ok(state)
}
Err(e) => {
error!(
"[{}] failed to retrieve session ({}) from backend: {:?}",
state::request_id(&state),
identifier.value,
e
);
let e = io::Error::new(
io::ErrorKind::Other,
format!("backend failed to return session: {:?}", e),
);
future::err((state, e.into()))
}
}
}
fn new_session(
self,
mut state: State,
) -> impl Future<Output = Result<State, (State, HandlerError)>> {
let session_data = SessionData::<T>::new(self);
trace!(
"[{}] created new session ({})",
state::request_id(&state),
session_data.identifier.value
);
state.put(session_data);
future::ok(state)
}
}
#[cfg(test)]
mod tests {
use super::*;
use cookie::Cookie;
use hyper::header::{HeaderMap, COOKIE};
use hyper::{Response, StatusCode};
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
use std::time::Duration;
#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
struct TestSession {
val: u64,
}
#[test]
fn new_session() {
let backend = MemoryBackend::new(Duration::from_secs(1));
let nm = NewSessionMiddleware::new(backend).with_session_type::<TestSession>();
let m = nm.new_middleware().unwrap();
// Identifier generation is functioning as expected
//
// 64 -> 512 bits = (85 * 6 + 2)
// Without padding that requires 86 base64 characters to represent.
let identifier = m.random_identifier();
assert_eq!(identifier.value.len(), 86);
let identifier2 = m.random_identifier();
assert_eq!(identifier2.value.len(), 86);
assert_ne!(identifier, identifier2);
assert_eq!(&m.cookie_config.name, "_gotham_session");
assert!(m.cookie_config.secure);
assert!(m.cookie_config.http_only);
assert_eq!(m.cookie_config.same_site, SameSiteEnforcement::Lax);
assert_eq!(&m.cookie_config.path, "/");
assert!(m.cookie_config.domain.is_none());
assert_eq!(
m.cookie_config.to_cookie_string(&identifier.value),
format!(
"_gotham_session={}; Secure; HttpOnly; SameSite=Lax; Path=/",
&identifier.value
)
);
}
#[test]
fn enforce_secure_cookie_prefix_attributes() {
let backend = MemoryBackend::new(Duration::from_secs(1));
let nm = NewSessionMiddleware::new(backend)
.with_cookie_name("__Secure-my_session")
.insecure()
.with_session_type::<TestSession>();
let m = nm.new_middleware().unwrap();
assert!(m.cookie_config.secure);
}
#[test]
fn enforce_host_cookie_prefix_attributes() {
let backend = MemoryBackend::new(Duration::from_secs(1));
let nm = NewSessionMiddleware::new(backend)
.with_cookie_name("__Host-my_session")
.insecure()
.with_cookie_domain("example.com")
.with_cookie_path("/myapp")
.with_session_type::<TestSession>();
let m = nm.new_middleware().unwrap();
assert!(m.cookie_config.secure);
assert!(m.cookie_config.domain.is_none());
assert!(m.cookie_config.path == "/");
}
#[test]
fn new_session_custom_settings() {
let backend = MemoryBackend::new(Duration::from_secs(1));
let nm = NewSessionMiddleware::new(backend.clone())
.with_cookie_name("_my_session")
.with_cookie_domain("example.com")
.with_strict_same_site_enforcement()
.with_cookie_path("/myapp")
.insecure()
.with_session_type::<TestSession>();
let m = nm.new_middleware().unwrap();
let identifier = m.random_identifier();
assert_eq!(identifier.value.len(), 86);
assert_eq!(
m.cookie_config.to_cookie_string(&identifier.value),
format!(
"_my_session={}; HttpOnly; SameSite=Strict; Domain=example.com; Path=/myapp",
&identifier.value
)
);
let nm = NewSessionMiddleware::new(backend)
.with_cookie_name("x_session")
.with_cookie_path("/xapp")
.allow_cross_site_usage()
.with_session_type::<TestSession>();
let m = nm.new_middleware().unwrap();
let identifier = m.random_identifier();
assert_eq!(identifier.value.len(), 86);
assert_eq!(
m.cookie_config.to_cookie_string(&identifier.value),
format!(
"x_session={}; Secure; HttpOnly; Path=/xapp",
&identifier.value
)
);
}
#[test]
fn existing_session() {
let nm = NewSessionMiddleware::default().with_session_type::<TestSession>();
let m = nm.new_middleware().unwrap();
let mut state = State::new();
let identifier = m.random_identifier();
// 64 -> 512 bits = (85 * 6 + 2)
// Without padding that requires 86 base64 characters to represent.
assert_eq!(identifier.value.len(), 86);
let session = TestSession {
val: rand::random(),
};
let bytes = bincode::serialize(&session).unwrap();
futures_executor::block_on(
m.backend
.persist_session(&state, identifier.clone(), &bytes),
)
.unwrap();
let received: Arc<Mutex<Option<u64>>> = Arc::new(Mutex::new(None));
let r = received.clone();
let handler = move |mut state: State| {
{
let session_data = state.borrow_mut::<SessionData<TestSession>>();
*r.lock().unwrap() = Some(session_data.val);
session_data.val += 1;
}
future::ok((
state,
Response::builder()
.status(StatusCode::ACCEPTED)
.body(Body::empty())
.unwrap(),
))
.boxed()
};
let mut headers = HeaderMap::new();
let cookie = Cookie::build("_gotham_session", identifier.value.clone()).finish();
headers.insert(COOKIE, cookie.to_string().parse().unwrap());
state.put(headers);
let r = m.call(state, handler);
match futures_executor::block_on(r) {
Ok(_) => {
let guard = received.lock().unwrap();
if let Some(value) = *guard {
assert_eq!(value, session.val);
} else {
panic!("no session data");
}
}
Err((_, e)) => panic!("error: {:?}", e),
}
let state = State::new();
let m = nm.new_middleware().unwrap();
let bytes = futures_executor::block_on(m.backend.read_session(&state, identifier.clone()))
.unwrap()
.unwrap();
let updated = bincode::deserialize::<TestSession>(&bytes[..]).unwrap();
assert_eq!(updated.val, session.val + 1);
let handler = move |mut state: State| {
async move {
{
let session_data = state.take::<SessionData<TestSession>>();
session_data.discard(&mut state).await.unwrap();
}
Ok((
state,
Response::builder()
.status(StatusCode::NO_CONTENT)
.body(Body::empty())
.unwrap(),
))
}
.boxed()
};
let mut state = State::new();
let mut headers = HeaderMap::new();
let cookie = Cookie::build("_gotham_session", identifier.value.clone()).finish();
headers.insert(COOKIE, cookie.to_string().parse().unwrap());
state.put(headers);
let m = nm.new_middleware().unwrap();
let r = m.call(state, handler);
if let Err((_, e)) = futures_executor::block_on(r) {
panic!("error: {:?}", e);
}
let state = State::new();
let m = nm.new_middleware().unwrap();
let data = futures_executor::block_on(m.backend.read_session(&state, identifier)).unwrap();
assert_eq!(data, None);
}
}