using System;
using System.Linq;
using System.Net;
using System.Web;
using System.Threading.Tasks;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Vulnerability
{
///
/// Returns the full software inventory for a tenant from the SoftwareInventory table.
/// Global Admin only. Query param: ?tenantId=...
///
public class GetSoftwareInventoryFunction
{
private readonly ILogger _logger;
private readonly IVulnerabilityRepository _vulnRepo;
private readonly GlobalAdminService _globalAdminService;
public GetSoftwareInventoryFunction(
ILogger logger,
IVulnerabilityRepository vulnRepo,
GlobalAdminService globalAdminService)
{
_logger = logger;
_vulnRepo = vulnRepo;
_globalAdminService = globalAdminService;
}
[Function("GetSoftwareInventory")]
public async Task Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "vulnerability/software-inventory")] HttpRequestData req)
{
try
{
// Global Admin only — enforced by PolicyEnforcementMiddleware
var userIdentifier = TenantHelper.GetUserIdentifier(req);
var query = HttpUtility.ParseQueryString(req.Url.Query);
var tenantId = query["tenantId"];
if (string.IsNullOrEmpty(tenantId))
{
var badRequest = req.CreateResponse(HttpStatusCode.BadRequest);
await badRequest.WriteAsJsonAsync(new { success = false, message = "tenantId query parameter is required" });
return badRequest;
}
var inventory = await _vulnRepo.GetSoftwareInventoryAsync(tenantId);
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync(new SoftwareInventoryResponse
{
Success = true,
TenantId = tenantId,
Total = inventory.Count,
Matched = inventory.Count(i => !string.IsNullOrEmpty(i["cpeUri"]?.ToString())),
Unmatched = inventory.Count(i => string.IsNullOrEmpty(i["cpeUri"]?.ToString())),
Inventory = inventory
});
return response;
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "GetSoftwareInventory");
}
}
}
}