iron-shell 14.0.2

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
use crate::ai_api::{
    models::*,
    storage::{validate_model_id, ModelStorage},
};
use anyhow::Result;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use tokio::io::AsyncWriteExt;
use url::Url;

/// The largest single file the downloader writes. Model weights run to
/// hundreds of gigabytes, so this is not a size policy; it is the bound on a
/// server that never ends its stream, which would otherwise fill the disk.
pub const MODEL_FILE_MAX: u64 = 512 * 1024 * 1024 * 1024;

/// Model downloader for Hugging Face and other sources
pub struct ModelDownloader {
    client: Client,
    storage: ModelStorage,
    cache_dir: std::path::PathBuf,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadRequest {
    pub model_id: String,
    pub source: ModelSource,
    pub format_preference: Option<ModelFormat>,
    pub quantization: Option<String>,
    pub validate_checksum: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadProgress {
    pub model_id: String,
    pub stage: DownloadStage,
    pub progress: f64, // 0.0 to 1.0
    pub bytes_downloaded: u64,
    pub total_bytes: Option<u64>,
    pub speed_bps: Option<u64>,
    pub eta_seconds: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DownloadStage {
    Initializing,
    DownloadingMetadata,
    DownloadingModel,
    ValidatingChecksum,
    ExtractingFiles,
    StoringModel,
    Complete,
    Failed(String),
}

/// Hugging Face model info from API
#[derive(Debug, Clone, Deserialize)]
pub struct HuggingFaceModelInfo {
    pub id: String,
    pub sha: String,
    pub downloads: u64,
    pub likes: u64,
    pub tags: Vec<String>,
    pub siblings: Vec<HuggingFaceFile>,
    pub library_name: Option<String>,
    pub pipeline_tag: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct HuggingFaceFile {
    pub rfilename: String,
    pub size: Option<u64>,
    pub blob_id: String,
}

impl ModelDownloader {
    pub fn new(storage: ModelStorage) -> Result<Self> {
        let cache_dir = storage.get_cache_dir().to_path_buf();
        fs::create_dir_all(&cache_dir)?;

        // SECURITY FIX (LOW-002): Use secure HTTP client with timeouts
        crate::tls::install_provider();
        let client =
            crate::security::create_secure_async_client().unwrap_or_else(|_| Client::new());

        Ok(Self {
            client,
            storage,
            cache_dir,
        })
    }

    /// Download a model from Hugging Face
    pub async fn download_model(&mut self, request: DownloadRequest) -> Result<LocalModelMetadata> {
        // The id becomes a file name and a metadata path, so it is checked
        // before any request is made or any file is written.
        validate_model_id(&request.model_id)?;
        match &request.source.origin {
            origin if origin == "huggingface" => self.download_huggingface_model(request).await,
            origin if origin == "url" => self.download_from_url(request).await,
            _ => Err(anyhow::anyhow!(
                "Unsupported model source: {}",
                request.source.origin
            )),
        }
    }

    /// Download model from Hugging Face
    async fn download_huggingface_model(
        &mut self,
        request: DownloadRequest,
    ) -> Result<LocalModelMetadata> {
        let model_id = &request.model_id;

        // Get model info from Hugging Face API
        let model_info = self.fetch_huggingface_model_info(model_id).await?;

        // Determine which files to download based on format preference
        let files_to_download = self.select_files_to_download(&model_info, &request)?;

        if files_to_download.is_empty() {
            return Err(anyhow::anyhow!(
                "No suitable files found for model {}",
                model_id
            ));
        }

        // Create temporary directory for download
        let temp_dir = self
            .cache_dir
            .join(format!("download_{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&temp_dir)?;

        let mut downloaded_files = Vec::new();
        let mut total_size = 0u64;

        // Download all required files
        for file in &files_to_download {
            let file_url = format!(
                "https://huggingface.co/{}/resolve/main/{}",
                model_id, file.rfilename
            );

            // The name comes from the remote listing, so it is checked before it
            // becomes a path: `..` in it would write outside the temp directory.
            check_listed_file_name(&file.rfilename)?;
            let local_path = temp_dir.join(&file.rfilename);

            // Create subdirectories if needed
            if let Some(parent) = local_path.parent() {
                fs::create_dir_all(parent)?;
            }

            let downloaded_size = self.download_file(&file_url, &local_path).await?;
            total_size += downloaded_size;

            downloaded_files.push((file.clone(), local_path));
        }

        // Determine the main model file and format
        let (_main_file, main_path, format) = self.identify_main_model_file(&downloaded_files)?;

        // Hash the main model file in chunks; it was read whole into memory.
        let checksum = crate::ai_api::storage::sha256_file(&main_path)?;

        // Create metadata
        let metadata = LocalModelMetadata {
            id: model_id.clone(),
            name: model_id.clone(),
            description: Some(format!("Downloaded from Hugging Face: {}", model_id)),
            version: model_info.sha.clone(),
            format,
            file_path: String::new(), // Will be set by storage
            config_path: self.find_config_file(&downloaded_files),
            tokenizer_path: self.find_tokenizer_file(&downloaded_files),
            size_bytes: total_size,
            sha256: checksum,
            downloaded_at: chrono::Utc::now(),
            last_used: None,
            usage_count: 0,
            capabilities: self.infer_capabilities(&model_info),
            parameters: self.extract_parameters(&model_info),
            source: ModelSource {
                origin: "huggingface".to_string(),
                url: Some(format!("https://huggingface.co/{}", model_id)),
                repository: Some(model_id.clone()),
                commit: Some(model_info.sha),
                license: None, // TODO: Extract from model card
            },
        };

        // Store the model
        self.storage
            .store_model_file(&main_path, metadata.clone())
            .await?;

        // Copy additional files to storage if needed
        self.store_additional_files(&downloaded_files, &metadata)
            .await?;

        // Clean up temporary directory
        if fs::remove_dir_all(&temp_dir).is_err() {
            // Log warning but don't fail
        }

        Ok(metadata)
    }

    /// Download model from a direct URL
    async fn download_from_url(&mut self, request: DownloadRequest) -> Result<LocalModelMetadata> {
        let url = request
            .source
            .url
            .clone()
            .ok_or_else(|| anyhow::anyhow!("URL required for URL source"))?;

        // The first URL and every redirect hop must pass the same SSRF rules as
        // the other fetch builtins: no loopback, private or link-local target.
        // reqwest's default client follows redirects without looking at them,
        // so this download uses a client whose redirect policy checks each hop.
        crate::security::validate_http_url("download_model", &url)?;
        let client = url_download_client()?;

        let temp_path = self
            .cache_dir
            .join(format!("temp_{}", uuid::Uuid::new_v4()));
        let downloaded_size = download_capped(&client, &url, &temp_path, MODEL_FILE_MAX).await?;

        let checksum = crate::ai_api::storage::sha256_file(&temp_path)?;

        // Infer format from URL or filename
        let format = self.infer_format_from_url(&url)?;

        let metadata = LocalModelMetadata {
            id: request.model_id.clone(),
            name: request.model_id.clone(),
            description: Some(format!("Downloaded from URL: {}", url)),
            version: "1.0".to_string(),
            format,
            file_path: String::new(),
            config_path: None,
            tokenizer_path: None,
            size_bytes: downloaded_size,
            sha256: checksum,
            downloaded_at: chrono::Utc::now(),
            last_used: None,
            usage_count: 0,
            capabilities: ModelCapabilities {
                chat: true,
                completions: true,
                embeddings: false,
                image_generation: false,
                image_understanding: false,
                audio_generation: false,
                audio_understanding: false,
                video_understanding: false,
                function_calling: true,
                streaming: true,
            },
            parameters: HashMap::new(),
            source: request.source,
        };

        self.storage
            .store_model_file(&temp_path, metadata.clone())
            .await?;

        // Clean up temporary file
        if fs::remove_file(&temp_path).is_err() {
            // Log warning but don't fail
        }

        Ok(metadata)
    }

    /// Fetch model information from Hugging Face API
    async fn fetch_huggingface_model_info(&self, model_id: &str) -> Result<HuggingFaceModelInfo> {
        let url = format!("https://huggingface.co/api/models/{}", model_id);

        let response = self
            .client
            .get(&url)
            .header("User-Agent", "ai-model-api/1.0")
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Failed to fetch model info: HTTP {}",
                response.status()
            ));
        }

        let model_info: HuggingFaceModelInfo =
            crate::http_body::body_json_capped(response, crate::http_body::AI_BODY_MAX).await?;
        Ok(model_info)
    }

    /// Download a single file, at most MODEL_FILE_MAX bytes of it
    async fn download_file(&self, url: &str, local_path: &Path) -> Result<u64> {
        download_capped(&self.client, url, local_path, MODEL_FILE_MAX).await
    }

    /// Select which files to download based on preferences
    fn select_files_to_download(
        &self,
        model_info: &HuggingFaceModelInfo,
        request: &DownloadRequest,
    ) -> Result<Vec<HuggingFaceFile>> {
        let mut selected_files = Vec::new();

        // Priority order for different formats
        let format_extensions = match &request.format_preference {
            Some(ModelFormat::GGUF) => vec!["gguf"],
            Some(ModelFormat::SafeTensors) => vec!["safetensors"],
            Some(ModelFormat::PyTorch) => vec!["bin", "pt", "pth"],
            Some(ModelFormat::ONNX) => vec!["onnx"],
            _ => vec!["gguf", "safetensors", "bin", "pt", "onnx"], // Default priority
        };

        // Find model files
        for ext in &format_extensions {
            for file in &model_info.siblings {
                if file.rfilename.ends_with(&format!(".{}", ext)) {
                    // Prefer quantized versions if requested
                    if let Some(quant) = &request.quantization {
                        if file.rfilename.contains(quant) {
                            selected_files.push(file.clone());
                            break;
                        }
                    } else {
                        selected_files.push(file.clone());
                        break;
                    }
                }
            }
            if !selected_files.is_empty() {
                break;
            }
        }

        // Always include config and tokenizer files
        for file in &model_info.siblings {
            if file.rfilename == "config.json"
                || file.rfilename == "tokenizer.json"
                || file.rfilename == "tokenizer_config.json"
                || file.rfilename.starts_with("tokenizer")
            {
                selected_files.push(file.clone());
            }
        }

        Ok(selected_files)
    }

    /// Identify the main model file from downloaded files
    fn identify_main_model_file(
        &self,
        files: &[(HuggingFaceFile, std::path::PathBuf)],
    ) -> Result<(HuggingFaceFile, std::path::PathBuf, ModelFormat)> {
        for (file, path) in files {
            if file.rfilename.ends_with(".gguf") {
                return Ok((file.clone(), path.clone(), ModelFormat::GGUF));
            }
        }

        for (file, path) in files {
            if file.rfilename.ends_with(".safetensors") {
                return Ok((file.clone(), path.clone(), ModelFormat::SafeTensors));
            }
        }

        for (file, path) in files {
            if file.rfilename.ends_with(".bin") || file.rfilename.ends_with(".pt") {
                return Ok((file.clone(), path.clone(), ModelFormat::PyTorch));
            }
        }

        Err(anyhow::anyhow!("No suitable model file found"))
    }

    /// Find config file path
    fn find_config_file(&self, files: &[(HuggingFaceFile, std::path::PathBuf)]) -> Option<String> {
        for (file, path) in files {
            if file.rfilename == "config.json" {
                return Some(path.to_string_lossy().to_string());
            }
        }
        None
    }

    /// Find tokenizer file path
    fn find_tokenizer_file(
        &self,
        files: &[(HuggingFaceFile, std::path::PathBuf)],
    ) -> Option<String> {
        for (file, path) in files {
            if file.rfilename == "tokenizer.json" {
                return Some(path.to_string_lossy().to_string());
            }
        }
        None
    }

    /// Store additional files alongside the main model
    async fn store_additional_files(
        &self,
        _files: &[(HuggingFaceFile, std::path::PathBuf)],
        _metadata: &LocalModelMetadata,
    ) -> Result<()> {
        // TODO: Implement storing additional files
        // This would copy config.json, tokenizer files, etc. to the model directory
        Ok(())
    }

    /// Infer model capabilities from Hugging Face metadata
    fn infer_capabilities(&self, model_info: &HuggingFaceModelInfo) -> ModelCapabilities {
        let mut capabilities = ModelCapabilities {
            chat: false,
            completions: true,
            embeddings: false,
            image_generation: false,
            image_understanding: false,
            audio_generation: false,
            audio_understanding: false,
            video_understanding: false,
            function_calling: false,
            streaming: true,
        };

        // Infer from tags and pipeline_tag
        if let Some(pipeline) = &model_info.pipeline_tag {
            match pipeline.as_str() {
                "text-generation" => {
                    capabilities.chat = true;
                    capabilities.completions = true;
                }
                "feature-extraction" | "sentence-similarity" => {
                    capabilities.embeddings = true;
                }
                "text-to-image" => {
                    capabilities.image_generation = true;
                }
                "image-to-text" => {
                    capabilities.image_understanding = true;
                }
                _ => {}
            }
        }

        // Check tags for additional capabilities
        for tag in &model_info.tags {
            match tag.as_str() {
                "conversational" | "chat" => capabilities.chat = true,
                "function-calling" => capabilities.function_calling = true,
                "multimodal" => capabilities.image_understanding = true,
                _ => {}
            }
        }

        capabilities
    }

    /// Extract model parameters from metadata
    fn extract_parameters(
        &self,
        model_info: &HuggingFaceModelInfo,
    ) -> HashMap<String, serde_json::Value> {
        let mut params = HashMap::new();

        params.insert(
            "downloads".to_string(),
            serde_json::Value::Number(model_info.downloads.into()),
        );
        params.insert(
            "likes".to_string(),
            serde_json::Value::Number(model_info.likes.into()),
        );

        if let Some(library) = &model_info.library_name {
            params.insert(
                "library_name".to_string(),
                serde_json::Value::String(library.clone()),
            );
        }

        if let Some(pipeline) = &model_info.pipeline_tag {
            params.insert(
                "pipeline_tag".to_string(),
                serde_json::Value::String(pipeline.clone()),
            );
        }

        params.insert(
            "tags".to_string(),
            serde_json::Value::Array(
                model_info
                    .tags
                    .iter()
                    .map(|t| serde_json::Value::String(t.clone()))
                    .collect(),
            ),
        );

        params
    }

    /// Infer format from URL
    fn infer_format_from_url(&self, url: &str) -> Result<ModelFormat> {
        let url_parsed = Url::parse(url)?;
        let path = url_parsed.path();

        if path.ends_with(".gguf") {
            Ok(ModelFormat::GGUF)
        } else if path.ends_with(".safetensors") {
            Ok(ModelFormat::SafeTensors)
        } else if path.ends_with(".bin") || path.ends_with(".pt") || path.ends_with(".pth") {
            Ok(ModelFormat::PyTorch)
        } else if path.ends_with(".onnx") {
            Ok(ModelFormat::ONNX)
        } else {
            Err(anyhow::anyhow!("Cannot infer format from URL: {}", url))
        }
    }

    /// List available models from various sources
    pub async fn search_models(&self, query: &str, source: &str) -> Result<Vec<ModelSearchResult>> {
        match source {
            "huggingface" => self.search_huggingface_models(query).await,
            _ => Err(anyhow::anyhow!("Unsupported search source: {}", source)),
        }
    }

    /// Search Hugging Face models
    async fn search_huggingface_models(&self, query: &str) -> Result<Vec<ModelSearchResult>> {
        let url = format!(
            "https://huggingface.co/api/models?search={}&limit=20",
            urlencoding::encode(query)
        );

        let response = self
            .client
            .get(&url)
            .header("User-Agent", "ai-model-api/1.0")
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(anyhow::anyhow!("Search failed: HTTP {}", response.status()));
        }

        let models: Vec<HuggingFaceModelInfo> =
            crate::http_body::body_json_capped(response, crate::http_body::AI_BODY_MAX).await?;

        let results = models
            .into_iter()
            .map(|model| ModelSearchResult {
                id: model.id.clone(),
                name: model.id,
                description: format!("Hugging Face model with {} downloads", model.downloads),
                source: "huggingface".to_string(),
                downloads: Some(model.downloads),
                likes: Some(model.likes),
                tags: model.tags,
                library_name: model.library_name,
                pipeline_tag: model.pipeline_tag,
            })
            .collect();

        Ok(results)
    }
}

/// The client for a direct-URL download. It has the timeouts of the shared
/// secure client, and every redirect target must pass `validate_http_url`
/// before it is followed, with the same ten-hop ceiling reqwest uses.
fn url_download_client() -> Result<Client> {
    crate::tls::install_provider();
    Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .connect_timeout(std::time::Duration::from_secs(10))
        .redirect(reqwest::redirect::Policy::custom(|attempt| {
            if attempt.previous().len() >= 10 {
                return attempt.error("too many redirects");
            }
            let next = attempt.url().to_string();
            match redirect_hop_refusal(&next) {
                None => attempt.follow(),
                Some(reason) => attempt.error(reason),
            }
        }))
        .build()
        .map_err(Into::into)
}

/// The decision for one redirect hop: `None` to follow it, or the reason to
/// refuse it. It applies the same URL check as the first URL, so a hop to a
/// loopback, private, link-local or metadata address is refused.
fn redirect_hop_refusal(next: &str) -> Option<String> {
    match crate::security::validate_http_url("download_model", next) {
        Ok(_) => None,
        Err(e) => Some(format!("redirect to {next} refused: {e}")),
    }
}

/// Streams `url` into `local_path`, refusing a declared or actual length over
/// `max`. On any failure the partial file is removed, since a truncated file
/// would be taken for a model on the next run.
async fn download_capped(client: &Client, url: &str, local_path: &Path, max: u64) -> Result<u64> {
    let response = client
        .get(url)
        .header("User-Agent", "ai-model-api/1.0")
        .send()
        .await?;

    if !response.status().is_success() {
        return Err(anyhow::anyhow!(
            "Failed to download file: HTTP {}",
            response.status()
        ));
    }

    if let Some(declared) = response.content_length() {
        if declared > max {
            return Err(too_large(url, max));
        }
    }
    let mut file = tokio::fs::File::create(local_path).await?;
    let written = copy_capped(response, &mut file, url, max).await;
    drop(file);
    if written.is_err() {
        let _ = tokio::fs::remove_file(local_path).await;
    }
    written
}

async fn copy_capped(
    response: reqwest::Response,
    file: &mut tokio::fs::File,
    url: &str,
    max: u64,
) -> Result<u64> {
    let mut downloaded = 0u64;
    let mut stream = response.bytes_stream();
    use futures_util::StreamExt;

    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        downloaded += chunk.len() as u64;
        if downloaded > max {
            return Err(too_large(url, max));
        }
        file.write_all(&chunk).await?;
    }

    file.flush().await?;
    Ok(downloaded)
}

/// Refuse a file name from a remote listing unless it stays under the directory
/// it is joined to: only plain path segments, separated by `/`.
fn check_listed_file_name(name: &str) -> Result<()> {
    let plain = !name.is_empty()
        && !name.contains(['\\', ':', '\0'])
        && name
            .split('/')
            .all(|part| !part.is_empty() && part != "." && part != "..");
    if plain {
        Ok(())
    } else {
        anyhow::bail!("the model listing names an unsafe file: {name:?}")
    }
}

fn too_large(url: &str, max: u64) -> anyhow::Error {
    crate::safety::budget_exceeded(
        "model_download",
        format!("{url} is larger than {max} bytes"),
        "download the file by other means if it really is this large",
    )
}

#[cfg(test)]
mod listed_file_name_tests {
    use super::check_listed_file_name;

    #[test]
    fn a_listed_name_cannot_leave_the_directory() {
        for bad in [
            "",
            "..",
            "../x",
            "a/../../x",
            "/etc/x",
            "a//b",
            "./a",
            "a\\..\\b",
            "C:x",
            "C:/x",
        ] {
            assert!(
                check_listed_file_name(bad).is_err(),
                "{bad:?} must be refused"
            );
        }
        for good in [
            "model.gguf",
            "sub/dir/model-00001.safetensors",
            "a b.bin",
            "a..b",
        ] {
            assert!(check_listed_file_name(good).is_ok(), "{good:?} must pass");
        }
    }
}

#[cfg(test)]
mod redirect_hop_tests {
    use super::redirect_hop_refusal;

    // Only the decision is tested here: no hop is followed, so nothing
    // connects. These hosts are refused by the address check itself; the
    // test seam that exempts loopback is not set in this test binary.
    #[test]
    fn a_hop_to_an_internal_address_is_refused() {
        for next in [
            "http://127.0.0.1/model.gguf",
            "http://127.0.0.1:8080/",
            "http://localhost/",
            "http://[::1]/",
            "http://[::ffff:127.0.0.1]/",
            "http://169.254.169.254/latest/meta-data/",
            "http://[::ffff:169.254.169.254]/",
            "http://10.0.0.5/",
            "http://192.168.1.1/",
            "http://0.0.0.0/",
            "file:///etc/passwd",
        ] {
            let reason =
                redirect_hop_refusal(next).unwrap_or_else(|| panic!("{next} must be refused"));
            assert!(
                reason.starts_with(&format!("redirect to {next} refused")),
                "{reason}"
            );
        }
    }

    #[test]
    fn a_hop_to_a_public_address_is_followed() {
        // An IP literal is checked without a lookup, and nothing is connected.
        assert_eq!(
            redirect_hop_refusal("https://93.184.216.34/model.safetensors"),
            None
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};

    /// Serves one HTTP response on a local port and returns its URL.
    fn serve_once(head: String, body: Vec<u8>) -> String {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((mut conn, _)) = listener.accept() {
                let mut buf = [0u8; 4096];
                let _ = conn.read(&mut buf);
                let _ = conn.write_all(head.as_bytes());
                let _ = conn.write_all(&body);
            }
        });
        format!("http://{addr}/model.bin")
    }

    fn scratch(name: &str) -> std::path::PathBuf {
        let d = std::env::temp_dir().join(format!("ae-dlcap-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        d.join(name)
    }

    fn is_budget(e: &anyhow::Error) -> bool {
        e.downcast_ref::<crate::safety::SafetyError>()
            .map(|s| s.code == crate::safety::ErrorCode::BudgetExceeded)
            .unwrap_or(false)
    }

    #[tokio::test]
    async fn a_file_past_the_cap_is_refused_and_leaves_nothing() {
        crate::tls::install_provider();
        let client = Client::new();

        // Declared too large: refused before a file is made.
        let url = serve_once(
            "HTTP/1.1 200 OK\r\nContent-Length: 64\r\nConnection: close\r\n\r\n".into(),
            vec![b'x'; 64],
        );
        let declared = scratch("declared.bin");
        let err = download_capped(&client, &url, &declared, 16)
            .await
            .unwrap_err();
        assert!(is_budget(&err), "{err:#}");
        assert!(!declared.exists());

        // No length declared: refused mid-stream, and the partial file removed.
        let url = serve_once(
            "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".into(),
            vec![b'x'; 64],
        );
        let streamed = scratch("streamed.bin");
        let err = download_capped(&client, &url, &streamed, 16)
            .await
            .unwrap_err();
        assert!(is_budget(&err), "{err:#}");
        assert!(!streamed.exists());

        // Within the cap: written whole.
        let url = serve_once(
            "HTTP/1.1 200 OK\r\nContent-Length: 8\r\nConnection: close\r\n\r\n".into(),
            vec![b'y'; 8],
        );
        let fits = scratch("fits.bin");
        assert_eq!(download_capped(&client, &url, &fits, 16).await.unwrap(), 8);
        assert_eq!(std::fs::read(&fits).unwrap(), vec![b'y'; 8]);
        let _ = std::fs::remove_file(&fits);
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelSearchResult {
    pub id: String,
    pub name: String,
    pub description: String,
    pub source: String,
    pub downloads: Option<u64>,
    pub likes: Option<u64>,
    pub tags: Vec<String>,
    pub library_name: Option<String>,
    pub pipeline_tag: Option<String>,
}