Installing Kantoor
Kantoor ships as a container image built from the Dockerfile in the
repository: an Elixir release on Debian, run by an unprivileged user. This
page covers what the image needs around it. The guides in this site are built
into the same image and served by the application at /docs.
What you need
- Postgres. Development and CI use Postgres 17. The migrations use
gen_random_uuid()as a column default, which needs PostgreSQL 13 or later. - A reverse proxy that terminates TLS for the web interface, CalDAV, CardDAV and the Karta inbound webhook.
- A public host name for the web interface, for example
mail.example.com. - A mail source, today Karta, if Kantoor is to receive, fetch and send mail. See Connecting to Karta.
- An OpenID Connect provider for web sign-in. See Sign-in.
- For IMAP and POP3: a TLS certificate for the mail host name, or a TCP proxy that terminates TLS. Both protocols are off by default.
A first installation, step by step
The order matters; each step names the page that has the details. The example
assumes the host name mail.example.com.
Postgres. Create an empty database and a user that owns it (PostgreSQL 13 or later).
Build the image (see "Build the image" below):
docker build -t kantoor .Write an environment file, for example
kantoor.env, with at least:DATABASE_URL=ecto://kantoor:PASSWORD@db.internal/kantoor SECRET_KEY_BASE=<output of: openssl rand -base64 64 | tr -d '\n'> PHX_HOST=mail.example.com OIDC_ISSUER=https://id.example.com/application/o/kantoor/ OIDC_CLIENT_ID=... OIDC_CLIENT_SECRET=... OIDC_REDIRECT_URI=https://mail.example.com/auth/callback OIDC_ADMIN_GROUP=kantoor-admins KANTOOR_VAULT_KEY=<output of: openssl rand -base64 32> KARTA_BASE_URL=https://karta.example.com KARTA_API_KEY=... KANTOOR_TRUSTED_PROXIES=<the network your reverse proxy connects from>A password with
/,@or:in it must be percent-encoded inDATABASE_URL.SECRET_KEY_BASEcan be any random string of 64 or more characters. SetKANTOOR_VAULT_KEYbefore you attach a domain, and keep a copy of it outside the server. The OIDC provider needs a client whose redirect URI is exactlyOIDC_REDIRECT_URIand which sends a group claim (Sign-in). Leave out theKARTA_*lines to look at the interface without a mail source.Migrate, then start:
docker run --rm --env-file kantoor.env kantoor /app/bin/migrate docker run -d --name kantoor --env-file kantoor.env -p 127.0.0.1:4000:4000 kantoor curl -fsS http://127.0.0.1:4000/health/healthanswers 200 with the version when the database is reachable. If the container exits at once,docker logs kantoornames the missing variable.Put a reverse proxy in front that terminates TLS for
mail.example.com, forwards to port 4000 and sendsX-Forwarded-Proto: https(Kantoor redirects plain HTTP to https, apart from requests forlocalhost).Sign in at
https://mail.example.com/with a user who has the admin group. The first sign-in creates the account; a user without the group is an ordinary user.Attach a domain at
/admin/domains(choose one of Karta's, or type its name; Connecting to Karta). Karta must be able to reachhttps://mail.example.com/karta/inbound.Create a mailbox at
/admin/mailboxesand give a user access to it at/admin/users(Mailboxes). Admins can open every mailbox anyway.Send a message to the mailbox from outside and watch it arrive at
/mail.Create an app password at Settings, App passwords to use IMAP, POP3, CalDAV or CardDAV (the last two need nothing else switched on; IMAP and POP3 need
KANTOOR_IMAP_ENABLED=true/KANTOOR_POP3_ENABLED=true, a certificate and published ports, see "IMAP and POP3" below).
Several replicas, Docker Compose and Kubernetes: Running several replicas.
Build the image
Two libraries are forks and are not on Hex: dav (CalDAV and CardDAV; an
Apache-2.0 fork of elixir-tempo/dav, branch kantoor) and libcluster_postgres
(how replicas find each other; an MIT fork of supabase/libcluster_postgres, branch
shiloh). Both are public on git.shilohbv.com, so you need nothing but this
repository and network access to build:
docker build -t kantoor .
mix deps.get inside the build clones both over https. Without Docker, run
mix deps.get in a checkout. To build against local checkouts of the forks, set
DAV_PATH and/or LIBCLUSTER_POSTGRES_PATH (and copy them into the build context
for Docker); DAV_GIT_URL, DAV_GIT_BRANCH, LIBCLUSTER_POSTGRES_GIT_URL and
LIBCLUSTER_POSTGRES_GIT_BRANCH point at other copies. Their location is set in
one place, the top of the dependency list in mix.exs.
The image:
- runs as uid 10001 (user
kantoor, no shell); - expects a writable
/tmp(RELEASE_TMP=/tmp) and can run with a read-only root; - exposes 4000 for HTTP;
- starts
/app/bin/server, which runs the release withPHX_SERVER=true.
The same build runs mix docs in the dev environment (ExDoc is a dev
dependency) and copies the generated site into the release's
priv/static/docs. The application serves it at /docs; /docs and
/docs/ redirect to /docs/overview.html.
Required environment variables
| Variable | Meaning |
|---|---|
DATABASE_URL | ecto://USER:PASS@HOST/DATABASE |
SECRET_KEY_BASE | secret for cookies and sessions; generate with mix phx.gen.secret |
PHX_HOST | public host name, for example mail.example.com |
PHX_SERVER=true is already set in the image.
Optional environment variables
HTTP and database
| Variable | Default | Meaning |
|---|---|---|
PORT | 4000 | HTTP listener port |
POOL_SIZE | 10 | database connection pool size (see Behind a transaction pooler for the size behind PgBouncer) |
KANTOOR_DATABASE_POOLER | off | true or 1 when DATABASE_URL points at PgBouncer in transaction pooling mode: prepared statements become unnamed and the maintenance lock moves to a connection of its own. Leave it off for a direct connection. See Behind a transaction pooler |
KANTOOR_DIRECT_DATABASE_URL | unset | optional direct ecto:// or postgres:// URL of the same database, for what cannot go through a pooler: bin/migrate (and KANTOOR_MIGRATE_ON_START) use it, and replica discovery uses it when KANTOOR_CLUSTER_DATABASE_URL is not set. Never needed for Kantoor to run correctly |
ECTO_IPV6 | unset | true uses an IPv6 database socket |
| KANTOOR_CLUSTER, KANTOOR_CLUSTER_DATABASE_URL, KANTOOR_CLUSTER_HEARTBEAT_MS, KANTOOR_NODE_HOST, KANTOOR_DIST_PORT, RELEASE_COOKIE | several replicas; see Running several replicas |
| KANTOOR_MIGRATE_ON_START | false | true runs the migrations in /app/bin/server before boot |
Web sign-in
| Variable | Meaning |
|---|---|
OIDC_ISSUER | issuer URL of the OpenID Connect provider |
OIDC_CLIENT_ID | client id registered at the provider |
OIDC_CLIENT_SECRET | client secret |
OIDC_REDIRECT_URI | registered callback URL, for example https://mail.example.com/auth/callback |
OIDC_ADMIN_GROUP | group claim value that makes a user an administrator |
OIDC_CACERTFILE | CA certificate file, when the provider uses a private CA |
Without the first four, /auth/* answers 503 and the rest of the application,
including /health, keeps working.
Client address
| Variable | Meaning |
|---|---|
KANTOOR_TRUSTED_PROXIES | comma-separated CIDRs of reverse proxies whose X-Forwarded-For is believed |
By default Kantoor uses only the TCP peer address and ignores
X-Forwarded-For, so nobody can spoof an address to evade a login block or
to frame another user. Behind a reverse proxy the peer is always the proxy,
so all users would share one throttling limit until the proxy network is
listed here. Kantoor then takes the last address in the header that is not
itself a trusted proxy. Use the narrowest network that contains the proxy,
and do not publish the application port directly.
Invalid entries are ignored with a warning at boot.
Time zone
| Variable | Meaning |
|---|---|
KANTOOR_TIME_ZONE | IANA zone for events created in the web interface, for example Europe/Amsterdam |
Without it, those events are written as floating wall-clock times.
Karta
| Variable | Meaning |
|---|---|
KARTA_BASE_URL | base URL of the Karta instance |
KARTA_API_KEY | API key restricted to the Kantoor interface |
KARTA_INBOUND_SECRETS | comma-separated whsec_ signing secrets of the inbound endpoints (optional with the vault key) |
KANTOOR_VAULT_KEY | base64 of 32 bytes (openssl rand -base64 32): encrypts the secrets Kantoor stores: the endpoint secret of each domain you attach, and the address of each subscribed calendar. Set it before attaching a domain or subscribing; if secrets are stored and the key is missing or wrong, Kantoor refuses to start |
KANTOOR_VAULT_KEY_ID | label of the key, default v1 |
KANTOOR_VAULT_RETIRED_KEYS | id:base64 pairs after a key rotation |
KARTA_INBOUND_HEADER | optional extra shared header, as Name: value |
KARTA_MAX_BODY_BYTES | largest inbound body accepted, default 40 MiB |
See Connecting to Karta.
IMAP, POP3 and SMTP submission
Each protocol is off until KANTOOR_IMAP_ENABLED=true,
KANTOOR_POP3_ENABLED=true or KANTOOR_SMTP_ENABLED=true is set.
| Variable | Default | Meaning |
|---|---|---|
KANTOOR_IMAP_ENABLED | off | true starts the IMAP listeners |
KANTOOR_IMAP_LISTEN | 0.0.0.0 | bind address (IPv4 or IPv6) |
KANTOOR_IMAP_PORT | 1143 | plain listener with STARTTLS (0 or off disables) |
KANTOOR_IMAPS_PORT | 1993 | implicit-TLS listener, started only with a certificate |
KANTOOR_IMAP_ALLOW_PLAINTEXT_AUTH | false | allow login without TLS; leave off |
KANTOOR_IMAP_MAX_MESSAGE_BYTES | 26214400 | largest APPEND literal |
KANTOOR_POP3_ENABLED | off | true starts the POP3 listeners |
KANTOOR_POP3_LISTEN | 0.0.0.0 | bind address |
KANTOOR_POP3_PORT | 1110 | plain listener with STLS |
KANTOOR_POP3S_PORT | 1995 | implicit-TLS listener |
KANTOOR_POP3_ALLOW_PLAINTEXT_AUTH | false | allow login without TLS; leave off |
KANTOOR_POP3_DELETE_MODE | mark | mark keeps downloaded mail; delete expunges what the client deleted |
KANTOOR_CHAT | off | true switches on the chat (see "Chat") |
KANTOOR_SMTP_ENABLED | off | true starts the SMTP submission listeners (see "Mail clients") |
KANTOOR_SMTP_LISTEN | 0.0.0.0 | bind address |
KANTOOR_SMTP_PORT | 1587 | plain listener with STARTTLS (587 outside) |
KANTOOR_SMTPS_PORT | 1465 | implicit-TLS listener (465 outside) |
KANTOOR_SMTP_ALLOW_PLAINTEXT_AUTH | false | allow AUTH without TLS; leave off |
KANTOOR_SMTP_HOSTNAME | PHX_HOST | name in the greeting |
KANTOOR_SMTP_MAX_MESSAGE_BYTES | 26214400 | largest message (also announced as SIZE) |
KANTOOR_SMTP_MAX_RECIPIENTS | 100 | recipients per message (Karta takes at most 150) |
KANTOOR_SMTP_MAX_DATA_LINE | 998 | longest line of a message |
KANTOOR_SMTP_RATE_WINDOW_S | 3600 | window for the two limits below |
KANTOOR_SMTP_MAX_MESSAGES_PER_USER | 200 | messages per user per window (450 beyond) |
KANTOOR_SMTP_MAX_MESSAGES_PER_IP | 400 | messages per client IP per window |
KANTOOR_SMTP_SAVE_SENT | false | also store a copy in the sender's Sent folder (clients normally save their own over IMAP; turn on only for clients that do not) |
KANTOOR_MAIL_TLS_CERTFILE | unset | PEM certificate chain for STARTTLS/STLS and implicit TLS |
KANTOOR_MAIL_TLS_KEYFILE | unset | PEM private key |
KANTOOR_MAIL_PROXY_TRUSTED | empty | CIDRs of TCP proxies whose PROXY protocol header is believed |
KANTOOR_MAIL_PROXY_TLS | false | a connection through a trusted proxy counts as already encrypted |
KANTOOR_MAIL_MAX_CONNECTIONS | 200 | simultaneous connections per protocol |
KANTOOR_MAIL_MAX_CONNECTIONS_PER_IP | 20 | connections per client IP (IPv6 per /64) |
The certificate and key are read at every handshake, so a renewed file is used without a restart. The container runs as uid 10001, so the default ports are unprivileged; map them to 143, 993, 110 and 995 outside the container. See Mail clients.
Scheduled maintenance
| Variable | Meaning |
|---|---|
KANTOOR_MAINTENANCE | off disables every maintenance job |
KANTOOR_MAINTENANCE_<JOB>_ENABLED | false disables one job |
KANTOOR_MAINTENANCE_<JOB>_INTERVAL_S | interval of one job, in seconds |
KANTOOR_TOMBSTONE_DAYS | retention of IMAP and DAV tombstones, default 90 |
KANTOOR_APP_PASSWORD_GRACE_DAYS | how long expired app passwords are kept, default 30 |
KANTOOR_CHAT_STORAGE | local (default) or s3: where chat files are kept |
KANTOOR_CHAT_FILES_PATH | local storage: the directory (default chat_files in the working directory: mount a persistent volume there, or files are lost at redeploy) |
KANTOOR_CHAT_S3_ENDPOINT, _BUCKET, _ACCESS_KEY_ID, _SECRET_ACCESS_KEY | required with KANTOOR_CHAT_STORAGE=s3; KANTOOR_CHAT_S3_REGION defaults to garage |
KANTOOR_CHAT_MAX_FILE_MB | largest chat file, default 25 |
KANTOOR_CHAT_DOMAIN_QUOTA_GB | chat file space per mail domain, default 5 |
KANTOOR_CHAT_CLAMAV / KANTOOR_CHAT_CLAMAV_REQUIRED | host:port of a clamd to scan uploads; scanning is off unless set; once set, files that cannot be scanned are refused unless KANTOOR_CHAT_CLAMAV_REQUIRED=false. clamd's StreamMaxLength must be above the file limit |
KANTOOR_CHAT_DELETED_DAYS | how long a deleted chat message (and its edit history) is kept for audit before the daily job CHAT_RETENTION removes it, default 30 |
KANTOOR_PENDING_FETCH_MAX_AGE_DAYS | when a notify-only message is marked degraded, default 7 |
KANTOOR_PENDING_FETCH_MIN_GAP_S | minimum gap between body fetches, default 1800 |
<JOB> is one of IMAP_TOMBSTONES, DAV_TOMBSTONES, PENDING_FETCH,
APP_PASSWORDS, KNOWN_LOGIN_IPS, RATE_LIMITER, ORPHAN_BODIES,
CHAT_RETENTION and QUOTA_RELEASE, for example
KANTOOR_MAINTENANCE_PENDING_FETCH_ENABLED=false. Values must be positive
integers; anything else stops the boot with a message.
Mail search index upgrade
After deploying the normalized mail search migration, start the resumable backfill in the running release:
bin/kantoor rpc 'Task.start(fn -> Kantoor.Search.Backfill.run() end)'
It commits 200 messages at a time, pauses 100 ms between batches, skips locked
rows and logs the total rows and elapsed milliseconds on completion. Run it
again after an interruption; already indexed messages are skipped. Multiple
workers are safe. To check completion, count rows in messages where
search_vector_v2 IS NULL. Search uses the same normalization on existing
rows until the backfill finishes, and inserts and source-field updates maintain
the new vector through a database trigger. Message contents, flags, UIDs,
modseqs and timestamps are preserved. The original IMAP search index remains.
Database and migrations
The release does not migrate at start unless asked to. Run the migrations before the first start and after every upgrade, with the same environment as the server:
docker run --rm --env-file kantoor.env kantoor /app/bin/migrate
/app/bin/migrate runs Kantoor.Release.migrate/0, which applies every
pending migration of Kantoor.Repo. Ecto takes a database lock while
migrating, so concurrent invocations during a rolling deploy are safe.
Alternatively, set KANTOOR_MIGRATE_ON_START=true; /app/bin/server then
runs the migrations before booting.
In development, start the bundled Postgres with
docker compose -f dev/compose.yml up -d --wait and run mix setup.
Behind a transaction pooler
Connect directly to Postgres where you can. When DATABASE_URL has to go through
PgBouncer in transaction pooling mode (a shared database cluster), set
KANTOOR_DATABASE_POOLER=true. Each transaction may then run on a different server
connection, so Kantoor:
- sends unnamed prepared statements (a named one is prepared on one server connection and then looked up on another: "prepared statement does not exist"). The cost is that Postgres parses and plans every statement again; at Kantoor's request rates that is not noticeable;
- takes the maintenance lock differently. The maintenance jobs (tombstones,
re-fetch, housekeeping, quota release) run on one node at a time, which they ensure
with a Postgres session advisory lock. A session lock cannot be held on a pooled
connection: lock and unlock would reach different server connections, the unlock
would fail and the lock would stay behind, so that no node would ever run that job
again until PgBouncer closed the connection. With the setting on, the lock is a
transaction-scoped one (
pg_try_advisory_xact_lock) taken in a transaction on a connection of its own that lives exactly as long as the job: it ends with the job, and also if the node dies. The cost is one more database connection, idle in a transaction, while a job runs (one job at a time per node). If PgBouncer hasidle_transaction_timeoutset shorter than the longest job, it ends that transaction and the lock with it; the jobs are idempotent, so the effect is that a second node may run the same job as well, not damage; - leaves the rest alone, because none of it needs a session: the other advisory lock
(
chat_files) ispg_advisory_xact_lockinside a transaction, the row locks areSELECT ... FOR UPDATEinside transactions, the counters and uploads are single statements, Ecto's migration lock is a table lock inside the migration's own transaction, and the code uses noSET, temporary tables orLISTEN. Kantoor has no job queue of its own, andPhoenix.PubSubruns over Erlang distribution, not over Postgres.
What needs a direct connection, and what happens without one. Nothing is
required: with the pooler alone Kantoor is correct and everything works, including
the migrations (bin/migrate runs through the pooler) and the maintenance jobs. Two
things can use a direct connection when the database offers one:
- Replica discovery (
KANTOOR_CLUSTER=true) usesLISTEN. Behind a pooler it needsKANTOOR_CLUSTER_DATABASE_URLorKANTOOR_DIRECT_DATABASE_URL; without either, discovery stays off and the log says so. The replicas then run unclustered, still correct through the database: only the speed-up of distribution (a message ingested on one replica waking IMAP IDLE sessions and open pages on the others at once) is missing, and those wait for their next database check, a matter of seconds (Running several replicas). - Migrations with
KANTOOR_DIRECT_DATABASE_URLrun on that connection with named statements. Only a migration that needs a session would require it (today none does).
Pool size. POOL_SIZE is the number of connections Kantoor opens to PgBouncer,
not to Postgres. A connection holds a server connection only while a transaction
runs, so POOL_SIZE may be larger than PgBouncer's pool, and the surplus waits in
PgBouncer's queue. The sum of POOL_SIZE over all replicas (and migrate
containers) must stay below PgBouncer's max_client_conn, and the server pool of the
database (default_pool_size, the role's limit) should be at least the number of
transactions that run at the same time, at most POOL_SIZE per replica plus the one
maintenance connection. A transaction that waits for a slow call keeps its server
connection the whole time, so a pool set too small shows as requests waiting for a
connection, never as a wrong answer. Start with the default of 10 per replica.
Testing it. scripts/pooler-test.sh starts a throwaway Postgres and PgBouncer
(container names pooler-test-kantoor-*, removed afterwards), runs the part of the
test suite that uses locks, maintenance and the cluster through it with
KANTOOR_DATABASE_POOLER=true, and the test test/kantoor/pooler_test.exs: named
statements and a session lock break there without the setting, the maintenance lock
excludes and releases with it, a migration runs from an empty database, and the
maintenance jobs run. scripts/pooler-test.sh --all runs the whole suite through it.
Needs docker.
Health check
GET /health returns 200 with the application status and version when the
database answers, and 503 when it does not. Use it as the container health
check.
Reverse proxy
- Terminate TLS at the proxy and forward to port 4000.
- Set
KANTOOR_TRUSTED_PROXIESto the proxy network so login throttling sees the real client address. - Pass the WebDAV methods and request bodies up to 6 MiB to
/dav(see Calendar, contacts and tasks). - If the proxy also fronts IMAP, POP3 and SMTP submission, use a TCP router with the PROXY
protocol and set
KANTOOR_MAIL_PROXY_TRUSTEDandKANTOOR_MAIL_PROXY_TLS.
Error reporting (optional)
Set SENTRY_DSN to the project's DSN from Bugsink (or a Sentry-compatible server)
in the release's runtime environment, then restart the release. Keep the DSN in
your secret store, never in source control. An unset or empty DSN disables sending.
The Sentry client reports production errors and process crashes, including Bandit
requests and LiveViews, without forwarding ordinary logs or performance traces.
Request bodies are omitted because they can contain mail, calendars and contacts.
The client scrubs authentication headers, cookies and sensitive parameters; the
additional url filter also removes feed URLs that may contain credentials.
Do not include private message contents or credentials in exception messages.
To verify a configured release without disturbing a request or sending mail:
/app/bin/kantoor rpc 'Sentry.capture_message("Kantoor error reporting verification", result: :sync)'
Check that the event appears in the correct project, then resolve the test issue.
Upgrading
Build a new image, run /app/bin/migrate with the new image, then start the
new release. Migrations are additive. Back up the database before an upgrade:
the index holds folders, flags and UIDs that the mail source cannot rebuild.