|
@@ -10,6 +10,11 @@
|
|
|
#include "filters.hpp"
|
|
#include "filters.hpp"
|
|
|
#include "functions/embed_budget.hpp"
|
|
#include "functions/embed_budget.hpp"
|
|
|
#include "functions/timezone.hpp"
|
|
#include "functions/timezone.hpp"
|
|
|
|
|
+#include "net/imap_commands.hpp"
|
|
|
|
|
+#include "net/imap_fetch.hpp"
|
|
|
|
|
+#include "net/mail_budget.hpp"
|
|
|
|
|
+#include "net/mail_session.hpp"
|
|
|
|
|
+#include "net/mime_build.hpp"
|
|
|
#include "outbound_http.hpp"
|
|
#include "outbound_http.hpp"
|
|
|
#include "principal.hpp"
|
|
#include "principal.hpp"
|
|
|
#include "project_settings.hpp"
|
|
#include "project_settings.hpp"
|
|
@@ -48,6 +53,7 @@
|
|
|
#include <functional>
|
|
#include <functional>
|
|
|
#include <limits>
|
|
#include <limits>
|
|
|
#include <map>
|
|
#include <map>
|
|
|
|
|
+#include <mutex>
|
|
|
#include <optional>
|
|
#include <optional>
|
|
|
#include <unordered_map>
|
|
#include <unordered_map>
|
|
|
#include <utility>
|
|
#include <utility>
|
|
@@ -554,21 +560,26 @@ int64_t embedTimeoutFrom(const nlohmann::json& payload) {
|
|
|
/// here and classified with blockReasonForAddresses(), which net_guard.hpp
|
|
/// here and classified with blockReasonForAddresses(), which net_guard.hpp
|
|
|
/// documents as ssrfBlockReason's own classification half. One classifier, one
|
|
/// documents as ssrfBlockReason's own classification half. One classifier, one
|
|
|
/// lookup, and the address the connection pins was the address that was checked.
|
|
/// lookup, and the address the connection pins was the address that was checked.
|
|
|
-EgressDecision decideEgress(const functions::HttpUrlParts& parts,
|
|
|
|
|
- const functions::SsrfPolicy& policy, const Resolver& resolve) {
|
|
|
|
|
|
|
+///
|
|
|
|
|
+/// Takes the HOST and not a parsed URL, because the host is all it has ever
|
|
|
|
|
+/// looked at and a mail account has no URL to parse: fabricating one so this
|
|
|
|
|
+/// could keep its old signature would mean inventing a scheme and a path for a
|
|
|
|
|
+/// decision that reads neither.
|
|
|
|
|
+EgressDecision decideEgress(const std::string& host, const functions::SsrfPolicy& policy,
|
|
|
|
|
+ const Resolver& resolve) {
|
|
|
EgressDecision d;
|
|
EgressDecision d;
|
|
|
- if (isAddressLiteral(parts.host)) {
|
|
|
|
|
- if (auto why = functions::ssrfBlockReason(parts.host, policy)) {
|
|
|
|
|
|
|
+ if (isAddressLiteral(host)) {
|
|
|
|
|
+ if (auto why = functions::ssrfBlockReason(host, policy)) {
|
|
|
d.reason = *why;
|
|
d.reason = *why;
|
|
|
return d;
|
|
return d;
|
|
|
}
|
|
}
|
|
|
d.allowed = true;
|
|
d.allowed = true;
|
|
|
- d.pinnedAddress = parts.host;
|
|
|
|
|
|
|
+ d.pinnedAddress = host;
|
|
|
return d;
|
|
return d;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- const std::vector<std::string> addresses = resolve(parts.host);
|
|
|
|
|
- if (auto why = functions::blockReasonForAddresses(parts.host, addresses, policy)) {
|
|
|
|
|
|
|
+ const std::vector<std::string> addresses = resolve(host);
|
|
|
|
|
+ if (auto why = functions::blockReasonForAddresses(host, addresses, policy)) {
|
|
|
d.reason = *why;
|
|
d.reason = *why;
|
|
|
return d;
|
|
return d;
|
|
|
}
|
|
}
|
|
@@ -579,6 +590,527 @@ EgressDecision decideEgress(const functions::HttpUrlParts& parts,
|
|
|
return d;
|
|
return d;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+// --- ctx.mail --------------------------------------------------------------
|
|
|
|
|
+//
|
|
|
|
|
+// The division of labour runner/CMakeLists.txt states is kept strictly: the
|
|
|
|
|
+// command TEXT comes from imap_commands.hpp (the injection boundary), the
|
|
|
|
|
+// response interpretation from imap_fetch.hpp, the outgoing bytes from
|
|
|
|
|
+// mime_build.hpp and the timeouts from mail_budget.hpp. What is left on this
|
|
|
|
|
+// side is turning a JS options bag into those calls and shaping their answers
|
|
|
|
|
+// for a JSON boundary - no curl, no IMAP grammar, no timeout arithmetic.
|
|
|
|
|
+
|
|
|
|
|
+/// The most one ctx.mail call may pull off the wire, in bytes.
|
|
|
|
|
+///
|
|
|
|
|
+/// The same question kCtxFileMaxBytes answers, asked about mail: not what a
|
|
|
|
|
+/// mailbox may hold, but what ONE run may load into a 64 MiB JS heap. A read of
|
|
|
|
|
+/// twenty messages' headers and text is tens of kilobytes, so this leaves room
|
|
|
|
|
+/// for a large message or two while still refusing the mailbox whose single
|
|
|
|
|
+/// message is a 30 MiB video. Higher than the file cap because a read is many
|
|
|
|
|
+/// messages where a file is one, and the base64 inflation of a third applies to
|
|
|
|
|
+/// both.
|
|
|
|
|
+///
|
|
|
|
|
+/// It is enforced TWICE, because the transport's cap and the run's exposure are
|
|
|
|
|
+/// not the same number. `MailTransferOptions::maxBytes` is checked against one
|
|
|
|
|
+/// transfer's buffer, which is reset per command, so on its own it would bound
|
|
|
|
|
+/// one message and let a 200-message read accumulate two hundred times as much
|
|
|
|
|
+/// in the array it is building. The read therefore also totals what it has
|
|
|
|
|
+/// kept and refuses past the same number. Refused rather than truncated: half a
|
|
|
|
|
+/// mailbox silently presented as all of it is the wrong answer, and a caller
|
|
|
|
|
+/// told the cap can lower `limit` or narrow the criteria.
|
|
|
|
|
+constexpr int64_t kCtxMailMaxBytes = 4 * 1024 * 1024;
|
|
|
|
|
+
|
|
|
|
|
+/// How many messages a read returns when it does not say, and the most it may
|
|
|
|
|
+/// ever ask for. The cap is the point: a mailbox has no bound of its own, and a
|
|
|
|
|
+/// function that asks for everything would spend the whole run's budget finding
|
|
|
|
|
+/// out how much everything is.
|
|
|
|
|
+constexpr int64_t kCtxMailDefaultLimit = 20;
|
|
|
|
|
+constexpr int64_t kCtxMailMaxLimit = 200;
|
|
|
|
|
+
|
|
|
|
|
+/// One built command as the bytes CURLOPT_CUSTOMREQUEST wants.
|
|
|
|
|
+///
|
|
|
|
|
+/// The builders emit `tag VERB args CRLF`, which is what a client writing to a
|
|
|
|
|
+/// socket must send; curl writes the tag and the terminator itself, so sending
|
|
|
|
|
+/// ours would put two tags on one line. The tag is therefore stripped HERE
|
|
|
|
|
+/// rather than by asking imap_commands for an untagged form: that header is the
|
|
|
|
|
+/// injection boundary and every command has to go through it, so it keeps
|
|
|
|
|
+/// producing real protocol and the transport adapts to it.
|
|
|
|
|
+///
|
|
|
|
|
+/// A command needing a continuation is REFUSED rather than flattened. Its
|
|
|
|
|
+/// octets may only follow the server's `+`, which a one-shot custom request
|
|
|
|
|
+/// cannot wait for; writing them anyway works against a permissive server and
|
|
|
|
|
+/// deadlocks against a strict one, which is the kind of bug that only appears
|
|
|
|
|
+/// in production.
|
|
|
|
|
+std::string customRequestFor(const net::ImapCommand& c) {
|
|
|
|
|
+ if (c.needsContinuation())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "mail_bad_argument",
|
|
|
|
|
+ "that argument has to be sent as an IMAP literal, which this one-shot "
|
|
|
|
|
+ "mail path cannot send; use a shorter 7-bit value");
|
|
|
|
|
+ std::string line = c.chunks.empty() ? std::string() : c.chunks.front();
|
|
|
|
|
+ if (line.size() >= 2 && line.compare(line.size() - 2, 2, "\r\n") == 0)
|
|
|
|
|
+ line.resize(line.size() - 2);
|
|
|
|
|
+ const std::string prefix = c.tag + " ";
|
|
|
|
|
+ if (line.compare(0, prefix.size(), prefix) == 0) line.erase(0, prefix.size());
|
|
|
|
|
+ return line;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// Is this host a loopback ADDRESS LITERAL?
|
|
|
|
|
+///
|
|
|
|
|
+/// Only a literal, deliberately: a name that resolves to 127.0.0.1 is the
|
|
|
|
|
+/// rebinding case, and the answer here decides whether a session may run in the
|
|
|
|
|
+/// clear. Reuses the guard's own CIDR arithmetic so there is one implementation
|
|
|
|
|
+/// of what loopback means.
|
|
|
|
|
+bool isLoopbackLiteral(const std::string& host) {
|
|
|
|
|
+ static const std::optional<functions::CidrRange> v4 = functions::parseCidr("127.0.0.0/8");
|
|
|
|
|
+ static const std::optional<functions::CidrRange> v6 = functions::parseCidr("::1/128");
|
|
|
|
|
+ return (v4 && functions::cidrContains(*v4, host)) ||
|
|
|
|
|
+ (v6 && functions::cidrContains(*v6, host));
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// How many messages this read may name. Validated rather than coerced, for the
|
|
|
|
|
+/// reason embedTimeoutMs records: an option accepted and ignored leaves the
|
|
|
|
|
+/// author believing a bound is in force. Above the cap is refused rather than
|
|
|
|
|
+/// silently clamped, because a script asking for 5000 is reasoning about a
|
|
|
|
|
+/// result set it is not going to get.
|
|
|
|
|
+int64_t mailReadLimit(const nlohmann::json& payload) {
|
|
|
|
|
+ if (!payload.is_object()) return kCtxMailDefaultLimit;
|
|
|
|
|
+ const auto it = payload.find("limit");
|
|
|
|
|
+ if (it == payload.end() || it->is_null()) return kCtxMailDefaultLimit;
|
|
|
|
|
+ if (!it->is_number_integer() || it->get<int64_t>() <= 0)
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "limit must be a positive integer number of messages");
|
|
|
|
|
+ const int64_t want = it->get<int64_t>();
|
|
|
|
|
+ if (want > kCtxMailMaxLimit)
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "limit is capped at " + std::to_string(kCtxMailMaxLimit) +
|
|
|
|
|
+ " messages per read; page with a narrower criteria instead");
|
|
|
|
|
+ return want;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// The `timeoutMs` this call asked for, or 0 for "unstated". Narrowing only -
|
|
|
|
|
+/// resolveMailBudget cannot raise the run's remaining budget - and validated
|
|
|
|
|
+/// for the same reason the limit is.
|
|
|
|
|
+int64_t mailTimeoutFrom(const nlohmann::json& payload) {
|
|
|
|
|
+ if (!payload.is_object()) return 0;
|
|
|
|
|
+ const auto it = payload.find("timeoutMs");
|
|
|
|
|
+ if (it == payload.end() || it->is_null()) return 0;
|
|
|
|
|
+ if (!it->is_number_integer() || it->get<int64_t>() <= 0)
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "timeoutMs must be a positive integer number of milliseconds");
|
|
|
|
|
+ return it->get<int64_t>();
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// A credential for a mail account: a stored secret by NAME, or a literal.
|
|
|
|
|
+///
|
|
|
|
|
+/// `<x>Secret` is the preferred shape and the reason is worth stating: the value
|
|
|
|
|
+/// never enters the script's own variables, so an author who logs the options
|
|
|
|
|
+/// bag - or whose error handler echoes it - cannot leak it, and an operator can
|
|
|
|
|
+/// rotate it without a code push. A literal is still accepted, because ctx.env
|
|
|
|
|
+/// already hands the script every secret it is entitled to; refusing the literal
|
|
|
|
|
+/// would buy nothing, it would only move the same value one line earlier.
|
|
|
|
|
+///
|
|
|
|
|
+/// A named secret that does not exist is an ERROR. Falling back to an empty
|
|
|
|
|
+/// password would reach the server as an auth failure, and the author would then
|
|
|
|
|
+/// go looking at the mail account rather than at the typo in the name. The error
|
|
|
|
|
+/// names the SECRET, never a value.
|
|
|
|
|
+std::string mailCredential(const nlohmann::json& payload, const nlohmann::json& env,
|
|
|
|
|
+ const char* literalKey, const char* secretKey) {
|
|
|
|
|
+ const bool hasLiteral = payload.is_object() && payload.contains(literalKey) &&
|
|
|
|
|
+ payload.at(literalKey).is_string();
|
|
|
|
|
+ const bool hasSecret = payload.is_object() && payload.contains(secretKey) &&
|
|
|
|
|
+ payload.at(secretKey).is_string();
|
|
|
|
|
+ if (hasLiteral && hasSecret)
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
|
|
|
|
|
+ std::string("ctx.mail takes ") + literalKey + " or " + secretKey +
|
|
|
|
|
+ ", not both");
|
|
|
|
|
+ if (hasSecret) {
|
|
|
|
|
+ const std::string name = payload.at(secretKey).get<std::string>();
|
|
|
|
|
+ if (!env.is_object() || !env.contains(name) || !env.at(name).is_string())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "mail_secret_missing",
|
|
|
|
|
+ "no secret named '" + name + "' is available to this function; set it "
|
|
|
|
|
+ "on the project or in the runner environment");
|
|
|
|
|
+ return env.at(name).get<std::string>();
|
|
|
|
|
+ }
|
|
|
|
|
+ if (hasLiteral) return payload.at(literalKey).get<std::string>();
|
|
|
|
|
+ return std::string();
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// A read's search criteria. "ALL" and absence are the same request: an empty
|
|
|
|
|
+/// criteria set is what imapUidSearch renders as `UID SEARCH ALL`, so the common
|
|
|
|
|
+/// case needs no special case here.
|
|
|
|
|
+net::ImapSearchCriteria mailCriteriaFrom(const nlohmann::json& v) {
|
|
|
|
|
+ net::ImapSearchCriteria c;
|
|
|
|
|
+ if (v.is_null()) return c;
|
|
|
|
|
+ if (v.is_string()) {
|
|
|
|
|
+ if (v.get<std::string>() == "ALL") return c;
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "criteria as a string may only be 'ALL'; pass an object for anything "
|
|
|
|
|
+ "narrower");
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!v.is_object())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "criteria must be an object or the string 'ALL'");
|
|
|
|
|
+
|
|
|
|
|
+ auto text = [&v](const char* key) -> std::optional<std::string> {
|
|
|
|
|
+ const auto it = v.find(key);
|
|
|
|
|
+ if (it == v.end() || it->is_null()) return std::nullopt;
|
|
|
|
|
+ if (!it->is_string())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ std::string("criteria.") + key + " must be a string");
|
|
|
|
|
+ return it->get<std::string>();
|
|
|
|
|
+ };
|
|
|
|
|
+ auto flag = [&v](const char* key) {
|
|
|
|
|
+ const auto it = v.find(key);
|
|
|
|
|
+ if (it == v.end() || it->is_null()) return false;
|
|
|
|
|
+ if (!it->is_boolean())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ std::string("criteria.") + key + " must be a boolean");
|
|
|
|
|
+ return it->get<bool>();
|
|
|
|
|
+ };
|
|
|
|
|
+ auto size = [&v](const char* key) -> std::optional<uint64_t> {
|
|
|
|
|
+ const auto it = v.find(key);
|
|
|
|
|
+ if (it == v.end() || it->is_null()) return std::nullopt;
|
|
|
|
|
+ if (!it->is_number_integer() || it->get<int64_t>() < 0)
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ std::string("criteria.") + key +
|
|
|
|
|
+ " must be a non-negative integer number of bytes");
|
|
|
|
|
+ return static_cast<uint64_t>(it->get<int64_t>());
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ c.since = text("since");
|
|
|
|
|
+ c.before = text("before");
|
|
|
|
|
+ c.from = text("from");
|
|
|
|
|
+ c.to = text("to");
|
|
|
|
|
+ c.subject = text("subject");
|
|
|
|
|
+ c.text = text("text");
|
|
|
|
|
+ c.body = text("body");
|
|
|
|
|
+ c.headerName = text("headerName");
|
|
|
|
|
+ c.headerValue = text("headerValue");
|
|
|
|
|
+ c.unseen = flag("unseen");
|
|
|
|
|
+ c.seen = flag("seen");
|
|
|
|
|
+ c.flagged = flag("flagged");
|
|
|
|
|
+ c.largerThanBytes = size("largerThanBytes");
|
|
|
|
|
+ c.smallerThanBytes = size("smallerThanBytes");
|
|
|
|
|
+ // Every remaining rule - the date shape, the ASCII-only search terms, the
|
|
|
|
|
+ // paired HEADER halves - belongs to imapUidSearch and is left there, so a
|
|
|
|
|
+ // criterion cannot be validated by two rules that drift apart.
|
|
|
|
|
+ return c;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// One address field as a list. A single string is accepted because `to: 'a@b'`
|
|
|
|
|
+/// is what a script writes and an array of one is not an improvement.
|
|
|
|
|
+std::vector<std::string> mailAddressList(const nlohmann::json& v, const char* what) {
|
|
|
|
|
+ std::vector<std::string> out;
|
|
|
|
|
+ if (v.is_null()) return out;
|
|
|
|
|
+ if (v.is_string()) {
|
|
|
|
|
+ out.push_back(v.get<std::string>());
|
|
|
|
|
+ return out;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!v.is_array())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ std::string(what) + " must be a string or an array of strings");
|
|
|
|
|
+ for (const nlohmann::json& e : v) {
|
|
|
|
|
+ if (!e.is_string())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ std::string(what) + " must contain only address strings");
|
|
|
|
|
+ out.push_back(e.get<std::string>());
|
|
|
|
|
+ }
|
|
|
|
|
+ return out;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// The outgoing message, as mime_build.hpp wants it.
|
|
|
|
|
+///
|
|
|
|
|
+/// Mapping only. Every rule about what a header may contain - the CR and LF
|
|
|
|
|
+/// refusals, the structural headers that may not be supplied, the encoded-word
|
|
|
|
|
+/// decisions - is buildMail's, because that is the injection boundary for a
|
|
|
|
|
+/// send and a second opinion here could only disagree with it.
|
|
|
|
|
+net::MailMessage mailMessageFrom(const nlohmann::json& payload) {
|
|
|
|
|
+ net::MailMessage m;
|
|
|
|
|
+ const auto str = [&payload](const char* key) -> std::string {
|
|
|
|
|
+ const auto it = payload.find(key);
|
|
|
|
|
+ if (it == payload.end() || it->is_null()) return std::string();
|
|
|
|
|
+ if (!it->is_string())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ std::string(key) + " must be a string");
|
|
|
|
|
+ return it->get<std::string>();
|
|
|
|
|
+ };
|
|
|
|
|
+ const auto list = [&payload](const char* key) {
|
|
|
|
|
+ const auto it = payload.find(key);
|
|
|
|
|
+ return mailAddressList(it == payload.end() ? nlohmann::json() : *it, key);
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ m.from = str("from");
|
|
|
|
|
+ if (m.from.empty())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "a send needs a from address");
|
|
|
|
|
+ m.to = list("to");
|
|
|
|
|
+ m.cc = list("cc");
|
|
|
|
|
+ m.bcc = list("bcc");
|
|
|
|
|
+ if (m.to.empty() && m.cc.empty() && m.bcc.empty())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "a send needs at least one recipient");
|
|
|
|
|
+ m.replyTo = str("replyTo");
|
|
|
|
|
+ m.subject = str("subject");
|
|
|
|
|
+ m.text = str("text");
|
|
|
|
|
+ m.html = str("html");
|
|
|
|
|
+ m.inReplyTo = str("inReplyTo");
|
|
|
|
|
+ m.references = str("references");
|
|
|
|
|
+
|
|
|
|
|
+ const auto attachments = payload.find("attachments");
|
|
|
|
|
+ if (attachments != payload.end() && !attachments->is_null()) {
|
|
|
|
|
+ if (!attachments->is_array())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "attachments must be an array");
|
|
|
|
|
+ for (const nlohmann::json& a : *attachments) {
|
|
|
|
|
+ if (!a.is_object())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "each attachment must be an object");
|
|
|
|
|
+ net::MailAttachment out;
|
|
|
|
|
+ if (!a.contains("filename") || !a.at("filename").is_string())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "each attachment needs a filename");
|
|
|
|
|
+ out.filename = a.at("filename").get<std::string>();
|
|
|
|
|
+ // An empty content type is left empty on purpose: buildMail turns
|
|
|
|
|
+ // it into application/octet-stream, which is what unknown MEANS and
|
|
|
|
|
+ // is safer than guessing from the extension.
|
|
|
|
|
+ if (a.contains("contentType") && a.at("contentType").is_string())
|
|
|
|
|
+ out.contentType = a.at("contentType").get<std::string>();
|
|
|
|
|
+ // The same `{text}`/`{base64}` reader the crypto surface uses, so a
|
|
|
|
|
+ // payload cannot be decoded by two different rules.
|
|
|
|
|
+ out.content = bytesArgument(a, "an attachment's content");
|
|
|
|
|
+ m.attachments.push_back(std::move(out));
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const auto headers = payload.find("headers");
|
|
|
|
|
+ if (headers != payload.end() && !headers->is_null()) {
|
|
|
|
|
+ if (!headers->is_object())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "headers must be an object of name -> value");
|
|
|
|
|
+ // nlohmann keeps an object's keys sorted, so the rendered bytes are the
|
|
|
|
|
+ // same for the same message - which is what makes a send assertable.
|
|
|
|
|
+ for (auto it = headers->begin(); it != headers->end(); ++it) {
|
|
|
|
|
+ if (!it.value().is_string())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "header '" + it.key() + "' must have a string value");
|
|
|
|
|
+ m.headers.push_back(net::MailHeader{it.key(), it.value().get<std::string>()});
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return m;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// The last `limit` uids of a search result.
|
|
|
|
|
+///
|
|
|
|
|
+/// UID SEARCH answers in ascending order and a mailbox's newest message carries
|
|
|
|
|
+/// its highest uid, so the TAIL is the recent mail - which is what a read of 20
|
|
|
|
|
+/// out of a thousand is asking for. Taking the head would answer with the
|
|
|
|
|
+/// oldest, which is almost never the question and is a silently wrong answer
|
|
|
|
|
+/// rather than an error. Sorted here rather than trusted, because the ordering
|
|
|
|
|
+/// is the server's and "newest" has to be well defined either way.
|
|
|
|
|
+std::vector<uint64_t> newestUids(const std::vector<uint64_t>& uids, int64_t limit) {
|
|
|
|
|
+ if (limit <= 0) return {};
|
|
|
|
|
+ std::vector<uint64_t> out = uids;
|
|
|
|
|
+ std::sort(out.begin(), out.end());
|
|
|
|
|
+ out.erase(std::unique(out.begin(), out.end()), out.end());
|
|
|
|
|
+ if (static_cast<int64_t>(out.size()) > limit) out.erase(out.begin(), out.end() - limit);
|
|
|
|
|
+ return out;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// Put a fetched string on `out` as something JSON can actually carry.
|
|
|
|
|
+///
|
|
|
|
|
+/// Mail is routinely not UTF-8 - a Hungarian message in ISO-8859-2 is ordinary
|
|
|
|
|
+/// rather than exotic - and nlohmann's dump() answers an invalid sequence by
|
|
|
|
|
+/// throwing, which would reach the author as an internal error naming neither
|
|
|
|
|
+/// the message nor the fix. So a part that is valid UTF-8 travels as text and
|
|
|
|
|
+/// anything else travels as base64, with `<key>Encoding` STATING which, exactly
|
|
|
|
|
+/// as ctx.fetch reports a response body it could not carry as text.
|
|
|
|
|
+void putMailText(nlohmann::json& out, const char* key, const std::string& bytes) {
|
|
|
|
|
+ const std::string encodingKey = std::string(key) + "Encoding";
|
|
|
|
|
+ if (isValidUtf8(bytes)) {
|
|
|
|
|
+ out[key] = bytes;
|
|
|
|
|
+ out[encodingKey] = "text";
|
|
|
|
|
+ } else {
|
|
|
|
|
+ out[key] = base64Encode(bytes);
|
|
|
|
|
+ out[encodingKey] = "base64";
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// A LIST name as a script should see it.
|
|
|
|
|
+///
|
|
|
|
|
+/// imap_fetch returns the name exactly as it arrived - still modified UTF-7 on a
|
|
|
|
|
+/// server that is not running UTF8=ACCEPT - and documents that decoding it is
|
|
|
|
|
+/// the caller's job. This is that caller. A name that will not decode is handed
|
|
|
|
|
+/// back RAW rather than dropped: the mailbox exists either way, and a server
|
|
|
|
|
+/// sending something that is not modified UTF-7 is almost certainly sending
|
|
|
|
|
+/// UTF-8 already, so the raw bytes are both the honest answer and the only ones
|
|
|
|
|
+/// that can be fed back to a read.
|
|
|
|
|
+std::string decodeMailboxName(const std::string& raw) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ return net::fromModifiedUtf7(raw);
|
|
|
|
|
+ } catch (const net::ImapCommandError&) {
|
|
|
|
|
+ return raw;
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// Our own sentence for a transport failure, by slug.
|
|
|
|
|
+///
|
|
|
|
|
+/// The transport's message carries curl's error buffer and the server's reply
|
|
|
|
|
+/// text verbatim, and neither may reach a script: the first can name the
|
|
|
|
|
+/// connection and the account it was made with, the second is text a remote
|
|
|
|
|
+/// server chose. The SLUG does reach the script, because the slugs are what
|
|
|
|
|
+/// distinguish the remedies, and the verbatim detail goes to the operator's
|
|
|
|
|
+/// journal instead - the same split the embedding path makes.
|
|
|
|
|
+std::string mailSlugMessage(const std::string& slug) {
|
|
|
|
|
+ if (slug == "mail_too_large")
|
|
|
|
|
+ return "the mail response was larger than one function run may load";
|
|
|
|
|
+ if (slug == "mail_timeout" || slug == "mail_aborted")
|
|
|
|
|
+ return "the mail operation ran out of the time this run could allow it";
|
|
|
|
|
+ if (slug == "mail_auth_failed")
|
|
|
|
|
+ return "the mail server rejected the credentials";
|
|
|
|
|
+ if (slug == "mail_access_denied")
|
|
|
|
|
+ return "the mail server denied access to that mailbox";
|
|
|
|
|
+ if (slug == "mail_rejected")
|
|
|
|
|
+ return "the mail server refused the message permanently; check the sender, the "
|
|
|
|
|
+ "recipients and the size";
|
|
|
|
|
+ if (slug == "mail_server_busy")
|
|
|
|
|
+ return "the mail server refused the command temporarily; retry later";
|
|
|
|
|
+ if (slug == "mail_unresolvable")
|
|
|
|
|
+ return "the mail host could not be resolved";
|
|
|
|
|
+ if (slug == "mail_unreachable")
|
|
|
|
|
+ return "the mail host could not be connected to";
|
|
|
|
|
+ if (slug == "mail_tls_untrusted")
|
|
|
|
|
+ return "the mail server's certificate did not verify";
|
|
|
|
|
+ if (slug == "mail_tls_failed")
|
|
|
|
|
+ return "the TLS handshake with the mail server failed";
|
|
|
|
|
+ if (slug == "mail_connection_lost")
|
|
|
|
|
+ return "the connection to the mail server was lost mid-conversation";
|
|
|
|
|
+ if (slug == "mail_protocol_error")
|
|
|
|
|
+ return "the mail server sent a reply that could not be parsed";
|
|
|
|
|
+ if (slug == "mail_incomplete")
|
|
|
|
|
+ return "the mail server stopped mid-response; the message was not received in full";
|
|
|
|
|
+ if (slug == "mail_no_sender")
|
|
|
|
|
+ return "a send needs an envelope sender";
|
|
|
|
|
+ if (slug == "mail_no_recipient")
|
|
|
|
|
+ return "a send needs at least one recipient";
|
|
|
|
|
+ if (slug == "mail_bad_url")
|
|
|
|
|
+ return "the mail host or port is not usable";
|
|
|
|
|
+ return "the mail operation failed";
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// A FETCH response as curl's IMAP download actually delivers it.
|
|
|
|
|
+///
|
|
|
|
|
+/// MEASURED, against real curl 8.22 and an in-process server, because every
|
|
|
|
|
+/// line of this is a fact about the transport rather than about IMAP:
|
|
|
|
|
+///
|
|
|
|
|
+/// * A successful single-uid fetch arrives as the untagged line plus the
|
|
|
|
|
+/// literal's octets and NOTHING MORE - `* 1 FETCH (UID 7 BODY[] {50}\r\n`
|
|
|
|
|
+/// followed by exactly 50 octets. curl keeps the closing `)` and the tagged
|
|
|
|
|
+/// completion to itself. The parser is octet-counted and right to call that
|
|
|
|
|
+/// buffer incomplete: it answers NeedMore.
|
|
|
|
|
+/// * A uid the server did not return arrives as ZERO bytes. Fetching nothing
|
|
|
|
|
+/// is not an error in IMAP - the server answers with the tagged completion
|
|
|
|
|
+/// alone - and curl passes none of it on.
|
|
|
|
|
+///
|
|
|
|
|
+/// So: an empty buffer is Ok with no messages, which the caller SKIPS. A buffer
|
|
|
|
|
+/// that does not parse has its closing framing restored and is parsed again,
|
|
|
|
|
+/// and that second parse is what decides. Restoring the framing cannot rescue a
|
|
|
|
|
+/// short literal, which is the whole reason it is safe: the announced `{n}` is
|
|
|
|
|
+/// still unsatisfied, so a server that stopped mid-literal still answers
|
|
|
|
|
+/// NeedMore and is still a failure. Measured both ways.
|
|
|
|
|
+///
|
|
|
|
|
+/// What this must NEVER become is a search for a terminator such as `")\r\n"`
|
|
|
|
|
+/// in the buffer. The reader anchors on the byte count, which is what lets a
|
|
|
|
|
+/// body whose CONTENT contains `")\r\n"` and a line that looks like a tagged
|
|
|
|
|
+/// reply come through intact; a terminator search would truncate exactly those
|
|
|
|
|
+/// bodies, and real mail contains them.
|
|
|
|
|
+net::ImapFetchResult parseCurlFetch(const std::string& response) {
|
|
|
|
|
+ if (response.empty()) {
|
|
|
|
|
+ net::ImapFetchResult empty;
|
|
|
|
|
+ empty.status = net::ImapParse::Ok;
|
|
|
|
|
+ return empty;
|
|
|
|
|
+ }
|
|
|
|
|
+ net::ImapFetchResult direct = net::parseFetchResponse(response);
|
|
|
|
|
+ if (direct.status == net::ImapParse::Ok) return direct;
|
|
|
|
|
+ return net::parseFetchResponse(response + ")\r\n");
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// The record for `uid`, or nullptr.
|
|
|
|
|
+///
|
|
|
|
|
+/// Matched by uid rather than taken positionally, because "the server did not
|
|
|
|
|
+/// return this uid" is an ordinary outcome of a mailbox that changed under us.
|
|
|
|
|
+/// The one fallback: a single record carrying no UID item at all is attributed
|
|
|
|
|
+/// to the uid this command asked for, which is sound only because each command
|
|
|
|
|
+/// names exactly one.
|
|
|
|
|
+const net::ImapFetchRecord* recordForUid(const net::ImapFetchResult& result, uint64_t uid) {
|
|
|
|
|
+ if (const net::ImapFetchRecord* exact = net::findByUid(result.messages, uid)) return exact;
|
|
|
|
|
+ if (result.messages.size() == 1 && !result.messages.front().hasUid)
|
|
|
|
|
+ return &result.messages.front();
|
|
|
|
|
+ return nullptr;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// The one body part a fetch asked for.
|
|
|
|
|
+///
|
|
|
|
|
+/// Keyed by section when the server labels it the way we asked, and otherwise
|
|
|
|
|
+/// by being the only part present. The fallback is not laziness: each command
|
|
|
|
|
+/// requests exactly ONE part, so whatever single part came back IS the answer,
|
|
|
|
|
+/// and a server that answers `BODY[]` to a `BODY.PEEK[HEADER]` request would
|
|
|
|
|
+/// otherwise read as an empty message.
|
|
|
|
|
+std::string soleBodyPart(const net::ImapFetchRecord* record, const char* section) {
|
|
|
|
|
+ if (record == nullptr) return std::string();
|
|
|
|
|
+ const auto exact = record->bodyParts.find(section);
|
|
|
|
|
+ if (exact != record->bodyParts.end()) return exact->second;
|
|
|
|
|
+ if (record->bodyParts.size() == 1) return record->bodyParts.begin()->second;
|
|
|
|
|
+ return std::string();
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// A response that did not parse completely, as the failure it is.
|
|
|
|
|
+///
|
|
|
|
|
+/// `NeedMore` is the one that bites. It means THE RESPONSE IS INCOMPLETE, and
|
|
|
|
|
+/// by the time we parse, the transport has already finished the transfer - so
|
|
|
|
|
+/// NeedMore at this point means the server stopped mid-literal. A sibling
|
|
|
|
|
+/// implementation took whatever had arrived, trimmed the trailing `)` and CRLF
|
|
|
|
|
+/// off it and reported success, so an interrupted transfer came back as a short
|
|
|
|
|
+/// but perfectly valid-looking e-mail. It is therefore a failure, and a
|
|
|
|
|
+/// RETRYABLE one: a peek fetch changes no flag, so nothing in the mailbox was
|
|
|
|
|
+/// touched and repeating it is safe.
|
|
|
|
|
+///
|
|
|
|
|
+/// The fix is never to hunt for a terminator such as `")\r\n"`. The reader is
|
|
|
|
|
+/// octet-counted and anchors on the announced `{n}`, which is what lets a body
|
|
|
|
|
+/// whose CONTENT contains `")\r\n"` and a line that looks like a tagged reply
|
|
|
|
|
+/// come through byte-intact. A terminator search would truncate exactly those
|
|
|
|
|
+/// bodies, and real mail contains them.
|
|
|
|
|
+net::MailFailure mailParseFailure(net::ImapParse status, const char* what) {
|
|
|
|
|
+ if (status == net::ImapParse::NeedMore)
|
|
|
|
|
+ return net::MailFailure{504, "mail_incomplete",
|
|
|
|
|
+ std::string("the mail server's ") + what +
|
|
|
|
|
+ " response ended mid-literal",
|
|
|
|
|
+ true};
|
|
|
|
|
+ return net::MailFailure{502, "mail_protocol_error",
|
|
|
|
|
+ std::string("the mail server's ") + what +
|
|
|
|
|
+ " response could not be read",
|
|
|
|
|
+ false};
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// A transport failure as the error a script catches.
|
|
|
|
|
+///
|
|
|
|
|
+/// `retryable` is carried in `details` rather than folded into the status,
|
|
|
|
|
+/// because the transport's three-way answer is the useful one: a read that timed
|
|
|
|
|
+/// out may be repeated, a send past the point of delivery may NOT, and a script
|
|
|
|
|
+/// deciding that from a status code alone would get it wrong in the direction
|
|
|
|
|
+/// that sends an e-mail twice.
|
|
|
|
|
+ApiError apiErrorForMail(const net::MailFailure& f) {
|
|
|
|
|
+ ErrCode code = ErrCode::Unavailable;
|
|
|
|
|
+ switch (f.status) {
|
|
|
|
|
+ case 413:
|
|
|
|
|
+ case 422: code = ErrCode::Unprocessable; break;
|
|
|
|
|
+ case 504: code = ErrCode::GatewayTimeout; break;
|
|
|
|
|
+ case 503: code = ErrCode::Unavailable; break;
|
|
|
|
|
+ case 500: code = ErrCode::Internal; break;
|
|
|
|
|
+ // 502 and anything unmapped. Never a guessed 422: telling a caller its
|
|
|
|
|
+ // payload was wrong when the server was unreachable sends it to fix
|
|
|
|
|
+ // something that is already correct.
|
|
|
|
|
+ default: code = ErrCode::Unavailable; break;
|
|
|
|
|
+ }
|
|
|
|
|
+ return ApiError(code, f.slug.empty() ? "mail_error" : f.slug, mailSlugMessage(f.slug),
|
|
|
|
|
+ nlohmann::json{{"retryable", f.retryable}});
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
// --- ctx.crypto ------------------------------------------------------------
|
|
// --- ctx.crypto ------------------------------------------------------------
|
|
|
|
|
|
|
|
std::string toHex(std::string_view bytes) {
|
|
std::string toHex(std::string_view bytes) {
|
|
@@ -1446,7 +1978,7 @@ struct HostContext::Impl {
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
auto decision =
|
|
auto decision =
|
|
|
- hostdetail::decideEgress(*parts, ssrfPolicy(), hostdetail::resolveWithGetaddrinfo);
|
|
|
|
|
|
|
+ hostdetail::decideEgress(parts->host, ssrfPolicy(), hostdetail::resolveWithGetaddrinfo);
|
|
|
if (!decision.allowed) {
|
|
if (!decision.allowed) {
|
|
|
blocked.push_back(decision.reason);
|
|
blocked.push_back(decision.reason);
|
|
|
throw ApiError(ErrCode::Forbidden, "egress_blocked", decision.reason);
|
|
throw ApiError(ErrCode::Forbidden, "egress_blocked", decision.reason);
|
|
@@ -1788,6 +2320,332 @@ struct HostContext::Impl {
|
|
|
return out;
|
|
return out;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ // --- mail ---------------------------------------------------------------
|
|
|
|
|
+
|
|
|
|
|
+ /// Report a transport failure, leaving its verbatim detail behind.
|
|
|
|
|
+ ///
|
|
|
|
|
+ /// An operator trace, which the ctx.fetch and embedding paths both had to
|
|
|
|
|
+ /// learn to leave: a failing provider visible ONLY inside a tenant's
|
|
|
|
|
+ /// function means the journal says nothing at all, which is the wrong way
|
|
|
|
|
+ /// round. The transport's own message belongs here and nowhere else, because
|
|
|
|
|
+ /// it carries curl's error buffer and the server's reply text verbatim.
|
|
|
|
|
+ [[noreturn]] void failMail(const char* what, const net::MailFailure& f) {
|
|
|
|
|
+ spdlog::warn("ctx.mail {} failed (project {}, function {}): {} status {} retryable {} - {}",
|
|
|
|
|
+ what, config.project, config.functionId, f.slug, f.status, f.retryable,
|
|
|
|
|
+ f.message);
|
|
|
|
|
+ throw hostdetail::apiErrorForMail(f);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /// The account and the per-call bounds for one mail session.
|
|
|
|
|
+ ///
|
|
|
|
|
+ /// Everything that decides WHETHER the session may happen is here, before a
|
|
|
|
|
+ /// socket exists: the TLS posture, the egress classification and the budget.
|
|
|
|
|
+ /// The three operations below differ only in what they then say on the wire.
|
|
|
|
|
+ struct MailSetup {
|
|
|
|
|
+ net::MailAccount account;
|
|
|
|
|
+ net::MailTransferOptions options;
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ MailSetup mailSetup(const nlohmann::json& payload) {
|
|
|
|
|
+ // curl_global_init is not thread-safe, and curl's lazy first-use
|
|
|
|
|
+ // initialisation from two pool threads at once is a real race rather
|
|
|
|
|
+ // than a theoretical one. Done once per process, and it also carries the
|
|
|
|
|
+ // transport's refusal to run on a libcurl that was not built
|
|
|
|
|
+ // thread-safe: fail closed, before any credential is sent.
|
|
|
|
|
+ static std::once_flag once;
|
|
|
|
|
+ static std::string initError;
|
|
|
|
|
+ std::call_once(once, [] { initError = net::mailGlobalInit(); });
|
|
|
|
|
+ if (!initError.empty())
|
|
|
|
|
+ throw ApiError(ErrCode::Unavailable, "mail_unavailable", initError);
|
|
|
|
|
+
|
|
|
|
|
+ MailSetup s;
|
|
|
|
|
+ s.account.host = payload.value("host", std::string());
|
|
|
|
|
+ if (s.account.host.empty())
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "ctx.mail needs a host");
|
|
|
|
|
+
|
|
|
|
|
+ if (payload.contains("port") && !payload.at("port").is_null()) {
|
|
|
|
|
+ const nlohmann::json& port = payload.at("port");
|
|
|
|
|
+ if (!port.is_number_integer() || port.get<int64_t>() <= 0 ||
|
|
|
|
|
+ port.get<int64_t>() > 65535)
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "port must be an integer between 1 and 65535");
|
|
|
|
|
+ s.account.port = static_cast<uint16_t>(port.get<int64_t>());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ s.account.tls = !payload.contains("tls") || !payload.at("tls").is_boolean()
|
|
|
|
|
+ ? true
|
|
|
|
|
+ : payload.at("tls").get<bool>();
|
|
|
|
|
+ s.account.startTls = payload.contains("startTls") &&
|
|
|
|
|
+ payload.at("startTls").is_boolean() &&
|
|
|
|
|
+ payload.at("startTls").get<bool>();
|
|
|
|
|
+ // Refused rather than resolved by precedence: implicit TLS and STARTTLS
|
|
|
|
|
+ // are different ports and different handshakes, so a request for both
|
|
|
|
|
+ // is a misunderstanding, and silently picking one would leave an author
|
|
|
|
|
+ // believing the other is in force.
|
|
|
|
|
+ if (s.account.tls && s.account.startTls)
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
|
|
|
|
|
+ "ctx.mail takes tls or startTls, not both: implicit TLS is a different "
|
|
|
|
|
+ "port and a different handshake from STARTTLS");
|
|
|
|
|
+ // Plaintext is what the transport says the host layer must refuse off
|
|
|
|
|
+ // loopback. The credentials go over this connection in the clear, so the
|
|
|
|
|
+ // only place it is defensible is a server on this machine.
|
|
|
|
|
+ if (!s.account.tls && !s.account.startTls &&
|
|
|
|
|
+ !hostdetail::isLoopbackLiteral(s.account.host))
|
|
|
|
|
+ throw ApiError(ErrCode::Forbidden, "mail_tls_required",
|
|
|
|
|
+ "a mail session to '" + s.account.host +
|
|
|
|
|
+ "' must use TLS or STARTTLS; an unencrypted session is permitted "
|
|
|
|
|
+ "only to a loopback address");
|
|
|
|
|
+
|
|
|
|
|
+ // Resolved BEFORE the egress check, so a typo in a secret's name is
|
|
|
|
|
+ // reported as a typo rather than as whatever the host lookup happens to
|
|
|
|
|
+ // say. Both are the author's mistake, and the one they can act on is
|
|
|
|
|
+ // the one they wrote two lines earlier.
|
|
|
|
|
+ s.account.user = hostdetail::mailCredential(payload, config.env, "user", "userSecret");
|
|
|
|
|
+ s.account.password =
|
|
|
|
|
+ hostdetail::mailCredential(payload, config.env, "password", "passwordSecret");
|
|
|
|
|
+
|
|
|
|
|
+ // The SAME classifier ctx.fetch goes through: a literal is classified
|
|
|
|
|
+ // directly, a name is resolved EXACTLY ONCE and every address it returns
|
|
|
|
|
+ // is classified. The approved address is then pinned for the transport,
|
|
|
|
|
+ // because re-resolving IS the rebinding window.
|
|
|
|
|
+ auto decision = hostdetail::decideEgress(s.account.host, ssrfPolicy(),
|
|
|
|
|
+ hostdetail::resolveWithGetaddrinfo);
|
|
|
|
|
+ if (!decision.allowed) {
|
|
|
|
|
+ blocked.push_back(decision.reason);
|
|
|
|
|
+ throw ApiError(ErrCode::Forbidden, "egress_blocked", decision.reason);
|
|
|
|
|
+ }
|
|
|
|
|
+ s.options.pinnedAddresses = {decision.pinnedAddress};
|
|
|
|
|
+
|
|
|
|
|
+ // Checked BEFORE connecting, so an exhausted budget costs no socket.
|
|
|
|
|
+ // Not an egress refusal: nothing about the destination was wrong.
|
|
|
|
|
+ const int64_t budget = hostdetail::outboundTimeoutMs(config.deadlineMs, elapsedMs(), 0);
|
|
|
|
|
+ if (budget <= 0)
|
|
|
|
|
+ throw ApiError(ErrCode::Unavailable, "deadline_exceeded",
|
|
|
|
|
+ "the run's time budget is exhausted; not connecting to '" +
|
|
|
|
|
+ s.account.host + "'");
|
|
|
|
|
+ net::MailBudgetRequest want;
|
|
|
|
|
+ want.remainingBudgetMs = budget;
|
|
|
|
|
+ // No operator-configured mail timeouts to narrow with - there is no
|
|
|
|
|
+ // settings field for them - so both phases are derived from the run's
|
|
|
|
|
+ // own remaining budget. Stated rather than left to be inferred from two
|
|
|
|
|
+ // zeroes. The per-call value is narrowing only, which is what lets
|
|
|
|
|
+ // resolveMailBudget report a timeout as the script's own choice.
|
|
|
|
|
+ want.callTimeoutMs = hostdetail::mailTimeoutFrom(payload);
|
|
|
|
|
+ s.options.budget = net::resolveMailBudget(want);
|
|
|
|
|
+ s.options.maxBytes = hostdetail::kCtxMailMaxBytes;
|
|
|
|
|
+
|
|
|
|
|
+ return s;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /// `__hostMail(op, payload)` - read a mailbox, list mailboxes, send a message.
|
|
|
|
|
+ ///
|
|
|
|
|
+ /// Three operations, deliberately few, each opening ONE session and closing
|
|
|
|
|
+ /// it. A read is ONE login for the whole thing (EXAMINE, UID SEARCH, UID
|
|
|
|
|
+ /// FETCH): a login per message is what gets a mail account throttled or
|
|
|
|
|
+ /// locked, which is why the session is held across the commands rather than
|
|
|
|
|
+ /// reopened per uid.
|
|
|
|
|
+ ///
|
|
|
|
|
+ /// No scope rule gates this, for the same reason none gates ctx.fetch: the
|
|
|
|
|
+ /// destination is outside the tenancy a policy describes, so the gates that
|
|
|
|
|
+ /// apply are the egress guard and the credential - and a named credential is
|
|
|
|
|
+ /// a project secret only an admin can store.
|
|
|
|
|
+ nlohmann::json mailCall(const std::string& op, const nlohmann::json& payload) {
|
|
|
|
|
+ if (!payload.is_object())
|
|
|
|
|
+ throw ApiError(ErrCode::BadRequest, "validation", "the request must be an object");
|
|
|
|
|
+ if (op != "read" && op != "mailboxes" && op != "send")
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
|
|
+ "ctx.mail does not support '" + op + "'");
|
|
|
|
|
+
|
|
|
|
|
+ const MailSetup s = mailSetup(payload);
|
|
|
|
|
+ try {
|
|
|
|
|
+ if (op == "send") return mailSend(s, payload);
|
|
|
|
|
+ if (op == "mailboxes") return mailMailboxes(s);
|
|
|
|
|
+ return mailRead(s, payload);
|
|
|
|
|
+ } catch (const net::ImapCommandError& e) {
|
|
|
|
|
+ // A script author's typo is data, and the builder's message names
|
|
|
|
|
+ // the field the author can change. Nothing it says comes from the
|
|
|
|
|
+ // server or from a credential.
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "mail_bad_argument", e.what());
|
|
|
|
|
+ } catch (const net::MailBuildError& e) {
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "mail_bad_message", e.what());
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /// Every command carries its mailbox in the COMMAND and leaves the URL path
|
|
|
|
|
+ /// EMPTY, which is not a detail: a mailbox in the path is what makes curl
|
|
|
|
|
+ /// issue its own SELECT, and SELECT opens the mailbox read-WRITE. EXAMINE is
|
|
|
|
|
+ /// the read-only form, and with BODY.PEEK that pair is what makes a read
|
|
|
|
|
+ /// touch no flag at all.
|
|
|
|
|
+ std::string mailCommand(net::ImapSession& session, const char* what,
|
|
|
|
|
+ const net::ImapCommand& command) {
|
|
|
|
|
+ std::string response;
|
|
|
|
|
+ const net::MailFailure f =
|
|
|
|
|
+ session.command(std::string(), hostdetail::customRequestFor(command), response);
|
|
|
|
|
+ if (!f.ok()) failMail(what, f);
|
|
|
|
|
+ return response;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ nlohmann::json mailRead(const MailSetup& s, const nlohmann::json& payload) {
|
|
|
|
|
+ const std::string mailbox = payload.contains("mailbox") &&
|
|
|
|
|
+ payload.at("mailbox").is_string()
|
|
|
|
|
+ ? payload.at("mailbox").get<std::string>()
|
|
|
|
|
+ : std::string("INBOX");
|
|
|
|
|
+ const int64_t limit = hostdetail::mailReadLimit(payload);
|
|
|
|
|
+ const net::ImapSearchCriteria criteria = hostdetail::mailCriteriaFrom(
|
|
|
|
|
+ payload.contains("criteria") ? payload.at("criteria") : nlohmann::json());
|
|
|
|
|
+
|
|
|
|
|
+ net::ImapSession session;
|
|
|
|
|
+ const net::MailFailure opened = session.open(s.account, s.options);
|
|
|
|
|
+ if (!opened.ok()) failMail("open", opened);
|
|
|
|
|
+
|
|
|
|
|
+ // One tagger for the session: a tag reused inside a session makes two
|
|
|
|
|
+ // commands indistinguishable, and the failure mode is a wrong answer
|
|
|
|
|
+ // attributed to the wrong command rather than an error.
|
|
|
|
|
+ net::ImapTagger tagger;
|
|
|
|
|
+ mailCommand(session, "examine", net::imapExamine(tagger.next(), mailbox));
|
|
|
|
|
+
|
|
|
|
|
+ const std::string searched =
|
|
|
|
|
+ mailCommand(session, "search", net::imapUidSearch(tagger.next(), criteria));
|
|
|
|
|
+ const net::ImapSearchResult found = net::parseSearchResponse(searched);
|
|
|
|
|
+ if (found.status != net::ImapParse::Ok)
|
|
|
|
|
+ failMail("search", hostdetail::mailParseFailure(found.status, "search"));
|
|
|
|
|
+
|
|
|
|
|
+ const std::vector<uint64_t> uids = hostdetail::newestUids(found.uids, limit);
|
|
|
|
|
+ nlohmann::json messages = nlohmann::json::array();
|
|
|
|
|
+ if (uids.empty())
|
|
|
|
|
+ return nlohmann::json{{"messages", messages},
|
|
|
|
|
+ {"matched", static_cast<int64_t>(found.uids.size())}};
|
|
|
|
|
+
|
|
|
|
|
+ // TWO commands per uid, and both halves of that are MEASURED rather
|
|
|
|
|
+ // than chosen.
|
|
|
|
|
+ //
|
|
|
|
|
+ // Per UID, because curl's IMAP download hands the write callback ZERO
|
|
|
|
|
+ // bytes for a UID FETCH naming more than one uid - `7,9` and `7:9` both
|
|
|
|
|
+ // produce nothing at all, where `7` produces the untagged line and the
|
|
|
|
|
+ // literal. The rule that matters is ONE LOGIN for the whole read, not
|
|
|
|
|
+ // one command, and the session holds its connection across every
|
|
|
|
|
+ // command here. Note the consequence: a read near the 200-message cap
|
|
|
|
|
+ // is 400 round trips, and what actually limits it is the run's wall
|
|
|
|
|
+ // budget rather than the cap.
|
|
|
|
|
+ //
|
|
|
|
|
+ // Two parts, because a body-part specifier names a single part while a
|
|
|
|
|
+ // message's headers and its text are two, and a surface that returned
|
|
|
|
|
+ // only one of them answers no useful question about a mailbox. Both are
|
|
|
|
|
+ // BODY.PEEK, which is the only form the builder emits - the unpeeked
|
|
|
|
|
+ // form sets \Seen as a side effect of reading.
|
|
|
|
|
+ int64_t keptBytes = 0;
|
|
|
|
|
+ for (const uint64_t uid : uids) {
|
|
|
|
|
+ const std::string headerBytes = mailCommand(
|
|
|
|
|
+ session, "fetch", net::imapUidFetch(tagger.next(), {uid}, "HEADER"));
|
|
|
|
|
+ const net::ImapFetchResult headers = hostdetail::parseCurlFetch(headerBytes);
|
|
|
|
|
+ // NOT just Malformed. NeedMore means the response is INCOMPLETE,
|
|
|
|
|
+ // and by now the transport has finished the transfer - so it means
|
|
|
|
|
+ // the server stopped mid-literal, and the partial bytes must never
|
|
|
|
|
+ // become a message body. See parseCurlFetch() for why restoring the
|
|
|
|
|
+ // framing cannot hide this.
|
|
|
|
|
+ if (headers.status != net::ImapParse::Ok)
|
|
|
|
|
+ failMail("fetch", hostdetail::mailParseFailure(headers.status, "header fetch"));
|
|
|
|
|
+
|
|
|
|
|
+ const std::string textBytes =
|
|
|
|
|
+ mailCommand(session, "fetch", net::imapUidFetch(tagger.next(), {uid}, "TEXT"));
|
|
|
|
|
+ const net::ImapFetchResult bodies = hostdetail::parseCurlFetch(textBytes);
|
|
|
|
|
+ if (bodies.status != net::ImapParse::Ok)
|
|
|
|
|
+ failMail("fetch", hostdetail::mailParseFailure(bodies.status, "body fetch"));
|
|
|
|
|
+
|
|
|
|
|
+ const net::ImapFetchRecord* h = hostdetail::recordForUid(headers, uid);
|
|
|
|
|
+ const net::ImapFetchRecord* b = hostdetail::recordForUid(bodies, uid);
|
|
|
|
|
+ // A uid the server did not return is an ordinary outcome of a
|
|
|
|
|
+ // mailbox that changed between the SEARCH and the FETCH: it is
|
|
|
|
|
+ // SKIPPED, never reported as a blank message.
|
|
|
|
|
+ //
|
|
|
|
|
+ // The trap is above the parser rather than in it. An implementation
|
|
|
|
|
+ // that saw a status of Ok and read the response buffer anyway
|
|
|
|
|
+ // handed the PROTOCOL LINE back as the e-mail, and the result was a
|
|
|
|
|
+ // successful fetch whose body was "A003 OK Fetch completed" and
|
|
|
|
|
+ // whose sender was empty. Every byte a message carries here comes
|
|
|
|
|
+ // from the parser's bodyParts and never from the buffer.
|
|
|
|
|
+ if (h == nullptr && b == nullptr) continue;
|
|
|
|
|
+
|
|
|
|
|
+ const std::string header = hostdetail::soleBodyPart(h, "HEADER");
|
|
|
|
|
+ const std::string text = hostdetail::soleBodyPart(b, "TEXT");
|
|
|
|
|
+ // The aggregate half of the cap. The transport bounded each command
|
|
|
|
|
+ // on its own; this bounds the array the run is building out of them.
|
|
|
|
|
+ keptBytes += static_cast<int64_t>(header.size() + text.size());
|
|
|
|
|
+ if (keptBytes > hostdetail::kCtxMailMaxBytes)
|
|
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "mail_too_large",
|
|
|
|
|
+ "this read passed the " +
|
|
|
|
|
+ std::to_string(hostdetail::kCtxMailMaxBytes) +
|
|
|
|
|
+ " bytes a single function run may load; lower the limit or "
|
|
|
|
|
+ "narrow the criteria");
|
|
|
|
|
+
|
|
|
|
|
+ nlohmann::json m = net::toJson(h != nullptr ? *h : *b);
|
|
|
|
|
+ if (!m.contains("uid")) m["uid"] = uid;
|
|
|
|
|
+ // toJson is a projection that deliberately omits part BYTES, so the
|
|
|
|
|
+ // two parts are added here - the one place that owns both the size
|
|
|
|
|
+ // cap and the encoding decision.
|
|
|
|
|
+ hostdetail::putMailText(m, "header", header);
|
|
|
|
|
+ hostdetail::putMailText(m, "text", text);
|
|
|
|
|
+ messages.push_back(std::move(m));
|
|
|
|
|
+ }
|
|
|
|
|
+ // `matched` is the whole search result and `messages` only the newest
|
|
|
|
|
+ // `limit` of it, so a script can tell "that is all of it" from "there is
|
|
|
|
|
+ // more behind this" instead of inferring it from a full page.
|
|
|
|
|
+ return nlohmann::json{{"messages", std::move(messages)},
|
|
|
|
|
+ {"matched", static_cast<int64_t>(found.uids.size())}};
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ nlohmann::json mailMailboxes(const MailSetup& s) {
|
|
|
|
|
+ net::ImapSession session;
|
|
|
|
|
+ const net::MailFailure opened = session.open(s.account, s.options);
|
|
|
|
|
+ if (!opened.ok()) failMail("open", opened);
|
|
|
|
|
+
|
|
|
|
|
+ net::ImapTagger tagger;
|
|
|
|
|
+ // An empty reference and `*` for the pattern: everything the account can
|
|
|
|
|
+ // see. Both go through the builder, which is why the pattern is quoted -
|
|
|
|
|
+ // `*` is an atom-special.
|
|
|
|
|
+ const std::string listed =
|
|
|
|
|
+ mailCommand(session, "list", net::imapList(tagger.next(), std::string(), "*"));
|
|
|
|
|
+ const net::ImapListResult result = net::parseListResponse(listed);
|
|
|
|
|
+ if (result.status != net::ImapParse::Ok)
|
|
|
|
|
+ failMail("list", hostdetail::mailParseFailure(result.status, "mailbox list"));
|
|
|
|
|
+
|
|
|
|
|
+ nlohmann::json out = nlohmann::json::array();
|
|
|
|
|
+ for (const net::ImapMailbox& m : result.mailboxes) {
|
|
|
|
|
+ nlohmann::json entry = nlohmann::json::object();
|
|
|
|
|
+ hostdetail::putMailText(entry, "name", hostdetail::decodeMailboxName(m.nameRaw));
|
|
|
|
|
+ entry["flags"] = m.flags;
|
|
|
|
|
+ // Empty means "no delimiter" - a flat namespace - never "unknown",
|
|
|
|
|
+ // which is what the parser's contract says and what a script
|
|
|
|
|
+ // building a path has to be able to rely on.
|
|
|
|
|
+ entry["delimiter"] = m.delimiter;
|
|
|
|
|
+ out.push_back(std::move(entry));
|
|
|
|
|
+ }
|
|
|
|
|
+ return out;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ nlohmann::json mailSend(const MailSetup& s, const nlohmann::json& payload) {
|
|
|
|
|
+ const net::MailMessage msg = hostdetail::mailMessageFrom(payload);
|
|
|
|
|
+ // The seed is the only variation in the rendered bytes, and it has to be
|
|
|
|
|
+ // unpredictable per message: a guessable MIME boundary lets anyone who
|
|
|
|
|
+ // can influence any part of a body close the multipart early and append
|
|
|
|
|
+ // parts of their own.
|
|
|
|
|
+ uint64_t seed = 0;
|
|
|
|
|
+ if (RAND_bytes(reinterpret_cast<unsigned char*>(&seed), sizeof(seed)) != 1)
|
|
|
|
|
+ throw ApiError(ErrCode::Internal, "crypto_unavailable",
|
|
|
|
|
+ "no entropy was available for a MIME boundary");
|
|
|
|
|
+ const net::BuiltMail built = net::buildMail(msg, seed);
|
|
|
|
|
+
|
|
|
|
|
+ net::MailEnvelope envelope;
|
|
|
|
|
+ envelope.sender = built.envelopeFrom;
|
|
|
|
|
+ envelope.recipients = built.envelopeRecipients;
|
|
|
|
|
+ const net::MailFailure f = net::smtpSend(s.account, s.options, envelope, built.data);
|
|
|
|
|
+ if (!f.ok()) failMail("send", f);
|
|
|
|
|
+ // The ENVELOPE recipients, which is what was actually offered to the
|
|
|
|
|
+ // server - not the To header, which a sender may make say anything and
|
|
|
|
|
+ // which carries no Bcc at all.
|
|
|
|
|
+ return nlohmann::json{{"ok", true}, {"accepted", built.envelopeRecipients}};
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
/// `__hostTime(op, payload)`. Every answer comes from functions/timezone.hpp
|
|
/// `__hostTime(op, payload)`. Every answer comes from functions/timezone.hpp
|
|
|
/// so a function and a cron schedule can never disagree about what 08:00 in
|
|
/// so a function and a cron schedule can never disagree about what 08:00 in
|
|
|
/// a zone means.
|
|
/// a zone means.
|
|
@@ -1989,6 +2847,7 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
|
|
|
JSValue crypto = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::cryptoCall>, 2, 0, 1, data);
|
|
JSValue crypto = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::cryptoCall>, 2, 0, 1, data);
|
|
|
JSValue time = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::timeCall>, 2, 0, 1, data);
|
|
JSValue time = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::timeCall>, 2, 0, 1, data);
|
|
|
JSValue files = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::filesCall>, 2, 0, 1, data);
|
|
JSValue files = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::filesCall>, 2, 0, 1, data);
|
|
|
|
|
+ JSValue mail = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::mailCall>, 2, 0, 1, data);
|
|
|
JS_FreeValue(ctx, cookie);
|
|
JS_FreeValue(ctx, cookie);
|
|
|
|
|
|
|
|
const std::string_view prelude = hostPreludeSource();
|
|
const std::string_view prelude = hostPreludeSource();
|
|
@@ -2004,8 +2863,8 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
|
|
|
JS_FreeValue(ctx, exc);
|
|
JS_FreeValue(ctx, exc);
|
|
|
ok = false;
|
|
ok = false;
|
|
|
} else {
|
|
} else {
|
|
|
- JSValueConst args[8] = {*ctxObject, db, fetch, log, jobs, crypto, time, files};
|
|
|
|
|
- JSValue applied = JS_Call(ctx, factory, JS_UNDEFINED, 8, args);
|
|
|
|
|
|
|
+ JSValueConst args[9] = {*ctxObject, db, fetch, log, jobs, crypto, time, files, mail};
|
|
|
|
|
+ JSValue applied = JS_Call(ctx, factory, JS_UNDEFINED, 9, args);
|
|
|
if (JS_IsException(applied)) {
|
|
if (JS_IsException(applied)) {
|
|
|
JSValue exc = JS_GetException(ctx);
|
|
JSValue exc = JS_GetException(ctx);
|
|
|
error = "the host prelude failed to install: " + toText(ctx, exc);
|
|
error = "the host prelude failed to install: " + toText(ctx, exc);
|
|
@@ -2023,6 +2882,7 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
|
|
|
JS_FreeValue(ctx, crypto);
|
|
JS_FreeValue(ctx, crypto);
|
|
|
JS_FreeValue(ctx, time);
|
|
JS_FreeValue(ctx, time);
|
|
|
JS_FreeValue(ctx, files);
|
|
JS_FreeValue(ctx, files);
|
|
|
|
|
+ JS_FreeValue(ctx, mail);
|
|
|
return ok;
|
|
return ok;
|
|
|
}
|
|
}
|
|
|
|
|
|