Skip to main content

light_openid/
client.rs

1//! # Open ID client implementation
2
3use crate::code_challenge::CodeChallenge;
4use crate::errors::{OpenIdError, Res};
5use crate::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
6use crate::utils::http_client;
7use jsonwebtoken::{DecodingKey, TokenData, Validation};
8use serde::de::DeserializeOwned;
9use std::collections::{HashMap, HashSet};
10use std::fmt::Display;
11use zeroize::Zeroizing;
12
13/// OpenID client options
14#[derive(Debug, Clone)]
15pub struct OpenIDClientOpts {
16    /// This client ID
17    pub client_id: String,
18    /// This client secret
19    pub client_secret: Option<Zeroizing<String>>,
20    /// Redirect URI to use when performing authentication requests
21    pub redirect_uri: String,
22    /// Disable id token signature & content check
23    pub validate_id_token_sig: bool,
24    /// Accepted audiences in JWT
25    pub accepted_audiences: Vec<String>,
26    /// Whether audience field of jwt should be validated or not
27    pub validate_aud: bool,
28    /// Whether expiration field of jwt should be validated or not
29    pub validate_exp: bool,
30    /// Whether not before field of jwt should be validated or not
31    pub validate_nbf: bool,
32}
33
34impl OpenIDClientOpts {
35    pub fn new(
36        client_id: impl Display,
37        client_secret: Option<&str>,
38        redirect_uri: impl Display,
39    ) -> Self {
40        Self {
41            client_id: client_id.to_string(),
42            client_secret: client_secret.map(|s| Zeroizing::new(s.to_string())),
43            redirect_uri: redirect_uri.to_string(),
44            accepted_audiences: vec![client_id.to_string()],
45            validate_id_token_sig: true,
46            validate_aud: true,
47            validate_exp: true,
48            validate_nbf: false,
49        }
50    }
51}
52
53enum TokenEndpointAuth<'a> {
54    AuthorizationCode(&'a str),
55    RefreshToken(&'a str),
56}
57
58/// OpenID client
59pub struct OpenIDClient {
60    pub config: OpenIDConfig,
61    pub jwks: Option<jsonwebtoken::jwk::JwkSet>,
62    pub opts: OpenIDClientOpts,
63}
64
65impl OpenIDClient {
66    /// Construct an OpenID client by give hard-coded configuration values
67    pub async fn new(
68        config: OpenIDConfig,
69        jwks: Option<jsonwebtoken::jwk::JwkSet>,
70        opts: &OpenIDClientOpts,
71    ) -> Self {
72        Self {
73            config,
74            jwks,
75            opts: opts.clone(),
76        }
77    }
78
79    /// Construct an OpenID client by loading configuration from a given
80    /// .well-known/openid-configuration URL
81    #[tracing::instrument(skip(opts))]
82    pub async fn new_from_url(url: &str, opts: &OpenIDClientOpts) -> Res<Self> {
83        let config = http_client::get_json_request(url).await?;
84
85        let mut client = Self {
86            config,
87            jwks: None,
88            opts: opts.clone(),
89        };
90
91        if opts.validate_id_token_sig {
92            client.jwks = Some(http_client::get_json_request(&client.config.jwks_uri).await?)
93        }
94
95        Ok(client)
96    }
97
98    /// Get the authorization URL where a user should be redirect to perform authentication
99    #[tracing::instrument(skip(self, state))]
100    pub fn gen_authorization_url(
101        &self,
102        state: &str,
103        code_challenge: Option<CodeChallenge>,
104    ) -> String {
105        let client_id = urlencoding::encode(self.opts.client_id.as_str());
106        let state = urlencoding::encode(state);
107        let redirect_uri = urlencoding::encode(self.opts.redirect_uri.as_str());
108
109        let mut url = format!(
110            "{}?response_type=code&scope=openid%20profile%20email&client_id={client_id}&state={state}&redirect_uri={redirect_uri}",
111            self.config.authorization_endpoint
112        );
113
114        if let Some(chlg) = code_challenge {
115            let code_challenge = urlencoding::encode(&chlg.code_challenge);
116            let code_challenge_method = urlencoding::encode(&chlg.code_challenge_method);
117
118            url.push_str(&format!(
119                "&code_challenge={code_challenge}&code_challenge_method={code_challenge_method}"
120            ))
121        }
122
123        url
124    }
125
126    /// Query the token endpoint using an authorization code
127    #[tracing::instrument(skip(self, code, code_verifier))]
128    pub async fn request_token_from_code(
129        &self,
130        code: &str,
131        code_verifier: Option<&str>,
132    ) -> Res<(OpenIDTokenResponse, String)> {
133        self.request_token(&TokenEndpointAuth::AuthorizationCode(code), code_verifier)
134            .await
135    }
136
137    /// Query the token endpoint using a refresh token
138    #[tracing::instrument(skip(self, refresh_token))]
139    pub async fn request_token_from_refresh_token(
140        &self,
141        refresh_token: &str,
142    ) -> Res<(OpenIDTokenResponse, String)> {
143        self.request_token(&TokenEndpointAuth::RefreshToken(refresh_token), None)
144            .await
145    }
146
147    /// Query the token endpoint
148    ///
149    /// This endpoint returns both the parsed and the raw response, to allow handling
150    /// of bonus fields
151    async fn request_token(
152        &self,
153        auth: &TokenEndpointAuth<'_>,
154        code_verifier: Option<&str>,
155    ) -> Res<(OpenIDTokenResponse, String)> {
156        let mut params = HashMap::new();
157        match auth {
158            TokenEndpointAuth::AuthorizationCode(code) => {
159                params.insert("grant_type", "authorization_code");
160                params.insert("code", code);
161            }
162            TokenEndpointAuth::RefreshToken(token) => {
163                params.insert("grant_type", "refresh_token");
164                params.insert("refresh_token", token);
165            }
166        }
167        if let Some(verifier) = code_verifier {
168            params.insert("code_verifier", verifier);
169        }
170        params.insert("redirect_uri", self.opts.redirect_uri.as_str());
171
172        let response = http_client::send_request(
173            reqwest::Client::new()
174                .post(&self.config.token_endpoint)
175                .basic_auth(&self.opts.client_id, self.opts.client_secret.as_deref())
176                .form(&params),
177        )
178        .await?
179        .text()
180        .await?;
181
182        let token: OpenIDTokenResponse = serde_json::from_str(&response)?;
183
184        // Check id token signature
185        if self.opts.validate_id_token_sig
186            && self.jwks.is_some()
187            && let Some(id_token) = &token.id_token
188        {
189            self.verify_jwt::<serde_json::Value>(id_token)
190                .map_err(|e| OpenIdError::ValidateIdToken(Box::new(e)))?;
191        }
192
193        Ok((token, response))
194    }
195
196    /// Decode & verify a JWT signature
197    pub fn verify_jwt<T: DeserializeOwned>(&self, jwt: &str) -> Res<TokenData<T>> {
198        let header = jsonwebtoken::decode_header(jwt).map_err(OpenIdError::DecodeJWTHeader)?;
199
200        let Some(kid) = header.kid else {
201            return Err(OpenIdError::KidRequiredForSignatureVerification);
202        };
203
204        let Some(jwks) = &self.jwks else {
205            return Err(OpenIdError::MissingJWKs);
206        };
207
208        let Some(jwk) = jwks.find(&kid) else {
209            return Err(OpenIdError::UnknownKid(kid));
210        };
211
212        let decoding_key = DecodingKey::from_jwk(jwk).map_err(OpenIdError::DecodeJWK)?;
213
214        let mut validation = Validation::new(header.alg);
215        validation.validate_aud = true;
216        validation.aud = Some(HashSet::from_iter(
217            self.opts.accepted_audiences.iter().cloned(),
218        ));
219        validation.validate_aud = self.opts.validate_aud;
220        validation.validate_exp = self.opts.validate_exp;
221        validation.validate_nbf = self.opts.validate_nbf;
222
223        jsonwebtoken::decode(jwt, &decoding_key, &validation).map_err(OpenIdError::ValidateJWT)
224    }
225
226    /// Query the UserInfo endpoint.
227    ///
228    /// This endpoint should be used after having successfully retrieved the token
229    ///
230    /// This endpoint returns both the parsed value and the raw response, in case of presence
231    /// of additional fields
232    #[tracing::instrument(skip(self, token))]
233    pub async fn request_user_info(
234        &self,
235        token: &OpenIDTokenResponse,
236    ) -> Res<(OpenIDUserInfo, String)> {
237        let response = http_client::send_request(
238            reqwest::Client::new()
239                .get(self.config.userinfo_endpoint.as_ref().expect(
240                    "This client only support information retrieval through userinfo endpoint!",
241                ))
242                .header("Authorization", format!("Bearer {}", token.access_token)),
243        )
244        .await?
245        .text()
246        .await?;
247
248        Ok((serde_json::from_str(&response)?, response))
249    }
250}