Fixed signing in to mailboxes with characters beyond ASCII in the username or password (#1224)

Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
Peer HogeterpandThorsten Sommer authored and GitHub committed 2026-11-24 15:53:19 +01:00
1 parent f6a4348820
commit c72a1948b3
27 files changed
+1052 -30

No files matched your search

@@ -39,6 +39,7 @@ public sealed class MailboxProviderConfigurationTests
["Port"] = "1143",
["UsernameHint"] = "\"Your account as DOMAIN\\\\username\"",
["HelpUrl"] = "\"https://intranet.example.org/mail/imap\"",
["PasswordEncoding"] = "\" Windows-1254 \"",
});
Assert.That(provider, Is.Not.Null);
@@ -52,6 +53,7 @@ public sealed class MailboxProviderConfigurationTests
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?.Name, Is.EqualTo("windows-1254"));
}
}
@@ -68,6 +70,7 @@ public sealed class MailboxProviderConfigurationTests
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,12 @@ public sealed class MailboxProviderConfigurationTests
[TestCase("Port", "65536")]
[TestCase("HelpUrl", "\"ftp://intranet.example.org/mail\"")]
[TestCase("HelpUrl", "\"/mail/imap\"")]
[TestCase("PasswordEncoding", "\"UNKNOWN\"")]
[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)
{
var provider = await ReadAsync(new Dictionary<string, string?> { [field] = value });
@@ -3,6 +3,7 @@ using System.Text.Json;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.Mail;
using Microsoft.Extensions.Logging.Abstractions;
@@ -40,6 +41,7 @@ public sealed class MailboxSettingsTests
Port = 143,
TransportSecurity = MailboxTransportSecurity.STARTTLS,
AuthMethod = MailboxAuthMethod.PASSWORD,
PasswordEncoding = MailboxPasswordEncoding.FromName("windows-1252"),
Username = "someone@example.org",
RootFolder = "INBOX/Projects",
IncludeSentAndDrafts = false,
@@ -137,6 +139,45 @@ public sealed class MailboxSettingsTests
Assert.That(mailbox.IncludeSentAndDrafts, Is.True);
}
[Test]
public void AMailboxStoredBeforeThePasswordEncodingSignsInWithUtf8()
{
// UTF-8 is what every sign-in used until then:
var mailbox = JsonSerializer.Deserialize<DataSourceMailbox>("""{"RootFolder": "INBOX"}""", SettingsManager.JSON_OPTIONS);
Assert.That(mailbox.PasswordEncoding, Is.EqualTo(MailboxPasswordEncoding.DEFAULT));
}
[Test]
public void AnEncodingThisVersionDoesNotKnowIsKeptButSignsInNowhere()
{
// The name stays, so that it is stored as it was; ImapMailboxConnectorTests checks that nothing is sent:
var mailbox = JsonSerializer.Deserialize<DataSourceMailbox>("""{"PasswordEncoding": "x-encoding-of-the-future"}""", SettingsManager.JSON_OPTIONS);
using (Assert.EnterMultipleScope())
{
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<DataSourceMailbox>("""{"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<DataSourceMailbox>("""{"PasswordEncoding": " Windows-1254 "}""", SettingsManager.JSON_OPTIONS);
Assert.That(JsonSerializer.Serialize(mailbox, SettingsManager.JSON_OPTIONS), Does.Contain("\"PasswordEncoding\": \"windows-1254\""));
}
[Test]
public void ValuesThisVersionCannotReadFallBackToTheSafeSide()
{
+12 -1
View File
@@ -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<Encryption> CreateEncryptionAsync()
/// <summary>
/// The encryption with the password and the salt of these tests, which the tests of the runtime use as well.
/// </summary>
internal static async Task<Encryption> CreateEncryptionAsync()
{
var encryption = new Encryption(NullLogger<Encryption>.Instance, SECRET_PASSWORD, SECRET_KEY_SALT);
await encryption.Initialize();
@@ -33,6 +36,7 @@ public sealed class EncryptionTests
[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 sealed class EncryptionTests
[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();
@@ -55,6 +55,8 @@ public sealed class ImapMailboxConnectorTests
{
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.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);
@@ -107,11 +109,59 @@ public sealed class ImapMailboxConnectorTests
// 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<MailboxConnectionException>(() => connector.ConnectAsync(MAILBOX, PASSWORD, policy, CancellationToken.None));
Assert.That(exception?.Failure, Is.EqualTo(MailboxConnectionFailure.SERVER_NOT_ALLOWED));
}
private static IEnumerable<TestCaseData> SignInPreparations()
{
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);
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 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, false);
yield break;
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(string encoding, string username, string password, bool offersPlain)
{
return ImapMailboxConnector.TryPrepareSignIn(MailboxPasswordEncodingTests.GetKnownEncoding(encoding), username, password, offersPlain, out _, out _);
}
[Test]
public void APreparedSignInComposesADecomposedUmlautForWindows1252()
{
// An a followed by a combining diaeresis, as some password managers deliver an ä:
const string DECOMPOSED = "Ka\u0308se";
using (Assert.EnterMultipleScope())
{
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"));
}
}
[TestCase("Projects", '/', ExpectedResult = true)]
[TestCase("Projekte 2026", '.', ExpectedResult = true)]
[TestCase("Ablage/Alt", '.', ExpectedResult = true)]
+22 -2
View File
@@ -1,19 +1,24 @@
using AIStudio.Settings.DataModel;
using AIStudio.Tools.Mail;
namespace AIStudio.Tests.Tools.Mail;
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[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", MailboxPasswordEncoding.FromName("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)?.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 = MailboxPasswordEncoding.FromName(mailboxEncoding) }).Name;
[Test]
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"));
}
@@ -0,0 +1,266 @@
using AIStudio.Tools;
using AIStudio.Tools.Mail;
using MailKit.Security;
namespace AIStudio.Tests.Tools.Mail;
/// <summary>
/// Checks which encodings a mailbox may use, and the bytes a password becomes in them when signing in.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[TestFixture]
public sealed class MailboxPasswordEncodingTests
{
private const string USERNAME = "u";
private static IEnumerable<TestCaseData> 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(MailboxPasswordEncoding.DEFAULT.Name, character), Is.EqualTo(inUtf8));
}
}
[Test]
public void AsciiIsTheSameInEveryEncoding()
{
const string PASSWORD = "Sommer-2026!";
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(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"));
}
}
[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 MailboxPasswordEncoding.FromName(name) is { IsKnown: true } encoding ? encoding.Name : 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(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", "ẞ")]
[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(GetKnownEncoding(encodingName).TryPrepare(text, out _), Is.False);
Assert.That(MailboxPasswordEncoding.DEFAULT.TryPrepare(text, out var prepared), Is.True);
Assert.That(prepared, Is.EqualTo(text));
}
}
[Test]
public void ALoneSurrogateIsRefusedByEveryEncoding()
{
const string TEXT = "abc\uD800";
Assert.That(MailboxPasswordEncoding.ALL.Where(encoding => encoding.TryPrepare(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(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"));
}
}
[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(MailboxPasswordEncoding.DEFAULT.TryPrepare(DECOMPOSED, out var prepared), Is.True);
Assert.That(prepared, Is.EqualTo(DECOMPOSED));
}
}
[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(MailboxPasswordEncoding.DEFAULT.Name, 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")]
[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 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) => MailboxPasswordEncoding.DependsOnEncoding(username, password);
/// <summary>
/// The encoding of a name which a mailbox may use; fails the test for any other name.
/// </summary>
internal static MailboxPasswordEncoding GetKnownEncoding(string name)
{
var encoding = MailboxPasswordEncoding.FromName(name);
Assert.That(encoding.IsKnown, Is.True, $"The encoding '{name}' should be known.");
return encoding;
}
/// <summary>
/// The bytes of the password in the message which the SASL mechanism PLAIN sends, as hex.
/// </summary>
private static string GetPlainPasswordBytes(string encodingName, string password)
{
var encoding = GetKnownEncoding(encodingName);
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.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)));
}
}
@@ -46,6 +46,17 @@ public sealed class MailboxProviderTemplatesTests
}
}
[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()
{