# Data sources

# Data sources

A data source is one mailbox Drillmark polls. One data source maps to one IMAP (or JMAP) account; multiple sources pull from independent inboxes in parallel.

## Creating a source

Add a source from Settings in the frontend. Each source needs:

- A label (free text) and the tenant it belongs to.
- IMAP host, port, SSL mode (`plain`, `starttls`, `tls`).
- Credentials. The password is encrypted with `ENCRYPTION_KEY` (AES-256-GCM) before it reaches `data_sources.encrypted_password`. The plaintext is never persisted.
- Folder names (see below).
- Optional OAuth refresh token for providers that need it; stored in `data_sources.oauth_refresh_token_enc` under the same key.

Drillmark does not create folders. Create them yourself in the mailbox before enabling the source.

## Folder layout

Drillmark expects three folders per mailbox, named by you and stored on the source row:

- `inbox` (or whatever folder DMARC reports land in). Polled on every incoming-queue run.
- `processed` folder. Successfully parsed emails move here.
- `failed` folder. Emails that failed parsing move here. The failed-queue job reattempts them on its own schedule.

A fourth `duplicate` folder is used when a report has already been ingested (same org name, report id, and date range). Duplicates move there instead of being reprocessed.

## What the incoming-queue job does per message

1. Fetch the raw MIME.
2. Extract each attachment.
3. Decompress gzip (only gzip is supported today).
4. Parse with the `mail-auth` library. A parser failure moves the email to `failed`.
5. Check for duplicates by org name + report id + date range. Duplicates move to `duplicate`.
6. Insert the parsed records into Postgres and store the raw blob alongside.
7. Move the email to `processed`.

Multiple attachments in one email are processed together; if any one attachment fails, the whole email moves to `failed`.

## Supported ingestion

- IMAP with password or OAuth refresh token.
- JMAP (the backend has a JMAP client; the exact matrix of tested providers is operator-verified).

## Credentials and rotation

Rotating a mailbox password: update the source from Settings. The frontend re-encrypts with the current `ENCRYPTION_KEY` and writes the new ciphertext.

Rotating `ENCRYPTION_KEY`: there is no online primitive. Changing the key invalidates every existing `data_sources.encrypted_password` and `data_sources.oauth_refresh_token_enc` row. Operators must disable every source, change the key, and re-enter credentials on each source.

## Disabling a source

Toggle `is_enabled` off. The incoming-queue job skips disabled sources entirely; existing records remain visible in analytics.
