-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsigner.rs
More file actions
740 lines (650 loc) · 26.6 KB
/
Copy pathsigner.rs
File metadata and controls
740 lines (650 loc) · 26.6 KB
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! Cryptographic signing utilities for AT Protocol.
//!
//! This module provides ES256 (ECDSA with P-256) signing and verification for service auth tokens.
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as BASE64URL};
use p256::ecdsa::{SigningKey, VerifyingKey, signature::hazmat::PrehashSigner, signature::hazmat::PrehashVerifier};
use serde::Serialize;
use sha2::{Digest, Sha256};
/// Error type for signing operations.
#[derive(Debug)]
pub enum SignerError {
InvalidKey(String),
SigningFailed(String),
EncodingError(String),
}
impl std::fmt::Display for SignerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SignerError::InvalidKey(msg) => write!(f, "Invalid key: {}", msg),
SignerError::SigningFailed(msg) => write!(f, "Signing failed: {}", msg),
SignerError::EncodingError(msg) => write!(f, "Encoding error: {}", msg),
}
}
}
impl std::error::Error for SignerError {}
/// JWT header for ES256 signing.
#[derive(Serialize)]
struct JwtHeader {
alg: &'static str,
typ: &'static str,
}
/// JWT header for space delegation tokens.
///
/// Delegation tokens carry a distinguishing `typ` and a `kid` naming the
/// account's `#atproto` signing key.
#[derive(Serialize)]
struct DelegationJwtHeader {
alg: &'static str,
typ: &'static str,
kid: &'static str,
}
/// JWT payload for space delegation tokens (AT Protocol permissioned spaces).
#[derive(Serialize)]
struct DelegationPayload {
/// Issuer - the user's DID.
iss: String,
/// Subject - the target space URI (`at://{authority}/space/{type}/{skey}`).
sub: String,
/// Audience - the space authority's space host (`{authority}#atproto_space_host`).
aud: String,
/// Issued at timestamp.
iat: i64,
/// Expiration timestamp.
exp: i64,
/// Random single-use identifier.
jti: String,
}
/// The `typ` header value identifying a space delegation token.
pub const DELEGATION_TOKEN_TYP: &str = "atproto-space-delegation+jwt";
/// Default lifetime of a delegation token, in seconds (spec default).
pub const DELEGATION_TOKEN_TTL_SECS: i64 = 60;
/// The `typ` header value identifying a space credential.
pub const SPACE_CREDENTIAL_TYP: &str = "atproto-space-credential+jwt";
/// Default lifetime of a space credential, in seconds (spec default, 2 hours).
pub const SPACE_CREDENTIAL_TTL_SECS: i64 = 7200;
/// JWT header for space credentials.
///
/// Credentials carry a distinguishing `typ` and a `kid` naming the space
/// authority's signing key.
#[derive(Serialize)]
struct SpaceCredentialJwtHeader {
alg: &'static str,
typ: &'static str,
kid: &'static str,
}
/// DPoP confirmation claim (RFC 7800), binding a credential to a key.
#[derive(Serialize)]
struct Confirmation {
/// JWK thumbprint (RFC 7638) of the bound key.
jkt: String,
}
/// JWT payload for space credentials (AT Protocol permissioned spaces).
#[derive(Serialize)]
struct SpaceCredentialPayload {
/// Issuer - the space authority's DID.
iss: String,
/// Subject - the target space URI (`at://{authority}/space/{type}/{skey}`).
sub: String,
/// Confirmation - binds the credential to the application's DPoP key.
cnf: Confirmation,
/// Issued at timestamp.
iat: i64,
/// Expiration timestamp.
exp: i64,
/// Random single-use identifier.
jti: String,
}
/// JWT payload for service auth tokens.
#[derive(Serialize)]
struct ServiceAuthPayload {
/// Issuer - the user's DID (the one requesting the token)
iss: String,
/// Audience - the service DID that will validate this token
aud: String,
/// Issued at timestamp
iat: i64,
/// Expiration timestamp
exp: i64,
/// Lexicon method (optional binding)
#[serde(skip_serializing_if = "Option::is_none")]
lxm: Option<String>,
}
/// Sign a service auth token using ES256 (ECDSA with P-256).
///
/// # Arguments
///
/// * `private_key_multibase` - The user's private key in multibase format (z prefix = base58btc)
/// * `issuer` - The user's DID (iss claim)
/// * `audience` - The target service's DID (aud claim)
/// * `lxm` - Optional lexicon method to bind the token to
/// * `expires_in_seconds` - Token lifetime in seconds
///
/// # Returns
///
/// A signed JWT token string.
pub fn sign_service_auth_token(
private_key_multibase: &str,
issuer: &str,
audience: &str,
lxm: Option<&str>,
expires_in_seconds: i64,
) -> Result<String, SignerError> {
// Load the P-256 signing key from the multibase-encoded private key.
let signing_key = load_p256_signing_key(private_key_multibase)?;
// Create header
let header = JwtHeader {
alg: "ES256",
typ: "JWT",
};
// Create payload
let now = chrono::Utc::now().timestamp();
let payload = ServiceAuthPayload {
iss: issuer.to_string(),
aud: audience.to_string(),
iat: now,
exp: now + expires_in_seconds,
lxm: lxm.map(|s| s.to_string()),
};
// Encode header and payload
let header_json = serde_json::to_string(&header)
.map_err(|e| SignerError::EncodingError(format!("Header serialization failed: {}", e)))?;
let payload_json = serde_json::to_string(&payload)
.map_err(|e| SignerError::EncodingError(format!("Payload serialization failed: {}", e)))?;
sign_es256_jwt(&signing_key, &header_json, &payload_json)
}
/// Sign a space delegation token using ES256 (ECDSA with P-256).
///
/// Mints the single-use, short-lived JWT a client presents to a space
/// authority to prove it is acting on the user's behalf when requesting a
/// space credential (`com.atproto.space.getDelegationToken`).
///
/// # Arguments
///
/// * `private_key_multibase` - The user's private signing key in multibase format.
/// * `issuer` - The user's DID (`iss` claim).
/// * `space_uri` - The target space URI (`sub` claim), in the form
/// `at://{authority}/space/{spaceType}/{skey}`.
/// * `authority` - The space authority DID; the token's audience is
/// `{authority}#atproto_space_host`.
/// * `expires_in_seconds` - Token lifetime in seconds.
///
/// # Returns
///
/// A signed JWT delegation token string.
pub fn sign_delegation_token(
private_key_multibase: &str,
issuer: &str,
space_uri: &str,
authority: &str,
expires_in_seconds: i64,
) -> Result<String, SignerError> {
// Load the P-256 signing key from the multibase-encoded private key.
let signing_key = load_p256_signing_key(private_key_multibase)?;
// Create header
let header = DelegationJwtHeader {
alg: "ES256",
typ: DELEGATION_TOKEN_TYP,
kid: "#atproto",
};
// Create payload
let now = chrono::Utc::now().timestamp();
let payload = DelegationPayload {
iss: issuer.to_string(),
sub: space_uri.to_string(),
aud: format!("{}#atproto_space_host", authority),
iat: now,
exp: now + expires_in_seconds,
jti: uuid::Uuid::new_v4().to_string(),
};
// Encode header and payload
let header_json = serde_json::to_string(&header)
.map_err(|e| SignerError::EncodingError(format!("Header serialization failed: {}", e)))?;
let payload_json = serde_json::to_string(&payload)
.map_err(|e| SignerError::EncodingError(format!("Payload serialization failed: {}", e)))?;
sign_es256_jwt(&signing_key, &header_json, &payload_json)
}
/// Sign a space credential using ES256 (ECDSA with P-256).
///
/// The space authority mints this token in exchange for a delegation token
/// (`com.atproto.space.getSpaceCredential`). It grants whole-space read/sync
/// access and is DPoP-bound to the requesting application via its `cnf.jkt`
/// claim, so it can be presented to any repo host serving a repo in the space.
///
/// # Arguments
///
/// * `private_key_multibase` - The space authority's private signing key in
/// multibase format. When the authority publishes no dedicated
/// `#atproto_space` key, this is the account's `#atproto` signing key.
/// * `authority` - The space authority DID (`iss` claim).
/// * `space_uri` - The target space URI (`sub` claim), in the form
/// `at://{authority}/space/{spaceType}/{skey}`.
/// * `dpop_jkt` - JWK thumbprint (RFC 7638) of the application's DPoP key, copied
/// into the credential's `cnf.jkt` to bind it to that key.
/// * `expires_in_seconds` - Token lifetime in seconds.
///
/// # Returns
///
/// A signed JWT space credential string.
pub fn sign_space_credential(
private_key_multibase: &str,
authority: &str,
space_uri: &str,
dpop_jkt: &str,
expires_in_seconds: i64,
) -> Result<String, SignerError> {
// Load the P-256 signing key from the multibase-encoded private key.
let signing_key = load_p256_signing_key(private_key_multibase)?;
// Create header. The credential is signed by the account's `#atproto` key,
// which is the fallback space signing key when no `#atproto_space` key is
// published.
let header = SpaceCredentialJwtHeader {
alg: "ES256",
typ: SPACE_CREDENTIAL_TYP,
kid: "#atproto",
};
// Create payload. A space credential has no `aud`: it is presented to any
// repo host serving a repo in the space, not to a single recipient.
let now = chrono::Utc::now().timestamp();
let payload = SpaceCredentialPayload {
iss: authority.to_string(),
sub: space_uri.to_string(),
cnf: Confirmation {
jkt: dpop_jkt.to_string(),
},
iat: now,
exp: now + expires_in_seconds,
jti: uuid::Uuid::new_v4().to_string(),
};
// Encode header and payload
let header_json = serde_json::to_string(&header)
.map_err(|e| SignerError::EncodingError(format!("Header serialization failed: {}", e)))?;
let payload_json = serde_json::to_string(&payload)
.map_err(|e| SignerError::EncodingError(format!("Payload serialization failed: {}", e)))?;
sign_es256_jwt(&signing_key, &header_json, &payload_json)
}
/// Decode a multibase (base58btc, `z` prefix) P-256 private key and construct a
/// [`SigningKey`].
fn load_p256_signing_key(private_key_multibase: &str) -> Result<SigningKey, SignerError> {
// Decode the multibase private key (z prefix = base58btc)
if !private_key_multibase.starts_with('z') {
return Err(SignerError::InvalidKey(
"Private key must be multibase (base58btc, z prefix)".to_string(),
));
}
let private_key_with_prefix = bs58::decode(&private_key_multibase[1..])
.into_vec()
.map_err(|e| SignerError::InvalidKey(format!("Invalid base58: {}", e)))?;
// Check for P-256 private key prefix (0x86 0x26)
if private_key_with_prefix.len() < 34 {
return Err(SignerError::InvalidKey("Private key too short".to_string()));
}
if private_key_with_prefix[0] != 0x86 || private_key_with_prefix[1] != 0x26 {
return Err(SignerError::InvalidKey(format!(
"Expected P-256 private key prefix (0x86 0x26), got 0x{:02X} 0x{:02X}",
private_key_with_prefix[0], private_key_with_prefix[1]
)));
}
let private_key_bytes = &private_key_with_prefix[2..];
if private_key_bytes.len() != 32 {
return Err(SignerError::InvalidKey(format!(
"Expected 32-byte private key, got {} bytes",
private_key_bytes.len()
)));
}
SigningKey::from_slice(private_key_bytes)
.map_err(|e| SignerError::InvalidKey(format!("Invalid P-256 key: {}", e)))
}
/// Sign a JWT (`header.payload.signature`) with a P-256 key using ES256.
///
/// The signature is computed over `sha256(header_b64.payload_b64)` and
/// normalized to low-S form per the atproto convention.
fn sign_es256_jwt(
signing_key: &SigningKey,
header_json: &str,
payload_json: &str,
) -> Result<String, SignerError> {
let header_b64 = BASE64URL.encode(header_json.as_bytes());
let payload_b64 = BASE64URL.encode(payload_json.as_bytes());
// Create signing input
let signing_input = format!("{}.{}", header_b64, payload_b64);
// Hash the input
let mut hasher = Sha256::new();
hasher.update(signing_input.as_bytes());
let hash: [u8; 32] = hasher.finalize().into();
// Sign the hash
let signature: p256::ecdsa::Signature = signing_key
.sign_prehash(&hash)
.map_err(|e| SignerError::SigningFailed(format!("Signing failed: {}", e)))?;
// Get signature bytes and normalize to low-S form
let signature_bytes = signature.to_bytes();
let normalized_sig = normalize_low_s(&signature_bytes);
// Encode signature
let signature_b64 = BASE64URL.encode(&normalized_sig);
// Assemble JWT
Ok(format!("{}.{}.{}", header_b64, payload_b64, signature_b64))
}
/// Normalize ECDSA signature to low-S form (BIP-62 compliance).
fn normalize_low_s(signature: &[u8]) -> Vec<u8> {
if signature.len() != 64 {
return signature.to_vec();
}
let r = &signature[0..32];
let s = &signature[32..64];
// P-256 curve order
let order: [u8; 32] = [
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xBC, 0xE6, 0xFA, 0xAD, 0xA7, 0x17, 0x9E, 0x84,
0xF3, 0xB9, 0xCA, 0xC2, 0xFC, 0x63, 0x25, 0x51,
];
// half_order = order / 2
let half_order = div_by_2(&order);
// Check if s > half_order (need to normalize)
if compare_be(s, &half_order) > 0 {
// s = order - s
let normalized_s = subtract_be(&order, s);
let mut result = Vec::with_capacity(64);
result.extend_from_slice(r);
result.extend_from_slice(&normalized_s);
result
} else {
signature.to_vec()
}
}
/// Verify a service auth token signature using ES256 (ECDSA with P-256).
///
/// # Arguments
///
/// * `token` - The JWT token to verify
/// * `public_key_multibase` - The public key in multibase format (z prefix = base58btc)
///
/// # Returns
///
/// `Ok(true)` if signature is valid, `Ok(false)` if invalid, `Err` if verification failed.
pub fn verify_service_auth_token(
token: &str,
public_key_multibase: &str,
) -> Result<bool, SignerError> {
// Decode the multibase public key (z prefix = base58btc)
if !public_key_multibase.starts_with('z') {
return Err(SignerError::InvalidKey(
"Public key must be multibase (base58btc, z prefix)".to_string(),
));
}
let public_key_with_prefix = bs58::decode(&public_key_multibase[1..])
.into_vec()
.map_err(|e| SignerError::InvalidKey(format!("Invalid base58: {}", e)))?;
// Check for P-256 public key prefix (0x80 0x24) - compressed
// or uncompressed prefix
if public_key_with_prefix.len() < 2 {
return Err(SignerError::InvalidKey("Public key too short".to_string()));
}
// Determine the curve from the multicodec prefix and extract the raw key
// bytes. atproto signing keys are either P-256 (multicodec 0x80 0x24) or
// secp256k1 (0xe7 0x01). did:plc accounts are predominantly secp256k1, so
// both must be supported or cross-account delegation tokens (whose issuer
// key is resolved from the issuer's DID document) fail to verify.
enum Curve {
P256,
K256,
}
let (curve, public_key_bytes) =
if public_key_with_prefix[0] == 0x80 && public_key_with_prefix[1] == 0x24 {
(Curve::P256, &public_key_with_prefix[2..])
} else if public_key_with_prefix[0] == 0xe7 && public_key_with_prefix[1] == 0x01 {
(Curve::K256, &public_key_with_prefix[2..])
} else {
// No recognized multicodec prefix: assume raw P-256 SEC1 bytes.
(Curve::P256, &public_key_with_prefix[..])
};
// Parse the JWT parts
let parts: Vec<&str> = token.split('.').collect();
if parts.len() != 3 {
return Err(SignerError::EncodingError("Invalid JWT format".to_string()));
}
// Decode the signature
let signature_bytes = BASE64URL
.decode(parts[2])
.map_err(|e| SignerError::EncodingError(format!("Invalid signature encoding: {}", e)))?;
// Signature should be 64 bytes (32 bytes r + 32 bytes s)
if signature_bytes.len() != 64 {
return Err(SignerError::EncodingError(format!(
"Invalid signature length: expected 64, got {}",
signature_bytes.len()
)));
}
// Create signing input (header.payload) and hash it. Both ES256 and ES256K
// sign the SHA-256 digest of the signing input.
let signing_input = format!("{}.{}", parts[0], parts[1]);
let mut hasher = Sha256::new();
hasher.update(signing_input.as_bytes());
let hash: [u8; 32] = hasher.finalize().into();
// Verify against the appropriate curve, normalizing to low-S first so a
// high-S signature (which some signers emit) is still accepted.
match curve {
Curve::P256 => {
let verifying_key = VerifyingKey::from_sec1_bytes(public_key_bytes)
.map_err(|e| SignerError::InvalidKey(format!("Invalid P-256 public key: {}", e)))?;
let signature = p256::ecdsa::Signature::from_slice(&signature_bytes)
.map_err(|e| SignerError::EncodingError(format!("Invalid signature format: {}", e)))?;
let signature = signature.normalize_s().unwrap_or(signature);
Ok(verifying_key.verify_prehash(&hash, &signature).is_ok())
}
Curve::K256 => {
let verifying_key = k256::ecdsa::VerifyingKey::from_sec1_bytes(public_key_bytes)
.map_err(|e| {
SignerError::InvalidKey(format!("Invalid secp256k1 public key: {}", e))
})?;
let signature = k256::ecdsa::Signature::from_slice(&signature_bytes)
.map_err(|e| SignerError::EncodingError(format!("Invalid signature format: {}", e)))?;
let signature = signature.normalize_s().unwrap_or(signature);
Ok(verifying_key.verify_prehash(&hash, &signature).is_ok())
}
}
}
/// Compare two big-endian byte arrays.
fn compare_be(a: &[u8], b: &[u8]) -> i32 {
for i in 0..a.len().min(b.len()) {
if a[i] > b[i] {
return 1;
}
if a[i] < b[i] {
return -1;
}
}
0
}
/// Divide a big-endian number by 2.
fn div_by_2(n: &[u8]) -> Vec<u8> {
let mut result = vec![0u8; n.len()];
let mut carry = 0u8;
for i in 0..n.len() {
let new_val = (n[i] >> 1) | (carry << 7);
carry = n[i] & 1;
result[i] = new_val;
}
result
}
/// Subtract two big-endian numbers: a - b.
fn subtract_be(a: &[u8], b: &[u8]) -> Vec<u8> {
let mut result = vec![0u8; a.len()];
let mut borrow = 0i32;
for i in (0..a.len()).rev() {
let diff = (a[i] as i32) - (b[i] as i32) - borrow;
if diff < 0 {
result[i] = (diff + 256) as u8;
borrow = 1;
} else {
result[i] = diff as u8;
borrow = 0;
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sign_service_auth_token_invalid_key() {
let result = sign_service_auth_token(
"not-multibase",
"did:plc:test",
"did:plc:service",
None,
60,
);
assert!(result.is_err());
}
#[test]
fn test_normalize_low_s_short_signature() {
let short = vec![0x01, 0x02];
let result = normalize_low_s(&short);
assert_eq!(result, short);
}
/// Encode a P-256 signing key as a multibase (base58btc) private key with
/// the `0x86 0x26` multicodec prefix, as stored in `UserPrivateKeyMultibase`.
fn multibase_private_key(signing_key: &SigningKey) -> String {
let mut bytes = vec![0x86u8, 0x26u8];
bytes.extend_from_slice(&signing_key.to_bytes());
format!("z{}", bs58::encode(bytes).into_string())
}
fn decode_jwt_part(part: &str) -> serde_json::Value {
let bytes = BASE64URL.decode(part).expect("valid base64url");
serde_json::from_slice(&bytes).expect("valid json")
}
#[test]
fn test_sign_delegation_token_invalid_key() {
let result = sign_delegation_token(
"not-multibase",
"did:plc:user",
"at://did:plc:authority/space/my.bulletin.board/self",
"did:plc:authority",
60,
);
assert!(result.is_err());
}
#[test]
fn test_sign_delegation_token_header_and_claims() {
let signing_key = SigningKey::from_slice(&[0x42u8; 32]).unwrap();
let private_key = multibase_private_key(&signing_key);
let space_uri = "at://did:plc:authority/space/my.bulletin.board/self";
let token = sign_delegation_token(
&private_key,
"did:plc:user",
space_uri,
"did:plc:authority",
DELEGATION_TOKEN_TTL_SECS,
)
.expect("delegation token mints");
let parts: Vec<&str> = token.split('.').collect();
assert_eq!(parts.len(), 3);
let header = decode_jwt_part(parts[0]);
assert_eq!(header["alg"], "ES256");
assert_eq!(header["typ"], DELEGATION_TOKEN_TYP);
assert_eq!(header["kid"], "#atproto");
let claims = decode_jwt_part(parts[1]);
assert_eq!(claims["iss"], "did:plc:user");
assert_eq!(claims["sub"], space_uri);
assert_eq!(claims["aud"], "did:plc:authority#atproto_space_host");
assert!(claims["jti"].is_string());
let iat = claims["iat"].as_i64().unwrap();
let exp = claims["exp"].as_i64().unwrap();
assert_eq!(exp - iat, DELEGATION_TOKEN_TTL_SECS);
// The signature verifies against the account's public key.
let verifying_key = signing_key.verifying_key();
let mut pub_bytes = vec![0x80u8, 0x24u8];
pub_bytes.extend_from_slice(verifying_key.to_encoded_point(true).as_bytes());
let public_key = format!("z{}", bs58::encode(pub_bytes).into_string());
assert!(verify_service_auth_token(&token, &public_key).unwrap());
}
#[test]
fn test_delegation_token_jti_is_unique() {
let signing_key = SigningKey::from_slice(&[0x42u8; 32]).unwrap();
let private_key = multibase_private_key(&signing_key);
let space_uri = "at://did:plc:authority/space/my.bulletin.board/self";
let first = sign_delegation_token(&private_key, "did:plc:user", space_uri, "did:plc:authority", 60).unwrap();
let second = sign_delegation_token(&private_key, "did:plc:user", space_uri, "did:plc:authority", 60).unwrap();
let jti_a = decode_jwt_part(first.split('.').nth(1).unwrap())["jti"].clone();
let jti_b = decode_jwt_part(second.split('.').nth(1).unwrap())["jti"].clone();
assert_ne!(jti_a, jti_b);
}
#[test]
fn test_sign_space_credential_invalid_key() {
let result = sign_space_credential(
"not-multibase",
"did:plc:authority",
"at://did:plc:authority/space/my.bulletin.board/self",
"0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I",
SPACE_CREDENTIAL_TTL_SECS,
);
assert!(result.is_err());
}
#[test]
fn test_sign_space_credential_header_and_claims() {
let signing_key = SigningKey::from_slice(&[0x42u8; 32]).unwrap();
let private_key = multibase_private_key(&signing_key);
let space_uri = "at://did:plc:authority/space/my.bulletin.board/self";
let jkt = "0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I";
let token = sign_space_credential(
&private_key,
"did:plc:authority",
space_uri,
jkt,
SPACE_CREDENTIAL_TTL_SECS,
)
.expect("space credential mints");
let parts: Vec<&str> = token.split('.').collect();
assert_eq!(parts.len(), 3);
let header = decode_jwt_part(parts[0]);
assert_eq!(header["alg"], "ES256");
assert_eq!(header["typ"], SPACE_CREDENTIAL_TYP);
assert_eq!(header["kid"], "#atproto");
let claims = decode_jwt_part(parts[1]);
assert_eq!(claims["iss"], "did:plc:authority");
assert_eq!(claims["sub"], space_uri);
assert_eq!(claims["cnf"]["jkt"], jkt);
// A space credential is presented to any repo host, so it carries no aud.
assert!(claims.get("aud").is_none());
assert!(claims["jti"].is_string());
let iat = claims["iat"].as_i64().unwrap();
let exp = claims["exp"].as_i64().unwrap();
assert_eq!(exp - iat, SPACE_CREDENTIAL_TTL_SECS);
// The signature verifies against the authority's public key.
let verifying_key = signing_key.verifying_key();
let mut pub_bytes = vec![0x80u8, 0x24u8];
pub_bytes.extend_from_slice(verifying_key.to_encoded_point(true).as_bytes());
let public_key = format!("z{}", bs58::encode(pub_bytes).into_string());
assert!(verify_service_auth_token(&token, &public_key).unwrap());
}
#[test]
fn verifies_secp256k1_signed_token() {
// did:plc accounts are predominantly secp256k1. A delegation token
// signed with such a key (issuer key resolved from the DID document)
// must verify, otherwise cross-account getSpaceCredential fails before
// authorization runs.
let signing_key = k256::ecdsa::SigningKey::from_slice(&[0x24u8; 32]).unwrap();
let header = BASE64URL
.encode(br##"{"alg":"ES256K","typ":"atproto-space-delegation+jwt","kid":"#atproto"}"##);
let payload = BASE64URL.encode(br#"{"iss":"did:plc:user"}"#);
let signing_input = format!("{}.{}", header, payload);
let mut hasher = Sha256::new();
hasher.update(signing_input.as_bytes());
let hash: [u8; 32] = hasher.finalize().into();
let signature: k256::ecdsa::Signature = signing_key.sign_prehash(&hash).unwrap();
let signature = signature.normalize_s().unwrap_or(signature);
let token = format!("{}.{}", signing_input, BASE64URL.encode(signature.to_bytes()));
// Encode the public key as multibase with the secp256k1 multicodec
// prefix (0xe7 0x01), exactly as it appears in a DID document.
let verifying_key = signing_key.verifying_key();
let mut pub_bytes = vec![0xe7u8, 0x01u8];
pub_bytes.extend_from_slice(verifying_key.to_encoded_point(true).as_bytes());
let public_key = format!("z{}", bs58::encode(pub_bytes).into_string());
assert!(verify_service_auth_token(&token, &public_key).unwrap());
// A different secp256k1 key must not verify the same token.
let other = k256::ecdsa::SigningKey::from_slice(&[0x25u8; 32]).unwrap();
let mut other_bytes = vec![0xe7u8, 0x01u8];
other_bytes.extend_from_slice(other.verifying_key().to_encoded_point(true).as_bytes());
let other_pub = format!("z{}", bs58::encode(other_bytes).into_string());
assert!(!verify_service_auth_token(&token, &other_pub).unwrap());
}
}