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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! # Frontegg API client
//!
//! The `client` module provides an API client with typed methods for
//! interacting with the Frontegg API. This client implements authentication,
//! token management, and basic requests against the API.
//!
//! The [`Client`] requires an [`AppPassword`] as a parameter. The
//! app password is used to manage an access token. _Manage_ means issuing a new
//! access token or refreshing when half of its lifetime has passed.
//!
//! [`AppPassword`]: mz_frontegg_auth::AppPassword

use std::time::{Duration, SystemTime};

use jsonwebtoken::jwk::JwkSet;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use mz_frontegg_auth::{AppPassword, Claims};
use reqwest::{Method, RequestBuilder};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use url::Url;

use crate::config::{ClientBuilder, ClientConfig};
use crate::error::{ApiError, Error};

pub mod app_password;
pub mod role;
pub mod user;

const CREDENTIALS_AUTH_PATH: [&str; 5] = ["identity", "resources", "auth", "v1", "user"];
const APP_PASSWORD_AUTH_PATH: [&str; 5] = ["identity", "resources", "auth", "v1", "api-token"];

const REFRESH_AUTH_PATH: [&str; 7] = [
    "identity",
    "resources",
    "auth",
    "v1",
    "api-token",
    "token",
    "refresh",
];

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AuthenticationResponse {
    access_token: String,
    expires: String,
    expires_in: i64,
    refresh_token: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CredentialsAuthenticationRequest<'a> {
    email: &'a str,
    password: &'a str,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AppPasswordAuthenticationRequest<'a> {
    client_id: &'a str,
    secret: &'a str,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RefreshRequest<'a> {
    refresh_token: &'a str,
}

#[derive(Debug, Clone)]
pub(crate) struct Auth {
    token: String,
    /// The time after which the token must be refreshed.
    refresh_at: SystemTime,
    refresh_token: String,
}

/// Representation of the two possible ways to authenticate a user.
///
/// The usage of [Authentication::AppPassword] is more favorable
/// and recommended. App-passwords can be created for a particular
/// usage and be removed at any time. While the user credentials
/// may have a broader impact.
pub enum Authentication {
    /// Legitimate email and password that will remain in use to identify
    /// the user throughout the client's existence.
    Credentials(Credentials),
    /// A singular, legitimate app password that will remain in use to identify
    /// the user throughout the client's existence.
    AppPassword(AppPassword),
}

/// Representation of a user's credentials.
/// They are the same as a user needs to
/// log in to Materialize's console.
pub struct Credentials {
    /// User's email to authenticate with Materialize console
    pub email: String,
    /// User's password to authenticate with Materialize console
    pub password: String,
}

/// An API client for Frontegg.
///
/// The API client is designed to be wrapped in an [`Arc`] and used from
/// multiple threads simultaneously. A successful authentication response is
/// shared by all threads.
///
/// [`Arc`]: std::sync::Arc
pub struct Client {
    pub(crate) inner: reqwest::Client,
    pub(crate) authentication: Authentication,
    pub(crate) endpoint: Url,
    pub(crate) auth: Mutex<Option<Auth>>,
}

impl Client {
    /// Creates a new `Client` from its required configuration parameters.
    pub fn new(config: ClientConfig) -> Client {
        ClientBuilder::default().build(config)
    }

    /// Creates a builder for a `Client` that allows for customization of
    /// optional parameters.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Builds a request towards the `Client`'s endpoint
    fn build_request<P>(&self, method: Method, path: P) -> RequestBuilder
    where
        P: IntoIterator,
        P::Item: AsRef<str>,
    {
        let mut url = self.endpoint.clone();
        url.path_segments_mut()
            .expect("builder validated URL can be a base")
            .clear()
            .extend(path);
        self.inner.request(method, url)
    }

    /// Sends a requests and adds the authorization bearer token.
    async fn send_request<T>(&self, req: RequestBuilder) -> Result<T, Error>
    where
        T: DeserializeOwned,
    {
        let token = self.auth().await?;
        let req = req.bearer_auth(token);
        self.send_unauthenticated_request(req).await
    }

    async fn send_unauthenticated_request<T>(&self, req: RequestBuilder) -> Result<T, Error>
    where
        T: DeserializeOwned,
    {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct ErrorResponse {
            #[serde(default)]
            message: Option<String>,
            #[serde(default)]
            errors: Vec<String>,
        }

        let res = req.send().await?;
        let status_code = res.status();
        if status_code.is_success() {
            Ok(res.json().await?)
        } else {
            match res.json::<ErrorResponse>().await {
                Ok(e) => {
                    let mut messages = e.errors;
                    messages.extend(e.message);
                    Err(Error::Api(ApiError {
                        status_code,
                        messages,
                    }))
                }
                Err(_) => Err(Error::Api(ApiError {
                    status_code,
                    messages: vec!["unable to decode error details".into()],
                })),
            }
        }
    }

    /// Authenticates with the server, if not already authenticated,
    /// and returns the authentication token.
    pub async fn auth(&self) -> Result<String, Error> {
        let mut auth = self.auth.lock().await;
        let mut req;

        match &*auth {
            Some(auth) => {
                if SystemTime::now() < auth.refresh_at {
                    return Ok(auth.token.clone());
                } else {
                    // Auth is available in the client but needs a refresh request.
                    req = self.build_request(Method::POST, REFRESH_AUTH_PATH);
                    let refresh_request = RefreshRequest {
                        refresh_token: auth.refresh_token.as_str(),
                    };
                    req = req.json(&refresh_request);
                }
            }
            None => {
                match &self.authentication {
                    Authentication::Credentials(credentials) => {
                        // No auth available in the client, request a new one.
                        req = self.build_request(Method::POST, CREDENTIALS_AUTH_PATH);

                        let authentication_request = CredentialsAuthenticationRequest {
                            email: &credentials.email,
                            password: &credentials.password,
                        };
                        req = req.json(&authentication_request);
                    }
                    Authentication::AppPassword(app_password) => {
                        req = self.build_request(Method::POST, APP_PASSWORD_AUTH_PATH);

                        let authentication_request = AppPasswordAuthenticationRequest {
                            client_id: &app_password.client_id.to_string(),
                            secret: &app_password.secret_key.to_string(),
                        };
                        req = req.json(&authentication_request);
                    }
                }
            }
        }

        // Do the request.
        let res: AuthenticationResponse = self.send_unauthenticated_request(req).await?;

        *auth = Some(Auth {
            token: res.access_token.clone(),
            // Refresh twice as frequently as we need to, to be safe.
            refresh_at: SystemTime::now()
                + (Duration::from_secs(res.expires_in.try_into().unwrap()) / 2),
            refresh_token: res.refresh_token,
        });
        Ok(res.access_token)
    }

    /// Returns the JSON Web Key Set (JWKS) from the well known endpoint: `/.well-known/jwks.json`
    async fn get_jwks(&self) -> Result<JwkSet, Error> {
        let well_known = vec![".well-known", "jwks.json"];
        let req = self.build_request(Method::GET, well_known);
        let jwks: JwkSet = self.send_request(req).await?;
        Ok(jwks)
    }

    /// Verifies the JWT signature using a JWK from the well-known endpoint and
    /// returns the user claims.
    pub async fn claims(&self) -> Result<Claims, Error> {
        let jwks = self.get_jwks().await.map_err(|_| Error::FetchingJwks)?;
        let jwk = jwks.keys.first().ok_or_else(|| Error::EmptyJwks)?;
        let token = self.auth().await?;

        let mut validation = Validation::new(Algorithm::RS256);

        // We don't validate the audience because:
        //
        //   1. We don't have easy access to the expected audience ID here.
        //
        //   2. There is no meaningful security improvement to doing so, because
        //      Frontegg always sets the audience to the ID of the workspace
        //      that issued the token. Since we only trust the signing keys from
        //      a single Frontegg workspace, the audience is redundant.
        //
        // For details, see this conversation [0] from the Materialize–Frontegg
        // shared Slack channel on 1 January 2024.
        //
        // [0]: https://materializeinc.slack.com/archives/C02940WNMRQ/p1704131331041669
        validation.validate_aud = false;

        let token_data = decode::<Claims>(
            &token,
            &DecodingKey::from_jwk(jwk).map_err(|_| Error::ConvertingJwks)?,
            &validation,
        )
        .map_err(Error::DecodingClaims)?;

        Ok(token_data.claims)
    }
}