webgates-sessions 1.0.0

Framework-agnostic session lifecycle and renewal primitives for webgates.
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
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
//! Session domain types.
//!
//! This module contains the framework-agnostic session model used by issuance,
//! renewal, revocation, and repository orchestration.

use std::time::SystemTime;

use uuid::Uuid;

/// Unique identifier for a single session record.
///
/// # Examples
///
/// ```
/// use webgates_sessions::session::SessionId;
///
/// let id = SessionId::new();
/// let uuid = id.into_uuid();
/// let restored = SessionId::from_uuid(uuid);
/// assert_eq!(restored.into_uuid(), uuid);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SessionId(Uuid);

impl SessionId {
    /// Creates a new session identifier.
    #[must_use]
    pub fn new() -> Self {
        Self(Uuid::now_v7())
    }

    /// Creates a session identifier from an existing UUID.
    #[must_use]
    pub fn from_uuid(value: Uuid) -> Self {
        Self(value)
    }

    /// Returns the underlying UUID value.
    #[must_use]
    pub fn into_uuid(self) -> Uuid {
        self.0
    }
}

impl Default for SessionId {
    fn default() -> Self {
        Self::new()
    }
}

/// Unique identifier for a session family.
///
/// A session family groups related sessions so higher-level logic can revoke
/// them together when replay or broader logout behavior requires it.
///
/// # Examples
///
/// ```
/// use webgates_sessions::session::SessionFamilyId;
///
/// let family_id = SessionFamilyId::new();
/// let uuid = family_id.into_uuid();
/// let restored = SessionFamilyId::from_uuid(uuid);
/// assert_eq!(restored.into_uuid(), uuid);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SessionFamilyId(Uuid);

impl SessionFamilyId {
    /// Creates a new session-family identifier.
    #[must_use]
    pub fn new() -> Self {
        Self(Uuid::now_v7())
    }

    /// Creates a session-family identifier from an existing UUID.
    #[must_use]
    pub fn from_uuid(value: Uuid) -> Self {
        Self(value)
    }

    /// Returns the underlying UUID value.
    #[must_use]
    pub fn into_uuid(self) -> Uuid {
        self.0
    }
}

impl Default for SessionFamilyId {
    fn default() -> Self {
        Self::new()
    }
}

/// Persisted session state tracked by the session layer.
///
/// This is the canonical framework-agnostic session record used by repository
/// contracts and higher-level renewal services.
///
/// # Examples
///
/// ```
/// use std::time::{Duration, SystemTime};
/// use webgates_sessions::session::{Session, SessionFamilyId};
///
/// let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
/// let session = Session::new(
///     SessionFamilyId::new(),
///     "user-42",
///     now,
///     now + Duration::from_secs(3_600),
/// );
///
/// assert_eq!(session.subject_id, "user-42");
/// assert!(session.is_active_at(now));
/// assert!(!session.is_expired_at(now));
///
/// let revoked = session.revoked();
/// assert!(!revoked.is_active_at(now));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Session {
    /// Stable session identifier.
    pub session_id: SessionId,
    /// Owning session family identifier.
    pub family_id: SessionFamilyId,
    /// Stable subject identifier that owns the session.
    pub subject_id: String,
    /// Creation timestamp for the session.
    pub created_at: SystemTime,
    /// Expiration timestamp for the session.
    pub expires_at: SystemTime,
    /// Last observed activity timestamp for the session.
    pub last_seen_at: Option<SystemTime>,
    /// Whether the session is currently revoked.
    pub revoked: bool,
}

impl Session {
    /// Creates a new active session record.
    #[must_use]
    pub fn new(
        family_id: SessionFamilyId,
        subject_id: impl Into<String>,
        created_at: SystemTime,
        expires_at: SystemTime,
    ) -> Self {
        Self {
            session_id: SessionId::new(),
            family_id,
            subject_id: subject_id.into(),
            created_at,
            expires_at,
            last_seen_at: None,
            revoked: false,
        }
    }

    /// Returns a copy of the session with an updated `last_seen_at` value.
    #[must_use]
    pub fn touched(mut self, last_seen_at: SystemTime) -> Self {
        self.last_seen_at = Some(last_seen_at);
        self
    }

    /// Returns a copy of the session marked as revoked.
    #[must_use]
    pub fn revoked(mut self) -> Self {
        self.revoked = true;
        self
    }

    /// Returns `true` when the session is active at `now`.
    #[must_use]
    pub fn is_active_at(&self, now: SystemTime) -> bool {
        !self.revoked && self.expires_at > now
    }

    /// Returns `true` when the session has expired at `now`.
    #[must_use]
    pub fn is_expired_at(&self, now: SystemTime) -> bool {
        self.expires_at <= now
    }
}

/// Canonical repository-facing session record.
///
/// Repository interfaces use this alias when they operate on persisted session
/// records.
pub type SessionRecord = Session;

/// Repository-facing summary of a session family.
///
/// This view captures the minimum metadata needed for family-wide revocation and
/// replay handling.
///
/// # Examples
///
/// ```
/// use std::time::{Duration, SystemTime};
/// use webgates_sessions::session::{SessionFamilyId, SessionFamilyRecord};
///
/// let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
/// let family = SessionFamilyRecord::new(SessionFamilyId::new(), "user-42", now);
///
/// assert!(family.is_active());
///
/// let revoked = family.revoked();
/// assert!(!revoked.is_active());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionFamilyRecord {
    /// Stable family identifier.
    pub family_id: SessionFamilyId,
    /// Stable subject identifier that owns the family.
    pub subject_id: String,
    /// Creation timestamp for the family.
    pub created_at: SystemTime,
    /// Whether the full family has been revoked.
    pub revoked: bool,
}

impl SessionFamilyRecord {
    /// Creates a new active session-family record.
    #[must_use]
    pub fn new(
        family_id: SessionFamilyId,
        subject_id: impl Into<String>,
        created_at: SystemTime,
    ) -> Self {
        Self {
            family_id,
            subject_id: subject_id.into(),
            created_at,
            revoked: false,
        }
    }

    /// Returns a copy of the family marked as revoked.
    #[must_use]
    pub fn revoked(mut self) -> Self {
        self.revoked = true;
        self
    }

    /// Returns `true` when the family is still active.
    #[must_use]
    pub fn is_active(&self) -> bool {
        !self.revoked
    }
}

/// Repository-facing record for the currently active refresh token of a session.
///
/// # Examples
///
/// ```
/// use std::time::{Duration, SystemTime};
/// use webgates_sessions::session::{SessionFamilyId, SessionId, SessionRefreshRecord};
///
/// let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
/// let expires_at = now + Duration::from_secs(3_600);
/// let refresh = SessionRefreshRecord::new(SessionId::new(), SessionFamilyId::new(), expires_at);
///
/// assert!(refresh.is_active_at(now));
/// assert!(!refresh.is_expired_at(now));
///
/// let revoked = refresh.revoked();
/// assert!(!revoked.is_active_at(now));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionRefreshRecord {
    /// Session that owns the refresh token.
    pub session_id: SessionId,
    /// Session family that owns the refresh token.
    pub family_id: SessionFamilyId,
    /// Timestamp when the current refresh token expires.
    pub expires_at: SystemTime,
    /// Whether the refresh token is currently revoked.
    pub revoked: bool,
}

impl SessionRefreshRecord {
    /// Creates a new active refresh-token record.
    #[must_use]
    pub fn new(session_id: SessionId, family_id: SessionFamilyId, expires_at: SystemTime) -> Self {
        Self {
            session_id,
            family_id,
            expires_at,
            revoked: false,
        }
    }

    /// Returns a copy of the refresh-token record marked as revoked.
    #[must_use]
    pub fn revoked(mut self) -> Self {
        self.revoked = true;
        self
    }

    /// Returns `true` when the refresh token is active at `now`.
    #[must_use]
    pub fn is_active_at(&self, now: SystemTime) -> bool {
        !self.revoked && self.expires_at > now
    }

    /// Returns `true` when the refresh token has expired at `now`.
    #[must_use]
    pub fn is_expired_at(&self, now: SystemTime) -> bool {
        self.expires_at <= now
    }
}

/// Combined repository lookup result used when locating session state by a
/// refresh token hash.
///
/// # Examples
///
/// ```
/// use std::time::{Duration, SystemTime};
/// use webgates_sessions::session::{
///     Session, SessionFamilyId, SessionFamilyRecord, SessionLookup, SessionRefreshRecord,
/// };
///
/// let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
/// let family = SessionFamilyRecord::new(SessionFamilyId::new(), "user-42", now);
/// let session = Session::new(
///     family.family_id,
///     "user-42",
///     now,
///     now + Duration::from_secs(3_600),
/// );
/// let refresh = SessionRefreshRecord::new(
///     session.session_id,
///     family.family_id,
///     now + Duration::from_secs(3_600),
/// );
///
/// let lookup = SessionLookup::new(session, family, refresh);
/// assert!(lookup.is_active_at(now));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionLookup {
    /// Session matched by the lookup.
    pub session: SessionRecord,
    /// Session family that owns the matched session.
    pub family: SessionFamilyRecord,
    /// Current refresh-token record for the matched session.
    pub refresh: SessionRefreshRecord,
}

impl SessionLookup {
    /// Creates a new combined session lookup result.
    #[must_use]
    pub fn new(
        session: SessionRecord,
        family: SessionFamilyRecord,
        refresh: SessionRefreshRecord,
    ) -> Self {
        Self {
            session,
            family,
            refresh,
        }
    }

    /// Returns `true` when all looked-up state is currently active at `now`.
    #[must_use]
    pub fn is_active_at(&self, now: SystemTime) -> bool {
        self.session.is_active_at(now) && self.family.is_active() && self.refresh.is_active_at(now)
    }
}

/// Input used to record session activity updates.
///
/// # Examples
///
/// ```
/// use std::time::{Duration, SystemTime};
/// use webgates_sessions::session::{SessionId, SessionTouch};
///
/// let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
/// let touch = SessionTouch::new(SessionId::new(), now);
///
/// assert_eq!(touch.last_seen_at, now);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionTouch {
    /// Session to update.
    pub session_id: SessionId,
    /// New activity timestamp to persist.
    pub last_seen_at: SystemTime,
}

impl SessionTouch {
    /// Creates a new session-touch input.
    #[must_use]
    pub fn new(session_id: SessionId, last_seen_at: SystemTime) -> Self {
        Self {
            session_id,
            last_seen_at,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Session, SessionFamilyId, SessionFamilyRecord, SessionLookup, SessionRefreshRecord,
        SessionTouch,
    };
    use std::time::{Duration, SystemTime};

    #[test]
    fn new_session_is_active_and_not_revoked() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let session = Session::new(
            SessionFamilyId::new(),
            "user-123",
            now,
            now + Duration::from_secs(60),
        );

        assert!(!session.revoked);
        assert!(session.last_seen_at.is_none());
        assert!(session.is_active_at(now));
        assert!(!session.is_expired_at(now));
    }

    #[test]
    fn touched_session_updates_last_seen() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let touched_at = now + Duration::from_secs(10);
        let session = Session::new(
            SessionFamilyId::new(),
            "user-123",
            now,
            now + Duration::from_secs(60),
        )
        .touched(touched_at);

        assert_eq!(session.last_seen_at, Some(touched_at));
    }

    #[test]
    fn revoked_session_is_not_active() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let session = Session::new(
            SessionFamilyId::new(),
            "user-123",
            now,
            now + Duration::from_secs(60),
        )
        .revoked();

        assert!(session.revoked);
        assert!(!session.is_active_at(now));
    }

    #[test]
    fn expired_session_reports_expired() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let session = Session::new(
            SessionFamilyId::new(),
            "user-123",
            now,
            now + Duration::from_secs(1),
        );

        assert!(session.is_expired_at(now + Duration::from_secs(1)));
        assert!(!session.is_active_at(now + Duration::from_secs(1)));
    }

    #[test]
    fn family_record_reports_activity_state() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let active_family = SessionFamilyRecord::new(SessionFamilyId::new(), "user-123", now);
        let revoked_family = active_family.clone().revoked();

        assert!(active_family.is_active());
        assert!(!revoked_family.is_active());
    }

    #[test]
    fn refresh_record_reports_activity_state() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let refresh = SessionRefreshRecord::new(
            super::SessionId::new(),
            SessionFamilyId::new(),
            now + Duration::from_secs(60),
        );
        let revoked = refresh.clone().revoked();

        assert!(refresh.is_active_at(now));
        assert!(!refresh.is_expired_at(now));
        assert!(!revoked.is_active_at(now));
    }

    #[test]
    fn lookup_is_active_only_when_all_components_are_active() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let family = SessionFamilyRecord::new(SessionFamilyId::new(), "user-123", now);
        let session = Session::new(
            family.family_id,
            "user-123",
            now,
            now + Duration::from_secs(60),
        );
        let refresh = SessionRefreshRecord::new(
            session.session_id,
            family.family_id,
            now + Duration::from_secs(60),
        );

        let lookup = SessionLookup::new(session.clone(), family.clone(), refresh.clone());
        let revoked_lookup = SessionLookup::new(session.revoked(), family, refresh);

        assert!(lookup.is_active_at(now));
        assert!(!revoked_lookup.is_active_at(now));
    }

    #[test]
    fn session_touch_captures_target_and_timestamp() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let touch = SessionTouch::new(super::SessionId::new(), now);

        assert_eq!(touch.last_seen_at, now);
    }
}