mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-11-24 21:33:48 +00:00
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:
1 parent
f6a4348820
commit
c72a1948b3
27 files changed
+1052
-30
No files matched your search
@@ -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`.
|
||||
- **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
|
||||
|
||||
|
||||
@@ -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."
|
||||
|
||||
|
||||
@@ -222,6 +222,16 @@
|
||||
</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
|
||||
@* Not part of the source: the encoding only decides how the password travels, so it stays open once the mails are prepared. *@
|
||||
<MudSelect T="MailboxPasswordEncoding" Value="@this.PasswordEncoding" ValueChanged="@this.SelectPasswordEncoding" Label="@T("Encoding of username and password")" Class="mt-3" ReadOnly="@this.IsPasswordEncodingSetByOrganization" HelperText="@this.PasswordEncodingHelperText" OpenIcon="@AppIcons.EXPAND_MORE" AdornmentColor="Color.Info" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.PASSWORD_ENCODING">
|
||||
@foreach (var passwordEncoding in MailboxPasswordEncoding.ALL)
|
||||
{
|
||||
<MudSelectItem T="MailboxPasswordEncoding" Value="@passwordEncoding">
|
||||
@passwordEncoding.Name
|
||||
</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</div>
|
||||
</MudCollapse>
|
||||
|
||||
@@ -258,6 +268,20 @@
|
||||
@this.TestResultText
|
||||
</MudText>
|
||||
</MudStack>
|
||||
@if (this.ShowsPasswordEncodingHint)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Dense="@true" Class="mt-3">
|
||||
<MudJustifiedText Typo="Typo.body2">
|
||||
@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)
|
||||
</MudJustifiedText>
|
||||
@if (this.SuggestedPasswordEncoding is { } suggestedPasswordEncoding)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@AppIcons.PASSWORD_ENCODING" Class="mt-2" Disabled="@(!this.CanTestConnection)" OnClick="@this.TestWithSuggestedPasswordEncoding">
|
||||
@string.Format(T("Test again with {0}"), suggestedPasswordEncoding.Name)
|
||||
</MudButton>
|
||||
}
|
||||
</MudAlert>
|
||||
}
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.h6" Class="mb-1">
|
||||
|
||||
@@ -20,10 +20,14 @@ namespace AIStudio.Dialogs;
|
||||
/// Adds or edits a mailbox.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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 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. 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.<br/><br/>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
{
|
||||
@@ -88,6 +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 MailboxPasswordEncoding dataPasswordEncoding = MailboxPasswordEncoding.DEFAULT;
|
||||
private string dataRootFolder = string.Empty;
|
||||
private bool dataIncludeSentAndDrafts = true;
|
||||
private MailboxMaxAge dataMaxAge = MailboxMaxAge.LAST_12_MONTHS;
|
||||
@@ -116,6 +121,9 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
private IReadOnlyList<MailServerFolder> serverFolders = [];
|
||||
private string folderIssue = string.Empty;
|
||||
|
||||
// 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:
|
||||
private MudForm form = null!;
|
||||
|
||||
@@ -166,6 +174,7 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
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;
|
||||
@@ -179,7 +188,7 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
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)
|
||||
@@ -195,6 +204,7 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
}
|
||||
|
||||
this.ApplyOrganizationRules();
|
||||
this.osLanguage = await this.RustService.ReadUserLanguage();
|
||||
|
||||
await base.OnInitializedAsync();
|
||||
|
||||
@@ -243,13 +253,44 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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, MailboxPasswordEncoding PasswordEncoding);
|
||||
|
||||
private ConnectionSettings CurrentSettings => new(this.dataHost.Trim(), this.dataPort, this.dataTransportSecurity, this.dataUsername.Trim(), this.dataPassword);
|
||||
private ConnectionSettings CurrentSettings => new(this.dataHost.Trim(), this.dataPort, this.dataTransportSecurity, this.dataUsername.Trim(), this.dataPassword, this.PasswordEncoding);
|
||||
|
||||
private ConnectionSettings StoredSettings => new(this.DataSource.Host.Trim(), this.DataSource.Port, this.DataSource.TransportSecurity, this.DataSource.Username.Trim(), this.storedPassword);
|
||||
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));
|
||||
|
||||
/// <summary>
|
||||
/// The encoding the next sign-in uses: the one the organization names for the server, if any, and the chosen one otherwise.
|
||||
/// </summary>
|
||||
private MailboxPasswordEncoding PasswordEncoding => this.mailServerPolicy.GetPasswordEncoding(this.dataHost.Trim(), this.dataPasswordEncoding);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the organization names the encoding for the server, so that the user cannot choose another one.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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. 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.
|
||||
/// </summary>
|
||||
private bool ShowsPasswordEncodingHint => this.testedSettings == this.CurrentSettings
|
||||
&& this.testFailure is MailboxConnectionFailure.AUTHENTICATION_FAILED
|
||||
&& !this.IsPasswordEncodingSetByOrganization
|
||||
&& MailboxProviderTemplates.FindByHost(this.dataHost) is null
|
||||
&& MailboxPasswordEncoding.DependsOnEncoding(this.dataUsername.Trim(), this.dataPassword);
|
||||
|
||||
/// <summary>
|
||||
/// The encoding to offer for one more test, cf. MailboxPasswordEncoding.Suggest, or null for none.
|
||||
/// </summary>
|
||||
private MailboxPasswordEncoding? SuggestedPasswordEncoding => MailboxPasswordEncoding.Suggest(this.osLanguage, this.PasswordEncoding, this.dataUsername.Trim(), this.dataPassword);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the settings to connect with are the ones stored for this mailbox.
|
||||
@@ -401,6 +442,7 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
Port = this.dataPort,
|
||||
TransportSecurity = this.dataTransportSecurity,
|
||||
AuthMethod = MailboxAuthMethod.PASSWORD,
|
||||
PasswordEncoding = this.dataPasswordEncoding,
|
||||
MaxAge = this.dataMaxAge,
|
||||
IndexAttachments = this.dataIndexAttachments,
|
||||
MaxAttachmentSizeMegabytes = this.dataMaxAttachmentSizeMegabytes,
|
||||
@@ -499,6 +541,21 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
this.dataTransportSecurity = transportSecurity;
|
||||
}
|
||||
|
||||
private void SelectPasswordEncoding(MailboxPasswordEncoding passwordEncoding) => this.dataPasswordEncoding = passwordEncoding;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task TestWithSuggestedPasswordEncoding()
|
||||
{
|
||||
if (this.SuggestedPasswordEncoding is not { } suggestedPasswordEncoding)
|
||||
return;
|
||||
|
||||
this.dataPasswordEncoding = suggestedPasswordEncoding;
|
||||
await this.TestConnection();
|
||||
}
|
||||
|
||||
private async Task TestConnection()
|
||||
{
|
||||
if (!this.CanTestConnection)
|
||||
@@ -511,9 +568,12 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
|
||||
try
|
||||
{
|
||||
var mailbox = this.CreateDataSource();
|
||||
var policy = MailServerPolicy.Read(this.SettingsManager);
|
||||
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(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.");
|
||||
@@ -670,8 +730,9 @@ public partial class DataSourceMailboxDialog : MSGComponentBase
|
||||
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 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))
|
||||
{
|
||||
var indexStore = await this.DatabaseClientProvider.GetIndexStoreAsync();
|
||||
await indexStore.ClearMailboxAuthFailureAsync(this.dataId, CancellationToken.None);
|
||||
|
||||
@@ -351,6 +351,16 @@ 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 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. 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"] = {}
|
||||
@@ -364,6 +374,7 @@ CONFIG["MAILBOX_PROVIDERS"] = {}
|
||||
-- ["Port"] = 993,
|
||||
-- ["UsernameHint"] = "Your account as DOMAIN\\username",
|
||||
-- ["HelpUrl"] = "https://intranet.example.org/mail/imap",
|
||||
-- ["PasswordEncoding"] = "windows-1252",
|
||||
-- }
|
||||
|
||||
CONFIG["SETTINGS"] = {}
|
||||
|
||||
+24
@@ -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."
|
||||
|
||||
|
||||
+24
@@ -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."
|
||||
|
||||
|
||||
@@ -58,6 +58,18 @@ public sealed record DataMailboxProvider : ILivePluginContent
|
||||
/// </summary>
|
||||
public string HelpUrl { get; private init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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: every mailbox on this server signs in with
|
||||
/// it, cf. MailServerPolicy.GetPasswordEncoding.
|
||||
/// </remarks>
|
||||
public MailboxPasswordEncoding? PasswordEncoding { get; private init; }
|
||||
|
||||
/// <summary>
|
||||
/// Reads a mail server from an entry of the table MAILBOX_PROVIDERS.
|
||||
/// </summary>
|
||||
@@ -131,6 +143,19 @@ public sealed record DataMailboxProvider : ILivePluginContent
|
||||
helpUrl = helpUri.OriginalString;
|
||||
}
|
||||
|
||||
MailboxPasswordEncoding? passwordEncoding = null;
|
||||
if (table.TryGetValue("PasswordEncoding", out var passwordEncodingValue))
|
||||
{
|
||||
var readPasswordEncoding = passwordEncodingValue.TryRead<string>(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 = readPasswordEncoding;
|
||||
}
|
||||
|
||||
provider = new DataMailboxProvider
|
||||
{
|
||||
Id = id.ToString(),
|
||||
@@ -141,6 +166,7 @@ public sealed record DataMailboxProvider : ILivePluginContent
|
||||
TransportSecurity = transportSecurity,
|
||||
UsernameHint = usernameHint,
|
||||
HelpUrl = helpUrl,
|
||||
PasswordEncoding = passwordEncoding,
|
||||
};
|
||||
|
||||
return true;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
using AIStudio.Provider;
|
||||
using AIStudio.Tools.Mail;
|
||||
using AIStudio.Tools.Services;
|
||||
|
||||
namespace AIStudio.Settings.DataModel;
|
||||
@@ -73,6 +74,17 @@ public record struct DataSourceMailbox: IIndexedDataSource, ISecretId
|
||||
/// </summary>
|
||||
public MailboxAuthMethod AuthMethod { get; set; } = MailboxAuthMethod.PASSWORD;
|
||||
|
||||
/// <summary>
|
||||
/// 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".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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 into the settings by hand, keeps
|
||||
/// the mailbox from signing in at all, cf. MailboxPasswordEncoding.IsKnown.
|
||||
/// </remarks>
|
||||
public MailboxPasswordEncoding PasswordEncoding { get; set; } = MailboxPasswordEncoding.DEFAULT;
|
||||
|
||||
/// <summary>
|
||||
/// The username to sign in with, often the e-mail address.
|
||||
/// </summary>
|
||||
|
||||
@@ -827,6 +827,9 @@ public static class AppIcons
|
||||
/// <summary>Marks the check of which retrieved passages fit the question.</summary>
|
||||
public const string PASSAGE_RELEVANCE_CHECK = LucideIcons.LIST_CHECKS;
|
||||
|
||||
/// <summary>Marks the encoding in which a username and a password travel, such as when signing in to a mailbox.</summary>
|
||||
public const string PASSWORD_ENCODING = LucideIcons.BINARY;
|
||||
|
||||
/// <summary>Marks the component that reads PDF files, such as the PDFium version on the information page.</summary>
|
||||
public const string PDF_READER = LucideIcons.FILE_SCAN;
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
using AIStudio.Settings.DataModel;
|
||||
using AIStudio.Tools.Databases.IndexStore;
|
||||
@@ -19,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.<br/><br/>
|
||||
/// 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.<br/><br/>
|
||||
/// 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
|
||||
@@ -111,12 +114,12 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
/// </summary>
|
||||
/// <param name="mailbox">The mailbox to connect to.</param>
|
||||
/// <param name="password">The password, as stored in the OS keyring or just typed in.</param>
|
||||
/// <param name="policy">Which mail servers the organization allows. Every connection passes here, so this is where a server it does not allow is refused.</param>
|
||||
/// <param name="policy">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.</param>
|
||||
/// <param name="token">The cancellation token.</param>
|
||||
/// <exception cref="MailboxConnectionException">The connection or the sign-in failed.</exception>
|
||||
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 || 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))
|
||||
@@ -137,9 +140,13 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
throw new MailboxConnectionException(failure, $"Connecting to the IMAP server failed: {failure}.", e);
|
||||
}
|
||||
|
||||
var offersPlain = this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM);
|
||||
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
|
||||
{
|
||||
await this.SignInAsync(mailbox.Username, password, token);
|
||||
await this.SignInAsync(textEncoding, preparedUsername, preparedPassword, offersPlain, token);
|
||||
}
|
||||
catch (Exception e) when (Classify(e, token) is { } failure)
|
||||
{
|
||||
@@ -486,11 +493,41 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
return entity is TextPart textPart ? textPart.Text : null;
|
||||
}
|
||||
|
||||
private async Task SignInAsync(string username, string password, CancellationToken token)
|
||||
/// <summary>
|
||||
/// Prepares the username and the password for one sign-in in the encoding of the mailbox, cf. MailServerPolicy.GetPasswordEncoding.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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 a mailbox
|
||||
/// may use, cf. MailboxPasswordEncoding, so it goes through the LOGIN command as well.
|
||||
/// </remarks>
|
||||
/// <param name="encoding">The encoding of the mailbox.</param>
|
||||
/// <param name="username">The username.</param>
|
||||
/// <param name="password">The password.</param>
|
||||
/// <param name="offersPlain">Whether the server offers the SASL mechanism PLAIN.</param>
|
||||
/// <param name="preparedUsername">The username to sign in with.</param>
|
||||
/// <param name="preparedPassword">The password to sign in with.</param>
|
||||
/// <returns>Whether the sign-in may go ahead.</returns>
|
||||
internal static bool TryPrepareSignIn(MailboxPasswordEncoding encoding, string username, string password, bool offersPlain, out string preparedUsername, out string preparedPassword)
|
||||
{
|
||||
if (this.client.AuthenticationMechanisms.Contains(PLAIN_MECHANISM))
|
||||
preparedPassword = password;
|
||||
if (!encoding.TryPrepare(username, out preparedUsername) || !encoding.TryPrepare(password, out preparedPassword))
|
||||
return false;
|
||||
|
||||
return offersPlain || encoding.IsUtf8 || !MailboxPasswordEncoding.DependsOnEncoding(preparedUsername, preparedPassword);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signs in once, with a username and a password which TryPrepareSignIn prepared.
|
||||
/// </summary>
|
||||
private async Task SignInAsync(Encoding textEncoding, string username, string password, bool offersPlain, CancellationToken token)
|
||||
{
|
||||
if (offersPlain)
|
||||
{
|
||||
await this.client.AuthenticateAsync(new SaslMechanismPlain(username, password), token);
|
||||
await this.client.AuthenticateAsync(new SaslMechanismPlain(textEncoding, username, password), token);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -498,7 +535,8 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
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. TryPrepareSignIn:
|
||||
//
|
||||
this.client.AuthenticationMechanisms.Clear();
|
||||
await this.client.AuthenticateAsync(username, password, token);
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
using AIStudio.Settings;
|
||||
using AIStudio.Settings.DataModel;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
|
||||
namespace AIStudio.Tools.Mail;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="AllowsOnlyOrganizationMailServers">Whether the organization allows only its own mail servers, see DataMailboxes.AllowOnlyOrganizationMailServers.</param>
|
||||
/// <param name="OrganizationHosts">The hosts of the mail servers which the configuration plugins offer.</param>
|
||||
public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IReadOnlyList<string> OrganizationHosts)
|
||||
/// <param name="OrganizationServers">The mail servers which the configuration plugins offer.</param>
|
||||
public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IReadOnlyList<OrganizationMailServer> OrganizationServers)
|
||||
{
|
||||
/// <summary>
|
||||
/// Every server: what holds as long as no organization rules otherwise.
|
||||
@@ -26,7 +28,7 @@ public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IR
|
||||
/// <returns>The policy.</returns>
|
||||
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());
|
||||
|
||||
/// <summary>
|
||||
/// Whether AI Studio may connect to a server, and the AI read the mailboxes on it.
|
||||
@@ -37,5 +39,39 @@ public sealed record MailServerPolicy(bool AllowsOnlyOrganizationMailServers, IR
|
||||
/// </remarks>
|
||||
/// <param name="host">The host of the server.</param>
|
||||
/// <returns>True when the server is allowed.</returns>
|
||||
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));
|
||||
|
||||
/// <summary>
|
||||
/// The encoding the organization names for a server.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="host">The host of the server.</param>
|
||||
/// <returns>The encoding, or null when the organization names none for this server.</returns>
|
||||
public MailboxPasswordEncoding? GetOrganizationPasswordEncoding(string host) => this.OrganizationServers
|
||||
.FirstOrDefault(server => server.PasswordEncoding is not null && MailServerHosts.AreSame(server.Host, host))?
|
||||
.PasswordEncoding;
|
||||
|
||||
/// <summary>
|
||||
/// The encoding in which a mailbox sends its username and password.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="mailbox">The mailbox.</param>
|
||||
/// <returns>The encoding.</returns>
|
||||
public MailboxPasswordEncoding GetPasswordEncoding(DataSourceMailbox mailbox) => this.GetPasswordEncoding(mailbox.Host, mailbox.PasswordEncoding);
|
||||
|
||||
/// <summary>
|
||||
/// The encoding in which a mailbox on a server sends its username and password, cf. GetPasswordEncoding of a mailbox.
|
||||
/// </summary>
|
||||
/// <param name="host">The host of the server.</param>
|
||||
/// <param name="mailboxEncoding">The encoding of the mailbox.</param>
|
||||
/// <returns>The encoding.</returns>
|
||||
public MailboxPasswordEncoding GetPasswordEncoding(string host, MailboxPasswordEncoding mailboxEncoding) => this.GetOrganizationPasswordEncoding(host) ?? mailboxEncoding;
|
||||
}
|
||||
@@ -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.
|
||||
/// </summary>
|
||||
SERVER_NOT_ALLOWED,
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
UNSUITABLE_ENCODING,
|
||||
}
|
||||
@@ -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. 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."),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace AIStudio.Tools.Mail;
|
||||
|
||||
/// <summary>
|
||||
/// The encoding in which AI Studio sends the username and the password of a mailbox.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.<br/><br/>
|
||||
/// 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.<br/><br/>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[JsonConverter(typeof(MailboxPasswordEncodingJsonConverter))]
|
||||
public readonly record struct MailboxPasswordEncoding
|
||||
{
|
||||
/// <summary>
|
||||
/// The characters of ASCII, which every encoding a mailbox may use has to keep as they are.
|
||||
/// </summary>
|
||||
private static readonly string ASCII_TEXT = new(Enumerable.Range(0, 128).Select(code => (char)code).ToArray());
|
||||
|
||||
/// <summary>
|
||||
/// The bytes of ASCII_TEXT in ASCII.
|
||||
/// </summary>
|
||||
private static readonly byte[] ASCII_BYTES = Encoding.ASCII.GetBytes(ASCII_TEXT);
|
||||
|
||||
/// <summary>
|
||||
/// The encoding of a new mailbox, and of one stored before the setting existed: UTF-8, which AI Studio always used until then.
|
||||
/// </summary>
|
||||
public static readonly MailboxPasswordEncoding DEFAULT;
|
||||
|
||||
/// <summary>
|
||||
/// All encodings a mailbox may use: UTF-8 first, the others in alphabetical order of their names.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<MailboxPasswordEncoding> ALL;
|
||||
|
||||
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 => 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string Name => field ?? string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <value>The encoding, or null when this version does not know it.</value>
|
||||
public Encoding? TextEncoding { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether this version knows the encoding, and so whether a mailbox may sign in with it.
|
||||
/// </summary>
|
||||
public bool IsKnown => this.TextEncoding is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the encoding is UTF-8, the only one the LOGIN command of the IMAP client sends.
|
||||
/// </summary>
|
||||
public bool IsUtf8 => this.TextEncoding?.CodePage == Encoding.UTF8.CodePage;
|
||||
|
||||
/// <summary>
|
||||
/// Finds the encoding of a name.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the encoding, e.g., "windows-1252", in any case and with spaces around it.</param>
|
||||
/// <returns>The encoding. When .NET does not know the name, or when the encoding changes ASCII, one which signs in nowhere, cf. IsKnown.</returns>
|
||||
public static MailboxPasswordEncoding FromName(string? name)
|
||||
{
|
||||
var unknown = new MailboxPasswordEncoding(name ?? string.Empty, null);
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return unknown;
|
||||
|
||||
try
|
||||
{
|
||||
var candidate = Encoding.GetEncoding(name.Trim(), EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
|
||||
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 unknown;
|
||||
}
|
||||
|
||||
// Thrown for an encoding .NET knows but no longer supports, such as UTF-7:
|
||||
catch (NotSupportedException)
|
||||
{
|
||||
return unknown;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the bytes of a username and a password depend on the encoding: only characters beyond ASCII do.
|
||||
/// </summary>
|
||||
/// <param name="username">The username.</param>
|
||||
/// <param name="password">The password.</param>
|
||||
/// <returns>True when either holds a character beyond ASCII.</returns>
|
||||
public static bool DependsOnEncoding(string username, string password) => !Ascii.IsValid(username) || !Ascii.IsValid(password);
|
||||
|
||||
/// <summary>
|
||||
/// The encoding to offer for one more connection test after the server refused a username or a
|
||||
/// password with characters beyond ASCII.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="localeTag">The language of the operating system, e.g., "de-DE".</param>
|
||||
/// <param name="testedEncoding">The encoding the refused test used.</param>
|
||||
/// <param name="username">The username.</param>
|
||||
/// <param name="password">The password.</param>
|
||||
/// <returns>The encoding, or null when there is none to offer.</returns>
|
||||
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 not { } encoding || encoding == testedEncoding)
|
||||
continue;
|
||||
|
||||
if (encoding.TryPrepare(username, out _) && encoding.TryPrepare(password, out _))
|
||||
return encoding;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prepares a username or a password for this encoding.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="text">The username or the password.</param>
|
||||
/// <param name="prepared">The text to sign in with.</param>
|
||||
/// <returns>Whether this version knows the encoding and it has every character of the text.</returns>
|
||||
public bool TryPrepare(string text, out string prepared)
|
||||
{
|
||||
prepared = text;
|
||||
if (this.TextEncoding is not { } textEncoding)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
if (!this.IsUtf8)
|
||||
prepared = text.Normalize(NormalizationForm.FormC);
|
||||
|
||||
textEncoding.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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(MailboxPasswordEncoding other) => string.Equals(this.Name, other.Name, StringComparison.Ordinal);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(this.Name);
|
||||
|
||||
/// <summary>
|
||||
/// The name of the encoding, as the mailbox dialog shows it, cf. Name.
|
||||
/// </summary>
|
||||
public override string ToString() => this.Name;
|
||||
|
||||
/// <summary>
|
||||
/// The ANSI code page of Windows for a language, cf. Suggest.
|
||||
/// </summary>
|
||||
/// <param name="localeTag">The language, e.g., "tr-TR".</param>
|
||||
/// <returns>The encoding, or null for an unknown language and for one without a code page of its own, such as Hindi.</returns>
|
||||
private static MailboxPasswordEncoding? GetRegionalEncoding(string localeTag)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(localeTag))
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
var codePage = CultureInfo.GetCultureInfo(localeTag.Trim()).TextInfo.ANSICodePage;
|
||||
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.
|
||||
// CultureNotFoundException is one of them:
|
||||
catch (Exception e) when (e is ArgumentException or NotSupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace AIStudio.Tools.Mail;
|
||||
|
||||
/// <summary>
|
||||
/// Stores the password encoding of a mailbox by its name, e.g., "windows-1252".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public sealed class MailboxPasswordEncodingJsonConverter : JsonConverter<MailboxPasswordEncoding>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Write(Utf8JsonWriter writer, MailboxPasswordEncoding value, JsonSerializerOptions options) => writer.WriteStringValue(value.Name);
|
||||
}
|
||||
@@ -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),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Finds the well-known provider whose server a host names, however the host was written.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Microsoft Exchange Server never matches: every organization runs a server of its own.
|
||||
/// </remarks>
|
||||
/// <param name="host">The host of a mailbox.</param>
|
||||
/// <returns>The provider, or null when the host belongs to none of them.</returns>
|
||||
public static MailboxProviderTemplate? FindByHost(string host) => ALL.FirstOrDefault(template => template.Host.Length > 0 && MailServerHosts.AreSame(template.Host, host));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace AIStudio.Tools.Mail;
|
||||
|
||||
/// <summary>
|
||||
/// What MailServerPolicy needs to know about a mail server which a configuration plugin offers.
|
||||
/// </summary>
|
||||
/// <param name="Host">The host of the server.</param>
|
||||
/// <param name="PasswordEncoding">The encoding the server expects for usernames and passwords, cf. DataMailboxProvider.PasswordEncoding, or null when the organization did not say.</param>
|
||||
public sealed record OrganizationMailServer(string Host, MailboxPasswordEncoding? PasswordEncoding);
|
||||
@@ -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. 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.
|
||||
@@ -36,6 +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 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.
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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<u8> = (0..512u32).map(|index| (index % 256) as u8).collect();
|
||||
let salt: Vec<u8> = (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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user