reputation-core 0.1.0

Core calculation engine for the KnowThat Reputation System with advanced scoring algorithms
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
use crate::error::ValidationError;
use reputation_types::AgentData;
use chrono::Utc;

/// Validates all fields of AgentData to ensure they meet required constraints.
/// 
/// This function performs comprehensive validation including:
/// - DID format validation
/// - Date validation (no future dates)
/// - Rating bounds and consistency
/// - Review count consistency
/// - MCP level validation
/// 
/// # Example
/// ```
/// use reputation_core::validation::validate_agent_data;
/// use reputation_types::AgentData;
/// use chrono::Utc;
/// 
/// let agent = AgentData {
///     did: "did:example:123".to_string(),
///     created_at: Utc::now(),
///     mcp_level: Some(2),
///     identity_verified: true,
///     security_audit_passed: false,
///     open_source: true,
///     total_interactions: 100,
///     total_reviews: 50,
///     average_rating: Some(4.2),
///     positive_reviews: 40,
///     negative_reviews: 10,
/// };
/// 
/// match validate_agent_data(&agent) {
///     Ok(()) => println!("Agent data is valid"),
///     Err(e) => println!("Validation failed: {}", e),
/// }
/// ```
pub fn validate_agent_data(data: &AgentData) -> Result<(), ValidationError> {
    validate_did(&data.did)?;
    validate_dates(data)?;
    validate_ratings(data)?;
    validate_review_counts(data)?;
    validate_mcp_level(data.mcp_level)?;
    validate_interactions(data)?;
    Ok(())
}

/// Validates DID format according to W3C DID specification.
/// 
/// DIDs must start with "did:" followed by a method name and method-specific identifier.
/// Also performs security validation to prevent malicious inputs.
/// 
/// # Examples
/// - Valid: "did:example:123", "did:web:example.com", "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH"
/// - Invalid: "example:123", "DID:example:123", "", "did:", "did::"
fn validate_did(did: &str) -> Result<(), ValidationError> {
    if did.is_empty() {
        return Err(ValidationError::InvalidDid("DID cannot be empty".to_string()));
    }
    
    // Security: Check for path traversal attempts
    if did.contains("..") || did.contains("//") {
        return Err(ValidationError::InvalidDid(
            "DID contains invalid path sequences".to_string()
        ));
    }
    
    // Security: Check for script injection attempts
    if did.contains('<') || did.contains('>') || did.contains("javascript:") {
        return Err(ValidationError::InvalidDid(
            "DID contains invalid characters".to_string()
        ));
    }
    
    // Security: Check for SQL injection patterns
    if did.contains('\'') || did.contains('"') || did.contains(';') || did.contains("--") {
        return Err(ValidationError::InvalidDid(
            "DID contains invalid characters".to_string()
        ));
    }
    
    // Security: Check for null bytes and control characters
    if did.contains('\0') || did.contains('\n') || did.contains('\r') || did.contains('\t') {
        return Err(ValidationError::InvalidDid(
            "DID contains invalid control characters".to_string()
        ));
    }
    
    // Security: Reasonable length limit
    if did.len() > 1000 {
        return Err(ValidationError::InvalidDid(
            "DID exceeds maximum length".to_string()
        ));
    }
    
    if !did.starts_with("did:") {
        return Err(ValidationError::InvalidDid(
            "DID must start with 'did:' prefix".to_string()
        ));
    }
    
    // Check for basic DID structure: did:method:method-specific-id
    let parts: Vec<&str> = did.split(':').collect();
    if parts.len() < 3 {
        return Err(ValidationError::InvalidDid(
            "DID must have format 'did:method:id'".to_string()
        ));
    }
    
    // Validate method name (second part)
    let method = parts[1];
    if method.is_empty() {
        return Err(ValidationError::InvalidDid(
            "DID method name cannot be empty".to_string()
        ));
    }
    
    // Validate method-specific identifier (third part and beyond)
    let identifier = parts[2..].join(":");
    if identifier.is_empty() {
        return Err(ValidationError::InvalidDid(
            "DID method-specific identifier cannot be empty".to_string()
        ));
    }
    
    Ok(())
}

/// Validates date fields to ensure they are not in the future.
fn validate_dates(data: &AgentData) -> Result<(), ValidationError> {
    let now = Utc::now();
    
    if data.created_at > now {
        return Err(ValidationError::FutureDate(format!(
            "created_at ({}) cannot be in the future", 
            data.created_at.to_rfc3339()
        )));
    }
    
    Ok(())
}

/// Validates rating values and consistency.
/// 
/// Ensures:
/// - Average rating is between 1.0 and 5.0 (inclusive) when reviews exist
/// - Average rating is None when there are no reviews
/// - Rating values are not NaN or infinite
fn validate_ratings(data: &AgentData) -> Result<(), ValidationError> {
    match (data.average_rating, data.total_reviews) {
        (Some(rating), reviews) if reviews > 0 => {
            // Check for NaN or infinite values
            if rating.is_nan() || rating.is_infinite() {
                return Err(ValidationError::InvalidRating(rating));
            }
            
            // Check rating bounds
            if rating < 1.0 || rating > 5.0 {
                return Err(ValidationError::InvalidRating(rating));
            }
        },
        (Some(rating), 0) => {
            // If there are no reviews, there shouldn't be an average rating
            return Err(ValidationError::InvalidField {
                field: "average_rating".to_string(),
                value: format!("{} (but total_reviews is 0)", rating),
            });
        },
        (None, reviews) if reviews > 0 => {
            // If there are reviews, there should be an average rating
            return Err(ValidationError::InvalidField {
                field: "average_rating".to_string(),
                value: format!("None (but total_reviews is {})", reviews),
            });
        },
        _ => {}, // None rating with 0 reviews is valid
    }
    
    Ok(())
}

/// Validates review count consistency.
/// 
/// Ensures positive_reviews + negative_reviews = total_reviews
fn validate_review_counts(data: &AgentData) -> Result<(), ValidationError> {
    // Use checked_add to prevent overflow
    let calculated_total = match data.positive_reviews.checked_add(data.negative_reviews) {
        Some(total) => total,
        None => {
            // Overflow occurred - this is definitely inconsistent
            return Err(ValidationError::InconsistentReviews);
        }
    };
    
    if calculated_total != data.total_reviews {
        return Err(ValidationError::InconsistentReviews);
    }
    
    Ok(())
}

/// Validates MCP level is within allowed range (0-3).
fn validate_mcp_level(level: Option<u8>) -> Result<(), ValidationError> {
    if let Some(mcp) = level {
        if mcp > 3 {
            return Err(ValidationError::InvalidMcpLevel(mcp));
        }
    }
    
    Ok(())
}

/// Validates interaction counts and their relationships.
/// 
/// Ensures:
/// - Total reviews doesn't exceed total interactions
/// - Values are logically consistent
fn validate_interactions(data: &AgentData) -> Result<(), ValidationError> {
    // Reviews can't exceed total interactions
    if data.total_reviews > data.total_interactions {
        return Err(ValidationError::InvalidField {
            field: "total_reviews".to_string(),
            value: format!(
                "{} (exceeds total_interactions: {})", 
                data.total_reviews, 
                data.total_interactions
            ),
        });
    }
    
    Ok(())
}

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

    fn create_valid_agent() -> AgentData {
        AgentData {
            did: "did:example:123".to_string(),
            created_at: Utc::now() - Duration::days(1),
            mcp_level: None,
            identity_verified: false,
            security_audit_passed: false,
            open_source: false,
            total_interactions: 0,
            total_reviews: 0,
            average_rating: None,
            positive_reviews: 0,
            negative_reviews: 0,
        }
    }

    #[test]
    fn test_valid_agent_data() {
        let agent = create_valid_agent();
        assert!(validate_agent_data(&agent).is_ok());
    }

    #[test]
    fn test_valid_did_formats() {
        let valid_dids = vec![
            "did:example:123",
            "did:web:example.com",
            "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH",
            "did:ethr:0x1234567890123456789012345678901234567890",
            "did:ion:EiDyOQbbZAa3aiRzeCkV7LOx3SERjjH93EXoIM3UoN4oWg",
            "did:test:foo:bar:baz", // Multiple colons in identifier
        ];

        for did in valid_dids {
            assert!(validate_did(did).is_ok(), "DID '{}' should be valid", did);
        }
    }

    #[test]
    fn test_invalid_did_formats() {
        let test_cases = vec![
            ("", "DID cannot be empty"),
            ("example:123", "DID must start with 'did:'"),
            ("DID:example:123", "DID must start with 'did:'"),
            ("did:", "DID must have format"),
            ("did::", "DID method name cannot be empty"),
            ("did:example", "DID must have format"),
            ("did:example:", "DID method-specific identifier cannot be empty"),
            ("did::123", "DID method name cannot be empty"),
        ];

        for (did, expected_msg) in test_cases {
            let result = validate_did(did);
            assert!(result.is_err(), "DID '{}' should be invalid", did);
            let err_msg = result.unwrap_err().to_string();
            assert!(err_msg.contains(expected_msg), 
                "Error message '{}' should contain '{}'", err_msg, expected_msg);
        }
    }

    #[test]
    fn test_very_long_did() {
        // Test that DIDs up to the limit are accepted
        let long_identifier = "x".repeat(987); // "did:example:" is 12 chars, so 987 + 12 = 999 < 1000
        let long_did = format!("did:example:{}", long_identifier);
        assert!(validate_did(&long_did).is_ok());
        
        // Test that DIDs over the limit are rejected
        let too_long_identifier = "x".repeat(989); // 989 + 12 = 1001 > 1000
        let too_long_did = format!("did:example:{}", too_long_identifier);
        assert!(matches!(
            validate_did(&too_long_did),
            Err(ValidationError::InvalidDid(msg)) if msg.contains("exceeds maximum length")
        ));
    }

    #[test]
    fn test_future_date_validation() {
        let mut agent = create_valid_agent();
        agent.created_at = Utc::now() + Duration::days(1);
        
        let result = validate_agent_data(&agent);
        assert!(matches!(result, Err(ValidationError::FutureDate(_))));
    }

    #[test]
    fn test_date_edge_cases() {
        let mut agent = create_valid_agent();
        
        // Exactly now should be valid
        agent.created_at = Utc::now();
        assert!(validate_dates(&agent).is_ok());
        
        // Far past should be valid
        agent.created_at = Utc::now() - Duration::days(3650); // 10 years ago
        assert!(validate_dates(&agent).is_ok());
    }

    #[test]
    fn test_rating_validation() {
        let mut agent = create_valid_agent();
        
        // Valid ratings with reviews
        agent.total_reviews = 10;
        agent.positive_reviews = 8;
        agent.negative_reviews = 2;
        agent.total_interactions = 20;
        
        let valid_ratings = vec![1.0, 2.5, 3.0, 4.5, 5.0];
        for rating in valid_ratings {
            agent.average_rating = Some(rating);
            assert!(validate_ratings(&agent).is_ok(), 
                "Rating {} should be valid", rating);
        }
        
        // Invalid ratings
        let invalid_ratings = vec![0.0, 0.9, 5.1, 6.0, -1.0, 10.0];
        for rating in invalid_ratings {
            agent.average_rating = Some(rating);
            let result = validate_ratings(&agent);
            assert!(matches!(result, Err(ValidationError::InvalidRating(_))),
                "Rating {} should be invalid", rating);
        }
    }

    #[test]
    fn test_rating_special_values() {
        let mut agent = create_valid_agent();
        agent.total_reviews = 10;
        agent.positive_reviews = 10;
        agent.total_interactions = 10;
        
        // NaN
        agent.average_rating = Some(f64::NAN);
        let result = validate_ratings(&agent);
        assert!(matches!(result, Err(ValidationError::InvalidRating(_))));
        
        // Positive infinity
        agent.average_rating = Some(f64::INFINITY);
        let result = validate_ratings(&agent);
        assert!(matches!(result, Err(ValidationError::InvalidRating(_))));
        
        // Negative infinity
        agent.average_rating = Some(f64::NEG_INFINITY);
        let result = validate_ratings(&agent);
        assert!(matches!(result, Err(ValidationError::InvalidRating(_))));
    }

    #[test]
    fn test_rating_consistency() {
        let mut agent = create_valid_agent();
        
        // No reviews but has rating
        agent.total_reviews = 0;
        agent.average_rating = Some(4.5);
        let result = validate_ratings(&agent);
        assert!(matches!(result, Err(ValidationError::InvalidField { field, .. }) if field == "average_rating"));
        
        // Has reviews but no rating
        agent.total_reviews = 10;
        agent.positive_reviews = 6;
        agent.negative_reviews = 4;
        agent.total_interactions = 10;
        agent.average_rating = None;
        let result = validate_ratings(&agent);
        assert!(matches!(result, Err(ValidationError::InvalidField { field, .. }) if field == "average_rating"));
    }

    #[test]
    fn test_review_count_validation() {
        let mut agent = create_valid_agent();
        
        // Valid: positive + negative = total
        agent.positive_reviews = 10;
        agent.negative_reviews = 5;
        agent.total_reviews = 15;
        agent.total_interactions = 20;
        assert!(validate_review_counts(&agent).is_ok());
        
        // Invalid: doesn't add up
        agent.total_reviews = 20;
        let result = validate_review_counts(&agent);
        assert!(matches!(result, Err(ValidationError::InconsistentReviews)));
    }

    #[test]
    fn test_review_count_edge_cases() {
        let mut agent = create_valid_agent();
        
        // All zeros
        assert!(validate_review_counts(&agent).is_ok());
        
        // Only positive reviews
        agent.positive_reviews = 100;
        agent.total_reviews = 100;
        agent.total_interactions = 100;
        assert!(validate_review_counts(&agent).is_ok());
        
        // Only negative reviews
        agent.positive_reviews = 0;
        agent.negative_reviews = 50;
        agent.total_reviews = 50;
        assert!(validate_review_counts(&agent).is_ok());
        
        // Large numbers
        agent.positive_reviews = 1_000_000;
        agent.negative_reviews = 500_000;
        agent.total_reviews = 1_500_000;
        agent.total_interactions = 2_000_000;
        assert!(validate_review_counts(&agent).is_ok());
    }

    #[test]
    fn test_mcp_level_validation() {
        // Valid levels
        for level in 0..=3 {
            assert!(validate_mcp_level(Some(level)).is_ok(), 
                "MCP level {} should be valid", level);
        }
        
        // None is valid
        assert!(validate_mcp_level(None).is_ok());
        
        // Invalid levels
        for level in 4..=10 {
            let result = validate_mcp_level(Some(level));
            assert!(matches!(result, Err(ValidationError::InvalidMcpLevel(_))),
                "MCP level {} should be invalid", level);
        }
    }

    #[test]
    fn test_interaction_validation() {
        let mut agent = create_valid_agent();
        
        // Valid: reviews <= interactions
        agent.total_reviews = 50;
        agent.positive_reviews = 30;
        agent.negative_reviews = 20;
        agent.total_interactions = 100;
        assert!(validate_interactions(&agent).is_ok());
        
        // Valid: reviews = interactions
        agent.total_interactions = 50;
        assert!(validate_interactions(&agent).is_ok());
        
        // Invalid: reviews > interactions
        agent.total_interactions = 40;
        let result = validate_interactions(&agent);
        assert!(matches!(result, Err(ValidationError::InvalidField { field, .. }) if field == "total_reviews"));
    }

    #[test]
    fn test_complete_validation_chain() {
        let mut agent = create_valid_agent();
        
        // Set up a complex valid scenario
        agent.did = "did:web:example.com:users:alice".to_string();
        agent.created_at = Utc::now() - Duration::days(30);
        agent.mcp_level = Some(2);
        agent.identity_verified = true;
        agent.security_audit_passed = true;
        agent.open_source = true;
        agent.total_interactions = 1000;
        agent.total_reviews = 500;
        agent.average_rating = Some(4.2);
        agent.positive_reviews = 400;
        agent.negative_reviews = 100;
        
        assert!(validate_agent_data(&agent).is_ok());
    }

    #[test]
    fn test_validation_stops_on_first_error() {
        let mut agent = create_valid_agent();
        
        // Multiple errors: bad DID, future date, invalid rating
        agent.did = "not-a-did".to_string();
        agent.created_at = Utc::now() + Duration::days(1);
        agent.average_rating = Some(10.0);
        agent.total_reviews = 10;
        agent.positive_reviews = 5;
        agent.negative_reviews = 5;
        
        let result = validate_agent_data(&agent);
        // Should get DID error first
        assert!(matches!(result, Err(ValidationError::InvalidDid(_))));
    }

    #[test]
    fn test_unicode_did_validation() {
        let unicode_dids = vec![
            "did:测试:123",
            "did:тест:456",
            "did:テスト:789",
            "did:example:用户:alice",
        ];
        
        for did in unicode_dids {
            assert!(validate_did(did).is_ok(), 
                "Unicode DID '{}' should be valid", did);
        }
    }

    #[test]
    fn test_empty_string_fields() {
        let mut agent = create_valid_agent();
        agent.did = "".to_string();
        
        let result = validate_agent_data(&agent);
        assert!(matches!(result, Err(ValidationError::InvalidDid(_))));
    }

    #[test]
    fn test_max_u32_values() {
        let mut agent = create_valid_agent();
        agent.total_interactions = u32::MAX;
        agent.total_reviews = u32::MAX;
        // These values will cause the sum to overflow when added
        agent.positive_reviews = u32::MAX / 2 + 1;
        agent.negative_reviews = u32::MAX / 2 + 1;
        agent.average_rating = Some(3.5);
        
        // This will fail because positive + negative != total_reviews
        let result = validate_review_counts(&agent);
        assert!(result.is_err());
        assert!(matches!(result, Err(ValidationError::InconsistentReviews)));
    }

    #[test]
    fn test_validation_performance() {
        use std::time::Instant;
        
        let agent = create_valid_agent();
        let start = Instant::now();
        
        // Run validation 1000 times
        for _ in 0..1000 {
            let _ = validate_agent_data(&agent);
        }
        
        let duration = start.elapsed();
        let avg_time = duration.as_micros() as f64 / 1000.0;
        
        // Should be well under 1ms per validation
        assert!(avg_time < 1000.0, 
            "Validation took {} microseconds on average, should be < 1000", avg_time);
    }
}