< Summary

Information
Class: InferenceEngine.Core.ModelProviders.DownloadingModelProvider
Assembly: InferenceEngine.Core
File(s): /home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Core/ModelProviders/DownloadingModelProvider.cs
Line coverage
98%
Covered lines: 130
Uncovered lines: 2
Coverable lines: 132
Total lines: 310
Line coverage: 98.4%
Branch coverage
95%
Covered branches: 67
Total branches: 70
Branch coverage: 95.7%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%1212100%
GetModelPathAsync()83.33%66100%
DownloadModelAsync()100%1616100%
ComputeFileSha256Async()100%22100%
CreateHttpClient()100%11100%
ValidateModelName(...)93.75%161688.23%
ValidateCacheDirectory(...)87.5%88100%
ValidateSha256(...)100%88100%
DeleteFileBestEffort(...)100%22100%
GetDefaultCacheDirectory()100%11100%

File(s)

/home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Core/ModelProviders/DownloadingModelProvider.cs

#LineLine coverage
 1using System;
 2using System.IO;
 3using System.Net.Http;
 4using System.Security.Cryptography;
 5using System.Text;
 6using System.Threading;
 7using System.Threading.Tasks;
 8using Microsoft.Extensions.Logging;
 9using Microsoft.Extensions.Logging.Abstractions;
 10
 11namespace InferenceEngine.Core.ModelProviders
 12{
 13    /// <summary>
 14    /// Model provider that downloads models from URLs with local caching.
 15    /// If the model already exists in the cache, returns the cached path immediately.
 16    /// Downloads are hardened (security assessment MEDIUM-1): model names are validated
 17    /// against path traversal, files are downloaded atomically via a temp file, an optional
 18    /// SHA-256 checksum is enforced, a size cap aborts runaway downloads, and redirects
 19    /// are capped.
 20    /// </summary>
 21    public class DownloadingModelProvider : IModelProvider
 22    {
 23        /// <summary>Default cap applied when <c>maxDownloadBytes</c> is not specified (2 GiB).</summary>
 24        public const long DefaultMaxDownloadBytes = 2L * 1024 * 1024 * 1024;
 25
 26        private const int MaxAutomaticRedirections = 5;
 27
 28        private readonly string _modelName;
 29        private readonly string[] _downloadUrls;
 30        private readonly string _cacheDirectory;
 31        private readonly string? _expectedSha256;
 32        private readonly long _maxDownloadBytes;
 33        private readonly ILogger _logger;
 34        private readonly HttpClient _http;
 135        private static readonly HttpClient DefaultHttp = CreateHttpClient();
 36
 37        /// <summary>
 38        /// Creates a provider that downloads models from URLs with caching.
 39        /// </summary>
 40        /// <param name="modelName">Name of the model file (e.g., "yolov8n.onnx"). Must be a plain
 41        /// file name: directory separators, rooted paths, ".." segments, and invalid filename
 42        /// characters are rejected.</param>
 43        /// <param name="downloadUrls">One or more URLs to try downloading from (tried in order)</param>
 44        /// <param name="cacheDirectory">Directory to cache downloaded models. Defaults to local app data.</param>
 45        /// <param name="logger">Optional logger</param>
 46        /// <param name="sha256">
 47        /// Optional expected SHA-256 of the model file as 64 lowercase hex characters. When set, the
 48        /// downloaded file is verified against it and a mismatch rejects (and deletes) the download.
 49        /// When null, the download is accepted but logged as unverified.
 50        /// </param>
 51        /// <param name="maxDownloadBytes">
 52        /// Maximum allowed download size in bytes (validated against Content-Length and the running
 53        /// byte count). Must be positive; defaults to <see cref="DefaultMaxDownloadBytes"/> (2 GiB).
 54        /// </param>
 55        /// <param name="httpClient">Optional HTTP client to use (mainly for tests). Defaults to a
 56        /// shared client with automatic redirects capped at 5.</param>
 57        /// <exception cref="ArgumentNullException">A required argument is null.</exception>
 58        /// <exception cref="ArgumentException">
 59        /// <paramref name="modelName"/> contains path traversal or invalid characters, no download
 60        /// URL is provided, <paramref name="sha256"/> is malformed, or
 61        /// <paramref name="maxDownloadBytes"/> is not positive.
 62        /// </exception>
 4663        public DownloadingModelProvider(
 4664            string modelName,
 4665            string[] downloadUrls,
 4666            string? cacheDirectory = null,
 4667            ILogger? logger = null,
 4668            string? sha256 = null,
 4669            long maxDownloadBytes = DefaultMaxDownloadBytes,
 4670            HttpClient? httpClient = null)
 71        {
 4672            _modelName = ValidateModelName(modelName);
 3573            _downloadUrls = downloadUrls ?? throw new ArgumentNullException(nameof(downloadUrls));
 3474            _cacheDirectory = ValidateCacheDirectory(cacheDirectory ?? GetDefaultCacheDirectory());
 3175            _expectedSha256 = ValidateSha256(sha256);
 2976            _maxDownloadBytes = maxDownloadBytes > 0
 2977                ? maxDownloadBytes
 2978                : throw new ArgumentException("Maximum download size must be positive.", nameof(maxDownloadBytes));
 2779            _logger = logger ?? NullLogger.Instance;
 2780            _http = httpClient ?? DefaultHttp;
 81
 2782            if (_downloadUrls.Length == 0)
 83            {
 184                throw new ArgumentException("At least one download URL must be provided", nameof(downloadUrls));
 85            }
 2686        }
 87
 88        /// <inheritdoc />
 89        public async Task<string> GetModelPathAsync(CancellationToken cancellationToken = default)
 90        {
 2691            Directory.CreateDirectory(_cacheDirectory);
 2692            var modelPath = Path.Combine(_cacheDirectory, _modelName);
 2693            var tempPath = modelPath + ".downloading";
 94
 95            // Return cached model if available
 2696            if (File.Exists(modelPath))
 97            {
 698                _logger.LogDebug("Using cached model: {ModelPath}", modelPath);
 699                return modelPath;
 100            }
 101
 20102            _logger.LogInformation("Model not found in cache. Downloading {ModelName}...", _modelName);
 103
 104            // Try each URL until one succeeds
 20105            Exception? lastError = null;
 77106            foreach (var url in _downloadUrls)
 107            {
 108                try
 109                {
 23110                    _logger.LogDebug("Attempting download from: {Url}", url);
 23111                    await DownloadModelAsync(url, tempPath, cancellationToken).ConfigureAwait(false);
 9112                    File.Move(tempPath, modelPath, overwrite: true);
 9113                    _logger.LogInformation("Successfully downloaded {ModelName} from {Url}", _modelName, url);
 9114                    return modelPath;
 115                }
 14116                catch (Exception ex)
 117                {
 14118                    DeleteFileBestEffort(tempPath);
 14119                    lastError = ex;
 14120                    _logger.LogWarning("Failed to download from {Url}: {Error}", url, ex.Message);
 121                    // Try next URL
 14122                }
 14123            }
 124
 11125            throw new InvalidOperationException(
 11126                $"Failed to download model '{_modelName}' from all sources. Last error: {lastError?.Message}",
 11127                lastError);
 15128        }
 129
 130        private async Task DownloadModelAsync(string url, string tempPath, CancellationToken ct)
 131        {
 23132            using var response = await _http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(
 17133            response.EnsureSuccessStatusCode();
 134
 14135            if (response.Content.Headers.ContentLength is long declared && declared > _maxDownloadBytes)
 136            {
 1137                throw new InvalidOperationException(
 1138                    $"Download from '{url}' declares {declared} bytes, which exceeds the maximum of {_maxDownloadBytes} 
 139            }
 140
 13141            await using var fs = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None);
 13142            await using var source = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
 143
 13144            var buffer = new byte[81920];
 13145            long total = 0;
 146            int read;
 5238147            while ((read = await source.ReadAsync(buffer.AsMemory(0, buffer.Length), ct).ConfigureAwait(false)) > 0)
 148            {
 5226149                total += read;
 5226150                if (total > _maxDownloadBytes)
 151                {
 1152                    throw new InvalidOperationException(
 1153                        $"Download from '{url}' exceeded the maximum of {_maxDownloadBytes} bytes.");
 154                }
 155
 5225156                await fs.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
 157            }
 158
 10159            if (_expectedSha256 is null)
 160            {
 8161                _logger.LogWarning(
 8162                    "Model '{ModelName}' downloaded from '{Url}' without integrity verification: no sha256 is configured
 8163                    _modelName, url);
 8164                return;
 165            }
 166
 2167            fs.Close();
 2168            var actual = await ComputeFileSha256Async(tempPath, ct).ConfigureAwait(false);
 2169            if (!string.Equals(actual, _expectedSha256, StringComparison.OrdinalIgnoreCase))
 170            {
 1171                throw new InvalidOperationException(
 1172                    $"SHA-256 mismatch for model '{_modelName}' downloaded from '{url}': " +
 1173                    $"expected {_expectedSha256}, got {actual}.");
 174            }
 175
 1176            _logger.LogInformation("SHA-256 verified for model '{ModelName}' downloaded from '{Url}'.", _modelName, url)
 9177        }
 178
 179        private static async Task<string> ComputeFileSha256Async(string path, CancellationToken ct)
 180        {
 2181            await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
 2182            using var sha = SHA256.Create();
 2183            var hash = await sha.ComputeHashAsync(stream, ct).ConfigureAwait(false);
 2184            var sb = new StringBuilder(hash.Length * 2);
 132185            foreach (var b in hash)
 186            {
 64187                sb.Append(b.ToString("x2"));
 188            }
 189
 2190            return sb.ToString();
 2191        }
 192
 193        private static HttpClient CreateHttpClient()
 194        {
 1195            var handler = new HttpClientHandler
 1196            {
 1197                MaxAutomaticRedirections = MaxAutomaticRedirections,
 1198                AllowAutoRedirect = true,
 1199            };
 1200            return new HttpClient(handler);
 201        }
 202
 203        private static string ValidateModelName(string? modelName)
 204        {
 46205            if (modelName is null)
 206            {
 1207                throw new ArgumentNullException(nameof(modelName));
 208            }
 209
 45210            if (modelName.Length == 0)
 211            {
 1212                throw new ArgumentException("Model name must not be empty.", nameof(modelName));
 213            }
 214
 44215            if (modelName.IndexOf('/') >= 0 || modelName.IndexOf('\\') >= 0)
 216            {
 6217                throw new ArgumentException(
 6218                    $"Model name '{modelName}' must not contain directory separators.", nameof(modelName));
 219            }
 220
 38221            if (Path.IsPathRooted(modelName))
 222            {
 0223                throw new ArgumentException(
 0224                    $"Model name '{modelName}' must be a plain file name, not a rooted path.", nameof(modelName));
 225            }
 226
 38227            if (modelName == ".." || modelName.Contains("..", StringComparison.Ordinal))
 228            {
 2229                throw new ArgumentException(
 2230                    $"Model name '{modelName}' must not contain '..' segments.", nameof(modelName));
 231            }
 232
 36233            if (modelName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
 234            {
 1235                throw new ArgumentException(
 1236                    $"Model name '{modelName}' contains invalid filename characters.", nameof(modelName));
 237            }
 238
 35239            return modelName;
 240        }
 241
 242        private static string ValidateCacheDirectory(string cacheDirectory)
 243        {
 34244            if (string.IsNullOrWhiteSpace(cacheDirectory))
 245            {
 1246                throw new ArgumentException("Cache directory must not be empty or whitespace.", nameof(cacheDirectory));
 247            }
 248
 33249            if (cacheDirectory == ".." || cacheDirectory.Contains("..", StringComparison.Ordinal))
 250            {
 1251                throw new ArgumentException(
 1252                    $"Cache directory '{cacheDirectory}' must not contain '..' segments.", nameof(cacheDirectory));
 253            }
 254
 32255            if (cacheDirectory.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
 256            {
 1257                throw new ArgumentException(
 1258                    $"Cache directory '{cacheDirectory}' contains invalid path characters.", nameof(cacheDirectory));
 259            }
 260
 31261            return cacheDirectory;
 262        }
 263
 264        private static string? ValidateSha256(string? sha256)
 265        {
 31266            if (sha256 is null)
 267            {
 27268                return null;
 269            }
 270
 4271            if (sha256.Length != 64)
 272            {
 1273                throw new ArgumentException("sha256 must be exactly 64 hex characters.", nameof(sha256));
 274            }
 275
 263276            foreach (var c in sha256)
 277            {
 129278                if (!Uri.IsHexDigit(c))
 279                {
 1280                    throw new ArgumentException("sha256 must contain only hex characters.", nameof(sha256));
 281                }
 282            }
 283
 2284            return sha256.ToLowerInvariant();
 285        }
 286
 287        private void DeleteFileBestEffort(string path)
 288        {
 289            try
 290            {
 14291                if (File.Exists(path))
 292                {
 4293                    File.Delete(path);
 294                }
 13295            }
 1296            catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
 297            {
 1298                _logger.LogWarning(ex, "Failed to delete temporary download file '{Path}'.", path);
 1299            }
 14300        }
 301
 302        private static string GetDefaultCacheDirectory()
 303        {
 1304            return Path.Combine(
 1305                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
 1306                "InferenceEngine",
 1307                "Models");
 308        }
 309    }
 310}