diff --git a/app/MindWork AI Studio/MindWork AI Studio.csproj b/app/MindWork AI Studio/MindWork AI Studio.csproj index b3a6832da..2e246326c 100644 --- a/app/MindWork AI Studio/MindWork AI Studio.csproj +++ b/app/MindWork AI Studio/MindWork AI Studio.csproj @@ -103,7 +103,7 @@ - + diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index 3d9029144..7489ed48f 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -39,6 +39,13 @@ public sealed class ImapMailboxConnector : IAsyncDisposable /// public const long MAX_TEXT_PART_BYTES = 4 * 1024 * 1024; + /// + /// 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. + /// + internal const int MAX_HEADER_FIELD_BYTES = 1024 * 1024; + /// /// 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. @@ -67,6 +74,15 @@ public sealed class ImapMailboxConnector : IAsyncDisposable /// 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() { 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). /// Without it, the flags of every mail have to be fetched to find the changed ones. /// - public bool SupportsChangeTracking => this.client.Capabilities.HasFlag(ImapCapabilities.CondStore); + public bool SupportsChangeTracking => this.client.Capabilities.Contains(ImapCapability.CondStore); /// /// Connects to the IMAP server of the mailbox and signs in. @@ -292,10 +308,10 @@ public sealed class ImapMailboxConnector : IAsyncDisposable public async Task> FetchSummariesAsync(IReadOnlyCollection uids, CancellationToken token) { 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; - if (this.client.Capabilities.HasFlag(ImapCapabilities.GMailExt1)) + if (this.client.Capabilities.Contains(ImapCapability.GMailExt1)) items |= MessageSummaryItems.GMailMessageId; return await this.FetchAsync(uids, new FetchRequest(items), token); @@ -449,7 +465,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable return summaries; } - private static async Task FetchAttachmentPieceAsync(IMailFolder folder, UniqueId uid, string section, int offset, CancellationToken token) + private static async Task FetchAttachmentPieceAsync(IMailFolder folder, UniqueId uid, string section, long offset, CancellationToken token) { try { @@ -478,7 +494,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable 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."); // diff --git a/app/MindWork AI Studio/Tools/Mail/MailAttachmentPieces.cs b/app/MindWork AI Studio/Tools/Mail/MailAttachmentPieces.cs index a7c567dd0..9987ef8d6 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailAttachmentPieces.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailAttachmentPieces.cs @@ -25,8 +25,8 @@ public static class MailAttachmentPieces /// The largest attachment, as it travels, which can be fetched at all. /// /// - /// The IMAP client addresses a piece by an offset of type int. With Base64, this allows for files - /// of about 1.5 GB, whereas mail servers rarely accept a mail a tenth as large. + /// With Base64, this allows for files of about 1.5 GB, whereas mail servers rarely accept a mail a + /// tenth as large. The limit also ends the fetching when a server keeps delivering full pieces. /// public const long MAX_OCTETS = int.MaxValue; @@ -41,7 +41,7 @@ public static class MailAttachmentPieces /// How large a piece is, cf. PIECE_BYTES. /// The cancellation token. /// The transfer encoding is unknown, or the server delivered more than it was asked for. - public static async Task WriteDecodedAsync(Func> fetchPieceAsync, string? transferEncoding, Stream destination, int pieceBytes, CancellationToken token) + public static async Task WriteDecodedAsync(Func> fetchPieceAsync, string? transferEncoding, Stream destination, int pieceBytes, CancellationToken token) { var encoding = GetEncoding(transferEncoding); await using var decoded = new FilteredStream(destination); @@ -52,7 +52,7 @@ public static class MailAttachmentPieces for (var offset = 0L; offset <= MAX_OCTETS; offset += pieceBytes) { var pieceLength = 0L; - await using (var piece = await fetchPieceAsync((int)offset, token)) + await using (var piece = await fetchPieceAsync(offset, token)) { int read; 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: if (string.IsNullOrWhiteSpace(transferEncoding)) - return ContentEncoding.Default; + return ContentEncoding.Unspecified; if (MimeUtils.TryParse(transferEncoding, out ContentEncoding encoding)) return encoding; diff --git a/app/MindWork AI Studio/Tools/Mail/MailEncryptionDetection.cs b/app/MindWork AI Studio/Tools/Mail/MailEncryptionDetection.cs index 0c06c7820..1e8c9e19a 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailEncryptionDetection.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailEncryptionDetection.cs @@ -36,17 +36,49 @@ public static class MailEncryptionDetection /// /// Reads the encryption from the structure the server describes. /// + /// + /// 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. + /// /// The BODYSTRUCTURE of the mail, or null when the server sent none. /// How the content is encrypted, NONE when it is readable as far as the structure tells. - public static MailEncryptionKind Detect(BodyPart? bodyStructure) => bodyStructure switch + public static MailEncryptionKind Detect(BodyPart? bodyStructure) { - // An attached mail keeps its protection to itself: - BodyPartMessage => MailEncryptionKind.NONE, + var pending = new Stack(); + if (bodyStructure is not null) + pending.Push(bodyStructure); - BodyPartMultipart multipart => DetectMultipart(multipart.ContentType, multipart.BodyParts.Select(Detect)), - BodyPartBasic part => DetectPart(part.ContentType, part.FileName), - _ => MailEncryptionKind.NONE, - }; + while (pending.TryPop(out var current)) + { + 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; + } /// /// 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 partKinds) { - // RFC 1847 knows no other use of multipart/encrypted than PGP/MIME in practice: - if (contentType.IsMimeType("multipart", "encrypted")) + if (IsPgpMime(contentType)) return MailEncryptionKind.PGP_MIME; return partKinds.FirstOrDefault(kind => kind is not MailEncryptionKind.NONE); } + /// + /// Whether a multipart is encrypted. RFC 1847 knows no other use of multipart/encrypted than PGP/MIME in practice. + /// + private static bool IsPgpMime(ContentType contentType) => contentType.IsMimeType("multipart", "encrypted"); + private static MailEncryptionKind DetectPart(ContentType contentType, string? fileName) { if (contentType.IsMimeType("application", "pkcs7-mime") || contentType.IsMimeType("application", "x-pkcs7-mime")) diff --git a/app/MindWork AI Studio/Tools/Mail/MailHeaders.cs b/app/MindWork AI Studio/Tools/Mail/MailHeaders.cs index ebaced7ef..1fcb21af8 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailHeaders.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailHeaders.cs @@ -35,6 +35,19 @@ public static class MailHeaders return mailboxes; } + /// + /// Reads the address of a mailbox, with an internationalized domain in Unicode, e.g. "müller.example" + /// rather than "xn--mller-kva.example". + /// + /// + /// 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. + /// + /// The mailbox, as parsed from a header. + /// The address. + public static string ReadAddress(MailboxAddress mailbox) => mailbox.GetAddress(idnEncode: false); + /// /// Reads the Message-IDs of a header, without their angle brackets. /// diff --git a/app/MindWork AI Studio/Tools/Mail/MailSummaryReader.cs b/app/MindWork AI Studio/Tools/Mail/MailSummaryReader.cs index 99a923f0f..6b922c36c 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailSummaryReader.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailSummaryReader.cs @@ -33,7 +33,7 @@ public static class MailSummaryReader summary.GMailMessageId, headers[HeaderId.MessageId], 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], summary.Size ?? 0); } @@ -83,7 +83,7 @@ public static class MailSummaryReader return roles .SelectMany(role => MailHeaders.ReadMailboxes(headers, role.HeaderId).Select(mailbox => new MailAddressRecord( role.Role, - MailTextNormalization.NormalizeHeaderValue(mailbox.Address), + MailTextNormalization.NormalizeHeaderValue(MailHeaders.ReadAddress(mailbox)), MailTextNormalization.NormalizeHeaderValue(mailbox.Name)))) .Where(address => address.Address.Length > 0) .ToList(); @@ -135,5 +135,18 @@ public static class MailSummaryReader 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."); + /// + /// Reads the header block the server delivered with a mail. + /// + /// + /// 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. + /// + /// The summary of the mail. + /// The header block, or null when the mail was fetched without one, or with one which could not be read. + 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."); } \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Mail/MailTextBuilder.cs b/app/MindWork AI Studio/Tools/Mail/MailTextBuilder.cs index 0e51ff35a..5362b91ca 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailTextBuilder.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailTextBuilder.cs @@ -111,7 +111,7 @@ public static class MailTextBuilder 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); if (name.Length is 0 || name.Equals(address, StringComparison.OrdinalIgnoreCase)) return address; diff --git a/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.Mails.cs b/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.Mails.cs index f94f171d7..a0a8aeb5a 100644 --- a/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.Mails.cs +++ b/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.Mails.cs @@ -39,9 +39,9 @@ internal sealed partial class MailboxIndexer /// private async Task SyncNewMailAsync(IndexedRunContext context, DataSourceMailbox mailbox, ImapMailboxConnector connector, string folderPath, IMessageSummary summary, DocumentRunProgress progress, ISet 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; } @@ -219,7 +219,7 @@ internal sealed partial class MailboxIndexer /// The mail as the index keeps it. internal static MailRecord CreateMailRecord(string mailId, IMessageSummary summary, MailText text, IReadOnlyList 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); // @@ -276,7 +276,7 @@ internal sealed partial class MailboxIndexer /// 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); } diff --git a/app/MindWork AI Studio/packages.lock.json b/app/MindWork AI Studio/packages.lock.json index e081e6200..789006f95 100644 --- a/app/MindWork AI Studio/packages.lock.json +++ b/app/MindWork AI Studio/packages.lock.json @@ -50,11 +50,11 @@ }, "MailKit": { "type": "Direct", - "requested": "[4.18.2, )", - "resolved": "4.18.2", - "contentHash": "ofqddpSbdrD00NqTD0ZyVfKvrl/ZZ70VFFEQ+DuR8r8CdbY3U02/sdb0CSQBNUqJifsXfVHIwRe1ToR2MvJJkw==", + "requested": "[5.0.0, )", + "resolved": "5.0.0", + "contentHash": "PG6hnsklTzd/iK9A6j03OxDOas9mh8zOBkbPzcsLmFOODE8Hw3HTy7HAKiJvVHXNpKc3/KMVG/4QvOAKCBbGhA==", "dependencies": { - "MimeKit": "4.18.2" + "MimeKit.Core": "5.0.0" } }, "Microsoft.AspNetCore.App.Internal.Assets": { @@ -136,11 +136,6 @@ "resolved": "4.13.1", "contentHash": "Da5+i4kFHUseJRZGcBG5fmZGpA/Ns180ibrQMxgZzjpQOnENVvSL5gi5HZ8Ncz8/AR2WsKbOg2lMBzjz0HUQcA==" }, - "BouncyCastle.Cryptography": { - "type": "Transitive", - "resolved": "2.7.0", - "contentHash": "U+12df8UEWHgBi04YVf/Lgi2dy3SItlIYvHjjEVa/BngCQIzDCDRBk50DDByCfDvSbe5pRNFr3b7UrVK2kMcLw==" - }, "DocumentFormat.OpenXml.Framework": { "type": "Transitive", "resolved": "3.5.1", @@ -217,14 +212,10 @@ "resolved": "10.0.15", "contentHash": "087ome/PndkacsUGmB6OoTyhQ3UwoSRqv9odKbvdD4h3o6TqSIVIK/v1WaNKZ/oiMUVuMcV0l2yXdt55RHRxGw==" }, - "MimeKit": { + "MimeKit.Core": { "type": "Transitive", - "resolved": "4.18.2", - "contentHash": "aYnwCCq+ZgQIsnHSJd3TMeGqf/Rz/9jYEItXpOoG3E2REOCZtLishwBSDFl2wQ/W2SB5wBsvE38DgHZ0IEyz4Q==", - "dependencies": { - "BouncyCastle.Cryptography": "2.7.0", - "System.Security.Cryptography.Pkcs": "10.0.13" - } + "resolved": "5.0.0", + "contentHash": "0RLaVyex/BjUGqiw9xtGwzyCMaBcsu33Rth61bDCeVeQaaQK7tjcy4TA+nHKTqwUdp4OGd+gnhuq2fuR+c20qA==" }, "PeterO.Numbers": { "type": "Transitive", @@ -262,11 +253,6 @@ "resolved": "10.0.2", "contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg==" }, - "System.Security.Cryptography.Pkcs": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" - }, "sharedtools": { "type": "Project" } @@ -276,11 +262,6 @@ "type": "Transitive", "resolved": "3.53.4", "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" - }, - "System.Security.Cryptography.Pkcs": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" } }, "net10.0/linux-x64": { @@ -288,11 +269,6 @@ "type": "Transitive", "resolved": "3.53.4", "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" - }, - "System.Security.Cryptography.Pkcs": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" } }, "net10.0/osx-arm64": { @@ -300,11 +276,6 @@ "type": "Transitive", "resolved": "3.53.4", "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" - }, - "System.Security.Cryptography.Pkcs": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" } }, "net10.0/osx-x64": { @@ -312,11 +283,6 @@ "type": "Transitive", "resolved": "3.53.4", "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" - }, - "System.Security.Cryptography.Pkcs": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" } }, "net10.0/win-arm64": { @@ -324,11 +290,6 @@ "type": "Transitive", "resolved": "3.53.4", "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" - }, - "System.Security.Cryptography.Pkcs": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" } }, "net10.0/win-x64": { @@ -336,11 +297,6 @@ "type": "Transitive", "resolved": "3.53.4", "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" - }, - "System.Security.Cryptography.Pkcs": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" } } } diff --git a/app/Tests/Tools/Mail/Fixtures/idn-sender.eml b/app/Tests/Tools/Mail/Fixtures/idn-sender.eml new file mode 100644 index 000000000..21ea98f98 --- /dev/null +++ b/app/Tests/Tools/Mail/Fixtures/idn-sender.eml @@ -0,0 +1,10 @@ +From: =?utf-8?q?M=C3=BCller=2C_J=C3=BCrgen?= +To: Team +Cc: Library +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: +MIME-Version: 1.0 +Content-Type: text/plain; charset=utf-8 + +The figures for the third quarter are ready. diff --git a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs index ec42acc68..1ceb2ecb0 100644 --- a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs +++ b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs @@ -1,4 +1,7 @@ +using System.Globalization; using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Text; using AIStudio.Settings.DataModel; using AIStudio.Tools.Mail; @@ -7,6 +10,8 @@ using MailKit; using MailKit.Net.Imap; using MailKit.Security; +using MimeKit; + namespace AIStudio.Tests.Tools.Mail; /// @@ -142,4 +147,33 @@ public sealed class ImapMailboxConnectorTests [TestCase(FolderAttributes.Trash | FolderAttributes.HasNoChildren, ExpectedResult = MailFolderSpecialUse.TRASH)] [TestCase(FolderAttributes.Junk | FolderAttributes.Important, ExpectedResult = MailFolderSpecialUse.JUNK)] 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(), "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(); + } + } } \ No newline at end of file diff --git a/app/Tests/Tools/Mail/MailAttachmentPiecesTests.cs b/app/Tests/Tools/Mail/MailAttachmentPiecesTests.cs index 58770a185..4ff1b0251 100644 --- a/app/Tests/Tools/Mail/MailAttachmentPiecesTests.cs +++ b/app/Tests/Tools/Mail/MailAttachmentPiecesTests.cs @@ -47,7 +47,7 @@ public sealed class MailAttachmentPiecesTests using (Assert.EnterMultipleScope()) { 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 /// How many bytes it delivers per piece. A correct server delivers what it was asked for. private sealed class PieceServer(byte[] content, int deliveredBytes = PIECE_BYTES) { - public List RequestedOffsets { get; } = []; + public List RequestedOffsets { get; } = []; - public Task FetchAsync(int offset, CancellationToken token) + public Task FetchAsync(long offset, CancellationToken token) { 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); return Task.FromResult(new MemoryStream(content, start, length, writable: false)); } diff --git a/app/Tests/Tools/Mail/MailEncryptionDetectionTests.cs b/app/Tests/Tools/Mail/MailEncryptionDetectionTests.cs index 6816c26a4..c840f37fd 100644 --- a/app/Tests/Tools/Mail/MailEncryptionDetectionTests.cs +++ b/app/Tests/Tools/Mail/MailEncryptionDetectionTests.cs @@ -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-----
hQEMA

", ExpectedResult = true)] [TestCase("-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\nReadable text.", ExpectedResult = false)] diff --git a/app/Tests/Tools/Mail/MailSummaryReaderTests.cs b/app/Tests/Tools/Mail/MailSummaryReaderTests.cs index 9b2977e81..a30b7168f 100644 --- a/app/Tests/Tools/Mail/MailSummaryReaderTests.cs +++ b/app/Tests/Tools/Mail/MailSummaryReaderTests.cs @@ -42,6 +42,38 @@ public sealed class MailSummaryReaderTests } } + /// + /// 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. + /// + [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] public void EveryAddressKeepsItsHeader() { @@ -169,8 +201,20 @@ public sealed class MailSummaryReaderTests } [Test] - public void AMailFetchedWithoutItsHeaderBlockIsRefused() => - Assert.That(() => MailSummaryReader.ReadIdentity(new MessageSummary(0)), Throws.InvalidOperationException); + public void AMailFetchedWithoutItsHeaderBlockIsRefused() + { + // + // 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 }; diff --git a/app/Tests/Tools/Mail/MailTextBuilderTests.cs b/app/Tests/Tools/Mail/MailTextBuilderTests.cs index 3a0aa626e..34e119604 100644 --- a/app/Tests/Tools/Mail/MailTextBuilderTests.cs +++ b/app/Tests/Tools/Mail/MailTextBuilderTests.cs @@ -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 ", + "To: Team ", + "Cc: Library ", + "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-opaque-signed.eml", MailEncryptionKind.SMIME_OPAQUE_SIGNED)] [TestCase("pgp-mime.eml", MailEncryptionKind.PGP_MIME)]