watchword 0.1.0

Authentication for axum servers and Yew frontends: password, Cloudflare Access and Google sign-in, sessions and user management.
Documentation
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
//! Identifying users behind Cloudflare Access.
//!
//! Access forwards the authenticated user's email in a header and a signed
//! JWT (RS256) in a header and the `CF_Authorization` cookie. The JWT is
//! verified against the team's signing keys published at
//! `https://<team_domain>/cdn-cgi/access/certs`.
//!
//! [`Access`] identifies a request's user by email. The [`Auth`](crate::Auth)
//! service builds on it: it takes the settings as a
//! [`CloudflareConfig`](crate::CloudflareConfig) (see
//! [`AuthBuilder::cloudflare`](crate::AuthBuilder::cloudflare) and
//! [`Auth::set_cloudflare`](crate::Auth::set_cloudflare)), matches the
//! email to an existing user, and signs them in with
//! [`Auth::sign_in_cloudflare`](crate::Auth::sign_in_cloudflare).

use std::collections::HashMap;
use std::error::Error as StdError;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use aws_lc_rs::rsa::PublicKeyComponents;
use aws_lc_rs::signature::RSA_PKCS1_2048_8192_SHA256;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use cookie::Cookie;
use http::HeaderMap;
use http::header::COOKIE;
use jiff::Timestamp;
use serde::Deserialize;

use crate::types::normalize_email;

mod provider;
pub(crate) use self::provider::Provider;

/// The header in which Access sends the authenticated user's email.
pub const EMAIL_HEADER: &str = "cf-access-authenticated-user-email";
/// The header in which Access sends its signed JWT.
pub const JWT_HEADER: &str = "cf-access-jwt-assertion";
/// The cookie in which Access keeps its signed JWT.
pub const JWT_COOKIE: &str = "CF_Authorization";

/// Tolerated clock skew when checking `exp` and `nbf`.
const LEEWAY_SECONDS: i64 = 60;

/// Unknown key ids trigger a refetch at most this often, failed or not, so
/// forged tokens cannot make every request fetch the keys.
const MIN_REFETCH_INTERVAL: Duration = Duration::from_secs(60);

/// How long fetching the signing keys may take.
const FETCH_TIMEOUT: Duration = Duration::from_secs(10);

/// How [`Access`] identifies a request's user.
#[derive(Debug, Clone)]
pub struct Config {
    /// The team's host, such as `example.cloudflareaccess.com`.
    pub team_domain: String,
    /// The Access application's audience (AUD) tag.
    pub audience: String,
    /// Accept the email header that Access sets.
    pub trust_email_header: bool,
    /// Require and verify the Access JWT.
    pub verify_jwt: bool,
}

/// Why [`Access`] did not identify a request's user.
#[derive(Debug, thiserror::Error)]
pub enum AccessError {
    #[error("neither the email header nor the JWT is enabled")]
    Disabled,
    #[error("missing {EMAIL_HEADER} header")]
    MissingEmail,
    #[error("missing Access JWT")]
    MissingJwt,
    #[error("malformed Access JWT")]
    Malformed,
    #[error("unsupported JWT algorithm")]
    UnsupportedAlgorithm,
    #[error("unknown JWT signing key")]
    UnknownKey,
    #[error("invalid JWT signature")]
    BadSignature,
    #[error("JWT audience does not match")]
    WrongAudience,
    #[error("JWT issuer does not match")]
    WrongIssuer,
    #[error("JWT has expired")]
    Expired,
    #[error("JWT is not yet valid")]
    NotYetValid,
    #[error("JWT has no email")]
    MissingJwtEmail,
    #[error("email header does not match the JWT")]
    EmailMismatch,
    #[error("failed to fetch Access signing keys")]
    Fetch(#[source] Box<dyn StdError + Send + Sync>),
    #[error("fetching Access signing keys failed recently; retrying within a minute")]
    FetchFailedRecently,
}

/// An RSA signing key, with `n` and `e` as big-endian bytes.
#[derive(Debug, Clone)]
pub struct Jwk {
    /// The key id, as named by a JWT's `kid`.
    pub kid: String,
    /// The modulus.
    pub n: Vec<u8>,
    /// The public exponent.
    pub e: Vec<u8>,
}

/// Fetches a team's current signing keys.
pub trait KeyFetcher: Send + Sync {
    /// Fetches the signing keys of the team at `team_domain`.
    fn fetch(
        &self,
        team_domain: &str,
    ) -> impl Future<Output = Result<Vec<Jwk>, Box<dyn StdError + Send + Sync>>> + Send;
}

/// Fetches signing keys from Cloudflare over HTTPS.
#[derive(Debug, Clone, Default)]
pub struct HttpKeyFetcher {
    client: reqwest::Client,
}

impl HttpKeyFetcher {
    /// Fetches with `client`. Crate-private so reqwest stays out of the
    /// public API; apps use [`HttpKeyFetcher::default`].
    pub(crate) fn new(client: reqwest::Client) -> Self {
        Self { client }
    }
}

impl KeyFetcher for HttpKeyFetcher {
    async fn fetch(&self, team_domain: &str) -> Result<Vec<Jwk>, Box<dyn StdError + Send + Sync>> {
        let url = format!("https://{team_domain}/cdn-cgi/access/certs");
        let body = self
            .client
            .get(url)
            .timeout(FETCH_TIMEOUT)
            .send()
            .await?
            .error_for_status()?
            .bytes()
            .await?;
        Ok(parse_jwks(&body)?)
    }
}

/// Why a key set could not be parsed.
#[derive(Debug, thiserror::Error)]
pub enum JwksError {
    #[error("malformed key set")]
    Json(#[from] serde_json::Error),
    #[error("malformed key component")]
    Base64(#[from] base64::DecodeError),
}

/// Parses a JSON Web Key Set, keeping its RSA keys.
pub fn parse_jwks(body: &[u8]) -> Result<Vec<Jwk>, JwksError> {
    #[derive(Deserialize)]
    struct Set {
        keys: Vec<Key>,
    }

    #[derive(Deserialize)]
    struct Key {
        kty: String,
        kid: Option<String>,
        n: Option<String>,
        e: Option<String>,
    }

    let set: Set = serde_json::from_slice(body)?;
    let mut keys = Vec::new();

    for key in set.keys {
        let (Some(kid), Some(n), Some(e)) = (key.kid, key.n, key.e) else {
            continue;
        };

        if key.kty != "RSA" {
            continue;
        }

        keys.push(Jwk {
            kid,
            n: URL_SAFE_NO_PAD.decode(n)?,
            e: URL_SAFE_NO_PAD.decode(e)?,
        });
    }

    Ok(keys)
}

#[derive(Default)]
struct KeyCache {
    keys: HashMap<String, PublicKeyComponents<Vec<u8>>>,
    /// When the keys were last fetched or a fetch was last attempted.
    attempted_at: Option<Instant>,
    failed: bool,
}

/// Identifies the user of a request that came through Cloudflare Access.
pub struct Access<F = HttpKeyFetcher> {
    config: Config,
    fetcher: F,
    cache: Mutex<KeyCache>,
    /// Held while fetching, so concurrent requests share one fetch.
    fetching: tokio::sync::Mutex<()>,
}

impl Access<HttpKeyFetcher> {
    /// Identifies users as `config` says, fetching keys from Cloudflare.
    pub fn new(config: Config) -> Self {
        Self::with_fetcher(config, HttpKeyFetcher::default())
    }
}

impl<F> Access<F>
where
    F: KeyFetcher,
{
    /// Identifies users as `config` says, fetching keys with `fetcher`.
    pub fn with_fetcher(config: Config, fetcher: F) -> Self {
        Self {
            config,
            fetcher,
            cache: Mutex::new(KeyCache::default()),
            fetching: tokio::sync::Mutex::new(()),
        }
    }

    /// Returns the normalized email of the request's user.
    ///
    /// With both sources enabled, the header's email must match the JWT's.
    pub async fn email(&self, headers: &HeaderMap) -> Result<String, AccessError> {
        self.email_at(headers, Timestamp::now()).await
    }

    async fn email_at(&self, headers: &HeaderMap, now: Timestamp) -> Result<String, AccessError> {
        let header_email = if self.config.trust_email_header {
            let email = headers
                .get(EMAIL_HEADER)
                .and_then(|v| v.to_str().ok())
                .map(normalize_email)
                .filter(|e| !e.is_empty())
                .ok_or(AccessError::MissingEmail)?;
            Some(email)
        } else {
            None
        };

        if !self.config.verify_jwt {
            return header_email.ok_or(AccessError::Disabled);
        }

        let token = jwt_from_headers(headers).ok_or(AccessError::MissingJwt)?;
        let jwt_email = self.verify_jwt(&token, now).await?;

        if let Some(header_email) = header_email
            && header_email != jwt_email
        {
            return Err(AccessError::EmailMismatch);
        }

        Ok(jwt_email)
    }

    /// Verifies an Access JWT and returns its normalized email.
    async fn verify_jwt(&self, token: &str, now: Timestamp) -> Result<String, AccessError> {
        #[derive(Deserialize)]
        struct Header {
            alg: String,
            kid: String,
        }

        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Audience {
            One(String),
            Many(Vec<String>),
        }

        #[derive(Deserialize)]
        struct Claims {
            aud: Audience,
            iss: String,
            exp: i64,
            nbf: Option<i64>,
            email: Option<String>,
        }

        let mut parts = token.split('.');

        let (Some(header), Some(claims), Some(signature), None) =
            (parts.next(), parts.next(), parts.next(), parts.next())
        else {
            return Err(AccessError::Malformed);
        };

        let signed = &token[..header.len() + 1 + claims.len()];
        let header: Header = decode_part(header)?;

        if header.alg != "RS256" {
            return Err(AccessError::UnsupportedAlgorithm);
        }

        let signature = URL_SAFE_NO_PAD
            .decode(signature)
            .map_err(|_| AccessError::Malformed)?;
        let key = self.key(&header.kid).await?;

        key.verify(&RSA_PKCS1_2048_8192_SHA256, signed.as_bytes(), &signature)
            .map_err(|_| AccessError::BadSignature)?;

        let claims: Claims = decode_part(claims)?;

        let audience_matches = match &claims.aud {
            Audience::One(aud) => *aud == self.config.audience,
            Audience::Many(auds) => auds.contains(&self.config.audience),
        };

        if !audience_matches {
            return Err(AccessError::WrongAudience);
        }

        if claims.iss != format!("https://{}", self.config.team_domain) {
            return Err(AccessError::WrongIssuer);
        }

        let now = now.as_second();

        if claims.exp + LEEWAY_SECONDS <= now {
            return Err(AccessError::Expired);
        }

        if claims.nbf.is_some_and(|nbf| nbf - LEEWAY_SECONDS > now) {
            return Err(AccessError::NotYetValid);
        }

        let email = claims
            .email
            .as_deref()
            .map(normalize_email)
            .filter(|e| !e.is_empty())
            .ok_or(AccessError::MissingJwtEmail)?;

        Ok(email)
    }

    /// Looks up a signing key, refetching the key set when `kid` is unknown.
    async fn key(&self, kid: &str) -> Result<PublicKeyComponents<Vec<u8>>, AccessError> {
        if let Some(key) = self.cache.lock().unwrap().keys.get(kid) {
            return Ok(key.clone());
        }

        let _fetching = self.fetching.lock().await;

        // Another request may have fetched while this one waited.
        if let Some(key) = self.cached_key(kid)? {
            return Ok(key);
        }

        self.cache.lock().unwrap().attempted_at = Some(Instant::now());
        let result = self.fetcher.fetch(&self.config.team_domain).await;

        let mut cache = self.cache.lock().unwrap();
        cache.failed = result.is_err();
        let keys = result.map_err(AccessError::Fetch)?;

        cache.keys = keys
            .into_iter()
            .map(|k| {
                (
                    k.kid,
                    PublicKeyComponents {
                        n: strip_leading_zeros(k.n),
                        e: strip_leading_zeros(k.e),
                    },
                )
            })
            .collect();

        cache.keys.get(kid).cloned().ok_or(AccessError::UnknownKey)
    }

    /// A cached key, `None` when the keys may be refetched, or an error when
    /// they were fetched too recently to try again.
    fn cached_key(&self, kid: &str) -> Result<Option<PublicKeyComponents<Vec<u8>>>, AccessError> {
        let cache = self.cache.lock().unwrap();

        if let Some(key) = cache.keys.get(kid) {
            return Ok(Some(key.clone()));
        }

        if cache
            .attempted_at
            .is_some_and(|at| at.elapsed() < MIN_REFETCH_INTERVAL)
        {
            return Err(if cache.failed {
                AccessError::FetchFailedRecently
            } else {
                AccessError::UnknownKey
            });
        }

        Ok(None)
    }
}

/// Key components must be minimal big-endian integers.
fn strip_leading_zeros(mut bytes: Vec<u8>) -> Vec<u8> {
    let zeros = bytes.iter().take_while(|&&b| b == 0).count();
    bytes.drain(..zeros);
    bytes
}

fn decode_part<T>(part: &str) -> Result<T, AccessError>
where
    T: for<'de> Deserialize<'de>,
{
    let bytes = URL_SAFE_NO_PAD
        .decode(part)
        .map_err(|_| AccessError::Malformed)?;
    serde_json::from_slice(&bytes).map_err(|_| AccessError::Malformed)
}

/// Whether the request carries anything Cloudflare Access adds: its email
/// header, its JWT header or its cookie. Whether it is valid is another
/// matter; see [`Access::email`].
pub fn presents_access(headers: &HeaderMap) -> bool {
    headers.contains_key(EMAIL_HEADER)
        || headers.contains_key(JWT_HEADER)
        || headers
            .get_all(COOKIE)
            .iter()
            .filter_map(|v| v.to_str().ok())
            .flat_map(Cookie::split_parse)
            .filter_map(Result::ok)
            .any(|c| c.name() == JWT_COOKIE)
}

fn jwt_from_headers(headers: &HeaderMap) -> Option<String> {
    if let Some(token) = headers.get(JWT_HEADER).and_then(|v| v.to_str().ok()) {
        return Some(token.to_owned());
    }

    headers
        .get_all(COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .flat_map(Cookie::split_parse)
        .filter_map(Result::ok)
        .find(|c| c.name() == JWT_COOKIE)
        .map(|c| c.value().to_owned())
}

#[cfg(test)]
mod tests;