ferrohealth-session 0.4.0

The OpenID Connect sign-in and the session of the FerroHEALTH operator consoles: the authorization code flow with PKCE over ferrohealth-smart, a server-side or sealed-cookie session with idle and absolute lifetimes counted from the sign-in time, and the session-watch route
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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! What a session holds: what a completed sign-in leaves, and the view of
//! it one request reads.

use std::fmt;
use std::time::Duration;

use ferrohealth_secret::secret::Secret;
use ferrohealth_ui::view::session::Left;
use serde::{Deserialize, Serialize};

use crate::lifetime::{from_seconds, millis, seconds_down, seconds_up};

/// How a session authenticates the console's calls to its own server.
#[derive(Clone, PartialEq, Eq)]
pub enum Credential {
    /// The operator's access token, sent as a bearer token (RFC 6750 §2.1).
    Bearer(Secret),
    /// A user name and password the console checked itself, sent with HTTP
    /// Basic (RFC 7617 §2).
    Basic {
        /// The user name.
        username: String,
        /// The password.
        password: Secret,
    },
}

impl fmt::Debug for Credential {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bearer(_) => f.write_str("Bearer(..)"),
            Self::Basic { username, .. } => f
                .debug_struct("Basic")
                .field("username", username)
                .finish_non_exhaustive(),
        }
    }
}

/// What a completed sign-in leaves the session.
pub struct SignedIn {
    pub(crate) operator: Option<String>,
    pub(crate) subject: Option<String>,
    pub(crate) scopes: Vec<String>,
    pub(crate) credential: Credential,
    pub(crate) expires_in: Option<Duration>,
    pub(crate) refresh_token: Option<Secret>,
    pub(crate) id_token: Option<Secret>,
}

impl fmt::Debug for SignedIn {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SignedIn")
            .field("operator", &self.operator)
            .field("subject", &self.subject)
            .field("scopes", &self.scopes)
            .field("credential", &self.credential)
            .field("expires_in", &self.expires_in)
            .finish_non_exhaustive()
    }
}

impl SignedIn {
    /// What the relying party's completed sign-in leaves: the operator's
    /// name from the verified ID Token's `name` or `preferred_username`
    /// (OpenID Connect Core 1.0 §5.1), its `sub`, the granted scopes
    /// (RFC 6749 §5.1), the access token with its lifetime, the refresh
    /// token, and the ID Token a sign-out hints with (OpenID Connect
    /// RP-Initiated Logout 1.0 §2).
    #[must_use]
    pub fn from_oidc(signed_in: ferrohealth_smart::oidc::SignedIn) -> Self {
        Self {
            operator: signed_in.claims.display_name().map(str::to_owned),
            subject: Some(signed_in.claims.subject.clone()),
            scopes: signed_in.scopes,
            credential: Credential::Bearer(signed_in.access_token),
            expires_in: signed_in.expires_in,
            refresh_token: signed_in.refresh_token,
            id_token: Some(signed_in.id_token),
        }
    }

    /// A sign-in the console checked itself with `username` and `password`,
    /// which every call to its own server then carries.
    #[must_use]
    pub fn basic(username: impl Into<String>, password: Secret) -> Self {
        let username = username.into();
        Self {
            operator: Some(username.clone()),
            subject: None,
            scopes: Vec::new(),
            credential: Credential::Basic { username, password },
            expires_in: None,
            refresh_token: None,
            id_token: None,
        }
    }
}

/// One request's view of its live session.
#[derive(Clone)]
pub struct Session {
    pub(crate) operator: Option<String>,
    pub(crate) subject: Option<String>,
    pub(crate) scopes: Vec<String>,
    pub(crate) credential: Credential,
    pub(crate) signed_in_at: i64,
    pub(crate) left: Left,
}

impl fmt::Debug for Session {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Session")
            .field("operator", &self.operator)
            .field("scopes", &self.scopes)
            .field("credential", &self.credential)
            .field("signed_in_at", &self.signed_in_at)
            .field("left", &self.left)
            .finish_non_exhaustive()
    }
}

impl Session {
    /// The operator's name as the provider or the sign-in gave it.
    #[must_use]
    pub fn operator(&self) -> Option<&str> {
        self.operator.as_deref()
    }

    /// The `sub` of the verified ID Token, for an OpenID Connect sign-in.
    #[must_use]
    pub fn subject(&self) -> Option<&str> {
        self.subject.as_deref()
    }

    /// The scopes the provider granted, empty for a Basic sign-in.
    #[must_use]
    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }

    /// What the console's calls to its own server carry.
    #[must_use]
    pub const fn credential(&self) -> &Credential {
        &self.credential
    }

    /// When the operator signed in, in whole seconds since the Unix epoch,
    /// rounded up.
    #[must_use]
    pub const fn signed_in_at(&self) -> i64 {
        seconds_up(self.signed_in_at)
    }

    /// What the session has left as this request found it.
    #[must_use]
    pub const fn left(&self) -> Left {
        self.left
    }
}

/// What one request carries.
#[derive(Debug, Clone)]
pub enum Held {
    /// A live session.
    SignedIn(Session),
    /// A live session whose access token expired and could not yet be
    /// refreshed; the next request tries again, and its lifetimes still end
    /// it.
    TokenExpired,
    /// A cookie that names no live session.
    Ended,
    /// No session cookie.
    Absent,
}

/// What an ended session held that the provider is told about.
pub struct Ended {
    /// The ID Token of the sign-in, the hint of the end-session request.
    pub id_token: Option<Secret>,
    /// The token a revocation names, with its `token_type_hint`: the refresh
    /// token when the provider issued one, since revoking it ends its access
    /// tokens too (RFC 7009 §2.1), and the access token otherwise; `None`
    /// for a Basic sign-in.
    pub revocable: Option<(Secret, ferrohealth_smart::oidc::TokenTypeHint)>,
}

impl fmt::Debug for Ended {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Ended")
            .field("hint", &self.revocable.as_ref().map(|(_, hint)| hint))
            .finish_non_exhaustive()
    }
}

/// The session record both stores keep, with its times in milliseconds
/// since the Unix epoch.
#[derive(Clone)]
pub(crate) struct Record {
    pub(crate) operator: Option<String>,
    pub(crate) subject: Option<String>,
    pub(crate) scopes: Vec<String>,
    pub(crate) credential: Credential,
    pub(crate) expires: Option<i64>,
    pub(crate) lifetime: Option<Duration>,
    pub(crate) refresh_token: Option<Secret>,
    pub(crate) id_token: Option<Secret>,
    pub(crate) signed_in: i64,
    pub(crate) touched: i64,
}

impl Record {
    /// The record a sign-in at `now` begins.
    pub(crate) fn begin(signed_in: SignedIn, now: i64) -> Self {
        let mut record = Self {
            operator: signed_in.operator,
            subject: signed_in.subject,
            scopes: signed_in.scopes,
            credential: signed_in.credential,
            expires: None,
            lifetime: None,
            refresh_token: signed_in.refresh_token,
            id_token: signed_in.id_token,
            signed_in: now,
            touched: now,
        };
        record.token_issued(signed_in.expires_in, now);
        record
    }

    /// Counts the access token's `lifetime` from `now`, when it was issued.
    pub(crate) fn token_issued(&mut self, lifetime: Option<Duration>, now: i64) {
        self.expires = lifetime.map(|lifetime| now.saturating_add(millis(lifetime)));
        self.lifetime = lifetime;
    }

    /// The times its lifetimes are counted from.
    pub(crate) fn times(&self) -> crate::lifetime::Times {
        crate::lifetime::Times {
            signed_in: self.signed_in,
            touched: self.touched,
            last_token: if self.refresh_token.is_some() {
                None
            } else {
                self.expires
            },
        }
    }

    /// Whether the access token is still valid at `now`.
    pub(crate) fn token_valid(&self, now: i64) -> bool {
        self.expires.is_none_or(|expires| now < expires)
    }

    /// The view a request reads, with `left`.
    pub(crate) fn session(&self, left: Left) -> Session {
        Session {
            operator: self.operator.clone(),
            subject: self.subject.clone(),
            scopes: self.scopes.clone(),
            credential: self.credential.clone(),
            signed_in_at: self.signed_in,
            left,
        }
    }

    /// What the provider is told when the record ends.
    pub(crate) fn ended(self) -> Ended {
        use ferrohealth_smart::oidc::TokenTypeHint;
        let revocable = match (self.refresh_token, self.credential) {
            (Some(refresh), _) => Some((refresh, TokenTypeHint::RefreshToken)),
            (None, Credential::Bearer(access)) => Some((access, TokenTypeHint::AccessToken)),
            (None, Credential::Basic { .. }) => None,
        };
        Ended {
            id_token: self.id_token,
            revocable,
        }
    }
}

/// The record as the sealed cookie carries it. The plain strings exist only
/// between this record and the sealing, and never reach a rendering.
///
/// Its times are whole seconds since the Unix epoch, the format every
/// earlier release sealed: the sign-in and the last activity rounded up, so
/// no lifetime counted from them ends early, and the token's expiry rounded
/// down, so no expired token is sent.
#[derive(Serialize, Deserialize)]
pub(crate) struct Sealed {
    operator: Option<String>,
    subject: Option<String>,
    scopes: Vec<String>,
    bearer: Option<String>,
    basic: Option<(String, String)>,
    expires: Option<i64>,
    lifetime: Option<u64>,
    id_token: Option<String>,
    signed_in: i64,
    touched: i64,
}

impl From<&Record> for Sealed {
    fn from(record: &Record) -> Self {
        let (bearer, basic) = match &record.credential {
            Credential::Bearer(token) => (Some(token.expose().to_owned()), None),
            Credential::Basic { username, password } => {
                (None, Some((username.clone(), password.expose().to_owned())))
            }
        };
        Self {
            operator: record.operator.clone(),
            subject: record.subject.clone(),
            scopes: record.scopes.clone(),
            bearer,
            basic,
            expires: record.expires.map(seconds_down),
            lifetime: record.lifetime.map(|lifetime| lifetime.as_secs()),
            id_token: record
                .id_token
                .as_ref()
                .map(|token| token.expose().to_owned()),
            signed_in: seconds_up(record.signed_in),
            touched: seconds_up(record.touched),
        }
    }
}

impl Sealed {
    /// The record it carries; `None` for a payload that names no credential.
    pub(crate) fn record(self) -> Option<Record> {
        let credential = match (self.bearer, self.basic) {
            (Some(token), None) => Credential::Bearer(Secret::new(token)),
            (None, Some((username, password))) => Credential::Basic {
                username,
                password: Secret::new(password),
            },
            _ => return None,
        };
        Some(Record {
            operator: self.operator,
            subject: self.subject,
            scopes: self.scopes,
            credential,
            expires: self.expires.map(from_seconds),
            lifetime: self.lifetime.map(Duration::from_secs),
            refresh_token: None,
            id_token: self.id_token.map(Secret::new),
            signed_in: from_seconds(self.signed_in),
            touched: from_seconds(self.touched),
        })
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use ferrohealth_secret::secret::Secret;

    use super::{Credential, Record, Sealed, SignedIn};

    const START: i64 = 1_800_000_000;

    /// The last millisecond of the second `START`.
    const LATE: i64 = START * 1000 + 999;

    fn record() -> Record {
        Record::begin(
            SignedIn {
                operator: Some(String::from("Synthetic Operator")),
                subject: None,
                scopes: Vec::new(),
                credential: Credential::Bearer(Secret::new("synthetic-access-token")),
                expires_in: Some(Duration::from_secs(30)),
                refresh_token: None,
                id_token: None,
            },
            LATE,
        )
    }

    #[test]
    fn a_sealed_record_keeps_whole_seconds_rounded_toward_a_longer_life() {
        let sealed = serde_json::to_value(Sealed::from(&record())).expect("serialized");
        assert_eq!(
            (Some(START + 1), Some(START + 1), Some(START + 30), Some(30)),
            (
                sealed["signed_in"].as_i64(),
                sealed["touched"].as_i64(),
                sealed["expires"].as_i64(),
                sealed["lifetime"].as_u64()
            ),
            "the sign-in and activity rounded up, the token's expiry down: {sealed}"
        );
    }

    #[test]
    fn a_record_sealed_in_whole_seconds_reads_back_in_milliseconds() {
        let earlier = serde_json::json!({
            "operator": "Synthetic Operator",
            "subject": null,
            "scopes": [],
            "bearer": "synthetic-access-token",
            "basic": null,
            "expires": START + 30,
            "lifetime": 30,
            "id_token": null,
            "signed_in": START,
            "touched": START + 10
        });
        let record = serde_json::from_value::<Sealed>(earlier)
            .expect("the earlier format reads")
            .record()
            .expect("a credential");
        assert_eq!(
            (
                START * 1000,
                (START + 10) * 1000,
                Some((START + 30) * 1000),
                Some(Duration::from_secs(30))
            ),
            (
                record.signed_in,
                record.touched,
                record.expires,
                record.lifetime
            )
        );
    }
}