loop-agent-sdk 0.1.0

Trustless agent SDK for Loop Protocol — intent-based execution on Solana.
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
//! Loop Agent SDK - Webhook Handler
//! 
//! Unified handler for Fidel, Square, and Stripe webhooks.
//! 
//! ## Security
//! 
//! - Signature verification BEFORE any processing
//! - Privacy layer hashing BEFORE any logging
//! - Reject spoofed webhooks at the door
//! 
//! ## Flow
//! 
//! ```text
//! Webhook arrives
//!//! Verify signature (reject if invalid)
//!//! Extract card_id
//!//! IMMEDIATELY hash to loop_fp_* (purge raw card_id)
//!//! Lookup user by fingerprint
//!//! Execute capture
//! ```

use crate::privacy::{LoopFingerprint, PrivacyLayer, PrivacyError};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{error, info, warn, instrument};

type HmacSha256 = Hmac<Sha256>;

// ============================================================================
// WEBHOOK CONFIGURATION
// ============================================================================

/// Webhook secrets for signature verification
#[derive(Debug, Clone)]
pub struct WebhookSecrets {
    /// Fidel webhook secrets by event type
    pub fidel: FidelSecrets,
    /// Square webhook signature key
    pub square: Option<String>,
    /// Stripe webhook signing secret
    pub stripe: Option<String>,
}

#[derive(Debug, Clone)]
pub struct FidelSecrets {
    /// transaction.auth event
    pub auth: String,
    /// transaction.clearing event (main one for captures)
    pub clearing: String,
    /// card.linked event
    pub card_linked: String,
}

impl WebhookSecrets {
    /// Load from environment variables
    pub fn from_env() -> Self {
        Self {
            fidel: FidelSecrets {
                auth: std::env::var("FIDEL_WEBHOOK_SECRET_AUTH")
                    .unwrap_or_default(),
                clearing: std::env::var("FIDEL_WEBHOOK_SECRET_CLEARING")
                    .unwrap_or_default(),
                card_linked: std::env::var("FIDEL_WEBHOOK_SECRET_CARD_LINKED")
                    .unwrap_or_default(),
            },
            square: std::env::var("SQUARE_WEBHOOK_SIGNATURE_KEY").ok(),
            stripe: std::env::var("STRIPE_WEBHOOK_SECRET").ok(),
        }
    }
}

// ============================================================================
// WEBHOOK SOURCE DETECTION
// ============================================================================

/// Detected webhook source
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WebhookSource {
    Fidel,
    Square,
    Stripe,
    Unknown,
}

impl WebhookSource {
    /// Detect source from headers
    pub fn detect(headers: &HashMap<String, String>) -> Self {
        // Fidel uses X-Fidel-Signature
        if headers.contains_key("x-fidel-signature") || headers.contains_key("X-Fidel-Signature") {
            return Self::Fidel;
        }
        
        // Square uses X-Square-Signature
        if headers.contains_key("x-square-signature") || headers.contains_key("X-Square-Signature") {
            return Self::Square;
        }
        
        // Stripe uses Stripe-Signature
        if headers.contains_key("stripe-signature") || headers.contains_key("Stripe-Signature") {
            return Self::Stripe;
        }
        
        Self::Unknown
    }
}

// ============================================================================
// NORMALIZED TRANSACTION (Source-Agnostic)
// ============================================================================

/// Normalized transaction data from any webhook source
/// 
/// This is the internal representation after parsing webhook payloads.
/// All source-specific fields are mapped to this common structure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NormalizedTransaction {
    /// Loop fingerprint (hashed card_id)
    pub fingerprint: String,
    /// Last 4 digits of card (for display only)
    pub card_last4: String,
    /// Card brand (VISA, MASTERCARD, etc.)
    pub card_brand: String,
    /// Transaction amount in cents
    pub amount_cents: u64,
    /// Currency code (USD, EUR, etc.)
    pub currency: String,
    /// Merchant identifier
    pub merchant_id: String,
    /// Merchant name (for display)
    pub merchant_name: Option<String>,
    /// Location identifier (if available)
    pub location_id: Option<String>,
    /// Transaction timestamp (Unix seconds)
    pub timestamp: i64,
    /// Source-specific transaction ID (for dedup)
    pub source_txn_id: String,
    /// Original webhook source
    pub source: WebhookSource,
    /// Transaction type
    pub txn_type: TransactionType,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransactionType {
    /// Authorization (pending)
    Auth,
    /// Clearing (settled) - this is what we capture
    Clearing,
    /// Refund
    Refund,
}

// ============================================================================
// FIDEL WEBHOOK HANDLING
// ============================================================================

/// Fidel webhook payload (transaction.clearing event)
#[derive(Debug, Deserialize)]
pub struct FidelWebhookPayload {
    /// Transaction data
    pub transaction: FidelTransaction,
    /// Event type
    #[serde(rename = "type")]
    pub event_type: String,
}

#[derive(Debug, Deserialize)]
pub struct FidelTransaction {
    /// Fidel's transaction ID
    pub id: String,
    /// Card ID (THIS IS WHAT WE HASH)
    #[serde(rename = "cardId")]
    pub card_id: String,
    /// Last 4 digits
    #[serde(rename = "lastNumbers")]
    pub last_numbers: String,
    /// Card scheme (VISA, MASTERCARD)
    pub scheme: String,
    /// Amount in original currency
    pub amount: f64,
    /// Currency code
    pub currency: String,
    /// Merchant info
    #[serde(rename = "brandId")]
    pub brand_id: Option<String>,
    #[serde(rename = "merchantName")]
    pub merchant_name: Option<String>,
    #[serde(rename = "locationId")]
    pub location_id: Option<String>,
    /// Transaction date (ISO 8601)
    #[serde(rename = "datetime")]
    pub datetime: String,
    /// Auth vs Clearing
    #[serde(rename = "auth")]
    pub is_auth: Option<bool>,
}

/// Verify Fidel webhook signature
/// 
/// Fidel signs webhooks with HMAC-SHA256.
/// Header: X-Fidel-Signature
#[instrument(skip(body, secret))]
pub fn verify_fidel_signature(
    signature_header: &str,
    body: &[u8],
    secret: &str,
) -> Result<bool, WebhookError> {
    // Fidel signature format: sha256=<hex>
    let signature = signature_header
        .strip_prefix("sha256=")
        .ok_or_else(|| WebhookError::InvalidSignature("Missing sha256= prefix".into()))?;
    
    let expected_bytes = hex::decode(signature)
        .map_err(|e| WebhookError::InvalidSignature(format!("Invalid hex: {}", e)))?;
    
    let mut mac = HmacSha256::new_from_slice(secret.as_bytes())
        .map_err(|e| WebhookError::InvalidSignature(format!("HMAC error: {}", e)))?;
    
    mac.update(body);
    
    // Use constant-time comparison
    match mac.verify_slice(&expected_bytes) {
        Ok(_) => {
            info!("Fidel signature verified");
            Ok(true)
        }
        Err(_) => {
            warn!("Fidel signature verification failed");
            Ok(false)
        }
    }
}

/// Parse Fidel webhook and normalize
/// 
/// # Privacy Protocol
/// 
/// This function implements Double-Blind Vaulting:
/// 1. Parse the raw payload
/// 2. IMMEDIATELY hash card_id to fingerprint
/// 3. Drop the raw card_id (it's moved into the hasher)
/// 4. Return only normalized data with fingerprint
#[instrument(skip(body, privacy))]
pub fn parse_fidel_webhook(
    body: &[u8],
    privacy: &PrivacyLayer,
) -> Result<NormalizedTransaction, WebhookError> {
    // Parse JSON
    let payload: FidelWebhookPayload = serde_json::from_slice(body)
        .map_err(|e| WebhookError::ParseError(format!("Invalid JSON: {}", e)))?;
    
    let txn = payload.transaction;
    
    // CRITICAL: Hash the card_id IMMEDIATELY
    // The hash_card_id function takes ownership and zeroizes the original
    let fingerprint = privacy.hash_card_id(txn.card_id);
    
    // After this point, raw card_id no longer exists in memory
    // All subsequent operations use only the fingerprint
    
    // Parse timestamp
    let timestamp = chrono::DateTime::parse_from_rfc3339(&txn.datetime)
        .map(|dt| dt.timestamp())
        .unwrap_or_else(|_| chrono::Utc::now().timestamp());
    
    // Determine transaction type
    let txn_type = match payload.event_type.as_str() {
        "transaction.auth" => TransactionType::Auth,
        "transaction.clearing" => TransactionType::Clearing,
        "transaction.refund" => TransactionType::Refund,
        _ => TransactionType::Clearing, // Default to clearing
    };
    
    // Convert amount to cents
    let amount_cents = (txn.amount * 100.0).round() as u64;
    
    Ok(NormalizedTransaction {
        fingerprint: fingerprint.into_string(),
        card_last4: txn.last_numbers,
        card_brand: txn.scheme,
        amount_cents,
        currency: txn.currency,
        merchant_id: txn.brand_id.unwrap_or_else(|| "unknown".to_string()),
        merchant_name: txn.merchant_name,
        location_id: txn.location_id,
        timestamp,
        source_txn_id: txn.id,
        source: WebhookSource::Fidel,
        txn_type,
    })
}

// ============================================================================
// SQUARE WEBHOOK HANDLING
// ============================================================================

/// Square webhook payload (payment.completed event)
#[derive(Debug, Deserialize)]
pub struct SquareWebhookPayload {
    /// Event type
    #[serde(rename = "type")]
    pub event_type: String,
    /// Event data
    pub data: SquareEventData,
}

#[derive(Debug, Deserialize)]
pub struct SquareEventData {
    /// Object containing payment details
    pub object: SquarePaymentObject,
}

#[derive(Debug, Deserialize)]
pub struct SquarePaymentObject {
    pub payment: SquarePayment,
}

#[derive(Debug, Deserialize)]
pub struct SquarePayment {
    pub id: String,
    #[serde(rename = "amount_money")]
    pub amount_money: SquareMoney,
    #[serde(rename = "card_details")]
    pub card_details: Option<SquareCardDetails>,
    #[serde(rename = "location_id")]
    pub location_id: String,
    #[serde(rename = "created_at")]
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct SquareMoney {
    pub amount: i64,
    pub currency: String,
}

#[derive(Debug, Deserialize)]
pub struct SquareCardDetails {
    pub card: SquareCard,
}

#[derive(Debug, Deserialize)]
pub struct SquareCard {
    /// Square's card fingerprint (we hash this too)
    pub fingerprint: Option<String>,
    #[serde(rename = "last_4")]
    pub last_4: Option<String>,
    #[serde(rename = "card_brand")]
    pub card_brand: Option<String>,
}

/// Verify Square webhook signature
#[instrument(skip(body, signature_key))]
pub fn verify_square_signature(
    signature_header: &str,
    body: &[u8],
    notification_url: &str,
    signature_key: &str,
) -> Result<bool, WebhookError> {
    // Square signature = Base64(HMAC-SHA256(notification_url + body))
    let mut mac = HmacSha256::new_from_slice(signature_key.as_bytes())
        .map_err(|e| WebhookError::InvalidSignature(format!("HMAC error: {}", e)))?;
    
    mac.update(notification_url.as_bytes());
    mac.update(body);
    
    let computed = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        mac.finalize().into_bytes(),
    );
    
    if computed == signature_header {
        info!("Square signature verified");
        Ok(true)
    } else {
        warn!("Square signature verification failed");
        Ok(false)
    }
}

/// Parse Square webhook and normalize
#[instrument(skip(body, privacy))]
pub fn parse_square_webhook(
    body: &[u8],
    privacy: &PrivacyLayer,
    merchant_id: &str, // Square merchant ID
) -> Result<NormalizedTransaction, WebhookError> {
    let payload: SquareWebhookPayload = serde_json::from_slice(body)
        .map_err(|e| WebhookError::ParseError(format!("Invalid JSON: {}", e)))?;
    
    let payment = payload.data.object.payment;
    
    // Get card details
    let card_details = payment.card_details
        .ok_or_else(|| WebhookError::ParseError("No card details".into()))?;
    
    let card = card_details.card;
    
    // Get Square's fingerprint and hash it
    let raw_fingerprint = card.fingerprint
        .ok_or_else(|| WebhookError::ParseError("No card fingerprint".into()))?;
    
    // CRITICAL: Hash immediately
    let fingerprint = privacy.hash_card_id(raw_fingerprint);
    
    // Parse timestamp
    let timestamp = chrono::DateTime::parse_from_rfc3339(&payment.created_at)
        .map(|dt| dt.timestamp())
        .unwrap_or_else(|_| chrono::Utc::now().timestamp());
    
    Ok(NormalizedTransaction {
        fingerprint: fingerprint.into_string(),
        card_last4: card.last_4.unwrap_or_default(),
        card_brand: card.card_brand.unwrap_or_default(),
        amount_cents: payment.amount_money.amount as u64,
        currency: payment.amount_money.currency,
        merchant_id: merchant_id.to_string(),
        merchant_name: None,
        location_id: Some(payment.location_id),
        timestamp,
        source_txn_id: payment.id,
        source: WebhookSource::Square,
        txn_type: TransactionType::Clearing,
    })
}

// ============================================================================
// STRIPE WEBHOOK HANDLING
// ============================================================================

/// Verify Stripe webhook signature
#[instrument(skip(body, secret))]
pub fn verify_stripe_signature(
    signature_header: &str,
    body: &[u8],
    secret: &str,
) -> Result<bool, WebhookError> {
    // Stripe signature format: t=timestamp,v1=signature,v1=signature...
    let parts: HashMap<&str, &str> = signature_header
        .split(',')
        .filter_map(|part| {
            let mut kv = part.splitn(2, '=');
            Some((kv.next()?, kv.next()?))
        })
        .collect();
    
    let timestamp = parts.get("t")
        .ok_or_else(|| WebhookError::InvalidSignature("Missing timestamp".into()))?;
    
    let signature = parts.get("v1")
        .ok_or_else(|| WebhookError::InvalidSignature("Missing v1 signature".into()))?;
    
    // Construct signed payload
    let signed_payload = format!("{}.{}", timestamp, String::from_utf8_lossy(body));
    
    let mut mac = HmacSha256::new_from_slice(secret.as_bytes())
        .map_err(|e| WebhookError::InvalidSignature(format!("HMAC error: {}", e)))?;
    
    mac.update(signed_payload.as_bytes());
    
    let computed = hex::encode(mac.finalize().into_bytes());
    
    if computed == *signature {
        info!("Stripe signature verified");
        Ok(true)
    } else {
        warn!("Stripe signature verification failed");
        Ok(false)
    }
}

// ============================================================================
// UNIFIED WEBHOOK HANDLER
// ============================================================================

/// Unified webhook handler
/// 
/// This is the main entry point for all webhook processing.
/// It detects the source, verifies the signature, and normalizes the transaction.
pub struct WebhookHandler {
    privacy: PrivacyLayer,
    secrets: WebhookSecrets,
}

impl WebhookHandler {
    /// Create new webhook handler
    pub async fn new(secrets: WebhookSecrets) -> Result<Self, WebhookError> {
        let privacy = PrivacyLayer::new(&Default::default()).await
            .map_err(|e| WebhookError::InitError(e.to_string()))?;
        
        Ok(Self { privacy, secrets })
    }
    
    /// Process incoming webhook
    /// 
    /// Returns normalized transaction if valid, error if signature fails or parsing fails.
    #[instrument(skip(self, body))]
    pub async fn process(
        &self,
        headers: &HashMap<String, String>,
        body: &[u8],
        context: &WebhookContext,
    ) -> Result<NormalizedTransaction, WebhookError> {
        // 1. Detect source
        let source = WebhookSource::detect(headers);
        info!(?source, "Detected webhook source");
        
        // 2. Verify signature (BEFORE any parsing)
        match source {
            WebhookSource::Fidel => {
                let sig = headers.get("x-fidel-signature")
                    .or_else(|| headers.get("X-Fidel-Signature"))
                    .ok_or_else(|| WebhookError::InvalidSignature("Missing signature header".into()))?;
                
                // Determine which secret based on event type (peek at body)
                let secret = self.get_fidel_secret(body)?;
                
                if !verify_fidel_signature(sig, body, &secret)? {
                    return Err(WebhookError::SignatureVerificationFailed);
                }
            }
            WebhookSource::Square => {
                let sig = headers.get("x-square-signature")
                    .or_else(|| headers.get("X-Square-Signature"))
                    .ok_or_else(|| WebhookError::InvalidSignature("Missing signature header".into()))?;
                
                let secret = self.secrets.square.as_ref()
                    .ok_or_else(|| WebhookError::MissingSecret("Square".into()))?;
                
                let url = context.webhook_url.as_ref()
                    .ok_or_else(|| WebhookError::MissingContext("webhook_url".into()))?;
                
                if !verify_square_signature(sig, body, url, secret)? {
                    return Err(WebhookError::SignatureVerificationFailed);
                }
            }
            WebhookSource::Stripe => {
                let sig = headers.get("stripe-signature")
                    .or_else(|| headers.get("Stripe-Signature"))
                    .ok_or_else(|| WebhookError::InvalidSignature("Missing signature header".into()))?;
                
                let secret = self.secrets.stripe.as_ref()
                    .ok_or_else(|| WebhookError::MissingSecret("Stripe".into()))?;
                
                if !verify_stripe_signature(sig, body, secret)? {
                    return Err(WebhookError::SignatureVerificationFailed);
                }
            }
            WebhookSource::Unknown => {
                return Err(WebhookError::UnknownSource);
            }
        }
        
        // 3. Parse and normalize (with privacy layer)
        let transaction = match source {
            WebhookSource::Fidel => parse_fidel_webhook(body, &self.privacy)?,
            WebhookSource::Square => {
                let merchant_id = context.merchant_id.as_ref()
                    .ok_or_else(|| WebhookError::MissingContext("merchant_id".into()))?;
                parse_square_webhook(body, &self.privacy, merchant_id)?
            }
            WebhookSource::Stripe => {
                // TODO: Implement Stripe parsing
                return Err(WebhookError::NotImplemented("Stripe parsing".into()));
            }
            WebhookSource::Unknown => unreachable!(),
        };
        
        info!(
            source = ?source,
            fingerprint = %transaction.fingerprint,
            amount_cents = transaction.amount_cents,
            "Transaction normalized"
        );
        
        Ok(transaction)
    }
    
    /// Get the appropriate Fidel secret based on event type
    fn get_fidel_secret(&self, body: &[u8]) -> Result<String, WebhookError> {
        // Quick peek to determine event type
        #[derive(Deserialize)]
        struct EventPeek {
            #[serde(rename = "type")]
            event_type: String,
        }
        
        let peek: EventPeek = serde_json::from_slice(body)
            .map_err(|e| WebhookError::ParseError(format!("Cannot determine event type: {}", e)))?;
        
        let secret = match peek.event_type.as_str() {
            "transaction.auth" => &self.secrets.fidel.auth,
            "transaction.clearing" => &self.secrets.fidel.clearing,
            "card.linked" => &self.secrets.fidel.card_linked,
            _ => &self.secrets.fidel.clearing, // Default
        };
        
        if secret.is_empty() {
            return Err(WebhookError::MissingSecret(format!("Fidel {}", peek.event_type)));
        }
        
        Ok(secret.clone())
    }
}

/// Additional context for webhook processing
#[derive(Debug, Default)]
pub struct WebhookContext {
    /// Webhook URL (needed for Square signature)
    pub webhook_url: Option<String>,
    /// Merchant ID (for Square)
    pub merchant_id: Option<String>,
}

// ============================================================================
// ERRORS
// ============================================================================

#[derive(Debug, Clone)]
pub enum WebhookError {
    /// Signature header invalid or malformed
    InvalidSignature(String),
    /// Signature verification failed
    SignatureVerificationFailed,
    /// Could not parse webhook payload
    ParseError(String),
    /// Unknown webhook source
    UnknownSource,
    /// Missing required secret
    MissingSecret(String),
    /// Missing required context
    MissingContext(String),
    /// Feature not implemented
    NotImplemented(String),
    /// Initialization error
    InitError(String),
}

impl std::fmt::Display for WebhookError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidSignature(msg) => write!(f, "Invalid signature: {}", msg),
            Self::SignatureVerificationFailed => write!(f, "Signature verification failed"),
            Self::ParseError(msg) => write!(f, "Parse error: {}", msg),
            Self::UnknownSource => write!(f, "Unknown webhook source"),
            Self::MissingSecret(name) => write!(f, "Missing secret: {}", name),
            Self::MissingContext(name) => write!(f, "Missing context: {}", name),
            Self::NotImplemented(feature) => write!(f, "Not implemented: {}", feature),
            Self::InitError(msg) => write!(f, "Initialization error: {}", msg),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn detect_fidel_source() {
        let mut headers = HashMap::new();
        headers.insert("x-fidel-signature".to_string(), "sha256=abc".to_string());
        
        assert_eq!(WebhookSource::detect(&headers), WebhookSource::Fidel);
    }
    
    #[test]
    fn detect_square_source() {
        let mut headers = HashMap::new();
        headers.insert("x-square-signature".to_string(), "abc".to_string());
        
        assert_eq!(WebhookSource::detect(&headers), WebhookSource::Square);
    }
    
    #[test]
    fn detect_unknown_source() {
        let headers = HashMap::new();
        assert_eq!(WebhookSource::detect(&headers), WebhookSource::Unknown);
    }
}