sylphx 0.3.0

The Sylphx SDK: one API, one key, every Sylphx service. Generated from the Sylphx schema registry.
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
// @generated by sylphx-gen 0.1.0 from contracts@446ceb843d4ff88057b0db68e2e54e4aea52d8143b72d66016122995b878de20. Do not edit.
//! Offline verification of tokens Sylphx signs: Auth session tokens and
//! service-to-service invocation tokens. A token is a compact JWS (ES256 or
//! EdDSA) whose key is published in the issuer's JWKS; verification needs no
//! call to Sylphx once the key set is cached.
//!
//! ```no_run
//! # async fn run() -> Result<(), sylphx::auth::verify::VerifyError> {
//! use sylphx::auth::verify::{Verifier, Expect};
//! let verifier = Verifier::new(Expect::issuer("https://api.sylphx.com").audience("my-app"));
//! let claims = verifier.verify("eyJ…").await?;
//! let user = claims.subject();
//! # Ok(()) }
//! ```
//!
//! [`verify_with_keys`] is the pure core (no network, caller-supplied time)
//! for tests and for callers who distribute keys themselves.

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

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::Deserialize;
use serde_json::{Map, Value};

/// Why a token was refused. Every variant means "do not trust this token".
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifyError {
    /// Not three base64url parts, or a part is not the JSON it must be.
    Malformed(String),
    /// `alg` is not ES256 or EdDSA (`none` and HMAC are never accepted).
    Algorithm(String),
    /// No key in the set has the token's `kid` (after one refetch).
    UnknownKey(String),
    /// The signature does not verify.
    Signature,
    /// `exp` is past, `nbf`/`iat` is in the future, or `exp` is missing.
    Expired,
    /// `iss` is not the expected issuer.
    Issuer(String),
    /// None of the token's audiences is expected.
    Audience,
    /// The key set could not be fetched or read.
    Keys(String),
}

impl std::fmt::Display for VerifyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VerifyError::Malformed(m) => write!(f, "malformed token: {m}"),
            VerifyError::Algorithm(a) => write!(f, "algorithm {a} is not accepted"),
            VerifyError::UnknownKey(k) => write!(f, "no key {k} in the issuer's key set"),
            VerifyError::Signature => f.write_str("the signature does not verify"),
            VerifyError::Expired => f.write_str("the token is expired or not yet valid"),
            VerifyError::Issuer(i) => write!(f, "unexpected issuer {i}"),
            VerifyError::Audience => f.write_str("the token is not for this audience"),
            VerifyError::Keys(m) => write!(f, "key set: {m}"),
        }
    }
}

impl std::error::Error for VerifyError {}

/// What a token must carry.
#[derive(Debug, Clone)]
pub struct Expect {
    pub issuer: String,
    /// Accepted audiences; the token must name at least one. Empty accepts
    /// any audience (only for a caller that checks `aud` itself).
    pub audiences: Vec<String>,
    /// Clock skew tolerated on `exp`, `nbf`, and `iat`.
    pub leeway: Duration,
}

impl Expect {
    pub fn issuer(issuer: impl Into<String>) -> Expect {
        Expect {
            issuer: issuer.into().trim_end_matches('/').to_string(),
            audiences: vec![],
            leeway: Duration::from_secs(60),
        }
    }

    pub fn audience(mut self, audience: impl Into<String>) -> Expect {
        self.audiences.push(audience.into());
        self
    }

    pub fn leeway(mut self, leeway: Duration) -> Expect {
        self.leeway = leeway;
        self
    }
}

/// A verified token's claims.
#[derive(Debug, Clone, PartialEq)]
pub struct Claims(pub Map<String, Value>);

impl Claims {
    pub fn subject(&self) -> Option<&str> {
        self.0.get("sub").and_then(Value::as_str)
    }
    pub fn get(&self, claim: &str) -> Option<&Value> {
        self.0.get(claim)
    }
    pub fn expires_at(&self) -> Option<i64> {
        self.0.get("exp").and_then(Value::as_i64)
    }
}

/// A JSON Web Key Set (RFC 7517), the keys this module can use.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Jwks {
    #[serde(default)]
    pub keys: Vec<Jwk>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Jwk {
    #[serde(default)]
    pub kid: String,
    pub kty: String,
    #[serde(default)]
    pub crv: String,
    #[serde(default)]
    pub x: String,
    #[serde(default)]
    pub y: String,
    #[serde(default)]
    pub alg: Option<String>,
    #[serde(rename = "use", default)]
    pub use_: Option<String>,
}

#[derive(Deserialize)]
struct Header {
    alg: String,
    #[serde(default)]
    kid: String,
}

fn part(s: &str, what: &str) -> Result<Vec<u8>, VerifyError> {
    URL_SAFE_NO_PAD
        .decode(s)
        .map_err(|_| VerifyError::Malformed(format!("{what} is not base64url")))
}

fn verify_signature(jwk: &Jwk, alg: &str, signed: &[u8], sig: &[u8]) -> Result<(), VerifyError> {
    if jwk.use_.as_deref().is_some_and(|u| u != "sig")
        || jwk.alg.as_deref().is_some_and(|a| a != alg)
    {
        return Err(VerifyError::Signature);
    }
    match (alg, jwk.kty.as_str(), jwk.crv.as_str()) {
        ("ES256", "EC", "P-256") => {
            use p256::ecdsa::signature::Verifier as _;
            let mut point = vec![0x04];
            point.extend(part(&jwk.x, "key x")?);
            point.extend(part(&jwk.y, "key y")?);
            let key = p256::ecdsa::VerifyingKey::from_sec1_bytes(&point)
                .map_err(|_| VerifyError::Keys("bad P-256 key".into()))?;
            let sig =
                p256::ecdsa::Signature::from_slice(sig).map_err(|_| VerifyError::Signature)?;
            key.verify(signed, &sig).map_err(|_| VerifyError::Signature)
        }
        ("EdDSA", "OKP", "Ed25519") => {
            use ed25519_dalek::Verifier as _;
            let raw: [u8; 32] = part(&jwk.x, "key x")?
                .try_into()
                .map_err(|_| VerifyError::Keys("bad Ed25519 key".into()))?;
            let key = ed25519_dalek::VerifyingKey::from_bytes(&raw)
                .map_err(|_| VerifyError::Keys("bad Ed25519 key".into()))?;
            let sig: [u8; 64] = sig.try_into().map_err(|_| VerifyError::Signature)?;
            key.verify(signed, &ed25519_dalek::Signature::from_bytes(&sig))
                .map_err(|_| VerifyError::Signature)
        }
        _ => Err(VerifyError::Signature),
    }
}

/// The token's `kid` (to pick or refetch keys), without verifying anything.
pub fn key_id(token: &str) -> Result<String, VerifyError> {
    let head = token.split('.').next().unwrap_or_default();
    let h: Header = serde_json::from_slice(&part(head, "header")?)
        .map_err(|_| VerifyError::Malformed("header is not JSON".into()))?;
    Ok(h.kid)
}

/// Verifies `token` against `keys` at `now` (Unix seconds).
pub fn verify_with_keys(
    token: &str,
    keys: &Jwks,
    expect: &Expect,
    now: i64,
) -> Result<Claims, VerifyError> {
    let mut it = token.split('.');
    let (Some(h), Some(p), Some(s), None) = (it.next(), it.next(), it.next(), it.next()) else {
        return Err(VerifyError::Malformed("not three parts".into()));
    };
    let header: Header = serde_json::from_slice(&part(h, "header")?)
        .map_err(|_| VerifyError::Malformed("header is not JSON".into()))?;
    if !matches!(header.alg.as_str(), "ES256" | "EdDSA") {
        return Err(VerifyError::Algorithm(header.alg));
    }
    let candidates: Vec<&Jwk> = keys
        .keys
        .iter()
        .filter(|k| header.kid.is_empty() || k.kid == header.kid)
        .collect();
    if candidates.is_empty() {
        return Err(VerifyError::UnknownKey(header.kid));
    }
    let sig = part(s, "signature")?;
    let signed = format!("{h}.{p}");
    if !candidates
        .iter()
        .any(|k| verify_signature(k, &header.alg, signed.as_bytes(), &sig).is_ok())
    {
        return Err(VerifyError::Signature);
    }
    let claims: Map<String, Value> = serde_json::from_slice(&part(p, "payload")?)
        .map_err(|_| VerifyError::Malformed("payload is not a JSON object".into()))?;
    let leeway = expect.leeway.as_secs() as i64;
    let num = |k: &str| claims.get(k).and_then(Value::as_i64);
    match num("exp") {
        Some(exp) if exp + leeway > now => {}
        _ => return Err(VerifyError::Expired),
    }
    if num("nbf").is_some_and(|nbf| nbf - leeway > now)
        || num("iat").is_some_and(|iat| iat - leeway > now)
    {
        return Err(VerifyError::Expired);
    }
    let iss = claims
        .get("iss")
        .and_then(Value::as_str)
        .unwrap_or_default();
    if iss.trim_end_matches('/') != expect.issuer {
        return Err(VerifyError::Issuer(iss.to_string()));
    }
    if !expect.audiences.is_empty() {
        let auds: Vec<&str> = match claims.get("aud") {
            Some(Value::String(a)) => vec![a.as_str()],
            Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(),
            _ => vec![],
        };
        if !auds.iter().any(|a| expect.audiences.iter().any(|e| e == a)) {
            return Err(VerifyError::Audience);
        }
    }
    Ok(Claims(claims))
}

fn now_unix() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// Verifies tokens against the issuer's published key set, cached. An
/// unknown `kid` refetches the set at once, but at most once every
/// [`Verifier::MIN_REFETCH`] (so key rotation is picked up and a flood of bad
/// `kid`s cannot hammer the issuer).
#[cfg(feature = "http")]
pub struct Verifier {
    expect: Expect,
    jwks_url: String,
    http: reqwest::Client,
    cache: tokio::sync::RwLock<Option<(Jwks, std::time::Instant)>>,
    last_forced: std::sync::Mutex<Option<std::time::Instant>>,
}

#[cfg(feature = "http")]
impl Verifier {
    /// Keys are kept this long before a refresh.
    pub const TTL: Duration = Duration::from_secs(600);
    /// The shortest interval between two refetches caused by an unknown `kid`.
    pub const MIN_REFETCH: Duration = Duration::from_secs(30);

    /// Keys from `{issuer}/v1/oauth/jwks.json`.
    pub fn new(expect: Expect) -> Verifier {
        let url = format!("{}/v1/oauth/jwks.json", expect.issuer);
        Verifier::with_jwks_url(expect, url)
    }

    pub fn with_jwks_url(expect: Expect, jwks_url: impl Into<String>) -> Verifier {
        Verifier {
            expect,
            jwks_url: jwks_url.into(),
            http: reqwest::Client::builder()
                .timeout(Duration::from_secs(10))
                .build()
                .expect("a reqwest client"),
            cache: tokio::sync::RwLock::new(None),
            last_forced: std::sync::Mutex::new(None),
        }
    }

    async fn keys(&self, force: bool) -> Result<Jwks, VerifyError> {
        if let Some((k, at)) = self.cache.read().await.as_ref() {
            let fresh = at.elapsed() < Verifier::TTL;
            let throttled = force && {
                let mut last = self.last_forced.lock().unwrap_or_else(|e| e.into_inner());
                let recent = last.is_some_and(|t| t.elapsed() < Verifier::MIN_REFETCH);
                if !recent {
                    *last = Some(std::time::Instant::now());
                }
                recent
            };
            if fresh && (!force || throttled) {
                return Ok(k.clone());
            }
        }
        let fetched: Jwks = self
            .http
            .get(&self.jwks_url)
            .send()
            .await
            .and_then(|r| r.error_for_status())
            .map_err(|e| VerifyError::Keys(e.to_string()))?
            .json()
            .await
            .map_err(|e| VerifyError::Keys(e.to_string()))?;
        *self.cache.write().await = Some((fetched.clone(), std::time::Instant::now()));
        Ok(fetched)
    }

    pub async fn verify(&self, token: &str) -> Result<Claims, VerifyError> {
        let keys = self.keys(false).await?;
        match verify_with_keys(token, &keys, &self.expect, now_unix()) {
            Err(VerifyError::UnknownKey(_)) => {
                let keys = self.keys(true).await?;
                verify_with_keys(token, &keys, &self.expect, now_unix())
            }
            other => other,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use p256::ecdsa::signature::Signer as _;
    use serde_json::json;

    fn b64(v: &[u8]) -> String {
        URL_SAFE_NO_PAD.encode(v)
    }

    fn es256() -> (p256::ecdsa::SigningKey, Jwk) {
        let sk = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap();
        let pt = sk.verifying_key().to_encoded_point(false);
        let jwk = Jwk {
            kid: "k1".into(),
            kty: "EC".into(),
            crv: "P-256".into(),
            x: b64(pt.x().unwrap()),
            y: b64(pt.y().unwrap()),
            alg: Some("ES256".into()),
            use_: Some("sig".into()),
        };
        (sk, jwk)
    }

    fn sign_es(sk: &p256::ecdsa::SigningKey, header: Value, claims: Value) -> String {
        let signed = format!(
            "{}.{}",
            b64(header.to_string().as_bytes()),
            b64(claims.to_string().as_bytes())
        );
        let sig: p256::ecdsa::Signature = sk.sign(signed.as_bytes());
        format!("{signed}.{}", b64(&sig.to_bytes()))
    }

    const NOW: i64 = 1_800_000_000;

    fn good() -> Value {
        json!({"iss": "https://api.sylphx.com", "aud": ["app"], "sub": "u1", "exp": NOW + 300, "iat": NOW - 10})
    }

    fn expect() -> Expect {
        Expect::issuer("https://api.sylphx.com").audience("app")
    }

    #[test]
    fn a_valid_es256_token_verifies() {
        let (sk, jwk) = es256();
        let keys = Jwks { keys: vec![jwk] };
        let t = sign_es(&sk, json!({"alg": "ES256", "kid": "k1"}), good());
        let c = verify_with_keys(&t, &keys, &expect(), NOW).unwrap();
        assert_eq!(c.subject(), Some("u1"));
        assert_eq!(key_id(&t).unwrap(), "k1");
    }

    #[test]
    fn a_valid_eddsa_token_verifies() {
        use ed25519_dalek::Signer as _;
        let sk = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]);
        let keys = Jwks {
            keys: vec![Jwk {
                kid: "e1".into(),
                kty: "OKP".into(),
                crv: "Ed25519".into(),
                x: b64(sk.verifying_key().as_bytes()),
                y: String::new(),
                alg: None,
                use_: None,
            }],
        };
        let signed = format!(
            "{}.{}",
            b64(json!({"alg": "EdDSA", "kid": "e1"}).to_string().as_bytes()),
            b64(good().to_string().as_bytes())
        );
        let t = format!("{signed}.{}", b64(&sk.sign(signed.as_bytes()).to_bytes()));
        assert!(verify_with_keys(&t, &keys, &expect(), NOW).is_ok());
    }

    #[test]
    fn hostile_tokens_are_refused() {
        let (sk, jwk) = es256();
        let keys = Jwks { keys: vec![jwk] };
        let h = json!({"alg": "ES256", "kid": "k1"});
        let with = |f: &dyn Fn(&mut Map<String, Value>)| {
            let mut c = good().as_object().unwrap().clone();
            f(&mut c);
            sign_es(&sk, h.clone(), Value::Object(c))
        };
        let cases: Vec<(&str, String, fn(&VerifyError) -> bool)> = vec![
            (
                "expired",
                with(&|c| {
                    c.insert("exp".into(), json!(NOW - 120));
                }),
                |e| *e == VerifyError::Expired,
            ),
            (
                "no exp",
                with(&|c| {
                    c.remove("exp");
                }),
                |e| *e == VerifyError::Expired,
            ),
            (
                "not yet valid",
                with(&|c| {
                    c.insert("nbf".into(), json!(NOW + 600));
                }),
                |e| *e == VerifyError::Expired,
            ),
            (
                "other issuer",
                with(&|c| {
                    c.insert("iss".into(), json!("https://evil.example"));
                }),
                |e| matches!(e, VerifyError::Issuer(_)),
            ),
            (
                "other audience",
                with(&|c| {
                    c.insert("aud".into(), json!("other"));
                }),
                |e| *e == VerifyError::Audience,
            ),
            (
                "alg none",
                format!(
                    "{}.{}.",
                    b64(br#"{"alg":"none"}"#),
                    b64(good().to_string().as_bytes())
                ),
                |e| matches!(e, VerifyError::Algorithm(_)),
            ),
            (
                "alg HS256",
                format!(
                    "{}.{}.x",
                    b64(br#"{"alg":"HS256","kid":"k1"}"#),
                    b64(good().to_string().as_bytes())
                ),
                |e| matches!(e, VerifyError::Algorithm(_)),
            ),
            (
                "unknown kid",
                sign_es(&sk, json!({"alg": "ES256", "kid": "zz"}), good()),
                |e| matches!(e, VerifyError::UnknownKey(_)),
            ),
            ("two parts", "a.b".into(), |e| {
                matches!(e, VerifyError::Malformed(_))
            }),
            ("garbage", "!!.!!.!!".into(), |e| {
                matches!(e, VerifyError::Malformed(_))
            }),
        ];
        for (name, token, ok) in cases {
            let e = verify_with_keys(&token, &keys, &expect(), NOW).expect_err(name);
            assert!(ok(&e), "{name}: {e:?}");
        }
        // A payload swapped under a valid signature.
        let t = sign_es(&sk, h.clone(), good());
        let mut parts: Vec<&str> = t.split('.').collect();
        let forged = b64(json!({"iss": "https://api.sylphx.com", "aud": "app", "sub": "admin", "exp": NOW + 300}).to_string().as_bytes());
        parts[1] = &forged;
        assert_eq!(
            verify_with_keys(&parts.join("."), &keys, &expect(), NOW),
            Err(VerifyError::Signature)
        );
        // A key from another issuer set under the same kid.
        let other = p256::ecdsa::SigningKey::from_slice(&[8u8; 32]).unwrap();
        let t = sign_es(&other, h.clone(), good());
        assert_eq!(
            verify_with_keys(&t, &keys, &expect(), NOW),
            Err(VerifyError::Signature)
        );
        // Leeway: 30 s past exp is still inside the default 60 s.
        let t = with(&|c| {
            c.insert("exp".into(), json!(NOW - 30));
        });
        assert!(verify_with_keys(&t, &keys, &expect(), NOW).is_ok());
    }
}