allthingssecurity opened a new pull request, #30914:
URL: https://github.com/apache/camel/pull/30914

   # Description
   
   [CAMEL-27531](https://issues.apache.org/jira/browse/CAMEL-27531)
   
   The mail consumer marks a mail (SEEN, DELETED, copyTo/moveTo) when its 
exchange completes. With `pollEnrich` or a `ConsumerTemplate`, the polling 
consumer only queues the exchange, which completes later on the caller's thread 
while the poll thread goes on: it closes the folder (`closeFolder=true`), 
disconnects (`disconnect=true`), or connects again in the next poll. Four 
things go wrong:
   
   - With `disconnect=true` the poll has set `folder` to null, so `onComplete` 
fails with a `NullPointerException` in `mailToCommit` (`folder.isOpen()`), 
which `UnitOfWorkHelper` only logs. The mail is never marked and its idempotent 
key stays added: with `delete=true` every `pollEnrich` gets the same mail 
again, and with an idempotent repository the unseen mail is skipped for good. 
The same happens when the poll re-creates the connection while an exchange of 
the previous poll completes.
   - `mailToCommit` checks that the mail object belongs to the current open of 
the folder (CAMEL-25808), then `processCommit` checks `folder.isOpen()` again 
and, when the folder was closed in between (by the poll, a dropped connection 
or a stop), opens it itself and marks the same mail object. After an expunge 
its message number designates another mail, which gets marked SEEN, or DELETED 
and expunged without ever being routed.
   - When marking fails (`MessageRemovedException`, `FolderClosedException`, a 
failed copy, `IllegalStateException`), `processCommit` reports it but leaves 
the idempotent key added, while `mailToCommit` settles the key in the same 
situation.
   - An exchange that completes after the consumer was stopped (a 
`ConsumerTemplate` or `pollEnrich` whose consumer is stopped, or a forced 
shutdown) opens the folder again in `mailToCommit` or `processCommit`. `doStop` 
closed the folder and the store but kept both objects, and `IMAPFolder.open` 
gets its connection from `IMAPStore.getProtocol`, which logs in again with the 
host, user and password the closed store kept, without checking that the store 
is connected (angus-mail 2.0.5). The stopped consumer marks the mail and leaves 
an open IMAP connection that nobody closes: a later start replaces the store 
and the folder.
   
   ## The fix
   
   - `MailConsumer` gets a lock for the folder and the store. The poll holds it 
while it connects and opens the folder, then again while it reads the message 
count and the UIDVALIDITY of that open (it returns at once if the consumer was 
stopped in between), and while it closes the folder and disconnects at its end 
(one step now, so a completion does not run between the close and the 
disconnect). The completion (`onComplete`, now `commit(...)`) holds it while it 
checks the mail and marks it.
   - The lock is never held while a mail is routed, so the completion of a mail 
routed by the poll thread (the usual route consumer, also with `threads()`) 
takes it without contention and nothing waits for a route while holding it.
   - `doStop` closes the folder and the store while holding the lock. The 
completion checks `isRunAllowed()` under the lock before it touches the folder: 
once the consumer is stopping or stopped, the mail is not marked (WARN), its 
key is settled as on commit, and nothing opens the folder or connects. A 
completion that already holds the lock when the stop comes finishes its mark 
first, and `doStop` then closes the folder and the store it used, so no 
connection is left open in that order either. A poll that is running when the 
consumer stops does not log in again either. `doStop` sets a flag under the 
lock (cleared by `doStart`), and the poll checks it under the lock before it 
connects, and again before it reads the message count and the UIDVALIDITY of 
the folder it opened: on a closed IMAP folder, `getMessageCount()` and 
`getUIDValidity()` send a STATUS through `IMAPStore.getStoreProtocol`, which 
logs in again in the same way (before, the poll read the count outside the 
lock, in `poll
 ()` and again in `retrieveAllMessages()`, and the UIDVALIDITY after fetching 
the UIDs). `retrieveAllMessages()` now uses the count read under the lock. The 
poll's later calls on the folder (`search`, `getSortedMessages`, `getMessage`, 
`fetch`, `getUID`, and reading a mail) check that the folder is open and fail 
on a closed folder without connecting. A suspended consumer (`pollEnrich` 
suspends its consumer between calls) still marks its mails, and graceful 
shutdown suspends route consumers until their exchanges completed, so the usual 
flow is not affected.
   - When the completion finds no folder (the poll disconnected), it connects 
again, finds the mail by its UID (IMAP, with the UIDVALIDITY check of 
CAMEL-25808) or by its key (POP3) as after any other new open of the folder, 
marks it, and disconnects again with `disconnect=true`. Connecting again is the 
normal path for `pollEnrich` with `disconnect=true`, so it is logged at DEBUG. 
It costs a full connect, login, select, the lookup of the mail (one `UID FETCH` 
for IMAP; for POP3 the headers of the mails until the key matches), the mark 
and a logout for each completion, one completion at a time, and at most one 
connection per consumer at a time; before this fix these mails were not marked 
at all.
   - `processCommit` no longer opens an IMAP folder again for a mail object 
that `mailToCommit` already checked: neither the poll nor `doStop` can close it 
in between, so only a dropped connection can, and the mail is then not marked 
(reported as a `FolderClosedException`). POP3 still opens the folder there, as 
it finds the mail again by its key.
   - In every case where the mail is not marked, `processCommit` settles the 
key as on commit (removed by default, confirmed with 
`idempotentRepositoryRemoveOnCommit=false`), as `mailToCommit` does; it also 
catches `IllegalStateException`. With the default, an unmarked mail is consumed 
again by a later poll (as with a failed `mailToCommit`), instead of being 
skipped until the repository forgets the key.
   
   Not changed here:
   - the route consumer flow without `pollEnrich`/`ConsumerTemplate` behaves as 
before apart from the lock: its completion already ran on the poll thread 
before the poll closed the folder;
   - how long the lock can be held: a completion that comes while the poll 
connects (or reads the message count) waits for it, and a poll or a stop waits 
for a completion that connects again or marks a mail. With the session Camel 
creates, every connect and every read from the server is limited by 
`connectionTimeout` (`mail.<protocol>.connectiontimeout` and 
`mail.<protocol>.timeout`, 30 s by default), so the wait is a few network steps 
of at most that long each, as the poll itself already waits for the server 
today;
   - a stop with a custom `session` that has no timeouts: a stop waits as long 
as a server step under the lock hangs, and `doStop` takes the lock with 
`lock()`, which the interrupt of a forced shutdown does not end. On main a stop 
could already wait for a hung connect, folder open or folder command in the 
same way: `doStop` calls `folder.isOpen()` and `store.isConnected()`, which 
JavaMail synchronizes with them, and waiting for a monitor does not end on an 
interrupt either. With the lock, a stop also waits between the steps of a 
locked section. A `tryLock` with a timeout would have to close the folder and 
the store without the lock, while the poll or the completion still uses them, 
so it is not done here;
   - a `postProcessAction` (`MailBoxPostProcessAction`) still gets the folder 
after the batch, outside the lock, as before: if the consumer stopped 
meanwhile, what it calls on the closed folder is up to it (a call that asks the 
server for the folder status, such as `getMessageCount()`, logs in again on 
IMAP);
   - `closeFolder=true` with an exchange that completes after the poll: 
`mailToCommit` opens the folder again to mark the mail and leaves it open until 
the next poll closes it, as since CAMEL-25867;
   - POP3 finds the mail of a completion after a reconnect by reading the 
headers of the mails until the key matches; looking it up by UIDL would be one 
command, a possible follow-up;
   - consumers sharing an idempotent repository can still route a mail twice: 
separate PR with its own JIRA; both change `MailConsumer` in different places 
and merge without conflict;
   - no upgrade guide entry: users only see mails marked that were not marked 
before, and a mail whose mark failed being consumed again instead of skipped.
   
   ## How it was found
   
   A TLA+ model of the poll thread, the completions on other threads, folder 
close/reopen/disconnect, expunges by another client and dropped connections 
finds the NPE (`disconnect=true`, or a reconnect) and the mark of another mail. 
Both were reproduced against the real consumer and GreenMail. The model with 
the fix (commit as one step under the lock, key settled when not marked) passes 
all properties at the bounds the audit ran; the reconnect switch added for this 
branch was not run yet.
   
   ## Tests
   
   All new test classes are package-private, use JUnit assertions as the module 
does, latches and Awaitility, no sleeps; the mail server is the module's in-JVM 
GreenMail.
   
   - `MailConsumerCommitAfterDisconnectTest` (4): a consumer whose processor 
only queues the exchange (as the polling consumer of `pollEnrich` does), 
`disconnect=true`, the exchange completes after `poll()` returned: the mail is 
marked SEEN and its key removed (IMAP + repository), deleted (IMAP and POP3, 
`delete=true`), and a route with `pollEnrich(...&disconnect=true&delete=true)` 
deletes the enriched mail.
   - `MailConsumerCommitWhileFolderClosesTest` (3): the connection of the 
folder drops after "Mail 1" was checked and another client expunges "Mail 0": 
no mail is marked, the key of "Mail 1" is removed and the next poll routes 
"Mail 1" again. With `closeFolder=true` and with `disconnect=true`, the 
exchange of "Mail 1" completes on another thread while the poll ends; the 
commit waits after the check until the poll ended or waits to end: the poll 
waits for the mark, "Mail 1" is marked and "Mail 2" is not.
   - `MailConsumerCommitFailedKeyTest` (2, Mockito stand-ins as 
`MailConsumerCommitExpungedMessageTest`): a mark that fails with 
`MessageRemovedException` removes the key; one that fails with 
`FolderClosedException` confirms it with 
`idempotentRepositoryRemoveOnCommit=false`.
   - `MailConsumerCommitAfterStopTest` (7): the test counts the connections the 
consumer opens, with a socket factory set as `mail.<protocol>.socketFactory` in 
the session. The consumer is stopped after the poll and the exchange completes 
afterwards (IMAP default options, IMAP `closeFolder=true`, POP3 `delete=true`): 
the folder stays closed, no connection is opened after the stop, the mail is 
not marked or deleted, and the key is removed, or confirmed with 
`idempotentRepositoryRemoveOnCommit=false`. A poll after the stop returns 0 and 
does not connect. A poll that is stopped right after it connected and opened 
the folder (the test stops the consumer from `forceConsumerAsReady()`, which 
the poll calls just after it released the lock; default options and 
`disconnect=true`) routes nothing and opens no connection after the stop. 
(`store.isConnected()` cannot show a new login: it stays false after `close()` 
even when a new connection sits in the pool of the closed store.)
   - `MailConsumerAsyncCommitStressTest` (3): 4 threads call `pollEnrich` 5 
times each on 20 mails, with IMAP `disconnect=true&delete=true`, IMAP 
`closeFolder=true` and POP3 `disconnect=true&delete=true`, all with an 
idempotent repository: no call hangs, every mail is routed once and every mail 
is marked (deleted or SEEN).
   
   On main the 9 tests of the first three classes fail, in 3 runs out of 3 
(27/27): the mail is not marked or deleted (NPE), "Mail 2" is marked instead of 
"Mail 1", and the key is not settled. On main the 7 stop tests fail 3/3 (21/21: 
the stopped consumer opens the folder again and marks the mail, also with POP3; 
a poll after the stop connects and routes the mail; a poll stopped after it 
connected logs in again), and the IMAP and POP3 `disconnect=true` stress tests 
fail 3/3 (18 to 20 mails not deleted); the `closeFolder=true` stress test 
passes there. With the fix: 20 runs in one JVM of the 5 classes, 380/380 (the 
stress class takes under a second per run); camel-mail 270 tests (3 skipped), 0 
failures. `MailIdempotentRepositoryDuplicateTest` passed in that run, but it is 
flaky on main too and unrelated to this change: it asserts the repository size 
while the next POP3 poll, 100 ms later, can add keys again (on main it failed 3 
times in 160 runs, with the same assertion and values as 
 the failures seen with this change). Negative controls, measured on the 
previous revision of this PR (with its 4 stop tests): without the lock 
(everything else kept), the two concurrent tests fail 3/3 and the `pollEnrich` 
test 2/3; with `processCommit` opening the IMAP folder again as before, only 
the dropped-connection test fails, 3/3; without the `isRunAllowed()` check in 
`commit`, the 3 commit-after-stop tests fail 3/3; without the stop flag in the 
poll, only the poll-after-stop test fails, 3/3. With the previous revision of 
this PR, which read the message count outside the lock, the two 
stopped-after-connect tests fail 3/3 (one new connection each) and the other 5 
pass; without the check of the stop flag before the count (the count read under 
the lock), the same two fail 3/3. Merged with the companion PR: the new tests 
of both and the related idempotent and reopen tests, 3 runs, 102/102.
   
   Backport: the NPE with `disconnect=true` is also on camel-4.22.x and 
camel-4.18.x (there in `processCommit`, which has no `mailToCommit`). The check 
against the open of the folder and the UID lookup this fix builds on 
(CAMEL-25808) are on main only, so a backport needs CAMEL-25808 first.
   
   _Claude Code on behalf of allthingssecurity_
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

  • [PR] CAMEL-27531: camel-mail ... allthingssecurity (via GitHub) via commits

Reply via email to