spawn-access-control 0.1.12

A Rust library for access control management with WebAssembly support, including role-based access control (RBAC), permissions, and audit logging.
Documentation
use spawn_access_control::{
    security_analyzer::{SecurityAnalyzer, SecurityConfig},
    alert_analyzer::{PatternType, TimeRange, AlertAnalysis, AlertPattern, ResolutionMetrics},
    monitoring::{ModelMonitor, MonitoringConfig, HealthStatus},
    error::Error,
    Duration,
    audit::{AuditLogEntry, ActionResult},
};
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use async_trait::async_trait;

// Mock veri tipleri
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct MockAlert {
    id: String,
    timestamp: DateTime<Utc>,
    severity: String,
    metric: String,
    value: f64,
}

#[async_trait]
pub trait AlertStorageMock {
    async fn analyze_alerts(&self, time_range: TimeRange) -> Result<AlertAnalysis, Error>;
}

struct MockAlertStorage {
    #[allow(dead_code)]
    alerts: Vec<MockAlert>
}

#[async_trait]
impl AlertStorageMock for MockAlertStorage {
    async fn analyze_alerts(&self, time_range: TimeRange) -> Result<AlertAnalysis, Error> {
        let pattern = AlertPattern {
            pattern_type: PatternType::Correlated,
            frequency: 1,
            confidence: 0.9,
            affected_metrics: vec!["cpu_usage".to_string()],
        };

        Ok(AlertAnalysis {
            time_range,
            total_alerts: 1,
            severity_distribution: HashMap::new(),
            resolution_metrics: ResolutionMetrics {
                avg_resolution_time: Duration::minutes(5),
                resolution_rate: 0.9,
                unresolved_critical: 0,
            },
            patterns: vec![pattern],
            recommendations: vec![],
        })
    }
}

impl MockAlertStorage {
    fn new() -> Self {
        Self { alerts: generate_mock_alerts() }
    }
}

#[tokio::test]
async fn test_alert_correlation() -> Result<(), Error> {
    let storage = MockAlertStorage::new();
    
    let time_range = TimeRange {
        start: Utc::now() - Duration::days(1),
        end: Utc::now(),
        duration: Duration::days(1),
    };
    
    let analysis = storage.analyze_alerts(time_range).await?;
    assert!(matches!(analysis.patterns[0].pattern_type, PatternType::Correlated));
    Ok(())
}

fn generate_mock_alerts() -> Vec<MockAlert> {
    vec![
        MockAlert {
            id: "test1".into(),
            timestamp: Utc::now(),
            severity: "critical".into(),
            metric: "cpu_usage".into(),
            value: 95.5,
        },
        // Daha fazla mock alert eklenebilir
    ]
}

#[tokio::test]
async fn test_full_security_pipeline() -> Result<(), Error> {
    let config = SecurityConfig {
        recent_window: Duration::minutes(30),
        max_failures: 5,
        min_suspicious_score: 0.7,
    };
    let security_analyzer = SecurityAnalyzer::new(config);
    
    let test_data = generate_test_data();
    let _security_report = security_analyzer.analyze_recent_activity(&test_data);
    
    Ok(())
}

#[tokio::test]
async fn test_model_degradation() {
    let config = MonitoringConfig {
        metrics_window_size: 3600,
        performance_threshold: 0.8,
        security_threshold: 0.7,
        alert_cooldown: Duration::seconds(300),
    };
    let monitor = ModelMonitor::new(config);
    
    simulate_model_degradation().await;
    
    let health = monitor.get_model_health().await;
    assert_eq!(health.current_status, HealthStatus::Unknown);
}

fn generate_test_data() -> Vec<AuditLogEntry> {
    vec![AuditLogEntry {
        id: "test_1".to_string(),
        timestamp: Utc::now(),
        user_id: "test_user".to_string(),
        action: "test_action".to_string(),
        resource_id: "test_resource".to_string(),
        result: ActionResult::Success,
        details: Some("test details".to_string()),
        ip_address: Some("127.0.0.1".to_string()),
        user_agent: Some("test agent".to_string()),
    }]
}

async fn simulate_model_degradation() {
    // Model performansını düşürme simülasyonu...
}