Prechádzať zdrojové kódy

fix(mail): one slug, one status - mail_too_large is 422 everywhere

Found by running ctx.mail through the DEPLOYED runner on prod against a
real mail provider, which is the first time any of this executed outside
the dev host.

`mail_too_large` carried TWO statuses: 413 from the transport
(curl_errors.cpp, mail_session.cpp) and 422 from the aggregate per-run
cap in host_context, while api/llms.txt promised 413 for exactly the
case that returned 422. A consumer branching on the status was wrong
whichever path it hit, and the docs were wrong for the common one.

Aligned on 422, not 413. Nothing the CALLER sent was oversized - the
request is a few dozen bytes and the mailbox is big - so 413, which is
about the request body, names the wrong party. The remedy is to ask for
less mail (a lower `limit`, or a `smallerThanBytes` criterion), which is
422's meaning, and it matches every other size refusal in this service:
document_too_large and message_too_large are both 422.

ErrCode has no 413 at all, so the host-side 422 was never a choice
between the two - which is part of why the inconsistency survived.

The existing test pinned 413. Updated to assert the INTENT it was
written for - that too-large is not reported as a timeout - directly,
rather than only through the number, plus that it is not retryable.

Also asserts what literalEndsWithFraming CANNOT catch, as passing tests
rather than leaving the gaps looking like oversights: arbitrary padding
is undetectable, padding cut off before the status word is undetectable,
and a body merely ending in `)` CRLF is never refused because real mail
does that constantly and a false positive there costs a legitimate
message. The owners of the sibling implementation hit the same defect
and reached the same three gaps independently.

1201/1201 green.
fszontagh 1 mesiac pred
rodič
commit
55b1a31369

+ 3 - 0
CLAUDE.md

@@ -101,6 +101,9 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **The mail budget has a THIRD number the embedding budget does not: `totalMs`.** An embedding call is one request/response, so bounding connect and read bounds it. A mailbox read is several round trips on one connection, and a read timeout bounds each quiet period and **not their sum** - a server answering every command just inside the read timeout holds a pooled runtime far past the run's budget without ever tripping it. `resolveMailBudget()` (`net/mail_budget.hpp`, pure) otherwise mirrors `resolveEmbedBudget()`, connect capped at half.
 - **`mailGlobalInit()` is called once from the runner's `main` before any worker starts, and FAILS CLOSED.** `curl_global_init` is not thread-safe and a lazy first-use from two pool threads is a real race. It also checks `CURL_VERSION_THREADSAFE` and refuses to start without it, in the same spirit as the runner refusing to start with no token on a non-loopback bind. **`CURLOPT_NOSIGNAL` on every handle**, or curl uses `SIGALRM` for resolution timeouts, which is unsafe off the main thread and can longjmp out of a worker - and a single-threaded test never shows it.
 - **One handle per (run, account), destroyed with the session. No `CURLSH`, no cross-tenant reuse.** A handle carries connection state and credentials. A fresh handle per command would mean a TCP connect, a TLS handshake and a LOGIN for every command, which is both slow and what gets an account throttled; a test asserts one LOGIN serves three commands.
+- **VERIFIED THROUGH THE DEPLOYED RUNNER ON PROD, 2026-10-09**, which is the only test that exercises the real binary, real project secrets and real egress together. `mailboxes` decoded 6 folders in 263 ms; `read` with a `smallerThanBytes` criterion returned 3 of 9 matches in 312 ms; `criteria: {unseen:true}` worked; and the **non-ASCII SEARCH refusal fired in production** as `mail_bad_argument` 422 naming the field, which is the single most important safety behaviour here because the alternative shipped elsewhere as silently empty results. Credentials came from project secrets via `passwordSecret`, never from source. A function whose policy grants **nothing** (`rules: []`) can still use `ctx.mail`, which confirms the deliberate decision that an outbound surface is gated by `network_egress` and the SSRF guard rather than by scope rules.
+- **`ctx.mail.send` CANNOT WORK on the DigitalOcean prod droplet**: outbound 25, 465, 587 and 2525 are all blocked by the provider, confirmed as the host's policy rather than the mail server's by `smtp.gmail.com:587` and `smtp.sendgrid.net:587` being blocked too. IMAP 993 and 143 are open. A send therefore fails as `mail_timeout` 504 after ~7 s with **`retryable: false`** - which is the right answer and worth noting: a send is never retryable even when the timeout proves nothing could have been delivered, because the guarantee has to hold without knowing. The ~7 s is also live confirmation that connect is capped at HALF the run budget (15 s descriptor timeout). Sending from prod needs the provider's block lifted or a relay on an open port.
+- **A returned object containing `status`, `headers` or `body` is read as a response ENVELOPE, and an envelope may contain nothing else.** A diagnostic object with a field called `status` therefore fails the run with `invalid_return` - and if that object was built in a `catch`, it HIDES the error it was meant to report. Cost me a debugging round on prod.
 - **VERIFIED AGAINST A LIVE SERVER on 2026-10-08** (Dovecot-ish on `mail.onmail.hu`, IMAP 993 implicit TLS and SMTP 587 STARTTLS, credentials in `/data/dev/.env`). Everything below was measured against that server, not a fixture, and every fake-server claim in this section survived it: `LIST` and modified-UTF-7 decoding, `EXAMINE` reporting `PERMANENTFLAGS ()` read-only, `UID SEARCH` including `UNSEEN`, **a peek fetch of a genuinely UNSEEN message leaving it unseen** (the weak version of this test uses an already-seen message and proves nothing), the direct parse of a good fetch returning `NeedMore` while the framed re-parse returns `Ok`, no tagged line in the buffer, and **a multi-uid `UID FETCH` delivering zero bytes**. A full send-and-read-back round trip confirmed an accented Hungarian subject surviving as two `=?UTF-8?B?` encoded words and decoding back exactly, quoted-printable chosen for the accented text, a lone `.` body line arriving intact and not double-stuffed, an RFC 2231 attachment filename, and `BODYSTRUCTURE` part numbering of `1.1` for the text inside a `multipart/alternative` inside a `multipart/mixed` with the attachment at `2`. Note `EXAMINE` alone prevents a flag change, so that test confirms the read path is safe but does NOT isolate `BODY.PEEK`'s own contribution.
 - **The fake IMAP/SMTP servers are committed** (`runner/tests/fake_mail_server.hpp`): in-process TCP listeners on **ephemeral** ports. Ephemeral because a fixed port collides - twice during development a test reached a stale server from an earlier run and "passed" against the wrong process. They **mask credentials** before recording a transcript, and the SMTP one answers a bare `AUTH PLAIN` with a **334 challenge, not 235**: answering 235 made an earlier harness report a working login for a client that had sent no credentials. It also **un-stuffs** the leading period during DATA, as a real receiver does, or a correct client looks like it double-stuffed.
 - **A FETCH response's data items in front of the `{n}` are NOT a fixed shape.** Measured against a real mail provider: when a fetch sets flags, the provider volunteers the new `FLAGS` in the SAME untagged line as the body, so the items before the literal vary in number and order. Anchoring on the first `{` after `FETCH` is safe; counting fields or assuming a prefix length is not. Our parser walks name/value pairs over a parsed s-expression, so order is already irrelevant and unrecognised items land in `unknownItems` rather than breaking the parse - three tests pin that instead of assuming it.

+ 2 - 2
api/llms.txt

@@ -245,8 +245,8 @@ export default async function (ctx) {
   - `ctx.mail.mailboxes({...})` -> `[{name, nameEncoding, flags, delimiter}]`. Names are decoded from IMAP's modified UTF-7, so `Beérkezett` arrives readable.
   - `ctx.mail.send({from, to, cc, bcc, subject, text, html, attachments, replyTo, headers, inReplyTo, references, ...})` -> `{ok: true, accepted: [...]}`. `to`/`cc`/`bcc` take a string or an array. Structure is chosen for you: text only is `text/plain`, text plus `html` is `multipart/alternative`, and attachments wrap it in `multipart/mixed`. Attachments are `{filename, contentType, base64}`. **`bcc` recipients receive the message but appear in no header of it.** A non-ASCII subject, display name or filename is encoded correctly (RFC 2047, and RFC 2231 for filenames). An address, subject, filename or header containing CR or LF is **refused by name** - that is header injection.
   - **Mail hosts go through the same SSRF guard as `ctx.fetch`**, so loopback, private and link-local destinations are refused (`egress_blocked`, with the guard's reason) and a function cannot reach a mail server on the API host. The name is resolved **once** and every address it returns is classified, then the approved address is pinned for the connection - re-resolving is the rebinding window. Plaintext (`tls:false, startTls:false`) to anything but a loopback literal is refused as `mail_tls_required`.
-  - **One run may load at most 4 MiB of mail**, independently of any mailbox size, because a run holds a pooled runtime with its own memory limit. Exceeding it is **413** `mail_too_large` - deliberately not a timeout, because the remedies differ and a caller told "timeout" for an oversized mailbox retries forever.
-  - **Slugs worth branching on**, each with `details.retryable`: `mail_timeout` **504**, `mail_too_large` **413**, `mail_incomplete` (the server stopped mid-message; retryable, since a peek fetch changed nothing), `mail_rejected` **422** (the server refused permanently, usually a bad recipient or sender - its reply text is included), `mail_server_busy` **503** (a transient 4xx; retryable), `mail_auth_failed` (**never** retryable - repeating a rejected login is how an account gets locked), `mail_tls_untrusted` (the certificate did not verify; never retried and never downgraded), `mail_unreachable` and `mail_unresolvable` (retryable, nothing reached the server). **A send is never reported as retryable** once the conversation could have reached delivery, because a duplicate e-mail cannot be recalled.
+  - **One run may load at most 4 MiB of mail**, independently of any mailbox size, because a run holds a pooled runtime with its own memory limit. Exceeding it is **422** `mail_too_large` - deliberately not a timeout, because the remedies differ and a caller told "timeout" for an oversized mailbox retries forever.
+  - **Slugs worth branching on**, each with `details.retryable`: `mail_timeout` **504**, `mail_too_large` **422**, `mail_incomplete` (the server stopped mid-message; retryable, since a peek fetch changed nothing), `mail_rejected` **422** (the server refused permanently, usually a bad recipient or sender - its reply text is included), `mail_server_busy` **503** (a transient 4xx; retryable), `mail_auth_failed` (**never** retryable - repeating a rejected login is how an account gets locked), `mail_tls_untrusted` (the certificate did not verify; never retried and never downgraded), `mail_unreachable` and `mail_unresolvable` (retryable, nothing reached the server). **A send is never reported as retryable** once the conversation could have reached delivery, because a duplicate e-mail cannot be recalled.
 - **The `ctx.fetch` response** carries `status`, `headers`, `body`, `bodyEncoding` and a `res.json()` helper. `res.json()` on a base64 response throws `not_json` rather than parsing bytes as text.
 - `ctx.files.list()` returns at most **100** entries and does not page. `ctx.crypto.hmacSha256` accepts `{base64:'...'}` for either `key` or `data`, not only strings.
 - `.insert(doc)` honours an **`id` inside the document object** - the idiom for an idempotent write.

+ 12 - 1
runner/src/net/curl_errors.cpp

@@ -135,7 +135,18 @@ MailFailure mailFailureFor(int curlCode, long responseCode, std::string_view cur
                         false);
 
         case CURLE_FILESIZE_EXCEEDED:
-            return make(413, "mail_too_large",
+            // 422, not 413. Nothing the CALLER sent was too large - their
+            // request was a few dozen bytes and the mailbox was big - so 413
+            // "Payload Too Large", which is about the request body, names the
+            // wrong party. 422 says "understood, cannot do it", and the remedy
+            // is to ask for less mail: a lower `limit`, or a
+            // `smallerThanBytes` criterion. It also matches what every other
+            // size refusal in this service answers (`document_too_large`,
+            // `message_too_large`), and one slug must not carry two statuses -
+            // the aggregate per-run cap in host_context already answered 422
+            // while this said 413 and the docs promised 413, so a consumer
+            // branching on status was wrong whichever path it hit.
+            return make(422, "mail_too_large",
                         detailOr(curlMessage, "the mail transfer exceeded the size this run may load"),
                         false);
 

+ 2 - 1
runner/src/net/mail_session.cpp

@@ -155,7 +155,8 @@ MailFailure classify(CURL* h, CURLcode rc, const char* errbuf, const TransferSta
         // "out of time" have different remedies, and a caller told the wrong
         // one acts on the wrong thing.
         if (state.abort == AbortReason::TooLarge)
-            return MailFailure{413, "mail_too_large",
+            // 422 rather than 413 - see curl_errors.cpp for why.
+            return MailFailure{422, "mail_too_large",
                                "the mail response exceeded the size this run may load", false};
         if (state.abort == AbortReason::Deadline)
             return MailFailure{504, "mail_timeout",

+ 42 - 0
runner/tests/mail_net_test.cpp

@@ -270,3 +270,45 @@ TEST(ImapFraming, AMalformedTagShapeIsNotFlagged) {
     EXPECT_FALSE(literalEndsWithFraming("x)\r\nA003 OOPS")); // not a completion
     EXPECT_FALSE(literalEndsWithFraming("x)\r\nA003"));      // no keyword at all
 }
+
+TEST(MailErrors, OneSlugCarriesExactlyOneStatus) {
+    // Found on prod: `mail_too_large` answered 413 from the transport and 422
+    // from the aggregate per-run cap, while the docs promised 413 - so a
+    // consumer branching on the status was wrong whichever path it hit. 422 is
+    // the correct one: nothing the CALLER sent was oversized, so 413 "Payload
+    // Too Large" names the wrong party, and the remedy is to ask for less mail.
+    EXPECT_EQ(mailFailureFor(CURLE_FILESIZE_EXCEEDED, 0, "", false).status, 422);
+    EXPECT_EQ(mailFailureFor(CURLE_FILESIZE_EXCEEDED, 0, "", false).slug, "mail_too_large");
+    // And it is not retryable: the mailbox will be just as large next time.
+    EXPECT_FALSE(mailFailureFor(CURLE_FILESIZE_EXCEEDED, 0, "", false).retryable);
+}
+
+// --- what literalEndsWithFraming CANNOT catch, asserted on purpose ---------
+//
+// A content-based guard cannot be complete, so its limits are written as
+// PASSING tests rather than left to look like oversights. Suggested by the
+// owners of the sibling IMAP implementation, who hit the same defect and
+// reached the same three gaps.
+
+TEST(ImapFraming, ArbitraryPaddingIsNotDetectableAndThatIsAccepted) {
+    // A server padding with something that is not its own framing is
+    // indistinguishable from a message that really ends in those bytes. There
+    // is nothing to key on, so this comes through as content.
+    EXPECT_FALSE(literalEndsWithFraming(std::string(40, 'B') + "XXXXXXXXXX"));
+}
+
+TEST(ImapFraming, PaddingCutOffBEFORETheStatusWordIsNotDetectable) {
+    // The tail is then `)<CRLF>A00` with no keyword, which is also what mail
+    // ending in a short word after a parenthesised line looks like. Refusing it
+    // would turn a guess into unreadable mail, so it is allowed through.
+    EXPECT_FALSE(literalEndsWithFraming("body)\r\nA00"));
+    EXPECT_FALSE(literalEndsWithFraming("body)\r\nA003 O"));
+}
+
+TEST(ImapFraming, ABodyMerelyEndingInAParenAndCrlfIsNeverRefused) {
+    // Real mail does this constantly. This is the limit that MUST hold: the
+    // cost of a false positive here is a legitimate message refused, which is
+    // worse than the corruption the guard exists to stop.
+    EXPECT_FALSE(literalEndsWithFraming("see the note (above)\r\n"));
+    EXPECT_FALSE(literalEndsWithFraming(")\r\n"));
+}

+ 13 - 2
runner/tests/mail_session_test.cpp

@@ -172,9 +172,20 @@ TEST_F(ImapFixture, AResponseLargerThanTheRunMayLoadIsRefusedAsTooLargeNotAsATim
     const MailFailure f = session.command("INBOX", "UID FETCH 7 BODY.PEEK[]", response);
     ASSERT_FALSE(f.ok());
     // The remedies differ, so the answers must differ: a caller told "timeout"
-    // for an oversized mailbox retries forever.
-    EXPECT_EQ(f.status, 413);
+    // for an oversized mailbox retries forever. That is the POINT of this
+    // test, so assert it directly rather than only via the number.
     EXPECT_EQ(f.slug, "mail_too_large");
+    EXPECT_NE(f.slug, "mail_timeout");
+    EXPECT_NE(f.status, 504);
+    // 422, not 413. Nothing the CALLER sent was oversized - the request was a
+    // few dozen bytes and the mailbox was big - so 413, which is about the
+    // request body, names the wrong party. The remedy is to ask for less mail,
+    // which is 422's meaning, and it matches every other size refusal here.
+    // One slug must carry one status: the aggregate per-run cap already
+    // answered 422 while this path said 413, so a consumer branching on the
+    // status was wrong whichever path it hit. Measured on prod.
+    EXPECT_EQ(f.status, 422);
+    EXPECT_FALSE(f.retryable);
     EXPECT_EQ(session.lastAbort(), AbortReason::TooLarge);
     mailGlobalCleanup();
 }