using System.Security.Cryptography; using System.Text; using Khaemhat.Application.Licensing; using Khaemhat.Application.Modules; using Khaemhat.Application.Tables; using Khaemhat.Core.EInvoicing; using Khaemhat.Core.Instance; using Khaemhat.Core.Logging; using Khaemhat.Core.Security; using Khaemhat.Data; using Khaemhat.Data.Companies; using Khaemhat.Data.Querying; using Khaemhat.Fiscal.Abstractions; using Microsoft.Extensions.Logging; namespace Khaemhat.Application.EInvoicing; /// The answer to a push of the exchange system. /// The HTTP status. /// The content type. /// The body. public sealed record SdiPushAnswer(int StatusCode, string ContentType, string Body); /// /// Takes what the SDI pushes to the web service of a company (SdICoop, issue #76): invoices of suppliers and /// notifications. The request carries the key stored in the channel (header X-Khaemhat-SdiCoop-Key); the mutual /// TLS with the SDI is the job of the reverse proxy in front of Khaemhat. A disabled company, a channel that is not /// enabled or a wrong key get nothing. /// public sealed partial class SdiPushService { /// The header with the key of the channel. public const string KeyHeader = "X-Khaemhat-SdiCoop-Key"; private readonly ICompanyRegistry _companies; private readonly ILicenseGate _license; private readonly IUnitOfWorkFactory _factory; private readonly CompanyFiscalContext _packs; private readonly ISecretProtector _secrets; private readonly EInvoicePollingService _polling; private readonly TimeProvider _clock; private readonly ILogger _logger; /// Creates the service. /// The companies. /// The licence. /// The units of work. /// The fiscal pack of each company. /// Opens the key of the channel. /// Sorts the files received. /// The clock. /// The log (section SDI). public SdiPushService( ICompanyRegistry companies, ILicenseGate license, IUnitOfWorkFactory factory, CompanyFiscalContext packs, ISecretProtector secrets, EInvoicePollingService polling, TimeProvider clock, ILogger logger) { ArgumentNullException.ThrowIfNull(companies); ArgumentNullException.ThrowIfNull(license); ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(packs); ArgumentNullException.ThrowIfNull(secrets); ArgumentNullException.ThrowIfNull(polling); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(logger); _companies = companies; _license = license; _factory = factory; _packs = packs; _secrets = secrets; _polling = polling; _clock = clock; _logger = logger; } /// Takes a push. /// The company in the address. /// The key in the header. /// The content type. /// The body. /// Cancellation. /// The answer. public async Task ReceiveAsync(string companyCode, string? key, string? contentType, byte[] body, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(body); using var scope = _logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)); var notFound = new SdiPushAnswer(404, "text/plain", "Not found."); if (!_license.IsModuleActive(ModuleCodes.EInvoicing) || await _companies.FindAsync(companyCode, cancellationToken).ConfigureAwait(false) is not { } company || company.Status is CompanyStatus.Disabled) { return notFound; } var pack = await _packs.PackOfAsync(company.Code, cancellationToken).ConfigureAwait(false); if (pack.GetFeature() is not { } reader) { return notFound; } var channel = reader.Channel; EInvoiceChannelSetting? row; await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false)) { var rows = (await uow.Repository().ListAsync(Query.For().Where(c => c.Code == channel).Take(1), cancellationToken) .ConfigureAwait(false)).Items; row = rows.Count > 0 ? rows[0] : null; } var expected = row is { Enabled: true, ProtectedApiKey: { Length: > 0 } stored } ? _secrets.Unprotect(stored, EInvoiceStore.SecretPurpose) : null; if (expected is null || key is null || !SameKey(expected, key)) { LogRefused(_logger, company.Code, channel); return new SdiPushAnswer(401, "text/plain", "Unauthorized."); } if (reader.Read(contentType, body) is not { } push) { var (type, refusal) = reader.Refusal(); return new SdiPushAnswer(400, type, refusal); } var now = _clock.GetUtcNow(); var messageKey = push.ExchangeId ?? EInvoiceStore.Hash(body); var files = push.Files.Select(f => new EInvoiceIncoming(f.FileName, f.Content, now, messageKey, null)).ToList(); var outcome = await _polling.ReceivePushedAsync(company.Code, channel, files, cancellationToken).ConfigureAwait(false); LogReceived(_logger, company.Code, channel, outcome.Invoices, outcome.Receipts); return new SdiPushAnswer(200, push.AnswerContentType, push.Answer); } private static bool SameKey(string expected, string given) => CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(expected)), SHA256.HashData(Encoding.UTF8.GetBytes(given))); [LoggerMessage(Level = LogLevel.Warning, Message = "Push of channel {Channel} for company {Company} refused: wrong key or channel not enabled.")] private static partial void LogRefused(ILogger logger, string company, string channel); [LoggerMessage(Level = LogLevel.Information, Message = "Push of channel {Channel} for company {Company}: {Invoices} invoices, {Receipts} notifications.")] private static partial void LogReceived(ILogger logger, string company, string channel, int invoices, int receipts); }