Skip to content

Security: Busnes-app/KyPost-Server

SECURITY.md

Security Policy

KyPost is a self-hosted IMAP web client with end-to-end encryption support. This document describes security practices, known limitations, responsible disclosure, and deployment security considerations.

Incoming encryption

Incoming encryption is per-user opt-in and requires a saved-key-backup acknowledgment and fresh account confirmation. It classifies plaintext before encrypting and replacing unread, unprocessed inbox mail; the provider and KyPost see plaintext before replacement. Provider backups and other clients may retain copies. Routing metadata and classification keywords stay visible. Cache bodies stay disabled after opt-in, and pending jobs lock key replacement until verified recovery completes. Permanent size/rule failures are reported after bounded retries and leave the original plaintext in IMAP; recoverable failures remain pending. See the full contract.

Reporting Security Vulnerabilities

If you discover a security vulnerability in KyPost, please report it responsibly via GitHub Security Advisories rather than opening a public issue.

How to Report

  1. Go to the Security Advisories page
  2. Click "Report a vulnerability"
  3. Provide a detailed description, affected versions, and reproduction steps if applicable
  4. Do not disclose the vulnerability publicly until a patch is available

Disclosure Timeline

The timeline for public disclosure depends on severity:

  • Critical (e.g., unauthenticated data access, authentication bypass, remote code execution): 30 days
  • High (e.g., privilege escalation, cryptographic weakness): 60 days
  • Moderate (e.g., denial of service, information disclosure): 90 days

We will:

  • Acknowledge receipt of your report within 2 business days
  • Provide a timeline and severity assessment
  • Develop and test a patch
  • Coordinate a release that includes the fix before the deadline
  • Credit you in the patch release notes (unless you prefer anonymity)

This timeline assumes good-faith coordination. Patches are publicly available before any advisory is published.

Security Advisory Credits

We acknowledge security researchers and community members who help us improve. If you'd like credit in our release notes, please let us know your preferred name or handle when reporting.

Known Limitations & Trust Boundaries

Periodic device-index maintenance

The API device-index sweep validates each owner's current native storage before reading device rows through temporary read-only handles. Compatible reads do not populate per-user store/activity caches. Older layouts and read/open/close failures retain the validated migration fallback. Validation or read failure is not an empty device list: keep that owner's index entries, and preserve in-flight collision reservations. These rows remain resolution hints; every request still validates current credentials, ownership/source and restore state. No global API memory bound or workforce capacity is established by this change.

Daemon resource cache lifetimes

The daemon retains at most64 state-store and64 native-mailbox-client cache entries, including extra mailboxes. Eviction drops a reference and never closes a resource under a live caller. Existing runtime cleanup releases unreachable handles; poll and maintenance operations explicitly retain their live holders. This bounds cache retention, not instantaneous descriptors, process memory or workforce capacity. External IMAP sessions and rate-limit history are separate. Native acquisition and each mailbox operation still recheck current admission, source/owner/restore state. Mailbox WAL/FULL durability is unchanged.

Native authority storage

Native authority (the directory lifecycle and the mailbox/address ledger) is one SQLite database, $CONFIG/native-authority.db, beside two small stubs that make older binaries refuse (design). Every admission, ownership check, outbound claim and receiving bind runs its own read transaction on current committed rows; nothing decoded outlives the call and no permission decision, view or byte cache is retained (the bounded decoded views of earlier releases are gone). Each process holds the database open (owner decision Q1): SQLite's change-counter protocol makes each transaction see the latest commit, and after each read the store requires the path to still name the file it opened (os.SameFile), refusing and reopening otherwise. Each connection prepares a query once and keeps the statement until the connection closes; only the parse is reused, every run reads in its own transaction.

Every connection is checked when it opens: trusted_schema=OFF, defensive mode, recursive_triggers=ON, foreign keys, WAL, synchronous=FULL, user_version 3 and an exact sqlite_schema match, so the keys, the never-delete and append-only triggers and the immutable-identity triggers that carry the global invariants cannot be dropped behind the store. Writers never use REPLACE. The file is a private regular file (mode &0077 == 0, not a symlink), created by rename. Each read validates the rows it uses; the whole store (integrity, foreign keys, every row) is validated at migration, at migrate-native startup, in every backup and in the minute reconcile pass, whose failure refuses only that pass's writes (owner decision Q5): damage to one account's rows no longer refuses every other account. A process able to write the config root can still rewrite the database, as it could the JSON files.

migrate-native keeps sso-lifecycle.json.v2-migrated and native-provisioning.json.v2-migrated, which hold directory PII and stale authority; delete them after the first successful v3 backup (docs/RESTORE.md).

An open mail client's per-operation admission re-runs every prepared-storage check on two read-only handles the client keeps for its own state.db and mailbox.db, instead of reopening both. Each check also requires both paths to still name the files those handles opened, so deleted or replaced storage is refused on the next operation. In the API and the daemon, an admission without an open client runs the same checks on handles from a per-process pool of at most 1,024 mailboxes (about 10 descriptors each), closed after 5 to 10 minutes without an admission and at once when a check refuses; every other process keeps the full reopening path. Each cached client holds about 8 file descriptors instead of 3; the API and the daemon each retain at most 64 cached mail clients.

Browser OpenPGP RSA policy

frontend/src/lib/pgpClient.ts supplies a literal 2048-bit RSA minimum to OpenPGP.js for encryption, signing and signature verification, including the primary key and selected subkeys. This overrides the locked library's 2047-bit default. Recipient encryption, Sent copies, drafts and sealed autosaves refuse undersized keys; the browser does not omit a weak recipient or downgrade to plaintext. Historical decryption and key import/retention remain available; old signatures made with undersized RSA keys stay unverified. No private key, archive or recovery copy is replaced or discarded by this policy. Retaining weak keys for recovery does not make old ciphertext secure against key compromise. A failed autosave seal/write leaves the previous snapshot intact and displays a warning; newer typing remains only in the open compose window. TLS and native-client policies are separate boundaries. See the user-facing key policy.

Key strength

KyPost's own code refuses RSA keys below 2048 bits in OIDC provider JWKS, server-side OpenPGP encryption and signing, and TLS certificates it serves or hands to the receiver; operator secrets have minimum lengths. Setting GODEBUG=fips140=on (docker-compose.strong-crypto.yml) restricts every TLS client in KyPost to RSA-2048+, P-256+ and Ed25519 certificate chains. Upstream components (Maddy, Rspamd, Ollama, restic, remote mail servers, identity providers, push services, proxies and browsers) keep their own policies. The key table and enable steps are in key strength.

  • Optional Rspamd: native SMTP filtering gives the operator-local scanner raw MIME and SMTP envelope/peer metadata. A compromised scanner can allow/refuse incoming mail and, through its shared network namespace, reach KyPost's other loopback services; it receives no KyPost filesystem mounts or keys. The pinned nonroot/capability-free, read-only sidecar binds only loopback11333, disables controller/proxy and remote payload/map/AI services, and uses bounded temporary state. SPF/DKIM/DMARC checks make ordinary DNS lookups through the host resolver. False positives at the reject threshold permanently refuse new SMTP mail; outages, unknown/skipped acceptance verdicts and transport errors temporarily refuse it. Rejection never deletes an accepted obligation. Trusted source IP comes from Maddy, while HELO remains sender-asserted. Sender-written authentication/spam headers grant no authority. Raw response text and correspondence are excluded from scanner/application logs. This initial reject-only profile does not implement Junk placement, Bayesian learning, antivirus, PGP-body inspection. The separate hosted pilot is described below. See operator policy and rollback.

Cloudflare receiving pilot

The optional one-message Email Worker stores exact raw mail and its frozen envelope in private operator-owned R2. Cloudflare administrators can read ordinary mail; provider copies remain after local encryption, scanner refusal and successful pickup. A dedicated read-only secret protects bounded HTTPS pickup, while current KyPost domain/identity/source/revision and restore gates authorize delivery. The Worker supplies no trusted original peer, so fixed hosted scanner settings disable SPF/DMARC/ARC groups and retain content/DKIM checks. Sender-written authentication headers grant no authority. A full slot rejects further mail; an ambiguous write may retain bytes despite SMTP refusal. No automatic deletion or continuous receiving guarantee exists. See scope and rollback.

Native restore evidence

Protected administrator challenge/import routes record fresh app-specific KyIdentity evidence and revision barriers for unpublished native reservations. The separately confirmed repair route rechecks that evidence and existing native ownership, applies signed activity/roles to published native accounts, and revokes sessions, device/push, pairing and CardDAV credentials before recording completion. Legacy recovery administrators, passwords, mail, labels and PGP material remain retained; existing SSO-link revocations stay revoked. Held native accounts cannot authenticate or exercise session/admin authority. Every request requires CSRF/account confirmation and current administrator/session witnesses; repair retains that session fence through account publication. The selected current pairing key is the only evidence signing authority. A compromised authorized administrator together with that key can alter issuer-scoped native activity/roles; either compromised authority can disrupt recovery. Durable repair intents/barriers precede account writes. Partial cleanup failure remains held and incomplete; preserve staging, remediate and request fresh complete evidence. The cooperative 30-second context does not bound blocking cleanup storage calls. Receipts expire and remain historical; neither successful repair nor receipt presence releases the hold or proves domain/transport readiness. See the recovery contract.

KyPost is honest about what it does and does not protect. Read these carefully before deploying or relying on specific features.

PGP Key Custody

Client-protected custody is the only supported key protection mode. See Where your PGP private key lives for a complete explanation.

Client-Protected (End-to-End): Your browser generates or wraps the key under a password-derived key. The server cannot open it. Costs: you must unlock it each browser session, and admin operations cannot access your encrypted mail. Security can create an encrypted offline recovery backup in the browser; restoring it requires both the downloaded file and its separately displayed random secret. Neither the plaintext key nor the secret is sent to or stored by the server.

Server-Protected (retired): KyPost no longer generates or imports a private key the server can open, and it refuses to decrypt or sign with a legacy server-held key. An existing legacy key stays sealed under the server master key until its owner migrates it to client protection; until then the server, and anyone with access to its disk (root, backup operators, disk seizure), can still open that key. This is not end-to-end encryption, so migrate those accounts.

Automatic Label Classification

Labels (keywords) assigned by the classifier are a sorting hint, not a security boundary. The classifier reads sender-controlled email, so a sender can write instructions into their message and influence which label it receives. Testing shows roughly 50-87% resistance to prompt injection depending on configuration, but every model tested let some through.

What an attacker can achieve: steer the label on their own message into a different folder (e.g., Primary instead of Promotions). The keyword allowlist is enforced in Go after the model answers, so output outside that list is discarded. A message cannot be deleted, moved, marked read, or cause any other message to be affected.

Pre-sort does not raise trust. Mail from an address in your contacts is labelled Primary without asking the model, and the From header is not authenticated for this, so a sender spoofing a contact also lands in Primary — which a convincing message already achieves with the model. Contacts created automatically from Autocrypt headers or key discovery do not count. List and automation headers are sender-controlled too, which is why they only ever take Primary away: forging one demotes only the forger's own message. Header filter rules read every copy of a header, so a rule matching a provider's X-Spam-Flag: YES still fires when a sender has added their own X-Spam-Flag: NO above it; a rule that grants anything on a header a sender can add inherits that sender's control.

The embedding sorter changes the mechanism, not the boundary. It follows no instructions (it resisted every injection probe in the evaluation corpus), but a sender still chooses the text it embeds and can make a message resemble the label they want. It learns only from your own relabels, recorded per account; it never trains on the LLM's answers, which would let one sender's injected answer steer how everyone's similar mail is sorted. Its memory in state.db is message vectors, labels and a hash of sender and subject — no message text — and it never leaves the server. Vectors are derived from mail, so treat state.db (and backups, which include it) as private to the account, exactly like the decision log beside it.

Do not build security controls on labels. Never create a filter rule that grants trust based on a label, and never auto-archive anything by label alone. This is not a fixable limitation—it is a known property of using local LLMs to classify sender-controlled text. All decisions are recorded on the Decisions page so you can audit what actually happened.

Encrypted mail is not classified, and is never labelled as encrypted. A PGP-encrypted message has no readable body, so it skips the classifier and is tagged with your account's default label instead. It is deliberately not given an Encrypted keyword. IMAP keywords are stored on the mail server in the clear, so such a keyword would hand whoever runs that server a precise index of which of your messages are worth attacking—the exact adversary client-protected custody exists to defend against—while looking to you like a security feature. It would break the rule above in both directions at once: not trustworthy enough to rely on, and harmful merely by existing. The padlock you see in the reader is derived from the message itself each time it is displayed and is never written anywhere.

Encrypted mail also stays out of mobile push payloads. Native push travels to the relay Worker and on to FCM/APNs in cleartext at every hop. For an encrypted message the sender and subject are withheld from that payload regardless of your Content Preview setting, because a third-party PGP/MIME message that does not use protected headers carries its real subject in the clear. Web push is unaffected—those payloads are encrypted to your browser's own subscription keys (RFC 8291), so Content Preview remains your choice there.

See Classification flow for details.

Email HTML Rendering

KyPost renders email HTML in a sandboxed iframe with DOMPurify sanitization. The sandbox blocks most attacks (no script execution in the frame itself), but:

  • Remote content loads on opt-in. Images, stylesheets, and other remote resources are not loaded by default. Users can opt in per message.
  • Links open in new windows (via <base target="_blank">). The link destination is not constrained by KyPost; it goes wherever the sender directed.
  • Sender HTML survival. DOMPurify removes most dangerous elements, but sanitization is a defense layer, not a boundary. Treat all email HTML as potentially hostile, and do not trust email to be what it claims.

Session Security

See Session Behavior for full details. Key points:

  • Sessions expire after 24 hours without activity (sliding window).
  • Sessions have a hard cap: 7 days from issue, regardless of activity. Stolen cookies cannot be kept alive indefinitely.
  • Sessions are swept every hour; expiry does not wait for the cookie to be presented again.

CardDAV & External Services

  • CardDAV clients (phones, desktop apps) authenticate with a per-user app-specific password separate from your login password.
  • CardDAV clients that sync from external servers should use HTTPS-only connections.
  • KyPost does not validate external CardDAV server certificates beyond the OS default. Use a trusted network or a known server.

AI Agents (MCP)

  • An AI agent token opens /mcp and nothing else: it is a bearer token separate from the login password, the CardDAV password and device credentials, and each is refused on the others' channels. Requests with an Origin header are refused, so a web page cannot use one. Tokens are shown once, stored as a SHA-256 hash, revoked after 90 days unused, by a sealed-backup restore (a raw volume copy restores them as they were), and with every other credential when an account is deactivated, reset or changes its password. Administrator identities cannot hold one.
  • Mail is sender-controlled input to the agent. A message can contain text written to steer an agent (prompt injection). KyPost cannot stop an agent from following it; it limits what following it can do. Results mark sender text as sender_controlled, the server's instructions and the KyPost skill tell the agent to treat it as data, no tool takes an action from message content, and no tool sends, deletes or moves mail to Trash or Junk. Thread membership comes from headers the sender wrote, so a stranger can make a message appear in a thread; it is still marked sender-controlled, and which messages are kept never depends on a sender-claimed date. A Read and organize token can still be steered into labelling, moving, archiving or drafting; a draft is sent only by the user. Grant it only if you trust everyone who can email you or message the agent.
  • End-to-end encrypted mail never reaches an agent. A message whose root or any part is PGP/MIME, multipart/encrypted, S/MIME or inline PGP armor is returned as sender, recipients and date only: no subject, body or attachment names. A message the check cannot parse counts as encrypted. Search never returns an encrypted message, so a match cannot reveal words the server searched inside one. Listings judge each message by the same full walk.
  • No web page can obtain or use a token (the Joplin Web Clipper flaw, GHSA-9728-v7ww-mxjv, in reverse): /mcp answers any request with an Origin header 403 and sends no CORS headers; no KyPost route grants CORS to another origin (the only Access-Control-Allow-Origin: * is the public Web Key Directory key file). Creating, re-scoping and revoking a token need the session cookie, its CSRF token, step-up for create and re-scope, and the server's own origin: a foreign or opaque Origin, or Sec-Fetch-Site: cross-site, is refused. There is no pairing or consent endpoint another app can start; tokens come only from the user's own Security page, and every confirmation there and in KySignOn names the agent and the access level it grants.
  • Sending is deliberately absent: an agent that can read and send mail can exfiltrate the mailbox on instruction from any message it reads.

Mobile Pairing

  • Pairing tokens are valid for 90 seconds and signed with a per-instance secret.
  • All pairing payloads (QR codes, pickup links, key exchange URLs) carry bearer credentials in the query string.
  • Set SERVER_BASE_URL to an HTTPS URL so credentials travel over TLS. It is required: pairing endpoints are built from it and never from the request's Host header, because that header names whatever hostname the caller reached the server through — a pairing package built from it aims the token at that hostname. Unset, pairing refuses and says so.
  • Pairing secrets must remain on the server only. Multi-replica deployments share one secret via PAIRING_SECRET.

Deployment Security

Your deployment choices determine the actual security of KyPost. This section covers the configuration decisions that matter most.

TLS & Network Binding

This is the most important decision you make. KyPost serves plain HTTP by default. Session cookies are marked Secure only when the request provably arrived over TLS.

Before exposing KyPost to a network, get TLS in front of it. On bare http://, cookies are sent in the clear on every request.

Three ways to get TLS:

1. Terminate TLS in KyPost (recommended if you control the host)

  • Set TLS_CERT_FILE and TLS_KEY_FILE to mounted certificate paths.
  • KyPost will reload certificates without a restart (important: restarting logs everyone out).
  • Setting only one path is a startup error; it will not fall back to cleartext.
  • This is the only option where "did this arrive over TLS?" is answered by the connection itself, not by a header. TRUSTED_PROXY_CIDRS does not apply.
  • Certificates are never baked into the image.
  • See .env.example and the commented volume in docker-compose.yml.

2. Cloudflare Tunnel

  • cloudflared gives the browser a real HTTPS origin (needed for proof-of-work CAPTCHA).
  • No TLS configuration of your own.
  • Set TRUSTED_PROXY_CIDRS to cloudflared's address and TRUSTED_PROXY_HEADER=cf-connecting-ip.

3. Reverse proxy you operate (nginx, Caddy, etc.)

  • Set TRUSTED_PROXY_CIDRS to the proxy's address; TRUSTED_PROXY_HEADER stays x-forwarded-for.
  • Proxy must use HTTPS when reaching KyPost if the hop carries session cookies across a real network.

KYPOST_BIND: Which Interface to Publish

KYPOST_BIND controls which interface publishes port 5866. It has no default—compose refuses to start without it.

  • 127.0.0.1: loopback only. Use when your reverse proxy runs on this same host.
  • Your LAN IP (e.g., 192.168.1.10): publish to the LAN. Use when a proxy on another machine reaches this host.
  • 0.0.0.0: publish everywhere. Use only when you deliberately want KyPost reachable on all interfaces. This is usually wrong unless you also set ALLOW_INSECURE_HTTP=true and understand the consequences.

Check where your proxy actually reaches this container from before choosing. Loopback publishing severs a proxy that arrives by the host's LAN address, which is the typical shape for cloudflared or an nginx on another machine.

Better practice: Run the proxy as a container on kypost-net (the network the compose file defines) and point it at http://KyPost-Server:5866. That network has DNS, nothing needs publishing, and the path ignores source NAT entirely—the server sees the real client IP. See Reverse_Proxy_Networking.md for setup and Docker error recovery.

TRUSTED_PROXY_CIDRS: Client IP Trust

When a reverse proxy sits in front of KyPost, the server sees the proxy's address as the client IP. This address is used as the key for:

  • Login rate limiting (3 strikes, 15-minute lockout)
  • Per-IP account lockout (looser, across all accounts; a successful sign-in does not reset it)
  • Instance-wide login rate limit
  • MFA push approval notifications (the push names the address)

If TRUSTED_PROXY_CIDRS is empty, forwarded headers are discarded entirely. Every caller is keyed as the proxy, so all users share one lockout bucket and push notifications show the gateway address instead of the user signing in.

If TRUSTED_PROXY_CIDRS is set, KyPost trusts forwarded headers from that CIDR. This marks cookies Secure (X-Forwarded-Proto) and keys lockouts off the real caller. The caller's address comes from exactly one header, chosen by TRUSTED_PROXY_HEADER; the other is never read, because nginx and Caddy pass unknown headers through from the client:

  • x-forwarded-for (default): nginx or Caddy. In nginx, proxy_set_header X-Forwarded-For $remote_addr; ($proxy_add_x_forwarded_for also works; the right-most element that is not a trusted proxy is used).
  • cf-connecting-ip: cloudflared, which appends its own hop to X-Forwarded-For. Also for cloudflared → nginx → KyPost, with nginx passing it on (proxy_set_header CF-Connecting-IP $http_cf_connecting_ip;) and reachable only from cloudflared.
  • Cloudflare proxied DNS (CDN) in front of nginx: keep x-forwarded-for and have nginx restore the visitor from CF-Connecting-IP only for Cloudflare's ranges (set_real_ip_from, real_ip_header CF-Connecting-IP;); see Reverse_Proxy_Networking.md.

A malformed TRUSTED_PROXY_CIDRS entry or any other TRUSTED_PROXY_HEADER value refuses startup.

Name the proxy's address specifically, not a wide range. Any peer inside the range you name can forge their own client IP and bypass every rate limit and lockout. Never 0.0.0.0/0. Example:

  • Proxy pinned on kypost-net: TRUSTED_PROXY_CIDRS=10.89.0.10/32 (replace with your proxy's actual Docker network IP)
  • Proxy on same host reaching 127.0.0.1:5866: TRUSTED_PROXY_CIDRS=10.89.0.1/32, the kypost-net gateway (first address of KYPOST_SUBNET). Docker hands the connection over from there, not from 127.0.0.1, and so does every other process on the host, so use it only with KYPOST_BIND=127.0.0.1.

This replaces the old TRUST_PROXY_HEADERS=true, which trusted forwarded headers on every connection from any peer and was only ever safe when nothing but the proxy could reach the port.

Office networks (rate-limit allowlist)

Staff in one office usually share one public NAT address, so they share every per-address limit and can lock each other out on a busy morning. An administrator can list the office's networks under Server → Office networks, and the operator can set RATE_LIMIT_EXEMPT_CIDRS; the two lists are combined. Empty by default: with nothing listed every limit behaves as before.

A request from a listed network skips the per-address limits only, and only by drawing on a shared office budget instead: one budget per limit, shared by every listed network. Once it is spent, office requests meet the ordinary per-address limit again until it refills, so one machine inside an office cannot make unlimited requests.

Per-address limit skipped Office budget in its place
Proof-of-work challenge budget (30 a minute per address) 300 a minute
GET /api/auth/login-params and the SSO sign-in routes (one shared bucket: 30, then 1 a second per address) 300 a minute, shared the same way
Failed-sign-in address lock (50 failures in 15 minutes) 15 failures at once, then 1 a second: the instance-wide sign-in budget's own size. Correct sign-ins hand their place back

The sign-in budget is sized so that an office failing at full rate for a whole 15-minute lockout window writes under a thousand per-account lockout entries, far below the table's capacity, so a flood from a listed network cannot push other accounts' partial lockouts out of it. The identity provider's back-channel logout is not a sign-in and keeps its per-address limit.

Everything else still applies to it: the per-account lockout (3 failures per account per address), the instance-wide sign-in budget, the CAPTCHA or proof of work (and its difficulty escalation), MFA, SSO state, nonce and PKCE checks, and the CardDAV, agent-token and push-poll limits. A compromised machine on a listed network can still guess only three passwords per account per 15 minutes, and only as fast as the whole server's sign-in budget allows, and it can spread those guesses over many accounts only while the office budget lasts; then the address lock applies to it again. A host that spends the office budget slows sign-in for the rest of the office back to the per-address limits that apply without the list.

The match uses the client address resolved through TRUSTED_PROXY_CIDRS and nothing else, so a forged X-Forwarded-For from an untrusted peer, or an address prepended to the chain behind a trusted proxy, claims nothing. Ranges broader than /16 (IPv4) or /48 (IPv6), loopback and malformed entries are refused when saved and at startup. A change needs the admin's step-up and is logged (set_exempt_networks, with actor and old and new lists). The screen shows how many requests skipped a limit since the last change or restart.

List only networks you control. Everyone behind a listed address loses the per-address limits, so never list guest Wi-Fi, a shared or public network (a café, a coworking space, a carrier-grade NAT range), a VPN provider's exit, or the reverse proxy's own address: with the proxy listed, a misconfigured TRUSTED_PROXY_CIDRS would exempt every visitor.

Verification: Confirm Your Setup

Verify rather than assume. Sign in and fetch GET /api/status. Check two fields:

  • clientIp: must be your own public address (or 127.0.0.1 if TLS-terminating in KyPost)
  • proxyHeadersTrusted: must be true (if using a reverse proxy) or false (if TLS-terminating in KyPost)

If clientIp is a loopback or bridge address (e.g., 172.17.0.1), every user shares one lockout bucket and the session cookie is not being marked Secure.

Secret Handling

  • Data roots: The container sets config, private-key and state roots to 0700 before bootstrap and service startup, including mounted volumes. Existing descendant modes are retained. Host access requires the volume owner or operator privileges; root and Docker administrators remain trusted.
  • Bootstrap password: On first start, KyPost writes the generated admin password to first-run-password.txt (mode 600) in the config volume. Read it and delete it immediately. Logs are unrotated by default and readable by anything with Docker socket access—the password is never logged. This holds for both bootstrap paths: the container's --mode bootstrap-admin step and a server started directly against an empty config directory. If the file cannot be written, startup fails rather than falling back to printing the password.
  • IMAP credentials: Stored encrypted at /kypost/private/imap-config.key (master key) and per-user encrypted payloads. The key does not rotate; compromise of the key compromises all encrypted credentials.
  • TOTP secrets: Master key at /kypost/private/totp-secret.key. Same rotation caveat.
  • Pairing secret: /kypost/private/pairing.key (generated on first start). Must be identical across replicas if you run multiple.
  • Legacy PGP server keys: Master key at /kypost/private/pgp-private-key.key. It is kept only so legacy server-held keys can be exported for migration.

All of these live in /kypost/private. Back up this volume separately and store it securely. Compromise of this directory compromises all user data.

First Run & Bootstrap

  • Bootstrap credentials are written to a file on first run, not logged. Running the binary directly (systemd, CI, a bare host) takes the same path as the container: the password goes to first-run-password.txt, and only its path is printed.
  • You can pass BOOTSTRAP_ADMIN_PASS on the first run to avoid the file write (you already have the password).
  • You can also pass BOOTSTRAP_ADMIN_USER to name the initial admin (default: admin).
  • The bootstrap account starts on the password-change screen and cannot access anything else until you change it.
  • Change the password immediately after first login.

Authentication & Authorization

Login Flow

  • Username + password, with per-account salt and work factor.
  • Password never reaches the server. The browser derives an authentication half (what gets sent) and a key-wrapping half (for PGP key encryption, stays in the browser). Every credential check accepts only the derived half; a request carrying the password fails as a wrong credential.
  • An account still holding a pre-derived-auth password hash cannot sign in. To an unauthenticated caller it is indistinguishable from an unknown user or wrong password; the server logs a warning at startup and on each refused attempt, and Admin → Users flags it "needs password reset". An admin password reset restores access.
  • Exceptions: admin create/reset and BOOTSTRAP_ADMIN_PASS hand the server a temporary password. It derives and stores it in derived form immediately, and the forced first-login change replaces it with a credential the server never sees.
  • CAPTCHA challenge on login (optional, configurable: pow, turnstile, friendly, or none).
  • Proof-of-work CAPTCHA (pow) uses crypto.subtle and requires HTTPS (except localhost). Difficulty adapts per address; escalation is counted per IP and decays after 15 minutes or on successful login.
  • 3-strikes account lockout (15 minutes).
  • Per-IP lockout (looser, across all accounts; a successful sign-in does not reset it).
  • Instance-wide login rate limit.

Multi-Factor Authentication

  • TOTP: Time-based one-time passwords from an authenticator app.
  • Recovery codes: One-time codes for account recovery if you lose your authenticator.
  • Push approval: A pairing device receives a push notification and approves or denies the sign-in. Set up on Security's Devices tab.

Recovery codes are the only way to regain access if you lose your authenticator and have no paired push device. Export and store them securely.

Roles & Authorization

  • Admin: Create users, reset passwords, deactivate accounts, view system logs, edit global settings, start health repair.
  • User: Connect their own IMAP/SMTP, read mail, manage their own rules and filters, set notification preferences, tune their own prompt.

Authorization is checked on every request. Deactivation or role changes take effect on the user's next request, not at the next login.

Session Revocation

Browser and native ID-token verification require a positive iat no more than 30 seconds ahead of the server clock before directory revocation checks or account grants. Expiration remains mandatory; native device sign-in additionally limits token age to five minutes. Issuer/server clocks must stay synchronized. An issuance timestamp is not proof of fresh primary authentication and does not qualify native restore activation.

  • Logout invalidates the server-side session and clears the cookie.
  • An SSO session also ends when the identity provider says so: POST /api/auth/oidc/backchannel-logout accepts a signed logout+jwt for this client, records its jti on disk so a replay after a restart revokes nothing, and ends the session with that sid (or all of the subject's sessions issued before the token, when it carries no sid). A logout that lands while the browser is still completing the same login fences that login for five minutes. Paired devices and CardDAV app passwords are not derived from the SSO session and are revoked by directory deactivation, not by logout.
  • Directory offboarding removes access, never data. A KySignOn user.updated{active:false} or user.deleted is a signed, versioned event (POST /api/sync/webhook); it deactivates the account and revokes every session, device, CardDAV password and pairing token, and the mailbox, keys and account record stay, so a rehire restores the same account (one with a local password re-authorizes its SSO link from a local sign-in, as after any credential revocation). The last active admin can be neither removed nor demoted by the directory. A stale or replayed event is refused by a revision fence that survives restarts, and a sign-in for a subject the directory disabled, or with a token issued before its access last changed, is refused.
  • Deactivation or demotion takes effect on the user's next authenticated request.
  • An SSO session is admin only when both the account and the ID token say so: KySignOn's kypost.admin app role (or an admin group from Authentik/Keycloak) is recorded on the session as a ceiling, and a session without it acts as a regular user even if the account is an administrator. KySignOn's global admin role is never mapped to KyPost admin.
  • A session signed in through KySignOn itself (Authentik and Keycloak sessions keep the password gate) has no password to re-enter, so the actions that ask for one (the Security page, backup) send it back to KySignOn: a challenge bound to the exact request, a fresh sign-in in a popup (prompt=login; recovery-code sign-ins do not count), and a one-time grant spent only by that session for that request. PGP identity operations still require the password, which is also the vault credential.
  • KyPost will not let you deactivate or demote the last active admin.

Data Protection

Encryption at Rest

User data is stored in /kypost/config/users/<userID>/ and /kypost/state/users/<userID>/. What is encrypted:

  • IMAP credentials: AES encryption with a master key (imap-config.key).
  • TOTP secrets: AES encryption with a master key (totp-secret.key).
  • Legacy PGP keys (retired server-protected mode): Encryption with a master key (pgp-private-key.key), until the account migrates.
  • PGP keys (client-protected mode): Wrapped in the browser under a password-derived key; the server stores only the wrapped blob.
  • Client recovery backups: The downloaded backup contains a second browser-created AES-GCM envelope. Its recovery secret is shown once and is not stored by KyPost.

Unencrypted:

  • User account metadata: Username, role, hashed auth secret, account status.
  • Mailbox state: IMAP checkpoint, processed message IDs, decision history (which labels were assigned to which messages).
  • Configuration: Tuning prompts, notification preferences, rules, contacts.

If the /kypost/private volume is compromised, all encrypted data is compromised. This includes all IMAP credentials, TOTP secrets, and unmigrated legacy server-held PGP keys.

Encryption in Transit

  • Sessions: Cookies marked Secure only on HTTPS (when TRUSTED_PROXY_CIDRS is set or TLS terminates in KyPost).

  • API calls: All backend endpoints expect HTTPS (enforced by cookie marking and browser same-origin policy).

  • CardDAV: Sync clients should use HTTPS-only servers.

  • Mobile pairing: QR codes and pickup links carry bearer tokens in the query string. Use HTTPS for SERVER_BASE_URL.

  • External services: Push relay APIs use HTTPS only (PUSH_RELAY_URL and APNS_RELAY_URL must be HTTPS).

  • FCM service-account signing: worker/src/fcm.ts refuses RSA keys below a literal 2048-bit modulus before signing new OAuth assertions or contacting the token endpoint. It measures the public JWK modulus because workerd byte-rounds its key metadata, then uses a non-extractable signing key. Valid cached access tokens keep their existing lifetime. The refusal includes no credential material; replace an undersized service-account key before token refresh. This does not establish Cloudflare's hosted certificate-key policy.

  • Legacy outbound SMTP: Port 465 uses verified implicit TLS; other ports require STARTTLS, not opportunistic TLS. If the submission server does not advertise it, the send is refused — an on-path attacker can strip the capability from the EHLO response, and stripping AUTH with it means net/smtp's own refusal to authenticate over a cleartext link never fires either, so the message and password would reach the attacker while the user is shown a successful send. ALLOW_INSECURE_SMTP=true opts a deployment out for a plaintext relay on a trusted network. There is no per-request or per-account override: a downgrade must be a deployment decision, never something a caller or a remote server can trigger.

  • Native domain relay preparation: admin settings require current account confirmation, CSRF/request-bound step-up and fresh issuer-bound DNS proof. Both relay credentials are encrypted on disk and redacted from responses. The qualified internal transport always requires verified implicit TLS and AUTH, independent of ALLOW_INSECURE_SMTP; errors retain classification without rendering provider response text. Native primary compose/client-PGP sending uses fresh sender admission and the durable outbox; pickup/alias/system sending remains gated. Configuration is not provider readiness or delivery evidence; see DOMAIN_RELAY.md. The admin-confirmed saved-relay check contacts only the stored endpoint with its existing credential and requires matching generation plus fresh DNS/issuer and restore gates before and after the connection. The provider sees the login attempt; no mail is submitted. A single 15-second network budget, request cancellation and an instance-wide 30-second cooldown bound the operation. Configuration fences are not held across network I/O. Safe error text never echoes provider responses. TLS/AUTH success is transient connection evidence, not From authority or delivery readiness. Server → Mail domain is a client of those same gates. Account and relay credentials are distinct fields, retained only in component memory and cleared after each action. Unmount/account change prevents further submission/replay and discards late results; an already-issued mutation may complete. The server remains the authorization boundary. Challenge replacement warns that it clears verification; relay replacement warns that generation rotation invalidates unclaimed queued deliveries. Unreadable/mismatched status disables changes until reload, with no automatic retry of an uncertain write. This screen cannot enable public reception, release a restore hold or prove inbox placement.

  • Controlled setup wizard: the interactive host tool runs with the operator’s existing Docker authority. Confirmed native base rebuild can pause reception; validated public inputs replace named dotenv keys in an owned regular mode-0600 file. It never sources dotenv, captures provider/account secrets, changes DNS or deletes mail. New-spool init remains explicit and runs as kypost; current receiving authority/storage/TLS fences still decide startup. Human UI/external checks are instructions, not machine readiness evidence. Preserve settings/state on failure; see guided setup.

  • Controlled receiver configuration: receiving config requires explicit native flags, existing private storage, current DNS/issuer proof and no restore hold before emitting a fixed mandatory-STARTTLS profile. Certificate pair/name/date/purpose checks do not establish public CA trust or renewal. STARTTLS-only reception refuses plaintext senders. Configuration is historical evidence; live RCPT/DATA still enforce fresh authority. The optional supervised launcher is disabled by default and requires explicit flags, a read-only qualified engine mount and fresh preflight before every start. It hashes and executes the same open engine file; trusted host writes remain operator authority. The operator-supplied gateway shares the KyPost OS user and mail-storage authority, so compromise can reach the instance mail. Maddy records envelope/IP/command metadata and discards helper stderr; protect/rotate its logs. Fixed message/rate/concurrency limits and a separate process descriptor cap do not qualify public abuse protection, hard storage quotas or recovery. See controlled setup.

  • Native receiving capacity: new admission checks database/WAL/shared-memory file lengths and available filesystem blocks under the SQLite writer transaction, reserving estimated next-write growth and recovery space. Exact receipt retries and already accepted mail remain recoverable; import refresh cannot create routes or change owner, signed generation or activation. The managed near-budget checkpoint requires copy-growth headroom alongside the recovery reserve before reclamation; insufficient/unreadable headroom skips it and refuses growth without blocking exact receipt retries. Checkpoint failure or unreadable capacity refuses growth. These estimates cannot reserve space against other volume writers or bound pinned WAL from recovery; hard volume quotas, fenced abandoned-reservation cleanup and intended-volume failure drills remain public-deployment gates. Never delete active SQLite sidecars to reclaim space. See receiving runtime.

  • Native outbox custody: Native outbox intent is AES-GCM encrypted with domain-separated keys bound to mailbox owner/namespace/job ID. Signed-only wire MIME remains plaintext when submitted and uses server custody in the queue; host/backup access to database plus relay master key decrypts it. Claims do not expire into automatic retries, and restored evidence grants no send authorization. Native claims fence current DNS/settings/directory/user authority, local revocation epoch, PGP state and applicable device credentials/enrollment; locks are released before network I/O. Accepted historical Sent filing grants no network authority. Native primary sending is opt-in; see the outbox trust contract.

Sensitive Data in Logs

  • Passwords are never logged.
  • IMAP credentials are never logged in full; auth errors mention only the server and username.
  • CAPTCHA solutions are not logged.
  • Mail content (subject, body) is not logged except for decision history (which labels were assigned).

Check /kypost/logs regularly and configure your log aggregator appropriately if you have one.

Security Headers & Defense-in-Depth

KyPost applies multiple defense layers to protect against common web attacks.

Content Security Policy

CSP is configured per CAPTCHA provider to block script injection and limit the capabilities an attacker can use if HTML sanitization fails. Directives:

  • script-src: 'self' plus provider-specific origins only (e.g., challenges.cloudflare.com for Turnstile, cdn.jsdelivr.net for Friendly Captcha). Never 'unsafe-inline' or 'unsafe-eval'.
  • style-src: 'self' and 'unsafe-inline' (for the Quill editor's inline styles). No third-party origin.
  • font-src: 'self' and data:. The webfonts are served from this origin out of the app bundle, not from Google Fonts — an install with no CAPTCHA configured, or on the self-hosted pow provider, makes no cross-origin request at all.
  • img-src/media-src: Allows remote content (shown after user opt-in per message) and data URIs.
  • object-src: 'none' (blocks Flash, PDF plugins, etc.).
  • frame-ancestors: 'none' (prevents clickjacking).
  • base-uri: 'self' (prevents injection of a malicious <base> tag).
  • form-action: 'self' (all forms submit to this origin).

Other Security Headers

  • X-Content-Type-Options: nosniff (prevents MIME sniffing).
  • X-Frame-Options: DENY (prevents framing).
  • Referrer-Policy: strict-origin-when-cross-origin (limits referrer information).
  • Permissions-Policy: Blocks powerful features (camera, microphone, geolocation, payment, etc.) that KyPost never needs.
  • Cross-Origin-Opener-Policy: same-origin (severs window.opener for client-protected PGP keys).
  • Strict-Transport-Security: max-age=31536000; includeSubDomains (on HTTPS only).

Email HTML Sanitization

Email HTML is sanitized with DOMPurify before rendering in a sandboxed iframe. The sandbox blocks script execution in the frame itself, but DOMPurify is a defense layer, not a boundary. Treat all email HTML as potentially hostile.

CAPTCHA & Rate Limiting

  • CAPTCHA: Optional on login. Proof-of-work (pow) is self-hosted and requires HTTPS. Turnstile and Friendly Captcha use third-party verification.
  • Account lockout: 3 failed login attempts = 15-minute lockout per account.
  • Per-IP lockout: Looser, across all accounts. A successful sign-in refunds only its own attempt, so one valid account cannot reset failures spent guessing other accounts.
  • Instance-wide limit: Meters login attempts across the instance.
  • Proof-of-work escalation: Difficulty increases with each recent failed login from the same IP (up to a ceiling), decaying after 15 minutes or on success.

None of these replace the others; they work together.

Development & Security Testing

Security-sensitive code should meet these expectations:

Testing

  • Authentication changes: Tests for bypass scenarios (missing credentials, modified tokens, expired sessions).
  • Authorization changes: Tests for privilege escalation (users accessing admin endpoints, admins accessing user-scoped data).
  • Cryptographic operations: Tests for correct key derivation, encryption, and decryption.
  • Input validation: Tests for injection attacks (SQL if applicable, command injection, XSS via sanitized HTML).

See backend/internal/api/*_security_fixes_test.go for patterns.

Code Review

Security-sensitive PRs should include:

  • A description of the trust boundary or attack surface.
  • Explanation of why the approach is secure (or why a known limitation is acceptable).
  • Test coverage for both the happy path and attack scenarios.
  • Any assumptions about the deployment (e.g., "assumes TLS termination in KyPost").

Examples of Security-Sensitive Code

  • Authentication and session management (backend/internal/api/auth.go)
  • Authorization checks (role-based access)
  • Cryptographic operations (key derivation, encryption, decryption)
  • Input validation and sanitization (HTML email, filter rules, etc.)
  • Rate limiting and lockout logic
  • Trust boundary validation (client IP from forwarded headers, etc.)

Security Contacts

Additional Resources

Sealed server backups

KyRecovery receives sealed capsules; KyPost retains only the suite public key and never accepts custodian shares through HTTP. Only the offline restore CLI combines shares from stdin. Drills use a disposable key, never the suite private key. A source guard enforces this boundary.

Pairing tokens are sealed under the existing TOTP master key with a dedicated label. Key pins survive unpairing; remote token revocation requires a KyRecovery administrator. Backup changes require an admin session, CSRF and fresh account-credential verification, with durable intent audit before side effects. HTTPS and public destinations are required by default; private addresses need explicit operator opt-in.

Capsules contain deployment keys, internal native mailbox/receiving databases and encrypted pickup messages as well as account metadata. They exclude IMAP mail, mail cache, logs and external environment/TLS configuration. Payload bounds are 64 MiB per file and 256 MiB total. SQLite databases are snapshotted individually, not as a global transaction with account files; quiesce account/key changes for a coordinated recovery point. Native exports/drills validate historical ownership, not current external authority. Offline native restore extracts privately and publishes only after validation with a persistent hold; failed staging is retained. Native authentication/session/admin admission, pending MFA, SSO step-up, QR key exchange and allocation refuse the hold independently of native feature flags; either private native marker triggers it. Legacy local recovery administration remains available. Stopped-service restore is required; previously admitted operations are not canceled. Offline quarantine raises existing published native subjects’ ID-token revocation cutoffs to at least fence time plus 31 seconds, preserving higher cutoffs and legacy directory entries. Browser and native sign-in refuse older verified tokens. Allow the short cutoff interval to pass before obtaining a new token; this proves issuance freshness only, not fresh primary authentication or local-password/MFA recovery. No release path exists. Fresh access repair, receiver evidence and stale-message-ID fencing are required before native activation. Whole-tree power-loss durability remains unqualified. Follow RESTORE.md.

Application logs use shared JSON stderr with fixed field declarations and redaction; raw model output is excluded. Supervisord captures these as api.err.log and daemon.err.log.

There aren't any published security advisories