Безопасность, SMTP, очередь отправки, DKIM, деплой на Jambotron (Jambotron v0.2.3 75.1–75.3)

- SMTP-сервер переписан: разбор по строкам, AUTH PLAIN/LOGIN, нет открытого релея,
  MAIL FROM только свой после входа, 250 только после сохранения (иначе 451), лимит размера
- отправка наружу: очередь outbound_queue (V2) с повторами ~22 ч и уведомлением о недоставке;
  Jakarta Mail, режимы off / mx / smarthost, байты письма не меняются (DKIM)
- DKIM: подпись utils-mail-dkim, проверка Apache jDKIM; ключ PKCS#8, старый PKCS#1 читается
- права: письма, папки, вложения — только владельцу (было: любой по номеру); имена вложений без ../
- секреты без значений по умолчанию (DB_PASSWORD, JWT_SECRET), регистрация закрыта,
  admin123 и /api/simulate/receive — только профиль dev
- веб-клиент внутри jar (относительный /api), Dockerfile в 3 этапа, не root, health;
  docker-compose.jambotron.yml: секреты создаются при первом запуске, наружу только 8080
- gradle-wrapper.jar был в .gitignore — сборка не запускалась
- тесты: 26 (SMTP реальным клиентом и сокетом, GreenMail, DKIM подпись+проверка, очередь)

α
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jambotron α
2026-11-05 03:37:43 +01:00
parent b6f6d41813
commit 165edf1a1e
44 changed files with 2626 additions and 1715 deletions
@@ -0,0 +1,130 @@
package com.mailserver.service;
import com.mailserver.delivery.DeliveryWorker;
import com.mailserver.delivery.OutboundMessage;
import jakarta.mail.BodyPart;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.Part;
import jakarta.mail.Session;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
/**
* Stores a message in one of our mailboxes. Mail from outside is checked first — DKIM (signature),
* SPF (the connecting IP against the envelope sender's domain), DMARC (policy of the From domain);
* a failure marks it as spam. Mail from our own logged-in users is trusted.
*/
@Service
public class LocalDelivery implements DeliveryWorker.BounceSender {
private static final Logger log = LoggerFactory.getLogger(LocalDelivery.class);
private final MailService mailService;
private final DkimService dkimService;
private final SpfService spfService;
private final DmarcService dmarcService;
private final String hostname;
public LocalDelivery(MailService mailService, DkimService dkimService, SpfService spfService,
DmarcService dmarcService, @Value("${mailserver.smtp.hostname:localhost}") String hostname) {
this.mailService = mailService;
this.dkimService = dkimService;
this.spfService = spfService;
this.dmarcService = dmarcService;
this.hostname = hostname;
}
/** Blocking: call from a worker thread. */
public void deliver(byte[] raw, String mailbox, String remoteIp, String envelopeFrom, boolean trusted)
throws MessagingException, IOException {
MimeMessage mime = new MimeMessage(Session.getInstance(new Properties()), new ByteArrayInputStream(raw));
String senderEmail = envelopeFrom;
String senderName = null;
if (mime.getFrom() != null && mime.getFrom().length > 0 && mime.getFrom()[0] instanceof InternetAddress from) {
senderEmail = from.getAddress();
senderName = from.getPersonal();
}
String subject = mime.getSubject() == null ? "" : mime.getSubject();
Body body = body(mime);
boolean spam = false;
if (!trusted) {
DkimService.Verification dkim = dkimService.verify(raw);
String spfSender = envelopeFrom == null || envelopeFrom.isEmpty() ? senderEmail : envelopeFrom;
SpfService.SpfResult spf = spfService.checkSpf(spfSender, remoteIp);
boolean spfPassed = spf == SpfService.SpfResult.PASS;
DmarcService.DmarcResult dmarc = dmarcService.checkDmarc(senderEmail, remoteIp, spfPassed, dkim.passed(), dkim.domain());
spam = dmarcService.shouldMarkAsSpam(dmarc) || spf == SpfService.SpfResult.FAIL || (dkim.signed() && !dkim.passed());
log.info("Incoming {} -> {} from {}: DKIM {}, SPF {}, DMARC {}{}", senderEmail, mailbox, remoteIp,
dkim.signed() ? (dkim.passed() ? "pass " + dkim.domain() : "fail") : "none", spf, dmarc, spam ? " → spam" : "");
}
mailService.receiveMessage(senderEmail, senderName, mailbox, subject, body.text(), body.html(), spam).block();
}
/** Non-delivery report into the sender's inbox — only when the sender is our mailbox. */
@Override
public void bounce(OutboundMessage message, String reason) {
String text = "Your message to " + message.getRcptTo() + " could not be delivered.\n\n"
+ "Reason: " + reason + "\n\nAttempts: " + message.getAttempts() + "\n";
try {
mailService.receiveMessage("mailer-daemon@" + hostname, "Mail Delivery System", message.getMailFrom(),
"Undelivered: message to " + message.getRcptTo(), text, false, false).block();
} catch (IllegalArgumentException notOurs) {
log.info("Bounce not stored: sender {} is not a local mailbox", message.getMailFrom());
}
}
record Body(String text, boolean html) {
}
/** HTML part when the message has one, otherwise the plain text; nested multiparts are walked. */
static Body body(Part part) throws MessagingException, IOException {
String html = find(part, "text/html");
if (html != null) {
return new Body(html, true);
}
String plain = find(part, "text/plain");
return new Body(plain == null ? "" : plain, false);
}
private static String find(Part part, String type) throws MessagingException, IOException {
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
return null;
}
if (part.isMimeType(type)) {
Object content = part.getContent();
if (content instanceof String s) {
return s;
}
if (content instanceof InputStream in) {
try (in) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
return null;
}
if (part.isMimeType("multipart/*") && part.getContent() instanceof Multipart multipart) {
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart child = multipart.getBodyPart(i);
String found = find(child, type);
if (found != null) {
return found;
}
}
}
return null;
}
}