atproto-record 0.11.3

AT Protocol record signature operations - cryptographic signing and verification for AT Protocol records
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
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
//! Attestation and signature types for AT Protocol.
//!
//! This module provides types for cryptographic signatures and attestations
//! that can be attached to records to prove authenticity, authorization,
//! or other properties.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::lexicon::Bytes;
use crate::lexicon::com_atproto_repo::TypedStrongRef;
use crate::typed::{LexiconType, TypedLexicon};

/// The namespace identifier for signatures
pub const NSID: &str = "community.lexicon.attestation.signature";

/// Enum that can hold either a signature reference or an inline signature.
///
/// This type allows signatures to be either embedded directly in a record
/// or referenced via a strong reference. This flexibility enables:
/// - Inline signatures for immediate verification
/// - Referenced signatures for deduplication and separate storage
///
/// # Example
///
/// ```ignore
/// use atproto_record::lexicon::community::lexicon::attestation::{SignatureOrRef, create_typed_signature};
/// use atproto_record::lexicon::Bytes;
///
/// // Inline signature
/// let inline = SignatureOrRef::Inline(create_typed_signature(
///     "did:plc:issuer".to_string(),
///     Bytes { bytes: b"signature".to_vec() },
/// ));
///
/// // Referenced signature
/// let reference = SignatureOrRef::Reference(typed_strong_ref);
/// ```
#[derive(Deserialize, Serialize, Clone, PartialEq)]
#[cfg_attr(debug_assertions, derive(Debug))]
#[serde(untagged)]
pub enum SignatureOrRef {
    /// A reference to a signature stored elsewhere
    Reference(TypedStrongRef),
    /// An inline signature
    Inline(TypedSignature),
}

/// A vector of signatures that can be either inline or referenced.
///
/// This type alias is commonly used in records that support multiple
/// signatures, such as badges, awards, and RSVPs.
pub type Signatures = Vec<SignatureOrRef>;

/// Cryptographic signature structure.
///
/// Represents a signature created by an issuer (identified by DID) over
/// some data. The signature can be used to verify authenticity, authorization,
/// or other properties of the signed content.
///
/// # Fields
///
/// - `issuer`: DID of the entity that created the signature
/// - `signature`: The actual signature bytes
/// - `extra`: Additional fields that may be present in the signature
///
/// # Example
///
/// ```ignore
/// use atproto_record::lexicon::community::lexicon::attestation::Signature;
/// use atproto_record::lexicon::Bytes;
/// use std::collections::HashMap;
///
/// let sig = Signature {
///     issuer: "did:plc:example".to_string(),
///     signature: Bytes { bytes: b"signature_bytes".to_vec() },
///     extra: HashMap::new(),
/// };
/// ```
#[derive(Deserialize, Serialize, Clone, PartialEq)]
#[cfg_attr(debug_assertions, derive(Debug))]
pub struct Signature {
    /// DID of the entity that created this signature
    pub issuer: String,

    /// The cryptographic signature bytes
    pub signature: Bytes,

    /// Additional fields for extensibility
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

impl LexiconType for Signature {
    fn lexicon_type() -> &'static str {
        NSID
    }

    /// Type field is optional for signatures since they may appear without it
    fn type_required() -> bool {
        false
    }
}

/// Type alias for Signature with automatic $type field handling.
///
/// This wrapper ensures proper serialization/deserialization of the
/// `$type` field when present.
pub type TypedSignature = TypedLexicon<Signature>;

/// Helper function to create a typed signature.
///
/// Creates a new signature with the TypedLexicon wrapper, ensuring
/// proper `$type` field handling.
///
/// # Arguments
///
/// * `issuer` - DID of the signature issuer
/// * `signature` - The signature bytes
///
/// # Example
///
/// ```ignore
/// use atproto_record::lexicon::community::lexicon::attestation::create_typed_signature;
/// use atproto_record::lexicon::Bytes;
///
/// let sig = create_typed_signature(
///     "did:plc:issuer".to_string(),
///     Bytes { bytes: b"sig_data".to_vec() },
/// );
/// ```
pub fn create_typed_signature(issuer: String, signature: Bytes) -> TypedSignature {
    TypedLexicon::new(Signature {
        issuer,
        signature,
        extra: HashMap::new(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lexicon::com_atproto_repo::StrongRef;
    use serde_json::json;

    #[test]
    fn test_real_signature_or_ref_deserialization() {
        // Test with the exact signature structure from the user's RSVP
        let json_str = r#"{
            "$type": "community.lexicon.attestation.signature",
            "issuedAt": "2025-08-19T20:17:17.133Z",
            "issuer": "did:web:acudo-dev.smokesignal.tools",
            "signature": {
                "$bytes": "mr9c0MCu3g6SXNQ25JFhzfX1ecYgK9k1Kf6OZI2p2AlQRoQu09dOE7J5uaeilIx/UFCjJErO89C/uBBb9ANmUA"
            }
        }"#;

        // First, try to deserialize as TypedSignature
        let typed_sig_result: Result<TypedSignature, _> = serde_json::from_str(json_str);
        match &typed_sig_result {
            Ok(sig) => {
                println!("TypedSignature OK: issuer={}", sig.inner.issuer);
                assert_eq!(sig.inner.issuer, "did:web:acudo-dev.smokesignal.tools");
            }
            Err(e) => {
                eprintln!("TypedSignature deserialization error: {}", e);
            }
        }

        // Then try as SignatureOrRef
        let sig_or_ref_result: Result<SignatureOrRef, _> = serde_json::from_str(json_str);
        match &sig_or_ref_result {
            Ok(SignatureOrRef::Inline(sig)) => {
                println!("SignatureOrRef OK (Inline): issuer={}", sig.inner.issuer);
                assert_eq!(sig.inner.issuer, "did:web:acudo-dev.smokesignal.tools");
            }
            Ok(SignatureOrRef::Reference(_)) => {
                panic!("Expected Inline signature, got Reference");
            }
            Err(e) => {
                eprintln!("SignatureOrRef deserialization error: {}", e);
            }
        }

        // Try without $type field
        let json_no_type = r#"{
            "issuedAt": "2025-08-19T20:17:17.133Z",
            "issuer": "did:web:acudo-dev.smokesignal.tools",
            "signature": {
                "$bytes": "mr9c0MCu3g6SXNQ25JFhzfX1ecYgK9k1Kf6OZI2p2AlQRoQu09dOE7J5uaeilIx/UFCjJErO89C/uBBb9ANmUA"
            }
        }"#;

        let no_type_result: Result<Signature, _> = serde_json::from_str(json_no_type);
        match &no_type_result {
            Ok(sig) => {
                println!("Signature (no type) OK: issuer={}", sig.issuer);
                assert_eq!(sig.issuer, "did:web:acudo-dev.smokesignal.tools");
                assert_eq!(sig.signature.bytes.len(), 64);

                // Now wrap it in TypedLexicon and try as SignatureOrRef
                let typed = TypedLexicon::new(sig.clone());
                let _as_sig_or_ref = SignatureOrRef::Inline(typed);
                println!("Successfully created SignatureOrRef from Signature");
            }
            Err(e) => {
                eprintln!("Signature (no type) deserialization error: {}", e);
            }
        }

        // Check that at least one worked
        assert!(
            typed_sig_result.is_ok() || sig_or_ref_result.is_ok() || no_type_result.is_ok(),
            "Failed to deserialize signature in any form"
        );
    }

    #[test]
    fn test_signature_deserialization() {
        let json_str = r#"{
            "$type": "community.lexicon.attestation.signature",
            "issuer": "did:plc:test123",
            "signature": {"$bytes": "dGVzdCBzaWduYXR1cmU="}
        }"#;

        let signature: Signature = serde_json::from_str(json_str).unwrap();

        assert_eq!(signature.issuer, "did:plc:test123");
        assert_eq!(signature.signature.bytes, b"test signature");
        // The $type field will be captured in extra due to #[serde(flatten)]
        assert_eq!(signature.extra.len(), 1);
        assert!(signature.extra.contains_key("$type"));
    }

    #[test]
    fn test_signature_deserialization_with_extra_fields() {
        let json_str = r#"{
            "$type": "community.lexicon.attestation.signature",
            "issuer": "did:plc:test123",
            "signature": {"$bytes": "dGVzdCBzaWduYXR1cmU="},
            "issuedAt": "2024-01-01T00:00:00.000Z",
            "purpose": "verification"
        }"#;

        let signature: Signature = serde_json::from_str(json_str).unwrap();

        assert_eq!(signature.issuer, "did:plc:test123");
        assert_eq!(signature.signature.bytes, b"test signature");
        // 3 extra fields: $type, issuedAt, purpose
        assert_eq!(signature.extra.len(), 3);
        assert!(signature.extra.contains_key("$type"));
        assert_eq!(
            signature.extra.get("issuedAt").unwrap(),
            "2024-01-01T00:00:00.000Z"
        );
        assert_eq!(signature.extra.get("purpose").unwrap(), "verification");
    }

    #[test]
    fn test_signature_serialization() {
        let mut extra = HashMap::new();
        extra.insert("custom_field".to_string(), json!("custom_value"));

        let signature = Signature {
            issuer: "did:plc:serializer".to_string(),
            signature: Bytes {
                bytes: b"hello world".to_vec(),
            },
            extra,
        };

        let json = serde_json::to_value(&signature).unwrap();

        // Without custom Serialize impl, $type is not automatically added
        assert!(!json.as_object().unwrap().contains_key("$type"));
        assert_eq!(json["issuer"], "did:plc:serializer");
        // "hello world" base64 encoded is "aGVsbG8gd29ybGQ="
        assert_eq!(json["signature"]["$bytes"], "aGVsbG8gd29ybGQ=");
        assert_eq!(json["custom_field"], "custom_value");
    }

    #[test]
    fn test_signature_round_trip() {
        let original = Signature {
            issuer: "did:plc:roundtrip".to_string(),
            signature: Bytes {
                bytes: b"round trip test".to_vec(),
            },
            extra: HashMap::new(),
        };

        // Serialize to JSON
        let json = serde_json::to_string(&original).unwrap();

        // Deserialize back
        let deserialized: Signature = serde_json::from_str(&json).unwrap();

        assert_eq!(original.issuer, deserialized.issuer);
        assert_eq!(original.signature.bytes, deserialized.signature.bytes);
        // Without the custom Serialize impl, no $type is added
        // so the round-trip preserves the empty extra map
        assert_eq!(deserialized.extra.len(), 0);
    }

    #[test]
    fn test_signature_with_complex_extra_fields() {
        let mut extra = HashMap::new();
        extra.insert("timestamp".to_string(), json!(1234567890));
        extra.insert(
            "metadata".to_string(),
            json!({
                "version": "1.0",
                "algorithm": "ES256"
            }),
        );
        extra.insert("tags".to_string(), json!(["tag1", "tag2", "tag3"]));

        let signature = Signature {
            issuer: "did:plc:complex".to_string(),
            signature: Bytes {
                bytes: vec![0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA],
            },
            extra,
        };

        let json = serde_json::to_value(&signature).unwrap();

        // Without custom Serialize impl, $type is not automatically added
        assert!(!json.as_object().unwrap().contains_key("$type"));
        assert_eq!(json["issuer"], "did:plc:complex");
        assert_eq!(json["timestamp"], 1234567890);
        assert_eq!(json["metadata"]["version"], "1.0");
        assert_eq!(json["metadata"]["algorithm"], "ES256");
        assert_eq!(json["tags"], json!(["tag1", "tag2", "tag3"]));
    }

    #[test]
    fn test_empty_signature() {
        let signature = Signature {
            issuer: String::new(),
            signature: Bytes { bytes: Vec::new() },
            extra: HashMap::new(),
        };

        let json = serde_json::to_value(&signature).unwrap();

        // Without custom Serialize impl, $type is not automatically added
        assert!(!json.as_object().unwrap().contains_key("$type"));
        assert_eq!(json["issuer"], "");
        assert_eq!(json["signature"]["$bytes"], ""); // Empty bytes encode to empty string
    }

    #[test]
    fn test_signatures_vec_serialization() {
        // Test with plain Vec<Signature> for basic signature serialization
        let signatures: Vec<Signature> = vec![
            Signature {
                issuer: "did:plc:first".to_string(),
                signature: Bytes {
                    bytes: b"first".to_vec(),
                },
                extra: HashMap::new(),
            },
            Signature {
                issuer: "did:plc:second".to_string(),
                signature: Bytes {
                    bytes: b"second".to_vec(),
                },
                extra: HashMap::new(),
            },
        ];

        let json = serde_json::to_value(&signatures).unwrap();

        assert!(json.is_array());
        assert_eq!(json.as_array().unwrap().len(), 2);
        assert_eq!(json[0]["issuer"], "did:plc:first");
        assert_eq!(json[1]["issuer"], "did:plc:second");
    }

    #[test]
    fn test_signatures_as_signature_or_ref_vec() {
        // Test the new Signatures type with inline signatures
        let signatures: Signatures = vec![
            SignatureOrRef::Inline(create_typed_signature(
                "did:plc:first".to_string(),
                Bytes {
                    bytes: b"first".to_vec(),
                },
            )),
            SignatureOrRef::Inline(create_typed_signature(
                "did:plc:second".to_string(),
                Bytes {
                    bytes: b"second".to_vec(),
                },
            )),
        ];

        let json = serde_json::to_value(&signatures).unwrap();

        assert!(json.is_array());
        assert_eq!(json.as_array().unwrap().len(), 2);
        assert_eq!(json[0]["$type"], "community.lexicon.attestation.signature");
        assert_eq!(json[0]["issuer"], "did:plc:first");
        assert_eq!(json[1]["$type"], "community.lexicon.attestation.signature");
        assert_eq!(json[1]["issuer"], "did:plc:second");
    }

    #[test]
    fn test_typed_signature_serialization() {
        let typed_sig = create_typed_signature(
            "did:plc:typed".to_string(),
            Bytes {
                bytes: b"typed signature".to_vec(),
            },
        );

        let json = serde_json::to_value(&typed_sig).unwrap();

        assert_eq!(json["$type"], "community.lexicon.attestation.signature");
        assert_eq!(json["issuer"], "did:plc:typed");
        // "typed signature" base64 encoded
        assert_eq!(json["signature"]["$bytes"], "dHlwZWQgc2lnbmF0dXJl");
    }

    #[test]
    fn test_typed_signature_deserialization() {
        let json = json!({
            "$type": "community.lexicon.attestation.signature",
            "issuer": "did:plc:typed",
            "signature": {"$bytes": "dHlwZWQgc2lnbmF0dXJl"}
        });

        let typed_sig: TypedSignature = serde_json::from_value(json).unwrap();

        assert_eq!(typed_sig.inner.issuer, "did:plc:typed");
        assert_eq!(typed_sig.inner.signature.bytes, b"typed signature");
        assert!(typed_sig.has_type_field());
        assert!(typed_sig.validate().is_ok());
    }

    #[test]
    fn test_typed_signature_without_type_field() {
        let json = json!({
            "issuer": "did:plc:notype",
            "signature": {"$bytes": "bm8gdHlwZQ=="}  // "no type" in base64
        });

        let typed_sig: TypedSignature = serde_json::from_value(json).unwrap();

        assert_eq!(typed_sig.inner.issuer, "did:plc:notype");
        assert_eq!(typed_sig.inner.signature.bytes, b"no type");
        assert!(!typed_sig.has_type_field());
        // Validation should still pass because type_required() returns false for Signature
        assert!(typed_sig.validate().is_ok());
    }

    #[test]
    fn test_typed_signature_with_extra_fields() {
        let mut sig = Signature {
            issuer: "did:plc:extra".to_string(),
            signature: Bytes {
                bytes: b"extra test".to_vec(),
            },
            extra: HashMap::new(),
        };
        sig.extra
            .insert("customField".to_string(), json!("customValue"));
        sig.extra.insert("timestamp".to_string(), json!(1234567890));

        let typed_sig = TypedLexicon::new(sig);

        let json = serde_json::to_value(&typed_sig).unwrap();

        assert_eq!(json["$type"], "community.lexicon.attestation.signature");
        assert_eq!(json["issuer"], "did:plc:extra");
        assert_eq!(json["customField"], "customValue");
        assert_eq!(json["timestamp"], 1234567890);
    }

    #[test]
    fn test_typed_signature_round_trip() {
        let original = Signature {
            issuer: "did:plc:roundtrip2".to_string(),
            signature: Bytes {
                bytes: b"round trip typed".to_vec(),
            },
            extra: HashMap::new(),
        };

        let typed = TypedLexicon::new(original.clone());

        let json = serde_json::to_string(&typed).unwrap();
        let deserialized: TypedSignature = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.inner.issuer, original.issuer);
        assert_eq!(deserialized.inner.signature.bytes, original.signature.bytes);
        assert!(deserialized.has_type_field());
    }

    #[test]
    fn test_typed_signatures_vec() {
        let typed_sigs: Vec<TypedSignature> = vec![
            create_typed_signature(
                "did:plc:first".to_string(),
                Bytes {
                    bytes: b"first".to_vec(),
                },
            ),
            create_typed_signature(
                "did:plc:second".to_string(),
                Bytes {
                    bytes: b"second".to_vec(),
                },
            ),
        ];

        let json = serde_json::to_value(&typed_sigs).unwrap();

        assert!(json.is_array());
        assert_eq!(json[0]["$type"], "community.lexicon.attestation.signature");
        assert_eq!(json[0]["issuer"], "did:plc:first");
        assert_eq!(json[1]["$type"], "community.lexicon.attestation.signature");
        assert_eq!(json[1]["issuer"], "did:plc:second");
    }

    #[test]
    fn test_plain_vs_typed_signature() {
        // Plain Signature doesn't include $type field
        let plain_sig = Signature {
            issuer: "did:plc:plain".to_string(),
            signature: Bytes {
                bytes: b"plain sig".to_vec(),
            },
            extra: HashMap::new(),
        };

        let plain_json = serde_json::to_value(&plain_sig).unwrap();
        assert!(!plain_json.as_object().unwrap().contains_key("$type"));

        // TypedSignature automatically includes $type field
        let typed_sig = TypedLexicon::new(plain_sig.clone());
        let typed_json = serde_json::to_value(&typed_sig).unwrap();
        assert_eq!(
            typed_json["$type"],
            "community.lexicon.attestation.signature"
        );

        // Both have the same core data
        assert_eq!(plain_json["issuer"], typed_json["issuer"]);
        assert_eq!(plain_json["signature"], typed_json["signature"]);
    }

    #[test]
    fn test_signature_or_ref_inline() {
        // Test inline signature
        let inline_sig = create_typed_signature(
            "did:plc:inline".to_string(),
            Bytes {
                bytes: b"inline signature".to_vec(),
            },
        );

        let sig_or_ref = SignatureOrRef::Inline(inline_sig);

        // Serialize
        let json = serde_json::to_value(&sig_or_ref).unwrap();
        assert_eq!(json["$type"], "community.lexicon.attestation.signature");
        assert_eq!(json["issuer"], "did:plc:inline");
        assert_eq!(json["signature"]["$bytes"], "aW5saW5lIHNpZ25hdHVyZQ=="); // "inline signature" in base64

        // Deserialize
        let deserialized: SignatureOrRef = serde_json::from_value(json.clone()).unwrap();
        match deserialized {
            SignatureOrRef::Inline(sig) => {
                assert_eq!(sig.inner.issuer, "did:plc:inline");
                assert_eq!(sig.inner.signature.bytes, b"inline signature");
            }
            _ => panic!("Expected inline signature"),
        }
    }

    #[test]
    fn test_signature_or_ref_reference() {
        // Test reference to signature
        let strong_ref = StrongRef {
            uri: "at://did:plc:repo/community.lexicon.attestation.signature/abc123".to_string(),
            cid: "bafyreisigref123".to_string(),
        };
        let typed_ref = TypedLexicon::new(strong_ref);

        let sig_or_ref = SignatureOrRef::Reference(typed_ref);

        // Serialize
        let json = serde_json::to_value(&sig_or_ref).unwrap();
        assert_eq!(json["$type"], "com.atproto.repo.strongRef");
        assert_eq!(
            json["uri"],
            "at://did:plc:repo/community.lexicon.attestation.signature/abc123"
        );
        assert_eq!(json["cid"], "bafyreisigref123");

        // Deserialize
        let deserialized: SignatureOrRef = serde_json::from_value(json.clone()).unwrap();
        match deserialized {
            SignatureOrRef::Reference(ref_) => {
                assert_eq!(
                    ref_.uri,
                    "at://did:plc:repo/community.lexicon.attestation.signature/abc123"
                );
                assert_eq!(ref_.cid, "bafyreisigref123");
            }
            _ => panic!("Expected reference"),
        }
    }

    #[test]
    fn test_signatures_mixed_vector() {
        // Create a vector with both inline and referenced signatures
        let signatures: Signatures = vec![
            // Inline signature
            SignatureOrRef::Inline(create_typed_signature(
                "did:plc:signer1".to_string(),
                Bytes {
                    bytes: b"sig1".to_vec(),
                },
            )),
            // Referenced signature
            SignatureOrRef::Reference(TypedLexicon::new(StrongRef {
                uri: "at://did:plc:repo/community.lexicon.attestation.signature/sig2".to_string(),
                cid: "bafyreisig2".to_string(),
            })),
            // Another inline signature
            SignatureOrRef::Inline(create_typed_signature(
                "did:plc:signer3".to_string(),
                Bytes {
                    bytes: b"sig3".to_vec(),
                },
            )),
        ];

        // Serialize
        let json = serde_json::to_value(&signatures).unwrap();
        assert!(json.is_array());
        let array = json.as_array().unwrap();
        assert_eq!(array.len(), 3);

        // First element should be inline signature
        assert_eq!(array[0]["$type"], "community.lexicon.attestation.signature");
        assert_eq!(array[0]["issuer"], "did:plc:signer1");

        // Second element should be reference
        assert_eq!(array[1]["$type"], "com.atproto.repo.strongRef");
        assert_eq!(
            array[1]["uri"],
            "at://did:plc:repo/community.lexicon.attestation.signature/sig2"
        );

        // Third element should be inline signature
        assert_eq!(array[2]["$type"], "community.lexicon.attestation.signature");
        assert_eq!(array[2]["issuer"], "did:plc:signer3");

        // Deserialize back
        let deserialized: Signatures = serde_json::from_value(json).unwrap();
        assert_eq!(deserialized.len(), 3);

        // Verify each element
        match &deserialized[0] {
            SignatureOrRef::Inline(sig) => assert_eq!(sig.inner.issuer, "did:plc:signer1"),
            _ => panic!("Expected inline signature at index 0"),
        }

        match &deserialized[1] {
            SignatureOrRef::Reference(ref_) => {
                assert_eq!(
                    ref_.uri,
                    "at://did:plc:repo/community.lexicon.attestation.signature/sig2"
                )
            }
            _ => panic!("Expected reference at index 1"),
        }

        match &deserialized[2] {
            SignatureOrRef::Inline(sig) => assert_eq!(sig.inner.issuer, "did:plc:signer3"),
            _ => panic!("Expected inline signature at index 2"),
        }
    }

    #[test]
    fn test_signature_or_ref_deserialization_from_json() {
        // Test deserializing from raw JSON strings

        // Inline signature JSON
        let inline_json = r#"{
            "$type": "community.lexicon.attestation.signature",
            "issuer": "did:plc:testinline",
            "signature": {"$bytes": "aGVsbG8="}
        }"#;

        let inline_deser: SignatureOrRef = serde_json::from_str(inline_json).unwrap();
        match inline_deser {
            SignatureOrRef::Inline(sig) => {
                assert_eq!(sig.inner.issuer, "did:plc:testinline");
                assert_eq!(sig.inner.signature.bytes, b"hello");
            }
            _ => panic!("Expected inline signature"),
        }

        // Reference JSON
        let ref_json = r#"{
            "$type": "com.atproto.repo.strongRef",
            "uri": "at://did:plc:test/collection/record",
            "cid": "bafyreicid"
        }"#;

        let ref_deser: SignatureOrRef = serde_json::from_str(ref_json).unwrap();
        match ref_deser {
            SignatureOrRef::Reference(ref_) => {
                assert_eq!(ref_.uri, "at://did:plc:test/collection/record");
                assert_eq!(ref_.cid, "bafyreicid");
            }
            _ => panic!("Expected reference"),
        }
    }
}