diff --git a/skills/release-api-responses/SKILL.md b/skills/release-api-responses/SKILL.md new file mode 100644 index 0000000..8f435f1 --- /dev/null +++ b/skills/release-api-responses/SKILL.md @@ -0,0 +1,22 @@ +--- +name: release-api-responses +description: Safely consume configured Forgejo release manifests in Heimdall Central. +--- + +# Release API responses + +The Central `UpdatesController` reads a configured Forgejo latest-release endpoint and serves the result to anonymous update checks and authenticated agents. Treat both the JSON document and subsequent release assets as untrusted network input. + +## Implementation + +- Keep the release endpoint HTTPS-only and preserve its current upstream failure behavior (`null` internally and HTTP 502 at the API boundary). +- Read the release document with a fixed byte limit before deserialization. Check `Content-Length` as an early rejection, but enforce the limit while streaming because the header can be missing or incorrect. +- Catch `JsonException` at the provider parsing boundary. Return unavailable data without logging response bodies; do not convert request cancellation into an ordinary provider failure. +- Keep asset downloads independently bounded and digest-verified. Do not expand this change to provider retries, endpoint configuration, or public response contracts without a separate acceptance requirement. + +## Acceptance workflow + +1. Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore` for malformed HTML, invalid JSON, a valid release document, and the response size limit. +2. Run the Web project build with the SDK pinned by `global.json`. +3. Run the disposable Compose procedure in `compose-disposable-recipe` from the exact changed source. Configure a synthetic HTTPS provider endpoint that can return a valid Forgejo document and an HTML 200 response; probe the public update endpoint and verify valid data succeeds while malformed provider data yields the established 502 response. +4. Record the unique Compose project, exact built image tag, sanitized HTTP outcomes, teardown verification for containers/volumes/networks, and tag absence in the linked Gitea issue. Never use production provider configuration or credentials. diff --git a/src/Heimdall.Web/Controllers/UpdatesController.cs b/src/Heimdall.Web/Controllers/UpdatesController.cs index ff57c14..3e3670f 100644 --- a/src/Heimdall.Web/Controllers/UpdatesController.cs +++ b/src/Heimdall.Web/Controllers/UpdatesController.cs @@ -33,6 +33,7 @@ public class UpdatesController : ControllerBase private static readonly object _cacheLock = new(); private static LatestReleaseCache? _cache; private static readonly TimeSpan CacheDuration = TimeSpan.FromHours(1); + private const int MaxReleaseResponseBytes = 1_048_576; public UpdatesController(IHttpClientFactory httpClientFactory, ILogger logger, IConfigBroadcastService configBroadcast, ResourceAccess resourceAccess, IServiceProvider services) { @@ -122,7 +123,7 @@ public class UpdatesController : ControllerBase using var response = await GetReleaseResponseWithRetryAsync(client, sourceUri, ct); if (response is null || !response.IsSuccessStatusCode) return null; - var release = await response.Content.ReadFromJsonAsync(Json, ct); + var release = await ReadForgejoReleaseAsync(response.Content, ct); if (release is null) return null; var assets = new Dictionary(); foreach (var asset in release.Assets ?? []) @@ -168,6 +169,34 @@ public class UpdatesController : ControllerBase catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; } } + private static async Task ReadForgejoReleaseAsync(HttpContent content, CancellationToken ct) + { + if (content.Headers.ContentLength is long length && length > MaxReleaseResponseBytes) + return null; + + try + { + await using var stream = await content.ReadAsStreamAsync(ct).ConfigureAwait(false); + using var buffer = new MemoryStream(); + var chunk = new byte[8192]; + while (true) + { + var read = await stream.ReadAsync(chunk, ct).ConfigureAwait(false); + if (read == 0) break; + if (buffer.Length + read > MaxReleaseResponseBytes) return null; + buffer.Write(chunk, 0, read); + } + + return JsonSerializer.Deserialize(buffer.ToArray(), Json); + } + catch (JsonException) + { + // Release providers and intermediaries can return HTML or malformed JSON. + // Treat that as an unavailable release, without logging untrusted response content. + return null; + } + } + private async Task GetReleaseResponseWithRetryAsync(HttpClient client, Uri sourceUri, CancellationToken ct) diff --git a/tests/Heimdall.Web.Tests/Controllers/UpdatesControllerRetryTests.cs b/tests/Heimdall.Web.Tests/Controllers/UpdatesControllerRetryTests.cs index 0166b9f..2c7ce8a 100644 --- a/tests/Heimdall.Web.Tests/Controllers/UpdatesControllerRetryTests.cs +++ b/tests/Heimdall.Web.Tests/Controllers/UpdatesControllerRetryTests.cs @@ -1,6 +1,7 @@ using System.Net; using System.Net.Http; using System.Reflection; +using System.Text; using Heimdall.Api.Controllers; using Xunit; @@ -8,6 +9,60 @@ namespace Heimdall.Web.Tests.Controllers; public sealed class UpdatesControllerRetryTests { + [Theory] + [InlineData("Proxy error")] + [InlineData("{not-json")] + public async Task ReadForgejoReleaseAsync_returns_null_for_non_json_responses(string body) + { + var result = await ReadReleaseAsync(new StringContent(body, Encoding.UTF8, "text/html")); + + Assert.Null(result); + } + + [Fact] + public async Task ReadForgejoReleaseAsync_returns_release_for_valid_json() + { + var result = await ReadReleaseAsync(new StringContent( + "{\"tag_name\":\"v1.2.3\",\"body\":\"notes\"}", Encoding.UTF8, "application/json")); + + Assert.NotNull(result); + Assert.Equal("v1.2.3", result.GetType().GetProperty("TagName")?.GetValue(result)); + Assert.Equal("notes", result.GetType().GetProperty("Body")?.GetValue(result)); + } + + [Fact] + public async Task ReadForgejoReleaseAsync_rejects_content_larger_than_limit() + { + using var content = new StringContent("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentLength = 1_048_577; + + var result = await ReadReleaseAsync(content); + + Assert.Null(result); + } + + [Fact] + public async Task ReadForgejoReleaseAsync_rejects_oversized_stream_without_content_length() + { + using var content = new StringContent(new string(' ', 1_048_577), Encoding.UTF8, "application/json"); + content.Headers.ContentLength = null; + + var result = await ReadReleaseAsync(content); + + Assert.Null(result); + } + + private static async Task ReadReleaseAsync(HttpContent content) + { + var method = typeof(UpdatesController).GetMethod("ReadForgejoReleaseAsync", + BindingFlags.NonPublic | BindingFlags.Static); + Assert.NotNull(method); + var task = method.Invoke(null, [content, CancellationToken.None]); + Assert.NotNull(task); + await (Task)task; + return task.GetType().GetProperty("Result")?.GetValue(task); + } + [Theory] [InlineData(HttpStatusCode.RequestTimeout, true)] [InlineData(HttpStatusCode.TooManyRequests, true)]