actix_session/storage/
session_key.rs

1use derive_more::derive::{Display, From};
2
3/// A session key, the string stored in a client-side cookie to associate a user with its session
4/// state on the backend.
5///
6/// # Validation
7/// Session keys are stored as cookies, therefore they cannot be arbitrary long. Session keys are
8/// required to be smaller than 4064 bytes.
9///
10/// ```
11/// use actix_session::storage::SessionKey;
12///
13/// let key: String = std::iter::repeat('a').take(4065).collect();
14/// let session_key: Result<SessionKey, _> = key.try_into();
15/// assert!(session_key.is_err());
16/// ```
17#[derive(Debug, PartialEq, Eq)]
18pub struct SessionKey(String);
19
20impl TryFrom<String> for SessionKey {
21    type Error = InvalidSessionKeyError;
22
23    fn try_from(val: String) -> Result<Self, Self::Error> {
24        if val.len() > 4064 {
25            return Err(anyhow::anyhow!(
26                "The session key is bigger than 4064 bytes, the upper limit on cookie content."
27            )
28            .into());
29        }
30
31        Ok(SessionKey(val))
32    }
33}
34
35impl AsRef<str> for SessionKey {
36    fn as_ref(&self) -> &str {
37        &self.0
38    }
39}
40
41impl From<SessionKey> for String {
42    fn from(key: SessionKey) -> Self {
43        key.0
44    }
45}
46
47#[derive(Debug, Display, From)]
48#[display("The provided string is not a valid session key")]
49pub struct InvalidSessionKeyError(anyhow::Error);
50
51impl std::error::Error for InvalidSessionKeyError {
52    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
53        Some(self.0.as_ref())
54    }
55}