From 00a0f8b278b49f758263ebd95909261f9580e2e8 Mon Sep 17 00:00:00 2001 From: Peer Hogeterp Date: Mon, 23 Nov 2026 14:22:28 +0100 Subject: [PATCH 01/15] Added German special characters to the agent instructions Many users of AI Studio write German, and a mailbox password with an umlaut failed to sign in at Exchange because the encoding was never considered. Agents now keep the German special characters in mind wherever text leaves or enters the app as bytes: the encoding the other side expects, the Unicode normalization, and tests with such characters. --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index 121b3fcd4..91fd82f77 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -199,6 +199,7 @@ again yourself when `metadata.txt` changes during the session, e.g., after a mer - **No automated formatting for Rust or .NET files** - Never run automated formatters on Rust files (`.rs`) or .NET files (`.cs`, `.razor`, `.csproj`, etc.). Only make the minimal manual formatting changes required for the specific edit. - **Spaces in paths** - Always quote paths with spaces in bash commands - **Compatibility shims** - Temporary fallback or read-repair code must be documented in `documentation/compatibility-shims/` with an introduced date, remove-after date, code references, and removal checklist. Add a short code comment near the shim that references the document and remove-after date. Check this folder before adding similar fallback logic, and do not extend expired shims without explicit maintainer direction. Do not use this process for permanent settings schema migrations; those belong in `app/MindWork AI Studio/Settings/SettingsMigrations.cs`. +- **German special characters** - Many users of AI Studio write German, so never assume that a text is ASCII. Keep the German special characters in mind wherever text leaves or enters the app as bytes, e.g., passwords and usernames, file and folder names, mail folders and headers, URLs, CSV, command lines, and network protocols: `ä ö ü Ä Ö Ü ß ẞ`, and the characters of a German keyboard and German typography, `§ ° ´ µ ² ³ € „ “ ‚ ‘ – …`. Check which encoding the other side expects: in UTF-8, each of them takes two or three bytes; Windows-1252 and Latin-1 take one byte for most of them, Latin-1 lacks `€ „ “ ‚ ‘ – …`, and both lack `ẞ`. Check the Unicode normalization as well: the same `ä` arrives as one code point (NFC) or as `a` with a combining diaeresis (NFD), e.g., in file names from macOS. Include such characters in the tests of this code. ## Wiki From adacbaffa5b0c9eeaa71444f168392bf52dc8c0b Mon Sep 17 00:00:00 2001 From: Peer Hogeterp Date: Mon, 23 Nov 2026 14:40:33 +0100 Subject: [PATCH 02/15] Added the password encoding to mailboxes A mailbox now stores how its username and password are encoded when signing in: UTF-8, as before, or Windows-1252, which Microsoft Exchange expects. Mailboxes stored earlier load with UTF-8, and an encoding this version does not know keeps the mailbox from signing in at all. Windows-1252 goes through the SASL mechanism PLAIN only: MailKit sends the LOGIN command in UTF-8, whatever encoding it is handed. A username or password the encoding lacks a character of is never sent in it, and Windows-1252 composes a decomposed umlaut first. Nothing changes yet for existing mailboxes; the connection test which finds the encoding follows in the next commit. --- .../Dialogs/DataSourceMailboxDialog.razor.cs | 3 + .../Settings/DataModel/DataSourceMailbox.cs | 9 ++ .../DataModel/MailboxPasswordEncoding.cs | 33 +++++ .../MailboxPasswordEncodingExtensions.cs | 73 ++++++++++ .../Tools/Mail/ImapMailboxConnector.cs | 53 ++++++- app/Tests/Settings/MailboxSettingsTests.cs | 11 ++ .../Tools/Mail/ImapMailboxConnectorTests.cs | 37 +++++ .../Mail/MailboxPasswordEncodingTests.cs | 134 ++++++++++++++++++ 8 files changed, 346 insertions(+), 7 deletions(-) create mode 100644 app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncoding.cs create mode 100644 app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncodingExtensions.cs create mode 100644 app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index 12af2ba53..ecbe11d0b 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -88,6 +88,7 @@ public partial class DataSourceMailboxDialog : MSGComponentBase private MailboxTransportSecurity dataTransportSecurity = MailboxTransportSecurity.SSL_ON_CONNECT; private string dataUsername = string.Empty; private string dataPassword = string.Empty; + private MailboxPasswordEncoding dataPasswordEncoding = MailboxPasswordEncoding.UTF8; private string dataRootFolder = string.Empty; private bool dataIncludeSentAndDrafts = true; private MailboxMaxAge dataMaxAge = MailboxMaxAge.LAST_12_MONTHS; @@ -166,6 +167,7 @@ protected override async Task OnInitializedAsync() this.dataPort = this.DataSource.Port; this.dataTransportSecurity = this.DataSource.TransportSecurity; this.dataUsername = this.DataSource.Username; + this.dataPasswordEncoding = this.DataSource.PasswordEncoding; this.dataRootFolder = this.DataSource.RootFolder; this.dataIncludeSentAndDrafts = this.DataSource.IncludeSentAndDrafts; this.dataMaxAge = this.DataSource.MaxAge; @@ -401,6 +403,7 @@ private string TestResultText Port = this.dataPort, TransportSecurity = this.dataTransportSecurity, AuthMethod = MailboxAuthMethod.PASSWORD, + PasswordEncoding = this.dataPasswordEncoding, MaxAge = this.dataMaxAge, IndexAttachments = this.dataIndexAttachments, MaxAttachmentSizeMegabytes = this.dataMaxAttachmentSizeMegabytes, diff --git a/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs b/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs index 48827a8ba..736580be5 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs @@ -73,6 +73,15 @@ public DataSourceMailbox() /// public MailboxAuthMethod AuthMethod { get; set; } = MailboxAuthMethod.PASSWORD; + /// + /// How the username and the password are encoded when signing in. + /// + /// + /// A mailbox stored before this setting existed loads with UTF-8, which AI Studio always used + /// until then. + /// + public MailboxPasswordEncoding PasswordEncoding { get; set; } = MailboxPasswordEncoding.UTF8; + /// /// The username to sign in with, often the e-mail address. /// diff --git a/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncoding.cs b/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncoding.cs new file mode 100644 index 000000000..7735a0fd1 --- /dev/null +++ b/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncoding.cs @@ -0,0 +1,33 @@ +namespace AIStudio.Settings.DataModel; + +/// +/// How AI Studio encodes the username and the password when it signs in to an IMAP server. +/// +/// +/// The characters of ASCII come out the same in every member, but those beyond it do not, e.g., the +/// German umlauts, ß, §, or €. Most servers expect UTF-8. Others, Microsoft Exchange among them, +/// compare the bytes with the password of the Windows account and expect Windows-1252. +/// +public enum MailboxPasswordEncoding +{ + /// + /// An encoding this version of AI Studio does not know, e.g., one written by a newer version. AI Studio never signs in then. + /// + /// + /// It is the member with the underlying value 0 on purpose: when the settings file holds a value + /// TolerantEnumConverter cannot read, it falls back to that member. Falling back to an encoding + /// instead would sign in with bytes which may not be the password, and every such attempt counts + /// as a failed sign-in, which can lock the account. + /// + UNKNOWN = 0, + + /// + /// UTF-8, as the standard for signing in with a password demands (RFC 4616). + /// + UTF8, + + /// + /// Windows-1252, the Western European code page of Windows, which Latin-1 is a part of. + /// + WINDOWS_1252, +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncodingExtensions.cs b/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncodingExtensions.cs new file mode 100644 index 000000000..3c8e8cce3 --- /dev/null +++ b/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncodingExtensions.cs @@ -0,0 +1,73 @@ +using System.Text; + +namespace AIStudio.Settings.DataModel; + +public static class MailboxPasswordEncodingExtensions +{ + /// + /// UTF-8 which refuses what it cannot encode, such as a lone surrogate, instead of replacing it. + /// + private static readonly Encoding UTF8_STRICT = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + /// + /// Windows-1252 which refuses a character it lacks, such as ẞ, instead of sending a question mark. + /// + /// + /// .NET knows the code pages of Windows only once their provider is registered. + /// + private static readonly Lazy WINDOWS_1252_STRICT = new(() => + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + return Encoding.GetEncoding(1252, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); + }); + + extension(MailboxPasswordEncoding passwordEncoding) + { + /// + /// The encoding to hand to the IMAP client. + /// + /// The encoding, or null for one this version does not know. + public Encoding? TextEncoding => passwordEncoding switch + { + MailboxPasswordEncoding.UTF8 => UTF8_STRICT, + MailboxPasswordEncoding.WINDOWS_1252 => WINDOWS_1252_STRICT.Value, + + _ => null, + }; + + /// + /// Prepares a username or a password for this encoding. + /// + /// + /// For Windows-1252, the text is normalized first (NFC): an ä may arrive as an a followed by a + /// combining diaeresis, e.g., from a password manager, and only the composed ä exists in + /// Windows-1252. UTF-8 takes the text as it is, as it always did. + /// + /// The username or the password. + /// The text to sign in with. + /// Whether the encoding has every character of the text. + public bool TryPrepare(string text, out string prepared) + { + prepared = text; + if (passwordEncoding.TextEncoding is not { } encoding) + return false; + + try + { + if (passwordEncoding is MailboxPasswordEncoding.WINDOWS_1252) + prepared = text.Normalize(NormalizationForm.FormC); + + encoding.GetByteCount(prepared); + return true; + } + + // Thrown for a character the encoding lacks, and for a lone surrogate, which no encoding has. + // EncoderFallbackException is one of them: + catch (ArgumentException) + { + prepared = text; + return false; + } + } + } +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index 3d9029144..b989a83d1 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -1,4 +1,5 @@ using System.Net.Sockets; +using System.Text; using AIStudio.Settings.DataModel; using AIStudio.Tools.Databases.IndexStore; @@ -100,7 +101,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable /// The connection or the sign-in failed. public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, CancellationToken token) { - if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) + if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || mailbox.PasswordEncoding is MailboxPasswordEncoding.UNKNOWN || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The mailbox settings are incomplete, or this version of AI Studio does not know them."); if (!policy.IsAllowed(mailbox.Host)) @@ -123,7 +124,7 @@ public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailS try { - await this.SignInAsync(mailbox.Username, password, token); + await this.SignInAsync(mailbox.Username, password, mailbox.PasswordEncoding, token); } catch (Exception e) when (Classify(e, token) is { } failure) { @@ -470,11 +471,48 @@ private static async Task FetchAttachmentPieceAsync(IMailFolder folder, return entity is TextPart textPart ? textPart.Text : null; } - private async Task SignInAsync(string username, string password, CancellationToken token) + /// + /// The encodings a sign-in may use, the best first. + /// + /// + /// The stored encoding comes first, the other one second. An encoding is left out when it lacks + /// a character of the username or the password, e.g., Windows-1252 has no ẞ. Windows-1252 is + /// left out as well when the server does not offer PLAIN: MailKit sends the LOGIN command in + /// UTF-8, whatever encoding it is handed. When both are ASCII, every encoding sends the same + /// bytes, so only the first one is left: a second attempt would only fail the same way. + /// + /// The encoding stored for the mailbox. + /// The username. + /// The password. + /// Whether the server offers the SASL mechanism PLAIN. + /// The encodings, possibly none at all. + internal static IReadOnlyList GetSignInEncodings(MailboxPasswordEncoding storedEncoding, string username, string password, bool offersPlain) + { + MailboxPasswordEncoding[] candidates = storedEncoding is MailboxPasswordEncoding.WINDOWS_1252 + ? [MailboxPasswordEncoding.WINDOWS_1252, MailboxPasswordEncoding.UTF8] + : [MailboxPasswordEncoding.UTF8, MailboxPasswordEncoding.WINDOWS_1252]; + + var usable = candidates + .Where(candidate => candidate is MailboxPasswordEncoding.UTF8 || offersPlain) + .Where(candidate => candidate.TryPrepare(username, out _) && candidate.TryPrepare(password, out _)) + .ToList(); + + return Ascii.IsValid(username) && Ascii.IsValid(password) ? usable.Take(1).ToList() : usable; + } + + private async Task SignInAsync(string username, string password, MailboxPasswordEncoding storedEncoding, CancellationToken token) { - if (this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM)) + var offersPlain = this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM); + var encodings = GetSignInEncodings(storedEncoding, username, password, offersPlain); + if (encodings.Count == 0) + throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "No encoding has every character of the username and the password."); + + var encoding = encodings[0]; + encoding.TryPrepare(username, out var preparedUsername); + encoding.TryPrepare(password, out var preparedPassword); + if (offersPlain) { - await this.client.AuthenticateAsync(new SaslMechanismPlain(username, password), token); + await this.client.AuthenticateAsync(new SaslMechanismPlain(encoding.TextEncoding!, preparedUsername, preparedPassword), token); return; } @@ -482,10 +520,11 @@ private async Task SignInAsync(string username, string password, CancellationTok throw new MailboxConnectionException(MailboxConnectionFailure.SERVER_ERROR, "The IMAP server offers no way to sign in with a password."); // - // With no mechanism left to try, the client signs in with the LOGIN command alone: + // With no mechanism left to try, the client signs in with the LOGIN command alone, always in + // UTF-8, cf. GetSignInEncodings: // this.client.AuthenticationMechanisms.Clear(); - await this.client.AuthenticateAsync(username, password, token); + await this.client.AuthenticateAsync(preparedUsername, preparedPassword, token); } private static bool TryGetSocketOptions(MailboxTransportSecurity transportSecurity, out SecureSocketOptions socketOptions) diff --git a/app/Tests/Settings/MailboxSettingsTests.cs b/app/Tests/Settings/MailboxSettingsTests.cs index 292707ac9..5949bc4c6 100644 --- a/app/Tests/Settings/MailboxSettingsTests.cs +++ b/app/Tests/Settings/MailboxSettingsTests.cs @@ -40,6 +40,7 @@ public sealed class MailboxSettingsTests Port = 143, TransportSecurity = MailboxTransportSecurity.STARTTLS, AuthMethod = MailboxAuthMethod.PASSWORD, + PasswordEncoding = MailboxPasswordEncoding.WINDOWS_1252, Username = "someone@example.org", RootFolder = "INBOX/Projects", IncludeSentAndDrafts = false, @@ -137,6 +138,14 @@ public void AMailboxStoredBeforeSentMailsAndDraftsWereChoosableIncludesThem() Assert.That(mailbox.IncludeSentAndDrafts, Is.True); } + [Test] + public void AMailboxStoredBeforeThePasswordEncodingSignsInWithUTF8() + { + // UTF-8 is what every sign-in used until then: + var mailbox = JsonSerializer.Deserialize("""{"RootFolder": "INBOX"}""", SettingsManager.JSON_OPTIONS); + Assert.That(mailbox.PasswordEncoding, Is.EqualTo(MailboxPasswordEncoding.UTF8)); + } + [Test] public void ValuesThisVersionCannotReadFallBackToTheSafeSide() { @@ -151,6 +160,7 @@ public void ValuesThisVersionCannotReadFallBackToTheSafeSide() "ConfidenceLevel": "EXTREMELY_HIGH", "TransportSecurity": "QUANTUM_TLS", "AuthMethod": "PASSKEY", + "PasswordEncoding": "EBCDIC", "MaxAge": "LAST_36_MONTHS", "OutboundDataRestriction": "NOTHING_AT_ALL" } @@ -162,6 +172,7 @@ public void ValuesThisVersionCannotReadFallBackToTheSafeSide() Assert.That(mailbox.ConfidenceLevel, Is.EqualTo(ConfidenceLevel.NONE)); Assert.That(mailbox.TransportSecurity, Is.EqualTo(MailboxTransportSecurity.UNKNOWN)); Assert.That(mailbox.AuthMethod, Is.EqualTo(MailboxAuthMethod.UNKNOWN)); + Assert.That(mailbox.PasswordEncoding, Is.EqualTo(MailboxPasswordEncoding.UNKNOWN)); Assert.That(mailbox.MaxAge, Is.EqualTo(MailboxMaxAge.LAST_3_MONTHS)); Assert.That(mailbox.OutboundDataRestriction, Is.EqualTo(OutboundDataRestriction.ONLY_CONFIGURED_SERVICES)); } diff --git a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs index ec42acc68..d05e53166 100644 --- a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs +++ b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs @@ -50,6 +50,7 @@ private static IEnumerable InvalidSettings() { yield return Case("unknown transport security", MAILBOX with { TransportSecurity = MailboxTransportSecurity.UNKNOWN }, PASSWORD); yield return Case("unknown auth method", MAILBOX with { AuthMethod = MailboxAuthMethod.UNKNOWN }, PASSWORD); + yield return Case("unknown password encoding", MAILBOX with { PasswordEncoding = MailboxPasswordEncoding.UNKNOWN }, PASSWORD); yield return Case("no host", MAILBOX with { Host = " " }, PASSWORD); yield return Case("a URL as host", MAILBOX with { Host = "imaps://imap.example.org" }, PASSWORD); yield return Case("port 0", MAILBOX with { Port = 0 }, PASSWORD); @@ -107,6 +108,42 @@ public async Task AServerTheOrganizationDoesNotAllowIsNeverContacted() Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.SERVER_NOT_ALLOWED)); } + private static IEnumerable SignInEncodings() + { + const MailboxPasswordEncoding UTF8 = MailboxPasswordEncoding.UTF8; + const MailboxPasswordEncoding WINDOWS_1252 = MailboxPasswordEncoding.WINDOWS_1252; + + // ASCII sends the same bytes in every encoding, so a second attempt would fail the same way: + yield return Case("ASCII", UTF8, "someone", "Sommer-2026!", true, [UTF8]); + yield return Case("ASCII, Windows-1252 stored", WINDOWS_1252, "someone", "Sommer-2026!", true, [WINDOWS_1252]); + + yield return Case("umlaut in the password", UTF8, "someone", "Grüße-2026", true, [UTF8, WINDOWS_1252]); + yield return Case("umlaut, Windows-1252 stored", WINDOWS_1252, "someone", "Grüße-2026", true, [WINDOWS_1252, UTF8]); + yield return Case("umlaut in the username", UTF8, @"FIRMA\müller", "Sommer-2026!", true, [UTF8, WINDOWS_1252]); + yield return Case("section sign", UTF8, "someone", "Abs§2", true, [UTF8, WINDOWS_1252]); + yield return Case("euro sign", UTF8, "someone", "100€", true, [UTF8, WINDOWS_1252]); + + // Windows-1252 has no capital sharp s: + yield return Case("capital sharp s", UTF8, "someone", "STRAẞE", true, [UTF8]); + yield return Case("capital sharp s, Windows-1252 stored", WINDOWS_1252, "someone", "STRAẞE", true, [UTF8]); + + // Without PLAIN, MailKit sends the LOGIN command in UTF-8, whatever it is handed: + yield return Case("umlaut without PLAIN", UTF8, "someone", "Grüße-2026", false, [UTF8]); + yield return Case("umlaut without PLAIN, Windows-1252 stored", WINDOWS_1252, "someone", "Grüße-2026", false, [UTF8]); + + // No encoding has a lone surrogate: + yield return Case("lone surrogate", UTF8, "someone", "abc\uD800", true, []); + yield break; + + static TestCaseData Case(string name, MailboxPasswordEncoding storedEncoding, string username, string password, bool offersPlain, MailboxPasswordEncoding[] expected) => new TestCaseData(storedEncoding, username, password, offersPlain, expected).SetArgDisplayNames(name); + } + + [TestCaseSource(nameof(SignInEncodings))] + public void ASignInUsesOnlyTheEncodingsWhichMakeADifference(MailboxPasswordEncoding storedEncoding, string username, string password, bool offersPlain, MailboxPasswordEncoding[] expected) + { + Assert.That(ImapMailboxConnector.GetSignInEncodings(storedEncoding, username, password, offersPlain), Is.EqualTo(expected)); + } + [TestCase("Projects", '/', ExpectedResult = true)] [TestCase("Projekte 2026", '.', ExpectedResult = true)] [TestCase("Ablage/Alt", '.', ExpectedResult = true)] diff --git a/app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs b/app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs new file mode 100644 index 000000000..0b4768710 --- /dev/null +++ b/app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs @@ -0,0 +1,134 @@ +using AIStudio.Settings.DataModel; + +using MailKit.Security; + +namespace AIStudio.Tests.Tools.Mail; + +/// +/// Checks the bytes a password becomes when signing in, for the special characters of German. +/// +/// +/// Microsoft Exchange compares the bytes with the password of the Windows account in Windows-1252, +/// so a password sent in UTF-8 fails there as soon as it holds one of these characters. +/// +[TestFixture] +public sealed class MailboxPasswordEncodingTests +{ + private const string USERNAME = "u"; + + private static IEnumerable GermanCharacters() + { + yield return Case("ä", "C3 A4", "E4"); + yield return Case("ö", "C3 B6", "F6"); + yield return Case("ü", "C3 BC", "FC"); + yield return Case("Ä", "C3 84", "C4"); + yield return Case("Ö", "C3 96", "D6"); + yield return Case("Ü", "C3 9C", "DC"); + yield return Case("ß", "C3 9F", "DF"); + yield return Case("§", "C2 A7", "A7"); + yield return Case("°", "C2 B0", "B0"); + yield return Case("´", "C2 B4", "B4"); + yield return Case("µ", "C2 B5", "B5"); + yield return Case("²", "C2 B2", "B2"); + yield return Case("³", "C2 B3", "B3"); + yield return Case("€", "E2 82 AC", "80"); + yield return Case("„", "E2 80 9E", "84"); + yield return Case("“", "E2 80 9C", "93"); + yield return Case("‚", "E2 80 9A", "82"); + yield return Case("‘", "E2 80 98", "91"); + yield return Case("–", "E2 80 93", "96"); + yield return Case("…", "E2 80 A6", "85"); + yield break; + + static TestCaseData Case(string character, string utf8, string windows1252) => new TestCaseData(character, utf8, windows1252).SetArgDisplayNames(character); + } + + [TestCaseSource(nameof(GermanCharacters))] + public void PlainSendsTheBytesOfTheChosenEncoding(string character, string utf8, string windows1252) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.UTF8, character), Is.EqualTo(utf8)); + Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.WINDOWS_1252, character), Is.EqualTo(windows1252)); + } + } + + [Test] + public void AsciiIsTheSameInEveryEncoding() + { + const string PASSWORD = "Sommer-2026!"; + Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.WINDOWS_1252, PASSWORD), Is.EqualTo(GetPlainPasswordBytes(MailboxPasswordEncoding.UTF8, PASSWORD))); + } + + [TestCase("ẞ")] + [TestCase("Straße 🙂")] + public void Windows1252RefusesWhatItLacks(string text) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncoding.WINDOWS_1252.TryPrepare(text, out _), Is.False); + Assert.That(MailboxPasswordEncoding.UTF8.TryPrepare(text, out var prepared), Is.True); + Assert.That(prepared, Is.EqualTo(text)); + } + } + + [Test] + public void ALoneSurrogateIsRefusedByEveryEncoding() + { + const string TEXT = "abc\uD800"; + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncoding.UTF8.TryPrepare(TEXT, out _), Is.False); + Assert.That(MailboxPasswordEncoding.WINDOWS_1252.TryPrepare(TEXT, out _), Is.False); + } + } + + [Test] + public void Windows1252ComposesADecomposedUmlaut() + { + // An a followed by a combining diaeresis, as some password managers deliver an ä: + const string DECOMPOSED = "Käse"; + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncoding.WINDOWS_1252.TryPrepare(DECOMPOSED, out var prepared), Is.True); + Assert.That(prepared, Is.EqualTo("Käse")); + Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.WINDOWS_1252, DECOMPOSED), Is.EqualTo("4B E4 73 65")); + } + } + + [Test] + public void Utf8TakesTheTextAsItIs() + { + const string DECOMPOSED = "Käse"; + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncoding.UTF8.TryPrepare(DECOMPOSED, out var prepared), Is.True); + Assert.That(prepared, Is.EqualTo(DECOMPOSED)); + } + } + + [Test] + public void AnUnknownEncodingEncodesNothing() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncoding.UNKNOWN.TextEncoding, Is.Null); + Assert.That(MailboxPasswordEncoding.UNKNOWN.TryPrepare("abc", out _), Is.False); + } + } + + /// + /// The bytes of the password in the message which the SASL mechanism PLAIN sends, as hex. + /// + private static string GetPlainPasswordBytes(MailboxPasswordEncoding passwordEncoding, string password) + { + Assert.That(passwordEncoding.TryPrepare(password, out var preparedPassword), Is.True); + + // PLAIN sends the authorization identity, the username, and the password, each after a zero byte: + var mechanism = new SaslMechanismPlain(passwordEncoding.TextEncoding!, USERNAME, preparedPassword); + var message = Convert.FromBase64String(mechanism.Challenge(null, CancellationToken.None)); + var passwordBytes = message.AsSpan(1 + USERNAME.Length + 1); + + return string.Join(' ', Convert.ToHexString(passwordBytes).Chunk(2).Select(pair => new string(pair))); + } +} \ No newline at end of file From aa307ca3f08bd2a4263cb4aa7c2f814cc1caf52a Mon Sep 17 00:00:00 2001 From: Peer Hogeterp Date: Mon, 23 Nov 2026 14:47:29 +0100 Subject: [PATCH 03/15] Fixed signing in to mailboxes with German special characters in the password MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Microsoft Exchange expects the username and the password in Windows-1252, while AI Studio always sent UTF-8. A password with an umlaut, ß, §, or € was therefore refused. The connection test, which the user starts, may now try the other encoding once more when the server refused the first one, but only when the username or the password holds a character beyond ASCII. The encoding the server accepted is stored with the mailbox. A refused sign-in on record is cleared once the mailbox is saved with the new encoding. The synchronization, a manual retry, and creating a folder still sign in exactly once, with the stored encoding. --- .../Dialogs/DataSourceMailboxDialog.razor.cs | 26 ++++--- .../Settings/DataModel/DataSourceMailbox.cs | 2 +- .../Tools/Mail/ImapMailboxConnector.cs | 76 ++++++++++++------- .../Tools/Services/Indexing/MailboxIndexer.cs | 2 +- .../wwwroot/changelog/v26.11.2.md | 1 + .../Tools/Mail/ImapMailboxConnectorTests.cs | 4 +- 6 files changed, 71 insertions(+), 40 deletions(-) diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index ecbe11d0b..e994d9fd0 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -20,10 +20,14 @@ namespace AIStudio.Dialogs; /// Adds or edits a mailbox. /// /// -/// Every connection test is exactly one sign-in, started by the user. Its outcome only touches the -/// recorded sign-in failure of the mailbox when the test used the settings and the password stored -/// for it: a failure with a password the user is still typing says nothing about the stored one, -/// and neither does a success. +/// Every connection test is one sign-in, started by the user, and a second one only when the username +/// or the password holds a character beyond ASCII and the server refused the first encoding, cf. +/// ImapMailboxConnector.GetSignInEncodings. The encoding the server accepted is kept and stored along +/// with the mailbox. The outcome of a test only touches the recorded sign-in failure of the mailbox +/// when the test used the settings and the password stored for it: a failure with a password the user +/// is still typing says nothing about the stored one, and neither does a success. A success in +/// another encoding clears the failure only once the mailbox is saved with it, since the +/// synchronization would sign in with the stored encoding until then. /// public partial class DataSourceMailboxDialog : MSGComponentBase { @@ -516,7 +520,7 @@ private async Task TestConnection() { using var timeout = new CancellationTokenSource(CONNECTION_TEST_TIMEOUT); await using var connector = new ImapMailboxConnector(); - await connector.ConnectAsync(this.CreateDataSource(), settings.Password, MailServerPolicy.Read(this.SettingsManager), timeout.Token); + this.dataPasswordEncoding = await connector.ConnectAsync(this.CreateDataSource(), settings.Password, MailServerPolicy.Read(this.SettingsManager), mayTryOtherEncoding: true, timeout.Token); this.serverFolders = await connector.GetFoldersAsync(timeout.Token); this.testFailure = null; this.Logger.LogInformation($"Tested the connection of the mailbox '{this.dataId}' successfully."); @@ -555,7 +559,7 @@ private async Task TestConnection() { using var timeout = new CancellationTokenSource(CONNECTION_TEST_TIMEOUT); await using var connector = new ImapMailboxConnector(); - await connector.ConnectAsync(this.CreateDataSource(), settings.Password, MailServerPolicy.Read(this.SettingsManager), timeout.Token); + await connector.ConnectAsync(this.CreateDataSource(), settings.Password, MailServerPolicy.Read(this.SettingsManager), mayTryOtherEncoding: false, timeout.Token); var createdFolder = await connector.CreateFolderAsync(parentFullName, name, timeout.Token); this.serverFolders = [..this.serverFolders, createdFolder]; @@ -605,7 +609,10 @@ private async Task RecordSignInOutcomeAsync(ConnectionSettings settings, Mailbox switch (failure) { case null: - await indexStore.ClearMailboxAuthFailureAsync(this.dataId, CancellationToken.None); + // In another encoding, the failure stays on record until the mailbox is saved, cf. Store: + if (this.dataPasswordEncoding == this.DataSource.PasswordEncoding) + await indexStore.ClearMailboxAuthFailureAsync(this.dataId, CancellationToken.None); + this.authFailure = null; break; @@ -673,8 +680,9 @@ private async Task Store() this.Logger.LogWarning($"Failed to delete the password of the mailbox '{this.dataId}' stored under its previous name: {deleteResponse.Issue}"); } - // A new password earns the next synchronization one attempt to sign in: - if (this.IsEditing && isNewPassword) + // A new password, or the encoding a connection test found, earns the next synchronization one attempt to sign in: + var isNewPasswordEncoding = this.IsEditing && this.DataSource.PasswordEncoding != mailbox.PasswordEncoding; + if (this.IsEditing && (isNewPassword || isNewPasswordEncoding)) { var indexStore = await this.DatabaseClientProvider.GetIndexStoreAsync(); await indexStore.ClearMailboxAuthFailureAsync(this.dataId, CancellationToken.None); diff --git a/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs b/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs index 736580be5..6bcfe284a 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs @@ -78,7 +78,7 @@ public DataSourceMailbox() /// /// /// A mailbox stored before this setting existed loads with UTF-8, which AI Studio always used - /// until then. + /// until then. The connection test finds out which one the server expects. /// public MailboxPasswordEncoding PasswordEncoding { get; set; } = MailboxPasswordEncoding.UTF8; diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index b989a83d1..e849f64b9 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -20,7 +20,9 @@ namespace AIStudio.Tools.Mail; /// Every sign-in is exactly one attempt with the password. An IMAP client would otherwise try one /// mechanism after the other and the LOGIN command last, and a directory such as Active Directory /// counts each rejected attempt on its way to locking the account. For the same reason, nothing is -/// sent at all when the password is empty or a setting is unknown to this version.

+/// sent at all when the password is empty or a setting is unknown to this version. The one exception +/// is a connection test the user started: when the username or the password holds a character beyond +/// ASCII, such as an umlaut, it may try the other encoding once more, cf. GetSignInEncodings.

/// Before signing in, the caller has to make sure that no failed sign-in is on record for this /// mailbox. Whatever fails arrives as MailboxConnectionException with its failure code, and nothing /// here writes to the log: the answers of a server may name the user, so the caller logs the @@ -97,9 +99,11 @@ public sealed class ImapMailboxConnector : IAsyncDisposable /// The mailbox to connect to. /// The password, as stored in the OS keyring or just typed in. /// Which mail servers the organization allows. Every connection passes here, so this is where a server it does not allow is refused. + /// Whether a refused sign-in may be tried once more in the other encoding, cf. GetSignInEncodings. Only for a connection test the user started. /// The cancellation token. + /// The encoding the server accepted the username and the password in. /// The connection or the sign-in failed. - public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, CancellationToken token) + public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, bool mayTryOtherEncoding, CancellationToken token) { if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || mailbox.PasswordEncoding is MailboxPasswordEncoding.UNKNOWN || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The mailbox settings are incomplete, or this version of AI Studio does not know them."); @@ -108,27 +112,31 @@ public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailS throw new MailboxConnectionException(MailboxConnectionFailure.SERVER_NOT_ALLOWED, "The organization allows only its own mail servers, and the server of this mailbox is none of them."); this.client.ServerCertificateValidationCallback = ExternalHttpClientTimeout.CreateServerCertificateValidationCallback(idnHost, ExternalHttpTrustPolicy.ALLOW_CUSTOM_ROOTS_WHEN_HOST_WHITELISTED); - try - { - await this.client.ConnectAsync(idnHost, mailbox.Port, socketOptions, token); - } - catch (NotSupportedException e) - { - // Thrown when the server does not offer STARTTLS. The connection never goes on without it: - throw new MailboxConnectionException(MailboxConnectionFailure.TLS_FAILED, "The IMAP server does not offer STARTTLS.", e); - } - catch (Exception e) when (Classify(e, token) is { } failure) - { - throw new MailboxConnectionException(failure, $"Connecting to the IMAP server failed: {failure}.", e); - } + await this.ConnectToServerAsync(idnHost, mailbox.Port, socketOptions, token); - try - { - await this.SignInAsync(mailbox.Username, password, mailbox.PasswordEncoding, token); - } - catch (Exception e) when (Classify(e, token) is { } failure) + var offersPlain = this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM); + var encodings = GetSignInEncodings(mailbox.PasswordEncoding, mailbox.Username, password, offersPlain); + if (encodings.Count == 0) + throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "No encoding has every character of the username and the password."); + + var attempts = mayTryOtherEncoding ? encodings.Count : 1; + for (var attempt = 0; ; attempt++) { - throw new MailboxConnectionException(failure, $"Signing in to the IMAP server failed: {failure}.", e); + try + { + await this.SignInAsync(mailbox.Username, password, encodings[attempt], offersPlain, token); + return encodings[attempt]; + } + catch (AuthenticationException) when (attempt + 1 < attempts) + { + // Some servers hang up after a refused sign-in: + if (!this.client.IsConnected) + await this.ConnectToServerAsync(idnHost, mailbox.Port, socketOptions, token); + } + catch (Exception e) when (Classify(e, token) is { } failure) + { + throw new MailboxConnectionException(failure, $"Signing in to the IMAP server failed: {failure}.", e); + } } } @@ -500,14 +508,28 @@ internal static IReadOnlyList GetSignInEncodings(Mailbo return Ascii.IsValid(username) && Ascii.IsValid(password) ? usable.Take(1).ToList() : usable; } - private async Task SignInAsync(string username, string password, MailboxPasswordEncoding storedEncoding, CancellationToken token) + private async Task ConnectToServerAsync(string idnHost, int port, SecureSocketOptions socketOptions, CancellationToken token) { - var offersPlain = this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM); - var encodings = GetSignInEncodings(storedEncoding, username, password, offersPlain); - if (encodings.Count == 0) - throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "No encoding has every character of the username and the password."); + try + { + await this.client.ConnectAsync(idnHost, port, socketOptions, token); + } + catch (NotSupportedException e) + { + // Thrown when the server does not offer STARTTLS. The connection never goes on without it: + throw new MailboxConnectionException(MailboxConnectionFailure.TLS_FAILED, "The IMAP server does not offer STARTTLS.", e); + } + catch (Exception e) when (Classify(e, token) is { } failure) + { + throw new MailboxConnectionException(failure, $"Connecting to the IMAP server failed: {failure}.", e); + } + } - var encoding = encodings[0]; + /// + /// Signs in once, in the given encoding, which GetSignInEncodings offered. + /// + private async Task SignInAsync(string username, string password, MailboxPasswordEncoding encoding, bool offersPlain, CancellationToken token) + { encoding.TryPrepare(username, out var preparedUsername); encoding.TryPrepare(password, out var preparedPassword); if (offersPlain) diff --git a/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.cs b/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.cs index beecb1a7d..d1240ab34 100644 --- a/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.cs +++ b/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.cs @@ -153,7 +153,7 @@ public async Task ProcessAsync(IndexedRunContext context, Dat await using var connector = new ImapMailboxConnector(); try { - await connector.ConnectAsync(mailbox, password, policy, token); + await connector.ConnectAsync(mailbox, password, policy, mayTryOtherEncoding: false, token); } catch (MailboxConnectionException e) { diff --git a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md index e3746be52..837b95001 100644 --- a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md +++ b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md @@ -36,6 +36,7 @@ - Fixed the settings of the security audit for assistant plugins, which you could change even when your organization had locked them through a configuration plugin. They now show the lock, like all other settings your organization manages. - Fixed the automatic security audit of assistant plugins when no model was set for it: you got two error messages for each plugin, again whenever you opened the assistants or plugins page. Now AI Studio tells you once, and the settings of the security audit show a warning. - Fixed the AI-based data validation of classic RAG, which kept passages that the AI had judged as not fitting your question. Now the AI only gets the passages that fit. When the check fails for a passage, AI Studio keeps it, and when it fails for all of them, AI Studio tells you. +- Fixed signing in to a mailbox when your username or password contains German special characters, such as ä, ö, ü, ß, §, or €. Some mail servers, Microsoft Exchange among them, expect these characters in another encoding than most others. When you test the connection of a mailbox, AI Studio now finds out which encoding your mail server expects and keeps it when you save the mailbox. If signing in to one of your mailboxes failed for this reason, open the settings of that mailbox, test the connection, and save it. - Upgraded several libraries to improve security. - Upgraded Tauri to v2.12.7. - Upgraded PDFium to v158.0.8125.0. diff --git a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs index d05e53166..0be623379 100644 --- a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs +++ b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs @@ -91,7 +91,7 @@ public async Task InvalidSettingsNeverReachTheServer(DataSourceMailbox mailbox, // failure instead of this one. // await using var connector = new ImapMailboxConnector(); - var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(mailbox, password, MailServerPolicy.ANY_SERVER, CancellationToken.None)); + var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(mailbox, password, MailServerPolicy.ANY_SERVER, mayTryOtherEncoding: true, CancellationToken.None)); Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.INVALID_SETTINGS)); } @@ -104,7 +104,7 @@ public async Task AServerTheOrganizationDoesNotAllowIsNeverContacted() // await using var connector = new ImapMailboxConnector(); var policy = new MailServerPolicy(true, ["imap.intra.example.org"]); - var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(MAILBOX, PASSWORD, policy, CancellationToken.None)); + var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(MAILBOX, PASSWORD, policy, mayTryOtherEncoding: true, CancellationToken.None)); Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.SERVER_NOT_ALLOWED)); } From 8d08c3a315736f57ba6664c8c1c146fe92ea336c Mon Sep 17 00:00:00 2001 From: Peer Hogeterp Date: Mon, 23 Nov 2026 15:59:47 +0100 Subject: [PATCH 04/15] Added the password encoding to the mail servers of organizations --- .../Dialogs/DataSourceMailboxDialog.razor.cs | 27 +++- .../Plugins/configuration/plugin.lua | 8 ++ .../Settings/DataModel/DataMailboxProvider.cs | 24 ++++ .../Tools/Mail/ImapMailboxConnector.cs | 56 ++++++-- .../wwwroot/changelog/v26.11.2.md | 1 + .../MailboxProviderConfigurationTests.cs | 8 ++ .../Tools/Mail/ImapMailboxConnectorTests.cs | 135 ++++++++++++++++++ 7 files changed, 246 insertions(+), 13 deletions(-) diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index e994d9fd0..f77112736 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -22,8 +22,9 @@ namespace AIStudio.Dialogs; /// /// Every connection test is one sign-in, started by the user, and a second one only when the username /// or the password holds a character beyond ASCII and the server refused the first encoding, cf. -/// ImapMailboxConnector.GetSignInEncodings. The encoding the server accepted is kept and stored along -/// with the mailbox. The outcome of a test only touches the recorded sign-in failure of the mailbox +/// ImapMailboxConnector.GetSignInEncodings. The first one is the encoding a configuration plugin sets +/// for the mail server, if any, and the one stored for the mailbox otherwise. The encoding the server +/// accepted is kept and stored along with the mailbox. The outcome of a test only touches the recorded sign-in failure of the mailbox /// when the test used the settings and the password stored for it: a failure with a password the user /// is still typing says nothing about the stored one, and neither does a success. A success in /// another encoding clears the failure only once the mailbox is saved with it, since the @@ -518,9 +519,17 @@ private async Task TestConnection() try { + // + // The organization knows which encoding its mail server expects, so the test tries that + // one first, and the other one only when the server refuses it: + // + var mailbox = this.CreateDataSource(); + if (this.GetOrganizationPasswordEncoding(mailbox.Host) is { } organizationPasswordEncoding) + mailbox = mailbox with { PasswordEncoding = organizationPasswordEncoding }; + using var timeout = new CancellationTokenSource(CONNECTION_TEST_TIMEOUT); await using var connector = new ImapMailboxConnector(); - this.dataPasswordEncoding = await connector.ConnectAsync(this.CreateDataSource(), settings.Password, MailServerPolicy.Read(this.SettingsManager), mayTryOtherEncoding: true, timeout.Token); + this.dataPasswordEncoding = await connector.ConnectAsync(mailbox, settings.Password, MailServerPolicy.Read(this.SettingsManager), mayTryOtherEncoding: true, timeout.Token); this.serverFolders = await connector.GetFoldersAsync(timeout.Token); this.testFailure = null; this.Logger.LogInformation($"Tested the connection of the mailbox '{this.dataId}' successfully."); @@ -548,6 +557,18 @@ private async Task TestConnection() await this.form.ValidateAsync(); } + /// + /// The encoding a configuration plugin sets for this mail server, cf. DataMailboxProvider.PasswordEncoding. + /// + /// + /// Found by the host rather than by the chosen provider: the user may have typed another host since. + /// + /// The host the connection goes to. + /// The encoding, or null when no mail server of the organization on this host sets one. + private MailboxPasswordEncoding? GetOrganizationPasswordEncoding(string host) => this.organizationProviders + .FirstOrDefault(provider => provider.PasswordEncoding is not null && MailServerHosts.AreSame(provider.Host, host))? + .PasswordEncoding; + private async Task CreateFolder(string parentFullName, string name) { var settings = this.CurrentSettings; diff --git a/app/MindWork AI Studio/Plugins/configuration/plugin.lua b/app/MindWork AI Studio/Plugins/configuration/plugin.lua index 9b06d5985..2e0eece83 100644 --- a/app/MindWork AI Studio/Plugins/configuration/plugin.lua +++ b/app/MindWork AI Studio/Plugins/configuration/plugin.lua @@ -351,6 +351,13 @@ CONFIG["DATA_SOURCES"] = {} -- UsernameHint Optional text telling users what to enter as their username. -- HelpUrl Optional http or https address of your instructions, e.g., on how to -- enable IMAP for a mailbox. +-- PasswordEncoding Optional encoding your mail server expects for usernames and passwords +-- with characters beyond ASCII, such as German umlauts: UTF8, which most +-- servers expect, or WINDOWS_1252, which Microsoft Exchange expects. The +-- connection test in the mailbox dialog tries this encoding first and the +-- other one only when the server refuses it. Without this field, a new +-- mailbox starts with UTF8, and on an Exchange server, every user whose +-- password holds such a character spends one failed sign-in on it. -- An entry with an invalid field is left out as a whole, and the log names the field. -- To allow mailboxes on these mail servers only, see DataMailboxes.AllowOnlyOrganizationMailServers. CONFIG["MAILBOX_PROVIDERS"] = {} @@ -364,6 +371,7 @@ CONFIG["MAILBOX_PROVIDERS"] = {} -- ["Port"] = 993, -- ["UsernameHint"] = "Your account as DOMAIN\\username", -- ["HelpUrl"] = "https://intranet.example.org/mail/imap", +-- ["PasswordEncoding"] = "WINDOWS_1252", -- } CONFIG["SETTINGS"] = {} diff --git a/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs b/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs index 5f9a2f3cc..4e6a75e7f 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs @@ -58,6 +58,17 @@ public sealed record DataMailboxProvider : ILivePluginContent /// public string HelpUrl { get; private init; } = string.Empty; + /// + /// The encoding the mail server expects for a username or a password with characters beyond + /// ASCII, such as umlauts. Null when the organization did not say. + /// + /// + /// The connection test in the mailbox dialog tries it first and the other encoding only when the + /// server refuses it, so that users of a server such as Microsoft Exchange, which expects + /// Windows-1252, spend no failed sign-in on UTF-8. + /// + public MailboxPasswordEncoding? PasswordEncoding { get; private init; } + /// /// Reads a mail server from an entry of the table MAILBOX_PROVIDERS. /// @@ -131,6 +142,18 @@ public static bool TryParseConfiguration(int index, LuaTable table, Guid configP helpUrl = helpUri.OriginalString; } + MailboxPasswordEncoding? passwordEncoding = null; + if (table.TryGetValue("PasswordEncoding", out var passwordEncodingValue)) + { + if (!passwordEncodingValue.TryRead(out var passwordEncodingText) || !MailboxPasswordEncoding.TryParseName(passwordEncodingText, out var readPasswordEncoding) || readPasswordEncoding is MailboxPasswordEncoding.UNKNOWN) + { + logger.LogWarning("The configured mailbox provider {ProviderIndex} does not contain a valid PasswordEncoding field. Allowed values are UTF8 and WINDOWS_1252.", index); + return false; + } + + passwordEncoding = readPasswordEncoding; + } + provider = new DataMailboxProvider { Id = id.ToString(), @@ -141,6 +164,7 @@ public static bool TryParseConfiguration(int index, LuaTable table, Guid configP TransportSecurity = transportSecurity, UsernameHint = usernameHint, HelpUrl = helpUrl, + PasswordEncoding = passwordEncoding, }; return true; diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index e849f64b9..dcc665588 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -116,22 +116,51 @@ public async Task ConnectAsync(DataSourceMailbox mailbo var offersPlain = this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM); var encodings = GetSignInEncodings(mailbox.PasswordEncoding, mailbox.Username, password, offersPlain); - if (encodings.Count == 0) + return await SignInWithEncodingsAsync( + encodings, + mayTryOtherEncoding, + encoding => this.SignInAsync(mailbox.Username, password, encoding, offersPlain, token), + async () => + { + // Some servers hang up after a refused sign-in: + if (!this.client.IsConnected) + await this.ConnectToServerAsync(idnHost, mailbox.Port, socketOptions, token); + }, + token); + } + + /// + /// Signs in with the encodings GetSignInEncodings offered, at most one attempt each. + /// + /// + /// Every attempt the server refuses counts on the way to locking the account, so this is where + /// their number is decided: one, unless the caller may try the other encoding, and then one per + /// encoding. Only a refused sign-in leads to the next attempt; any other failure ends the sign-in. + /// ImapMailboxConnectorTests counts the attempts. + /// + /// The encodings to try, the best first; at least one. + /// Whether a refused sign-in may be tried once more in the next encoding. + /// Signs in once, in the given encoding. + /// Connects again before the next attempt, when the server hung up. + /// The cancellation token. + /// The encoding the server accepted. + /// Every attempt failed, or another failure ended the sign-in. + internal static async Task SignInWithEncodingsAsync(IReadOnlyList encodings, bool mayTryOtherEncoding, Func signInAsync, Func reconnectAsync, CancellationToken token) + { + var attempts = mayTryOtherEncoding ? encodings.Count : Math.Min(encodings.Count, 1); + if (attempts == 0) throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "No encoding has every character of the username and the password."); - var attempts = mayTryOtherEncoding ? encodings.Count : 1; for (var attempt = 0; ; attempt++) { try { - await this.SignInAsync(mailbox.Username, password, encodings[attempt], offersPlain, token); + await signInAsync(encodings[attempt]); return encodings[attempt]; } catch (AuthenticationException) when (attempt + 1 < attempts) { - // Some servers hang up after a refused sign-in: - if (!this.client.IsConnected) - await this.ConnectToServerAsync(idnHost, mailbox.Port, socketOptions, token); + await reconnectAsync(); } catch (Exception e) when (Classify(e, token) is { } failure) { @@ -526,15 +555,22 @@ private async Task ConnectToServerAsync(string idnHost, int port, SecureSocketOp } /// - /// Signs in once, in the given encoding, which GetSignInEncodings offered. + /// Signs in once, in the given encoding. /// + /// + /// Only for an encoding which GetSignInEncodings offered for this username, password, and server: + /// it made sure that the encoding has every character of both, and that the server offers PLAIN + /// unless the encoding is UTF-8. Should another encoding arrive here anyway, nothing is sent, + /// since the bytes would not be the password and the attempt would count as a failed sign-in. + /// private async Task SignInAsync(string username, string password, MailboxPasswordEncoding encoding, bool offersPlain, CancellationToken token) { - encoding.TryPrepare(username, out var preparedUsername); - encoding.TryPrepare(password, out var preparedPassword); + if (encoding.TextEncoding is not { } textEncoding || !encoding.TryPrepare(username, out var preparedUsername) || !encoding.TryPrepare(password, out var preparedPassword) || (!offersPlain && encoding is not MailboxPasswordEncoding.UTF8)) + throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The encoding cannot carry the username and the password to this IMAP server."); + if (offersPlain) { - await this.client.AuthenticateAsync(new SaslMechanismPlain(encoding.TextEncoding!, preparedUsername, preparedPassword), token); + await this.client.AuthenticateAsync(new SaslMechanismPlain(textEncoding, preparedUsername, preparedPassword), token); return; } diff --git a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md index 837b95001..518a41ba3 100644 --- a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md +++ b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md @@ -9,6 +9,7 @@ - Added the Model Comparison assistant, which shows you which of two models helps you better. You compare them blindly, without knowing which model wrote which answer: with the same request sent to both, or while you work on your own tasks over days or weeks. Charts show you which model wins, and a judge model can give you a second opinion based on your own expectations. You find the assistant in the category "General". Thanks, Dominic Neuburg (`donework`), for this contribution. - Added the minimum confidence of the provider for each AI task, such as the data source selection or the security audit of assistant plugins, to configuration plugins, so that organizations can preset or lock it. - Added the settings of the text content cleaner to configuration plugins, so that organizations can preset or lock which model cleans web content. +- Added the password encoding to the mail servers which organizations offer through configuration plugins. When a username or password contains German special characters, such as umlauts, mail servers like Microsoft Exchange expect them in another encoding than most others. With this setting, the connection test of a mailbox tries the encoding of your organization first, so that you spend no failed sign-in on the other one. - Improved how well the AI remembers what it looked up in a chat: for its earlier answers, it now knows which web pages it read, which searches it ran, and which sources it used. When you ask a follow-up question, it can read the page again instead of claiming that it never read it. - Improved follow-up questions about web pages which a tool found, such as the results of a web search: the Read Web Page tool may read these pages again later in the same chat, also after you restart AI Studio and also when it may otherwise read only addresses which stand in the chat. - Improved the texts of AI Studio: we corrected grammar mistakes, missing words, and punctuation in many English texts and improved the wording of some German ones. A few texts which every language showed in English are now translated as well. diff --git a/app/Tests/Settings/MailboxProviderConfigurationTests.cs b/app/Tests/Settings/MailboxProviderConfigurationTests.cs index 8fab104b7..d12b8c007 100644 --- a/app/Tests/Settings/MailboxProviderConfigurationTests.cs +++ b/app/Tests/Settings/MailboxProviderConfigurationTests.cs @@ -39,6 +39,7 @@ public async Task AFullEntryIsReadAsWritten() ["Port"] = "1143", ["UsernameHint"] = "\"Your account as DOMAIN\\\\username\"", ["HelpUrl"] = "\"https://intranet.example.org/mail/imap\"", + ["PasswordEncoding"] = "\" windows_1252 \"", }); Assert.That(provider, Is.Not.Null); @@ -52,6 +53,7 @@ public async Task AFullEntryIsReadAsWritten() Assert.That(provider.Port, Is.EqualTo(1143)); Assert.That(provider.UsernameHint, Is.EqualTo(@"Your account as DOMAIN\username")); Assert.That(provider.HelpUrl, Is.EqualTo("https://intranet.example.org/mail/imap")); + Assert.That(provider.PasswordEncoding, Is.EqualTo(MailboxPasswordEncoding.WINDOWS_1252)); } } @@ -68,6 +70,7 @@ public async Task WithoutAPortTheEncryptionDecidesIt() Assert.That(withStartTls?.Port, Is.EqualTo(143)); Assert.That(withoutEncryption?.UsernameHint, Is.Empty); Assert.That(withoutEncryption?.HelpUrl, Is.Empty); + Assert.That(withoutEncryption?.PasswordEncoding, Is.Null, "Without a word from the organization, the mailbox keeps the encoding it has."); } } @@ -94,6 +97,11 @@ public async Task AHostWithUmlautsIsKeptAsWritten() [TestCase("Port", "65536")] [TestCase("HelpUrl", "\"ftp://intranet.example.org/mail\"")] [TestCase("HelpUrl", "\"/mail/imap\"")] + [TestCase("PasswordEncoding", "\"UNKNOWN\"")] + [TestCase("PasswordEncoding", "\"UTF-8\"")] + [TestCase("PasswordEncoding", "\"ISO-8859-1\"")] + [TestCase("PasswordEncoding", "\"UTF8, WINDOWS_1252\"")] + [TestCase("PasswordEncoding", "true")] public async Task AnEntryWithAnInvalidFieldIsLeftOut(string field, string? value) { var provider = await ReadAsync(new Dictionary { [field] = value }); diff --git a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs index 0be623379..9bb783d56 100644 --- a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs +++ b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs @@ -31,6 +31,8 @@ public sealed class ImapMailboxConnectorTests Username = "someone@example.org", }; + private static readonly MailboxPasswordEncoding[] BOTH_ENCODINGS = [MailboxPasswordEncoding.UTF8, MailboxPasswordEncoding.WINDOWS_1252]; + private static IEnumerable ExceptionsWithTheirFailure() { yield return Case(new AuthenticationException("The server rejected the credentials."), MailboxConnectionFailure.AUTHENTICATION_FAILED); @@ -144,6 +146,139 @@ public void ASignInUsesOnlyTheEncodingsWhichMakeADifference(MailboxPasswordEncod Assert.That(ImapMailboxConnector.GetSignInEncodings(storedEncoding, username, password, offersPlain), Is.EqualTo(expected)); } + [Test] + public async Task ASynchronizationSignsInOnceInTheStoredEncoding() + { + // The server would accept the other encoding, but only a connection test may find that out: + var server = new SignInServer(accepted: MailboxPasswordEncoding.WINDOWS_1252); + var exception = await SignInExpectingFailureAsync(server, BOTH_ENCODINGS, mayTryOtherEncoding: false); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.AUTHENTICATION_FAILED)); + Assert.That(server.Attempts, Is.EqualTo(new[] { MailboxPasswordEncoding.UTF8 })); + Assert.That(server.Reconnects, Is.Zero); + } + } + + [Test] + public async Task AConnectionTestTriesTheOtherEncodingOnce() + { + var server = new SignInServer(accepted: MailboxPasswordEncoding.WINDOWS_1252); + var accepted = await ImapMailboxConnector.SignInWithEncodingsAsync(BOTH_ENCODINGS, mayTryOtherEncoding: true, server.SignInAsync, server.ReconnectAsync, CancellationToken.None); + + using (Assert.EnterMultipleScope()) + { + Assert.That(accepted, Is.EqualTo(MailboxPasswordEncoding.WINDOWS_1252)); + Assert.That(server.Attempts, Is.EqualTo(BOTH_ENCODINGS)); + Assert.That(server.Reconnects, Is.EqualTo(1), "Some servers hang up after a refused sign-in."); + } + } + + [Test] + public async Task AConnectionTestStopsOnceEveryEncodingWasRefused() + { + var server = new SignInServer(accepted: null); + var exception = await SignInExpectingFailureAsync(server, BOTH_ENCODINGS, mayTryOtherEncoding: true); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.AUTHENTICATION_FAILED)); + Assert.That(server.Attempts, Is.EqualTo(BOTH_ENCODINGS)); + Assert.That(server.Reconnects, Is.EqualTo(1)); + } + } + + [Test] + public async Task AConnectionTestWithASingleEncodingSignsInOnce() + { + // GetSignInEncodings offers one encoding for ASCII, where every encoding sends the same bytes: + var server = new SignInServer(accepted: null); + var exception = await SignInExpectingFailureAsync(server, [MailboxPasswordEncoding.UTF8], mayTryOtherEncoding: true); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.AUTHENTICATION_FAILED)); + Assert.That(server.Attempts, Has.Count.EqualTo(1)); + Assert.That(server.Reconnects, Is.Zero); + } + } + + [Test] + public async Task OnlyARefusedSignInLeadsToTheOtherEncoding() + { + var server = new SignInServer(accepted: MailboxPasswordEncoding.WINDOWS_1252, failure: new IOException("The connection was reset.")); + var exception = await SignInExpectingFailureAsync(server, BOTH_ENCODINGS, mayTryOtherEncoding: true); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.NETWORK_UNAVAILABLE)); + Assert.That(server.Attempts, Has.Count.EqualTo(1)); + } + } + + [Test] + public async Task AFailedReconnectEndsTheSignIn() + { + var server = new SignInServer(accepted: MailboxPasswordEncoding.WINDOWS_1252, reconnectFailure: new MailboxConnectionException(MailboxConnectionFailure.NETWORK_UNAVAILABLE, "The server is gone.")); + var exception = await SignInExpectingFailureAsync(server, BOTH_ENCODINGS, mayTryOtherEncoding: true); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.NETWORK_UNAVAILABLE)); + Assert.That(server.Attempts, Has.Count.EqualTo(1)); + } + } + + [Test] + public async Task WithoutAnEncodingNothingIsSent() + { + // No encoding has every character, e.g., of a password with a lone surrogate: + var server = new SignInServer(accepted: MailboxPasswordEncoding.UTF8); + var exception = await SignInExpectingFailureAsync(server, [], mayTryOtherEncoding: true); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.INVALID_SETTINGS)); + Assert.That(server.Attempts, Is.Empty); + } + } + + private static async Task SignInExpectingFailureAsync(SignInServer server, MailboxPasswordEncoding[] encodings, bool mayTryOtherEncoding) => + await Assert.ThrowsAsync(() => ImapMailboxConnector.SignInWithEncodingsAsync(encodings, mayTryOtherEncoding, server.SignInAsync, server.ReconnectAsync, CancellationToken.None)); + + /// + /// Stands in for an IMAP server: accepts a sign-in in one encoding only, and counts every attempt. + /// + /// The encoding the server accepts, or null for a wrong password. + /// What every sign-in throws instead of an answer, e.g., a lost connection. + /// What connecting again throws. + private sealed class SignInServer(MailboxPasswordEncoding? accepted, Exception? failure = null, Exception? reconnectFailure = null) + { + public List Attempts { get; } = []; + + public int Reconnects { get; private set; } + + public async Task SignInAsync(MailboxPasswordEncoding encoding) + { + await Task.Yield(); + this.Attempts.Add(encoding); + if (failure is not null) + throw failure; + + if (encoding != accepted) + throw new AuthenticationException("The server rejected the credentials."); + } + + public async Task ReconnectAsync() + { + await Task.Yield(); + this.Reconnects++; + if (reconnectFailure is not null) + throw reconnectFailure; + } + } + [TestCase("Projects", '/', ExpectedResult = true)] [TestCase("Projekte 2026", '.', ExpectedResult = true)] [TestCase("Ablage/Alt", '.', ExpectedResult = true)] From 15548b812b970e5deee0f7b4d06fad4b4b0d878c Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 09:34:05 +0100 Subject: [PATCH 05/15] Removed the automatic second sign-in of mailboxes in another encoding --- .../Dialogs/DataSourceMailboxDialog.razor.cs | 28 ++- .../Tools/Mail/ImapMailboxConnector.cs | 153 +++++---------- .../Tools/Mail/MailboxConnectionFailure.cs | 5 + .../MailboxConnectionFailureExtensions.cs | 1 + .../Tools/Services/Indexing/MailboxIndexer.cs | 2 +- .../Tools/Mail/ImapMailboxConnectorTests.cs | 178 +++--------------- 6 files changed, 94 insertions(+), 273 deletions(-) diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index f77112736..8529eecc9 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -20,15 +20,13 @@ namespace AIStudio.Dialogs; /// Adds or edits a mailbox. /// /// -/// Every connection test is one sign-in, started by the user, and a second one only when the username -/// or the password holds a character beyond ASCII and the server refused the first encoding, cf. -/// ImapMailboxConnector.GetSignInEncodings. The first one is the encoding a configuration plugin sets -/// for the mail server, if any, and the one stored for the mailbox otherwise. The encoding the server -/// accepted is kept and stored along with the mailbox. The outcome of a test only touches the recorded sign-in failure of the mailbox -/// when the test used the settings and the password stored for it: a failure with a password the user -/// is still typing says nothing about the stored one, and neither does a success. A success in -/// another encoding clears the failure only once the mailbox is saved with it, since the -/// synchronization would sign in with the stored encoding until then. +/// Every connection test is exactly one sign-in, started by the user, in the encoding a configuration +/// plugin sets for the mail server, if any, and in the one stored for the mailbox otherwise. The +/// encoding of a successful test is stored along with the mailbox. The outcome of a test only touches +/// the recorded sign-in failure of the mailbox when the test used the settings and the password stored +/// for it: a failure with a password the user is still typing says nothing about the stored one, and +/// neither does a success. A success in another encoding clears the failure only once the mailbox is +/// saved with it, since the synchronization would sign in with the stored encoding until then. /// public partial class DataSourceMailboxDialog : MSGComponentBase { @@ -519,17 +517,15 @@ private async Task TestConnection() try { - // - // The organization knows which encoding its mail server expects, so the test tries that - // one first, and the other one only when the server refuses it: - // + // The organization knows which encoding its mail server expects: var mailbox = this.CreateDataSource(); if (this.GetOrganizationPasswordEncoding(mailbox.Host) is { } organizationPasswordEncoding) mailbox = mailbox with { PasswordEncoding = organizationPasswordEncoding }; using var timeout = new CancellationTokenSource(CONNECTION_TEST_TIMEOUT); await using var connector = new ImapMailboxConnector(); - this.dataPasswordEncoding = await connector.ConnectAsync(mailbox, settings.Password, MailServerPolicy.Read(this.SettingsManager), mayTryOtherEncoding: true, timeout.Token); + await connector.ConnectAsync(mailbox, settings.Password, MailServerPolicy.Read(this.SettingsManager), timeout.Token); + this.dataPasswordEncoding = mailbox.PasswordEncoding; this.serverFolders = await connector.GetFoldersAsync(timeout.Token); this.testFailure = null; this.Logger.LogInformation($"Tested the connection of the mailbox '{this.dataId}' successfully."); @@ -580,7 +576,7 @@ private async Task TestConnection() { using var timeout = new CancellationTokenSource(CONNECTION_TEST_TIMEOUT); await using var connector = new ImapMailboxConnector(); - await connector.ConnectAsync(this.CreateDataSource(), settings.Password, MailServerPolicy.Read(this.SettingsManager), mayTryOtherEncoding: false, timeout.Token); + await connector.ConnectAsync(this.CreateDataSource(), settings.Password, MailServerPolicy.Read(this.SettingsManager), timeout.Token); var createdFolder = await connector.CreateFolderAsync(parentFullName, name, timeout.Token); this.serverFolders = [..this.serverFolders, createdFolder]; @@ -701,7 +697,7 @@ private async Task Store() this.Logger.LogWarning($"Failed to delete the password of the mailbox '{this.dataId}' stored under its previous name: {deleteResponse.Issue}"); } - // A new password, or the encoding a connection test found, earns the next synchronization one attempt to sign in: + // A new password, or the encoding of a successful connection test, earns the next synchronization one attempt to sign in: var isNewPasswordEncoding = this.IsEditing && this.DataSource.PasswordEncoding != mailbox.PasswordEncoding; if (this.IsEditing && (isNewPassword || isNewPasswordEncoding)) { diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index a63bfead1..bc9cb77f5 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -20,9 +20,9 @@ namespace AIStudio.Tools.Mail; /// Every sign-in is exactly one attempt with the password. An IMAP client would otherwise try one /// mechanism after the other and the LOGIN command last, and a directory such as Active Directory /// counts each rejected attempt on its way to locking the account. For the same reason, nothing is -/// sent at all when the password is empty or a setting is unknown to this version. The one exception -/// is a connection test the user started: when the username or the password holds a character beyond -/// ASCII, such as an umlaut, it may try the other encoding once more, cf. GetSignInEncodings.

+/// sent at all when the password is empty, a setting is unknown to this version, or the encoding of +/// the mailbox cannot carry the username and the password, cf. TryPrepareSignIn. AI Studio never +/// switches to another encoding on its own: only the user chooses another one.

/// Before signing in, the caller has to make sure that no failed sign-in is on record for this /// mailbox. Whatever fails arrives as MailboxConnectionException with its failure code, and nothing /// here writes to the log: the answers of a server may name the user, so the caller logs the @@ -115,73 +115,42 @@ static ImapMailboxConnector() /// The mailbox to connect to. /// The password, as stored in the OS keyring or just typed in. /// Which mail servers the organization allows. Every connection passes here, so this is where a server it does not allow is refused. - /// Whether a refused sign-in may be tried once more in the other encoding, cf. GetSignInEncodings. Only for a connection test the user started. /// The cancellation token. - /// The encoding the server accepted the username and the password in. /// The connection or the sign-in failed. - public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, bool mayTryOtherEncoding, CancellationToken token) + public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, CancellationToken token) { - if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || mailbox.PasswordEncoding is MailboxPasswordEncoding.UNKNOWN || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) + if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || mailbox.PasswordEncoding.TextEncoding is not { } textEncoding || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The mailbox settings are incomplete, or this version of AI Studio does not know them."); if (!policy.IsAllowed(mailbox.Host)) throw new MailboxConnectionException(MailboxConnectionFailure.SERVER_NOT_ALLOWED, "The organization allows only its own mail servers, and the server of this mailbox is none of them."); this.client.ServerCertificateValidationCallback = ExternalHttpClientTimeout.CreateServerCertificateValidationCallback(idnHost, ExternalHttpTrustPolicy.ALLOW_CUSTOM_ROOTS_WHEN_HOST_WHITELISTED); - await this.ConnectToServerAsync(idnHost, mailbox.Port, socketOptions, token); + try + { + await this.client.ConnectAsync(idnHost, mailbox.Port, socketOptions, token); + } + catch (NotSupportedException e) + { + // Thrown when the server does not offer STARTTLS. The connection never goes on without it: + throw new MailboxConnectionException(MailboxConnectionFailure.TLS_FAILED, "The IMAP server does not offer STARTTLS.", e); + } + catch (Exception e) when (Classify(e, token) is { } failure) + { + throw new MailboxConnectionException(failure, $"Connecting to the IMAP server failed: {failure}.", e); + } var offersPlain = this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM); - var encodings = GetSignInEncodings(mailbox.PasswordEncoding, mailbox.Username, password, offersPlain); - return await SignInWithEncodingsAsync( - encodings, - mayTryOtherEncoding, - encoding => this.SignInAsync(mailbox.Username, password, encoding, offersPlain, token), - async () => - { - // Some servers hang up after a refused sign-in: - if (!this.client.IsConnected) - await this.ConnectToServerAsync(idnHost, mailbox.Port, socketOptions, token); - }, - token); - } + if (!TryPrepareSignIn(mailbox.PasswordEncoding, mailbox.Username, password, offersPlain, out var preparedUsername, out var preparedPassword)) + throw new MailboxConnectionException(MailboxConnectionFailure.UNSUITABLE_ENCODING, "The encoding of the mailbox cannot carry the username and the password to this IMAP server."); - /// - /// Signs in with the encodings GetSignInEncodings offered, at most one attempt each. - /// - /// - /// Every attempt the server refuses counts on the way to locking the account, so this is where - /// their number is decided: one, unless the caller may try the other encoding, and then one per - /// encoding. Only a refused sign-in leads to the next attempt; any other failure ends the sign-in. - /// ImapMailboxConnectorTests counts the attempts. - /// - /// The encodings to try, the best first; at least one. - /// Whether a refused sign-in may be tried once more in the next encoding. - /// Signs in once, in the given encoding. - /// Connects again before the next attempt, when the server hung up. - /// The cancellation token. - /// The encoding the server accepted. - /// Every attempt failed, or another failure ended the sign-in. - internal static async Task SignInWithEncodingsAsync(IReadOnlyList encodings, bool mayTryOtherEncoding, Func signInAsync, Func reconnectAsync, CancellationToken token) - { - var attempts = mayTryOtherEncoding ? encodings.Count : Math.Min(encodings.Count, 1); - if (attempts == 0) - throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "No encoding has every character of the username and the password."); - - for (var attempt = 0; ; attempt++) + try { - try - { - await signInAsync(encodings[attempt]); - return encodings[attempt]; - } - catch (AuthenticationException) when (attempt + 1 < attempts) - { - await reconnectAsync(); - } - catch (Exception e) when (Classify(e, token) is { } failure) - { - throw new MailboxConnectionException(failure, $"Signing in to the IMAP server failed: {failure}.", e); - } + await this.SignInAsync(textEncoding, preparedUsername, preparedPassword, offersPlain, token); + } + catch (Exception e) when (Classify(e, token) is { } failure) + { + throw new MailboxConnectionException(failure, $"Signing in to the IMAP server failed: {failure}.", e); } } @@ -525,68 +494,40 @@ private static async Task FetchAttachmentPieceAsync(IMailFolder folder, } /// - /// The encodings a sign-in may use, the best first. + /// Prepares the username and the password for one sign-in in the encoding of the mailbox. /// /// - /// The stored encoding comes first, the other one second. An encoding is left out when it lacks - /// a character of the username or the password, e.g., Windows-1252 has no ẞ. Windows-1252 is - /// left out as well when the server does not offer PLAIN: MailKit sends the LOGIN command in - /// UTF-8, whatever encoding it is handed. When both are ASCII, every encoding sends the same - /// bytes, so only the first one is left: a second attempt would only fail the same way. + /// A sign-in in bytes which are not the password counts as a failed attempt, just like a wrong + /// password. So nothing may be sent when the encoding cannot carry the username and the password: + /// when it lacks one of their characters, e.g., Windows-1252 has no ẞ, and when the server does not + /// offer PLAIN and the encoding is not UTF-8, since MailKit sends the LOGIN command in UTF-8, + /// whatever encoding it is handed. Text in ASCII has the same bytes in every encoding this + /// version knows, so it goes through the LOGIN command as well. /// - /// The encoding stored for the mailbox. + /// The encoding of the mailbox. /// The username. /// The password. /// Whether the server offers the SASL mechanism PLAIN. - /// The encodings, possibly none at all. - internal static IReadOnlyList GetSignInEncodings(MailboxPasswordEncoding storedEncoding, string username, string password, bool offersPlain) + /// The username to sign in with. + /// The password to sign in with. + /// Whether the sign-in may go ahead. + internal static bool TryPrepareSignIn(MailboxPasswordEncoding encoding, string username, string password, bool offersPlain, out string preparedUsername, out string preparedPassword) { - MailboxPasswordEncoding[] candidates = storedEncoding is MailboxPasswordEncoding.WINDOWS_1252 - ? [MailboxPasswordEncoding.WINDOWS_1252, MailboxPasswordEncoding.UTF8] - : [MailboxPasswordEncoding.UTF8, MailboxPasswordEncoding.WINDOWS_1252]; - - var usable = candidates - .Where(candidate => candidate is MailboxPasswordEncoding.UTF8 || offersPlain) - .Where(candidate => candidate.TryPrepare(username, out _) && candidate.TryPrepare(password, out _)) - .ToList(); - - return Ascii.IsValid(username) && Ascii.IsValid(password) ? usable.Take(1).ToList() : usable; - } + preparedPassword = password; + if (!encoding.TryPrepare(username, out preparedUsername) || !encoding.TryPrepare(password, out preparedPassword)) + return false; - private async Task ConnectToServerAsync(string idnHost, int port, SecureSocketOptions socketOptions, CancellationToken token) - { - try - { - await this.client.ConnectAsync(idnHost, port, socketOptions, token); - } - catch (NotSupportedException e) - { - // Thrown when the server does not offer STARTTLS. The connection never goes on without it: - throw new MailboxConnectionException(MailboxConnectionFailure.TLS_FAILED, "The IMAP server does not offer STARTTLS.", e); - } - catch (Exception e) when (Classify(e, token) is { } failure) - { - throw new MailboxConnectionException(failure, $"Connecting to the IMAP server failed: {failure}.", e); - } + return offersPlain || encoding is MailboxPasswordEncoding.UTF8 || (Ascii.IsValid(preparedUsername) && Ascii.IsValid(preparedPassword)); } /// - /// Signs in once, in the given encoding. + /// Signs in once, with a username and a password which TryPrepareSignIn prepared. /// - /// - /// Only for an encoding which GetSignInEncodings offered for this username, password, and server: - /// it made sure that the encoding has every character of both, and that the server offers PLAIN - /// unless the encoding is UTF-8. Should another encoding arrive here anyway, nothing is sent, - /// since the bytes would not be the password and the attempt would count as a failed sign-in. - /// - private async Task SignInAsync(string username, string password, MailboxPasswordEncoding encoding, bool offersPlain, CancellationToken token) + private async Task SignInAsync(Encoding textEncoding, string username, string password, bool offersPlain, CancellationToken token) { - if (encoding.TextEncoding is not { } textEncoding || !encoding.TryPrepare(username, out var preparedUsername) || !encoding.TryPrepare(password, out var preparedPassword) || (!offersPlain && encoding is not MailboxPasswordEncoding.UTF8)) - throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The encoding cannot carry the username and the password to this IMAP server."); - if (offersPlain) { - await this.client.AuthenticateAsync(new SaslMechanismPlain(textEncoding, preparedUsername, preparedPassword), token); + await this.client.AuthenticateAsync(new SaslMechanismPlain(textEncoding, username, password), token); return; } @@ -595,10 +536,10 @@ private async Task SignInAsync(string username, string password, MailboxPassword // // With no mechanism left to try, the client signs in with the LOGIN command alone, always in - // UTF-8, cf. GetSignInEncodings: + // UTF-8, cf. TryPrepareSignIn: // this.client.AuthenticationMechanisms.Clear(); - await this.client.AuthenticateAsync(preparedUsername, preparedPassword, token); + await this.client.AuthenticateAsync(username, password, token); } private static bool TryGetSocketOptions(MailboxTransportSecurity transportSecurity, out SecureSocketOptions socketOptions) diff --git a/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailure.cs b/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailure.cs index 96e6a9638..3a3454f13 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailure.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailure.cs @@ -34,4 +34,9 @@ public enum MailboxConnectionFailure /// The organization allows only its own mail servers, and the server of the mailbox is none of them. Nothing was sent to the server. /// SERVER_NOT_ALLOWED, + + /// + /// The encoding of the mailbox cannot carry the username or the password to the server: it lacks one of their characters, or the server takes no other encoding than UTF-8 for them. Nothing was sent to the server. + /// + UNSUITABLE_ENCODING, } \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailureExtensions.cs b/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailureExtensions.cs index 022866a12..0742342bf 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailureExtensions.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailureExtensions.cs @@ -21,6 +21,7 @@ public static class MailboxConnectionFailureExtensions MailboxConnectionFailure.SERVER_ERROR => TA("The server reported an error. Please try again later."), MailboxConnectionFailure.INVALID_SETTINGS => TB("The settings of this mailbox are incomplete, or they were made by a newer version of AI Studio."), MailboxConnectionFailure.SERVER_NOT_ALLOWED => TA("Your organization allows mailboxes only on its own mail servers, and this server is none of them. AI Studio does not connect to it, and the AI does not read this mailbox."), + MailboxConnectionFailure.UNSUITABLE_ENCODING => TA("The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked."), _ => TB("The connection to the server failed for an unknown reason."), }; diff --git a/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.cs b/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.cs index d1240ab34..beecb1a7d 100644 --- a/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.cs +++ b/app/MindWork AI Studio/Tools/Services/Indexing/MailboxIndexer.cs @@ -153,7 +153,7 @@ public async Task ProcessAsync(IndexedRunContext context, Dat await using var connector = new ImapMailboxConnector(); try { - await connector.ConnectAsync(mailbox, password, policy, mayTryOtherEncoding: false, token); + await connector.ConnectAsync(mailbox, password, policy, token); } catch (MailboxConnectionException e) { diff --git a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs index fc9e8748e..1d2924fec 100644 --- a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs +++ b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs @@ -36,8 +36,6 @@ public sealed class ImapMailboxConnectorTests Username = "someone@example.org", }; - private static readonly MailboxPasswordEncoding[] BOTH_ENCODINGS = [MailboxPasswordEncoding.UTF8, MailboxPasswordEncoding.WINDOWS_1252]; - private static IEnumerable ExceptionsWithTheirFailure() { yield return Case(new AuthenticationException("The server rejected the credentials."), MailboxConnectionFailure.AUTHENTICATION_FAILED); @@ -98,7 +96,7 @@ public async Task InvalidSettingsNeverReachTheServer(DataSourceMailbox mailbox, // failure instead of this one. // await using var connector = new ImapMailboxConnector(); - var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(mailbox, password, MailServerPolicy.ANY_SERVER, mayTryOtherEncoding: true, CancellationToken.None)); + var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(mailbox, password, MailServerPolicy.ANY_SERVER, CancellationToken.None)); Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.INVALID_SETTINGS)); } @@ -111,176 +109,56 @@ public async Task AServerTheOrganizationDoesNotAllowIsNeverContacted() // await using var connector = new ImapMailboxConnector(); var policy = new MailServerPolicy(true, ["imap.intra.example.org"]); - var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(MAILBOX, PASSWORD, policy, mayTryOtherEncoding: true, CancellationToken.None)); + var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(MAILBOX, PASSWORD, policy, CancellationToken.None)); Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.SERVER_NOT_ALLOWED)); } - private static IEnumerable SignInEncodings() + private static IEnumerable SignInPreparations() { const MailboxPasswordEncoding UTF8 = MailboxPasswordEncoding.UTF8; const MailboxPasswordEncoding WINDOWS_1252 = MailboxPasswordEncoding.WINDOWS_1252; - // ASCII sends the same bytes in every encoding, so a second attempt would fail the same way: - yield return Case("ASCII", UTF8, "someone", "Sommer-2026!", true, [UTF8]); - yield return Case("ASCII, Windows-1252 stored", WINDOWS_1252, "someone", "Sommer-2026!", true, [WINDOWS_1252]); - - yield return Case("umlaut in the password", UTF8, "someone", "Grüße-2026", true, [UTF8, WINDOWS_1252]); - yield return Case("umlaut, Windows-1252 stored", WINDOWS_1252, "someone", "Grüße-2026", true, [WINDOWS_1252, UTF8]); - yield return Case("umlaut in the username", UTF8, @"FIRMA\müller", "Sommer-2026!", true, [UTF8, WINDOWS_1252]); - yield return Case("section sign", UTF8, "someone", "Abs§2", true, [UTF8, WINDOWS_1252]); - yield return Case("euro sign", UTF8, "someone", "100€", true, [UTF8, WINDOWS_1252]); + yield return Case("ASCII", UTF8, "someone", "Sommer-2026!", true, true); + yield return Case("umlaut in the password", UTF8, "someone", "Grüße-2026", true, true); + yield return Case("umlaut in the username", WINDOWS_1252, @"FIRMA\müller", "Sommer-2026!", true, true); + yield return Case("Windows-1252 with umlaut and euro sign", WINDOWS_1252, "someone", "Grüße-100€", true, true); + yield return Case("UTF-8 with Turkish and Japanese", UTF8, "kişi", "şifre-日本", true, true); - // Windows-1252 has no capital sharp s: - yield return Case("capital sharp s", UTF8, "someone", "STRAẞE", true, [UTF8]); - yield return Case("capital sharp s, Windows-1252 stored", WINDOWS_1252, "someone", "STRAẞE", true, [UTF8]); + // Windows-1252 lacks the capital sharp s and the Turkish s with cedilla, and AI Studio never switches to UTF-8 on its own: + yield return Case("capital sharp s in Windows-1252", WINDOWS_1252, "someone", "STRAẞE", true, false); + yield return Case("Turkish s in Windows-1252", WINDOWS_1252, "kişi", "Sommer-2026!", true, false); // Without PLAIN, MailKit sends the LOGIN command in UTF-8, whatever it is handed: - yield return Case("umlaut without PLAIN", UTF8, "someone", "Grüße-2026", false, [UTF8]); - yield return Case("umlaut without PLAIN, Windows-1252 stored", WINDOWS_1252, "someone", "Grüße-2026", false, [UTF8]); + yield return Case("umlaut without PLAIN in UTF-8", UTF8, "someone", "Grüße-2026", false, true); + yield return Case("umlaut without PLAIN in Windows-1252", WINDOWS_1252, "someone", "Grüße-2026", false, false); + yield return Case("ASCII without PLAIN in Windows-1252", WINDOWS_1252, "someone", "Sommer-2026!", false, true); // No encoding has a lone surrogate: - yield return Case("lone surrogate", UTF8, "someone", "abc\uD800", true, []); - yield break; - - static TestCaseData Case(string name, MailboxPasswordEncoding storedEncoding, string username, string password, bool offersPlain, MailboxPasswordEncoding[] expected) => new TestCaseData(storedEncoding, username, password, offersPlain, expected).SetArgDisplayNames(name); - } - - [TestCaseSource(nameof(SignInEncodings))] - public void ASignInUsesOnlyTheEncodingsWhichMakeADifference(MailboxPasswordEncoding storedEncoding, string username, string password, bool offersPlain, MailboxPasswordEncoding[] expected) - { - Assert.That(ImapMailboxConnector.GetSignInEncodings(storedEncoding, username, password, offersPlain), Is.EqualTo(expected)); - } - - [Test] - public async Task ASynchronizationSignsInOnceInTheStoredEncoding() - { - // The server would accept the other encoding, but only a connection test may find that out: - var server = new SignInServer(accepted: MailboxPasswordEncoding.WINDOWS_1252); - var exception = await SignInExpectingFailureAsync(server, BOTH_ENCODINGS, mayTryOtherEncoding: false); - - using (Assert.EnterMultipleScope()) - { - Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.AUTHENTICATION_FAILED)); - Assert.That(server.Attempts, Is.EqualTo(new[] { MailboxPasswordEncoding.UTF8 })); - Assert.That(server.Reconnects, Is.Zero); - } - } - - [Test] - public async Task AConnectionTestTriesTheOtherEncodingOnce() - { - var server = new SignInServer(accepted: MailboxPasswordEncoding.WINDOWS_1252); - var accepted = await ImapMailboxConnector.SignInWithEncodingsAsync(BOTH_ENCODINGS, mayTryOtherEncoding: true, server.SignInAsync, server.ReconnectAsync, CancellationToken.None); - - using (Assert.EnterMultipleScope()) - { - Assert.That(accepted, Is.EqualTo(MailboxPasswordEncoding.WINDOWS_1252)); - Assert.That(server.Attempts, Is.EqualTo(BOTH_ENCODINGS)); - Assert.That(server.Reconnects, Is.EqualTo(1), "Some servers hang up after a refused sign-in."); - } - } - - [Test] - public async Task AConnectionTestStopsOnceEveryEncodingWasRefused() - { - var server = new SignInServer(accepted: null); - var exception = await SignInExpectingFailureAsync(server, BOTH_ENCODINGS, mayTryOtherEncoding: true); - - using (Assert.EnterMultipleScope()) - { - Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.AUTHENTICATION_FAILED)); - Assert.That(server.Attempts, Is.EqualTo(BOTH_ENCODINGS)); - Assert.That(server.Reconnects, Is.EqualTo(1)); - } - } + yield return Case("lone surrogate", UTF8, "someone", "abc\uD800", true, false); - [Test] - public async Task AConnectionTestWithASingleEncodingSignsInOnce() - { - // GetSignInEncodings offers one encoding for ASCII, where every encoding sends the same bytes: - var server = new SignInServer(accepted: null); - var exception = await SignInExpectingFailureAsync(server, [MailboxPasswordEncoding.UTF8], mayTryOtherEncoding: true); - - using (Assert.EnterMultipleScope()) - { - Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.AUTHENTICATION_FAILED)); - Assert.That(server.Attempts, Has.Count.EqualTo(1)); - Assert.That(server.Reconnects, Is.Zero); - } - } - - [Test] - public async Task OnlyARefusedSignInLeadsToTheOtherEncoding() - { - var server = new SignInServer(accepted: MailboxPasswordEncoding.WINDOWS_1252, failure: new IOException("The connection was reset.")); - var exception = await SignInExpectingFailureAsync(server, BOTH_ENCODINGS, mayTryOtherEncoding: true); + // An encoding this version does not know encodes nothing: + yield return Case("unknown encoding", MailboxPasswordEncoding.UNKNOWN, "someone", "Sommer-2026!", true, false); + yield break; - using (Assert.EnterMultipleScope()) - { - Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.NETWORK_UNAVAILABLE)); - Assert.That(server.Attempts, Has.Count.EqualTo(1)); - } + static TestCaseData Case(string name, MailboxPasswordEncoding encoding, string username, string password, bool offersPlain, bool expected) => new TestCaseData(encoding, username, password, offersPlain).Returns(expected).SetArgDisplayNames(name); } - [Test] - public async Task AFailedReconnectEndsTheSignIn() + [TestCaseSource(nameof(SignInPreparations))] + public bool ASignInGoesAheadOnlyWhenTheEncodingCarriesTheUsernameAndThePassword(MailboxPasswordEncoding encoding, string username, string password, bool offersPlain) { - var server = new SignInServer(accepted: MailboxPasswordEncoding.WINDOWS_1252, reconnectFailure: new MailboxConnectionException(MailboxConnectionFailure.NETWORK_UNAVAILABLE, "The server is gone.")); - var exception = await SignInExpectingFailureAsync(server, BOTH_ENCODINGS, mayTryOtherEncoding: true); - - using (Assert.EnterMultipleScope()) - { - Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.NETWORK_UNAVAILABLE)); - Assert.That(server.Attempts, Has.Count.EqualTo(1)); - } + return ImapMailboxConnector.TryPrepareSignIn(encoding, username, password, offersPlain, out _, out _); } [Test] - public async Task WithoutAnEncodingNothingIsSent() + public void APreparedSignInComposesADecomposedUmlautForWindows1252() { - // No encoding has every character, e.g., of a password with a lone surrogate: - var server = new SignInServer(accepted: MailboxPasswordEncoding.UTF8); - var exception = await SignInExpectingFailureAsync(server, [], mayTryOtherEncoding: true); - + // An a followed by a combining diaeresis, as some password managers deliver an ä: + const string DECOMPOSED = "Ka\u0308se"; using (Assert.EnterMultipleScope()) { - Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.INVALID_SETTINGS)); - Assert.That(server.Attempts, Is.Empty); - } - } - - private static async Task SignInExpectingFailureAsync(SignInServer server, MailboxPasswordEncoding[] encodings, bool mayTryOtherEncoding) => - await Assert.ThrowsAsync(() => ImapMailboxConnector.SignInWithEncodingsAsync(encodings, mayTryOtherEncoding, server.SignInAsync, server.ReconnectAsync, CancellationToken.None)); - - /// - /// Stands in for an IMAP server: accepts a sign-in in one encoding only, and counts every attempt. - /// - /// The encoding the server accepts, or null for a wrong password. - /// What every sign-in throws instead of an answer, e.g., a lost connection. - /// What connecting again throws. - private sealed class SignInServer(MailboxPasswordEncoding? accepted, Exception? failure = null, Exception? reconnectFailure = null) - { - public List Attempts { get; } = []; - - public int Reconnects { get; private set; } - - public async Task SignInAsync(MailboxPasswordEncoding encoding) - { - await Task.Yield(); - this.Attempts.Add(encoding); - if (failure is not null) - throw failure; - - if (encoding != accepted) - throw new AuthenticationException("The server rejected the credentials."); - } - - public async Task ReconnectAsync() - { - await Task.Yield(); - this.Reconnects++; - if (reconnectFailure is not null) - throw reconnectFailure; + Assert.That(ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncoding.WINDOWS_1252, "müller", DECOMPOSED, true, out var username, out var password), Is.True); + Assert.That(username, Is.EqualTo("müller")); + Assert.That(password, Is.EqualTo("Käse")); } } From 2b46a3c2e17cb4bc518127913f51ef6cf370df86 Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 09:40:32 +0100 Subject: [PATCH 06/15] Improved the password encoding of mailboxes to every ASCII-compatible encoding --- .../Dialogs/DataSourceMailboxDialog.razor.cs | 4 +- .../Plugins/configuration/plugin.lua | 18 +- .../Settings/DataModel/DataMailboxProvider.cs | 20 +- .../Settings/DataModel/DataSourceMailbox.cs | 10 +- .../DataModel/MailboxPasswordEncoding.cs | 33 --- .../MailboxPasswordEncodingExtensions.cs | 73 ------- .../Tools/Mail/ImapMailboxConnector.cs | 16 +- .../Tools/Mail/MailboxPasswordEncodings.cs | 135 ++++++++++++ .../MailboxProviderConfigurationTests.cs | 11 +- app/Tests/Settings/MailboxSettingsTests.cs | 21 +- .../Tools/Mail/ImapMailboxConnectorTests.cs | 20 +- .../Mail/MailboxPasswordEncodingTests.cs | 134 ------------ .../Mail/MailboxPasswordEncodingsTests.cs | 199 ++++++++++++++++++ 13 files changed, 403 insertions(+), 291 deletions(-) delete mode 100644 app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncoding.cs delete mode 100644 app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncodingExtensions.cs create mode 100644 app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs delete mode 100644 app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs create mode 100644 app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index 8529eecc9..29db3af37 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -91,7 +91,7 @@ public partial class DataSourceMailboxDialog : MSGComponentBase private MailboxTransportSecurity dataTransportSecurity = MailboxTransportSecurity.SSL_ON_CONNECT; private string dataUsername = string.Empty; private string dataPassword = string.Empty; - private MailboxPasswordEncoding dataPasswordEncoding = MailboxPasswordEncoding.UTF8; + private string dataPasswordEncoding = MailboxPasswordEncodings.DEFAULT; private string dataRootFolder = string.Empty; private bool dataIncludeSentAndDrafts = true; private MailboxMaxAge dataMaxAge = MailboxMaxAge.LAST_12_MONTHS; @@ -561,7 +561,7 @@ private async Task TestConnection() ///
/// The host the connection goes to. /// The encoding, or null when no mail server of the organization on this host sets one. - private MailboxPasswordEncoding? GetOrganizationPasswordEncoding(string host) => this.organizationProviders + private string? GetOrganizationPasswordEncoding(string host) => this.organizationProviders .FirstOrDefault(provider => provider.PasswordEncoding is not null && MailServerHosts.AreSame(provider.Host, host))? .PasswordEncoding; diff --git a/app/MindWork AI Studio/Plugins/configuration/plugin.lua b/app/MindWork AI Studio/Plugins/configuration/plugin.lua index 2e0eece83..3c2e0d407 100644 --- a/app/MindWork AI Studio/Plugins/configuration/plugin.lua +++ b/app/MindWork AI Studio/Plugins/configuration/plugin.lua @@ -351,13 +351,15 @@ CONFIG["DATA_SOURCES"] = {} -- UsernameHint Optional text telling users what to enter as their username. -- HelpUrl Optional http or https address of your instructions, e.g., on how to -- enable IMAP for a mailbox. --- PasswordEncoding Optional encoding your mail server expects for usernames and passwords --- with characters beyond ASCII, such as German umlauts: UTF8, which most --- servers expect, or WINDOWS_1252, which Microsoft Exchange expects. The --- connection test in the mailbox dialog tries this encoding first and the --- other one only when the server refuses it. Without this field, a new --- mailbox starts with UTF8, and on an Exchange server, every user whose --- password holds such a character spends one failed sign-in on it. +-- PasswordEncoding Optional name of the encoding your mail server expects for usernames and +-- passwords with characters beyond ASCII, such as umlauts, accents, Turkish, +-- Cyrillic, or Asian characters. Most servers expect utf-8, the default. +-- Depending on its configuration, a server may expect another one, e.g., +-- Microsoft Exchange the code page of its Windows system: windows-1252 in +-- Western Europe, windows-1250 in Central Europe, windows-1251 for Cyrillic, +-- windows-1254 in Turkey, or shift_jis in Japan. Any encoding .NET knows by +-- name works, as long as it keeps ASCII as it is; utf-16 does not. The +-- connection test in the mailbox dialog signs in with this encoding. -- An entry with an invalid field is left out as a whole, and the log names the field. -- To allow mailboxes on these mail servers only, see DataMailboxes.AllowOnlyOrganizationMailServers. CONFIG["MAILBOX_PROVIDERS"] = {} @@ -371,7 +373,7 @@ CONFIG["MAILBOX_PROVIDERS"] = {} -- ["Port"] = 993, -- ["UsernameHint"] = "Your account as DOMAIN\\username", -- ["HelpUrl"] = "https://intranet.example.org/mail/imap", --- ["PasswordEncoding"] = "WINDOWS_1252", +-- ["PasswordEncoding"] = "windows-1252", -- } CONFIG["SETTINGS"] = {} diff --git a/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs b/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs index 4e6a75e7f..5bc37d189 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs @@ -59,15 +59,15 @@ public sealed record DataMailboxProvider : ILivePluginContent public string HelpUrl { get; private init; } = string.Empty; /// - /// The encoding the mail server expects for a username or a password with characters beyond - /// ASCII, such as umlauts. Null when the organization did not say. + /// The name of the encoding the mail server expects for a username or a password with characters + /// beyond ASCII, e.g., "windows-1252", cf. MailboxPasswordEncodings. Null when the organization did not say. /// /// - /// The connection test in the mailbox dialog tries it first and the other encoding only when the - /// server refuses it, so that users of a server such as Microsoft Exchange, which expects - /// Windows-1252, spend no failed sign-in on UTF-8. + /// Depending on its configuration, a mail server may expect another encoding than UTF-8, e.g., + /// Microsoft Exchange the code page of its Windows system. The organization knows which one, so + /// its users spend no failed sign-in on finding out. /// - public MailboxPasswordEncoding? PasswordEncoding { get; private init; } + public string? PasswordEncoding { get; private init; } /// /// Reads a mail server from an entry of the table MAILBOX_PROVIDERS. @@ -142,16 +142,16 @@ public static bool TryParseConfiguration(int index, LuaTable table, Guid configP helpUrl = helpUri.OriginalString; } - MailboxPasswordEncoding? passwordEncoding = null; + string? passwordEncoding = null; if (table.TryGetValue("PasswordEncoding", out var passwordEncodingValue)) { - if (!passwordEncodingValue.TryRead(out var passwordEncodingText) || !MailboxPasswordEncoding.TryParseName(passwordEncodingText, out var readPasswordEncoding) || readPasswordEncoding is MailboxPasswordEncoding.UNKNOWN) + if (!passwordEncodingValue.TryRead(out var passwordEncodingText) || !MailboxPasswordEncodings.TryGet(passwordEncodingText, out var encoding)) { - logger.LogWarning("The configured mailbox provider {ProviderIndex} does not contain a valid PasswordEncoding field. Allowed values are UTF8 and WINDOWS_1252.", index); + logger.LogWarning("The configured mailbox provider {ProviderIndex} does not contain a valid PasswordEncoding field. It needs the name of an encoding which keeps ASCII as it is, such as utf-8, windows-1252, or shift_jis.", index); return false; } - passwordEncoding = readPasswordEncoding; + passwordEncoding = encoding.WebName; } provider = new DataMailboxProvider diff --git a/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs b/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs index 6bcfe284a..906fe90a3 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs @@ -1,6 +1,7 @@ using System.Text.Json.Serialization; using AIStudio.Provider; +using AIStudio.Tools.Mail; using AIStudio.Tools.Services; namespace AIStudio.Settings.DataModel; @@ -74,13 +75,16 @@ public DataSourceMailbox() public MailboxAuthMethod AuthMethod { get; set; } = MailboxAuthMethod.PASSWORD; /// - /// How the username and the password are encoded when signing in. + /// The name of the encoding in which the username and the password are sent when signing in, + /// e.g., "utf-8" or "windows-1252", cf. MailboxPasswordEncodings. /// /// /// A mailbox stored before this setting existed loads with UTF-8, which AI Studio always used - /// until then. The connection test finds out which one the server expects. + /// until then. A name this version does not know, e.g., one written by a newer version, keeps the + /// mailbox from signing in at all: bytes which may not be the password would count as a failed + /// sign-in, which can lock the account. /// - public MailboxPasswordEncoding PasswordEncoding { get; set; } = MailboxPasswordEncoding.UTF8; + public string PasswordEncoding { get; set; } = MailboxPasswordEncodings.DEFAULT; /// /// The username to sign in with, often the e-mail address. diff --git a/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncoding.cs b/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncoding.cs deleted file mode 100644 index 7735a0fd1..000000000 --- a/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncoding.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace AIStudio.Settings.DataModel; - -/// -/// How AI Studio encodes the username and the password when it signs in to an IMAP server. -/// -/// -/// The characters of ASCII come out the same in every member, but those beyond it do not, e.g., the -/// German umlauts, ß, §, or €. Most servers expect UTF-8. Others, Microsoft Exchange among them, -/// compare the bytes with the password of the Windows account and expect Windows-1252. -/// -public enum MailboxPasswordEncoding -{ - /// - /// An encoding this version of AI Studio does not know, e.g., one written by a newer version. AI Studio never signs in then. - /// - /// - /// It is the member with the underlying value 0 on purpose: when the settings file holds a value - /// TolerantEnumConverter cannot read, it falls back to that member. Falling back to an encoding - /// instead would sign in with bytes which may not be the password, and every such attempt counts - /// as a failed sign-in, which can lock the account. - /// - UNKNOWN = 0, - - /// - /// UTF-8, as the standard for signing in with a password demands (RFC 4616). - /// - UTF8, - - /// - /// Windows-1252, the Western European code page of Windows, which Latin-1 is a part of. - /// - WINDOWS_1252, -} \ No newline at end of file diff --git a/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncodingExtensions.cs b/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncodingExtensions.cs deleted file mode 100644 index 3c8e8cce3..000000000 --- a/app/MindWork AI Studio/Settings/DataModel/MailboxPasswordEncodingExtensions.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Text; - -namespace AIStudio.Settings.DataModel; - -public static class MailboxPasswordEncodingExtensions -{ - /// - /// UTF-8 which refuses what it cannot encode, such as a lone surrogate, instead of replacing it. - /// - private static readonly Encoding UTF8_STRICT = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); - - /// - /// Windows-1252 which refuses a character it lacks, such as ẞ, instead of sending a question mark. - /// - /// - /// .NET knows the code pages of Windows only once their provider is registered. - /// - private static readonly Lazy WINDOWS_1252_STRICT = new(() => - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - return Encoding.GetEncoding(1252, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); - }); - - extension(MailboxPasswordEncoding passwordEncoding) - { - /// - /// The encoding to hand to the IMAP client. - /// - /// The encoding, or null for one this version does not know. - public Encoding? TextEncoding => passwordEncoding switch - { - MailboxPasswordEncoding.UTF8 => UTF8_STRICT, - MailboxPasswordEncoding.WINDOWS_1252 => WINDOWS_1252_STRICT.Value, - - _ => null, - }; - - /// - /// Prepares a username or a password for this encoding. - /// - /// - /// For Windows-1252, the text is normalized first (NFC): an ä may arrive as an a followed by a - /// combining diaeresis, e.g., from a password manager, and only the composed ä exists in - /// Windows-1252. UTF-8 takes the text as it is, as it always did. - /// - /// The username or the password. - /// The text to sign in with. - /// Whether the encoding has every character of the text. - public bool TryPrepare(string text, out string prepared) - { - prepared = text; - if (passwordEncoding.TextEncoding is not { } encoding) - return false; - - try - { - if (passwordEncoding is MailboxPasswordEncoding.WINDOWS_1252) - prepared = text.Normalize(NormalizationForm.FormC); - - encoding.GetByteCount(prepared); - return true; - } - - // Thrown for a character the encoding lacks, and for a lone surrogate, which no encoding has. - // EncoderFallbackException is one of them: - catch (ArgumentException) - { - prepared = text; - return false; - } - } - } -} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index bc9cb77f5..a9450ffbc 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -119,7 +119,7 @@ static ImapMailboxConnector() /// The connection or the sign-in failed. public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, CancellationToken token) { - if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || mailbox.PasswordEncoding.TextEncoding is not { } textEncoding || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) + if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || !MailboxPasswordEncodings.TryGet(mailbox.PasswordEncoding, out var textEncoding) ||!MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The mailbox settings are incomplete, or this version of AI Studio does not know them."); if (!policy.IsAllowed(mailbox.Host)) @@ -141,7 +141,7 @@ public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailS } var offersPlain = this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM); - if (!TryPrepareSignIn(mailbox.PasswordEncoding, mailbox.Username, password, offersPlain, out var preparedUsername, out var preparedPassword)) + if (!TryPrepareSignIn(textEncoding, mailbox.Username, password, offersPlain, out var preparedUsername, out var preparedPassword)) throw new MailboxConnectionException(MailboxConnectionFailure.UNSUITABLE_ENCODING, "The encoding of the mailbox cannot carry the username and the password to this IMAP server."); try @@ -501,23 +501,23 @@ private static async Task FetchAttachmentPieceAsync(IMailFolder folder, /// password. So nothing may be sent when the encoding cannot carry the username and the password: /// when it lacks one of their characters, e.g., Windows-1252 has no ẞ, and when the server does not /// offer PLAIN and the encoding is not UTF-8, since MailKit sends the LOGIN command in UTF-8, - /// whatever encoding it is handed. Text in ASCII has the same bytes in every encoding this - /// version knows, so it goes through the LOGIN command as well. + /// whatever encoding it is handed. Text in ASCII has the same bytes in every encoding a mailbox + /// may use, cf. MailboxPasswordEncodings, so it goes through the LOGIN command as well. /// - /// The encoding of the mailbox. + /// The encoding of the mailbox, as MailboxPasswordEncodings.TryGet returns it. /// The username. /// The password. /// Whether the server offers the SASL mechanism PLAIN. /// The username to sign in with. /// The password to sign in with. /// Whether the sign-in may go ahead. - internal static bool TryPrepareSignIn(MailboxPasswordEncoding encoding, string username, string password, bool offersPlain, out string preparedUsername, out string preparedPassword) + internal static bool TryPrepareSignIn(Encoding encoding, string username, string password, bool offersPlain, out string preparedUsername, out string preparedPassword) { preparedPassword = password; - if (!encoding.TryPrepare(username, out preparedUsername) || !encoding.TryPrepare(password, out preparedPassword)) + if (!MailboxPasswordEncodings.TryPrepare(encoding, username, out preparedUsername) || !MailboxPasswordEncodings.TryPrepare(encoding, password, out preparedPassword)) return false; - return offersPlain || encoding is MailboxPasswordEncoding.UTF8 || (Ascii.IsValid(preparedUsername) && Ascii.IsValid(preparedPassword)); + return offersPlain || MailboxPasswordEncodings.IsUtf8(encoding) || (Ascii.IsValid(preparedUsername) && Ascii.IsValid(preparedPassword)); } /// diff --git a/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs b/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs new file mode 100644 index 000000000..9ee779143 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs @@ -0,0 +1,135 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; + +namespace AIStudio.Tools.Mail; + +/// +/// The encodings in which AI Studio can send the username and the password of a mailbox. +/// +/// +/// The standard for signing in with a password demands UTF-8 (RFC 4616), but a mail server compares +/// the bytes it receives with what it stored, and depending on its configuration, it may decode them +/// in another encoding. Microsoft Exchange, e.g., may expect the code page of its Windows system: +/// Windows-1252 in Western Europe, Windows-1254 in Turkey, or Shift-JIS in Japan. ASCII comes out the +/// same in all of them, so only users whose username or password holds other characters notice.

+/// AI Studio therefore offers every encoding .NET knows which keeps ASCII as it is, stored by its name, +/// e.g., "windows-1254". UTF-16, UTF-32, UTF-7, and the EBCDIC code pages are left out: they change +/// ASCII, and SASL PLAIN separates its parts with zero bytes, which UTF-16 and UTF-32 would break. +///
+public static class MailboxPasswordEncodings +{ + /// + /// The encoding of a new mailbox, and of one stored before the setting existed: UTF-8, which AI Studio always used until then. + /// + public const string DEFAULT = "utf-8"; + + /// + /// The characters of ASCII, which every encoding a mailbox may use has to keep as they are. + /// + private static readonly string ASCII_TEXT = new(Enumerable.Range(0, 128).Select(code => (char)code).ToArray()); + + /// + /// The bytes of ASCII_TEXT in ASCII. + /// + private static readonly byte[] ASCII_BYTES = Encoding.ASCII.GetBytes(ASCII_TEXT); + + /// + /// The names of all encodings a mailbox may use: UTF-8 first, the others in alphabetical order. + /// + public static readonly IReadOnlyList ALL; + + static MailboxPasswordEncodings() + { + // .NET knows the code pages of Windows and most others only once their provider is registered: + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + ALL = Encoding.GetEncodings() + .Select(info => TryGet(info.Name, out var encoding) ? encoding.WebName : null) + .OfType() + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(name => !string.Equals(name, DEFAULT, StringComparison.OrdinalIgnoreCase)) + .ThenBy(name => name, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + /// + /// Finds an encoding a mailbox may use. + /// + /// + /// The encoding refuses what it cannot encode instead of replacing it, e.g., with a question mark: + /// a password sent with a replaced character is not the password, and every such attempt counts as + /// a failed sign-in, which can lock the account. + /// + /// The name of the encoding, e.g., "windows-1252", in any case and with spaces around it. + /// The encoding, which throws on a character it lacks. + /// Whether .NET knows the encoding and it keeps ASCII as it is. + public static bool TryGet(string? name, [NotNullWhen(true)] out Encoding? encoding) + { + encoding = null; + if (string.IsNullOrWhiteSpace(name)) + return false; + + try + { + var candidate = Encoding.GetEncoding(name.Trim(), EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); + if (!candidate.GetBytes(ASCII_TEXT).AsSpan().SequenceEqual(ASCII_BYTES)) + return false; + + encoding = candidate; + return true; + } + + // Thrown for a name .NET does not know, and for an encoding which lacks a character of ASCII. + // EncoderFallbackException is one of them: + catch (ArgumentException) + { + return false; + } + + // Thrown for an encoding .NET knows but no longer supports, such as UTF-7: + catch (NotSupportedException) + { + return false; + } + } + + /// + /// Whether an encoding is UTF-8, the only one the LOGIN command of the IMAP client sends. + /// + /// The encoding. + /// True for UTF-8. + public static bool IsUtf8(Encoding encoding) => encoding.CodePage == Encoding.UTF8.CodePage; + + /// + /// Prepares a username or a password for an encoding. + /// + /// + /// For every encoding but UTF-8, the text is normalized first (NFC): an ä may arrive as an a + /// followed by a combining diaeresis, e.g., from a password manager, and the code pages mostly have + /// only the composed ä. UTF-8 takes the text as it is, as AI Studio always sent it. + /// + /// The encoding, as TryGet returns it. + /// The username or the password. + /// The text to sign in with. + /// Whether the encoding has every character of the text. + public static bool TryPrepare(Encoding encoding, string text, out string prepared) + { + prepared = text; + try + { + if (!IsUtf8(encoding)) + prepared = text.Normalize(NormalizationForm.FormC); + + encoding.GetByteCount(prepared); + return true; + } + + // Thrown for a character the encoding lacks, and for a lone surrogate, which no encoding has. + // EncoderFallbackException is one of them: + catch (ArgumentException) + { + prepared = text; + return false; + } + } +} \ No newline at end of file diff --git a/app/Tests/Settings/MailboxProviderConfigurationTests.cs b/app/Tests/Settings/MailboxProviderConfigurationTests.cs index d12b8c007..f0a06cd73 100644 --- a/app/Tests/Settings/MailboxProviderConfigurationTests.cs +++ b/app/Tests/Settings/MailboxProviderConfigurationTests.cs @@ -39,7 +39,7 @@ public async Task AFullEntryIsReadAsWritten() ["Port"] = "1143", ["UsernameHint"] = "\"Your account as DOMAIN\\\\username\"", ["HelpUrl"] = "\"https://intranet.example.org/mail/imap\"", - ["PasswordEncoding"] = "\" windows_1252 \"", + ["PasswordEncoding"] = "\" Windows-1254 \"", }); Assert.That(provider, Is.Not.Null); @@ -53,7 +53,7 @@ public async Task AFullEntryIsReadAsWritten() Assert.That(provider.Port, Is.EqualTo(1143)); Assert.That(provider.UsernameHint, Is.EqualTo(@"Your account as DOMAIN\username")); Assert.That(provider.HelpUrl, Is.EqualTo("https://intranet.example.org/mail/imap")); - Assert.That(provider.PasswordEncoding, Is.EqualTo(MailboxPasswordEncoding.WINDOWS_1252)); + Assert.That(provider.PasswordEncoding, Is.EqualTo("windows-1254")); } } @@ -98,9 +98,10 @@ public async Task AHostWithUmlautsIsKeptAsWritten() [TestCase("HelpUrl", "\"ftp://intranet.example.org/mail\"")] [TestCase("HelpUrl", "\"/mail/imap\"")] [TestCase("PasswordEncoding", "\"UNKNOWN\"")] - [TestCase("PasswordEncoding", "\"UTF-8\"")] - [TestCase("PasswordEncoding", "\"ISO-8859-1\"")] - [TestCase("PasswordEncoding", "\"UTF8, WINDOWS_1252\"")] + [TestCase("PasswordEncoding", "\"\"")] + [TestCase("PasswordEncoding", "\"utf-16\"")] + [TestCase("PasswordEncoding", "\"IBM037\"")] + [TestCase("PasswordEncoding", "\"utf-8, windows-1252\"")] [TestCase("PasswordEncoding", "true")] public async Task AnEntryWithAnInvalidFieldIsLeftOut(string field, string? value) { diff --git a/app/Tests/Settings/MailboxSettingsTests.cs b/app/Tests/Settings/MailboxSettingsTests.cs index 5949bc4c6..af3c6e2f7 100644 --- a/app/Tests/Settings/MailboxSettingsTests.cs +++ b/app/Tests/Settings/MailboxSettingsTests.cs @@ -3,6 +3,7 @@ using AIStudio.Provider; using AIStudio.Settings; using AIStudio.Settings.DataModel; +using AIStudio.Tools.Mail; using Microsoft.Extensions.Logging.Abstractions; @@ -40,7 +41,7 @@ public sealed class MailboxSettingsTests Port = 143, TransportSecurity = MailboxTransportSecurity.STARTTLS, AuthMethod = MailboxAuthMethod.PASSWORD, - PasswordEncoding = MailboxPasswordEncoding.WINDOWS_1252, + PasswordEncoding = "windows-1252", Username = "someone@example.org", RootFolder = "INBOX/Projects", IncludeSentAndDrafts = false, @@ -139,11 +140,23 @@ public void AMailboxStoredBeforeSentMailsAndDraftsWereChoosableIncludesThem() } [Test] - public void AMailboxStoredBeforeThePasswordEncodingSignsInWithUTF8() + public void AMailboxStoredBeforeThePasswordEncodingSignsInWithUtf8() { // UTF-8 is what every sign-in used until then: var mailbox = JsonSerializer.Deserialize("""{"RootFolder": "INBOX"}""", SettingsManager.JSON_OPTIONS); - Assert.That(mailbox.PasswordEncoding, Is.EqualTo(MailboxPasswordEncoding.UTF8)); + Assert.That(mailbox.PasswordEncoding, Is.EqualTo(MailboxPasswordEncodings.DEFAULT)); + } + + [Test] + public void AnEncodingThisVersionDoesNotKnowIsKeptButSignsInNowhere() + { + // The name stays, so that it works again with the version that wrote it; ImapMailboxConnectorTests checks that nothing is sent: + var mailbox = JsonSerializer.Deserialize("""{"PasswordEncoding": "x-encoding-of-the-future"}""", SettingsManager.JSON_OPTIONS); + using (Assert.EnterMultipleScope()) + { + Assert.That(mailbox.PasswordEncoding, Is.EqualTo("x-encoding-of-the-future")); + Assert.That(MailboxPasswordEncodings.TryGet(mailbox.PasswordEncoding, out _), Is.False); + } } [Test] @@ -160,7 +173,6 @@ public void ValuesThisVersionCannotReadFallBackToTheSafeSide() "ConfidenceLevel": "EXTREMELY_HIGH", "TransportSecurity": "QUANTUM_TLS", "AuthMethod": "PASSKEY", - "PasswordEncoding": "EBCDIC", "MaxAge": "LAST_36_MONTHS", "OutboundDataRestriction": "NOTHING_AT_ALL" } @@ -172,7 +184,6 @@ public void ValuesThisVersionCannotReadFallBackToTheSafeSide() Assert.That(mailbox.ConfidenceLevel, Is.EqualTo(ConfidenceLevel.NONE)); Assert.That(mailbox.TransportSecurity, Is.EqualTo(MailboxTransportSecurity.UNKNOWN)); Assert.That(mailbox.AuthMethod, Is.EqualTo(MailboxAuthMethod.UNKNOWN)); - Assert.That(mailbox.PasswordEncoding, Is.EqualTo(MailboxPasswordEncoding.UNKNOWN)); Assert.That(mailbox.MaxAge, Is.EqualTo(MailboxMaxAge.LAST_3_MONTHS)); Assert.That(mailbox.OutboundDataRestriction, Is.EqualTo(OutboundDataRestriction.ONLY_CONFIGURED_SERVICES)); } diff --git a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs index 1d2924fec..a20064867 100644 --- a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs +++ b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs @@ -55,7 +55,8 @@ private static IEnumerable InvalidSettings() { yield return Case("unknown transport security", MAILBOX with { TransportSecurity = MailboxTransportSecurity.UNKNOWN }, PASSWORD); yield return Case("unknown auth method", MAILBOX with { AuthMethod = MailboxAuthMethod.UNKNOWN }, PASSWORD); - yield return Case("unknown password encoding", MAILBOX with { PasswordEncoding = MailboxPasswordEncoding.UNKNOWN }, PASSWORD); + yield return Case("unknown password encoding", MAILBOX with { PasswordEncoding = "EBCDIC" }, PASSWORD); + yield return Case("password encoding which changes ASCII", MAILBOX with { PasswordEncoding = "utf-16" }, PASSWORD); yield return Case("no host", MAILBOX with { Host = " " }, PASSWORD); yield return Case("a URL as host", MAILBOX with { Host = "imaps://imap.example.org" }, PASSWORD); yield return Case("port 0", MAILBOX with { Port = 0 }, PASSWORD); @@ -115,14 +116,16 @@ public async Task AServerTheOrganizationDoesNotAllowIsNeverContacted() private static IEnumerable SignInPreparations() { - const MailboxPasswordEncoding UTF8 = MailboxPasswordEncoding.UTF8; - const MailboxPasswordEncoding WINDOWS_1252 = MailboxPasswordEncoding.WINDOWS_1252; + const string UTF8 = "utf-8"; + const string WINDOWS_1252 = "windows-1252"; yield return Case("ASCII", UTF8, "someone", "Sommer-2026!", true, true); yield return Case("umlaut in the password", UTF8, "someone", "Grüße-2026", true, true); yield return Case("umlaut in the username", WINDOWS_1252, @"FIRMA\müller", "Sommer-2026!", true, true); yield return Case("Windows-1252 with umlaut and euro sign", WINDOWS_1252, "someone", "Grüße-100€", true, true); yield return Case("UTF-8 with Turkish and Japanese", UTF8, "kişi", "şifre-日本", true, true); + yield return Case("Windows-1254 with Turkish", "windows-1254", "kişi", "şifre-2026", true, true); + yield return Case("Shift-JIS with Japanese", "shift_jis", "利用者", "日本-2026", true, true); // Windows-1252 lacks the capital sharp s and the Turkish s with cedilla, and AI Studio never switches to UTF-8 on its own: yield return Case("capital sharp s in Windows-1252", WINDOWS_1252, "someone", "STRAẞE", true, false); @@ -135,18 +138,15 @@ private static IEnumerable SignInPreparations() // No encoding has a lone surrogate: yield return Case("lone surrogate", UTF8, "someone", "abc\uD800", true, false); - - // An encoding this version does not know encodes nothing: - yield return Case("unknown encoding", MailboxPasswordEncoding.UNKNOWN, "someone", "Sommer-2026!", true, false); yield break; - static TestCaseData Case(string name, MailboxPasswordEncoding encoding, string username, string password, bool offersPlain, bool expected) => new TestCaseData(encoding, username, password, offersPlain).Returns(expected).SetArgDisplayNames(name); + static TestCaseData Case(string name, string encoding, string username, string password, bool offersPlain, bool expected) => new TestCaseData(encoding, username, password, offersPlain).Returns(expected).SetArgDisplayNames(name); } [TestCaseSource(nameof(SignInPreparations))] - public bool ASignInGoesAheadOnlyWhenTheEncodingCarriesTheUsernameAndThePassword(MailboxPasswordEncoding encoding, string username, string password, bool offersPlain) + public bool ASignInGoesAheadOnlyWhenTheEncodingCarriesTheUsernameAndThePassword(string encoding, string username, string password, bool offersPlain) { - return ImapMailboxConnector.TryPrepareSignIn(encoding, username, password, offersPlain, out _, out _); + return ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncodingsTests.GetKnownEncoding(encoding), username, password, offersPlain, out _, out _); } [Test] @@ -156,7 +156,7 @@ public void APreparedSignInComposesADecomposedUmlautForWindows1252() const string DECOMPOSED = "Ka\u0308se"; using (Assert.EnterMultipleScope()) { - Assert.That(ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncoding.WINDOWS_1252, "müller", DECOMPOSED, true, out var username, out var password), Is.True); + Assert.That(ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncodingsTests.GetKnownEncoding("windows-1252"), "müller", DECOMPOSED, true, out var username, out var password), Is.True); Assert.That(username, Is.EqualTo("müller")); Assert.That(password, Is.EqualTo("Käse")); } diff --git a/app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs b/app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs deleted file mode 100644 index 0b4768710..000000000 --- a/app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs +++ /dev/null @@ -1,134 +0,0 @@ -using AIStudio.Settings.DataModel; - -using MailKit.Security; - -namespace AIStudio.Tests.Tools.Mail; - -/// -/// Checks the bytes a password becomes when signing in, for the special characters of German. -/// -/// -/// Microsoft Exchange compares the bytes with the password of the Windows account in Windows-1252, -/// so a password sent in UTF-8 fails there as soon as it holds one of these characters. -/// -[TestFixture] -public sealed class MailboxPasswordEncodingTests -{ - private const string USERNAME = "u"; - - private static IEnumerable GermanCharacters() - { - yield return Case("ä", "C3 A4", "E4"); - yield return Case("ö", "C3 B6", "F6"); - yield return Case("ü", "C3 BC", "FC"); - yield return Case("Ä", "C3 84", "C4"); - yield return Case("Ö", "C3 96", "D6"); - yield return Case("Ü", "C3 9C", "DC"); - yield return Case("ß", "C3 9F", "DF"); - yield return Case("§", "C2 A7", "A7"); - yield return Case("°", "C2 B0", "B0"); - yield return Case("´", "C2 B4", "B4"); - yield return Case("µ", "C2 B5", "B5"); - yield return Case("²", "C2 B2", "B2"); - yield return Case("³", "C2 B3", "B3"); - yield return Case("€", "E2 82 AC", "80"); - yield return Case("„", "E2 80 9E", "84"); - yield return Case("“", "E2 80 9C", "93"); - yield return Case("‚", "E2 80 9A", "82"); - yield return Case("‘", "E2 80 98", "91"); - yield return Case("–", "E2 80 93", "96"); - yield return Case("…", "E2 80 A6", "85"); - yield break; - - static TestCaseData Case(string character, string utf8, string windows1252) => new TestCaseData(character, utf8, windows1252).SetArgDisplayNames(character); - } - - [TestCaseSource(nameof(GermanCharacters))] - public void PlainSendsTheBytesOfTheChosenEncoding(string character, string utf8, string windows1252) - { - using (Assert.EnterMultipleScope()) - { - Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.UTF8, character), Is.EqualTo(utf8)); - Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.WINDOWS_1252, character), Is.EqualTo(windows1252)); - } - } - - [Test] - public void AsciiIsTheSameInEveryEncoding() - { - const string PASSWORD = "Sommer-2026!"; - Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.WINDOWS_1252, PASSWORD), Is.EqualTo(GetPlainPasswordBytes(MailboxPasswordEncoding.UTF8, PASSWORD))); - } - - [TestCase("ẞ")] - [TestCase("Straße 🙂")] - public void Windows1252RefusesWhatItLacks(string text) - { - using (Assert.EnterMultipleScope()) - { - Assert.That(MailboxPasswordEncoding.WINDOWS_1252.TryPrepare(text, out _), Is.False); - Assert.That(MailboxPasswordEncoding.UTF8.TryPrepare(text, out var prepared), Is.True); - Assert.That(prepared, Is.EqualTo(text)); - } - } - - [Test] - public void ALoneSurrogateIsRefusedByEveryEncoding() - { - const string TEXT = "abc\uD800"; - using (Assert.EnterMultipleScope()) - { - Assert.That(MailboxPasswordEncoding.UTF8.TryPrepare(TEXT, out _), Is.False); - Assert.That(MailboxPasswordEncoding.WINDOWS_1252.TryPrepare(TEXT, out _), Is.False); - } - } - - [Test] - public void Windows1252ComposesADecomposedUmlaut() - { - // An a followed by a combining diaeresis, as some password managers deliver an ä: - const string DECOMPOSED = "Käse"; - using (Assert.EnterMultipleScope()) - { - Assert.That(MailboxPasswordEncoding.WINDOWS_1252.TryPrepare(DECOMPOSED, out var prepared), Is.True); - Assert.That(prepared, Is.EqualTo("Käse")); - Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.WINDOWS_1252, DECOMPOSED), Is.EqualTo("4B E4 73 65")); - } - } - - [Test] - public void Utf8TakesTheTextAsItIs() - { - const string DECOMPOSED = "Käse"; - using (Assert.EnterMultipleScope()) - { - Assert.That(MailboxPasswordEncoding.UTF8.TryPrepare(DECOMPOSED, out var prepared), Is.True); - Assert.That(prepared, Is.EqualTo(DECOMPOSED)); - } - } - - [Test] - public void AnUnknownEncodingEncodesNothing() - { - using (Assert.EnterMultipleScope()) - { - Assert.That(MailboxPasswordEncoding.UNKNOWN.TextEncoding, Is.Null); - Assert.That(MailboxPasswordEncoding.UNKNOWN.TryPrepare("abc", out _), Is.False); - } - } - - /// - /// The bytes of the password in the message which the SASL mechanism PLAIN sends, as hex. - /// - private static string GetPlainPasswordBytes(MailboxPasswordEncoding passwordEncoding, string password) - { - Assert.That(passwordEncoding.TryPrepare(password, out var preparedPassword), Is.True); - - // PLAIN sends the authorization identity, the username, and the password, each after a zero byte: - var mechanism = new SaslMechanismPlain(passwordEncoding.TextEncoding!, USERNAME, preparedPassword); - var message = Convert.FromBase64String(mechanism.Challenge(null, CancellationToken.None)); - var passwordBytes = message.AsSpan(1 + USERNAME.Length + 1); - - return string.Join(' ', Convert.ToHexString(passwordBytes).Chunk(2).Select(pair => new string(pair))); - } -} \ No newline at end of file diff --git a/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs b/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs new file mode 100644 index 000000000..dc2dd5424 --- /dev/null +++ b/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs @@ -0,0 +1,199 @@ +using System.Text; + +using AIStudio.Tools.Mail; + +using MailKit.Security; + +namespace AIStudio.Tests.Tools.Mail; + +/// +/// Checks which encodings a mailbox may use, and the bytes a password becomes in them when signing in. +/// +/// +/// Depending on its configuration, a mail server compares the bytes with the password in another +/// encoding than UTF-8, e.g., Microsoft Exchange in the code page of its Windows system. A password sent +/// in the wrong encoding fails there as soon as it holds a character beyond ASCII. The expected bytes +/// come from the code page tables, not from .NET. +/// +[TestFixture] +public sealed class MailboxPasswordEncodingsTests +{ + private const string USERNAME = "u"; + + private static IEnumerable CharactersOfSeveralScripts() + { + // German, as on a German keyboard and in German typography: + yield return Case("windows-1252", "ä", "E4", "C3 A4"); + yield return Case("windows-1252", "Ö", "D6", "C3 96"); + yield return Case("windows-1252", "ß", "DF", "C3 9F"); + yield return Case("windows-1252", "§", "A7", "C2 A7"); + yield return Case("windows-1252", "°", "B0", "C2 B0"); + yield return Case("windows-1252", "µ", "B5", "C2 B5"); + yield return Case("windows-1252", "€", "80", "E2 82 AC"); + yield return Case("windows-1252", "„", "84", "E2 80 9E"); + yield return Case("windows-1252", "“", "93", "E2 80 9C"); + yield return Case("windows-1252", "–", "96", "E2 80 93"); + + // French, Spanish, and the Nordic languages: + yield return Case("windows-1252", "é", "E9", "C3 A9"); + yield return Case("windows-1252", "ç", "E7", "C3 A7"); + yield return Case("windows-1252", "œ", "9C", "C5 93"); + yield return Case("windows-1252", "ñ", "F1", "C3 B1"); + yield return Case("windows-1252", "ø", "F8", "C3 B8"); + yield return Case("windows-1252", "å", "E5", "C3 A5"); + + // Central Europe: + yield return Case("windows-1250", "ł", "B3", "C5 82"); + yield return Case("windows-1250", "ś", "9C", "C5 9B"); + yield return Case("windows-1250", "ř", "F8", "C5 99"); + yield return Case("windows-1250", "ő", "F5", "C5 91"); + + // Cyrillic, Greek, and Turkish: + yield return Case("windows-1251", "ж", "E6", "D0 B6"); + yield return Case("windows-1251", "Ж", "C6", "D0 96"); + yield return Case("koi8-r", "ж", "D6", "D0 B6"); + yield return Case("windows-1253", "α", "E1", "CE B1"); + yield return Case("windows-1254", "ş", "FE", "C5 9F"); + yield return Case("windows-1254", "ğ", "F0", "C4 9F"); + yield return Case("windows-1254", "ı", "FD", "C4 B1"); + yield return Case("windows-1254", "İ", "DD", "C4 B0"); + + // ISO-8859-15 has the euro sign where Latin-1 has the currency sign: + yield return Case("iso-8859-15", "€", "A4", "E2 82 AC"); + + // East Asia: + yield return Case("shift_jis", "日", "93 FA", "E6 97 A5"); + yield return Case("shift_jis", "あ", "82 A0", "E3 81 82"); + yield return Case("gb2312", "中", "D6 D0", "E4 B8 AD"); + yield return Case("big5", "中", "A4 A4", "E4 B8 AD"); + yield return Case("ks_c_5601-1987", "한", "C7 D1", "ED 95 9C"); + yield break; + + static TestCaseData Case(string encodingName, string character, string inEncoding, string inUtf8) => new TestCaseData(encodingName, character, inEncoding, inUtf8).SetArgDisplayNames($"{character} in {encodingName}"); + } + + [TestCaseSource(nameof(CharactersOfSeveralScripts))] + public void PlainSendsTheBytesOfTheChosenEncoding(string encodingName, string character, string inEncoding, string inUtf8) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(GetPlainPasswordBytes(encodingName, character), Is.EqualTo(inEncoding)); + Assert.That(GetPlainPasswordBytes(MailboxPasswordEncodings.DEFAULT, character), Is.EqualTo(inUtf8)); + } + } + + [Test] + public void AsciiIsTheSameInEveryEncoding() + { + const string PASSWORD = "Sommer-2026!"; + var utf8 = GetPlainPasswordBytes(MailboxPasswordEncodings.DEFAULT, PASSWORD); + Assert.That(MailboxPasswordEncodings.ALL.Select(name => GetPlainPasswordBytes(name, PASSWORD)), Is.All.EqualTo(utf8)); + } + + [Test] + public void TheListStartsWithUtf8AndHoldsTheCodePagesOfWindows() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncodings.ALL[0], Is.EqualTo(MailboxPasswordEncodings.DEFAULT)); + Assert.That(MailboxPasswordEncodings.ALL, Is.Unique); + Assert.That(MailboxPasswordEncodings.ALL, Is.SupersetOf(new[] { "windows-1250", "windows-1251", "windows-1252", "windows-1254", "shift_jis", "gb2312", "big5", "iso-8859-15" })); + Assert.That(MailboxPasswordEncodings.ALL, Has.None.StartsWith("utf-16").And.None.StartsWith("utf-32").And.None.EqualTo("utf-7")); + } + } + + [TestCase("utf-8", ExpectedResult = "utf-8")] + [TestCase(" Windows-1254 ", ExpectedResult = "windows-1254")] + [TestCase("SHIFT_JIS", ExpectedResult = "shift_jis")] + [TestCase("latin1", ExpectedResult = "iso-8859-1")] + public string? AKnownEncodingIsFoundByItsName(string name) + { + return MailboxPasswordEncodings.TryGet(name, out var encoding) ? encoding.WebName : null; + } + + [TestCase(null)] + [TestCase("")] + [TestCase(" ")] + [TestCase("EBCDIC")] + [TestCase("utf-16")] + [TestCase("utf-32")] + [TestCase("utf-7")] + [TestCase("IBM037")] + [TestCase("utf-8, windows-1252")] + public void AnEncodingWhichChangesAsciiOrIsUnknownIsRefused(string? name) + { + Assert.That(MailboxPasswordEncodings.TryGet(name, out _), Is.False); + } + + [TestCase("windows-1252", "ẞ")] + [TestCase("windows-1252", "Straße 🙂")] + [TestCase("windows-1252", "ş")] + [TestCase("windows-1254", "€uro ẞ")] + [TestCase("shift_jis", "한")] + public void AnEncodingRefusesWhatItLacks(string encodingName, string text) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncodings.TryPrepare(GetKnownEncoding(encodingName), text, out _), Is.False); + Assert.That(MailboxPasswordEncodings.TryPrepare(GetKnownEncoding(MailboxPasswordEncodings.DEFAULT), text, out var prepared), Is.True); + Assert.That(prepared, Is.EqualTo(text)); + } + } + + [Test] + public void ALoneSurrogateIsRefusedByEveryEncoding() + { + const string TEXT = "abc\uD800"; + Assert.That(MailboxPasswordEncodings.ALL.Where(name => MailboxPasswordEncodings.TryPrepare(GetKnownEncoding(name), TEXT, out _)), Is.Empty); + } + + [Test] + public void ACodePageComposesADecomposedUmlaut() + { + // An a followed by a combining diaeresis, as some password managers deliver an ä: + const string DECOMPOSED = "Ka\u0308se"; + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncodings.TryPrepare(GetKnownEncoding("windows-1252"), DECOMPOSED, out var prepared), Is.True); + Assert.That(prepared, Is.EqualTo("K\u00E4se")); + Assert.That(GetPlainPasswordBytes("windows-1252", DECOMPOSED), Is.EqualTo("4B E4 73 65")); + } + } + + [Test] + public void Utf8TakesTheTextAsItIs() + { + // AI Studio always sent the text in UTF-8 as it was, so a server which knows a password in this form keeps accepting it: + const string DECOMPOSED = "Ka\u0308se"; + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncodings.TryPrepare(GetKnownEncoding(MailboxPasswordEncodings.DEFAULT), DECOMPOSED, out var prepared), Is.True); + Assert.That(prepared, Is.EqualTo(DECOMPOSED)); + } + } + + /// + /// The encoding of a name which a mailbox may use; fails the test for any other name. + /// + internal static Encoding GetKnownEncoding(string name) + { + Assert.That(MailboxPasswordEncodings.TryGet(name, out var encoding), Is.True, $"The encoding '{name}' should be known."); + return encoding!; + } + + /// + /// The bytes of the password in the message which the SASL mechanism PLAIN sends, as hex. + /// + private static string GetPlainPasswordBytes(string encodingName, string password) + { + var encoding = GetKnownEncoding(encodingName); + Assert.That(MailboxPasswordEncodings.TryPrepare(encoding, password, out var preparedPassword), Is.True); + + // PLAIN sends the authorization identity, the username, and the password, each after a zero byte: + var mechanism = new SaslMechanismPlain(encoding, USERNAME, preparedPassword); + var message = Convert.FromBase64String(mechanism.Challenge(null, CancellationToken.None)); + var passwordBytes = message.AsSpan(1 + USERNAME.Length + 1); + + return string.Join(' ', Convert.ToHexString(passwordBytes).Chunk(2).Select(pair => new string(pair))); + } +} \ No newline at end of file From 049407a1a4655d862a2f3e54253d28141a06724f Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 09:43:08 +0100 Subject: [PATCH 07/15] Applied the password encoding of the organization to every mailbox connection --- .../Dialogs/DataSourceMailboxDialog.razor.cs | 27 +++---------- .../Plugins/configuration/plugin.lua | 5 ++- .../Settings/DataModel/DataMailboxProvider.cs | 3 +- .../Tools/Mail/ImapMailboxConnector.cs | 6 +-- .../Tools/Mail/MailServerPolicy.cs | 40 ++++++++++++++++--- .../Tools/Mail/OrganizationMailServer.cs | 8 ++++ .../Tools/Mail/ImapMailboxConnectorTests.cs | 2 +- app/Tests/Tools/Mail/MailServerPolicyTests.cs | 24 ++++++++++- 8 files changed, 79 insertions(+), 36 deletions(-) create mode 100644 app/MindWork AI Studio/Tools/Mail/OrganizationMailServer.cs diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index 29db3af37..84d795903 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -20,9 +20,9 @@ namespace AIStudio.Dialogs; /// Adds or edits a mailbox. ///
/// -/// Every connection test is exactly one sign-in, started by the user, in the encoding a configuration -/// plugin sets for the mail server, if any, and in the one stored for the mailbox otherwise. The -/// encoding of a successful test is stored along with the mailbox. The outcome of a test only touches +/// Every connection test is exactly one sign-in, started by the user, in the encoding which +/// MailServerPolicy.GetPasswordEncoding decides on, like every other sign-in. The encoding of a +/// successful test is stored along with the mailbox. The outcome of a test only touches /// the recorded sign-in failure of the mailbox when the test used the settings and the password stored /// for it: a failure with a password the user is still typing says nothing about the stored one, and /// neither does a success. A success in another encoding clears the failure only once the mailbox is @@ -517,15 +517,12 @@ private async Task TestConnection() try { - // The organization knows which encoding its mail server expects: var mailbox = this.CreateDataSource(); - if (this.GetOrganizationPasswordEncoding(mailbox.Host) is { } organizationPasswordEncoding) - mailbox = mailbox with { PasswordEncoding = organizationPasswordEncoding }; - + var policy = MailServerPolicy.Read(this.SettingsManager); using var timeout = new CancellationTokenSource(CONNECTION_TEST_TIMEOUT); await using var connector = new ImapMailboxConnector(); - await connector.ConnectAsync(mailbox, settings.Password, MailServerPolicy.Read(this.SettingsManager), timeout.Token); - this.dataPasswordEncoding = mailbox.PasswordEncoding; + await connector.ConnectAsync(mailbox, settings.Password, policy, timeout.Token); + this.dataPasswordEncoding = policy.GetPasswordEncoding(mailbox); this.serverFolders = await connector.GetFoldersAsync(timeout.Token); this.testFailure = null; this.Logger.LogInformation($"Tested the connection of the mailbox '{this.dataId}' successfully."); @@ -553,18 +550,6 @@ private async Task TestConnection() await this.form.ValidateAsync(); } - /// - /// The encoding a configuration plugin sets for this mail server, cf. DataMailboxProvider.PasswordEncoding. - /// - /// - /// Found by the host rather than by the chosen provider: the user may have typed another host since. - /// - /// The host the connection goes to. - /// The encoding, or null when no mail server of the organization on this host sets one. - private string? GetOrganizationPasswordEncoding(string host) => this.organizationProviders - .FirstOrDefault(provider => provider.PasswordEncoding is not null && MailServerHosts.AreSame(provider.Host, host))? - .PasswordEncoding; - private async Task CreateFolder(string parentFullName, string name) { var settings = this.CurrentSettings; diff --git a/app/MindWork AI Studio/Plugins/configuration/plugin.lua b/app/MindWork AI Studio/Plugins/configuration/plugin.lua index 3c2e0d407..e93fb2e48 100644 --- a/app/MindWork AI Studio/Plugins/configuration/plugin.lua +++ b/app/MindWork AI Studio/Plugins/configuration/plugin.lua @@ -358,8 +358,9 @@ CONFIG["DATA_SOURCES"] = {} -- Microsoft Exchange the code page of its Windows system: windows-1252 in -- Western Europe, windows-1250 in Central Europe, windows-1251 for Cyrillic, -- windows-1254 in Turkey, or shift_jis in Japan. Any encoding .NET knows by --- name works, as long as it keeps ASCII as it is; utf-16 does not. The --- connection test in the mailbox dialog signs in with this encoding. +-- name works, as long as it keeps ASCII as it is; utf-16 does not. Every +-- mailbox on this server signs in with this encoding, also one added +-- before you set it, and users cannot change it. -- An entry with an invalid field is left out as a whole, and the log names the field. -- To allow mailboxes on these mail servers only, see DataMailboxes.AllowOnlyOrganizationMailServers. CONFIG["MAILBOX_PROVIDERS"] = {} diff --git a/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs b/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs index 5bc37d189..57a70151f 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs @@ -65,7 +65,8 @@ public sealed record DataMailboxProvider : ILivePluginContent /// /// Depending on its configuration, a mail server may expect another encoding than UTF-8, e.g., /// Microsoft Exchange the code page of its Windows system. The organization knows which one, so - /// its users spend no failed sign-in on finding out. + /// its users spend no failed sign-in on finding out: every mailbox on this server signs in with + /// it, cf. MailServerPolicy.GetPasswordEncoding. /// public string? PasswordEncoding { get; private init; } diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index a9450ffbc..c1e4ea338 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -114,12 +114,12 @@ static ImapMailboxConnector() ///
/// The mailbox to connect to. /// The password, as stored in the OS keyring or just typed in. - /// Which mail servers the organization allows. Every connection passes here, so this is where a server it does not allow is refused. + /// Which mail servers the organization allows, and which encodings it names for them. Every connection passes here, so this is where a server it does not allow is refused, and where its encoding takes effect. /// The cancellation token. /// The connection or the sign-in failed. public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, CancellationToken token) { - if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || !MailboxPasswordEncodings.TryGet(mailbox.PasswordEncoding, out var textEncoding) ||!MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) + if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || !MailboxPasswordEncodings.TryGet(policy.GetPasswordEncoding(mailbox), out var textEncoding) ||!MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The mailbox settings are incomplete, or this version of AI Studio does not know them."); if (!policy.IsAllowed(mailbox.Host)) @@ -494,7 +494,7 @@ private static async Task FetchAttachmentPieceAsync(IMailFolder folder, } /// - /// Prepares the username and the password for one sign-in in the encoding of the mailbox. + /// Prepares the username and the password for one sign-in in the encoding of the mailbox, cf. MailServerPolicy.GetPasswordEncoding. /// /// /// A sign-in in bytes which are not the password counts as a failed attempt, just like a wrong diff --git a/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs b/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs index 28824d24c..889e25f4d 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs @@ -1,18 +1,20 @@ using AIStudio.Settings; +using AIStudio.Settings.DataModel; using AIStudio.Tools.PluginSystem; namespace AIStudio.Tools.Mail; /// -/// Which mail servers AI Studio may connect to, and whose mailboxes the AI may read. +/// Which mail servers AI Studio may connect to, whose mailboxes the AI may read, and in which encoding +/// a mailbox sends its username and password. /// /// -/// Read anew for every decision rather than kept: both parts come from configuration plugins, which +/// Read anew for every decision rather than kept: all parts come from configuration plugins, which /// may change while AI Studio runs. /// /// Whether the organization allows only its own mail servers, see DataMailboxes.AllowOnlyOrganizationMailServers. -/// The hosts of the mail servers which the configuration plugins offer. -public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IReadOnlyList OrganizationHosts) +/// The mail servers which the configuration plugins offer. +public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IReadOnlyList OrganizationServers) { /// /// Every server: what holds as long as no organization rules otherwise. @@ -26,7 +28,7 @@ public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IR /// The policy. public static MailServerPolicy Read(SettingsManager settingsManager) => new( settingsManager.ConfigurationData.MailboxSettings.AllowOnlyOrganizationMailServers, - PluginFactory.GetMailboxProviders().Select(provider => provider.Host).ToList()); + PluginFactory.GetMailboxProviders().Select(provider => new OrganizationMailServer(provider.Host, provider.PasswordEncoding)).ToList()); /// /// Whether AI Studio may connect to a server, and the AI read the mailboxes on it. @@ -37,5 +39,31 @@ public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IR /// /// The host of the server. /// True when the server is allowed. - public bool IsAllowed(string host) => !this.AllowsOnlyOrganizationMailServers || this.OrganizationHosts.Any(organizationHost => MailServerHosts.AreSame(organizationHost, host)); + public bool IsAllowed(string host) => !this.AllowsOnlyOrganizationMailServers || this.OrganizationServers.Any(server => MailServerHosts.AreSame(server.Host, host)); + + /// + /// The encoding the organization names for a server. + /// + /// + /// Found by the host, like IsAllowed: the user may have typed the host rather than chosen the + /// mail server of the organization. It holds whether or not the organization allows only its own + /// mail servers. + /// + /// The host of the server. + /// The name of the encoding, or null when the organization names none for this server. + public string? GetOrganizationPasswordEncoding(string host) => this.OrganizationServers + .FirstOrDefault(server => server.PasswordEncoding is not null && MailServerHosts.AreSame(server.Host, host))? + .PasswordEncoding; + + /// + /// The encoding in which a mailbox sends its username and password. + /// + /// + /// The encoding the organization names for the server comes first: it knows what its server + /// expects, and it may name the encoding only after the mailbox was added. Every sign-in, the + /// connection test and the synchronization alike, takes the encoding from here. + /// + /// The mailbox. + /// The name of the encoding. + public string GetPasswordEncoding(DataSourceMailbox mailbox) => this.GetOrganizationPasswordEncoding(mailbox.Host) ?? mailbox.PasswordEncoding; } \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Mail/OrganizationMailServer.cs b/app/MindWork AI Studio/Tools/Mail/OrganizationMailServer.cs new file mode 100644 index 000000000..b9bc292b8 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Mail/OrganizationMailServer.cs @@ -0,0 +1,8 @@ +namespace AIStudio.Tools.Mail; + +/// +/// What MailServerPolicy needs to know about a mail server which a configuration plugin offers. +/// +/// The host of the server. +/// The name of the encoding the server expects for usernames and passwords, cf. DataMailboxProvider.PasswordEncoding, or null when the organization did not say. +public sealed record OrganizationMailServer(string Host, string? PasswordEncoding); \ No newline at end of file diff --git a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs index a20064867..9e11f1011 100644 --- a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs +++ b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs @@ -109,7 +109,7 @@ public async Task AServerTheOrganizationDoesNotAllowIsNeverContacted() // a network failure instead of this one. // await using var connector = new ImapMailboxConnector(); - var policy = new MailServerPolicy(true, ["imap.intra.example.org"]); + var policy = new MailServerPolicy(true, [new("imap.intra.example.org", null)]); var exception = await Assert.ThrowsAsync(() => connector.ConnectAsync(MAILBOX, PASSWORD, policy, CancellationToken.None)); Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.SERVER_NOT_ALLOWED)); } diff --git a/app/Tests/Tools/Mail/MailServerPolicyTests.cs b/app/Tests/Tools/Mail/MailServerPolicyTests.cs index 383c1bd01..05a9e2ba8 100644 --- a/app/Tests/Tools/Mail/MailServerPolicyTests.cs +++ b/app/Tests/Tools/Mail/MailServerPolicyTests.cs @@ -1,19 +1,24 @@ +using AIStudio.Settings.DataModel; using AIStudio.Tools.Mail; namespace AIStudio.Tests.Tools.Mail; /// -/// Checks which mail servers AI Studio may connect to. +/// Checks which mail servers AI Studio may connect to, and in which encoding a mailbox signs in. /// /// /// Without a rule of the organization, every server is allowed, as before. With it, only the hosts /// of the mail servers the organization offers are, however they are written. An organization /// which switched the rule on but offers no mail server yet allows none at all, rather than all. +/// The encoding the organization names for a server wins over the one of the mailbox, with or +/// without the rule: it also reaches mailboxes added before the organization named it. /// [TestFixture] public sealed class MailServerPolicyTests { - private static readonly MailServerPolicy ORGANIZATION_ONLY = new(true, ["imap.intra.example.org", "mail.müller.example"]); + private static readonly MailServerPolicy ORGANIZATION_ONLY = new(true, [new("imap.intra.example.org", null), new("mail.müller.example", null)]); + + private static readonly MailServerPolicy WITH_ENCODINGS = new(false, [new("imap.intra.example.org", null), new("exchange.müller.example", "windows-1254")]); [TestCase("imap.example.com")] [TestCase("imap.gmail.com")] @@ -32,4 +37,19 @@ public sealed class MailServerPolicyTests [Test] public void ARuleWithoutServersAllowsNone() => Assert.That(new MailServerPolicy(true, []).IsAllowed("imap.intra.example.org"), Is.False); + + [TestCase("exchange.müller.example", ExpectedResult = "windows-1254")] + [TestCase("EXCHANGE.xn--mller-kva.example", ExpectedResult = "windows-1254")] + [TestCase("imap.intra.example.org", ExpectedResult = null)] + [TestCase("imap.gmail.com", ExpectedResult = null)] + public string? TheOrganizationNamesTheEncodingOfItsServers(string host) => WITH_ENCODINGS.GetOrganizationPasswordEncoding(host); + + [TestCase("exchange.müller.example", "utf-8", ExpectedResult = "windows-1254")] + [TestCase("exchange.müller.example", "x-encoding-of-the-future", ExpectedResult = "windows-1254")] + [TestCase("imap.intra.example.org", "windows-1252", ExpectedResult = "windows-1252")] + [TestCase("imap.gmail.com", "utf-8", ExpectedResult = "utf-8")] + public string AMailboxSignsInWithTheEncodingOfTheOrganizationFirst(string host, string mailboxEncoding) => WITH_ENCODINGS.GetPasswordEncoding(new DataSourceMailbox { Host = host, PasswordEncoding = mailboxEncoding }); + + [Test] + public void WithoutAnOrganizationAMailboxKeepsItsEncoding() => Assert.That(MailServerPolicy.ANY_SERVER.GetPasswordEncoding(new DataSourceMailbox { Host = "imap.gmail.com", PasswordEncoding = "iso-8859-15" }), Is.EqualTo("iso-8859-15")); } \ No newline at end of file From 144c1b65262f4186205bb775b5c4e89c2e46f920 Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 09:49:04 +0100 Subject: [PATCH 08/15] Added the choice of the password encoding to the mailbox dialog --- .../Dialogs/DataSourceMailboxDialog.razor | 24 ++++++ .../Dialogs/DataSourceMailboxDialog.razor.cs | 78 +++++++++++++++---- app/MindWork AI Studio/Tools/AppIcons.cs | 3 + .../Tools/Mail/ImapMailboxConnector.cs | 2 +- .../Tools/Mail/MailServerPolicy.cs | 10 ++- .../MailboxConnectionFailureExtensions.cs | 2 +- .../Tools/Mail/MailboxPasswordEncodings.cs | 67 ++++++++++++++++ .../Mail/MailboxPasswordEncodingsTests.cs | 21 +++++ 8 files changed, 190 insertions(+), 17 deletions(-) diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor index 76a2bd32d..49ff1d149 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor @@ -222,6 +222,16 @@ } + + @* Not part of the source: the encoding only decides how the password travels, so it stays open once the mails are prepared. *@ + + @foreach (var passwordEncoding in MailboxPasswordEncodings.ALL) + { + + @passwordEncoding + + } + @@ -258,6 +268,20 @@ @this.TestResultText + @if (this.ShowsPasswordEncodingHint) + { + + + @string.Format(TA("Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account."), this.PasswordEncoding) + + @if (this.SuggestedPasswordEncoding is { } suggestedPasswordEncoding) + { + + @string.Format(T("Test again with {0}"), suggestedPasswordEncoding) + + } + + } diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index 84d795903..cfa5e443c 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -21,12 +21,13 @@ namespace AIStudio.Dialogs; /// /// /// Every connection test is exactly one sign-in, started by the user, in the encoding which -/// MailServerPolicy.GetPasswordEncoding decides on, like every other sign-in. The encoding of a -/// successful test is stored along with the mailbox. The outcome of a test only touches -/// the recorded sign-in failure of the mailbox when the test used the settings and the password stored -/// for it: a failure with a password the user is still typing says nothing about the stored one, and -/// neither does a success. A success in another encoding clears the failure only once the mailbox is -/// saved with it, since the synchronization would sign in with the stored encoding until then. +/// MailServerPolicy.GetPasswordEncoding decides on, like every other sign-in. AI Studio never tries +/// another encoding on its own: after a refused sign-in, it offers one, cf. SuggestedPasswordEncoding, +/// and the user decides. The encoding of a successful test is stored along with the mailbox.

+/// The outcome of a test only touches the recorded sign-in failure of the mailbox when the test used +/// the settings, the encoding, and the password stored for it: a failure with a password the user is +/// still typing says nothing about the stored one, and neither does a success. A success in another +/// encoding clears the failure once the mailbox is saved with it, cf. Store. ///
public partial class DataSourceMailboxDialog : MSGComponentBase { @@ -120,6 +121,9 @@ public partial class DataSourceMailboxDialog : MSGComponentBase private IReadOnlyList serverFolders = []; private string folderIssue = string.Empty; + // The language of the operating system, which tells the encoding to offer after a refused sign-in, cf. MailboxPasswordEncodings.Suggest: + private string osLanguage = string.Empty; + // We get the form reference from Blazor code to validate it manually: private MudForm form = null!; @@ -200,6 +204,7 @@ protected override async Task OnInitializedAsync() } this.ApplyOrganizationRules(); + this.osLanguage = await this.RustService.ReadUserLanguage(); await base.OnInitializedAsync(); @@ -248,13 +253,41 @@ protected override async Task OnAfterRenderAsync(bool firstRender) #endregion /// - /// What a connection test depends on. A test only counts for the settings it was made with. + /// What a connection test depends on. A test only counts for the settings it was made with. The + /// encoding is the one the sign-in uses, cf. MailServerPolicy.GetPasswordEncoding. /// - private readonly record struct ConnectionSettings(string Host, int Port, MailboxTransportSecurity TransportSecurity, string Username, string Password); + private readonly record struct ConnectionSettings(string Host, int Port, MailboxTransportSecurity TransportSecurity, string Username, string Password, string PasswordEncoding); + + private ConnectionSettings CurrentSettings => new(this.dataHost.Trim(), this.dataPort, this.dataTransportSecurity, this.dataUsername.Trim(), this.dataPassword, this.PasswordEncoding); - private ConnectionSettings CurrentSettings => new(this.dataHost.Trim(), this.dataPort, this.dataTransportSecurity, this.dataUsername.Trim(), this.dataPassword); + private ConnectionSettings StoredSettings => new(this.DataSource.Host.Trim(), this.DataSource.Port, this.DataSource.TransportSecurity, this.DataSource.Username.Trim(), this.storedPassword, this.mailServerPolicy.GetPasswordEncoding(this.DataSource)); - private ConnectionSettings StoredSettings => new(this.DataSource.Host.Trim(), this.DataSource.Port, this.DataSource.TransportSecurity, this.DataSource.Username.Trim(), this.storedPassword); + /// + /// The encoding the next sign-in uses: the one the organization names for the server, if any, and the chosen one otherwise. + /// + private string PasswordEncoding => this.mailServerPolicy.GetPasswordEncoding(this.dataHost.Trim(), this.dataPasswordEncoding); + + /// + /// Whether the organization names the encoding for the server, so that the user cannot choose another one. + /// + private bool IsPasswordEncodingSetByOrganization => this.mailServerPolicy.GetOrganizationPasswordEncoding(this.dataHost.Trim()) is not null; + + private string PasswordEncodingHelperText => this.IsPasswordEncodingSetByOrganization ? TA("Your organization sets the encoding for this mail server.") : string.Empty; + + /// + /// Whether the last test failed because the server refused a username or a password with + /// characters beyond ASCII, which may be the encoding's fault. Not when the organization names + /// the encoding: then it is not the user's to choose. + /// + private bool ShowsPasswordEncodingHint => this.testedSettings == this.CurrentSettings + && this.testFailure is MailboxConnectionFailure.AUTHENTICATION_FAILED + && !this.IsPasswordEncodingSetByOrganization + && MailboxPasswordEncodings.DependsOnEncoding(this.dataUsername.Trim(), this.dataPassword); + + /// + /// The encoding to offer for one more test, cf. MailboxPasswordEncodings.Suggest, or null for none. + /// + private string? SuggestedPasswordEncoding => MailboxPasswordEncodings.Suggest(this.osLanguage, this.PasswordEncoding, this.dataUsername.Trim(), this.dataPassword); /// /// Whether the settings to connect with are the ones stored for this mailbox. @@ -505,6 +538,26 @@ private void SelectTransportSecurity(MailboxTransportSecurity transportSecurity) this.dataTransportSecurity = transportSecurity; } + private void SelectPasswordEncoding(string? passwordEncoding) + { + // The select hands over null only when cleared, which it does not allow: + if (passwordEncoding is not null) + this.dataPasswordEncoding = passwordEncoding; + } + + /// + /// Tests the connection once more, in the encoding SuggestedPasswordEncoding offers. Like every + /// test, it is exactly one sign-in, and only the user starts it. + /// + private async Task TestWithSuggestedPasswordEncoding() + { + if (this.SuggestedPasswordEncoding is not { } suggestedPasswordEncoding) + return; + + this.dataPasswordEncoding = suggestedPasswordEncoding; + await this.TestConnection(); + } + private async Task TestConnection() { if (!this.CanTestConnection) @@ -611,10 +664,7 @@ private async Task RecordSignInOutcomeAsync(ConnectionSettings settings, Mailbox switch (failure) { case null: - // In another encoding, the failure stays on record until the mailbox is saved, cf. Store: - if (this.dataPasswordEncoding == this.DataSource.PasswordEncoding) - await indexStore.ClearMailboxAuthFailureAsync(this.dataId, CancellationToken.None); - + await indexStore.ClearMailboxAuthFailureAsync(this.dataId, CancellationToken.None); this.authFailure = null; break; diff --git a/app/MindWork AI Studio/Tools/AppIcons.cs b/app/MindWork AI Studio/Tools/AppIcons.cs index 2f1cbef59..cf406e9a0 100644 --- a/app/MindWork AI Studio/Tools/AppIcons.cs +++ b/app/MindWork AI Studio/Tools/AppIcons.cs @@ -827,6 +827,9 @@ public static class AppIcons /// Marks the check of which retrieved passages fit the question. public const string PASSAGE_RELEVANCE_CHECK = LucideIcons.LIST_CHECKS; + /// Marks the encoding in which a username and a password travel, such as when signing in to a mailbox. + public const string PASSWORD_ENCODING = LucideIcons.BINARY; + /// Marks the component that reads PDF files, such as the PDFium version on the information page. public const string PDF_READER = LucideIcons.FILE_SCAN; diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index c1e4ea338..cf1011480 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -517,7 +517,7 @@ internal static bool TryPrepareSignIn(Encoding encoding, string username, string if (!MailboxPasswordEncodings.TryPrepare(encoding, username, out preparedUsername) || !MailboxPasswordEncodings.TryPrepare(encoding, password, out preparedPassword)) return false; - return offersPlain || MailboxPasswordEncodings.IsUtf8(encoding) || (Ascii.IsValid(preparedUsername) && Ascii.IsValid(preparedPassword)); + return offersPlain || MailboxPasswordEncodings.IsUtf8(encoding) || !MailboxPasswordEncodings.DependsOnEncoding(preparedUsername, preparedPassword); } /// diff --git a/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs b/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs index 889e25f4d..b732197fc 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs @@ -65,5 +65,13 @@ public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IR /// /// The mailbox. /// The name of the encoding. - public string GetPasswordEncoding(DataSourceMailbox mailbox) => this.GetOrganizationPasswordEncoding(mailbox.Host) ?? mailbox.PasswordEncoding; + public string GetPasswordEncoding(DataSourceMailbox mailbox) => this.GetPasswordEncoding(mailbox.Host, mailbox.PasswordEncoding); + + /// + /// The encoding in which a mailbox on a server sends its username and password, cf. GetPasswordEncoding of a mailbox. + /// + /// The host of the server. + /// The name of the encoding of the mailbox. + /// The name of the encoding. + public string GetPasswordEncoding(string host, string mailboxEncoding) => this.GetOrganizationPasswordEncoding(host) ?? mailboxEncoding; } \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailureExtensions.cs b/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailureExtensions.cs index 0742342bf..42b472a48 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailureExtensions.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailboxConnectionFailureExtensions.cs @@ -21,7 +21,7 @@ public static class MailboxConnectionFailureExtensions MailboxConnectionFailure.SERVER_ERROR => TA("The server reported an error. Please try again later."), MailboxConnectionFailure.INVALID_SETTINGS => TB("The settings of this mailbox are incomplete, or they were made by a newer version of AI Studio."), MailboxConnectionFailure.SERVER_NOT_ALLOWED => TA("Your organization allows mailboxes only on its own mail servers, and this server is none of them. AI Studio does not connect to it, and the AI does not read this mailbox."), - MailboxConnectionFailure.UNSUITABLE_ENCODING => TA("The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked."), + MailboxConnectionFailure.UNSUITABLE_ENCODING => TA("The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects."), _ => TB("The connection to the server failed for an unknown reason."), }; diff --git a/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs b/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs index 9ee779143..2688bc8df 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs @@ -1,4 +1,5 @@ using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Text; namespace AIStudio.Tools.Mail; @@ -93,6 +94,48 @@ public static bool TryGet(string? name, [NotNullWhen(true)] out Encoding? encodi } } + /// + /// Whether the bytes of a username and a password depend on the encoding: only characters beyond ASCII do. + /// + /// The username. + /// The password. + /// True when either holds a character beyond ASCII. + public static bool DependsOnEncoding(string username, string password) => !Ascii.IsValid(username) || !Ascii.IsValid(password); + + /// + /// The encoding to offer for one more connection test after the server refused a username or a + /// password with characters beyond ASCII. + /// + /// + /// A server which expects another encoding than UTF-8 mostly expects the code page of the Windows + /// system it runs on, and that is mostly the code page of the region its users live in: the ANSI + /// code page of Windows for the language of the operating system, e.g., windows-1252 for de-DE or + /// windows-1254 for tr-TR. When the test used that one already, UTF-8 comes next. An encoding which + /// lacks a character of the username or the password is never offered. It is only an offer: the + /// user decides, and every test is one attempt to sign in. + /// + /// The language of the operating system, e.g., "de-DE". + /// The name of the encoding the refused test used. + /// The username. + /// The password. + /// The name of the encoding, or null when there is none to offer. + public static string? Suggest(string localeTag, string testedEncoding, string username, string password) + { + if (!DependsOnEncoding(username, password)) + return null; + + foreach (var candidate in new[] { GetRegionalEncoding(localeTag), DEFAULT }) + { + if (candidate is null || string.Equals(candidate, testedEncoding, StringComparison.OrdinalIgnoreCase)) + continue; + + if (TryGet(candidate, out var encoding) && TryPrepare(encoding, username, out _) && TryPrepare(encoding, password, out _)) + return candidate; + } + + return null; + } + /// /// Whether an encoding is UTF-8, the only one the LOGIN command of the IMAP client sends. /// @@ -132,4 +175,28 @@ public static bool TryPrepare(Encoding encoding, string text, out string prepare return false; } } + + /// + /// The ANSI code page of Windows for a language, cf. Suggest. + /// + /// The language, e.g., "tr-TR". + /// The name of the code page, or null for an unknown language and for one without a code page of its own, such as Hindi. + private static string? GetRegionalEncoding(string localeTag) + { + if (string.IsNullOrWhiteSpace(localeTag)) + return null; + + try + { + var codePage = CultureInfo.GetCultureInfo(localeTag.Trim()).TextInfo.ANSICodePage; + return codePage is 0 ? null : Encoding.GetEncoding(codePage).WebName; + } + + // Thrown for a language .NET does not know, and for a code page it does not support. + // CultureNotFoundException is one of them: + catch (Exception e) when (e is ArgumentException or NotSupportedException) + { + return null; + } + } } \ No newline at end of file diff --git a/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs b/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs index dc2dd5424..8ff6259e4 100644 --- a/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs +++ b/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs @@ -172,6 +172,27 @@ public void Utf8TakesTheTextAsItIs() } } + [TestCase("de-DE", "utf-8", "müller", "Grüße-2026", ExpectedResult = "windows-1252")] + [TestCase("fr-FR", "utf-8", "someone", "Été-2026", ExpectedResult = "windows-1252")] + [TestCase("tr-TR", "utf-8", "kişi", "şifre-2026", ExpectedResult = "windows-1254")] + [TestCase("pl-PL", "utf-8", "someone", "Łódź-2026", ExpectedResult = "windows-1250")] + [TestCase("ru-RU", "utf-8", "someone", "пароль-2026", ExpectedResult = "windows-1251")] + [TestCase("ja-JP", "utf-8", "someone", "日本-2026", ExpectedResult = "shift_jis")] + [TestCase("de-DE", "windows-1252", "someone", "Grüße-2026", ExpectedResult = "utf-8")] + [TestCase("de-DE", "utf-8", "someone", "STRAẞE", ExpectedResult = null)] + [TestCase("de-DE", "utf-8", "someone", "Sommer-2026!", ExpectedResult = null)] + [TestCase("", "utf-8", "someone", "Grüße-2026", ExpectedResult = null)] + [TestCase("", "windows-1252", "someone", "Grüße-2026", ExpectedResult = "utf-8")] + public string? AfterARefusedSignInTheEncodingOfTheRegionIsOffered(string localeTag, string testedEncoding, string username, string password) + { + return MailboxPasswordEncodings.Suggest(localeTag, testedEncoding, username, password); + } + + [TestCase("someone", "Sommer-2026!", ExpectedResult = false)] + [TestCase("müller", "Sommer-2026!", ExpectedResult = true)] + [TestCase("someone", "日本", ExpectedResult = true)] + public bool OnlyCharactersBeyondAsciiDependOnTheEncoding(string username, string password) => MailboxPasswordEncodings.DependsOnEncoding(username, password); + /// /// The encoding of a name which a mailbox may use; fails the test for any other name. /// From e511c498cafc0c51a28029693eecf2142b544c6c Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 09:51:43 +0100 Subject: [PATCH 09/15] Added tests for passwords beyond ASCII on their way through the secret store --- app/Tests/Tools/EncryptionTests.cs | 13 +++++- .../Mail/MailboxPasswordEncodingsTests.cs | 19 ++++++++ runtime/src/encryption.rs | 43 +++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) diff --git a/app/Tests/Tools/EncryptionTests.cs b/app/Tests/Tools/EncryptionTests.cs index 28d73486a..a7e8c0ca6 100644 --- a/app/Tests/Tools/EncryptionTests.cs +++ b/app/Tests/Tools/EncryptionTests.cs @@ -23,7 +23,10 @@ public sealed class EncryptionTests private static readonly byte[] SECRET_KEY_SALT = Enumerable.Range(0xA0, 16).Select(index => (byte)index).ToArray(); - private static async Task CreateEncryptionAsync() + /// + /// The encryption with the password and the salt of these tests, which the tests of the runtime use as well. + /// + internal static async Task CreateEncryptionAsync() { var encryption = new Encryption(NullLogger.Instance, SECRET_PASSWORD, SECRET_KEY_SALT); await encryption.Initialize(); @@ -33,6 +36,7 @@ private static async Task CreateEncryptionAsync() [TestCase("oKGio6SlpqeoqaqrrK2ur3lNRzNAfoSYKyC70CpjwS8=", "", TestName = "An empty text")] [TestCase("oKGio6SlpqeoqaqrrK2urwUfAfn5LbbIjbOC9nSvtUU=", "sk-imported-key", TestName = "A text within one block")] [TestCase("oKGio6SlpqeoqaqrrK2urwbjgbJCNk6Zw1Z9HyIiJdZJ+E7czzLYlM/undXUIsDr", "Schlüssel für Größe 🔑", TestName = "A text beyond ASCII")] + [TestCase("oKGio6SlpqeoqaqrrK2ur3BiwUyVT93sLAJFWcOIdZt7LL+HTABMxQmvnRNB/L1fvXrfJEBKdaufFaHZj+sLnQ==", "şifre-Łódź-пароль-日本-한글", TestName = "A text in several scripts")] public async Task TheAppEncryptsLikeTheRuntime(string expectedEncryptedValue, string text) { var encryption = await CreateEncryptionAsync(); @@ -44,6 +48,13 @@ public async Task TheAppEncryptsLikeTheRuntime(string expectedEncryptedValue, st [TestCase("oKGio6SlpqeoqaqrrK2ur3lNRzNAfoSYKyC70CpjwS8=", "", TestName = "An empty encrypted text")] [TestCase("oKGio6SlpqeoqaqrrK2urwUfAfn5LbbIjbOC9nSvtUU=", "sk-imported-key", TestName = "An encrypted text within one block")] [TestCase("oKGio6SlpqeoqaqrrK2urwbjgbJCNk6Zw1Z9HyIiJdZJ+E7czzLYlM/undXUIsDr", "Schlüssel für Größe 🔑", TestName = "An encrypted text beyond ASCII")] + [TestCase("oKGio6SlpqeoqaqrrK2ur3BiwUyVT93sLAJFWcOIdZt7LL+HTABMxQmvnRNB/L1fvXrfJEBKdaufFaHZj+sLnQ==", "şifre-Łódź-пароль-日本-한글", TestName = "An encrypted text in several scripts")] + + // The runtime encodes the salt and the encrypted text one after the other, so the salt keeps its + // padding, cf. encrypts_text_beyond_ascii_for_the_app in runtime/src/encryption.rs. This is how + // a secret from the OS keyring arrives: + [TestCase("oKGio6SlpqeoqaqrrK2urw==BuOBskI2TpnDVn0fIiIl1kn4TtzPMtiUz+6d1dQiwOs=", "Schlüssel für Größe 🔑", TestName = "A text beyond ASCII as the runtime encrypts it")] + [TestCase("oKGio6SlpqeoqaqrrK2urw==cGLBTJVP3ewsAkVZw4h1m3ssv4dMAEzFCa+dE0H8vV+9et8kQEp1q58VodmP6wud", "şifre-Łódź-пароль-日本-한글", TestName = "A text in several scripts as the runtime encrypts it")] public async Task TheAppDecryptsWhatTheRuntimeEncrypted(string encryptedValue, string expectedText) { var encryption = await CreateEncryptionAsync(); diff --git a/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs b/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs index 8ff6259e4..0a85d93a4 100644 --- a/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs +++ b/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs @@ -1,5 +1,6 @@ using System.Text; +using AIStudio.Tools; using AIStudio.Tools.Mail; using MailKit.Security; @@ -172,6 +173,24 @@ public void Utf8TakesTheTextAsItIs() } } + [Test] + public async Task APasswordFromTheSecretStoreBecomesTheBytesOfTheChosenEncoding() + { + // + // The runtime reads the password from the OS keyring and hands it over encrypted, as here. + // Only the keyring itself is left out: it takes and returns the text as Unicode. Wherever + // the password was stored, it arrives as text, and only signing in turns it into bytes: + // + var encryption = await EncryptionTests.CreateEncryptionAsync(); + var password = await encryption.Decrypt(new EncryptedText("oKGio6SlpqeoqaqrrK2urw==0NrfOsjWs3R9d/zzOA5Mvw==")); + using (Assert.EnterMultipleScope()) + { + Assert.That(password, Is.EqualTo("Grüße-100€")); + Assert.That(GetPlainPasswordBytes("windows-1252", password), Is.EqualTo("47 72 FC DF 65 2D 31 30 30 80")); + Assert.That(GetPlainPasswordBytes(MailboxPasswordEncodings.DEFAULT, password), Is.EqualTo("47 72 C3 BC C3 9F 65 2D 31 30 30 E2 82 AC")); + } + } + [TestCase("de-DE", "utf-8", "müller", "Grüße-2026", ExpectedResult = "windows-1252")] [TestCase("fr-FR", "utf-8", "someone", "Été-2026", ExpectedResult = "windows-1252")] [TestCase("tr-TR", "utf-8", "kişi", "şifre-2026", ExpectedResult = "windows-1254")] diff --git a/runtime/src/encryption.rs b/runtime/src/encryption.rs index 22e58806e..5ba778614 100644 --- a/runtime/src/encryption.rs +++ b/runtime/src/encryption.rs @@ -164,4 +164,47 @@ impl fmt::Display for EncryptedText { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "**********") } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Creates the encryption with the same password and salt as `EncryptionTests` in `app/Tests`, + /// so that both sides check the same values. The expected values were computed independently, + /// with PBKDF2 of Python and AES of OpenSSL. + fn create_encryption() -> Encryption { + let password: Vec = (0..512u32).map(|index| (index % 256) as u8).collect(); + let salt: Vec = (0xA0..0xB0u8).collect(); + Encryption::new(&password, &salt).expect("the password and the salt of the test are valid") + } + + /// Secrets such as passwords reach the OS keyring through here, encrypted by the app. Characters + /// beyond ASCII, of any script, must arrive as they were typed. + #[test] + fn decrypts_text_beyond_ascii_which_the_app_encrypted() { + let encryption = create_encryption(); + for (encrypted, expected) in [ + ("oKGio6SlpqeoqaqrrK2urwbjgbJCNk6Zw1Z9HyIiJdZJ+E7czzLYlM/undXUIsDr", "Schlüssel für Größe 🔑"), + ("oKGio6SlpqeoqaqrrK2ur3BiwUyVT93sLAJFWcOIdZt7LL+HTABMxQmvnRNB/L1fvXrfJEBKdaufFaHZj+sLnQ==", "şifre-Łódź-пароль-日本-한글"), + ] { + let decrypted = encryption.decrypt(&EncryptedText::new(encrypted.to_string())); + assert_eq!(decrypted.as_deref(), Ok(expected)); + } + } + + /// Secrets read from the OS keyring leave through here, for the app to decrypt, which + /// `TheAppDecryptsWhatTheRuntimeEncrypted` in `EncryptionTests` checks with the same values. The + /// salt and the encrypted text are encoded one after the other, so the salt keeps its padding. + #[test] + fn encrypts_text_beyond_ascii_for_the_app() { + let encryption = create_encryption(); + for (text, expected) in [ + ("Schlüssel für Größe 🔑", "oKGio6SlpqeoqaqrrK2urw==BuOBskI2TpnDVn0fIiIl1kn4TtzPMtiUz+6d1dQiwOs="), + ("şifre-Łódź-пароль-日本-한글", "oKGio6SlpqeoqaqrrK2urw==cGLBTJVP3ewsAkVZw4h1m3ssv4dMAEzFCa+dE0H8vV+9et8kQEp1q58VodmP6wud"), + ] { + let encrypted = encryption.encrypt(text).expect("encrypting a text works"); + assert_eq!(encrypted.get_encrypted(), expected); + } + } } \ No newline at end of file From 5642a7c9f7106dfe8fa907924df4e69a2b99d3b4 Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 09:52:03 +0100 Subject: [PATCH 10/15] Improved the changelog entries of the password encoding --- app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md index 683620562..93e30d25d 100644 --- a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md +++ b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md @@ -9,7 +9,7 @@ - Added the Model Comparison assistant, which shows you which of two models helps you better. You compare them blindly, without knowing which model wrote which answer: with the same request sent to both, or while you work on your own tasks over days or weeks. Charts show you which model wins, and a judge model can give you a second opinion based on your own expectations. You find the assistant in the category "General". Thanks, Dominic Neuburg (`donework`), for this contribution. - Added the minimum confidence of the provider for each AI task, such as the data source selection or the security audit of assistant plugins, to configuration plugins, so that organizations can preset or lock it. - Added the settings of the text content cleaner to configuration plugins, so that organizations can preset or lock which model cleans web content. -- Added the password encoding to the mail servers which organizations offer through configuration plugins. When a username or password contains German special characters, such as umlauts, mail servers like Microsoft Exchange expect them in another encoding than most others. With this setting, the connection test of a mailbox tries the encoding of your organization first, so that you spend no failed sign-in on the other one. +- Added the password encoding to the mail servers which organizations offer through configuration plugins. Depending on its configuration, a mail server may expect usernames and passwords with characters beyond ASCII in another encoding than UTF-8. With this setting, every mailbox on such a server signs in with the encoding your organization names. - Improved how well the AI remembers what it looked up in a chat: for its earlier answers, it now knows which web pages it read, which searches it ran, and which sources it used. When you ask a follow-up question, it can read the page again instead of claiming that it never read it. - Improved follow-up questions about web pages which a tool found, such as the results of a web search: the Read Web Page tool may read these pages again later in the same chat, also after you restart AI Studio and also when it may otherwise read only addresses which stand in the chat. - Improved the texts of AI Studio: we corrected grammar mistakes, missing words, and punctuation in many English texts and improved the wording of some German ones. A few texts which every language showed in English are now translated as well. @@ -37,7 +37,7 @@ - Fixed the settings of the security audit for assistant plugins, which you could change even when your organization had locked them through a configuration plugin. They now show the lock, like all other settings your organization manages. - Fixed the automatic security audit of assistant plugins when no model was set for it: you got two error messages for each plugin, again whenever you opened the assistants or plugins page. Now AI Studio tells you once, and the settings of the security audit show a warning. - Fixed the AI-based data validation of classic RAG, which kept passages that the AI had judged as not fitting your question. Now the AI only gets the passages that fit. When the check fails for a passage, AI Studio keeps it, and when it fails for all of them, AI Studio tells you. -- Fixed signing in to a mailbox when your username or password contains German special characters, such as ä, ö, ü, ß, §, or €. Some mail servers, Microsoft Exchange among them, expect these characters in another encoding than most others. When you test the connection of a mailbox, AI Studio now finds out which encoding your mail server expects and keeps it when you save the mailbox. If signing in to one of your mailboxes failed for this reason, open the settings of that mailbox, test the connection, and save it. +- Fixed signing in to a mailbox when your username or password contains characters beyond ASCII, such as umlauts, accents, or Asian characters. Depending on its configuration, a mail server may expect them in another encoding than UTF-8. You can now choose the encoding in the server details of the mailbox, and after a failed sign-in, AI Studio offers to test the connection once more with the encoding common in your region. - Upgraded several libraries to improve security. - Upgraded Tauri to v2.12.7. - Upgraded PDFium to v158.0.8125.0. From 665f2ee866fa81cf6adc15d2b66b382175c082a4 Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 09:52:15 +0100 Subject: [PATCH 11/15] Improved the agent instructions on text beyond ASCII --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 91fd82f77..81dbc3ba7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -199,7 +199,7 @@ again yourself when `metadata.txt` changes during the session, e.g., after a mer - **No automated formatting for Rust or .NET files** - Never run automated formatters on Rust files (`.rs`) or .NET files (`.cs`, `.razor`, `.csproj`, etc.). Only make the minimal manual formatting changes required for the specific edit. - **Spaces in paths** - Always quote paths with spaces in bash commands - **Compatibility shims** - Temporary fallback or read-repair code must be documented in `documentation/compatibility-shims/` with an introduced date, remove-after date, code references, and removal checklist. Add a short code comment near the shim that references the document and remove-after date. Check this folder before adding similar fallback logic, and do not extend expired shims without explicit maintainer direction. Do not use this process for permanent settings schema migrations; those belong in `app/MindWork AI Studio/Settings/SettingsMigrations.cs`. -- **German special characters** - Many users of AI Studio write German, so never assume that a text is ASCII. Keep the German special characters in mind wherever text leaves or enters the app as bytes, e.g., passwords and usernames, file and folder names, mail folders and headers, URLs, CSV, command lines, and network protocols: `ä ö ü Ä Ö Ü ß ẞ`, and the characters of a German keyboard and German typography, `§ ° ´ µ ² ³ € „ “ ‚ ‘ – …`. Check which encoding the other side expects: in UTF-8, each of them takes two or three bytes; Windows-1252 and Latin-1 take one byte for most of them, Latin-1 lacks `€ „ “ ‚ ‘ – …`, and both lack `ẞ`. Check the Unicode normalization as well: the same `ä` arrives as one code point (NFC) or as `a` with a combining diaeresis (NFD), e.g., in file names from macOS. Include such characters in the tests of this code. +- **Text beyond ASCII** - Users of AI Studio write in many languages and scripts, so never assume that a text is ASCII, nor that it fits one particular code page. Wherever text leaves or enters the app as bytes, e.g., passwords and usernames, file and folder names, mail folders and headers, URLs, CSV, command lines, and network protocols, check which encoding the other side expects. In UTF-8, a character beyond ASCII takes two to four bytes; a code page such as Windows-1252, Windows-1254, or Shift-JIS takes other bytes and lacks most characters of other scripts, e.g., Windows-1252 has no `ş` and no `ẞ`. Use the `Encoding` of .NET with an exception fallback, never one which silently replaces a missing character with `?`. Check the Unicode normalization as well: the same `ä` arrives as one code point (NFC) or as `a` with a combining diaeresis (NFD), e.g., in file names from macOS. Include characters of several scripts in the tests of such code, e.g., `ä ß € é ø ş ł ж 日本 한`, and a decomposed `ä`. ## Wiki From c4e8368d3c4dcaef74e2c02a6f725125ce5a05e2 Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 10:25:30 +0100 Subject: [PATCH 12/15] Fixed a missing space in the sign-in check of mailboxes --- app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index cf1011480..599e35938 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -119,7 +119,7 @@ static ImapMailboxConnector() /// The connection or the sign-in failed. public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, CancellationToken token) { - if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || !MailboxPasswordEncodings.TryGet(policy.GetPasswordEncoding(mailbox), out var textEncoding) ||!MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) + if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || !MailboxPasswordEncodings.TryGet(policy.GetPasswordEncoding(mailbox), out var textEncoding) || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The mailbox settings are incomplete, or this version of AI Studio does not know them."); if (!policy.IsAllowed(mailbox.Host)) From aa2deddb069f29532193b8417b60a21a1afd78dc Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 10:31:46 +0100 Subject: [PATCH 13/15] Added the translations of the password encoding of mailboxes --- .../Assistants/I18N/allTexts.lua | 24 +++++++++++++++++++ .../plugin.lua | 24 +++++++++++++++++++ .../plugin.lua | 24 +++++++++++++++++++ 3 files changed, 72 insertions(+) diff --git a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua index 938944993..e17a3eadf 100644 --- a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua +++ b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua @@ -13801,6 +13801,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1836253938"] = "Se -- Update UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1847791252"] = "Update" +-- Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1885860334"] = "Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account." + +-- Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1885860334::INFORMAL"] = "Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account." + -- Sign-in UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1936191160"] = "Sign-in" @@ -13960,15 +13966,27 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3362621909"] = "Sh -- Hide Server Details UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3516057682"] = "Hide Server Details" +-- Encoding of username and password +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3611739483"] = "Encoding of username and password" + -- Port UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3804576966"] = "Port" +-- Test again with {0} +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4041320769"] = "Test again with {0}" + -- Not tested yet. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T417002657"] = "Not tested yet." -- Yes, also index the sent mails and the drafts UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4209023132"] = "Yes, also index the sent mails and the drafts" +-- Your organization sets the encoding for this mail server. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4269875433"] = "Your organization sets the encoding for this mail server." + +-- Your organization sets the encoding for this mail server. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4269875433::INFORMAL"] = "Your organization sets the encoding for this mail server." + -- Username UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T470340825"] = "Username" @@ -21397,6 +21415,12 @@ UI_TEXT_CONTENT["AISTUDIO::TOOLS::FILENAMEPATTERNS::T495100949"] = "Please use o -- Please use only single asterisks as wildcards, e.g., *.txt or report-*.md. UI_TEXT_CONTENT["AISTUDIO::TOOLS::FILENAMEPATTERNS::T495100949::INFORMAL"] = "Please use only single asterisks as wildcards, e.g., *.txt or report-*.md." +-- The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1203063005"] = "The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects." + +-- The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1203063005::INFORMAL"] = "The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects." + -- The server could not be reached. Please check the host and the port, and whether you need a VPN connection. UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1314233926"] = "The server could not be reached. Please check the host and the port, and whether you need a VPN connection." diff --git a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua index 8e9a4c6ce..6df089cbb 100644 --- a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua +++ b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua @@ -13803,6 +13803,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1836253938"] = "Se -- Update UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1847791252"] = "Aktualisieren" +-- Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1885860334"] = "Ihr Benutzername oder Ihr Passwort enthält Zeichen außerhalb des ASCII-Zeichensatzes, etwa Umlaute oder Buchstaben mit Akzent. Je nach Konfiguration erwartet ein Mailserver diese möglicherweise in einer anderen Zeichenkodierung als {0}, die dieser Test verwendet hat. Fragen Sie in Ihrer IT-Abteilung nach, welche Zeichenkodierung der Server erwartet, und wählen Sie diese in den Servereinstellungen aus. Jeder Test entspricht einem Anmeldeversuch. Zu viele fehlgeschlagene Versuche können dazu führen, dass Ihr Konto gesperrt wird." + +-- Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1885860334::INFORMAL"] = "Dein Benutzername oder dein Passwort enthält Zeichen außerhalb des ASCII-Zeichensatzes, etwa Umlaute oder Buchstaben mit Akzent. Je nach Konfiguration erwartet ein Mailserver diese möglicherweise in einer anderen Zeichenkodierung als {0}, die dieser Test verwendet hat. Frag in deiner IT-Abteilung nach, welche Zeichenkodierung der Server erwartet, und wähle diese in den Servereinstellungen aus. Jeder Test entspricht einem Anmeldeversuch. Zu viele fehlgeschlagene Versuche können dazu führen, dass dein Konto gesperrt wird." + -- Sign-in UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1936191160"] = "Anmeldung" @@ -13962,15 +13968,27 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3362621909"] = "Se -- Hide Server Details UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3516057682"] = "Servereinstellungen ausblenden" +-- Encoding of username and password +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3611739483"] = "Zeichenkodierung von Benutzername und Passwort" + -- Port UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3804576966"] = "Port" +-- Test again with {0} +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4041320769"] = "Mit {0} erneut testen" + -- Not tested yet. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T417002657"] = "Noch nicht getestet." -- Yes, also index the sent mails and the drafts UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4209023132"] = "Ja, auch die gesendeten E-Mails und die Entwürfe indexieren" +-- Your organization sets the encoding for this mail server. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4269875433"] = "Ihre Organisation legt die Zeichenkodierung für diesen Mailserver fest." + +-- Your organization sets the encoding for this mail server. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4269875433::INFORMAL"] = "Deine Organisation legt die Zeichenkodierung für diesen Mailserver fest." + -- Username UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T470340825"] = "Benutzername" @@ -21399,6 +21417,12 @@ UI_TEXT_CONTENT["AISTUDIO::TOOLS::FILENAMEPATTERNS::T495100949"] = "Bitte verwen -- Please use only single asterisks as wildcards, e.g., *.txt or report-*.md. UI_TEXT_CONTENT["AISTUDIO::TOOLS::FILENAMEPATTERNS::T495100949::INFORMAL"] = "Bitte verwende als Platzhalter nur einzelne Sternchen, z. B. *.txt oder report-*.md." +-- The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1203063005"] = "Die ausgewählte Zeichenkodierung kann Ihren Benutzernamen oder Ihr Passwort nicht an diesen Server übertragen: Sie unterstützt mindestens eines der darin enthaltenen Zeichen nicht, oder der Server akzeptiert ausschließlich UTF-8. AI Studio hat deshalb keinen Anmeldeversuch unternommen, damit Ihr Konto nicht gesperrt wird. Wählen Sie in den Servereinstellungen des Postfachs eine andere Zeichenkodierung aus, oder fragen Sie Ihre IT-Abteilung, welche Zeichenkodierung der Server erwartet." + +-- The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1203063005::INFORMAL"] = "Die ausgewählte Zeichenkodierung kann deinen Benutzernamen oder dein Passwort nicht an diesen Server übertragen: Sie unterstützt mindestens eines der darin enthaltenen Zeichen nicht, oder der Server akzeptiert ausschließlich UTF-8. AI Studio hat deshalb keinen Anmeldeversuch unternommen, damit dein Konto nicht gesperrt wird. Wähle in den Servereinstellungen des Postfachs eine andere Zeichenkodierung aus, oder frag deine IT-Abteilung, welche Zeichenkodierung der Server erwartet." + -- The server could not be reached. Please check the host and the port, and whether you need a VPN connection. UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1314233926"] = "Der Server konnte nicht erreicht werden. Bitte prüfen Sie Host und Port und ob Sie eine VPN-Verbindung benötigen." diff --git a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua index f10e29773..f6ec1d5cd 100644 --- a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua +++ b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua @@ -13803,6 +13803,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1836253938"] = "Se -- Update UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1847791252"] = "Update" +-- Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1885860334"] = "Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account." + +-- Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1885860334::INFORMAL"] = "Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account." + -- Sign-in UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T1936191160"] = "Sign-in" @@ -13962,15 +13968,27 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3362621909"] = "Sh -- Hide Server Details UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3516057682"] = "Hide Server Details" +-- Encoding of username and password +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3611739483"] = "Encoding of username and password" + -- Port UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T3804576966"] = "Port" +-- Test again with {0} +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4041320769"] = "Test again with {0}" + -- Not tested yet. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T417002657"] = "Not tested yet." -- Yes, also index the sent mails and the drafts UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4209023132"] = "Yes, also index the sent mails and the drafts" +-- Your organization sets the encoding for this mail server. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4269875433"] = "Your organization sets the encoding for this mail server." + +-- Your organization sets the encoding for this mail server. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T4269875433::INFORMAL"] = "Your organization sets the encoding for this mail server." + -- Username UI_TEXT_CONTENT["AISTUDIO::DIALOGS::DATASOURCEMAILBOXDIALOG::T470340825"] = "Username" @@ -21399,6 +21417,12 @@ UI_TEXT_CONTENT["AISTUDIO::TOOLS::FILENAMEPATTERNS::T495100949"] = "Please use o -- Please use only single asterisks as wildcards, e.g., *.txt or report-*.md. UI_TEXT_CONTENT["AISTUDIO::TOOLS::FILENAMEPATTERNS::T495100949::INFORMAL"] = "Please use only single asterisks as wildcards, e.g., *.txt or report-*.md." +-- The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1203063005"] = "The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects." + +-- The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1203063005::INFORMAL"] = "The chosen encoding cannot carry your username or your password to this server: it lacks one of their characters, or the server accepts no other encoding than UTF-8. AI Studio did not try to sign in, so that your account is not locked. Choose another encoding in the server details of the mailbox, or ask your IT department which one the server expects." + -- The server could not be reached. Please check the host and the port, and whether you need a VPN connection. UI_TEXT_CONTENT["AISTUDIO::TOOLS::MAIL::MAILBOXCONNECTIONFAILUREEXTENSIONS::T1314233926"] = "The server could not be reached. Please check the host and the port, and whether you need a VPN connection." From 5a1809a3a77003d415254dbc19ca1e9e423cff08 Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 15:31:06 +0100 Subject: [PATCH 14/15] Removed the encoding hint for the mail servers of well-known providers --- .../Dialogs/DataSourceMailboxDialog.razor.cs | 9 ++++++--- .../Tools/Mail/MailboxProviderTemplates.cs | 10 ++++++++++ app/Tests/Tools/Mail/MailboxProviderTemplatesTests.cs | 11 +++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index cfa5e443c..f8722c2ae 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -23,7 +23,7 @@ namespace AIStudio.Dialogs; /// Every connection test is exactly one sign-in, started by the user, in the encoding which /// MailServerPolicy.GetPasswordEncoding decides on, like every other sign-in. AI Studio never tries /// another encoding on its own: after a refused sign-in, it offers one, cf. SuggestedPasswordEncoding, -/// and the user decides. The encoding of a successful test is stored along with the mailbox.

+/// and the user decides. It offers none on the server of a well-known provider, cf. ShowsPasswordEncodingHint. The encoding of a successful test is stored along with the mailbox.

/// The outcome of a test only touches the recorded sign-in failure of the mailbox when the test used /// the settings, the encoding, and the password stored for it: a failure with a password the user is /// still typing says nothing about the stored one, and neither does a success. A success in another @@ -188,7 +188,7 @@ protected override async Task OnInitializedAsync() this.dataConfidenceLevel = this.DataSource.ConfidenceLevel; // A mail server of the organization goes first, see FitProviderSelection: - this.selectedTemplate = MailboxProviderTemplates.ALL.FirstOrDefault(template => template.Host.Length > 0 && template.Host.Equals(this.DataSource.Host.Trim(), StringComparison.OrdinalIgnoreCase)); + this.selectedTemplate = MailboxProviderTemplates.FindByHost(this.DataSource.Host); var requestedSecret = await this.RustService.GetSecret(this.DataSource, SecretStoreType.DATA_SOURCE, isTrying: true); if (requestedSecret.Success) @@ -277,11 +277,14 @@ protected override async Task OnAfterRenderAsync(bool firstRender) /// /// Whether the last test failed because the server refused a username or a password with /// characters beyond ASCII, which may be the encoding's fault. Not when the organization names - /// the encoding: then it is not the user's to choose. + /// the encoding: then it is not the user's to choose. Nor on the server of a well-known provider, + /// also when the user typed its host: there is no IT department to ask, and the server serves + /// users of every language rather than one region. /// private bool ShowsPasswordEncodingHint => this.testedSettings == this.CurrentSettings && this.testFailure is MailboxConnectionFailure.AUTHENTICATION_FAILED && !this.IsPasswordEncodingSetByOrganization + && MailboxProviderTemplates.FindByHost(this.dataHost) is null && MailboxPasswordEncodings.DependsOnEncoding(this.dataUsername.Trim(), this.dataPassword); /// diff --git a/app/MindWork AI Studio/Tools/Mail/MailboxProviderTemplates.cs b/app/MindWork AI Studio/Tools/Mail/MailboxProviderTemplates.cs index 6852bf3aa..c617e6c10 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailboxProviderTemplates.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailboxProviderTemplates.cs @@ -41,4 +41,14 @@ public static class MailboxProviderTemplates // Every organization runs a server of its own, and IMAP ships switched off: new("Microsoft Exchange Server", string.Empty, IMAPS_PORT, MailboxTransportSecurity.SSL_ON_CONNECT, MailboxUsernameFormat.DOMAIN_ACCOUNT, MailboxProviderRequirements.ADMIN_ACTIVATION, "https://learn.microsoft.com/en-us/exchange/clients/pop3-and-imap4/configure-imap4", string.Empty), ]; + + /// + /// Finds the well-known provider whose server a host names, however the host was written. + /// + /// + /// Microsoft Exchange Server never matches: every organization runs a server of its own. + /// + /// The host of a mailbox. + /// The provider, or null when the host belongs to none of them. + public static MailboxProviderTemplate? FindByHost(string host) => ALL.FirstOrDefault(template => template.Host.Length > 0 && MailServerHosts.AreSame(template.Host, host)); } \ No newline at end of file diff --git a/app/Tests/Tools/Mail/MailboxProviderTemplatesTests.cs b/app/Tests/Tools/Mail/MailboxProviderTemplatesTests.cs index 359dd80c5..3e2841c15 100644 --- a/app/Tests/Tools/Mail/MailboxProviderTemplatesTests.cs +++ b/app/Tests/Tools/Mail/MailboxProviderTemplatesTests.cs @@ -46,6 +46,17 @@ public void EveryProviderIsListedOnce() } } + [TestCase("imap.gmail.com", "Gmail")] + [TestCase(" IMAP.Mailbox.ORG. ", "mailbox.org")] + [TestCase("posteo.de", "Posteo")] + public void AHostFindsItsProvider(string host, string expectedName) => Assert.That(MailboxProviderTemplates.FindByHost(host)?.Name, Is.EqualTo(expectedName)); + + [TestCase("")] + [TestCase("exchange.intra.example.org")] + [TestCase("imap.gmail.com.example.org")] + [TestCase("not a host")] + public void AnotherHostFindsNoProvider(string host) => Assert.That(MailboxProviderTemplates.FindByHost(host), Is.Null); + [Test] public void EveryRequirementHasItsOwnDescription() { From b5869ea6da0bf4f7fb4aaa412292c15aff7972dc Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 24 Nov 2026 15:38:27 +0100 Subject: [PATCH 15/15] Improved the password encoding of mailboxes with a type of its own --- .../Dialogs/DataSourceMailboxDialog.razor | 12 +- .../Dialogs/DataSourceMailboxDialog.razor.cs | 21 +-- .../Settings/DataModel/DataMailboxProvider.cs | 13 +- .../Settings/DataModel/DataSourceMailbox.cs | 11 +- .../Tools/Mail/ImapMailboxConnector.cs | 14 +- .../Tools/Mail/MailServerPolicy.cs | 14 +- ...ncodings.cs => MailboxPasswordEncoding.cs} | 145 +++++++++++------- .../MailboxPasswordEncodingJsonConverter.cs | 28 ++++ .../Tools/Mail/OrganizationMailServer.cs | 4 +- .../MailboxProviderConfigurationTests.cs | 2 +- app/Tests/Settings/MailboxSettingsTests.cs | 29 +++- .../Tools/Mail/ImapMailboxConnectorTests.cs | 8 +- app/Tests/Tools/Mail/MailServerPolicyTests.cs | 8 +- ...sts.cs => MailboxPasswordEncodingTests.cs} | 77 +++++++--- 14 files changed, 243 insertions(+), 143 deletions(-) rename app/MindWork AI Studio/Tools/Mail/{MailboxPasswordEncodings.cs => MailboxPasswordEncoding.cs} (56%) create mode 100644 app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodingJsonConverter.cs rename app/Tests/Tools/Mail/{MailboxPasswordEncodingsTests.cs => MailboxPasswordEncodingTests.cs} (72%) diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor index 49ff1d149..dea6157a3 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor @@ -224,11 +224,11 @@ @* Not part of the source: the encoding only decides how the password travels, so it stays open once the mails are prepared. *@ - - @foreach (var passwordEncoding in MailboxPasswordEncodings.ALL) + + @foreach (var passwordEncoding in MailboxPasswordEncoding.ALL) { - - @passwordEncoding + + @passwordEncoding.Name } @@ -272,12 +272,12 @@ { - @string.Format(TA("Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account."), this.PasswordEncoding) + @string.Format(TA("Your username or password contains characters beyond ASCII, such as umlauts or accents. Depending on its configuration, a mail server may expect them in another encoding than {0}, which this test used. Ask your IT department which encoding the server expects, and choose it in the server details. Every test is one attempt to sign in, and too many failed attempts may lock your account."), this.PasswordEncoding.Name) @if (this.SuggestedPasswordEncoding is { } suggestedPasswordEncoding) { - @string.Format(T("Test again with {0}"), suggestedPasswordEncoding) + @string.Format(T("Test again with {0}"), suggestedPasswordEncoding.Name) } diff --git a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs index f8722c2ae..cc3d0d657 100644 --- a/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/DataSourceMailboxDialog.razor.cs @@ -92,7 +92,7 @@ public partial class DataSourceMailboxDialog : MSGComponentBase private MailboxTransportSecurity dataTransportSecurity = MailboxTransportSecurity.SSL_ON_CONNECT; private string dataUsername = string.Empty; private string dataPassword = string.Empty; - private string dataPasswordEncoding = MailboxPasswordEncodings.DEFAULT; + private MailboxPasswordEncoding dataPasswordEncoding = MailboxPasswordEncoding.DEFAULT; private string dataRootFolder = string.Empty; private bool dataIncludeSentAndDrafts = true; private MailboxMaxAge dataMaxAge = MailboxMaxAge.LAST_12_MONTHS; @@ -121,7 +121,7 @@ public partial class DataSourceMailboxDialog : MSGComponentBase private IReadOnlyList serverFolders = []; private string folderIssue = string.Empty; - // The language of the operating system, which tells the encoding to offer after a refused sign-in, cf. MailboxPasswordEncodings.Suggest: + // The language of the operating system, which tells the encoding to offer after a refused sign-in, cf. MailboxPasswordEncoding.Suggest: private string osLanguage = string.Empty; // We get the form reference from Blazor code to validate it manually: @@ -256,7 +256,7 @@ protected override async Task OnAfterRenderAsync(bool firstRender) /// What a connection test depends on. A test only counts for the settings it was made with. The /// encoding is the one the sign-in uses, cf. MailServerPolicy.GetPasswordEncoding. /// - private readonly record struct ConnectionSettings(string Host, int Port, MailboxTransportSecurity TransportSecurity, string Username, string Password, string PasswordEncoding); + private readonly record struct ConnectionSettings(string Host, int Port, MailboxTransportSecurity TransportSecurity, string Username, string Password, MailboxPasswordEncoding PasswordEncoding); private ConnectionSettings CurrentSettings => new(this.dataHost.Trim(), this.dataPort, this.dataTransportSecurity, this.dataUsername.Trim(), this.dataPassword, this.PasswordEncoding); @@ -265,7 +265,7 @@ protected override async Task OnAfterRenderAsync(bool firstRender) /// /// The encoding the next sign-in uses: the one the organization names for the server, if any, and the chosen one otherwise. /// - private string PasswordEncoding => this.mailServerPolicy.GetPasswordEncoding(this.dataHost.Trim(), this.dataPasswordEncoding); + private MailboxPasswordEncoding PasswordEncoding => this.mailServerPolicy.GetPasswordEncoding(this.dataHost.Trim(), this.dataPasswordEncoding); /// /// Whether the organization names the encoding for the server, so that the user cannot choose another one. @@ -285,12 +285,12 @@ protected override async Task OnAfterRenderAsync(bool firstRender) && this.testFailure is MailboxConnectionFailure.AUTHENTICATION_FAILED && !this.IsPasswordEncodingSetByOrganization && MailboxProviderTemplates.FindByHost(this.dataHost) is null - && MailboxPasswordEncodings.DependsOnEncoding(this.dataUsername.Trim(), this.dataPassword); + && MailboxPasswordEncoding.DependsOnEncoding(this.dataUsername.Trim(), this.dataPassword); /// - /// The encoding to offer for one more test, cf. MailboxPasswordEncodings.Suggest, or null for none. + /// The encoding to offer for one more test, cf. MailboxPasswordEncoding.Suggest, or null for none. /// - private string? SuggestedPasswordEncoding => MailboxPasswordEncodings.Suggest(this.osLanguage, this.PasswordEncoding, this.dataUsername.Trim(), this.dataPassword); + private MailboxPasswordEncoding? SuggestedPasswordEncoding => MailboxPasswordEncoding.Suggest(this.osLanguage, this.PasswordEncoding, this.dataUsername.Trim(), this.dataPassword); /// /// Whether the settings to connect with are the ones stored for this mailbox. @@ -541,12 +541,7 @@ private void SelectTransportSecurity(MailboxTransportSecurity transportSecurity) this.dataTransportSecurity = transportSecurity; } - private void SelectPasswordEncoding(string? passwordEncoding) - { - // The select hands over null only when cleared, which it does not allow: - if (passwordEncoding is not null) - this.dataPasswordEncoding = passwordEncoding; - } + private void SelectPasswordEncoding(MailboxPasswordEncoding passwordEncoding) => this.dataPasswordEncoding = passwordEncoding; /// /// Tests the connection once more, in the encoding SuggestedPasswordEncoding offers. Like every diff --git a/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs b/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs index 57a70151f..539754e37 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataMailboxProvider.cs @@ -59,8 +59,8 @@ public sealed record DataMailboxProvider : ILivePluginContent public string HelpUrl { get; private init; } = string.Empty; /// - /// The name of the encoding the mail server expects for a username or a password with characters - /// beyond ASCII, e.g., "windows-1252", cf. MailboxPasswordEncodings. Null when the organization did not say. + /// The encoding the mail server expects for a username or a password with characters beyond + /// ASCII, e.g., "windows-1252". Null when the organization did not say. /// /// /// Depending on its configuration, a mail server may expect another encoding than UTF-8, e.g., @@ -68,7 +68,7 @@ public sealed record DataMailboxProvider : ILivePluginContent /// its users spend no failed sign-in on finding out: every mailbox on this server signs in with /// it, cf. MailServerPolicy.GetPasswordEncoding. /// - public string? PasswordEncoding { get; private init; } + public MailboxPasswordEncoding? PasswordEncoding { get; private init; } /// /// Reads a mail server from an entry of the table MAILBOX_PROVIDERS. @@ -143,16 +143,17 @@ public static bool TryParseConfiguration(int index, LuaTable table, Guid configP helpUrl = helpUri.OriginalString; } - string? passwordEncoding = null; + MailboxPasswordEncoding? passwordEncoding = null; if (table.TryGetValue("PasswordEncoding", out var passwordEncodingValue)) { - if (!passwordEncodingValue.TryRead(out var passwordEncodingText) || !MailboxPasswordEncodings.TryGet(passwordEncodingText, out var encoding)) + var readPasswordEncoding = passwordEncodingValue.TryRead(out var passwordEncodingText) ? MailboxPasswordEncoding.FromName(passwordEncodingText) : default; + if (!readPasswordEncoding.IsKnown) { logger.LogWarning("The configured mailbox provider {ProviderIndex} does not contain a valid PasswordEncoding field. It needs the name of an encoding which keeps ASCII as it is, such as utf-8, windows-1252, or shift_jis.", index); return false; } - passwordEncoding = encoding.WebName; + passwordEncoding = readPasswordEncoding; } provider = new DataMailboxProvider diff --git a/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs b/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs index 906fe90a3..ec582580a 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataSourceMailbox.cs @@ -75,16 +75,15 @@ public DataSourceMailbox() public MailboxAuthMethod AuthMethod { get; set; } = MailboxAuthMethod.PASSWORD; /// - /// The name of the encoding in which the username and the password are sent when signing in, - /// e.g., "utf-8" or "windows-1252", cf. MailboxPasswordEncodings. + /// The encoding in which the username and the password are sent when signing in, stored by its + /// name, e.g., "utf-8" or "windows-1252". /// /// /// A mailbox stored before this setting existed loads with UTF-8, which AI Studio always used - /// until then. A name this version does not know, e.g., one written by a newer version, keeps the - /// mailbox from signing in at all: bytes which may not be the password would count as a failed - /// sign-in, which can lock the account. + /// until then. A name this version does not know, e.g., one written into the settings by hand, keeps + /// the mailbox from signing in at all, cf. MailboxPasswordEncoding.IsKnown. /// - public string PasswordEncoding { get; set; } = MailboxPasswordEncodings.DEFAULT; + public MailboxPasswordEncoding PasswordEncoding { get; set; } = MailboxPasswordEncoding.DEFAULT; /// /// The username to sign in with, often the e-mail address. diff --git a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs index 599e35938..8e766909e 100644 --- a/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs +++ b/app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs @@ -119,7 +119,7 @@ static ImapMailboxConnector() /// The connection or the sign-in failed. public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailServerPolicy policy, CancellationToken token) { - if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || !MailboxPasswordEncodings.TryGet(policy.GetPasswordEncoding(mailbox), out var textEncoding) || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) + if (!TryGetSocketOptions(mailbox.TransportSecurity, out var socketOptions) || mailbox.AuthMethod is not MailboxAuthMethod.PASSWORD || policy.GetPasswordEncoding(mailbox) is not { TextEncoding: { } textEncoding } passwordEncoding || !MailServerHosts.TryGetIdnHost(mailbox.Host, out var idnHost) || mailbox.Port is < 1 or > 65535 || string.IsNullOrWhiteSpace(mailbox.Username) || string.IsNullOrEmpty(password)) throw new MailboxConnectionException(MailboxConnectionFailure.INVALID_SETTINGS, "The mailbox settings are incomplete, or this version of AI Studio does not know them."); if (!policy.IsAllowed(mailbox.Host)) @@ -141,7 +141,7 @@ public async Task ConnectAsync(DataSourceMailbox mailbox, string password, MailS } var offersPlain = this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM); - if (!TryPrepareSignIn(textEncoding, mailbox.Username, password, offersPlain, out var preparedUsername, out var preparedPassword)) + if (!TryPrepareSignIn(passwordEncoding, mailbox.Username, password, offersPlain, out var preparedUsername, out var preparedPassword)) throw new MailboxConnectionException(MailboxConnectionFailure.UNSUITABLE_ENCODING, "The encoding of the mailbox cannot carry the username and the password to this IMAP server."); try @@ -502,22 +502,22 @@ private static async Task FetchAttachmentPieceAsync(IMailFolder folder, /// when it lacks one of their characters, e.g., Windows-1252 has no ẞ, and when the server does not /// offer PLAIN and the encoding is not UTF-8, since MailKit sends the LOGIN command in UTF-8, /// whatever encoding it is handed. Text in ASCII has the same bytes in every encoding a mailbox - /// may use, cf. MailboxPasswordEncodings, so it goes through the LOGIN command as well. + /// may use, cf. MailboxPasswordEncoding, so it goes through the LOGIN command as well. /// - /// The encoding of the mailbox, as MailboxPasswordEncodings.TryGet returns it. + /// The encoding of the mailbox. /// The username. /// The password. /// Whether the server offers the SASL mechanism PLAIN. /// The username to sign in with. /// The password to sign in with. /// Whether the sign-in may go ahead. - internal static bool TryPrepareSignIn(Encoding encoding, string username, string password, bool offersPlain, out string preparedUsername, out string preparedPassword) + internal static bool TryPrepareSignIn(MailboxPasswordEncoding encoding, string username, string password, bool offersPlain, out string preparedUsername, out string preparedPassword) { preparedPassword = password; - if (!MailboxPasswordEncodings.TryPrepare(encoding, username, out preparedUsername) || !MailboxPasswordEncodings.TryPrepare(encoding, password, out preparedPassword)) + if (!encoding.TryPrepare(username, out preparedUsername) || !encoding.TryPrepare(password, out preparedPassword)) return false; - return offersPlain || MailboxPasswordEncodings.IsUtf8(encoding) || !MailboxPasswordEncodings.DependsOnEncoding(preparedUsername, preparedPassword); + return offersPlain || encoding.IsUtf8 || !MailboxPasswordEncoding.DependsOnEncoding(preparedUsername, preparedPassword); } /// diff --git a/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs b/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs index b732197fc..b01cdb239 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailServerPolicy.cs @@ -50,8 +50,8 @@ public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IR /// mail servers. /// /// The host of the server. - /// The name of the encoding, or null when the organization names none for this server. - public string? GetOrganizationPasswordEncoding(string host) => this.OrganizationServers + /// The encoding, or null when the organization names none for this server. + public MailboxPasswordEncoding? GetOrganizationPasswordEncoding(string host) => this.OrganizationServers .FirstOrDefault(server => server.PasswordEncoding is not null && MailServerHosts.AreSame(server.Host, host))? .PasswordEncoding; @@ -64,14 +64,14 @@ public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IR /// connection test and the synchronization alike, takes the encoding from here. /// /// The mailbox. - /// The name of the encoding. - public string GetPasswordEncoding(DataSourceMailbox mailbox) => this.GetPasswordEncoding(mailbox.Host, mailbox.PasswordEncoding); + /// The encoding. + public MailboxPasswordEncoding GetPasswordEncoding(DataSourceMailbox mailbox) => this.GetPasswordEncoding(mailbox.Host, mailbox.PasswordEncoding); /// /// The encoding in which a mailbox on a server sends its username and password, cf. GetPasswordEncoding of a mailbox. /// /// The host of the server. - /// The name of the encoding of the mailbox. - /// The name of the encoding. - public string GetPasswordEncoding(string host, string mailboxEncoding) => this.GetOrganizationPasswordEncoding(host) ?? mailboxEncoding; + /// The encoding of the mailbox. + /// The encoding. + public MailboxPasswordEncoding GetPasswordEncoding(string host, MailboxPasswordEncoding mailboxEncoding) => this.GetOrganizationPasswordEncoding(host) ?? mailboxEncoding; } \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs b/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncoding.cs similarity index 56% rename from app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs rename to app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncoding.cs index 2688bc8df..8e9481cf7 100644 --- a/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodings.cs +++ b/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncoding.cs @@ -1,11 +1,11 @@ -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; +using System.Text.Json.Serialization; namespace AIStudio.Tools.Mail; /// -/// The encodings in which AI Studio can send the username and the password of a mailbox. +/// The encoding in which AI Studio sends the username and the password of a mailbox. /// /// /// The standard for signing in with a password demands UTF-8 (RFC 4616), but a mail server compares @@ -15,15 +15,15 @@ namespace AIStudio.Tools.Mail; /// same in all of them, so only users whose username or password holds other characters notice.

/// AI Studio therefore offers every encoding .NET knows which keeps ASCII as it is, stored by its name, /// e.g., "windows-1254". UTF-16, UTF-32, UTF-7, and the EBCDIC code pages are left out: they change -/// ASCII, and SASL PLAIN separates its parts with zero bytes, which UTF-16 and UTF-32 would break. +/// ASCII, and SASL PLAIN separates its parts with zero bytes, which UTF-16 and UTF-32 would break.

+/// A name this version does not know, e.g., one written into the settings by hand, keeps its name, so +/// that it is stored as it was, but signs in nowhere, cf. IsKnown. Falling back to UTF-8 instead would +/// sign in with bytes which may not be the password, and every such attempt counts as a failed sign-in, +/// which can lock the account. Two values are equal when their names are, cf. Name. ///
-public static class MailboxPasswordEncodings +[JsonConverter(typeof(MailboxPasswordEncodingJsonConverter))] +public readonly record struct MailboxPasswordEncoding { - /// - /// The encoding of a new mailbox, and of one stored before the setting existed: UTF-8, which AI Studio always used until then. - /// - public const string DEFAULT = "utf-8"; - /// /// The characters of ASCII, which every encoding a mailbox may use has to keep as they are. /// @@ -35,62 +35,87 @@ public static class MailboxPasswordEncodings private static readonly byte[] ASCII_BYTES = Encoding.ASCII.GetBytes(ASCII_TEXT); /// - /// The names of all encodings a mailbox may use: UTF-8 first, the others in alphabetical order. + /// The encoding of a new mailbox, and of one stored before the setting existed: UTF-8, which AI Studio always used until then. + /// + public static readonly MailboxPasswordEncoding DEFAULT; + + /// + /// All encodings a mailbox may use: UTF-8 first, the others in alphabetical order of their names. /// - public static readonly IReadOnlyList ALL; + public static readonly IReadOnlyList ALL; - static MailboxPasswordEncodings() + static MailboxPasswordEncoding() { // .NET knows the code pages of Windows and most others only once their provider is registered: Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + DEFAULT = FromName("utf-8"); ALL = Encoding.GetEncodings() - .Select(info => TryGet(info.Name, out var encoding) ? encoding.WebName : null) - .OfType() - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(name => !string.Equals(name, DEFAULT, StringComparison.OrdinalIgnoreCase)) - .ThenBy(name => name, StringComparer.OrdinalIgnoreCase) + .Select(info => FromName(info.Name)) + .Where(encoding => encoding.IsKnown) + .Distinct() + .OrderBy(encoding => encoding != DEFAULT) + .ThenBy(encoding => encoding.Name, StringComparer.Ordinal) .ToList(); } + private MailboxPasswordEncoding(string name, Encoding? textEncoding) + { + this.Name = name; + this.TextEncoding = textEncoding; + } + /// - /// Finds an encoding a mailbox may use. + /// The name of the encoding: the one .NET gives it, e.g., "windows-1252", or, for an encoding this + /// version does not know, the name as it was written. + /// + public string Name => field ?? string.Empty; + + /// + /// The encoding to hand to the IMAP client. It refuses what it cannot encode instead of replacing + /// it, e.g., with a question mark: a password sent with a replaced character is not the password. + /// + /// The encoding, or null when this version does not know it. + public Encoding? TextEncoding { get; } + + /// + /// Whether this version knows the encoding, and so whether a mailbox may sign in with it. + /// + public bool IsKnown => this.TextEncoding is not null; + + /// + /// Whether the encoding is UTF-8, the only one the LOGIN command of the IMAP client sends. + /// + public bool IsUtf8 => this.TextEncoding?.CodePage == Encoding.UTF8.CodePage; + + /// + /// Finds the encoding of a name. /// - /// - /// The encoding refuses what it cannot encode instead of replacing it, e.g., with a question mark: - /// a password sent with a replaced character is not the password, and every such attempt counts as - /// a failed sign-in, which can lock the account. - /// /// The name of the encoding, e.g., "windows-1252", in any case and with spaces around it. - /// The encoding, which throws on a character it lacks. - /// Whether .NET knows the encoding and it keeps ASCII as it is. - public static bool TryGet(string? name, [NotNullWhen(true)] out Encoding? encoding) + /// The encoding. When .NET does not know the name, or when the encoding changes ASCII, one which signs in nowhere, cf. IsKnown. + public static MailboxPasswordEncoding FromName(string? name) { - encoding = null; + var unknown = new MailboxPasswordEncoding(name ?? string.Empty, null); if (string.IsNullOrWhiteSpace(name)) - return false; + return unknown; try { var candidate = Encoding.GetEncoding(name.Trim(), EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); - if (!candidate.GetBytes(ASCII_TEXT).AsSpan().SequenceEqual(ASCII_BYTES)) - return false; - - encoding = candidate; - return true; + return candidate.GetBytes(ASCII_TEXT).AsSpan().SequenceEqual(ASCII_BYTES) ? new(candidate.WebName, candidate) : unknown; } // Thrown for a name .NET does not know, and for an encoding which lacks a character of ASCII. // EncoderFallbackException is one of them: catch (ArgumentException) { - return false; + return unknown; } // Thrown for an encoding .NET knows but no longer supports, such as UTF-7: catch (NotSupportedException) { - return false; + return unknown; } } @@ -115,55 +140,50 @@ public static bool TryGet(string? name, [NotNullWhen(true)] out Encoding? encodi /// user decides, and every test is one attempt to sign in. /// /// The language of the operating system, e.g., "de-DE". - /// The name of the encoding the refused test used. + /// The encoding the refused test used. /// The username. /// The password. - /// The name of the encoding, or null when there is none to offer. - public static string? Suggest(string localeTag, string testedEncoding, string username, string password) + /// The encoding, or null when there is none to offer. + public static MailboxPasswordEncoding? Suggest(string localeTag, MailboxPasswordEncoding testedEncoding, string username, string password) { if (!DependsOnEncoding(username, password)) return null; foreach (var candidate in new[] { GetRegionalEncoding(localeTag), DEFAULT }) { - if (candidate is null || string.Equals(candidate, testedEncoding, StringComparison.OrdinalIgnoreCase)) + if (candidate is not { } encoding || encoding == testedEncoding) continue; - if (TryGet(candidate, out var encoding) && TryPrepare(encoding, username, out _) && TryPrepare(encoding, password, out _)) - return candidate; + if (encoding.TryPrepare(username, out _) && encoding.TryPrepare(password, out _)) + return encoding; } return null; } /// - /// Whether an encoding is UTF-8, the only one the LOGIN command of the IMAP client sends. - /// - /// The encoding. - /// True for UTF-8. - public static bool IsUtf8(Encoding encoding) => encoding.CodePage == Encoding.UTF8.CodePage; - - /// - /// Prepares a username or a password for an encoding. + /// Prepares a username or a password for this encoding. /// /// /// For every encoding but UTF-8, the text is normalized first (NFC): an ä may arrive as an a /// followed by a combining diaeresis, e.g., from a password manager, and the code pages mostly have /// only the composed ä. UTF-8 takes the text as it is, as AI Studio always sent it. /// - /// The encoding, as TryGet returns it. /// The username or the password. /// The text to sign in with. - /// Whether the encoding has every character of the text. - public static bool TryPrepare(Encoding encoding, string text, out string prepared) + /// Whether this version knows the encoding and it has every character of the text. + public bool TryPrepare(string text, out string prepared) { prepared = text; + if (this.TextEncoding is not { } textEncoding) + return false; + try { - if (!IsUtf8(encoding)) + if (!this.IsUtf8) prepared = text.Normalize(NormalizationForm.FormC); - encoding.GetByteCount(prepared); + textEncoding.GetByteCount(prepared); return true; } @@ -176,12 +196,23 @@ public static bool TryPrepare(Encoding encoding, string text, out string prepare } } + /// + public bool Equals(MailboxPasswordEncoding other) => string.Equals(this.Name, other.Name, StringComparison.Ordinal); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(this.Name); + + /// + /// The name of the encoding, as the mailbox dialog shows it, cf. Name. + /// + public override string ToString() => this.Name; + /// /// The ANSI code page of Windows for a language, cf. Suggest. /// /// The language, e.g., "tr-TR". - /// The name of the code page, or null for an unknown language and for one without a code page of its own, such as Hindi. - private static string? GetRegionalEncoding(string localeTag) + /// The encoding, or null for an unknown language and for one without a code page of its own, such as Hindi. + private static MailboxPasswordEncoding? GetRegionalEncoding(string localeTag) { if (string.IsNullOrWhiteSpace(localeTag)) return null; @@ -189,7 +220,7 @@ public static bool TryPrepare(Encoding encoding, string text, out string prepare try { var codePage = CultureInfo.GetCultureInfo(localeTag.Trim()).TextInfo.ANSICodePage; - return codePage is 0 ? null : Encoding.GetEncoding(codePage).WebName; + return codePage is 0 ? null : FromName(Encoding.GetEncoding(codePage).WebName); } // Thrown for a language .NET does not know, and for a code page it does not support. diff --git a/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodingJsonConverter.cs b/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodingJsonConverter.cs new file mode 100644 index 000000000..4a1bd8794 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Mail/MailboxPasswordEncodingJsonConverter.cs @@ -0,0 +1,28 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace AIStudio.Tools.Mail; + +/// +/// Stores the password encoding of a mailbox by its name, e.g., "windows-1252". +/// +/// +/// A name this version does not know is read as it is and written back unchanged, cf. +/// MailboxPasswordEncoding.IsKnown. Anything else than a name, e.g., a number written by hand, is no +/// encoding at all: the mailbox then signs in nowhere, but the other settings are read as usual. +/// +public sealed class MailboxPasswordEncodingJsonConverter : JsonConverter +{ + /// + public override MailboxPasswordEncoding Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType is JsonTokenType.String) + return MailboxPasswordEncoding.FromName(reader.GetString()); + + reader.Skip(); + return MailboxPasswordEncoding.FromName(null); + } + + /// + public override void Write(Utf8JsonWriter writer, MailboxPasswordEncoding value, JsonSerializerOptions options) => writer.WriteStringValue(value.Name); +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Mail/OrganizationMailServer.cs b/app/MindWork AI Studio/Tools/Mail/OrganizationMailServer.cs index b9bc292b8..50a5b3b77 100644 --- a/app/MindWork AI Studio/Tools/Mail/OrganizationMailServer.cs +++ b/app/MindWork AI Studio/Tools/Mail/OrganizationMailServer.cs @@ -4,5 +4,5 @@ namespace AIStudio.Tools.Mail; /// What MailServerPolicy needs to know about a mail server which a configuration plugin offers. ///
/// The host of the server. -/// The name of the encoding the server expects for usernames and passwords, cf. DataMailboxProvider.PasswordEncoding, or null when the organization did not say. -public sealed record OrganizationMailServer(string Host, string? PasswordEncoding); \ No newline at end of file +/// The encoding the server expects for usernames and passwords, cf. DataMailboxProvider.PasswordEncoding, or null when the organization did not say. +public sealed record OrganizationMailServer(string Host, MailboxPasswordEncoding? PasswordEncoding); \ No newline at end of file diff --git a/app/Tests/Settings/MailboxProviderConfigurationTests.cs b/app/Tests/Settings/MailboxProviderConfigurationTests.cs index f0a06cd73..9e39d5bea 100644 --- a/app/Tests/Settings/MailboxProviderConfigurationTests.cs +++ b/app/Tests/Settings/MailboxProviderConfigurationTests.cs @@ -53,7 +53,7 @@ public async Task AFullEntryIsReadAsWritten() Assert.That(provider.Port, Is.EqualTo(1143)); Assert.That(provider.UsernameHint, Is.EqualTo(@"Your account as DOMAIN\username")); Assert.That(provider.HelpUrl, Is.EqualTo("https://intranet.example.org/mail/imap")); - Assert.That(provider.PasswordEncoding, Is.EqualTo("windows-1254")); + Assert.That(provider.PasswordEncoding?.Name, Is.EqualTo("windows-1254")); } } diff --git a/app/Tests/Settings/MailboxSettingsTests.cs b/app/Tests/Settings/MailboxSettingsTests.cs index af3c6e2f7..4fe3bacad 100644 --- a/app/Tests/Settings/MailboxSettingsTests.cs +++ b/app/Tests/Settings/MailboxSettingsTests.cs @@ -41,7 +41,7 @@ public sealed class MailboxSettingsTests Port = 143, TransportSecurity = MailboxTransportSecurity.STARTTLS, AuthMethod = MailboxAuthMethod.PASSWORD, - PasswordEncoding = "windows-1252", + PasswordEncoding = MailboxPasswordEncoding.FromName("windows-1252"), Username = "someone@example.org", RootFolder = "INBOX/Projects", IncludeSentAndDrafts = false, @@ -144,21 +144,40 @@ public void AMailboxStoredBeforeThePasswordEncodingSignsInWithUtf8() { // UTF-8 is what every sign-in used until then: var mailbox = JsonSerializer.Deserialize("""{"RootFolder": "INBOX"}""", SettingsManager.JSON_OPTIONS); - Assert.That(mailbox.PasswordEncoding, Is.EqualTo(MailboxPasswordEncodings.DEFAULT)); + Assert.That(mailbox.PasswordEncoding, Is.EqualTo(MailboxPasswordEncoding.DEFAULT)); } [Test] public void AnEncodingThisVersionDoesNotKnowIsKeptButSignsInNowhere() { - // The name stays, so that it works again with the version that wrote it; ImapMailboxConnectorTests checks that nothing is sent: + // The name stays, so that it is stored as it was; ImapMailboxConnectorTests checks that nothing is sent: var mailbox = JsonSerializer.Deserialize("""{"PasswordEncoding": "x-encoding-of-the-future"}""", SettingsManager.JSON_OPTIONS); using (Assert.EnterMultipleScope()) { - Assert.That(mailbox.PasswordEncoding, Is.EqualTo("x-encoding-of-the-future")); - Assert.That(MailboxPasswordEncodings.TryGet(mailbox.PasswordEncoding, out _), Is.False); + Assert.That(mailbox.PasswordEncoding.Name, Is.EqualTo("x-encoding-of-the-future")); + Assert.That(mailbox.PasswordEncoding.IsKnown, Is.False); + Assert.That(JsonSerializer.Serialize(mailbox, SettingsManager.JSON_OPTIONS), Does.Contain("\"PasswordEncoding\": \"x-encoding-of-the-future\"")); } } + [Test] + public void AnEncodingWhichIsNoNameSignsInNowhereButKeepsTheOtherSettings() + { + var mailbox = JsonSerializer.Deserialize("""{"PasswordEncoding": {"CodePage": 1252}, "RootFolder": "INBOX"}""", SettingsManager.JSON_OPTIONS); + using (Assert.EnterMultipleScope()) + { + Assert.That(mailbox.PasswordEncoding.IsKnown, Is.False); + Assert.That(mailbox.RootFolder, Is.EqualTo("INBOX")); + } + } + + [Test] + public void AKnownEncodingIsStoredByTheNameDotNetGivesIt() + { + var mailbox = JsonSerializer.Deserialize("""{"PasswordEncoding": " Windows-1254 "}""", SettingsManager.JSON_OPTIONS); + Assert.That(JsonSerializer.Serialize(mailbox, SettingsManager.JSON_OPTIONS), Does.Contain("\"PasswordEncoding\": \"windows-1254\"")); + } + [Test] public void ValuesThisVersionCannotReadFallBackToTheSafeSide() { diff --git a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs index 9e11f1011..0229b0b7d 100644 --- a/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs +++ b/app/Tests/Tools/Mail/ImapMailboxConnectorTests.cs @@ -55,8 +55,8 @@ private static IEnumerable InvalidSettings() { yield return Case("unknown transport security", MAILBOX with { TransportSecurity = MailboxTransportSecurity.UNKNOWN }, PASSWORD); yield return Case("unknown auth method", MAILBOX with { AuthMethod = MailboxAuthMethod.UNKNOWN }, PASSWORD); - yield return Case("unknown password encoding", MAILBOX with { PasswordEncoding = "EBCDIC" }, PASSWORD); - yield return Case("password encoding which changes ASCII", MAILBOX with { PasswordEncoding = "utf-16" }, PASSWORD); + yield return Case("unknown password encoding", MAILBOX with { PasswordEncoding = MailboxPasswordEncoding.FromName("EBCDIC") }, PASSWORD); + yield return Case("password encoding which changes ASCII", MAILBOX with { PasswordEncoding = MailboxPasswordEncoding.FromName("utf-16") }, PASSWORD); yield return Case("no host", MAILBOX with { Host = " " }, PASSWORD); yield return Case("a URL as host", MAILBOX with { Host = "imaps://imap.example.org" }, PASSWORD); yield return Case("port 0", MAILBOX with { Port = 0 }, PASSWORD); @@ -146,7 +146,7 @@ private static IEnumerable SignInPreparations() [TestCaseSource(nameof(SignInPreparations))] public bool ASignInGoesAheadOnlyWhenTheEncodingCarriesTheUsernameAndThePassword(string encoding, string username, string password, bool offersPlain) { - return ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncodingsTests.GetKnownEncoding(encoding), username, password, offersPlain, out _, out _); + return ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncodingTests.GetKnownEncoding(encoding), username, password, offersPlain, out _, out _); } [Test] @@ -156,7 +156,7 @@ public void APreparedSignInComposesADecomposedUmlautForWindows1252() const string DECOMPOSED = "Ka\u0308se"; using (Assert.EnterMultipleScope()) { - Assert.That(ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncodingsTests.GetKnownEncoding("windows-1252"), "müller", DECOMPOSED, true, out var username, out var password), Is.True); + Assert.That(ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncodingTests.GetKnownEncoding("windows-1252"), "müller", DECOMPOSED, true, out var username, out var password), Is.True); Assert.That(username, Is.EqualTo("müller")); Assert.That(password, Is.EqualTo("Käse")); } diff --git a/app/Tests/Tools/Mail/MailServerPolicyTests.cs b/app/Tests/Tools/Mail/MailServerPolicyTests.cs index 05a9e2ba8..d4a703561 100644 --- a/app/Tests/Tools/Mail/MailServerPolicyTests.cs +++ b/app/Tests/Tools/Mail/MailServerPolicyTests.cs @@ -18,7 +18,7 @@ public sealed class MailServerPolicyTests { private static readonly MailServerPolicy ORGANIZATION_ONLY = new(true, [new("imap.intra.example.org", null), new("mail.müller.example", null)]); - private static readonly MailServerPolicy WITH_ENCODINGS = new(false, [new("imap.intra.example.org", null), new("exchange.müller.example", "windows-1254")]); + private static readonly MailServerPolicy WITH_ENCODINGS = new(false, [new("imap.intra.example.org", null), new("exchange.müller.example", MailboxPasswordEncoding.FromName("windows-1254"))]); [TestCase("imap.example.com")] [TestCase("imap.gmail.com")] @@ -42,14 +42,14 @@ public sealed class MailServerPolicyTests [TestCase("EXCHANGE.xn--mller-kva.example", ExpectedResult = "windows-1254")] [TestCase("imap.intra.example.org", ExpectedResult = null)] [TestCase("imap.gmail.com", ExpectedResult = null)] - public string? TheOrganizationNamesTheEncodingOfItsServers(string host) => WITH_ENCODINGS.GetOrganizationPasswordEncoding(host); + public string? TheOrganizationNamesTheEncodingOfItsServers(string host) => WITH_ENCODINGS.GetOrganizationPasswordEncoding(host)?.Name; [TestCase("exchange.müller.example", "utf-8", ExpectedResult = "windows-1254")] [TestCase("exchange.müller.example", "x-encoding-of-the-future", ExpectedResult = "windows-1254")] [TestCase("imap.intra.example.org", "windows-1252", ExpectedResult = "windows-1252")] [TestCase("imap.gmail.com", "utf-8", ExpectedResult = "utf-8")] - public string AMailboxSignsInWithTheEncodingOfTheOrganizationFirst(string host, string mailboxEncoding) => WITH_ENCODINGS.GetPasswordEncoding(new DataSourceMailbox { Host = host, PasswordEncoding = mailboxEncoding }); + public string AMailboxSignsInWithTheEncodingOfTheOrganizationFirst(string host, string mailboxEncoding) => WITH_ENCODINGS.GetPasswordEncoding(new DataSourceMailbox { Host = host, PasswordEncoding = MailboxPasswordEncoding.FromName(mailboxEncoding) }).Name; [Test] - public void WithoutAnOrganizationAMailboxKeepsItsEncoding() => Assert.That(MailServerPolicy.ANY_SERVER.GetPasswordEncoding(new DataSourceMailbox { Host = "imap.gmail.com", PasswordEncoding = "iso-8859-15" }), Is.EqualTo("iso-8859-15")); + public void WithoutAnOrganizationAMailboxKeepsItsEncoding() => Assert.That(MailServerPolicy.ANY_SERVER.GetPasswordEncoding(new DataSourceMailbox { Host = "imap.gmail.com", PasswordEncoding = MailboxPasswordEncoding.FromName("iso-8859-15") }).Name, Is.EqualTo("iso-8859-15")); } \ No newline at end of file diff --git a/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs b/app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs similarity index 72% rename from app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs rename to app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs index 0a85d93a4..14d3f2e03 100644 --- a/app/Tests/Tools/Mail/MailboxPasswordEncodingsTests.cs +++ b/app/Tests/Tools/Mail/MailboxPasswordEncodingTests.cs @@ -1,5 +1,3 @@ -using System.Text; - using AIStudio.Tools; using AIStudio.Tools.Mail; @@ -17,7 +15,7 @@ namespace AIStudio.Tests.Tools.Mail; /// come from the code page tables, not from .NET. /// [TestFixture] -public sealed class MailboxPasswordEncodingsTests +public sealed class MailboxPasswordEncodingTests { private const string USERNAME = "u"; @@ -79,7 +77,7 @@ public void PlainSendsTheBytesOfTheChosenEncoding(string encodingName, string ch using (Assert.EnterMultipleScope()) { Assert.That(GetPlainPasswordBytes(encodingName, character), Is.EqualTo(inEncoding)); - Assert.That(GetPlainPasswordBytes(MailboxPasswordEncodings.DEFAULT, character), Is.EqualTo(inUtf8)); + Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.DEFAULT.Name, character), Is.EqualTo(inUtf8)); } } @@ -87,19 +85,20 @@ public void PlainSendsTheBytesOfTheChosenEncoding(string encodingName, string ch public void AsciiIsTheSameInEveryEncoding() { const string PASSWORD = "Sommer-2026!"; - var utf8 = GetPlainPasswordBytes(MailboxPasswordEncodings.DEFAULT, PASSWORD); - Assert.That(MailboxPasswordEncodings.ALL.Select(name => GetPlainPasswordBytes(name, PASSWORD)), Is.All.EqualTo(utf8)); + var utf8 = GetPlainPasswordBytes(MailboxPasswordEncoding.DEFAULT.Name, PASSWORD); + Assert.That(MailboxPasswordEncoding.ALL.Select(encoding => GetPlainPasswordBytes(encoding.Name, PASSWORD)), Is.All.EqualTo(utf8)); } [Test] public void TheListStartsWithUtf8AndHoldsTheCodePagesOfWindows() { + var names = MailboxPasswordEncoding.ALL.Select(encoding => encoding.Name).ToList(); using (Assert.EnterMultipleScope()) { - Assert.That(MailboxPasswordEncodings.ALL[0], Is.EqualTo(MailboxPasswordEncodings.DEFAULT)); - Assert.That(MailboxPasswordEncodings.ALL, Is.Unique); - Assert.That(MailboxPasswordEncodings.ALL, Is.SupersetOf(new[] { "windows-1250", "windows-1251", "windows-1252", "windows-1254", "shift_jis", "gb2312", "big5", "iso-8859-15" })); - Assert.That(MailboxPasswordEncodings.ALL, Has.None.StartsWith("utf-16").And.None.StartsWith("utf-32").And.None.EqualTo("utf-7")); + Assert.That(names[0], Is.EqualTo(MailboxPasswordEncoding.DEFAULT.Name)); + Assert.That(names, Is.Unique); + Assert.That(names, Is.SupersetOf(["windows-1250", "windows-1251", "windows-1252", "windows-1254", "shift_jis", "gb2312", "big5", "iso-8859-15"])); + Assert.That(names, Has.None.StartsWith("utf-16").And.None.StartsWith("utf-32").And.None.EqualTo("utf-7")); } } @@ -109,7 +108,7 @@ public void TheListStartsWithUtf8AndHoldsTheCodePagesOfWindows() [TestCase("latin1", ExpectedResult = "iso-8859-1")] public string? AKnownEncodingIsFoundByItsName(string name) { - return MailboxPasswordEncodings.TryGet(name, out var encoding) ? encoding.WebName : null; + return MailboxPasswordEncoding.FromName(name) is { IsKnown: true } encoding ? encoding.Name : null; } [TestCase(null)] @@ -123,7 +122,34 @@ public void TheListStartsWithUtf8AndHoldsTheCodePagesOfWindows() [TestCase("utf-8, windows-1252")] public void AnEncodingWhichChangesAsciiOrIsUnknownIsRefused(string? name) { - Assert.That(MailboxPasswordEncodings.TryGet(name, out _), Is.False); + Assert.That(MailboxPasswordEncoding.FromName(name).IsKnown, Is.False); + } + + [Test] + public void AnUnknownEncodingKeepsItsNameButSignsInNowhere() + { + var encoding = MailboxPasswordEncoding.FromName("x-encoding-of-the-future"); + using (Assert.EnterMultipleScope()) + { + Assert.That(encoding.Name, Is.EqualTo("x-encoding-of-the-future")); + Assert.That(encoding.TextEncoding, Is.Null); + Assert.That(encoding.TryPrepare("Sommer-2026!", out _), Is.False); + Assert.That(default(MailboxPasswordEncoding).IsKnown, Is.False); + Assert.That(default(MailboxPasswordEncoding).Name, Is.Empty); + } + } + + [Test] + public void TwoEncodingsAreEqualWhenTheirNamesAre() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(MailboxPasswordEncoding.FromName(" Windows-1252 "), Is.EqualTo(MailboxPasswordEncoding.FromName("windows-1252"))); + Assert.That(MailboxPasswordEncoding.FromName("cp1252") == MailboxPasswordEncoding.FromName("windows-1252"), Is.True); + Assert.That(MailboxPasswordEncoding.FromName("windows-1252") != MailboxPasswordEncoding.DEFAULT, Is.True); + Assert.That(MailboxPasswordEncoding.FromName("windows-1252").GetHashCode(), Is.EqualTo(MailboxPasswordEncoding.FromName("CP1252").GetHashCode())); + Assert.That(MailboxPasswordEncoding.FromName("windows-1252").ToString(), Is.EqualTo("windows-1252")); + } } [TestCase("windows-1252", "ẞ")] @@ -135,8 +161,8 @@ public void AnEncodingRefusesWhatItLacks(string encodingName, string text) { using (Assert.EnterMultipleScope()) { - Assert.That(MailboxPasswordEncodings.TryPrepare(GetKnownEncoding(encodingName), text, out _), Is.False); - Assert.That(MailboxPasswordEncodings.TryPrepare(GetKnownEncoding(MailboxPasswordEncodings.DEFAULT), text, out var prepared), Is.True); + Assert.That(GetKnownEncoding(encodingName).TryPrepare(text, out _), Is.False); + Assert.That(MailboxPasswordEncoding.DEFAULT.TryPrepare(text, out var prepared), Is.True); Assert.That(prepared, Is.EqualTo(text)); } } @@ -145,7 +171,7 @@ public void AnEncodingRefusesWhatItLacks(string encodingName, string text) public void ALoneSurrogateIsRefusedByEveryEncoding() { const string TEXT = "abc\uD800"; - Assert.That(MailboxPasswordEncodings.ALL.Where(name => MailboxPasswordEncodings.TryPrepare(GetKnownEncoding(name), TEXT, out _)), Is.Empty); + Assert.That(MailboxPasswordEncoding.ALL.Where(encoding => encoding.TryPrepare(TEXT, out _)), Is.Empty); } [Test] @@ -155,7 +181,7 @@ public void ACodePageComposesADecomposedUmlaut() const string DECOMPOSED = "Ka\u0308se"; using (Assert.EnterMultipleScope()) { - Assert.That(MailboxPasswordEncodings.TryPrepare(GetKnownEncoding("windows-1252"), DECOMPOSED, out var prepared), Is.True); + Assert.That(GetKnownEncoding("windows-1252").TryPrepare(DECOMPOSED, out var prepared), Is.True); Assert.That(prepared, Is.EqualTo("K\u00E4se")); Assert.That(GetPlainPasswordBytes("windows-1252", DECOMPOSED), Is.EqualTo("4B E4 73 65")); } @@ -168,7 +194,7 @@ public void Utf8TakesTheTextAsItIs() const string DECOMPOSED = "Ka\u0308se"; using (Assert.EnterMultipleScope()) { - Assert.That(MailboxPasswordEncodings.TryPrepare(GetKnownEncoding(MailboxPasswordEncodings.DEFAULT), DECOMPOSED, out var prepared), Is.True); + Assert.That(MailboxPasswordEncoding.DEFAULT.TryPrepare(DECOMPOSED, out var prepared), Is.True); Assert.That(prepared, Is.EqualTo(DECOMPOSED)); } } @@ -187,7 +213,7 @@ public async Task APasswordFromTheSecretStoreBecomesTheBytesOfTheChosenEncoding( { Assert.That(password, Is.EqualTo("Grüße-100€")); Assert.That(GetPlainPasswordBytes("windows-1252", password), Is.EqualTo("47 72 FC DF 65 2D 31 30 30 80")); - Assert.That(GetPlainPasswordBytes(MailboxPasswordEncodings.DEFAULT, password), Is.EqualTo("47 72 C3 BC C3 9F 65 2D 31 30 30 E2 82 AC")); + Assert.That(GetPlainPasswordBytes(MailboxPasswordEncoding.DEFAULT.Name, password), Is.EqualTo("47 72 C3 BC C3 9F 65 2D 31 30 30 E2 82 AC")); } } @@ -204,21 +230,22 @@ public async Task APasswordFromTheSecretStoreBecomesTheBytesOfTheChosenEncoding( [TestCase("", "windows-1252", "someone", "Grüße-2026", ExpectedResult = "utf-8")] public string? AfterARefusedSignInTheEncodingOfTheRegionIsOffered(string localeTag, string testedEncoding, string username, string password) { - return MailboxPasswordEncodings.Suggest(localeTag, testedEncoding, username, password); + return MailboxPasswordEncoding.Suggest(localeTag, GetKnownEncoding(testedEncoding), username, password)?.Name; } [TestCase("someone", "Sommer-2026!", ExpectedResult = false)] [TestCase("müller", "Sommer-2026!", ExpectedResult = true)] [TestCase("someone", "日本", ExpectedResult = true)] - public bool OnlyCharactersBeyondAsciiDependOnTheEncoding(string username, string password) => MailboxPasswordEncodings.DependsOnEncoding(username, password); + public bool OnlyCharactersBeyondAsciiDependOnTheEncoding(string username, string password) => MailboxPasswordEncoding.DependsOnEncoding(username, password); /// /// The encoding of a name which a mailbox may use; fails the test for any other name. /// - internal static Encoding GetKnownEncoding(string name) + internal static MailboxPasswordEncoding GetKnownEncoding(string name) { - Assert.That(MailboxPasswordEncodings.TryGet(name, out var encoding), Is.True, $"The encoding '{name}' should be known."); - return encoding!; + var encoding = MailboxPasswordEncoding.FromName(name); + Assert.That(encoding.IsKnown, Is.True, $"The encoding '{name}' should be known."); + return encoding; } /// @@ -227,10 +254,10 @@ internal static Encoding GetKnownEncoding(string name) private static string GetPlainPasswordBytes(string encodingName, string password) { var encoding = GetKnownEncoding(encodingName); - Assert.That(MailboxPasswordEncodings.TryPrepare(encoding, password, out var preparedPassword), Is.True); + Assert.That(encoding.TryPrepare(password, out var preparedPassword), Is.True); // PLAIN sends the authorization identity, the username, and the password, each after a zero byte: - var mechanism = new SaslMechanismPlain(encoding, USERNAME, preparedPassword); + var mechanism = new SaslMechanismPlain(encoding.TextEncoding!, USERNAME, preparedPassword); var message = Convert.FromBase64String(mechanism.Challenge(null, CancellationToken.None)); var passwordBytes = message.AsSpan(1 + USERNAME.Length + 1);