Upgraded MailKit and MimeKit to v5.0 (#1226)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-24 08:35:36 +01:00
1 parent d121ec3b47
commit f6a4348820
15 files changed
+242 -85

No files matched your search

@@ -103,7 +103,7 @@
<PackageReference Include="CodeBeam.MudBlazor.Extensions" Version="9.2.0" /> <PackageReference Include="CodeBeam.MudBlazor.Extensions" Version="9.2.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" /> <PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
<PackageReference Include="HtmlAgilityPack" Version="1.12.4" /> <PackageReference Include="HtmlAgilityPack" Version="1.12.4" />
<PackageReference Include="MailKit" Version="4.18.2" /> <PackageReference Include="MailKit" Version="5.0.0" />
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="10.0.15" /> <PackageReference Include="Microsoft.Data.Sqlite.Core" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
@@ -39,6 +39,13 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
/// </summary> /// </summary>
public const long MAX_TEXT_PART_BYTES = 4 * 1024 * 1024; public const long MAX_TEXT_PART_BYTES = 4 * 1024 * 1024;
/// <summary>
/// The longest single header field which is read, in bytes. MimeKit reads 16 KB by default, and the
/// IMAP client hands over a mail with a longer one with an empty header block. A mail to a few
/// hundred people has such a To field, and so has a long thread its References field.
/// </summary>
internal const int MAX_HEADER_FIELD_BYTES = 1024 * 1024;
/// <summary> /// <summary>
/// How many UIDs go into one FETCH. A long list of scattered UIDs makes a long command line, and /// How many UIDs go into one FETCH. A long list of scattered UIDs makes a long command line, and
/// some servers refuse lines beyond a few kilobytes. /// some servers refuse lines beyond a few kilobytes.
@@ -67,6 +74,15 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
/// </summary> /// </summary>
private static readonly TimeSpan DISCONNECT_TIMEOUT = TimeSpan.FromSeconds(5); private static readonly TimeSpan DISCONNECT_TIMEOUT = TimeSpan.FromSeconds(5);
static ImapMailboxConnector()
{
//
// The IMAP client reads every header block with the default options of MimeKit and takes no
// options of its own. Raised here, the limit holds before the first mail is fetched:
//
ParserOptions.Default.MaxHeaderLength = Math.Max(ParserOptions.Default.MaxHeaderLength, MAX_HEADER_FIELD_BYTES);
}
private readonly ImapClient client = new() private readonly ImapClient client = new()
{ {
Timeout = (int)COMMAND_TIMEOUT.TotalMilliseconds, Timeout = (int)COMMAND_TIMEOUT.TotalMilliseconds,
@@ -88,7 +104,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
/// Whether the server tells which mails changed since a point it handed out before (CONDSTORE). /// Whether the server tells which mails changed since a point it handed out before (CONDSTORE).
/// Without it, the flags of every mail have to be fetched to find the changed ones. /// Without it, the flags of every mail have to be fetched to find the changed ones.
/// </summary> /// </summary>
public bool SupportsChangeTracking => this.client.Capabilities.HasFlag(ImapCapabilities.CondStore); public bool SupportsChangeTracking => this.client.Capabilities.Contains(ImapCapability.CondStore);
/// <summary> /// <summary>
/// Connects to the IMAP server of the mailbox and signs in. /// Connects to the IMAP server of the mailbox and signs in.
@@ -292,10 +308,10 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
public async Task<IReadOnlyList<IMessageSummary>> FetchSummariesAsync(IReadOnlyCollection<long> uids, CancellationToken token) public async Task<IReadOnlyList<IMessageSummary>> FetchSummariesAsync(IReadOnlyCollection<long> uids, CancellationToken token)
{ {
var items = MessageSummaryItems.UniqueId | MessageSummaryItems.Flags | MessageSummaryItems.InternalDate | MessageSummaryItems.Size | MessageSummaryItems.BodyStructure | MessageSummaryItems.Headers; var items = MessageSummaryItems.UniqueId | MessageSummaryItems.Flags | MessageSummaryItems.InternalDate | MessageSummaryItems.Size | MessageSummaryItems.BodyStructure | MessageSummaryItems.Headers;
if (this.client.Capabilities.HasFlag(ImapCapabilities.ObjectID)) if (this.client.Capabilities.Contains(ImapCapability.ObjectID))
items |= MessageSummaryItems.EmailId; items |= MessageSummaryItems.EmailId;
if (this.client.Capabilities.HasFlag(ImapCapabilities.GMailExt1)) if (this.client.Capabilities.Contains(ImapCapability.GMailExt1))
items |= MessageSummaryItems.GMailMessageId; items |= MessageSummaryItems.GMailMessageId;
return await this.FetchAsync(uids, new FetchRequest(items), token); return await this.FetchAsync(uids, new FetchRequest(items), token);
@@ -449,7 +465,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
return summaries; return summaries;
} }
private static async Task<Stream> FetchAttachmentPieceAsync(IMailFolder folder, UniqueId uid, string section, int offset, CancellationToken token) private static async Task<Stream> FetchAttachmentPieceAsync(IMailFolder folder, UniqueId uid, string section, long offset, CancellationToken token)
{ {
try try
{ {
@@ -478,7 +494,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
return; return;
} }
if (this.client.Capabilities.HasFlag(ImapCapabilities.LoginDisabled)) if (this.client.Capabilities.Contains(ImapCapability.LoginDisabled))
throw new MailboxConnectionException(MailboxConnectionFailure.SERVER_ERROR, "The IMAP server offers no way to sign in with a password."); throw new MailboxConnectionException(MailboxConnectionFailure.SERVER_ERROR, "The IMAP server offers no way to sign in with a password.");
// //
@@ -25,8 +25,8 @@ public static class MailAttachmentPieces
/// The largest attachment, as it travels, which can be fetched at all. /// The largest attachment, as it travels, which can be fetched at all.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The IMAP client addresses a piece by an offset of type int. With Base64, this allows for files /// With Base64, this allows for files of about 1.5 GB, whereas mail servers rarely accept a mail a
/// of about 1.5 GB, whereas mail servers rarely accept a mail a tenth as large. /// tenth as large. The limit also ends the fetching when a server keeps delivering full pieces.
/// </remarks> /// </remarks>
public const long MAX_OCTETS = int.MaxValue; public const long MAX_OCTETS = int.MaxValue;
@@ -41,7 +41,7 @@ public static class MailAttachmentPieces
/// <param name="pieceBytes">How large a piece is, cf. PIECE_BYTES.</param> /// <param name="pieceBytes">How large a piece is, cf. PIECE_BYTES.</param>
/// <param name="token">The cancellation token.</param> /// <param name="token">The cancellation token.</param>
/// <exception cref="InvalidDataException">The transfer encoding is unknown, or the server delivered more than it was asked for.</exception> /// <exception cref="InvalidDataException">The transfer encoding is unknown, or the server delivered more than it was asked for.</exception>
public static async Task WriteDecodedAsync(Func<int, CancellationToken, Task<Stream>> fetchPieceAsync, string? transferEncoding, Stream destination, int pieceBytes, CancellationToken token) public static async Task WriteDecodedAsync(Func<long, CancellationToken, Task<Stream>> fetchPieceAsync, string? transferEncoding, Stream destination, int pieceBytes, CancellationToken token)
{ {
var encoding = GetEncoding(transferEncoding); var encoding = GetEncoding(transferEncoding);
await using var decoded = new FilteredStream(destination); await using var decoded = new FilteredStream(destination);
@@ -52,7 +52,7 @@ public static class MailAttachmentPieces
for (var offset = 0L; offset <= MAX_OCTETS; offset += pieceBytes) for (var offset = 0L; offset <= MAX_OCTETS; offset += pieceBytes)
{ {
var pieceLength = 0L; var pieceLength = 0L;
await using (var piece = await fetchPieceAsync((int)offset, token)) await using (var piece = await fetchPieceAsync(offset, token))
{ {
int read; int read;
while ((read = await piece.ReadAsync(buffer, token)) > 0) while ((read = await piece.ReadAsync(buffer, token)) > 0)
@@ -80,7 +80,7 @@ public static class MailAttachmentPieces
{ {
// Without a transfer encoding, the content travels as it is, cf. RFC 2045, section 6.1: // Without a transfer encoding, the content travels as it is, cf. RFC 2045, section 6.1:
if (string.IsNullOrWhiteSpace(transferEncoding)) if (string.IsNullOrWhiteSpace(transferEncoding))
return ContentEncoding.Default; return ContentEncoding.Unspecified;
if (MimeUtils.TryParse(transferEncoding, out ContentEncoding encoding)) if (MimeUtils.TryParse(transferEncoding, out ContentEncoding encoding))
return encoding; return encoding;
@@ -36,17 +36,49 @@ public static class MailEncryptionDetection
/// <summary> /// <summary>
/// Reads the encryption from the structure the server describes. /// Reads the encryption from the structure the server describes.
/// </summary> /// </summary>
/// <remarks>
/// The structure is walked with a stack of its own rather than by recursion: the IMAP client reads
/// a structure of any depth, and a mail nested deeply enough on purpose would otherwise end AI
/// Studio with a stack overflow, which no catch block stops. The parts are visited in their order,
/// so the first encrypted part decides, as for a parsed mail.
/// </remarks>
/// <param name="bodyStructure">The BODYSTRUCTURE of the mail, or null when the server sent none.</param> /// <param name="bodyStructure">The BODYSTRUCTURE of the mail, or null when the server sent none.</param>
/// <returns>How the content is encrypted, NONE when it is readable as far as the structure tells.</returns> /// <returns>How the content is encrypted, NONE when it is readable as far as the structure tells.</returns>
public static MailEncryptionKind Detect(BodyPart? bodyStructure) => bodyStructure switch public static MailEncryptionKind Detect(BodyPart? bodyStructure)
{ {
// An attached mail keeps its protection to itself: var pending = new Stack<BodyPart>();
BodyPartMessage => MailEncryptionKind.NONE, if (bodyStructure is not null)
pending.Push(bodyStructure);
BodyPartMultipart multipart => DetectMultipart(multipart.ContentType, multipart.BodyParts.Select(Detect)), while (pending.TryPop(out var current))
BodyPartBasic part => DetectPart(part.ContentType, part.FileName), {
_ => MailEncryptionKind.NONE, switch (current)
}; {
// An attached mail keeps its protection to itself:
case BodyPartMessage:
continue;
case BodyPartMultipart multipart when IsPgpMime(multipart.ContentType):
return MailEncryptionKind.PGP_MIME;
case BodyPartMultipart multipart:
// Pushed in reverse, so that the first part comes off the stack first:
for (var index = multipart.BodyParts.Count - 1; index >= 0; index--)
pending.Push(multipart.BodyParts[index]);
continue;
case BodyPartBasic part:
var kind = DetectPart(part.ContentType, part.FileName);
if (kind is not MailEncryptionKind.NONE)
return kind;
continue;
}
}
return MailEncryptionKind.NONE;
}
/// <summary> /// <summary>
/// Reads the encryption from the MIME tree of a parsed mail. /// Reads the encryption from the MIME tree of a parsed mail.
@@ -73,13 +105,17 @@ public static class MailEncryptionDetection
private static MailEncryptionKind DetectMultipart(ContentType contentType, IEnumerable<MailEncryptionKind> partKinds) private static MailEncryptionKind DetectMultipart(ContentType contentType, IEnumerable<MailEncryptionKind> partKinds)
{ {
// RFC 1847 knows no other use of multipart/encrypted than PGP/MIME in practice: if (IsPgpMime(contentType))
if (contentType.IsMimeType("multipart", "encrypted"))
return MailEncryptionKind.PGP_MIME; return MailEncryptionKind.PGP_MIME;
return partKinds.FirstOrDefault(kind => kind is not MailEncryptionKind.NONE); return partKinds.FirstOrDefault(kind => kind is not MailEncryptionKind.NONE);
} }
/// <summary>
/// Whether a multipart is encrypted. RFC 1847 knows no other use of multipart/encrypted than PGP/MIME in practice.
/// </summary>
private static bool IsPgpMime(ContentType contentType) => contentType.IsMimeType("multipart", "encrypted");
private static MailEncryptionKind DetectPart(ContentType contentType, string? fileName) private static MailEncryptionKind DetectPart(ContentType contentType, string? fileName)
{ {
if (contentType.IsMimeType("application", "pkcs7-mime") || contentType.IsMimeType("application", "x-pkcs7-mime")) if (contentType.IsMimeType("application", "pkcs7-mime") || contentType.IsMimeType("application", "x-pkcs7-mime"))
@@ -35,6 +35,19 @@ public static class MailHeaders
return mailboxes; return mailboxes;
} }
/// <summary>
/// Reads the address of a mailbox, with an internationalized domain in Unicode, e.g. "müller.example"
/// rather than "xn--mller-kva.example".
/// </summary>
/// <remarks>
/// MimeKit decoded such a domain by itself up to version 4, and the index keeps every address in
/// this form. The key of a mail depends on it, too, see MailContentKey: in another form, every mail
/// from such a domain would be embedded anew.
/// </remarks>
/// <param name="mailbox">The mailbox, as parsed from a header.</param>
/// <returns>The address.</returns>
public static string ReadAddress(MailboxAddress mailbox) => mailbox.GetAddress(idnEncode: false);
/// <summary> /// <summary>
/// Reads the Message-IDs of a header, without their angle brackets. /// Reads the Message-IDs of a header, without their angle brackets.
/// </summary> /// </summary>
@@ -33,7 +33,7 @@ public static class MailSummaryReader
summary.GMailMessageId, summary.GMailMessageId,
headers[HeaderId.MessageId], headers[HeaderId.MessageId],
MailHeaders.ReadDate(headers), MailHeaders.ReadDate(headers),
MailHeaders.ReadMailboxes(headers, HeaderId.From).Select(mailbox => mailbox.Address).ToList(), MailHeaders.ReadMailboxes(headers, HeaderId.From).Select(MailHeaders.ReadAddress).ToList(),
headers[HeaderId.Subject], headers[HeaderId.Subject],
summary.Size ?? 0); summary.Size ?? 0);
} }
@@ -83,7 +83,7 @@ public static class MailSummaryReader
return roles return roles
.SelectMany(role => MailHeaders.ReadMailboxes(headers, role.HeaderId).Select(mailbox => new MailAddressRecord( .SelectMany(role => MailHeaders.ReadMailboxes(headers, role.HeaderId).Select(mailbox => new MailAddressRecord(
role.Role, role.Role,
MailTextNormalization.NormalizeHeaderValue(mailbox.Address), MailTextNormalization.NormalizeHeaderValue(MailHeaders.ReadAddress(mailbox)),
MailTextNormalization.NormalizeHeaderValue(mailbox.Name)))) MailTextNormalization.NormalizeHeaderValue(mailbox.Name))))
.Where(address => address.Address.Length > 0) .Where(address => address.Address.Length > 0)
.ToList(); .ToList();
@@ -135,5 +135,18 @@ public static class MailSummaryReader
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(source))); return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(source)));
} }
private static HeaderList GetHeaders(IMessageSummary summary) => summary.Headers ?? throw new InvalidOperationException("The mail was fetched without its header block."); /// <summary>
/// Reads the header block the server delivered with a mail.
/// </summary>
/// <remarks>
/// The IMAP client hands over an empty header block when it cannot parse the one the server sent,
/// e.g. because a field is longer than ImapMailboxConnector.MAX_HEADER_FIELD_BYTES. Every mail has a
/// header, so an empty one counts as missing: a mail read from it would have neither sender, nor
/// subject, nor date, and its key would rest on its size alone.
/// </remarks>
/// <param name="summary">The summary of the mail.</param>
/// <returns>The header block, or null when the mail was fetched without one, or with one which could not be read.</returns>
public static HeaderList? ReadHeaders(IMessageSummary summary) => summary.Headers is { Count: > 0 } headers ? headers : null;
private static HeaderList GetHeaders(IMessageSummary summary) => ReadHeaders(summary) ?? throw new InvalidOperationException("The mail was fetched without a header block which could be read.");
} }
@@ -111,7 +111,7 @@ public static class MailTextBuilder
private static string FormatAddress(MailboxAddress mailbox) private static string FormatAddress(MailboxAddress mailbox)
{ {
var address = MailTextNormalization.NormalizeHeaderValue(mailbox.Address); var address = MailTextNormalization.NormalizeHeaderValue(MailHeaders.ReadAddress(mailbox));
var name = MailTextNormalization.NormalizeHeaderValue(mailbox.Name); var name = MailTextNormalization.NormalizeHeaderValue(mailbox.Name);
if (name.Length is 0 || name.Equals(address, StringComparison.OrdinalIgnoreCase)) if (name.Length is 0 || name.Equals(address, StringComparison.OrdinalIgnoreCase))
return address; return address;
@@ -39,9 +39,9 @@ internal sealed partial class MailboxIndexer
/// </summary> /// </summary>
private async Task SyncNewMailAsync(IndexedRunContext context, DataSourceMailbox mailbox, ImapMailboxConnector connector, string folderPath, IMessageSummary summary, DocumentRunProgress progress, ISet<string> encounteredKeys, CancellationToken token) private async Task SyncNewMailAsync(IndexedRunContext context, DataSourceMailbox mailbox, ImapMailboxConnector connector, string folderPath, IMessageSummary summary, DocumentRunProgress progress, ISet<string> encounteredKeys, CancellationToken token)
{ {
if (summary.Headers is not { } headers) if (MailSummaryReader.ReadHeaders(summary) is not { } headers)
{ {
logger.LogWarning("The server delivered a mail of mailbox '{MailboxId}' without its header block. The mail is skipped.", mailbox.Id); logger.LogWarning("The server delivered a mail of mailbox '{MailboxId}' without a header block which could be read. The mail is skipped.", mailbox.Id);
return; return;
} }
@@ -219,7 +219,7 @@ internal sealed partial class MailboxIndexer
/// <returns>The mail as the index keeps it.</returns> /// <returns>The mail as the index keeps it.</returns>
internal static MailRecord CreateMailRecord(string mailId, IMessageSummary summary, MailText text, IReadOnlyList<MailAttachmentText> attachments, string mailHash, MailLocationRecord location, DateTimeOffset foundAtUtc) internal static MailRecord CreateMailRecord(string mailId, IMessageSummary summary, MailText text, IReadOnlyList<MailAttachmentText> attachments, string mailHash, MailLocationRecord location, DateTimeOffset foundAtUtc)
{ {
var headers = summary.Headers ?? throw new ArgumentException("The mail was fetched without its header block.", nameof(summary)); var headers = MailSummaryReader.ReadHeaders(summary) ?? throw new ArgumentException("The mail was fetched without a header block which could be read.", nameof(summary));
var (sentAtUtc, receivedAtUtc) = ReadDates(summary, foundAtUtc); var (sentAtUtc, receivedAtUtc) = ReadDates(summary, foundAtUtc);
// //
@@ -276,7 +276,7 @@ internal sealed partial class MailboxIndexer
/// </remarks> /// </remarks>
private static (DateTimeOffset? SentAtUtc, DateTimeOffset ReceivedAtUtc) ReadDates(IMessageSummary summary, DateTimeOffset foundAtUtc) private static (DateTimeOffset? SentAtUtc, DateTimeOffset ReceivedAtUtc) ReadDates(IMessageSummary summary, DateTimeOffset foundAtUtc)
{ {
var sentAtUtc = summary.Headers is { } headers ? MailHeaders.ReadDate(headers)?.ToUniversalTime() : null; var sentAtUtc = MailSummaryReader.ReadHeaders(summary) is { } headers ? MailHeaders.ReadDate(headers)?.ToUniversalTime() : null;
return (sentAtUtc, summary.InternalDate?.ToUniversalTime() ?? sentAtUtc ?? foundAtUtc); return (sentAtUtc, summary.InternalDate?.ToUniversalTime() ?? sentAtUtc ?? foundAtUtc);
} }
+7 -51
View File
@@ -50,11 +50,11 @@
}, },
"MailKit": { "MailKit": {
"type": "Direct", "type": "Direct",
"requested": "[4.18.2, )", "requested": "[5.0.0, )",
"resolved": "4.18.2", "resolved": "5.0.0",
"contentHash": "ofqddpSbdrD00NqTD0ZyVfKvrl/ZZ70VFFEQ+DuR8r8CdbY3U02/sdb0CSQBNUqJifsXfVHIwRe1ToR2MvJJkw==", "contentHash": "PG6hnsklTzd/iK9A6j03OxDOas9mh8zOBkbPzcsLmFOODE8Hw3HTy7HAKiJvVHXNpKc3/KMVG/4QvOAKCBbGhA==",
"dependencies": { "dependencies": {
"MimeKit": "4.18.2" "MimeKit.Core": "5.0.0"
} }
}, },
"Microsoft.AspNetCore.App.Internal.Assets": { "Microsoft.AspNetCore.App.Internal.Assets": {
@@ -136,11 +136,6 @@
"resolved": "4.13.1", "resolved": "4.13.1",
"contentHash": "Da5+i4kFHUseJRZGcBG5fmZGpA/Ns180ibrQMxgZzjpQOnENVvSL5gi5HZ8Ncz8/AR2WsKbOg2lMBzjz0HUQcA==" "contentHash": "Da5+i4kFHUseJRZGcBG5fmZGpA/Ns180ibrQMxgZzjpQOnENVvSL5gi5HZ8Ncz8/AR2WsKbOg2lMBzjz0HUQcA=="
}, },
"BouncyCastle.Cryptography": {
"type": "Transitive",
"resolved": "2.7.0",
"contentHash": "U+12df8UEWHgBi04YVf/Lgi2dy3SItlIYvHjjEVa/BngCQIzDCDRBk50DDByCfDvSbe5pRNFr3b7UrVK2kMcLw=="
},
"DocumentFormat.OpenXml.Framework": { "DocumentFormat.OpenXml.Framework": {
"type": "Transitive", "type": "Transitive",
"resolved": "3.5.1", "resolved": "3.5.1",
@@ -217,14 +212,10 @@
"resolved": "10.0.15", "resolved": "10.0.15",
"contentHash": "087ome/PndkacsUGmB6OoTyhQ3UwoSRqv9odKbvdD4h3o6TqSIVIK/v1WaNKZ/oiMUVuMcV0l2yXdt55RHRxGw==" "contentHash": "087ome/PndkacsUGmB6OoTyhQ3UwoSRqv9odKbvdD4h3o6TqSIVIK/v1WaNKZ/oiMUVuMcV0l2yXdt55RHRxGw=="
}, },
"MimeKit": { "MimeKit.Core": {
"type": "Transitive", "type": "Transitive",
"resolved": "4.18.2", "resolved": "5.0.0",
"contentHash": "aYnwCCq+ZgQIsnHSJd3TMeGqf/Rz/9jYEItXpOoG3E2REOCZtLishwBSDFl2wQ/W2SB5wBsvE38DgHZ0IEyz4Q==", "contentHash": "0RLaVyex/BjUGqiw9xtGwzyCMaBcsu33Rth61bDCeVeQaaQK7tjcy4TA+nHKTqwUdp4OGd+gnhuq2fuR+c20qA=="
"dependencies": {
"BouncyCastle.Cryptography": "2.7.0",
"System.Security.Cryptography.Pkcs": "10.0.13"
}
}, },
"PeterO.Numbers": { "PeterO.Numbers": {
"type": "Transitive", "type": "Transitive",
@@ -262,11 +253,6 @@
"resolved": "10.0.2", "resolved": "10.0.2",
"contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg==" "contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg=="
}, },
"System.Security.Cryptography.Pkcs": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw=="
},
"sharedtools": { "sharedtools": {
"type": "Project" "type": "Project"
} }
@@ -276,11 +262,6 @@
"type": "Transitive", "type": "Transitive",
"resolved": "3.53.4", "resolved": "3.53.4",
"contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw=="
},
"System.Security.Cryptography.Pkcs": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw=="
} }
}, },
"net10.0/linux-x64": { "net10.0/linux-x64": {
@@ -288,11 +269,6 @@
"type": "Transitive", "type": "Transitive",
"resolved": "3.53.4", "resolved": "3.53.4",
"contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw=="
},
"System.Security.Cryptography.Pkcs": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw=="
} }
}, },
"net10.0/osx-arm64": { "net10.0/osx-arm64": {
@@ -300,11 +276,6 @@
"type": "Transitive", "type": "Transitive",
"resolved": "3.53.4", "resolved": "3.53.4",
"contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw=="
},
"System.Security.Cryptography.Pkcs": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw=="
} }
}, },
"net10.0/osx-x64": { "net10.0/osx-x64": {
@@ -312,11 +283,6 @@
"type": "Transitive", "type": "Transitive",
"resolved": "3.53.4", "resolved": "3.53.4",
"contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw=="
},
"System.Security.Cryptography.Pkcs": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw=="
} }
}, },
"net10.0/win-arm64": { "net10.0/win-arm64": {
@@ -324,11 +290,6 @@
"type": "Transitive", "type": "Transitive",
"resolved": "3.53.4", "resolved": "3.53.4",
"contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw=="
},
"System.Security.Cryptography.Pkcs": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw=="
} }
}, },
"net10.0/win-x64": { "net10.0/win-x64": {
@@ -336,11 +297,6 @@
"type": "Transitive", "type": "Transitive",
"resolved": "3.53.4", "resolved": "3.53.4",
"contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw=="
},
"System.Security.Cryptography.Pkcs": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw=="
} }
} }
} }
@@ -0,0 +1,10 @@
From: =?utf-8?q?M=C3=BCller=2C_J=C3=BCrgen?= <juergen@xn--mller-kva.example>
To: Team <team@example.org>
Cc: Library <info@xn--bcher-kva.example>
Subject: =?utf-8?q?Quarterly_report=C2=A0Q3_=E2=80=93_please_review=C2=A0?=
Date: Mon, 16 Nov 2026 09:30:00 +0100
Message-ID: <idn-sender@xn--mller-kva.example>
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
The figures for the third quarter are ready.
@@ -1,4 +1,7 @@
using System.Globalization;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using AIStudio.Settings.DataModel; using AIStudio.Settings.DataModel;
using AIStudio.Tools.Mail; using AIStudio.Tools.Mail;
@@ -7,6 +10,8 @@ using MailKit;
using MailKit.Net.Imap; using MailKit.Net.Imap;
using MailKit.Security; using MailKit.Security;
using MimeKit;
namespace AIStudio.Tests.Tools.Mail; namespace AIStudio.Tests.Tools.Mail;
/// <summary> /// <summary>
@@ -142,4 +147,33 @@ public sealed class ImapMailboxConnectorTests
[TestCase(FolderAttributes.Trash | FolderAttributes.HasNoChildren, ExpectedResult = MailFolderSpecialUse.TRASH)] [TestCase(FolderAttributes.Trash | FolderAttributes.HasNoChildren, ExpectedResult = MailFolderSpecialUse.TRASH)]
[TestCase(FolderAttributes.Junk | FolderAttributes.Important, ExpectedResult = MailFolderSpecialUse.JUNK)] [TestCase(FolderAttributes.Junk | FolderAttributes.Important, ExpectedResult = MailFolderSpecialUse.JUNK)]
public MailFolderSpecialUse AFolderIsForWhatTheServerAnnounces(FolderAttributes attributes) => ImapMailboxConnector.ToSpecialUse(attributes); public MailFolderSpecialUse AFolderIsForWhatTheServerAnnounces(FolderAttributes attributes) => ImapMailboxConnector.ToSpecialUse(attributes);
[Test]
public void AHeaderBlockWithAVeryLongFieldIsReadAsAWhole()
{
//
// The IMAP client parses every header block like this, with the default options of MimeKit,
// whose limit the connector raises before the first mail is fetched:
//
RuntimeHelpers.RunClassConstructor(typeof(ImapMailboxConnector).TypeHandle);
var recipients = string.Join(",\r\n ", Enumerable.Range(1, 1000).Select(number => $"recipient{number.ToString(CultureInfo.InvariantCulture)}@example.org"));
var headerBlock = Encoding.ASCII.GetBytes($"From: alice@example.org\r\nTo: {recipients}\r\nSubject: All hands\r\n\r\n");
var headers = Parse(headerBlock, ParserOptions.Default);
using (Assert.EnterMultipleScope())
{
Assert.That(() => Parse(headerBlock, new ParserOptions()), Throws.TypeOf<FormatException>(), "MimeKit reads such a field by default, so the limit needs no raising.");
Assert.That(headers[HeaderId.Subject], Is.EqualTo("All hands"));
Assert.That(MailHeaders.ReadMailboxes(headers, HeaderId.To), Has.Count.EqualTo(1000));
}
return;
static HeaderList Parse(byte[] headerBlock, ParserOptions options)
{
using var stream = new MemoryStream(headerBlock);
return new MimeParser(options, stream).ParseHeaders();
}
}
} }
@@ -47,7 +47,7 @@ public sealed class MailAttachmentPiecesTests
using (Assert.EnterMultipleScope()) using (Assert.EnterMultipleScope())
{ {
Assert.That(written, Is.EqualTo(file)); Assert.That(written, Is.EqualTo(file));
Assert.That(server.RequestedOffsets, Is.EqualTo(new[] { 0, 7, 14, 21 })); Assert.That(server.RequestedOffsets, Is.EqualTo(new long[] { 0, 7, 14, 21 }));
} }
} }
@@ -93,12 +93,12 @@ public sealed class MailAttachmentPiecesTests
/// <param name="deliveredBytes">How many bytes it delivers per piece. A correct server delivers what it was asked for.</param> /// <param name="deliveredBytes">How many bytes it delivers per piece. A correct server delivers what it was asked for.</param>
private sealed class PieceServer(byte[] content, int deliveredBytes = PIECE_BYTES) private sealed class PieceServer(byte[] content, int deliveredBytes = PIECE_BYTES)
{ {
public List<int> RequestedOffsets { get; } = []; public List<long> RequestedOffsets { get; } = [];
public Task<Stream> FetchAsync(int offset, CancellationToken token) public Task<Stream> FetchAsync(long offset, CancellationToken token)
{ {
this.RequestedOffsets.Add(offset); this.RequestedOffsets.Add(offset);
var start = Math.Min(offset, content.Length); var start = (int)Math.Min(offset, content.Length);
var length = Math.Min(deliveredBytes, content.Length - start); var length = Math.Min(deliveredBytes, content.Length - start);
return Task.FromResult<Stream>(new MemoryStream(content, start, length, writable: false)); return Task.FromResult<Stream>(new MemoryStream(content, start, length, writable: false));
} }
@@ -56,6 +56,32 @@ public sealed class MailEncryptionDetectionTests
} }
} }
[Test]
public void AStructureOfAnyDepthIsRead()
{
//
// Deep enough to overflow the stack of a recursive walk. The IMAP client reads a structure of
// any depth, so a mail nested this deeply on purpose must not end AI Studio:
//
BodyPart encrypted = Part("application", "pkcs7-mime", smimeType: "enveloped-data");
BodyPart readable = PLAIN_TEXT;
for (var depth = 0; depth < 100_000; depth++)
{
encrypted = Multipart("mixed", PLAIN_TEXT, encrypted);
readable = Multipart("mixed", readable, PLAIN_TEXT);
}
using (Assert.EnterMultipleScope())
{
Assert.That(MailEncryptionDetection.Detect(encrypted), Is.EqualTo(MailEncryptionKind.SMIME));
Assert.That(MailEncryptionDetection.Detect(readable), Is.EqualTo(MailEncryptionKind.NONE));
}
}
[Test]
public void TheFirstEncryptedPartDecides() =>
Assert.That(MailEncryptionDetection.Detect(Multipart("mixed", PLAIN_TEXT, Multipart("mixed", Part("application", "x-microsoft-rpmsg-message")), Part("application", "pkcs7-mime", smimeType: "enveloped-data"))), Is.EqualTo(MailEncryptionKind.MICROSOFT_IRM), "The parts are not visited in their order.");
[TestCase("-----BEGIN PGP MESSAGE-----\n\nhQEMA\n-----END PGP MESSAGE-----", ExpectedResult = true)] [TestCase("-----BEGIN PGP MESSAGE-----\n\nhQEMA\n-----END PGP MESSAGE-----", ExpectedResult = true)]
[TestCase("<p>-----BEGIN PGP MESSAGE-----<br>hQEMA</p>", ExpectedResult = true)] [TestCase("<p>-----BEGIN PGP MESSAGE-----<br>hQEMA</p>", ExpectedResult = true)]
[TestCase("-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\nReadable text.", ExpectedResult = false)] [TestCase("-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\nReadable text.", ExpectedResult = false)]
+46 -2
View File
@@ -42,6 +42,38 @@ public sealed class MailSummaryReaderTests
} }
} }
/// <remarks>
/// The keys come from what MimeKit reads out of the header block. A version of MimeKit which reads
/// a header in another way would give every mail it concerns a new key and embed it anew, so these
/// keys stay as MimeKit 4.18.2 made them. Change a pinned value only on purpose.
/// </remarks>
[TestCase("header-injection.eml", "mail:4ad6f665ee9a7b698d32276855cc2c8da31e5c7d25057c45d15484712ee045ad")]
[TestCase("priority-with-attachment.eml", "mail:797ac20c552b0aed439f87095a2345f38a5268a7656024b5394349652ac08e18")]
[TestCase("idn-sender.eml", "mail:e7284cb3afe9041918d344de00e01f55aebc7b29ebcd25967a8810eca13068d8")]
public void TheKeysOfIndexedMailsStayTheSame(string fixtureName, string expectedKey)
{
var summary = Summary(fixtureName);
summary.Size = 4096;
Assert.That(MailContentKey.Create(MailSummaryReader.ReadIdentity(summary)), Is.EqualTo(expectedKey));
}
[Test]
public void AnInternationalDomainIsReadInUnicode()
{
var summary = Summary("idn-sender.eml");
using (Assert.EnterMultipleScope())
{
Assert.That(MailSummaryReader.ReadIdentity(summary).FromAddresses, Is.EqualTo(new[] { "juergen@müller.example" }));
Assert.That(MailSummaryReader.ReadAddresses(summary.Headers!), Is.EqualTo(new[]
{
new MailAddressRecord(MailAddressRole.FROM, "juergen@müller.example", "Müller, Jürgen"),
new MailAddressRecord(MailAddressRole.TO, "team@example.org", "Team"),
new MailAddressRecord(MailAddressRole.CC, "info@bücher.example", "Library"),
}), "The index keeps an address in the form the mails indexed before keep it.");
}
}
[Test] [Test]
public void EveryAddressKeepsItsHeader() public void EveryAddressKeepsItsHeader()
{ {
@@ -169,8 +201,20 @@ public sealed class MailSummaryReaderTests
} }
[Test] [Test]
public void AMailFetchedWithoutItsHeaderBlockIsRefused() => public void AMailFetchedWithoutItsHeaderBlockIsRefused()
Assert.That(() => MailSummaryReader.ReadIdentity(new MessageSummary(0)), Throws.InvalidOperationException); {
//
// The IMAP client hands over an empty header block when it cannot parse the one the server sent:
//
var withEmptyHeaderBlock = new MessageSummary(0) { Headers = new HeaderList() };
using (Assert.EnterMultipleScope())
{
Assert.That(MailSummaryReader.ReadHeaders(new MessageSummary(0)), Is.Null);
Assert.That(MailSummaryReader.ReadHeaders(withEmptyHeaderBlock), Is.Null, "An empty header block counts as one which could be read.");
Assert.That(() => MailSummaryReader.ReadIdentity(new MessageSummary(0)), Throws.InvalidOperationException);
Assert.That(() => MailSummaryReader.ReadIdentity(withEmptyHeaderBlock), Throws.InvalidOperationException);
}
}
private static MessageSummary Summary(string fixtureName) => new(0) { Headers = MailFixtures.Load(fixtureName).Headers }; private static MessageSummary Summary(string fixtureName) => new(0) { Headers = MailFixtures.Load(fixtureName).Headers };
@@ -96,6 +96,15 @@ public sealed class MailTextBuilderTests
} }
} }
[Test]
public void AnInternationalDomainIsShownInUnicode() =>
Assert.That(Build("idn-sender.eml").HeaderBlock, Is.EqualTo(string.Join('\n',
"From: Müller, Jürgen <juergen@müller.example>",
"To: Team <team@example.org>",
"Cc: Library <info@bücher.example>",
"Subject: Quarterly report Q3 – please review",
"Date: 2026-11-16 09:30 +01:00")), "The text shows an address in another form than the mails indexed before.");
[TestCase("smime-enveloped.eml", MailEncryptionKind.SMIME)] [TestCase("smime-enveloped.eml", MailEncryptionKind.SMIME)]
[TestCase("smime-opaque-signed.eml", MailEncryptionKind.SMIME_OPAQUE_SIGNED)] [TestCase("smime-opaque-signed.eml", MailEncryptionKind.SMIME_OPAQUE_SIGNED)]
[TestCase("pgp-mime.eml", MailEncryptionKind.PGP_MIME)] [TestCase("pgp-mime.eml", MailEncryptionKind.PGP_MIME)]