ssi-jwt 0.6.0

Implementation of JWT for the ssi library.
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
use super::{Claim, InvalidClaimValue, JWTClaims};
use crate::{CastClaim, ClaimSet, InfallibleClaimSet, NumericDate, StringOrURI};
use chrono::{DateTime, Utc};
use ssi_claims_core::{ClaimsValidity, DateTimeProvider, InvalidClaims, ValidateClaims};
use ssi_core::OneOrMany;
use ssi_jws::JwsPayload;
use std::{borrow::Cow, collections::BTreeMap};

pub trait RegisteredClaim: Claim + Into<AnyRegisteredClaim> {
    const JWT_REGISTERED_CLAIM_KIND: RegisteredClaimKind;

    fn extract(claim: AnyRegisteredClaim) -> Option<Self>;

    fn extract_ref(claim: &AnyRegisteredClaim) -> Option<&Self>;

    fn extract_mut(claim: &mut AnyRegisteredClaim) -> Option<&mut Self>;
}

#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RegisteredClaims(BTreeMap<RegisteredClaimKind, AnyRegisteredClaim>);

impl RegisteredClaims {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn iter(&'_ self) -> RegisteredClaimsIter<'_> {
        self.0.values()
    }

    pub fn contains<C: RegisteredClaim>(&self) -> bool {
        self.0.contains_key(&C::JWT_REGISTERED_CLAIM_KIND)
    }

    pub fn get<C: RegisteredClaim>(&self) -> Option<&C> {
        self.0
            .get(&C::JWT_REGISTERED_CLAIM_KIND)
            .and_then(C::extract_ref)
    }

    pub fn get_mut<C: RegisteredClaim>(&mut self) -> Option<&mut C> {
        self.0
            .get_mut(&C::JWT_REGISTERED_CLAIM_KIND)
            .and_then(C::extract_mut)
    }

    pub fn set<C: RegisteredClaim>(&mut self, claim: C) -> Option<C> {
        self.0
            .insert(C::JWT_REGISTERED_CLAIM_KIND, claim.into())
            .and_then(C::extract)
    }

    pub fn insert_any(&mut self, claim: AnyRegisteredClaim) -> Option<AnyRegisteredClaim> {
        self.0.insert(claim.kind(), claim)
    }

    pub fn remove<C: RegisteredClaim>(&mut self) -> Option<C> {
        self.0
            .remove(&C::JWT_REGISTERED_CLAIM_KIND)
            .and_then(C::extract)
    }

    pub fn with_private_claims<P>(self, claims: P) -> JWTClaims<P> {
        JWTClaims {
            registered: self,
            private: claims,
        }
    }
}

impl InfallibleClaimSet for RegisteredClaims {}

impl JwsPayload for RegisteredClaims {
    fn typ(&self) -> Option<&'static str> {
        Some("JWT")
    }

    fn payload_bytes(&'_ self) -> Cow<'_, [u8]> {
        Cow::Owned(serde_json::to_vec(self).unwrap())
    }
}

impl<E, P> ValidateClaims<E, P> for RegisteredClaims
where
    E: DateTimeProvider,
{
    fn validate_claims(&self, env: &E, _proof: &P) -> ClaimsValidity {
        ClaimSet::validate_registered_claims(self, env)
    }
}

pub type RegisteredClaimsIter<'a> =
    std::collections::btree_map::Values<'a, RegisteredClaimKind, AnyRegisteredClaim>;

impl<'a> IntoIterator for &'a RegisteredClaims {
    type IntoIter = RegisteredClaimsIter<'a>;
    type Item = &'a AnyRegisteredClaim;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl serde::Serialize for RegisteredClaims {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(Some(self.0.len()))?;

        for claim in self {
            claim.serialize(&mut map)?;
        }

        map.end()
    }
}

impl<'de> serde::Deserialize<'de> for RegisteredClaims {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct Visitor;

        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = RegisteredClaims;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(formatter, "JWT registered claim set")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::MapAccess<'de>,
            {
                let mut result = RegisteredClaims::new();
                while let Some(kind) = map.next_key::<RegisteredClaimKind>()? {
                    let claim = kind.deserialize_value(&mut map)?;
                    result.insert_any(claim);
                }
                Ok(result)
            }
        }

        deserializer.deserialize_map(Visitor)
    }
}

pub trait TryIntoClaim<C> {
    type Error;

    fn try_into_claim(self) -> Result<C, Self::Error>;
}

macro_rules! registered_claims {
    ($($(#[$meta:meta])* $name:literal: $variant:ident ( $ty:ty )),*) => {
        $(
            $(#[$meta])*
            #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
            #[derive(serde::Serialize, serde::Deserialize)]
            #[serde(transparent)]
            pub struct $variant(pub $ty);

            impl Claim for $variant {
                const JWT_CLAIM_NAME: &'static str = $name;
            }

            impl<T> TryIntoClaim<$variant> for T
            where
                T: TryInto<$ty>
            {
                type Error = T::Error;

                fn try_into_claim(self) -> Result<$variant, Self::Error> {
                    self.try_into().map($variant)
                }
            }

            impl RegisteredClaim for $variant {
                const JWT_REGISTERED_CLAIM_KIND: RegisteredClaimKind = RegisteredClaimKind::$variant;

                fn extract(claim: AnyRegisteredClaim) -> Option<Self> {
                    match claim {
                        AnyRegisteredClaim::$variant(value) => Some(value),
                        _ => None
                    }
                }

                fn extract_ref(claim: &AnyRegisteredClaim) -> Option<&Self> {
                    match claim {
                        AnyRegisteredClaim::$variant(value) => Some(value),
                        _ => None
                    }
                }

                fn extract_mut(claim: &mut AnyRegisteredClaim) -> Option<&mut Self> {
                    match claim {
                        AnyRegisteredClaim::$variant(value) => Some(value),
                        _ => None
                    }
                }
            }
        )*

        impl ClaimSet for RegisteredClaims {
            fn contains<C: Claim>(&self) -> bool {
                $(
                    if std::any::TypeId::of::<C>() == std::any::TypeId::of::<$variant>() {
                        return self.contains::<$variant>();
                    }
                )*

                false
            }

            fn try_get<C: Claim>(&'_ self) -> Result<Option<Cow<'_, C>>, InvalidClaimValue> {
                $(
                    if std::any::TypeId::of::<C>() == std::any::TypeId::of::<$variant>() {
                        return Ok(unsafe { CastClaim::cast_claim(self.get::<$variant>()) }.map(Cow::Borrowed));
                    }
                )*

                Ok(None)
            }

            fn try_set<C: Claim>(&mut self, claim: C) -> Result<Result<(), C>, InvalidClaimValue> {
                $(
                    if std::any::TypeId::of::<C>() == std::any::TypeId::of::<$variant>() {
                        self.set::<$variant>(unsafe { CastClaim::cast_claim(claim) });
                        return Ok(Ok(()))
                    }
                )*

                Ok(Err(claim))
            }

            fn try_remove<C: Claim>(&mut self) -> Result<Option<C>, InvalidClaimValue> {
                $(
                    if std::any::TypeId::of::<C>() == std::any::TypeId::of::<$variant>() {
                        return Ok(unsafe { CastClaim::cast_claim(self.remove::<$variant>()) });
                    }
                )*

                Ok(None)
            }
        }

        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub enum RegisteredClaimKind {
            $(
                $variant
            ),*
        }

        impl RegisteredClaimKind {
            pub fn new(s: &str) -> Option<Self> {
                match s {
                    $(
                        $name => Some(Self::$variant),
                    )*
                    _ => None
                }
            }

            pub fn as_str(&self) -> &'static str {
                match self {
                    $(
                        Self::$variant => $name,
                    )*
                }
            }

            pub(crate) fn deserialize_value<'de, M: serde::de::MapAccess<'de>>(&self, map: &mut M) -> Result<AnyRegisteredClaim, M::Error> {
                match self {
                    $(
                        Self::$variant => {
                            map.next_value().map(AnyRegisteredClaim::$variant)
                        }
                    ),*
                }
            }
        }

		impl<'de> serde::Deserialize<'de> for RegisteredClaimKind {
			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
			where
				D: serde::Deserializer<'de>
			{
				let name = String::deserialize(deserializer)?;
				match Self::new(&name) {
					Some(r) => Ok(r),
					None => Err(serde::de::Error::custom(format!("unknown registered claim `{}`", name)))
				}
			}
		}

        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub enum AnyRegisteredClaim {
            $(
                $variant($variant)
            ),*
        }

        impl AnyRegisteredClaim {
            pub fn kind(&self) -> RegisteredClaimKind {
                match self {
                    $(
                        Self::$variant(_) => RegisteredClaimKind::$variant
                    ),*
                }
            }

            fn serialize<S: serde::ser::SerializeMap>(&self, serializer: &mut S) -> Result<(), S::Error> {
                match self {
                    $(
                        Self::$variant(value) => {
                            serializer.serialize_entry(
                                $name,
                                value
                            )
                        }
                    ),*
                }
            }
        }

        $(
            impl From<$variant> for AnyRegisteredClaim {
                fn from(value: $variant) -> Self {
                    Self::$variant(value)
                }
            }
        )*
    };
}

registered_claims! {
    /// Issuer (`iss`) claim.
    ///
    /// Principal that issued the JWT. The processing of this claim is generally
    /// application specific.
    "iss": Issuer(StringOrURI),

    /// Subject (`sub`) claim.
    ///
    /// Principal that is the subject of the JWT. The claims in a JWT are
    /// normally statements about the subject. The subject value MUST either be
    /// scoped to be locally unique in the context of the issuer or be globally
    /// unique.
    ///
    /// The processing of this claim is generally application specific.
    "sub": Subject(StringOrURI),

    /// Audience (`aud`) claim.
    ///
    /// Recipients that the JWT is intended for. Each principal intended to
    /// process the JWT MUST identify itself with a value in the audience claim.
    /// If the principal processing the claim does not identify itself with a
    /// value in the `aud` claim when this claim is present, then the JWT MUST
    /// be rejected.
    "aud": Audience(OneOrMany<StringOrURI>),

    /// Expiration Time (`exp`) claim.
    ///
    /// Expiration time on or after which the JWT MUST NOT be accepted for
    /// processing. The processing of the `exp` claim requires that the current
    /// date/time MUST be before the expiration date/time listed in the `exp`
    /// claim.
    #[derive(Copy)]
    "exp": ExpirationTime(NumericDate),

    /// Not Before (`nbf`) claim.
    ///
    /// Time before which the JWT MUST NOT be accepted for processing. The
    /// processing of the `nbf` claim requires that the current date/time MUST
    /// be after or equal to the not-before date/time listed in the "nbf" claim.
    /// Implementers MAY provide for some small leeway, usually no more than a
    /// few minutes, to account for clock skew.
    #[derive(Copy)]
    "nbf": NotBefore(NumericDate),

    /// Issued At (`iat`) claim.
    ///
    /// Time at which the JWT was issued. This claim can be used to determine
    /// the age of the JWT.
    #[derive(Copy)]
    "iat": IssuedAt(NumericDate),

    /// JWT ID (`jti`) claim.
    ///
    /// Unique identifier for the JWT. The identifier value MUST be assigned in
    /// a manner that ensures that there is a negligible probability that the
    /// same value will be accidentally assigned to a different data object; if
    /// the application uses multiple issuers, collisions MUST be prevented
    /// among values produced by different issuers as well.
    ///
    /// The "jti" claim can be used to prevent the JWT from being replayed.
    "jti": JwtId(String),

    "nonce": Nonce(String),

    "vc": VerifiableCredential(json_syntax::Value),

    "vp": VerifiablePresentation(json_syntax::Value)
}

pub enum JwtClaimValidationFailed {
    Premature {
        now: DateTime<Utc>,
        valid_from: DateTime<Utc>,
    },
    Expired {
        now: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    },
}

impl From<JwtClaimValidationFailed> for InvalidClaims {
    fn from(value: JwtClaimValidationFailed) -> Self {
        match value {
            JwtClaimValidationFailed::Premature { now, valid_from } => {
                Self::Premature { now, valid_from }
            }
            JwtClaimValidationFailed::Expired { now, valid_until } => {
                Self::Expired { now, valid_until }
            }
        }
    }
}

impl ExpirationTime {
    pub fn verify(&self, now: DateTime<Utc>) -> Result<(), JwtClaimValidationFailed> {
        let exp: DateTime<Utc> = self.0.into();
        if exp > now {
            Ok(())
        } else {
            Err(JwtClaimValidationFailed::Expired {
                now,
                valid_until: exp,
            })
        }
    }
}

impl NotBefore {
    pub fn verify(&self, now: DateTime<Utc>) -> Result<(), JwtClaimValidationFailed> {
        let nbf: DateTime<Utc> = self.0.into();
        if nbf <= now {
            Ok(())
        } else {
            Err(JwtClaimValidationFailed::Premature {
                now,
                valid_from: nbf,
            })
        }
    }
}

impl IssuedAt {
    pub fn now() -> Self {
        Self(Utc::now().into())
    }

    pub fn verify(&self, now: DateTime<Utc>) -> Result<(), JwtClaimValidationFailed> {
        let iat: DateTime<Utc> = self.0.into();
        if iat <= now {
            Ok(())
        } else {
            Err(JwtClaimValidationFailed::Premature {
                now,
                valid_from: iat,
            })
        }
    }
}