sqlpage 0.43.0

Build data user interfaces entirely in SQL. A web server that takes .sql files and formats the query result using pre-made configurable professional-looking components.
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
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
use std::collections::HashSet;
use std::future::ready;
use std::rc::Rc;
use std::time::Duration;
use std::{future::Future, pin::Pin, str::FromStr, sync::Arc};
use tokio::time::Instant;

use crate::webserver::http_client::get_http_client_from_appdata;
use crate::{app_config::AppConfig, AppState};
use actix_web::http::header;
use actix_web::{
    body::BoxBody,
    cookie::Cookie,
    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
    middleware::Condition,
    web::{self, Query},
    Error, HttpMessage, HttpResponse,
};
use anyhow::{anyhow, Context};
use awc::Client;
use openidconnect::core::{
    CoreAuthDisplay, CoreAuthPrompt, CoreErrorResponseType, CoreGenderClaim, CoreJsonWebKey,
    CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm, CoreRevocableToken,
    CoreRevocationErrorResponse, CoreTokenIntrospectionResponse, CoreTokenType,
};
use openidconnect::{
    core::CoreAuthenticationFlow,
    url::{form_urlencoded, Url},
    AsyncHttpClient, Audience, CsrfToken, EndSessionUrl, EndpointMaybeSet, EndpointNotSet,
    EndpointSet, IssuerUrl, LogoutRequest, Nonce, OAuth2TokenResponse, PostLogoutRedirectUrl,
    ProviderMetadataWithLogout, RedirectUrl, Scope, TokenResponse,
};
use openidconnect::{
    EmptyExtraTokenFields, IdTokenFields, IdTokenVerifier, StandardErrorResponse,
    StandardTokenResponse,
};
use serde::{Deserialize, Serialize};

use super::error::anyhow_err_to_actix_resp;
use super::http_client::make_http_client;

type LocalBoxFuture<T> = Pin<Box<dyn Future<Output = T> + 'static>>;

const SQLPAGE_AUTH_COOKIE_NAME: &str = "sqlpage_auth";
const SQLPAGE_REDIRECT_URI: &str = "/sqlpage/oidc_callback";
const SQLPAGE_LOGOUT_URI: &str = "/sqlpage/oidc_logout";
const SQLPAGE_NONCE_COOKIE_NAME: &str = "sqlpage_oidc_nonce";
const SQLPAGE_TMP_LOGIN_STATE_COOKIE_PREFIX: &str = "sqlpage_oidc_state_";
const OIDC_CLIENT_MAX_REFRESH_INTERVAL: Duration = Duration::from_secs(60 * 60);
const OIDC_CLIENT_MIN_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
const OIDC_HTTP_BODY_TIMEOUT: Duration = OIDC_CLIENT_MIN_REFRESH_INTERVAL;
const SQLPAGE_OIDC_REDIRECT_COUNT_COOKIE: &str = "sqlpage_oidc_redirect_count";
const MAX_OIDC_REDIRECTS: u8 = 3;
const AUTH_COOKIE_EXPIRATION: awc::cookie::time::Duration =
    actix_web::cookie::time::Duration::days(7);
const LOGIN_FLOW_STATE_COOKIE_EXPIRATION: awc::cookie::time::Duration =
    actix_web::cookie::time::Duration::minutes(10);

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct OidcAdditionalClaims(pub(crate) serde_json::Map<String, serde_json::Value>);

impl openidconnect::AdditionalClaims for OidcAdditionalClaims {}
type OidcToken = openidconnect::IdToken<
    OidcAdditionalClaims,
    openidconnect::core::CoreGenderClaim,
    openidconnect::core::CoreJweContentEncryptionAlgorithm,
    openidconnect::core::CoreJwsSigningAlgorithm,
>;
pub type OidcClaims =
    openidconnect::IdTokenClaims<OidcAdditionalClaims, openidconnect::core::CoreGenderClaim>;

#[derive(Clone, Debug)]
pub struct OidcConfig {
    pub issuer_url: IssuerUrl,
    pub client_id: String,
    pub client_secret: String,
    pub protected_paths: Vec<String>,
    pub public_paths: Vec<String>,
    pub app_host: String,
    pub scopes: Vec<Scope>,
    pub additional_audience_verifier: AudienceVerifier,
    pub site_prefix: String,
    pub redirect_uri: String,
    pub logout_uri: String,
}

impl TryFrom<&AppConfig> for OidcConfig {
    type Error = Option<&'static str>;

    fn try_from(config: &AppConfig) -> Result<Self, Self::Error> {
        let issuer_url = config.oidc_issuer_url.as_ref().ok_or(None)?;
        let client_secret = config.oidc_client_secret.as_ref().ok_or(Some(
            "The \"oidc_client_secret\" setting is required to authenticate with the OIDC provider",
        ))?;

        let app_host = get_app_host(config);

        let site_prefix_trimmed = config.site_prefix.trim_end_matches('/');
        let redirect_uri = format!("{site_prefix_trimmed}{SQLPAGE_REDIRECT_URI}");
        let logout_uri = format!("{site_prefix_trimmed}{SQLPAGE_LOGOUT_URI}");

        let protected_paths: Vec<String> = config
            .oidc_protected_paths
            .iter()
            .map(|path| format!("{site_prefix_trimmed}{path}"))
            .collect();

        let public_paths: Vec<String> = config
            .oidc_public_paths
            .iter()
            .map(|path| format!("{site_prefix_trimmed}{path}"))
            .collect();

        Ok(Self {
            issuer_url: issuer_url.clone(),
            client_id: config.oidc_client_id.clone(),
            client_secret: client_secret.clone(),
            protected_paths,
            public_paths,
            scopes: config
                .oidc_scopes
                .split_whitespace()
                .map(|s| Scope::new(s.to_string()))
                .collect(),
            app_host: app_host.clone(),
            additional_audience_verifier: AudienceVerifier::new(
                config.oidc_additional_trusted_audiences.clone(),
            ),
            site_prefix: config.site_prefix.clone(),
            redirect_uri,
            logout_uri,
        })
    }
}

impl OidcConfig {
    #[must_use]
    pub fn is_public_path(&self, path: &str) -> bool {
        !self.protected_paths.iter().any(|p| path.starts_with(p))
            || self.public_paths.iter().any(|p| path.starts_with(p))
    }

    /// Creates a custom ID token verifier that supports multiple issuers
    fn create_id_token_verifier<'a>(
        &'a self,
        oidc_client: &'a OidcClient,
    ) -> IdTokenVerifier<'a, CoreJsonWebKey> {
        oidc_client
            .id_token_verifier()
            .set_other_audience_verifier_fn(self.additional_audience_verifier.as_fn())
    }

    /// Creates a logout URL with the given redirect URI
    #[must_use]
    pub fn create_logout_url(&self, redirect_uri: &str) -> String {
        let timestamp = chrono::Utc::now().timestamp();
        let signature = compute_logout_signature(redirect_uri, timestamp, &self.client_secret);
        let query = form_urlencoded::Serializer::new(String::new())
            .append_pair("redirect_uri", redirect_uri)
            .append_pair("timestamp", &timestamp.to_string())
            .append_pair("signature", &signature)
            .finish();
        format!("{}?{}", self.logout_uri, query)
    }
}

fn get_app_host(config: &AppConfig) -> String {
    if let Some(host) = &config.host {
        return host.clone();
    }
    if let Some(https_domain) = &config.https_domain {
        return https_domain.clone();
    }

    let socket_addr = config.listen_on();
    let ip = socket_addr.ip();
    let host = if ip.is_unspecified() || ip.is_loopback() {
        format!("localhost:{}", socket_addr.port())
    } else {
        socket_addr.to_string()
    };
    log::warn!(
        "No host or https_domain provided in the configuration, \
         using \"{host}\" as the app host to build the redirect URL. \
         This will only work locally. \
         Disable this warning by providing a value for the \"host\" setting."
    );
    host
}

/// A point-in-time snapshot of the OIDC provider's client and metadata.
/// Cheaply cloneable via Arc — callers never hold a lock while using this.
struct OidcSnapshot {
    client: OidcClient,
    end_session_endpoint: Option<EndSessionUrl>,
    created_at: Instant,
}

pub struct OidcState {
    pub config: OidcConfig,
    /// Current snapshot. The lock is only held for the instant
    /// needed to clone/swap the Arc — never across await points.
    snapshot: std::sync::RwLock<Arc<OidcSnapshot>>,
    /// Prevents concurrent background refreshes.
    refresh_in_progress: std::sync::atomic::AtomicBool,
}

impl OidcState {
    pub async fn new(oidc_cfg: OidcConfig, app_config: AppConfig) -> anyhow::Result<Self> {
        let http_client = make_http_client(&app_config)?;
        let (client, end_session_endpoint) = build_oidc_client(&oidc_cfg, &http_client).await?;

        Ok(Self {
            config: oidc_cfg,
            snapshot: std::sync::RwLock::new(Arc::new(OidcSnapshot {
                client,
                end_session_endpoint,
                created_at: Instant::now(),
            })),
            refresh_in_progress: std::sync::atomic::AtomicBool::new(false),
        })
    }

    /// Returns the current snapshot. Never blocks in practice.
    fn snapshot(&self) -> Arc<OidcSnapshot> {
        self.snapshot.read().unwrap().clone()
    }

    /// If the snapshot is older than `max_age` and no refresh is already running,
    /// spawns a background task to fetch new provider metadata.
    /// Returns immediately — never blocks the caller on I/O.
    pub fn maybe_refresh(self: &Arc<Self>, http_client: &Client, max_age: Duration) {
        use std::sync::atomic::Ordering;
        if self.snapshot().created_at.elapsed() <= max_age {
            return;
        }
        if self.refresh_in_progress.swap(true, Ordering::AcqRel) {
            return;
        }
        let state = Arc::clone(self);
        let http_client = http_client.clone();
        tokio::task::spawn_local(async move {
            match build_oidc_client(&state.config, &http_client).await {
                Ok((client, end_session_endpoint)) => {
                    *state.snapshot.write().unwrap() = Arc::new(OidcSnapshot {
                        client,
                        end_session_endpoint,
                        created_at: Instant::now(),
                    });
                }
                Err(e) => log::error!("Failed to refresh OIDC client: {e:#}"),
            }
            state.refresh_in_progress.store(false, Ordering::Release);
        });
    }

    pub fn end_session_endpoint(&self) -> Option<EndSessionUrl> {
        self.snapshot().end_session_endpoint.clone()
    }

    /// Validate and decode the claims of an OIDC token.
    fn get_token_claims(
        &self,
        id_token: OidcToken,
        expected_nonce: &Nonce,
    ) -> anyhow::Result<OidcClaims> {
        let snapshot = self.snapshot();
        let verifier = self.config.create_id_token_verifier(&snapshot.client);
        let nonce_verifier = |nonce: Option<&Nonce>| check_nonce(nonce, expected_nonce);
        let claims: OidcClaims = id_token
            .into_claims(&verifier, nonce_verifier)
            .map_err(|e| anyhow::anyhow!("Could not verify the ID token: {e}"))?;
        Ok(claims)
    }

    /// Builds an absolute redirect URI from the client's configured redirect URL.
    pub fn build_absolute_redirect_uri(
        &self,
        relative_redirect_uri: &str,
    ) -> anyhow::Result<String> {
        let snapshot = self.snapshot();
        let client_redirect_url = snapshot
            .client
            .redirect_uri()
            .ok_or_else(|| anyhow!("OIDC client has no redirect URL configured"))?;
        let absolute_redirect_uri = client_redirect_url
            .url()
            .join(relative_redirect_uri)
            .with_context(|| {
                format!(
                    "Failed to join redirect URI {} with client redirect URL {}",
                    relative_redirect_uri,
                    client_redirect_url.url()
                )
            })?
            .to_string();
        Ok(absolute_redirect_uri)
    }
}

pub async fn initialize_oidc_state(
    app_config: &AppConfig,
) -> anyhow::Result<Option<Arc<OidcState>>> {
    let oidc_cfg = match OidcConfig::try_from(app_config) {
        Ok(c) => c,
        Err(None) => return Ok(None), // OIDC not configured
        Err(Some(e)) => return Err(anyhow::anyhow!(e)),
    };

    Ok(Some(Arc::new(
        OidcState::new(oidc_cfg, app_config.clone()).await?,
    )))
}

async fn build_oidc_client(
    oidc_cfg: &OidcConfig,
    http_client: &Client,
) -> anyhow::Result<(OidcClient, Option<EndSessionUrl>)> {
    let issuer_url = oidc_cfg.issuer_url.clone();
    let provider_metadata = discover_provider_metadata(http_client, issuer_url.clone()).await?;
    let end_session_endpoint = provider_metadata
        .additional_metadata()
        .end_session_endpoint
        .clone();
    let client = make_oidc_client(oidc_cfg, provider_metadata)?;
    Ok((client, end_session_endpoint))
}

pub struct OidcMiddleware {
    oidc_state: Option<Arc<OidcState>>,
}

impl OidcMiddleware {
    #[must_use]
    pub fn new(app_state: &web::Data<AppState>) -> Condition<Self> {
        let oidc_state = app_state.oidc_state.clone();
        Condition::new(oidc_state.is_some(), Self { oidc_state })
    }
}

async fn discover_provider_metadata(
    http_client: &awc::Client,
    issuer_url: IssuerUrl,
) -> anyhow::Result<ProviderMetadataWithLogout> {
    log::debug!("Discovering provider metadata for {issuer_url}");
    let provider_metadata = ProviderMetadataWithLogout::discover_async(
        issuer_url,
        &AwcHttpClient::from_client(http_client),
    )
    .await
    .with_context(|| "Failed to discover OIDC provider metadata".to_string())?;
    log::debug!("Provider metadata discovered: {provider_metadata:?}");
    log::debug!(
        "end_session_endpoint: {:?}",
        provider_metadata.additional_metadata().end_session_endpoint
    );
    Ok(provider_metadata)
}

impl<S> Transform<S, ServiceRequest> for OidcMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error> + 'static,
    S::Future: 'static,
{
    type Response = ServiceResponse<BoxBody>;
    type Error = Error;
    type InitError = ();
    type Transform = OidcService<S>;
    type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        match &self.oidc_state {
            Some(state) => ready(Ok(OidcService::new(service, Arc::clone(state)))),
            None => ready(Err(())),
        }
    }
}

#[derive(Clone)]
pub struct OidcService<S> {
    service: Rc<S>,
    oidc_state: Arc<OidcState>,
}

impl<S> OidcService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error>,
    S::Future: 'static,
{
    pub fn new(service: S, oidc_state: Arc<OidcState>) -> Self {
        Self {
            service: Rc::new(service),
            oidc_state,
        }
    }
}

enum MiddlewareResponse {
    Forward(ServiceRequest),
    Respond(ServiceResponse),
}

async fn handle_request(
    oidc_state: &Arc<OidcState>,
    request: ServiceRequest,
) -> MiddlewareResponse {
    log::trace!("Started OIDC middleware request handling");
    let http_client = get_http_client_from_appdata(&request).ok();
    if let Some(c) = http_client {
        oidc_state.maybe_refresh(c, OIDC_CLIENT_MAX_REFRESH_INTERVAL);
    }

    if request.path() == oidc_state.config.redirect_uri {
        let response = handle_oidc_callback(oidc_state, request).await;
        return MiddlewareResponse::Respond(response);
    }

    if request.path() == oidc_state.config.logout_uri {
        let response = handle_oidc_logout(oidc_state, request);
        return MiddlewareResponse::Respond(response);
    }

    match get_authenticated_user_info(oidc_state, &request) {
        Ok(Some(claims)) => {
            log::trace!("Storing authenticated user info in request extensions: {claims:?}");
            request.extensions_mut().insert(claims);
            MiddlewareResponse::Forward(request)
        }
        Ok(None) => {
            log::trace!("No authenticated user found");
            handle_unauthenticated_request(oidc_state, request)
        }
        Err(e) => {
            log::debug!("An auth cookie is present but could not be verified. Redirecting to OIDC provider to re-authenticate. {e:?}");
            if let Some(c) = http_client {
                oidc_state.maybe_refresh(c, OIDC_CLIENT_MIN_REFRESH_INTERVAL);
            }
            handle_unauthenticated_request(oidc_state, request)
        }
    }
}

fn handle_unauthenticated_request(
    oidc_state: &OidcState,
    request: ServiceRequest,
) -> MiddlewareResponse {
    log::debug!("Handling unauthenticated request to {}", request.path());

    if oidc_state.config.is_public_path(request.path()) {
        return MiddlewareResponse::Forward(request);
    }

    log::debug!("Redirecting to OIDC provider");

    let initial_url = request.uri().to_string();
    let redirect_count = get_redirect_count(&request);
    let response = build_auth_provider_redirect_response(oidc_state, &initial_url, redirect_count);
    MiddlewareResponse::Respond(request.into_response(response))
}

async fn handle_oidc_callback(
    oidc_state: &Arc<OidcState>,
    request: ServiceRequest,
) -> ServiceResponse {
    match process_oidc_callback(oidc_state, &request).await {
        Ok(mut response) => {
            clear_redirect_count_cookie(&mut response);
            request.into_response(response)
        }
        Err(e) => handle_oidc_callback_error(oidc_state, request, &e),
    }
}

fn handle_oidc_callback_error(
    oidc_state: &Arc<OidcState>,
    request: ServiceRequest,
    e: &anyhow::Error,
) -> ServiceResponse {
    let redirect_count = get_redirect_count(&request);
    if redirect_count >= MAX_OIDC_REDIRECTS {
        return handle_max_redirect_count_reached(request, e, redirect_count);
    }
    log::error!(
        "Failed to process OIDC callback (attempt {redirect_count}). Refreshing oidc provider metadata, then redirecting to home page: {e:#}"
    );
    if let Ok(http_client) = get_http_client_from_appdata(&request) {
        oidc_state.maybe_refresh(http_client, OIDC_CLIENT_MIN_REFRESH_INTERVAL);
    }
    let resp = build_auth_provider_redirect_response(oidc_state, "/", redirect_count);
    request.into_response(resp)
}

fn handle_max_redirect_count_reached(
    request: ServiceRequest,
    e: &anyhow::Error,
    redirect_count: u8,
) -> ServiceResponse {
    log::error!(
        "Failed to process OIDC callback after {redirect_count} attempts. \
         Stopping to avoid infinite redirections: {e:#}"
    );
    let resp = build_oidc_error_response(&request, e);
    request.into_response(resp)
}

fn handle_oidc_logout(oidc_state: &OidcState, request: ServiceRequest) -> ServiceResponse {
    match process_oidc_logout(oidc_state, &request) {
        Ok(response) => request.into_response(response),
        Err(e) => {
            log::error!("Failed to process OIDC logout: {e:#}");
            request.into_response(
                HttpResponse::BadRequest()
                    .content_type("text/plain")
                    .body(format!("Logout failed: {e}")),
            )
        }
    }
}

#[derive(Debug, Deserialize)]
struct LogoutParams {
    redirect_uri: String,
    timestamp: i64,
    signature: String,
}

const LOGOUT_TOKEN_VALIDITY_SECONDS: i64 = 600;

fn parse_logout_params(query: &str) -> anyhow::Result<LogoutParams> {
    Query::<LogoutParams>::from_query(query)
        .with_context(|| format!("{SQLPAGE_LOGOUT_URI}: missing required parameters"))
        .map(Query::into_inner)
}

fn process_oidc_logout(
    oidc_state: &OidcState,
    request: &ServiceRequest,
) -> anyhow::Result<HttpResponse> {
    let params = parse_logout_params(request.query_string())?;

    verify_logout_params(&params, &oidc_state.config.client_secret)?;

    let id_token_cookie = request.cookie(SQLPAGE_AUTH_COOKIE_NAME);
    let id_token = id_token_cookie
        .as_ref()
        .map(|c| OidcToken::from_str(c.value()))
        .transpose()
        .ok()
        .flatten();

    let mut response = if let Some(end_session_endpoint) = oidc_state.end_session_endpoint() {
        let absolute_redirect_uri = oidc_state.build_absolute_redirect_uri(&params.redirect_uri)?;

        let post_logout_redirect_uri = PostLogoutRedirectUrl::new(absolute_redirect_uri.clone())
            .with_context(|| {
                format!("Invalid post_logout_redirect_uri: {absolute_redirect_uri}")
            })?;

        let mut logout_request = LogoutRequest::from(end_session_endpoint)
            .set_post_logout_redirect_uri(post_logout_redirect_uri);

        if let Some(ref token) = id_token {
            logout_request = logout_request.set_id_token_hint(token);
        }

        let logout_url = logout_request.http_get_url();
        log::info!("Redirecting to OIDC logout URL: {logout_url}");
        build_redirect_response(logout_url.to_string())
    } else {
        log::info!(
            "No end_session_endpoint, redirecting to {}",
            params.redirect_uri
        );
        build_redirect_response(params.redirect_uri)
    };

    response.add_removal_cookie(
        &Cookie::build(SQLPAGE_AUTH_COOKIE_NAME, "")
            .path("/")
            .finish(),
    )?;
    response.add_removal_cookie(
        &Cookie::build(SQLPAGE_NONCE_COOKIE_NAME, "")
            .path("/")
            .finish(),
    )?;

    log::debug!("User logged out successfully");
    Ok(response)
}

fn compute_logout_signature(redirect_uri: &str, timestamp: i64, client_secret: &str) -> String {
    use base64::Engine;
    use hmac::{Hmac, Mac};
    use sha2::Sha256;

    let mut mac = Hmac::<Sha256>::new_from_slice(client_secret.as_bytes())
        .expect("HMAC accepts any key size");
    mac.update(redirect_uri.as_bytes());
    mac.update(&timestamp.to_be_bytes());
    let signature = mac.finalize().into_bytes();
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signature)
}

fn verify_logout_params(params: &LogoutParams, client_secret: &str) -> anyhow::Result<()> {
    use base64::Engine;

    let expected_signature =
        compute_logout_signature(&params.redirect_uri, params.timestamp, client_secret);

    let provided_signature = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(&params.signature)
        .with_context(|| "Invalid logout signature encoding")?;

    let expected_signature_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(&expected_signature)
        .with_context(|| "Failed to decode expected signature")?;

    if expected_signature_bytes[..] != provided_signature[..] {
        anyhow::bail!("Invalid logout signature");
    }

    let now = chrono::Utc::now().timestamp();
    if now - params.timestamp > LOGOUT_TOKEN_VALIDITY_SECONDS {
        anyhow::bail!("Logout token has expired");
    }
    if params.timestamp > now + 60 {
        anyhow::bail!("Logout token timestamp is in the future");
    }

    if !params.redirect_uri.starts_with('/') || params.redirect_uri.starts_with("//") {
        anyhow::bail!("Invalid redirect URI");
    }

    Ok(())
}

impl<S> Service<ServiceRequest> for OidcService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error> + 'static,
    S::Future: 'static,
{
    type Response = ServiceResponse<BoxBody>;
    type Error = Error;
    type Future = LocalBoxFuture<Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, request: ServiceRequest) -> Self::Future {
        let srv = Rc::clone(&self.service);
        let oidc_state = Arc::clone(&self.oidc_state);
        Box::pin(async move {
            match handle_request(&oidc_state, request).await {
                MiddlewareResponse::Respond(response) => Ok(response),
                MiddlewareResponse::Forward(request) => srv.call(request).await,
            }
        })
    }
}

async fn process_oidc_callback(
    oidc_state: &OidcState,
    request: &ServiceRequest,
) -> anyhow::Result<HttpResponse> {
    let params = Query::<OidcCallbackParams>::from_query(request.query_string())
        .with_context(|| format!("{SQLPAGE_REDIRECT_URI}: invalid url parameters"))?
        .into_inner();
    log::debug!("Processing OIDC callback with params: {params:?}. Requesting token...");
    let mut tmp_login_flow_state_cookie = get_tmp_login_flow_state_cookie(request, &params.state)?;
    let snapshot = oidc_state.snapshot();
    let http_client = get_http_client_from_appdata(request)?;
    let id_token = exchange_code_for_token(&snapshot.client, http_client, params.clone()).await?;
    log::debug!("Received token response: {id_token:?}");
    let LoginFlowState {
        nonce,
        redirect_target,
    } = parse_login_flow_state(&tmp_login_flow_state_cookie)?;
    let redirect_target =
        validate_redirect_url(redirect_target.to_string(), &oidc_state.config.redirect_uri);

    log::info!("Redirecting to {redirect_target} after a successful login");
    let mut response = build_redirect_response(redirect_target);
    set_auth_cookie(&mut response, &id_token);
    let claims = oidc_state
        .get_token_claims(id_token, &nonce)
        .context("The identity provider returned an invalid ID token")?;
    log::debug!("{} successfully logged in", claims.subject().as_str());
    let nonce_cookie = create_final_nonce_cookie(&nonce);
    response.add_cookie(&nonce_cookie)?;
    tmp_login_flow_state_cookie.set_path("/"); // Required to clean up the cookie
    response.add_removal_cookie(&tmp_login_flow_state_cookie)?;
    Ok(response)
}

async fn exchange_code_for_token(
    oidc_client: &OidcClient,
    http_client: &awc::Client,
    oidc_callback_params: OidcCallbackParams,
) -> anyhow::Result<OidcToken> {
    let token_response = oidc_client
        .exchange_code(openidconnect::AuthorizationCode::new(
            oidc_callback_params.code,
        ))?
        .request_async(&AwcHttpClient::from_client(http_client))
        .await
        .context("Failed to exchange code for token")?;
    let access_token = token_response.access_token();
    log::trace!("Received access token: {}", access_token.secret());
    let id_token = token_response
        .id_token()
        .context("No ID token found in the token response. You may have specified an oauth2 provider that does not support OIDC.")?;
    Ok(id_token.clone())
}

fn set_auth_cookie(response: &mut HttpResponse, id_token: &OidcToken) {
    let id_token_str = id_token.to_string();
    log::trace!("Setting auth cookie: {SQLPAGE_AUTH_COOKIE_NAME}=\"{id_token_str}\"");
    let id_token_size_kb = id_token_str.len() / 1024;
    if id_token_size_kb > 4 {
        log::warn!(
            "The ID token cookie from the OIDC provider is {id_token_size_kb}kb. \
             Large cookies can cause performance issues and may be rejected by browsers or by reverse proxies."
        );
    }
    let cookie = Cookie::build(SQLPAGE_AUTH_COOKIE_NAME, id_token_str)
        .secure(true)
        .http_only(true)
        .max_age(AUTH_COOKIE_EXPIRATION)
        .same_site(actix_web::cookie::SameSite::Lax)
        .path("/")
        .finish();

    response.add_cookie(&cookie).unwrap();
}

fn build_auth_provider_redirect_response(
    oidc_state: &OidcState,
    initial_url: &str,
    redirect_count: u8,
) -> HttpResponse {
    let AuthUrl { url, params } = build_auth_url(oidc_state);
    let tmp_login_flow_state_cookie = create_tmp_login_flow_state_cookie(&params, initial_url);
    let redirect_count_cookie = Cookie::build(
        SQLPAGE_OIDC_REDIRECT_COUNT_COOKIE,
        (redirect_count + 1).to_string(),
    )
    .path("/")
    .http_only(true)
    .same_site(actix_web::cookie::SameSite::Lax)
    .max_age(LOGIN_FLOW_STATE_COOKIE_EXPIRATION)
    .finish();
    HttpResponse::SeeOther()
        .append_header((header::LOCATION, url.to_string()))
        .cookie(tmp_login_flow_state_cookie)
        .cookie(redirect_count_cookie)
        .body("Redirecting...")
}

fn build_redirect_response(target_url: String) -> HttpResponse {
    HttpResponse::SeeOther()
        .append_header(("Location", target_url))
        .body("Redirecting...")
}

fn get_redirect_count(request: &ServiceRequest) -> u8 {
    request
        .cookie(SQLPAGE_OIDC_REDIRECT_COUNT_COOKIE)
        .and_then(|c| c.value().parse().ok())
        .unwrap_or(0)
}

fn clear_redirect_count_cookie(response: &mut HttpResponse) {
    let cookie = Cookie::build(SQLPAGE_OIDC_REDIRECT_COUNT_COOKIE, "")
        .path("/")
        .finish()
        .into_owned();
    response.add_removal_cookie(&cookie).ok();
}

fn build_oidc_error_response(request: &ServiceRequest, e: &anyhow::Error) -> HttpResponse {
    request.app_data::<web::Data<AppState>>().map_or_else(
        || HttpResponse::InternalServerError().body(format!("Authentication error: {e}")),
        |state| anyhow_err_to_actix_resp(e, state),
    )
}

/// Returns the claims from the ID token in the `SQLPage` auth cookie.
fn get_authenticated_user_info(
    oidc_state: &OidcState,
    request: &ServiceRequest,
) -> anyhow::Result<Option<OidcClaims>> {
    let Some(cookie) = request.cookie(SQLPAGE_AUTH_COOKIE_NAME) else {
        return Ok(None);
    };
    let cookie_value = cookie.value().to_string();
    let id_token = OidcToken::from_str(&cookie_value)
        .with_context(|| format!("Invalid SQLPage auth cookie: {cookie_value:?}"))?;

    let nonce = get_final_nonce_from_cookie(request)?;
    log::debug!("Verifying id token: {id_token:?}");
    let claims = oidc_state.get_token_claims(id_token, &nonce)?;
    log::debug!("The current user is: {claims:?}");
    Ok(Some(claims))
}

pub struct AwcHttpClient<'c> {
    client: &'c awc::Client,
}

impl<'c> AwcHttpClient<'c> {
    #[must_use]
    pub fn from_client(client: &'c awc::Client) -> Self {
        Self { client }
    }
}

impl<'c> AsyncHttpClient<'c> for AwcHttpClient<'c> {
    type Error = AwcWrapperError;
    type Future =
        Pin<Box<dyn Future<Output = Result<openidconnect::HttpResponse, Self::Error>> + 'c>>;

    fn call(&'c self, request: openidconnect::HttpRequest) -> Self::Future {
        let client = self.client.clone();
        Box::pin(async move {
            execute_oidc_request_with_awc(client, request)
                .await
                .map_err(AwcWrapperError)
        })
    }
}

async fn execute_oidc_request_with_awc(
    client: Client,
    request: openidconnect::HttpRequest,
) -> Result<openidconnect::http::Response<Vec<u8>>, anyhow::Error> {
    let awc_method = awc::http::Method::from_bytes(request.method().as_str().as_bytes())?;
    let awc_uri = awc::http::Uri::from_str(&request.uri().to_string())?;
    log::debug!("Executing OIDC request: {awc_method} {awc_uri}");
    let mut req = client.request(awc_method, awc_uri);
    for (name, value) in request.headers() {
        req = req.insert_header((name.as_str(), value.to_str()?));
    }
    let (req_head, body) = request.into_parts();
    let response = req.send_body(body).await.map_err(|e| {
        anyhow!(e.to_string()).context(format!(
            "Failed to send request: {} {}",
            &req_head.method, &req_head.uri
        ))
    })?;
    let head = response.headers();
    let mut resp_builder =
        openidconnect::http::Response::builder().status(response.status().as_u16());
    for (name, value) in head {
        resp_builder = resp_builder.header(name.as_str(), value.to_str()?);
    }
    let mut response = response.timeout(OIDC_HTTP_BODY_TIMEOUT);
    let body = response
        .body()
        .await
        .with_context(|| format!("Couldnt read from {}", &req_head.uri))?;
    log::debug!(
        "Received OIDC response with status {}: {}",
        response.status(),
        String::from_utf8_lossy(&body)
    );
    let resp = resp_builder.body(body.to_vec())?;
    Ok(resp)
}

#[derive(Debug)]
pub struct AwcWrapperError(anyhow::Error);

impl std::fmt::Display for AwcWrapperError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.0, f)
    }
}

type OidcTokenResponse = StandardTokenResponse<
    IdTokenFields<
        OidcAdditionalClaims,
        EmptyExtraTokenFields,
        CoreGenderClaim,
        CoreJweContentEncryptionAlgorithm,
        CoreJwsSigningAlgorithm,
    >,
    CoreTokenType,
>;

type OidcClient = openidconnect::Client<
    OidcAdditionalClaims,
    CoreAuthDisplay,
    CoreGenderClaim,
    CoreJweContentEncryptionAlgorithm,
    CoreJsonWebKey,
    CoreAuthPrompt,
    StandardErrorResponse<CoreErrorResponseType>,
    OidcTokenResponse,
    CoreTokenIntrospectionResponse,
    CoreRevocableToken,
    CoreRevocationErrorResponse,
    EndpointSet,
    EndpointNotSet,
    EndpointNotSet,
    EndpointNotSet,
    EndpointMaybeSet,
    EndpointMaybeSet,
>;

impl std::error::Error for AwcWrapperError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.0.source()
    }
}

fn make_oidc_client(
    config: &OidcConfig,
    provider_metadata: ProviderMetadataWithLogout,
) -> anyhow::Result<OidcClient> {
    let client_id = openidconnect::ClientId::new(config.client_id.clone());
    let client_secret = openidconnect::ClientSecret::new(config.client_secret.clone());

    let mut redirect_url = RedirectUrl::new(format!(
        "https://{}{}",
        config.app_host, config.redirect_uri,
    ))
    .with_context(|| {
        format!(
            "Failed to build the redirect URL; invalid app host \"{}\"",
            config.app_host
        )
    })?;
    let needs_http = match redirect_url.url().host() {
        Some(openidconnect::url::Host::Domain(domain)) => {
            domain == "localhost" || domain.ends_with(".localhost")
        }
        Some(openidconnect::url::Host::Ipv4(_) | openidconnect::url::Host::Ipv6(_)) => true,
        None => false,
    };
    if needs_http {
        log::debug!("App host seems to be local, changing redirect URL to HTTP");
        redirect_url =
            RedirectUrl::new(format!("http://{}{}", config.app_host, config.redirect_uri,))?;
    }
    log::info!("OIDC redirect URL for {}: {redirect_url}", config.client_id);
    let client =
        OidcClient::from_provider_metadata(provider_metadata, client_id, Some(client_secret))
            .set_redirect_uri(redirect_url);

    Ok(client)
}

#[derive(Debug, Deserialize, Clone)]
struct OidcCallbackParams {
    code: String,
    state: CsrfToken,
}

struct AuthUrl {
    url: Url,
    params: AuthUrlParams,
}

struct AuthUrlParams {
    csrf_token: CsrfToken,
    nonce: Nonce,
}

fn build_auth_url(oidc_state: &OidcState) -> AuthUrl {
    let nonce_source = Nonce::new_random();
    let hashed_nonce = Nonce::new(hash_nonce(&nonce_source));
    let scopes = &oidc_state.config.scopes;
    let snapshot = oidc_state.snapshot();
    let (url, csrf_token, _nonce) = snapshot
        .client
        .authorize_url(
            CoreAuthenticationFlow::AuthorizationCode,
            CsrfToken::new_random,
            || hashed_nonce,
        )
        .add_scopes(scopes.iter().cloned())
        .url();
    AuthUrl {
        url,
        params: AuthUrlParams {
            csrf_token,
            nonce: nonce_source,
        },
    }
}

fn hash_nonce(nonce: &Nonce) -> String {
    use argon2::password_hash::{rand_core::OsRng, PasswordHasher, SaltString};
    let salt = SaltString::generate(&mut OsRng);
    // low-cost parameters: oidc tokens are short-lived and the source nonce is high-entropy
    let params = argon2::Params::new(8, 1, 1, Some(16)).expect("bug: invalid Argon2 parameters");
    let argon2 = argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params);
    let hash = argon2
        .hash_password(nonce.secret().as_bytes(), &salt)
        .expect("bug: failed to hash nonce");
    hash.to_string()
}

fn check_nonce(id_token_nonce: Option<&Nonce>, expected_nonce: &Nonce) -> Result<(), String> {
    match id_token_nonce {
        Some(id_token_nonce) => nonce_matches(id_token_nonce, expected_nonce),
        None => Err("No nonce found in the ID token".to_string()),
    }
}

fn nonce_matches(id_token_nonce: &Nonce, state_nonce: &Nonce) -> Result<(), String> {
    log::debug!(
        "Checking nonce: {} == {}",
        id_token_nonce.secret(),
        state_nonce.secret()
    );
    let hash = argon2::password_hash::PasswordHash::new(id_token_nonce.secret()).map_err(|e| {
        format!(
            "Failed to parse state nonce ({}): {e}",
            id_token_nonce.secret()
        )
    })?;
    argon2::password_hash::PasswordVerifier::verify_password(
        &argon2::Argon2::default(),
        state_nonce.secret().as_bytes(),
        &hash,
    )
    .map_err(|e| format!("Failed to verify nonce ({}): {e}", state_nonce.secret()))?;
    log::debug!("Nonce successfully verified");
    Ok(())
}

fn create_final_nonce_cookie(nonce: &Nonce) -> Cookie<'_> {
    Cookie::build(SQLPAGE_NONCE_COOKIE_NAME, nonce.secret())
        .secure(true)
        .http_only(true)
        .same_site(actix_web::cookie::SameSite::Lax)
        .max_age(AUTH_COOKIE_EXPIRATION)
        .path("/")
        .finish()
}

fn create_tmp_login_flow_state_cookie<'a>(
    params: &'a AuthUrlParams,
    initial_url: &'a str,
) -> Cookie<'a> {
    let csrf_token = &params.csrf_token;
    let cookie_name = SQLPAGE_TMP_LOGIN_STATE_COOKIE_PREFIX.to_owned() + csrf_token.secret();
    let cookie_value = serde_json::to_string(&LoginFlowState {
        nonce: params.nonce.clone(),
        redirect_target: initial_url,
    })
    .expect("login flow state is always serializable");
    Cookie::build(cookie_name, cookie_value)
        .secure(true)
        .http_only(true)
        .same_site(actix_web::cookie::SameSite::Lax)
        .path("/")
        .max_age(LOGIN_FLOW_STATE_COOKIE_EXPIRATION)
        .finish()
}

fn get_final_nonce_from_cookie(request: &ServiceRequest) -> anyhow::Result<Nonce> {
    let cookie = request
        .cookie(SQLPAGE_NONCE_COOKIE_NAME)
        .with_context(|| format!("No {SQLPAGE_NONCE_COOKIE_NAME} cookie found"))?;
    Ok(Nonce::new(cookie.value().to_string()))
}

fn get_tmp_login_flow_state_cookie(
    request: &ServiceRequest,
    csrf_token: &CsrfToken,
) -> anyhow::Result<Cookie<'static>> {
    let cookie_name = SQLPAGE_TMP_LOGIN_STATE_COOKIE_PREFIX.to_owned() + csrf_token.secret();
    request
        .cookie(&cookie_name)
        .with_context(|| format!("No {cookie_name} cookie found"))
}

#[derive(Debug, Serialize, Deserialize, Clone)]
struct LoginFlowState<'a> {
    #[serde(rename = "n")]
    nonce: Nonce,
    #[serde(rename = "r")]
    redirect_target: &'a str,
}

fn parse_login_flow_state<'a>(cookie: &'a Cookie<'_>) -> anyhow::Result<LoginFlowState<'a>> {
    serde_json::from_str(cookie.value())
        .with_context(|| format!("Invalid login flow state cookie: {}", cookie.value()))
}

/// Given an audience, verify if it is trusted. The `client_id` is always trusted, independently of this function.
#[derive(Clone, Debug)]
pub struct AudienceVerifier(Option<HashSet<String>>);

impl AudienceVerifier {
    /// JWT audiences (aud claim) are always required to contain the `client_id`, but they can also contain additional audiences.
    /// By default we allow any additional audience.
    /// The user can restrict the allowed additional audiences by providing a list of trusted audiences.
    fn new(additional_trusted_audiences: Option<Vec<String>>) -> Self {
        AudienceVerifier(additional_trusted_audiences.map(HashSet::from_iter))
    }

    /// Returns a function that given an audience, verifies if it is trusted.
    fn as_fn(&self) -> impl Fn(&Audience) -> bool + '_ {
        move |aud: &Audience| -> bool {
            let Some(trusted_set) = &self.0 else {
                return true;
            };
            trusted_set.contains(aud.as_str())
        }
    }
}

/// Validate that a redirect URL is safe to use (prevents open redirect attacks)
fn validate_redirect_url(url: String, redirect_uri: &str) -> String {
    if url.starts_with('/') && !url.starts_with("//") && !url.starts_with(redirect_uri) {
        return url;
    }
    log::warn!("Refusing to redirect to {url}");
    '/'.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::http::StatusCode;
    use openidconnect::url::Url;

    #[test]
    fn login_redirects_use_see_other() {
        let response = build_redirect_response("/foo".to_string());
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        let location = response
            .headers()
            .get(header::LOCATION)
            .expect("missing location header")
            .to_str()
            .expect("invalid location header");
        assert_eq!(location, "/foo");
    }

    #[test]
    fn parse_auth0_rfc3339_updated_at() {
        let claims_json = r#"{
            "sub": "auth0|123456",
            "iss": "https://example.auth0.com/",
            "aud": "test-client-id",
            "iat": 1700000000,
            "exp": 1700086400,
            "updated_at": "2023-11-14T12:00:00.000Z"
        }"#;
        let claims: OidcClaims = serde_json::from_str(claims_json)
            .expect("Auth0 returns updated_at as RFC3339 string, not unix timestamp");
        assert!(claims.updated_at().is_some());
    }

    #[test]
    fn logout_url_generation_and_parsing_are_compatible() {
        let secret = "super_secret_key";
        let config = OidcConfig {
            issuer_url: IssuerUrl::new("https://example.com".to_string()).unwrap(),
            client_id: "test_client".to_string(),
            client_secret: secret.to_string(),
            protected_paths: vec![],
            public_paths: vec![],
            app_host: "example.com".to_string(),
            scopes: vec![],
            additional_audience_verifier: AudienceVerifier::new(None),
            site_prefix: "https://example.com".to_string(),
            redirect_uri: format!("https://example.com{SQLPAGE_REDIRECT_URI}"),
            logout_uri: format!("https://example.com{SQLPAGE_LOGOUT_URI}"),
        };
        let generated = config.create_logout_url("/after");

        let parsed = Url::parse(&generated).expect("generated URL should be valid");
        assert_eq!(parsed.path(), SQLPAGE_LOGOUT_URI);

        let params = parse_logout_params(parsed.query().expect("query string is present"))
            .expect("generated URL should parse");
        verify_logout_params(&params, secret).expect("generated URL should validate");
    }
}