forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

jwt.rs212 lines, 7.7 KiBHistoryRawDownload
1//! EdDSA (Ed25519) JSON Web Tokens: signing, verification, claim checks and the public key format.
2//!
3//! The header is `{"alg":"EdDSA","typ":"JWT","kid":...}`. Verification reads the algorithm first and
4//! accepts only `EdDSA`, so `none` and every other algorithm fail before any key is used. The key is
5//! chosen by `kid` from the keys that are published; an unknown `kid` is refused. Claim checks are a
6//! separate call, so each caller states its own issuer and audience.
7
8use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
9use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
10use serde_json::{Map, Value, json};
11
12/// The only algorithm this provider signs or accepts.
13pub const ALG: &str = "EdDSA";
14
15/// How far an `iat` may lie in the future, in seconds (contracts section 2.3: five minutes).
16pub const MAX_FUTURE_IAT_SECS: i64 = 300;
17
18/// Why a token was refused. Only the web layer sees these; the client gets one generic answer.
19#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20pub enum JwtError {
21 /// The token does not have three parts, or a part is not valid base64url JSON.
22 #[error("the token is malformed")]
23 Malformed,
24 /// The header names an algorithm other than EdDSA.
25 #[error("the algorithm is not EdDSA")]
26 Algorithm,
27 /// The `kid` is missing or not published.
28 #[error("the key id is not published")]
29 UnknownKey,
30 /// The signature does not verify with the key.
31 #[error("the signature does not verify")]
32 Signature,
33 /// A claim is missing, has the wrong type or has a wrong value.
34 #[error("the claim {0} is missing or wrong")]
35 Claim(&'static str),
36}
37
38/// A public key that may verify tokens, under its `kid`.
39pub struct PublishedKey {
40 kid: String,
41 key: VerifyingKey,
42}
43
44impl PublishedKey {
45 /// A verifying key from its `kid` and its 32 raw public bytes. `None` for bytes that are not a key.
46 pub fn new(kid: String, public: &[u8]) -> Option<Self> {
47 let raw: [u8; 32] = public.try_into().ok()?;
48 VerifyingKey::from_bytes(&raw)
49 .ok()
50 .map(|key| PublishedKey { kid, key })
51 }
52}
53
54/// Signs `claims` (a JSON object) with `key`, and puts `kid` in the header.
55pub fn sign(key: &SigningKey, kid: &str, claims: &Value) -> String {
56 let header = json!({"alg": ALG, "typ": "JWT", "kid": kid});
57 let signing_input = format!("{}.{}", encode_json(&header), encode_json(claims));
58 let signature: Signature = key.sign(signing_input.as_bytes());
59 format!(
60 "{signing_input}.{}",
61 BASE64_URL_SAFE_NO_PAD.encode(signature.to_bytes())
62 )
63}
64
65/// Signs `claims` with the key whose 32-byte seed is `seed`. The seed is the sealed form of the key
66/// (`keys::generate`), opened for the one call.
67pub fn sign_with_seed(seed: &[u8; 32], kid: &str, claims: &Value) -> String {
68 sign(&SigningKey::from_bytes(seed), kid, claims)
69}
70
71/// Verifies a token against the published keys and returns its claims. The algorithm, the `kid`, and
72/// the signature are checked; the time and the issuer are not (see [`check_claims`]).
73pub fn verify(keys: &[PublishedKey], token: &str) -> Result<Map<String, Value>, JwtError> {
74 let mut parts = token.split('.');
75 let (Some(header), Some(payload), Some(signature), None) =
76 (parts.next(), parts.next(), parts.next(), parts.next())
77 else {
78 return Err(JwtError::Malformed);
79 };
80 let header = decode_object(header)?;
81 if header.get("alg").and_then(Value::as_str) != Some(ALG) {
82 return Err(JwtError::Algorithm);
83 }
84 let kid = header
85 .get("kid")
86 .and_then(Value::as_str)
87 .ok_or(JwtError::UnknownKey)?;
88 let key = keys
89 .iter()
90 .find(|known| known.kid == kid)
91 .ok_or(JwtError::UnknownKey)?;
92 let raw = BASE64_URL_SAFE_NO_PAD
93 .decode(signature)
94 .map_err(|_| JwtError::Malformed)?;
95 let raw: [u8; 64] = raw.try_into().map_err(|_| JwtError::Malformed)?;
96 let signature = Signature::from_bytes(&raw);
97 let signing_input = format!(
98 "{}.{}",
99 token.split('.').next().unwrap_or_default(),
100 payload
101 );
102 key.key
103 .verify_strict(signing_input.as_bytes(), &signature)
104 .map_err(|_| JwtError::Signature)?;
105 decode_object(payload)
106}
107
108/// Checks the registered claims: `iss` equals `issuer` exactly, `aud` is `audience` (a string, or an
109/// array holding only that string), `exp` is in the future, and `iat` is at most five minutes ahead.
110pub fn check_claims(
111 claims: &Map<String, Value>,
112 issuer: &str,
113 audience: &str,
114 now: i64,
115) -> Result<(), JwtError> {
116 if claims.get("iss").and_then(Value::as_str) != Some(issuer) {
117 return Err(JwtError::Claim("iss"));
118 }
119 if !audience_is(claims.get("aud"), audience) {
120 return Err(JwtError::Claim("aud"));
121 }
122 let exp = claims
123 .get("exp")
124 .and_then(Value::as_i64)
125 .ok_or(JwtError::Claim("exp"))?;
126 if exp <= now {
127 return Err(JwtError::Claim("exp"));
128 }
129 let iat = claims
130 .get("iat")
131 .and_then(Value::as_i64)
132 .ok_or(JwtError::Claim("iat"))?;
133 if iat > now + MAX_FUTURE_IAT_SECS {
134 return Err(JwtError::Claim("iat"));
135 }
136 Ok(())
137}
138
139/// Checks only the issuer: `iss` equals `issuer` exactly. For a caller that checks its own expiry
140/// (an ID token used as a logout hint may be expired) and its own audience.
141pub fn check_issuer(claims: &Map<String, Value>, issuer: &str) -> Result<(), JwtError> {
142 if claims.get("iss").and_then(Value::as_str) == Some(issuer) {
143 Ok(())
144 } else {
145 Err(JwtError::Claim("iss"))
146 }
147}
148
149/// The audience of a token when it is a single string. `None` for an array or a missing claim.
150pub fn single_audience(claims: &Map<String, Value>) -> Option<&str> {
151 claims.get("aud").and_then(Value::as_str)
152}
153
154fn audience_is(aud: Option<&Value>, expected: &str) -> bool {
155 match aud {
156 Some(Value::String(one)) => one == expected,
157 Some(Value::Array(list)) => list.len() == 1 && list[0].as_str() == Some(expected),
158 _ => false,
159 }
160}
161
162/// One public key as a JWK (RFC 8037), for the JWKS document.
163pub fn jwk(kid: &str, public: &[u8]) -> Value {
164 json!({
165 "kty": "OKP",
166 "crv": "Ed25519",
167 "x": BASE64_URL_SAFE_NO_PAD.encode(public),
168 "kid": kid,
169 "use": "sig",
170 "alg": ALG,
171 })
172}
173
174fn encode_json(value: &Value) -> String {
175 BASE64_URL_SAFE_NO_PAD.encode(value.to_string())
176}
177
178fn decode_object(segment: &str) -> Result<Map<String, Value>, JwtError> {
179 let bytes = BASE64_URL_SAFE_NO_PAD
180 .decode(segment)
181 .map_err(|_| JwtError::Malformed)?;
182 match serde_json::from_slice(&bytes) {
183 Ok(Value::Object(map)) => Ok(map),
184 _ => Err(JwtError::Malformed),
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 #[test]
193 fn a_signed_token_verifies_and_a_tampered_one_does_not() {
194 let key = SigningKey::from_bytes(&[9u8; 32]);
195 let public = key.verifying_key().to_bytes();
196 let keys = vec![PublishedKey::new("k1".into(), &public).expect("key")];
197 let token = sign(&key, "k1", &json!({"iss": "https://im.test", "aud": "im"}));
198 assert!(verify(&keys, &token).is_ok());
199
200 let forged = json!({"iss": "https://im.test", "aud": "admin"});
201 let mut parts: Vec<&str> = token.split('.').collect();
202 let forged_part = BASE64_URL_SAFE_NO_PAD.encode(forged.to_string());
203 parts[1] = &forged_part;
204 assert_eq!(verify(&keys, &parts.join(".")), Err(JwtError::Signature));
205 let none = format!(
206 "{}.{}.",
207 BASE64_URL_SAFE_NO_PAD.encode(r#"{"alg":"none","kid":"k1"}"#),
208 BASE64_URL_SAFE_NO_PAD.encode("{}")
209 );
210 assert_eq!(verify(&keys, &none), Err(JwtError::Algorithm));
211 }
212}