Files
Heimdall/src/Heimdall.Web/Controllers/UpdatesController.cs
T
Arnaud Dartois e74d48812b
Heimdall Gitea / Build and tests (pull_request) Failing after 6m0s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
feat(agent): resolve container image through Central
2026-10-22 07:12:08 +02:00

231 lines
11 KiB
C#

using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
using Heimdall.Infrastructure.Security;
using Heimdall.Application.Services;
using Heimdall.Api.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/updates")]
[EnableRateLimiting("Api")]
public class UpdatesController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<UpdatesController> _logger;
private readonly IConfigBroadcastService _configBroadcast;
private readonly ResourceAccess _resourceAccess;
private static readonly JsonSerializerOptions Json = new()
{
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
private static readonly object _cacheLock = new();
private static LatestReleaseCache? _cache;
private static readonly TimeSpan CacheDuration = TimeSpan.FromHours(1);
private const string ForgejoApiUrl =
"https://forgejo.tordais.cc/api/v1/repos/nonobis/Heimdall/releases/latest";
public UpdatesController(IHttpClientFactory httpClientFactory, ILogger<UpdatesController> logger,
IConfigBroadcastService configBroadcast, ResourceAccess resourceAccess)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_configBroadcast = configBroadcast;
_resourceAccess = resourceAccess;
}
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
[HttpGet("latest")]
[ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> GetLatestRelease(CancellationToken ct)
{
var cached = GetCached();
if (cached is not null && !IsStale(cached))
return Ok(cached.Response);
if (cached is not null && IsStale(cached))
{
_ = RefreshCacheAsync(ct);
return Ok(cached.Response);
}
var result = await FetchLatestReleaseAsync(ct);
if (result is null)
return StatusCode(502, new { error = "Failed to fetch release info" });
return Ok(result);
}
/// <summary>Release manifest for a registered agent authenticated with its API key.</summary>
[Authorize(AuthenticationSchemes = "ApiKey")]
[HttpGet("agent/latest")]
[ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> GetLatestReleaseForAgent(CancellationToken ct)
{
var requester = await _resourceAccess.ResolveAsync(User, ct);
if (requester is null || requester.Kind != RequesterKind.Agent) return Forbid();
var cached = GetCached();
if (cached is not null && !IsStale(cached)) return Ok(cached.Response);
if (cached is not null)
{
_ = RefreshCacheAsync(ct);
return Ok(cached.Response);
}
var result = await FetchLatestReleaseAsync(ct);
return result is null ? StatusCode(502, new { error = "Failed to fetch release info" }) : Ok(result);
}
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
[HttpPost("agents/{id:guid}/update")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
public async Task<IActionResult> TriggerAgentUpdate(Guid id, CancellationToken ct)
{
_logger.LogInformation("Manual update requested for agent {AgentId}", id);
var cached = GetCached();
var release = cached is not null && !IsStale(cached) ? cached.Response : await FetchLatestReleaseAsync(ct);
if (release is null)
return StatusCode(502, new { error = "Failed to fetch release info" });
if (!await _configBroadcast.RequestAgentUpdate(id, ct))
return Conflict(new { error = "Agent is not connected to the configuration channel", agentId = id });
return Accepted(new { agentId = id, command = "update-check", dispatched = true, release });
}
private async Task<LatestReleaseResponse?> FetchLatestReleaseAsync(CancellationToken ct)
{
try
{
using var client = _httpClientFactory.CreateClient("Central");
client.Timeout = TimeSpan.FromSeconds(15);
var response = await client.GetAsync(ForgejoApiUrl, ct);
if (!response.IsSuccessStatusCode) { _logger.LogWarning("Forgejo returned {Code}", response.StatusCode); return null; }
var release = await response.Content.ReadFromJsonAsync<ForgejoRelease>(Json, ct);
if (release is null) return null;
var assets = new Dictionary<string, PlatformAsset>();
foreach (var asset in release.Assets ?? [])
{
var platform = DetectPlatform(asset.Name);
if (platform is null) continue;
assets[platform] = new PlatformAsset { Url = asset.BrowserDownloadUrl, Sha256 = ExtractSha256(asset.Digest), Size = asset.Size };
}
var result = new LatestReleaseResponse { Version = release.TagName, ReleaseNotes = release.Body, PublishedAt = release.PublishedAt, Assets = assets };
var image = await FetchAgentImageManifestAsync(release.Assets, client, ct);
result.ContainerImage = image?.Image;
result.ContainerImageDigest = image?.Digest;
lock (_cacheLock) { _cache = new LatestReleaseCache(result, DateTime.UtcNow); }
return result;
}
catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; }
}
private static async Task<AgentImageManifest?> FetchAgentImageManifestAsync(List<ForgejoAsset>? assets, HttpClient client, CancellationToken ct)
{
var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, "agent-image.json", StringComparison.OrdinalIgnoreCase));
var expectedSha256 = asset is null ? null : ExtractSha256(asset.Digest);
if (asset is null || !IsSha256Digest(expectedSha256)) return null;
try
{
using var response = await client.GetAsync(asset.BrowserDownloadUrl, HttpCompletionOption.ResponseHeadersRead, ct);
if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is > 1_048_576)
return null;
await using var stream = await response.Content.ReadAsStreamAsync(ct);
using var buffer = new MemoryStream();
var chunk = new byte[8192];
while (true)
{
var read = await stream.ReadAsync(chunk, ct);
if (read == 0) break;
if (buffer.Length + read > 1_048_576) return null;
buffer.Write(chunk, 0, read);
}
var bytes = buffer.ToArray();
var actualSha256 = Convert.ToHexString(SHA256.HashData(bytes));
if (!string.Equals(actualSha256, expectedSha256, StringComparison.OrdinalIgnoreCase)) return null;
var manifest = JsonSerializer.Deserialize<AgentImageManifest>(bytes, Json);
return manifest is not null && IsValidContainerImageRepository(manifest.Image) && IsValidContainerImageDigest(manifest.Digest)
? manifest
: null;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch { return null; }
}
private static bool IsSha256Digest(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit);
private static bool IsValidContainerImageRepository(string? image) => image is { Length: > 0 and <= 255 }
&& char.IsAsciiLetterOrDigit(image[0])
&& image.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or ':' or '/' or '-')
&& !image.Contains('@')
&& !image.Any(char.IsWhiteSpace)
&& !image.Split('/').Last().Contains(':');
private static bool IsValidContainerImageDigest(string? digest) => digest is { Length: 71 }
&& digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase)
&& digest[7..].All(Uri.IsHexDigit);
private sealed class AgentImageManifest
{
[JsonPropertyName("image")] public string Image { get; init; } = string.Empty;
[JsonPropertyName("digest")] public string Digest { get; init; } = string.Empty;
}
private async Task RefreshCacheAsync(CancellationToken ct) { try { await FetchLatestReleaseAsync(ct); } catch { } }
private static LatestReleaseCache? GetCached() { lock (_cacheLock) return _cache; }
private static bool IsStale(LatestReleaseCache c) => DateTime.UtcNow - c.Timestamp > CacheDuration;
private static string? DetectPlatform(string? name)
{
if (string.IsNullOrEmpty(name)) return null;
var l = name.ToLowerInvariant();
if (l.Contains("linux-x64")) return "linux-x64";
if (l.Contains("linux-arm64")) return "linux-arm64";
if (l.Contains("linux-arm")) return "linux-arm";
if (l.Contains("win-x64") || l.Contains("windows-x64")) return "win-x64";
if (l.Contains("osx-x64") || l.Contains("macos-x64")) return "osx-x64";
if (l.Contains("osx-arm64") || l.Contains("macos-arm64")) return "osx-arm64";
return null;
}
private static string? ExtractSha256(string? digest)
{
if (string.IsNullOrEmpty(digest)) return null;
const string pfx = "sha256:";
return digest.StartsWith(pfx, StringComparison.OrdinalIgnoreCase) ? digest[pfx.Length..] : null;
}
public class LatestReleaseResponse
{
[JsonPropertyName("version")] public string Version { get; set; } = string.Empty;
[JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; }
[JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; }
[JsonPropertyName("assets")] public Dictionary<string, PlatformAsset> Assets { get; set; } = [];
[JsonPropertyName("containerImage")] public string? ContainerImage { get; set; }
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; }
}
public class PlatformAsset
{
[JsonPropertyName("url")] public string Url { get; set; } = string.Empty;
[JsonPropertyName("sha256")] public string? Sha256 { get; set; }
[JsonPropertyName("size")] public long Size { get; set; }
}
private sealed class ForgejoRelease
{
[JsonPropertyName("tag_name")] public string TagName { get; set; } = string.Empty;
[JsonPropertyName("body")] public string? Body { get; set; }
[JsonPropertyName("published_at")] public DateTime? PublishedAt { get; set; }
[JsonPropertyName("assets")] public List<ForgejoAsset>? Assets { get; set; }
}
private sealed class ForgejoAsset
{
[JsonPropertyName("name")] public string Name { get; set; } = string.Empty;
[JsonPropertyName("browser_download_url")] public string BrowserDownloadUrl { get; set; } = string.Empty;
[JsonPropertyName("digest")] public string? Digest { get; set; }
[JsonPropertyName("size")] public long Size { get; set; }
}
private sealed record LatestReleaseCache(LatestReleaseResponse Response, DateTime Timestamp);
}