using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SlpModularCms.Core.Availability; using SlpModularCms.Core.Observability; using SlpModularCms.Modules.Availability.Models; using SlpModularCms.Modules.Availability.Services; namespace SlpModularCms.Modules.Availability.Controllers; [ApiController] [Route("[controller]")] public class MasterController : ControllerBase { private readonly IMasterAvailabilityService _svc; private readonly ILogger _logger; public MasterController(IMasterAvailabilityService svc, ILogger logger) { _svc = svc; _logger = logger; } [HttpPost("register")] public async Task Register([FromBody] RegisterMasterRequest request) { var apiKey = Request.Headers["X-Master-Api-Key"].FirstOrDefault(); if (string.IsNullOrEmpty(apiKey)) return RejectKey(); // The address is stored and polled later: refuse one that cannot be used, and say so without echoing it. if (!MasterUrlRules.IsValid(request.MasterUrl)) { _logger.LogWarning("Master registration refused: the master URL is not an absolute http(s) address (invalid_master_url)."); return BadRequest(new { code = "invalid_master_url", detail = "The master URL must be an absolute http(s) address, for example https://master.example.com." }); } var success = await _svc.RegisterAsync(request.MasterUrl.Trim(), apiKey); return success ? Ok() : RejectKey(); } [HttpPost("status")] public async Task PushStatus([FromBody] PushStatusRequest request) { var apiKey = Request.Headers["X-Master-Api-Key"].FirstOrDefault(); if (string.IsNullOrEmpty(apiKey)) return RejectKey(); var success = await _svc.PushStatusAsync(apiKey, request.IsAvailable, request.DisableMessage); return success ? Ok() : RejectKey(); } [HttpGet("registered-url")] public async Task GetRegisteredUrl() { var apiKey = Request.Headers["X-Master-Api-Key"].FirstOrDefault(); if (string.IsNullOrEmpty(apiKey)) return RejectKey(); var url = await _svc.GetRegisteredUrlAsync(apiKey); return url is not null ? Ok(new { MasterUrl = url }) : RejectKey(); } /// /// Reports the rejection and returns 401. Never logs the key or any part of it. /// /// /// This event is ambiguous by nature: it means either an intruder, or that the Data /// Protection key ring has become unreadable so a legitimate master can no longer be /// recognised. The durability work exists to make the second cause impossible, but if it ever /// happens this is the first sign of it — and the two need telling apart quickly. /// private IActionResult RejectKey() { SecurityEvents.MasterApiKeyRejected( _logger, Request.Path, HttpContext.Connection.RemoteIpAddress?.ToString() ?? "(unknown)"); return Unauthorized(); } }