The mailbox interface (Kantoor)

Karta can offer a small HTTP interface to an outside mailbox: a webmail, a mail client or any mail store that keeps its own index (folders, flags, users) and uses Karta as its mail store. Karta receives and sends, keeps the encrypted bodies, and the mailbox asks for what it needs. The interface is /kantoor/v1; Kantoor, a mail client (IMAP, CalDAV, CardDAV and a web front end), is its first user and the contract's reference implementation. Nothing in the interface is specific to Kantoor beyond the name.

The interface is optional and off by default. While it is off there is no route to it (every /kantoor/v1 path answers exactly as an unknown path does, 404), no metric poller, no retention lookup and no extra query on a request path: nothing of the feature runs. The columns it adds stay NULL.

Switching it on

Set KARTA_KANTOOR in the environment to 1 or true:

KARTA_KANTOOR=1

config/runtime.exs reads it at run time (config :karta, :kantoor, enabled: true), so a deployment is switched by setting the variable and restarting Karta, without rebuilding it. The routes themselves are always compiled; KartaWeb.Kantoor.Gate, the first plug of their pipeline, answers them as unknown routes while the switch is off.

Run the migrations (/app/bin/migrate). All five are additive: nullable columns and three partial indexes that stay empty until the interface is used.

Kantoor keys

A Kantoor key is an ordinary Karta API key (karta_<prefix>_<secret>, Argon2id, rate limits, one mail server) marked kantoor: true:

{:ok, _credential, key} =
  Karta.Credentials.create_kantoor_key(server, %{
    name: "Kantoor Bonaire",
    allowed_domains: ["example.com"],          # optional
    allowed_mailboxes: ["*@example.com"]       # optional
  })
  • A Kantoor key is accepted on /kantoor/v1 and nowhere else; every other key is refused there (401). The check is in KartaWeb.APIAuth. No API sets the marker or the restrictions: only Credentials.create_kantoor_key/2 and Credentials.update_kantoor_restrictions/2 do.
  • New scopes: messages:list, messages:delete, messages:raw, domains:read. A Kantoor key gets these and messages:send, messages:read, routes:read, routes:write by default.
  • Restrictions limit what the key may touch, so that several mailboxes can serve different subsets of one server. Patterns are case-insensitive. A domain pattern is *, example.com or *.example.com (subdomains only). A mailbox pattern is *, ann@example.com or *@example.com; its domain part may be a domain pattern. An address must match allowed_domains (when set) and allowed_mailboxes (when set). Unset means no restriction. Nothing else is interpreted (no + tags, no partial wildcards).

Endpoints

All need Authorization: Bearer <Kantoor key>; errors are the v2 API's.

OperationRequestScope
Health (12)GET /health: {"contract_version", "commit"}none
Domains (13)GET /domains: the organisation's verified domains the key's restrictions allow, with this server's routes theredomains:read
Register endpoint (1, 10)POST /endpoints: {"type": "http", "name", "url", "notify_only"}routes:write
Attach route (10)POST /routes: {"domain", "local_part", "mode", "endpoint_id"}, optionally "takeover": trueroutes:write
Message metadata (3)GET /messages/:idmessages:read
Raw message (4)GET or HEAD /messages/:id/rawmessages:raw
List (5)GET /messages?direction=&rcpt=&since=&order=&limit=&cursor=messages:list
Delete (6)DELETE /deliveries/:idmessages:delete
Send (7, 8)POST /messages, POST /messages/rawmessages:send
Route retention (11)PATCH /routes/:id with {"retention": ...}routes:write

Attaching a mailbox to a domain

A mailbox attaches itself in two calls: it registers its inbound HTTP endpoint, then creates a route that sends an address, or a whole domain, to that endpoint. It needs the domain's name from GET /domains (domains are still created, verified and published in Karta, never here) and a routes:write key.

POST /kantoor/v1/endpoints
Authorization: Bearer karta_...

{"type": "http", "name": "kantoor:example.com",
 "url": "https://kantoor.example/karta/inbound", "notify_only": false}
201 Created
{"id": "0199...", "name": "kantoor:example.com", "kind": "http",
 "url": "https://kantoor.example/karta/inbound", "format": "karta",
 "created_at": "...", "updated_at": "...", "secret": "whsec_..."}

The endpoint is marked for Kantoor, so the answer to a push may carry a retention; notify_only (the karta format only) pushes the metadata without the body. The URL must be https: and its host must be one Karta may connect to: the outbound-address check it applies before connecting, so no private or loopback target. The signing secret is shown once, here.

Registering the same name again is idempotent: it answers 200 with the endpoint that is there, updates its URL and notify_only, and shows no secret again. A name already used by an endpoint that is not a mailbox endpoint is 409 endpoint_conflict; it is never taken over.

Ownership. The key that registers an endpoint owns it. Only that key, or an unrestricted key of the same server (one with neither allowed_domains nor allowed_mailboxes), may register it again, change it or point a route at it. A restricted key may never touch an endpoint it does not own, and never one whose owner is gone: an endpoint an operator made, or one whose key was deleted. An unrestricted key that registers an endpoint with no owner adopts it — the endpoint becomes that key's. This is how a rotated or replaced key takes its endpoints back. A refusal is 403 forbidden_endpoint, and it does not reveal the other endpoint, not even its URL.

Two registrations of one name at once make one endpoint: the unique index on a mailbox endpoint's name settles them, and the loser answers as the second request would a moment later (the endpoint, 200, when it owns it or may adopt it; otherwise the 403 above).

POST /kantoor/v1/routes
Authorization: Bearer karta_...

{"domain": "example.com", "local_part": "*", "mode": "endpoint",
 "endpoint_id": "0199..."}
201 Created
{"id": "019a...", "address": "*@example.com", "domain": "example.com",
 "local_part": "*", "mode": "endpoint", "endpoint_id": "0199...", ...}

The route is created for the key's server, its domain must be a verified domain of that server's organisation, and the address must match the key's allowed_domains / allowed_mailboxes restrictions. A * route needs a restriction that matches a * address, so a key restricted to ann@example.com cannot attach a whole domain. The endpoint must be a mailbox endpoint (marked for Kantoor) of the same server, which this key owns or may use as an unrestricted key (see Ownership above); a restricted key cannot route to another key's endpoint or to one whose owner is gone (403 forbidden_endpoint), and a route can never be pointed at an operator's SMTP or forwarding endpoint.

A route that already matches the request is answered 200 with that route (a lost answer can be retried). A different route at the same address is 409 route_conflict and is not silently replaced. The request may say "takeover": true to change one, but only when it already points at the endpoint the request names; a takeover never moves a route to another endpoint. A new route is 201. Two creations at once make one route: the loser answers as the second request would a moment later (200 with the route when identical, otherwise 409 route_conflict).

Both calls go through the same code as the operator's pages (Karta.Inbound), so the server's open pages hear of the change (Karta.Changes) as they do of an operator's.

Message metadata. GET /messages/:id returns one message the key may see in the same shape as a list entry, or 404 when there is none or the key's restrictions do not allow it; it needs messages:read.

Raw message. Incoming and outgoing messages the key may see: an incoming message when the key may touch one of its live deliveries' addresses, an outgoing one when it may touch its envelope sender. The body is Karta's Received: field and the message. Content-Length is exactly messages.size; ETag is "<message id>". A single Range: bytes=a-b, a- or -n answers 206 with Content-Range; a range past the end is 416 with Content-Range: bytes */size; several ranges, another unit, a malformed value and a non-matching If-Range are ignored (the whole message is sent). Bodies are AES-GCM in 64 KiB chunks, so only the chunks that hold the range are fetched from the blob store (S3 Range reads) and decrypted, up to 16 chunks at a time; the body is never loaded whole.

List. Keyset pages (Karta.Pager), oldest first unless order=desc; since is an ISO 8601 time (created at or after it); rcpt an address. The answer is {"data": [...], "next": cursor | null}; pass next as cursor. An incoming message lists only the deliveries the key may see.

Delete. Per delivery, not per message: a message to ann@ and bob@ is one body with two deliveries. The delivery is marked deleted (inbound_deliveries.deleted_at); the message and its body go, through Karta.Messages.discard/3, only when every delivery of it is deleted or expired. Idempotent and revealing nothing: 204 for a UUID that is already deleted, unknown, another server's or an address the key may not touch (and nothing happens then); a non-UUID is 404. A deleted delivery is not dispatched, listed or served.

Send. The v2 sending logic (KartaWeb.API.V2.MessageController) with the key's sender restriction (from/sender, or the envelope mail_from; 403 forbidden_sender; the From header inside a raw message is not checked) and two more fields: retention ("keep" or days) and source (default "kantoor"), stored on the message.

The body of POST /messages/raw may have 37,049,688 bytes (a 25 MiB message as base64 and 2 MiB for the rest; other bodies 8,000,000); a larger one is 413, and a message that is larger than 25 MiB once decoded is 422 message_too_large.

A raw message may ask for the null reverse path with auto_reply: true and mail_from empty or left out, for an automatic reply such as a vacation answer: Karta then sends MAIL FROM:<>, so a failure can never bounce. The message must carry Auto-Submitted: auto-replied or auto-generated; without it the send is refused (422 not_auto_submitted). The null sender names no address, so the key's sender restriction does not apply to it (the From header is still checked by the v2 sending logic). See Delivery.

Receiving: what Karta pushes

A mailbox registers one HTTP endpoint in the karta format per domain (with POST /endpoints) and routes (* for a whole domain) to it (with POST /routes), and filters per mailbox itself. The push is the existing message.received JSON, signed as Standard Webhooks (webhook-id is the delivery id; the receiver dedupes on it). Registering an endpoint sets its two options:

  • kantoor: true lets the 2xx answer carry a retention (below);
  • notify_only from the request (format karta only) pushes the metadata without raw (size is the stored size); the receiver fetches the body with GET /messages/:id/raw. The dispatcher neither reads the stored body nor applies its 25 MiB limit to such an endpoint, so any size can be announced. The receiver must accept pushes with and without raw.

An operator may still set both by hand, e.g. for an endpoint made before this interface had the calls:

{:ok, endpoint} = Karta.Kantoor.mark_endpoint(endpoint, true, notify_only: true)

Retention

The mailbox decides, Karta enforces. A policy is "keep" (never expires), a number of days (1 to 36500) or none (the server's retention_days and retention_size_mb, as always). It lives on the delivery:

  1. the route default (PATCH /kantoor/v1/routes/:id), copied onto new deliveries;
  2. replaced by the 2xx answer to a push, {"retention": "keep"} or {"retention": 30} (switch on, Kantoor-marked endpoint only; an invalid value is ignored and noted in the delivery's details; non-2xx answers are retried as ever and apply nothing);
  3. outgoing messages carry the policy of the send request.

Karta.Messages.Retention honours stored policies (also with the switch off, so switching it off never purges mail that was kept under a policy; no new policy is recorded while it is off): keep never expires and is exempt from the size cap (and not counted in it); days replace the server's for that delivery; with several deliveries the longest wins and keep beats any days; deleted deliveries do not hold a message, and one whose deliveries are all deleted goes at the next run. A message without any policy is retained exactly as before.

The cap on kept storage

keep would otherwise make Karta an unbounded mail store, so there is an optional per-server hard cap, servers.kept_storage_cap_mb, with no default (unset: no cap):

Karta.Kantoor.KeptStorage.set_cap(server, 50_000)   # megabytes; nil clears it

With a cap, a keep that would take the server's kept bytes past it is refused: a send fails with 507 kept_storage_full; an endpoint's keep answer is not applied (the delivery keeps the route's or the server's policy and says so in its details). Nothing already kept is deleted. The check is not locked, so concurrent requests may overshoot by what they hold.

Metrics (while the switch is on; Karta does not alert, you do): karta_kantoor_kept_storage_bytes{server_id}, karta_kantoor_kept_storage_messages{server_id}, karta_kantoor_kept_storage_cap_bytes{server_id} (servers with a cap) and karta_kantoor_keep_refused_total{server_id}. For example:

karta_kantoor_kept_storage_bytes / karta_kantoor_kept_storage_cap_bytes > 0.8
increase(karta_kantoor_keep_refused_total[1h]) > 0

Plan S3 capacity and backups for kept mail. Bodies are encrypted with keys derived from the vault key, so the vault key backup becomes critical (Storage and encryption).

What this does not do

  • It does not create, verify or publish domains: they are managed in Karta (GET /domains only lists them).
  • A route made through the interface may point only at an endpoint marked for Kantoor on the same server, never at an operator's SMTP or forwarding endpoint, and a takeover never moves a route to another endpoint. Removing a route or an endpoint is still an operator's job (there is no DELETE under /kantoor/v1).
  • Bounce and DSN handling is parked until the bounce milestone is merged.

Testing

mix test runs with the switch off, as a deployment does by default; the tests of the interface switch it on at run time (Karta.KantoorFlag.on!/0) and are not async, because the switch is global. test/karta_web/kantoor/routes_test.exs proves both states: the routes are compiled either way, and while it is off every path answers as an unknown route does, no kept-storage poller runs and copying a route's retention reads nothing.