Ver Fonte

fix(mail): refuse a body padded with the response's own framing

A server that announces a literal larger than the body it sends makes
libcurl count the trailing protocol text toward the announced count. curl
reports SUCCESS, so the fetch came back 200 with ten octets of IMAP
framing welded to the end of both the header and the text.

Measured against libcurl 8.22.0: announce 50 for a 40-byte body yields
CURLE_OK and a 50-byte literal whose tail is `)<CRLF>A003 OK`.

It cannot be caught structurally. curl consumes the real `)` and the
tagged line in the healthy case too, so a padded response and a correct
one are byte-for-byte the same shape - untagged line, literal header,
exactly n bytes, nothing after. Only the content differs, which is why
literalEndsWithFraming() matches the tail rather than the framing.

The tag it matches is curl's own: customRequestFor strips the tag from
every command, so curl re-tags on the wire (measured A001, A002, ...
sequential) and our ImapTagger value never reaches the server.

Malformed rather than NeedMore, deliberately: a truncated transfer is
transient and retryable, while a server that miscounts its own literal
will miscount it again, so retrying only burns the run's budget.

The guard lives in parseCurlFetch so no later caller can forget it. Nine
tests, and the falsifying half matters more than the rest: a body that
both mentions a tagged completion line and ends with `)` CRLF - which
real mail does constantly - must still arrive byte-intact.

Corrects an earlier note that described this as the DIRECT parse
returning Ok. Measured, the direct parse returns NeedMore and the
corruption arrives through the framed re-parse, so a fix aimed at the
direct path would have aimed at nothing.

1165/1165 green.
fszontagh há 1 mês atrás
pai
commit
1c93bbadb3

+ 1 - 0
CLAUDE.md

@@ -89,6 +89,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **libcurl is VENDORED at `curl-8_22_0`** (`SVAPI_CURL_TAG`, `SVAPI_VENDOR_CURL=ON`; `OFF` links the system one and is what the dev loop uses, because vendoring costs minutes). The pin comment carries the obligations, and they are real: **CVE tracking is ours now**, a statically linked curl is invisible to `apt`, and a fix means a rebuild and a republish of both binaries rather than an unattended upgrade. Judge an advisory against **what this service reaches** - exactly `imaps`/`imap`/`smtps`/`smtp` - the same discipline the httplib pin uses. `PROXY` is compiled out rather than disabled per handle, because curl reads `*_proxy` from the environment where httplib does not and `runner.env` is a file an operator edits; a stray proxy variable would silently reroute a destination the SSRF guard had already approved. `NETRC` is out so credentials can only come from project secrets. Cookies/ALTSVC/HSTS are out because each is persistent cross-request state, which a multi-tenant pool must not accumulate. A build from a git tag reports its version as `8.22.0-DEV`.
 - **A fetch goes through `CURLOPT_CUSTOMREQUEST` with `BODY.PEEK[]`, NEVER curl's `;UID=` URL form.** Measured against a live server elsewhere: the URL form **always** sets `\Seen`. Undoing it afterwards with a `UID STORE -FLAGS` is worse than the disease - it removes a flag it may not have set, so a message the user had **already read comes back unread**, and a timeout between the fetch and the undo leaves the message read anyway, which is the exact outcome peek exists to prevent. A test asserts no `STORE`, `+FLAGS` or `-FLAGS` ever reaches the wire.
 - **curl consumes the closing `)` AND the tagged completion line; untagged response lines are what reach the write callback.** Measured by byte count, which is the only way to see it: a fetch whose fake response was a 30-byte untagged line plus a 50-byte literal plus `)\r\n` plus the tagged `OK` delivered exactly 80 bytes. **An earlier version of this note claimed the tagged line DOES arrive, and that was wrong** - it came from a substring check for `" OK "` that matched `* OK [UIDVALIDITY 1]`, an untagged line. The consequence is real: a successful fetch's raw buffer legitimately parses as **`NeedMore`**, because the framing it was told to expect was never sent, so the binding restores the framing and re-parses rather than treating that as a short read. Restoring framing is safe only because it cannot satisfy an unsent `{n}`, so a genuinely truncated literal still reports `NeedMore`. Never resolve this with a terminator search. Separately: a `BODY.PEEK[...]` fetch comes back labelled **`BODY[...]`** without the `.PEEK`, so a parser looking for the string it sent finds nothing.
+- **A server that announces `{n}` LARGER than the body it sends corrupts silently, and only its CONTENT gives it away.** curl counts the response's own framing toward the announced count and reports **success**: measured against 8.22.0, an announce of 50 for a 40-byte body yielded `CURLE_OK` and a 50-byte literal ending `)<CRLF>A003 OK`, which `ctx.mail` then returned as a 200 whose header and text both carried those ten octets. It cannot be caught structurally - curl strips the real framing in the healthy case too, so a padded response and a correct one are byte-for-byte the same SHAPE (untagged line, literal header, exactly n bytes, nothing after). `literalEndsWithFraming()` (`net/imap_fetch.cpp`, pure) therefore matches the tail, and `parseCurlFetch` refuses a body that ends in framing. **The tag it matches is CURL'S, not ours**: `customRequestFor` strips the tag from every command, so curl re-tags on the wire (measured: `A001`, `A002`, ... sequential) and our own `ImapTagger` value never reaches the server at all. **`Malformed`, not `NeedMore`** - a truncated transfer is transient and worth retrying, while a server that miscounts its own literal will miscount it again, so this is `mail_protocol_error` 502 and NOT retryable. An earlier note here described this defect as the DIRECT parse returning `Ok`; measured, the direct parse returns `NeedMore` and the corruption arrives through the framed re-parse, so a fix aimed at the direct path would have aimed at nothing.
 - **A `UID FETCH` naming more than one uid delivers ZERO bytes to the write callback** (`7,9` and `7:9` both; a single `7` delivers normally). So a read is one command per uid, all on the one session and the one LOGIN. Measured; it is why the obvious batching optimisation does not work.
 - **A uid absent from the mailbox arrives as zero bytes, and that is `Ok` with no messages.** The caller skips it. Nothing a returned message carries ever comes from the raw buffer, which is what makes the "tagged completion line returned as the e-mail body" bug structurally impossible here rather than merely absent.
 - **curl dot-stuffs the payload it is given, so the renderer must not.** Both doing it corrupts any line beginning with a period; neither doing it truncates the message at a lone `.`. The renderer additionally emits a leading period as `=2E` in quoted-printable, so the protection holds either way.

+ 25 - 1
runner/src/host_context.cpp

@@ -1027,7 +1027,31 @@ net::ImapFetchResult parseCurlFetch(const std::string& response) {
     }
     net::ImapFetchResult direct = net::parseFetchResponse(response);
     if (direct.status == net::ImapParse::Ok) return direct;
-    return net::parseFetchResponse(response + ")\r\n");
+    net::ImapFetchResult framed = net::parseFetchResponse(response + ")\r\n");
+
+    // A literal whose TAIL is the response's own framing did not come from a
+    // truncated transfer - it came from a server that announced `{n}` larger
+    // than the body it sent, so curl counted the framing toward n and reported
+    // SUCCESS. Measured against libcurl 8.22.0 (announce 50, body 40): the
+    // delivered literal was 50 bytes ending `)<CRLF>A003 OK`, and because curl
+    // strips the real framing in the healthy case too, this is byte-for-byte
+    // the same SHAPE as a correct response. Content is the only signal.
+    //
+    // The check lives HERE rather than at the call sites so it cannot be
+    // forgotten by a later caller: every fetch in this file goes through this
+    // function. Malformed rather than NeedMore on purpose - NeedMore is
+    // retryable because a truncated transfer is transient, while a server that
+    // miscounts its own literal will miscount it again, so retrying only wastes
+    // the run's budget.
+    if (framed.status == net::ImapParse::Ok) {
+        for (const net::ImapFetchRecord& record : framed.messages)
+            for (const auto& part : record.bodyParts)
+                if (net::literalEndsWithFraming(part.second)) {
+                    framed.status = net::ImapParse::Malformed;
+                    return framed;
+                }
+    }
+    return framed;
 }
 
 /// The record for `uid`, or nullptr.

+ 48 - 0
runner/src/net/imap_fetch.cpp

@@ -850,4 +850,52 @@ nlohmann::json toJson(const ImapFetchRecord& r) {
     return j;
 }
 
+namespace {
+
+/// The IMAP completion keywords. A FETCH can finish NO or BAD, not only OK, so
+/// matching OK alone would miss two thirds of the shape.
+bool isCompletionKeyword(std::string_view word) {
+    return word == "OK" || word == "NO" || word == "BAD";
+}
+
+}  // namespace
+
+bool literalEndsWithFraming(std::string_view literal) {
+    // The `)` CRLF is the giveaway, and it must be the LAST one: anything after
+    // the candidate framing proves those bytes really were inside the literal
+    // the server announced, because curl stops delivering at exactly N.
+    const std::size_t paren = literal.rfind(")\r\n");
+    if (paren == std::string_view::npos) return false;
+
+    std::string_view rest = literal.substr(paren + 3);
+    // curl's own tag: 'A' then at least one digit. Its counter keeps growing
+    // across a session, so the digit count must not be fixed.
+    if (rest.empty() || rest.front() != 'A') return false;
+    rest.remove_prefix(1);
+    std::size_t digits = 0;
+    while (digits < rest.size() && rest[digits] >= '0' && rest[digits] <= '9') ++digits;
+    if (digits == 0) return false;
+    rest.remove_prefix(digits);
+
+    // Exactly one space separates the tag from the keyword.
+    if (rest.empty() || rest.front() != ' ') return false;
+    rest.remove_prefix(1);
+
+    // The keyword runs to the next space, CRLF or the end of the buffer.
+    const std::size_t wordEnd = rest.find_first_of(" \r\n");
+    const std::string_view word =
+        wordEnd == std::string_view::npos ? rest : rest.substr(0, wordEnd);
+    if (!isCompletionKeyword(word)) return false;
+    if (wordEnd == std::string_view::npos) return true;
+
+    // What follows a real completion line is a human sentence and at most the
+    // CRLF that ends it. A CRLF with content after it means these bytes were
+    // genuinely body, not padding.
+    std::string_view tail = rest.substr(wordEnd);
+    if (tail.size() >= 2 && tail.compare(tail.size() - 2, 2, "\r\n") == 0)
+        tail.remove_suffix(2);
+    if (tail.find_first_of("\r\n") != std::string_view::npos) return false;
+    return tail.empty() || tail.front() == ' ';
+}
+
 }  // namespace svapi::runner::net

+ 27 - 0
runner/src/net/imap_fetch.hpp

@@ -381,6 +381,33 @@ ImapFetchResult parseFetchResponse(std::string_view bytes);
 /// that changed under us, not an error.
 const ImapFetchRecord* findByUid(const std::vector<ImapFetchRecord>& messages, uint64_t uid);
 
+/// True when `literal` ends with bytes that can only be IMAP framing: the
+/// closing paren of a FETCH response, CRLF, and the start of a tagged
+/// completion line.
+///
+/// This exists for one measured defect, and it is the ONLY signal available for
+/// it. A server that announces `{N}` larger than the body it then sends makes
+/// libcurl count the trailing protocol text toward N, so the literal libcurl
+/// delivers is padded with the response's own framing. curl reports success:
+/// measured against 8.22.0, an announce of 50 for a 40-byte body yielded
+/// `CURLE_OK` and a 50-byte literal whose tail was `)<CRLF>A003 OK`.
+///
+/// It cannot be caught structurally. curl consumes the real `)` and the tagged
+/// line in the HEALTHY case too, so a padded response and a correct one are
+/// byte-for-byte the same shape - untagged line, literal header, exactly N
+/// bytes, nothing after. The only thing that differs is what those N bytes
+/// CONTAIN.
+///
+/// The tag matched is CURL's, not ours: `customRequestFor` strips the tag from
+/// every command, so libcurl re-tags on the wire (measured: A001, A002, ...
+/// sequential). So this matches the shape `A<digits>` rather than a tag we
+/// could have remembered.
+///
+/// A legitimate message whose last bytes are exactly this shape is refused
+/// rather than corrupted, which is the right direction to fail: the caller gets
+/// an error it can see instead of a body with protocol text welded to the end.
+bool literalEndsWithFraming(std::string_view literal);
+
 // ---------------------------------------------------------------------------
 // JSON shapes
 // ---------------------------------------------------------------------------

+ 76 - 0
runner/tests/host_context_test.cpp

@@ -1777,6 +1777,29 @@ protected:
     }
 };
 
+/// A server that announces a literal LARGER than the body it sends, and then
+/// supplies enough further bytes that the count is satisfied anyway.
+///
+/// This is the shape that corrupts silently. MEASURED against libcurl 8.22.0:
+/// curl counts the response's own framing toward the announced 50, reports
+/// CURLE_OK, and hands up a 50-byte literal whose last ten bytes are
+/// `)<CRLF>A003 OK`. Note this is NOT the truncating server above - that one
+/// closes the connection and curl notices. Here the transfer completes
+/// cleanly, which is exactly why nothing below the parser can catch it.
+class UnderAnnouncedLiteralImapServer : public svapi::testing::FakeImapServer {
+protected:
+    std::string respond(const std::string& line, bool& closeAfter) override {
+        if (upperOf(line).find("UID FETCH") != std::string::npos) {
+            // 40 bytes of body, announced as 50. The ten bytes curl will eat
+            // out of the framing are `)<CRLF>A003 OK`, and a well-formed close
+            // and completion line follow so the transfer still finishes.
+            return "* 1 FETCH (UID 7 BODY[HEADER] {50}\r\n" + std::string(40, 'B') +
+                   ")\r\nA003 OK)\r\nA003 OK Fetch completed\r\n";
+        }
+        return svapi::testing::FakeImapServer::respond(line, closeAfter);
+    }
+};
+
 } // namespace
 
 TEST(HostContextMail, AUidThatVanishedBetweenTheSearchAndTheFetchIsSkippedNotFabricated) {
@@ -1824,3 +1847,56 @@ TEST(HostContextMail, ATruncatedLiteralIsAnErrorRatherThanAShortBody) {
         << out.result.value.dump();
     server.stop();
 }
+
+TEST(HostContextMail, AnUnderAnnouncedLiteralIsRefusedRatherThanCarryingProtocolTextAsBody) {
+    // The defect: curl reports SUCCESS for this response, the direct parse
+    // returns NeedMore (so the framing guard fires, correctly), and the framed
+    // re-parse then returns Ok with a body carrying ten bytes of IMAP framing
+    // welded to its end. Without the content check that is a 200 with a
+    // corrupted message.
+    UnderAnnouncedLiteralImapServer server;
+    ASSERT_TRUE(server.start());
+
+    auto out = runScript(mailTrigger(),
+                         withPort(catching("ctx.mail.read({ host: '127.0.0.1', port: %PORT%,"
+                                           "  tls: false, user: 'u', password: 'p' })"),
+                                  server.port()));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), true) << out.result.value.dump();
+    // Not retryable and not a timeout: a server that miscounts its own literal
+    // will miscount it again.
+    EXPECT_EQ(out.result.value.at("code"), "mail_protocol_error") << out.result.value.dump();
+    // The actual corruption, asserted directly: no framing may appear anywhere
+    // in what reached the script.
+    const std::string dumped = out.result.value.dump();
+    EXPECT_EQ(dumped.find("A003 OK"), std::string::npos) << dumped;
+    EXPECT_EQ(dumped.find("BBBB"), std::string::npos) << dumped;
+    server.stop();
+}
+
+TEST(HostContextMail, AnHonestBodyEndingInAParenAndCrlfIsStillDelivered) {
+    // The falsifying half. The guard keys on the framing SHAPE, so a body that
+    // legitimately ends with `)` and a CRLF - which real mail does, constantly -
+    // must still come through byte-intact. A guard that refused this would pass
+    // the test above while breaking ordinary mailboxes.
+    svapi::testing::FakeImapServer server;
+    // A body that both MENTIONS a tagged completion line and ends with `)`
+    // CRLF - the two features the guard keys on, arranged as real mail
+    // arranges them. Our own documentation looks like this.
+    server.messageBody =
+        "From: a@example.com\r\nSubject: imap notes\r\n\r\n"
+        "the server answered A003 OK Fetch completed (as it should)\r\n";
+    ASSERT_TRUE(server.start());
+
+    auto out = runScript(mailTrigger(),
+                         withPort(catching("ctx.mail.read({ host: '127.0.0.1', port: %PORT%,"
+                                           "  tls: false, user: 'u', password: 'p' })"),
+                                  server.port()));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), false) << out.result.value.dump();
+    const nlohmann::json& value = out.result.value.at("value");
+    ASSERT_EQ(value.at("messages").size(), 1u) << value.dump();
+    // Intact, not merely present: the guard must not have trimmed the tail.
+    EXPECT_NE(value.dump().find("as it should"), std::string::npos) << value.dump();
+    server.stop();
+}

+ 69 - 0
runner/tests/mail_net_test.cpp

@@ -3,6 +3,7 @@
 #include <curl/curl.h>
 
 #include "net/curl_errors.hpp"
+#include "net/imap_fetch.hpp"
 #include "net/mail_budget.hpp"
 #include "net/xfer_abort.hpp"
 
@@ -201,3 +202,71 @@ TEST(MailErrors, AMalformedUrlIsTheCallersMistakeAndNotRetryable) {
     EXPECT_EQ(f.status, 422);
     EXPECT_FALSE(f.retryable);
 }
+
+// ------------------------------------------------- a literal padded with framing
+//
+// MEASURED against libcurl 8.22.0: a server that announces {50} and sends a
+// 40-byte body makes curl count the response's own framing toward the 50, and
+// curl reports SUCCESS. The padded literal's tail is `)<CRLF>A003 OK`. Since
+// curl strips the real framing in the healthy case too, the padded and the
+// correct response are the same SHAPE, and only the content differs - which is
+// why this predicate looks at the content.
+
+TEST(ImapFraming, AFramingPaddedLiteralIsRecognised) {
+    // Exactly what was measured: 40 body bytes plus the ten bytes curl ate.
+    const std::string padded = std::string(40, 'B') + ")\r\nA003 OK";
+    EXPECT_TRUE(literalEndsWithFraming(padded));
+}
+
+TEST(ImapFraming, EveryCompletionKeywordCounts) {
+    // A FETCH can complete NO or BAD as well as OK, and all three are framing.
+    for (const char* word : {"OK", "NO", "BAD"}) {
+        const std::string padded = "body" + std::string(")\r\nA007 ") + word;
+        EXPECT_TRUE(literalEndsWithFraming(padded)) << word;
+    }
+}
+
+TEST(ImapFraming, TheTagIsCurlsSoAnyDigitRunMatches) {
+    // curl re-tags every command (customRequestFor strips ours), and its
+    // counter keeps growing, so the digit count must not be fixed at three.
+    EXPECT_TRUE(literalEndsWithFraming("x)\r\nA1 OK"));
+    EXPECT_TRUE(literalEndsWithFraming("x)\r\nA123456 OK"));
+}
+
+TEST(ImapFraming, TrailingTextAfterTheKeywordStillCounts) {
+    // The real thing carries a human sentence after the keyword.
+    EXPECT_TRUE(literalEndsWithFraming("x)\r\nA003 OK Fetch completed\r\n"));
+}
+
+// --- and now the half that makes the test suite falsifiable: what must NOT
+// --- be flagged. A predicate that answered true for everything would pass
+// --- every test above while refusing every e-mail in existence.
+
+TEST(ImapFraming, AnOrdinaryBodyIsNotFlagged) {
+    EXPECT_FALSE(literalEndsWithFraming("Subject: hello\r\n\r\nHi there.\r\n"));
+    EXPECT_FALSE(literalEndsWithFraming(std::string(40, 'B')));
+    EXPECT_FALSE(literalEndsWithFraming(""));
+}
+
+TEST(ImapFraming, ABodyMentioningImapIsNotFlaggedWithoutTheFramingBeforeIt) {
+    // The giveaway is the `)` CRLF immediately before the tag, not the tag
+    // shape on its own - otherwise any message discussing IMAP would be
+    // refused. This is the false-positive case that matters: our own
+    // documentation quotes these lines.
+    EXPECT_FALSE(literalEndsWithFraming("the server answered A003 OK Fetch completed"));
+    EXPECT_FALSE(literalEndsWithFraming("A003 OK"));
+    EXPECT_FALSE(literalEndsWithFraming("no paren here\r\nA003 OK"));
+}
+
+TEST(ImapFraming, FramingInTheMIDDLEOfABodyIsNotFlagged) {
+    // Only the TAIL can be curl's padding: anything after it proves those
+    // bytes were genuinely inside the literal the server announced.
+    EXPECT_FALSE(literalEndsWithFraming(")\r\nA003 OK\r\nand then more real body text"));
+}
+
+TEST(ImapFraming, AMalformedTagShapeIsNotFlagged) {
+    EXPECT_FALSE(literalEndsWithFraming("x)\r\nA OK"));      // no digits
+    EXPECT_FALSE(literalEndsWithFraming("x)\r\nB003 OK"));   // not curl's prefix
+    EXPECT_FALSE(literalEndsWithFraming("x)\r\nA003 OOPS")); // not a completion
+    EXPECT_FALSE(literalEndsWithFraming("x)\r\nA003"));      // no keyword at all
+}