// rust/01-gdpr-compliance.rs/*GDPR compliance patterns and best practices*/usestd::collections::HashMap;usestd::sync::Arc;usestd::time::{Duration,Instant};usetokio::sync::RwLock;useserde::{Deserialize,Serialize};/// GDPR compliance manager.pubstructGdprCompliance{data_subjects:Arc<RwLock<HashMap<String,DataSubject>>>,consent_records:Arc<RwLock<HashMap<String,ConsentRecord>>>,data_retention:Arc<RwLock<HashMap<String,DataRetentionPolicy>>>,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructDataSubject{pubid:String,pubemail:String,pubconsent_given:bool,pubconsent_date:Option<Instant>,pubdata_categories:Vec<String>,pubretention_period:Duration,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructConsentRecord{pubsubject_id:String,pubconsent_type:String,pubgiven:bool,pubtimestamp:Instant,pubpurpose:String,pubwithdrawal_date:Option<Instant>,}implGdprCompliance{pubfnnew()->Self{Self{data_subjects:Arc::new(RwLock::new(HashMap::new())),consent_records:Arc::new(RwLock::new(HashMap::new())),data_retention:Arc::new(RwLock::new(HashMap::new())),}}/// Register a data subject.pubasyncfnregister_data_subject(&self,subject:DataSubject)->Result<(),String>{letmutsubjects=self.data_subjects.write().await;subjects.insert(subject.id.clone(),subject);Ok(())}/// Record consent.pubasyncfnrecord_consent(&self,subject_id:&str,consent_type:&str,purpose:&str)->Result<(),String>{letconsent_record=ConsentRecord{subject_id:subject_id.to_string(),consent_type:consent_type.to_string(),given:true,timestamp:Instant::now(),purpose:purpose.to_string(),withdrawal_date:None,};letmutrecords=self.consent_records.write().await;records.insert(format!("{}_{}",subject_id,consent_type),consent_record);Ok(())}/// Withdraw consent.pubasyncfnwithdraw_consent(&self,subject_id:&str,consent_type:&str)->Result<(),String>{letmutrecords=self.consent_records.write().await;ifletSome(record)=records.get_mut(&format!("{}_{}",subject_id,consent_type)){record.given=false;record.withdrawal_date=Some(Instant::now());}Ok(())}/// Get data subject information.pubasyncfnget_data_subject_info(&self,subject_id:&str)->Result<DataSubject,String>{letsubjects=self.data_subjects.read().await;subjects.get(subject_id).cloned().ok_or_else(||"Data subject not found".to_string())}/// Delete data subject (right to be forgotten).pubasyncfndelete_data_subject(&self,subject_id:&str)->Result<(),String>{letmutsubjects=self.data_subjects.write().await;subjects.remove(subject_id);letmutrecords=self.consent_records.write().await;records.retain(|key,_|!key.starts_with(subject_id));Ok(())}/// Export data subject data (data portability).pubasyncfnexport_data_subject_data(&self,subject_id:&str)->Result<HashMap<String,serde_json::Value>,String>{letmutexport_data=HashMap::new();// Get data subject infoifletOk(subject)=self.get_data_subject_info(subject_id).await{export_data.insert("data_subject".to_string(),serde_json::to_value(subject).unwrap());}// Get consent recordsletrecords=self.consent_records.read().await;letsubject_records:Vec<_>=records.values().filter(|record|record.subject_id==subject_id).collect();export_data.insert("consent_records".to_string(),serde_json::to_value(subject_records).unwrap());Ok(export_data)}}#[cfg(test)]modtests{usesuper::*;#[tokio::test]asyncfntest_gdpr_compliance(){letcompliance=GdprCompliance::new();letsubject=DataSubject{id:"subject1".to_string(),email:"test@example.com".to_string(),consent_given:true,consent_date:Some(Instant::now()),data_categories:vec!["personal".to_string(),"contact".to_string()],retention_period:Duration::from_days(365),};compliance.register_data_subject(subject).await.unwrap();compliance.record_consent("subject1","marketing","email campaigns").await.unwrap();letinfo=compliance.get_data_subject_info("subject1").await.unwrap();assert_eq!(info.email,"test@example.com");}}
// rust/02-hipaa-compliance.rs/*HIPAA compliance patterns and best practices*/usestd::collections::HashMap;usestd::sync::Arc;usestd::time::{Duration,Instant};usetokio::sync::RwLock;useserde::{Deserialize,Serialize};/// HIPAA compliance manager.pubstructHipaaCompliance{phi_records:Arc<RwLock<HashMap<String,PhiRecord>>>,access_logs:Arc<RwLock<Vec<AccessLog>>>,encryption_keys:Arc<RwLock<HashMap<String,String>>>,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructPhiRecord{pubid:String,pubpatient_id:String,pubdata_type:String,pubencrypted_data:Vec<u8>,pubcreated_at:Instant,pubaccess_level:AccessLevel,}#[derive(Debug, Clone, Serialize, Deserialize)]pubenumAccessLevel{Public,Internal,Restricted,Confidential,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructAccessLog{pubuser_id:String,pubresource_id:String,pubaction:String,pubtimestamp:Instant,pubip_address:String,pubsuccess:bool,}implHipaaCompliance{pubfnnew()->Self{Self{phi_records:Arc::new(RwLock::new(HashMap::new())),access_logs:Arc::new(RwLock::new(Vec::new())),encryption_keys:Arc::new(RwLock::new(HashMap::new())),}}/// Store PHI record.pubasyncfnstore_phi(&self,record:PhiRecord)->Result<(),String>{// Encrypt PHI dataletencrypted_data=self.encrypt_phi_data(&record.encrypted_data).await?;letmutrecords=self.phi_records.write().await;records.insert(record.id.clone(),record);// Log accessself.log_access("system",&record.id,"store",true).await;Ok(())}/// Access PHI record.pubasyncfnaccess_phi(&self,record_id:&str,user_id:&str)->Result<PhiRecord,String>{// Check access permissionsif!self.has_access_permission(user_id,record_id).await{self.log_access(user_id,record_id,"access",false).await;returnErr("Access denied".to_string());}letrecords=self.phi_records.read().await;ifletSome(record)=records.get(record_id){// Log accessself.log_access(user_id,record_id,"access",true).await;// Decrypt dataletdecrypted_data=self.decrypt_phi_data(&record.encrypted_data).await?;Ok(PhiRecord{id:record.id.clone(),patient_id:record.patient_id.clone(),data_type:record.data_type.clone(),encrypted_data:decrypted_data,created_at:record.created_at,access_level:record.access_level.clone(),})}else{Err("PHI record not found".to_string())}}/// Log access attempt.asyncfnlog_access(&self,user_id:&str,resource_id:&str,action:&str,success:bool){letlog=AccessLog{user_id:user_id.to_string(),resource_id:resource_id.to_string(),action:action.to_string(),timestamp:Instant::now(),ip_address:"127.0.0.1".to_string(),// In real implementation, get actual IPsuccess,};letmutlogs=self.access_logs.write().await;logs.push(log);}/// Check access permissions.asyncfnhas_access_permission(&self,user_id:&str,resource_id:&str)->bool{// In a real implementation, check user roles and permissionstrue}/// Encrypt PHI data.asyncfnencrypt_phi_data(&self,data:&[u8])->Result<Vec<u8>,String>{// In a real implementation, use proper encryptionOk(data.to_vec())}/// Decrypt PHI data.asyncfndecrypt_phi_data(&self,encrypted_data:&[u8])->Result<Vec<u8>,String>{// In a real implementation, use proper decryptionOk(encrypted_data.to_vec())}/// Get access logs.pubasyncfnget_access_logs(&self,user_id:Option<&str>)->Result<Vec<AccessLog>,String>{letlogs=self.access_logs.read().await;ifletSome(user_id)=user_id{Ok(logs.iter().filter(|log|log.user_id==user_id).cloned().collect())}else{Ok(logs.clone())}}}#[cfg(test)]modtests{usesuper::*;#[tokio::test]asyncfntest_hipaa_compliance(){letcompliance=HipaaCompliance::new();letrecord=PhiRecord{id:"phi1".to_string(),patient_id:"patient1".to_string(),data_type:"medical_record".to_string(),encrypted_data:b"encrypted data".to_vec(),created_at:Instant::now(),access_level:AccessLevel::Confidential,};compliance.store_phi(record).await.unwrap();letaccessed_record=compliance.access_phi("phi1","user1").await.unwrap();assert_eq!(accessed_record.patient_id,"patient1");}}
// rust/03-audit-logging.rs/*Audit logging patterns and best practices*/usestd::collections::HashMap;usestd::sync::Arc;usestd::time::{Duration,Instant};usetokio::sync::RwLock;useserde::{Deserialize,Serialize};/// Audit logger.pubstructAuditLogger{logs:Arc<RwLock<Vec<AuditLog>>>,retention_period:Duration,max_logs:usize,}#[derive(Debug, Clone, Serialize, Deserialize)]pubstructAuditLog{pubid:String,pubtimestamp:Instant,pubuser_id:String,pubaction:String,pubresource:String,pubresult:AuditResult,pubmetadata:HashMap<String,String>,pubip_address:String,pubuser_agent:String,}#[derive(Debug, Clone, Serialize, Deserialize)]pubenumAuditResult{Success,Failure,Warning,}implAuditLogger{pubfnnew(retention_period:Duration,max_logs:usize)->Self{Self{logs:Arc::new(RwLock::new(Vec::new())),retention_period,max_logs,}}/// Log an audit event.pubasyncfnlog_event(&self,event:AuditLog)->Result<(),String>{letmutlogs=self.logs.write().await;// Add loglogs.push(event);// Clean up old logsself.cleanup_old_logs(&mutlogs).await;// Limit log sizeiflogs.len()>self.max_logs{logs.drain(0..logs.len()-self.max_logs);}Ok(())}/// Get audit logs.pubasyncfnget_logs(&self,filter:Option<AuditFilter>)->Result<Vec<AuditLog>,String>{letlogs=self.logs.read().await;letmutresult=logs.clone();ifletSome(filter)=filter{result=result.into_iter().filter(|log|{ifletSome(user_id)=&filter.user_id{iflog.user_id!=*user_id{returnfalse;}}ifletSome(action)=&filter.action{iflog.action!=*action{returnfalse;}}ifletSome(result)=&filter.result{iflog.result!=*result{returnfalse;}}ifletSome(start_time)=filter.start_time{iflog.timestamp<start_time{returnfalse;}}ifletSome(end_time)=filter.end_time{iflog.timestamp>end_time{returnfalse;}}true}).collect();}Ok(result)}/// Clean up old logs.asyncfncleanup_old_logs(&self,logs:&mutVec<AuditLog>){letcutoff=Instant::now()-self.retention_period;logs.retain(|log|log.timestamp>cutoff);}}#[derive(Debug, Clone)]pubstructAuditFilter{pubuser_id:Option<String>,pubaction:Option<String>,pubresult:Option<AuditResult>,pubstart_time:Option<Instant>,pubend_time:Option<Instant>,}#[cfg(test)]modtests{usesuper::*;#[tokio::test]asyncfntest_audit_logging(){letlogger=AuditLogger::new(Duration::from_days(30),10000);letlog=AuditLog{id:"log1".to_string(),timestamp:Instant::now(),user_id:"user1".to_string(),action:"login".to_string(),resource:"auth".to_string(),result:AuditResult::Success,metadata:HashMap::new(),ip_address:"127.0.0.1".to_string(),user_agent:"test".to_string(),};logger.log_event(log).await.unwrap();letlogs=logger.get_logs(None).await.unwrap();assert_eq!(logs.len(),1);assert_eq!(logs[0].user_id,"user1");}}