diff --git a/Sigyll.Common/Security/SigyllRoles.cs b/Sigyll.Common/Security/SigyllRoles.cs index 5cdb23d..93ac09d 100644 --- a/Sigyll.Common/Security/SigyllRoles.cs +++ b/Sigyll.Common/Security/SigyllRoles.cs @@ -45,6 +45,9 @@ public enum Permission /// Issue a certificate from a CSR an RA has vetted; held only by the RA client. IssueFromRa, + + /// Revoke certificates whose exchange purpose authorization an RA withdrew; held only by the RA client. + RevokeFromRa, } /// The single mapping from operator roles to permissions. diff --git a/Sigyll.Common/Services/Audit/AuditTrail.cs b/Sigyll.Common/Services/Audit/AuditTrail.cs index 75f113e..c14ff2a 100644 --- a/Sigyll.Common/Services/Audit/AuditTrail.cs +++ b/Sigyll.Common/Services/Audit/AuditTrail.cs @@ -48,10 +48,11 @@ public static class AuditActions public const string OperatorLockedOut = "operator.locked-out"; public const string OperatorSignedOut = "operator.signed-out"; public const string OperatorSecurityChanged = "operator.security-changed"; + public const string CertificatesRevokedByExchangePurpose = "certificate.bulk-revoked"; public static readonly string[] All = [ - CertificateIssued, CertificateImported, CertificateRevoked, CertificateDeleted, CertificateArchived, + CertificateIssued, CertificateImported, CertificateRevoked, CertificatesRevokedByExchangePurpose, CertificateDeleted, CertificateArchived, CertificateMoved, CrlGenerated, CrlImported, CrlDeleted, KeyExported, VaultExported, VaultBackedUp, VaultUpdated, VaultSecretsRemoved, RequestCreated, RequestFulfilled, RequestDeleted, TrustDomainDeleted, TrustDomainKeyPolicyChanged, OperatorCreated, OperatorDeleted, OperatorRolesChanged, OperatorPasswordSet, OperatorUnlocked, OperatorSecondFactorReset, diff --git a/Sigyll.Common/Services/CertificateManagementService.cs b/Sigyll.Common/Services/CertificateManagementService.cs index f096aa3..c2b5b2e 100644 --- a/Sigyll.Common/Services/CertificateManagementService.cs +++ b/Sigyll.Common/Services/CertificateManagementService.cs @@ -12,6 +12,8 @@ using System.Security.Cryptography.X509Certificates; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Sigyll.Contracts; using Sigyll.Common.Data; using Sigyll.Common.Data.Entities; using Sigyll.Common.Security; @@ -61,6 +63,7 @@ public class CertificateManagementService private readonly IssuanceValidator _validator; private readonly IRemoteKeyStore? _remoteKeys; private readonly AuditTrail _audit; + private readonly ExchangePurposeSanOptions _exchangePurposeSan; public CertificateManagementService( IDbContextFactory dbFactory, @@ -70,8 +73,10 @@ public CertificateManagementService( CrlGenerationService crlGenService, IssuanceValidator? validator = null, IRemoteKeyStore? remoteKeys = null, - AuditTrail? audit = null) + AuditTrail? audit = null, + IOptions? exchangePurposeSan = null) { + _exchangePurposeSan = exchangePurposeSan?.Value ?? new ExchangePurposeSanOptions(); _dbFactory = dbFactory; _operator = operatorContext; _logger = logger; @@ -464,6 +469,95 @@ await _audit.RecordAsync(identity, AuditActions.CertificateRevoked, target, return new RevokeResult(true); } + /// + /// Revokes, with reason privilegeWithdrawn, each listed issued certificate whose URI SANs carry + /// (read by ), records each revocation and one + /// summary event in the audit trail, then generates and publishes a new CRL for every issuing CA involved. + /// Certificates that are unknown, already revoked or carry no such SAN are left alone and reported as skipped. + /// + public async Task RevokeByExchangePurposeAsync( + IReadOnlyCollection serialNumbers, string exchangePurpose, string subscriberRef, string requestedBy, + CancellationToken ct = default) + { + var identity = await _operator.DemandAsync(Permission.Operate, Permission.RevokeFromRa); + + var code = ExchangePurposeSan.Normalize(exchangePurpose); + if (code is null) + return RevocationApiResult.Failure($"'{exchangePurpose}' is not an exchange purpose code."); + + var result = new RevocationApiResult { Success = true }; + var wanted = serialNumbers + .Where(s => !string.IsNullOrWhiteSpace(s)) + .Select(s => s.Trim().ToUpperInvariant()) + .Distinct() + .ToList(); + if (wanted.Count == 0) return result; + + await using var db = await _dbFactory.CreateDbContextAsync(ct); + var candidates = await db.IssuedCertificates + .Include(c => c.IssuingCaCertificate) + .Where(c => wanted.Contains(c.SerialNumber.ToUpper())) + .ToListAsync(ct); + + var now = DateTime.UtcNow; + var revoked = new List(); + foreach (var serial in wanted) + { + var issued = candidates.FirstOrDefault(c => string.Equals(c.SerialNumber, serial, StringComparison.OrdinalIgnoreCase)); + if (issued is null) { result.Skipped[serial] = "No certificate with this serial number."; continue; } + if (issued.IsRevoked) { result.Skipped[serial] = "Already revoked."; continue; } + + ExchangePurposeScan scan; + try + { + using var cert = X509Certificate2.CreateFromPem(issued.X509CertificatePem); + scan = ExchangePurposeSan.Scan(cert, _exchangePurposeSan.QueryParameterName); + } + catch (Exception ex) when (ex is System.Security.Cryptography.CryptographicException or ArgumentException) + { + result.Skipped[serial] = "The stored certificate could not be read."; + continue; + } + + if (!scan.Codes.Contains(code)) + { + result.Skipped[serial] = scan.AmbiguousSans.Count > 0 + ? $"No SAN unambiguously carries {code}; ambiguous: {string.Join(", ", scan.AmbiguousSans)}." + : $"No SAN carries {code}."; + continue; + } + + issued.IsRevoked = true; + issued.RevokedAt = now; + issued.RevocationReason = (int)X509RevocationReason.PrivilegeWithdrawn; + revoked.Add(issued); + } + + await db.SaveChangesAsync(ct); + + var detail = $"Exchange purpose {code} withdrawn for {subscriberRef}; ordered by {requestedBy}."; + foreach (var issued in revoked) + { + result.Revoked.Add(issued.SerialNumber); + await _audit.RecordAsync(identity, AuditActions.CertificateRevoked, AuditTarget.Of(issued), + $"Reason: {X509RevocationReason.PrivilegeWithdrawn} ({(int)X509RevocationReason.PrivilegeWithdrawn}). {detail}", ct: ct); + } + + await _audit.RecordAsync(identity, AuditActions.CertificatesRevokedByExchangePurpose, null, + $"{detail} Revoked {revoked.Count}: {string.Join(", ", result.Revoked)}." + + (result.Skipped.Count > 0 ? $" Skipped {result.Skipped.Count}: {string.Join(", ", result.Skipped.Keys)}." : ""), + ct: ct); + + foreach (var caId in revoked.Select(c => c.IssuingCaCertificateId).Distinct()) + { + var crl = await _crlGenService.GenerateCrlAsync(caId, ct: ct); + if (!crl.IsSuccess) + result.CrlErrors.Add($"CRL for CA {caId} failed: {crl.Error}"); + } + + return result; + } + public async Task FindCaBySkiAsync(int trustDomainId, string authorityKeyIdentifier, CancellationToken ct = default) { await _operator.DemandAsync(Permission.View); diff --git a/Sigyll.Common/Services/Jobs/CrlGenerationService.cs b/Sigyll.Common/Services/Jobs/CrlGenerationService.cs index 9129ed6..645c5e4 100644 --- a/Sigyll.Common/Services/Jobs/CrlGenerationService.cs +++ b/Sigyll.Common/Services/Jobs/CrlGenerationService.cs @@ -83,7 +83,8 @@ public async Task GenerateCrlAsync( TimeSpan? validity = null, CancellationToken ct = default) { - var identity = await _operator.DemandAsync(Permission.Operate); + // The RA client may revoke (RevokeFromRa), and must then publish the CRL that carries those revocations. + var identity = await _operator.DemandAsync(Permission.Operate, Permission.RevokeFromRa); await using var db = await _dbFactory.CreateDbContextAsync(ct); diff --git a/Sigyll.Common/Sigyll.Common.csproj b/Sigyll.Common/Sigyll.Common.csproj index 0bf9d07..c786ac4 100644 --- a/Sigyll.Common/Sigyll.Common.csproj +++ b/Sigyll.Common/Sigyll.Common.csproj @@ -11,6 +11,11 @@ + + + + + diff --git a/Sigyll.Contracts/ExchangePurposeSan.cs b/Sigyll.Contracts/ExchangePurposeSan.cs new file mode 100644 index 0000000..1b7c76b --- /dev/null +++ b/Sigyll.Contracts/ExchangePurposeSan.cs @@ -0,0 +1,211 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Formats.Asn1; +using System.Security.Cryptography.X509Certificates; +using System.Text.RegularExpressions; + +namespace Sigyll.Contracts; + +/// +/// How SAN URIs carry an exchange purpose. Bound from the ExchangePurposeSan configuration section of both the +/// CA and the RA portal, which must agree. +/// +public sealed class ExchangePurposeSanOptions +{ + public const string Section = "ExchangePurposeSan"; + + /// + /// Name of the query parameter that carries the exchange purpose, e.g. ?<name>=T-TRTMNT, matched + /// case-sensitively. The TEFCA client SAN format is not settled, so there is no default: unset, the query form is + /// not recognised at all and only the fragment and last-path-segment forms are. + /// + public string? QueryParameterName { get; set; } +} + +/// What found in one SAN URI. +/// The exchange purpose code, or null when there is none or it is ambiguous. +/// True when the URI carries conflicting exchange purposes; is then null. +public readonly record struct ExchangePurposeMatch(string? Code, bool Ambiguous); + +/// What found in a set of SAN URIs. +/// The distinct exchange purpose codes carried unambiguously. +/// SAN URIs that carry conflicting exchange purposes, verbatim. +public sealed record ExchangePurposeScan(IReadOnlySet Codes, IReadOnlyList AmbiguousSans); + +/// +/// Reads the TEFCA exchange purpose (XP) code a SAN URI carries. The client SAN format is not settled, so this is the +/// one place that knows it; every caller (issuance checks, RA approval, bulk revocation) follows. +/// +/// URIs are handled as HL7 SSRAA requires: as case-sensitive strings, never normalized, percent-decoded or re-encoded. +/// The raw string is split by hand: the fragment is everything after the first #; the query is everything +/// after the first ? that comes before it; the path runs from the end of the authority (or of the scheme, for a +/// URN) to the query or fragment. +/// +/// +/// An exchange purpose may appear in any of three places, and each value must equal a code exactly +/// (T-TRTMNT, never t-trtmnt or T%2DTRTMNT): +/// the fragment (urn:oid:2.16.840.1.113883.3.7204.1.5.2.1#T-TRTMNT); the last path segment +/// (https://example.org/fhir/T-TRTMNT); and, only when +/// is configured, that query parameter (https://example.org/fhir?<name>=T-TRTMNT). +/// +/// +/// Precedence: none of the places outranks another. If more than one carries a code, they must all carry the same +/// one; different codes in different places, or the query parameter repeated with different values, make the URI +/// ambiguous, and it then carries no exchange purpose ( is set so callers +/// can flag it). +/// +/// +public static partial class ExchangePurposeSan +{ + /// The id-ce-subjectAltName extension OID. + private const string SanOid = "2.5.29.17"; + + /// + /// An exchange purpose code as listed in the TEFCA Exchange Purposes SOP: T- followed by one or more + /// hyphen-separated upper-case segments (T-TRTMNT, T-PH-ECR, T-IAS). Case-sensitive. + /// + [GeneratedRegex("^T-[A-Z0-9]+(?:-[A-Z0-9]+)*$", RegexOptions.CultureInvariant)] + private static partial Regex CodePattern(); + + /// True when is exactly an exchange purpose code. + public static bool IsCode(string? value) => value is not null && CodePattern().IsMatch(value); + + /// A code typed by a person, with surrounding white space removed, or null when it isn't a code. + public static string? Normalize(string? code) => code?.Trim() is { } trimmed && IsCode(trimmed) ? trimmed : null; + + /// The exchange purpose code carries, or null when it carries none or it is ambiguous. + public static string? Extract(string? sanUri, string? queryParameterName) => Parse(sanUri, queryParameterName).Code; + + /// Reads the exchange purpose of one SAN URI; see the class remarks for the rules. + public static ExchangePurposeMatch Parse(string? sanUri, string? queryParameterName) + { + if (string.IsNullOrEmpty(sanUri)) return default; + + var rest = sanUri; + string? fragment = null; + var hash = rest.IndexOf('#'); + if (hash >= 0) + { + fragment = rest[(hash + 1)..]; + rest = rest[..hash]; + } + + string? query = null; + var question = rest.IndexOf('?'); + if (question >= 0) + { + query = rest[(question + 1)..]; + rest = rest[..question]; + } + + var found = new HashSet(StringComparer.Ordinal); + + if (IsCode(fragment)) found.Add(fragment!); + + var lastSegment = LastPathSegment(rest); + if (IsCode(lastSegment)) found.Add(lastSegment!); + + if (query is not null && !string.IsNullOrEmpty(queryParameterName)) + { + var values = new HashSet(StringComparer.Ordinal); + foreach (var pair in query.Split('&')) + { + var eq = pair.IndexOf('='); + var name = eq >= 0 ? pair[..eq] : pair; + if (!string.Equals(name, queryParameterName, StringComparison.Ordinal)) continue; + values.Add(eq >= 0 ? pair[(eq + 1)..] : string.Empty); + } + + if (values.Count > 1) return new ExchangePurposeMatch(null, Ambiguous: true); + if (values.Count == 1 && IsCode(values.First())) found.Add(values.First()); + } + + return found.Count switch + { + 0 => default, + 1 => new ExchangePurposeMatch(found.First(), Ambiguous: false), + _ => new ExchangePurposeMatch(null, Ambiguous: true), + }; + } + + /// The exchange purposes carried by , and the ambiguous ones. + public static ExchangePurposeScan Scan(IEnumerable sanUris, string? queryParameterName) + { + var codes = new HashSet(StringComparer.Ordinal); + var ambiguous = new List(); + foreach (var uri in sanUris) + { + var match = Parse(uri, queryParameterName); + if (match.Ambiguous) ambiguous.Add(uri!); + else if (match.Code is not null) codes.Add(match.Code); + } + return new ExchangePurposeScan(codes, ambiguous); + } + + /// The exchange purposes carried by the URI entries in . + public static ExchangePurposeScan Scan(IEnumerable sans, string? queryParameterName) => + Scan(sans + .Where(s => string.Equals(s.Type, "Uri", StringComparison.OrdinalIgnoreCase)) + .Select(s => s.Value), queryParameterName); + + /// The exchange purposes carried by the URI SANs of . + public static ExchangePurposeScan Scan(X509Certificate2 certificate, string? queryParameterName) => + Scan(ReadSanUris(certificate), queryParameterName); + + /// + /// The last segment of the path part of (the URI with query and fragment removed), + /// or null when the path has no /. For scheme://authority/path the path starts at the first + /// / after the authority; for a URN it is everything after the scheme. + /// + private static string? LastPathSegment(string beforeQuery) + { + var colon = beforeQuery.IndexOf(':'); + var path = colon >= 0 ? beforeQuery[(colon + 1)..] : beforeQuery; + if (path.StartsWith("//", StringComparison.Ordinal)) + { + var slash = path.IndexOf('/', 2); + if (slash < 0) return null; // authority only, no path + path = path[slash..]; + } + + var last = path.LastIndexOf('/'); + return last >= 0 ? path[(last + 1)..] : null; + } + + /// The uniformResourceIdentifier entries of a certificate's subjectAltName extension, verbatim. + public static IReadOnlyList ReadSanUris(X509Certificate2 certificate) + { + var extension = certificate.Extensions[SanOid]; + if (extension is null) return []; + + var uris = new List(); + try + { + var reader = new AsnReader(extension.RawData, AsnEncodingRules.DER); + var names = reader.ReadSequence(); + var uriTag = new Asn1Tag(TagClass.ContextSpecific, 6); + while (names.HasData) + { + var tag = names.PeekTag(); + if (tag.HasSameClassAndValue(uriTag)) + uris.Add(names.ReadCharacterString(UniversalTagNumber.IA5String, uriTag)); + else + names.ReadEncodedValue(); + } + } + catch (AsnContentException) + { + // A malformed extension carries no usable URI. + } + + return uris; + } +} diff --git a/Sigyll.Contracts/IssuanceApiRequest.cs b/Sigyll.Contracts/IssuanceApiRequest.cs index 897fe63..1c4fc70 100644 --- a/Sigyll.Contracts/IssuanceApiRequest.cs +++ b/Sigyll.Contracts/IssuanceApiRequest.cs @@ -42,6 +42,10 @@ public class IssuanceApiRequest /// Subject Alternative Names requested for the certificate. public List RequestedSans { get; set; } = []; + + /// Exchange purpose codes the subscriber is authorized for. When set, the CA refuses a URI SAN carrying + /// any other exchange purpose (see ). Null skips the check. + public List? AuthorizedExchangePurposes { get; set; } } /// A single Subject Alternative Name entry on the wire. diff --git a/Sigyll.Contracts/RevocationApiRequest.cs b/Sigyll.Contracts/RevocationApiRequest.cs new file mode 100644 index 0000000..4751c6b --- /dev/null +++ b/Sigyll.Contracts/RevocationApiRequest.cs @@ -0,0 +1,50 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +namespace Sigyll.Contracts; + +/// +/// Request from the RA portal to the CA core to revoke certificates whose exchange purpose authorization was withdrawn +/// (POST /api/ra/revoke-by-exchange-purpose). The CA revokes each listed certificate with reason +/// privilegeWithdrawn only when one of its URI SANs carries , records each +/// revocation in its audit trail and publishes a new CRL for every issuing CA involved. +/// +public class RevocationApiRequest +{ + /// Serial numbers (hex, as returned on issuance) of the certificates to revoke. + public List SerialNumbers { get; set; } = []; + + /// The exchange purpose code (e.g. T-TRTMNT) whose authorization was withdrawn. + public string ExchangePurpose { get; set; } = string.Empty; + + /// The subscriber (organization) the certificates were issued to, as the portal names it, for audit. + public string SubscriberRef { get; set; } = string.Empty; + + /// The RA user who ordered the revocation, for audit. + public string RequestedBy { get; set; } = string.Empty; +} + +/// Result of . +public class RevocationApiResult +{ + public bool Success { get; set; } + public string? Error { get; set; } + + /// Serial numbers the CA revoked. + public List Revoked { get; set; } = []; + + /// Serial numbers the CA left alone, each with the reason (already revoked, unknown, no matching SAN). + public Dictionary Skipped { get; set; } = []; + + /// Problems publishing the new CRLs; the revocations themselves stand. + public List CrlErrors { get; set; } = []; + + public static RevocationApiResult Failure(string error) => new() { Success = false, Error = error }; +} diff --git a/Sigyll.Portal/Components/Layout/MainLayout.razor b/Sigyll.Portal/Components/Layout/MainLayout.razor index 2636618..80973db 100644 --- a/Sigyll.Portal/Components/Layout/MainLayout.razor +++ b/Sigyll.Portal/Components/Layout/MainLayout.razor @@ -43,6 +43,7 @@ RA Queue + Exchange Purposes diff --git a/Sigyll.Portal/Components/Pages/Ra/ExchangePurposes.razor b/Sigyll.Portal/Components/Pages/Ra/ExchangePurposes.razor new file mode 100644 index 0000000..44aa396 --- /dev/null +++ b/Sigyll.Portal/Components/Pages/Ra/ExchangePurposes.razor @@ -0,0 +1,211 @@ +@* (c) 2026 Joseph Shook. See LICENSE in the project root. *@ +@page "/ra/exchange-purposes" +@rendermode InteractiveServer +@attribute [Authorize(Roles = "RA,PortalAdmin")] +@using System.Security.Claims +@using Microsoft.AspNetCore.Authorization +@using Microsoft.EntityFrameworkCore +@using Sigyll.Contracts +@using Sigyll.Portal.Data +@using Sigyll.Portal.Data.Entities +@using Sigyll.Portal.Services +@inject PortalDbContext Db +@inject ExchangePurposeService ExchangePurposeService +@inject AuthenticationStateProvider AuthState + +Exchange Purposes +Exchange Purposes by Subscriber + + A subscriber's certificates may only carry SANs for the exchange purposes recorded here; requests for any other + are flagged and cannot be approved. Withdrawing an exchange purpose lets you revoke every certificate of the + subscriber that carries it (reason privilegeWithdrawn); the CA publishes a new CRL. + + +@if (_message is not null) +{ + @_message +} + +@if (_orgs is null) +{ + +} +else if (_orgs.Count == 0) +{ + No subscriber organizations exist yet. +} +else +{ + @foreach (var org in _orgs) + { + + @org.Name @(org.Enabled ? "" : "(disabled)") + + @if (org.ExchangePurposes.Count == 0) + { +

No exchange purposes authorized.

+ } + else + { + + + + @foreach (var xp in org.ExchangePurposes.OrderBy(x => x.Code)) + { + + + + + + + } + +
CodeApproved byApproved (UTC)
@xp.Code@xp.ApprovedBy@xp.ApprovedAt.ToString("u") + Withdraw +
+ } + + + + Authorize + + + + + Find certificates + + + @if (_found.TryGetValue(org.Id, out var found)) + { + @if (found.Requests.Count == 0) + { +

No issued certificates of @org.Name carry @found.Code.

+ } + else + { +
    + @foreach (var r in found.Requests) + { +
  • #@r.Id @r.SubjectDn, serial @r.SerialNumber
  • + } +
+ @if (AuthorizedCodes(org).Contains(found.Code)) + { +

@org.Name is still authorized for @found.Code; withdraw it first unless these certificates must go regardless.

+ } + Revoke @found.Requests.Count certificate(s) + } + } +
+ } +} + +@code { + private List? _orgs; + private readonly Dictionary _newCode = new(); + private readonly Dictionary _revokeCode = new(); + private readonly Dictionary Requests)> _found = new(); + private bool _busy; + private string? _message; + + protected override async Task OnInitializedAsync() => await Load(); + + private async Task Load() + { + _orgs = await Db.Organizations + .Include(o => o.ExchangePurposes) + .AsNoTracking() + .OrderBy(o => o.Name) + .ToListAsync(); + foreach (var o in _orgs) + { + _newCode.TryAdd(o.Id, ""); + _revokeCode.TryAdd(o.Id, ""); + } + } + + private static HashSet AuthorizedCodes(Organization org) => + org.ExchangePurposes.Select(x => x.Code).ToHashSet(StringComparer.Ordinal); + + private async Task Actor() + { + var state = await AuthState.GetAuthenticationStateAsync(); + return state.User.FindFirstValue(ClaimTypes.Name) + ?? state.User.FindFirstValue(ClaimTypes.NameIdentifier) + ?? "ra"; + } + + private async Task Authorize(int orgId) + { + await Run(async () => + { + var code = _newCode.GetValueOrDefault(orgId); + if (ExchangePurposeSan.Normalize(code) is null) + { + _message = $"'{code}' is not an exchange purpose code (e.g. T-TRTMNT)."; + return; + } + var row = await ExchangePurposeService.AuthorizeAsync(orgId, code!, await Actor()); + _newCode[orgId] = ""; + _message = $"Authorized {row.Code}."; + }); + } + + private async Task Withdraw(int orgId, string code) + { + await Run(async () => + { + await ExchangePurposeService.WithdrawAsync(orgId, code, await Actor()); + _revokeCode[orgId] = code; + _found[orgId] = (code, await ExchangePurposeService.FindIssuedCarryingAsync(orgId, code)); + _message = $"Withdrew {code}. {_found[orgId].Requests.Count} issued certificate(s) carry it; revoke them below."; + }); + } + + private async Task Find(int orgId) + { + await Run(async () => + { + var code = ExchangePurposeSan.Normalize(_revokeCode.GetValueOrDefault(orgId)); + if (code is null) + { + _message = $"'{_revokeCode.GetValueOrDefault(orgId)}' is not an exchange purpose code (e.g. T-TRTMNT)."; + _found.Remove(orgId); + return; + } + _found[orgId] = (code, await ExchangePurposeService.FindIssuedCarryingAsync(orgId, code)); + _message = null; + }); + } + + private async Task Revoke(int orgId, string code) + { + await Run(async () => + { + var outcome = await ExchangePurposeService.RevokeByExchangePurposeAsync(orgId, code, await Actor()); + _found.Remove(orgId); + _message = !outcome.Success + ? $"Revocation failed: {outcome.Error}" + : $"Revoked {outcome.Revoked.Count} certificate(s) carrying {code}." + + (outcome.Skipped.Count > 0 ? $" Skipped {outcome.Skipped.Count}: {string.Join("; ", outcome.Skipped.Select(s => $"{s.Key} ({s.Value})"))}." : "") + + (outcome.CrlErrors.Count > 0 ? $" CRL problems: {string.Join("; ", outcome.CrlErrors)}." : " New CRLs published."); + }); + } + + private async Task Run(Func action) + { + _busy = true; + try + { + await action(); + await Load(); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + _message = ex.Message; + } + finally { _busy = false; } + } +} diff --git a/Sigyll.Portal/Components/Pages/Ra/RaQueue.razor b/Sigyll.Portal/Components/Pages/Ra/RaQueue.razor index 4058b21..7ba13c4 100644 --- a/Sigyll.Portal/Components/Pages/Ra/RaQueue.razor +++ b/Sigyll.Portal/Components/Pages/Ra/RaQueue.razor @@ -10,6 +10,7 @@ @using Sigyll.Portal.Services @inject PortalDbContext Db @inject RequestWorkflowService Workflow +@inject ExchangePurposeService ExchangePurposes @inject AuthenticationStateProvider AuthState RA Queue @@ -80,9 +81,14 @@ else try { var result = await Workflow.ApproveAsync(id, await RaUserId(), Reason(id)); - _message = result.Status == RequestStatus.Issued - ? $"Request #{id} approved and issued (serial {result.SerialNumber})." - : $"Request #{id} approved but issuance reported: {result.FailureReason ?? result.Status.ToString()}."; + _message = result.Status switch + { + RequestStatus.Issued => $"Request #{id} approved and issued (serial {result.SerialNumber}).", + RequestStatus.PendingRaApproval => + $"Request #{id} was not approved. {(await ExchangePurposes.CheckRequestAsync(result)).Describe()} " + + "Record the authorization under Exchange Purposes, or reject the request.", + _ => $"Request #{id} approved but issuance reported: {result.FailureReason ?? result.Status.ToString()}.", + }; await Load(); } finally { _busy = false; } diff --git a/Sigyll.Portal/Data/Entities/CertificateRequest.cs b/Sigyll.Portal/Data/Entities/CertificateRequest.cs index 24e1348..73637be 100644 --- a/Sigyll.Portal/Data/Entities/CertificateRequest.cs +++ b/Sigyll.Portal/Data/Entities/CertificateRequest.cs @@ -84,6 +84,9 @@ public enum RequestStatus Issued = 9, Failed = 10, Closed = 11, + + /// The issued certificate was revoked (e.g. its exchange purpose authorization was withdrawn). + Revoked = 12, } /// Outcome of the classification policy evaluation. diff --git a/Sigyll.Portal/Data/Entities/Organization.cs b/Sigyll.Portal/Data/Entities/Organization.cs index 89c68d1..67f5acc 100644 --- a/Sigyll.Portal/Data/Entities/Organization.cs +++ b/Sigyll.Portal/Data/Entities/Organization.cs @@ -30,4 +30,7 @@ public class Organization public DateTime CreatedAt { get; set; } = DateTime.UtcNow; public ICollection Memberships { get; set; } = new List(); + + /// Exchange purposes this org's certificates may carry in their SANs. + public ICollection ExchangePurposes { get; set; } = new List(); } diff --git a/Sigyll.Portal/Data/Entities/OrganizationExchangePurpose.cs b/Sigyll.Portal/Data/Entities/OrganizationExchangePurpose.cs new file mode 100644 index 0000000..a1dee6b --- /dev/null +++ b/Sigyll.Portal/Data/Entities/OrganizationExchangePurpose.cs @@ -0,0 +1,31 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +namespace Sigyll.Portal.Data.Entities; + +/// +/// An exchange purpose (e.g. T-TRTMNT) a subscriber organization is authorized to carry in its certificates' +/// SANs, and who recorded that authorization. Withdrawing it removes the row; the audit trail keeps the history. +/// +public class OrganizationExchangePurpose +{ + public int Id { get; set; } + + public int OrganizationId { get; set; } + public Organization Organization { get; set; } = null!; + + /// Exchange purpose code, upper-case (see ExchangePurposeSan). + public string Code { get; set; } = string.Empty; + + /// The RA or portal admin who recorded the authorization. + public string ApprovedBy { get; set; } = string.Empty; + + public DateTime ApprovedAt { get; set; } = DateTime.UtcNow; +} diff --git a/Sigyll.Portal/Data/PortalDbContext.cs b/Sigyll.Portal/Data/PortalDbContext.cs index da80acc..28d314c 100644 --- a/Sigyll.Portal/Data/PortalDbContext.cs +++ b/Sigyll.Portal/Data/PortalDbContext.cs @@ -29,12 +29,24 @@ public class PortalDbContext(DbContextOptions options) : Identi public DbSet RequestEvents => Set(); public DbSet DomainValidationChallenges => Set(); public DbSet AuditEvents => Set(); + public DbSet OrganizationExchangePurposes => Set(); protected override void OnModelCreating(ModelBuilder builder) { builder.HasDefaultSchema(Schema); base.OnModelCreating(builder); + builder.Entity(e => + { + e.HasOne(x => x.Organization) + .WithMany(o => o.ExchangePurposes) + .HasForeignKey(x => x.OrganizationId) + .OnDelete(DeleteBehavior.Cascade); + e.HasIndex(x => new { x.OrganizationId, x.Code }).IsUnique(); + e.Property(x => x.Code).HasMaxLength(64).IsRequired(); + e.Property(x => x.ApprovedBy).HasMaxLength(256).IsRequired(); + }); + builder.Entity(e => { e.HasOne(m => m.Organization) diff --git a/Sigyll.Portal/Program.cs b/Sigyll.Portal/Program.cs index c5f36aa..620bd60 100644 --- a/Sigyll.Portal/Program.cs +++ b/Sigyll.Portal/Program.cs @@ -70,6 +70,9 @@ // Portal services: catalog (cached), classification policy, http-01 validation, CA client, workflow. builder.Services.Configure(builder.Configuration.GetSection("Portal")); +// How SAN URIs carry an exchange purpose; must match the CA's setting. No query parameter name by default. +builder.Services.Configure( + builder.Configuration.GetSection(Sigyll.Contracts.ExchangePurposeSanOptions.Section)); builder.Services.AddMemoryCache(); // http-01 challenge URLs name the requester's host, so their fetches go through the outbound fetch policy. builder.Services.AddOutboundFetchClient("dv", builder.Configuration); @@ -93,6 +96,7 @@ builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton, IdentityNoOpEmailSender>(); diff --git a/Sigyll.Portal/Services/CaApiClient.cs b/Sigyll.Portal/Services/CaApiClient.cs index c140644..220ffe7 100644 --- a/Sigyll.Portal/Services/CaApiClient.cs +++ b/Sigyll.Portal/Services/CaApiClient.cs @@ -46,6 +46,21 @@ public async Task IssueAsync(IssuanceApiRequest request, Canc return result ?? IssuanceApiResult.Failure($"CA returned {(int)resp.StatusCode} with no body."); } + /// Asks the CA to revoke certificates whose exchange purpose authorization was withdrawn. + public async Task RevokeByExchangePurposeAsync(RevocationApiRequest request, CancellationToken ct = default) + { + using var req = new HttpRequestMessage(HttpMethod.Post, "/api/ra/revoke-by-exchange-purpose") + { + Content = JsonContent.Create(request), + }; + AddAuth(req); + using var resp = await http.SendAsync(req, ct); + if (resp.Content.Headers.ContentLength == 0) + return RevocationApiResult.Failure($"CA returned {(int)resp.StatusCode} with no body."); + var result = await resp.Content.ReadFromJsonAsync(ct); + return result ?? RevocationApiResult.Failure($"CA returned {(int)resp.StatusCode} with no body."); + } + private void AddAuth(HttpRequestMessage req) { // mTLS (production) is configured on the HttpClient handler in DI. The dev fallback is the diff --git a/Sigyll.Portal/Services/ExchangePurposeService.cs b/Sigyll.Portal/Services/ExchangePurposeService.cs new file mode 100644 index 0000000..cc1a69f --- /dev/null +++ b/Sigyll.Portal/Services/ExchangePurposeService.cs @@ -0,0 +1,254 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Sigyll.Contracts; +using Sigyll.Portal.Data; +using Sigyll.Portal.Data.Entities; +using CertificateRequest = Sigyll.Portal.Data.Entities.CertificateRequest; + +namespace Sigyll.Portal.Services; + +/// Outcome of . +public record BulkRevocationOutcome( + bool Success, + string? Error, + IReadOnlyList Revoked, + IReadOnlyDictionary Skipped, + IReadOnlyList CrlErrors); + +/// Result of checking requested SANs against a subscriber's authorized exchange purposes. +/// Exchange purposes the SANs carry that the subscriber is not authorized for, sorted. +/// SANs carrying conflicting exchange purposes; they can't be checked, so they block too. +public record SanAuthorizationCheck(IReadOnlyList Unauthorized, IReadOnlyList AmbiguousSans) +{ + public bool Passes => Unauthorized.Count == 0 && AmbiguousSans.Count == 0; + + /// A sentence describing what failed; empty when the check passes. + public string Describe() => string.Join(" ", new[] + { + Unauthorized.Count > 0 + ? $"Subscriber is not authorized for exchange purpose(s): {string.Join(", ", Unauthorized)}." + : null, + AmbiguousSans.Count > 0 + ? $"SAN(s) carry conflicting exchange purposes: {string.Join(", ", AmbiguousSans)}." + : null, + }.OfType()); +} + +/// +/// The exchange purposes (TEFCA XP codes) each subscriber organization is authorized for: recording and withdrawing +/// them, checking requested SANs against them, and revoking an organization's certificates for a withdrawn one. +/// Which SAN carries which exchange purpose is decided by alone. +/// +public class ExchangePurposeService( + PortalDbContext db, + CaApiClient ca, + PortalAuditTrail audit, + IOptions sanOptions, + ILogger logger) +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + private readonly string? _queryParameterName = sanOptions.Value.QueryParameterName; + + /// The organization's authorized exchange purposes, by code. + public async Task> ListAsync(int organizationId, CancellationToken ct = default) => + await db.OrganizationExchangePurposes + .Where(x => x.OrganizationId == organizationId) + .OrderBy(x => x.Code) + .ToListAsync(ct); + + /// The codes the organization is authorized for; empty when there is no organization. + public async Task> AuthorizedCodesAsync(int? organizationId, CancellationToken ct = default) + { + if (organizationId is null) return new HashSet(StringComparer.Ordinal); + var codes = await db.OrganizationExchangePurposes + .Where(x => x.OrganizationId == organizationId) + .Select(x => x.Code) + .ToListAsync(ct); + return codes.ToHashSet(StringComparer.Ordinal); + } + + /// Checks against the codes . + public SanAuthorizationCheck Check(IEnumerable sans, IReadOnlySet authorized) + { + var scan = ExchangePurposeSan.Scan(sans, _queryParameterName); + return new SanAuthorizationCheck( + scan.Codes.Where(xp => !authorized.Contains(xp)).Order(StringComparer.Ordinal).ToList(), + scan.AmbiguousSans); + } + + /// Checks against the codes is authorized for. + public async Task CheckAsync( + IEnumerable sans, int? organizationId, CancellationToken ct = default) => + Check(sans, await AuthorizedCodesAsync(organizationId, ct)); + + /// Checks the request's SANs against the codes its organization is authorized for. + public async Task CheckRequestAsync(CertificateRequest request, CancellationToken ct = default) + { + var sans = JsonSerializer.Deserialize>(request.RequestedSansJson ?? "[]", Json) ?? []; + return await CheckAsync(sans, request.OrganizationId, ct); + } + + /// Records that the organization is authorized for . Re-authorizing is a no-op. + public async Task AuthorizeAsync( + int organizationId, string code, string approvedBy, CancellationToken ct = default) + { + var normalized = ExchangePurposeSan.Normalize(code) + ?? throw new ArgumentException($"'{code}' is not an exchange purpose code (e.g. T-TRTMNT).", nameof(code)); + var org = await db.Organizations.FindAsync([organizationId], ct) + ?? throw new InvalidOperationException($"Organization {organizationId} not found."); + + var existing = await db.OrganizationExchangePurposes + .FirstOrDefaultAsync(x => x.OrganizationId == organizationId && x.Code == normalized, ct); + if (existing is not null) return existing; + + var row = new OrganizationExchangePurpose + { + OrganizationId = organizationId, + Code = normalized, + ApprovedBy = approvedBy, + ApprovedAt = DateTime.UtcNow, + }; + db.OrganizationExchangePurposes.Add(row); + await db.SaveChangesAsync(ct); + await audit.RecordAsync(approvedBy, PortalAuditActions.ExchangePurposeAuthorized, null, + $"{org.Name} (organization {org.Id}) authorized for {normalized}."); + return row; + } + + /// Withdraws the organization's authorization for ; false if it had none. + public async Task WithdrawAsync(int organizationId, string code, string actor, CancellationToken ct = default) + { + var normalized = ExchangePurposeSan.Normalize(code); + if (normalized is null) return false; + + var row = await db.OrganizationExchangePurposes + .Include(x => x.Organization) + .FirstOrDefaultAsync(x => x.OrganizationId == organizationId && x.Code == normalized, ct); + if (row is null) return false; + + db.OrganizationExchangePurposes.Remove(row); + await db.SaveChangesAsync(ct); + await audit.RecordAsync(actor, PortalAuditActions.ExchangePurposeWithdrawn, null, + $"{row.Organization.Name} (organization {organizationId}) no longer authorized for {normalized}; " + + $"authorized by {row.ApprovedBy} at {row.ApprovedAt:O}."); + return true; + } + + /// The organization's issued (not yet revoked) certificates whose SANs carry . + public async Task> FindIssuedCarryingAsync( + int organizationId, string code, CancellationToken ct = default) + { + var normalized = ExchangePurposeSan.Normalize(code); + if (normalized is null) return []; + + var issued = await db.CertificateRequests + .Where(r => r.OrganizationId == organizationId && r.Status == RequestStatus.Issued && r.SerialNumber != null) + .OrderBy(r => r.Id) + .ToListAsync(ct); + return issued.Where(r => CarriedExchangePurposes(r).Contains(normalized)).ToList(); + } + + /// + /// Revokes (reason privilegeWithdrawn) every issued certificate of the organization whose SANs carry + /// . The CA re-checks each certificate, records each revocation and publishes new CRLs; + /// the portal marks the requests revoked and records the action in its own audit trail. + /// + public async Task RevokeByExchangePurposeAsync( + int organizationId, string code, string actor, CancellationToken ct = default) + { + var normalized = ExchangePurposeSan.Normalize(code) + ?? throw new ArgumentException($"'{code}' is not an exchange purpose code (e.g. T-TRTMNT).", nameof(code)); + var org = await db.Organizations.FindAsync([organizationId], ct) + ?? throw new InvalidOperationException($"Organization {organizationId} not found."); + var subscriber = $"{org.Name} (organization {org.Id})"; + + var requests = await FindIssuedCarryingAsync(organizationId, normalized, ct); + if (requests.Count == 0) + { + await audit.RecordAsync(actor, PortalAuditActions.CertificatesRevokedByExchangePurpose, null, + $"No issued certificates of {subscriber} carry {normalized}; nothing revoked."); + return new BulkRevocationOutcome(true, null, [], new Dictionary(), []); + } + + RevocationApiResult result; + try + { + result = await ca.RevokeByExchangePurposeAsync(new RevocationApiRequest + { + SerialNumbers = requests.Select(r => r.SerialNumber!).ToList(), + ExchangePurpose = normalized, + SubscriberRef = subscriber, + RequestedBy = actor, + }, ct); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException) + { + logger.LogError(ex, "CA revocation call failed for {Subscriber} / {Code}", subscriber, normalized); + result = RevocationApiResult.Failure($"CA call failed: {ex.Message}"); + } + + if (!result.Success) + { + await audit.RecordAsync(actor, PortalAuditActions.CertificatesRevokedByExchangePurpose, null, + $"Revoking certificates of {subscriber} carrying {normalized} failed: {result.Error}", succeeded: false); + return new BulkRevocationOutcome(false, result.Error, [], new Dictionary(), []); + } + + var revoked = result.Revoked.ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var request in requests.Where(r => revoked.Contains(r.SerialNumber!))) + { + request.Status = RequestStatus.Revoked; + request.UpdatedAt = DateTime.UtcNow; + request.Events.Add(new RequestEvent + { + Actor = actor, + EventType = "Revoked", + Detail = $"privilegeWithdrawn: exchange purpose {normalized} withdrawn for {subscriber}.", + }); + } + await db.SaveChangesAsync(ct); + + await audit.RecordAsync(actor, PortalAuditActions.CertificatesRevokedByExchangePurpose, null, + $"Revoked {result.Revoked.Count} certificate(s) of {subscriber} carrying {normalized}" + + (result.Revoked.Count > 0 ? $": {string.Join(", ", result.Revoked)}" : "") + "." + + (result.Skipped.Count > 0 + ? $" Skipped: {string.Join("; ", result.Skipped.Select(s => $"{s.Key} ({s.Value})"))}." + : "") + + (result.CrlErrors.Count > 0 ? $" CRL problems: {string.Join("; ", result.CrlErrors)}." : "")); + + return new BulkRevocationOutcome(true, null, result.Revoked, result.Skipped, result.CrlErrors); + } + + /// Exchange purposes the issued certificate's SANs carry, or the requested SANs' when it can't be read. + private IReadOnlySet CarriedExchangePurposes(CertificateRequest request) + { + if (!string.IsNullOrWhiteSpace(request.CertificatePem)) + { + try + { + using var cert = X509Certificate2.CreateFromPem(request.CertificatePem); + return ExchangePurposeSan.Scan(cert, _queryParameterName).Codes; + } + catch (Exception ex) when (ex is CryptographicException or ArgumentException) + { + // Fall back to what was requested. + } + } + + var sans = JsonSerializer.Deserialize>(request.RequestedSansJson ?? "[]", Json) ?? []; + return ExchangePurposeSan.Scan(sans, _queryParameterName).Codes; + } +} diff --git a/Sigyll.Portal/Services/PortalAuditTrail.cs b/Sigyll.Portal/Services/PortalAuditTrail.cs index 3f5acc4..d2eadf3 100644 --- a/Sigyll.Portal/Services/PortalAuditTrail.cs +++ b/Sigyll.Portal/Services/PortalAuditTrail.cs @@ -22,6 +22,9 @@ public static class PortalAuditActions public const string LockedOut = "user.locked-out"; public const string SignedOut = "user.signed-out"; public const string SecurityChanged = "user.security-changed"; + public const string ExchangePurposeAuthorized = "organization.exchange-purpose-authorized"; + public const string ExchangePurposeWithdrawn = "organization.exchange-purpose-withdrawn"; + public const string CertificatesRevokedByExchangePurpose = "certificate.bulk-revoked"; } /// diff --git a/Sigyll.Portal/Services/RequestWorkflowService.cs b/Sigyll.Portal/Services/RequestWorkflowService.cs index 93ed6e7..96b6e44 100644 --- a/Sigyll.Portal/Services/RequestWorkflowService.cs +++ b/Sigyll.Portal/Services/RequestWorkflowService.cs @@ -28,6 +28,7 @@ public class RequestWorkflowService( IssuancePolicyService policy, DomainValidationService dv, CaApiClient ca, + ExchangePurposeService exchangePurposes, ILogger logger) { private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); @@ -43,6 +44,10 @@ public async Task SubmitAsync( string csrPem, CancellationToken ct = default) { + // A requester in exactly one enabled organization requests for it: the subscriber whose exchange purpose + // authorizations apply and whose certificates a bulk revocation finds. + organizationId ??= await SoleOrganizationAsync(requesterId, ct); + var request = new CertificateRequest { RequesterId = requesterId, @@ -69,6 +74,16 @@ public async Task SubmitAsync( request.Status = RequestStatus.PolicyEvaluated; AddEvent(request, "system", "PolicyEvaluated", $"{decision.Kind}: {decision.Reason}"); + // Flag SANs carrying an exchange purpose the subscriber is not authorized for, or conflicting exchange + // purposes; RA approval is blocked while either remains (see ApproveAsync). + var sanCheck = await exchangePurposes.CheckAsync(sans, organizationId, ct); + if (!sanCheck.Passes) + { + var flag = sanCheck.Describe(); + request.PolicyReason = $"{request.PolicyReason} {flag}"; + AddEvent(request, "system", "ExchangePurposeFlagged", flag); + } + switch (decision.Kind) { case PolicyDecisionKind.AutoIssue: @@ -128,6 +143,18 @@ public async Task ApproveAsync(int requestId, string raUserI if (request.Status != RequestStatus.PendingRaApproval) return request; + // Blocked while any SAN carries an exchange purpose the subscriber is not authorized for, or conflicting + // exchange purposes. The request stays in the queue so it can be approved once the authorization is + // recorded, or rejected. + var sanCheck = await exchangePurposes.CheckRequestAsync(request, ct); + if (!sanCheck.Passes) + { + AddEvent(request, $"ra:{raUserId}", "ApprovalBlocked", sanCheck.Describe()); + request.UpdatedAt = DateTime.UtcNow; + await db.SaveChangesAsync(ct); + return request; + } + request.RaApproverId = raUserId; request.RaReason = reason; request.RaDecisionAt = DateTime.UtcNow; @@ -178,6 +205,9 @@ private async Task IssueAsync( RaApprovalRef = raApprovalRef, ValidatedIdentifiers = validatedIdentifiers, RequestedSans = sans, + // The CA re-checks every exchange purpose a SAN carries against this list. + AuthorizedExchangePurposes = (await exchangePurposes.AuthorizedCodesAsync(request.OrganizationId, ct)) + .Order(StringComparer.Ordinal).ToList(), }; IssuanceApiResult result; @@ -230,6 +260,18 @@ private async Task IsRequesterAuthorizedAsync(string requesterId, string t .Any(td => string.Equals(td, trustDomainName, StringComparison.OrdinalIgnoreCase))); } + /// The requester's organization when they belong to exactly one enabled organization; otherwise null. + private async Task SoleOrganizationAsync(string requesterId, CancellationToken ct) + { + var orgIds = await db.OrganizationMemberships + .Where(m => m.UserId == requesterId && m.Organization.Enabled) + .Select(m => m.OrganizationId) + .Distinct() + .Take(2) + .ToListAsync(ct); + return orgIds.Count == 1 ? orgIds[0] : null; + } + private async Task LoadAsync(int requestId, CancellationToken ct) => await db.CertificateRequests .Include(r => r.Challenges) diff --git a/Sigyll/Program.cs b/Sigyll/Program.cs index 0bd4c8e..771e2a8 100644 --- a/Sigyll/Program.cs +++ b/Sigyll/Program.cs @@ -124,6 +124,9 @@ builder.Configuration.GetSection("GcpKms")); builder.Services.Configure( builder.Configuration.GetSection("Pkcs11")); + // How SAN URIs carry an exchange purpose; must match the RA portal's setting. No query parameter name by default. + builder.Services.Configure( + builder.Configuration.GetSection(ExchangePurposeSanOptions.Section)); builder.Services.AddHttpClient("VaultTransit"); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -354,8 +357,9 @@ Log.Warning("RA API accepts the development placeholder key; this is refused outside Development"); } - // The RA can only ask for CSR-based issuance; every other service call from its requests is refused. - var RaClient = OperatorIdentity.System("ra-client", Permission.IssueFromRa); + // The RA can only ask for CSR-based issuance and for revocation of certificates whose exchange purpose + // authorization it withdrew; every other service call from its requests is refused. + var RaClient = OperatorIdentity.System("ra-client", Permission.IssueFromRa, Permission.RevokeFromRa); app.MapGet("/api/ra/catalog", async (HttpContext http, IDbContextFactory dbFactory) => { @@ -394,7 +398,8 @@ IssuanceApiRequest apiRequest, IDbContextFactory dbFactory, OperatorContext operatorContext, - CertificateIssuanceService issuanceService) => + CertificateIssuanceService issuanceService, + IOptions exchangePurposeSan) => { if (!RaAuth.IsAuthorized(http, raOptions)) return Results.Unauthorized(); operatorContext.RunAs(RaClient); @@ -429,6 +434,27 @@ statusCode: StatusCodes.Status403Forbidden); } + // Defense in depth: when the RA sends the subscriber's authorized exchange purposes, every exchange purpose + // a URI SAN carries must be among them, and no SAN may carry conflicting exchange purposes. + if (apiRequest.AuthorizedExchangePurposes is { } authorizedPurposes) + { + var authorizedSet = authorizedPurposes + .Select(ExchangePurposeSan.Normalize).OfType().ToHashSet(StringComparer.Ordinal); + var scan = ExchangePurposeSan.Scan(apiRequest.RequestedSans, exchangePurposeSan.Value.QueryParameterName); + if (scan.AmbiguousSans.Count > 0) + return Results.Json(IssuanceApiResult.Failure( + $"SAN(s) carry conflicting exchange purposes: {string.Join(", ", scan.AmbiguousSans)}"), + statusCode: StatusCodes.Status403Forbidden); + var unauthorized = scan.Codes + .Where(xp => !authorizedSet.Contains(xp)) + .Order(StringComparer.Ordinal) + .ToList(); + if (unauthorized.Count > 0) + return Results.Json(IssuanceApiResult.Failure( + $"The subscriber is not authorized for exchange purpose(s): {string.Join(", ", unauthorized)}"), + statusCode: StatusCodes.Status403Forbidden); + } + // Select an issuing CA in this trust domain with signing capability (prefer an intermediate). var issuingCa = await db.CaCertificates .Where(c => c.TrustDomainId == trustDomain.Id && c.Enabled && !c.IsArchived && !c.IsRevoked @@ -463,6 +489,23 @@ }); }); + // Revokes the listed certificates whose exchange purpose authorization the RA withdrew (reason privilegeWithdrawn), + // each only if a URI SAN carries that exchange purpose, and publishes new CRLs. Audit-logged by the service. + app.MapPost("/api/ra/revoke-by-exchange-purpose", async ( + HttpContext http, + RevocationApiRequest apiRequest, + OperatorContext operatorContext, + CertificateManagementService management) => + { + if (!RaAuth.IsAuthorized(http, raOptions)) return Results.Unauthorized(); + operatorContext.RunAs(RaClient); + + var result = await management.RevokeByExchangePurposeAsync( + apiRequest.SerialNumbers, apiRequest.ExchangePurpose, apiRequest.SubscriberRef, apiRequest.RequestedBy, + http.RequestAborted); + return result.Success ? Results.Ok(result) : Results.BadRequest(result); + }); + app.Run(); } // A test host stops startup once it has the app (HostAbortedException); that is not a failure. diff --git a/_tests/Sigyll.Signing.Tests/ExchangePurposeSanTests.cs b/_tests/Sigyll.Signing.Tests/ExchangePurposeSanTests.cs new file mode 100644 index 0000000..3c8b9a9 --- /dev/null +++ b/_tests/Sigyll.Signing.Tests/ExchangePurposeSanTests.cs @@ -0,0 +1,156 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Shouldly; +using Sigyll.Contracts; +using Xunit; + +namespace Sigyll.Signing.Tests; + +public class ExchangePurposeSanTests +{ + // A stand-in for whatever query parameter name gets configured; deliberately not a real or proposed name. + private const string Param = "purpose-param"; + + [Theory] + [InlineData("urn:oid:2.16.840.1.113883.3.7204.1.5.2.1#T-TRTMNT", "T-TRTMNT")] + [InlineData("https://fhir.example.org/r4#T-PYMNT", "T-PYMNT")] + [InlineData("https://fhir.example.org/r4/T-TRTMNT", "T-TRTMNT")] + [InlineData("https://fhir.example.org/r4/T-PH-ECR", "T-PH-ECR")] + [InlineData("urn:oid:2.16.840.1.113883.3.7204.1.5.2.1/T-IAS", "T-IAS")] + [InlineData("https://fhir.example.org/r4/T-TRTMNT#T-TRTMNT", "T-TRTMNT")] + public void FragmentAndPathForms_WorkWithoutConfiguration(string san, string expected) + { + ExchangePurposeSan.Extract(san, queryParameterName: null).ShouldBe(expected); + ExchangePurposeSan.Extract(san, Param).ShouldBe(expected); + } + + [Theory] + [InlineData("https://fhir.example.org/r4?purpose-param=T-TRTMNT", "T-TRTMNT")] + [InlineData("https://fhir.example.org/r4?app=one&purpose-param=T-HCO", "T-HCO")] + [InlineData("https://fhir.example.org/r4?purpose-param=T-HCO&purpose-param=T-HCO", "T-HCO")] + [InlineData("https://fhir.example.org/r4/T-HCO?purpose-param=T-HCO#T-HCO", "T-HCO")] + public void QueryForm_UsesTheConfiguredName(string san, string expected) + { + ExchangePurposeSan.Extract(san, Param).ShouldBe(expected); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void QueryForm_IsIgnoredWhenNoNameIsConfigured(string? name) + { + ExchangePurposeSan.Parse("https://fhir.example.org/r4?purpose-param=T-TRTMNT", name) + .ShouldBe(new ExchangePurposeMatch(null, false)); + } + + [Fact] + public void QueryForm_NameIsCaseSensitive() + { + ExchangePurposeSan.Extract("https://fhir.example.org/r4?Purpose-Param=T-TRTMNT", Param).ShouldBeNull(); + } + + [Fact] + public void QueryForm_ValueIsNotPercentDecoded() + { + ExchangePurposeSan.Extract("https://fhir.example.org/r4?purpose-param=T%2DTRTMNT", Param).ShouldBeNull(); + } + + [Fact] + public void QueryForm_RepeatedWithDifferentValues_IsAmbiguous() + { + ExchangePurposeSan.Parse("https://fhir.example.org/r4?purpose-param=T-TRTMNT&purpose-param=T-PYMNT", Param) + .ShouldBe(new ExchangePurposeMatch(null, true)); + } + + [Theory] + [InlineData("https://x.example/T-IAS#T-HCO", null)] + [InlineData("https://x.example/fhir?purpose-param=T-PYMNT#T-HCO", Param)] + [InlineData("https://x.example/T-IAS?purpose-param=T-PYMNT", Param)] + public void DifferentCodesInDifferentPlaces_AreAmbiguous(string san, string? name) + { + ExchangePurposeSan.Parse(san, name).ShouldBe(new ExchangePurposeMatch(null, true)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("https://fhir.example.org")] + [InlineData("https://fhir.example.org/r4")] + [InlineData("https://fhir.example.org/r4#section-2")] + [InlineData("https://fhir.example.org/r4/T-PH-ECR/")] // trailing slash: the last segment is empty + [InlineData("urn:oid:1.2.3#t-trtmnt")] // codes are case-sensitive + [InlineData("https://fhir.example.org/r4/t-trtmnt")] + [InlineData("https://fhir.example.org/r4/T%2DTRTMNT")] // never percent-decoded + [InlineData("urn:oid:2.16.840.1.113883.3.7204.1.5.2.1")] + [InlineData("T-TRTMNT")] + [InlineData("https://T-TRTMNT")] // authority, not path + public void ReturnsNullWhenNoExchangePurpose(string? san) + { + ExchangePurposeSan.Parse(san, Param).ShouldBe(new ExchangePurposeMatch(null, false)); + } + + [Fact] + public void Scan_IgnoresNonUriEntries_AndReportsAmbiguousSans() + { + var sans = new List + { + new() { Type = "Uri", Value = "urn:oid:1.2.3#T-TRTMNT" }, + new() { Type = "uri", Value = "urn:oid:1.2.3#T-TRTMNT" }, + new() { Type = "Uri", Value = "https://x.example/fhir?purpose-param=T-PYMNT" }, + new() { Type = "Uri", Value = "https://x.example/T-IAS#T-HCO" }, + new() { Type = "Dns", Value = "T-HCO" }, + }; + + var scan = ExchangePurposeSan.Scan(sans, Param); + + scan.Codes.Order().ShouldBe(["T-PYMNT", "T-TRTMNT"]); + scan.AmbiguousSans.ShouldBe(["https://x.example/T-IAS#T-HCO"]); + ExchangePurposeSan.Scan(sans, null).Codes.ShouldBe(["T-TRTMNT"]); + } + + [Fact] + public void Scan_ReadsTheCertificateSanUris() + { + using var rsa = RSA.Create(2048); + var req = new CertificateRequest("CN=client", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + var san = new SubjectAlternativeNameBuilder(); + san.AddUri(new Uri("urn:oid:2.16.840.1.113883.3.7204.1.5.2.1#T-TRTMNT")); + san.AddDnsName("client.example.org"); + san.AddUri(new Uri("https://fhir.example.org/r4")); + req.CertificateExtensions.Add(san.Build()); + using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1)); + + ExchangePurposeSan.ReadSanUris(cert).Count.ShouldBe(2); + ExchangePurposeSan.Scan(cert, null).Codes.ShouldBe(["T-TRTMNT"]); + } + + [Theory] + [InlineData("T-TRTMNT", true)] + [InlineData("T-PH-ECR", true)] + [InlineData("t-pymnt", false)] + [InlineData(" T-PYMNT", false)] + [InlineData("TRTMNT", false)] + [InlineData("T-", false)] + [InlineData("T-TRT MNT", false)] + public void IsCode_IsExact(string code, bool expected) + { + ExchangePurposeSan.IsCode(code).ShouldBe(expected); + } + + [Fact] + public void Normalize_TrimsTypedInputButKeepsCase() + { + ExchangePurposeSan.Normalize(" T-TRTMNT ").ShouldBe("T-TRTMNT"); + ExchangePurposeSan.Normalize("t-trtmnt").ShouldBeNull(); + } +} diff --git a/_tests/Sigyll.Signing.Tests/ExchangePurposeServiceTests.cs b/_tests/Sigyll.Signing.Tests/ExchangePurposeServiceTests.cs new file mode 100644 index 0000000..3d4d9fa --- /dev/null +++ b/_tests/Sigyll.Signing.Tests/ExchangePurposeServiceTests.cs @@ -0,0 +1,210 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Net; +using System.Net.Http.Json; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Shouldly; +using Sigyll.Contracts; +using Sigyll.Portal.Data; +using Sigyll.Portal.Data.Entities; +using Sigyll.Portal.Services; +using Xunit; +using CertificateRequest = Sigyll.Portal.Data.Entities.CertificateRequest; + +namespace Sigyll.Signing.Tests; + +public class ExchangePurposeServiceTests +{ + private readonly DbContextOptions _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + + private readonly StubCaHandler _ca = new(); + + private (ExchangePurposeService Service, PortalDbContext Db) Create() + { + var db = new PortalDbContext(_options); + var client = new CaApiClient(new HttpClient(_ca) { BaseAddress = new Uri("https://ca.test") }, + Options.Create(new PortalOptions())); + return (new ExchangePurposeService(db, client, new PortalAuditTrail(_options), + Options.Create(new ExchangePurposeSanOptions()), NullLogger.Instance), db); + } + + private async Task SeedOrgAsync(string name = "Example Clinic") + { + await using var db = new PortalDbContext(_options); + var org = new Organization { Name = name }; + db.Organizations.Add(org); + await db.SaveChangesAsync(); + return org.Id; + } + + [Fact] + public async Task Authorize_RecordsWhoAndWhen_AndIsAudited() + { + var orgId = await SeedOrgAsync(); + var (service, db) = Create(); + + var row = await service.AuthorizeAsync(orgId, " T-TRTMNT ", "ra@example.test"); + await service.AuthorizeAsync(orgId, "T-TRTMNT", "someone-else@example.test"); + + row.Code.ShouldBe("T-TRTMNT"); + row.ApprovedBy.ShouldBe("ra@example.test"); + (await db.OrganizationExchangePurposes.CountAsync()).ShouldBe(1); + (await service.AuthorizedCodesAsync(orgId)).ShouldBe(["T-TRTMNT"]); + (await db.AuditEvents.SingleAsync()).Action.ShouldBe(PortalAuditActions.ExchangePurposeAuthorized); + } + + [Fact] + public async Task Authorize_RefusesSomethingThatIsNotACode() + { + var orgId = await SeedOrgAsync(); + var (service, _) = Create(); + + await Should.ThrowAsync(() => service.AuthorizeAsync(orgId, "treatment", "ra")); + await Should.ThrowAsync(() => service.AuthorizeAsync(orgId, "t-trtmnt", "ra")); + } + + [Fact] + public async Task Withdraw_RemovesTheAuthorization_AndIsAudited() + { + var orgId = await SeedOrgAsync(); + var (service, db) = Create(); + await service.AuthorizeAsync(orgId, "T-TRTMNT", "ra"); + + (await service.WithdrawAsync(orgId, "T-TRTMNT", "ra2")).ShouldBeTrue(); + (await service.WithdrawAsync(orgId, "T-TRTMNT", "ra2")).ShouldBeFalse(); + + (await service.AuthorizedCodesAsync(orgId)).ShouldBeEmpty(); + (await db.AuditEvents.CountAsync(e => e.Action == PortalAuditActions.ExchangePurposeWithdrawn)).ShouldBe(1); + } + + [Fact] + public void Check_ListsUnauthorizedExchangePurposes_AndFlagsAmbiguousSans() + { + var sans = new List + { + new() { Type = "Uri", Value = "urn:oid:1.2.3#T-TRTMNT" }, + new() { Type = "Uri", Value = "urn:oid:1.2.3#T-PYMNT" }, + new() { Type = "Uri", Value = "https://fhir.example.org/r4" }, + }; + var (service, _) = Create(); + + var check = service.Check(sans, new HashSet { "T-TRTMNT" }); + check.Unauthorized.ShouldBe(["T-PYMNT"]); + check.Passes.ShouldBeFalse(); + + var ambiguous = service.Check( + [new ApiSanEntry { Type = "Uri", Value = "https://fhir.example.org/T-PYMNT#T-TRTMNT" }], + new HashSet { "T-TRTMNT", "T-PYMNT" }); + ambiguous.Unauthorized.ShouldBeEmpty(); + ambiguous.AmbiguousSans.ShouldBe(["https://fhir.example.org/T-PYMNT#T-TRTMNT"]); + ambiguous.Passes.ShouldBeFalse(); + ambiguous.Describe().ShouldContain("conflicting"); + } + + [Fact] + public async Task RevokeByExchangePurpose_SendsMatchingSerials_MarksRequestsRevoked_AndAudits() + { + var orgId = await SeedOrgAsync(); + var otherOrgId = await SeedOrgAsync("Other"); + var treatment = await SeedIssuedAsync(orgId, "urn:oid:1.2.3#T-TRTMNT"); + var payment = await SeedIssuedAsync(orgId, "urn:oid:1.2.3#T-PYMNT"); + var otherOrg = await SeedIssuedAsync(otherOrgId, "urn:oid:1.2.3#T-TRTMNT"); + _ca.Respond = req => new RevocationApiResult { Success = true, Revoked = [.. req.SerialNumbers] }; + + var (service, db) = Create(); + var outcome = await service.RevokeByExchangePurposeAsync(orgId, "T-TRTMNT", "ra@example.test"); + + outcome.Success.ShouldBeTrue(); + _ca.Received!.SerialNumbers.ShouldBe([treatment.Serial]); + _ca.Received.ExchangePurpose.ShouldBe("T-TRTMNT"); + _ca.Received.RequestedBy.ShouldBe("ra@example.test"); + _ca.Received.SubscriberRef.ShouldContain("Example Clinic"); + + await using var check = new PortalDbContext(_options); + (await check.CertificateRequests.FindAsync(treatment.Id))!.Status.ShouldBe(RequestStatus.Revoked); + (await check.CertificateRequests.FindAsync(payment.Id))!.Status.ShouldBe(RequestStatus.Issued); + (await check.CertificateRequests.FindAsync(otherOrg.Id))!.Status.ShouldBe(RequestStatus.Issued); + (await check.RequestEvents.SingleAsync(e => e.RequestId == treatment.Id && e.EventType == "Revoked")) + .Detail!.ShouldContain("privilegeWithdrawn"); + var audit = await check.AuditEvents.SingleAsync(e => e.Action == PortalAuditActions.CertificatesRevokedByExchangePurpose); + audit.Succeeded.ShouldBeTrue(); + audit.Detail!.ShouldContain(treatment.Serial); + } + + [Fact] + public async Task RevokeByExchangePurpose_RecordsAFailedCaCall() + { + var orgId = await SeedOrgAsync(); + var issued = await SeedIssuedAsync(orgId, "urn:oid:1.2.3#T-TRTMNT"); + _ca.Respond = _ => RevocationApiResult.Failure("boom"); + + var (service, _) = Create(); + var outcome = await service.RevokeByExchangePurposeAsync(orgId, "T-TRTMNT", "ra"); + + outcome.Success.ShouldBeFalse(); + await using var check = new PortalDbContext(_options); + (await check.CertificateRequests.FindAsync(issued.Id))!.Status.ShouldBe(RequestStatus.Issued); + (await check.AuditEvents.SingleAsync()).Succeeded.ShouldBeFalse(); + } + + private async Task<(int Id, string Serial)> SeedIssuedAsync(int orgId, string sanUri) + { + using var rsa = RSA.Create(2048); + var req = new System.Security.Cryptography.X509Certificates.CertificateRequest( + "CN=client", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + var san = new SubjectAlternativeNameBuilder(); + san.AddUri(new Uri(sanUri)); + req.CertificateExtensions.Add(san.Build()); + using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1)); + + await using var db = new PortalDbContext(_options); + var request = new CertificateRequest + { + RequesterId = "user", + OrganizationId = orgId, + TrustDomainName = "TEFCA", + ProfileName = "Client", + SubjectDn = "CN=client", + RequestedSansJson = JsonSerializer.Serialize(new[] { new ApiSanEntry { Type = "Uri", Value = sanUri } }), + Status = RequestStatus.Issued, + SerialNumber = cert.SerialNumber, + CertificatePem = cert.ExportCertificatePem(), + }; + db.CertificateRequests.Add(request); + await db.SaveChangesAsync(); + return (request.Id, cert.SerialNumber); + } + + private sealed class StubCaHandler : HttpMessageHandler + { + public Func Respond { get; set; } = + _ => new RevocationApiResult { Success = true }; + + public RevocationApiRequest? Received { get; private set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Received = await request.Content!.ReadFromJsonAsync(ct); + var result = Respond(Received!); + return new HttpResponseMessage(result.Success ? HttpStatusCode.OK : HttpStatusCode.BadRequest) + { + Content = JsonContent.Create(result), + }; + } + } +} diff --git a/_tests/Sigyll.Signing.Tests/RevokeByExchangePurposeTests.cs b/_tests/Sigyll.Signing.Tests/RevokeByExchangePurposeTests.cs new file mode 100644 index 0000000..33ec2d7 --- /dev/null +++ b/_tests/Sigyll.Signing.Tests/RevokeByExchangePurposeTests.cs @@ -0,0 +1,183 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook JoeShook@Gmail.com +// Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using Sigyll.Contracts; +using Shouldly; +using Sigyll.Common.Data; +using Sigyll.Common.Data.Entities; +using Sigyll.Common.Security; +using Sigyll.Common.Services; +using Sigyll.Common.Services.Audit; +using Sigyll.Common.Services.Jobs; +using Sigyll.Common.Services.Signing; +using Xunit; + +namespace Sigyll.Signing.Tests; + +public class RevokeByExchangePurposeTests +{ + private readonly IDbContextFactory _dbFactory = new TestDbContextFactory(); + + private CertificateManagementService CreateService(IOperatorContext operatorContext, string? queryParameterName = null) + { + var httpFactory = Substitute.For(); + httpFactory.CreateClient(Arg.Any()).Returns(new HttpClient()); + var chain = new ChainValidationService(_dbFactory, operatorContext, httpFactory, + NullLogger.Instance); + var crl = new CrlGenerationService(_dbFactory, operatorContext, + NullLogger.Instance, new LocalSigningProvider()); + return new CertificateManagementService(_dbFactory, operatorContext, + NullLogger.Instance, chain, crl, + exchangePurposeSan: Options.Create(new ExchangePurposeSanOptions { QueryParameterName = queryParameterName })); + } + + [Fact] + public async Task RevokesOnlyCertificatesCarryingTheExchangePurpose_AndPublishesACrl() + { + var caId = await SeedCaAsync(); + var treatment = await SeedIssuedAsync(caId, "urn:oid:2.16.840.1.113883.3.7204.1.5.2.1#T-TRTMNT"); + var queryForm = await SeedIssuedAsync(caId, "https://fhir.example.org/r4?purpose-param=T-TRTMNT"); + var payment = await SeedIssuedAsync(caId, "urn:oid:2.16.840.1.113883.3.7204.1.5.2.1#T-PYMNT"); + var ambiguous = await SeedIssuedAsync(caId, "https://fhir.example.org/T-PYMNT#T-TRTMNT"); + + var ra = TestOperators.As(OperatorIdentity.System("ra-client", Permission.IssueFromRa, Permission.RevokeFromRa)); + var result = await CreateService(ra, "purpose-param").RevokeByExchangePurposeAsync( + [treatment.ToLowerInvariant(), queryForm, payment, ambiguous, "DEADBEEF"], "T-TRTMNT", "Example Clinic (organization 7)", "ra@example.test"); + + result.Success.ShouldBeTrue(); + result.Revoked.Order().ShouldBe(new[] { treatment, queryForm }.Order()); + result.Skipped.Keys.Order().ShouldBe(new[] { payment, ambiguous, "DEADBEEF" }.Order()); + result.Skipped[ambiguous].ShouldContain("ambiguous"); + result.CrlErrors.ShouldBeEmpty(); + + await using var db = _dbFactory.CreateDbContext(); + var certs = await db.IssuedCertificates.ToListAsync(); + certs.Single(c => c.SerialNumber == ambiguous).IsRevoked.ShouldBeFalse(); + foreach (var c in certs.Where(c => c.SerialNumber != payment && c.SerialNumber != ambiguous)) + { + c.IsRevoked.ShouldBeTrue(); + c.RevocationReason.ShouldBe((int)X509RevocationReason.PrivilegeWithdrawn); + } + certs.Single(c => c.SerialNumber == payment).IsRevoked.ShouldBeFalse(); + + (await db.Crls.CountAsync(c => c.CaCertificateId == caId)).ShouldBe(1); + + var events = await db.AuditEvents.ToListAsync(); + events.Count(e => e.Action == AuditActions.CertificateRevoked).ShouldBe(2); + var summary = events.Single(e => e.Action == AuditActions.CertificatesRevokedByExchangePurpose); + summary.Actor.ShouldBe("ra-client"); + summary.Detail!.ShouldContain("T-TRTMNT"); + summary.Detail.ShouldContain("Example Clinic"); + summary.Detail.ShouldContain("ra@example.test"); + events.ShouldContain(e => e.Action == AuditActions.CrlGenerated); + } + + [Fact] + public async Task AlreadyRevokedCertificatesAreSkipped() + { + var caId = await SeedCaAsync(); + var serial = await SeedIssuedAsync(caId, "urn:oid:1.2.3#T-TRTMNT", revoked: true); + + var result = await CreateService(TestOperators.Full).RevokeByExchangePurposeAsync( + [serial], "T-TRTMNT", "org", "ra"); + + result.Revoked.ShouldBeEmpty(); + result.Skipped[serial].ShouldBe("Already revoked."); + await using var db = _dbFactory.CreateDbContext(); + (await db.Crls.CountAsync()).ShouldBe(0); + } + + [Fact] + public async Task RejectsSomethingThatIsNotAnExchangePurpose() + { + var result = await CreateService(TestOperators.Full).RevokeByExchangePurposeAsync( + ["01"], "treatment", "org", "ra"); + + result.Success.ShouldBeFalse(); + } + + [Fact] + public async Task TheRaClientMayNotUseOrdinaryRevocation() + { + var caId = await SeedCaAsync(); + var ra = TestOperators.As(OperatorIdentity.System("ra-client", Permission.IssueFromRa, Permission.RevokeFromRa)); + + await Should.ThrowAsync( + () => CreateService(ra).RevokeAsync(caId, "CaCertificate", 1)); + } + + private async Task SeedCaAsync() + { + using var rsa = RSA.Create(2048); + var req = new CertificateRequest("CN=XP Test CA", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + req.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + req.CertificateExtensions.Add(new X509KeyUsageExtension( + X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); + req.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(req.PublicKey, false)); + using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); + + await using var db = _dbFactory.CreateDbContext(); + var trustDomain = new TrustDomain { Name = "XP", Enabled = true }; + db.TrustDomains.Add(trustDomain); + await db.SaveChangesAsync(); + + var ca = new CaCertificate + { + TrustDomainId = trustDomain.Id, + Name = "XP Test CA", + Subject = cert.Subject, + X509CertificatePem = cert.ExportCertificatePem(), + EncryptedPfxBytes = cert.Export(X509ContentType.Pkcs12, "test"), + PfxPassword = "test", + Thumbprint = cert.Thumbprint, + SerialNumber = cert.SerialNumber, + NotBefore = cert.NotBefore.ToUniversalTime(), + NotAfter = cert.NotAfter.ToUniversalTime(), + }; + db.CaCertificates.Add(ca); + await db.SaveChangesAsync(); + return ca.Id; + } + + private async Task SeedIssuedAsync(int caId, string sanUri, bool revoked = false) + { + using var rsa = RSA.Create(2048); + var req = new CertificateRequest("CN=client", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + var san = new SubjectAlternativeNameBuilder(); + san.AddUri(new Uri(sanUri)); + req.CertificateExtensions.Add(san.Build()); + using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1)); + + await using var db = _dbFactory.CreateDbContext(); + db.IssuedCertificates.Add(new IssuedCertificate + { + IssuingCaCertificateId = caId, + Name = $"client-{cert.SerialNumber}", + Subject = cert.Subject, + SubjectAltNames = $"Uri:{sanUri}", + X509CertificatePem = cert.ExportCertificatePem(), + Thumbprint = cert.Thumbprint, + SerialNumber = cert.SerialNumber, + NotBefore = cert.NotBefore.ToUniversalTime(), + NotAfter = cert.NotAfter.ToUniversalTime(), + IsRevoked = revoked, + RevokedAt = revoked ? DateTime.UtcNow : null, + RevocationReason = revoked ? 1 : 0, + }); + await db.SaveChangesAsync(); + return cert.SerialNumber; + } +} diff --git a/dist/AlloyDB/portal/portal/tables/V4__organization_exchange_purposes.sql b/dist/AlloyDB/portal/portal/tables/V4__organization_exchange_purposes.sql new file mode 100644 index 0000000..bbfbdfd --- /dev/null +++ b/dist/AlloyDB/portal/portal/tables/V4__organization_exchange_purposes.sql @@ -0,0 +1,27 @@ +-- Exchange purposes (TEFCA XP codes such as T-TRTMNT) each subscriber organization is authorized to carry in its +-- certificates' SANs. Issuance and RA approval check SANs against this list, and withdrawing an exchange purpose +-- lets the RA revoke every certificate of the organization that carries it. + +CREATE TABLE "OrganizationExchangePurposes" ( + "Id" INTEGER GENERATED BY DEFAULT AS IDENTITY, + "OrganizationId" INTEGER NOT NULL, + "Code" CHARACTER VARYING(64) NOT NULL, + "ApprovedBy" CHARACTER VARYING(256) NOT NULL, + "ApprovedAt" TIMESTAMP WITH TIME ZONE NOT NULL, + CONSTRAINT "PK_OrganizationExchangePurposes" PRIMARY KEY ("Id"), + CONSTRAINT "FK_OrganizationExchangePurposes_Organizations_OrganizationId" FOREIGN KEY ("OrganizationId") REFERENCES "Organizations" ("Id") ON DELETE CASCADE +); + +CREATE UNIQUE INDEX "IX_OrganizationExchangePurposes_OrganizationId_Code" ON "OrganizationExchangePurposes" USING btree ("OrganizationId", "Code"); + +COMMENT ON TABLE "OrganizationExchangePurposes" IS 'Exchange purposes a subscriber organization is authorized for; a withdrawn one is deleted and kept in the audit trail'; + +COMMENT ON COLUMN "OrganizationExchangePurposes"."Id" IS 'Primary key'; + +COMMENT ON COLUMN "OrganizationExchangePurposes"."OrganizationId" IS 'Subscriber organization (Organizations.Id)'; + +COMMENT ON COLUMN "OrganizationExchangePurposes"."Code" IS 'Exchange purpose code, upper-case, e.g. T-TRTMNT'; + +COMMENT ON COLUMN "OrganizationExchangePurposes"."ApprovedBy" IS 'RA or portal admin account that recorded the authorization'; + +COMMENT ON COLUMN "OrganizationExchangePurposes"."ApprovedAt" IS 'When the authorization was recorded (UTC)';