1use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::path::PathBuf;
10use trustformers_core::errors::Result;
11use trustformers_core::TrustformersError;
12
13use aes_gcm::aead::{Aead, Generate, KeyInit};
19use aes_gcm::{Aes128Gcm, Aes256Gcm};
20use chacha20poly1305::ChaCha20Poly1305;
21
22pub struct AndroidModelContentProvider {
24 config: ContentProviderConfig,
25 model_registry: ModelRegistry,
26 security_manager: ContentProviderSecurity,
27 cache_manager: ModelCacheManager,
28 uri_matcher: UriMatcher,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct ContentProviderConfig {
34 pub authority: String,
36 pub enable_sharing: bool,
38 pub max_cached_models: usize,
40 pub cache_size_limit_mb: usize,
42 pub security: SecurityConfig,
44 pub performance: PerformanceConfig,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct SecurityConfig {
51 pub require_signature_verification: bool,
53 pub allowed_packages: Vec<String>,
55 pub per_model_permissions: bool,
57 pub encryption: EncryptionConfig,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
63pub struct EncryptionConfig {
64 pub encrypt_at_rest: bool,
66 pub encrypt_in_transit: bool,
68 pub algorithm: EncryptionAlgorithm,
70 pub key_management: KeyManagementConfig,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76pub enum EncryptionAlgorithm {
77 AES256GCM,
78 ChaCha20Poly1305,
79 AES128GCM,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct KeyManagementConfig {
85 pub use_android_keystore: bool,
87 pub key_rotation_days: u32,
89 pub backup_keys: bool,
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct PerformanceConfig {
96 pub background_loading: bool,
98 pub worker_threads: usize,
100 pub connection_pool_size: usize,
102 pub enable_compression: bool,
104 pub compression_algorithm: CompressionAlgorithm,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110pub enum CompressionAlgorithm {
111 Gzip,
112 Lz4,
113 Zstd,
114}
115
116struct ModelRegistry {
118 models: HashMap<String, ModelInfo>,
119 access_logs: HashMap<String, Vec<AccessLog>>,
120 usage_stats: HashMap<String, UsageStats>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct ModelInfo {
126 pub id: String,
128 pub name: String,
130 pub version: String,
132 pub model_type: ModelType,
134 pub file_path: PathBuf,
136 pub size_bytes: u64,
138 pub metadata: ModelMetadata,
140 pub permissions: ModelPermissions,
142 pub created_at: u64,
144 pub modified_at: u64,
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150pub enum ModelType {
151 Transformer,
152 CNN,
153 RNN,
154 Custom,
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct ModelMetadata {
160 pub description: String,
162 pub architecture: String,
164 pub dataset: Option<String>,
166 pub accuracy: Option<f32>,
168 pub latency_ms: Option<f32>,
170 pub memory_mb: Option<f32>,
172 pub tags: Vec<String>,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct ModelPermissions {
179 pub public_access: bool,
181 pub allowed_packages: Vec<String>,
183 pub required_permissions: Vec<String>,
185 pub access_level: AccessLevel,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
191pub enum AccessLevel {
192 Public,
193 Restricted,
194 Private,
195 System,
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize)]
200struct AccessLog {
201 timestamp: u64,
202 package_name: String,
203 operation: Operation,
204 result: AccessResult,
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
209pub enum Operation {
210 Query,
211 Insert,
212 Update,
213 Delete,
214 Download,
215 Stream,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
220pub enum AccessResult {
221 Success,
222 Denied,
223 Error,
224 NotFound,
225}
226
227#[derive(Debug, Clone, Serialize, Deserialize)]
229struct UsageStats {
230 total_accesses: u64,
231 successful_accesses: u64,
232 failed_accesses: u64,
233 average_response_time_ms: f32,
234 last_access: u64,
235 bandwidth_used_mb: f64,
236}
237
238struct ContentProviderSecurity {
240 config: SecurityConfig,
241 signature_verifier: SignatureVerifier,
242 encryption_manager: EncryptionManager,
243}
244
245struct SignatureVerifier {
247 trusted_signatures: Vec<String>,
248}
249
250struct EncryptionManager {
252 config: EncryptionConfig,
253 active_keys: HashMap<String, Vec<u8>>,
254}
255
256struct ModelCacheManager {
258 cache: HashMap<String, CachedModel>,
259 cache_size_bytes: u64,
260 config: PerformanceConfig,
261}
262
263struct CachedModel {
265 model_info: ModelInfo,
266 data: Vec<u8>,
267 last_accessed: u64,
268 access_count: u64,
269}
270
271struct UriMatcher {
273 patterns: HashMap<String, UriPattern>,
274}
275
276#[derive(Debug, Clone)]
278struct UriPattern {
279 pattern: String,
280 operation: Operation,
281 parameters: Vec<String>,
282}
283
284#[derive(Debug, Clone, Serialize, Deserialize)]
286pub struct QueryParams {
287 pub model_type: Option<ModelType>,
289 pub name_filter: Option<String>,
291 pub version_filter: Option<String>,
293 pub tags: Vec<String>,
295 pub limit: Option<usize>,
297 pub offset: Option<usize>,
299 pub sort_by: Option<SortOrder>,
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
305pub enum SortOrder {
306 Name,
307 Version,
308 Size,
309 CreatedAt,
310 ModifiedAt,
311 Usage,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct QueryResult {
317 pub models: Vec<ModelInfo>,
319 pub total_count: usize,
321 pub execution_time_ms: f32,
323}
324
325impl Default for ContentProviderConfig {
326 fn default() -> Self {
327 Self {
328 authority: "com.trustformers.models".to_string(),
329 enable_sharing: true,
330 max_cached_models: 10,
331 cache_size_limit_mb: 500,
332 security: SecurityConfig::default(),
333 performance: PerformanceConfig::default(),
334 }
335 }
336}
337
338impl Default for SecurityConfig {
339 fn default() -> Self {
340 Self {
341 require_signature_verification: true,
342 allowed_packages: vec![],
343 per_model_permissions: true,
344 encryption: EncryptionConfig::default(),
345 }
346 }
347}
348
349impl Default for EncryptionConfig {
350 fn default() -> Self {
351 Self {
352 encrypt_at_rest: true,
353 encrypt_in_transit: true,
354 algorithm: EncryptionAlgorithm::AES256GCM,
355 key_management: KeyManagementConfig::default(),
356 }
357 }
358}
359
360impl Default for KeyManagementConfig {
361 fn default() -> Self {
362 Self {
363 use_android_keystore: true,
364 key_rotation_days: 90,
365 backup_keys: true,
366 }
367 }
368}
369
370impl Default for PerformanceConfig {
371 fn default() -> Self {
372 Self {
373 background_loading: true,
374 worker_threads: 4,
375 connection_pool_size: 10,
376 enable_compression: true,
377 compression_algorithm: CompressionAlgorithm::Lz4,
378 }
379 }
380}
381
382impl AndroidModelContentProvider {
383 pub fn new(config: ContentProviderConfig) -> Result<Self> {
385 let model_registry = ModelRegistry::new();
386 let security_manager = ContentProviderSecurity::new(config.security.clone())?;
387 let cache_manager = ModelCacheManager::new(config.performance.clone());
388 let uri_matcher = UriMatcher::new(&config.authority);
389
390 Ok(Self {
391 config,
392 model_registry,
393 security_manager,
394 cache_manager,
395 uri_matcher,
396 })
397 }
398
399 pub fn register_model(&mut self, model_info: ModelInfo) -> Result<()> {
401 self.validate_model_info(&model_info)?;
403
404 self.security_manager.verify_model_registration(&model_info)?;
406
407 self.model_registry.register_model(model_info.clone())?;
409
410 if self.config.performance.background_loading {
412 self.cache_manager.preload_model(&model_info)?;
413 }
414
415 tracing::info!("Model registered: {} ({})", model_info.name, model_info.id);
416 Ok(())
417 }
418
419 pub fn query(&mut self, params: QueryParams, calling_package: &str) -> Result<QueryResult> {
421 let start_time = std::time::Instant::now();
422
423 self.security_manager.verify_query_access(calling_package)?;
425
426 let models = self.model_registry.query_models(¶ms)?;
428
429 let filtered_models = self.filter_models_by_permissions(&models, calling_package)?;
431
432 let execution_time = start_time.elapsed().as_millis() as f32;
433
434 self.log_access(calling_package, Operation::Query, AccessResult::Success);
436
437 Ok(QueryResult {
438 models: filtered_models.clone(),
439 total_count: filtered_models.len(),
440 execution_time_ms: execution_time,
441 })
442 }
443
444 pub fn download_model(&mut self, model_id: &str, calling_package: &str) -> Result<Vec<u8>> {
446 self.security_manager.verify_download_access(model_id, calling_package)?;
448
449 if let Some(cached_data) = self.cache_manager.get_cached_model(model_id)? {
451 self.log_access(calling_package, Operation::Download, AccessResult::Success);
452 return Ok(cached_data);
453 }
454
455 let model_info = self.model_registry.get_model(model_id)?.ok_or_else(|| {
457 TrustformersError::runtime_error(format!("Model not found: {}", model_id))
458 })?;
459
460 let data = self.load_model_data(&model_info)?;
461
462 let encrypted_data = if self.config.security.encryption.encrypt_in_transit {
464 self.security_manager.encrypt_data(&data)?
465 } else {
466 data
467 };
468
469 self.cache_manager.cache_model(model_id, &encrypted_data)?;
471
472 self.log_access(calling_package, Operation::Download, AccessResult::Success);
474
475 Ok(encrypted_data)
476 }
477
478 pub fn stream_model(&mut self, model_id: &str, calling_package: &str) -> Result<ModelStream> {
480 self.security_manager.verify_download_access(model_id, calling_package)?;
482
483 let model_info = self.model_registry.get_model(model_id)?.ok_or_else(|| {
484 TrustformersError::runtime_error(format!("Model not found: {}", model_id))
485 })?;
486
487 let stream = ModelStream::new(model_info, self.config.performance.compression_algorithm)?;
489
490 self.log_access(calling_package, Operation::Stream, AccessResult::Success);
492
493 Ok(stream)
494 }
495
496 pub fn update_model(
498 &mut self,
499 model_id: &str,
500 metadata: ModelMetadata,
501 calling_package: &str,
502 ) -> Result<()> {
503 self.security_manager.verify_update_access(model_id, calling_package)?;
505
506 self.model_registry.update_model_metadata(model_id, metadata)?;
508
509 self.cache_manager.invalidate_cache(model_id)?;
511
512 self.log_access(calling_package, Operation::Update, AccessResult::Success);
514
515 Ok(())
516 }
517
518 pub fn delete_model(&mut self, model_id: &str, calling_package: &str) -> Result<()> {
520 self.security_manager.verify_delete_access(model_id, calling_package)?;
522
523 self.model_registry.remove_model(model_id)?;
525
526 self.cache_manager.remove_from_cache(model_id)?;
528
529 self.log_access(calling_package, Operation::Delete, AccessResult::Success);
531
532 Ok(())
533 }
534
535 pub fn get_usage_stats(&self, model_id: Option<&str>) -> Result<Vec<(String, UsageStats)>> {
537 match model_id {
538 Some(id) => {
539 if let Some(stats) = self.model_registry.get_usage_stats(id) {
540 Ok(vec![(id.to_string(), stats)])
541 } else {
542 Ok(vec![])
543 }
544 },
545 None => Ok(self.model_registry.get_all_usage_stats()),
546 }
547 }
548
549 pub fn cleanup_cache(&mut self) -> Result<()> {
551 self.cache_manager.cleanup_expired_entries()?;
552 Ok(())
553 }
554
555 fn validate_model_info(&self, model_info: &ModelInfo) -> Result<()> {
558 if model_info.id.is_empty() {
559 return Err(TrustformersError::config_error(
560 "Model ID cannot be empty",
561 "validate",
562 ));
563 }
564
565 if model_info.name.is_empty() {
566 return Err(TrustformersError::config_error(
567 "Model name cannot be empty",
568 "validate",
569 ));
570 }
571
572 if !model_info.file_path.exists() {
573 return Err(TrustformersError::runtime_error(format!(
574 "Model file does not exist: {:?}",
575 model_info.file_path
576 )));
577 }
578
579 Ok(())
580 }
581
582 fn filter_models_by_permissions(
583 &self,
584 models: &[ModelInfo],
585 calling_package: &str,
586 ) -> Result<Vec<ModelInfo>> {
587 let mut filtered = Vec::new();
588
589 for model in models {
590 if self.security_manager.check_model_access(&model.permissions, calling_package)? {
591 filtered.push(model.clone());
592 }
593 }
594
595 Ok(filtered)
596 }
597
598 fn load_model_data(&self, model_info: &ModelInfo) -> Result<Vec<u8>> {
599 std::fs::read(&model_info.file_path).map_err(|e| {
600 TrustformersError::runtime_error(format!("Failed to read model file: {}", e))
601 })
602 }
603
604 fn log_access(&mut self, package_name: &str, operation: Operation, result: AccessResult) {
605 let log_entry = AccessLog {
606 timestamp: std::time::SystemTime::now()
607 .duration_since(std::time::UNIX_EPOCH)
608 .unwrap_or_default()
609 .as_secs(),
610 package_name: package_name.to_string(),
611 operation,
612 result,
613 };
614
615 self.model_registry.add_access_log("global".to_string(), log_entry);
616 }
617}
618
619pub struct ModelStream {
621 model_info: ModelInfo,
622 compression: CompressionAlgorithm,
623 chunk_size: usize,
624 current_position: usize,
625}
626
627impl ModelStream {
628 fn new(model_info: ModelInfo, compression: CompressionAlgorithm) -> Result<Self> {
629 Ok(Self {
630 model_info,
631 compression,
632 chunk_size: 1024 * 1024, current_position: 0,
634 })
635 }
636
637 pub fn read_chunk(&mut self) -> Result<Option<Vec<u8>>> {
644 use std::io::{Read, Seek, SeekFrom};
645
646 if self.current_position >= self.model_info.size_bytes as usize {
647 return Ok(None);
648 }
649
650 let chunk_end =
651 (self.current_position + self.chunk_size).min(self.model_info.size_bytes as usize);
652 let chunk_len = chunk_end - self.current_position;
653
654 let mut file = std::fs::File::open(&self.model_info.file_path).map_err(|e| {
655 TrustformersError::runtime_error(format!(
656 "failed to open model file {:?} for streaming: {e}",
657 self.model_info.file_path
658 ))
659 })?;
660 file.seek(SeekFrom::Start(self.current_position as u64)).map_err(|e| {
661 TrustformersError::runtime_error(format!(
662 "failed to seek model file {:?} to offset {}: {e}",
663 self.model_info.file_path, self.current_position
664 ))
665 })?;
666
667 let mut chunk = vec![0u8; chunk_len];
668 file.read_exact(&mut chunk).map_err(|e| {
669 TrustformersError::runtime_error(format!(
670 "failed to read {chunk_len} bytes from model file {:?} at offset {}: {e}",
671 self.model_info.file_path, self.current_position
672 ))
673 })?;
674 self.current_position = chunk_end;
675
676 Ok(Some(chunk))
677 }
678
679 pub fn progress(&self) -> f32 {
681 self.current_position as f32 / self.model_info.size_bytes as f32
682 }
683}
684
685impl ModelRegistry {
688 fn new() -> Self {
689 Self {
690 models: HashMap::new(),
691 access_logs: HashMap::new(),
692 usage_stats: HashMap::new(),
693 }
694 }
695
696 fn register_model(&mut self, model_info: ModelInfo) -> Result<()> {
697 let id = model_info.id.clone();
698 self.models.insert(id.clone(), model_info);
699 self.usage_stats.insert(id, UsageStats::new());
700 Ok(())
701 }
702
703 fn query_models(&self, params: &QueryParams) -> Result<Vec<ModelInfo>> {
704 let mut results: Vec<_> = self.models.values().cloned().collect();
705
706 if let Some(model_type) = params.model_type {
708 results.retain(|m| m.model_type == model_type);
709 }
710
711 if let Some(ref name_filter) = params.name_filter {
712 results.retain(|m| m.name.contains(name_filter));
713 }
714
715 if let Some(ref version_filter) = params.version_filter {
716 results.retain(|m| m.version == *version_filter);
717 }
718
719 if !params.tags.is_empty() {
720 results.retain(|m| params.tags.iter().any(|tag| m.metadata.tags.contains(tag)));
721 }
722
723 if let Some(sort_by) = params.sort_by {
725 match sort_by {
726 SortOrder::Name => results.sort_by_key(|a| a.name.clone()),
727 SortOrder::Version => results.sort_by_key(|a| a.version.clone()),
728 SortOrder::Size => results.sort_by_key(|a| a.size_bytes),
729 SortOrder::CreatedAt => results.sort_by_key(|a| a.created_at),
730 SortOrder::ModifiedAt => results.sort_by_key(|a| a.modified_at),
731 SortOrder::Usage => {
732 results.sort_by(|a, b| {
733 let usage_a =
734 self.usage_stats.get(&a.id).map(|u| u.total_accesses).unwrap_or(0);
735 let usage_b =
736 self.usage_stats.get(&b.id).map(|u| u.total_accesses).unwrap_or(0);
737 usage_b.cmp(&usage_a) });
739 },
740 }
741 }
742
743 if let Some(offset) = params.offset {
745 if offset < results.len() {
746 results = results.into_iter().skip(offset).collect();
747 } else {
748 results.clear();
749 }
750 }
751
752 if let Some(limit) = params.limit {
753 results.truncate(limit);
754 }
755
756 Ok(results)
757 }
758
759 fn get_model(&self, model_id: &str) -> Result<Option<ModelInfo>> {
760 Ok(self.models.get(model_id).cloned())
761 }
762
763 fn update_model_metadata(&mut self, model_id: &str, metadata: ModelMetadata) -> Result<()> {
764 if let Some(model) = self.models.get_mut(model_id) {
765 model.metadata = metadata;
766 model.modified_at = std::time::SystemTime::now()
767 .duration_since(std::time::UNIX_EPOCH)
768 .unwrap_or_default()
769 .as_secs();
770 Ok(())
771 } else {
772 Err(TrustformersError::runtime_error(format!(
773 "Model not found: {}",
774 model_id
775 )))
776 }
777 }
778
779 fn remove_model(&mut self, model_id: &str) -> Result<()> {
780 self.models.remove(model_id);
781 self.access_logs.remove(model_id);
782 self.usage_stats.remove(model_id);
783 Ok(())
784 }
785
786 fn add_access_log(&mut self, model_id: String, log: AccessLog) {
787 self.access_logs.entry(model_id).or_default().push(log);
788 }
789
790 fn get_usage_stats(&self, model_id: &str) -> Option<UsageStats> {
791 self.usage_stats.get(model_id).cloned()
792 }
793
794 fn get_all_usage_stats(&self) -> Vec<(String, UsageStats)> {
795 self.usage_stats.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
796 }
797}
798
799impl UsageStats {
800 fn new() -> Self {
801 Self {
802 total_accesses: 0,
803 successful_accesses: 0,
804 failed_accesses: 0,
805 average_response_time_ms: 0.0,
806 last_access: 0,
807 bandwidth_used_mb: 0.0,
808 }
809 }
810}
811
812impl ContentProviderSecurity {
813 fn new(config: SecurityConfig) -> Result<Self> {
814 Ok(Self {
815 config: config.clone(),
816 signature_verifier: SignatureVerifier::new(),
817 encryption_manager: EncryptionManager::new(config.encryption)?,
818 })
819 }
820
821 fn verify_model_registration(&self, _model_info: &ModelInfo) -> Result<()> {
822 Ok(())
824 }
825
826 fn verify_query_access(&self, _calling_package: &str) -> Result<()> {
827 Ok(())
829 }
830
831 fn verify_download_access(&self, _model_id: &str, _calling_package: &str) -> Result<()> {
832 Ok(())
834 }
835
836 fn verify_update_access(&self, _model_id: &str, _calling_package: &str) -> Result<()> {
837 Ok(())
839 }
840
841 fn verify_delete_access(&self, _model_id: &str, _calling_package: &str) -> Result<()> {
842 Ok(())
844 }
845
846 fn check_model_access(
847 &self,
848 permissions: &ModelPermissions,
849 calling_package: &str,
850 ) -> Result<bool> {
851 if permissions.public_access {
852 return Ok(true);
853 }
854
855 if permissions.allowed_packages.contains(&calling_package.to_string()) {
856 return Ok(true);
857 }
858
859 Ok(false)
860 }
861
862 fn encrypt_data(&self, data: &[u8]) -> Result<Vec<u8>> {
863 self.encryption_manager.encrypt(data)
864 }
865}
866
867impl SignatureVerifier {
868 fn new() -> Self {
869 Self {
870 trusted_signatures: Vec::new(),
871 }
872 }
873}
874
875const ACTIVE_KEY_ID: &str = "default";
881
882impl EncryptionManager {
883 fn new(config: EncryptionConfig) -> Result<Self> {
888 let mut key = vec![0u8; 32];
889 getrandom::fill(&mut key).map_err(|e| {
890 TrustformersError::runtime_error(format!(
891 "failed to generate an encryption key from the OS CSPRNG: {e}"
892 ))
893 })?;
894
895 let mut active_keys = HashMap::new();
896 active_keys.insert(ACTIVE_KEY_ID.to_string(), key);
897
898 Ok(Self {
899 config,
900 active_keys,
901 })
902 }
903
904 fn active_key(&self) -> Result<&[u8]> {
905 self.active_keys.get(ACTIVE_KEY_ID).map(Vec::as_slice).ok_or_else(|| {
906 TrustformersError::runtime_error(
907 "EncryptionManager has no active key (internal error: EncryptionManager::new \
908 should always populate one)"
909 .to_string(),
910 )
911 })
912 }
913
914 fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>> {
922 let key = self.active_key()?;
923
924 let (nonce_bytes, ciphertext): (Vec<u8>, Vec<u8>) = match self.config.algorithm {
925 EncryptionAlgorithm::AES256GCM => {
926 let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| {
927 TrustformersError::runtime_error(format!(
928 "failed to initialise AES-256-GCM cipher: {e}"
929 ))
930 })?;
931 let nonce = aes_gcm::Nonce::generate();
932 let ct = cipher.encrypt(&nonce, data).map_err(|e| {
933 TrustformersError::runtime_error(format!("AES-256-GCM encryption failed: {e}"))
934 })?;
935 (nonce.to_vec(), ct)
936 },
937 EncryptionAlgorithm::AES128GCM => {
938 let cipher = Aes128Gcm::new_from_slice(&key[..16]).map_err(|e| {
939 TrustformersError::runtime_error(format!(
940 "failed to initialise AES-128-GCM cipher: {e}"
941 ))
942 })?;
943 let nonce = aes_gcm::Nonce::generate();
944 let ct = cipher.encrypt(&nonce, data).map_err(|e| {
945 TrustformersError::runtime_error(format!("AES-128-GCM encryption failed: {e}"))
946 })?;
947 (nonce.to_vec(), ct)
948 },
949 EncryptionAlgorithm::ChaCha20Poly1305 => {
950 let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| {
951 TrustformersError::runtime_error(format!(
952 "failed to initialise ChaCha20-Poly1305 cipher: {e}"
953 ))
954 })?;
955 let nonce = chacha20poly1305::Nonce::generate();
956 let ct = cipher.encrypt(&nonce, data).map_err(|e| {
957 TrustformersError::runtime_error(format!(
958 "ChaCha20-Poly1305 encryption failed: {e}"
959 ))
960 })?;
961 (nonce.to_vec(), ct)
962 },
963 };
964
965 let mut out = Vec::with_capacity(nonce_bytes.len() + ciphertext.len());
966 out.extend_from_slice(&nonce_bytes);
967 out.extend_from_slice(&ciphertext);
968 Ok(out)
969 }
970
971 #[allow(dead_code)] fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>> {
977 const NONCE_LEN: usize = 12;
978 if data.len() < NONCE_LEN {
979 return Err(TrustformersError::runtime_error(format!(
980 "encrypted data must be at least {NONCE_LEN} bytes (AEAD nonce size), got {}",
981 data.len()
982 )));
983 }
984 let key = self.active_key()?;
985 let (nonce_bytes, ciphertext) = data.split_at(NONCE_LEN);
986
987 let auth_fail = |e: aes_gcm::aead::Error| -> TrustformersError {
988 TrustformersError::runtime_error(format!(
989 "decryption failed: wrong key, or the ciphertext was corrupted or tampered with \
990 ({e})"
991 ))
992 };
993
994 match self.config.algorithm {
995 EncryptionAlgorithm::AES256GCM => {
996 let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| {
997 TrustformersError::runtime_error(format!(
998 "failed to initialise AES-256-GCM cipher: {e}"
999 ))
1000 })?;
1001 let nonce = aes_gcm::Nonce::try_from(nonce_bytes).map_err(|_| {
1002 TrustformersError::runtime_error("malformed AES-256-GCM nonce".to_string())
1003 })?;
1004 cipher.decrypt(&nonce, ciphertext).map_err(auth_fail)
1005 },
1006 EncryptionAlgorithm::AES128GCM => {
1007 let cipher = Aes128Gcm::new_from_slice(&key[..16]).map_err(|e| {
1008 TrustformersError::runtime_error(format!(
1009 "failed to initialise AES-128-GCM cipher: {e}"
1010 ))
1011 })?;
1012 let nonce = aes_gcm::Nonce::try_from(nonce_bytes).map_err(|_| {
1013 TrustformersError::runtime_error("malformed AES-128-GCM nonce".to_string())
1014 })?;
1015 cipher.decrypt(&nonce, ciphertext).map_err(auth_fail)
1016 },
1017 EncryptionAlgorithm::ChaCha20Poly1305 => {
1018 let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| {
1019 TrustformersError::runtime_error(format!(
1020 "failed to initialise ChaCha20-Poly1305 cipher: {e}"
1021 ))
1022 })?;
1023 let nonce = chacha20poly1305::Nonce::try_from(nonce_bytes).map_err(|_| {
1024 TrustformersError::runtime_error(
1025 "malformed ChaCha20-Poly1305 nonce".to_string(),
1026 )
1027 })?;
1028 cipher.decrypt(&nonce, ciphertext).map_err(auth_fail)
1029 },
1030 }
1031 }
1032}
1033
1034impl ModelCacheManager {
1035 fn new(config: PerformanceConfig) -> Self {
1036 Self {
1037 cache: HashMap::new(),
1038 cache_size_bytes: 0,
1039 config,
1040 }
1041 }
1042
1043 fn preload_model(&mut self, _model_info: &ModelInfo) -> Result<()> {
1044 Ok(())
1046 }
1047
1048 fn get_cached_model(&mut self, model_id: &str) -> Result<Option<Vec<u8>>> {
1049 if let Some(cached) = self.cache.get_mut(model_id) {
1050 cached.last_accessed = std::time::SystemTime::now()
1051 .duration_since(std::time::UNIX_EPOCH)
1052 .unwrap_or_default()
1053 .as_secs();
1054 cached.access_count += 1;
1055 Ok(Some(cached.data.clone()))
1056 } else {
1057 Ok(None)
1058 }
1059 }
1060
1061 fn cache_model(&mut self, model_id: &str, data: &[u8]) -> Result<()> {
1062 if self.cache_size_bytes + data.len() as u64
1064 > (self.config.connection_pool_size * 1024 * 1024) as u64
1065 {
1066 self.evict_lru_models()?;
1067 }
1068
1069 let cached_model = CachedModel {
1070 model_info: ModelInfo {
1071 id: model_id.to_string(),
1072 name: "cached".to_string(),
1073 version: "1.0".to_string(),
1074 model_type: ModelType::Custom,
1075 file_path: PathBuf::new(),
1076 size_bytes: data.len() as u64,
1077 metadata: ModelMetadata {
1078 description: "Cached model".to_string(),
1079 architecture: "Unknown".to_string(),
1080 dataset: None,
1081 accuracy: None,
1082 latency_ms: None,
1083 memory_mb: None,
1084 tags: vec![],
1085 },
1086 permissions: ModelPermissions {
1087 public_access: false,
1088 allowed_packages: vec![],
1089 required_permissions: vec![],
1090 access_level: AccessLevel::Private,
1091 },
1092 created_at: std::time::SystemTime::now()
1093 .duration_since(std::time::UNIX_EPOCH)
1094 .unwrap_or_default()
1095 .as_secs(),
1096 modified_at: std::time::SystemTime::now()
1097 .duration_since(std::time::UNIX_EPOCH)
1098 .unwrap_or_default()
1099 .as_secs(),
1100 },
1101 data: data.to_vec(),
1102 last_accessed: std::time::SystemTime::now()
1103 .duration_since(std::time::UNIX_EPOCH)
1104 .unwrap_or_default()
1105 .as_secs(),
1106 access_count: 1,
1107 };
1108
1109 self.cache_size_bytes += data.len() as u64;
1110 self.cache.insert(model_id.to_string(), cached_model);
1111
1112 Ok(())
1113 }
1114
1115 fn invalidate_cache(&mut self, model_id: &str) -> Result<()> {
1116 if let Some(cached) = self.cache.remove(model_id) {
1117 self.cache_size_bytes -= cached.data.len() as u64;
1118 }
1119 Ok(())
1120 }
1121
1122 fn remove_from_cache(&mut self, model_id: &str) -> Result<()> {
1123 self.invalidate_cache(model_id)
1124 }
1125
1126 fn cleanup_expired_entries(&mut self) -> Result<()> {
1127 let cutoff_time = std::time::SystemTime::now()
1129 .duration_since(std::time::UNIX_EPOCH)
1130 .unwrap_or_default()
1131 .as_secs()
1132 - 3600; let to_remove: Vec<String> = self
1135 .cache
1136 .iter()
1137 .filter(|(_, cached)| cached.last_accessed < cutoff_time)
1138 .map(|(id, _)| id.clone())
1139 .collect();
1140
1141 for id in to_remove {
1142 self.invalidate_cache(&id)?;
1143 }
1144
1145 Ok(())
1146 }
1147
1148 fn evict_lru_models(&mut self) -> Result<()> {
1149 if let Some((lru_id, _)) = self
1151 .cache
1152 .iter()
1153 .min_by_key(|(_, cached)| cached.last_accessed)
1154 .map(|(id, cached)| (id.clone(), cached))
1155 {
1156 self.invalidate_cache(&lru_id)?;
1157 }
1158 Ok(())
1159 }
1160}
1161
1162impl UriMatcher {
1163 fn new(authority: &str) -> Self {
1164 let mut patterns = HashMap::new();
1165
1166 patterns.insert(
1168 format!("content://{}/models", authority),
1169 UriPattern {
1170 pattern: "/models".to_string(),
1171 operation: Operation::Query,
1172 parameters: vec![],
1173 },
1174 );
1175
1176 patterns.insert(
1177 format!("content://{}/models/#", authority),
1178 UriPattern {
1179 pattern: "/models/#".to_string(),
1180 operation: Operation::Download,
1181 parameters: vec!["model_id".to_string()],
1182 },
1183 );
1184
1185 Self { patterns }
1186 }
1187}
1188
1189#[cfg(test)]
1190mod tests {
1191 use super::*;
1192
1193 #[test]
1194 fn test_content_provider_creation() {
1195 let config = ContentProviderConfig::default();
1196 let provider = AndroidModelContentProvider::new(config);
1197 assert!(provider.is_ok());
1198 }
1199
1200 #[test]
1201 fn test_model_info_validation() {
1202 let config = ContentProviderConfig::default();
1203 let provider = AndroidModelContentProvider::new(config).expect("Operation failed");
1204
1205 let invalid_model = ModelInfo {
1206 id: "".to_string(), name: "test".to_string(),
1208 version: "1.0".to_string(),
1209 model_type: ModelType::Transformer,
1210 file_path: PathBuf::from("/nonexistent/path"),
1211 size_bytes: 1000,
1212 metadata: ModelMetadata {
1213 description: "Test model".to_string(),
1214 architecture: "Test".to_string(),
1215 dataset: None,
1216 accuracy: None,
1217 latency_ms: None,
1218 memory_mb: None,
1219 tags: vec![],
1220 },
1221 permissions: ModelPermissions {
1222 public_access: true,
1223 allowed_packages: vec![],
1224 required_permissions: vec![],
1225 access_level: AccessLevel::Public,
1226 },
1227 created_at: 0,
1228 modified_at: 0,
1229 };
1230
1231 assert!(provider.validate_model_info(&invalid_model).is_err());
1232 }
1233
1234 #[test]
1235 fn test_query_params() {
1236 let params = QueryParams {
1237 model_type: Some(ModelType::Transformer),
1238 name_filter: Some("bert".to_string()),
1239 version_filter: None,
1240 tags: vec!["nlp".to_string()],
1241 limit: Some(10),
1242 offset: Some(0),
1243 sort_by: Some(SortOrder::Name),
1244 };
1245
1246 assert_eq!(
1247 params.model_type.expect("Operation failed"),
1248 ModelType::Transformer
1249 );
1250 assert_eq!(params.tags.len(), 1);
1251 }
1252
1253 #[test]
1254 fn test_content_provider_config_default() {
1255 let config = ContentProviderConfig::default();
1256 assert!(!config.authority.is_empty());
1257 assert!(config.enable_sharing);
1258 assert!(config.max_cached_models > 0);
1259 assert!(config.cache_size_limit_mb > 0);
1260 }
1261
1262 #[test]
1263 fn test_security_config_default() {
1264 let config = SecurityConfig::default();
1265 assert!(config.require_signature_verification);
1266 assert!(config.per_model_permissions);
1267 }
1268
1269 #[test]
1270 fn test_encryption_config_default() {
1271 let config = EncryptionConfig::default();
1272 assert!(config.encrypt_at_rest);
1273 assert!(config.encrypt_in_transit);
1274 }
1275
1276 #[test]
1277 fn test_key_management_config_default() {
1278 let config = KeyManagementConfig::default();
1279 assert!(config.use_android_keystore);
1280 assert!(config.key_rotation_days > 0);
1281 }
1282
1283 #[test]
1284 fn test_performance_config_default() {
1285 let config = PerformanceConfig::default();
1286 assert!(config.background_loading);
1287 assert!(config.worker_threads > 0);
1288 assert!(config.connection_pool_size > 0);
1289 }
1290
1291 #[test]
1292 fn test_encryption_algorithm_variants() {
1293 let algos = vec![
1294 EncryptionAlgorithm::AES256GCM,
1295 EncryptionAlgorithm::ChaCha20Poly1305,
1296 EncryptionAlgorithm::AES128GCM,
1297 ];
1298 assert_eq!(algos.len(), 3);
1299 }
1300
1301 #[test]
1302 fn test_compression_algorithm_variants() {
1303 let algos = vec![
1304 CompressionAlgorithm::Gzip,
1305 CompressionAlgorithm::Lz4,
1306 CompressionAlgorithm::Zstd,
1307 ];
1308 assert_eq!(algos.len(), 3);
1309 }
1310
1311 #[test]
1312 fn test_model_type_variants() {
1313 let types = vec![
1314 ModelType::Transformer,
1315 ModelType::CNN,
1316 ModelType::RNN,
1317 ModelType::Custom,
1318 ];
1319 assert_eq!(types.len(), 4);
1320 }
1321
1322 #[test]
1323 fn test_access_level_variants() {
1324 let levels = vec![
1325 AccessLevel::Public,
1326 AccessLevel::Private,
1327 AccessLevel::Restricted,
1328 AccessLevel::System,
1329 ];
1330 assert_eq!(levels.len(), 4);
1331 }
1332
1333 #[test]
1334 fn test_sort_order_variants() {
1335 let orders = vec![SortOrder::Name, SortOrder::Size, SortOrder::CreatedAt];
1336 assert_eq!(orders.len(), 3);
1337 }
1338
1339 #[test]
1340 fn test_model_info_with_valid_id() {
1341 let config = ContentProviderConfig::default();
1342 let provider = AndroidModelContentProvider::new(config).expect("Operation failed");
1343
1344 let dir = std::env::temp_dir();
1350 let file_path = dir.join(format!(
1351 "trustformers_mobile_valid_model_test_{}.bin",
1352 std::process::id()
1353 ));
1354 std::fs::write(&file_path, b"fake model bytes").expect("write temp model file");
1355
1356 let model = ModelInfo {
1357 id: "valid_model_id".to_string(),
1358 name: "Test Model".to_string(),
1359 version: "1.0".to_string(),
1360 model_type: ModelType::Transformer,
1361 file_path: file_path.clone(),
1362 size_bytes: 10000,
1363 metadata: ModelMetadata {
1364 description: "Test".to_string(),
1365 architecture: "Transformer".to_string(),
1366 dataset: None,
1367 accuracy: Some(0.95),
1368 latency_ms: Some(10.0),
1369 memory_mb: Some(128.0),
1370 tags: vec!["nlp".to_string()],
1371 },
1372 permissions: ModelPermissions {
1373 public_access: true,
1374 allowed_packages: vec![],
1375 required_permissions: vec![],
1376 access_level: AccessLevel::Public,
1377 },
1378 created_at: 1000,
1379 modified_at: 1000,
1380 };
1381
1382 assert!(provider.validate_model_info(&model).is_ok());
1383 let _ = std::fs::remove_file(&file_path);
1384 }
1385
1386 #[test]
1387 fn test_query_params_with_no_filters() {
1388 let params = QueryParams {
1389 model_type: None,
1390 name_filter: None,
1391 version_filter: None,
1392 tags: vec![],
1393 limit: None,
1394 offset: None,
1395 sort_by: None,
1396 };
1397 assert!(params.model_type.is_none());
1398 assert!(params.tags.is_empty());
1399 }
1400
1401 #[test]
1402 fn test_query_params_with_limit() {
1403 let params = QueryParams {
1404 model_type: None,
1405 name_filter: None,
1406 version_filter: None,
1407 tags: vec![],
1408 limit: Some(50),
1409 offset: Some(10),
1410 sort_by: Some(SortOrder::CreatedAt),
1411 };
1412 assert_eq!(params.limit, Some(50));
1413 assert_eq!(params.offset, Some(10));
1414 }
1415
1416 #[test]
1417 fn test_model_metadata_optional_fields() {
1418 let metadata = ModelMetadata {
1419 description: "Minimal model".to_string(),
1420 architecture: "CNN".to_string(),
1421 dataset: None,
1422 accuracy: None,
1423 latency_ms: None,
1424 memory_mb: None,
1425 tags: vec![],
1426 };
1427 assert!(metadata.dataset.is_none());
1428 assert!(metadata.accuracy.is_none());
1429 }
1430
1431 #[test]
1432 fn test_model_permissions_private() {
1433 let perms = ModelPermissions {
1434 public_access: false,
1435 allowed_packages: vec!["com.example.app".to_string()],
1436 required_permissions: vec!["READ_MODELS".to_string()],
1437 access_level: AccessLevel::Private,
1438 };
1439 assert!(!perms.public_access);
1440 assert_eq!(perms.allowed_packages.len(), 1);
1441 }
1442
1443 #[test]
1444 fn test_model_stream_progress() {
1445 let dir = std::env::temp_dir();
1452 let file_path = dir.join(format!(
1453 "trustformers_mobile_stream_test_{}.bin",
1454 std::process::id()
1455 ));
1456 let contents: Vec<u8> = (0..5u8).map(|b| b * 37 + 1).collect(); std::fs::write(&file_path, &contents).expect("write temp model file");
1458
1459 let model_info = ModelInfo {
1460 id: "stream_test".to_string(),
1461 name: "Stream Test Model".to_string(),
1462 version: "1.0".to_string(),
1463 model_type: ModelType::Transformer,
1464 file_path: file_path.clone(),
1465 size_bytes: contents.len() as u64,
1466 metadata: ModelMetadata {
1467 description: "Test".to_string(),
1468 architecture: "Transformer".to_string(),
1469 dataset: None,
1470 accuracy: None,
1471 latency_ms: None,
1472 memory_mb: None,
1473 tags: vec![],
1474 },
1475 permissions: ModelPermissions {
1476 public_access: true,
1477 allowed_packages: vec![],
1478 required_permissions: vec![],
1479 access_level: AccessLevel::Public,
1480 },
1481 created_at: 0,
1482 modified_at: 0,
1483 };
1484
1485 let mut stream = ModelStream::new(model_info, CompressionAlgorithm::Gzip)
1486 .expect("ModelStream::new should succeed for a real file");
1487 stream.chunk_size = 2;
1488 assert_eq!(stream.progress(), 0.0);
1489
1490 let mut read_back = Vec::new();
1491 while let Some(chunk) = stream.read_chunk().expect("read_chunk should succeed") {
1492 read_back.extend_from_slice(&chunk);
1493 }
1494 assert_eq!(
1495 read_back, contents,
1496 "streamed bytes must match the real file contents"
1497 );
1498 assert_eq!(stream.progress(), 1.0);
1499
1500 let _ = std::fs::remove_file(&file_path);
1501 }
1502
1503 #[test]
1504 fn test_usage_stats_default() {
1505 let stats = UsageStats::new();
1506 assert_eq!(stats.total_accesses, 0);
1507 assert_eq!(stats.successful_accesses, 0);
1508 assert_eq!(stats.failed_accesses, 0);
1509 }
1510}