Skip to content

Security & Encryption

How sensitive data is protected at rest, how a fresh deployment is secured before anyone can sign in, and how to keep the encryption keys safe.

Overview

Sensitive data is protected in four layers:

  • Field-level encryption for credentials and personal data the app reads back (API keys, OAuth secrets, names, phone numbers).
  • File encryption for uploaded files, on every storage provider.
  • One-way hashing for values that only need verifying (invitation tokens, recovery codes, single-use links).
  • Storage-layer protection — disk encryption, encrypted backups, network isolation — a deployment concern, not a code one.

Encryption is on by default. The keys are described in Encryption keys.

Rate limits, lockout, security headers, CSP and the outbound-URL (SSRF) guard are configured in Configuration → Authentication and Configuration → Security headers & outbound URLs. Requests the outbound-URL guard covers (outgoing webhooks, push endpoints, an organisation’s SSO provider) never go through an HTTP proxy, whatever HTTP_PROXY / HTTPS_PROXY say, because the guard checks the address it actually connects to.

Field-level encryption

How it works

Tag a string property with [Encrypted]. The storage layer encrypts on write and decrypts on read through ISecretProtector — a BSON serializer convention on MongoDB, an EF value converter on PostgreSQL and SQL Server. Values are encrypted with ASP.NET Core Data Protection (AES-256-GCM) under the deployment’s key ring, kept in the platform database and wrapped by the KEK; the stored form starts bbe1. and names the key it was written under. Code sees plaintext; the database stores ciphertext. No service, repository or page needs to change.

public class EmailSettings : BaseEntity
{
[Encrypted] public string ApiKey { get; set; } = string.Empty;
[Encrypted] public string SmtpPassword { get; set; } = string.Empty;
public string SenderEmail { get; set; } = string.Empty;
}

What’s encrypted

The authoritative list is every [Encrypted] property in Core/BlazorBlueprint.Domain. By category:

  • Provider credentials — email (EmailSettings.ApiKey, SmtpPassword); OAuth client secrets (ExternalAuthSettings); per-organisation SSO (SsoSettings.ClientSecret); AI integrations, platform payment accounts and per-organisation Stripe/PayPal credentials (ApiKey and Settings on ApiIntegration, PlatformApiIntegration and PaymentProviderCredentials); Twilio (SmsProviderCredentials.AuthToken); Mailgun (MailgunCredentials.ApiKey, WebhookSigningKey); cloud storage keys (PlatformStorageSettings); the Cloudflare API token; outgoing webhook signing secrets.
  • Deployment keys — PlatformPushSettings.VapidPrivateKey.
  • User data — ApplicationUser.FirstName, LastName, PhoneNumber (encrypted by each backend’s mapping, as it is inherited from Identity), DateOfBirth (an ISO date string), and the TOTP seed AuthenticatorKey.
  • Content — SMS recipient, sender, body and error, and SMS opt-out notes; appointment titles, descriptions and locations; uploaded file names (StoredFile.FileName); payment customer email, description, card last four, hosted checkout URL, client secret, failure reason and metadata; outgoing webhook URLs, custom headers, delivery payloads, response excerpts and errors; the provider’s diagnostic on an email suppression; the email outbox’s subject and bodies (EmailMessage — its To, Cc, Bcc, Reply-To and sender addresses and its attachments are stored unencrypted, until the processed row is pruned MaxAgeInDays (90) after it was queued); the sender and subject in an organisation’s received-mail log (InboundEmailReceipt).

What’s not encrypted, on purpose

  • Email / NormalizedEmail / UserName / NormalizedUserName — sign-in lookup and uniqueness.
  • DisplayName — the registration uniqueness check.
  • Public values — passkey credential ids and public keys, VapidPublicKey.
  • Provider reference ids (Stripe, PayPal, Twilio) — the lookup key for incoming webhooks.
  • The domain verification token — a keyed HMAC that is published in DNS anyway.

Encrypted fields cannot be queried

The ciphertext is non-deterministic: the same value encrypts differently each time, so a database-side equality, substring or sort on an encrypted field never matches. Never filter on an [Encrypted] field in a repository query — filter in memory, or keep a separate plain field. (This is why the user search at /Platform/Users searches display name, user name and email.)

For exact-match lookup (say, “the user with this phone number”), store a blind index — an HMAC of the normalised value — beside it and query that. Avoid blind indexes on low-entropy fields such as first names: hash counts can be matched against public name frequencies.

Adding an encrypted field

  1. The property must be a string — any other type throws at startup.
  2. Add [Encrypted] (BlazorBlueprint.Domain.Attributes).
  3. Do not give it [StringLength] or [MaxLength]: on PostgreSQL and SQL Server that bounds the ciphertext column, several times longer than the value, so long values fail to save there. Limit the form input instead. A test fails the build if an encrypted property carries one.

Reads follow the stored value: a value in the ciphertext form is decrypted (and a value that is ciphertext but does not decrypt throws CryptographicException, failing the query), anything else is returned as stored. A field that already held plain values before the attribute was added therefore keeps reading; each value is encrypted when that field next changes (a save that leaves a field unchanged does not rewrite it).

Stored files

Every upload goes through IFileService, which encrypts the bytes under the key ring before they reach the storage provider — GridFS, PostgreSQL bytea, SQL Server varbinary, Azure Blob and S3 alike — unless the file is to be served directly from storage. A leaked bucket, GridFS collection, file table or database backup therefore holds ciphertext.

  • Format. The file is encrypted in 64 KiB chunks with AES-256-GCM, under a random key made for that file alone. The header holds that key, protected by the key ring, and the file’s id, and is authenticated by every chunk, so a truncated, reordered or extended file fails, and a blob copied over another file (in the same organisation or another) fails to open. Stored bytes start BBF2.
  • Reads. A download holds one chunk in memory, not the file, and range requests (video seeking) fetch only the chunks they need, on every provider. A damaged header or first chunk fails before any response is sent; a file damaged further in fails part-way through the download. Nothing unauthenticated is ever returned.
  • Recorded on the file. Each StoredFile records at upload whether its bytes are encrypted (Encrypted) and which serve mode it asked for (ServeMode). Both are records of how the file was written, not settings: reads follow them, whatever the settings say now.
  • What stays plain. The file name is an [Encrypted] field. Its size, content type, image dimensions, owner and storage key are not. An encrypted file records no hash of its content (an unkeyed hash beside the ciphertext would let anyone holding the database confirm a guess at what a file holds); a file stored plain records its SHA-256.
  • Uploads are buffered in memory up to the upload size limit (MaxFileSizeMb, 25 MB by default) before they are stored, as they are hashed and checked first.

Files served directly

On Azure Blob and S3 a Member file can be handed to the browser as a short-lived signed URL instead of streaming through the app (ServeMode Direct — the platform setting on Platform → Storage, or a plugin asking for it on one upload). The browser then fetches the stored bytes itself, so a file uploaded to be served directly is stored without the app’s encryption, relying on the storage provider’s own encryption at rest — check what yours provides. That protects the provider’s disks, not a leaked bucket credential, and gives no binding to the file’s id.

With encryption on:

Situation Result
Platform Proxy, upload asks nothing or Proxy encrypted; streamed through the app
Platform Direct, upload asks nothing or Direct (Member file, Azure Blob or S3) stored plain; signed URL
Platform Direct, upload asks Proxy encrypted; streamed through the app
Platform Proxy, upload asks Direct (Member file, Azure Blob or S3) stored plain; signed URL
Upload asks Direct for a Public file, or on GridFS, PostgreSQL or SQL Server recorded as asking nothing; follows the platform setting, which on those providers always streams
Serve mode or encryption changed after upload the file keeps the form it was written in; an encrypted file always streams, a plain one may be served directly

Public files (branding, avatars, anything at /api/files/public/{id}) always stream through the app, decrypted when encrypted: a signed URL would expire. The route answers public, max-age=86400 with an ETag, so a CDN in front of the app serves repeat requests from its cache and decryption runs only on a miss.

Turning encryption off

Security:Encryption:Enabled (default true, shipped true in every host) decides how new stored data is written: values of [Encrypted] fields and uploaded files. It is the operator’s choice in every environment, Production included.

"Security": {
"Encryption": {
"Enabled": true
}
}
Setting Writes Reads
true fields and files encrypted (files served directly excepted) ciphertext decrypted; anything else returned as stored
false fields and files stored in plain text the same: data stored encrypted still decrypts
  • Off means database backups and storage buckets hold that data in plain text — provider keys, passwords, message bodies, uploaded files. Startup logs a warning while it is off, and the Encryption keys panel shows one.
  • Nothing already stored is converted when it changes either way; data stays as it was written. After turning it on, a field stored plain is encrypted when that field next changes, and a file stored plain stays plain (upload it again to encrypt it). After turning it off, encrypted fields and files still decrypt.
  • Sealed values (queued webhook bodies and job payloads, the account deletion status link) are always encrypted, whatever the setting, so turning it off never makes them forgeable.
  • The key ring exists either way (created at first start): sign-in and sealed values need it, and turning encryption on later needs no setup.
  • Every host of a deployment must hold the same value; a test fails the build if the shipped appsettings.json files disagree. A host with a different value writes what it stores in its own form.
  • It is configuration, not a feature switch, so an admin session cannot turn it off.
  • Reading both forms is deliberate: with encryption on, someone who can already write the database could replace a ciphertext value with a plain one and the app would use it — but such a writer can change every plain column already, and refusing plain values would break every deployment that turns encryption on after running with it off.

One-way hashing

Values that only need to be verified are stored as SHA-256 hashes; the raw value is shown or sent once.

  • Organisation invitation tokens (OrganisationMembership.InvitationToken) — the raw token is in the emailed link, and it is the only way to accept: a matching account email is not proof. Links use the platform address, so none can be sent until one is set. /Org/Select shows invitations only for an address the account has proven through an emailed confirmation link (ApplicationUser.EmailProvenAtUtc). Sending is capped at 30 an hour per inviter and 100 an hour per organisation. Accepting an invitation into a deactivated organisation is refused and never reactivates it.
  • Recovery codes (ApplicationUser.RecoveryCodes) — shown once; redeeming one removes its hash. Setting up an authenticator app issues a fresh set, and resetting it or turning two-factor off clears the old set.
  • Site preview links (SitePreviewLink.TokenHash) — the raw token is shown once, in the share link. Lookups that match no live link are limited to 300 a minute per client address, in the shared store; a valid token never spends that allowance.
  • Single-use access links — anything giving an unauthenticated visitor a token in a URL should store only its hash and an expiry and compare in constant time. Use ITokenHasher (Sha256TokenHasher): 256-bit random tokens, verified with CryptographicOperations.FixedTimeEquals.

Personal data export

[PersonalData] (ASP.NET Core Identity) decides which fields the download on /Account/Manage/PersonalData contains; [ProtectedPersonalData] fields are handled individually (the authenticator key only as whether one is set). [Encrypted] decides storage independently, and encrypted personal data is exported in plaintext. See Privacy → Personal Data Rights.

Account security

What a user can see and do about their own account:

  • Active sessions (/Account/Manage/Sessions) — every sign-in with device, IP and last activity, with per-session and sign-out-everywhere revocation, applied on every instance. A password change revokes the other sessions. Each sign-in has an absolute lifetime (Authentication:SessionAbsoluteLifetimeDays, default 90).
  • Security activity (/Account/Manage/SecurityActivity) — the user’s own sign-ins and security changes; pruned on the audit retention window.
  • Lockout — 5 failed sign-in attempts lock the account for 15 minutes by default (Authentication:Lockout:MaxFailedAttempts, LockoutMinutes).
  • Requiring two-step sign-in — RequireTwoFactorForPlatformAdmins and RequireTwoFactor at Platform Settings → Features, both off by default. A covered person with neither an authenticator app nor a passkey is confined to /Account/Manage/SecureAccount (plus sign-out, legal pages and their own data) until they enrol, whatever the sign-in method; if the check cannot run, they count as not enrolled.
    • A passkey counts, and then it is how they sign in. A covered account whose only second factor is a passkey is refused password-only and external (Google, Facebook, Microsoft, organisation SSO) sign-in. Someone who loses that passkey needs a platform administrator to reset their two-factor (below).
    • Switch it on before handing out accounts. An account with no factor yet enrols one on its next password sign-in. A platform admin who switches it on without a factor is sent to set one up straight away.
  • Passkey sign-in names no account — passkeys are registered as discoverable credentials (residentKey: "required"), and the options endpoint (/Account/PasskeyRequestOptions) takes no address and returns no credential ids, so it cannot reveal which addresses are registered. A security key that cannot store a discoverable credential is refused at registration.
  • Passkey suggestion — with PromptPasskeySetup on (the default), someone without a passkey is offered one at sign-in (“Not now” re-asks in 30 days).
  • Recovery-code sign-in rotates the security stamp and signs out every other session.
  • Password reset through the emailed link signs out every session and removes the account’s passkeys and external logins (Google, Facebook, Microsoft, organisation SSO), so a login someone else linked cannot survive the owner proving the mailbox; the owner re-links them from Account → External logins. Exception: where a two-factor switch covers the account and passkeys are its only second factor, they are kept, so a mailbox alone cannot take the account over. A signed-in password change keeps them and signs out other sessions.
  • Changing the email address or deleting the account asks for the current password; an account without one must have signed in within the last 15 minutes (the same rule as adding or removing a passkey, setting a password or changing two-factor settings). A session cookie alone cannot move an account to a new inbox or close it.
  • Email confirmation happens only when the confirmation page’s button is pressed (a POST), so a link scanner cannot confirm an address.
  • Account email links (password reset, confirmation, email change, invitation) always point at the saved platform address — never the request’s scheme, host or port, which come from the client — and are https:// except for a local http://localhost:{port} address. Before initial setup none is sent.
  • Resetting someone’s two-factor — Platform → Users → Details → Reset two-factor, for someone who has lost their only second factor. It signs out every session, removes every passkey, resets the authenticator app and clears recovery codes; it is audited, reports any step that did not complete, is safe to re-run, and requires a sign-in within the last 15 minutes. Linked external logins are kept (the confirmation lists them), so verify the request comes from the owner: whoever next signs in, with the password or any of those logins, sets up the new factor. It is not offered on your own account, so keep a second platform administrator, or register more than one passkey.
  • Revoking a platform admin, or locking an account, ends their sessions immediately.
  • Deleting someone’s account — Platform → Users offers a soft delete (the grace window, restorable) or Hard delete now: immediate and irreversible, and audited. Neither is allowed on the last usable platform admin. See Privacy → Personal data rights.

Count anonymous attempts in the shared store

A limiter in front of an anonymous surface must count in IRateLimitStore (Redis-backed when Redis is present), not process memory — a per-process counter gives an attacker N times the budget across N instances. Key a per-client budget on ClientIpHash.ForRateLimitBucket, which counts an IPv6 client by its /64 and an IPv4-mapped address as its IPv4. An anonymous write also needs a per-organisation ceiling.

Organisation single sign-on is a credential the organisation controls

An organisation’s identity provider (Admin → Single Sign-On, scheme oidc-org:{organisationId}) is configured by its administrator, and accounts are platform-wide, so the host treats it as a third-party credential:

  • It reaches only a fixed provider’s own servers. The administrator picks Microsoft Entra ID, Google Workspace, Okta or Auth0 and enters a tenant identifier matching that provider’s pattern (Okta and Auth0: a name plus a region from a list); the sign-in address is built in code. Tokens must come from that tenant’s issuer — for Google, from an account in the organisation’s Workspace domain (the hd claim).
  • It never vouches for an email address. An account created through it (or through any provider sending email_verified=false) is not recorded as confirmed; with RequireEmailConfirmation on it gets a confirmation link.
  • It signs in only active members of that organisation, even with the login still linked.
  • A password reset removes it, like every external login. A member re-links it from Account → External logins, which offers it only for an organisation whose SSO is enabled and complete, and re-checks membership when the provider returns.

Audit trail

Three trails record who did what, each in the database with its own page:

Trail Records Read at
Organisation The organisation’s own events — settings and payment-provider credentials saved; member roles changed; members joining, leaving and removed; invitations sent, re-issued, cancelled or declined; payments refunded; website addresses and preview links changed; outgoing webhook subscriptions changed; apps turned on or off and their settings saved; custom roles changed, granted or removed; a platform admin entering the organisation (while Security:Audit:TenantVisibleImpersonationAudit is on) Admin → Audit (/Admin/Audit), by its admins
Platform Platform-wide events — sign-ins, failed sign-ins, lockouts, sign-outs and registrations; accounts locked, unlocked or deleted by a platform admin; a platform admin revealing a user’s personal data; every deployment setting saved; feature switches (naming each change); organisations created, changed (SSO configuration included), activated, deactivated or deleted; platform-admin grants; two-factor resets; impersonation, and attempts refused while it is off; hostname claims and blocks; operator refunds and subscription changes; disputes on subscription charges; plans changed; orphaned organisations resolved; Rotate Data Protection key; the recovery key confirmed at initial setup Platform → Audit (/Platform/Audit)
Security activity Each user’s own sign-ins and security changes Account → Security activity, by that user

Every row holds personal data: the actor’s label and the client IP address, unaltered. Platform rows name the signed-in account by display name, else email address (Unknown for failed sign-ins and lockouts); organisation rows by display name, full name or the email’s local part. Organisation admins see the IP column at Admin → Audit, including a platform admin’s when one enters the organisation. Erasing an account leaves its audit rows in place until they age out — see Privacy.

Rows are kept for 180 days (BackgroundServices:DataRetention:AuditRetentionInDays). The organisation trail is also capped at BackgroundServices:DataRetention:MaxRecordCount rows per organisation (10,000 shipped); past that the oldest are deleted whatever their age. Raise the cap, or set 0 to rely on age alone, if your retention obligation is a period.

Saves are audited by the service that makes them, so a change from a plugin page or background job is recorded too. A platform admin’s visit to an organisation they are not a member of is recorded at most every 30 minutes per organisation.

Every audit event is also logged and counted — a line in the BlazorBlueprint.Audit log category and the blazorblueprint.audit.events counter. The log line carries ids only (trail, action, user, organisation, row) — never names, emails, IP addresses or free text. That copy is what reaches your SIEM (see Deployment → Observability); set Logging:LogLevel:BlazorBlueprint.Audit to None to stop it without affecting the database trail.

Platform admins entering organisations is Security:PlatformAdmin:OrgImpersonation, true by default: a platform admin can open and administer an organisation they are not a member of, and every visit is in the platform audit log. Set false to keep them out.

Whether the customer sees such a visit is Security:Audit:TenantVisibleImpersonationAudit, true by default: it also records the visit in that organisation’s own log (the platform log records it regardless).

Each trail’s database storage can be switched off: Security:Audit:StoreOrganisationAudit, StorePlatformAudit, StoreSecurityEvents and StoreApiUsage (the daily totals at Platform → API Usage), all true by default. While one is false:

  • no new rows are stored; existing rows stay until the retention sweep removes them;
  • events are still logged and counted (StoreApiUsage: the OpenTelemetry usage metrics are still recorded — see Privacy);
  • the trail’s page shows a notice instead of its list, and its menu link is dimmed and tagged Off;
  • every host logs a startup warning naming the audit trails it is not storing.

These keys are configuration, deliberately not Platform Settings switches, so the person a trail records cannot turn it off without a redeploy. Current values are listed at Platform → Infrastructure. All three hosts write audit records, so set the same values on every host (an environment variable reaches them all).

Initial setup

Creating the platform organisation and first platform admin hands out full control, and on a fresh install nobody is signed in to authorise it. Either of two things does:

  • A trusted connection — the socket peer is loopback (in Development only) or an address in Security:Setup:TrustedProxies / TrustedNetworks, and the Host header is localhost, 127.0.0.1 or ::1 (not configurable). This path is for a browser on the server itself. Loopback is not trusted outside Development because a reverse proxy on the same host connects from loopback for every visitor.

  • A setup token — Security:Setup:Token if set (at least 32 characters; a shorter one is ignored, logged as an error, and a token generated instead), otherwise 256 random bits per process. Open /initial-setup?setupToken=…. It is compared in constant time, held in memory only, and a blank value never validates. A generated token is logged at Warning the first time a setup attempt is refused, and changes on every restart:

    Terminal window
    docker compose logs blazorblueprint-web | grep setupToken # Lite: docker compose -f <your Lite file> logs web

    A token you set is never logged. Pin it if you run more than one web replica.

Neither applies once an organisation exists.

In a container, the address cannot tell you who is asking

With a published port, the app sees Docker’s bridge gateway as the peer for every caller, so no shipped compose file trusts that network and first run in a container uses the token. You can opt in on the web service:

- "Security__Setup__TrustedNetworks__0=172.16.0.0/12"

That trusts every caller that can reach the published port until setup is complete — do it only if the port is unreachable from outside the host, and remove it afterwards.

Running first setup over a domain

Use the token — the trusted-connection path requires a localhost Host header. The setup page requires the platform address, pre-filled with the domain or, over localhost, the local address (http://localhost:5034 for dotnet run or Aspire, http://localhost:8080 for a local Docker stack). See Getting started → First run.

An address that arrived in a header is never trusted here

The setup gate refuses any request whose client address was rewritten from forwarded headers (it carries X-Original-For). Security:ForwardedHeaders ships loopback-only and warns at startup if widened; add your proxy only when the app’s port is reachable solely through it. See Deployment → Reverse proxy and forwarded headers.

A forwarded host must be one the app serves

A host from X-Forwarded-Host (via a trusted proxy) decides the organisation and security policy, so it is kept only when it is the platform address or beneath it, a customer hostname an organisation has added, localhost, or listed in Security:ForwardedHeaders:AllowedHosts (empty by default). Otherwise the request is served for the Host the proxy connected with, and a warning is logged at most every five minutes. Before initial setup there is no platform address to check against, so complete setup before exposing the app. See Configuration.

Encryption keys

One set of keys, the ASP.NET Core Data Protection key ring, protects both sign-in and stored data, under one key-encrypting key (KEK). The key ring lives in the platform database, each key wrapped by the KEK before it is stored.

Layer Protects Where Rotation Backed up
Key-encrypting key (KEK) Every key in the key ring An Azure Key Vault key, a file on the KEK volume, or DataProtection:Kek Key Vault key versions; a volume or configured KEK cannot rotate Once, as the recovery key (Key Vault looks after its own)
Data Protection keys (the key ring) Auth cookies, antiforgery tokens, sign-in tickets and hub connection tokens; [Encrypted] fields, sealed values (queued webhook bodies and job payloads, the account deletion status link) and stored files The platform database Every 90 days by Data Protection, plus a button With the database

Lose the key ring and every encrypted field and file is permanently unreadable, and every user is signed out. A database backup always holds every key its data needs. The KEK is never in the database, so a leaked dump or backup cannot be decrypted on its own.

How stored data uses the key ring

  • New keys use AES-256-GCM (configured in AddDataProtection, on every host). The newest active key protects new values; every older key, expired ones included, still decrypts. Every payload names the key it was written under.
  • Each kind of value has its own Data Protection purpose, so none opens as another: fields are written bbe1.{…} (BlazorBlueprint.Fields.v1), sealed values bbs1.{…} (BlazorBlueprint.Sealed.v1), file keys under BlazorBlueprint.Files.v1 (see Stored files), and cookies and tokens under their own.
  • Sealed values carried by jobs never expire: a job can legitimately be old (a dead-lettered webhook replayed weeks later), and its message is signed as well.
  • The account deletion status link comes back from outside, in a URL, so it is sealed with a 60-day lifetime. The expiry is authenticated with the value, so it cannot be extended, and the code is refused once it has passed.

Where the KEK comes from

The first that applies:

  1. Azure Key Vault — DataProtection:KeyVault:KeyId (DATA_PROTECTION_KEY_VAULT_KEY_ID). The KEK never leaves the vault. See Keeping the KEK in Azure Key Vault. Not combinable with DataProtection:Kek.
  2. DataProtection:Kek (DATA_PROTECTION_KEK) — a KEK you supply. Required when app containers do not share a disk and you do not use Key Vault. Once set, leave it set: after recovering a lost volume this way the volume holds no KEK file, and removing the variable stops startup.
  3. The KEK file — kek.txt in DataProtection:KekPath (/kek, the KEK volume: bb_kek on the full stack, shared by web, internal API and worker; bb_lite_kek on Lite), generated on first start.
  4. Development — a per-checkout file under your local application-data folder.

A KEK is bbkek1- followed by 43 base64url characters (32 random bytes). To generate one for a deployment with no data yet:

Terminal window
echo "bbkek1-$(openssl rand 32 | base64 | tr '+/' '-_' | tr -d '=')"

The recovery key

When the app generates the KEK, initial setup shows it once as the recovery key (Copy and Download), and will not finish until you type back its last six characters. It is never shown again.

When the KEK came from elsewhere, setup shows what to check instead: the last six characters of your DATA_PROTECTION_KEK, or the Key Vault key and version in use (check it is this environment’s vault — a first start cannot tell). Platform → Infrastructure shows the same afterwards.

Save it in a password manager and keep one offline copy. If the KEK volume is lost, start with DATA_PROTECTION_KEK set to the recovery key and nothing is lost. Lose the volume and the recovery key, and every encrypted field and file is gone.

Keeping the KEK in Azure Key Vault

The strongest option: the KEK is never on the server, so a stolen server or snapshot cannot take it. Someone who takes over the server can use the application’s access while they have it — every use is logged, and revoking the identity ends it.

  1. Create a vault with soft-delete and purge protection on, and an RSA key in it (e.g. dataprotection-kek). Purge protection is required outside Development (Lite and staging included) or the application refuses to start; a vault that does not report its recovery level counts as having none.
  2. Give the application an identity with only get, wrap key and unwrap key on that key (Key Vault Crypto Service Encryption User, or an equivalent access policy):
    • on an Azure VM, its managed identity — nothing to configure for system-assigned; for user-assigned set DataProtection:KeyVault:ManagedIdentityClientId (DATA_PROTECTION_KEY_VAULT_MANAGED_IDENTITY_CLIENT_ID). Outside Development the app uses exactly this identity, with no fallback;
    • elsewhere, a service principal: DataProtection:KeyVault:TenantId, ClientId and ClientSecret (all three, not with a managed identity). Renew the secret before it expires (at most 24 months). Azure Government and Azure China vaults are detected from the vault address;
    • in Development, your own Azure sign-in (Azure CLI, Visual Studio) also works.
  3. Set DataProtection:KeyVault:KeyId to the key id without a version: https://<vault>.vault.azure.net/keys/<name>.
  4. Optionally restrict the vault firewall to the server’s address and keep one az keyvault key backup copy.

At startup each host wraps and unwraps a test value and checks purge protection (giving up after about a minute). A missing wrap permission is not caught there, as wrapping normally runs locally with the public key. Use the vault’s canonical address. Each stored key records the key version that wrapped it, so rotating the key in Azure needs nothing from the app — but never disable or delete an old version. Switching to a different key or vault is not supported.

What happens at startup

Every host runs these checks before anything can encrypt, and refuses to start if one fails:

  • The KEK — a new one is generated only on a genuine first start (no keys, no canary, setup not done). A missing KEK file over a database with keys asks for the recovery key; it never creates a new KEK over existing data.
  • Every stored key is unwrapped; one that cannot be (wrong KEK, a disabled Key Vault key version, a tampered row) refuses to start, naming the KEK that wrapped it and the one configured.
  • The canary row records the KEK and application discriminator the ring was created under; a mismatch refuses to start. On a new deployment it also elects one container to create the first key.
  • A lost key ring is refused, not replaced. Keys without a canary, a canary without keys, or — after initial setup — neither (a partial restore) all refuse to start: a new ring would boot healthy while every user is signed out and every encrypted field and file stored so far fails to read. Restore those rows from the matching backup. Only if the keys are gone for good, start once with DataProtection:AllowDiscriminatorChange: true — which abandons everything encrypted under the lost ring — then remove it. A canary with no keys is refused even then: restore the keys.
  • With Key Vault, the vault must answer: a host started during an outage refuses after about a minute. Running hosts are unaffected.
  • Keep container clocks in sync (NTP); a clock fifteen minutes out also breaks sign-in tokens.
  • The KEK folder must belong to the app user. A named volume gets this from the image; a host-mounted folder must be readable (and on first start writable) by UID 1654.

Two values you must never change after first deploy

  • DataProtection:ApplicationDiscriminator — feeds key derivation; blank uses BlazorBlueprint. A different value makes everything encrypted before unreadable. If you rebrand, do not search-and-replace the default. Give a new deployment its own value before its first deploy if you like, never after. A mismatch refuses to start, naming both values; DataProtection:AllowDiscriminatorChange=true acknowledges abandoning the old data.
  • The KEK — keep the recovery key. There is no supported way to change it on a deployment with data.

Also leave these fixed strings alone when rebranding: the purposes BlazorBlueprint.Fields.v1, BlazorBlueprint.Sealed.v1 and BlazorBlueprint.Files.v1, the bbe1. and bbs1. prefixes and the BBF2 file header, the key ring’s bbkek1- prefix and BlazorBlueprint.KeyRing.* strings, and the account-flow purposes (AccountProtectorPurposes). Changing them makes stored secrets and files unreadable; a build test fails if they move.

Rotation

  • Automatic — every 90 days, by Data Protection in each container. By hand — Rotate Data Protection key.
  • A new key takes over two days after it is created (containers reload the ring about daily).
  • Old keys are kept for ever and still decrypt (the deletion status link only within its lifetime).
  • Existing data moves to the new key — a cookie or ticket when next issued, a field when it next changes, a file never.

The button is on the Encryption keys panel at Platform → Infrastructure, for platform admins, and is recorded in the platform audit trail. Only one new key may wait at a time. Rotation never touches the KEK.

Rotation is not revocation, and nothing is re-encrypted. Data stays under the key it was written with. After a suspected compromise, rotating stops new data going under the old key; fields and files already written under it stay readable with it. Never delete a key row: whatever is still under that key becomes unreadable.

The app offers no way to revoke a key, and nothing should: a revoked key no longer decrypts, so every field and file stored under it would become unreadable along with the cookies and tickets.

Watching the keys

The Encryption keys panel on Platform → Infrastructure shows the KEK source and fingerprint, then the Data Protection keys: the current key, when the next takes over, and every key with its dates (Retired and Expired keys still decrypt), the last rotation by hand and who did it. It warns when encryption is off, when no key has been created for over 92 days (rotation has stopped), when no key is active, when the Key Vault key has no purge protection, and in Production when the KEK is a file on the server’s volume.

The BlazorBlueprint.Security meter reports blazorblueprint.data_protection.keys and .newest_key_age. The bundled Grafana’s Platform dashboard graphs them, with alert rules Data Protection key rotation has stopped (newest key over 92 days old) and Data Protection key ring errors (a host logged a key-ring error: a key it could not read or unwrap, a refused replacement key).

Backing up

Back up How often
The database, kept off the server. It holds the whole key ring. Daily or more
With Azure Blob or S3 storage, the bucket or container too. Its encrypted files need the database’s key ring to read. With the database
The recovery key (or your DATA_PROTECTION_KEK): password manager plus one offline copy. Once
With Key Vault: nothing extra; optionally one az keyvault key backup. Once

Redis and the KEK volume need no backup for the keys’ sake. A VM snapshot holds both the database and the KEK volume — guard it like the server. A production backup restored elsewhere needs production’s KEK: by design, staging cannot read a production dump’s encrypted fields or files.

What destroys data:

  • Losing the recovery key and the KEK volume.
  • Deleting key rows, or restoring a database without them (or starting with DataProtection:AllowDiscriminatorChange).
  • docker compose down -v (deletes volumes) — never in production; plain down / up -d, image upgrades and reboots keep them.

What the KEK protects against

Leak Volume or configured KEK Key Vault, service principal Key Vault, managed identity
A database dump or backup, on its own Safe — the keys in it are wrapped Safe Safe
Database credentials, read-only access, a hosted database breached Safe Safe Safe
A storage bucket or its credentials Safe — files are encrypted, except files served directly and files uploaded with encryption off Same Same
Redis lost or flushed Safe — Redis holds no keys Safe Safe
Redis read access Cached values exposed: whatever decrypted settings and names are cached at the time (see IAppCache). No keys Same Same
A full VM snapshot Exposed — it holds the KEK file (and deploy.env) Exposed until the client secret is revoked Safe
Root or docker access on the server Exposed, for ever Exposed while they are in; logged; ends when access is revoked Same

Whatever the app can read unattended, whoever owns the machine can read too.

What encryption does not do

  • It does not protect against a compromised application. The app holds every key while it runs; anyone who controls the process or the server reads what it reads.
  • Not everything is encrypted. Only [Encrypted] fields, sealed values and file bytes are; every other column is plain (see What’s not encrypted), as are file metadata, files served directly, data written while encryption was off, values the app has cached in Redis, and logs.
  • No erasure by destroying a key. One key ring serves every organisation and its keys are kept for ever, so deleting an organisation deletes its database and files but no key; a backup taken before stays readable with the KEK. Organisations are kept apart by their separate databases, not by keys.
  • No re-encryption. Rotation and settings changes apply to data written from then on; stored data stays under the key and in the form it was written with until that field next changes or the file is uploaded again.
  • A volume or configured KEK cannot be rotated. For a deployment that is audited for key management (a defined lifetime for every key, the key-encrypting key included), keep the KEK in Azure Key Vault, whose key versions rotate without the app re-wrapping anything.

Local development

The Aspire AppHost gives every project the same per-checkout KEK folder — %LOCALAPPDATA%\BlazorBlueprint\kek\{hash} on Windows, ~/.local/share/BlazorBlueprint/kek/{hash} on Linux, ~/Library/Application Support/BlazorBlueprint/kek/{hash} on macOS — and the keys go in the local database. Removing the database volume starts a fresh ring; deleting only the KEK folder makes startup refuse, so remove the database volume too.

Other built-in controls

  • Uploaded files — capped at MaxFileSizeMb (/Platform/Storage). A public file (served anonymously at /api/files/public/{id} — logos, icons, avatars) must be PNG, JPEG, GIF, WebP, BMP or ICO by content, is stored under its sniffed type, and has EXIF (including GPS), XMP, IPTC and comments stripped; an image too malformed to strip is rejected. Only raster images (and, for members-only files, PDF and plain text) render inline; everything else, SVG and HTML included, downloads, with X-Content-Type-Options: nosniff.
  • Self-service organisation creation — 5 a day per person at /Org/Select (platform admins exempt).
  • Customer hostnames — an organisation cannot connect the platform address or any name beneath it, because the session cookie may be scoped to .{platform address}. Checked when a hostname is added and whenever it is verified. See Architecture → Custom domains and sites.
  • Incoming webhooks (/api/webhooks/organisation/{organisationId}/{provider} and /api/webhooks/platform/{provider}) — each request is verified against the credentials it claims before anything is processed, and the matched credential travels with the queued job, so verification happens once.
    • PayPal verification is a call back to PayPal, made once as a background job; if it cannot complete in time the request answers 503 so PayPal retries. A PayPal delivery whose signed transmission time is missing, more than three days old or more than ten minutes in the future is refused. Stripe and Twilio signatures are checked locally and reject old signatures.
    • Duplicate deliveries are dropped for Messaging:WebhookDedupeTtlSeconds — held in Redis under Full, in process memory under Lite. Payments also record the provider’s event ids, so a payment is never applied twice.
    • Bodies are capped at 1 MB unless the handler declares more (IInboundWebhookHandler.MaxRequestBodyBytes; inbound mail allows 25 MB); larger bodies get 413. Requests are rate-limited in the shared store to 60 a minute per caller, tenant and provider, under a ceiling of 3,000 a minute per caller and provider across tenants (high, because a payment provider sends every organisation’s events from a few addresses). Every authentication failure answers the same 401.
  • Background jobs — over Redis (Messaging:Transport=Redis), every message is HMAC-SHA256 signed with Messaging:MessageSigningKey and verified before it runs. Outside Development every host refuses to start without a key or with the shipped placeholder. Set the same value on every host; to rotate, see Messaging:PreviousMessageSigningKey in Configuration → Background messaging.

Optional hardening

  • The KEK in Azure Key Vault — see above. Another key service (e.g. AWS KMS) would plug into the key-ring store.
  • Storage-level encryption for the database and any storage bucket (encryption at rest, encrypted volumes and backups). It protects against a stolen disk, not stolen database or bucket credentials, and complements the app’s own encryption — for files served directly, it is the only encryption.

Key file locations

  • Core/BlazorBlueprint.Domain/Attributes/EncryptedAttribute.cs — the attribute
  • Infrastructure/BlazorBlueprint.Infrastructure.Persistence.MongoDB/Encryption/ — BSON serializer and convention (MongoDB)
  • Infrastructure/BlazorBlueprint.Infrastructure.Persistence.EntityFrameworkCore/Encryption/ — value converters (PostgreSQL / SQL Server)
  • Core/BlazorBlueprint.Application/Services/Security/FieldEncryption.cs — the switch and the read/write rule every backend applies
  • Core/BlazorBlueprint.Application/Services/Security/DataProtectionSecretProtector.cs and DataProtectionSealedValueProtector.cs — the field and sealed-value protectors over the key ring
  • Core/BlazorBlueprint.Application/Services/Storage/Encryption/ — the chunked file format; Services/Storage/FileServePolicy.cs — which files are served directly
  • Core/BlazorBlueprint.ServiceDefaults/Extensions/ServiceCollectionExtensions.cs — Data Protection discriminator, algorithms and key lifetime
  • Core/BlazorBlueprint.Application/Services/Security/KeyRing/ — the key-ring store, the KEK and the startup checks
  • Web/BlazorBlueprint.Web/Middleware/SetupRedirectMiddleware.cs — the initial-setup gate