From 40de3b5943efcc8d9d6951fd60898cc0c2ce6ea3 Mon Sep 17 00:00:00 2001 From: Fedele Mantuano Date: Sun, 22 Nov 2026 18:42:03 +0100 Subject: [PATCH 1/5] docs: spec and ticket for returning the MIME tree --- .../issues/01-return-the-mime-tree.md | 38 ++++++ docs/features/message-structure/spec.md | 123 ++++++++++++++++++ 2 files changed, 161 insertions(+) create mode 100644 docs/features/message-structure/issues/01-return-the-mime-tree.md create mode 100644 docs/features/message-structure/spec.md diff --git a/docs/features/message-structure/issues/01-return-the-mime-tree.md b/docs/features/message-structure/issues/01-return-the-mime-tree.md new file mode 100644 index 0000000..31b586c --- /dev/null +++ b/docs/features/message-structure/issues/01-return-the-mime-tree.md @@ -0,0 +1,38 @@ +# 01: Return the MIME tree beside the message + +Status: needs-triage + +**What to build:** `POST /api/parse` returns a third key, `mime_tree`, as +the [spec](../spec.md) defines it. 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:** a mail-parser release with the `--mime-tree` flag (see +"Blocked by" in the spec). Until then the work can be done against +mail-parser's `feature/message-structure` branch, but not released. + +**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. Its return value has to carry + both documents. +- `pyproject.toml` requires `mail-parser[outlook]>=4.11.0`; that version + rejects the new flag. + +**Open questions:** the two listed in the spec: a cap on the number of +entries, and the memory of measuring base64 attachments under the +192 MiB cap. Both need a measurement before the ticket is ready for an +agent. + +**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`. +- [ ] Measurements for the many-parts and the deeply-nested email recorded + in this file, with the decision they led to. +- [ ] `pyproject.toml`, `uv.lock` and the README contract updated. +- [ ] `make pre-commit` and `make test-cov` pass. diff --git a/docs/features/message-structure/spec.md b/docs/features/message-structure/spec.md new file mode 100644 index 0000000..e041b0a --- /dev/null +++ b/docs/features/message-structure/spec.md @@ -0,0 +1,123 @@ +# Return the MIME tree of the parsed email + +Branch: `feature/message-structure`. Agreed with the owner on 2026-11-22, +in the session that designed the feature in mail-parser. This file carries +everything decided there that concerns this repository, so the work can +start without that conversation. + +Source of truth for the tree: `docs/features/message-structure/spec.md` and +`docs/adr/0002-mime-tree-as-flat-parent-indexed-list.md` in +[SpamScope/mail-parser](https://github.com/SpamScope/mail-parser). If this +file and that one differ, that one is right. + +## Goal and boundaries + +The live parser page of spamscope.ai will draw the structure of an email: +its delivery path and its MIME tree. The delivery path is already in the +response (`message.received`). This service adds the one missing piece, the +MIME tree. + +- `message` does not change. Whoever reads it today reads the same thing. +- The tree is a new key beside it, `mime_tree`. +- This service does not draw anything and returns no text drawing. The + page draws from the data. +- No change to limits, rate limiting, logging or the Outlook refusal. + +## Blocked by + +A mail-parser release that has the `--mime-tree` flag. It was implemented +on mail-parser's `feature/message-structure` branch after 4.11.0 and is not +released yet. `pyproject.toml` must then require that version +(`mail-parser[outlook]>=`), because an older CLI rejects the +flag and every parse would fail. + +## What mail-parser provides + +`mailparser --stdin --json --mime-tree` prints two JSON documents, one +after the other, both indented: + +1. the mail, exactly as `--json` alone prints it; +1. the MIME tree, a JSON array, starting on the line after the first + document ends. An empty tree is `[]`. + +Log lines can still precede the first document, as today. + +The tree is a flat array. Entry `i` describes MIME part `i`, the number +defect messages quote as `part N`, and names its enclosing part in +`parent`. Every entry has all of these keys: + +| Key | Type | Meaning | +| --------------------------- | ------------- | ------------------------------------------------------------------------------ | +| `index` | int | Position in the array. | +| `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` | array | Any of `container`, `body`, `attachment`. | +| `attachment` | int / null | Position of the matching entry in `message.attachments`. | +| `defects` | array | 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. | + +The tree holds no payload, so there is nothing to strip from it. +`attachment` stays valid after this service removes `payload` from the +attachments, because entries are removed from none of them. + +## Response + +```json +{ + "mail_parser_version": "", + "message": {"...": "unchanged"}, + "mime_tree": [ + {"index": 0, "parent": null, "depth": 0, "content_type": "multipart/mixed", "...": "..."}, + {"index": 1, "parent": 0, "depth": 1, "content_type": "text/plain", "...": "..."} + ] +} +``` + +## Rules + +1. One subprocess and one parse per request, as today. Do not run the CLI + twice: it would double the CPU spent inside the 10-second timeout. +1. A response always has `mime_tree`. If the second document is missing + or does not decode, the request fails with `422` like any other + unparsable output; it is never answered with `message` alone. +1. Every value in the tree except the numbers, booleans and role names is + text chosen by the sender. This service passes it on as JSON and does + not interpret it. It never reaches a log line. +1. The tree grows with the number of MIME parts, which the sender + chooses, and so does the response. Measure the response and the + child's memory for a 5 MB email made of as many tiny parts as fit, and + for one nested several hundred levels deep, before deciding whether the + existing limits are enough or the tree needs its own. + Measured in mail-parser (Python 3.13, macOS) on a 2.7 MiB message of + 400,000 empty parts: the tree is 159 MiB of JSON, about 400 bytes per + entry, and producing it peaks at 626 MiB, against 281 MiB for parsing + alone. Under the 192 MiB cap such a message fails as too complex; the + open point is the largest tree that still passes. + +## Open questions for the implementation + +- Does the number above call for a cap on the number of entries, and if + so how is a cut tree reported to the page? +- Reading the tree makes mail-parser decode each base64 attachment once to + measure it. Does a 5 MB email stay inside the 192 MiB address-space cap? + +## Acceptance + +1. `POST /api/parse` with `mail_test_10` returns `200` with `message` + equal to today's and a `mime_tree` of nine entries whose `attachment` + values are 0 to 3. +1. A stub CLI that prints only the first document yields `422`. +1. A test covers an email with no MIME structure (one entry) and one + nested several hundred levels deep. +1. README endpoint contract updated with the new key and the table above. +1. `make pre-commit` and `make test-cov` pass. From 5d0b1220460393a9541359edb0c4e21284268cbc Mon Sep 17 00:00:00 2001 From: Fedele Mantuano Date: Fri, 27 Nov 2026 11:01:19 +0100 Subject: [PATCH 2/5] docs: decide how a cut MIME tree is reported Record the bounds agreed with MailXRay (500 entries, 1024 characters per value, mime_tree_parts_left_out and cut), mark the ticket unblocked by mail-parser 4.12.0 and add the MIME tree terms to the glossary. --- GLOSSARY.md | 15 +++++++ .../issues/01-return-the-mime-tree.md | 21 ++++++---- docs/features/message-structure/spec.md | 41 ++++++++++++++----- 3 files changed, 60 insertions(+), 17 deletions(-) diff --git a/GLOSSARY.md b/GLOSSARY.md index 8121d24..4e83b34 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -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 diff --git a/docs/features/message-structure/issues/01-return-the-mime-tree.md b/docs/features/message-structure/issues/01-return-the-mime-tree.md index 31b586c..10ce447 100644 --- a/docs/features/message-structure/issues/01-return-the-mime-tree.md +++ b/docs/features/message-structure/issues/01-return-the-mime-tree.md @@ -7,9 +7,9 @@ the [spec](../spec.md) defines it. 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:** a mail-parser release with the `--mime-tree` flag (see -"Blocked by" in the spec). Until then the work can be done against -mail-parser's `feature/message-structure` branch, but not released. +**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:** @@ -22,16 +22,23 @@ mail-parser's `feature/message-structure` branch, but not released. - `pyproject.toml` requires `mail-parser[outlook]>=4.11.0`; that version rejects the new flag. -**Open questions:** the two listed in the spec: a cap on the number of -entries, and the memory of measuring base64 attachments under the -192 MiB cap. Both need a measurement before the ticket is ready for an -agent. +**Decided:** how a cut tree is reported (500 entries, 1024 characters per +value, `mime_tree_parts_left_out` and `cut`): see "How a cut tree is +reported" in the spec. + +**Open questions:** the two listed in the spec: the largest tree the child +still produces under the 192 MiB cap, and the memory of measuring base64 +attachments under it. Both need a measurement before the ticket is ready +for an agent. **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"]`. - [ ] Measurements for the many-parts and the deeply-nested email recorded in this file, with the decision they led to. - [ ] `pyproject.toml`, `uv.lock` and the README contract updated. diff --git a/docs/features/message-structure/spec.md b/docs/features/message-structure/spec.md index e041b0a..a9424e3 100644 --- a/docs/features/message-structure/spec.md +++ b/docs/features/message-structure/spec.md @@ -25,11 +25,10 @@ MIME tree. ## Blocked by -A mail-parser release that has the `--mime-tree` flag. It was implemented -on mail-parser's `feature/message-structure` branch after 4.11.0 and is not -released yet. `pyproject.toml` must then require that version -(`mail-parser[outlook]>=`), because an older CLI rejects the -flag and every parse would fail. +Nothing any more. mail-parser 4.12.0, released, has the `--mime-tree` flag +and the security fixes made since 4.11.0. `pyproject.toml` must require it +(`mail-parser[outlook]>=4.12.0`), because an older CLI rejects the flag and +every parse would fail. ## What mail-parser provides @@ -77,9 +76,10 @@ attachments, because entries are removed from none of them. "mail_parser_version": "", "message": {"...": "unchanged"}, "mime_tree": [ - {"index": 0, "parent": null, "depth": 0, "content_type": "multipart/mixed", "...": "..."}, - {"index": 1, "parent": 0, "depth": 1, "content_type": "text/plain", "...": "..."} - ] + {"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 } ``` @@ -104,10 +104,31 @@ attachments, because entries are removed from none of them. alone. Under the 192 MiB cap such a message fails as too complex; the open point is the largest tree that still passes. +## How a cut tree is reported + +Decided with the owner on 2026-11-26, together with the same feature in +MailXRay (`docs/features/message-structure/spec.md` in mailxray-backend), so +that the live parser page and MailXRay read one shape: + +- The response keeps the first 500 entries of the tree. Parents come before + children, so what is kept is a valid tree. +- A new key beside `mime_tree`, `mime_tree_parts_left_out`, is the number of + entries not kept, `0` when the tree is whole. It is always present. +- Every string value of an entry, the three values of `embedded_headers` + included, is cut to 1024 characters. Every entry gains a key `cut`: the + names of the keys that were cut (`embedded_headers.subject` for a nested + one), an empty list otherwise. + +MailXRay also refuses to build the tree of a message with more than 50,000 +parts, by counting them first. This service cannot: the CLI builds the whole +tree in the child before anything is printed. The child's limits stay the +guard here, and such a message fails as too complex. + ## Open questions for the implementation -- Does the number above call for a cap on the number of entries, and if - so how is a cut tree reported to the page? +- The cut above bounds the response, not the child. What is the largest tree + the child still produces under the 192 MiB cap, and is failing above it + acceptable for the page? - Reading the tree makes mail-parser decode each base64 attachment once to measure it. Does a 5 MB email stay inside the 192 MiB address-space cap? From 7e31e2dd1f58c5e372017e003dff5fa5a10fd42d Mon Sep 17 00:00:00 2001 From: Fedele Mantuano Date: Fri, 27 Nov 2026 11:06:25 +0100 Subject: [PATCH 3/5] feat: return the MIME tree beside the parsed message Raise the requirement to mail-parser[outlook]>=4.12.0 and run the CLI with --mime-tree. POST /api/parse returns mime_tree and mime_tree_parts_left_out beside an unchanged message. - mime_tree.py decodes the tree one entry at a time and keeps the first 500 entries, cuts every string value to 1024 characters (named in cut) and bounds the text of the kept entries to 262,144 characters, as MailXRay does. Entries past the bounds are counted, never held. - 4.12.0 logs to stderr: the 422 detail is read from there, and stdout must start with the mail JSON. Without this every 422 carried the generic error after the bump. - A missing or undecodable tree is unparsable output (422). - Spec and ticket record the measurements under the child limits and the decisions they led to; README documents the contract. --- README.md | 59 +++++++- .../issues/01-return-the-mime-tree.md | 45 +++--- docs/features/message-structure/spec.md | 91 +++++++++--- pyproject.toml | 2 +- src/mail_parser_api/app.py | 9 +- src/mail_parser_api/mime_tree.py | 137 ++++++++++++++++++ src/mail_parser_api/parser.py | 81 +++++++---- tests/unittests/test_app.py | 83 ++++++++++- tests/unittests/test_mime_tree.py | 123 ++++++++++++++++ tests/unittests/test_parser.py | 85 ++++++++--- uv.lock | 10 +- 11 files changed, 618 insertions(+), 107 deletions(-) create mode 100644 src/mail_parser_api/mime_tree.py create mode 100644 tests/unittests/test_mime_tree.py diff --git a/README.md b/README.md index 8073f35..9b0007d 100644 --- a/README.md +++ b/README.md @@ -22,14 +22,61 @@ 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. + | Status | When | Body | | ------ | ------------------------------------------------------------ | --------------------------------------------------- | | `413` | Body larger than 5 MB | `{"detail": "Body exceeds 5 MB"}` | @@ -49,15 +96,17 @@ 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 between 68,000 and 90,000 MIME parts, + or past 970 levels of nesting; a 5 MB email of base64 attachments passes. - 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 diff --git a/docs/features/message-structure/issues/01-return-the-mime-tree.md b/docs/features/message-structure/issues/01-return-the-mime-tree.md index 10ce447..042868e 100644 --- a/docs/features/message-structure/issues/01-return-the-mime-tree.md +++ b/docs/features/message-structure/issues/01-return-the-mime-tree.md @@ -1,11 +1,11 @@ # 01: Return the MIME tree beside the message -Status: needs-triage +Status: ready-for-agent -**What to build:** `POST /api/parse` returns a third key, `mime_tree`, as -the [spec](../spec.md) defines it. 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. +**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 @@ -17,19 +17,27 @@ brings the security fixes made since 4.11.0. 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. Its return value has to carry - both documents. +- `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, `mime_tree_parts_left_out` and `cut`): see "How a cut tree is -reported" in the spec. +**Decided:** -**Open questions:** the two listed in the spec: the largest tree the child -still produces under the 192 MiB cap, and the memory of measuring base64 -attachments under it. Both need a measurement before the ticket is ready -for an agent. +- 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. +- Failing above about 70,000 parts is acceptable; the service counts no + parts of its own (owner, 2026-11-27). The measurements are under + "Measurements" in the spec: 68,000 tiny parts, 88,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:** @@ -38,8 +46,11 @@ for an agent. - [ ] 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"]`. -- [ ] Measurements for the many-parts and the deeply-nested email recorded - in this file, with the decision they led to. + returns 1024 of them and `cut == ["filename"]`; entries past 262,144 + characters of text are left out and counted. +- [ ] 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. diff --git a/docs/features/message-structure/spec.md b/docs/features/message-structure/spec.md index a9424e3..b30fdc4 100644 --- a/docs/features/message-structure/spec.md +++ b/docs/features/message-structure/spec.md @@ -37,9 +37,13 @@ after the other, both indented: 1. the mail, exactly as `--json` alone prints it; 1. the MIME tree, a JSON array, starting on the line after the first - document ends. An empty tree is `[]`. + document ends. It always has at least one entry, the root: an email + without MIME structure, and even an empty one, has one part. -Log lines can still precede the first document, as today. +Since 4.12.0 the CLI logs to stderr, the `An error occurred:` line +included, so stdout holds nothing but the two documents (measured on +2026-11-27, see below). Before 4.12.0 log lines went to stdout and could +precede the first document; the service no longer looks for them there. The tree is a flat array. Entry `i` describes MIME part `i`, the number defect messages quote as `part N`, and names its enclosing part in @@ -94,15 +98,14 @@ attachments, because entries are removed from none of them. text chosen by the sender. This service passes it on as JSON and does not interpret it. It never reaches a log line. 1. The tree grows with the number of MIME parts, which the sender - chooses, and so does the response. Measure the response and the - child's memory for a 5 MB email made of as many tiny parts as fit, and - for one nested several hundred levels deep, before deciding whether the - existing limits are enough or the tree needs its own. - Measured in mail-parser (Python 3.13, macOS) on a 2.7 MiB message of - 400,000 empty parts: the tree is 159 MiB of JSON, about 400 bytes per - entry, and producing it peaks at 626 MiB, against 281 MiB for parsing - alone. Under the 192 MiB cap such a message fails as too complex; the - open point is the largest tree that still passes. + chooses. The child's limits bound what it can print (see + [Measurements](#measurements-2026-11-27)); the cut below bounds the + response. +1. Errors are read from stderr. The detail of a `422` is the text after + `An error occurred:` on stderr, `TOO_COMPLEX_ERROR` when that text is + empty (a `MemoryError` has none), the generic error otherwise. stdout + must start with `{`; anything else is unparsable output. stderr never + reaches a log line. ## How a cut tree is reported @@ -118,19 +121,63 @@ that the live parser page and MailXRay read one shape: included, is cut to 1024 characters. Every entry gains a key `cut`: the names of the keys that were cut (`embedded_headers.subject` for a nested one), an empty list otherwise. +- The kept entries hold at most 262,144 characters of text together: the + characters of every string value, those of `embedded_headers` included, + counted after the cut to 1024. Entries are kept in order while they fit; + the first entry that would exceed the bound and every entry after it are + left out and counted in `mime_tree_parts_left_out`. The kept entries are + still a prefix, so the tree is still valid. Without this bound, 500 + entries of eleven values of 1024 characters hold 5.6 million characters, + and a control character takes six bytes once escaped in JSON. MailXRay + added the same bound after its security review of 2026-11-26 (rule 5 of + "Bounds" in its spec); agreed for this service on 2026-11-27. + +Decided on 2026-11-27: `message` is not cut. MailXRay also keeps only the +first 100 `received_header_defects`; this service does not, because +`message` stays what mail-parser prints. MailXRay also refuses to build the tree of a message with more than 50,000 parts, by counting them first. This service cannot: the CLI builds the whole tree in the child before anything is printed. The child's limits stay the guard here, and such a message fails as too complex. -## Open questions for the implementation - -- The cut above bounds the response, not the child. What is the largest tree - the child still produces under the 192 MiB cap, and is failing above it - acceptable for the page? -- Reading the tree makes mail-parser decode each base64 attachment once to - measure it. Does a 5 MB email stay inside the 192 MiB address-space cap? +The service decodes the entries of the array one at a time and keeps only +those inside the bounds; the others are counted and dropped as soon as they +are decoded. Decoding the whole array first would hold up to 55 MiB of +objects per parse in uvicorn (PID 1), with two parses at once. + +## Measurements (2026-11-27) + +Docker on Apple silicon, `python:3.13-slim` (3.13.18, aarch64), +`mail-parser[outlook]==4.12.0`, a 512 MiB container, the child run as the +service runs it: `choom -n 1000 -- prlimit --as=201326592 --`, +`--json --mime-tree`, 10-second timeout. + +| Email | Result | +| ----------------------------------------- | ----------------------------------------- | +| N empty parts (5 bytes each) | passes up to 88,000; 91,000 and more fail | +| N tiny `text/plain` parts (32 bytes each) | passes up to 68,000; 70,000 and more fail | +| 5 MiB, one base64 attachment | passes, 60.5 MiB child peak, as `--json` | +| 5 MiB, twenty base64 attachments | passes, 52.4 MiB child peak, as `--json` | +| multipart nested N levels | passes up to 970; 980 and more fail | + +- Above the limit the child fails with `MemoryError` while printing the + tree: exit code 1, the first document complete on stdout, nothing of the + tree. That is unparsable output, a `422` with `TOO_COMPLEX_ERROR`. No run + was killed and none came closer than 6.5 seconds to the timeout. +- Without `--mime-tree` the same cap passes about 250,000 empty parts: the + tree lowers the limit to about 90,000. +- The largest tree that passes is 29 to 37 MB of JSON, about 420 bytes per + entry. Holding and decoding it in the parent peaks at 125 MiB; two such + parses at once peaked at 411 MiB in the container, without uvicorn. +- Nesting fails with `MailParserRecursionError` with or without + `--mime-tree`; it is a limit of the parse, not of the tree. +- No lone surrogate reached stdout: the CLI writes UTF-8 with + `ensure_ascii=False`, and undecodable bytes in tree values arrive as + U+FFFD. + +Decision (owner, 2026-11-27): failing above about 70,000 parts is +acceptable for the page; no count of our own before the parse. ## Acceptance @@ -140,5 +187,11 @@ guard here, and such a message fails as too complex. 1. A stub CLI that prints only the first document yields `422`. 1. A test covers an email with no MIME structure (one entry) and one nested several hundred levels deep. -1. README endpoint contract updated with the new key and the table above. +1. 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. +1. A failing CLI whose stderr has `An error occurred: ` yields `422` + with ``, and with `TOO_COMPLEX_ERROR` when the text is empty. +1. README endpoint contract updated with the new keys and the table above. 1. `make pre-commit` and `make test-cov` pass. diff --git a/pyproject.toml b/pyproject.toml index 0be61bd..4eced67 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,7 @@ requires-python = ">=3.13" dependencies = [ "fastapi>=0.115.0", "uvicorn[standard]>=0.30.0", - "mail-parser[outlook]>=4.11.0", + "mail-parser[outlook]>=4.12.0", ] [project.urls] diff --git a/src/mail_parser_api/app.py b/src/mail_parser_api/app.py index f96b045..d492a3d 100644 --- a/src/mail_parser_api/app.py +++ b/src/mail_parser_api/app.py @@ -95,14 +95,19 @@ async def parse(request: Request) -> JSONResponse: try: async with parse_slots: - message = await asyncio.to_thread(parse_email, raw_email) + parsed = await asyncio.to_thread(parse_email, raw_email) except ParseTimeoutError as error: raise HTTPException(status_code=504, detail="Parsing timed out") from error except ParseError as error: raise HTTPException(status_code=422, detail=str(error)) from error return JSONResponse( - {"mail_parser_version": MAIL_PARSER_VERSION, "message": message} + { + "mail_parser_version": MAIL_PARSER_VERSION, + "message": parsed.message, + "mime_tree": parsed.mime_tree, + "mime_tree_parts_left_out": parsed.mime_tree_parts_left_out, + } ) return app diff --git a/src/mail_parser_api/mime_tree.py b/src/mail_parser_api/mime_tree.py new file mode 100644 index 0000000..9a8a8a2 --- /dev/null +++ b/src/mail_parser_api/mime_tree.py @@ -0,0 +1,137 @@ +"""Read the MIME tree printed by the mail-parser CLI and bound it. + +The bounds are those of MailXRay, so that the live parser page and MailXRay +read one shape: the first entries are kept, every string value is cut, and +the text of the kept entries is bounded as a whole. Nothing is dropped +silently: a cut value is named in ``cut`` and a part left out is counted. +""" + +import json +import re +from collections.abc import Iterator +from typing import Any + +MAX_MIME_TREE_PARTS = 500 +"""Entries kept. Parents precede children, so the kept prefix is a tree.""" + +MAX_STRUCTURE_TEXT = 1024 +"""Characters kept of every string value, ``embedded_headers`` included.""" + +MAX_MIME_TREE_TEXT = 262_144 +"""Characters of text the kept entries hold together, counted after the cut. + +The first entry that would exceed it and every entry after it are left out: +500 entries of eleven values of 1024 characters would otherwise hold 5.6 +million characters, and a control character takes six bytes in JSON. +""" + +_NOT_WHITESPACE = re.compile(r"[^ \t\n\r]") + + +def read_mime_tree(text: str, start: int) -> tuple[list[dict[str, Any]], int]: + """Decode the JSON array of the MIME tree and keep its bounded prefix. + + Entries are decoded one at a time: those past the bounds are counted and + dropped as soon as they are decoded, so the memory held does not grow + with the number of parts the sender chose. + + Args: + text: The CLI output. + start: Where the array may start, after optional whitespace. + + Returns: + ``(mime_tree, mime_tree_parts_left_out)``: the kept entries, each + with ``cut``, and the number of entries not kept. + + Raises: + ValueError: The text at ``start`` is not a JSON array of objects. + + """ + kept: list[dict[str, Any]] = [] + left_out = 0 + characters = 0 + for entry in _entries(text, start): + if not left_out and len(kept) < MAX_MIME_TREE_PARTS: + part = _bounded_part(entry) + characters += _text_length(part) + if characters <= MAX_MIME_TREE_TEXT: + kept.append(part) + continue + left_out += 1 + return kept, left_out + + +def _entries(text: str, start: int) -> Iterator[dict[str, Any]]: + """Yield the objects of the JSON array at ``start``, one at a time. + + Raises: + ValueError: The text is not a closed JSON array of objects. + + """ + decoder = json.JSONDecoder() + position = _skip_whitespace(text, start) + if not text.startswith("[", position): + message = "the MIME tree is not a JSON array" + raise ValueError(message) + position = _skip_whitespace(text, position + 1) + if text.startswith("]", position): + return + while True: + entry, position = decoder.raw_decode(text, position) + if not isinstance(entry, dict): + message = "a MIME tree entry is not a JSON object" + raise ValueError(message) # noqa: TRY004 - malformed output, not a type + yield entry + position = _skip_whitespace(text, position) + if text.startswith("]", position): + return + if not text.startswith(",", position): + message = "the MIME tree array is not closed" + raise ValueError(message) + position = _skip_whitespace(text, position + 1) + + +def _skip_whitespace(text: str, position: int) -> int: + """Return the position of the next non-whitespace character, or the end.""" + match = _NOT_WHITESPACE.search(text, position) + return match.start() if match else len(text) + + +def _bounded_part(entry: dict[str, Any]) -> dict[str, Any]: + """Return an entry with every string value cut and its ``cut`` list. + + The values of ``embedded_headers`` are cut too and named + ``embedded_headers.``. Nothing else changes: control characters + and bidirectional overrides are evidence and stay as declared. + """ + cut: list[str] = [] + part: dict[str, Any] = {} + for key, value in entry.items(): + if isinstance(value, str): + part[key] = _bounded_text(value, key, cut) + elif key == "embedded_headers" and isinstance(value, dict): + part[key] = { + name: _bounded_text(text, f"{key}.{name}", cut) + if isinstance(text, str) + else text + for name, text in value.items() + } + else: + part[key] = value + part["cut"] = cut + return part + + +def _bounded_text(value: str, key: str, cut: list[str]) -> str: + """Return ``value`` cut to the bound, naming ``key`` in ``cut`` if cut.""" + if len(value) <= MAX_STRUCTURE_TEXT: + return value + cut.append(key) + return value[:MAX_STRUCTURE_TEXT] + + +def _text_length(part: dict[str, Any]) -> int: + """Return the characters of the string values of a bounded entry.""" + headers = part.get("embedded_headers") + values = [*part.values(), *(headers.values() if isinstance(headers, dict) else ())] + return sum(len(value) for value in values if isinstance(value, str)) diff --git a/src/mail_parser_api/parser.py b/src/mail_parser_api/parser.py index 164bdfc..63cb0a9 100644 --- a/src/mail_parser_api/parser.py +++ b/src/mail_parser_api/parser.py @@ -4,8 +4,11 @@ import signal import subprocess import sys +from dataclasses import dataclass from typing import Any +from mail_parser_api.mime_tree import read_mime_tree + PARSE_TIMEOUT_SECONDS = 10 # Address-space cap of one parse. Real emails up to 5 MB stay well below it; @@ -13,13 +16,15 @@ CHILD_ADDRESS_SPACE_BYTES = 192 * 1024 * 1024 # The installed mail-parser CLI, run with the same interpreter as the service. -# ``-l ERROR`` keeps warnings off stdout; error lines may still precede the JSON. +# It prints the mail, then the MIME tree, as two JSON documents on stdout; its +# log lines go to stderr, and ``--log-level ERROR`` keeps only the errors. MAIL_PARSER_COMMAND = ( sys.executable, "-m", "mailparser", "--stdin", "--json", + "--mime-tree", "--log-level", "ERROR", ) @@ -38,13 +43,29 @@ "--", ) -# Prefix of the line the CLI logs on stdout when parsing fails. +# Prefix of the line the CLI logs on stderr when parsing fails. ERROR_MARKER = "An error occurred: " GENERIC_ERROR = "mail-parser could not parse the email" # The child was killed by the kernel or logged a MemoryError, which has no text. TOO_COMPLEX_ERROR = "email too complex to parse within the service limits" +@dataclass(frozen=True) +class ParsedEmail: + """The two documents the CLI prints for one email, shaped for the response. + + Attributes: + message: The mail-parser JSON of the email without attachment payloads. + mime_tree: The kept entries of the MIME tree, each with ``cut``. + mime_tree_parts_left_out: The entries of the MIME tree not kept. + + """ + + message: dict[str, Any] + mime_tree: list[dict[str, Any]] + mime_tree_parts_left_out: int + + class ParseError(Exception): """mail-parser failed to parse the email.""" @@ -53,20 +74,22 @@ class ParseTimeoutError(Exception): """mail-parser did not finish within the timeout.""" -def parse_email(raw_email: bytes) -> dict[str, Any]: +def parse_email(raw_email: bytes) -> ParsedEmail: """Parse a raw email with the mail-parser CLI. The email is passed on stdin, never through a shell. Attachment payloads are - removed from the result; their metadata is kept. + removed from the message; their metadata is kept. The MIME tree is bounded + as :func:`mail_parser_api.mime_tree.read_mime_tree` describes. Args: raw_email: The raw email bytes. Returns: - The mail-parser JSON of the email without attachment payloads. + The message and the MIME tree of the email. Raises: - ParseError: mail-parser exited with an error or printed no JSON. + ParseError: mail-parser exited with an error or did not print both + JSON documents. ParseTimeoutError: mail-parser ran longer than the timeout and was killed. """ @@ -83,14 +106,18 @@ def parse_email(raw_email: bytes) -> dict[str, Any]: if completed.returncode == -signal.SIGKILL: raise ParseError(TOO_COMPLEX_ERROR) - stdout = completed.stdout.decode("utf-8", errors="replace") if completed.returncode != 0: - raise ParseError(_error_message(stdout)) + raise ParseError(_error_message(completed.stderr)) - message = _extract_json(stdout) + stdout = completed.stdout.decode("utf-8", errors="replace") + try: + message, end = _decode_message(stdout) + mime_tree, parts_left_out = read_mime_tree(stdout, end) + except ValueError as error: + raise ParseError(GENERIC_ERROR) from error for attachment in message.get("attachments", []): attachment.pop("payload", None) - return message + return ParsedEmail(message, mime_tree, parts_left_out) def _command() -> tuple[str, ...]: @@ -100,29 +127,25 @@ def _command() -> tuple[str, ...]: return MAIL_PARSER_COMMAND -def _extract_json(stdout: str) -> dict[str, Any]: - """Return the JSON object printed by the CLI. +def _decode_message(stdout: str) -> tuple[dict[str, Any], int]: + """Return the mail JSON object that starts stdout and where it ends. + + It is decoded in place, without copying the output, to keep the memory of + large results low. + + Raises: + ValueError: stdout does not start with a JSON object. - Log lines start with a timestamp; the JSON object is printed with indent=2, - so it is the first line made of a lone ``{``. It is decoded in place, without - copying the output, to keep the memory of large results low. """ - if stdout.startswith("{\n"): - start = 0 - else: - start = stdout.find("\n{\n") + 1 - if start == 0: - raise ParseError(GENERIC_ERROR) - try: - message, _ = json.JSONDecoder().raw_decode(stdout, start) - except ValueError as error: - raise ParseError(GENERIC_ERROR) from error - return message + if not stdout.startswith("{"): + message = "the output does not start with a JSON object" + raise ValueError(message) + return json.JSONDecoder().raw_decode(stdout) -def _error_message(stdout: str) -> str: - """Return the error message logged by the CLI, or a generic one.""" - for line in stdout.splitlines(): +def _error_message(stderr: bytes) -> str: + """Return the error message the CLI logged on stderr, or a generic one.""" + for line in stderr.decode("utf-8", errors="replace").splitlines(): _, marker, message = line.partition(ERROR_MARKER) if marker: return message.strip() or TOO_COMPLEX_ERROR diff --git a/tests/unittests/test_app.py b/tests/unittests/test_app.py index 5daf2a6..b92d5fd 100644 --- a/tests/unittests/test_app.py +++ b/tests/unittests/test_app.py @@ -1,3 +1,4 @@ +import json import logging import subprocess from importlib.metadata import version @@ -6,7 +7,11 @@ from mail_parser_api import app as app_module from mail_parser_api.app import MAX_BODY_BYTES, RATE_LIMIT_REQUESTS -from mail_parser_api.parser import TOO_COMPLEX_ERROR +from mail_parser_api.parser import ( + MAIL_PARSER_COMMAND, + TOO_COMPLEX_ERROR, + ParsedEmail, +) RFC822 = {"Content-Type": "message/rfc822"} @@ -32,6 +37,60 @@ def test_parse_strips_attachment_payloads(client, read_sample): assert all("filename" in attachment for attachment in attachments) +def test_parse_returns_the_mime_tree_beside_an_unchanged_message(client, read_sample): + raw_email = read_sample("mail_test_10") + without_tree = [arg for arg in MAIL_PARSER_COMMAND if arg != "--mime-tree"] + expected = json.loads( + subprocess.run( # noqa: S603 - fixed argv, sample email on stdin + without_tree, input=raw_email, capture_output=True, check=True + ).stdout + ) + for attachment in expected["attachments"]: + del attachment["payload"] + + response = client.post("/api/parse", content=raw_email, headers=RFC822) + + assert response.status_code == 200 + body = response.json() + assert body["message"] == expected + tree = body["mime_tree"] + assert [part["index"] for part in tree] == list(range(9)) + linked = [part["attachment"] for part in tree if part["attachment"] is not None] + assert linked == [0, 1, 2, 3] + assert all(part["cut"] == [] for part in tree) + assert body["mime_tree_parts_left_out"] == 0 + + +def test_email_without_mime_structure_has_one_part(client): + response = client.post("/api/parse", content=b"Subject: x\n\nx", headers=RFC822) + + assert response.status_code == 200 + body = response.json() + assert [part["content_type"] for part in body["mime_tree"]] == ["text/plain"] + assert body["mime_tree_parts_left_out"] == 0 + + +def test_deeply_nested_email_keeps_a_bounded_tree(client): + levels = 600 + opening = "".join( + f'--b{level}\nContent-Type: multipart/mixed; boundary="b{level + 1}"\n\n' + for level in range(levels) + ) + closing = "".join(f"--b{level}--\n" for level in reversed(range(levels + 1))) + raw_email = ( + 'Subject: deep\nContent-Type: multipart/mixed; boundary="b0"\n\n' + f"{opening}--b{levels}\n\nleaf\n{closing}" + ).encode() + + response = client.post("/api/parse", content=raw_email, headers=RFC822) + + assert response.status_code == 200 + body = response.json() + assert len(body["mime_tree"]) == 500 + assert body["mime_tree"][-1]["depth"] == 499 + assert body["mime_tree_parts_left_out"] == levels + 2 - 500 + + def test_parse_accepts_content_type_parameters(client, read_sample): response = client.post( "/api/parse", @@ -99,13 +158,15 @@ def chunks(): def test_parser_failure_returns_422(client, monkeypatch): - stdout = ( - b"2026-01-01 00:00:00,000 | mailparser | __main__ | main | 203 | ERROR " + stderr = ( + b"2026-01-01 00:00:00,000 | mailparser | __main__ | main | 235 | ERROR " b"| An error occurred: boom\nTraceback (most recent call last):\n" ) def fail(*_args, **_kwargs): - return subprocess.CompletedProcess(args=[], returncode=1, stdout=stdout) + return subprocess.CompletedProcess( + args=[], returncode=1, stdout=b"", stderr=stderr + ) monkeypatch.setattr(subprocess, "run", fail) response = client.post("/api/parse", content=b"Subject: x\n\nx", headers=RFC822) @@ -114,6 +175,18 @@ def fail(*_args, **_kwargs): assert response.json() == {"detail": "boom"} +def test_mail_without_tree_returns_422(client, monkeypatch): + def mail_only(*_args, **_kwargs): + return subprocess.CompletedProcess( + args=[], returncode=0, stdout=b'{\n "subject": "x"\n}\n', stderr=b"" + ) + + monkeypatch.setattr(subprocess, "run", mail_only) + response = client.post("/api/parse", content=b"Subject: x\n\nx", headers=RFC822) + + assert response.status_code == 422 + + def test_killed_parser_returns_422_too_complex(client, monkeypatch): def killed(*_args, **_kwargs): return subprocess.CompletedProcess(args=[], returncode=-9, stdout=b"") @@ -137,7 +210,7 @@ def hang(*args, **kwargs): def test_rate_limit_per_forwarded_client(client, monkeypatch): - monkeypatch.setattr(app_module, "parse_email", lambda _raw: {}) + monkeypatch.setattr(app_module, "parse_email", lambda _raw: ParsedEmail({}, [], 0)) first_client = {**RFC822, "X-Forwarded-For": "198.51.100.7"} statuses = [ diff --git a/tests/unittests/test_mime_tree.py b/tests/unittests/test_mime_tree.py new file mode 100644 index 0000000..2c88532 --- /dev/null +++ b/tests/unittests/test_mime_tree.py @@ -0,0 +1,123 @@ +import json + +import pytest + +from mail_parser_api.mime_tree import ( + MAX_MIME_TREE_PARTS, + MAX_MIME_TREE_TEXT, + MAX_STRUCTURE_TEXT, + read_mime_tree, +) + + +def entry(index: int, **values): + return { + "index": index, + "parent": None if index == 0 else 0, + "depth": 0 if index == 0 else 1, + "content_type": "text/plain", + "filename": None, + "size": 1, + "roles": ["body"], + "defects": [], + "recovered": False, + "embedded_headers": None, + **values, + } + + +def read(entries, indent=2): + # The CLI prints the tree after the mail; ``start`` is where the mail ends. + text = '{"subject": "x"}\n' + json.dumps(entries, indent=indent) + "\n" + return read_mime_tree(text, text.index("\n")) + + +def test_whole_tree_is_kept_with_an_empty_cut(): + tree = [entry(0, content_type="multipart/mixed"), entry(1)] + + kept, left_out = read(tree) + + assert kept == [{**part, "cut": []} for part in tree] + assert left_out == 0 + + +@pytest.mark.parametrize("indent", [None, 0, 2]) +def test_any_json_layout_is_read(indent): + kept, left_out = read([entry(0), entry(1)], indent=indent) + + assert [part["index"] for part in kept] == [0, 1] + assert left_out == 0 + + +def test_empty_array_is_an_empty_tree(): + assert read([]) == ([], 0) + + +def test_entries_past_the_limit_are_counted(): + kept, left_out = read([entry(index) for index in range(600)]) + + assert len(kept) == MAX_MIME_TREE_PARTS + assert [part["index"] for part in kept] == list(range(MAX_MIME_TREE_PARTS)) + assert left_out == 100 + + +def test_long_value_is_cut_and_named(): + kept, _ = read([entry(0, filename="a" * 5000)]) + + assert kept[0]["filename"] == "a" * MAX_STRUCTURE_TEXT + assert kept[0]["cut"] == ["filename"] + + +def test_value_at_the_bound_is_not_cut(): + kept, _ = read([entry(0, filename="a" * MAX_STRUCTURE_TEXT)]) + + assert kept[0]["cut"] == [] + + +def test_embedded_headers_are_cut_and_named(): + headers = {"from": "a@example.com", "subject": "s" * 2000, "date": None} + + kept, _ = read([entry(0, embedded_headers=headers)]) + + assert kept[0]["embedded_headers"] == { + "from": "a@example.com", + "subject": "s" * MAX_STRUCTURE_TEXT, + "date": None, + } + assert kept[0]["cut"] == ["embedded_headers.subject"] + + +def test_control_characters_are_kept_as_declared(): + name = "invoice‮fdp.exe\x1b[2J" + + kept, _ = read([entry(0, filename=name)]) + + assert kept[0]["filename"] == name + + +def test_text_bound_keeps_a_prefix_and_counts_the_rest(): + # 10 characters of content_type plus 1000 of filename: 1010 per entry. + tree = [entry(index, filename="f" * 1000) for index in range(300)] + fitting = MAX_MIME_TREE_TEXT // 1010 + + kept, left_out = read([*tree, entry(300)]) + + assert len(kept) == fitting + # A short entry after the first one left out is left out too. + assert left_out == len(tree) + 1 - fitting + + +@pytest.mark.parametrize( + "text", + [ + pytest.param("", id="nothing"), + pytest.param("{}", id="object"), + pytest.param("[1]", id="entry-not-an-object"), + pytest.param('[{"index": 0}', id="not-closed"), + pytest.param('[{"index": 0} {"index": 1}]', id="no-comma"), + pytest.param('[{"index": 0},]', id="trailing-comma"), + ], +) +def test_malformed_tree_raises(text): + with pytest.raises(ValueError): # noqa: PT011 - every malformed shape + read_mime_tree(text, 0) diff --git a/tests/unittests/test_parser.py b/tests/unittests/test_parser.py index 3185896..0f2ebed 100644 --- a/tests/unittests/test_parser.py +++ b/tests/unittests/test_parser.py @@ -8,36 +8,73 @@ LINUX_CHILD_LIMITS, MAIL_PARSER_COMMAND, TOO_COMPLEX_ERROR, + ParsedEmail, ParseError, parse_email, ) +TREE = b'[\n {\n "index": 0,\n "parent": null\n }\n]\n' -def completed(returncode: int, stdout: bytes): + +def completed(returncode: int, stdout: bytes, stderr: bytes = b""): def run(*_args, **_kwargs): return subprocess.CompletedProcess( - args=[], returncode=returncode, stdout=stdout + args=[], returncode=returncode, stdout=stdout, stderr=stderr ) return run -def test_log_lines_before_json_are_skipped(monkeypatch): - stdout = b'2026-01-01 | mailparser | ERROR | Failed\n{\n "subject": "hi"\n}\n' +def test_both_documents_are_returned(monkeypatch): + stdout = b'{\n "subject": "hi"\n}\n' + TREE monkeypatch.setattr(subprocess, "run", completed(0, stdout)) - assert parse_email(b"raw") == {"subject": "hi"} + assert parse_email(b"raw") == ParsedEmail( + message={"subject": "hi"}, + mime_tree=[{"index": 0, "parent": None, "cut": []}], + mime_tree_parts_left_out=0, + ) + + +def test_attachment_payloads_are_removed(monkeypatch): + stdout = b'{"attachments": [{"filename": "a", "payload": "QQ=="}]}\n' + TREE + monkeypatch.setattr(subprocess, "run", completed(0, stdout)) + assert parse_email(b"raw").message == {"attachments": [{"filename": "a"}]} -def test_output_without_json_is_a_parse_error(monkeypatch): - monkeypatch.setattr(subprocess, "run", completed(0, b"no json here\n")) + +@pytest.mark.parametrize( + "stdout", + [ + pytest.param(b"no json here\n", id="no-json"), + pytest.param(b"log line\n{\n}\n" + TREE, id="text-before-the-mail"), + pytest.param(b"{\n trunc", id="truncated-mail"), + pytest.param(b'{\n "subject": "hi"\n}\n', id="missing-tree"), + pytest.param(b'{\n}\n[\n {\n "index": 0', id="truncated-tree"), + pytest.param(b"{\n}\n{\n}\n", id="tree-not-an-array"), + ], +) +def test_output_without_both_documents_is_a_parse_error(monkeypatch, stdout): + monkeypatch.setattr(subprocess, "run", completed(0, stdout)) with pytest.raises(ParseError, match=GENERIC_ERROR): parse_email(b"raw") +def test_failure_reports_the_error_logged_on_stderr(monkeypatch): + stderr = ( + b"2026-01-01 00:00:00,000 | mailparser | __main__ | main | 235 | ERROR " + b"| An error occurred: boom\nTraceback (most recent call last):\n" + ) + # 4.12.0 prints the mail before it fails on the tree; it is not used. + monkeypatch.setattr(subprocess, "run", completed(1, b"{\n}\n", stderr)) + + with pytest.raises(ParseError, match=r"^boom$"): + parse_email(b"raw") + + def test_failure_without_error_line_uses_generic_message(monkeypatch): - monkeypatch.setattr(subprocess, "run", completed(1, b"")) + monkeypatch.setattr(subprocess, "run", completed(1, b"", b"Traceback\n")) with pytest.raises(ParseError, match=GENERIC_ERROR): parse_email(b"raw") @@ -45,32 +82,30 @@ def test_failure_without_error_line_uses_generic_message(monkeypatch): def test_failure_with_empty_error_message_is_too_complex(monkeypatch): # A MemoryError has no text, so the CLI logs an empty error message. - stdout = b"2026-01-01 | mailparser | ERROR | An error occurred: \nTraceback\n" - monkeypatch.setattr(subprocess, "run", completed(1, stdout)) + stderr = b"2026-01-01 | mailparser | ERROR | An error occurred: \nTraceback\n" + monkeypatch.setattr(subprocess, "run", completed(1, b"{\n}\n", stderr)) with pytest.raises(ParseError, match=TOO_COMPLEX_ERROR): parse_email(b"raw") -def test_json_at_start_is_parsed_and_trailing_output_ignored(monkeypatch): - stdout = b'{\n "subject": "hi"\n}\ntrailer\n' - monkeypatch.setattr(subprocess, "run", completed(0, stdout)) - - assert parse_email(b"raw") == {"subject": "hi"} +def test_error_line_on_stdout_is_not_read(monkeypatch): + stdout = b"2026-01-01 | mailparser | ERROR | An error occurred: boom\n" + monkeypatch.setattr(subprocess, "run", completed(1, stdout)) + with pytest.raises(ParseError, match=GENERIC_ERROR): + parse_email(b"raw") -def test_log_line_ending_with_a_brace_is_skipped(monkeypatch): - stdout = b'2026-01-01 | ERROR | bad {\n{\n "subject": "hi"\n}\n' - monkeypatch.setattr(subprocess, "run", completed(0, stdout)) - assert parse_email(b"raw") == {"subject": "hi"} +def test_killed_child_is_too_complex(monkeypatch): + monkeypatch.setattr(subprocess, "run", completed(-9, b"")) + with pytest.raises(ParseError, match=TOO_COMPLEX_ERROR): + parse_email(b"raw") -def test_truncated_json_is_a_parse_error(monkeypatch): - monkeypatch.setattr(subprocess, "run", completed(0, b"log\n{\n trunc")) - with pytest.raises(ParseError, match=GENERIC_ERROR): - parse_email(b"raw") +def test_command_asks_for_the_mime_tree(): + assert "--mime-tree" in MAIL_PARSER_COMMAND @pytest.mark.parametrize( @@ -85,7 +120,9 @@ def test_child_limits_wrap_the_command_only_on_linux(monkeypatch, platform, expe def record(args, **_kwargs): calls.append(args) - return subprocess.CompletedProcess(args=args, returncode=0, stdout=b"{\n}\n") + return subprocess.CompletedProcess( + args=args, returncode=0, stdout=b"{\n}\n" + TREE, stderr=b"" + ) monkeypatch.setattr(sys, "platform", platform) monkeypatch.setattr(subprocess, "run", record) diff --git a/uv.lock b/uv.lock index f056142..a113e89 100644 --- a/uv.lock +++ b/uv.lock @@ -551,11 +551,11 @@ wheels = [ [[package]] name = "mail-parser" -version = "4.11.0" +version = "4.12.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/95/b9/743e3c677f2adcd93b2a5739663f549d22506edced9e6d9416e9b6fd8f90/mail_parser-4.11.0.tar.gz", hash = "sha256:8bb90074f07a881f362e2d2cff75181cf85696ce6aff4b27f2604040c13d13b5", size = 3012705, upload-time = "2026-11-15T11:48:12.705Z" } +sdist = { url = "https://files.pythonhosted.org/packages/4b/e3/aa9c2dd7e2e721127ccb535d1ea4a40ab091c10da0ad5183e3c2aa96bd1a/mail_parser-4.12.0.tar.gz", hash = "sha256:bc951306315812c3366fc1e374e5619dd8f6c6d3bb0202b503a38ee6ff629209", size = 3072848, upload-time = "2026-11-26T16:54:55.822Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a7/9a/294765f556d0799893892a9011221e1e05d4471a6e4f18792f9c8d04186d/mail_parser-4.11.0-py3-none-any.whl", hash = "sha256:adb466cd96cfccc0ab2fc52e571565afa5073a85b47ea12037b2b98057a7a5f0", size = 71355, upload-time = "2026-11-15T11:48:11.427Z" }, + { url = "https://files.pythonhosted.org/packages/f3/f6/5004ce62eaef284b0de2839fb525b82167174d5a1a0bf3f2cefba316fab6/mail_parser-4.12.0-py3-none-any.whl", hash = "sha256:72889835e2748aec48a38308969ad2ef1f8c0a3f8f0f3b9af17098e430d7ff64", size = 89761, upload-time = "2026-11-26T16:54:54.79Z" }, ] [package.optional-dependencies] @@ -585,7 +585,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "fastapi", specifier = ">=0.115.0" }, - { name = "mail-parser", extras = ["outlook"], specifier = ">=4.11.0" }, + { name = "mail-parser", extras = ["outlook"], specifier = ">=4.12.0" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0" }, ] @@ -637,7 +637,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorclass" }, { name = "easygui" }, - { name = "msoffcrypto-tool", marker = "(platform_python_implementation != 'PyPy' and sys_platform == 'darwin') or (platform_python_implementation != 'PyPy' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" }, + { name = "msoffcrypto-tool", marker = "platform_python_implementation != 'PyPy' or (sys_platform != 'darwin' and sys_platform != 'win32')" }, { name = "olefile" }, { name = "pcodedmp" }, { name = "pyparsing" }, From be90c5a8c5a545dae416d3883c4752ce2881e475 Mon Sep 17 00:00:00 2001 From: Fedele Mantuano Date: Fri, 27 Nov 2026 11:35:17 +0100 Subject: [PATCH 4/5] fix: never decode the whole CLI output to text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decoding all of stdout into one str let a single character outside the BMP (Subject: 😀) store the whole output at four bytes per character. With --mime-tree, 0.6 MB of input prints about 35 MB, so the server held about six times that, and two concurrent emails of 85,000 parts got uvicorn (PID 1) OOM-killed in a 512 MiB container. The mail and each kept tree entry are now decoded from their own slice of the bytes, found in the indent=2 layout the CLI prints; entries past the bounds are only found and counted. Any other layout is unparsable output (422). The same replay keeps PID 1 alive. --- docs/features/message-structure/spec.md | 21 +++++-- src/mail_parser_api/mime_tree.py | 77 +++++++++++++++---------- src/mail_parser_api/parser.py | 27 +++++---- tests/unittests/test_mime_tree.py | 53 ++++++++++++----- tests/unittests/test_parser.py | 28 ++++++++- 5 files changed, 144 insertions(+), 62 deletions(-) diff --git a/docs/features/message-structure/spec.md b/docs/features/message-structure/spec.md index b30fdc4..47a777b 100644 --- a/docs/features/message-structure/spec.md +++ b/docs/features/message-structure/spec.md @@ -141,10 +141,17 @@ parts, by counting them first. This service cannot: the CLI builds the whole tree in the child before anything is printed. The child's limits stay the guard here, and such a message fails as too complex. -The service decodes the entries of the array one at a time and keeps only -those inside the bounds; the others are counted and dropped as soon as they -are decoded. Decoding the whole array first would hold up to 55 MiB of -objects per parse in uvicorn (PID 1), with two parses at once. +stdout is never decoded to text as a whole. The service decodes the mail, +then each kept entry of the tree, from its own slice of the bytes; past the +bounds it only finds where entries end and counts them. The slices are found +in the layout the CLI prints (`indent=2`: the mail closes with the only `}` +at column 0, an entry with the only `}` at column 2, and no JSON string +holds a raw line break); any other layout is unparsable output. Security +review, 2026-11-27: decoding all of stdout made one character outside the +BMP (`Subject: 😀`) store the whole str at four bytes per character, about +six times stdout in uvicorn (PID 1), and two concurrent 85,000-part emails +got the container OOM-killed. With the slices the same sequence keeps PID 1 +alive; under that load the kernel kills children, which answer `422`. ## Measurements (2026-11-27) @@ -168,8 +175,10 @@ service runs it: `choom -n 1000 -- prlimit --as=201326592 --`, - Without `--mime-tree` the same cap passes about 250,000 empty parts: the tree lowers the limit to about 90,000. - The largest tree that passes is 29 to 37 MB of JSON, about 420 bytes per - entry. Holding and decoding it in the parent peaks at 125 MiB; two such - parses at once peaked at 411 MiB in the container, without uvicorn. + entry. Holding it and decoding all of it at once, ASCII only, peaked at + 125 MiB in the parent; two such parses at once peaked at 411 MiB in the + container, without uvicorn. The service no longer decodes it at once (see + above). - Nesting fails with `MailParserRecursionError` with or without `--mime-tree`; it is a limit of the parse, not of the tree. - No lone surrogate reached stdout: the CLI writes UTF-8 with diff --git a/src/mail_parser_api/mime_tree.py b/src/mail_parser_api/mime_tree.py index 9a8a8a2..24e3555 100644 --- a/src/mail_parser_api/mime_tree.py +++ b/src/mail_parser_api/mime_tree.py @@ -25,18 +25,22 @@ million characters, and a control character takes six bytes in JSON. """ -_NOT_WHITESPACE = re.compile(r"[^ \t\n\r]") +# The CLI prints the tree with ``indent=2``: an entry of the array opens and +# closes at column 2, its nested ``embedded_headers`` closes at column 4, and +# no JSON string holds a raw line break. So this marks the end of an entry. +_ENTRY_CLOSE = b"\n }" +_NOT_WHITESPACE = re.compile(rb"[^ \t\n\r]") -def read_mime_tree(text: str, start: int) -> tuple[list[dict[str, Any]], int]: - """Decode the JSON array of the MIME tree and keep its bounded prefix. +def read_mime_tree(output: bytes, start: int) -> tuple[list[dict[str, Any]], int]: + """Decode the MIME tree the CLI printed and keep its bounded prefix. - Entries are decoded one at a time: those past the bounds are counted and - dropped as soon as they are decoded, so the memory held does not grow - with the number of parts the sender chose. + The output is never decoded as a whole: one non-BMP character would make + Python store all of it at four bytes per character. Only the kept entries + are decoded, one at a time; the others are found and counted. Args: - text: The CLI output. + output: The CLI stdout. start: Where the array may start, after optional whitespace. Returns: @@ -44,15 +48,16 @@ def read_mime_tree(text: str, start: int) -> tuple[list[dict[str, Any]], int]: with ``cut``, and the number of entries not kept. Raises: - ValueError: The text at ``start`` is not a JSON array of objects. + ValueError: The bytes at ``start`` are not the indented JSON array of + objects the CLI prints. """ kept: list[dict[str, Any]] = [] left_out = 0 characters = 0 - for entry in _entries(text, start): + for begin, end in _entry_spans(output, start): if not left_out and len(kept) < MAX_MIME_TREE_PARTS: - part = _bounded_part(entry) + part = _bounded_part(_decode_entry(output[begin:end])) characters += _text_length(part) if characters <= MAX_MIME_TREE_TEXT: kept.append(part) @@ -61,40 +66,50 @@ def read_mime_tree(text: str, start: int) -> tuple[list[dict[str, Any]], int]: return kept, left_out -def _entries(text: str, start: int) -> Iterator[dict[str, Any]]: - """Yield the objects of the JSON array at ``start``, one at a time. +def _entry_spans(output: bytes, start: int) -> Iterator[tuple[int, int]]: + """Yield where each entry of the indented array at ``start`` begins and ends. Raises: - ValueError: The text is not a closed JSON array of objects. + ValueError: The bytes are not a closed, indented JSON array of objects. """ - decoder = json.JSONDecoder() - position = _skip_whitespace(text, start) - if not text.startswith("[", position): + position = _skip_whitespace(output, start) + if not output.startswith(b"[", position): message = "the MIME tree is not a JSON array" raise ValueError(message) - position = _skip_whitespace(text, position + 1) - if text.startswith("]", position): + position = _skip_whitespace(output, position + 1) + if output.startswith(b"]", position): return while True: - entry, position = decoder.raw_decode(text, position) - if not isinstance(entry, dict): - message = "a MIME tree entry is not a JSON object" - raise ValueError(message) # noqa: TRY004 - malformed output, not a type - yield entry - position = _skip_whitespace(text, position) - if text.startswith("]", position): + close = output.find(_ENTRY_CLOSE, position) + if not output.startswith(b"{", position) or close < 0: + message = "a MIME tree entry is not an indented JSON object" + raise ValueError(message) + end = close + len(_ENTRY_CLOSE) + yield position, end + position = _skip_whitespace(output, end) + if output.startswith(b"]", position): return - if not text.startswith(",", position): + if not output.startswith(b",", position): message = "the MIME tree array is not closed" raise ValueError(message) - position = _skip_whitespace(text, position + 1) + position = _skip_whitespace(output, position + 1) + + +def _skip_whitespace(output: bytes, position: int) -> int: + """Return the position of the next non-whitespace byte, or the end.""" + match = _NOT_WHITESPACE.search(output, position) + return match.start() if match else len(output) + +def _decode_entry(entry: bytes) -> dict[str, Any]: + """Decode one entry, whose bytes start with ``{``. -def _skip_whitespace(text: str, position: int) -> int: - """Return the position of the next non-whitespace character, or the end.""" - match = _NOT_WHITESPACE.search(text, position) - return match.start() if match else len(text) + Raises: + ValueError: The bytes are not one complete JSON object. + + """ + return json.loads(entry.decode("utf-8", errors="replace")) def _bounded_part(entry: dict[str, Any]) -> dict[str, Any]: diff --git a/src/mail_parser_api/parser.py b/src/mail_parser_api/parser.py index 63cb0a9..a652bdc 100644 --- a/src/mail_parser_api/parser.py +++ b/src/mail_parser_api/parser.py @@ -109,10 +109,9 @@ def parse_email(raw_email: bytes) -> ParsedEmail: if completed.returncode != 0: raise ParseError(_error_message(completed.stderr)) - stdout = completed.stdout.decode("utf-8", errors="replace") try: - message, end = _decode_message(stdout) - mime_tree, parts_left_out = read_mime_tree(stdout, end) + message, end = _decode_message(completed.stdout) + mime_tree, parts_left_out = read_mime_tree(completed.stdout, end) except ValueError as error: raise ParseError(GENERIC_ERROR) from error for attachment in message.get("attachments", []): @@ -127,20 +126,28 @@ def _command() -> tuple[str, ...]: return MAIL_PARSER_COMMAND -def _decode_message(stdout: str) -> tuple[dict[str, Any], int]: +# The CLI prints the mail with ``indent=2`` and a line break: its closing brace +# is the only one at column 0, and no JSON string holds a raw line break. +MESSAGE_END = b"\n}\n" + + +def _decode_message(stdout: bytes) -> tuple[dict[str, Any], int]: """Return the mail JSON object that starts stdout and where it ends. - It is decoded in place, without copying the output, to keep the memory of - large results low. + Only the mail is decoded to text. The MIME tree after it can be tens of + megabytes, and decoding all of stdout at once would hold it at up to four + bytes per character in the server. Raises: - ValueError: stdout does not start with a JSON object. + ValueError: stdout does not start with the indented mail object. """ - if not stdout.startswith("{"): - message = "the output does not start with a JSON object" + line_break = stdout.find(MESSAGE_END) + if not stdout.startswith(b"{") or line_break < 0: + message = "the output does not start with the mail JSON object" raise ValueError(message) - return json.JSONDecoder().raw_decode(stdout) + end = line_break + len(b"\n}") + return json.loads(stdout[:end].decode("utf-8", errors="replace")), end def _error_message(stderr: bytes) -> str: diff --git a/tests/unittests/test_mime_tree.py b/tests/unittests/test_mime_tree.py index 2c88532..7385567 100644 --- a/tests/unittests/test_mime_tree.py +++ b/tests/unittests/test_mime_tree.py @@ -26,10 +26,17 @@ def entry(index: int, **values): } -def read(entries, indent=2): - # The CLI prints the tree after the mail; ``start`` is where the mail ends. - text = '{"subject": "x"}\n' + json.dumps(entries, indent=indent) + "\n" - return read_mime_tree(text, text.index("\n")) +def printed(entries, indent=2) -> bytes: + # As the CLI prints it: the mail, then the tree, both indented. + mail = json.dumps({"subject": "x"}, indent=2) + tree = json.dumps(entries, ensure_ascii=False, indent=indent) + return f"{mail}\n{tree}\n".encode() + + +def read(entries): + output = printed(entries) + # ``start`` is where the mail ends, after its closing brace. + return read_mime_tree(output, output.index(b"\n}\n") + 2) def test_whole_tree_is_kept_with_an_empty_cut(): @@ -41,12 +48,26 @@ def test_whole_tree_is_kept_with_an_empty_cut(): assert left_out == 0 -@pytest.mark.parametrize("indent", [None, 0, 2]) -def test_any_json_layout_is_read(indent): - kept, left_out = read([entry(0), entry(1)], indent=indent) +@pytest.mark.parametrize("indent", [None, 0, 4]) +def test_tree_not_indented_as_the_cli_prints_it_raises(indent): + output = printed([entry(0), entry(1)], indent=indent) - assert [part["index"] for part in kept] == [0, 1] - assert left_out == 0 + with pytest.raises(ValueError): # noqa: PT011 - every other layout + read_mime_tree(output, output.index(b"\n}\n") + 2) + + +def test_non_ascii_values_are_decoded(): + kept, _ = read([entry(0, filename="fattura-\U0001f600-è.pdf")]) + + assert kept[0]["filename"] == "fattura-\U0001f600-è.pdf" + + +def test_invalid_utf8_is_replaced(): + output = printed([entry(0, filename="NAME")]).replace(b"NAME", b"a\xffb") + + kept, _ = read_mime_tree(output, output.index(b"\n}\n") + 2) + + assert kept[0]["filename"] == "a\ufffdb" def test_empty_array_is_an_empty_tree(): @@ -112,12 +133,16 @@ def test_text_bound_keeps_a_prefix_and_counts_the_rest(): [ pytest.param("", id="nothing"), pytest.param("{}", id="object"), - pytest.param("[1]", id="entry-not-an-object"), - pytest.param('[{"index": 0}', id="not-closed"), - pytest.param('[{"index": 0} {"index": 1}]', id="no-comma"), - pytest.param('[{"index": 0},]', id="trailing-comma"), + pytest.param("[\n 1\n]", id="entry-not-an-object"), + pytest.param('[\n {\n "index": 0', id="entry-not-closed"), + pytest.param('[\n {\n "index": 0\n }', id="array-not-closed"), + pytest.param('[\n {\n "index": 0,\n }\n]', id="invalid-entry"), + pytest.param( + '[\n {\n "index": 0\n } {\n "index": 1\n }\n]', id="no-comma" + ), + pytest.param('[\n {\n "index": 0\n },\n]', id="trailing-comma"), ], ) def test_malformed_tree_raises(text): with pytest.raises(ValueError): # noqa: PT011 - every malformed shape - read_mime_tree(text, 0) + read_mime_tree(text.encode(), 0) diff --git a/tests/unittests/test_parser.py b/tests/unittests/test_parser.py index 0f2ebed..e7e92ab 100644 --- a/tests/unittests/test_parser.py +++ b/tests/unittests/test_parser.py @@ -1,5 +1,7 @@ +import json import subprocess import sys +import tracemalloc import pytest @@ -37,16 +39,40 @@ def test_both_documents_are_returned(monkeypatch): def test_attachment_payloads_are_removed(monkeypatch): - stdout = b'{"attachments": [{"filename": "a", "payload": "QQ=="}]}\n' + TREE + mail = {"attachments": [{"filename": "a", "payload": "QQ=="}]} + stdout = json.dumps(mail, indent=2).encode() + b"\n" + TREE monkeypatch.setattr(subprocess, "run", completed(0, stdout)) assert parse_email(b"raw").message == {"attachments": [{"filename": "a"}]} +def test_large_tree_with_a_non_bmp_character_is_not_decoded_whole(monkeypatch): + # One character outside the BMP would make a str of all of stdout take + # four bytes per character: about six times stdout, in the server. + entries = [ + {"index": index, "filename": "\U0001f600" if index == 0 else "a" * 100} + for index in range(50_000) + ] + tree = json.dumps(entries, ensure_ascii=False, indent=2).encode() + stdout = b'{\n "subject": "\xf0\x9f\x98\x80"\n}\n' + tree + b"\n" + monkeypatch.setattr(subprocess, "run", completed(0, stdout)) + + tracemalloc.start() + try: + parsed = parse_email(b"raw") + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + + assert parsed.mime_tree_parts_left_out == 50_000 - 500 + assert peak < len(stdout) // 4 + + @pytest.mark.parametrize( "stdout", [ pytest.param(b"no json here\n", id="no-json"), + pytest.param(b'{"subject": "hi"}\n' + TREE, id="mail-not-indented"), pytest.param(b"log line\n{\n}\n" + TREE, id="text-before-the-mail"), pytest.param(b"{\n trunc", id="truncated-mail"), pytest.param(b'{\n "subject": "hi"\n}\n', id="missing-tree"), From c2e35632a5ef22e8b8b3181d41b9323c2a9890d0 Mon Sep 17 00:00:00 2001 From: Fedele Mantuano Date: Fri, 27 Nov 2026 16:43:28 +0100 Subject: [PATCH 5/5] fix: cap the CLI output at 16 MiB message had no bound: JSON prints a control character as six bytes and a value can appear more than once (to, then raw and candidates of its address defect). 5 MB of control characters in the body or in the Received headers made a 30 MB response and held about 114 MiB in uvicorn per parse; 3 MB in a Content-Type parameter made 18 MB. The CLI now writes stdout to an anonymous temporary file in /tmp, which prlimit --fsize caps at 16 MiB in the container, and the size is checked after the child exits on every platform. An email that reaches the cap gets 422 with TOO_COMPLEX_ERROR; message is whole or absent, never cut. A real 5 MB email prints 5 to 7 MB. The largest MIME tree that passes drops from about 70,000 parts to about 35,000. Replayed on Linux with the service limits: the attack emails get 422 and uvicorn stays below 60 MiB, against 229 MiB before. --- README.md | 13 ++- .../issues/01-return-the-mime-tree.md | 8 +- docs/features/message-structure/spec.md | 62 +++++++++---- src/mail_parser_api/parser.py | 78 +++++++++++----- tests/unittests/conftest.py | 26 ++++++ tests/unittests/test_app.py | 39 ++++---- tests/unittests/test_parser.py | 91 +++++++++++-------- 7 files changed, 214 insertions(+), 103 deletions(-) diff --git a/README.md b/README.md index 9b0007d..9533312 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,8 @@ The tree is bounded, and nothing is dropped silently: 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. +tree is whole. `message` is never cut: it is whole or the request fails +(see the output cap below). | Status | When | Body | | ------ | ------------------------------------------------------------ | --------------------------------------------------- | @@ -105,8 +106,14 @@ the reverse proxy does not expose it. (`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`. Measured with - mail-parser 4.12.0, the limit falls between 68,000 and 90,000 MIME parts, - or past 970 levels of nesting; a 5 MB email of base64 attachments passes. + 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 diff --git a/docs/features/message-structure/issues/01-return-the-mime-tree.md b/docs/features/message-structure/issues/01-return-the-mime-tree.md index 042868e..18ec921 100644 --- a/docs/features/message-structure/issues/01-return-the-mime-tree.md +++ b/docs/features/message-structure/issues/01-return-the-mime-tree.md @@ -33,9 +33,12 @@ brings the security fixes made since 4.11.0. - 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. -- Failing above about 70,000 parts is acceptable; the service counts no +- 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: 68,000 tiny parts, 88,000 empty parts and + "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. @@ -48,6 +51,7 @@ brings the security fixes made since 4.11.0. `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 diff --git a/docs/features/message-structure/spec.md b/docs/features/message-structure/spec.md index 47a777b..8173c5c 100644 --- a/docs/features/message-structure/spec.md +++ b/docs/features/message-structure/spec.md @@ -98,9 +98,9 @@ attachments, because entries are removed from none of them. text chosen by the sender. This service passes it on as JSON and does not interpret it. It never reaches a log line. 1. The tree grows with the number of MIME parts, which the sender - chooses. The child's limits bound what it can print (see - [Measurements](#measurements-2026-11-27)); the cut below bounds the - response. + chooses, and `message` grows with what the sender writes. The output cap + below bounds what the child can print, both documents together; the cut + below bounds the tree in the response. 1. Errors are read from stderr. The detail of a `422` is the text after `An error occurred:` on stderr, `TOO_COMPLEX_ERROR` when that text is empty (a `MemoryError` has none), the generic error otherwise. stdout @@ -134,7 +134,29 @@ that the live parser page and MailXRay read one shape: Decided on 2026-11-27: `message` is not cut. MailXRay also keeps only the first 100 `received_header_defects`; this service does not, because -`message` stays what mail-parser prints. +`message` stays what mail-parser prints. It is bounded as a whole instead, +by the output cap. + +## Output cap + +Decided with the owner on 2026-11-27, after the security review: the CLI +may print at most 16 MiB (`CHILD_OUTPUT_BYTES`), the mail and the tree +together. An email that reaches it fails with `422` and +`TOO_COMPLEX_ERROR`; `message` is whole or absent, never cut. + +- Why: a control character prints as six bytes (`\u0001`), and a value can + appear more than once in `message` (`to`, then `raw` and `candidates` of + its address defect). 5 MB of control characters in the body or in the + `Received` headers made a 30 MB response and held about 114 MiB in + uvicorn per parse; 3 MB in one `Content-Type` parameter made 18 MB. +- How: stdout goes to an anonymous temporary file in `/tmp` (a tmpfs in + the container), and on Linux `prlimit --fsize` makes the kernel refuse + writes past the cap, so the child stops there. Its size is checked after + the child exits on every platform. +- Cost: a real 5 MB email prints 5 to 7 MB, payloads of attachments + included, which the service removes afterwards. The tree is the other + cost: about 420 bytes per part, so the largest tree that passes drops + from about 70,000 parts to about 35,000 (see the measurements). MailXRay also refuses to build the tree of a message with more than 50,000 parts, by counting them first. This service cannot: the CLI builds the whole @@ -158,34 +180,38 @@ alive; under that load the kernel kills children, which answer `422`. Docker on Apple silicon, `python:3.13-slim` (3.13.18, aarch64), `mail-parser[outlook]==4.12.0`, a 512 MiB container, the child run as the service runs it: `choom -n 1000 -- prlimit --as=201326592 --`, -`--json --mime-tree`, 10-second timeout. +`--json --mime-tree`, 10-second timeout. The rows of parts are those of the +16 MiB output cap (`prlimit --fsize`); without it the address-space cap +alone passed 88,000 empty and 68,000 tiny parts. | Email | Result | | ----------------------------------------- | ----------------------------------------- | -| N empty parts (5 bytes each) | passes up to 88,000; 91,000 and more fail | -| N tiny `text/plain` parts (32 bytes each) | passes up to 68,000; 70,000 and more fail | +| N empty parts (5 bytes each) | passes up to 40,000; 50,000 and more fail | +| N tiny `text/plain` parts (32 bytes each) | passes up to 34,000; 36,000 and more fail | | 5 MiB, one base64 attachment | passes, 60.5 MiB child peak, as `--json` | | 5 MiB, twenty base64 attachments | passes, 52.4 MiB child peak, as `--json` | | multipart nested N levels | passes up to 970; 980 and more fail | -- Above the limit the child fails with `MemoryError` while printing the - tree: exit code 1, the first document complete on stdout, nothing of the - tree. That is unparsable output, a `422` with `TOO_COMPLEX_ERROR`. No run - was killed and none came closer than 6.5 seconds to the timeout. +- Above the limit the child reaches the output cap and answers `422` with + `TOO_COMPLEX_ERROR` in under 1.5 seconds. Without the output cap it + failed with `MemoryError` while printing the tree, the first document + complete on stdout. No run was killed and none came closer than 6.5 + seconds to the timeout. +- With the output cap, uvicorn held at most 42 MiB per parse in every run, + the 5 MB emails of control characters included. - Without `--mime-tree` the same cap passes about 250,000 empty parts: the tree lowers the limit to about 90,000. -- The largest tree that passes is 29 to 37 MB of JSON, about 420 bytes per - entry. Holding it and decoding all of it at once, ASCII only, peaked at - 125 MiB in the parent; two such parses at once peaked at 411 MiB in the - container, without uvicorn. The service no longer decodes it at once (see - above). +- Without the output cap the largest tree that passed was 29 to 37 MB of + JSON, about 420 bytes per entry. Holding it and decoding all of it at + once, ASCII only, peaked at 125 MiB in the parent; two such parses at + once peaked at 411 MiB in the container, without uvicorn. - Nesting fails with `MailParserRecursionError` with or without `--mime-tree`; it is a limit of the parse, not of the tree. - No lone surrogate reached stdout: the CLI writes UTF-8 with `ensure_ascii=False`, and undecodable bytes in tree values arrive as U+FFFD. -Decision (owner, 2026-11-27): failing above about 70,000 parts is +Decision (owner, 2026-11-27): failing above about 35,000 parts is acceptable for the page; no count of our own before the parse. ## Acceptance @@ -200,6 +226,8 @@ acceptable for the page; no count of our own before the parse. 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. +1. Output that reaches 16 MiB yields `422` with `TOO_COMPLEX_ERROR`, and + the Linux child limits include `--fsize`. 1. A failing CLI whose stderr has `An error occurred: ` yields `422` with ``, and with `TOO_COMPLEX_ERROR` when the text is empty. 1. README endpoint contract updated with the new keys and the table above. diff --git a/src/mail_parser_api/parser.py b/src/mail_parser_api/parser.py index a652bdc..847414c 100644 --- a/src/mail_parser_api/parser.py +++ b/src/mail_parser_api/parser.py @@ -1,9 +1,11 @@ """Run the mail-parser CLI in a subprocess and shape its JSON output.""" import json +import os import signal import subprocess import sys +import tempfile from dataclasses import dataclass from typing import Any @@ -15,6 +17,12 @@ # header-heavy ones that would grow past it fail with MemoryError instead. CHILD_ADDRESS_SPACE_BYTES = 192 * 1024 * 1024 +# Bytes the CLI may print, mail and MIME tree together. A real 5 MB email prints +# 5 to 7 MB, attachment payloads included; a control character prints as six +# (``\u0001``), so 5 MB of them would make a 30 MB response. An email that +# reaches the cap fails as too complex. +CHILD_OUTPUT_BYTES = 16 * 1024 * 1024 + # The installed mail-parser CLI, run with the same interpreter as the service. # It prints the mail, then the MIME tree, as two JSON documents on stdout; its # log lines go to stderr, and ``--log-level ERROR`` keeps only the errors. @@ -31,8 +39,10 @@ # On Linux (the container) util-linux tools set the child limits before exec: # ``choom`` makes the kernel kill the child, never uvicorn (PID 1), when memory -# runs out, and ``prlimit`` caps the memory of one parse. ``preexec_fn`` is -# avoided because the parse runs in a worker thread. macOS has neither tool. +# runs out, and ``prlimit`` caps the memory of one parse and the size of the +# file its stdout is written to. ``preexec_fn`` is avoided because the parse +# runs in a worker thread. macOS has neither tool: there the output is checked +# only after the child exits. LINUX_CHILD_LIMITS = ( "choom", "-n", @@ -40,13 +50,15 @@ "--", "prlimit", f"--as={CHILD_ADDRESS_SPACE_BYTES}", + f"--fsize={CHILD_OUTPUT_BYTES}", "--", ) # Prefix of the line the CLI logs on stderr when parsing fails. ERROR_MARKER = "An error occurred: " GENERIC_ERROR = "mail-parser could not parse the email" -# The child was killed by the kernel or logged a MemoryError, which has no text. +# The child was killed by the kernel, logged a MemoryError, which has no text, +# or reached the output cap. TOO_COMPLEX_ERROR = "email too complex to parse within the service limits" @@ -88,30 +100,16 @@ def parse_email(raw_email: bytes) -> ParsedEmail: The message and the MIME tree of the email. Raises: - ParseError: mail-parser exited with an error or did not print both - JSON documents. + ParseError: mail-parser exited with an error, printed + ``CHILD_OUTPUT_BYTES`` or more, or did not print both JSON + documents. ParseTimeoutError: mail-parser ran longer than the timeout and was killed. """ + stdout = _run_cli(raw_email) try: - completed = subprocess.run( # noqa: S603 - fixed argv, email on stdin - _command(), - input=raw_email, - capture_output=True, - timeout=PARSE_TIMEOUT_SECONDS, - check=False, - ) - except subprocess.TimeoutExpired as error: - raise ParseTimeoutError from error - - if completed.returncode == -signal.SIGKILL: - raise ParseError(TOO_COMPLEX_ERROR) - if completed.returncode != 0: - raise ParseError(_error_message(completed.stderr)) - - try: - message, end = _decode_message(completed.stdout) - mime_tree, parts_left_out = read_mime_tree(completed.stdout, end) + message, end = _decode_message(stdout) + mime_tree, parts_left_out = read_mime_tree(stdout, end) except ValueError as error: raise ParseError(GENERIC_ERROR) from error for attachment in message.get("attachments", []): @@ -119,6 +117,40 @@ def parse_email(raw_email: bytes) -> ParsedEmail: return ParsedEmail(message, mime_tree, parts_left_out) +def _run_cli(raw_email: bytes) -> bytes: + """Run the CLI on the email and return its stdout. + + stdout goes to an anonymous temporary file, not a pipe, so that on Linux + the kernel stops the child at ``CHILD_OUTPUT_BYTES`` (``--fsize``) and the + server never holds more than that. + + Raises: + ParseError: The child failed, was killed or reached the output cap. + ParseTimeoutError: The child ran longer than the timeout. + + """ + with tempfile.TemporaryFile() as output: + try: + completed = subprocess.run( # noqa: S603 - fixed argv, email on stdin + _command(), + input=raw_email, + stdout=output, + stderr=subprocess.PIPE, + timeout=PARSE_TIMEOUT_SECONDS, + check=False, + ) + except subprocess.TimeoutExpired as error: + raise ParseTimeoutError from error + + too_large = os.fstat(output.fileno()).st_size >= CHILD_OUTPUT_BYTES + if too_large or completed.returncode == -signal.SIGKILL: + raise ParseError(TOO_COMPLEX_ERROR) + if completed.returncode != 0: + raise ParseError(_error_message(completed.stderr)) + output.seek(0) + return output.read() + + def _command() -> tuple[str, ...]: """Return the CLI command, wrapped in the child limits on Linux.""" if sys.platform == "linux": diff --git a/tests/unittests/conftest.py b/tests/unittests/conftest.py index 09a6ad1..5da3cde 100644 --- a/tests/unittests/conftest.py +++ b/tests/unittests/conftest.py @@ -1,3 +1,4 @@ +import subprocess from pathlib import Path import pytest @@ -19,3 +20,28 @@ def read(name: str) -> bytes: return (FILES / name).read_bytes() return read + + +@pytest.fixture +def fake_cli(monkeypatch): + """Replace the CLI run: write ``stdout`` to its output file, return stderr. + + The fixture value installs the fake and returns the list of argument + tuples it was called with. + """ + + def install(returncode: int, stdout: bytes = b"", stderr: bytes = b""): + calls = [] + + def run(args, **kwargs): + calls.append(args) + kwargs["stdout"].write(stdout) + kwargs["stdout"].flush() + return subprocess.CompletedProcess( + args=args, returncode=returncode, stderr=stderr + ) + + monkeypatch.setattr(subprocess, "run", run) + return calls + + return install diff --git a/tests/unittests/test_app.py b/tests/unittests/test_app.py index b92d5fd..6ce8f60 100644 --- a/tests/unittests/test_app.py +++ b/tests/unittests/test_app.py @@ -6,6 +6,7 @@ import pytest from mail_parser_api import app as app_module +from mail_parser_api import parser as parser_module from mail_parser_api.app import MAX_BODY_BYTES, RATE_LIMIT_REQUESTS from mail_parser_api.parser import ( MAIL_PARSER_COMMAND, @@ -91,6 +92,19 @@ def test_deeply_nested_email_keeps_a_bounded_tree(client): assert body["mime_tree_parts_left_out"] == levels + 2 - 500 +def test_output_over_the_cap_returns_422_too_complex(client, read_sample, monkeypatch): + # The real CLI: on macOS the cap is checked after the child exits, on + # Linux the kernel also stops the child at the original cap. + monkeypatch.setattr(parser_module, "CHILD_OUTPUT_BYTES", 1024) + + response = client.post( + "/api/parse", content=read_sample("mail_test_10"), headers=RFC822 + ) + + assert response.status_code == 422 + assert response.json() == {"detail": TOO_COMPLEX_ERROR} + + def test_parse_accepts_content_type_parameters(client, read_sample): response = client.post( "/api/parse", @@ -157,41 +171,28 @@ def chunks(): assert response.status_code == 413 -def test_parser_failure_returns_422(client, monkeypatch): +def test_parser_failure_returns_422(client, fake_cli): stderr = ( b"2026-01-01 00:00:00,000 | mailparser | __main__ | main | 235 | ERROR " b"| An error occurred: boom\nTraceback (most recent call last):\n" ) - def fail(*_args, **_kwargs): - return subprocess.CompletedProcess( - args=[], returncode=1, stdout=b"", stderr=stderr - ) - - monkeypatch.setattr(subprocess, "run", fail) + fake_cli(1, stderr=stderr) response = client.post("/api/parse", content=b"Subject: x\n\nx", headers=RFC822) assert response.status_code == 422 assert response.json() == {"detail": "boom"} -def test_mail_without_tree_returns_422(client, monkeypatch): - def mail_only(*_args, **_kwargs): - return subprocess.CompletedProcess( - args=[], returncode=0, stdout=b'{\n "subject": "x"\n}\n', stderr=b"" - ) - - monkeypatch.setattr(subprocess, "run", mail_only) +def test_mail_without_tree_returns_422(client, fake_cli): + fake_cli(0, b'{\n "subject": "x"\n}\n') response = client.post("/api/parse", content=b"Subject: x\n\nx", headers=RFC822) assert response.status_code == 422 -def test_killed_parser_returns_422_too_complex(client, monkeypatch): - def killed(*_args, **_kwargs): - return subprocess.CompletedProcess(args=[], returncode=-9, stdout=b"") - - monkeypatch.setattr(subprocess, "run", killed) +def test_killed_parser_returns_422_too_complex(client, fake_cli): + fake_cli(-9) response = client.post("/api/parse", content=b"Subject: x\n\nx", headers=RFC822) assert response.status_code == 422 diff --git a/tests/unittests/test_parser.py b/tests/unittests/test_parser.py index e7e92ab..d23b6e3 100644 --- a/tests/unittests/test_parser.py +++ b/tests/unittests/test_parser.py @@ -1,11 +1,13 @@ import json -import subprocess import sys import tracemalloc import pytest +from mail_parser_api import parser from mail_parser_api.parser import ( + CHILD_ADDRESS_SPACE_BYTES, + CHILD_OUTPUT_BYTES, GENERIC_ERROR, LINUX_CHILD_LIMITS, MAIL_PARSER_COMMAND, @@ -18,18 +20,9 @@ TREE = b'[\n {\n "index": 0,\n "parent": null\n }\n]\n' -def completed(returncode: int, stdout: bytes, stderr: bytes = b""): - def run(*_args, **_kwargs): - return subprocess.CompletedProcess( - args=[], returncode=returncode, stdout=stdout, stderr=stderr - ) - - return run - - -def test_both_documents_are_returned(monkeypatch): +def test_both_documents_are_returned(fake_cli): stdout = b'{\n "subject": "hi"\n}\n' + TREE - monkeypatch.setattr(subprocess, "run", completed(0, stdout)) + fake_cli(0, stdout) assert parse_email(b"raw") == ParsedEmail( message={"subject": "hi"}, @@ -38,15 +31,15 @@ def test_both_documents_are_returned(monkeypatch): ) -def test_attachment_payloads_are_removed(monkeypatch): +def test_attachment_payloads_are_removed(fake_cli): mail = {"attachments": [{"filename": "a", "payload": "QQ=="}]} stdout = json.dumps(mail, indent=2).encode() + b"\n" + TREE - monkeypatch.setattr(subprocess, "run", completed(0, stdout)) + fake_cli(0, stdout) assert parse_email(b"raw").message == {"attachments": [{"filename": "a"}]} -def test_large_tree_with_a_non_bmp_character_is_not_decoded_whole(monkeypatch): +def test_large_tree_with_a_non_bmp_character_is_not_decoded_whole(fake_cli): # One character outside the BMP would make a str of all of stdout take # four bytes per character: about six times stdout, in the server. entries = [ @@ -55,7 +48,7 @@ def test_large_tree_with_a_non_bmp_character_is_not_decoded_whole(monkeypatch): ] tree = json.dumps(entries, ensure_ascii=False, indent=2).encode() stdout = b'{\n "subject": "\xf0\x9f\x98\x80"\n}\n' + tree + b"\n" - monkeypatch.setattr(subprocess, "run", completed(0, stdout)) + fake_cli(0, stdout) tracemalloc.start() try: @@ -65,7 +58,9 @@ def test_large_tree_with_a_non_bmp_character_is_not_decoded_whole(monkeypatch): tracemalloc.stop() assert parsed.mime_tree_parts_left_out == 50_000 - 500 - assert peak < len(stdout) // 4 + # stdout is read once from the output file; decoding all of it as text + # would add four more bytes per byte. + assert peak < 2 * len(stdout) @pytest.mark.parametrize( @@ -80,51 +75,51 @@ def test_large_tree_with_a_non_bmp_character_is_not_decoded_whole(monkeypatch): pytest.param(b"{\n}\n{\n}\n", id="tree-not-an-array"), ], ) -def test_output_without_both_documents_is_a_parse_error(monkeypatch, stdout): - monkeypatch.setattr(subprocess, "run", completed(0, stdout)) +def test_output_without_both_documents_is_a_parse_error(fake_cli, stdout): + fake_cli(0, stdout) with pytest.raises(ParseError, match=GENERIC_ERROR): parse_email(b"raw") -def test_failure_reports_the_error_logged_on_stderr(monkeypatch): +def test_failure_reports_the_error_logged_on_stderr(fake_cli): stderr = ( b"2026-01-01 00:00:00,000 | mailparser | __main__ | main | 235 | ERROR " b"| An error occurred: boom\nTraceback (most recent call last):\n" ) # 4.12.0 prints the mail before it fails on the tree; it is not used. - monkeypatch.setattr(subprocess, "run", completed(1, b"{\n}\n", stderr)) + fake_cli(1, b"{\n}\n", stderr) with pytest.raises(ParseError, match=r"^boom$"): parse_email(b"raw") -def test_failure_without_error_line_uses_generic_message(monkeypatch): - monkeypatch.setattr(subprocess, "run", completed(1, b"", b"Traceback\n")) +def test_failure_without_error_line_uses_generic_message(fake_cli): + fake_cli(1, b"", b"Traceback\n") with pytest.raises(ParseError, match=GENERIC_ERROR): parse_email(b"raw") -def test_failure_with_empty_error_message_is_too_complex(monkeypatch): +def test_failure_with_empty_error_message_is_too_complex(fake_cli): # A MemoryError has no text, so the CLI logs an empty error message. stderr = b"2026-01-01 | mailparser | ERROR | An error occurred: \nTraceback\n" - monkeypatch.setattr(subprocess, "run", completed(1, b"{\n}\n", stderr)) + fake_cli(1, b"{\n}\n", stderr) with pytest.raises(ParseError, match=TOO_COMPLEX_ERROR): parse_email(b"raw") -def test_error_line_on_stdout_is_not_read(monkeypatch): +def test_error_line_on_stdout_is_not_read(fake_cli): stdout = b"2026-01-01 | mailparser | ERROR | An error occurred: boom\n" - monkeypatch.setattr(subprocess, "run", completed(1, stdout)) + fake_cli(1, stdout) with pytest.raises(ParseError, match=GENERIC_ERROR): parse_email(b"raw") -def test_killed_child_is_too_complex(monkeypatch): - monkeypatch.setattr(subprocess, "run", completed(-9, b"")) +def test_killed_child_is_too_complex(fake_cli): + fake_cli(-9, b"") with pytest.raises(ParseError, match=TOO_COMPLEX_ERROR): parse_email(b"raw") @@ -141,17 +136,35 @@ def test_command_asks_for_the_mime_tree(): ("darwin", MAIL_PARSER_COMMAND), ], ) -def test_child_limits_wrap_the_command_only_on_linux(monkeypatch, platform, expected): - calls = [] - - def record(args, **_kwargs): - calls.append(args) - return subprocess.CompletedProcess( - args=args, returncode=0, stdout=b"{\n}\n" + TREE, stderr=b"" - ) - +def test_child_limits_wrap_the_command_only_on_linux( + fake_cli, monkeypatch, platform, expected +): + calls = fake_cli(0, b"{\n}\n" + TREE) monkeypatch.setattr(sys, "platform", platform) - monkeypatch.setattr(subprocess, "run", record) + parse_email(b"raw") assert calls == [expected] + + +def test_linux_limits_cap_memory_and_output(): + assert f"--as={CHILD_ADDRESS_SPACE_BYTES}" in LINUX_CHILD_LIMITS + assert f"--fsize={CHILD_OUTPUT_BYTES}" in LINUX_CHILD_LIMITS + + +def test_output_at_the_cap_is_too_complex(fake_cli, monkeypatch): + stdout = b"{\n}\n" + TREE + monkeypatch.setattr(parser, "CHILD_OUTPUT_BYTES", len(stdout)) + # On Linux the kernel stops the child there and the CLI exits with 1. + fake_cli(1, stdout, b"An error occurred: [Errno 27] File too large\n") + + with pytest.raises(ParseError, match=TOO_COMPLEX_ERROR): + parse_email(b"raw") + + +def test_output_below_the_cap_is_parsed(fake_cli, monkeypatch): + stdout = b"{\n}\n" + TREE + monkeypatch.setattr(parser, "CHILD_OUTPUT_BYTES", len(stdout) + 1) + fake_cli(0, stdout) + + assert parse_email(b"raw").mime_tree_parts_left_out == 0