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
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! The `[oidc]` and `[session]` sections every console embeds in its
//! configuration.
//!
//! Both are read with `deny_unknown_fields`, every default lives in the
//! section's `Default`, and every secret is a
//! `ferrohealth_secret::secret::Secret` read inline or from the file its
//! `<key>_file` sibling names. [`OidcSection::check`] and
//! [`SessionSection::check`] refuse a section the console cannot run with,
//! naming the key and never the secret.

use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use base64::Engine as _;
use ferrohealth_secret::file::{SecretError, read_secret, require_secret};
use ferrohealth_secret::secret::Secret;
use ferrohealth_smart::client::{Reach, Tls, TlsVersion};
use ferrohealth_smart::metadata::{DiscoveryError, Http, ServerMetadata};
use ferrohealth_smart::oidc::{OFFLINE_ACCESS, OPENID, OidcError, Provider, RelyingParty};
use secrecy::SecretSlice;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::lifetime::Lifetimes;

/// The fewest bytes a sealing key decodes to: the 512 bits the `cookie`
/// crate's `Key` derives its signing and encryption halves from.
pub const KEY_BYTES: usize = 64;

/// Why a section was refused, or the provider could not be reached.
///
/// No variant carries a secret.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// A secret could not be read.
    #[error(transparent)]
    Secret(#[from] SecretError),
    /// A required key is empty.
    #[error("{key} is not set")]
    Missing {
        /// The key.
        key: &'static str,
    },
    /// A key is not a URL.
    #[error("{key} is not a URL")]
    Url {
        /// The key.
        key: &'static str,
        /// What the parser said.
        #[source]
        source: url::ParseError,
    },
    /// A URL is not one its key admits: a provider URL that is not `https`
    /// off loopback, or a redirection endpoint with userinfo or a fragment.
    #[error("{key} {reason}")]
    UrlShape {
        /// The key.
        key: &'static str,
        /// What the key requires.
        reason: &'static str,
    },
    /// `scopes` lacks `openid` (OpenID Connect Core 1.0 §3.1.2.1).
    #[error("oidc.scopes must hold openid")]
    NoOpenId,
    /// `scopes` lists `offline_access`, which `offline_access = true` asks
    /// for (OpenID Connect Core 1.0 §11).
    #[error("oidc.scopes must not list offline_access; set oidc.offline_access = true")]
    OfflineAccessScope,
    /// A lifetime or a bound is zero.
    #[error("{key} must be greater than zero")]
    Zero {
        /// The key.
        key: &'static str,
    },
    /// The absolute lifetime is shorter than the idle one.
    #[error("session.absolute_timeout_s must be at least session.idle_timeout_s")]
    AbsoluteBeforeIdle,
    /// A sealed store has no key.
    #[error("session.store = \"sealed\" needs session.key or session.key_file")]
    NoKey,
    /// A key is set for a store that seals nothing.
    #[error("session.key is set, but session.store = \"memory\" seals nothing")]
    KeyUnused,
    /// The sealing key is not base64.
    #[error("session.key is not base64")]
    KeyBase64 {
        /// What the decoder said.
        #[source]
        source: base64::DecodeError,
    },
    /// The sealing key decodes to too few bytes.
    #[error("session.key decodes to {found} bytes; it needs at least {KEY_BYTES}")]
    KeyShort {
        /// How many bytes it decodes to.
        found: usize,
    },
    /// A sealed store with `offline_access`, which would put a refresh
    /// token in a browser cookie.
    #[error("oidc.offline_access cannot be used with session.store = \"sealed\"")]
    OfflineAccessSealed,
    /// The trust roots of `oidc.ca_file` could not be read.
    #[error("oidc.ca_file names {}, which could not be read", path.display())]
    CaFile {
        /// The file.
        path: PathBuf,
        /// What the file system said.
        #[source]
        source: std::io::Error,
    },
    /// An `oidc.resolve` entry is not `host=ip:port`.
    #[error("oidc.resolve entry {index} must be host=ip:port")]
    Resolve {
        /// The entry's position, from zero.
        index: usize,
    },
    /// `oidc.tls` names a client certificate without its key, or a key
    /// without its certificate.
    #[error("oidc.tls.client_certificate and oidc.tls.client_key must be set together")]
    ClientIdentityHalf,
    /// The client certificate of `oidc.tls.client_certificate` could not be
    /// read.
    #[error("oidc.tls.client_certificate names {}, which could not be read", path.display())]
    ClientCertificate {
        /// The file.
        path: PathBuf,
        /// What the file system said.
        #[source]
        source: std::io::Error,
    },
    /// The HTTP engine could not be built.
    #[error("the OpenID Provider's client could not be built")]
    Http(#[source] DiscoveryError),
    /// The provider's metadata could not be read or names no endpoint the
    /// sign-in needs.
    #[error("the OpenID Provider could not be read")]
    Provider(#[source] OidcError),
}

/// `[oidc]`: the console's client at its OpenID Provider.
///
/// With `issuer` alone, the endpoints are discovered (RFC 8414 §3, OpenID
/// Connect Discovery 1.0 §4); each endpoint given here takes the place of
/// the discovered one.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct OidcSection {
    /// The provider's issuer identifier, which an ID Token's `iss` must
    /// equal exactly (OpenID Connect Core 1.0 §3.1.3.7).
    pub issuer: String,
    /// The authorization endpoint (RFC 6749 §3.1).
    pub authorization_endpoint: Option<String>,
    /// The token endpoint (RFC 6749 §3.2).
    pub token_endpoint: Option<String>,
    /// The JWK Set of the keys that sign the ID Tokens.
    pub jwks_uri: Option<String>,
    /// The end-session endpoint (OpenID Connect RP-Initiated Logout 1.0 §2).
    pub end_session_endpoint: Option<String>,
    /// The revocation endpoint (RFC 7009 §2).
    pub revocation_endpoint: Option<String>,
    /// The console's client identifier (RFC 6749 §2.2).
    pub client_id: String,
    /// The console's client secret, inline, for a confidential client.
    pub client_secret: Option<Secret>,
    /// A file holding the console's client secret.
    pub client_secret_file: Option<PathBuf>,
    /// The redirection endpoint, the console's `/auth/callback`
    /// (RFC 6749 §3.1.2).
    pub redirect_uri: String,
    /// Where the provider sends the operator after a sign-out.
    pub post_logout_redirect_uri: Option<String>,
    /// The scopes requested, `openid` among them.
    pub scopes: Vec<String>,
    /// Whether the sign-in asks for `offline_access` (OpenID Connect Core
    /// 1.0 §11), so the provider issues a refresh token.
    pub offline_access: bool,
    /// PEM trust roots added to the platform's for a provider behind a
    /// private certificate authority.
    pub ca_file: Option<PathBuf>,
    /// Provider hosts reached at a fixed address in place of resolving
    /// their names, each `host=ip:port`, for a provider whose name resolves
    /// only inside a private network. The URL's port and the certificate
    /// check against the host name stay as the URL names them.
    pub resolve: Vec<String>,
    /// `[oidc.tls]`: the client certificate and the TLS floor of the
    /// provider connection.
    pub tls: OidcTlsSection,
    /// How long one call to the provider may take, in seconds.
    pub timeout_s: u64,
}

/// `[oidc.tls]`: the client certificate the console presents to its
/// provider (RFC 8705 §2) and the lowest TLS version it negotiates.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct OidcTlsSection {
    /// The PEM client certificate chain, set together with `client_key`.
    pub client_certificate: Option<PathBuf>,
    /// The PEM private key of the client certificate, inline.
    pub client_key: Option<Secret>,
    /// A file holding the private key of the client certificate.
    pub client_key_file: Option<PathBuf>,
    /// The lowest TLS version of the provider connection, `"1.2"` or
    /// `"1.3"`.
    pub min_version: TlsVersion,
}

impl Default for OidcSection {
    fn default() -> Self {
        Self {
            issuer: String::new(),
            authorization_endpoint: None,
            token_endpoint: None,
            jwks_uri: None,
            end_session_endpoint: None,
            revocation_endpoint: None,
            client_id: String::new(),
            client_secret: None,
            client_secret_file: None,
            redirect_uri: String::new(),
            post_logout_redirect_uri: None,
            scopes: vec![String::from(OPENID)],
            offline_access: false,
            ca_file: None,
            resolve: Vec::new(),
            tls: OidcTlsSection::default(),
            timeout_s: 10,
        }
    }
}

/// The checked `[oidc]`.
#[derive(Clone)]
pub struct OidcSettings {
    issuer: String,
    endpoints: ServerMetadata,
    client_id: String,
    client_secret: Option<Secret>,
    redirect_uri: Url,
    post_logout_redirect_uri: Option<Url>,
    scopes: Vec<String>,
    offline_access: bool,
    roots: Option<Vec<u8>>,
    identity: Option<Arc<SecretSlice<u8>>>,
    reach: Reach,
    timeout: Duration,
}

impl fmt::Debug for OidcSettings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OidcSettings")
            .field("issuer", &self.issuer)
            .field("client_id", &self.client_id)
            .field("redirect_uri", &self.redirect_uri.as_str())
            .field("scopes", &self.scopes)
            .field("offline_access", &self.offline_access)
            .finish_non_exhaustive()
    }
}

impl OidcSection {
    /// Checks the section and reads its secret and its trust roots.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::Missing`] for an empty `issuer`, `client_id`
    /// or `redirect_uri`, [`ConfigError::Url`] for a value that is not a
    /// URL, [`ConfigError::UrlShape`] for a provider URL that is not `https`
    /// off loopback or a redirection endpoint that is no `http` or `https`
    /// URL with a host, no userinfo and no fragment,
    /// [`ConfigError::NoOpenId`] and [`ConfigError::OfflineAccessScope`] for
    /// `scopes` without `openid` or with `offline_access`,
    /// [`ConfigError::Zero`] for a zero `timeout_s`,
    /// [`ConfigError::Resolve`] for a `resolve` entry that is not
    /// `host=ip:port`, [`ConfigError::ClientIdentityHalf`] for a client
    /// certificate without its key or a key without its certificate, and the
    /// errors of reading `client_secret`, `ca_file`, the client certificate
    /// and its key.
    pub fn check(&self) -> Result<OidcSettings, ConfigError> {
        let issuer = required("oidc.issuer", &self.issuer)?;
        provider_url("oidc.issuer", issuer)?;
        let client_id = required("oidc.client_id", &self.client_id)?;
        let redirect_uri = web_url(
            "oidc.redirect_uri",
            required("oidc.redirect_uri", &self.redirect_uri)?,
        )?;
        // NOTE: RFC 6749 §3.1.2: the redirection endpoint URI MUST NOT include a fragment
        // component.
        if redirect_uri.fragment().is_some() {
            return Err(ConfigError::UrlShape {
                key: "oidc.redirect_uri",
                reason: "must not carry a fragment",
            });
        }
        // NOTE: OpenID Connect Core 1.0 §3.1.2.1: an OpenID Connect request MUST carry the
        // `openid` scope value.
        if !self.scopes.iter().any(|scope| scope == OPENID) {
            return Err(ConfigError::NoOpenId);
        }
        // NOTE: OpenID Connect Core 1.0 §11: `offline_access` goes with `prompt=consent`,
        // which the relying party sends only for `offline_access = true`.
        if self.scopes.iter().any(|scope| scope == OFFLINE_ACCESS) {
            return Err(ConfigError::OfflineAccessScope);
        }
        let endpoints = ServerMetadata {
            issuer: issuer.to_owned(),
            authorization_endpoint: endpoint(
                "oidc.authorization_endpoint",
                self.authorization_endpoint.as_deref(),
            )?,
            token_endpoint: endpoint("oidc.token_endpoint", self.token_endpoint.as_deref())?,
            jwks_uri: endpoint("oidc.jwks_uri", self.jwks_uri.as_deref())?,
            end_session_endpoint: endpoint(
                "oidc.end_session_endpoint",
                self.end_session_endpoint.as_deref(),
            )?,
            revocation_endpoint: endpoint(
                "oidc.revocation_endpoint",
                self.revocation_endpoint.as_deref(),
            )?,
            ..ServerMetadata::default()
        };
        let post_logout_redirect_uri = self
            .post_logout_redirect_uri
            .as_deref()
            .map(|value| web_url("oidc.post_logout_redirect_uri", value))
            .transpose()?;
        if self.timeout_s == 0 {
            return Err(ConfigError::Zero {
                key: "oidc.timeout_s",
            });
        }
        let client_secret = read_secret(
            "oidc.client_secret",
            self.client_secret.clone(),
            self.client_secret_file.as_deref(),
        )?;
        let roots = self.ca_file.as_deref().map(read_roots).transpose()?;
        let identity = self.tls.identity()?;
        let mut reach = Reach::default().with_min_tls_version(self.tls.min_version);
        for (index, entry) in self.resolve.iter().enumerate() {
            let (host, address) = resolve_entry(entry).ok_or(ConfigError::Resolve { index })?;
            reach = reach.with_resolve(host, address);
        }
        Ok(OidcSettings {
            issuer: issuer.to_owned(),
            endpoints,
            client_id: client_id.to_owned(),
            client_secret,
            redirect_uri,
            post_logout_redirect_uri,
            scopes: self.scopes.clone(),
            offline_access: self.offline_access,
            roots,
            identity,
            reach,
            timeout: Duration::from_secs(self.timeout_s),
        })
    }
}

impl OidcSettings {
    /// Whether the sign-in asks for a refresh token.
    #[must_use]
    pub const fn offline_access(&self) -> bool {
        self.offline_access
    }

    /// The console's relying party at the provider, its endpoints discovered
    /// unless the section names the three the sign-in needs.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::Http`] when the client cannot be built and
    /// [`ConfigError::Provider`] when discovery fails or the metadata names
    /// no authorization, token or key-set endpoint.
    pub async fn relying_party(&self) -> Result<RelyingParty, ConfigError> {
        let tls = Tls {
            root_certificates: self.roots.clone(),
            identity: self.identity.clone(),
        };
        let http = Http::reaching(self.timeout, &tls, &self.reach).map_err(ConfigError::Http)?;
        let given = &self.endpoints;
        let complete = given.authorization_endpoint.is_some()
            && given.token_endpoint.is_some()
            && given.jwks_uri.is_some();
        let metadata = if complete {
            given.clone()
        } else {
            let found = http
                .discover(&self.issuer)
                .await
                .map_err(|error| ConfigError::Provider(OidcError::Discovery(error)))?;
            ServerMetadata {
                authorization_endpoint: given
                    .authorization_endpoint
                    .clone()
                    .or(found.authorization_endpoint.clone()),
                token_endpoint: given
                    .token_endpoint
                    .clone()
                    .or(found.token_endpoint.clone()),
                jwks_uri: given.jwks_uri.clone().or(found.jwks_uri.clone()),
                end_session_endpoint: given
                    .end_session_endpoint
                    .clone()
                    .or(found.end_session_endpoint.clone()),
                revocation_endpoint: given
                    .revocation_endpoint
                    .clone()
                    .or(found.revocation_endpoint.clone()),
                ..found
            }
        };
        let provider = Provider::from_metadata(&metadata).map_err(ConfigError::Provider)?;
        let mut party = RelyingParty::new(
            http,
            provider,
            self.client_id.clone(),
            self.redirect_uri.clone(),
        )
        .with_scopes(self.scopes.iter().cloned());
        if let Some(secret) = &self.client_secret {
            party = party.with_client_secret(secret.to_secret_string());
        }
        if self.offline_access {
            party = party.with_offline_access();
        }
        if let Some(redirect) = &self.post_logout_redirect_uri {
            party = party.with_post_logout_redirect_uri(redirect.clone());
        }
        Ok(party)
    }
}

/// Where a console keeps its sessions.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum StoreKind {
    /// In the console's process, bounded; the cookie carries an opaque id.
    #[default]
    Memory,
    /// In one AES-256-GCM sealed cookie, which every instance holding the
    /// key opens.
    Sealed,
}

/// `[session]`: the store and the lifetimes of the console's sessions.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct SessionSection {
    /// Where the sessions are kept.
    pub store: StoreKind,
    /// Whether the cookies carry `Secure`, and with it the `__Host-` prefix.
    pub secure_cookie: bool,
    /// How long a pending sign-in waits for the provider's redirect back.
    pub sign_in_timeout_s: u64,
    /// How many pending sign-ins a `memory` store holds; past it the oldest
    /// is dropped.
    pub max_sign_ins: usize,
    /// How long a session lives with no request that counts as activity.
    pub idle_timeout_s: u64,
    /// How long a session lives from its sign-in, whatever the activity.
    pub absolute_timeout_s: u64,
    /// How many sessions a `memory` store holds; past it a new one is
    /// refused.
    pub max_sessions: usize,
    /// The sealing key of a `sealed` store, inline: base64 of at least 64
    /// bytes, the same on every instance.
    pub key: Option<Secret>,
    /// A file holding the sealing key.
    pub key_file: Option<PathBuf>,
}

impl Default for SessionSection {
    fn default() -> Self {
        Self {
            store: StoreKind::Memory,
            secure_cookie: true,
            sign_in_timeout_s: 300,
            max_sign_ins: 1000,
            idle_timeout_s: 1800,
            absolute_timeout_s: 43_200,
            max_sessions: 10_000,
            key: None,
            key_file: None,
        }
    }
}

/// The store a checked `[session]` names.
#[derive(Clone)]
pub(crate) enum Storage {
    /// In process, with its two bounds.
    Memory {
        /// Pending sign-ins.
        max_sign_ins: usize,
        /// Sessions.
        max_sessions: usize,
    },
    /// Sealed, with its key.
    Sealed(cookie::Key),
}

/// The checked `[session]`.
#[derive(Clone)]
pub struct SessionSettings {
    pub(crate) storage: Storage,
    pub(crate) secure_cookie: bool,
    pub(crate) sign_in_timeout: Duration,
    pub(crate) lifetimes: Lifetimes,
}

impl fmt::Debug for SessionSettings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let store = match self.storage {
            Storage::Memory { .. } => StoreKind::Memory,
            Storage::Sealed(_) => StoreKind::Sealed,
        };
        f.debug_struct("SessionSettings")
            .field("store", &store)
            .field("secure_cookie", &self.secure_cookie)
            .field("sign_in_timeout", &self.sign_in_timeout)
            .field("lifetimes", &self.lifetimes)
            .finish_non_exhaustive()
    }
}

impl SessionSettings {
    /// The lifetimes of every session.
    #[must_use]
    pub const fn lifetimes(&self) -> Lifetimes {
        self.lifetimes
    }

    /// Whether the cookies carry `Secure` and the `__Host-` prefix.
    #[must_use]
    pub const fn secure_cookie(&self) -> bool {
        self.secure_cookie
    }
}

impl SessionSection {
    /// Checks the section against the console's checked `[oidc]` and reads
    /// its key.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::Zero`] for a zero lifetime or bound,
    /// [`ConfigError::AbsoluteBeforeIdle`] for an absolute lifetime shorter
    /// than the idle one, [`ConfigError::NoKey`], [`ConfigError::KeyBase64`]
    /// or [`ConfigError::KeyShort`] for a sealed store's missing or unusable
    /// key, [`ConfigError::KeyUnused`] for a key beside a memory store, and
    /// [`ConfigError::OfflineAccessSealed`] for a sealed store whose sign-in
    /// asks for a refresh token.
    pub fn check(&self, oidc: &OidcSettings) -> Result<SessionSettings, ConfigError> {
        self.check_with(oidc.offline_access())
    }

    /// [`Self::check`] for a console whose sign-in asks for a refresh token
    /// when `offline_access` holds, the configuration having no `[oidc]` of
    /// its own (a sign-in the console checks itself).
    ///
    /// # Errors
    ///
    /// The errors of [`Self::check`].
    pub fn check_with(&self, offline_access: bool) -> Result<SessionSettings, ConfigError> {
        for (key, value) in [
            ("session.sign_in_timeout_s", self.sign_in_timeout_s),
            ("session.idle_timeout_s", self.idle_timeout_s),
            ("session.absolute_timeout_s", self.absolute_timeout_s),
        ] {
            if value == 0 {
                return Err(ConfigError::Zero { key });
            }
        }
        if self.absolute_timeout_s < self.idle_timeout_s {
            return Err(ConfigError::AbsoluteBeforeIdle);
        }
        let storage = match self.store {
            StoreKind::Memory => {
                if self.key.is_some() || self.key_file.is_some() {
                    return Err(ConfigError::KeyUnused);
                }
                for (key, value) in [
                    ("session.max_sign_ins", self.max_sign_ins),
                    ("session.max_sessions", self.max_sessions),
                ] {
                    if value == 0 {
                        return Err(ConfigError::Zero { key });
                    }
                }
                Storage::Memory {
                    max_sign_ins: self.max_sign_ins,
                    max_sessions: self.max_sessions,
                }
            }
            StoreKind::Sealed => {
                // NOTE: RFC 6749 §10.4: a refresh token is kept confidential, and one sealed into
                // a browser cookie outlives a sign-out that cannot reach that cookie.
                if offline_access {
                    return Err(ConfigError::OfflineAccessSealed);
                }
                let secret: Secret =
                    match require_secret("session.key", self.key.clone(), self.key_file.as_deref())
                    {
                        Ok(secret) => secret,
                        Err(SecretError::Missing { .. }) => return Err(ConfigError::NoKey),
                        Err(error) => return Err(error.into()),
                    };
                Storage::Sealed(sealing_key(&secret)?)
            }
        };
        Ok(SessionSettings {
            storage,
            secure_cookie: self.secure_cookie,
            sign_in_timeout: Duration::from_secs(self.sign_in_timeout_s),
            lifetimes: Lifetimes {
                idle: Duration::from_secs(self.idle_timeout_s),
                absolute: Duration::from_secs(self.absolute_timeout_s),
            },
        })
    }
}

/// The key `secret` decodes to.
fn sealing_key(secret: &Secret) -> Result<cookie::Key, ConfigError> {
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(secret.expose().trim())
        .map_err(|source| ConfigError::KeyBase64 { source })?;
    cookie::Key::try_from(bytes.as_slice())
        .map_err(|_short| ConfigError::KeyShort { found: bytes.len() })
}

/// `value` of `key`, refused when empty.
fn required<'a>(key: &'static str, value: &'a str) -> Result<&'a str, ConfigError> {
    let value = value.trim();
    if value.is_empty() {
        Err(ConfigError::Missing { key })
    } else {
        Ok(value)
    }
}

/// `value` of `key` as a URL.
fn url(key: &'static str, value: &str) -> Result<Url, ConfigError> {
    Url::parse(value).map_err(|source| ConfigError::Url { key, source })
}

/// An optional provider endpoint, checked as [`provider_url`] and kept as
/// written.
fn endpoint(key: &'static str, value: Option<&str>) -> Result<Option<String>, ConfigError> {
    value
        .map(|text| provider_url(key, text).map(|_| text.to_owned()))
        .transpose()
}

/// `value` of `key` as an `http` or `https` URL with a host and no userinfo.
fn web_url(key: &'static str, value: &str) -> Result<Url, ConfigError> {
    let parsed = url(key, value)?;
    let shape = |reason| Err(ConfigError::UrlShape { key, reason });
    if !matches!(parsed.scheme(), "http" | "https") {
        return shape("must be an http or https URL");
    }
    if parsed.host().is_none() {
        return shape("must name a host");
    }
    if !parsed.username().is_empty() || parsed.password().is_some() {
        return shape("must not carry userinfo");
    }
    Ok(parsed)
}

/// `value` of `key` as a provider URL: `https`, or `http` on a loopback host.
fn provider_url(key: &'static str, value: &str) -> Result<Url, ConfigError> {
    let parsed = web_url(key, value)?;
    // NOTE: RFC 6749 §3.1: the authorization server MUST require TLS at its authorization
    // endpoint, so plain `http` is admitted only on loopback.
    if parsed.scheme() == "https" || is_loopback(&parsed) {
        Ok(parsed)
    } else {
        Err(ConfigError::UrlShape {
            key,
            reason: "must be an https URL unless its host is loopback",
        })
    }
}

/// Whether `url` names a loopback host: `localhost`, `127.0.0.0/8` or `::1`.
fn is_loopback(url: &Url) -> bool {
    match url.host() {
        Some(url::Host::Domain(name)) => name == "localhost",
        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
        None => false,
    }
}

/// The PEM trust roots in `path`.
impl OidcTlsSection {
    /// The client certificate chain and its key as one PEM document, when
    /// both are set.
    fn identity(&self) -> Result<Option<Arc<SecretSlice<u8>>>, ConfigError> {
        let key = read_secret(
            "oidc.tls.client_key",
            self.client_key.clone(),
            self.client_key_file.as_deref(),
        )?;
        match (&self.client_certificate, key) {
            (None, None) => Ok(None),
            (Some(path), Some(key)) => {
                let mut pem =
                    std::fs::read(path).map_err(|source| ConfigError::ClientCertificate {
                        path: path.clone(),
                        source,
                    })?;
                pem.push(b'\n');
                pem.extend_from_slice(key.expose().as_bytes());
                Ok(Some(Arc::new(SecretSlice::from(pem))))
            }
            _ => Err(ConfigError::ClientIdentityHalf),
        }
    }
}

/// The host and the address of one `resolve` entry, `host=ip:port`.
fn resolve_entry(entry: &str) -> Option<(String, SocketAddr)> {
    let (host, address) = entry.split_once('=')?;
    let host = host.trim();
    if host.is_empty() {
        return None;
    }
    let address = address.trim().parse().ok()?;
    Some((host.to_ascii_lowercase(), address))
}

fn read_roots(path: &Path) -> Result<Vec<u8>, ConfigError> {
    std::fs::read(path).map_err(|source| ConfigError::CaFile {
        path: path.to_path_buf(),
        source,
    })
}

#[cfg(test)]
mod tests {
    use base64::Engine as _;
    use ferrohealth_secret::secret::Secret;

    use ferrohealth_smart::oidc::{OFFLINE_ACCESS, OPENID};

    use super::{ConfigError, OidcSection, OidcTlsSection, SessionSection, StoreKind};

    fn key(bytes: usize) -> Secret {
        let mut raw = vec![0_u8; bytes];
        aws_lc_rs::rand::fill(&mut raw).expect("the random source works");
        Secret::new(base64::engine::general_purpose::STANDARD.encode(raw))
    }

    fn sealed() -> SessionSection {
        SessionSection {
            store: StoreKind::Sealed,
            key: Some(key(64)),
            ..SessionSection::default()
        }
    }

    #[test]
    fn the_sections_refuse_an_unknown_key() {
        let refused = toml::from_str::<SessionSection>("idle_minutes = 5");
        assert!(refused.is_err(), "deny_unknown_fields");
        let refused = toml::from_str::<OidcSection>("issuer = \"x\"\nclient = \"y\"");
        assert!(refused.is_err(), "deny_unknown_fields");
    }

    #[test]
    fn the_defaults_are_a_memory_store_with_secure_cookies() {
        let section: SessionSection = toml::from_str("").expect("all defaults");
        let settings = section.check_with(false).expect("valid");
        assert!(settings.secure_cookie(), "Secure by default");
        assert_eq!(1800, settings.lifetimes().idle.as_secs(), "idle");
        assert_eq!(43_200, settings.lifetimes().absolute.as_secs(), "absolute");
    }

    #[test]
    fn an_absolute_lifetime_shorter_than_the_idle_one_is_refused() {
        let section = SessionSection {
            absolute_timeout_s: 10,
            idle_timeout_s: 20,
            ..SessionSection::default()
        };
        assert!(matches!(
            section.check_with(false),
            Err(ConfigError::AbsoluteBeforeIdle)
        ));
    }

    #[test]
    fn a_sealed_store_refuses_offline_access_when_it_loads() {
        assert!(matches!(
            sealed().check_with(true),
            Err(ConfigError::OfflineAccessSealed)
        ));
        assert!(sealed().check_with(false).is_ok(), "without offline_access");
    }

    #[test]
    fn a_sealed_store_without_a_usable_key_is_refused() {
        let none = SessionSection {
            key: None,
            ..sealed()
        };
        assert!(matches!(none.check_with(false), Err(ConfigError::NoKey)));
        let short = SessionSection {
            key: Some(key(32)),
            ..sealed()
        };
        assert!(matches!(
            short.check_with(false),
            Err(ConfigError::KeyShort { found: 32 })
        ));
        let garbled = SessionSection {
            key: Some(Secret::new("not base64 !")),
            ..sealed()
        };
        assert!(matches!(
            garbled.check_with(false),
            Err(ConfigError::KeyBase64 { .. })
        ));
    }

    #[test]
    fn a_key_beside_a_memory_store_is_refused() {
        let section = SessionSection {
            key: Some(key(64)),
            ..SessionSection::default()
        };
        assert!(matches!(
            section.check_with(false),
            Err(ConfigError::KeyUnused)
        ));
    }

    #[test]
    fn no_secret_reaches_a_debug_rendering_or_an_error() {
        let section = sealed();
        let shown = format!(
            "{section:?} {:?}",
            section.check_with(false).expect("valid")
        );
        let raw = section.key.as_ref().expect("set").expose().to_owned();
        assert!(!shown.contains(&raw), "{shown}");
        let oidc = OidcSection {
            issuer: String::from("https://idp.example.org"),
            client_id: String::from("console"),
            client_secret: Some(Secret::new("synthetic-client-secret")),
            redirect_uri: String::from("https://console.example.org/auth/callback"),
            ..OidcSection::default()
        };
        let shown = format!("{oidc:?} {:?}", oidc.check().expect("valid"));
        assert!(!shown.contains("synthetic-client-secret"), "{shown}");
    }

    fn oidc() -> OidcSection {
        OidcSection {
            issuer: String::from("https://idp.example.org"),
            client_id: String::from("console"),
            redirect_uri: String::from("https://console.example.org/auth/callback"),
            ..OidcSection::default()
        }
    }

    #[test]
    fn a_provider_url_off_loopback_must_be_https() {
        assert!(oidc().check().is_ok(), "https");
        for (key, section) in [
            (
                "oidc.issuer",
                OidcSection {
                    issuer: String::from("http://idp.example.org"),
                    ..oidc()
                },
            ),
            (
                "oidc.token_endpoint",
                OidcSection {
                    token_endpoint: Some(String::from("http://idp.example.org/token")),
                    ..oidc()
                },
            ),
            (
                "oidc.revocation_endpoint",
                OidcSection {
                    revocation_endpoint: Some(String::from("http://idp.example.org/revoke")),
                    ..oidc()
                },
            ),
        ] {
            let refused = section.check();
            assert!(
                matches!(refused, Err(ConfigError::UrlShape { key: named, .. }) if named == key),
                "{key}: {refused:?}"
            );
        }
        let loopback = OidcSection {
            issuer: String::from("http://127.0.0.1:8081/realm"),
            jwks_uri: Some(String::from("http://localhost:8081/jwks")),
            ..oidc()
        };
        assert!(loopback.check().is_ok(), "plain http on loopback");
    }

    #[test]
    fn a_redirect_with_a_fragment_or_userinfo_is_refused() {
        for redirect in [
            "https://console.example.org/auth/callback#x",
            "https://u:p@console.example.org/auth/callback",
            "ftp://console.example.org/auth/callback",
        ] {
            let refused = OidcSection {
                redirect_uri: String::from(redirect),
                ..oidc()
            }
            .check();
            assert!(
                matches!(
                    refused,
                    Err(ConfigError::UrlShape {
                        key: "oidc.redirect_uri",
                        ..
                    })
                ),
                "{redirect}: {refused:?}"
            );
        }
    }

    #[test]
    fn the_scopes_hold_openid_and_never_offline_access() {
        let refused = OidcSection {
            scopes: vec![String::from("profile")],
            ..oidc()
        }
        .check();
        assert!(matches!(refused, Err(ConfigError::NoOpenId)), "{refused:?}");
        let refused = OidcSection {
            scopes: vec![String::from(OPENID), String::from(OFFLINE_ACCESS)],
            ..oidc()
        }
        .check();
        assert!(
            matches!(refused, Err(ConfigError::OfflineAccessScope)),
            "{refused:?}"
        );
        let asked = OidcSection {
            offline_access: true,
            ..oidc()
        };
        assert!(asked.check().is_ok(), "offline_access = true asks for it");
    }

    #[test]
    fn an_oidc_section_needs_an_issuer_a_client_and_a_redirect() {
        let refused = OidcSection::default().check();
        assert!(
            matches!(refused, Err(ConfigError::Missing { key: "oidc.issuer" })),
            "{refused:?}"
        );
        let refused = OidcSection {
            issuer: String::from("https://idp.example.org"),
            client_id: String::from("console"),
            redirect_uri: String::from("not a url"),
            ..OidcSection::default()
        }
        .check();
        assert!(
            matches!(
                refused,
                Err(ConfigError::Url {
                    key: "oidc.redirect_uri",
                    ..
                })
            ),
            "{refused:?}"
        );
    }

    #[test]
    fn resolve_entries_name_a_host_and_its_address() {
        let section: OidcSection = toml::from_str(
            "issuer = \"https://keycloak:8443/realms/console\"\n\
             client_id = \"console\"\n\
             redirect_uri = \"https://console.example.org/auth/callback\"\n\
             resolve = [\"Keycloak = 127.0.0.1:8443\"]\n\
             [tls]\nmin_version = \"1.3\"\n",
        )
        .expect("the section reads");
        let settings = section.check().expect("valid");
        assert_eq!(
            settings.reach.resolve(),
            [(
                String::from("keycloak"),
                "127.0.0.1:8443".parse().expect("an address")
            )]
        );
        assert_eq!(
            settings.reach.min_tls_version(),
            ferrohealth_smart::client::TlsVersion::Tls13
        );
        assert!(
            toml::from_str::<OidcSection>("[tls]\nmin_version = \"1.1\"").is_err(),
            "no floor below TLS 1.2"
        );
        for (index, entry) in [
            "keycloak",
            "=127.0.0.1:8443",
            "keycloak=localhost:8443",
            "keycloak=127.0.0.1",
        ]
        .into_iter()
        .enumerate()
        {
            let refused = OidcSection {
                resolve: vec![String::from("idp.example.org=127.0.0.1:443"); index]
                    .into_iter()
                    .chain([entry.to_owned()])
                    .collect(),
                ..oidc()
            }
            .check();
            assert!(
                matches!(refused, Err(ConfigError::Resolve { index: found }) if found == index),
                "{entry}: {refused:?}"
            );
        }
    }

    #[test]
    fn a_client_certificate_is_set_with_its_key() {
        let dir = tempfile::tempdir().expect("a directory");
        let certificate = dir.path().join("client.pem");
        std::fs::write(&certificate, "synthetic certificate").expect("written");
        let key = Secret::new("synthetic-client-key");
        let both = OidcSection {
            tls: OidcTlsSection {
                client_certificate: Some(certificate.clone()),
                client_key: Some(key.clone()),
                ..OidcTlsSection::default()
            },
            ..oidc()
        };
        let settings = both.check().expect("valid");
        assert!(settings.identity.is_some(), "the identity is read");
        let shown = format!("{both:?} {settings:?}");
        assert!(!shown.contains("synthetic-client-key"), "{shown}");

        for tls in [
            OidcTlsSection {
                client_certificate: Some(certificate.clone()),
                ..OidcTlsSection::default()
            },
            OidcTlsSection {
                client_key: Some(key.clone()),
                ..OidcTlsSection::default()
            },
        ] {
            let refused = OidcSection { tls, ..oidc() }.check();
            assert!(
                matches!(refused, Err(ConfigError::ClientIdentityHalf)),
                "{refused:?}"
            );
        }
        let refused = OidcSection {
            tls: OidcTlsSection {
                client_certificate: Some(dir.path().join("absent.pem")),
                client_key: Some(key),
                ..OidcTlsSection::default()
            },
            ..oidc()
        }
        .check();
        assert!(
            matches!(refused, Err(ConfigError::ClientCertificate { .. })),
            "{refused:?}"
        );
    }
}