using System.Net.Http.Json; 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 _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 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 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); } /// Release manifest for a registered agent authenticated with its API key. [Authorize(AuthenticationSchemes = "ApiKey")] [HttpGet("agent/latest")] [ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)] public async Task 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 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 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(Json, ct); if (release is null) return null; var assets = new Dictionary(); 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 }; lock (_cacheLock) { _cache = new LatestReleaseCache(result, DateTime.UtcNow); } return result; } catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; } } 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 Assets { 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? 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); }