about summary refs log tree commit diff
path: root/indieauth/src/lib.rs
blob: 96ddea4086c853a344175ca4ff90332da83c1fbb (plain) (blame)
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
#![deny(missing_docs)]
#![forbid(rustdoc::broken_intra_doc_links)]
//! A library of useful structs and helpers to implement [IndieAuth
//! version 20220212][indieauth].
//!
//! This crate is completely network-agnostic, which means it can be
//! used with both sync and async web frameworks, and even on the
//! client side to implement identity consumers.
//!
//! ## Integration with web frameworks
//!
//! For convenience, helpers for [`axum`], the web framework Kittybox
//! happens to use, are provided. Enable the `axum` feature to use
//! them.
//!
//! The author is happy to accept patches to add more
//! framework-specific helpers.
//!
//! [indieauth]: https://indieauth.spec.indieweb.org/20220212/
//! [`axum`]: https://github.com/tokio-rs/axum
use std::borrow::Cow;

use serde::{Serialize, Deserialize};
use url::Url;

mod scopes;
pub use self::scopes::{Scope, Scopes};
mod pkce;
pub use self::pkce::{PKCEMethod, PKCEVerifier, PKCEChallenge};

// Re-export rand crate just to be sure.
pub use rand;

/// Authentication methods supported by the introspection endpoint.
/// Note that authentication at the introspection endpoint is
/// mandatory.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub enum IntrospectionEndpointAuthMethod {
    /// `Authorization` header with a `Bearer` token.
    Bearer,
    /// A token passed as part of a POST request.
    #[serde(rename = "snake_case")]
    ClientSecretPost,
    /// Username and password passed using HTTP Basic authentication.
    #[serde(rename = "snake_case")]
    ClientSecretBasic,
    /// TLS client auth with a certificate signed by a valid CA.
    #[serde(rename = "snake_case")]
    TlsClientAuth,
    /// TLS client auth with a self-signed certificate.
    #[serde(rename = "snake_case")]
    SelfSignedTlsClientAuth
}

/// Authentication methods supported by the revocation endpoint.
///
/// The intent of the IndieAuth revocation endpoints is to quickly
/// revoke leaked tokens. As it requires posession of a token, no
/// authentication is neccesary to protect tokens. A well-intentioned
/// person discovering a leaked token could quickly revoke it without
/// disturbing anyone.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RevocationEndpointAuthMethod {
    /// No authentication is required to access an endpoint declaring
    /// this value.
    None
}

/// The response types supported by the authorization endpoint.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResponseType {
    /// An authorization code will be issued if this response type is
    /// requested.
    Code,
    /// A token for an external realm will be issued if this response
    /// type is requested. See [AutoAuth spec] for more details.
    ///
    /// This response type requires a valid access token.
    ///
    /// [AutoAuth spec]: https://github.com/sknebel/AutoAuth/blob/master/AutoAuth.md#allowing-external-clients-to-obtain-tokens
    ExternalToken
}
// TODO serde_variant
impl ResponseType {
    /// Return the response type as it would appear in serialized form.
    pub fn as_str(&self) -> &'static str {
        match self {
            ResponseType::Code => "code",
            ResponseType::ExternalToken => "external_token",
        }
    }
}

/// Grant types that are described in the IndieAuth spec.
///
/// This type is strictly for usage in the [`Metadata`] response. For
/// grant requests and responses, see [`GrantRequest`] and
/// [`GrantResponse`].
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GrantType {
    /// The authorization code grant, allowing to exchange an
    /// authorization code for a confirmation of identity or an access
    /// token.
    AuthorizationCode,
    /// The refresh token grant, allowing to exchange a refresh token
    /// for a fresh access token and a new refresh token, to
    /// facilitate long-term access.
    RefreshToken
}

/// OAuth 2.0 Authorization Server Metadata in application to the IndieAuth protocol.
///
/// Your metadata endpoint should return this as a response.
///
/// ```rust
/// use kittybox_indieauth::{
///     Metadata, IntrospectionEndpointAuthMethod, RevocationEndpointAuthMethod,
///     ResponseType, Scope, GrantType, PKCEMethod
/// };
///
/// let metadata = Metadata {
///     issuer: "https://indieauth.example.com/".parse().unwrap(),
///     authorization_endpoint: "https://indieauth.example.com/auth".parse().unwrap(),
///     token_endpoint: "https://indieauth.example.com/token".parse().unwrap(),
///     introspection_endpoint: "https://indieauth.example.com/introspection".parse().unwrap(),
///     introspection_endpoint_auth_methods_supported: Some(vec![IntrospectionEndpointAuthMethod::Bearer]),
///     revocation_endpoint: Some("https://indieauth.example.com/revoke".parse().unwrap()),
///     revocation_endpoint_auth_methods_supported: Some(vec![RevocationEndpointAuthMethod::None]),
///     scopes_supported: Some(vec![Scope::Create, Scope::Update, Scope::custom("manage_tokens")]),
///     response_types_supported: Some(vec![ResponseType::Code]),
///     grant_types_supported: Some(vec![GrantType::AuthorizationCode, GrantType::RefreshToken]),
///     service_documentation: Some("https://indieauth.spec.indieweb.org/".parse().unwrap()),
///     code_challenge_methods_supported: vec![PKCEMethod::S256],
///     authorization_response_iss_parameter_supported: Some(true),
///     userinfo_endpoint: Some("https://indieauth.example.com/userinfo".parse().unwrap())
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metadata {
    /// The server's issuer identifier. The issuer identifier is a URL
    /// that uses the "https" scheme and has no query or fragment
    /// components. The identifier MUST be a prefix of the
    /// `indieauth-metadata` URL.
    pub issuer: Url,
    /// The Authorization Endpoint
    pub authorization_endpoint: Url,
    /// The Token Endpoint
    pub token_endpoint: Url,
    /// The Introspection Endpoint
    pub introspection_endpoint: Url,
    /// JSON array containing a list of client authentication methods
    /// supported by this introspection endpoint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub introspection_endpoint_auth_methods_supported: Option<Vec<IntrospectionEndpointAuthMethod>>,
    /// The Revocation Endpoint
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revocation_endpoint: Option<Url>,
    /// JSON array containing the value
    /// [`RevocationEndpointAuthMethod::None`]. If a revocation endpoint
    /// is provided, this property should also be provided with the
    /// value `vec![RevocationEndpointAuthMethod::None]`, since the
    /// omission of this value defaults to `client_secret_basic`
    /// according to [RFC8414].
    ///
    /// [RFC8414]: https://www.rfc-editor.org/rfc/rfc8414
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revocation_endpoint_auth_methods_supported: Option<Vec<RevocationEndpointAuthMethod>>,
    /// JSON array containing scope values supported by the IndieAuth
    /// server. Servers MAY choose not to advertise some supported
    /// scope values even when this parameter is used.
    // Note: Scopes isn't used here because this field should be
    // serialized as a list, not as a string
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scopes_supported: Option<Vec<Scope>>,
    /// JSON array containing the response_type values supported. This
    /// differs from [RFC8414] in that this parameter is OPTIONAL and
    /// that, if omitted, the default is [`ResponseType::Code`].
    ///
    /// [RFC8414]: https://www.rfc-editor.org/rfc/rfc8414
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_types_supported: Option<Vec<ResponseType>>,
    /// JSON array containing grant type values supported. If omitted,
    /// the default value differs from [RFC8414] and is
    /// `authorization_code`.
    ///
    /// [RFC8414]: https://www.rfc-editor.org/rfc/rfc8414
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grant_types_supported: Option<Vec<GrantType>>,
    /// URL of a page containing human-readable information that
    /// developers might need to know when using the server. This
    /// might be a link to the IndieAuth spec or something more
    /// personal to your implementation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_documentation: Option<Url>,
    /// JSON array containing the methods supported for PKCE. This
    /// parameter differs from [RFC8414] in that it is not optional as
    /// PKCE is *REQUIRED*.
    ///
    /// [RFC8414]: https://www.rfc-editor.org/rfc/rfc8414
    pub code_challenge_methods_supported: Vec<PKCEMethod>,
    /// Boolean parameter indicating whether the authorization server
    /// provides the iss parameter. If omitted, the default value is
    /// false. As the iss parameter is REQUIRED, this is provided for
    /// compatibility with OAuth 2.0 servers implementing the
    /// parameter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorization_response_iss_parameter_supported: Option<bool>,
    /// The User Info Endpoint
    #[serde(skip_serializing_if = "Option::is_none")]
    pub userinfo_endpoint: Option<Url>,
    /// Does the current authorization server support reading OAuth
    /// Client ID metadata?
    ///
    /// This may help enable some non-IndieAuth implementations to
    /// interoperate with IndieAuth by allowing dynamic client
    /// registration.
    #[serde(skip_serializing_if = "ref_identity")]
    #[serde(default = "Default::default")]
    pub client_id_metadata_document_supported: bool
}

fn ref_identity(v: &bool) -> bool { *v }

#[cfg(feature = "axum")]
impl axum_core::response::IntoResponse for Metadata {
    fn into_response(self) -> axum_core::response::Response {
        use http::StatusCode;

        (StatusCode::OK,
         [("Content-Type", "application/json")],
         serde_json::to_vec(&self).unwrap())
            .into_response()
    }
}

/// Client ID metadata, as specified in
/// https://datatracker.ietf.org/doc/html/draft-parecki-oauth-client-id-metadata-document.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ClientMetadata {
    /// Client ID. This MUST match the URL this is served from.
    // XXX: we really ought to do string comparison here.
    pub client_id: Url,
    /// URL of a web page providing more information about the client.
    /// For IndieAuth, this MUST be a prefix of `client_id`.
    pub client_uri: Url,
    /// Human-friendly displayable name for the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_name: Option<String>,
    /// URL that refers to a logo for the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logo_uri: Option<Url>,
    /// Registered redirect URIs for this application.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redirect_uris: Option<Vec<Url>>,
    // The following is a random grab-bag of registry options that I
    // deemed useful. Feel free to expand these as needed.
    /// Grant types this application may use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grant_types: Option<Vec<GrantType>>,
    /// Response types this application may use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_types: Option<Vec<ResponseType>>,
    /// Scopes that this client may request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<Scopes>,
    /// Contact points for this client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contacts: Option<Vec<String>>,
    /// URI for the human-readable Terms of Service.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tos_uri: Option<Url>,
    /// URI for the human-readable policy document.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_uri: Option<Url>,
    /// Identifier for the client software.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub software_id: Option<Cow<'static, str>>,
    /// Version of the client software.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub software_version: Option<Cow<'static, str>>,
    /// URI for the homepage of this client's owners
    #[serde(skip_serializing_if = "Option::is_none")]
    pub homepage_uri: Option<Url>
}

impl ClientMetadata {
    /// Create a new [`ClientMetadata`] with all the optional fields
    /// omitted.
    ///
    /// # Errors
    ///
    /// Returns `()` if the `client_uri` is not a prefix of
    /// `client_id` as required by the IndieAuth spec.
    pub fn new(client_id: url::Url, client_uri: url::Url) -> Result<Self, ()> {
        if client_id.as_str().as_bytes()[..client_uri.as_str().len()] != *client_uri.as_str().as_bytes() {
            return Err(());
        }

        Ok(Self {
            client_id, client_uri,
            client_name: None,
            logo_uri: None,
            redirect_uris: None,
            grant_types: None,
            response_types: None,
            scope: None,
            contacts: None,
            tos_uri: None,
            policy_uri: None,
            software_id: None,
            software_version: None,
            homepage_uri: None,
        })
    }

    /// Transform this into h-app metadata in mf2+html format for
    /// compatibility with older identity providers that do not
    /// recognize the new spec yet.
    #[cfg(feature = "axum")]
    pub fn into_html(self) -> axum_core::response::Response {
        todo!()
    }
}

#[cfg(feature = "axum")]
impl axum_core::response::IntoResponse for ClientMetadata {
    fn into_response(self) -> axum_core::response::Response {
        use http::StatusCode;

        (StatusCode::OK,
         [("Content-Type", "application/json")],
         serde_json::to_vec(&self).unwrap())
            .into_response()
    }
}


/// User profile to be returned from the userinfo endpoint and when
/// the `profile` scope was requested.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Profile {
    /// User's chosen name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// User's profile page. Fetching it may reveal an `h-card`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<Url>,
    /// User's profile picture suitable to represent them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub photo: Option<Url>,
    /// User's email, if they've chosen to reveal it. This is guarded
    /// by the `email` scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>
}

#[cfg(feature = "axum")]
impl axum_core::response::IntoResponse for Profile {
    fn into_response(self) -> axum_core::response::Response {
        use http::StatusCode;

        (StatusCode::OK,
         [("Content-Type", "application/json")],
         serde_json::to_vec(&self).unwrap())
            .into_response()
    }
}

/// A state string comprised of alphanumeric characters to protect
/// from CSRF attacks.
///
/// There is no reason to inspect the string itself except to ensure
/// it hasn't been tampered with.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct State(String);

// Default doesn't make sense semantically, as there is not an
// identity value.
#[allow(clippy::new_without_default)]
impl State {
    /// Generate a random state string of 128 bytes in length.
    pub fn new() -> Self {
        Self::from_rng(&mut rand::thread_rng())
    }

    /// Generate a random state string of 128 bytes in length, using
    /// the provided random number generator.
    pub fn from_rng(rng: &mut (impl rand::CryptoRng + rand::Rng)) -> Self {
        use rand::{Rng, distributions::Alphanumeric};

        let bytes = rng.sample_iter(&Alphanumeric)
            .take(128)
            .collect::<Vec<u8>>();
        Self(String::from_utf8(bytes).unwrap())

    }
}
impl AsRef<str> for State {
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

/// The authorization request that should be affixed to the URL of an
/// authorization endpoint to start the IndieAuth ceremony.
///
/// ```rust
/// use kittybox_indieauth::{
///     AuthorizationRequest, ResponseType, State,
///     Scopes, Scope,
///     PKCEChallenge, PKCEVerifier, PKCEMethod
/// };
///
/// // Save that for later, it'll come in handy
/// let verifier = PKCEVerifier::new();
///
/// let request = AuthorizationRequest {
///     response_type: ResponseType::Code,
///     client_id: "https://kittybox.fireburn.ru/companion/native".parse().unwrap(),
///     redirect_uri: "https://kittybox.fireburn.ru/companion/native/redirect".parse().unwrap(),
///     state: State::new(),
///     code_challenge: PKCEChallenge::new(&verifier, PKCEMethod::default()),
///     scope: Some(Scopes::new(vec![Scope::Create, Scope::Update, Scope::Delete, Scope::Media])),
///     me: Some("https://fireburn.ru/".parse().unwrap())
/// };
///
/// let mut url: url::Url = "https://fireburn.ru/.kittybox/indieauth/auth"
///     .parse()
///     .unwrap();
///
/// url.query_pairs_mut().extend_pairs(request.as_query_pairs().iter());
///
/// // Open a user's browser to navigate to the authorization endpoint page...
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationRequest {
    /// The response type expected to this request.
    pub response_type: ResponseType,
    /// The homepage of the client. It must be fetched to show
    /// metadata and check the redirect URI's authenticity.
    pub client_id: Url,
    /// The URI that the user will be redirected to in case they
    /// approve the authentication request. A query string containing
    /// the response is affixed to it.
    pub redirect_uri: Url,
    /// A random state to protect from CSRF attacks. The server should
    /// return this string unmodified.
    pub state: State,
    /// A PKCE challenge neccesary to protect from authorization code
    /// injection and CSRF attacks.
    #[serde(flatten)]
    pub code_challenge: PKCEChallenge,
    /// An array of scopes that are requested for a token. If no
    /// scopes are provided, a token will not be issued.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<Scopes>,
    /// The URL that user entered. The authorization endpoint MAY use
    /// it as a hint of which user is attempting to sign in, and to
    /// indicate which profile URL the client is expecting in the
    /// resulting profile URL response or access token response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub me: Option<Url>,
}

impl AuthorizationRequest {
    /// Transform this authorization request into a vector of string
    /// pairs suitable into serialization into a query string.
    ///
    /// This is a bit more efficient than using serde, since it avoids
    /// a deserialization an borrows where possible.
    ///
    /// (In the current implementation, only the scope field is owned.)
    pub fn as_query_pairs(&'_ self) -> Vec<(&'static str, Cow<'_, str>)> {
        let mut v = vec![
            ("response_type", Cow::Borrowed(self.response_type.as_str())),
            ("client_id", Cow::Borrowed(self.client_id.as_str())),
            ("redirect_uri", Cow::Borrowed(self.redirect_uri.as_str())),
            ("code_challenge", Cow::Borrowed(self.code_challenge.as_str())),
            ("code_challenge_method", Cow::Borrowed(self.code_challenge.method().as_str())),
            ("state", Cow::Borrowed(self.state.as_ref()))
        ];

        if let Some(ref scope) = self.scope {
            v.push(
                ("scope", Cow::Owned(scope.to_string()))
            );
        }

        if let Some(ref me) = self.me {
            v.push(
                ("me", Cow::Borrowed(me.as_str()))
            );
        }

        v
    }
}

/// An authorization request that must be POSTed to an IndieAuth
/// endpoint together with a token with a scope of
/// `request_external_token:<scope>` to request external tokens with
/// the specific scope.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoAuthRequest {
    /// The response type expected for this request.
    /// Always [`ResponseType::ExternalToken`].
    pub response_type: ResponseType,
    /// URL for which the external token must be obtained.
    pub target_url: Url,
    /// An array of scopes that are requested for a token. All scopes
    /// must have a matching scope in the `request_external_token`
    /// realm.
    pub scope: Scopes,
    /// AutoAuth callback data. If not specified, polling will be
    /// used to return a token.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(flatten)]
    pub callback: Option<AutoAuthCallbackData>,
}

/// Data to be used to establish an AutoAuth callback.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoAuthCallbackData {
    state: State,
    callback_url: Url
}

#[inline(always)]
fn deserialize_secs<'de, D: serde::de::Deserializer<'de>>(d: D) -> Result<std::time::Duration, D::Error> {
    use serde::Deserialize;
    Ok(std::time::Duration::from_secs(u64::deserialize(d)?))
}

#[inline(always)]
fn serialize_secs<S: serde::ser::Serializer>(d: &std::time::Duration, s: S) -> Result<S::Ok, S::Error> {
    s.serialize_u64(std::time::Duration::as_secs(d))
}

/// Response to be returned in the start of AutoAuth polling flow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoAuthPollingResponse {
    request_id: State,
    #[serde(serialize_with = "serialize_secs")]
    #[serde(deserialize_with = "deserialize_secs")]
    interval: std::time::Duration
}

/// The authorization response that must be appended to the
/// [`AuthorizationRequest::redirect_uri`]'s query string.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationResponse {
    /// The authorization code generated by the authorization
    /// endpoint. The code MUST expire shortly after it is issued to
    /// mitigate the risk of leaks, and MUST be valid for only one
    /// use. A maximum lifetime of 10 minutes is recommended. See
    /// [OAuth 2.0 Section 4.1.2][oauth2-sec-4.1.2] for additional
    /// requirements on the authorization code.
    ///
    /// [oauth2-sec-4.1.2]: https://tools.ietf.org/html/rfc6749#section-4.1.2
    pub code: String,
    /// The state parameter from the [AuthorizationRequest],
    /// unmodified.
    pub state: State,
    /// The issuer identifier for client validation.
    ///
    /// Clients MUST verify this matches the [`Metadata::issuer`]
    /// parameter provided by the Server [Metadata] endpoint during
    /// Discovery as outlined in [OAuth 2.0 Authorization Server
    /// Issuer Identification][oauth2-iss]. If the value does not
    /// match the expected issuer identifier, clients MUST reject the
    /// authorization response and MUST NOT proceed with the
    /// authorization grant. For error responses, clients MUST NOT
    /// assume that the error originates from the intended
    /// authorization server.
    ///
    /// [oauth2-iss]: https://www.ietf.org/archive/id/draft-ietf-oauth-iss-auth-resp-02.html
    pub iss: Url
}


/// A special grant request that is used in the AutoAuth ceremony.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AutoAuthCodeGrant {
    /// Code that the requester's authorization endpoint generated.
    code: String,
    /// Client ID that this grant belongs to. Must always be the
    /// requester's authorization endpoint.
    client_id: Url,
    /// Root URI of the protection space.
    root_uri: Url,
    /// The authorization realm requested if any.
    realm: Option<String>,
    /// Scopes that the authorization endpoint trusts the client with.
    scope: Scopes,
    /// Randomly chosen spoofing-protection state.
    ///
    /// **DO NOT REUSE CLIENT STATE.**
    state: State,
    /// Callback URL to send the token to once the ceremony is done.
    callback_url: Url,
    /// The user's URL. Will be used to confirm the authorization
    /// endpoint's authority.
    me: Url
}

/// A grant request that continues the IndieAuth ceremony.
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "grant_type")]
#[serde(rename_all = "snake_case")]
pub enum GrantRequest {
    /// Use an authorization code to receive identity verification
    /// and/or an access token.
    AuthorizationCode {
        /// The code from [`AuthorizationResponse`].
        code: String,
        /// Client ID that this grant belongs to.
        client_id: Url,
        /// Redirect URI that was used to receive the grant.
        redirect_uri: Url,
        /// The PKCE code verifier that was used to create the code
        /// challenge.
        code_verifier: PKCEVerifier
    },
    /// Use a refresh token to get a fresh access token and a new
    /// matching refresh token.
    RefreshToken {
        /// The refresh token that was issued before.
        refresh_token: String,
        /// The client ID to which the token belongs to.
        client_id: url::Url,
        /// A list of scopes, not exceeding the already-granted scope,
        /// that can be passed to further restrict the scopes on the
        /// new token.
        ///
        /// This cannot be used to gain new scopes -- you need to
        /// start over if you need new scopes from the user.
        scope: Option<Scopes>
    }
}

/// Token type, as described in [RFC6749][].
///
/// [RFC6749]: https://www.rfc-editor.org/rfc/rfc6749#section-7.1
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenType {
    /// A Bearer token described in [RFC6750][]. As far as the author
    /// of this library is concerned, this is the only type that
    /// IndieAuth uses.
    ///
    /// [RFC6750]: https://www.rfc-editor.org/rfc/rfc6750
    Bearer
}

/// The response to a successful [`GrantRequest`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GrantResponse {
    /// An access token response, containing an access token, a refresh
    /// token (if the identity provider supports them) and the profile
    /// (if access was granted to the profile data).
    ///
    /// Is also used for AutoAuth: leave `profile` empty, do not issue
    /// a refresh token, pass `state`.
    AccessToken {
        /// The URL for the user this token corresponds to.
        me: Url,
        /// Token type. Required by OAuth2, not mentioned in
        /// IndieAuth. Confirmed as erroneous.
        token_type: TokenType,
        /// Scopes. REQUIRED if different from what was
        /// requested. Absence from IndieAuth spec confirmed as
        /// erroneous.
        scope: Option<Scopes>,
        /// The access token that can be used to access protected resources.
        access_token: String,
        /// Only used in AutoAuth. Protects from spoofing.
        #[serde(skip_serializing_if = "Option::is_none")]
        state: Option<State>,
        /// The duration in which the access token expires, represented in seconds.
        // TODO replace with std::time::Duration
        #[serde(skip_serializing_if = "Option::is_none")]
        expires_in: Option<u64>,
        /// The user's profile information, if it was requested.
        #[serde(skip_serializing_if = "Option::is_none")]
        profile: Option<Profile>,
        /// The refresh token, if it was issued.
        #[serde(skip_serializing_if = "Option::is_none")]
        refresh_token: Option<String>
    },
    /// A profile URL response, that only contains the profile URL and
    /// the profile, if it was requested.
    ///
    /// This is suitable for confirming the identity of the user, but
    /// no more than that.
    ProfileUrl(ProfileUrl)
}

/// The contents of a profile URL response.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProfileUrl {
    /// The authenticated user's URL.
    pub me: Url,
    /// The user's profile information, if it was requested.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile: Option<Profile>
}

#[cfg(feature = "axum")]
impl axum_core::response::IntoResponse for GrantResponse {
    fn into_response(self) -> axum_core::response::Response {
        use http::StatusCode;

        (StatusCode::OK,
         [("Content-Type", "application/json"),
          ("Cache-Control", "no-store"),
          ("Pragma", "no-cache")
         ],
         serde_json::to_vec(&self).unwrap())
            .into_response()
    }
}

/// Describes requests that the authorization endpoint might want to handle.
///
/// This type mostly exists for ease-of-use with serde.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
#[allow(missing_docs)]
pub enum RequestMaybeAuthorizationEndpoint {
    Authorization(AuthorizationRequest),
    Grant(GrantRequest),
    AutoAuth(AutoAuthCodeGrant)
}

/// A token introspection request that can be handled by the token
/// introspection endpoint.
///
/// Note that this request doesn't contain authentication data, which
/// is commonly transmitted out-of-band (e.g. via the `Authorization`
/// header).
#[derive(Debug, Serialize, Deserialize)]
pub struct TokenIntrospectionRequest {
    /// The token for which data was requested.
    pub token: String
}

/// Data for a token that will be returned by the introspection
/// endpoint (and can also be used internally by the resource server
/// if it is part of a monolith with the identity provider).
#[derive(Debug, Serialize, Deserialize)]
pub struct TokenData {
    /// The user this token corresponds to.
    pub me: Url,
    /// The client ID for the client that this token was issued to.
    pub client_id: Url,
    /// Scope that was granted to this token.
    pub scope: Scopes,
    /// The expiration date for this token, measured in seconds from
    /// the Unix time epoch (1970-01-01 00:00:00).
    // TODO replace these two with std::time::SystemTime
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exp: Option<u64>,
    /// The issue date, represented in the same format as the
    /// [`exp`][TokenData::exp] field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iat: Option<u64>
}

impl TokenData {
    /// Check if the token in question expired.
    pub fn expired(&self) -> bool {
        use std::time::{Duration, SystemTime, UNIX_EPOCH};

        self.exp
            .map(|exp| SystemTime::now()
                 .duration_since(UNIX_EPOCH)
                 .unwrap_or(Duration::ZERO)
                 .as_secs() >= exp)
            .unwrap_or_default()
    }

    /// Return a timestamp at which the token is not considered valid anymore.
    pub fn expires_at(&self) -> Option<std::time::SystemTime> {
        self.exp.map(|time| {
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(time)
        })
    }
    /// Return a timestamp describing when the token was issued.
    pub fn issued_at(&self) -> Option<std::time::SystemTime> {
        self.iat.map(|time| {
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(time)
        })
    }

    /// Check if a certain scope is allowed for this token.
    pub fn check_scope(&self, scope: &Scope) -> bool {
        self.scope.has(scope)
    }
}

// I don't like this type, because it could've been represented
// internally by Option<TokenData>. But the IndieAuth standard
// requires the "active" field to be present. I can't do anything
// about it.
/// The introspection response that the introspection endpoint must
/// return.
///
/// It is recommended to use the [`From`][`std::convert::From`] trait
/// to convert from `Option<TokenData>` for ergonomics.
#[derive(Debug, Serialize, Deserialize)]
pub struct TokenIntrospectionResponse {
    active: bool,
    #[serde(flatten)]
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<TokenData>
}
// These wrappers and impls should take care of making use of this
// type as painless as possible.
impl TokenIntrospectionResponse {
    /// Indicate that this token is not valid.
    pub fn inactive() -> Self {
        Self { active: false, data: None }
    }
    /// Indicate that this token is valid, and provide data about it.
    pub fn active(data: TokenData) -> Self {
        Self { active: true, data: Some(data) }
    }
    /// Check if the endpoint reports this token as valid.
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Get data contained in the response, if the token is valid.
    pub fn data(&self) -> Option<&TokenData> {
        if !self.active {
            return None
        }
        self.data.as_ref()
    }
}
impl Default for TokenIntrospectionResponse {
    fn default() -> Self {
        Self::inactive()
    }
}
impl From<Option<TokenData>> for TokenIntrospectionResponse {
    fn from(data: Option<TokenData>) -> Self {
        Self { active: data.is_some(), data }
    }
}
impl From<TokenIntrospectionResponse> for Option<TokenData> {
    fn from(response: TokenIntrospectionResponse) -> Option<TokenData> {
        response.data
    }
}

#[cfg(feature = "axum")]
impl axum_core::response::IntoResponse for TokenIntrospectionResponse {
    fn into_response(self) -> axum_core::response::Response {
        use http::StatusCode;

        (StatusCode::OK,
         [("Content-Type", "application/json")],
         serde_json::to_vec(&self).unwrap())
            .into_response()
    }
}

/// A request for revoking a token. There is no response beyond `HTTP
/// 200 OK`.
#[derive(Debug, Serialize, Deserialize)]
pub struct TokenRevocationRequest {
    /// The token that needs to be revoked in case it is valid.
    pub token: String
}

/// Types of errors that a resource server (IndieAuth consumer) can
/// throw when authentication goes wrong.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceErrorKind {
    /// The provided token was invalid.
    InvalidToken,
    /// The scope on the token was insufficient to perform the
    /// requested operation.
    InsufficientScope,
}

/// Various kinds of errors that could occur when performing the
/// IndieAuth ceremony.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorKind {
    /// The request is missing a required parameter, includes an
    /// unsupported parameter value (other than grant type), repeats a
    /// parameter, includes multiple credentials, utilizes more than
    /// one mechanism for authenticating the client, or is otherwise
    /// malformed.
    InvalidRequest,
    /// Client authentication failed (e.g., unknown client, no client
    /// authentication included, or unsupported authentication
    /// method).  The authorization server MAY return an HTTP 401
    /// (Unauthorized) status code to indicate which HTTP
    /// authentication schemes are supported.  If the client attempted
    /// to authenticate via the "Authorization" request header field,
    /// the authorization server MUST respond with an HTTP 401
    /// (Unauthorized) status code and include the "WWW-Authenticate"
    /// response header field matching the authentication scheme used
    /// by the client.
    InvalidClient,
    /// The provided authorization grant (e.g., authorization
    /// code, resource owner credentials) or refresh token is
    /// invalid, expired, revoked, does not match the redirection
    /// URI used in the authorization request, or was issued to
    /// another client.
    InvalidGrant,
    /// The authenticated client is not authorized to use this
    /// authorization grant type.
    UnauthorizedClient,
    /// The authorization grant type is not supported by the
    /// authorization server.
    UnsupportedGrantType,
    /// The requested scope is invalid, unknown, malformed, or
    /// exceeds the scope granted by the resource owner.
    InvalidScope,
    /// AutoAuth/OAuth2 Device Flow: authorization ceremony is still
    /// being performed. Wait `interval` seconds and try again.
    AuthorizationPending,
    /// AutoAuth/OAuth2 Device Flow: You're polling too fast, slow
    /// down by 5 seconds for all subsequent requests.
    SlowDown,
    /// AutoAuth/OAuth2 Device Flow: Access was denied by the
    /// authorization endpoint.
    AccessDenied,
    
}
// TODO consider relying on serde_variant for these conversions
impl AsRef<str> for ErrorKind {
    fn as_ref(&self) -> &str {
        match self {
            ErrorKind::InvalidRequest => "invalid_request",
            ErrorKind::InvalidClient => "invalid_client",
            ErrorKind::InvalidGrant => "invalid_grant",
            ErrorKind::UnauthorizedClient => "unauthorized_client",
            ErrorKind::UnsupportedGrantType => "unsupported_grant_type",
            ErrorKind::InvalidScope => "invalid_scope",
            ErrorKind::AuthorizationPending => "authorization_pending",
            ErrorKind::SlowDown => "slow_down",
            ErrorKind::AccessDenied => "access_denied",
        }
    }
}
impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_ref())
    }
}

/// An error that can be returned when performing the IndieAuth ceremony.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Error {
    /// Type of an error.
    #[serde(rename = "error")]
    pub kind: ErrorKind,
    /// Human-friendly description of an error, suitable for a
    /// developer to read while debugging.
    #[serde(rename = "error_description")]
    pub msg: Option<String>,
    /// An URL to documentation describing what went wrong and how to
    /// fix it.
    pub error_uri: Option<url::Url>
}

impl From<ErrorKind> for Error {
    fn from(kind: ErrorKind) -> Error {
        Error {
            kind, msg: None, error_uri: None
        }
    }
}

impl std::error::Error for self::Error {}

impl std::fmt::Display for self::Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "IndieAuth error ({})", self.kind)?;
        if let Some(msg) = self.msg.as_deref() {
            write!(f, ": {}", msg)?;
        }
        if let Some(error_uri) = &self.error_uri {
            write!(f, " (see `{}` for more info)", error_uri)?;
        }

        Ok(())
    }
}

#[cfg(feature = "axum")]
impl axum_core::response::IntoResponse for self::Error {
    fn into_response(self) -> axum_core::response::Response {
        use http::StatusCode;

        (StatusCode::BAD_REQUEST,
         [("Content-Type", "application/json")],
         serde_json::to_vec(&self).unwrap())
            .into_response()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_serialize_deserialize_grant_request() {
        let authorization_code: GrantRequest = GrantRequest::AuthorizationCode {
            client_id: "https://kittybox.fireburn.ru/".parse().unwrap(),
            redirect_uri: "https://kittybox.fireburn.ru/.kittybox/login/redirect".parse().unwrap(),
            code_verifier: PKCEVerifier("helloworld".to_string()),
            code: "hithere".to_owned()
        };
        let serialized = serde_urlencoded::to_string([
            ("grant_type", "authorization_code"),
            ("code", "hithere"),
            ("client_id", "https://kittybox.fireburn.ru/"),
            ("redirect_uri", "https://kittybox.fireburn.ru/.kittybox/login/redirect"),
            ("code_verifier", "helloworld"),
        ]).unwrap();

        let deserialized = serde_urlencoded::from_str(&serialized).unwrap();

        assert_eq!(authorization_code, deserialized);

        assert_eq!(
            serialized,
            serde_urlencoded::to_string(authorization_code).unwrap()
        )
    }
}