tap-msg 0.7.0

Core message processing library for the Transaction Authorization Protocol
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! Connection types for TAP messages.
//!
//! This module defines the structure of connection messages and related types
//! used in the Transaction Authorization Protocol (TAP).

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::error::{Error, Result};
use crate::message::agent::TapParticipant;
use crate::message::tap_message_trait::{TapMessage as TapMessageTrait, TapMessageBody};
use crate::message::{Agent, Party};
use crate::TapMessage;

/// Agent structure specific to Connect messages (legacy).
/// In TAIP-15 v2, standard Agent objects from TAIP-5 are used instead.
/// This type is kept for backward compatibility with older messages.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectAgent {
    /// DID of the agent.
    #[serde(rename = "@id")]
    pub id: String,

    /// Name of the agent (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Type of the agent (optional).
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub agent_type: Option<String>,

    /// Service URL for the agent (optional).
    #[serde(rename = "serviceUrl", skip_serializing_if = "Option::is_none")]
    pub service_url: Option<String>,

    /// Additional metadata.
    #[serde(flatten)]
    pub metadata: HashMap<String, serde_json::Value>,
}

impl TapParticipant for ConnectAgent {
    fn id(&self) -> &str {
        &self.id
    }
}

impl ConnectAgent {
    /// Create a new ConnectAgent with just an ID.
    pub fn new(id: &str) -> Self {
        Self {
            id: id.to_string(),
            name: None,
            agent_type: None,
            service_url: None,
            metadata: HashMap::new(),
        }
    }

    /// Convert to a regular Agent by adding a for_party.
    pub fn to_agent(&self, for_party: &str) -> Agent {
        let mut agent = Agent::new_without_role(&self.id, for_party);

        // Copy metadata fields
        if let Some(name) = &self.name {
            agent
                .metadata
                .insert("name".to_string(), serde_json::Value::String(name.clone()));
        }
        if let Some(agent_type) = &self.agent_type {
            agent.metadata.insert(
                "type".to_string(),
                serde_json::Value::String(agent_type.clone()),
            );
        }
        if let Some(service_url) = &self.service_url {
            agent.metadata.insert(
                "serviceUrl".to_string(),
                serde_json::Value::String(service_url.clone()),
            );
        }

        // Copy any additional metadata
        for (k, v) in &self.metadata {
            agent.metadata.insert(k.clone(), v.clone());
        }

        agent
    }
}

/// Transaction limits for connection constraints (TAIP-15).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionLimits {
    /// Maximum amount per transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_transaction: Option<String>,

    /// Maximum daily amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_day: Option<String>,

    /// Maximum weekly amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_week: Option<String>,

    /// Maximum monthly amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_month: Option<String>,

    /// Maximum yearly amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_year: Option<String>,

    /// Currency for the limits (ISO 4217). Required when limits are specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
}

/// Connection constraints for the Connect message (TAIP-15).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionConstraints {
    /// Allowed TAIP-13 purpose codes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub purposes: Option<Vec<String>>,

    /// Allowed TAIP-13 category purpose codes.
    #[serde(rename = "categoryPurposes", skip_serializing_if = "Option::is_none")]
    pub category_purposes: Option<Vec<String>>,

    /// Transaction limits.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limits: Option<TransactionLimits>,

    /// Allowed beneficiary parties (TAIP-6 Party objects).
    #[serde(
        rename = "allowedBeneficiaries",
        skip_serializing_if = "Option::is_none"
    )]
    pub allowed_beneficiaries: Option<Vec<Party>>,

    /// Allowed settlement addresses (CAIP-10 format).
    #[serde(
        rename = "allowedSettlementAddresses",
        skip_serializing_if = "Option::is_none"
    )]
    pub allowed_settlement_addresses: Option<Vec<String>>,

    /// Allowed asset identifiers (CAIP-19 format).
    #[serde(rename = "allowedAssets", skip_serializing_if = "Option::is_none")]
    pub allowed_assets: Option<Vec<String>>,
}

/// Connect message body (TAIP-15).
#[derive(Debug, Clone, Serialize, Deserialize, TapMessage)]
#[tap(
    message_type = "https://tap.rsvp/schema/1.0#Connect",
    initiator,
    authorizable
)]
pub struct Connect {
    /// Transaction ID (only available after creation).
    #[serde(skip)]
    #[tap(transaction_id)]
    pub transaction_id: Option<String>,

    /// Requester party (TAIP-15 v2, required for new messages).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[tap(participant)]
    pub requester: Option<Party>,

    /// Principal party this connection is for.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[tap(participant)]
    pub principal: Option<Party>,

    /// Agents involved in the connection (TAIP-5 agents).
    #[serde(default)]
    #[tap(participant_list)]
    pub agents: Vec<Agent>,

    /// Connection constraints (required per TAIP-15).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub constraints: Option<ConnectionConstraints>,

    /// URL pointing to terms of service or agreement.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agreement: Option<String>,

    /// Expiration time in ISO 8601 format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiry: Option<String>,

    // --- Legacy fields for backward compatibility ---
    /// Agent DID (legacy, use agents array instead).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,

    /// Legacy agent object (use agents array instead).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent: Option<ConnectAgent>,

    /// Legacy entity this connection is for (use principal instead).
    #[serde(rename = "for", skip_serializing_if = "Option::is_none", default)]
    pub for_: Option<String>,

    /// Legacy role field (use agents with roles instead).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
}

impl Connect {
    /// Create a new Connect message with requester, principal, and agents (TAIP-15 v2).
    pub fn new_v2(
        requester: Party,
        principal: Party,
        agents: Vec<Agent>,
        constraints: ConnectionConstraints,
    ) -> Self {
        Self {
            transaction_id: None,
            requester: Some(requester),
            principal: Some(principal),
            agents,
            constraints: Some(constraints),
            agreement: None,
            expiry: None,
            agent_id: None,
            agent: None,
            for_: None,
            role: None,
        }
    }

    /// Create a new Connect message (legacy backward compatible).
    pub fn new(transaction_id: &str, agent_id: &str, for_id: &str, role: Option<&str>) -> Self {
        Self {
            transaction_id: Some(transaction_id.to_string()),
            requester: None,
            principal: None,
            agents: vec![],
            constraints: None,
            agreement: None,
            expiry: None,
            agent_id: Some(agent_id.to_string()),
            agent: None,
            for_: Some(for_id.to_string()),
            role: role.map(|s| s.to_string()),
        }
    }

    /// Create a new Connect message with Agent and Principal.
    pub fn new_with_agent_and_principal(
        transaction_id: &str,
        agent: ConnectAgent,
        principal: Party,
    ) -> Self {
        Self {
            transaction_id: Some(transaction_id.to_string()),
            requester: None,
            principal: Some(principal),
            agents: vec![],
            constraints: None,
            agreement: None,
            expiry: None,
            agent_id: None,
            agent: Some(agent),
            for_: None,
            role: None,
        }
    }

    /// Add constraints to the Connect message.
    pub fn with_constraints(mut self, constraints: ConnectionConstraints) -> Self {
        self.constraints = Some(constraints);
        self
    }

    /// Set the agreement URL.
    pub fn with_agreement(mut self, agreement: String) -> Self {
        self.agreement = Some(agreement);
        self
    }

    /// Set the expiry timestamp.
    pub fn with_expiry(mut self, expiry: String) -> Self {
        self.expiry = Some(expiry);
        self
    }
}

impl Connect {
    /// Custom validation for Connect messages
    pub fn validate_connect(&self) -> Result<()> {
        // New TAIP-15 v2 validation: if requester is present, use new validation
        if self.requester.is_some() {
            if self.principal.is_none() {
                return Err(Error::Validation("principal is required".to_string()));
            }
            if self.agents.is_empty() {
                return Err(Error::Validation(
                    "at least one agent is required".to_string(),
                ));
            }
            if self.constraints.is_none() {
                return Err(Error::Validation(
                    "Connection request must include constraints".to_string(),
                ));
            }
            return Ok(());
        }

        // Legacy validation
        if self.agent_id.is_none() && self.agent.is_none() {
            return Err(Error::Validation(
                "either agent_id or agent is required".to_string(),
            ));
        }

        let for_empty = self.for_.as_ref().is_none_or(|s| s.is_empty());
        if for_empty && self.principal.is_none() {
            return Err(Error::Validation(
                "either for or principal is required".to_string(),
            ));
        }

        if self.constraints.is_none() {
            return Err(Error::Validation(
                "Connection request must include constraints".to_string(),
            ));
        }

        Ok(())
    }

    /// Validation method that will be called by TapMessageBody trait
    pub fn validate(&self) -> Result<()> {
        self.validate_connect()
    }
}

/// Out of Band invitation for TAP connections.
#[derive(Debug, Clone, Serialize, Deserialize, TapMessage)]
#[tap(message_type = "https://tap.rsvp/schema/1.0#OutOfBand")]
pub struct OutOfBand {
    /// The goal code for this invitation.
    pub goal_code: String,

    /// The goal for this invitation.
    pub goal: String,

    /// The public DID or endpoint URL for the inviter.
    pub service: String,

    /// Accept media types.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accept: Option<Vec<String>>,

    /// Handshake protocols supported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handshake_protocols: Option<Vec<String>>,

    /// Additional metadata.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, serde_json::Value>,
}

impl OutOfBand {
    /// Create a new OutOfBand message.
    pub fn new(goal_code: String, goal: String, service: String) -> Self {
        Self {
            goal_code,
            goal,
            service,
            accept: None,
            handshake_protocols: None,
            metadata: HashMap::new(),
        }
    }
}

/// Authorization Required message body (TAIP-4, TAIP-15).
///
/// Indicates that authorization is required to proceed with a transaction or connection.
#[derive(Debug, Clone, Serialize, Deserialize, TapMessage)]
#[tap(message_type = "https://tap.rsvp/schema/1.0#AuthorizationRequired")]
pub struct AuthorizationRequired {
    /// Authorization URL where the user can authorize the transaction.
    #[serde(rename = "authorizationUrl")]
    pub authorization_url: String,

    /// ISO 8601 timestamp when the authorization URL expires (REQUIRED per TAIP-4).
    pub expires: String,

    /// Optional party type (e.g., "customer", "principal", "originator") that is required to open the URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,

    /// Additional metadata.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, serde_json::Value>,
}

impl AuthorizationRequired {
    /// Create a new AuthorizationRequired message.
    pub fn new(authorization_url: String, expires: String) -> Self {
        Self {
            authorization_url,
            expires,
            from: None,
            metadata: HashMap::new(),
        }
    }

    /// Create a new AuthorizationRequired message with a specified party type.
    pub fn new_with_from(authorization_url: String, expires: String, from: String) -> Self {
        Self {
            authorization_url,
            expires,
            from: Some(from),
            metadata: HashMap::new(),
        }
    }

    /// Set the party type that is required to open the URL.
    pub fn with_from(mut self, from: String) -> Self {
        self.from = Some(from);
        self
    }

    /// Add metadata to the message.
    pub fn add_metadata(mut self, key: &str, value: serde_json::Value) -> Self {
        self.metadata.insert(key.to_string(), value);
        self
    }
}

impl OutOfBand {
    /// Custom validation for OutOfBand messages
    pub fn validate_out_of_band(&self) -> Result<()> {
        if self.goal_code.is_empty() {
            return Err(Error::Validation("Goal code is required".to_string()));
        }

        if self.service.is_empty() {
            return Err(Error::Validation("Service is required".to_string()));
        }

        Ok(())
    }

    /// Validation method that will be called by TapMessageBody trait
    pub fn validate(&self) -> Result<()> {
        self.validate_out_of_band()
    }
}

impl AuthorizationRequired {
    /// Custom validation for AuthorizationRequired messages
    pub fn validate_authorization_required(&self) -> Result<()> {
        if self.authorization_url.is_empty() {
            return Err(Error::Validation(
                "Authorization URL is required".to_string(),
            ));
        }

        if self.expires.is_empty() {
            return Err(Error::Validation(
                "Expires timestamp is required".to_string(),
            ));
        }

        if !self.expires.contains('T') || !self.expires.contains(':') {
            return Err(Error::Validation(
                "Invalid expiry date format. Expected ISO8601/RFC3339 format".to_string(),
            ));
        }

        if let Some(ref from) = self.from {
            let valid_from_values = ["customer", "principal", "originator", "beneficiary"];
            if !valid_from_values.contains(&from.as_str()) {
                return Err(Error::Validation(
                    format!("Invalid 'from' value '{}'. Expected one of: customer, principal, originator, beneficiary", from),
                ));
            }
        }

        Ok(())
    }

    /// Validation method that will be called by TapMessageBody trait
    pub fn validate(&self) -> Result<()> {
        self.validate_authorization_required()
    }
}

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

    #[test]
    fn test_connect_v2_creation() {
        let requester = Party::new("did:example:b2b-service");
        let principal = Party::new("did:example:customer");
        let agent = Agent::new_without_role("did:example:b2b-service", "did:example:b2b-service");
        let constraints = ConnectionConstraints {
            purposes: Some(vec!["BEXP".to_string()]),
            category_purposes: None,
            limits: Some(TransactionLimits {
                per_transaction: Some("10000.00".to_string()),
                per_day: Some("50000.00".to_string()),
                per_week: None,
                per_month: None,
                per_year: None,
                currency: Some("USD".to_string()),
            }),
            allowed_beneficiaries: None,
            allowed_settlement_addresses: None,
            allowed_assets: None,
        };

        let connect = Connect::new_v2(requester, principal, vec![agent], constraints)
            .with_agreement("https://example.com/terms".to_string())
            .with_expiry("2024-03-22T15:00:00Z".to_string());

        assert!(connect.requester.is_some());
        assert!(connect.principal.is_some());
        assert_eq!(connect.agents.len(), 1);
        assert!(connect.constraints.is_some());
        assert_eq!(
            connect.agreement,
            Some("https://example.com/terms".to_string())
        );
        assert_eq!(connect.expiry, Some("2024-03-22T15:00:00Z".to_string()));
        assert!(connect.validate().is_ok());
    }

    #[test]
    fn test_connect_v2_serialization() {
        let requester = Party::new("did:example:b2b-service");
        let principal = Party::new("did:example:customer");
        let agent = Agent::new_without_role("did:example:b2b-service", "did:example:b2b-service");
        let constraints = ConnectionConstraints {
            purposes: Some(vec!["BEXP".to_string()]),
            category_purposes: None,
            limits: Some(TransactionLimits {
                per_transaction: Some("10000.00".to_string()),
                per_day: Some("50000.00".to_string()),
                per_week: None,
                per_month: None,
                per_year: None,
                currency: Some("USD".to_string()),
            }),
            allowed_beneficiaries: Some(vec![Party::new("did:example:vendor-1")]),
            allowed_settlement_addresses: Some(vec![
                "eip155:1:0x742d35Cc6e4dfE2eDFaD2C0b91A8b0780EDAEb58".to_string(),
            ]),
            allowed_assets: Some(vec!["eip155:1/slip44:60".to_string()]),
        };

        let connect = Connect::new_v2(requester, principal, vec![agent], constraints);
        let json = serde_json::to_value(&connect).unwrap();

        assert!(json.get("requester").is_some());
        assert!(json.get("principal").is_some());
        assert!(json.get("agents").is_some());
        assert!(json.get("constraints").is_some());

        let constraints = json.get("constraints").unwrap();
        assert!(constraints.get("allowedBeneficiaries").is_some());
        assert!(constraints.get("allowedSettlementAddresses").is_some());
        assert!(constraints.get("allowedAssets").is_some());

        let limits = constraints.get("limits").unwrap();
        assert_eq!(limits.get("per_day").unwrap(), "50000.00");
    }

    #[test]
    fn test_connect_v2_validation_missing_principal() {
        let connect = Connect {
            transaction_id: None,
            requester: Some(Party::new("did:example:service")),
            principal: None,
            agents: vec![Agent::new_without_role(
                "did:example:service",
                "did:example:service",
            )],
            constraints: Some(ConnectionConstraints {
                purposes: Some(vec!["BEXP".to_string()]),
                category_purposes: None,
                limits: None,
                allowed_beneficiaries: None,
                allowed_settlement_addresses: None,
                allowed_assets: None,
            }),
            agreement: None,
            expiry: None,
            agent_id: None,
            agent: None,
            for_: None,
            role: None,
        };

        let result = connect.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("principal is required"));
    }

    #[test]
    fn test_connect_v2_validation_no_agents() {
        let connect = Connect {
            transaction_id: None,
            requester: Some(Party::new("did:example:service")),
            principal: Some(Party::new("did:example:customer")),
            agents: vec![],
            constraints: Some(ConnectionConstraints {
                purposes: Some(vec!["BEXP".to_string()]),
                category_purposes: None,
                limits: None,
                allowed_beneficiaries: None,
                allowed_settlement_addresses: None,
                allowed_assets: None,
            }),
            agreement: None,
            expiry: None,
            agent_id: None,
            agent: None,
            for_: None,
            role: None,
        };

        let result = connect.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("at least one agent"));
    }

    #[test]
    fn test_authorization_required_creation() {
        let auth_req = AuthorizationRequired::new(
            "https://vasp.com/authorize?request=abc123".to_string(),
            "2024-12-31T23:59:59Z".to_string(),
        );

        assert_eq!(
            auth_req.authorization_url,
            "https://vasp.com/authorize?request=abc123"
        );
        assert_eq!(auth_req.expires, "2024-12-31T23:59:59Z");
        assert!(auth_req.from.is_none());
        assert!(auth_req.metadata.is_empty());
    }

    #[test]
    fn test_authorization_required_with_from() {
        let auth_req = AuthorizationRequired::new_with_from(
            "https://vasp.com/authorize".to_string(),
            "2024-12-31T23:59:59Z".to_string(),
            "customer".to_string(),
        );

        assert_eq!(auth_req.from, Some("customer".to_string()));
    }

    #[test]
    fn test_authorization_required_builder_pattern() {
        let auth_req = AuthorizationRequired::new(
            "https://vasp.com/authorize".to_string(),
            "2024-12-31T23:59:59Z".to_string(),
        )
        .with_from("principal".to_string())
        .add_metadata("custom_field", serde_json::json!("value"));

        assert_eq!(auth_req.from, Some("principal".to_string()));
        assert_eq!(
            auth_req.metadata.get("custom_field"),
            Some(&serde_json::json!("value"))
        );
    }

    #[test]
    fn test_authorization_required_serialization() {
        let auth_req = AuthorizationRequired::new_with_from(
            "https://vasp.com/authorize?request=abc123".to_string(),
            "2024-12-31T23:59:59Z".to_string(),
            "customer".to_string(),
        );

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

        assert_eq!(
            json["authorizationUrl"],
            "https://vasp.com/authorize?request=abc123"
        );
        assert_eq!(json["expires"], "2024-12-31T23:59:59Z");
        assert_eq!(json["from"], "customer");

        let deserialized: AuthorizationRequired = serde_json::from_value(json).unwrap();
        assert_eq!(deserialized.authorization_url, auth_req.authorization_url);
        assert_eq!(deserialized.expires, auth_req.expires);
        assert_eq!(deserialized.from, auth_req.from);
    }

    #[test]
    fn test_authorization_required_validation_success() {
        let auth_req = AuthorizationRequired::new(
            "https://vasp.com/authorize".to_string(),
            "2024-12-31T23:59:59Z".to_string(),
        );

        assert!(auth_req.validate().is_ok());
    }

    #[test]
    fn test_authorization_required_validation_with_valid_from() {
        let valid_from_values = ["customer", "principal", "originator", "beneficiary"];

        for from_value in &valid_from_values {
            let auth_req = AuthorizationRequired::new_with_from(
                "https://vasp.com/authorize".to_string(),
                "2024-12-31T23:59:59Z".to_string(),
                from_value.to_string(),
            );

            assert!(
                auth_req.validate().is_ok(),
                "Validation failed for from value: {}",
                from_value
            );
        }
    }

    #[test]
    fn test_authorization_required_validation_empty_url() {
        let auth_req =
            AuthorizationRequired::new("".to_string(), "2024-12-31T23:59:59Z".to_string());

        let result = auth_req.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Authorization URL is required"));
    }

    #[test]
    fn test_authorization_required_validation_empty_expires() {
        let auth_req = AuthorizationRequired {
            authorization_url: "https://vasp.com/authorize".to_string(),
            expires: "".to_string(),
            from: None,
            metadata: HashMap::new(),
        };

        let result = auth_req.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Expires timestamp is required"));
    }

    #[test]
    fn test_authorization_required_validation_invalid_expires_format() {
        let auth_req = AuthorizationRequired::new(
            "https://vasp.com/authorize".to_string(),
            "2024-12-31".to_string(),
        );

        let result = auth_req.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid expiry date format"));
    }

    #[test]
    fn test_authorization_required_validation_invalid_from() {
        let auth_req = AuthorizationRequired::new_with_from(
            "https://vasp.com/authorize".to_string(),
            "2024-12-31T23:59:59Z".to_string(),
            "invalid_party".to_string(),
        );

        let result = auth_req.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid 'from' value"));
    }

    #[test]
    fn test_authorization_required_json_compliance_with_taip4() {
        let auth_req = AuthorizationRequired::new_with_from(
            "https://beneficiary.vasp/authorize?request=abc123".to_string(),
            "2024-01-01T12:00:00Z".to_string(),
            "customer".to_string(),
        );

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

        assert!(json.get("authorizationUrl").is_some());
        assert!(json.get("expires").is_some());
        assert!(json.get("from").is_some());

        assert!(json.get("authorization_url").is_none());
        assert!(json.get("url").is_none());
    }
}