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/README.md b/README.md index 8073f35..9533312 100644 --- a/README.md +++ b/README.md @@ -22,14 +22,62 @@ Response `200`: ```json { - "mail_parser_version": "4.10.0", - "message": {"subject": "...", "attachments": [{"filename": "...", "binary": true}]} + "mail_parser_version": "4.12.0", + "message": {"subject": "...", "attachments": [{"filename": "...", "binary": true}]}, + "mime_tree": [ + {"index": 0, "parent": null, "depth": 0, "content_type": "multipart/mixed", "...": "...", "cut": []}, + {"index": 1, "parent": 0, "depth": 1, "content_type": "text/plain", "...": "...", "cut": []} + ], + "mime_tree_parts_left_out": 0 } ``` `message` is the full `mail_json` of mail-parser. Every entry of `attachments` keeps its metadata and loses the `payload` key. +`mime_tree` is the MIME tree of the email, as mail-parser's `--mime-tree` +prints it: a flat list in which entry `i` is MIME part `i` (the `part N` of +defect messages) and names its enclosing part in `parent`. Every entry has +these keys: + +| Key | Type | Meaning | +| --------------------------- | ------------- | ------------------------------------------------------------------------------ | +| `index` | int | Position in the list. | +| `parent` | int / null | `index` of the enclosing part; null for the root. | +| `depth` | int | 0 for the root. | +| `content_type` | string | The type the parser acted on, lowercase. | +| `content_type_raw` | string / null | The literal `Content-Type` value; null when the part has none. | +| `content_transfer_encoding` | string / null | Declared encoding; null when absent. | +| `charset` | string / null | Declared charset. | +| `content_disposition` | string / null | Declared disposition type. | +| `filename` | string / null | Declared file name, decoded. | +| `content_id` | string / null | Declared `Content-ID`. | +| `boundary` | string / null | Declared boundary of a multipart. | +| `size` | int / null | Octets of a leaf after transfer decoding; null for a container. | +| `roles` | list | Any of `container`, `body`, `attachment`. | +| `attachment` | int / null | Position of the matching entry in `message.attachments`. | +| `defects` | list | Names of the defect categories recorded against the part. | +| `recovered` | bool | True for a part recovered from an epilogue. | +| `embedded_headers` | object / null | Literal `from`, `subject`, `date` of a message enclosed in a `message/*` part. | +| `cut` | list | Keys whose value was cut to 1024 characters (`embedded_headers.subject`). | + +Every string in the tree, except the role and defect names, is text chosen +by the sender, passed on as declared: control characters and bidirectional +overrides included. A client must escape it before showing it. + +The tree is bounded, and nothing is dropped silently: + +- at most the first 500 entries are kept; parents come before children, so + what is kept is still a tree; +- every string value, those of `embedded_headers` included, is cut to 1024 + characters, and its key is named in `cut`; +- the kept entries hold at most 262,144 characters of text together; the + first entry that would exceed it and every entry after it are left out. + +`mime_tree_parts_left_out` is the number of entries left out, `0` when the +tree is whole. `message` is never cut: it is whole or the request fails +(see the output cap below). + | Status | When | Body | | ------ | ------------------------------------------------------------ | --------------------------------------------------- | | `413` | Body larger than 5 MB | `{"detail": "Body exceeds 5 MB"}` | @@ -49,15 +97,23 @@ the reverse proxy does not expose it. ## Limits and isolation -- Each request runs the installed mail-parser CLI (`mail-parser --stdin --json`) - in a subprocess. The email goes to its stdin, never through a shell; the +- Each request runs the installed mail-parser CLI + (`mail-parser --stdin --json --mime-tree`) in a subprocess, once. The email goes to its stdin, never through a shell; the subprocess is killed after 10 seconds. - The request body is limited to 5 MB. - At most 2 emails are parsed at once; further requests wait for a free slot. - In the container each parse is limited to 192 MiB of address space (`prlimit`) and is the first process the kernel kills when memory runs out (`choom`), so the server survives. Such an email gets `422` with - `email too complex to parse within the service limits`. + `email too complex to parse within the service limits`. Measured with + mail-parser 4.12.0, the limit falls past 970 levels of nesting; a 5 MB + email of base64 attachments passes. +- The CLI may print at most 16 MiB, the mail and the MIME tree together: + its stdout goes to a temporary file in `/tmp`, which `prlimit --fsize` + caps in the container. An email that reaches it gets the same `422`. A + real 5 MB email prints 5 to 7 MB; the cap is reached by emails full of + control characters, which JSON prints as six bytes each, or with more than + about 35,000 MIME parts. - Rate limit: 10 requests per 60-second sliding window per client key, in memory, for at most 10 000 keys (least recently used evicted first). The client key is the first `X-Forwarded-For` value, or the peer address without 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..18ec921 --- /dev/null +++ b/docs/features/message-structure/issues/01-return-the-mime-tree.md @@ -0,0 +1,60 @@ +# 01: Return the MIME tree beside the message + +Status: ready-for-agent + +**What to build:** `POST /api/parse` returns two new keys, `mime_tree` and +`mime_tree_parts_left_out`, as the [spec](../spec.md) defines them. The CLI +command gains `--mime-tree`; `parser.py` decodes the second JSON document +printed after the mail and `app.py` returns it. `message` is unchanged. + +**Blocked by:** nothing. mail-parser 4.12.0 has the `--mime-tree` flag; this +ticket raises the requirement to `mail-parser[outlook]>=4.12.0`, which also +brings the security fixes made since 4.11.0. + +**Context:** + +- `MAIL_PARSER_COMMAND` in `src/mail_parser_api/parser.py` is the fixed + argument list; `_extract_json()` finds the first document and decodes it + with `raw_decode`, which also returns where it ends. The second document + starts on the next line. +- `parse_email()` returns one dict today. It returns a `ParsedEmail` with + `message`, `mime_tree` and `mime_tree_parts_left_out`. +- The cut lives in a module of its own, `src/mail_parser_api/mime_tree.py`, + tested without a subprocess. It decodes the entries of the array one at a + time and keeps only those inside the bounds. +- 4.12.0 logs to stderr: `_error_message()` reads the `An error occurred:` + line from stderr, and stdout must start with `{`. Without this, every + `422` after the bump carries the generic error. +- `pyproject.toml` requires `mail-parser[outlook]>=4.11.0`; that version + rejects the new flag. + +**Decided:** + +- How a cut tree is reported (500 entries, 1024 characters per value, + 262,144 characters of text in all, `mime_tree_parts_left_out` and + `cut`): see "How a cut tree is reported" in the spec. +- The CLI may print at most 16 MiB, mail and tree together; above, `422` + with `TOO_COMPLEX_ERROR` (owner, 2026-11-27, after the security review): + see "Output cap" in the spec. `message` is whole or absent, never cut. +- Failing above about 35,000 parts is acceptable; the service counts no + parts of its own (owner, 2026-11-27). The measurements are under + "Measurements" in the spec: 34,000 tiny parts, 40,000 empty parts and + 970 levels of nesting pass, a 5 MiB email of base64 attachments passes + at the same peak as `--json` alone. + +**Acceptance:** + +- [ ] `mail_test_10` returns `200`, an unchanged `message` and nine + `mime_tree` entries linked to the four attachments. +- [ ] Output with a missing or undecodable second document returns `422`. +- [ ] A tree of 600 entries returns 500 and + `mime_tree_parts_left_out == 100`; a file name of 5,000 characters + returns 1024 of them and `cut == ["filename"]`; entries past 262,144 + characters of text are left out and counted. +- [ ] Output that reaches 16 MiB returns `422` with `TOO_COMPLEX_ERROR`. +- [ ] A failing CLI's `An error occurred:` line on stderr becomes the + `422` detail. +- [x] Measurements for the many-parts and the deeply-nested email recorded + in the spec, with the decision they led to. +- [ ] `pyproject.toml`, `uv.lock` and the README contract updated. +- [ ] `make pre-commit` and `make test-cov` pass. diff --git a/docs/features/message-structure/spec.md b/docs/features/message-structure/spec.md new file mode 100644 index 0000000..8173c5c --- /dev/null +++ b/docs/features/message-structure/spec.md @@ -0,0 +1,234 @@ +# 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 + +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 + +`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. It always has at least one entry, the root: an email + without MIME structure, and even an empty one, has one part. + +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 +`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", "...": "...", "cut": []}, + {"index": 1, "parent": 0, "depth": 1, "content_type": "text/plain", "...": "...", "cut": []} + ], + "mime_tree_parts_left_out": 0 +} +``` + +## 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 `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 + must start with `{`; anything else is unparsable output. stderr never + reaches a log line. + +## 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. +- 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. 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 +tree in the child before anything is printed. The child's limits stay the +guard here, and such a message fails as too complex. + +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) + +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. 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 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 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. +- 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 35,000 parts is +acceptable for the page; no count of our own before the parse. + +## 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. 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. 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. +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..24e3555 --- /dev/null +++ b/src/mail_parser_api/mime_tree.py @@ -0,0 +1,152 @@ +"""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. +""" + +# 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(output: bytes, start: int) -> tuple[list[dict[str, Any]], int]: + """Decode the MIME tree the CLI printed and keep its bounded prefix. + + 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: + output: The CLI stdout. + 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 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 begin, end in _entry_spans(output, start): + if not left_out and len(kept) < MAX_MIME_TREE_PARTS: + part = _bounded_part(_decode_entry(output[begin:end])) + characters += _text_length(part) + if characters <= MAX_MIME_TREE_TEXT: + kept.append(part) + continue + left_out += 1 + return kept, left_out + + +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 bytes are not a closed, indented JSON array of objects. + + """ + 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(output, position + 1) + if output.startswith(b"]", position): + return + while True: + 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 output.startswith(b",", position): + message = "the MIME tree array is not closed" + raise ValueError(message) + 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 ``{``. + + 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]: + """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..847414c 100644 --- a/src/mail_parser_api/parser.py +++ b/src/mail_parser_api/parser.py @@ -1,33 +1,48 @@ """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 +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; # 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. -# ``-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", ) # 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", @@ -35,16 +50,34 @@ "--", "prlimit", f"--as={CHILD_ADDRESS_SPACE_BYTES}", + f"--fsize={CHILD_OUTPUT_BYTES}", "--", ) -# 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. +# 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" +@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,44 +86,69 @@ 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, 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) - stdout = completed.stdout.decode("utf-8", errors="replace") - if completed.returncode != 0: - raise ParseError(_error_message(stdout)) - - message = _extract_json(stdout) + 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 _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, ...]: @@ -100,29 +158,33 @@ def _command() -> tuple[str, ...]: return MAIL_PARSER_COMMAND -def _extract_json(stdout: str) -> dict[str, Any]: - """Return the JSON object printed by the CLI. +# 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. + + 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 the indented mail 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 + 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) + end = line_break + len(b"\n}") + return json.loads(stdout[:end].decode("utf-8", errors="replace")), end -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/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 5daf2a6..6ce8f60 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 @@ -5,8 +6,13 @@ 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 TOO_COMPLEX_ERROR +from mail_parser_api.parser import ( + MAIL_PARSER_COMMAND, + TOO_COMPLEX_ERROR, + ParsedEmail, +) RFC822 = {"Content-Type": "message/rfc822"} @@ -32,6 +38,73 @@ 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_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", @@ -98,27 +171,28 @@ def chunks(): assert response.status_code == 413 -def test_parser_failure_returns_422(client, monkeypatch): - stdout = ( - b"2026-01-01 00:00:00,000 | mailparser | __main__ | main | 203 | ERROR " +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=stdout) - - 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_killed_parser_returns_422_too_complex(client, monkeypatch): - def killed(*_args, **_kwargs): - return subprocess.CompletedProcess(args=[], returncode=-9, stdout=b"") +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 + - 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 @@ -137,7 +211,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..7385567 --- /dev/null +++ b/tests/unittests/test_mime_tree.py @@ -0,0 +1,148 @@ +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 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(): + 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, 4]) +def test_tree_not_indented_as_the_cli_prints_it_raises(indent): + output = printed([entry(0), entry(1)], indent=indent) + + 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(): + 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("[\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.encode(), 0) diff --git a/tests/unittests/test_parser.py b/tests/unittests/test_parser.py index 3185896..d23b6e3 100644 --- a/tests/unittests/test_parser.py +++ b/tests/unittests/test_parser.py @@ -1,76 +1,132 @@ -import subprocess +import json 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, 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 run(*_args, **_kwargs): - return subprocess.CompletedProcess( - args=[], returncode=returncode, stdout=stdout - ) - return run +def test_both_documents_are_returned(fake_cli): + stdout = b'{\n "subject": "hi"\n}\n' + TREE + fake_cli(0, stdout) + assert parse_email(b"raw") == ParsedEmail( + message={"subject": "hi"}, + mime_tree=[{"index": 0, "parent": None, "cut": []}], + mime_tree_parts_left_out=0, + ) -def test_log_lines_before_json_are_skipped(monkeypatch): - stdout = b'2026-01-01 | mailparser | ERROR | Failed\n{\n "subject": "hi"\n}\n' - monkeypatch.setattr(subprocess, "run", completed(0, stdout)) - assert parse_email(b"raw") == {"subject": "hi"} +def test_attachment_payloads_are_removed(fake_cli): + mail = {"attachments": [{"filename": "a", "payload": "QQ=="}]} + stdout = json.dumps(mail, indent=2).encode() + b"\n" + TREE + fake_cli(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")) + +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 = [ + {"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" + fake_cli(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 + # 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( + "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"), + 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(fake_cli, stdout): + fake_cli(0, stdout) with pytest.raises(ParseError, match=GENERIC_ERROR): parse_email(b"raw") -def test_failure_without_error_line_uses_generic_message(monkeypatch): - monkeypatch.setattr(subprocess, "run", completed(1, b"")) +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. + 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(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. - 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" + fake_cli(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(fake_cli): + stdout = b"2026-01-01 | mailparser | ERROR | An error occurred: boom\n" + fake_cli(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(fake_cli): + fake_cli(-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( @@ -80,15 +136,35 @@ def test_truncated_json_is_a_parse_error(monkeypatch): ("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") - +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 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" },