using System.Reflection; using Sentry.AspNetCore; using Heimdall.Agent; using Heimdall.Agent.Logging; using Heimdall.Agent.Services; using Heimdall.Application.Discovery; using Heimdall.Application.Metrics; using Heimdall.Mdns; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTelemetry.Metrics; var builder = WebApplication.CreateSlimBuilder(args); // ── Sentry (GlitchTip) — DSN from config pipeline with legacy env var fallback ── // Primary: Sentry:Dsn from appsettings.json or env var Sentry__Dsn // Fallback: legacy SENTRY_DSN env var (Docker backward compat) // Neither set → DSN is null → Sentry SDK no-ops gracefully var sentryDsn = builder.Configuration["Sentry:Dsn"] ?? Environment.GetEnvironmentVariable("SENTRY_DSN"); if (!string.IsNullOrEmpty(sentryDsn)) { builder.WebHost.UseSentry((SentryAspNetCoreOptions options) => { options.Dsn = sentryDsn; options.MinimumBreadcrumbLevel = LogLevel.Debug; options.MinimumEventLevel = LogLevel.Error; options.TracesSampleRate = 0.05; options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small; options.ProfilesSampleRate = 0.05; }); } // Strongly-typed configuration with validation builder.Services.AddOptions() .BindConfiguration(AgentOptions.SectionName) .ValidateDataAnnotations() .Validate(options => Uri.TryCreate(options.CentralUrl, UriKind.Absolute, out var centralUri) && (centralUri.Scheme == Uri.UriSchemeHttps || (options.AllowInsecureHttp && centralUri.Scheme == Uri.UriSchemeHttp)), "Agent:CentralUrl must use HTTPS unless Agent:AllowInsecureHttp is explicitly enabled.") .ValidateOnStart(); // HTTP clients builder.Services.AddHttpClient("Central", (sp, client) => { var options = sp.GetRequiredService>().Value; var baseUrl = options.CentralUrl.EndsWith('/') ? options.CentralUrl : options.CentralUrl + "/"; client.BaseAddress = new Uri(baseUrl); client.Timeout = TimeSpan.FromSeconds(10); }); builder.Services.AddHttpClient("IpResolver", client => { client.Timeout = TimeSpan.FromSeconds(5); }); // Broker HTTP client — used by RemoteFrameBrokerService when AnalysisMode=Remote. // BaseAddress is set from AgentOptions.BrokerUrl at client creation time. builder.Services.AddHttpClient("Broker", (sp, client) => { var options = sp.GetRequiredService>().Value; if (!string.IsNullOrEmpty(options.BrokerUrl)) { var baseUrl = options.BrokerUrl.EndsWith('/') ? options.BrokerUrl : options.BrokerUrl + "/"; client.BaseAddress = new Uri(baseUrl); } client.Timeout = TimeSpan.FromSeconds(5); }); // Data Protection — encrypts the agent API key at rest (issue #21). The key // ring is persisted next to the state file so the agent can decrypt its // identity after a restart. Directory locked to owner-only (0700). For // production hardening against full-volume compromise, bind the key ring to a // TPM/HSM-backed store or mount it outside the backed-up volume. var stateDir = builder.Configuration["Agent:StateDirectory"] ?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); var keysDir = Path.Combine(stateDir, "dp-keys"); Directory.CreateDirectory(keysDir); if (OperatingSystem.IsLinux()) File.SetUnixFileMode(keysDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); builder.Services.AddDataProtection() .SetApplicationName("Heimdall.Agent") .PersistKeysToFileSystem(new DirectoryInfo(keysDir)); // Agent services builder.Services.AddSingleton(sp => { var state = new AgentState( sp.GetRequiredService().CreateProtector(AgentState.KeyProtectionPurpose), sp.GetRequiredService>()); var options = sp.GetRequiredService>().Value; var stateDir = options.StateDirectory ?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); state.ConfigureStateDirectory(stateDir); return state; }); builder.Services.AddSingleton(); // Inventory providers (grouped under InventoryProviders to reduce constructor parameter count) builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); // Video capture pipeline (ticket #1): FFmpeg capture per assigned camera, // bounded snapshot channel, adaptive interval, frames → FrameAnalyzerService. // Circuit breaker + degradation manager for graceful IA pipeline degradation. builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => new FrameAnalyzerService( sp.GetRequiredService>(), sp.GetRequiredService(), sp.GetRequiredService())); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(sp => new SnapshotPipelineService(new SnapshotPipelineServiceOptions( sp.GetRequiredService(), sp.GetRequiredService>(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService()))); builder.Services.AddHostedService(sp => sp.GetRequiredService()); // Log capture & upload to Central (ticket #50) builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddHostedService(); // Auto-update service (ticket #96) — checks central for new releases and replaces binary builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => sp.GetRequiredService()); // Docker auto-update (ticket #97) builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => sp.GetRequiredService()); // Health checks — used by Docker HEALTHCHECK builder.Services.AddHealthChecks() .AddCheck("agent_health", tags: ["ready"]) .AddCheck("live", tags: ["live"]); // ── OpenTelemetry metrics (spec 13.1) ────────────────────────────── builder.Services.AddOpenTelemetry() .WithMetrics(metrics => { metrics.AddPrometheusExporter(); metrics.AddMeter(HeimdallMetrics.MeterName); }); var app = builder.Build(); // Health endpoint app.MapHealthChecks("/healthz", new HealthCheckOptions { Predicate = _ => true, ResultStatusCodes = { [HealthStatus.Healthy] = StatusCodes.Status200OK, [HealthStatus.Degraded] = StatusCodes.Status200OK, [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable, } }); // ── Version endpoint — exposes assembly version for auto-update (ticket #100) ── // Public (no auth): used by agents and external tooling for version checks. app.MapGet("/api/version", () => { var assembly = typeof(AgentOptions).Assembly; var informational = assembly .GetCustomAttribute()? .InformationalVersion; var version = assembly.GetName().Version?.ToString() ?? "0.0.0"; return Results.Ok(new { version = informational?.Split('+')[0] ?? version, informational, environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production", timestamp = DateTime.UtcNow, }); }); // ── Prometheus metrics endpoint (spec 13.1) ──────────────────────── app.MapPrometheusScrapingEndpoint("/metrics"); // Live health endpoint (MASTER_SPEC) — reports degradation level app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = check => check.Tags.Contains("live"), ResultStatusCodes = { [HealthStatus.Healthy] = StatusCodes.Status200OK, [HealthStatus.Degraded] = StatusCodes.Status503ServiceUnavailable, [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable, } }); await app.RunAsync();