feat: Initialize Zastava Webhook service with TLS and Authority authentication
- Added Program.cs to set up the web application with Serilog for logging, health check endpoints, and a placeholder admission endpoint. - Configured Kestrel server to use TLS 1.3 and handle client certificates appropriately. - Created StellaOps.Zastava.Webhook.csproj with necessary dependencies including Serilog and Polly. - Documented tasks in TASKS.md for the Zastava Webhook project, outlining current work and exit criteria for each task.
This commit is contained in:
175
src/StellaOps.Scanner.WebService/Endpoints/PolicyEndpoints.cs
Normal file
175
src/StellaOps.Scanner.WebService/Endpoints/PolicyEndpoints.cs
Normal file
@@ -0,0 +1,175 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using StellaOps.Policy;
|
||||
using StellaOps.Scanner.WebService.Constants;
|
||||
using StellaOps.Scanner.WebService.Contracts;
|
||||
using StellaOps.Scanner.WebService.Infrastructure;
|
||||
using StellaOps.Scanner.WebService.Security;
|
||||
using StellaOps.Scanner.WebService.Services;
|
||||
|
||||
namespace StellaOps.Scanner.WebService.Endpoints;
|
||||
|
||||
internal static class PolicyEndpoints
|
||||
{
|
||||
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
||||
};
|
||||
public static void MapPolicyEndpoints(this RouteGroupBuilder apiGroup, string policySegment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(apiGroup);
|
||||
|
||||
var policyGroup = apiGroup
|
||||
.MapGroup(NormalizeSegment(policySegment))
|
||||
.WithTags("Policy");
|
||||
|
||||
policyGroup.MapGet("/schema", HandleSchemaAsync)
|
||||
.WithName("scanner.policy.schema")
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.RequireAuthorization(ScannerPolicies.Reports)
|
||||
.WithOpenApi(operation =>
|
||||
{
|
||||
operation.Summary = "Retrieve the embedded policy JSON schema.";
|
||||
operation.Description = "Returns the policy schema (`policy-schema@1`) used to validate YAML or JSON rulesets.";
|
||||
return operation;
|
||||
});
|
||||
|
||||
policyGroup.MapPost("/diagnostics", HandleDiagnosticsAsync)
|
||||
.WithName("scanner.policy.diagnostics")
|
||||
.Produces<PolicyDiagnosticsResponseDto>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status400BadRequest)
|
||||
.RequireAuthorization(ScannerPolicies.Reports)
|
||||
.WithOpenApi(operation =>
|
||||
{
|
||||
operation.Summary = "Run policy diagnostics.";
|
||||
operation.Description = "Accepts YAML or JSON policy content and returns normalization issues plus recommendations (ignore rules, VEX include/exclude, vendor precedence).";
|
||||
return operation;
|
||||
});
|
||||
|
||||
policyGroup.MapPost("/preview", HandlePreviewAsync)
|
||||
.WithName("scanner.policy.preview")
|
||||
.Produces<PolicyPreviewResponseDto>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status400BadRequest)
|
||||
.RequireAuthorization(ScannerPolicies.Reports)
|
||||
.WithOpenApi(operation =>
|
||||
{
|
||||
operation.Summary = "Preview policy impact against findings.";
|
||||
operation.Description = "Evaluates the supplied findings against the active or proposed policy, returning diffs, quieted verdicts, and actionable validation messages.";
|
||||
return operation;
|
||||
});
|
||||
}
|
||||
|
||||
private static IResult HandleSchemaAsync(HttpContext context)
|
||||
{
|
||||
var schema = PolicySchemaResource.ReadSchemaJson();
|
||||
return Results.Text(schema, "application/schema+json", Encoding.UTF8);
|
||||
}
|
||||
|
||||
private static IResult HandleDiagnosticsAsync(
|
||||
PolicyDiagnosticsRequestDto request,
|
||||
TimeProvider timeProvider,
|
||||
HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(timeProvider);
|
||||
|
||||
if (request.Policy is null || string.IsNullOrWhiteSpace(request.Policy.Content))
|
||||
{
|
||||
return ProblemResultFactory.Create(
|
||||
context,
|
||||
ProblemTypes.Validation,
|
||||
"Invalid policy diagnostics request",
|
||||
StatusCodes.Status400BadRequest,
|
||||
detail: "Policy content is required for diagnostics.");
|
||||
}
|
||||
|
||||
var format = PolicyDtoMapper.ParsePolicyFormat(request.Policy.Format);
|
||||
var binding = PolicyBinder.Bind(request.Policy.Content, format);
|
||||
var diagnostics = PolicyDiagnostics.Create(binding, timeProvider);
|
||||
|
||||
var response = new PolicyDiagnosticsResponseDto
|
||||
{
|
||||
Success = diagnostics.ErrorCount == 0,
|
||||
Version = diagnostics.Version,
|
||||
RuleCount = diagnostics.RuleCount,
|
||||
ErrorCount = diagnostics.ErrorCount,
|
||||
WarningCount = diagnostics.WarningCount,
|
||||
GeneratedAt = diagnostics.GeneratedAt,
|
||||
Issues = diagnostics.Issues.Select(PolicyDtoMapper.ToIssueDto).ToImmutableArray(),
|
||||
Recommendations = diagnostics.Recommendations
|
||||
};
|
||||
|
||||
return Json(response);
|
||||
}
|
||||
|
||||
private static async Task<IResult> HandlePreviewAsync(
|
||||
PolicyPreviewRequestDto request,
|
||||
PolicyPreviewService previewService,
|
||||
HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(previewService);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(request.ImageDigest))
|
||||
{
|
||||
return ProblemResultFactory.Create(
|
||||
context,
|
||||
ProblemTypes.Validation,
|
||||
"Invalid policy preview request",
|
||||
StatusCodes.Status400BadRequest,
|
||||
detail: "imageDigest is required.");
|
||||
}
|
||||
|
||||
if (!request.ImageDigest.Contains(':', StringComparison.Ordinal))
|
||||
{
|
||||
return ProblemResultFactory.Create(
|
||||
context,
|
||||
ProblemTypes.Validation,
|
||||
"Invalid policy preview request",
|
||||
StatusCodes.Status400BadRequest,
|
||||
detail: "imageDigest must include algorithm prefix (e.g. sha256:...).");
|
||||
}
|
||||
|
||||
if (request.Findings is not null)
|
||||
{
|
||||
var missingIds = request.Findings.Any(f => string.IsNullOrWhiteSpace(f.Id));
|
||||
if (missingIds)
|
||||
{
|
||||
return ProblemResultFactory.Create(
|
||||
context,
|
||||
ProblemTypes.Validation,
|
||||
"Invalid policy preview request",
|
||||
StatusCodes.Status400BadRequest,
|
||||
detail: "All findings must include an id value.");
|
||||
}
|
||||
}
|
||||
|
||||
var domainRequest = PolicyDtoMapper.ToDomain(request);
|
||||
var response = await previewService.PreviewAsync(domainRequest, cancellationToken).ConfigureAwait(false);
|
||||
var payload = PolicyDtoMapper.ToDto(response);
|
||||
return Json(payload);
|
||||
}
|
||||
|
||||
private static string NormalizeSegment(string segment)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(segment))
|
||||
{
|
||||
return "/policy";
|
||||
}
|
||||
|
||||
var trimmed = segment.Trim('/');
|
||||
return "/" + trimmed;
|
||||
}
|
||||
|
||||
private static IResult Json<T>(T value)
|
||||
{
|
||||
var payload = JsonSerializer.Serialize(value, SerializerOptions);
|
||||
return Results.Content(payload, "application/json", Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
266
src/StellaOps.Scanner.WebService/Endpoints/ReportEndpoints.cs
Normal file
266
src/StellaOps.Scanner.WebService/Endpoints/ReportEndpoints.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using StellaOps.Policy;
|
||||
using StellaOps.Scanner.WebService.Constants;
|
||||
using StellaOps.Scanner.WebService.Contracts;
|
||||
using StellaOps.Scanner.WebService.Infrastructure;
|
||||
using StellaOps.Scanner.WebService.Security;
|
||||
using StellaOps.Scanner.WebService.Services;
|
||||
|
||||
namespace StellaOps.Scanner.WebService.Endpoints;
|
||||
|
||||
internal static class ReportEndpoints
|
||||
{
|
||||
private const string PayloadType = "application/vnd.stellaops.report+json";
|
||||
|
||||
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
|
||||
public static void MapReportEndpoints(this RouteGroupBuilder apiGroup, string reportsSegment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(apiGroup);
|
||||
|
||||
var reports = apiGroup
|
||||
.MapGroup(NormalizeSegment(reportsSegment))
|
||||
.WithTags("Reports");
|
||||
|
||||
reports.MapPost("/", HandleCreateReportAsync)
|
||||
.WithName("scanner.reports.create")
|
||||
.Produces<ReportResponseDto>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status400BadRequest)
|
||||
.Produces(StatusCodes.Status503ServiceUnavailable)
|
||||
.RequireAuthorization(ScannerPolicies.Reports)
|
||||
.WithOpenApi(operation =>
|
||||
{
|
||||
operation.Summary = "Assemble a signed scan report.";
|
||||
operation.Description = "Aggregates latest findings with the active policy snapshot, returning verdicts plus an optional DSSE envelope.";
|
||||
return operation;
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<IResult> HandleCreateReportAsync(
|
||||
ReportRequestDto request,
|
||||
PolicyPreviewService previewService,
|
||||
IReportSigner signer,
|
||||
TimeProvider timeProvider,
|
||||
IReportEventDispatcher eventDispatcher,
|
||||
HttpContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(previewService);
|
||||
ArgumentNullException.ThrowIfNull(signer);
|
||||
ArgumentNullException.ThrowIfNull(timeProvider);
|
||||
ArgumentNullException.ThrowIfNull(eventDispatcher);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(request.ImageDigest))
|
||||
{
|
||||
return ProblemResultFactory.Create(
|
||||
context,
|
||||
ProblemTypes.Validation,
|
||||
"Invalid report request",
|
||||
StatusCodes.Status400BadRequest,
|
||||
detail: "imageDigest is required.");
|
||||
}
|
||||
|
||||
if (!request.ImageDigest.Contains(':', StringComparison.Ordinal))
|
||||
{
|
||||
return ProblemResultFactory.Create(
|
||||
context,
|
||||
ProblemTypes.Validation,
|
||||
"Invalid report request",
|
||||
StatusCodes.Status400BadRequest,
|
||||
detail: "imageDigest must include algorithm prefix (e.g. sha256:...).");
|
||||
}
|
||||
|
||||
if (request.Findings is not null && request.Findings.Any(f => string.IsNullOrWhiteSpace(f.Id)))
|
||||
{
|
||||
return ProblemResultFactory.Create(
|
||||
context,
|
||||
ProblemTypes.Validation,
|
||||
"Invalid report request",
|
||||
StatusCodes.Status400BadRequest,
|
||||
detail: "All findings must include an id value.");
|
||||
}
|
||||
|
||||
var previewDto = new PolicyPreviewRequestDto
|
||||
{
|
||||
ImageDigest = request.ImageDigest,
|
||||
Findings = request.Findings,
|
||||
Baseline = request.Baseline,
|
||||
Policy = null
|
||||
};
|
||||
|
||||
var domainRequest = PolicyDtoMapper.ToDomain(previewDto) with { ProposedPolicy = null };
|
||||
var preview = await previewService.PreviewAsync(domainRequest, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!preview.Success)
|
||||
{
|
||||
var issues = preview.Issues.Select(PolicyDtoMapper.ToIssueDto).ToArray();
|
||||
var extensions = new Dictionary<string, object?>(StringComparer.Ordinal)
|
||||
{
|
||||
["issues"] = issues
|
||||
};
|
||||
|
||||
return ProblemResultFactory.Create(
|
||||
context,
|
||||
ProblemTypes.Validation,
|
||||
"Unable to assemble report",
|
||||
StatusCodes.Status503ServiceUnavailable,
|
||||
detail: "No policy snapshot is available or validation failed.",
|
||||
extensions: extensions);
|
||||
}
|
||||
|
||||
var projectedVerdicts = preview.Diffs
|
||||
.Select(diff => PolicyDtoMapper.ToVerdictDto(diff.Projected))
|
||||
.ToArray();
|
||||
|
||||
var issuesDto = preview.Issues.Select(PolicyDtoMapper.ToIssueDto).ToArray();
|
||||
var summary = BuildSummary(projectedVerdicts);
|
||||
var verdict = ComputeVerdict(projectedVerdicts);
|
||||
var reportId = CreateReportId(request.ImageDigest!, preview.PolicyDigest);
|
||||
var generatedAt = timeProvider.GetUtcNow();
|
||||
|
||||
var document = new ReportDocumentDto
|
||||
{
|
||||
ReportId = reportId,
|
||||
ImageDigest = request.ImageDigest!,
|
||||
GeneratedAt = generatedAt,
|
||||
Verdict = verdict,
|
||||
Policy = new ReportPolicyDto
|
||||
{
|
||||
RevisionId = preview.RevisionId,
|
||||
Digest = preview.PolicyDigest
|
||||
},
|
||||
Summary = summary,
|
||||
Verdicts = projectedVerdicts,
|
||||
Issues = issuesDto
|
||||
};
|
||||
|
||||
var payloadBytes = JsonSerializer.SerializeToUtf8Bytes(document, SerializerOptions);
|
||||
var signature = signer.Sign(payloadBytes);
|
||||
DsseEnvelopeDto? envelope = null;
|
||||
if (signature is not null)
|
||||
{
|
||||
envelope = new DsseEnvelopeDto
|
||||
{
|
||||
PayloadType = PayloadType,
|
||||
Payload = Convert.ToBase64String(payloadBytes),
|
||||
Signatures = new[]
|
||||
{
|
||||
new DsseSignatureDto
|
||||
{
|
||||
KeyId = signature.KeyId,
|
||||
Algorithm = signature.Algorithm,
|
||||
Signature = signature.Signature
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var response = new ReportResponseDto
|
||||
{
|
||||
Report = document,
|
||||
Dsse = envelope
|
||||
};
|
||||
|
||||
await eventDispatcher
|
||||
.PublishAsync(request, preview, document, envelope, context, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return Json(response);
|
||||
}
|
||||
|
||||
private static ReportSummaryDto BuildSummary(IReadOnlyList<PolicyPreviewVerdictDto> verdicts)
|
||||
{
|
||||
if (verdicts.Count == 0)
|
||||
{
|
||||
return new ReportSummaryDto { Total = 0 };
|
||||
}
|
||||
|
||||
var blocked = verdicts.Count(v => string.Equals(v.Status, nameof(PolicyVerdictStatus.Blocked), StringComparison.OrdinalIgnoreCase));
|
||||
var warned = verdicts.Count(v =>
|
||||
string.Equals(v.Status, nameof(PolicyVerdictStatus.Warned), StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(v.Status, nameof(PolicyVerdictStatus.Deferred), StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(v.Status, nameof(PolicyVerdictStatus.RequiresVex), StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(v.Status, nameof(PolicyVerdictStatus.Escalated), StringComparison.OrdinalIgnoreCase));
|
||||
var ignored = verdicts.Count(v => string.Equals(v.Status, nameof(PolicyVerdictStatus.Ignored), StringComparison.OrdinalIgnoreCase));
|
||||
var quieted = verdicts.Count(v => v.Quiet is true);
|
||||
|
||||
return new ReportSummaryDto
|
||||
{
|
||||
Total = verdicts.Count,
|
||||
Blocked = blocked,
|
||||
Warned = warned,
|
||||
Ignored = ignored,
|
||||
Quieted = quieted
|
||||
};
|
||||
}
|
||||
|
||||
private static string ComputeVerdict(IReadOnlyList<PolicyPreviewVerdictDto> verdicts)
|
||||
{
|
||||
if (verdicts.Count == 0)
|
||||
{
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
if (verdicts.Any(v => string.Equals(v.Status, nameof(PolicyVerdictStatus.Blocked), StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return "blocked";
|
||||
}
|
||||
|
||||
if (verdicts.Any(v => string.Equals(v.Status, nameof(PolicyVerdictStatus.Escalated), StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return "escalated";
|
||||
}
|
||||
|
||||
if (verdicts.Any(v =>
|
||||
string.Equals(v.Status, nameof(PolicyVerdictStatus.Warned), StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(v.Status, nameof(PolicyVerdictStatus.Deferred), StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(v.Status, nameof(PolicyVerdictStatus.RequiresVex), StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return "warn";
|
||||
}
|
||||
|
||||
return "pass";
|
||||
}
|
||||
|
||||
private static string CreateReportId(string imageDigest, string policyDigest)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.Append(imageDigest.Trim());
|
||||
builder.Append('|');
|
||||
builder.Append(policyDigest ?? string.Empty);
|
||||
|
||||
using var sha256 = SHA256.Create();
|
||||
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString()));
|
||||
var hex = Convert.ToHexString(hash.AsSpan(0, 10)).ToLowerInvariant();
|
||||
return $"report-{hex}";
|
||||
}
|
||||
|
||||
private static string NormalizeSegment(string segment)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(segment))
|
||||
{
|
||||
return "/reports";
|
||||
}
|
||||
|
||||
var trimmed = segment.Trim('/');
|
||||
return "/" + trimmed;
|
||||
}
|
||||
|
||||
private static IResult Json<T>(T value)
|
||||
{
|
||||
var payload = JsonSerializer.Serialize(value, SerializerOptions);
|
||||
return Results.Content(payload, "application/json", Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
@@ -23,11 +23,11 @@ internal static class ScanEndpoints
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
|
||||
public static void MapScanEndpoints(this RouteGroupBuilder apiGroup)
|
||||
public static void MapScanEndpoints(this RouteGroupBuilder apiGroup, string scansSegment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(apiGroup);
|
||||
|
||||
var scans = apiGroup.MapGroup("/scans");
|
||||
var scans = apiGroup.MapGroup(NormalizeSegment(scansSegment));
|
||||
|
||||
scans.MapPost("/", HandleSubmitAsync)
|
||||
.WithName("scanner.scans.submit")
|
||||
@@ -295,4 +295,15 @@ internal static class ScanEndpoints
|
||||
var payload = JsonSerializer.Serialize(value, SerializerOptions);
|
||||
return Results.Content(payload, "application/json", System.Text.Encoding.UTF8, statusCode);
|
||||
}
|
||||
|
||||
private static string NormalizeSegment(string segment)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(segment))
|
||||
{
|
||||
return "/scans";
|
||||
}
|
||||
|
||||
var trimmed = segment.Trim('/');
|
||||
return "/" + trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user