jacquard-common 0.10.0

Core AT Protocol types and utilities for Jacquard
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
//! Service authentication JWT parsing and verification for AT Protocol.
//!
//! Service auth is atproto's inter-service authentication mechanism. When a backend
//! service (feed generator, labeler, etc.) receives requests, the PDS signs a
//! short-lived JWT with the user's signing key and includes it as a Bearer token.
//!
//! # JWT Structure
//!
//! - Header: `alg` (ES256K for k256, ES256 for p256), `typ` ("JWT")
//! - Payload:
//!   - `iss`: user's DID (issuer)
//!   - `aud`: target service DID (audience)
//!   - `exp`: expiration unix timestamp
//!   - `iat`: issued at unix timestamp
//!   - `jti`: random nonce (128-bit hex) for replay protection
//!   - `lxm`: lexicon method NSID (method binding)
//! - Signature: signed with user's signing key from DID doc (ES256 or ES256K)

use crate::CowStr;
use crate::IntoStatic;
use crate::types::string::{Did, Nsid};
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ouroboros::self_referencing;
use serde::{Deserialize, Serialize};
use signature::Verifier;
use smol_str::SmolStr;
use smol_str::format_smolstr;
use thiserror::Error;

#[cfg(feature = "crypto-p256")]
use p256::ecdsa::{Signature as P256Signature, VerifyingKey as P256VerifyingKey};

#[cfg(feature = "crypto-k256")]
use k256::ecdsa::{Signature as K256Signature, VerifyingKey as K256VerifyingKey};

/// Errors that can occur during JWT parsing and verification.
#[derive(Debug, Error, miette::Diagnostic)]
#[non_exhaustive]
pub enum ServiceAuthError {
    /// JWT format is invalid (not three base64-encoded parts separated by dots)
    #[error("malformed JWT: {0}")]
    MalformedToken(CowStr<'static>),

    /// Base64 decoding failed
    #[error("base64 decode error: {0}")]
    Base64Decode(#[from] base64::DecodeError),

    /// JSON parsing failed
    #[error("JSON parsing error: {0}")]
    JsonParse(#[from] serde_json::Error),

    /// Signature verification failed
    #[error("invalid signature")]
    InvalidSignature,

    /// Unsupported algorithm
    #[error("unsupported algorithm: {alg}")]
    UnsupportedAlgorithm {
        /// Algorithm name from JWT header
        alg: SmolStr,
    },

    /// Token has expired
    #[error("token expired at {exp} (current time: {now})")]
    Expired {
        /// Expiration timestamp from token
        exp: i64,
        /// Current timestamp
        now: i64,
    },

    /// Audience mismatch
    #[error("audience mismatch: expected {expected}, got {actual}")]
    AudienceMismatch {
        /// Expected audience DID
        expected: Did<'static>,
        /// Actual audience DID in token
        actual: Did<'static>,
    },

    /// Method mismatch (lxm field)
    #[error("method mismatch: expected {expected}, got {actual:?}")]
    MethodMismatch {
        /// Expected method NSID
        expected: Nsid<'static>,
        /// Actual method NSID in token (if any)
        actual: Option<Nsid<'static>>,
    },

    /// Missing required field
    #[error("missing required field: {0}")]
    MissingField(&'static str),

    /// Crypto error
    #[error("crypto error: {0}")]
    Crypto(CowStr<'static>),
}

/// JWT header for service auth tokens.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwtHeader<'a> {
    /// Algorithm used for signing
    #[serde(borrow)]
    pub alg: CowStr<'a>,
    /// Type (always "JWT")
    #[serde(borrow)]
    pub typ: CowStr<'a>,
}

impl IntoStatic for JwtHeader<'_> {
    type Output = JwtHeader<'static>;

    fn into_static(self) -> Self::Output {
        JwtHeader {
            alg: self.alg.into_static(),
            typ: self.typ.into_static(),
        }
    }
}

/// Service authentication claims.
///
/// These are the payload fields in a service auth JWT.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceAuthClaims<'a> {
    /// Issuer (user's DID)
    #[serde(borrow)]
    pub iss: Did<'a>,

    /// Audience (target service DID)
    #[serde(borrow)]
    pub aud: Did<'a>,

    /// Expiration time (unix timestamp)
    pub exp: i64,

    /// Issued at (unix timestamp)
    pub iat: i64,

    /// JWT ID (nonce for replay protection)
    #[serde(borrow, skip_serializing_if = "Option::is_none")]
    pub jti: Option<CowStr<'a>>,

    /// Lexicon method NSID (method binding)
    #[serde(borrow, skip_serializing_if = "Option::is_none")]
    pub lxm: Option<Nsid<'a>>,
}

impl<'a> IntoStatic for ServiceAuthClaims<'a> {
    type Output = ServiceAuthClaims<'static>;

    fn into_static(self) -> Self::Output {
        ServiceAuthClaims {
            iss: self.iss.into_static(),
            aud: self.aud.into_static(),
            exp: self.exp,
            iat: self.iat,
            jti: self.jti.map(|j| j.into_static()),
            lxm: self.lxm.map(|l| l.into_static()),
        }
    }
}

impl<'a> ServiceAuthClaims<'a> {
    /// Validate the claims against expected values.
    ///
    /// Checks:
    /// - Audience matches expected DID
    /// - Token is not expired
    pub fn validate(&self, expected_aud: &Did) -> Result<(), ServiceAuthError> {
        // Check audience
        if self.aud.as_str() != expected_aud.as_str() {
            return Err(ServiceAuthError::AudienceMismatch {
                expected: expected_aud.clone().into_static(),
                actual: self.aud.clone().into_static(),
            });
        }

        // Check expiration
        if self.is_expired() {
            let now = chrono::Utc::now().timestamp();
            return Err(ServiceAuthError::Expired { exp: self.exp, now });
        }

        Ok(())
    }

    /// Check if the token has expired.
    pub fn is_expired(&self) -> bool {
        let now = chrono::Utc::now().timestamp();
        self.exp <= now
    }

    /// Check if the method (lxm) matches the expected NSID.
    pub fn check_method(&self, nsid: &Nsid) -> bool {
        self.lxm
            .as_ref()
            .map(|lxm| lxm.as_str() == nsid.as_str())
            .unwrap_or(false)
    }

    /// Require that the method (lxm) matches the expected NSID.
    pub fn require_method(&self, nsid: &Nsid) -> Result<(), ServiceAuthError> {
        if !self.check_method(nsid) {
            return Err(ServiceAuthError::MethodMismatch {
                expected: nsid.clone().into_static(),
                actual: self.lxm.as_ref().map(|l| l.clone().into_static()),
            });
        }
        Ok(())
    }
}

/// Parsed JWT components.
///
/// This struct owns the decoded buffers and parsed components using ouroboros
/// self-referencing. The header and claims borrow from their respective buffers.
#[self_referencing]
pub struct ParsedJwt {
    /// Decoded header buffer (owned)
    header_buf: Vec<u8>,
    /// Decoded payload buffer (owned)
    payload_buf: Vec<u8>,
    /// Original token string for signing_input
    token: String,
    /// Signature bytes
    signature: Vec<u8>,
    /// Parsed header borrowing from header_buf
    #[borrows(header_buf)]
    #[covariant]
    header: JwtHeader<'this>,
    /// Parsed claims borrowing from payload_buf
    #[borrows(payload_buf)]
    #[covariant]
    claims: ServiceAuthClaims<'this>,
}

impl ParsedJwt {
    /// Get the signing input (header.payload) for signature verification.
    pub fn signing_input(&self) -> &[u8] {
        self.with_token(|token| {
            let dot_pos = token.find('.').unwrap();
            let second_dot_pos = token[dot_pos + 1..].find('.').unwrap() + dot_pos + 1;
            token[..second_dot_pos].as_bytes()
        })
    }

    /// Get a reference to the header.
    pub fn header(&self) -> &JwtHeader<'_> {
        self.borrow_header()
    }

    /// Get a reference to the claims.
    pub fn claims(&self) -> &ServiceAuthClaims<'_> {
        self.borrow_claims()
    }

    /// Get a reference to the signature.
    pub fn signature(&self) -> &[u8] {
        self.borrow_signature()
    }

    /// Get owned header with 'static lifetime.
    pub fn into_header(self) -> JwtHeader<'static> {
        self.with_header(|header| header.clone().into_static())
    }

    /// Get owned claims with 'static lifetime.
    pub fn into_claims(self) -> ServiceAuthClaims<'static> {
        self.with_claims(|claims| claims.clone().into_static())
    }
}

/// Parse a JWT token into its components without verifying the signature.
///
/// This extracts and decodes all JWT components. The header and claims are parsed
/// and borrow from their respective owned buffers using ouroboros self-referencing.
pub fn parse_jwt(token: &str) -> Result<ParsedJwt, ServiceAuthError> {
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() != 3 {
        return Err(ServiceAuthError::MalformedToken(CowStr::new_static(
            "JWT must have exactly 3 parts separated by dots",
        )));
    }

    let header_b64 = parts[0];
    let payload_b64 = parts[1];
    let signature_b64 = parts[2];

    // Decode all components
    let header_buf = URL_SAFE_NO_PAD.decode(header_b64)?;
    let payload_buf = URL_SAFE_NO_PAD.decode(payload_b64)?;
    let signature = URL_SAFE_NO_PAD.decode(signature_b64)?;

    // Validate that buffers contain valid JSON for their types
    // We parse once here to validate, then again in the builder (unavoidable with ouroboros)
    let _header: JwtHeader = serde_json::from_slice(&header_buf)?;
    let _claims: ServiceAuthClaims = serde_json::from_slice(&payload_buf)?;

    Ok(ParsedJwtBuilder {
        header_buf,
        payload_buf,
        token: token.to_string(),
        signature,
        header_builder: |buf| {
            // Safe: we validated this succeeds above
            serde_json::from_slice(buf).expect("header was validated")
        },
        claims_builder: |buf| {
            // Safe: we validated this succeeds above
            serde_json::from_slice(buf).expect("claims were validated")
        },
    }
    .build())
}

/// Public key types for signature verification.
#[derive(Debug, Clone)]
pub enum PublicKey {
    /// P-256 (ES256) public key
    #[cfg(feature = "crypto-p256")]
    P256(P256VerifyingKey),

    /// secp256k1 (ES256K) public key
    #[cfg(feature = "crypto-k256")]
    K256(K256VerifyingKey),
}

impl PublicKey {
    /// Create a P-256 public key from compressed or uncompressed bytes.
    #[cfg(feature = "crypto-p256")]
    pub fn from_p256_bytes(bytes: &[u8]) -> Result<Self, ServiceAuthError> {
        let key = P256VerifyingKey::from_sec1_bytes(bytes).map_err(|e| {
            ServiceAuthError::Crypto(CowStr::Owned(format_smolstr!("invalid P-256 key: {}", e)))
        })?;
        Ok(PublicKey::P256(key))
    }

    /// Create a secp256k1 public key from compressed or uncompressed bytes.
    #[cfg(feature = "crypto-k256")]
    pub fn from_k256_bytes(bytes: &[u8]) -> Result<Self, ServiceAuthError> {
        let key = K256VerifyingKey::from_sec1_bytes(bytes).map_err(|e| {
            ServiceAuthError::Crypto(CowStr::Owned(format_smolstr!("invalid K-256 key: {}", e)))
        })?;
        Ok(PublicKey::K256(key))
    }
}

/// Verify a JWT signature using the provided public key.
///
/// The algorithm is determined by the JWT header and must match the public key type.
pub fn verify_signature(
    parsed: &ParsedJwt,
    public_key: &PublicKey,
) -> Result<(), ServiceAuthError> {
    let alg = parsed.header().alg.as_str();
    let signing_input = parsed.signing_input();
    let signature = parsed.signature();

    match (alg, public_key) {
        #[cfg(feature = "crypto-p256")]
        ("ES256", PublicKey::P256(key)) => {
            let sig = P256Signature::from_slice(signature).map_err(|e| {
                ServiceAuthError::Crypto(CowStr::Owned(format_smolstr!(
                    "invalid ES256 signature: {}",
                    e
                )))
            })?;
            key.verify(signing_input, &sig)
                .map_err(|_| ServiceAuthError::InvalidSignature)?;
            Ok(())
        }

        #[cfg(feature = "crypto-k256")]
        ("ES256K", PublicKey::K256(key)) => {
            let sig = K256Signature::from_slice(signature).map_err(|e| {
                ServiceAuthError::Crypto(CowStr::Owned(format_smolstr!(
                    "invalid ES256K signature: {}",
                    e
                )))
            })?;
            key.verify(signing_input, &sig)
                .map_err(|_| ServiceAuthError::InvalidSignature)?;
            Ok(())
        }

        _ => Err(ServiceAuthError::UnsupportedAlgorithm {
            alg: SmolStr::new(alg),
        }),
    }
}

/// Parse and verify a service auth JWT in one step, returning owned claims.
///
/// This is a convenience function that combines parsing and signature verification.
pub fn verify_service_jwt(
    token: &str,
    public_key: &PublicKey,
) -> Result<ServiceAuthClaims<'static>, ServiceAuthError> {
    let parsed = parse_jwt(token)?;
    verify_signature(&parsed, public_key)?;
    Ok(parsed.into_claims())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_jwt_invalid_format() {
        let result = parse_jwt("not.a.valid.jwt.with.too.many.parts");
        assert!(matches!(result, Err(ServiceAuthError::MalformedToken(_))));
    }

    #[test]
    fn test_claims_expiration() {
        let now = chrono::Utc::now().timestamp();
        let expired_claims = ServiceAuthClaims {
            iss: Did::new("did:plc:test").unwrap(),
            aud: Did::new("did:web:example.com").unwrap(),
            exp: now - 100,
            iat: now - 200,
            jti: None,
            lxm: None,
        };

        assert!(expired_claims.is_expired());

        let valid_claims = ServiceAuthClaims {
            iss: Did::new("did:plc:test").unwrap(),
            aud: Did::new("did:web:example.com").unwrap(),
            exp: now + 100,
            iat: now,
            jti: None,
            lxm: None,
        };

        assert!(!valid_claims.is_expired());
    }

    #[test]
    fn test_audience_validation() {
        let now = chrono::Utc::now().timestamp();
        let claims = ServiceAuthClaims {
            iss: Did::new("did:plc:test").unwrap(),
            aud: Did::new("did:web:example.com").unwrap(),
            exp: now + 100,
            iat: now,
            jti: None,
            lxm: None,
        };

        let expected_aud = Did::new("did:web:example.com").unwrap();
        assert!(claims.validate(&expected_aud).is_ok());

        let wrong_aud = Did::new("did:web:wrong.com").unwrap();
        assert!(matches!(
            claims.validate(&wrong_aud),
            Err(ServiceAuthError::AudienceMismatch { .. })
        ));
    }

    #[test]
    fn test_method_check() {
        let claims = ServiceAuthClaims {
            iss: Did::new("did:plc:test").unwrap(),
            aud: Did::new("did:web:example.com").unwrap(),
            exp: chrono::Utc::now().timestamp() + 100,
            iat: chrono::Utc::now().timestamp(),
            jti: None,
            lxm: Some(Nsid::new("app.bsky.feed.getFeedSkeleton").unwrap()),
        };

        let expected = Nsid::new("app.bsky.feed.getFeedSkeleton").unwrap();
        assert!(claims.check_method(&expected));

        let wrong = Nsid::new("app.bsky.feed.getTimeline").unwrap();
        assert!(!claims.check_method(&wrong));
    }
}