junobuild-auth 0.4.1

Authentication toolkit for Juno.
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
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
use crate::openid::jwt::header::decode_jwt_header;
use crate::openid::jwt::types::cert::{JwkParams, JwkType};
use crate::openid::jwt::types::token::JwtClaims;
use crate::openid::jwt::types::{cert::Jwk, errors::JwtVerifyError};
use crate::openid::utils::nonce::build_nonce;
use crate::state::types::state::Salt;
use jsonwebtoken::{decode, Algorithm, DecodingKey, TokenData, Validation};
use serde::de::DeserializeOwned;

fn pick_key<'a>(kid: &str, jwks: &'a [Jwk]) -> Option<&'a Jwk> {
    jwks.iter().find(|j| j.kid.as_deref() == Some(kid))
}

pub fn verify_openid_jwt<Claims, Custom>(
    jwt: &str,
    issuers: &[&str],
    jwks: &[Jwk],
    salt: &Salt,
    assert_custom: Custom,
) -> Result<TokenData<Claims>, JwtVerifyError>
where
    Claims: DeserializeOwned + JwtClaims,
    Custom: FnOnce(&Claims) -> Result<(), JwtVerifyError>,
{
    // 1) Read header to get `kid`
    let header = decode_jwt_header(jwt).map_err(JwtVerifyError::from)?;

    let kid = header.kid.ok_or(JwtVerifyError::MissingKid)?;

    // 2) Find matching RSA key
    let jwk = pick_key(&kid, jwks).ok_or(JwtVerifyError::NoKeyForKid)?;

    // 3) Extract RSA components - We support only Google at the moment,
    // which always uses RSA keys, and we also did so for GitHub.
    let (n, e) = match (&jwk.kty, &jwk.params) {
        (JwkType::Rsa, JwkParams::Rsa(params)) => (&params.n, &params.e),
        _ => return Err(JwtVerifyError::WrongKeyType),
    };

    // 4) Build decoding key
    let key = DecodingKey::from_rsa_components(n, e)
        .map_err(|e| JwtVerifyError::BadSig(e.to_string()))?;

    // 5) Build validation but disable automatic audience validation
    let mut val = Validation::new(Algorithm::RS256);

    // The forked library uses IC time for time-based checks.

    // We treat the ID token as a fresh proof of identity, so we ignore long-lived expiration (`exp`).
    // We enforce our own short window using update timestamp (`iat`) - 10 minutes currently.
    val.validate_exp = false;

    // We use the library to enforce "not before" (`nbf`) if present.
    // Not strictly required (we already check `iat` freshness), but it doesn't hurt.
    // Note: jsonwebtoken skips this validation when `nbf` is absent from the token.
    val.validate_nbf = true;

    // Let the lib check issuer
    val.set_issuer(issuers);

    // Disable aud checks — we’ll handle audience manually
    val.validate_aud = false;

    let token =
        decode::<Claims>(jwt, &key, &val).map_err(|e| JwtVerifyError::BadSig(e.to_string()))?;

    let c = &token.claims;

    // 6) Checks the nonce - i.e. the caller + salt is present in the jwt
    // This ensures the JWT has not been intercepted and submitted with a different identity.
    let nonce = build_nonce(salt);

    if c.nonce() != Some(nonce.as_str()) {
        return Err(JwtVerifyError::BadClaim("nonce".to_string()));
    }

    // 7) Assert custom fields according consumer's flow
    assert_custom(c)?;

    // 8) Assert expiration
    let now_ns = now_ns();
    const MAX_VALIDITY_WINDOW_NS: u64 = 10 * 60 * 1_000_000_000; // 10 min
    const IAT_FUTURE_SKEW_NS: u64 = 2 * 60 * 1_000_000_000; // 2 min

    let iat_s = c.iat().ok_or(JwtVerifyError::BadClaim("iat".to_string()))?;
    let iat_ns = iat_s.saturating_mul(1_000_000_000);

    // Reject if token is from the future
    // Note: in practice we noticed that using exactly iat for this comparison
    // lead to issue. That is why we add a bit of buffer to the comparison.
    if now_ns < iat_ns.saturating_sub(IAT_FUTURE_SKEW_NS) {
        return Err(JwtVerifyError::BadClaim("iat_future".to_string()));
    }

    // Reject if too old
    if now_ns > iat_ns.saturating_add(MAX_VALIDITY_WINDOW_NS) {
        return Err(JwtVerifyError::BadClaim("iat_expired".to_string()));
    }

    Ok(token)
}

#[cfg(target_arch = "wasm32")]
fn now_ns() -> u64 {
    ic_cdk::api::time()
}

// For test only
#[cfg(not(target_arch = "wasm32"))]
fn now_ns() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos() as u64
}

#[cfg(test)]
mod verify_tests {
    use super::verify_openid_jwt;
    use crate::openid::jwt::types::cert::{JwkParams, JwkParamsRsa, JwkType};
    use crate::openid::jwt::types::token::JwtClaims;
    use crate::openid::jwt::types::{cert::Jwk, errors::JwtVerifyError};
    use crate::openid::utils::nonce::build_nonce;
    use crate::state::types::state::Salt;
    use candid::Deserialize;
    use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
    use serde::Serialize;
    use std::time::{SystemTime, UNIX_EPOCH};

    const TEST_RSA_PEM: &str = include_str!("../../../tests/keys/test_rsa.pem");

    const N_B64URL: &str = "qtQHkWpyd489-_bWjRtrvlQX9CwiQreOsi6kNeeySznI8u-8sxyuO3spW1r2pRmu-rc4jnD9vY6eTGZ3WFNIMxe1geXsF_3nQc5fcNJUUZj19BZE4Ud3dCmUQ4ezkslTvBj8RgD-iBJL7BT7YpxpPgvmqQy_9IgYUkDW4I9_e6kME5kVpySvpRznlk73PfAaDkHWmUTN0j2WcxkW09SGJ_f-tStaYXtc4uH5J-PWMRjwsfL66A_sxLxAwUODJ0VUbeDxVFHGJa0L-58_6GYDTqeel1vH4XjezDL8lf53YRyva3aFxGrC_JeLuIUaJOJX1hXWQb2DruB4hVcQX9afrQ";
    const E_B64URL: &str = "AQAB";

    const ISS_GOOGLE: &str = "https://accounts.google.com";
    const AUD_OK: &str = "client-123";
    const KID_OK: &str = "test-kid-1";

    fn now_secs() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
    }

    fn test_salt() -> Salt {
        [42u8; 32]
    }

    fn header(typ: Option<&str>, kid: Option<&str>) -> Header {
        let mut h = Header::new(Algorithm::RS256);
        h.typ = typ.map(|t| t.to_string());
        h.kid = kid.map(|k| k.to_string());
        h
    }

    #[derive(Debug, Clone, Deserialize, Serialize)]
    pub struct GoogleClaims {
        pub iss: String,
        pub sub: String,
        pub aud: String,
        pub exp: Option<u64>,
        pub nbf: Option<u64>,
        pub iat: Option<u64>,

        pub nonce: Option<String>,

        pub email: Option<String>,
        pub name: Option<String>,
        pub given_name: Option<String>,
        pub family_name: Option<String>,
        pub preferred_username: Option<String>,
        pub picture: Option<String>,
        pub locale: Option<String>,
    }

    impl JwtClaims for GoogleClaims {
        fn iat(&self) -> Option<u64> {
            self.iat
        }
        fn nonce(&self) -> Option<&str> {
            self.nonce.as_deref()
        }
    }

    fn claims(
        iss: &str,
        aud: &str,
        iat: Option<u64>,
        nbf: Option<u64>,
        nonce: Option<&str>,
        exp: Option<u64>,
    ) -> GoogleClaims {
        GoogleClaims {
            iss: iss.into(),
            sub: "sub".into(),
            aud: aud.into(),
            exp,
            nbf,
            iat,
            email: None,
            name: None,
            given_name: None,
            family_name: None,
            preferred_username: None,
            picture: None,
            nonce: nonce.map(|s| s.into()),
            locale: None,
        }
    }

    fn sign_token(h: &Header, c: &GoogleClaims) -> String {
        let enc = EncodingKey::from_rsa_pem(TEST_RSA_PEM.as_bytes()).expect("valid pem");
        encode(h, c, &enc).expect("jwt encode")
    }

    fn jwk_with_kid(kid: &str) -> Jwk {
        Jwk {
            kty: JwkType::Rsa,
            alg: Some("RS256".into()),
            kid: Some(kid.into()),
            params: JwkParams::Rsa(JwkParamsRsa {
                n: N_B64URL.into(),
                e: E_B64URL.into(),
            }),
        }
    }

    fn assert_audience(claims: &GoogleClaims) -> Result<(), JwtVerifyError> {
        if claims.aud != AUD_OK {
            return Err(JwtVerifyError::BadClaim("aud".to_string()));
        }
        Ok(())
    }

    #[test]
    fn verifies_ok() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let token = sign_token(
            &header(Some("JWT"), Some(KID_OK)),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(now),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        let out = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .expect("should verify");

        assert_eq!(out.claims.iss, ISS_GOOGLE);
        assert_eq!(out.claims.aud, AUD_OK);
        assert_eq!(out.claims.nonce.as_deref(), Some(nonce.as_str()));
    }

    #[test]
    fn missing_kid() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let token = sign_token(
            &header(Some("JWT"), None),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(now),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::MissingKid));
    }

    #[test]
    fn no_key_for_kid() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let token = sign_token(
            &header(Some("JWT"), Some("kid-unknown")),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(now),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::NoKeyForKid));
    }

    #[test]
    fn wrong_issuer_is_badsig_from_lib() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let token = sign_token(
            &header(Some("JWT"), Some(KID_OK)),
            &claims(
                "https://not.google.example",
                AUD_OK,
                Some(now),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        // Validation.set_issuer rejects this → mapped to BadSig
        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::BadSig(_)));
    }

    #[test]
    fn wrong_typ_is_badclaim_typ() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let token = sign_token(
            &header(Some("JOT"), Some(KID_OK)),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(now),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::BadClaim(ref f) if f == "typ"));
    }

    #[test]
    fn bad_audience() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let token = sign_token(
            &header(Some("JWT"), Some(KID_OK)),
            &claims(
                ISS_GOOGLE,
                "wrong-aud",
                Some(now),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::BadClaim(ref f) if f == "aud"));
    }

    #[test]
    fn bad_nonce() {
        let now = now_secs();
        let salt = test_salt();

        let token = sign_token(
            &header(Some("JWT"), Some(KID_OK)),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(now),
                Some(now - 5),
                Some("wrong-nonce"),
                Some(now + 600),
            ),
        );

        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::BadClaim(ref f) if f == "nonce"));
    }

    #[test]
    fn iat_too_far_in_future() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let future = now + 4 * 60; // +4min, threshold is 2min skew
        let token = sign_token(
            &header(Some("JWT"), Some(KID_OK)),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(future),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::BadClaim(ref f) if f == "iat_future"));
    }

    #[test]
    fn iat_too_old() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let old = now.saturating_sub(11 * 60); // >10 min
        let token = sign_token(
            &header(Some("JWT"), Some(KID_OK)),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(old),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::BadClaim(ref f) if f == "iat_expired"));
    }

    #[test]
    fn nbf_in_future_is_rejected_by_lib() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let nbf_future = now + 300; // +5 min
        let token = sign_token(
            &header(Some("JWT"), Some(KID_OK)),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(now),
                Some(nbf_future),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        // validate_nbf = true -> jsonwebtoken rejects -> BadSig
        let err = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .unwrap_err();
        assert!(matches!(err, JwtVerifyError::BadSig(_)));
    }

    #[test]
    fn bad_signature_with_wrong_key_material() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let token = sign_token(
            &header(Some("JWT"), Some(KID_OK)),
            &claims(
                ISS_GOOGLE,
                AUD_OK,
                Some(now),
                Some(now - 5),
                Some(&nonce),
                Some(now + 600),
            ),
        );

        // Break the modulus slightly so the provided JWK doesn't match the signature
        // (change the last char; still valid base64url but wrong key)
        let mut bad_n = N_B64URL.to_string();
        let last = bad_n.pop().unwrap();
        bad_n.push(if last == 'A' { 'B' } else { 'A' });

        let bad_jwk = Jwk {
            kty: JwkType::Rsa,
            alg: Some("RS256".into()),
            kid: Some(KID_OK.into()),
            params: JwkParams::Rsa(JwkParamsRsa {
                n: bad_n,
                e: E_B64URL.into(),
            }),
        };

        let err = verify_openid_jwt(&token, &[ISS_GOOGLE], &[bad_jwk], &salt, assert_audience)
            .unwrap_err();
        assert!(matches!(err, JwtVerifyError::BadSig(_)));
    }

    #[test]
    fn decodes_optional_profile_claims() {
        let now = now_secs();
        let salt = test_salt();

        let nonce = build_nonce(&salt);

        let c = GoogleClaims {
            iss: ISS_GOOGLE.into(),
            sub: "sub-123".into(),
            aud: AUD_OK.into(),
            exp: Some(now + 600),
            nbf: Some(now - 5),
            iat: Some(now),
            email: Some("hello@example.com".into()),
            name: Some("World".into()),
            given_name: Some("Hello".into()),
            family_name: Some("World".into()),
            preferred_username: Some("hello_world".into()),
            picture: Some("https://example.com/world.png".into()),
            nonce: Some(nonce.clone()),
            locale: Some("fr-CH".into()),
        };

        let token = sign_token(&header(Some("JWT"), Some(KID_OK)), &c);

        let out = verify_openid_jwt(
            &token,
            &[ISS_GOOGLE],
            &[jwk_with_kid(KID_OK)],
            &salt,
            assert_audience,
        )
        .expect("should verify");

        let claims = out.claims;
        assert_eq!(claims.email.as_deref(), Some("hello@example.com"));
        assert_eq!(claims.name.as_deref(), Some("World"));
        assert_eq!(claims.given_name.as_deref(), Some("Hello"));
        assert_eq!(claims.family_name.as_deref(), Some("World"));
        assert_eq!(claims.preferred_username.as_deref(), Some("hello_world"));
        assert_eq!(
            claims.picture.as_deref(),
            Some("https://example.com/world.png")
        );
        assert_eq!(claims.locale.as_deref(), Some("fr-CH"));
    }
}