2026-08-27 18:56:57 +02:00
|
|
|
using System.Net.Http.Json;
|
2026-10-22 07:12:08 +02:00
|
|
|
using System.Security.Cryptography;
|
2026-08-27 18:56:57 +02:00
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
using Heimdall.Infrastructure.Security;
|
2026-10-21 09:20:07 +02:00
|
|
|
using Heimdall.Application.Services;
|
|
|
|
|
using Heimdall.Api.Security;
|
2026-08-27 18:56:57 +02:00
|
|
|
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;
|
2026-10-21 09:20:07 +02:00
|
|
|
private readonly IConfigBroadcastService _configBroadcast;
|
|
|
|
|
private readonly ResourceAccess _resourceAccess;
|
2026-10-22 21:00:21 +02:00
|
|
|
private readonly IConfiguration _configuration;
|
2026-08-27 18:56:57 +02:00
|
|
|
|
|
|
|
|
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);
|
2026-10-21 09:20:07 +02:00
|
|
|
public UpdatesController(IHttpClientFactory httpClientFactory, ILogger<UpdatesController> logger,
|
2026-10-22 21:00:21 +02:00
|
|
|
IConfigBroadcastService configBroadcast, ResourceAccess resourceAccess, IConfiguration configuration)
|
2026-08-27 18:56:57 +02:00
|
|
|
{
|
|
|
|
|
_httpClientFactory = httpClientFactory;
|
|
|
|
|
_logger = logger;
|
2026-10-21 09:20:07 +02:00
|
|
|
_configBroadcast = configBroadcast;
|
|
|
|
|
_resourceAccess = resourceAccess;
|
2026-10-22 21:00:21 +02:00
|
|
|
_configuration = configuration;
|
2026-08-27 18:56:57 +02:00
|
|
|
}
|
|
|
|
|
|
2026-10-23 18:54:14 +02:00
|
|
|
[AllowAnonymous]
|
2026-08-27 18:56:57 +02:00
|
|
|
[HttpGet("latest")]
|
|
|
|
|
[ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)]
|
|
|
|
|
public async Task<IActionResult> GetLatestRelease(CancellationToken ct)
|
|
|
|
|
{
|
2026-10-22 21:00:21 +02:00
|
|
|
var cached = GetCached(_configuration["Updates:ReleaseApiUrl"]);
|
2026-08-27 18:56:57 +02:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-21 09:20:07 +02:00
|
|
|
/// <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();
|
2026-10-22 21:00:21 +02:00
|
|
|
var cached = GetCached(_configuration["Updates:ReleaseApiUrl"]);
|
2026-10-21 09:20:07 +02:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-27 18:56:57 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
|
|
|
|
[HttpPost("agents/{id:guid}/update")]
|
2026-10-21 09:20:07 +02:00
|
|
|
[ProducesResponseType(StatusCodes.Status202Accepted)]
|
2026-08-27 18:56:57 +02:00
|
|
|
public async Task<IActionResult> TriggerAgentUpdate(Guid id, CancellationToken ct)
|
|
|
|
|
{
|
2026-10-21 09:20:07 +02:00
|
|
|
_logger.LogInformation("Manual update requested for agent {AgentId}", id);
|
2026-10-22 21:00:21 +02:00
|
|
|
var cached = GetCached(_configuration["Updates:ReleaseApiUrl"]);
|
2026-10-21 09:20:07 +02:00
|
|
|
var release = cached is not null && !IsStale(cached) ? cached.Response : await FetchLatestReleaseAsync(ct);
|
|
|
|
|
if (release is null)
|
2026-08-27 18:56:57 +02:00
|
|
|
return StatusCode(502, new { error = "Failed to fetch release info" });
|
2026-10-21 09:20:07 +02:00
|
|
|
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 });
|
2026-08-27 18:56:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task<LatestReleaseResponse?> FetchLatestReleaseAsync(CancellationToken ct)
|
|
|
|
|
{
|
2026-10-22 21:00:21 +02:00
|
|
|
var source = _configuration["Updates:ReleaseApiUrl"];
|
|
|
|
|
if (!Uri.TryCreate(source, UriKind.Absolute, out var sourceUri) ||
|
|
|
|
|
sourceUri.Scheme != Uri.UriSchemeHttps || !string.IsNullOrEmpty(sourceUri.UserInfo) ||
|
|
|
|
|
!string.IsNullOrEmpty(sourceUri.Fragment))
|
|
|
|
|
{
|
|
|
|
|
_logger.LogError("Updates:ReleaseApiUrl must be an absolute HTTPS URL without credentials or fragment");
|
|
|
|
|
return null;
|
|
|
|
|
}
|
2026-08-27 18:56:57 +02:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var client = _httpClientFactory.CreateClient("Central");
|
|
|
|
|
client.Timeout = TimeSpan.FromSeconds(15);
|
2026-10-22 21:00:21 +02:00
|
|
|
var response = await client.GetAsync(sourceUri, ct);
|
2026-08-27 18:56:57 +02:00
|
|
|
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 };
|
2026-10-22 07:12:08 +02:00
|
|
|
var image = await FetchAgentImageManifestAsync(release.Assets, client, ct);
|
|
|
|
|
result.ContainerImage = image?.Image;
|
|
|
|
|
result.ContainerImageDigest = image?.Digest;
|
2026-10-23 18:54:14 +02:00
|
|
|
var manifestBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
|
|
|
|
|
"agent-update-manifest.json", client, 1_048_576, ct);
|
|
|
|
|
var signatureBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
|
|
|
|
|
"agent-update-manifest.sig", client, 512, ct);
|
|
|
|
|
if (manifestBytes is not null && signatureBytes is not null)
|
|
|
|
|
{
|
|
|
|
|
result.SignedManifest = Convert.ToBase64String(manifestBytes);
|
|
|
|
|
result.ManifestSignature = Convert.ToBase64String(signatureBytes);
|
|
|
|
|
}
|
2026-10-22 21:00:21 +02:00
|
|
|
lock (_cacheLock) { _cache = new LatestReleaseCache(source!, result, DateTime.UtcNow); }
|
2026-08-27 18:56:57 +02:00
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; }
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 07:12:08 +02:00
|
|
|
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);
|
|
|
|
|
|
2026-10-23 18:54:14 +02:00
|
|
|
private static async Task<byte[]?> FetchBoundedReleaseAssetAsync(List<ForgejoAsset>? assets,
|
|
|
|
|
string name, HttpClient client, int maxBytes, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, name, StringComparison.Ordinal));
|
|
|
|
|
var expected = asset is null ? null : ExtractSha256(asset.Digest);
|
|
|
|
|
if (asset is null || !IsSha256Digest(expected)) return null;
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var response = await client.GetAsync(asset.BrowserDownloadUrl,
|
|
|
|
|
HttpCompletionOption.ResponseHeadersRead, ct);
|
|
|
|
|
if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is long length && length > maxBytes)
|
|
|
|
|
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 > maxBytes) return null;
|
|
|
|
|
buffer.Write(chunk, 0, read);
|
|
|
|
|
}
|
|
|
|
|
var bytes = buffer.ToArray();
|
|
|
|
|
return string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), expected,
|
|
|
|
|
StringComparison.OrdinalIgnoreCase) ? bytes : null;
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
|
|
|
|
|
catch { return null; }
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 07:12:08 +02:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-27 18:56:57 +02:00
|
|
|
private async Task RefreshCacheAsync(CancellationToken ct) { try { await FetchLatestReleaseAsync(ct); } catch { } }
|
2026-10-22 21:00:21 +02:00
|
|
|
private static LatestReleaseCache? GetCached(string? source)
|
|
|
|
|
{
|
|
|
|
|
lock (_cacheLock) return _cache?.Source == source ? _cache : null;
|
|
|
|
|
}
|
2026-08-27 18:56:57 +02:00
|
|
|
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";
|
2026-10-23 18:54:14 +02:00
|
|
|
if (l.Contains("agent-portable-")) return "portable";
|
2026-08-27 18:56:57 +02:00
|
|
|
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; } = [];
|
2026-10-22 07:12:08 +02:00
|
|
|
[JsonPropertyName("containerImage")] public string? ContainerImage { get; set; }
|
|
|
|
|
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; }
|
2026-10-23 18:54:14 +02:00
|
|
|
[JsonPropertyName("signedManifest")] public string? SignedManifest { get; set; }
|
|
|
|
|
[JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; set; }
|
2026-08-27 18:56:57 +02:00
|
|
|
}
|
|
|
|
|
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; }
|
|
|
|
|
}
|
2026-10-22 21:00:21 +02:00
|
|
|
private sealed record LatestReleaseCache(string Source, LatestReleaseResponse Response, DateTime Timestamp);
|
2026-08-27 18:56:57 +02:00
|
|
|
}
|