Skip to content

[FIX] Fix RFC compliance issues and race conditions across SMTP and JMAP RFC-8621 - #3236

Draft
prosgarz35 wants to merge 1 commit into
apache:masterfrom
prosgarz35:rfc
Draft

prosgarz35 wants to merge 1 commit into
apache:masterfrom
prosgarz35:rfc

Conversation

@prosgarz35

Copy link
Copy Markdown
Contributor

Summary

This pull request addresses several RFC compliance issues, race conditions, and determinism inconsistencies found during protocol verification of SMTP and JMAP RFC-8621 implementations.


Changes

1. SMTP: Remove extraneous trailing parenthesis in EHLO greeting (RFC 5321 §4.1.1.1)

  • File: protocols/smtp/src/main/java/org/apache/james/protocols/smtp/core/esmtp/EhloCmdHandler.java
  • Issue: The EHLO greeting response string formatted the client remote address with an unbalanced closing parenthesis ]) instead of ]:
    250 hostname Hello client [192.168.1.1])
    
  • Fix: Changed .append("])") to .append("]"), conforming strictly to RFC 5321 §4.1.1.1 syntax.

2. JMAP RFC-8621: Ensure atomicity in Email/set update and eliminate race window (RFC 8621 §3)

  • File: server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/method/EmailSetUpdatePerformer.scala
  • Issue: Previously, updateSingleMessage only used atomic execution when both mailbox IDs and flags were updated simultaneously (isMailboxUpdate && isFlagUpdate). In the else branch, flag updates and mailbox ID updates were executed in a chained non-atomic fashion (updateFlags(...).flatMap(... => updateMailboxIds(...))), introducing a partial-update failure window and potential data race between concurrent updates.
  • Fix:
    • Branching is now strictly separated into dedicated, atomic store operations:
      • Combined update: calls messageIdManager.updateEmail(...) (single atomic operation).
      • Flags-only update: calls messageIdManager.setFlagsReactive(...) directly.
      • Mailbox-only update: calls messageIdManager.setInMailboxesReactive(...) directly.
    • Removed redundant non-atomic helper methods updateFlags and updateMailboxIds.

3. JMAP RFC-8621: Deterministic message copy selection for multi-mailbox emails (RFC 8621 §4.1)

  • File: server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/mail/Email.scala
  • Issue: When an email exists across multiple mailboxes, message._2 contains a Seq[MessageResult] whose order depends on the backend store driver and is not guaranteed. View factories (EmailMetadataViewFactory, EmailHeaderViewFactory, EmailFullViewFactory, EmailFastViewReader, and EmailFastViewWithAttachmentsMetadataReader) previously called .headOption, which could lead to non-deterministic selection of the representative message metadata (such as size and receivedAt).
  • Fix: Added Email.pickFirstMessage(messages: Seq[MessageResult]) which deterministically sorts the message results by internal date timestamp and mailbox ID (messages.sortBy(m => (m.getInternalDate.getTime, m.getMailboxId.serialize())).headOption). All view factories now use this deterministic selection helper.

4. JMAP RFC-8621: Fix typo in validateTextBody error message

  • File: server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/mail/EmailSet.scala
  • Issue: validateTextBody raised an IllegalArgumentException stating "Expecting htmlBody type to be text/html" when validating a non-text/plain part due to copy-paste from validateHtmlBody.
  • Fix: Updated the error message to accurately state "Expecting textBody type to be text/plain".
@prosgarz35
prosgarz35 marked this pull request as ready for review October 6, 2026 04:42
SMTPResponse resp = new SMTPResponse(SMTPRetCode.MAIL_OK, new StringBuilder(session.getConfiguration().getHelloName()).append(" Hello ").append(argument)
.append(" [")
.append(session.getRemoteAddress().getAddress().getHostAddress()).append("])"));
.append(session.getRemoteAddress().getAddress().getHostAddress()).append("]"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

his isn't an RFC 5321 compliance issue: the text after the domain in an EHLO reply is free-form. It's a cosmetic fix, and still worth doing.

HeloCmdHandler has the same "])" at protocols/smtp/src/main/java/org/apache/james/protocols/smtp/core/HeloCmdHandler.java:85. Please fix it too.

.map(list => list.reduce(_ ++ _))
}

// RFC 8621 sec.4.1: Deterministically pick representative message copy across multiple mailboxes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We aggregate flag and the rest of the message is immutable. Please drop this unneeded commit.

textBody match {
case None => SMono.empty
case Some(text :: Nil) if !text.`type`.value.equals("text/plain") => SMono.error(new IllegalArgumentException("Expecting htmlBody type to be text/html"))
case Some(text :: Nil) if !text.`type`.value.equals("text/plain") => SMono.error(new IllegalArgumentException("Expecting textBody type to be text/plain"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok ;-)

.doOnSuccess(_ => auditMove(Seq(messageId), mailboxIds.value, targetIds.value, session))
.onErrorResume(e => SMono.just[EmailUpdateResult](EmailUpdateFailure(EmailSet.asUnparsed(messageId), e)))
.switchIfEmpty(SMono.just[EmailUpdateResult](EmailUpdateSuccess(messageId)))
} else {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the race described doesn't exist

  • The combined case is already handled. When both mailboxes and flags change, the code already calls the atomic updateEmail (JAMES-3728).
  • The else branch only ever does one real operation. It's reached only when at most one of the two changes. One of updateFlags/updateMailboxIds then returns EmailUpdateSuccess
    without touching the store. There was never a "partial update window" between two writes.
  • The refactor is equivalent but brings no benefit. It is a bit more explicit, at the cost of copy-pasting the flag computation (the fold over originalFlags), which now appears
    twice.
  • Verdict: a cosmetic refactor sold as a race-condition fix. Drop it.
@chibenwa

chibenwa commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Have tests for your changes please.

@chibenwa
chibenwa marked this pull request as draft October 6, 2026 19:53
@chibenwa

Copy link
Copy Markdown
Contributor

Hello @prosgarz35
Would you find time to shrink this work to what is a real life issue?
Best regards,
Benoit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants