fix: handle invalid release API JSON (#280)
Heimdall Gitea / Detect CI scope (pull_request) Successful in 6s
Heimdall Gitea / Build and tests (pull_request) Successful in 17m51s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 8m25s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 11m28s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Successful in 19m34s
Heimdall Gitea / CI policy (pull_request) Successful in 4s

This commit is contained in:
arnaud.dartois committed 2026-11-07 18:19:56 +01:00
1 parent 7869800ea5
commit cf017b49da
3 files changed
+107 -1

No files matched your search

+22
View File
@@ -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.
@@ -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<UpdatesController> 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<ForgejoRelease>(Json, ct);
var release = await ReadForgejoReleaseAsync(response.Content, ct);
if (release is null) return null;
var assets = new Dictionary<string, PlatformAsset>();
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<ForgejoRelease?> 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<ForgejoRelease>(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<HttpResponseMessage?> GetReleaseResponseWithRetryAsync(HttpClient client, Uri sourceUri,
CancellationToken ct)
@@ -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("<html><title>Proxy error</title></html>")]
[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<object?> 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)]