Ver Fonte

feat(mail): decode subject and addresses host-side, beside the raw header

A fetched `header` is raw RFC 5322 and therefore FOLDED, and both regexes
a consumer reaches for get it wrong. Measured through the deployed
runner against a real provider, a long accented subject arrived as

    Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=

with NOTHING on the `Subject:` line and the value split across two
continuation lines as two separate encoded words. So `/Subject:.*/`
finds an empty subject, and `/^Subject:\s*(.*)$/m` matches but captures
only the FIRST encoded word - a silently truncated subject, which is the
worse of the two. My own probe contained both mistakes at once, in
opposite directions, which is fair evidence that every consumer would
hit it.

So the host does it once, correctly: each message now carries `subject`,
`from`, `from_address`, `to`, `cc`, `date` and `message_id`, unfolded and
RFC 2047-decoded with the implementation this service already owns and
already encodes with on the send path.

`header` is ALWAYS still returned raw alongside. A decoded field is a
convenience and must never become the only way to see what arrived.

Decoded from the header rather than from IMAP's ENVELOPE deliberately:
ENVELOPE would make the value depend on the provider's parsing, and we
would own neither the bug nor the fix.

An undecodable value is passed through exactly as it arrived rather than
raising - a malformed header is the sender's doing, and one bad subject
must not make a mailbox unreadable. Same choice the mailbox-name decoder
makes, for the same reason.

The unfolding is pure and separately tested (functions/header_fields.*),
12 cases including the measured two-encoded-word shape, tab folds, bare
LF, the first occurrence winning so an injected header cannot override a
real one, the blank line ending the block so a body is never parsed as
headers, and a malformed line being skipped rather than fatal.

One test of mine failed first with an empty message list, and the cause
is worth recording: `limit` takes the NEWEST n uids, so `limit: 1`
selected uid 11 while the fixture always answers UID 7 - which the
binding then correctly SKIPPED as a uid the server did not return. The
skip path working is why the test failed quietly rather than returning
the wrong message.

1216/1216 green.
fszontagh há 1 mês atrás
pai
commit
597e210cad

+ 1 - 0
CLAUDE.md

@@ -102,6 +102,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`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.
+- **A message carries DECODED `subject`/`from`/`from_address`/`to`/`cc`/`date`/`message_id` beside the raw header** (`putDecodedHeaderFields`, over the pure `functions/unfoldHeaders` + the RFC 2047 decoder this service already owns). Built because the raw header is folded and every consumer would get it wrong - see the next bullet. `header` is ALWAYS still returned raw: a decoded field is a convenience and must never become the only way to see what arrived. An undecodable value passes through as it came rather than raising, matching what the mailbox-name decoder does and for the same reason. Decoded from the HEADER rather than from IMAP's `ENVELOPE` deliberately: `ENVELOPE` would make the value depend on the provider's parsing, and we would own neither the bug nor the fix.
 - **A returned `header` is RAW and FOLDED, and the naive regex truncates it SILENTLY.** Measured through the deployed runner: a long accented subject arrived as `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=` - nothing on the `Subject:` line at all, the value split across two continuation lines as two encoded words. `/Subject:.*=\?UTF-8\?/` is then false (`.` cannot cross the CRLF) while `/^Subject:\s*(.*)$/m` matches but captures only the FIRST encoded word, so one check fails loudly and the other lies. Both of my probe's checks were wrong, in opposite directions. Consumers must unfold before parsing and decode every encoded word, which `api/llms.txt` now says. Candidate improvement: expose a decoded `subject` on each message so no consumer has to get this right - deliberately NOT built, since it is a new surface.
 - **`ctx.mail.send` CANNOT WORK on the DigitalOcean prod droplet**: outbound 25, 465 and 587 are blocked by the provider (**2525 is NOT** - an earlier version of this note said it was, which was wrong: 2525 merely had nothing listening at the time, and I folded it into the block without the second host that would have told the two apart), 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 WORKS over port 2525 with STARTTLS**, verified end to end through the deployed runner: send accepted in ~1.3 s, then found by `UID SEARCH` and fetched back, with the message arriving `\\Recent` and NOT `\\Seen` - which is `BODY.PEEK` proven in production against a genuinely new message, the strongest form of that test. A send over 587 still fails as `mail_timeout` 504 with `retryable: false`.
 - **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.

+ 2 - 1
api/llms.txt

@@ -241,7 +241,8 @@ export default async function (ctx) {
 - **A job, cron or db run's `ctx` is NOT the HTTP shape.** It carries `trigger`, `depth`, `enqueued_by` and `enqueued_at_ms`, with your payload under **`ctx.body`** - there is no `ctx.method`, `ctx.path`, `ctx.query` or `ctx.params`. A cron payload is `{schedule, scheduled_at}`; a database-event payload is `{collection, table, id, event, document}`.
 - `ctx.mail` - **IMAP read and SMTP send.** Three calls, deliberately few, each opening one session and closing it. Connection fields are shared: `host`, `port` (optional, 0 or absent means the scheme default), `user`/`userSecret`, `password`/`passwordSecret`, `tls` (default **true**), `startTls`, `timeoutMs`. **Prefer `passwordSecret`/`userSecret`**: they name a project secret resolved host-side, so an error or a log that echoes your options object cannot leak it and an operator can rotate it without a code push. A literal `password` is accepted, because `ctx.env` already hands your script the value anyway. Naming a secret that does not exist is **422** `mail_secret_missing`, which names the secret and never a value; passing both a literal and a secret name for the same credential is `ambiguous_body`. An unknown option key is **refused, not ignored**.
   - `ctx.mail.read({mailbox, criteria, limit, ...})` -> `{messages: [...], matched: n}`. `mailbox` defaults to `INBOX`; `limit` defaults to 20 and is **capped at 200** (over it is refused, not clamped). `matched` is the size of the whole search result and `messages` the newest `limit` of it, so you can tell a full page from the end of the mailbox. Each message carries `uid`, `seq`, `flags`, `internal_date`, `size`, `header`, `text`, `body_sections` and a `headerEncoding`/`textEncoding` of `text` or `base64` - **mail is routinely not UTF-8**, so the encoding is stated rather than assumed. Reading uses `EXAMINE` and `BODY.PEEK`, so **it never marks mail as seen**.
-  - **`header` is RAW RFC 5322, which means it is FOLDED - do not parse it with an obvious regex.** Measured against a real provider: a long accented subject came back as `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=`, with **nothing on the `Subject:` line itself** and the value split across two continuation lines as two separate encoded words. So `/Subject:.*/` finds an EMPTY subject, and `/^Subject:\s*(.*)$/m` finds only the FIRST encoded word - a silently truncated subject, which is worse. Unfold first (join a line beginning with a space or tab onto the previous one), then RFC 2047-decode **every** encoded word in the result and concatenate. The same applies to any long header, `To` and `From` included.
+  - **Each message carries DECODED convenience fields, so you do not have to parse the header at all**: `subject`, `from`, `from_address` (the bare address with the display name stripped), `to`, `cc`, `date` and `message_id`. They are unfolded and RFC 2047-decoded host-side by the same implementation the send path encodes with. A value that will not decode is passed through exactly as it arrived rather than raising, because a malformed header is the sender's doing and one bad subject must not make a mailbox unreadable. `date` is left as sent, since turning an RFC 5322 date into an instant is a separate decision with its own failure modes. Absent headers are empty strings, never missing keys.
+  - **`header` is still returned RAW alongside those fields, and raw means FOLDED - do not parse it with an obvious regex.** Measured against a real provider: a long accented subject came back as `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=`, with **nothing on the `Subject:` line itself** and the value split across two continuation lines as two separate encoded words. So `/Subject:.*/` finds an EMPTY subject, and `/^Subject:\s*(.*)$/m` finds only the FIRST encoded word - a silently truncated subject, which is worse. Unfold first (join a line beginning with a space or tab onto the previous one), then RFC 2047-decode **every** encoded word in the result and concatenate. The same applies to any long header, `To` and `From` included.
   - **`criteria` is a structured object, never raw IMAP syntax** - the only string accepted is `'ALL'` (the default). Fields: `since`, `before`, `from`, `to`, `subject`, `text`, `body`, `headerName`+`headerValue`, `unseen`, `seen`, `flagged`, `largerThanBytes`, `smallerThanBytes`. `headerName` and `headerValue` are one criterion in two halves and must both be given, because a server answers a half-stated one with a syntax error rather than with a match. **A non-ASCII criterion value is REFUSED** (naming the field): expressing it needs a multi-step `CHARSET UTF-8` literal exchange this transport does not drive, and sending the bytes anyway makes the server match nothing - and zero results is indistinguishable from "there is no such mail", which is a silently wrong answer rather than a missing feature. Filter on an ASCII-safe criterion, or on sender or date, and match accented text yourself after fetching. Mailbox NAMES are unaffected and may be non-ASCII.
   - `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.

+ 53 - 0
runner/src/host_context.cpp

@@ -9,6 +9,8 @@
 #include "file_store.hpp"
 #include "filters.hpp"
 #include "functions/embed_budget.hpp"
+#include "functions/header_fields.hpp"
+#include "functions/mime_words.hpp"
 #include "functions/timezone.hpp"
 #include "net/imap_commands.hpp"
 #include "net/imap_fetch.hpp"
@@ -931,6 +933,55 @@ void putMailText(nlohmann::json& out, const char* key, const std::string& bytes)
     }
 }
 
+/// The decoded convenience fields for one message.
+///
+/// A raw `header` is RFC 5322 and therefore FOLDED, and the two regexes a
+/// consumer reaches for both get it wrong - one finds nothing, the other
+/// silently captures only the FIRST encoded word of a split value. Measured
+/// through the deployed runner against a real provider: a long accented subject
+/// arrived as `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=`, with
+/// nothing on the `Subject:` line at all. A probe written here contained BOTH
+/// mistakes simultaneously, which is fair evidence that every consumer would
+/// hit it.
+///
+/// So the host does it once, correctly, with the RFC 2047 decoder this service
+/// already owns. `header` is still returned RAW alongside: a decoded field is a
+/// convenience and must never become the only way to see what actually
+/// arrived.
+///
+/// A value that will not decode is passed through AS IT CAME rather than
+/// raising: a malformed header is the sender's doing, and one bad subject must
+/// not make a mailbox unreadable. That is the same choice the mailbox-name
+/// decoder below makes, for the same reason.
+void putDecodedHeaderFields(nlohmann::json& out, const std::string& rawHeader) {
+    const std::vector<functions::HeaderField> fields = functions::unfoldHeaders(rawHeader);
+    const auto field = [&fields](const char* name) {
+        return functions::headerValue(fields, name);
+    };
+    const auto decodeOrRaw = [](const std::string& v) {
+        if (v.empty()) return std::string();
+        try {
+            return functions::MimeWords::decode(v);
+        } catch (const std::exception&) {
+            return v;
+        }
+    };
+    out["subject"] = decodeOrRaw(field("Subject"));
+    const std::string from = field("From");
+    out["from"] = decodeOrRaw(from);
+    // The bare address as well, because that is what a script compares or
+    // replies to, and pulling it out of a display name is the other half of
+    // the job a consumer would otherwise get wrong.
+    out["from_address"] = from.empty() ? std::string()
+                                       : functions::MimeWords::envelopeAddress(from);
+    out["to"] = decodeOrRaw(field("To"));
+    out["cc"] = decodeOrRaw(field("Cc"));
+    // Left exactly as sent: an RFC 5322 date is already ASCII and parsing it
+    // into an instant is a separate decision with its own failure modes.
+    out["date"] = field("Date");
+    out["message_id"] = field("Message-ID");
+}
+
 /// A LIST name as a script should see it.
 ///
 /// imap_fetch returns the name exactly as it arrived - still modified UTF-7 on a
@@ -2642,6 +2693,8 @@ struct HostContext::Impl {
             // cap and the encoding decision.
             hostdetail::putMailText(m, "header", header);
             hostdetail::putMailText(m, "text", text);
+            // Decoded conveniences, from the RAW header which stays above.
+            hostdetail::putDecodedHeaderFields(m, header);
             messages.push_back(std::move(m));
         }
         // `matched` is the whole search result and `messages` only the newest

+ 66 - 0
runner/tests/host_context_test.cpp

@@ -1990,3 +1990,69 @@ TEST(HostContextEgressGate, AnUnsetGateLeavesTheSsrfGuardAsTheOnlyRefusal) {
               std::string::npos)
         << "the default must not be deny: " << out.result.value.dump();
 }
+
+TEST(HostContextMail, ADecodedSubjectIsReturnedBesideTheRawHeader) {
+    // The folded two-encoded-word shape measured through the deployed runner
+    // against a real provider. A consumer must get the WHOLE subject, and the
+    // raw header must still be there to check against.
+    svapi::testing::FakeImapServer server;
+    server.messageBody =
+        "Subject:\r\n"
+        " =?UTF-8?B?c3ZhcGkgcm91bmR0cmlwIC0gw6FydsOtenTFsXLFkQ==?=\r\n"
+        " =?UTF-8?B?IHTDvGvDtnJmw7pyw7Nnw6lw?=\r\n"
+        "From: =?UTF-8?Q?K=C5=91v=C3=A1g=C3=B3_=C3=96rs?= <ors.kovago@example.com>\r\n"
+        "To: <nbot@example.com>\r\n"
+        "\r\nbody\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& msgs = out.result.value.at("value").at("messages");
+    ASSERT_FALSE(msgs.empty()) << out.result.value.dump();
+    const nlohmann::json& m = msgs.front();
+
+    // BOTH encoded words, joined - not just the first, which is the silent
+    // truncation this exists to prevent.
+    EXPECT_EQ(m.at("subject"), "svapi roundtrip - árvíztűrő tükörfúrógép") << m.dump();
+    EXPECT_EQ(m.at("from"), "Kővágó Örs <ors.kovago@example.com>");
+    EXPECT_EQ(m.at("from_address"), "ors.kovago@example.com");
+    // The RAW header is still present and still folded: the decoded field is a
+    // convenience, never the only way to see what arrived.
+    const std::string raw = m.at("header").get<std::string>();
+    EXPECT_NE(raw.find("=?UTF-8?B?"), std::string::npos) << "the raw header must stay raw";
+}
+
+TEST(HostContextMail, AMessageWithNoSubjectGetsAnEmptyStringNotAnError) {
+    svapi::testing::FakeImapServer server;
+    server.messageBody = "From: a@example.com\r\n\r\nbody\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& m = out.result.value.at("value").at("messages").front();
+    EXPECT_EQ(m.at("subject"), "");
+    EXPECT_EQ(m.at("from_address"), "a@example.com");
+}
+
+TEST(HostContextMail, AnUndecodableSubjectComesBackAsItArrivedRatherThanFailing) {
+    // A malformed encoded word is the sender's doing. One bad header must not
+    // make a mailbox unreadable, so the raw value is passed through.
+    svapi::testing::FakeImapServer server;
+    server.messageBody = "Subject: =?NOSUCHCHARSET?Q?whatever?=\r\n\r\nbody\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 std::string subject =
+        out.result.value.at("value").at("messages").front().at("subject").get<std::string>();
+    EXPECT_FALSE(subject.empty()) << "an undecodable subject must not vanish";
+}

+ 1 - 0
src/CMakeLists.txt

@@ -3,6 +3,7 @@ add_library(vectorapi_core STATIC
     errors.cpp
     db_errors.cpp
     functions/mime_words.cpp
+    functions/header_fields.cpp
     json_http.cpp
     filters.cpp
     vector_search.cpp

+ 73 - 0
src/functions/header_fields.cpp

@@ -0,0 +1,73 @@
+#include "functions/header_fields.hpp"
+
+#include <algorithm>
+#include <cctype>
+
+namespace svapi::functions {
+namespace {
+
+bool isContinuation(std::string_view line) {
+    return !line.empty() && (line.front() == ' ' || line.front() == '\t');
+}
+
+std::string lowerOf(std::string_view s) {
+    std::string out(s);
+    std::transform(out.begin(), out.end(), out.begin(),
+                   [](unsigned char c) { return static_cast<char>(::tolower(c)); });
+    return out;
+}
+
+/// Trim trailing CR, and leading/trailing spaces and tabs.
+std::string_view trimmed(std::string_view s) {
+    while (!s.empty() && (s.back() == '\r' || s.back() == ' ' || s.back() == '\t'))
+        s.remove_suffix(1);
+    while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.remove_prefix(1);
+    return s;
+}
+
+}  // namespace
+
+std::vector<HeaderField> unfoldHeaders(std::string_view raw) {
+    std::vector<HeaderField> out;
+    std::size_t pos = 0;
+    while (pos <= raw.size()) {
+        const std::size_t nl = raw.find('\n', pos);
+        std::string_view line = raw.substr(pos, nl == std::string_view::npos ? std::string_view::npos
+                                                                            : nl - pos);
+        // A blank line ends the header block; a body may follow and is not ours.
+        if (trimmed(line).empty() && !isContinuation(line)) break;
+
+        if (isContinuation(line)) {
+            if (!out.empty()) {
+                const std::string_view piece = trimmed(line);
+                // One space for the fold, and none when the value is still
+                // empty - which is exactly the `Subject:<CRLF> <word>` shape.
+                if (!out.back().value.empty() && !piece.empty()) out.back().value += ' ';
+                out.back().value.append(piece);
+            }
+            // A continuation with no field before it is not attributable, so
+            // it is dropped rather than guessed at.
+        } else {
+            const std::size_t colon = line.find(':');
+            if (colon != std::string_view::npos) {
+                HeaderField f;
+                f.name.assign(trimmed(line.substr(0, colon)));
+                f.value.assign(trimmed(line.substr(colon + 1)));
+                out.push_back(std::move(f));
+            }
+            // No colon: not a header field. Skipped, never fatal.
+        }
+        if (nl == std::string_view::npos) break;
+        pos = nl + 1;
+    }
+    return out;
+}
+
+std::string headerValue(const std::vector<HeaderField>& fields, std::string_view name) {
+    const std::string want = lowerOf(name);
+    for (const HeaderField& f : fields)
+        if (lowerOf(f.name) == want) return f.value;
+    return std::string();
+}
+
+}  // namespace svapi::functions

+ 50 - 0
src/functions/header_fields.hpp

@@ -0,0 +1,50 @@
+#pragma once
+
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace svapi::functions {
+
+/// One header field, unfolded: the name as it was written and the value with
+/// its folds joined.
+struct HeaderField {
+    std::string name;   ///< as written, e.g. "Subject"
+    std::string value;  ///< unfolded, still RFC 2047-encoded
+};
+
+/// Split a raw RFC 5322 header block into unfolded fields.
+///
+/// This exists because a raw header is FOLDED and the obvious regex gets it
+/// wrong - quietly. Measured through the deployed runner against a real
+/// provider, a long accented subject arrived as:
+///
+///     Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=
+///
+/// with NOTHING on the `Subject:` line itself and the value split across two
+/// continuation lines as two separate encoded words. So `/Subject:.*/` finds an
+/// empty subject, and `/^Subject:\s*(.*)$/m` matches but captures only the
+/// FIRST encoded word - a silently truncated subject, which is the worse
+/// failure. A probe written here contained both mistakes at once.
+///
+/// Unfolding rule (RFC 5322 3.2.2): a line beginning with a space or tab is a
+/// continuation of the previous field. The leading whitespace is replaced by a
+/// single space, because the fold was inserted for line length and the space is
+/// part of the syntax rather than of the value - except that adjacent encoded
+/// words are allowed to be separated by whitespace which a decoder then drops,
+/// so keeping one space is both correct and harmless.
+///
+/// A line that is neither a field nor a continuation is SKIPPED rather than
+/// treated as an error: a header block is attacker-influenced data, and one
+/// malformed line must not make a mailbox unreadable.
+std::vector<HeaderField> unfoldHeaders(std::string_view raw);
+
+/// The unfolded value of the FIRST field named `name`, case-insensitively, or
+/// an empty string.
+///
+/// First, not last: a header injected further down must not win over the real
+/// one. Mail with two Subject lines is malformed, and taking the first is both
+/// the conventional reading and the safe one.
+std::string headerValue(const std::vector<HeaderField>& fields, std::string_view name);
+
+}  // namespace svapi::functions

+ 5 - 0
tests/CMakeLists.txt

@@ -248,6 +248,11 @@ target_include_directories(test_trigger_body PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_trigger_body PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_trigger_body)
 
+add_executable(test_header_fields test_header_fields.cpp)
+target_include_directories(test_header_fields PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_header_fields PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_header_fields)
+
 add_executable(test_imap_reader test_imap_reader.cpp)
 target_include_directories(test_imap_reader PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_imap_reader PRIVATE GTest::gtest_main)

+ 120 - 0
tests/test_header_fields.cpp

@@ -0,0 +1,120 @@
+#include <gtest/gtest.h>
+
+#include <string>
+
+#include "functions/header_fields.hpp"
+#include "functions/mime_words.hpp"
+
+using svapi::functions::headerValue;
+using svapi::functions::unfoldHeaders;
+
+namespace {
+/// The decoded value of one header, which is what a consumer actually wants.
+std::string decoded(const std::string& raw, const char* name) {
+    return svapi::functions::MimeWords::decode(headerValue(unfoldHeaders(raw), name));
+}
+}  // namespace
+
+TEST(HeaderFields, TheShapeMEASUREDAgainstARealProvider) {
+    // Exactly what came back through the deployed runner: `Subject:` with
+    // NOTHING on its own line, and the value split across two continuation
+    // lines as two separate encoded words.
+    const std::string raw =
+        "Return-Path: <nbot@fsociety.hu>\r\n"
+        "Subject:\r\n"
+        " =?UTF-8?B?c3ZhcGkgcm91bmR0cmlwIC0gw6FydsOtenTFsXLFkQ==?=\r\n"
+        " =?UTF-8?B?IHTDvGvDtnJmw7pyw7Nnw6lw?=\r\n"
+        "To: <nbot@fsociety.hu>\r\n"
+        "\r\n"
+        "body text that must not be parsed as a header\r\n";
+    // BOTH encoded words, in order, decoded and concatenated.
+    EXPECT_EQ(decoded(raw, "Subject"), "svapi roundtrip - árvíztűrő tükörfúrógép");
+    // And the body did not leak into the fields.
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "body text that must not be parsed as a header"),
+              "");
+}
+
+TEST(HeaderFields, TheTwoNAIVEExtractIONSAreWrongAndThisIsWhy) {
+    // The regexes a consumer reaches for first. Kept as a test so the reason
+    // this code exists cannot be forgotten: one fails loudly, the other LIES.
+    const std::string raw = "Subject:\r\n =?UTF-8?Q?first?=\r\n =?UTF-8?Q?_second?=\r\n\r\n";
+    const std::string full = decoded(raw, "Subject");
+    EXPECT_EQ(full, "first second");
+    // A `.*` after "Subject:" cannot cross the CRLF - it would see nothing.
+    // A per-line match would capture only "first" - a silently truncated value.
+    EXPECT_NE(full, "");
+    EXPECT_NE(full, "first");
+}
+
+TEST(HeaderFields, AnUnfoldedHeaderIsLeftAlone) {
+    const std::string raw = "Subject: plain and short\r\nFrom: a@b.com\r\n\r\n";
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "Subject"), "plain and short");
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "From"), "a@b.com");
+}
+
+TEST(HeaderFields, LookupIsCaseInsensitiveBecauseServersVary) {
+    const std::string raw = "SUBJECT: shouty\r\nx-Thing: v\r\n\r\n";
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "Subject"), "shouty");
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "subject"), "shouty");
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "X-THING"), "v");
+}
+
+TEST(HeaderFields, TheFIRSTOccurrenceWinsSoAnInjectedHeaderCannotOverride) {
+    // Mail with two Subject lines is malformed. Taking the first is the
+    // conventional reading AND the safe one: a header appended further down
+    // must not beat the real one.
+    const std::string raw = "Subject: real\r\nFrom: a@b.com\r\nSubject: injected\r\n\r\n";
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "Subject"), "real");
+}
+
+TEST(HeaderFields, TabContinuationsCountToo) {
+    // RFC 5322 allows a tab as the continuation prefix, and real servers use
+    // it - the Received line measured on prod folds with tabs.
+    const std::string raw = "Received: from x\r\n\tby y\r\n\tfor <z@example.com>\r\n\r\n";
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "Received"), "from x by y for <z@example.com>");
+}
+
+TEST(HeaderFields, BareLfIsAcceptedAsWellAsCrlf) {
+    // A fetched header is whatever the server sent. Insisting on CRLF would
+    // make a lenient server's mail unreadable.
+    const std::string raw = "Subject:\n one\n two\n\n";
+    EXPECT_EQ(headerValue(unfoldHeaders(raw), "Subject"), "one two");
+}
+
+TEST(HeaderFields, AMalformedLineIsSKIPPEDRatherThanFatal) {
+    // A header block is attacker-influenced. One junk line must not make a
+    // mailbox unreadable, so it is dropped and the rest still parses.
+    const std::string raw = "Subject: fine\r\nthis-line-has-no-colon\r\nFrom: a@b.com\r\n\r\n";
+    const auto fields = unfoldHeaders(raw);
+    EXPECT_EQ(headerValue(fields, "Subject"), "fine");
+    EXPECT_EQ(headerValue(fields, "From"), "a@b.com");
+}
+
+TEST(HeaderFields, AContinuationWithNoFieldBeforeItIsDropped) {
+    // Not attributable to anything, so guessing would be worse than dropping.
+    EXPECT_NO_THROW({ (void)unfoldHeaders(" orphan continuation\r\nSubject: ok\r\n\r\n"); });
+    EXPECT_EQ(headerValue(unfoldHeaders(" orphan\r\nSubject: ok\r\n\r\n"), "Subject"), "ok");
+}
+
+TEST(HeaderFields, AnAbsentHeaderIsEmptyNotAnError) {
+    EXPECT_EQ(headerValue(unfoldHeaders("Subject: x\r\n\r\n"), "Date"), "");
+    EXPECT_EQ(headerValue(unfoldHeaders(""), "Subject"), "");
+}
+
+TEST(HeaderFields, TheBLANKLineEndsTheBlockSoABodyIsNeverParsed) {
+    // A body can contain anything, including lines that look like headers.
+    const std::string raw = "Subject: real\r\n\r\nSubject: this is body text\r\n";
+    const auto fields = unfoldHeaders(raw);
+    EXPECT_EQ(fields.size(), 1u);
+    EXPECT_EQ(headerValue(fields, "Subject"), "real");
+}
+
+TEST(HeaderFields, AnAddressHeaderDecodesAndItsAddressSurvives) {
+    const std::string raw =
+        "From: =?UTF-8?Q?K=C5=91v=C3=A1g=C3=B3_=C3=96rs?= <ors.kovago@example.com>\r\n\r\n";
+    const std::string from = decoded(raw, "From");
+    EXPECT_EQ(from, "Kővágó Örs <ors.kovago@example.com>");
+    // And the envelope form strips the display name, which is the other half
+    // of what a consumer needs.
+    EXPECT_EQ(svapi::functions::MimeWords::envelopeAddress(from), "ors.kovago@example.com");
+}