coil-runtime 0.1.1

HTTP runtime and request handling for the Coil framework.
Documentation
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
use super::*;
use coil_core::BrowserSecurityError;

mod flash;
mod host;
mod live;
mod session;
mod support;
#[cfg(test)]
mod testing;
#[cfg(not(test))]
pub(crate) use live::live_shared_runtime;
#[cfg(test)]
pub(crate) use testing::test_only_sqlite_shared_runtime;

pub use flash::{FlashLevel, FlashMessage};
pub use host::{BrowserHost, BrowserHostBuildError, ResolvedBrowserRequest, RuntimeBrowserError};
pub use session::{
    BrowserInstant, BrowserSessionRecord, BrowserSessionStatus, DistributedSessionStoreClient,
    DistributedSessionStoreRuntime, IssuedBrowserSession, RotatedBrowserSession,
    SessionIssueRequest, SessionStoreBackendKind,
};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{HttpMethod, RequestInput};
    use coil_core::{
        BrowserSecurityServices, CookiePolicy, CookieProtection, CsrfProtection,
        SessionSecurityServices, SessionStoreTopology,
    };
    use std::sync::Arc;
    use std::time::Duration;

    fn services(store: SessionStoreTopology) -> BrowserSecurityServices {
        BrowserSecurityServices {
            sessions: SessionSecurityServices {
                store,
                idle_timeout: Duration::from_secs(300),
                absolute_timeout: Duration::from_secs(3600),
                session_cookie: CookiePolicy {
                    name: "session".to_string(),
                    domain: None,
                    path: "/".to_string(),
                    same_site: coil_config::SameSitePolicy::Lax,
                    secure: true,
                    http_only: true,
                    protection: CookieProtection::Signed,
                },
                flash_cookie: CookiePolicy {
                    name: "flash".to_string(),
                    domain: None,
                    path: "/".to_string(),
                    same_site: coil_config::SameSitePolicy::Lax,
                    secure: true,
                    http_only: true,
                    protection: CookieProtection::Signed,
                },
            },
            csrf: CsrfProtection {
                enabled: true,
                field_name: "_csrf".to_string(),
                header_name: "x-csrf-token".to_string(),
            },
        }
    }

    #[test]
    fn database_session_hosts_share_scoped_backend_by_default() {
        let services = services(SessionStoreTopology::Database);
        let mut left = BrowserHost::new_with_scope(
            "browser-db-shared".to_string(),
            services.clone(),
            "browser-db-shared",
        )
        .unwrap();
        let right = BrowserHost::new_with_scope(
            "browser-db-shared".to_string(),
            services,
            "browser-db-shared",
        )
        .unwrap();

        let issued = left
            .issue_session(
                SessionIssueRequest::new()
                    .for_principal("member-db")
                    .unwrap(),
                b"01234567012345670123456701234567",
                BrowserInstant::from_unix_seconds(100),
            )
            .unwrap();

        assert_eq!(left.session_store_kind(), SessionStoreBackendKind::Database);
        assert!(left.session_store_is_shared());
        assert_eq!(
            right
                .session(&issued.record.session_id)
                .unwrap()
                .and_then(|record| record.principal_id),
            Some("member-db".to_string())
        );
    }

    #[test]
    fn database_session_hosts_share_backend_when_reusing_an_explicit_client() {
        let services = services(SessionStoreTopology::Database);
        let client =
            DistributedSessionStoreClient::local_for_testing(SessionStoreBackendKind::Database);
        let mut left = BrowserHost::with_session_store_client(
            "browser-db-shared".to_string(),
            services.clone(),
            client.clone(),
        )
        .unwrap();
        let right = BrowserHost::with_session_store_client(
            "browser-db-shared".to_string(),
            services,
            client,
        )
        .unwrap();

        let issued = left
            .issue_session(
                SessionIssueRequest::new()
                    .for_principal("member-db")
                    .unwrap(),
                b"01234567012345670123456701234567",
                BrowserInstant::from_unix_seconds(100),
            )
            .unwrap();

        assert_eq!(left.session_store_kind(), SessionStoreBackendKind::Database);
        assert!(left.session_store_is_shared());
        assert_eq!(
            right
                .session(&issued.record.session_id)
                .unwrap()
                .and_then(|record| record.principal_id),
            Some("member-db".to_string())
        );
    }

    #[test]
    fn database_session_hosts_share_explicit_backend_across_independent_clients() {
        let services = services(SessionStoreTopology::Database);
        let client =
            DistributedSessionStoreClient::local_for_testing(SessionStoreBackendKind::Database);
        let mut left = BrowserHost::with_session_store_client(
            "browser-db-shared".to_string(),
            services.clone(),
            client.clone(),
        )
        .unwrap();
        let right = BrowserHost::with_session_store_client(
            "browser-db-shared".to_string(),
            services,
            client,
        )
        .unwrap();

        let issued = left
            .issue_session(
                SessionIssueRequest::new()
                    .for_principal("member-db")
                    .unwrap(),
                b"01234567012345670123456701234567",
                BrowserInstant::from_unix_seconds(100),
            )
            .unwrap();

        assert!(left.session_store_is_shared());
        assert_eq!(
            right
                .session(&issued.record.session_id)
                .unwrap()
                .and_then(|record| record.principal_id),
            Some("member-db".to_string())
        );
    }

    #[test]
    fn live_browser_rejects_memory_session_stores() {
        let services = services(SessionStoreTopology::Memory);
        let error =
            BrowserHost::new_with_scope("browser-memory".to_string(), services, "browser-memory")
                .unwrap_err();

        assert_eq!(
            error,
            BrowserHostBuildError::MemoryStoreRequiresTestOnlyBrowserHost
        );
    }

    #[test]
    fn live_browser_rejects_session_clients_without_explicit_shared_support() {
        #[derive(Debug)]
        struct UnconfiguredLiveSessionStoreRuntime;

        impl DistributedSessionStoreRuntime for UnconfiguredLiveSessionStoreRuntime {
            fn issue(&self, _record: BrowserSessionRecord) -> Result<(), RuntimeBrowserError> {
                Ok(())
            }

            fn session(
                &self,
                _session_id: &str,
            ) -> Result<Option<BrowserSessionRecord>, RuntimeBrowserError> {
                Ok(None)
            }

            fn delete(&self, _session_id: &str) -> Result<(), RuntimeBrowserError> {
                Ok(())
            }

            fn revoke(
                &self,
                _session_id: &str,
                _now: BrowserInstant,
            ) -> Result<(), RuntimeBrowserError> {
                Ok(())
            }

            fn touch_active_session(
                &self,
                _session_id: &str,
                _idle_timeout: Duration,
                _now: BrowserInstant,
            ) -> Result<Option<String>, RuntimeBrowserError> {
                Ok(None)
            }

            fn is_shared_backend(&self) -> bool {
                false
            }
        }

        let services = services(SessionStoreTopology::Database);
        let client = DistributedSessionStoreClient::new(
            SessionStoreBackendKind::Database,
            Arc::new(UnconfiguredLiveSessionStoreRuntime),
        );

        let error =
            BrowserHost::with_session_store_client("browser-live".to_string(), services, client)
                .unwrap_err();

        assert_eq!(
            error,
            BrowserHostBuildError::LiveSharedSessionStoreRequiresExplicitRuntime {
                kind: SessionStoreBackendKind::Database,
            }
        );
    }

    #[test]
    fn live_browser_session_client_returns_typed_runtime_errors() {
        #[derive(Debug)]
        struct RejectedLiveSessionStoreRuntime;

        impl DistributedSessionStoreRuntime for RejectedLiveSessionStoreRuntime {
            fn issue(&self, _record: BrowserSessionRecord) -> Result<(), RuntimeBrowserError> {
                Err(RuntimeBrowserError::LiveSharedSessionStoreUnavailable {
                    kind: SessionStoreBackendKind::Database,
                    scope: "browser-live".to_string(),
                })
            }

            fn session(
                &self,
                _session_id: &str,
            ) -> Result<Option<BrowserSessionRecord>, RuntimeBrowserError> {
                Err(RuntimeBrowserError::LiveSharedSessionStoreUnavailable {
                    kind: SessionStoreBackendKind::Database,
                    scope: "browser-live".to_string(),
                })
            }

            fn delete(&self, _session_id: &str) -> Result<(), RuntimeBrowserError> {
                Err(RuntimeBrowserError::LiveSharedSessionStoreUnavailable {
                    kind: SessionStoreBackendKind::Database,
                    scope: "browser-live".to_string(),
                })
            }

            fn revoke(
                &self,
                _session_id: &str,
                _now: BrowserInstant,
            ) -> Result<(), RuntimeBrowserError> {
                Err(RuntimeBrowserError::LiveSharedSessionStoreUnavailable {
                    kind: SessionStoreBackendKind::Database,
                    scope: "browser-live".to_string(),
                })
            }

            fn touch_active_session(
                &self,
                _session_id: &str,
                _idle_timeout: Duration,
                _now: BrowserInstant,
            ) -> Result<Option<String>, RuntimeBrowserError> {
                Err(RuntimeBrowserError::LiveSharedSessionStoreUnavailable {
                    kind: SessionStoreBackendKind::Database,
                    scope: "browser-live".to_string(),
                })
            }

            fn is_shared_backend(&self) -> bool {
                false
            }
        }

        let client = DistributedSessionStoreClient::new(
            SessionStoreBackendKind::Database,
            Arc::new(RejectedLiveSessionStoreRuntime),
        );

        let error = client
            .issue(BrowserSessionRecord {
                session_id: "session-1".to_string(),
                principal_id: Some("member".to_string()),
                issued_at: BrowserInstant::from_unix_seconds(1),
                last_seen_at: BrowserInstant::from_unix_seconds(1),
                idle_expires_at: BrowserInstant::from_unix_seconds(60),
                absolute_expires_at: BrowserInstant::from_unix_seconds(120),
                revoked_at: None,
            })
            .unwrap_err();

        assert_eq!(
            error,
            RuntimeBrowserError::LiveSharedSessionStoreUnavailable {
                kind: SessionStoreBackendKind::Database,
                scope: "browser-live".to_string(),
            }
        );
    }

    #[test]
    fn resolve_request_reissues_an_anonymous_session_when_cookie_state_is_missing() {
        let services = services(SessionStoreTopology::Database);
        let client =
            DistributedSessionStoreClient::local_for_testing(SessionStoreBackendKind::Database);
        let mut issuer = BrowserHost::with_session_store_client(
            "browser-db-shared".to_string(),
            services.clone(),
            client.clone(),
        )
        .unwrap();
        let mut resolver = BrowserHost::with_session_store_client(
            "browser-db-shared".to_string(),
            services,
            client,
        )
        .unwrap();
        let cookie_secret = b"01234567012345670123456701234567";
        let now = BrowserInstant::from_unix_seconds(100);
        let issued = issuer
            .issue_session(
                SessionIssueRequest::new()
                    .for_principal("member-db")
                    .unwrap(),
                cookie_secret,
                now,
            )
            .unwrap();

        issuer.sessions.delete(&issued.record.session_id).unwrap();

        let request = RequestInput::new(HttpMethod::Get, "www.example.com", "/")
            .unwrap()
            .with_session_cookie(issued.cookie_value);
        let resolved = resolver
            .resolve_request(&request, cookie_secret, now)
            .unwrap();

        assert!(resolved.session.resolved_from_cookie);
        assert!(resolved.session.session_id.is_some());
        assert_ne!(
            resolved.session.session_id.as_deref(),
            Some(issued.record.session_id.as_str())
        );
        assert_eq!(resolved.principal_id, None);
        assert_eq!(resolved.response_cookies.len(), 1);
        assert!(resolved.response_cookies[0].contains("session="));
    }

    #[test]
    fn resolve_request_rejects_expired_cookie_backed_sessions() {
        let services = services(SessionStoreTopology::Database);
        let client =
            DistributedSessionStoreClient::local_for_testing(SessionStoreBackendKind::Database);
        let mut host = BrowserHost::with_session_store_client(
            "browser-db-shared".to_string(),
            services,
            client,
        )
        .unwrap();
        let cookie_secret = b"01234567012345670123456701234567";
        let issued = host
            .issue_session(
                SessionIssueRequest::new()
                    .for_principal("member-db")
                    .unwrap(),
                cookie_secret,
                BrowserInstant::from_unix_seconds(100),
            )
            .unwrap();

        let request = RequestInput::new(HttpMethod::Get, "www.example.com", "/")
            .unwrap()
            .with_session_cookie(issued.cookie_value);
        let error = host
            .resolve_request(&request, cookie_secret, BrowserInstant::from_unix_seconds(4_000))
            .unwrap_err();

        assert_eq!(
            error,
            RuntimeBrowserError::ExpiredSession {
                session_id: issued.record.session_id,
            }
        );
    }
}