paladin-ai-core 0.5.1

Pure domain types for the Paladin framework — zero infrastructure dependencies
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
// src/core/platform/container/user.rs
/*
User Container

User type built on the core base entity Node type to utilize the versioning system
through composition. It represents a user entity in the system with all needed values
including username, email, and password hash.

This follows Domain-Driven Design principles and leverages the existing Node infrastructure.
*/

use crate::base::entity::node::Node;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use uuid::Uuid;

/// Email value object that encapsulates email validation logic
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Email {
    value: String,
}

impl Email {
    /// Creates a new Email value object with validation
    pub fn new(email: String) -> Result<Self, UserError> {
        if Self::is_valid(&email) {
            Ok(Self {
                value: email.to_lowercase(),
            })
        } else {
            Err(UserError::InvalidEmail(email))
        }
    }

    /// Validates email format using a comprehensive regex
    fn is_valid(email: &str) -> bool {
        use regex::Regex;

        let email_regex = Regex::new(
            r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
        ).unwrap();

        email_regex.is_match(email) && email.len() <= 254
    }

    /// Returns the email value as a string
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Returns the domain part of the email
    pub fn domain(&self) -> Option<&str> {
        self.value.split('@').nth(1)
    }

    /// Returns the local part of the email
    pub fn local_part(&self) -> Option<&str> {
        self.value.split('@').next()
    }
}

impl std::fmt::Display for Email {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.value)
    }
}

/// Role assigned to a user, governing access to privileged operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum UserRole {
    /// Administrative user with full access to user-management operations.
    Admin,
    /// Standard user with access limited to their own resources.
    #[default]
    User,
}

impl UserRole {
    /// Returns the canonical lowercase string representation of the role.
    pub fn as_str(&self) -> &'static str {
        match self {
            UserRole::Admin => "admin",
            UserRole::User => "user",
        }
    }

    /// Parses a role from its string representation, defaulting to [`UserRole::User`]
    /// for unrecognized values to fail safe toward least privilege.
    pub fn from_str_lossy(value: &str) -> Self {
        match value.trim().to_lowercase().as_str() {
            "admin" => UserRole::Admin,
            _ => UserRole::User,
        }
    }
}

impl std::str::FromStr for UserRole {
    type Err = UserError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.trim().to_lowercase().as_str() {
            "admin" => Ok(UserRole::Admin),
            "user" => Ok(UserRole::User),
            other => Err(UserError::InvalidRole(other.to_string())),
        }
    }
}

impl std::fmt::Display for UserRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// User data structure that will be wrapped by Node
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UserData {
    pub username: String,
    pub email: Email,
    pub password_hash: String,
    pub is_active: bool,
    pub is_verified: bool,
    #[serde(default)]
    pub role: UserRole,
    pub profile: UserProfile,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UserProfile {
    pub first_name: Option<String>,
    pub last_name: Option<String>,
    pub bio: Option<String>,
    pub avatar_url: Option<String>,
    pub timezone: Option<String>,
    pub locale: Option<String>,
}

impl Default for UserProfile {
    fn default() -> Self {
        Self {
            first_name: None,
            last_name: None,
            bio: None,
            avatar_url: None,
            timezone: Some("UTC".to_string()),
            locale: Some("en-US".to_string()),
        }
    }
}

impl Hash for UserData {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.username.hash(state);
        self.email.hash(state);
        self.password_hash.hash(state);
        self.is_active.hash(state);
        self.is_verified.hash(state);
        self.role.hash(state);
    }
}

/// User type built on Node for versioning and consistency
pub type User = Node<UserData>;

impl User {
    /// Creates a new User with UserData
    pub fn new_user(
        username: String,
        email: Email,
        password_hash: String,
        profile: Option<UserProfile>,
    ) -> Self {
        let user_data = UserData {
            username,
            email,
            password_hash,
            is_active: true,
            is_verified: false,
            role: UserRole::default(),
            profile: profile.unwrap_or_default(),
        };

        let name = Some(format!("User: {}", user_data.username.clone()));
        Node::new(user_data, name)
    }

    /// Gets the username
    pub fn username(&self) -> &str {
        &self.node.username
    }

    /// Gets the email
    pub fn email(&self) -> &Email {
        &self.node.email
    }

    /// Gets the password hash
    pub fn password_hash(&self) -> &str {
        &self.node.password_hash
    }

    /// Checks if user is active
    pub fn is_active(&self) -> bool {
        self.node.is_active
    }

    /// Checks if user is verified
    pub fn is_verified(&self) -> bool {
        self.node.is_verified
    }

    /// Gets the user profile
    pub fn profile(&self) -> &UserProfile {
        &self.node.profile
    }

    /// Gets the user's role.
    pub fn role(&self) -> UserRole {
        self.node.role
    }

    /// Sets the user's role and updates the modified timestamp.
    pub fn set_role(&mut self, role: UserRole) {
        self.node.role = role;
        self.modified = Utc::now();
    }

    /// Updates username
    pub fn update_username(&mut self, new_username: String) -> Result<(), UserError> {
        if new_username.trim().is_empty() {
            return Err(UserError::InvalidUsername(
                "Username cannot be empty".to_string(),
            ));
        }
        if new_username.len() < 3 {
            return Err(UserError::InvalidUsername(
                "Username must be at least 3 characters".to_string(),
            ));
        }
        if new_username.len() > 50 {
            return Err(UserError::InvalidUsername(
                "Username cannot exceed 50 characters".to_string(),
            ));
        }

        self.node.username = new_username;
        self.modified = Utc::now(); // Update modified timestamp directly
        Ok(())
    }

    /// Updates email
    pub fn update_email(&mut self, new_email: Email) -> Result<(), UserError> {
        self.node.email = new_email;
        self.node.is_verified = false; // Reset verification on email change
        self.modified = Utc::now(); // Update modified timestamp directly
        Ok(())
    }

    /// Updates password hash
    pub fn update_password_hash(&mut self, new_password_hash: String) {
        self.node.password_hash = new_password_hash;
        self.modified = Utc::now(); // Update modified timestamp directly
    }

    /// Activates the user
    pub fn activate(&mut self) {
        self.node.is_active = true;
        self.modified = Utc::now(); // Update modified timestamp directly
    }

    /// Deactivates the user
    pub fn deactivate(&mut self) {
        self.node.is_active = false;
        self.modified = Utc::now(); // Update modified timestamp directly
    }

    /// Verifies the user
    pub fn verify(&mut self) {
        self.node.is_verified = true;
        self.modified = Utc::now(); // Update modified timestamp directly
    }

    /// Updates the user profile
    pub fn update_profile(&mut self, profile: UserProfile) {
        self.node.profile = profile;
        self.modified = Utc::now(); // Update modified timestamp directly
    }
}

/// User-specific error types
#[derive(Debug, thiserror::Error)]
pub enum UserError {
    #[error("Invalid email format: {0}")]
    InvalidEmail(String),
    #[error("Invalid username: {0}")]
    InvalidUsername(String),
    #[error("Invalid role: {0}")]
    InvalidRole(String),
    #[error("User not found with ID: {0}")]
    UserNotFound(Uuid),
    #[error("User not found with email: {0}")]
    UserNotFoundByEmail(String),
    #[error("Email already exists: {0}")]
    EmailAlreadyExists(String),
    #[error("Username already exists: {0}")]
    UsernameAlreadyExists(String),
    #[error("Invalid password: {0}")]
    InvalidPassword(String),
    #[error("Authentication failed")]
    AuthenticationFailed,
    #[error("User is not active")]
    UserNotActive,
    #[error("User is not verified")]
    UserNotVerified,
    #[error("Repository error: {0}")]
    RepositoryError(String),
    #[error("Hash error: {0}")]
    HashError(String),
}

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

    #[test]
    fn test_email_validation() {
        // Valid emails
        assert!(Email::new("test@example.com".to_string()).is_ok());
        assert!(Email::new("user.name+tag@domain.co.uk".to_string()).is_ok());
        assert!(Email::new("123@test.org".to_string()).is_ok());

        // Invalid emails
        assert!(Email::new("invalid-email".to_string()).is_err());
        assert!(Email::new("@domain.com".to_string()).is_err());
        assert!(Email::new("user@".to_string()).is_err());
        assert!(Email::new("".to_string()).is_err());
    }

    #[test]
    fn test_email_methods() {
        let email = Email::new("Test.User@Example.COM".to_string()).unwrap();

        // Email should be normalized to lowercase
        assert_eq!(email.value(), "test.user@example.com");
        assert_eq!(email.domain(), Some("example.com"));
        assert_eq!(email.local_part(), Some("test.user"));
        assert_eq!(email.to_string(), "test.user@example.com");
    }

    #[test]
    fn test_user_creation() {
        let email = Email::new("user@example.com".to_string()).unwrap();
        let user = User::new_user(
            "testuser".to_string(),
            email.clone(),
            "password_hash".to_string(),
            None,
        );

        assert_eq!(user.username(), "testuser");
        assert_eq!(user.email(), &email);
        assert_eq!(user.password_hash(), "password_hash");
        assert!(user.is_active());
        assert!(!user.is_verified());
    }

    #[test]
    fn test_user_updates() {
        let email = Email::new("user@example.com".to_string()).unwrap();
        let mut user = User::new_user(
            "testuser".to_string(),
            email,
            "password_hash".to_string(),
            None,
        );

        let initial_modified = user.modified;

        // Small delay to ensure timestamp difference
        std::thread::sleep(std::time::Duration::from_millis(1));

        // Test username update
        assert!(user.update_username("newusername".to_string()).is_ok());
        assert_eq!(user.username(), "newusername");
        assert!(user.modified > initial_modified);

        // Test invalid username
        assert!(user.update_username("a".to_string()).is_err());
        assert!(user.update_username("".to_string()).is_err());

        // Test email update
        let new_email = Email::new("new@example.com".to_string()).unwrap();
        let before_email_update = user.modified;
        std::thread::sleep(std::time::Duration::from_millis(1));

        assert!(user.update_email(new_email.clone()).is_ok());
        assert_eq!(user.email(), &new_email);
        assert!(!user.is_verified()); // Should reset verification
        assert!(user.modified > before_email_update);

        // Test activation/deactivation
        let before_deactivate = user.modified;
        std::thread::sleep(std::time::Duration::from_millis(1));

        user.deactivate();
        assert!(!user.is_active());
        assert!(user.modified > before_deactivate);

        let before_activate = user.modified;
        std::thread::sleep(std::time::Duration::from_millis(1));

        user.activate();
        assert!(user.is_active());
        assert!(user.modified > before_activate);

        // Test verification
        let before_verify = user.modified;
        std::thread::sleep(std::time::Duration::from_millis(1));

        user.verify();
        assert!(user.is_verified());
        assert!(user.modified > before_verify);
    }

    #[test]
    fn test_user_profile_update() {
        let email = Email::new("user@example.com".to_string()).unwrap();
        let mut user = User::new_user(
            "testuser".to_string(),
            email,
            "password_hash".to_string(),
            None,
        );

        let new_profile = UserProfile {
            first_name: Some("John".to_string()),
            last_name: Some("Doe".to_string()),
            bio: Some("Software developer".to_string()),
            avatar_url: Some("https://example.com/avatar.jpg".to_string()),
            timezone: Some("America/New_York".to_string()),
            locale: Some("en-US".to_string()),
        };

        let before_update = user.modified;
        std::thread::sleep(std::time::Duration::from_millis(1));

        user.update_profile(new_profile.clone());
        assert_eq!(user.profile(), &new_profile);
        assert!(user.modified > before_update);
    }

    #[test]
    fn test_username_validation() {
        let email = Email::new("user@example.com".to_string()).unwrap();
        let mut user = User::new_user(
            "testuser".to_string(),
            email,
            "password_hash".to_string(),
            None,
        );

        // Valid usernames
        assert!(user.update_username("validuser".to_string()).is_ok());
        assert!(user.update_username("user_123".to_string()).is_ok());
        assert!(user.update_username("test-user".to_string()).is_ok());

        // Invalid usernames
        assert!(user.update_username("".to_string()).is_err());
        assert!(user.update_username("ab".to_string()).is_err());

        // Username too long
        let long_username = "a".repeat(51);
        assert!(user.update_username(long_username).is_err());
    }

    #[test]
    fn test_user_versioning() {
        let email = Email::new("user@example.com".to_string()).unwrap();
        let user = User::new_user(
            "testuser".to_string(),
            email,
            "password_hash".to_string(),
            None,
        );

        // User should have versioning enabled by default
        assert!(user.is_versioning_enabled());

        // UUID should be generated
        assert!(!user.uuid.is_nil());

        // Timestamps should be set
        assert_eq!(user.created, user.modified);
    }

    #[test]
    fn test_user_serialization() {
        let email = Email::new("user@example.com".to_string()).unwrap();
        let user = User::new_user(
            "testuser".to_string(),
            email,
            "password_hash".to_string(),
            Some(UserProfile {
                first_name: Some("Test".to_string()),
                last_name: Some("User".to_string()),
                bio: None,
                avatar_url: None,
                timezone: Some("UTC".to_string()),
                locale: Some("en-US".to_string()),
            }),
        );

        // Test serialization
        let serialized = serde_json::to_string(&user).unwrap();
        assert!(!serialized.is_empty());

        // Test deserialization
        let deserialized: User = serde_json::from_str(&serialized).unwrap();
        assert_eq!(user.uuid, deserialized.uuid);
        assert_eq!(user.node.username, deserialized.node.username);
        assert_eq!(user.node.email.value(), deserialized.node.email.value());
    }

    #[test]
    fn test_user_role_string_round_trip() {
        use std::str::FromStr;

        assert_eq!(UserRole::Admin.as_str(), "admin");
        assert_eq!(UserRole::User.as_str(), "user");
        assert_eq!(UserRole::from_str("admin").unwrap(), UserRole::Admin);
        assert_eq!(UserRole::from_str(" USER ").unwrap(), UserRole::User);
        assert!(UserRole::from_str("superuser").is_err());

        // Lossy parsing fails safe to least privilege.
        assert_eq!(UserRole::from_str_lossy("admin"), UserRole::Admin);
        assert_eq!(UserRole::from_str_lossy("nonsense"), UserRole::User);
    }

    #[test]
    fn test_user_role_default_and_accessors() {
        let email = Email::new("user@example.com".to_string()).unwrap();
        let mut user = User::new_user(
            "testuser".to_string(),
            email,
            "password_hash".to_string(),
            None,
        );

        // New users default to the least-privileged role.
        assert_eq!(user.role(), UserRole::User);

        let before = user.modified;
        std::thread::sleep(std::time::Duration::from_millis(1));
        user.set_role(UserRole::Admin);
        assert_eq!(user.role(), UserRole::Admin);
        assert!(user.modified > before);
    }
}