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.

  1. Postgres. Create an empty database and a user that owns it (PostgreSQL 13 or later).

  2. Build the image (see "Build the image" below): docker build -t kantoor .

  3. 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 in DATABASE_URL. SECRET_KEY_BASE can be any random string of 64 or more characters. Set KANTOOR_VAULT_KEY before you attach a domain, and keep a copy of it outside the server. The OIDC provider needs a client whose redirect URI is exactly OIDC_REDIRECT_URI and which sends a group claim (Sign-in). Leave out the KARTA_* lines to look at the interface without a mail source.

  4. 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
    

    /health answers 200 with the version when the database is reachable. If the container exits at once, docker logs kantoor names the missing variable.

  5. Put a reverse proxy in front that terminates TLS for mail.example.com, forwards to port 4000 and sends X-Forwarded-Proto: https (Kantoor redirects plain HTTP to https, apart from requests for localhost).

  6. 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.

  7. Attach a domain at /admin/domains (choose one of Karta's, or type its name; Connecting to Karta). Karta must be able to reach https://mail.example.com/karta/inbound.

  8. Create a mailbox at /admin/mailboxes and give a user access to it at /admin/users (Mailboxes). Admins can open every mailbox anyway.

  9. Send a message to the mailbox from outside and watch it arrive at /mail.

  10. 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 with PHX_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

VariableMeaning
DATABASE_URLecto://USER:PASS@HOST/DATABASE
SECRET_KEY_BASEsecret for cookies and sessions; generate with mix phx.gen.secret
PHX_HOSTpublic host name, for example mail.example.com

PHX_SERVER=true is already set in the image.

Optional environment variables

HTTP and database

VariableDefaultMeaning
PORT4000HTTP listener port
POOL_SIZE10database connection pool size (see Behind a transaction pooler for the size behind PgBouncer)
KANTOOR_DATABASE_POOLERofftrue 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_URLunsetoptional 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_IPV6unsettrue 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

VariableMeaning
OIDC_ISSUERissuer URL of the OpenID Connect provider
OIDC_CLIENT_IDclient id registered at the provider
OIDC_CLIENT_SECRETclient secret
OIDC_REDIRECT_URIregistered callback URL, for example https://mail.example.com/auth/callback
OIDC_ADMIN_GROUPgroup claim value that makes a user an administrator
OIDC_CACERTFILECA 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

VariableMeaning
KANTOOR_TRUSTED_PROXIEScomma-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

VariableMeaning
KANTOOR_TIME_ZONEIANA zone for events created in the web interface, for example Europe/Amsterdam

Without it, those events are written as floating wall-clock times.

Karta

VariableMeaning
KARTA_BASE_URLbase URL of the Karta instance
KARTA_API_KEYAPI key restricted to the Kantoor interface
KARTA_INBOUND_SECRETScomma-separated whsec_ signing secrets of the inbound endpoints (optional with the vault key)
KANTOOR_VAULT_KEYbase64 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_IDlabel of the key, default v1
KANTOOR_VAULT_RETIRED_KEYSid:base64 pairs after a key rotation
KARTA_INBOUND_HEADERoptional extra shared header, as Name: value
KARTA_MAX_BODY_BYTESlargest 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.

VariableDefaultMeaning
KANTOOR_IMAP_ENABLEDofftrue starts the IMAP listeners
KANTOOR_IMAP_LISTEN0.0.0.0bind address (IPv4 or IPv6)
KANTOOR_IMAP_PORT1143plain listener with STARTTLS (0 or off disables)
KANTOOR_IMAPS_PORT1993implicit-TLS listener, started only with a certificate
KANTOOR_IMAP_ALLOW_PLAINTEXT_AUTHfalseallow login without TLS; leave off
KANTOOR_IMAP_MAX_MESSAGE_BYTES26214400largest APPEND literal
KANTOOR_POP3_ENABLEDofftrue starts the POP3 listeners
KANTOOR_POP3_LISTEN0.0.0.0bind address
KANTOOR_POP3_PORT1110plain listener with STLS
KANTOOR_POP3S_PORT1995implicit-TLS listener
KANTOOR_POP3_ALLOW_PLAINTEXT_AUTHfalseallow login without TLS; leave off
KANTOOR_POP3_DELETE_MODEmarkmark keeps downloaded mail; delete expunges what the client deleted
KANTOOR_CHATofftrue switches on the chat (see "Chat")
KANTOOR_SMTP_ENABLEDofftrue starts the SMTP submission listeners (see "Mail clients")
KANTOOR_SMTP_LISTEN0.0.0.0bind address
KANTOOR_SMTP_PORT1587plain listener with STARTTLS (587 outside)
KANTOOR_SMTPS_PORT1465implicit-TLS listener (465 outside)
KANTOOR_SMTP_ALLOW_PLAINTEXT_AUTHfalseallow AUTH without TLS; leave off
KANTOOR_SMTP_HOSTNAMEPHX_HOSTname in the greeting
KANTOOR_SMTP_MAX_MESSAGE_BYTES26214400largest message (also announced as SIZE)
KANTOOR_SMTP_MAX_RECIPIENTS100recipients per message (Karta takes at most 150)
KANTOOR_SMTP_MAX_DATA_LINE998longest line of a message
KANTOOR_SMTP_RATE_WINDOW_S3600window for the two limits below
KANTOOR_SMTP_MAX_MESSAGES_PER_USER200messages per user per window (450 beyond)
KANTOOR_SMTP_MAX_MESSAGES_PER_IP400messages per client IP per window
KANTOOR_SMTP_SAVE_SENTfalsealso 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_CERTFILEunsetPEM certificate chain for STARTTLS/STLS and implicit TLS
KANTOOR_MAIL_TLS_KEYFILEunsetPEM private key
KANTOOR_MAIL_PROXY_TRUSTEDemptyCIDRs of TCP proxies whose PROXY protocol header is believed
KANTOOR_MAIL_PROXY_TLSfalsea connection through a trusted proxy counts as already encrypted
KANTOOR_MAIL_MAX_CONNECTIONS200simultaneous connections per protocol
KANTOOR_MAIL_MAX_CONNECTIONS_PER_IP20connections 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

VariableMeaning
KANTOOR_MAINTENANCEoff disables every maintenance job
KANTOOR_MAINTENANCE_<JOB>_ENABLEDfalse disables one job
KANTOOR_MAINTENANCE_<JOB>_INTERVAL_Sinterval of one job, in seconds
KANTOOR_TOMBSTONE_DAYSretention of IMAP and DAV tombstones, default 90
KANTOOR_APP_PASSWORD_GRACE_DAYShow long expired app passwords are kept, default 30
KANTOOR_CHAT_STORAGElocal (default) or s3: where chat files are kept
KANTOOR_CHAT_FILES_PATHlocal 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_KEYrequired with KANTOOR_CHAT_STORAGE=s3; KANTOOR_CHAT_S3_REGION defaults to garage
KANTOOR_CHAT_MAX_FILE_MBlargest chat file, default 25
KANTOOR_CHAT_DOMAIN_QUOTA_GBchat file space per mail domain, default 5
KANTOOR_CHAT_CLAMAV / KANTOOR_CHAT_CLAMAV_REQUIREDhost: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_DAYShow 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_DAYSwhen a notify-only message is marked degraded, default 7
KANTOOR_PENDING_FETCH_MIN_GAP_Sminimum 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 has idle_transaction_timeout set 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) is pg_advisory_xact_lock inside a transaction, the row locks are SELECT ... FOR UPDATE inside 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 no SET, temporary tables or LISTEN. Kantoor has no job queue of its own, and Phoenix.PubSub runs 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) uses LISTEN. Behind a pooler it needs KANTOOR_CLUSTER_DATABASE_URL or KANTOOR_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_URL run 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_PROXIES to 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_TRUSTED and KANTOOR_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.