summaryrefslogtreecommitdiff
path: root/crates/common/src/auth/oauth/oidc.rs
blob: 16a9192be066eef016a934763f49c28ae42bac30 (plain)
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use std::fmt;

use biscuit::{jws::RegisteredHeader, ClaimsSet, RegisteredClaims, SingleOrMultiple, JWT};
use serde::{
    de::{self, Visitor},
    Deserialize, Deserializer, Serialize,
};
use store::write::now;

use crate::Server;

#[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub struct Userinfo {
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sub: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub given_name: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub family_name: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub middle_name: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nickname: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preferred_username: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub picture: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub website: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,

    #[serde(default, deserialize_with = "any_bool")]
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub email_verified: bool,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub zoneinfo: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,

    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<i64>,
}

impl Server {
    pub fn issue_id_token(
        &self,
        subject: impl Into<String>,
        issuer: impl Into<String>,
        audience: impl Into<String>,
    ) -> trc::Result<String> {
        let now = now() as i64;

        JWT::new_decoded(
            From::from(RegisteredHeader {
                algorithm: self.core.oauth.oidc_signature_algorithm,
                key_id: Some("default".into()),
                ..Default::default()
            }),
            ClaimsSet::<()> {
                registered: RegisteredClaims {
                    issuer: Some(issuer.into()),
                    subject: Some(subject.into()),
                    audience: Some(SingleOrMultiple::Single(audience.into())),
                    not_before: Some(now.into()),
                    issued_at: Some(now.into()),
                    expiry: Some((now + self.core.oauth.oidc_expiry_id_token as i64).into()),
                    ..Default::default()
                },
                private: (),
            },
        )
        .into_encoded(&self.core.oauth.oidc_signing_secret)
        .map(|token| token.unwrap_encoded().to_string())
        .map_err(|err| {
            trc::AuthEvent::Error
                .into_err()
                .reason(err)
                .details("Failed to encode ID token")
        })
    }
}

fn any_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    struct AnyBoolVisitor;

    impl<'de> Visitor<'de> for AnyBoolVisitor {
        type Value = bool;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a boolean value")
        }

        fn visit_str<E>(self, value: &str) -> Result<bool, E>
        where
            E: de::Error,
        {
            match value {
                "true" => Ok(true),
                "false" => Ok(false),
                _ => Err(E::custom(format!("Unknown boolean: {value}"))),
            }
        }

        fn visit_bool<E>(self, value: bool) -> Result<bool, E>
        where
            E: de::Error,
        {
            Ok(value)
        }
    }

    deserializer.deserialize_any(AnyBoolVisitor)
}