Security review - September 2026¶
This page records the security review of the shared libraries performed on 2 September 2026, the fixes that shipped with it, and the items that still need a human decision.
The libraries are named as they were on the day of the review: MediatR and MediatR.ML are Mediator and Mediator.ML from 3.0.
Scope and method¶
- Every library under
src/(25 projects, about 12 000 lines of C#), the test projects, the GitHub Actions workflows and the PowerShell automation scripts. - Static review of all sources in five passes (payments core and providers, EF/Querying, MediatR/Email/ML, WebApi/ExceptionHandling, CI), each finding re-verified against the code before a fix was written.
dotnet list package --vulnerable --include-transitive: no vulnerable NuGet packages (direct or transitive).System.Linq.Dynamic.Coreis pinned above the CVE-2024-51417 fix.- Every fix is covered by unit tests; the whole solution (build + 900+ tests) was green before commit.
Findings and status¶
| # | Severity | Area | Finding | Status |
|---|---|---|---|---|
| 1 | Critical | Payments (tests) | A production CashBill shop secret and matching signatures were committed in a test source file (unused test data). | Removed from source. Rotation and history purge require the owner - see Action items. |
| 2 | High | ExceptionHandling | Default provider returned the innermost exception message (SQL errors, hosts, paths) to anonymous callers as HTTP 400 in every environment. | Fixed: 500 + generic message; details only in Development or on explicit opt-in. |
| 3 | High | Payments (all providers) | Signature verification silently degraded to an unkeyed hash when the secret was missing, so anyone could forge a "valid" notification. | Fixed: fail-closed in all 9 providers (incl. Stripe). |
| 4 | High | Payments (CashBill) | Webhook error message echoed the expected signature (an oracle for forging notifications); legacy TransactionStatusChange performed no verification. |
Fixed. |
| 5 | High | Payments (Revolut) | Signed payload used v1: instead of v1.; no timestamp check, so a captured webhook was replayable forever. |
Fixed: correct format, 300 s tolerance (configurable), multi-signature rotation. |
| 6 | High | EntityFramework | Client-controlled SortField passed straight to Dynamic LINQ (navigation traversal, multi-column, schema disclosure); no upper bound on page size. |
Fixed: identifier validation, allow-list overload, page bounds and overflow checks. |
| 7 | High | MediatR | Default cache key used ToString() on properties, so requests differing only in collection contents shared one entry (cross-user data). Logging scope serialized whole requests (secrets, images). |
Fixed: content-hash keys; scope carries only type name + correlation id. |
| 8 | High | Template variables inserted verbatim into HTML bodies (phishing links from a trusted sender); comma-separated recipient strings added extra recipients; SMTP TLS off by default. | Fixed: HTML-encoding by default ({{{raw}}} opt-out), single recipient, TLS on. |
|
| 9 | High | MediatR.ML | Training command read any directory and wrote any file path from the request; classification accepted unbounded, unvalidated bytes. | Fixed: paths confined to TrainingRoot/ModelsRoot; size and signature validation. |
| 10 | Medium | WebApi | Standard resilience handler retried POST/PATCH on every HttpClient, duplicating payments/orders after timeouts. | Fixed: unsafe-method retries disabled by default. |
| 11 | Medium | Payments | Non-constant-time signature comparison; case-sensitive header lookup (broken under HTTP/2); unescaped identifiers in gateway URLs; webhook results without a payment id. | Fixed: WebhookSignature, case-insensitive dictionaries, PaymentIdentifier, ids populated. |
| 12 | Medium | Payments (Przelewy24) | Notification/verify signatures computed over the wrong field sets (every genuine notification rejected). | Fixed to the documented field order. |
| 13 | Medium | EF UnitOfWork | Transaction filter committed when the action returned 4xx/5xx; commit-failure handling could leave a dangling transaction and hide the root cause. | Fixed. |
| 14 | Medium | Email.Office365 | Attachments returned still transfer-encoded and keyed by content type (crash on two attachments of one type). | Fixed. |
| 15 | Medium | CI/CD | Write-scoped tokens with persisted credentials, actions pinned to mutable tags, tag name interpolated into shell, NuGet publish without tests and with failures swallowed, unpinned pip installs. | Fixed: least-privilege permissions, SHA pins + Dependabot, env-var passing, tests before publish, --skip-duplicate, pinned mkdocs-material. |
| 16 | Medium | Payments (Tpay, Adyen) | Webhook verification does not match the vendor protocol (Tpay: form + md5sum + JWS; Adyen: HMAC over colon-separated fields in additionalData). Fails closed, so not exploitable, but non-functional. |
Fixed in 2.0: Tpay verifies md5sum and X-JWS-Signature (chain to the Tpay root), Adyen the HMAC from additionalData.hmacSignature. |
What changed, by library¶
Payments¶
- New
TailoredApps.Shared.Payments.Security.WebhookSignature(constant-timeFixedTimeEquals,FixedTimeEqualsIgnoreCase,IsSecretConfigured) andPaymentIdentifier(IsSafe,EnsureSafe). PaymentWebhookRequest.Headers/Queryare case-insensitive regardless of the dictionary assigned;TransactionStatusChangePayload.QueryParametersis nevernull.- All providers: fail-closed on empty secret/signature, constant-time comparison,
PaymentUniqueIdpopulated from the payload,Processingevents returned asIgnore, identifiers validated before URL interpolation,JsonDocumentdisposed. - CashBill: legacy path verifies the MD5 signature; error messages no longer contain the expected value; missing secret -> "Signature verification is not configured.".
- Revolut:
v1.{timestamp}.{body},WebhookToleranceSeconds(default 300), rotation signatures. - Przelewy24: documented sign field sets with unescaped-unicode JSON; currency normalised once.
- PayU: SHA-1 supported, unknown algorithms rejected. PayNow: stable
Idempotency-Key,EXPIRED. - Stripe: missing
WebhookSecret/header ->Fail; async payment events handled with ids. - Adyen: missing
successtreated as failure;merchantReference/pspReferencein results. - HotPay: the signed service name is the one sent.
ExceptionHandling¶
DefaultExceptionHandlingProvider: validation -> 400; everything else -> 500 with"An unexpected error occurred."; constructor overloads(),(IHostEnvironment),(bool).- Middleware uses
GetRequiredService, skips writing when the response has started, clamps the status code to 400-599.ExceptionOccuredResulthonours the model's code. Duplicate DI registration removed. Docs and agent prompt rewritten against the real API.
WebApi¶
HttpClientSettings.RetryUnsafeHttpMethods(defaultfalse) ->Retry.DisableForUnsafeHttpMethods().
MediatR¶
ICachePolicy.GetCacheKey->{Type.FullName}:{SHA-256(JSON)}viaCacheKeyGenerator.LoggingBehaviorno longer serializes the request; stack trace no longer concatenated into the message template.CachingBehavioruses structured log templates.
Email¶
TokenReplacingMailMessageBuilder: single-pass regex replacement, HTML-encoded{{token}}, raw{{{token}}},HtmlEncodeVariablesoption, null-safe arguments.DefaultMessageBuilder: single-pass, longest-key-first, HTML-encoded by default ((bool)ctor).SmtpEmailProvider: one recipient only (FormatExceptionon lists),CatchAllrequired whenIsProd = false,EnableSsldefaults totrue, proper Message-ID.Office365EmailProvider: attachments decoded and keyed by file name.
MediatR.ML¶
ImageClassificationOptions.TrainingRoot,ModelsRoot,MaxImageBytes(default 10 MB).TrainImageClassificationModelCommandHandlerconfines both paths (ArgumentExceptionoutside the roots,InvalidOperationExceptionwhen roots are not configured).ClassifyImageCommandHandlervalidates presence, size and JPEG/PNG signature. JPEG detection accepts anyFF D8 FFheader.
EntityFramework / Querying¶
QuerySortingExtensions: sort field must be a plain identifier;ApplySorting(..., allowedSortFields)overloads; Dynamic LINQ parse errors rethrown asArgumentExceptionwithout type details.PagingQuery<T>:MaxPageSize(default 1000, static + per-instance),Page >= 1,1 <= Count <= max, overflow-safe skip.TransactionFilterAttribute: rollback on 4xx/5xx results;AggregateExceptionwhen both commit and rollback fail.UnitOfWork: commit/rollback release the transaction infinally.
CI/CD¶
- All workflows:
permissions: contents: readby default,persist-credentials: false, actions pinned to commit SHAs (with version comments),.github/dependabot.ymlforgithub-actions. ci.yml: build/test job separated from thegh-pagesdeploy job (only the latter hascontents: write).release.yml:dotnet testbefore publishing, every package pushed fromartifacts/package/releasewith--skip-duplicate, the job fails when any push fails,environment: nuget(add required reviewers in repository settings). Publishing uses nuget.org Trusted Publishing: the job exchanges a GitHub OIDC token for an API key valid for one hour, so no long-lived NuGet key is stored in the repository.release-notes.yml: tag name passed throughenv, not interpolated into the script.bump-deps.yml: full test run before the PR is created.
Action items for the repository owner¶
- Rotate the CashBill secret for the shop named in the removed test data, in the CashBill
merchant panel. The value has been in git history since commit
ed838d6; rotation is the only reliable remedy. If the repository is or was public, also purge the history (git filter-repo) and force-push, which is a destructive operation that was deliberately not performed here. - The sandbox CashBill secret in
tests/TailoredApps.Shared.Payments.Tests/appsettings.jsonis a test-environment credential; move it to user-secrets/CI secrets if the sandbox shop matters. - In repository settings, add required reviewers to the new
nugetenvironment so tag pushes cannot publish packages without approval, and make the Docs guard and Build & Test PR checks required onmaster. Create the nuget.org Trusted Publishing policy and theNUGET_USERsecret described under Releasing in Contributing, then delete the oldNUGET_API_KEYsecret and revoke that key on nuget.org. - Configure
ImageClassification:TrainingRoot/ModelsRootin hosts that use the training command, and passallowedSortFieldstoApplySortingfor endpoints listing sensitive entities. - Review consumers that relied on the old behaviours: 400 with exception message (now 500 generic),
raw HTML in e-mail variables (now encoded; use
{{{token}}}), SMTP without TLS (EnableSslnowtrue), multi-recipient strings inSendMail, POST retries via the WebApi resilience defaults.
Follow-ups (not done in this change)¶
- Tpay and Adyen: notification verification now follows the vendor protocols, but it has not been exercised with a real sandbox notification - make a test payment before going live. Adyen: the Hosted Checkout session and reading its outcome follow the API specification, also without a test in the Adyen environment.
- A failing gateway is no longer reported as
PaymentStatusEnum.Rejected: the HTTP providers throwPaymentGatewayException(2.0), and from 3.0 Stripe does too (before:StripeException). CachingBehaviorno longer returnsdefaultfor a cache miss on a value-type response (fixed in 1.5.1: a default value is treated as a miss and the handler runs). In 2.0 the problem is gone:CachingBehaviorusesHybridCache, which tells a miss from a cached default value and protects against the handler running concurrently for the same key.- Amount conversion to minor units truncates and assumes two decimals; add a shared ISO-4217 helper.
- PayU order creation shares one pooled handler that does not follow redirects (fixed in 1.5.1; it used to create a handler per order). It still bypasses the named client. OAuth tokens (PayU, Tpay) are fetched on every call.
- EF: session-level
SET TRANSACTION ISOLATION LEVELis SQL-Server-only and redundant; multipleAddUnitOfWorkregistrations cross-wire contexts; audit collector skips proxied entities;HasDefaultValue(DateTime.UtcNow)bakes a constant into migrations. - Package hygiene:
Nullableoff in most projects, noPackageReadmeFilein most packages, floatingx.*versions without a lock file,SourceRevisionIdfromUtcNow, dead TFM conditions. PagedAndSortedRequestduplicatesPagedAndSortedQuery; add[Range]attributes.