Skip to content

Threat model

Scope: the Trellis API and Blazor web host as generated by the template, running against PostgreSQL under Aspire or a container orchestrator. This is the short, honest version — what the template already defends against, what it deliberately leaves to you, and what is simply out of scope. It is meant to be edited, not inherited unchanged: a generated project's real threat model depends on what you build on top.

Asset Why it matters
User credentials and refresh tokens Account takeover
The JWT signing key Forged tokens for any user, including administrators
Business data (invoices) Confidentiality and integrity of customer records
The database connection string Full read/write access to everything above

In-scope threats and the mitigations that exist today

Section titled “In-scope threats and the mitigations that exist today”
Threat Mitigation Where
Credential stuffing / brute force Stricter fixed-window rate limit on the auth endpoints, partitioned per authenticated user or client IP ApiHardeningExtensions
Password guessing against one account Account lockout: 5 failed passwords lock the account for 15 minutes (403 Auth.AccountLockedOut); lockout is checked before the password, so a 403 never confirms a password; a successful sign-in resets the counter IdentityService.ValidateCredentialsAsync, Identity options in AddPersistence
Account enumeration through login timing An unknown e-mail costs the same password-hash verification as a wrong password, and both answer 401 Auth.InvalidCredentials IdentityService, DummyPasswordHash
Anyone on the internet self-registering into read access Registration is closed unless configured (Registration:Mode, default Closed; Development opts in); closed answers 403 Auth.RegistrationClosed and creates nothing RegistrationOptions, RegisterCommandHandler
Missing or oversized auth input reaching Identity or the hasher Validators bound e-mail (254, the Domain's EmailAddress.MaxLength, which also fits Identity's 256-character columns), password (128) and refresh token (512) and reject missing fields with 400 before any lookup, hash or token hash runs Features/Auth/*/*Validator
Brute force going unnoticed Structured security events with stable ids: 1101 sign-in failed, 1102 no such account (masked e-mail), 1103 account locked out (Warning), 1104 rejected while locked, 1105 a failed sign-in the lockout could not count and 1106 a count not reset after a good sign-in (both Warning, Identity error codes only). User id or masked e-mail only, never a password SecurityEventLog
A development signing key shared by every project dotnet new writes a fresh random Development key into each generated project (dev-only- + 64 hex characters); no other environment has a committed key, and the API refuses to boot without one appsettings.Development.json, RequireValidTokenOptions
Stolen refresh token replayed Refresh tokens are single-use; presenting a consumed one revokes every outstanding token for that user (OAuth security BCP); every rejection is the same 401 Auth.InvalidRefreshToken (one AuthErrors member, returned by the store and the handler alike), whether the token was unknown, consumed or its user deleted IRefreshTokenStore.ConsumeAsync, RefreshTokenCommandHandler
SMTP relay credentials leaked from configuration or logs (mail sent as your domain: phishing, a burnt sender reputation) User-secrets in Development, the platform's secret store in production (Email__Smtp__UserName / __Password), never appsettings: the shipped appsettings.json has no UserName or Password key to fill in. While Email:Provider is Smtp, boot refuses half a credential pair and credentials without STARTTLS; the sender logs neither them nor the relay's reply SmtpOptions, SmtpOptionsValidator, SmtpEmailSender
Tokens forged with a weak or absent key Signing key must be ≥ 32 chars; the API refuses to boot otherwise RequireValidTokenOptions, AuthTokenOptions
Refresh tokens readable from a database dump Only SHA-256 hashes are persisted JwtTokenProvider.HashRefreshToken
Privilege escalation between roles Permission-based authorization, policies resolved per permission claim; endpoints declare .RequirePermission(...), and each endpoint's one permission is pinned in the ExpectedPermissions table, so a write declared with a read permission fails the test run, and checked on the wire (only that permission is admitted, every other is a 403) PermissionPolicyProvider, EndpointMetadataTests
An endpoint shipped without authorization Deny-by-default on the versioned API group; permissions per endpoint (unknown names fail the boot); the anonymous set is an allowlist test MapVersionedApiGroup, EndpointMetadataTests
Token forged by algorithm confusion Validation accepts HS256 only (ValidAlgorithms) AddApiAuthentication
Cross-tenant data access (--use-multitenancy) The tenant comes only from the signed tenant claim, minted from the user's persisted membership (AspNetUsers.TenantId); request headers are ignored; every aggregate root is filtered and stamped by convention, and its unique indexes are led by TenantId, so a duplicate in one of them answers only for the caller's own tenant (an alternate key on a root, which the convention cannot rewrite, fails TenancyTests, and so does a unique index or key declared on a value mapped into the root's table with OwnsOne, which the convention never visits); cache keys carry the tenant; a valid token without the claim is rejected 401 (ADR-0022) TenantContext, AuthenticationExtensions, AppDbContext, CacheKeys
A NUL character (U+0000) in a request string turning any write or sign-in into a 500 at will: PostgreSQL's text stores none, so the first query or save carrying it fails, and every such request is an unhandled-exception Error line an alert counts as an incident A JSON body string holding U+0000 is refused while the body binds, before any handler runs, as 400 Request.Malformed naming the member; EmailAddress also refuses every control character, so a caller without the API (the seeder, an event handler) cannot store one in an address. A route value cannot carry one: Kestrel refuses %00 in a path before routing. A string bound from the query is not covered, and none ships (?status= is an enum, page and pageSize integers): a feature that binds one (a ?search= filter) refuses U+0000 in its query's validator, and a test sends one to every query value a GET takes and fails on anything but a 400 NulFreeStringJsonConverter (AddApiCommon), EmailAddress, EndpointContractTests, RequestLimitTests
Client-supplied identifiers poisoning logs or response headers The inbound correlation id is accepted only if short and restricted to an id-shaped charset; otherwise a server id is used CorrelationIdMiddleware
A forged request line breaking a log line (CWE-117): a method or path carrying a line break, so that the malformed-request, unhandled-exception or idempotency-residue line ends early and an invented line follows Kestrel admits only RFC 9110 token characters in a method and PathString is logged in its escaped form (%0A), so neither carries a line break; the three lines still take both through one helper that replaces line endings with a space, which covers a less strict server and is the sanitiser CodeQL recognises, so the cs/log-forging scan a generated project inherits starts clean LogSafeRequestLine
A request or a change nobody can attribute to an account A signed-in caller's request span carries their user id (enduser.id), and so does every log line written past authentication (CallerUserId scope): a rejected write names the account in its outcome line, a 403 from a missing permission in its span (at the shipped log levels it writes no line); the audit columns hold the id of whoever created and last changed a record. The id only, never the e-mail UserTelemetryMiddleware, AuditingInterceptor
Rate-limit evasion behind a proxy X-Forwarded-For honoured only from explicitly configured trusted proxies/networks; the publish-mode ASPNETCORE_FORWARDEDHEADERS_ENABLED switch cannot widen it (loopback-only restored, startup warning) ApiHardeningExtensions
Duplicate submission of a write (double charge, double invoice) Idempotency-Key reserved per (user, method, route, key) inside the command's unit of work — a concurrent duplicate loses at the primary key, or, when it fails on the winner's data first, is answered from the store, a failed command leaves no reservation; a retry gets the stored response replayed, a reused key with a different body a 422 (ADR-0018); a repeated header or a list is a 400, never two keys joined into one, and POST /invoices requires a key (RequireIdempotency(keyRequired: true)) IdempotencyFilter, AppDbContext.CommitAsync
Lost update on concurrent edits xmin concurrency token; a stale write is returned as Concurrency.Conflict and becomes 409 IUnitOfWork.CommitAsync, CustomResults
A third party being down taking us down Per-client resilience pipeline; health check reports Degraded, not Unhealthy ADR-0020
/health used as a load lever against a dependency The external check caches its verdict and probes with a bare TCP connect ExchangeRateHealthCheck
Slow-loris / hung requests Default 30s request timeout returning 504 ApiHardeningExtensions
Oversized requests 1 MB body (413) and 32 KB header caps on Kestrel, configurable ApiHardeningExtensions
MIME sniffing, framing, token or per-user responses cached nosniff, Referrer-Policy, X-Frame-Options/frame-ancestors 'none' on every response; Cache-Control: no-store on every /api/ response (problems included) unless its endpoint sets its own, and always on /auth/ (ADR-0021 amendment) SecurityHeadersMiddleware
Clickjacking or injected script in the web UI CSP script-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none', X-Frame-Options: DENY, nosniff, Referrer-Policy: same-origin on every UI.Web response UI.Web Program.cs
A web session's refresh token used after the user left Sign-out revokes it at the API (/auth/logout, best-effort), and so does a closing circuit TokenAuthenticationStateProvider.SignOutAsync, UI.Web RevokeSessionOnCircuitClose
Open redirect through the sign-in returnUrl Only a plain relative path inside the app is followed; schemes, rooted or protocol-relative paths, backslashes, control characters and dot segments are refused LoginRedirect
Vulnerable dependency pulled in NuGetAudit over the full graph at low, warnings are errors on CI Directory.Build.props
A compromised or broken dependency release merged without a person looking New versions wait a week before Dependabot proposes them (cooldown); only patch and minor updates merge on their own, and only once every required check (build, tests, API contract, container smoke, CodeQL, secret scan, NuGetAudit, the licence ceilings) is green; majors, .NET SDK bumps and the GitHub Actions group wait for review; the release runbook starts with a read of the bumps that merged since the last tag .github/dependabot.yml, .github/workflows/dependabot-auto-merge.yml, docs/releasing.md
Secrets committed to the repository gitleaks scan over full history on every push and PR .github/workflows/ci.yml
Information disclosure through errors All expected failures are RFC 9457 problem documents with a stable code (ADR-0024); a request the framework cannot bind is a 400/413/415 problem whose detail names a parameter or a limit, never a stack; the opaque 500 carries a fixed sentence — exception messages and types stay in the Error log. The OpenAPI document declares exactly that shape on every operation's 4xx/5xx (schema generated from the Contracts record, ADR-0025), so a client never has to probe for the error format; the document itself is served only in Development ADR-0004, ADR-0024, ADR-0025
  • A lockout answer confirms that an account exists. After five failures, login answers 403 Auth.AccountLockedOut whatever password is supplied, which tells an anonymous caller the e-mail is a (locked) account. Accepted: it takes five failures per e-mail under the per-source auth limit, each lockout logs event 1103 at Warning, login timing no longer separates unknown e-mails from wrong passwords, and registration (whose 409 Auth.EmailAlreadyInUse is the cheaper enumeration path) is closed by default. Hiding the lockout would show a legitimate user "wrong password" for 15 minutes.

Known gaps — decide deliberately before production

Section titled “Known gaps — decide deliberately before production”

Each gap names its status: open (yours to decide), closed by default (the template's default is safe; changing the setting reopens it), or addressed (fixed in the template).

  • Open registration means open read access — closed by default. With Registration:Mode set to Open, anyone can register, a new account is a Member, Members hold invoices:read, e-mail is never confirmed and invoices are not owner-scoped: every registrant can read all business data. Before opening it, add e-mail confirmation or give Member no data permissions until an administrator grants a role.
  • Permissions are per endpoint, never per record — open. A permission lets its holder act on every record its endpoints can address (OWASP's broken object-level authorization when that is wrong). A rule about which records (the owner, a team) is each feature's own: a domain OwnerId, enforced in the specification or repository so a non-owner gets the same 404 as for a missing record, with owner-scoped reads keyed by owner or left uncached, because a read-cache hit never runs the handler (docs/features/auth.md, Protecting an endpoint). The reference invoices are business-wide on purpose.
  • The tenant chosen by a request header (--use-multitenancy) — addressed (ADR-0022). The X-Tenant-Id header used to select the tenant for authenticated callers; the tenant now comes only from the signed tenant claim minted from the user's persisted membership, and the header is not read. What remains is open: isolation is row-level in one database — no per-tenant schema or database; a cross-tenant admin view must opt out with IgnoreQueryFilters(["Tenant"]) and a bare IgnoreQueryFilters() drops the filter silently; a leaked signing key forges any tenant; and a unique constraint outside the aggregate-root convention (a child table's unique index or alternate key that its root's id does not lead, a primary key a request chooses, a constraint written into a migration by hand, which no test reads) is unique across every tenant, so its 409, or the 500 of a fault on purpose, tells the caller that another tenant holds the value. Mint ids on the server and declare a business key as a unique index on the root, or record here why a key stays global. A row written with no tenant (TenantId NULL: a job that did not set AmbientTenant, an anonymous endpoint, a webhook) is outside every tenant-led unique index, since PostgreSQL treats NULLs as distinct, so two tenant-less rows may hold the same key: give such a flow its tenant before it writes.
  • A Blazor Server web host is one rate-limit source — open. All of its users share 10 logins per minute (refreshes are unaffected). Widening it means trusting the web host as a proxy, per environment, or a BFF (ADR-0021, ADR-0007).
  • Personal data in outbox rows — open. InvoicePaidDomainEvent carries the customer e-mail, so outbox payloads hold personal data until processed and then for Retention windows (3 days processed, 30 days dead-lettered), longer in backups. Prefer ids over personal data in event payloads, or shorten the windows if your data-protection regime requires it.
  • Personal data in audit columns and telemetry — open. CreatedBy and ModifiedBy hold the acting user's id, a Guid (system for the migration job), never the e-mail: a dump of a business table does not list its editors by address, and a changed e-mail leaves the trail joined to its user (ADR-0027 amendment). A signed-in caller's request spans and log lines carry the same id (enduser.id, CallerUserId). An id is still personal data: erasing a user leaves it in every row they created or changed and in whatever their requests logged, for as long as the log and trace backends keep it, and nothing removes it. Decide the erasure path and how long the columns and the telemetry are kept.
  • No MFA, and no password-breach check on registration — open.
  • Access tokens cannot be revoked before expiry — open. Revocation applies to refresh tokens; an access token stays valid for its (short) lifetime. Shorten AccessTokenMinutes if that window matters.
  • No absolute session lifetime, and logout shares the replay marker — open. A refresh chain can rotate indefinitely (each token lives RefreshTokenDays), and presenting a logged-out token counts as a replay, which revokes the user's other sessions.
  • Rate limiting is per-instance, in-memory — open. Behind N replicas the effective limit is N×. Move to a shared store if the limit is a security control rather than a politeness control.
  • /health and /alive are anonymous so orchestrators can reach them — open. Readiness reveals dependency names and status — keep both off the public ingress.
  • The Aspire dashboard of a compose deployment shows every log line and trace — closed by default. The compose file aspire publish writes binds its UI to the server's loopback (127.0.0.1:18888), so it is reached over an SSH tunnel with the token it prints at start-up; the signing key and the seed password come from .env as parameters, never from the YAML.
  • The security-event log is partial — open. Sign-in failures and lockouts are structured events (1101–1106); registration, revocation, refresh-token replay (an unstructured warning) and role or permission changes are ordinary application logs, and nothing ships them to a tamper-evident store. A signed-in caller's lines carry their id (the CallerUserId scope) and their request spans enduser.id, so a rejected command can at least be traced to an account by its outcome line and a 403 by its span; a 403 from a missing permission writes no log line at the shipped levels, so a run of them shows in traces and in http.server.request.duration by status code, not in the log.
  • The seeded Development admin password is the same in every project — closed by default. The seeder refuses the well-known default outside Development; set Seed__AdminPassword. A replacement Identity rejects fails the migration job (exit 1, errors named) instead of leaving the deployment without an administrator, and Seed values are validated at boot.
  • A half-created account — addressed. Registration creates the user and assigns its role in one transaction, so a failed role assignment cannot leave an account that authenticates with no permissions and blocks its e-mail; the seed repairs an administrator left without its role.
  • Registration racing itself, or echoing what was typed — addressed. Two registrations of one e-mail that pass every check together are decided by the unique user-name index, and the loser gets the same 409 Auth.EmailAlreadyInUse as a sequential duplicate, not a 500. A registration Identity refuses answers 400 Auth.RegistrationRejected built from fixed sentences per Identity error code; Identity's own descriptions, which repeat the e-mail, never reach the response or the outcome log.
  • CORS is deny-by-default — open, which means it is only as good as the origins you add.

Infrastructure and platform concerns the template does not attempt to solve: TLS termination and certificate management, network segmentation, secret storage (use your platform's secret manager — the template only insists the values are present and well-formed at boot), database hardening and backups, OS/container image patching, DDoS protection at the edge, and physical security.

The documentation of Trellis.Templates 0.2.0 · release notes