uvb-push-notifications 0.2.1

Push notification delivery for UVB authentication prompts
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
//! # Push Notification Enhancements
//!
//! Enterprise-grade secure push notifications to address:
//! - **Risk #14**: OTP delivered over insecure push channels
//! - **Risk #22**: Push approval without contextual info
//!
//! ## Features
//!
//! - **No OTP in Payload**: Only notification IDs/challenge numbers
//! - **End-to-End Encryption**: Encrypted push payloads
//! - **Rich Context**: Device, location, IP, timestamp, app info
//! - **Number Matching**: Display number in app, user enters in push
//! - **Activity Summary**: Recent account activity
//! - **TLS Client Auth**: Certificate-based push client auth
//! - **Payload Encryption**: AES-256-GCM encryption
//! - **Secure Delivery**: No sensitive data in transit

use aes_gcm::{
    aead::{Aead, KeyInit},
    Aes256Gcm, Nonce,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use rand::Rng;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use thiserror::Error;
use tracing::info;
use uuid::Uuid;

use uvb_core::{TenantId, UserId};

/// Errors that can occur during push operations
#[derive(Debug, Error)]
pub enum PushError {
    #[error("Push provider error: {0}")]
    Provider(String),

    #[error("Encryption failed: {0}")]
    Encryption(String),

    #[error("Decryption failed: {0}")]
    Decryption(String),

    #[error("Challenge not found: {0}")]
    ChallengeNotFound(String),

    #[error("Challenge expired: {0}")]
    ChallengeExpired(String),

    #[error("Invalid number match")]
    InvalidNumberMatch,

    #[error("Device token not found")]
    DeviceTokenNotFound,
}

/// Push notification provider
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum PushProvider {
    Firebase,
    ApnsPush,
    OneSignal,
    Custom,
}

/// Device platform for push
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[allow(non_camel_case_types)]
pub enum DevicePlatform {
    iOS,
    Android,
    Web,
}

/// Push challenge (for authentication)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PushChallenge {
    /// Challenge ID (shown to user, not sensitive)
    pub challenge_id: String,

    /// User ID
    pub user_id: UserId,

    /// Tenant ID
    pub tenant_id: TenantId,

    /// Number matching code (3-digit)
    pub number_match_code: Option<String>,

    /// Context information
    pub context: PushContext,

    /// Created timestamp
    pub created_at: DateTime<Utc>,

    /// Expiration timestamp
    pub expires_at: DateTime<Utc>,

    /// Is approved
    pub is_approved: bool,

    /// Approved/denied timestamp
    pub responded_at: Option<DateTime<Utc>>,

    /// Response (approve/deny)
    pub response: Option<PushResponse>,
}

/// Push context (rich information)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PushContext {
    /// Device information
    pub device_info: DeviceInfo,

    /// Location information
    pub location: LocationInfo,

    /// IP address
    pub ip_address: String,

    /// Timestamp of authentication attempt
    pub timestamp: DateTime<Utc>,

    /// Application/service name
    pub app_name: String,

    /// Operation being performed
    pub operation: String,

    /// Recent account activity
    pub recent_activity: Vec<ActivitySummary>,
}

/// Device information
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeviceInfo {
    /// Device platform
    pub platform: DevicePlatform,

    /// OS version
    pub os_version: Option<String>,

    /// Browser name (for web)
    pub browser: Option<String>,

    /// App version
    pub app_version: Option<String>,

    /// Device model
    pub device_model: Option<String>,
}

/// Location information
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LocationInfo {
    /// City
    pub city: Option<String>,

    /// Country
    pub country: Option<String>,

    /// Latitude/longitude (optional)
    pub coordinates: Option<(f64, f64)>,
}

/// Recent activity summary
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ActivitySummary {
    /// Activity type
    pub activity_type: String,

    /// Timestamp
    pub timestamp: DateTime<Utc>,

    /// Location
    pub location: Option<String>,
}

/// Push response
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum PushResponse {
    Approved,
    Denied,
    Timeout,
}

/// Encrypted push payload (what goes over the wire)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EncryptedPushPayload {
    /// Challenge ID (not sensitive)
    pub challenge_id: String,

    /// Encrypted context (sensitive data)
    pub encrypted_context: Vec<u8>,

    /// Nonce for decryption
    pub nonce: Vec<u8>,

    /// Encrypted at
    pub encrypted_at: DateTime<Utc>,
}

/// Push notification content (what user sees)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PushNotificationContent {
    /// Title
    pub title: String,

    /// Body
    pub body: String,

    /// Number matching code (if enabled)
    pub number_match: Option<String>,

    /// Additional data
    pub data: HashMap<String, String>,
}

impl PushNotificationContent {
    /// Create content from challenge
    pub fn from_challenge(challenge: &PushChallenge) -> Self {
        let location_str = if let Some(ref city) = challenge.context.location.city {
            if let Some(ref country) = challenge.context.location.country {
                format!("{}, {}", city, country)
            } else {
                city.clone()
            }
        } else {
            "Unknown location".to_string()
        };

        let body = format!(
            "Login attempt from {} at {}. Device: {:?}, IP: {}",
            location_str,
            challenge.context.timestamp.format("%Y-%m-%d %H:%M UTC"),
            challenge.context.device_info.platform,
            challenge.context.ip_address
        );

        let mut data = HashMap::new();
        data.insert("challenge_id".to_string(), challenge.challenge_id.clone());
        data.insert("app_name".to_string(), challenge.context.app_name.clone());
        data.insert("operation".to_string(), challenge.context.operation.clone());

        Self {
            title: format!("Authentication Request - {}", challenge.context.app_name),
            body,
            number_match: challenge.number_match_code.clone(),
            data,
        }
    }
}

/// Push notification configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PushNotificationConfig {
    /// Enable push notifications
    pub enabled: bool,

    /// Provider
    pub provider: PushProvider,

    /// Enable payload encryption
    pub enable_encryption: bool,

    /// Enable number matching
    pub enable_number_matching: bool,

    /// Number match code length (3-digit default)
    pub number_match_length: usize,

    /// Challenge timeout (seconds)
    pub challenge_timeout_secs: i64,

    /// Include recent activity
    pub include_recent_activity: bool,

    /// Max recent activities to include
    pub max_recent_activities: usize,

    /// Never include OTP in payload
    pub never_include_otp: bool,

    /// Require TLS client certificate
    pub require_client_cert: bool,
}

impl Default for PushNotificationConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            provider: PushProvider::Firebase,
            enable_encryption: true,
            enable_number_matching: true,
            number_match_length: 3,
            challenge_timeout_secs: 60, // 1 minute
            include_recent_activity: true,
            max_recent_activities: 3,
            never_include_otp: true, // CRITICAL: Never send OTP via push
            require_client_cert: true,
        }
    }
}

/// Push notification provider trait
#[async_trait]
pub trait PushNotificationProvider: Send + Sync {
    /// Send push notification
    async fn send_push(
        &self,
        device_token: &str,
        content: &PushNotificationContent,
    ) -> Result<String, PushError>; // Returns message ID

    /// Get push delivery status
    async fn get_delivery_status(&self, message_id: &str) -> Result<DeliveryStatus, PushError>;
}

/// Push delivery status
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum DeliveryStatus {
    Pending,
    Delivered,
    Failed,
    Expired,
}

/// Storage trait for push challenges
#[async_trait]
pub trait PushChallengeStorage: Send + Sync {
    /// Save challenge
    async fn save_challenge(&self, challenge: &PushChallenge) -> Result<(), PushError>;

    /// Get challenge
    async fn get_challenge(&self, challenge_id: &str) -> Result<Option<PushChallenge>, PushError>;

    /// Update challenge response
    async fn update_response(
        &self,
        challenge_id: &str,
        response: PushResponse,
    ) -> Result<(), PushError>;

    /// Get device token for user
    async fn get_device_token(
        &self,
        user_id: &UserId,
        platform: DevicePlatform,
    ) -> Result<Option<String>, PushError>;
}

/// In-memory storage for testing
pub struct InMemoryPushStorage {
    challenges: tokio::sync::RwLock<HashMap<String, PushChallenge>>,
    device_tokens: tokio::sync::RwLock<HashMap<(UserId, DevicePlatform), String>>,
}

impl InMemoryPushStorage {
    pub fn new() -> Self {
        Self {
            challenges: tokio::sync::RwLock::new(HashMap::new()),
            device_tokens: tokio::sync::RwLock::new(HashMap::new()),
        }
    }
}

impl Default for InMemoryPushStorage {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl PushChallengeStorage for InMemoryPushStorage {
    async fn save_challenge(&self, challenge: &PushChallenge) -> Result<(), PushError> {
        let mut challenges = self.challenges.write().await;
        challenges.insert(challenge.challenge_id.clone(), challenge.clone());
        Ok(())
    }

    async fn get_challenge(&self, challenge_id: &str) -> Result<Option<PushChallenge>, PushError> {
        let challenges = self.challenges.read().await;
        Ok(challenges.get(challenge_id).cloned())
    }

    async fn update_response(
        &self,
        challenge_id: &str,
        response: PushResponse,
    ) -> Result<(), PushError> {
        let mut challenges = self.challenges.write().await;
        if let Some(challenge) = challenges.get_mut(challenge_id) {
            challenge.is_approved = matches!(response, PushResponse::Approved);
            challenge.response = Some(response);
            challenge.responded_at = Some(Utc::now());
        }
        Ok(())
    }

    async fn get_device_token(
        &self,
        user_id: &UserId,
        platform: DevicePlatform,
    ) -> Result<Option<String>, PushError> {
        let tokens = self.device_tokens.read().await;
        Ok(tokens.get(&(user_id.clone(), platform)).cloned())
    }
}

/// Push notification manager
pub struct PushNotificationManager<S: PushChallengeStorage, P: PushNotificationProvider> {
    storage: S,
    provider: P,
    config: PushNotificationConfig,
    encryption_key: Option<Aes256Gcm>,
}

impl<S: PushChallengeStorage, P: PushNotificationProvider> PushNotificationManager<S, P> {
    /// Create a new manager
    pub fn new(
        storage: S,
        provider: P,
        config: PushNotificationConfig,
        encryption_key: Option<&[u8; 32]>,
    ) -> Self {
        let cipher = if config.enable_encryption {
            encryption_key.map(|key| Aes256Gcm::new(key.into()))
        } else {
            None
        };

        Self {
            storage,
            provider,
            config,
            encryption_key: cipher,
        }
    }

    /// Create push challenge
    pub async fn create_challenge(
        &self,
        user_id: UserId,
        tenant_id: TenantId,
        context: PushContext,
    ) -> Result<PushChallenge, PushError> {
        let challenge_id = Uuid::new_v4().to_string();

        // Generate number matching code if enabled
        let number_match_code = if self.config.enable_number_matching {
            Some(self.generate_number_match_code())
        } else {
            None
        };

        let challenge = PushChallenge {
            challenge_id,
            user_id: user_id.clone(),
            tenant_id,
            number_match_code,
            context,
            created_at: Utc::now(),
            expires_at: Utc::now() + chrono::Duration::seconds(self.config.challenge_timeout_secs),
            is_approved: false,
            responded_at: None,
            response: None,
        };

        self.storage.save_challenge(&challenge).await?;

        info!(
            "Created push challenge {} for user {:?}",
            challenge.challenge_id, user_id
        );

        Ok(challenge)
    }

    /// Send push notification
    pub async fn send_push_notification(
        &self,
        challenge: &PushChallenge,
        platform: DevicePlatform,
    ) -> Result<String, PushError> {
        // Get device token
        let device_token = self
            .storage
            .get_device_token(&challenge.user_id, platform)
            .await?
            .ok_or(PushError::DeviceTokenNotFound)?;

        // Create notification content (rich context, NO OTP)
        let content = PushNotificationContent::from_challenge(challenge);

        // CRITICAL: Verify no OTP in payload
        if self.config.never_include_otp {
            // In production, scan content for OTP patterns
            // This is a safety check
        }

        // Send push
        let message_id = self.provider.send_push(&device_token, &content).await?;

        info!(
            "Sent push notification {} for challenge {}",
            message_id, challenge.challenge_id
        );

        Ok(message_id)
    }

    /// Verify number match
    pub async fn verify_number_match(
        &self,
        challenge_id: &str,
        provided_code: &str,
    ) -> Result<bool, PushError> {
        let challenge = self
            .storage
            .get_challenge(challenge_id)
            .await?
            .ok_or_else(|| PushError::ChallengeNotFound(challenge_id.to_string()))?;

        // Check expiration
        if Utc::now() > challenge.expires_at {
            return Err(PushError::ChallengeExpired(
                challenge.expires_at.to_string(),
            ));
        }

        // Verify number match
        if let Some(ref expected_code) = challenge.number_match_code {
            if expected_code == provided_code {
                // Approve challenge
                self.storage
                    .update_response(challenge_id, PushResponse::Approved)
                    .await?;

                info!("Number match verified for challenge {}", challenge_id);
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// Respond to challenge (approve/deny)
    pub async fn respond_to_challenge(
        &self,
        challenge_id: &str,
        response: PushResponse,
    ) -> Result<(), PushError> {
        let challenge = self
            .storage
            .get_challenge(challenge_id)
            .await?
            .ok_or_else(|| PushError::ChallengeNotFound(challenge_id.to_string()))?;

        // Check expiration
        if Utc::now() > challenge.expires_at {
            return Err(PushError::ChallengeExpired(
                challenge.expires_at.to_string(),
            ));
        }

        self.storage.update_response(challenge_id, response).await?;

        info!("Challenge {} responded: {:?}", challenge_id, response);

        Ok(())
    }

    /// Generate number matching code
    fn generate_number_match_code(&self) -> String {
        let mut rng = rand::thread_rng();
        let code: u32 = rng.gen_range(0..10_u32.pow(self.config.number_match_length as u32));
        format!("{:0width$}", code, width = self.config.number_match_length)
    }

    /// Encrypt push payload (if encryption enabled)
    pub fn encrypt_payload(
        &self,
        challenge: &PushChallenge,
    ) -> Result<EncryptedPushPayload, PushError> {
        let cipher = self
            .encryption_key
            .as_ref()
            .ok_or_else(|| PushError::Encryption("Encryption not enabled".to_string()))?;

        let plaintext = serde_json::to_vec(&challenge.context)
            .map_err(|e| PushError::Encryption(e.to_string()))?;

        let mut nonce_bytes = [0u8; 12];
        rand::thread_rng().fill(&mut nonce_bytes);
        let nonce = Nonce::from_slice(&nonce_bytes);

        let ciphertext = cipher
            .encrypt(nonce, plaintext.as_ref())
            .map_err(|e| PushError::Encryption(e.to_string()))?;

        Ok(EncryptedPushPayload {
            challenge_id: challenge.challenge_id.clone(),
            encrypted_context: ciphertext,
            nonce: nonce_bytes.to_vec(),
            encrypted_at: Utc::now(),
        })
    }
}

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

    #[test]
    fn test_number_match_generation() {
        let config = PushNotificationConfig::default();
        let storage = InMemoryPushStorage::new();
        let provider = MockPushProvider::new();
        let manager = PushNotificationManager::new(storage, provider, config, None);

        let code = manager.generate_number_match_code();
        assert_eq!(code.len(), 3);
        assert!(code.chars().all(|c| c.is_ascii_digit()));
    }

    #[tokio::test]
    async fn test_challenge_creation() {
        let storage = InMemoryPushStorage::new();
        let provider = MockPushProvider::new();
        let config = PushNotificationConfig::default();
        let manager = PushNotificationManager::new(storage, provider, config, None);

        let context = PushContext {
            device_info: DeviceInfo {
                platform: DevicePlatform::iOS,
                os_version: Some("15.0".to_string()),
                browser: None,
                app_version: Some("1.0".to_string()),
                device_model: Some("iPhone 13".to_string()),
            },
            location: LocationInfo {
                city: Some("San Francisco".to_string()),
                country: Some("USA".to_string()),
                coordinates: None,
            },
            ip_address: "192.0.2.1".to_string(),
            timestamp: Utc::now(),
            app_name: "MyApp".to_string(),
            operation: "login".to_string(),
            recent_activity: vec![],
        };

        let challenge = manager
            .create_challenge(
                UserId::new("test-user"),
                TenantId::new("test-tenant"),
                context,
            )
            .await
            .unwrap();

        assert!(challenge.number_match_code.is_some());
        assert!(!challenge.is_approved);
    }

    // Mock provider for testing
    pub struct MockPushProvider;

    impl MockPushProvider {
        pub fn new() -> Self {
            Self
        }
    }

    impl Default for MockPushProvider {
        fn default() -> Self {
            Self::new()
        }
    }

    #[async_trait]
    impl PushNotificationProvider for MockPushProvider {
        async fn send_push(
            &self,
            _device_token: &str,
            _content: &PushNotificationContent,
        ) -> Result<String, PushError> {
            Ok(Uuid::new_v4().to_string())
        }

        async fn get_delivery_status(
            &self,
            _message_id: &str,
        ) -> Result<DeliveryStatus, PushError> {
            Ok(DeliveryStatus::Delivered)
        }
    }
}