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
//! The session backend using Cookie as a session storage.
//!
//! # Example
//!
//! ```
//! #[macro_use]
//! extern crate finchers;
//! extern crate finchers_session;
//!
//! use finchers::prelude::*;
//! use finchers_session::Session;
//! use finchers_session::cookie::CookieSession;
//!
//! # fn main() {
//! let backend = finchers_session::cookie::plain();
//!
//! let endpoint = path!(@get /)
//!     .and(backend)
//!     .and_then(|session: Session<CookieSession>| {
//!         session.with(|_session| {
//!             // ...
//! #           Ok("done")
//!         })
//!     });
//! # drop(move || finchers::server::start(endpoint).serve("127.0.0.1:4000"));
//! # }
//! ```

extern crate cookie;

use finchers::endpoint::{ApplyContext, ApplyResult, Endpoint};
use finchers::error::Error;
use finchers::input::Input;

#[cfg(feature = "secure")]
use self::cookie::Key;
use self::cookie::{Cookie, SameSite};
use futures::future;
use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;
use time::Duration;

use session::{RawSession, Session};
use util::BuilderExt;

// TODOs:
// * add support for setting whether to compress data

/// Create a `CookieSessionBackend` without signing and encryption.
///
/// This function is equivalent to `CookieSessionBackend::plain()`.
pub fn plain() -> CookieBackend {
    CookieBackend::plain()
}

/// Create a `CookieSessionBackend` with signing
/// (requires `feature = "secure"`).
///
/// This function is equivalent to `CookieSessionBackend::signed(Key::from_master(key.as_ref()))`.
#[cfg(feature = "secure")]
pub fn signed(master: impl AsRef<[u8]>) -> CookieBackend {
    CookieBackend::signed(Key::from_master(master.as_ref()))
}

/// Create a `CookieSessionBackend` with encryption
/// (requires `feature = "secure"`).
///
/// This function is equivalent to `CookieSessionBackend::private(Key::from_master(key.as_ref()))`.
#[cfg(feature = "secure")]
pub fn private(master: impl AsRef<[u8]>) -> CookieBackend {
    CookieBackend::private(Key::from_master(master.as_ref()))
}

enum Security {
    Plain,
    #[cfg(feature = "secure")]
    Signed(Key),
    #[cfg(feature = "secure")]
    Private(Key),
}

impl fmt::Debug for Security {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Security::Plain => f.debug_tuple("Plain").finish(),
            #[cfg(feature = "secure")]
            Security::Signed(..) => f.debug_tuple("Signed").finish(),
            #[cfg(feature = "secure")]
            Security::Private(..) => f.debug_tuple("Private").finish(),
        }
    }
}

#[derive(Debug)]
struct CookieConfig {
    security: Security,
    name: String,
    path: Cow<'static, str>,
    secure: bool,
    http_only: bool,
    domain: Option<Cow<'static, str>>,
    same_site: Option<SameSite>,
    max_age: Option<Duration>,
}

impl CookieConfig {
    fn read_value(&self, input: &mut Input) -> Result<Option<String>, Error> {
        let jar = input.cookies()?;
        let cookie = match self.security {
            Security::Plain => jar.get(&self.name).cloned(),
            #[cfg(feature = "secure")]
            Security::Signed(ref key) => jar.signed(key).get(&self.name),
            #[cfg(feature = "secure")]
            Security::Private(ref key) => jar.private(key).get(&self.name),
        };

        match cookie {
            Some(cookie) => Ok(Some(cookie.value().to_string())),
            None => Ok(None),
        }
    }

    fn write_value(&self, input: &mut Input, value: String) -> Result<(), Error> {
        let cookie = Cookie::build(self.name.clone(), value)
            .path(self.path.clone())
            .secure(self.secure)
            .http_only(self.http_only)
            .if_some(self.domain.clone(), |cookie, value| cookie.domain(value))
            .if_some(self.same_site, |cookie, value| cookie.same_site(value))
            .if_some(self.max_age, |cookie, value| cookie.max_age(value))
            .finish();

        let jar = input.cookies()?;
        match self.security {
            Security::Plain => jar.add(cookie),
            #[cfg(feature = "secure")]
            Security::Signed(ref key) => jar.signed(key).add(cookie),
            #[cfg(feature = "secure")]
            Security::Private(ref key) => jar.private(key).add(cookie),
        }

        Ok(())
    }

    fn remove_value(&self, input: &mut Input) -> Result<(), Error> {
        let cookie = Cookie::named(self.name.clone());
        let jar = input.cookies()?;
        match self.security {
            Security::Plain => jar.remove(cookie),
            #[cfg(feature = "secure")]
            Security::Signed(ref key) => jar.signed(key).remove(cookie),
            #[cfg(feature = "secure")]
            Security::Private(ref key) => jar.private(key).remove(cookie),
        }
        Ok(())
    }
}

#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub struct CookieBackend {
    config: Arc<CookieConfig>,
}

impl CookieBackend {
    fn new(security: Security) -> CookieBackend {
        CookieBackend {
            config: Arc::new(CookieConfig {
                security,
                name: "finchers-session".into(),
                path: "/".into(),
                domain: None,
                same_site: None,
                max_age: None,
                secure: true,
                http_only: true,
            }),
        }
    }

    /// Creates a `CookieSessionBackend` which stores the Cookie values as a raw form.
    pub fn plain() -> CookieBackend {
        CookieBackend::new(Security::Plain)
    }

    /// Creates a `CookieSessionBackend` which signs the Cookie values with the specified secret key.
    ///
    /// This method is only available if the feature flag `secure` is set.
    #[cfg(feature = "secure")]
    pub fn signed(key: Key) -> CookieBackend {
        CookieBackend::new(Security::Signed(key))
    }

    /// Creates a `CookieSessionBackend` which encrypts the Cookie values with the specified secret key.
    ///
    /// This method is only available if the feature flag `secure` is set.
    #[cfg(feature = "secure")]
    pub fn private(key: Key) -> CookieBackend {
        CookieBackend::new(Security::Private(key))
    }

    fn config_mut(&mut self) -> &mut CookieConfig {
        Arc::get_mut(&mut self.config).expect("The instance has already shared.")
    }

    /// Sets the path of Cookie entry.
    ///
    /// The default value is `"/"`.
    pub fn path(mut self, value: impl Into<Cow<'static, str>>) -> CookieBackend {
        self.config_mut().path = value.into();
        self
    }

    /// Sets the value of `secure` in Cookie entry.
    ///
    /// The default value is `true`.
    pub fn secure(mut self, value: bool) -> CookieBackend {
        self.config_mut().secure = value;
        self
    }

    /// Sets the value of `http_only` in Cookie entry.
    ///
    /// The default value is `true`.
    pub fn http_only(mut self, value: bool) -> CookieBackend {
        self.config_mut().http_only = value;
        self
    }

    /// Sets the value of `domain` in Cookie entry.
    ///
    /// The default value is `None`.
    pub fn domain(mut self, value: impl Into<Cow<'static, str>>) -> CookieBackend {
        self.config_mut().domain = Some(value.into());
        self
    }

    /// Sets the value of `same_site` in Cookie entry.
    ///
    /// The default value is `None`.
    pub fn same_site(mut self, value: SameSite) -> CookieBackend {
        self.config_mut().same_site = Some(value);
        self
    }

    /// Sets the value of `max_age` in Cookie entry.
    ///
    /// The default value is `None`.
    pub fn max_age(mut self, value: Duration) -> CookieBackend {
        self.config_mut().max_age = Some(value);
        self
    }
}

impl<'a> Endpoint<'a> for CookieBackend {
    type Output = (Session<CookieSession>,);
    type Future = future::FutureResult<Self::Output, Error>;

    fn apply(&self, cx: &mut ApplyContext<'_>) -> ApplyResult<Self::Future> {
        Ok(future::result(self.config.read_value(cx.input()).map(
            |value| {
                (Session::new(CookieSession {
                    config: self.config.clone(),
                    value,
                }),)
            },
        )))
    }
}

#[allow(missing_docs)]
#[derive(Debug)]
pub struct CookieSession {
    config: Arc<CookieConfig>,
    value: Option<String>,
}

impl CookieSession {
    fn write_impl(self, input: &mut Input) -> Result<(), Error> {
        if let Some(value) = self.value {
            self.config.write_value(input, value)
        } else {
            self.config.remove_value(input)
        }
    }
}

impl RawSession for CookieSession {
    type WriteFuture = future::FutureResult<(), Error>;

    fn get(&self) -> Option<&str> {
        self.value.as_ref().map(|s| s.as_str())
    }

    fn set(&mut self, value: String) {
        self.value = Some(value);
    }

    fn remove(&mut self) {
        self.value = None;
    }

    fn write(self, input: &mut Input) -> Self::WriteFuture {
        future::result(self.write_impl(input))
    }
}