Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,18 @@ The identity the rate limiter counts requests against: the first
`X-Forwarded-For` value or the peer address, an IPv4 address whole or an IPv6
address collapsed to its `/64` network.
_Avoid_: Client IP, user, session

**MIME tree**:
The flat list of the MIME parts of one raw email, returned under `mime_tree`
beside the parsed message; every part names the part that encloses it.
_Avoid_: Structure, MIME structure, part tree

**Part left out**:
A MIME part of the raw email that is not in the returned MIME tree because a
response bound was reached; it is counted, never dropped silently.
_Avoid_: Dropped part, truncated part

**Cut value**:
A text value of a MIME tree entry shortened to the bound, with the name of its
key recorded in that entry's `cut`.
_Avoid_: Truncated value, trimmed value
66 changes: 61 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,62 @@ Response `200`:

```json
{
"mail_parser_version": "4.10.0",
"message": {"subject": "...", "attachments": [{"filename": "...", "binary": true}]}
"mail_parser_version": "4.12.0",
"message": {"subject": "...", "attachments": [{"filename": "...", "binary": true}]},
"mime_tree": [
{"index": 0, "parent": null, "depth": 0, "content_type": "multipart/mixed", "...": "...", "cut": []},
{"index": 1, "parent": 0, "depth": 1, "content_type": "text/plain", "...": "...", "cut": []}
],
"mime_tree_parts_left_out": 0
}
```

`message` is the full `mail_json` of mail-parser. Every entry of `attachments`
keeps its metadata and loses the `payload` key.

`mime_tree` is the MIME tree of the email, as mail-parser's `--mime-tree`
prints it: a flat list in which entry `i` is MIME part `i` (the `part N` of
defect messages) and names its enclosing part in `parent`. Every entry has
these keys:

| Key | Type | Meaning |
| --------------------------- | ------------- | ------------------------------------------------------------------------------ |
| `index` | int | Position in the list. |
| `parent` | int / null | `index` of the enclosing part; null for the root. |
| `depth` | int | 0 for the root. |
| `content_type` | string | The type the parser acted on, lowercase. |
| `content_type_raw` | string / null | The literal `Content-Type` value; null when the part has none. |
| `content_transfer_encoding` | string / null | Declared encoding; null when absent. |
| `charset` | string / null | Declared charset. |
| `content_disposition` | string / null | Declared disposition type. |
| `filename` | string / null | Declared file name, decoded. |
| `content_id` | string / null | Declared `Content-ID`. |
| `boundary` | string / null | Declared boundary of a multipart. |
| `size` | int / null | Octets of a leaf after transfer decoding; null for a container. |
| `roles` | list | Any of `container`, `body`, `attachment`. |
| `attachment` | int / null | Position of the matching entry in `message.attachments`. |
| `defects` | list | Names of the defect categories recorded against the part. |
| `recovered` | bool | True for a part recovered from an epilogue. |
| `embedded_headers` | object / null | Literal `from`, `subject`, `date` of a message enclosed in a `message/*` part. |
| `cut` | list | Keys whose value was cut to 1024 characters (`embedded_headers.subject`). |

Every string in the tree, except the role and defect names, is text chosen
by the sender, passed on as declared: control characters and bidirectional
overrides included. A client must escape it before showing it.

The tree is bounded, and nothing is dropped silently:

- at most the first 500 entries are kept; parents come before children, so
what is kept is still a tree;
- every string value, those of `embedded_headers` included, is cut to 1024
characters, and its key is named in `cut`;
- the kept entries hold at most 262,144 characters of text together; the
first entry that would exceed it and every entry after it are left out.

`mime_tree_parts_left_out` is the number of entries left out, `0` when the
tree is whole. `message` is never cut: it is whole or the request fails
(see the output cap below).

| Status | When | Body |
| ------ | ------------------------------------------------------------ | --------------------------------------------------- |
| `413` | Body larger than 5 MB | `{"detail": "Body exceeds 5 MB"}` |
Expand All @@ -49,15 +97,23 @@ the reverse proxy does not expose it.

## Limits and isolation

- Each request runs the installed mail-parser CLI (`mail-parser --stdin --json`)
in a subprocess. The email goes to its stdin, never through a shell; the
- Each request runs the installed mail-parser CLI
(`mail-parser --stdin --json --mime-tree`) in a subprocess, once. The email goes to its stdin, never through a shell; the
subprocess is killed after 10 seconds.
- The request body is limited to 5 MB.
- At most 2 emails are parsed at once; further requests wait for a free slot.
- In the container each parse is limited to 192 MiB of address space
(`prlimit`) and is the first process the kernel kills when memory runs out
(`choom`), so the server survives. Such an email gets `422` with
`email too complex to parse within the service limits`.
`email too complex to parse within the service limits`. Measured with
mail-parser 4.12.0, the limit falls past 970 levels of nesting; a 5 MB
email of base64 attachments passes.
- The CLI may print at most 16 MiB, the mail and the MIME tree together:
its stdout goes to a temporary file in `/tmp`, which `prlimit --fsize`
caps in the container. An email that reaches it gets the same `422`. A
real 5 MB email prints 5 to 7 MB; the cap is reached by emails full of
control characters, which JSON prints as six bytes each, or with more than
about 35,000 MIME parts.
- Rate limit: 10 requests per 60-second sliding window per client key, in
memory, for at most 10 000 keys (least recently used evicted first). The
client key is the first `X-Forwarded-For` value, or the peer address without
Expand Down
60 changes: 60 additions & 0 deletions docs/features/message-structure/issues/01-return-the-mime-tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# 01: Return the MIME tree beside the message

Status: ready-for-agent

**What to build:** `POST /api/parse` returns two new keys, `mime_tree` and
`mime_tree_parts_left_out`, as the [spec](../spec.md) defines them. The CLI
command gains `--mime-tree`; `parser.py` decodes the second JSON document
printed after the mail and `app.py` returns it. `message` is unchanged.

**Blocked by:** nothing. mail-parser 4.12.0 has the `--mime-tree` flag; this
ticket raises the requirement to `mail-parser[outlook]>=4.12.0`, which also
brings the security fixes made since 4.11.0.

**Context:**

- `MAIL_PARSER_COMMAND` in `src/mail_parser_api/parser.py` is the fixed
argument list; `_extract_json()` finds the first document and decodes it
with `raw_decode`, which also returns where it ends. The second document
starts on the next line.
- `parse_email()` returns one dict today. It returns a `ParsedEmail` with
`message`, `mime_tree` and `mime_tree_parts_left_out`.
- The cut lives in a module of its own, `src/mail_parser_api/mime_tree.py`,
tested without a subprocess. It decodes the entries of the array one at a
time and keeps only those inside the bounds.
- 4.12.0 logs to stderr: `_error_message()` reads the `An error occurred:`
line from stderr, and stdout must start with `{`. Without this, every
`422` after the bump carries the generic error.
- `pyproject.toml` requires `mail-parser[outlook]>=4.11.0`; that version
rejects the new flag.

**Decided:**

- How a cut tree is reported (500 entries, 1024 characters per value,
262,144 characters of text in all, `mime_tree_parts_left_out` and
`cut`): see "How a cut tree is reported" in the spec.
- The CLI may print at most 16 MiB, mail and tree together; above, `422`
with `TOO_COMPLEX_ERROR` (owner, 2026-11-27, after the security review):
see "Output cap" in the spec. `message` is whole or absent, never cut.
- Failing above about 35,000 parts is acceptable; the service counts no
parts of its own (owner, 2026-11-27). The measurements are under
"Measurements" in the spec: 34,000 tiny parts, 40,000 empty parts and
970 levels of nesting pass, a 5 MiB email of base64 attachments passes
at the same peak as `--json` alone.

**Acceptance:**

- [ ] `mail_test_10` returns `200`, an unchanged `message` and nine
`mime_tree` entries linked to the four attachments.
- [ ] Output with a missing or undecodable second document returns `422`.
- [ ] A tree of 600 entries returns 500 and
`mime_tree_parts_left_out == 100`; a file name of 5,000 characters
returns 1024 of them and `cut == ["filename"]`; entries past 262,144
characters of text are left out and counted.
- [ ] Output that reaches 16 MiB returns `422` with `TOO_COMPLEX_ERROR`.
- [ ] A failing CLI's `An error occurred:` line on stderr becomes the
`422` detail.
- [x] Measurements for the many-parts and the deeply-nested email recorded
in the spec, with the decision they led to.
- [ ] `pyproject.toml`, `uv.lock` and the README contract updated.
- [ ] `make pre-commit` and `make test-cov` pass.
Loading