diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs
new file mode 100644
index 00000000..aa1899b3
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
+using Lumina.Plugins.CoverArtArchive.Core;
+using Lumina.Plugins.CoverArtArchive.Core.Api;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using System;
+using System.Net.Http;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Common.DependencyInjection;
+
+///
+/// Utility class for registering the services of the Cover Art Archive artwork provider into the Dependency Injection container.
+///
+internal static class CoverArtArchiveServices
+{
+ ///
+ /// Registers the services of the Cover Art Archive artwork provider into the Dependency Injection container.
+ ///
+ /// The service collection to add the services to.
+ /// The unique identifier of the plugin that provides the artwork.
+ /// Action used to configure the .
+ /// The updated .
+ internal static IServiceCollection AddCoverArtArchiveArtworkProvider(this IServiceCollection services, Guid pluginId, Action? settingsCallback = null)
+ {
+ ArgumentNullException.ThrowIfNull(services);
+
+ // Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
+ services.TryAddScoped(serviceProvider =>
+ {
+ CoverArtArchiveSettingsDto defaults = new();
+ settingsCallback?.Invoke(defaults);
+
+ IPluginSettingsStore? settingsStore = serviceProvider.GetService();
+ return new CoverArtArchiveSettingsProvider(settingsStore, pluginId, defaults);
+ });
+
+ // The throttle must be process-wide, because the Cover Art Archive API enforces its request policy across all callers, not per scope.
+ services.TryAddSingleton();
+
+ // The response cache is process-wide, so that an entity shared by many items, like the release group shared by the releases of an album,
+ // is fetched only once during a run.
+ services.TryAddSingleton();
+
+ // Automatic redirects are disabled on purpose: the metadata endpoints answer with a temporary redirect to the Internet Archive, and the client
+ // follows that redirect itself, checking every hop against CoverArtArchiveHosts. Letting the primary handler follow redirects automatically
+ // would make it follow whatever Location the response carries, which is server controlled, and would bypass that host check, which is the SSRF
+ // control here; the base URL being a constant does not make the redirect target trustworthy.
+ services.AddHttpClient()
+ .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
+
+ // Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations.
+ services.AddKeyedTransient(pluginId);
+
+ return services;
+ }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponse.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponse.cs
new file mode 100644
index 00000000..3aa98afa
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponse.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for the artwork of a release or a release group from the Cover Art Archive API.
+///
+internal sealed record CoverArtArchiveArtworkResponse
+{
+ ///
+ /// Gets the images of the artwork. It is nullable because the deserializer writes a JSON null over the initializer, and may also contain null elements.
+ ///
+ [JsonPropertyName("images")]
+ public List? Images { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveImageResponse.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveImageResponse.cs
new file mode 100644
index 00000000..4d1a297c
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveImageResponse.cs
@@ -0,0 +1,49 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a single image of the artwork of a release or a release group from the Cover Art Archive API.
+///
+internal sealed record CoverArtArchiveImageResponse
+{
+ ///
+ /// Gets the URL of the full size image.
+ ///
+ [JsonPropertyName("image")]
+ public string? Image { get; init; }
+
+ ///
+ /// Gets the URL of the thumbnail of the image.
+ ///
+ [JsonPropertyName("thumbnail")]
+ public string? Thumbnail { get; init; }
+
+ ///
+ /// Gets the types of the image, like "Front", "Back", "Booklet", "Medium", "Tray", "Spine" or "Poster".
+ /// It is nullable because the deserializer writes a JSON null over the initializer, and may also contain null elements.
+ ///
+ [JsonPropertyName("types")]
+ public List? Types { get; init; }
+
+ ///
+ /// Gets a value indicating whether the image is the front cover.
+ ///
+ [JsonPropertyName("front")]
+ public bool IsFront { get; init; }
+
+ ///
+ /// Gets a value indicating whether the image is the back cover.
+ ///
+ [JsonPropertyName("back")]
+ public bool IsBack { get; init; }
+
+ ///
+ /// Gets the optional comment describing the image.
+ ///
+ [JsonPropertyName("comment")]
+ public string? Comment { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/DTO/Settings/CoverArtArchiveSettingsDto.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/DTO/Settings/CoverArtArchiveSettingsDto.cs
new file mode 100644
index 00000000..f9d5efe4
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/DTO/Settings/CoverArtArchiveSettingsDto.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
+
+///
+/// Data transfer object for the settings that configure the Cover Art Archive artwork plugin.
+///
+internal sealed class CoverArtArchiveSettingsDto
+{
+ ///
+ /// Gets or sets the user agent sent with every request to the Cover Art Archive API.
+ ///
+ public string UserAgent { get; set; } = "Lumina-CoverArtArchive/1.0";
+
+ ///
+ /// Gets or sets the contact email sent with every request to the Cover Art Archive API.
+ /// The MetaBrainz services expect a meaningful user agent that carries a way to contact its author.
+ ///
+ public string? ContactEmail { get; set; }
+
+ ///
+ /// Gets or sets the minimum interval between consecutive requests to the Cover Art Archive API, so that the public service is not overwhelmed.
+ ///
+ public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0);
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs
new file mode 100644
index 00000000..08cde755
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs
@@ -0,0 +1,256 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Core.Api;
+
+///
+/// HTTP client that calls the Cover Art Archive API and deserializes its JSON responses into typed response models.
+///
+internal sealed class CoverArtArchiveHttpClient
+{
+ private const string BASE_URL = "https://coverartarchive.org/";
+
+ // Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich.
+ private const int MAXIMUM_ATTEMPT_COUNT = 3;
+
+ // The metadata endpoints of the Cover Art Archive answer with a temporary redirect to the Internet Archive, so a bounded number of redirects is followed.
+ private const int MAXIMUM_REDIRECT_COUNT = 3;
+
+ // The delay requested by a rate limited response is honored, but only up to this many seconds, so a misbehaving server cannot stall the scan.
+ private const double MAXIMUM_RETRY_DELAY_SECONDS = 60;
+
+ private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web);
+
+ private readonly HttpClient _httpClient;
+ private readonly CoverArtArchiveSettingsProvider _settingsProvider;
+ private readonly CoverArtArchiveRequestThrottle _requestThrottle;
+ private readonly CoverArtArchiveResponseCache _responseCache;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The used to send requests to the Cover Art Archive API.
+ /// The provider of the settings that configure the Cover Art Archive API requests.
+ /// The process-wide throttle that spaces out the requests sent to the Cover Art Archive API.
+ /// The process-wide cache that avoids fetching the same entity more than once during a run.
+ public CoverArtArchiveHttpClient(HttpClient httpClient, CoverArtArchiveSettingsProvider settingsProvider, CoverArtArchiveRequestThrottle requestThrottle, CoverArtArchiveResponseCache responseCache)
+ {
+ _httpClient = httpClient;
+ _settingsProvider = settingsProvider;
+ _requestThrottle = requestThrottle;
+ _responseCache = responseCache;
+ }
+
+ ///
+ /// Gets the artwork of the release identified by .
+ ///
+ /// The MusicBrainz identifier of the release.
+ /// Cancellation token that can be used to stop the execution.
+ /// The artwork of the release, or when the release has no artwork.
+ public Task GetReleaseArtworkAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
+ {
+ return GetJsonOrNullAsync($"release/{musicBrainzReleaseId:D}", cancellationToken);
+ }
+
+ ///
+ /// Gets the artwork of the release group identified by .
+ ///
+ /// The MusicBrainz identifier of the release group.
+ /// Cancellation token that can be used to stop the execution.
+ /// The artwork of the release group, or when the release group has no artwork.
+ public Task GetReleaseGroupArtworkAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
+ {
+ return GetJsonOrNullAsync($"release-group/{musicBrainzReleaseGroupId:D}", cancellationToken);
+ }
+
+ ///
+ /// Gets the JSON resource at the given relative URL and deserializes it into .
+ ///
+ /// The type to deserialize the JSON response into.
+ /// The URL of the resource, relative to the base address.
+ /// Cancellation token that can be used to stop the execution.
+ /// The deserialized resource, or when the resource was not found.
+ private async Task GetJsonOrNullAsync(string relativeUrl, CancellationToken cancellationToken)
+ {
+ // A cached response, including a confirmed absence of artwork, removes the repeated lookups of the same entity, like the release group that the
+ // releases of an edition heavy library share, or the same library scanned again while the entry is still valid.
+ if (_responseCache.TryGet(relativeUrl, out string? cachedJson))
+ return string.IsNullOrEmpty(cachedJson) ? default : JsonSerializer.Deserialize(cachedJson, s_serializerOptions);
+
+ CoverArtArchiveSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
+
+ using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false);
+ // A 404 means the entity exists but has no artwork, which is a normal miss rather than an error, so it is reported as no result and cached as such.
+ if (response.StatusCode == HttpStatusCode.NotFound)
+ {
+ _responseCache.Set(relativeUrl, string.Empty);
+ return default;
+ }
+ response.EnsureSuccessStatusCode();
+
+ string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
+ TModel? model = JsonSerializer.Deserialize(json, s_serializerOptions);
+ _responseCache.Set(relativeUrl, json);
+ return model;
+ }
+
+ ///
+ /// Sends a GET request to the Cover Art Archive API, throttled to respect the configured minimum request interval. Transient failures and
+ /// rate limiting are retried, so a single hiccup does not surface as a failed resolution.
+ ///
+ /// The settings that configure the Cover Art Archive API requests.
+ /// The URL of the resource, relative to the base address.
+ /// Cancellation token that can be used to stop the execution.
+ /// The HTTP response message for the request.
+ private async Task SendAsync(CoverArtArchiveSettingsDto settings, string relativeUrl, CancellationToken cancellationToken)
+ {
+ EnsureRequestHeaders(settings);
+
+ Uri requestUri = new(new Uri(BASE_URL, UriKind.Absolute), relativeUrl);
+
+ // The metadata endpoints answer with a temporary redirect to the Internet Archive, so the redirect is followed explicitly, which keeps the
+ // automatic redirects disabled and confines the following to the hosts the Cover Art Archive is allowed to delegate its responses to.
+ for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++)
+ {
+ HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, cancellationToken).ConfigureAwait(false);
+
+ if (!IsRedirect(response.StatusCode) || response.Headers.Location is null)
+ return response;
+
+ Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location);
+ // The response of a redirect is not returned, so it must be disposed here to release its connection.
+ response.Dispose();
+
+ // A redirect that is not an absolute HTTPS URL, or that points to a host other than the Cover Art Archive or the Internet Archive, is refused,
+ // so a compromised or misbehaving endpoint cannot redirect the request to any other host.
+ if (redirectUri is null || redirectUri.Scheme != Uri.UriSchemeHttps || !CoverArtArchiveHosts.IsAllowed(redirectUri.Host))
+ throw new HttpRequestException($"The Cover Art Archive redirected the request to the disallowed host '{redirectUri?.Host}'.");
+
+ requestUri = redirectUri;
+ }
+
+ throw new HttpRequestException("The Cover Art Archive redirected the request too many times.");
+ }
+
+ ///
+ /// Sends a GET request to , throttled to respect the configured minimum request interval.
+ /// Transient failures and rate limiting are retried, so a single hiccup does not surface as a failed resolution.
+ ///
+ /// The settings that configure the Cover Art Archive API requests.
+ /// The absolute URI of the resource to request.
+ /// Cancellation token that can be used to stop the execution.
+ /// The HTTP response message for the request.
+ private async Task SendWithRetriesAsync(CoverArtArchiveSettingsDto settings, Uri requestUri, CancellationToken cancellationToken)
+ {
+ // A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every
+ // attempt, so that the retries of a failed request cannot burst past the rate limit of the public service.
+ for (int attempt = 1; ; attempt++)
+ {
+ await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false);
+
+ bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT;
+ HttpResponseMessage response;
+ try
+ {
+ HttpRequestMessage request = new(HttpMethod.Get, requestUri);
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
+ }
+ catch (HttpRequestException) when (!isLastAttempt)
+ {
+ await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500))
+ {
+ // The delay is read before the response is disposed, because a rate limited response tells the caller how long to wait.
+ TimeSpan retryDelay = GetRetryDelay(attempt, response);
+ // The response of a failed attempt is not returned, so it must be disposed here to release its connection.
+ response.Dispose();
+ await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ return response;
+ }
+ }
+
+ ///
+ /// Determines whether the provided status code is a redirect.
+ ///
+ /// The status code to check.
+ /// when the status code is a redirect, otherwise .
+ private static bool IsRedirect(HttpStatusCode statusCode)
+ {
+ return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther
+ or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect;
+ }
+
+ ///
+ /// Resolves the location of a redirect against the URI of the request it was returned for.
+ ///
+ /// The URI of the request the redirect was returned for.
+ /// The location of the redirect.
+ /// The absolute URI of the redirect, or when it could not be resolved.
+ private static Uri? ResolveRedirect(Uri requestUri, Uri location)
+ {
+ if (location.IsAbsoluteUri)
+ return location;
+ return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null;
+ }
+
+ ///
+ /// Gets the delay to wait before the next attempt, preferring the delay requested by the Cover Art Archive when it is provided.
+ ///
+ /// The one based number of the attempt that just failed.
+ /// The response of the failed attempt, when the failure was a response rather than a transport exception.
+ /// The delay to wait before the next attempt.
+ internal static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response)
+ {
+ // The delay requested by the response is preferred when it is provided, so the rate limit policy of the Cover Art Archive is honored.
+ if (response?.Headers.RetryAfter is { } retryAfter)
+ {
+ TimeSpan? requestedDelay = retryAfter.Delta;
+ if (requestedDelay is null && retryAfter.Date is DateTimeOffset date)
+ {
+ TimeSpan wait = date - DateTimeOffset.UtcNow;
+ if (wait > TimeSpan.Zero)
+ requestedDelay = wait;
+ }
+ if (requestedDelay is TimeSpan delay)
+ {
+ // A misbehaving server could ask for an extremely long delay, which would stall the scan until it is cancelled, so the wait is capped.
+ TimeSpan maximumDelay = TimeSpan.FromSeconds(MAXIMUM_RETRY_DELAY_SECONDS);
+ return delay > maximumDelay ? maximumDelay : delay;
+ }
+ }
+ return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
+ }
+
+ ///
+ /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set.
+ ///
+ /// The settings that configure the Cover Art Archive API requests.
+ private void EnsureRequestHeaders(CoverArtArchiveSettingsDto settings)
+ {
+ // The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once.
+ if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
+ {
+ string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail)
+ ? settings.UserAgent
+ : $"{settings.UserAgent} ( {settings.ContactEmail} )";
+ _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
+ }
+ }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveRequestThrottle.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveRequestThrottle.cs
new file mode 100644
index 00000000..d347f384
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveRequestThrottle.cs
@@ -0,0 +1,48 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Core.Api;
+
+///
+/// Class for spacing out the requests sent to the Cover Art Archive API, so the configured minimum request interval is respected across every caller in the process.
+///
+internal sealed class CoverArtArchiveRequestThrottle
+{
+ private readonly SemaphoreSlim _gate = new(1, 1);
+
+ // The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter which caller sends them.
+ private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
+
+ ///
+ /// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot.
+ ///
+ /// The minimum amount of time that must elapse between two consecutive requests.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that completes once the caller may send its request.
+ public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken)
+ {
+ // The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the
+ // previous reserved slot.
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ // A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it.
+ if (minimumRequestInterval > TimeSpan.Zero)
+ {
+ DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval;
+ TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
+ if (delay > TimeSpan.Zero)
+ await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
+ }
+
+ _lastRequestAt = DateTimeOffset.UtcNow;
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveResponseCache.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveResponseCache.cs
new file mode 100644
index 00000000..c3e407d5
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveResponseCache.cs
@@ -0,0 +1,141 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Core.Api;
+
+///
+/// In-memory cache of the responses returned by the Cover Art Archive API, keyed by the requested URL.
+/// It removes the repeated lookups of the same entity during a run, which is significant because the releases of an edition heavy library share their
+/// release groups, and it expires its entries after a bounded time.
+///
+internal sealed class CoverArtArchiveResponseCache
+{
+ ///
+ /// The maximum number of responses the cache keeps.
+ ///
+ internal const int MAXIMUM_ENTRY_COUNT = 20_000;
+
+ ///
+ /// The maximum total number of characters of the cached response bodies.
+ ///
+ internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000;
+
+ ///
+ /// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the
+ /// eviction from running on every write once a budget is reached.
+ ///
+ private const int TRIM_TARGET_PERCENT = 90;
+
+ private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15);
+
+ private readonly int _maximumEntryCount;
+ private readonly long _maximumCharacterCount;
+ private readonly TimeSpan _timeToLive;
+ private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal);
+
+ // The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction
+ // are guarded by a lock, while reads stay lock free.
+ private readonly Lock _sizeGate = new();
+ private long _cachedCharacterCount;
+
+ // Monotonically increasing insertion stamp, used to evict the oldest entries first.
+ private long _sequence;
+
+ ///
+ /// Initializes a new instance of the class with the default budgets and time to live.
+ ///
+ public CoverArtArchiveResponseCache()
+ {
+ _maximumEntryCount = MAXIMUM_ENTRY_COUNT;
+ _maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
+ _timeToLive = s_timeToLive;
+ }
+
+ ///
+ /// Initializes a new instance of the class with the provided budgets and time to live.
+ ///
+ /// The maximum number of responses the cache keeps.
+ /// The maximum total number of characters of the cached response bodies.
+ /// The amount of time a cached response stays valid.
+ internal CoverArtArchiveResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive)
+ {
+ _maximumEntryCount = maximumEntryCount;
+ _maximumCharacterCount = maximumCharacterCount;
+ _timeToLive = timeToLive;
+ }
+
+ ///
+ /// Tries to get the cached response body for .
+ ///
+ /// The key of the cached response.
+ /// The cached response body, when found.
+ /// when an unexpired response was found, otherwise .
+ public bool TryGet(string key, out string? json)
+ {
+ // An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it.
+ if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow)
+ {
+ json = entry.Json;
+ return true;
+ }
+ json = null;
+ return false;
+ }
+
+ ///
+ /// Adds or replaces the cached response body for , then trims the cache back to its budgets.
+ ///
+ /// The key of the cached response.
+ /// The response body to cache.
+ public void Set(string key, string json)
+ {
+ // A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache.
+ if (json.Length > _maximumCharacterCount)
+ return;
+
+ lock (_sizeGate)
+ {
+ if (_entries.TryRemove(key, out CacheEntry? existing))
+ _cachedCharacterCount -= existing.Json.Length;
+
+ _entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence);
+ _cachedCharacterCount += json.Length;
+
+ if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount)
+ TrimToBudget();
+ }
+ }
+
+ ///
+ /// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets.
+ ///
+ private void TrimToBudget()
+ {
+ DateTime utcNow = DateTime.UtcNow;
+ bool isOverEntryCount = _entries.Count > _maximumEntryCount;
+ bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount;
+ int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100);
+ long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100);
+
+ // Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when
+ // a budget was not exceeded, so the cache keeps reclaiming dead entries.
+ foreach (KeyValuePair candidate in _entries.OrderBy(entry => entry.Value.Sequence))
+ {
+ bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow;
+ bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget;
+ bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget;
+ if (!isExpired && !needsEntryTrim && !needsCharacterTrim)
+ break;
+
+ if (_entries.TryRemove(candidate.Key, out CacheEntry? removed))
+ _cachedCharacterCount -= removed.Json.Length;
+ }
+ }
+
+ private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence);
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveAlbumArtworkProvider.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveAlbumArtworkProvider.cs
new file mode 100644
index 00000000..ffa4422d
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveAlbumArtworkProvider.cs
@@ -0,0 +1,69 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using Lumina.Plugins.CoverArtArchive.Core.Api;
+using Lumina.Plugins.CoverArtArchive.Core.Mapping;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Core;
+
+///
+/// Provides the artwork of an album from the Cover Art Archive, by resolving the MusicBrainz identifiers of the album into artwork DTOs.
+/// The artwork of the exact release is preferred, and the artwork of its release group is used when the release itself carries none.
+///
+internal sealed class CoverArtArchiveAlbumArtworkProvider : IArtworkProvider
+{
+ private readonly CoverArtArchiveHttpClient _coverArtArchiveHttpClient;
+
+ ///
+ /// Gets the display name of the artwork provider.
+ ///
+ public string Name => "Cover Art Archive";
+
+ ///
+ /// Gets the media library types this artwork provider supports.
+ ///
+ public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music];
+
+ ///
+ /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
+ ///
+ public bool RequiresWebAccess => true;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The HTTP client used to call the Cover Art Archive API.
+ public CoverArtArchiveAlbumArtworkProvider(CoverArtArchiveHttpClient coverArtArchiveHttpClient)
+ {
+ _coverArtArchiveHttpClient = coverArtArchiveHttpClient;
+ }
+
+ ///
+ /// Gets the artworks of the album described by .
+ ///
+ /// The lookup describing the album to get the artwork for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The artworks of the album, or an empty collection when no artwork was found.
+ public async Task> GetArtworkAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ CoverArtArchiveArtworkResponse? artwork = null;
+
+ // The identifier of the exact release pins the edition the local files match, so its artwork is preferred.
+ if (lookup.MusicBrainzReleaseId is not null)
+ artwork = await _coverArtArchiveHttpClient.GetReleaseArtworkAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
+
+ // A release can carry no artwork of its own while its release group does, so the release group is the fallback.
+ // The collection is guarded here too, because the deserializer can produce a null collection regardless of the initializer.
+ if ((artwork?.Images is null || artwork.Images.Count == 0) && lookup.MusicBrainzReleaseGroupId is not null)
+ artwork = await _coverArtArchiveHttpClient.GetReleaseGroupArtworkAsync(lookup.MusicBrainzReleaseGroupId.Value, cancellationToken).ConfigureAwait(false);
+
+ return CoverArtArchiveMapper.MapArtwork(artwork);
+ }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveHosts.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveHosts.cs
new file mode 100644
index 00000000..68813e95
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveHosts.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Core;
+
+///
+/// Defines the hosts of the Cover Art Archive and the Internet Archive, which are the only hosts the plugin queries, the only hosts it may follow a
+/// redirect to, and the only hosts it may fetch artwork from. The Cover Art Archive is not self hostable, so no other host can be a legitimate source.
+///
+internal static class CoverArtArchiveHosts
+{
+ ///
+ /// Determines whether the provided host is one of the hosts the Cover Art Archive may delegate its responses to.
+ ///
+ /// The host to check.
+ /// when the host is allowed, otherwise .
+ public static bool IsAllowed(string host)
+ {
+ return host.Equals("coverartarchive.org", StringComparison.OrdinalIgnoreCase)
+ || host.EndsWith(".coverartarchive.org", StringComparison.OrdinalIgnoreCase)
+ || host.Equals("archive.org", StringComparison.OrdinalIgnoreCase)
+ || host.EndsWith(".archive.org", StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchivePlugin.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchivePlugin.cs
new file mode 100644
index 00000000..32db69c4
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchivePlugin.cs
@@ -0,0 +1,77 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
+using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.CoverArtArchive.Common.DependencyInjection;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Core;
+
+///
+/// Plugin that provides music album artwork retrieval from the Cover Art Archive.
+///
+public sealed class CoverArtArchivePlugin : IPlugin, IPluginServiceRegistrator
+{
+ ///
+ /// The unique identifier of the plugin.
+ ///
+ public static readonly Guid s_pluginId = new("b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14");
+
+ ///
+ /// Gets the unique identifier of the plugin.
+ ///
+ public Guid Id => s_pluginId;
+
+ ///
+ /// Gets the display name of the plugin.
+ ///
+ public string Name => "Cover Art Archive";
+
+ ///
+ /// Gets the author of the plugin.
+ ///
+ public string Author => "Lumina";
+
+ ///
+ /// Gets the version of the plugin.
+ ///
+ public Version Version => new(1, 0, 0);
+
+ ///
+ /// Gets the description of the plugin.
+ ///
+ public string Description => "Retrieves the cover, back, booklet, medium and other artwork of music albums from the Cover Art Archive.";
+
+ ///
+ /// Gets the settings schema of the plugin.
+ ///
+ /// The settings descriptors of the plugin.
+ public IReadOnlyList GetSettingsSchema()
+ {
+ return
+ [
+ new PluginSettingDescriptorDto(
+ Key: CoverArtArchiveSettingsKeys.CONTACT_EMAIL,
+ Label: "Contact Email",
+ Type: PluginSettingType.Text),
+ new PluginSettingDescriptorDto(
+ Key: CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS,
+ Label: "Minimum Request Interval (seconds)",
+ Type: PluginSettingType.Number,
+ DefaultValue: "1.0")
+ ];
+ }
+
+ ///
+ /// Registers the services required by the plugin.
+ ///
+ /// The service collection to register the services into.
+ public void RegisterServices(IServiceCollection services)
+ {
+ services.AddCoverArtArchiveArtworkProvider(pluginId: Id);
+ }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Mapping/CoverArtArchiveMapper.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Mapping/CoverArtArchiveMapper.cs
new file mode 100644
index 00000000..c1852ae9
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Mapping/CoverArtArchiveMapper.cs
@@ -0,0 +1,153 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Core.Mapping;
+
+///
+/// Maps the responses of the Cover Art Archive API into artwork DTOs.
+///
+internal static class CoverArtArchiveMapper
+{
+ ///
+ /// Maps the artwork carried by into artwork DTOs, one for every type each image is tagged with.
+ ///
+ /// The artwork response to map.
+ /// The mapped artworks, ordered as they appear in the response, or an empty collection when there is no artwork.
+ public static IReadOnlyList MapArtwork(CoverArtArchiveArtworkResponse? response)
+ {
+ // The collection and its elements are guarded, because the deserializer can produce a null collection, or null elements, regardless of the initializers.
+ if (response?.Images is null)
+ return [];
+
+ List artworks = [];
+ // The ordinals are tracked per type, so that multiple images of the same type, like the pages of a booklet, are ordered among themselves.
+ Dictionary nextOrdinals = [];
+ foreach (CoverArtArchiveImageResponse? image in response.Images)
+ {
+ if (image is null || !TryResolveArtworkUrl(image.Image, out string artworkUrl))
+ continue;
+
+ foreach (ArtworkType artworkType in ResolveArtworkTypes(image))
+ {
+ int ordinal = nextOrdinals.TryGetValue(artworkType, out int nextOrdinal) ? nextOrdinal : 0;
+ nextOrdinals[artworkType] = ordinal + 1;
+ artworks.Add(new ArtworkDto(artworkType, ordinal, LocalPath: null, RemoteUrl: artworkUrl));
+ }
+ }
+ return artworks;
+ }
+
+ ///
+ /// Resolves the URL of an artwork image, keeping it only when it points, over an encrypted connection, at a host the Cover Art Archive may serve
+ /// artwork from. An image URL of any other shape or host is dropped, so a compromised response cannot make the host download from an internal address.
+ ///
+ /// The image URL carried by the response.
+ /// The resolved, encrypted image URL, when it is usable.
+ /// when the image URL is usable, otherwise .
+ private static bool TryResolveArtworkUrl(string? candidate, out string artworkUrl)
+ {
+ artworkUrl = string.Empty;
+ if (string.IsNullOrWhiteSpace(candidate))
+ return false;
+
+ if (!Uri.TryCreate(candidate.Trim(), UriKind.Absolute, out Uri? uri) || !CoverArtArchiveHosts.IsAllowed(uri.Host))
+ return false;
+
+ // The artwork is always fetched over an encrypted connection, so a plain HTTP reference to a trusted host is upgraded to HTTPS,
+ // and a reference that uses any other scheme is dropped.
+ if (uri.Scheme == Uri.UriSchemeHttps)
+ artworkUrl = uri.AbsoluteUri;
+ else if (uri.Scheme == Uri.UriSchemeHttp)
+ artworkUrl = new UriBuilder(uri) { Scheme = Uri.UriSchemeHttps, Port = -1 }.Uri.AbsoluteUri;
+ else
+ return false;
+
+ return true;
+ }
+
+ ///
+ /// Resolves the artwork types an image is tagged with, falling back to the front and back flags when the image carries no type.
+ ///
+ /// The image whose types are resolved.
+ /// The distinct artwork types of the image, in the order they appear in the response.
+ private static List ResolveArtworkTypes(CoverArtArchiveImageResponse image)
+ {
+ // A list de-duplicated on insertion keeps the order of the response, unlike a set, whose iteration order is not deterministic.
+ List artworkTypes = [];
+ // The collection and its elements are guarded, because the deserializer can produce a null collection, or null elements, regardless of the initializers.
+ foreach (string? type in image.Types ?? [])
+ if (TryMapArtworkType(type, out ArtworkType artworkType) && !artworkTypes.Contains(artworkType))
+ artworkTypes.Add(artworkType);
+
+ // An image that carries no known type still describes the front or the back of the release when it is flagged as such.
+ if (artworkTypes.Count == 0)
+ {
+ if (image.IsFront)
+ artworkTypes.Add(ArtworkType.Cover);
+ if (image.IsBack)
+ artworkTypes.Add(ArtworkType.Back);
+ }
+ return artworkTypes;
+ }
+
+ ///
+ /// Maps a Cover Art Archive image type onto an artwork type.
+ ///
+ /// The Cover Art Archive image type.
+ /// The mapped artwork type, when the type is recognized.
+ /// when the type was recognized, otherwise .
+ private static bool TryMapArtworkType(string? type, out ArtworkType artworkType)
+ {
+ if (string.IsNullOrWhiteSpace(type))
+ {
+ artworkType = ArtworkType.Other;
+ return false;
+ }
+
+ switch (type.Trim().ToLowerInvariant())
+ {
+ case "front":
+ artworkType = ArtworkType.Cover;
+ return true;
+ case "back":
+ artworkType = ArtworkType.Back;
+ return true;
+ case "booklet":
+ artworkType = ArtworkType.Booklet;
+ return true;
+ case "medium":
+ artworkType = ArtworkType.Medium;
+ return true;
+ case "tray":
+ artworkType = ArtworkType.Tray;
+ return true;
+ case "spine":
+ artworkType = ArtworkType.Spine;
+ return true;
+ case "obi":
+ artworkType = ArtworkType.Obi;
+ return true;
+ case "sticker":
+ artworkType = ArtworkType.Sticker;
+ return true;
+ case "poster":
+ artworkType = ArtworkType.Poster;
+ return true;
+ case "liner":
+ artworkType = ArtworkType.Liner;
+ return true;
+ case "watermark":
+ artworkType = ArtworkType.Watermark;
+ return true;
+ default:
+ // The Cover Art Archive also uses a free form "Other" type and may add new types over time, which are all kept as generic artwork.
+ artworkType = ArtworkType.Other;
+ return true;
+ }
+ }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsKeys.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsKeys.cs
new file mode 100644
index 00000000..bc41419e
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsKeys.cs
@@ -0,0 +1,17 @@
+namespace Lumina.Plugins.CoverArtArchive.Core.Settings;
+
+///
+/// Keys of the settings of the Cover Art Archive artwork plugin, shared by the settings schema and the settings loader.
+///
+internal static class CoverArtArchiveSettingsKeys
+{
+ ///
+ /// The key of the setting defining the contact email sent to the Cover Art Archive API.
+ ///
+ internal const string CONTACT_EMAIL = "ContactEmail";
+
+ ///
+ /// The key of the setting defining the minimum interval between consecutive requests to the Cover Art Archive API, in seconds.
+ ///
+ internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds";
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsProvider.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsProvider.cs
new file mode 100644
index 00000000..aed1deff
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsProvider.cs
@@ -0,0 +1,129 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Core.Settings;
+
+///
+/// Provides the runtime settings of the Cover Art Archive artwork plugin, overlaying the settings persisted by the host over the configured defaults.
+///
+internal sealed class CoverArtArchiveSettingsProvider
+{
+ // The minimum request interval is clamped to a sane range, so a persisted value can neither be a non finite value that cannot be turned into a
+ // duration, nor be so large that waiting for it overflows the delay of the requests.
+ private const double MAXIMUM_REQUEST_INTERVAL_SECONDS = 60;
+
+ private readonly IPluginSettingsStore? _settingsStore;
+ private readonly Guid _pluginId;
+ private readonly CoverArtArchiveSettingsDto _defaults;
+
+ // The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already
+ // resolved path lock free; the gate is only needed by the first callers that race to resolve it.
+ private readonly SemaphoreSlim _gate = new(1, 1);
+ private CoverArtArchiveSettingsDto? _runtimeSettings;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The store of the settings persisted by the host, or when no store is available.
+ /// The unique identifier of the plugin whose settings are read.
+ /// The runtime settings with the default values and the optional configuration callback already applied.
+ public CoverArtArchiveSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, CoverArtArchiveSettingsDto defaults)
+ {
+ _settingsStore = settingsStore;
+ _pluginId = pluginId;
+ _defaults = defaults;
+ }
+
+ ///
+ /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ /// The runtime settings of the plugin.
+ public async Task GetAsync(CancellationToken cancellationToken)
+ {
+ // Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact.
+ CoverArtArchiveSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings);
+ if (runtimeSettings is not null)
+ return runtimeSettings;
+
+ // Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once.
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ // Second check inside the gate: another caller may have resolved the settings while this one was waiting for it.
+ runtimeSettings = Volatile.Read(ref _runtimeSettings);
+ if (runtimeSettings is null)
+ {
+ runtimeSettings = await ResolveAsync(cancellationToken).ConfigureAwait(false);
+ // Publishing through Volatile makes the fully built instance visible to the lock free readers above.
+ Volatile.Write(ref _runtimeSettings, runtimeSettings);
+ }
+
+ return runtimeSettings;
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ ///
+ /// Builds the runtime settings by overlaying the settings persisted by the host over the configured defaults.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ /// The runtime settings of the plugin.
+ private async Task ResolveAsync(CancellationToken cancellationToken)
+ {
+ // The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes.
+ CoverArtArchiveSettingsDto runtimeSettings = new()
+ {
+ UserAgent = _defaults.UserAgent,
+ ContactEmail = _defaults.ContactEmail,
+ MinimumRequestInterval = _defaults.MinimumRequestInterval
+ };
+
+ if (_settingsStore is null)
+ return runtimeSettings;
+
+ IReadOnlyDictionary? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
+ if (storedSettings is null)
+ return runtimeSettings;
+
+ if (storedSettings.TryGetValue(CoverArtArchiveSettingsKeys.CONTACT_EMAIL, out string? contactEmail))
+ {
+ string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim();
+ runtimeSettings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null;
+ }
+
+ // A persisted value that is not a finite number is rejected, and a finite one is clamped, so that neither a NaN, nor an infinity, nor an
+ // out of range value can make the conversion to a duration or the waiting for it throw.
+ if (storedSettings.TryGetValue(CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) &&
+ double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue) &&
+ double.IsFinite(minimumRequestIntervalValue))
+ runtimeSettings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Clamp(minimumRequestIntervalValue, 0, MAXIMUM_REQUEST_INTERVAL_SECONDS));
+
+ return runtimeSettings;
+ }
+
+ ///
+ /// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header.
+ ///
+ /// The persisted contact email.
+ /// when the email is safe, otherwise .
+ private static bool IsSafeContactEmail(string contactEmail)
+ {
+ // The email is embedded in the User-Agent header, and an invalid character there throws when the header is parsed, which would break every request of the plugin,
+ // so, anything outside a conservative email charset is rejected.
+ foreach (char character in contactEmail)
+ if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+'))
+ return false;
+ return true;
+ }
+}
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Lumina.Plugins.CoverArtArchive.csproj b/plugins/Lumina.Plugins.CoverArtArchive/Lumina.Plugins.CoverArtArchive.csproj
new file mode 100644
index 00000000..bed7d79c
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Lumina.Plugins.CoverArtArchive.csproj
@@ -0,0 +1,34 @@
+
+
+ net10.0
+ disable
+ enable
+ $(SolutionDir)..\bin\plugins\
+ false
+ true
+ true
+ $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ false
+ runtime
+
+
+
+
+
+
+
diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.CoverArtArchive/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..575f39dd
--- /dev/null
+++ b/plugins/Lumina.Plugins.CoverArtArchive/Properties/AssemblyInfo.cs
@@ -0,0 +1,6 @@
+using System.Runtime.CompilerServices;
+
+[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.UnitTests")]
+[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.SecurityTests")]
+[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.Fixtures")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseFixture.cs b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseFixture.cs
new file mode 100644
index 00000000..028fcb86
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseFixture.cs
@@ -0,0 +1,43 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class CoverArtArchiveArtworkResponseFixture
+{
+ private readonly CoverArtArchiveImageResponseFixture _coverArtArchiveImageResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The images of the artwork.
+ /// Whether the images should be included, or forced to .
+ /// A configured instance.
+ public CoverArtArchiveArtworkResponse Create(
+ List? images = null,
+ bool includeImages = true)
+ {
+ return new CoverArtArchiveArtworkResponse
+ {
+ Images = includeImages ? images ?? [.. _coverArtArchiveImageResponseFixture.CreateMany()] : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseFixture.cs b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseFixture.cs
new file mode 100644
index 00000000..72d9f7c1
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseFixture.cs
@@ -0,0 +1,67 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class CoverArtArchiveImageResponseFixture
+{
+ private static readonly string[] s_knownTypes =
+ [
+ "Front", "Back", "Booklet", "Medium", "Tray", "Spine", "Obi", "Sticker", "Poster", "Liner", "Watermark", "Other"
+ ];
+
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The URL of the full size image.
+ /// Whether the image URL should be included, or forced to .
+ /// Optional. The URL of the thumbnail of the image.
+ /// Optional. The types of the image.
+ /// Whether the types should be included, or forced to .
+ /// Optional. Whether the image is the front cover.
+ /// Optional. Whether the image is the back cover.
+ /// Optional. The comment describing the image.
+ /// A configured instance.
+ public CoverArtArchiveImageResponse Create(
+ string? image = null,
+ bool includeImage = true,
+ string? thumbnail = null,
+ List? types = null,
+ bool includeTypes = true,
+ bool? isFront = null,
+ bool? isBack = null,
+ string? comment = null)
+ {
+ return new CoverArtArchiveImageResponse
+ {
+ Image = includeImage ? image ?? $"https://coverartarchive.org/release/{Guid.NewGuid():D}/{_faker.Random.Long(1, 999_999_999)}.jpg" : null,
+ Thumbnail = thumbnail ?? $"https://coverartarchive.org/release/{Guid.NewGuid():D}/thumb.jpg",
+ Types = includeTypes ? types ?? [_faker.PickRandom(s_knownTypes)] : null,
+ IsFront = isFront ?? _faker.Random.Bool(),
+ IsBack = isBack ?? _faker.Random.Bool(),
+ Comment = comment ?? _faker.Lorem.Sentence()
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/DTO/Settings/CoverArtArchiveSettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/DTO/Settings/CoverArtArchiveSettingsDtoFixture.cs
new file mode 100644
index 00000000..43b7818b
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/DTO/Settings/CoverArtArchiveSettingsDtoFixture.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class CoverArtArchiveSettingsDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The user agent sent with every request.
+ /// Optional. The contact email sent to the Cover Art Archive API.
+ /// Whether the contact email should be included, or forced to .
+ /// Optional. The minimum interval between consecutive requests.
+ /// A configured instance.
+ public CoverArtArchiveSettingsDto Create(
+ string? userAgent = null,
+ string? contactEmail = null,
+ bool includeContactEmail = true,
+ TimeSpan? minimumRequestInterval = null)
+ {
+ return new CoverArtArchiveSettingsDto
+ {
+ UserAgent = userAgent ?? $"Lumina-CoverArtArchive/{_faker.Random.Int(1, 9)}.{_faker.Random.Int(0, 9)}",
+ ContactEmail = includeContactEmail ? contactEmail ?? _faker.Internet.Email() : null,
+ MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromSeconds(_faker.Random.Double(0, 5))
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Lumina.Plugins.CoverArtArchive.Fixtures.csproj b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Lumina.Plugins.CoverArtArchive.Fixtures.csproj
new file mode 100644
index 00000000..52e31869
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Lumina.Plugins.CoverArtArchive.Fixtures.csproj
@@ -0,0 +1,25 @@
+
+
+
+ net10.0
+ disable
+ enable
+ $(SolutionDir)..\bin\api\
+
+ false
+ false
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..30f3a862
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Properties/AssemblyInfo.cs
@@ -0,0 +1,21 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("Lumina.Plugins.CoverArtArchive.Fixtures")]
+[assembly: AssemblyProduct("Lumina.Plugins.CoverArtArchive.Fixtures")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("D4E2F7A1-8B3C-4D5E-A6F1-2B3C4D5E6F70")]
+
+[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.UnitTests")]
+[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.SecurityTests")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
diff --git a/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Api/CoverArtArchiveHttpClientSecurityTests.cs b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Api/CoverArtArchiveHttpClientSecurityTests.cs
new file mode 100644
index 00000000..6b2dcf25
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Api/CoverArtArchiveHttpClientSecurityTests.cs
@@ -0,0 +1,170 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.CoverArtArchive.Core;
+using Lumina.Plugins.CoverArtArchive.Core.Api;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.SecurityTests.Core.Api;
+
+///
+/// Contains security tests for the class, exercised through the requests it sends.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveHttpClientSecurityTests
+{
+ private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111");
+
+ private readonly CoverArtArchiveSettingsDtoFixture _coverArtArchiveSettingsDtoFixture = new();
+
+ [Theory]
+ [InlineData("https://evil.example/index.json")] // an unrelated public host
+ [InlineData("https://localhost/index.json")] // the loopback host name
+ [InlineData("https://127.0.0.1/index.json")] // the IPv4 loopback address
+ [InlineData("https://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint
+ [InlineData("https://10.0.0.5/index.json")] // a private class A address
+ [InlineData("https://192.168.1.10/index.json")] // a private class C address
+ [InlineData("https://coverartarchive.org.evil.example/index.json")] // the trusted host used as a prefix of an attacker controlled host
+ public async Task GetReleaseArtworkAsync_WhenTheRedirectPointsAtADisallowedHost_ShouldThrowAndNotReachIt(string location)
+ {
+ // Arrange
+ CapturingHttpMessageHandler handler = new((request, callIndex) =>
+ {
+ HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
+ redirect.Headers.Location = new Uri(location);
+ return redirect;
+ });
+ CoverArtArchiveHttpClient sut = CreateClient(handler);
+
+ // Act
+ Task Act()
+ {
+ return sut.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ }
+
+ // Assert
+ await Assert.ThrowsAsync(Act);
+ // No request is ever sent to the disallowed host, the client only ever talks to the Cover Art Archive.
+ Assert.All(handler.Requests, request => Assert.Equal("coverartarchive.org", request.RequestUri!.Host));
+ }
+
+ [Theory]
+ [InlineData("http://archive.org/index.json")] // a downgrade of the Internet Archive to plain HTTP
+ [InlineData("http://coverartarchive.org/index.json")] // a downgrade of the Cover Art Archive to plain HTTP
+ public async Task GetReleaseArtworkAsync_WhenTheRedirectDowngradesToPlainHttp_ShouldThrow(string location)
+ {
+ // Arrange
+ CapturingHttpMessageHandler handler = new((request, callIndex) =>
+ {
+ HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
+ redirect.Headers.Location = new Uri(location);
+ return redirect;
+ });
+ CoverArtArchiveHttpClient sut = CreateClient(handler);
+
+ // Act
+ Task Act()
+ {
+ return sut.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ }
+
+ // Assert
+ await Assert.ThrowsAsync(Act);
+ }
+
+ [Theory]
+ [InlineData("user@example.com\r\nX-Injected: value")] // carriage return and line feed header injection
+ [InlineData("user@example.com\nX-Injected: value")] // line feed header injection
+ public async Task GetReleaseArtworkAsync_WhenThePersistedContactEmailAttemptsHeaderInjection_ShouldNotInjectAnyHeader(string maliciousEmail)
+ {
+ // Arrange
+ IPluginSettingsStore mockStore = Substitute.For();
+ mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(
+ new Dictionary { [CoverArtArchiveSettingsKeys.CONTACT_EMAIL] = maliciousEmail });
+ CoverArtArchiveSettingsProvider settingsProvider = new(mockStore, CoverArtArchivePlugin.s_pluginId, _coverArtArchiveSettingsDtoFixture.Create(
+ userAgent: "Lumina-Security/1.0",
+ includeContactEmail: false,
+ minimumRequestInterval: TimeSpan.Zero));
+ CapturingHttpMessageHandler handler = new((request, callIndex) => CreateJsonResponse("""{"images":[]}"""));
+ CoverArtArchiveHttpClient sut = new(new HttpClient(handler), settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache());
+
+ // Act
+ await sut.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ HttpRequestMessage request = Assert.Single(handler.Requests);
+ Assert.Equal("Lumina-Security/1.0", request.Headers.UserAgent.ToString());
+ Assert.False(request.Headers.Contains("X-Injected"));
+ }
+
+ ///
+ /// Creates a that sends its requests through the provided handler, with no throttling.
+ ///
+ /// The handler that answers the requests of the client.
+ /// The created client.
+ private CoverArtArchiveHttpClient CreateClient(HttpMessageHandler handler)
+ {
+ CoverArtArchiveSettingsProvider settingsProvider = new(null, CoverArtArchivePlugin.s_pluginId, _coverArtArchiveSettingsDtoFixture.Create(
+ userAgent: "Lumina-Security/1.0",
+ includeContactEmail: false,
+ minimumRequestInterval: TimeSpan.Zero));
+ return new CoverArtArchiveHttpClient(new HttpClient(handler), settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache());
+ }
+
+ ///
+ /// Creates an OK response with the provided JSON body.
+ ///
+ /// The JSON body of the response.
+ /// The created response.
+ private static HttpResponseMessage CreateJsonResponse(string json)
+ {
+ return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
+ }
+
+ ///
+ /// HTTP message handler that answers every request through a factory and records the requests that were sent.
+ ///
+ [ExcludeFromCodeCoverage]
+ private sealed class CapturingHttpMessageHandler : HttpMessageHandler
+ {
+ private readonly Func _responseFactory;
+ private int _callCount;
+
+ ///
+ /// Gets the requests that were sent through the handler.
+ ///
+ public List Requests { get; } = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The factory that produces the response of a request, given the request and its one based call index.
+ public CapturingHttpMessageHandler(Func responseFactory)
+ {
+ _responseFactory = responseFactory;
+ }
+
+ ///
+ /// Answers the provided request through the configured factory.
+ ///
+ /// The request to answer.
+ /// Cancellation token that can be used to stop the execution.
+ /// The response to the request.
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ int callIndex = Interlocked.Increment(ref _callCount);
+ Requests.Add(request);
+ return Task.FromResult(_responseFactory(request, callIndex));
+ }
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Mapping/CoverArtArchiveMapperSecurityTests.cs b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Mapping/CoverArtArchiveMapperSecurityTests.cs
new file mode 100644
index 00000000..7ade7a53
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Mapping/CoverArtArchiveMapperSecurityTests.cs
@@ -0,0 +1,97 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using Lumina.Plugins.CoverArtArchive.Core.Mapping;
+using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.Contracts.Responses;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.SecurityTests.Core.Mapping;
+
+///
+/// Contains security tests for the class, exercised through the artwork it emits.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveMapperSecurityTests
+{
+ private readonly CoverArtArchiveArtworkResponseFixture _coverArtArchiveArtworkResponseFixture = new();
+ private readonly CoverArtArchiveImageResponseFixture _coverArtArchiveImageResponseFixture = new();
+
+ [Theory]
+ [InlineData("http://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint
+ [InlineData("http://localhost/admin")] // the loopback host name
+ [InlineData("http://127.0.0.1/admin")] // the IPv4 loopback address
+ [InlineData("http://[::1]/admin")] // the IPv6 loopback address
+ [InlineData("http://10.0.0.5/internal")] // a private class A address
+ [InlineData("http://172.16.0.1/internal")] // a private class B address
+ [InlineData("http://192.168.1.10/internal")] // a private class C address
+ [InlineData("http://0.0.0.0/internal")] // the unspecified address
+ [InlineData("http://[fc00::1]/internal")] // the IPv6 unique local range
+ [InlineData("https://evil.example/tracker.jpg")] // an unrelated public host
+ [InlineData("https://coverartarchive.org.evil.example/1.jpg")] // the trusted host used as a prefix of an attacker controlled host
+ [InlineData("https://archive.org.evil.example/1.jpg")] // the Internet Archive host used as a prefix of an attacker controlled host
+ public void MapArtwork_WhenAnImageUrlPointsAtAnInternalOrUntrustedHost_ShouldDropIt(string maliciousUrl)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: maliciousUrl, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Theory]
+ [InlineData("file:///etc/passwd")] // a local file URI
+ [InlineData("ftp://coverartarchive.org/1.jpg")] // a non web scheme
+ [InlineData("javascript:alert(1)")] // a script scheme
+ [InlineData("data:image/png;base64,SGVsbG8=")] // an inline data URI
+ public void MapArtwork_WhenAnImageUrlUsesAnUnsupportedScheme_ShouldDropIt(string maliciousUrl)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: maliciousUrl, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Theory]
+ [InlineData("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg")] // a trusted Cover Art Archive image
+ [InlineData("https://archive.org/download/mbid-11111111-1111-1111-1111-111111111111/front.jpg")] // a trusted Internet Archive image
+ public void MapArtwork_WhenAnImageUrlPointsAtATrustedHostOverHttps_ShouldKeepIt(string trustedUrl)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: trustedUrl, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal(trustedUrl, artwork.RemoteUrl);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenAnImageUrlPointsAtATrustedHostOverPlainHttp_ShouldUpgradeItToHttps()
+ {
+ // Arrange
+ const string HTTP_URL = "http://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg";
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: HTTP_URL, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", artwork.RemoteUrl);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests.csproj b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests.csproj
new file mode 100644
index 00000000..308e65dc
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests.csproj
@@ -0,0 +1,48 @@
+
+
+
+ net10.0
+ disable
+ enable
+
+ false
+ true
+
+
+
+
+ <_Parameter1>DisableTestParallelization = true
+ <_Parameter1_IsLiteral>true
+
+
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs
new file mode 100644
index 00000000..9daac4bb
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs
@@ -0,0 +1,205 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.CoverArtArchive.Common.DependencyInjection;
+using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
+using Lumina.Plugins.CoverArtArchive.Core.Api;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net.Http;
+using System.Reflection;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.DependencyInjection;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveServicesTests
+{
+ [Fact]
+ public void AddCoverArtArchiveArtworkProvider_WhenServicesIsNull_ShouldThrowArgumentNullException()
+ {
+ // Arrange
+ IServiceCollection services = null!;
+
+ // Act
+ Action act = () => services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
+
+ // Assert
+ Assert.Throws(act);
+ }
+
+ [Fact]
+ public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldReturnTheSameServiceCollection()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ IServiceCollection result = services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
+
+ // Assert
+ Assert.Same(services, result);
+ }
+
+ [Fact]
+ public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheArtworkProviderForKeyedResolution()
+ {
+ // Arrange
+ Guid pluginId = Guid.NewGuid();
+ ServiceCollection services = new();
+
+ // Act
+ services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId);
+ ServiceProvider serviceProvider = services.BuildServiceProvider();
+
+ // Assert
+ Assert.Single(serviceProvider.GetKeyedServices(pluginId));
+ Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid()));
+ }
+
+ [Fact]
+ public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
+
+ // Assert
+ ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveSettingsProvider));
+ Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime);
+ }
+
+ [Fact]
+ public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheThrottleAndTheResponseCacheAsSingletons()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
+
+ // Assert
+ ServiceDescriptor throttleDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveRequestThrottle));
+ ServiceDescriptor responseCacheDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveResponseCache));
+ Assert.Equal(ServiceLifetime.Singleton, throttleDescriptor.Lifetime);
+ Assert.Equal(ServiceLifetime.Singleton, responseCacheDescriptor.Lifetime);
+ }
+
+ [Fact]
+ public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheHttpClient()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
+ ServiceProvider serviceProvider = services.BuildServiceProvider();
+
+ // Assert
+ Assert.NotNull(serviceProvider.GetService());
+ }
+
+ [Fact]
+ public async Task AddCoverArtArchiveArtworkProvider_WhenASettingsCallbackIsProvided_ShouldApplyItToTheDefaults()
+ {
+ // Arrange
+ Guid pluginId = Guid.NewGuid();
+ ServiceCollection services = new();
+
+ // Act
+ services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId, settings => settings.ContactEmail = "custom@example.com");
+ ServiceProvider serviceProvider = services.BuildServiceProvider();
+ using (IServiceScope scope = serviceProvider.CreateScope())
+ {
+ CoverArtArchiveSettingsProvider settingsProvider = scope.ServiceProvider.GetRequiredService();
+ CoverArtArchiveSettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.Equal("custom@example.com", settings.ContactEmail);
+ }
+ }
+
+ [Fact]
+ public void AddCoverArtArchiveArtworkProvider_WhenTheClientIsResolved_ShouldDisableAutomaticRedirectsOnItsPrimaryHandler()
+ {
+ // Arrange
+ ServiceCollection services = new();
+ services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
+ ServiceProvider serviceProvider = services.BuildServiceProvider();
+ using (IServiceScope scope = serviceProvider.CreateScope())
+ {
+ // Act
+ CoverArtArchiveHttpClient client = scope.ServiceProvider.GetRequiredService();
+ HttpClientHandler primaryHandler = GetPrimaryHandler(client);
+
+ // Assert
+ // Automatic redirects must stay disabled on the primary handler, otherwise it would follow a server controlled redirect on its own,
+ // before the client can check the target host against the Cover Art Archive and the Internet Archive, bypassing that control.
+ Assert.False(primaryHandler.AllowAutoRedirect);
+ }
+ }
+
+ [Fact]
+ public void AddCoverArtArchiveArtworkProvider_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices()
+ {
+ // Arrange
+ Guid pluginId = Guid.NewGuid();
+ ServiceCollection services = new();
+
+ // Act
+ services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId);
+ services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId);
+
+ // Assert
+ // The settings provider, the throttle and the response cache are registered with TryAdd, so a second call must not add them again.
+ Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveRequestThrottle));
+ Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveResponseCache));
+ Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveSettingsProvider));
+ }
+
+ ///
+ /// Gets the primary HTTP message handler of the provided client, unwrapping the delegating handlers built by the HTTP client factory around it.
+ ///
+ /// The client whose primary handler is retrieved.
+ /// The primary HTTP client handler of the client.
+ private static HttpClientHandler GetPrimaryHandler(CoverArtArchiveHttpClient client)
+ {
+ HttpClient httpClient = (HttpClient)GetFieldOfType(client, typeof(HttpClient))!;
+ HttpMessageHandler? handler = (HttpMessageHandler?)GetFieldOfType(httpClient, typeof(HttpMessageHandler));
+ while (handler is DelegatingHandler delegatingHandler)
+ handler = delegatingHandler.InnerHandler;
+ return Assert.IsType(handler);
+ }
+
+ ///
+ /// Gets the value of the first field, declared on the provided or any of its base types, whose type is assignable to
+ /// , without relying on the field name, so the test keeps working across runtime versions.
+ ///
+ /// The instance whose field is read.
+ /// The type the field must be assignable to.
+ /// The value of the found field.
+ /// Thrown when no field assignable to is found.
+ private static object GetFieldOfType(object instance, Type fieldType)
+ {
+ Type? type = instance.GetType();
+ while (type is not null)
+ {
+ FieldInfo? field = type
+ .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly)
+ .FirstOrDefault(candidate => fieldType.IsAssignableFrom(candidate.FieldType));
+ if (field is not null)
+ return field.GetValue(instance)!;
+ type = type.BaseType;
+ }
+ throw new InvalidOperationException($"No field assignable to {fieldType} was found on {instance.GetType()} or its base types.");
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseTests.cs
new file mode 100644
index 00000000..2e8d87ec
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseTests.cs
@@ -0,0 +1,101 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveArtworkResponseTests
+{
+ [Fact]
+ public void Deserialize_WhenTheApiReturnsImages_ShouldDeserializeEveryImage()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "images": [
+ { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", "front": true, "types": [ "Front" ] },
+ { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/2.jpg", "back": true, "types": [ "Back" ] }
+ ]
+ }
+ """;
+
+ // Act
+ CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.NotNull(response.Images);
+ Assert.Equal(2, response.Images.Count);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", response.Images[0]!.Image);
+ Assert.Equal(["Front"], response.Images[0]!.Types);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/2.jpg", response.Images[1]!.Image);
+ Assert.Equal(["Back"], response.Images[1]!.Types);
+ }
+
+ [Fact]
+ public void Deserialize_WhenTheApiReturnsANullImagesCollection_ShouldDeserializeAsNull()
+ {
+ // Arrange
+ // The API can answer with a null images collection, which must not be turned into anything else by the deserializer.
+ const string JSON = """{"images":null}""";
+
+ // Act
+ CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Null(response.Images);
+ }
+
+ [Fact]
+ public void Deserialize_WhenTheImagesCollectionContainsNullElements_ShouldKeepThem()
+ {
+ // Arrange
+ const string JSON = """{"images":[null,{"image":"https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg"}]}""";
+
+ // Act
+ CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.NotNull(response.Images);
+ Assert.Equal(2, response.Images.Count);
+ Assert.Null(response.Images[0]);
+ Assert.NotNull(response.Images[1]);
+ }
+
+ [Fact]
+ public void Deserialize_WhenTheImagesCollectionIsEmpty_ShouldDeserializeAsEmpty()
+ {
+ // Arrange
+ const string JSON = """{"images":[]}""";
+
+ // Act
+ CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.NotNull(response.Images);
+ Assert.Empty(response.Images);
+ }
+
+ [Fact]
+ public void Deserialize_WhenThePropertyIsMissing_ShouldDefaultToNull()
+ {
+ // Arrange
+ const string JSON = "{}";
+
+ // Act
+ CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Null(response.Images);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseTests.cs
new file mode 100644
index 00000000..c3461252
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseTests.cs
@@ -0,0 +1,107 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveImageResponseTests
+{
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "approved": true,
+ "back": true,
+ "comment": "A comment",
+ "front": false,
+ "id": 12345,
+ "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345.jpg",
+ "thumbnail": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345-250.jpg",
+ "types": [ "Back", "Booklet" ]
+ }
+ """;
+
+ // Act
+ CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345.jpg", response.Image);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345-250.jpg", response.Thumbnail);
+ Assert.Equal(["Back", "Booklet"], response.Types);
+ Assert.False(response.IsFront);
+ Assert.True(response.IsBack);
+ Assert.Equal("A comment", response.Comment);
+ }
+
+ [Fact]
+ public void Deserialize_WhenTheApiReturnsANullTypes_ShouldDeserializeAsNull()
+ {
+ // Arrange
+ // The API can answer with a null types collection, which must not be turned into anything else by the deserializer.
+ const string JSON = """{"image":"https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg","types":null}""";
+
+ // Act
+ CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Null(response.Types);
+ }
+
+ [Fact]
+ public void Deserialize_WhenTheTypesCollectionContainsNullElements_ShouldKeepThem()
+ {
+ // Arrange
+ const string JSON = """{"types":["Front",null,"Booklet"]}""";
+
+ // Act
+ CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.NotNull(response.Types);
+ Assert.Equal(["Front", null, "Booklet"], response.Types);
+ }
+
+ [Fact]
+ public void Deserialize_WhenTheApiReturnsANullImage_ShouldDeserializeAsNull()
+ {
+ // Arrange
+ const string JSON = """{"image":null,"types":["Front"]}""";
+
+ // Act
+ CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Null(response.Image);
+ }
+
+ [Fact]
+ public void Deserialize_WhenThePropertiesAreMissing_ShouldDefaultToNullAndFalse()
+ {
+ // Arrange
+ const string JSON = "{}";
+
+ // Act
+ CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Null(response.Image);
+ Assert.Null(response.Thumbnail);
+ Assert.Null(response.Types);
+ Assert.False(response.IsFront);
+ Assert.False(response.IsBack);
+ Assert.Null(response.Comment);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs
new file mode 100644
index 00000000..3c2efb6d
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.TestHelpers;
+
+///
+/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class StubHttpMessageHandler : HttpMessageHandler
+{
+ private readonly Func _responseFactory;
+ private int _callCount;
+
+ ///
+ /// Gets the requests that were sent through the handler.
+ ///
+ public List Requests { get; } = [];
+
+ ///
+ /// Gets the number of requests that were sent through the handler.
+ ///
+ public int CallCount => _callCount;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The factory that produces the response of a request, given the request and its one based call index.
+ public StubHttpMessageHandler(Func responseFactory)
+ {
+ _responseFactory = responseFactory;
+ }
+
+ ///
+ /// Sends the provided request, producing its response through the configured factory.
+ ///
+ /// The request to send.
+ /// Cancellation token that can be used to stop the execution.
+ /// The response produced for the request.
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ int callIndex = Interlocked.Increment(ref _callCount);
+ Requests.Add(request);
+ try
+ {
+ return Task.FromResult(_responseFactory(request, callIndex));
+ }
+ catch (Exception exception)
+ {
+ // A response factory may throw to simulate a transport failure, which is surfaced as a faulted task.
+ return Task.FromException(exception);
+ }
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs
new file mode 100644
index 00000000..a79ccc3f
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs
@@ -0,0 +1,541 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using Lumina.Plugins.CoverArtArchive.Core;
+using Lumina.Plugins.CoverArtArchive.Core.Api;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings;
+using Lumina.Plugins.CoverArtArchive.UnitTests.Common.TestHelpers;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Api;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveHttpClientTests
+{
+ private const string ARTWORK_JSON = """
+ {
+ "images": [
+ { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", "front": true, "types": [ "Front" ] }
+ ]
+ }
+ """;
+
+ private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111");
+ private static readonly Guid s_releaseGroupId = Guid.Parse("22222222-2222-2222-2222-222222222222");
+
+ private readonly CoverArtArchiveSettingsDtoFixture _coverArtArchiveSettingsDtoFixture = new();
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheReleaseHasArtwork_ShouldDeserializeIt()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient();
+
+ // Act
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.NotNull(result.Images);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", Assert.Single(result.Images)!.Image);
+ Assert.Equal($"/release/{s_releaseId:D}", handler.Requests[0].RequestUri!.AbsolutePath);
+ Assert.Equal("coverartarchive.org", handler.Requests[0].RequestUri!.Host);
+ }
+
+ [Fact]
+ public async Task GetReleaseGroupArtworkAsync_WhenTheReleaseGroupHasArtwork_ShouldDeserializeIt()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient();
+
+ // Act
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseGroupArtworkAsync(s_releaseGroupId, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.NotNull(result.Images);
+ Assert.Single(result.Images);
+ Assert.Equal($"/release-group/{s_releaseGroupId:D}", handler.Requests[0].RequestUri!.AbsolutePath);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheReleaseIsNotFound_ShouldReturnNull()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound));
+
+ // Act
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.Null(result);
+ Assert.Equal(1, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheSameReleaseIsRequestedTwice_ShouldServeTheSecondRequestFromTheCache()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient();
+
+ // Act
+ CoverArtArchiveArtworkResponse? first = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ CoverArtArchiveArtworkResponse? second = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(first);
+ Assert.NotNull(second);
+ Assert.Equal(1, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheReleaseIsNotFound_ShouldCacheTheAbsence()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound));
+
+ // Act
+ CoverArtArchiveArtworkResponse? first = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ CoverArtArchiveArtworkResponse? second = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.Null(first);
+ Assert.Null(second);
+ Assert.Equal(1, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTwoDifferentReleasesAreRequested_ShouldNotShareTheCache()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient();
+
+ // Act
+ await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ await client.GetReleaseArtworkAsync(Guid.NewGuid(), CancellationToken.None);
+
+ // Assert
+ Assert.Equal(2, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheEndpointRedirectsToTheInternetArchive_ShouldFollowItAndDeserializeTheBody()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) =>
+ {
+ if (callIndex == 1)
+ {
+ HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
+ redirect.Headers.Location = new Uri($"https://archive.org/download/mbid-{s_releaseId:D}/index.json");
+ return redirect;
+ }
+ return CreateJsonResponse(ARTWORK_JSON);
+ });
+
+ // Act
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(2, handler.CallCount);
+ Assert.Equal("archive.org", handler.Requests[1].RequestUri!.Host);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheRedirectLocationIsRelative_ShouldResolveItAgainstTheRequest()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) =>
+ {
+ if (callIndex == 1)
+ {
+ HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
+ redirect.Headers.Location = new Uri($"/release/{s_releaseId:D}/index.json", UriKind.Relative);
+ return redirect;
+ }
+ return CreateJsonResponse(ARTWORK_JSON);
+ });
+
+ // Act
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(2, handler.CallCount);
+ Assert.Equal("coverartarchive.org", handler.Requests[1].RequestUri!.Host);
+ Assert.Equal($"/release/{s_releaseId:D}/index.json", handler.Requests[1].RequestUri!.AbsolutePath);
+ }
+
+ [Theory]
+ [InlineData("https://evil.example/index.json")] // an unrelated public host
+ [InlineData("https://localhost/index.json")] // the loopback host name
+ [InlineData("https://127.0.0.1/index.json")] // the IPv4 loopback address
+ [InlineData("https://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint
+ public async Task GetReleaseArtworkAsync_WhenTheRedirectPointsAtADisallowedHost_ShouldThrow(string location)
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) =>
+ {
+ HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
+ redirect.Headers.Location = new Uri(location);
+ return redirect;
+ });
+
+ // Act
+ Task Act()
+ {
+ return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ }
+
+ // Assert
+ await Assert.ThrowsAsync(Act);
+ Assert.Equal(1, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheRedirectDowngradesToPlainHttp_ShouldThrow()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) =>
+ {
+ HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
+ redirect.Headers.Location = new Uri("http://archive.org/index.json");
+ return redirect;
+ });
+
+ // Act
+ Task Act()
+ {
+ return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ }
+
+ // Assert
+ await Assert.ThrowsAsync(Act);
+ Assert.Equal(1, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheEndpointRedirectsTooManyTimes_ShouldThrow()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) =>
+ {
+ HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
+ redirect.Headers.Location = new Uri("https://archive.org/loop/index.json");
+ return redirect;
+ });
+
+ // Act
+ Task Act()
+ {
+ return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ }
+
+ // Assert
+ await Assert.ThrowsAsync(Act);
+ // The initial request plus the maximum number of followed redirects are sent before the loop is detected.
+ Assert.Equal(4, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheFirstAttemptReturns503_ShouldRetryAndSucceed()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => callIndex == 1
+ ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
+ : CreateJsonResponse(ARTWORK_JSON));
+
+ // Act
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(2, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheFirstAttemptIsRateLimited_ShouldRetryAndSucceed()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => callIndex == 1
+ ? new HttpResponseMessage(HttpStatusCode.TooManyRequests)
+ : CreateJsonResponse(ARTWORK_JSON));
+
+ // Act
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(2, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheFirstAttemptThrowsATransportException_ShouldRetryAndSucceed()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => callIndex == 1
+ ? throw new HttpRequestException("Transient failure.")
+ : CreateJsonResponse(ARTWORK_JSON));
+
+ // Act
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(2, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => new HttpResponseMessage(HttpStatusCode.InternalServerError));
+
+ // Act
+ Task Act()
+ {
+ return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ }
+
+ // Assert
+ await Assert.ThrowsAsync(Act);
+ Assert.Equal(3, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheFirstAttemptIsRateLimitedWithRetryAfter_ShouldHonorTheRequestedDelay()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) =>
+ {
+ if (callIndex != 1)
+ return CreateJsonResponse(ARTWORK_JSON);
+ HttpResponseMessage rateLimited = new(HttpStatusCode.TooManyRequests);
+ rateLimited.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.Zero);
+ return rateLimited;
+ });
+
+ // Act
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+ stopwatch.Stop();
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(2, handler.CallCount);
+ // The requested delay of zero is honored instead of the default five hundred millisecond backoff of the first retry.
+ Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(400), $"The elapsed time {stopwatch.Elapsed} shows the Retry-After header was ignored.");
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheContactEmailIsConfigured_ShouldIncludeItInTheUserAgent()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(contactEmail: "contact@example.com");
+
+ // Act
+ await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ string userAgent = handler.Requests[0].Headers.UserAgent.ToString();
+ Assert.Contains("Lumina-Test/1.0", userAgent);
+ Assert.Contains("contact@example.com", userAgent);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheContactEmailIsNotConfigured_ShouldNotIncludeItInTheUserAgent()
+ {
+ // Arrange
+ (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient();
+
+ // Act
+ await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ string userAgent = handler.Requests[0].Headers.UserAgent.ToString();
+ Assert.Equal("Lumina-Test/1.0", userAgent);
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheUserAgentIsAlreadySet_ShouldNotOverrideIt()
+ {
+ // Arrange
+ StubHttpMessageHandler handler = new((request, callIndex) => CreateJsonResponse(ARTWORK_JSON));
+ HttpClient httpClient = new(handler);
+ httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Custom/9.9");
+ CoverArtArchiveSettingsProvider settingsProvider = CreateSettingsProvider(contactEmail: null);
+ CoverArtArchiveHttpClient client = new(httpClient, settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache());
+
+ // Act
+ await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
+
+ // Assert
+ Assert.Equal("Custom/9.9", handler.Requests[0].Headers.UserAgent.ToString());
+ }
+
+ [Fact]
+ public async Task GetReleaseArtworkAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
+ {
+ // Arrange
+ using (CancellationTokenSource cancellationTokenSource = new())
+ {
+ cancellationTokenSource.Cancel();
+ (CoverArtArchiveHttpClient client, _) = CreateClient();
+
+ // Act
+ Task Act()
+ {
+ return client.GetReleaseArtworkAsync(s_releaseId, cancellationTokenSource.Token);
+ }
+
+ // Assert
+ await Assert.ThrowsAnyAsync(Act);
+ }
+ }
+
+ [Fact]
+ public void GetRetryDelay_WhenTheResponseIsNull_ShouldReturnTheExponentialBackoff()
+ {
+ // Act
+ TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, null);
+
+ // Assert
+ Assert.Equal(TimeSpan.FromMilliseconds(500), result);
+ }
+
+ [Fact]
+ public void GetRetryDelay_WhenTheResponseHasNoRetryAfter_ShouldReturnTheExponentialBackoff()
+ {
+ // Arrange
+ HttpResponseMessage response = new(HttpStatusCode.InternalServerError);
+
+ // Act
+ TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(2, response);
+
+ // Assert
+ Assert.Equal(TimeSpan.FromSeconds(1), result);
+ }
+
+ [Fact]
+ public void GetRetryDelay_WhenTheResponseHasARelativeRetryAfter_ShouldReturnTheRequestedDelay()
+ {
+ // Arrange
+ HttpResponseMessage response = new(HttpStatusCode.TooManyRequests);
+ response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(5));
+
+ // Act
+ TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response);
+
+ // Assert
+ Assert.Equal(TimeSpan.FromSeconds(5), result);
+ }
+
+ [Fact]
+ public void GetRetryDelay_WhenTheResponseHasARetryAfterOfZero_ShouldReturnZero()
+ {
+ // Arrange
+ HttpResponseMessage response = new(HttpStatusCode.TooManyRequests);
+ response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.Zero);
+
+ // Act
+ TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response);
+
+ // Assert
+ Assert.Equal(TimeSpan.Zero, result);
+ }
+
+ [Fact]
+ public void GetRetryDelay_WhenTheResponseHasAnAbsoluteRetryAfterInTheFuture_ShouldReturnTheRemainingTime()
+ {
+ // Arrange
+ HttpResponseMessage response = new(HttpStatusCode.TooManyRequests);
+ response.Headers.RetryAfter = new RetryConditionHeaderValue(DateTimeOffset.UtcNow.AddSeconds(5));
+
+ // Act
+ TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response);
+
+ // Assert
+ Assert.True(result > TimeSpan.FromSeconds(4) && result <= TimeSpan.FromSeconds(5), $"The delay {result} was not the remaining time of the absolute Retry-After.");
+ }
+
+ [Fact]
+ public void GetRetryDelay_WhenTheResponseHasAnAbsoluteRetryAfterInThePast_ShouldReturnTheExponentialBackoff()
+ {
+ // Arrange
+ HttpResponseMessage response = new(HttpStatusCode.TooManyRequests);
+ response.Headers.RetryAfter = new RetryConditionHeaderValue(DateTimeOffset.UtcNow.AddSeconds(-5));
+
+ // Act
+ TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response);
+
+ // Assert
+ Assert.Equal(TimeSpan.FromMilliseconds(500), result);
+ }
+
+ [Fact]
+ public void GetRetryDelay_WhenTheRequestedDelayExceedsTheMaximum_ShouldCapIt()
+ {
+ // Arrange
+ HttpResponseMessage response = new(HttpStatusCode.TooManyRequests);
+ response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromDays(10));
+
+ // Act
+ TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response);
+
+ // Assert
+ Assert.Equal(TimeSpan.FromSeconds(60), result);
+ }
+
+ ///
+ /// Creates a whose requests are answered by a stub handler, returning the artwork JSON by default.
+ ///
+ /// Optional. The factory that produces the response of a request.
+ /// Optional. The contact email configured for the client.
+ /// The created client and its stub handler.
+ private (CoverArtArchiveHttpClient Client, StubHttpMessageHandler Handler) CreateClient(
+ Func? responseFactory = null,
+ string? contactEmail = null)
+ {
+ StubHttpMessageHandler handler = new(responseFactory ?? ((request, callIndex) => CreateJsonResponse(ARTWORK_JSON)));
+ CoverArtArchiveSettingsProvider settingsProvider = CreateSettingsProvider(contactEmail);
+ CoverArtArchiveHttpClient client = new(new HttpClient(handler), settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache());
+ return (client, handler);
+ }
+
+ ///
+ /// Creates a settings provider configured for the tests, with no throttling.
+ ///
+ /// Optional. The contact email configured for the client.
+ /// The created settings provider.
+ private CoverArtArchiveSettingsProvider CreateSettingsProvider(string? contactEmail)
+ {
+ return new CoverArtArchiveSettingsProvider(null, CoverArtArchivePlugin.s_pluginId, _coverArtArchiveSettingsDtoFixture.Create(
+ userAgent: "Lumina-Test/1.0",
+ contactEmail: contactEmail,
+ includeContactEmail: contactEmail is not null,
+ minimumRequestInterval: TimeSpan.Zero));
+ }
+
+ ///
+ /// Creates an OK response with the provided JSON body.
+ ///
+ /// The JSON body of the response.
+ /// The created response.
+ private static HttpResponseMessage CreateJsonResponse(string json)
+ {
+ return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveRequestThrottleTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveRequestThrottleTests.cs
new file mode 100644
index 00000000..94e1d6ad
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveRequestThrottleTests.cs
@@ -0,0 +1,106 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.CoverArtArchive.Core.Api;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Api;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveRequestThrottleTests
+{
+ private readonly CoverArtArchiveRequestThrottle _sut = new();
+
+ [Fact]
+ public async Task WaitAsync_WhenTheMinimumIntervalHasNotElapsed_ShouldDelayTheSecondRequest()
+ {
+ // Arrange
+ TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(200);
+
+ // Act
+ await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
+ stopwatch.Stop();
+
+ // Assert
+ // The second request must wait for the remainder of the interval, which is close to the configured interval.
+ Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(150), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected minimum interval.");
+ }
+
+ [Fact]
+ public async Task WaitAsync_WhenTheMinimumIntervalIsZero_ShouldNotDelayTheRequests()
+ {
+ // Arrange
+ TimeSpan minimumRequestInterval = TimeSpan.Zero;
+
+ // Act
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
+ await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
+ stopwatch.Stop();
+
+ // Assert
+ Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay.");
+ }
+
+ [Fact]
+ public async Task WaitAsync_WhenTheMinimumIntervalIsNegative_ShouldNotDelayTheRequests()
+ {
+ // Arrange
+ TimeSpan minimumRequestInterval = TimeSpan.FromSeconds(-1);
+
+ // Act
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
+ await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None);
+ stopwatch.Stop();
+
+ // Assert
+ Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay.");
+ }
+
+ [Fact]
+ public async Task WaitAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException()
+ {
+ // Arrange
+ using (CancellationTokenSource cancellationTokenSource = new())
+ {
+ cancellationTokenSource.Cancel();
+
+ // Act
+ Task Act()
+ {
+ return _sut.WaitAsync(TimeSpan.FromMilliseconds(100), cancellationTokenSource.Token);
+ }
+
+ // Assert
+ await Assert.ThrowsAnyAsync(Act);
+ }
+ }
+
+ [Fact]
+ public async Task WaitAsync_WhenCalledConcurrently_ShouldSpaceOutEveryRequest()
+ {
+ // Arrange
+ TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(150);
+
+ // Act
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ await Task.WhenAll(
+ _sut.WaitAsync(minimumRequestInterval, CancellationToken.None),
+ _sut.WaitAsync(minimumRequestInterval, CancellationToken.None),
+ _sut.WaitAsync(minimumRequestInterval, CancellationToken.None));
+ stopwatch.Stop();
+
+ // Assert
+ // Three requests spaced by the interval take at least two intervals in total.
+ Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(250), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected total interval.");
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveResponseCacheTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveResponseCacheTests.cs
new file mode 100644
index 00000000..b2d0a360
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveResponseCacheTests.cs
@@ -0,0 +1,163 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.CoverArtArchive.Core.Api;
+using System;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Api;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveResponseCacheTests
+{
+ private readonly CoverArtArchiveResponseCache _sut = new();
+
+ [Fact]
+ public void TryGet_WhenTheKeyWasNeverCached_ShouldReturnFalse()
+ {
+ // Act
+ bool result = _sut.TryGet("missing", out string? json);
+
+ // Assert
+ Assert.False(result);
+ Assert.Null(json);
+ }
+
+ [Fact]
+ public void TryGet_WhenTheKeyWasCached_ShouldReturnTheCachedBody()
+ {
+ // Arrange
+ _sut.Set("key", "{\"images\":[]}");
+
+ // Act
+ bool result = _sut.TryGet("key", out string? json);
+
+ // Assert
+ Assert.True(result);
+ Assert.Equal("{\"images\":[]}", json);
+ }
+
+ [Fact]
+ public void Set_WhenTheKeyAlreadyExists_ShouldReplaceTheCachedBody()
+ {
+ // Arrange
+ _sut.Set("key", "a-longer-value");
+ _sut.Set("key", "short");
+
+ // Act
+ bool result = _sut.TryGet("key", out string? json);
+
+ // Assert
+ Assert.True(result);
+ Assert.Equal("short", json);
+ }
+
+ [Fact]
+ public void Set_WhenTheValueIsTheEmptyNotFoundMarker_ShouldCacheIt()
+ {
+ // Arrange
+ _sut.Set("release/11111111-1111-1111-1111-111111111111", string.Empty);
+
+ // Act
+ bool result = _sut.TryGet("release/11111111-1111-1111-1111-111111111111", out string? json);
+
+ // Assert
+ Assert.True(result);
+ Assert.Equal(string.Empty, json);
+ }
+
+ [Fact]
+ public void Set_WhenTheValueFitsTheCharacterBudgetExactly_ShouldCacheIt()
+ {
+ // Arrange
+ CoverArtArchiveResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1));
+
+ // Act
+ sut.Set("exact", "abc");
+
+ // Assert
+ Assert.True(sut.TryGet("exact", out string? json));
+ Assert.Equal("abc", json);
+ }
+
+ [Fact]
+ public void Set_WhenTheValueExceedsTheWholeCharacterBudget_ShouldNotCacheIt()
+ {
+ // Arrange
+ CoverArtArchiveResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1));
+
+ // Act
+ sut.Set("oversized", "abcd");
+
+ // Assert
+ Assert.False(sut.TryGet("oversized", out _));
+ }
+
+ [Fact]
+ public void Set_WhenTheCharacterBudgetIsExceeded_ShouldEvictTheOldestEntryAndKeepTheNewestOne()
+ {
+ // Arrange
+ CoverArtArchiveResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 10, timeToLive: TimeSpan.FromMinutes(1));
+ sut.Set("oldest", "1234567890");
+
+ // Act
+ sut.Set("newest", "x");
+
+ // Assert
+ Assert.False(sut.TryGet("oldest", out _));
+ Assert.True(sut.TryGet("newest", out string? json));
+ Assert.Equal("x", json);
+ }
+
+ [Fact]
+ public void Set_WhenTheEntryCountBudgetIsExceeded_ShouldEvictTheOldestEntriesAndKeepTheNewestOne()
+ {
+ // Arrange
+ CoverArtArchiveResponseCache sut = new(maximumEntryCount: 3, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1));
+ sut.Set("entry-1", "1");
+ sut.Set("entry-2", "2");
+ sut.Set("entry-3", "3");
+
+ // Act
+ sut.Set("entry-4", "4");
+
+ // Assert
+ // The oldest entries are trimmed to the lower water mark, while the most recently cached one always survives.
+ Assert.False(sut.TryGet("entry-1", out _));
+ Assert.False(sut.TryGet("entry-2", out _));
+ Assert.True(sut.TryGet("entry-3", out _));
+ Assert.True(sut.TryGet("entry-4", out _));
+ }
+
+ [Fact]
+ public void Set_WhenTheEntryCountBudgetIsExceededByOne_ShouldEvictTheOldestEntryAndKeepTheNewOne()
+ {
+ // Arrange
+ CoverArtArchiveResponseCache sut = new(maximumEntryCount: 1, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1));
+ sut.Set("entry-1", "1");
+
+ // Act
+ sut.Set("entry-2", "2");
+
+ // Assert
+ Assert.True(sut.TryGet("entry-2", out _));
+ Assert.False(sut.TryGet("entry-1", out _));
+ }
+
+ [Fact]
+ public void TryGet_WhenTheCachedEntryExpired_ShouldReturnFalse()
+ {
+ // Arrange
+ CoverArtArchiveResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMilliseconds(-1));
+ sut.Set("expired", "value");
+
+ // Act
+ bool result = sut.TryGet("expired", out string? json);
+
+ // Assert
+ Assert.False(result);
+ Assert.Null(json);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveAlbumArtworkProviderTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveAlbumArtworkProviderTests.cs
new file mode 100644
index 00000000..ba68eb43
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveAlbumArtworkProviderTests.cs
@@ -0,0 +1,275 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.CoverArtArchive.Core;
+using Lumina.Plugins.CoverArtArchive.Core.Api;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings;
+using Lumina.Plugins.CoverArtArchive.UnitTests.Common.TestHelpers;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveAlbumArtworkProviderTests
+{
+ private const string RELEASE_ARTWORK_JSON = """
+ {
+ "images": [
+ { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", "front": true, "types": [ "Front" ] },
+ { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", "back": true, "types": [ "Back" ] }
+ ]
+ }
+ """;
+
+ private const string RELEASE_GROUP_ARTWORK_JSON = """
+ {
+ "images": [
+ { "image": "https://coverartarchive.org/release-group/22222222-2222-2222-2222-222222222222/front.jpg", "front": true, "types": [ "Front" ] }
+ ]
+ }
+ """;
+
+ private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111");
+ private static readonly Guid s_releaseGroupId = Guid.Parse("22222222-2222-2222-2222-222222222222");
+
+ private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new();
+ private readonly CoverArtArchiveSettingsDtoFixture _coverArtArchiveSettingsDtoFixture = new();
+
+ [Fact]
+ public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, _) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON));
+
+ // Act
+ string result = sut.Name;
+
+ // Assert
+ Assert.Equal("Cover Art Archive", result);
+ }
+
+ [Fact]
+ public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, _) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON));
+
+ // Act
+ IReadOnlyList result = sut.SupportedLibraryTypes;
+
+ // Assert
+ Assert.Equal([LibraryType.Music], result);
+ }
+
+ [Fact]
+ public void RequiresWebAccess_WhenCalled_ShouldReturnTrue()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, _) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON));
+
+ // Act
+ bool result = sut.RequiresWebAccess;
+
+ // Assert
+ Assert.True(result);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenTheReleaseIdentifierIsPresent_ShouldFetchAndMapTheReleaseArtwork()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId);
+
+ // Act
+ IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Equal(2, result.Count);
+ Assert.Equal(ArtworkType.Cover, result[0].Type);
+ Assert.Equal(0, result[0].Ordinal);
+ Assert.Null(result[0].LocalPath);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", result[0].RemoteUrl);
+ Assert.Equal(ArtworkType.Back, result[1].Type);
+ Assert.Equal(0, result[1].Ordinal);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", result[1].RemoteUrl);
+ Assert.Equal(1, handler.CallCount);
+ Assert.Equal($"/release/{s_releaseId:D}", handler.Requests[0].RequestUri!.AbsolutePath);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenBothIdentifiersArePresent_ShouldPreferTheRelease()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse(
+ request.RequestUri!.AbsolutePath.Contains("/release-group/") ? RELEASE_GROUP_ARTWORK_JSON : RELEASE_ARTWORK_JSON));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzReleaseGroupId: s_releaseGroupId);
+
+ // Act
+ IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Equal(2, result.Count);
+ Assert.Equal(1, handler.CallCount);
+ Assert.Equal($"/release/{s_releaseId:D}", handler.Requests[0].RequestUri!.AbsolutePath);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenTheReleaseHasNoArtwork_ShouldFallBackToTheReleaseGroup()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse(
+ request.RequestUri!.AbsolutePath.Contains("/release-group/") ? RELEASE_GROUP_ARTWORK_JSON : """{"images":[]}"""));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzReleaseGroupId: s_releaseGroupId);
+
+ // Act
+ IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal(ArtworkType.Cover, artwork.Type);
+ Assert.Equal("https://coverartarchive.org/release-group/22222222-2222-2222-2222-222222222222/front.jpg", artwork.RemoteUrl);
+ Assert.Equal(2, handler.CallCount);
+ Assert.Equal($"/release/{s_releaseId:D}", handler.Requests[0].RequestUri!.AbsolutePath);
+ Assert.Equal($"/release-group/{s_releaseGroupId:D}", handler.Requests[1].RequestUri!.AbsolutePath);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenTheReleaseIsNotFound_ShouldFallBackToTheReleaseGroup()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) =>
+ request.RequestUri!.AbsolutePath.Contains("/release-group/")
+ ? CreateJsonResponse(RELEASE_GROUP_ARTWORK_JSON)
+ : new HttpResponseMessage(HttpStatusCode.NotFound));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzReleaseGroupId: s_releaseGroupId);
+
+ // Act
+ IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Single(result);
+ Assert.Equal(2, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenTheReleaseHasNoArtworkAndThereIsNoReleaseGroupIdentifier_ShouldReturnEmpty()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse("""{"images":[]}"""));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId);
+
+ // Act
+ IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Empty(result);
+ Assert.Equal(1, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenTheReleaseGroupIdentifierIsPresent_ShouldFetchTheReleaseGroupArtwork()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_GROUP_ARTWORK_JSON));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId);
+
+ // Act
+ IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Single(result);
+ Assert.Equal($"/release-group/{s_releaseGroupId:D}", handler.Requests[0].RequestUri!.AbsolutePath);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenTheReleaseGroupIsNotFound_ShouldReturnEmpty()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId);
+
+ // Act
+ IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Empty(result);
+ Assert.Equal(1, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenThereIsNoIdentifierAtAll_ShouldReturnEmptyWithoutAnyRequest()
+ {
+ // Arrange
+ (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path");
+
+ // Act
+ IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Empty(result);
+ Assert.Equal(0, handler.CallCount);
+ }
+
+ [Fact]
+ public async Task GetArtworkAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
+ {
+ // Arrange
+ using (CancellationTokenSource cancellationTokenSource = new())
+ {
+ cancellationTokenSource.Cancel();
+ (CoverArtArchiveAlbumArtworkProvider sut, _) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON));
+ AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId);
+
+ // Act
+ Task Act()
+ {
+ return sut.GetArtworkAsync(lookup, cancellationTokenSource.Token);
+ }
+
+ // Assert
+ await Assert.ThrowsAnyAsync(Act);
+ }
+ }
+
+ ///
+ /// Creates a whose requests are answered by the provided stub handler.
+ ///
+ /// The factory that produces the response of a request.
+ /// The created provider and its stub handler.
+ private (CoverArtArchiveAlbumArtworkProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func responseFactory)
+ {
+ StubHttpMessageHandler handler = new(responseFactory);
+ CoverArtArchiveSettingsProvider settingsProvider = new(null, CoverArtArchivePlugin.s_pluginId, _coverArtArchiveSettingsDtoFixture.Create(
+ userAgent: "Lumina-Test/1.0",
+ includeContactEmail: false,
+ minimumRequestInterval: TimeSpan.Zero));
+ CoverArtArchiveHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache());
+ return (new CoverArtArchiveAlbumArtworkProvider(httpClient), handler);
+ }
+
+ ///
+ /// Creates an OK response with the provided JSON body.
+ ///
+ /// The JSON body of the response.
+ /// The created response.
+ private static HttpResponseMessage CreateJsonResponse(string json)
+ {
+ return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveHostsTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveHostsTests.cs
new file mode 100644
index 00000000..d35c7005
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveHostsTests.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.CoverArtArchive.Core;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveHostsTests
+{
+ [Theory]
+ [InlineData("coverartarchive.org")] // the Cover Art Archive host
+ [InlineData("archive.org")] // the Internet Archive host
+ [InlineData("ia800100.us.archive.org")] // a subdomain of the Internet Archive that serves its downloads
+ [InlineData("media.coverartarchive.org")] // a subdomain of the Cover Art Archive
+ public void IsAllowed_WhenTheHostIsATrustedArchiveHost_ShouldReturnTrue(string host)
+ {
+ // Act
+ bool result = CoverArtArchiveHosts.IsAllowed(host);
+
+ // Assert
+ Assert.True(result);
+ }
+
+ [Theory]
+ [InlineData("COVERARTARCHIVE.ORG")] // the Cover Art Archive host, upper cased
+ [InlineData("Archive.Org")] // the Internet Archive host, mixed cased
+ public void IsAllowed_WhenTheHostDiffersOnlyByCase_ShouldReturnTrue(string host)
+ {
+ // Act
+ bool result = CoverArtArchiveHosts.IsAllowed(host);
+
+ // Assert
+ Assert.True(result);
+ }
+
+ [Theory]
+ [InlineData("")] // an empty host
+ [InlineData(" ")] // only white space
+ [InlineData("localhost")] // the loopback host name
+ [InlineData("127.0.0.1")] // the IPv4 loopback address
+ [InlineData("169.254.169.254")] // the link local cloud metadata endpoint
+ [InlineData("10.0.0.5")] // a private class A address
+ [InlineData("192.168.1.10")] // a private class C address
+ [InlineData("evil.example")] // an unrelated public host
+ [InlineData("coverartarchive.org.evil.example")] // the trusted host used as a prefix of an attacker controlled host
+ [InlineData("archive.org.evil.example")] // the Internet Archive host used as a prefix of an attacker controlled host
+ [InlineData("notcoverartarchive.org")] // a suffix collision that is not a subdomain
+ [InlineData("notarchive.org")] // a suffix collision that is not a subdomain
+ public void IsAllowed_WhenTheHostIsNotATrustedArchiveHost_ShouldReturnFalse(string host)
+ {
+ // Act
+ bool result = CoverArtArchiveHosts.IsAllowed(host);
+
+ // Assert
+ Assert.False(result);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchivePluginTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchivePluginTests.cs
new file mode 100644
index 00000000..056bc9fd
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchivePluginTests.cs
@@ -0,0 +1,121 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
+using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.CoverArtArchive.Core;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchivePluginTests
+{
+ private readonly CoverArtArchivePlugin _sut = new();
+
+ [Fact]
+ public void Id_WhenCalled_ShouldReturnStablePluginIdentifier()
+ {
+ // Act
+ Guid result = _sut.Id;
+
+ // Assert
+ Assert.Equal(CoverArtArchivePlugin.s_pluginId, result);
+ Assert.Equal(new Guid("b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14"), result);
+ }
+
+ [Fact]
+ public void Name_WhenCalled_ShouldReturnPluginDisplayName()
+ {
+ // Act
+ string result = _sut.Name;
+
+ // Assert
+ Assert.Equal("Cover Art Archive", result);
+ }
+
+ [Fact]
+ public void Author_WhenCalled_ShouldReturnPluginAuthor()
+ {
+ // Act
+ string result = _sut.Author;
+
+ // Assert
+ Assert.Equal("Lumina", result);
+ }
+
+ [Fact]
+ public void Version_WhenCalled_ShouldReturnPluginVersion()
+ {
+ // Act
+ Version result = _sut.Version;
+
+ // Assert
+ Assert.Equal(new Version(1, 0, 0), result);
+ }
+
+ [Fact]
+ public void Description_WhenCalled_ShouldReturnPluginDescription()
+ {
+ // Act
+ string result = _sut.Description;
+
+ // Assert
+ Assert.Equal("Retrieves the cover, back, booklet, medium and other artwork of music albums from the Cover Art Archive.", result);
+ }
+
+ [Fact]
+ public void GetSettingsSchema_WhenCalled_ShouldReturnTheTwoSettingDescriptors()
+ {
+ // Act
+ IReadOnlyList result = _sut.GetSettingsSchema();
+
+ // Assert
+ Assert.Equal(2, result.Count);
+ Assert.Equal(
+ [
+ CoverArtArchiveSettingsKeys.CONTACT_EMAIL,
+ CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS
+ ],
+ result.Select(descriptor => descriptor.Key));
+ }
+
+ [Theory]
+ [InlineData(CoverArtArchiveSettingsKeys.CONTACT_EMAIL, "Contact Email", PluginSettingType.Text, null)]
+ [InlineData(CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, "Minimum Request Interval (seconds)", PluginSettingType.Number, "1.0")]
+ public void GetSettingsSchema_WhenCalled_ShouldDescribeEachSettingCorrectly(string key, string label, PluginSettingType type, string? defaultValue)
+ {
+ // Act
+ IReadOnlyList result = _sut.GetSettingsSchema();
+
+ // Assert
+ PluginSettingDescriptorDto descriptor = Assert.Single(result, candidate => candidate.Key == key);
+ Assert.Equal(label, descriptor.Label);
+ Assert.Equal(type, descriptor.Type);
+ Assert.Equal(defaultValue, descriptor.DefaultValue);
+ Assert.Null(descriptor.AllowedValues);
+ }
+
+ [Fact]
+ public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedArtworkProvider()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ _sut.RegisterServices(services);
+ ServiceProvider serviceProvider = services.BuildServiceProvider();
+
+ // Assert
+ Assert.Single(serviceProvider.GetKeyedServices(CoverArtArchivePlugin.s_pluginId));
+ Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid()));
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Mapping/CoverArtArchiveMapperTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Mapping/CoverArtArchiveMapperTests.cs
new file mode 100644
index 00000000..82273ab1
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Mapping/CoverArtArchiveMapperTests.cs
@@ -0,0 +1,397 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
+using Lumina.Plugins.CoverArtArchive.Core.Mapping;
+using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.Contracts.Responses;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Mapping;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveMapperTests
+{
+ private const string COVER_URL = "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg";
+
+ private readonly CoverArtArchiveArtworkResponseFixture _coverArtArchiveArtworkResponseFixture = new();
+ private readonly CoverArtArchiveImageResponseFixture _coverArtArchiveImageResponseFixture = new();
+
+ [Fact]
+ public void MapArtwork_WhenTheResponseIsNull_ShouldReturnEmpty()
+ {
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(null);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenTheImagesCollectionIsNull_ShouldReturnEmpty()
+ {
+ // Arrange
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(includeImages: false);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenThereAreNoImages_ShouldReturnEmpty()
+ {
+ // Arrange
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: []);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenAnImageElementIsNull_ShouldSkipIt()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse validImage = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [null, validImage]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal(COVER_URL, artwork.RemoteUrl);
+ }
+
+ [Theory]
+ [InlineData(null)] // a null URL
+ [InlineData("")] // an empty URL
+ [InlineData(" ")] // a white space URL
+ public void MapArtwork_WhenTheImageUrlIsMissing_ShouldSkipIt(string? imageUrl)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: imageUrl, includeImage: imageUrl is not null, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Theory]
+ [InlineData("not-a-url")] // a value that is not an URI at all
+ [InlineData("/release/11111111-1111-1111-1111-111111111111/1.jpg")] // a relative URI
+ [InlineData("coverartarchive.org/release/1.jpg")] // a host without a scheme
+ public void MapArtwork_WhenTheImageUrlIsNotAnAbsoluteUri_ShouldSkipIt(string imageUrl)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: imageUrl, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Theory]
+ [InlineData("http://localhost/release/1.jpg")] // the loopback host name
+ [InlineData("http://127.0.0.1/release/1.jpg")] // the IPv4 loopback address
+ [InlineData("http://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint
+ [InlineData("http://10.0.0.5/release/1.jpg")] // a private class A address
+ [InlineData("http://192.168.1.10/release/1.jpg")] // a private class C address
+ [InlineData("https://evil.example/release/1.jpg")] // an unrelated public host
+ [InlineData("https://coverartarchive.org.evil.example/1.jpg")] // the trusted host used as a prefix of an attacker controlled host
+ [InlineData("https://archive.org.evil.example/1.jpg")] // the Internet Archive host used as a prefix of an attacker controlled host
+ public void MapArtwork_WhenTheImageUrlPointsAtAnUntrustedHost_ShouldSkipIt(string imageUrl)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: imageUrl, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Theory]
+ [InlineData("file:///etc/passwd")] // a local file URI
+ [InlineData("ftp://coverartarchive.org/1.jpg")] // an unsupported scheme on a trusted host
+ [InlineData("data:image/png;base64,SGVsbG8=")] // an inline data URI
+ public void MapArtwork_WhenTheImageUrlUsesAnUnsupportedScheme_ShouldSkipIt(string imageUrl)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: imageUrl, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenTheImageUrlUsesPlainHttpOnATrustedHost_ShouldUpgradeItToHttps()
+ {
+ // Arrange
+ const string HTTP_URL = "http://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg";
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: HTTP_URL, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", artwork.RemoteUrl);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenTheImageUrlUsesHttpsOnATrustedHost_ShouldKeepIt()
+ {
+ // Arrange
+ const string ARCHIVE_URL = "https://archive.org/download/mbid-11111111-1111-1111-1111-111111111111/1.jpg";
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: ARCHIVE_URL, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal(ARCHIVE_URL, artwork.RemoteUrl);
+ }
+
+ [Theory]
+ [InlineData("front", ArtworkType.Cover)] // the front cover type, lower cased
+ [InlineData("Front", ArtworkType.Cover)] // the front cover type
+ [InlineData("BACK", ArtworkType.Back)] // the back cover type, upper cased
+ [InlineData("Booklet", ArtworkType.Booklet)] // a booklet page
+ [InlineData("Medium", ArtworkType.Medium)] // a medium label
+ [InlineData("Tray", ArtworkType.Tray)] // the tray artwork
+ [InlineData("Spine", ArtworkType.Spine)] // the spine artwork
+ [InlineData("Obi", ArtworkType.Obi)] // the obi strip
+ [InlineData("Sticker", ArtworkType.Sticker)] // the sticker
+ [InlineData("Poster", ArtworkType.Poster)] // the poster
+ [InlineData("Liner", ArtworkType.Liner)] // the liner notes
+ [InlineData("Watermark", ArtworkType.Watermark)] // a watermark
+ [InlineData(" Booklet ", ArtworkType.Booklet)] // a type with surrounding white space
+ [InlineData("SomeUnknownType", ArtworkType.Other)] // an unknown type is kept as generic artwork
+ public void MapArtwork_WhenTheImageIsTaggedWithAType_ShouldMapItToTheExpectedArtworkType(string type, ArtworkType expectedArtworkType)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: [type]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal(expectedArtworkType, artwork.Type);
+ Assert.Equal(COVER_URL, artwork.RemoteUrl);
+ Assert.Equal(0, artwork.Ordinal);
+ Assert.Null(artwork.LocalPath);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenTheTypesAreNullAndTheImageIsFront_ShouldFallBackToCover()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, includeTypes: false, isFront: true, isBack: false);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal(ArtworkType.Cover, artwork.Type);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenTheTypesAreNullAndTheImageIsBack_ShouldFallBackToBack()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, includeTypes: false, isFront: false, isBack: true);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ ArtworkDto artwork = Assert.Single(result);
+ Assert.Equal(ArtworkType.Back, artwork.Type);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenTheTypesAreNullAndTheImageIsNeitherFrontNorBack_ShouldSkipIt()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, includeTypes: false, isFront: false, isBack: false);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Empty(result);
+ }
+
+ [Theory]
+ [InlineData(null)] // a null element inside the types collection
+ [InlineData("")] // an empty element inside the types collection
+ [InlineData(" ")] // a white space element inside the types collection
+ public void MapArtwork_WhenTheTypesCollectionContainsNullOrEmptyElements_ShouldSkipThem(string? type)
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: [type], isFront: false, isBack: false);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ // With no usable type and no front or back flag, the image describes no artwork at all.
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenTheTypesCollectionContainsDuplicates_ShouldDeDuplicateAndKeepTheResponseOrder()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: ["Booklet", "Front", "Booklet", "Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Equal(2, result.Count);
+ Assert.Equal(ArtworkType.Booklet, result[0].Type);
+ Assert.Equal(ArtworkType.Cover, result[1].Type);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenAnImageIsTaggedWithSeveralTypes_ShouldEmitThemInTheOrderOfTheResponse()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: ["Front", "Back", "Booklet"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Equal(3, result.Count);
+ Assert.Equal(ArtworkType.Cover, result[0].Type);
+ Assert.Equal(ArtworkType.Back, result[1].Type);
+ Assert.Equal(ArtworkType.Booklet, result[2].Type);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenSeveralImagesShareAType_ShouldAssignIncrementingOrdinals()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse firstPage = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?page=1", types: ["Booklet"]);
+ CoverArtArchiveImageResponse secondPage = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?page=2", types: ["Booklet"]);
+ CoverArtArchiveImageResponse thirdPage = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?page=3", types: ["Booklet"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [firstPage, secondPage, thirdPage]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Equal(3, result.Count);
+ Assert.All(result, artwork => Assert.Equal(ArtworkType.Booklet, artwork.Type));
+ Assert.Equal(0, result[0].Ordinal);
+ Assert.Equal(1, result[1].Ordinal);
+ Assert.Equal(2, result[2].Ordinal);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenSeveralTypesArePresent_ShouldAssignIndependentOrdinalsPerType()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse cover = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?c=1", types: ["Front"]);
+ CoverArtArchiveImageResponse booklet = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?b=1", types: ["Booklet"]);
+ CoverArtArchiveImageResponse secondCover = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?c=2", types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [cover, booklet, secondCover]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Equal(3, result.Count);
+ Assert.Equal(ArtworkType.Cover, result[0].Type);
+ Assert.Equal(0, result[0].Ordinal);
+ Assert.Equal(ArtworkType.Booklet, result[1].Type);
+ Assert.Equal(0, result[1].Ordinal);
+ Assert.Equal(ArtworkType.Cover, result[2].Type);
+ Assert.Equal(1, result[2].Ordinal);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenEveryFieldIsPresent_ShouldMapEveryArtwork()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse front = _coverArtArchiveImageResponseFixture.Create(
+ image: "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg",
+ types: ["Front"],
+ isFront: true,
+ isBack: false);
+ CoverArtArchiveImageResponse backAndMedium = _coverArtArchiveImageResponseFixture.Create(
+ image: "http://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg",
+ types: ["Back", "Medium"],
+ isFront: false,
+ isBack: true);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [front, backAndMedium]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.Equal(3, result.Count);
+ Assert.Equal(ArtworkType.Cover, result[0].Type);
+ Assert.Equal(0, result[0].Ordinal);
+ Assert.Null(result[0].LocalPath);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", result[0].RemoteUrl);
+ Assert.Equal(ArtworkType.Back, result[1].Type);
+ Assert.Equal(0, result[1].Ordinal);
+ Assert.Null(result[1].LocalPath);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", result[1].RemoteUrl);
+ Assert.Equal(ArtworkType.Medium, result[2].Type);
+ Assert.Equal(0, result[2].Ordinal);
+ Assert.Null(result[2].LocalPath);
+ Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", result[2].RemoteUrl);
+ }
+
+ [Fact]
+ public void MapArtwork_WhenCalled_ShouldNeverEmitALocalPath()
+ {
+ // Arrange
+ CoverArtArchiveImageResponse front = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: ["Front"]);
+ CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [front]);
+
+ // Act
+ IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response);
+
+ // Assert
+ Assert.All(result, artwork => Assert.Null(artwork.LocalPath));
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Settings/CoverArtArchiveSettingsProviderTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Settings/CoverArtArchiveSettingsProviderTests.cs
new file mode 100644
index 00000000..27423268
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Settings/CoverArtArchiveSettingsProviderTests.cs
@@ -0,0 +1,212 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
+using Lumina.Plugins.CoverArtArchive.Core.Settings;
+using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Settings;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class CoverArtArchiveSettingsProviderTests
+{
+ private readonly CoverArtArchiveSettingsDtoFixture _coverArtArchiveSettingsDtoFixture = new();
+
+ [Fact]
+ public async Task GetAsync_WhenNoStoreIsAvailable_ShouldReturnTheDefaults()
+ {
+ // Arrange
+ CoverArtArchiveSettingsDto defaults = CreateDefaults();
+ CoverArtArchiveSettingsProvider sut = new(null, Guid.NewGuid(), defaults);
+
+ // Act
+ CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.NotSame(defaults, result);
+ Assert.Equal("Lumina-CoverArtArchive/1.0", result.UserAgent);
+ Assert.Equal("default@example.com", result.ContactEmail);
+ Assert.Equal(TimeSpan.FromSeconds(1), result.MinimumRequestInterval);
+ }
+
+ [Fact]
+ public async Task GetAsync_WhenTheStoreReturnsNoSettings_ShouldReturnTheDefaults()
+ {
+ // Arrange
+ IPluginSettingsStore mockStore = Substitute.For();
+ mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns((IReadOnlyDictionary?)null);
+ CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
+
+ // Act
+ CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.Equal("Lumina-CoverArtArchive/1.0", result.UserAgent);
+ Assert.Equal("default@example.com", result.ContactEmail);
+ Assert.Equal(TimeSpan.FromSeconds(1), result.MinimumRequestInterval);
+ }
+
+ [Fact]
+ public async Task GetAsync_WhenEverySettingIsPersisted_ShouldOverlayThemOverTheDefaults()
+ {
+ // Arrange
+ IPluginSettingsStore mockStore = Substitute.For();
+ mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(
+ new Dictionary
+ {
+ [CoverArtArchiveSettingsKeys.CONTACT_EMAIL] = " contact@example.com ",
+ [CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "2.5"
+ });
+ CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
+
+ // Act
+ CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.Equal("contact@example.com", result.ContactEmail);
+ Assert.Equal(TimeSpan.FromSeconds(2.5), result.MinimumRequestInterval);
+ }
+
+ [Theory]
+ [InlineData("user\r\n@example.com")] // carriage return and line feed injection
+ [InlineData("user@example.com\r\nX-Injected: value")] // header injection attempt
+ [InlineData("user(comment)@example.com")] // parentheses break the user agent comment
+ [InlineData("user\"quoted\"@example.com")] // quotes break the header value
+ [InlineData("user example@example.com")] // an inner space is not a valid token character
+ public async Task GetAsync_WhenThePersistedContactEmailContainsUnsafeCharacters_ShouldDropIt(string storedEmail)
+ {
+ // Arrange
+ IPluginSettingsStore mockStore = Substitute.For();
+ mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(
+ new Dictionary { [CoverArtArchiveSettingsKeys.CONTACT_EMAIL] = storedEmail });
+ CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
+
+ // Act
+ CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.Null(result.ContactEmail);
+ }
+
+ [Theory]
+ [InlineData("", null)] // an empty value clears the email
+ [InlineData(" ", null)] // a white space value clears the email
+ [InlineData(" user@example.com ", "user@example.com")] // a value with surrounding white space is trimmed
+ public async Task GetAsync_WhenThePersistedContactEmailIsPresent_ShouldSetOrClearIt(string storedEmail, string? expectedEmail)
+ {
+ // Arrange
+ IPluginSettingsStore mockStore = Substitute.For();
+ mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(
+ new Dictionary { [CoverArtArchiveSettingsKeys.CONTACT_EMAIL] = storedEmail });
+ CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
+
+ // Act
+ CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.Equal(expectedEmail, result.ContactEmail);
+ }
+
+ [Theory]
+ [InlineData("2.5", 2.5)]
+ [InlineData("0", 0)] // an interval of zero is allowed
+ [InlineData("-3", 0)] // a negative interval is clamped to zero
+ [InlineData("not-a-number", 1)] // an unparsable value keeps the default
+ [InlineData("NaN", 1)] // a non finite value keeps the default
+ [InlineData("Infinity", 1)] // a non finite value keeps the default
+ [InlineData("-Infinity", 1)] // a non finite value keeps the default
+ [InlineData("1e400", 1)] // a value that overflows the double range keeps the default
+ [InlineData("1e308", 60)] // a huge but finite value is clamped to the maximum
+ [InlineData("1000", 60)] // a value above the maximum is clamped
+ [InlineData("60", 60)] // the maximum itself is kept
+ [InlineData("59", 59)] // a value within the range is kept
+ public async Task GetAsync_WhenThePersistedMinimumRequestIntervalIsPresent_ShouldParseAndClampIt(string storedInterval, double expectedSeconds)
+ {
+ // Arrange
+ IPluginSettingsStore mockStore = Substitute.For();
+ mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(
+ new Dictionary { [CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = storedInterval });
+ CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
+
+ // Act
+ CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.Equal(TimeSpan.FromSeconds(expectedSeconds), result.MinimumRequestInterval);
+ }
+
+ [Fact]
+ public async Task GetAsync_WhenCalledTwice_ShouldReadTheStoreOnlyOnce()
+ {
+ // Arrange
+ IPluginSettingsStore mockStore = Substitute.For();
+ mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary());
+ CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
+
+ // Act
+ CoverArtArchiveSettingsDto first = await sut.GetAsync(CancellationToken.None);
+ CoverArtArchiveSettingsDto second = await sut.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.Same(first, second);
+ await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce()
+ {
+ // Arrange
+ IPluginSettingsStore mockStore = Substitute.For();
+ mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary());
+ CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
+
+ // Act
+ CoverArtArchiveSettingsDto[] results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => sut.GetAsync(CancellationToken.None)));
+
+ // Assert
+ Assert.All(results, result => Assert.Same(results[0], result));
+ await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task GetAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException()
+ {
+ // Arrange
+ using (CancellationTokenSource cancellationTokenSource = new())
+ {
+ cancellationTokenSource.Cancel();
+ CoverArtArchiveSettingsProvider sut = new(null, Guid.NewGuid(), CreateDefaults());
+
+ // Act
+ Task Act()
+ {
+ return sut.GetAsync(cancellationTokenSource.Token);
+ }
+
+ // Assert
+ await Assert.ThrowsAnyAsync(Act);
+ }
+ }
+
+ ///
+ /// Creates the default settings used by the tests of the provider.
+ ///
+ /// The default settings.
+ private CoverArtArchiveSettingsDto CreateDefaults()
+ {
+ return _coverArtArchiveSettingsDtoFixture.Create(
+ userAgent: "Lumina-CoverArtArchive/1.0",
+ contactEmail: "default@example.com",
+ minimumRequestInterval: TimeSpan.FromSeconds(1));
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests.csproj
new file mode 100644
index 00000000..9e897ea9
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests.csproj
@@ -0,0 +1,48 @@
+
+
+
+ net10.0
+ disable
+ enable
+
+ false
+ true
+
+
+
+
+ <_Parameter1>DisableTestParallelization = true
+ <_Parameter1_IsLiteral>true
+
+
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+