diff --git a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua index e17a3eadf..4ece0fcb0 100644 --- a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua +++ b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua @@ -25030,6 +25030,30 @@ UI_TEXT_CONTENT["AISTUDIO::TOOLS::TOOLCALLINGSYSTEM::TOOLSETTINGSSERVICE::T40310 -- The file path is null or empty and the file therefore can not be loaded. UI_TEXT_CONTENT["AISTUDIO::TOOLS::USERFILE::T932243993"] = "The file path is null or empty and the file therefore can not be loaded." +-- The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3169974238"] = "The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department." + +-- The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3169974238::INFORMAL"] = "The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department." + +-- The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3476635333"] = "The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again." + +-- The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3476635333::INFORMAL"] = "The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again." + +-- The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3728920309"] = "The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key." + +-- The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3728920309::INFORMAL"] = "The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key." + +-- The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T839628124"] = "The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key." + +-- The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T839628124::INFORMAL"] = "The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key." + -- The hostname is not a valid HTTP(S) URL. UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::DATASOURCEVALIDATION::T1013354736"] = "The hostname is not a valid HTTP(S) URL." diff --git a/app/MindWork AI Studio/Components/ConfigurationBase.razor.cs b/app/MindWork AI Studio/Components/ConfigurationBase.razor.cs index d2670767e..81fc571af 100644 --- a/app/MindWork AI Studio/Components/ConfigurationBase.razor.cs +++ b/app/MindWork AI Studio/Components/ConfigurationBase.razor.cs @@ -56,7 +56,7 @@ public abstract partial class ConfigurationBase : MSGComponentBase protected bool IsDisabled => this.Disabled() || this.IsLocked(); - private string Classes => $"{this.GetClassForBase} {JUSTIFIED_HELP_CLASS} {this.MarginClass}"; + private string Classes => $"{this.GetClassForBase} {this.MarginClass}"; /// /// The bottom margin of the option. Options inside settings panels need the default @@ -66,8 +66,6 @@ public abstract partial class ConfigurationBase : MSGComponentBase private protected virtual RenderFragment? Body => null; - private const string JUSTIFIED_HELP_CLASS = "configuration-help-justified"; - private const string MARGIN_CLASS = "mb-6"; protected static readonly Dictionary SPELLCHECK_ATTRIBUTES = new(); diff --git a/app/MindWork AI Studio/Components/Issues.razor b/app/MindWork AI Studio/Components/Issues.razor index dda1ed2bf..b31565d01 100644 --- a/app/MindWork AI Studio/Components/Issues.razor +++ b/app/MindWork AI Studio/Components/Issues.razor @@ -9,7 +9,7 @@ @foreach (var issue in this.IssuesData) { - @issue + @issue } diff --git a/app/MindWork AI Studio/Components/UserAPIKeyPrompt.razor b/app/MindWork AI Studio/Components/UserAPIKeyPrompt.razor index d668f00da..69260a7ef 100644 --- a/app/MindWork AI Studio/Components/UserAPIKeyPrompt.razor +++ b/app/MindWork AI Studio/Components/UserAPIKeyPrompt.razor @@ -7,12 +7,12 @@ } else { - + @TA("Your organization has set up AI providers for you. To use them, AI Studio needs your personal API key. Please enter it below.") - + } - + @if (!string.IsNullOrWhiteSpace(this.issue)) { @@ -22,7 +22,7 @@ } - + @T("Check and save API key") @if (this.isBusy) diff --git a/app/MindWork AI Studio/Components/UserAPIKeyPrompt.razor.cs b/app/MindWork AI Studio/Components/UserAPIKeyPrompt.razor.cs index d9f7eb158..73e1541ff 100644 --- a/app/MindWork AI Studio/Components/UserAPIKeyPrompt.razor.cs +++ b/app/MindWork AI Studio/Components/UserAPIKeyPrompt.razor.cs @@ -1,5 +1,6 @@ using AIStudio.Tools.Services; using AIStudio.Tools.UserAPIKeys; +using AIStudio.Tools.Validation; using Microsoft.AspNetCore.Components; @@ -42,12 +43,20 @@ public partial class UserAPIKeyPrompt : MSGComponentBase private string Title => string.IsNullOrWhiteSpace(this.Group.Prompt?.Title) ? TA("Your API key is missing") : this.Group.Prompt.Title; + /// + /// Whether the entered key can be checked and stored: it is there, and it can be sent. + /// + private bool CanStoreAPIKey => !this.isBusy && !string.IsNullOrWhiteSpace(this.apiKey) && !APIKeyValidation.Check(this.apiKey).IsProblem; + + private static string? ValidateAPIKey(string apiKey) => APIKeyValidation.Validate(apiKey); + private async Task StoreAPIKeyAsync() { - var enteredAPIKey = this.apiKey.Trim(); - if (this.isBusy || string.IsNullOrWhiteSpace(enteredAPIKey)) + if (!this.CanStoreAPIKey) return; + var enteredAPIKey = APIKeyValidation.Normalize(this.apiKey); + this.isBusy = true; this.issue = string.Empty; try diff --git a/app/MindWork AI Studio/Dialogs/Settings/ToolSettingsDialog.razor b/app/MindWork AI Studio/Dialogs/Settings/ToolSettingsDialog.razor index 5c77221e9..876076e13 100644 --- a/app/MindWork AI Studio/Dialogs/Settings/ToolSettingsDialog.razor +++ b/app/MindWork AI Studio/Dialogs/Settings/ToolSettingsDialog.razor @@ -72,7 +72,7 @@ var fieldOptions = field.GetOptions(); if (fieldOptions.Count > 0) { - + @if (!toolSection.Definition.SettingsSchema.Required.Contains(fieldName)) { @T("Not set") @@ -85,7 +85,7 @@ } else { - + } } diff --git a/app/MindWork AI Studio/Dialogs/Settings/ToolSettingsDialog.razor.cs b/app/MindWork AI Studio/Dialogs/Settings/ToolSettingsDialog.razor.cs index 200012da0..ab0996b14 100644 --- a/app/MindWork AI Studio/Dialogs/Settings/ToolSettingsDialog.razor.cs +++ b/app/MindWork AI Studio/Dialogs/Settings/ToolSettingsDialog.razor.cs @@ -1,4 +1,6 @@ +using AIStudio.Components; using AIStudio.Tools.ToolCallingSystem; +using AIStudio.Tools.Validation; using Microsoft.AspNetCore.Components; @@ -173,6 +175,50 @@ public partial class ToolSettingsDialog : SettingsDialogBase private bool IsFieldDisabled(ToolSection section, string fieldName) => this.ToolSettingsService.IsFieldLocked(section.Definition, fieldName); + /// + /// Checks an API key while the user types it, and leaves every other field alone. + /// + private static Func? GetFieldValidation(ToolSettingsFieldDefinition fieldDefinition) => fieldDefinition.IsAPIKey ? APIKeyValidation.Validate : null; + + /// + /// Lets an API key field pass its text on while the user types, so that its check follows the typing. + /// + /// + /// Every other field keeps passing its text on only when the user leaves it, as it always did. + /// + private static double GetFieldDebounceInterval(ToolSettingsFieldDefinition fieldDefinition) => fieldDefinition.IsAPIKey ? TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS : 0; + + /// + /// Finds the first API key the user entered which cannot be sent. + /// + /// + /// Only a key the user can change stops the save. A key the organization locked is not theirs + /// to fix, and refusing to save would block every other setting of the collection as well. + /// + /// The field and what is wrong with its key, or empty when every key can be sent. + /// True when a key cannot be sent. + private bool TryFindAPIKeyIssue(out string message) + { + foreach (var section in this.sections) + { + foreach (var (fieldName, fieldDefinition) in section.Definition.SettingsSchema.Properties) + { + if (!fieldDefinition.IsAPIKey || this.IsFieldDisabled(section, fieldName)) + continue; + + var issue = APIKeyValidation.Validate(GetValue(section, fieldName)); + if (issue is null) + continue; + + message = $"{GetFieldLabel(section, fieldName, fieldDefinition)}: {issue}"; + return true; + } + } + + message = string.Empty; + return false; + } + private static string GetFieldPlaceholder(ToolSection section, string fieldName, ToolSettingsFieldDefinition fieldDefinition) => string.IsNullOrWhiteSpace(GetValue(section, fieldName)) ? GetFieldDefaultValue(section, fieldName, fieldDefinition) : string.Empty; @@ -194,6 +240,12 @@ public partial class ToolSettingsDialog : SettingsDialogBase if (this.item is null) return; + if (this.TryFindAPIKeyIssue(out var apiKeyIssue)) + { + this.validationMessage = apiKeyIssue; + return; + } + foreach (var section in this.sections) { var validationState = await this.ToolSettingsService.ValidateSettingsAsync(section.Definition, section.Values, section.Implementation); diff --git a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua index 6df089cbb..9545aab6f 100644 --- a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua +++ b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua @@ -25032,6 +25032,30 @@ UI_TEXT_CONTENT["AISTUDIO::TOOLS::TOOLCALLINGSYSTEM::TOOLSETTINGSSERVICE::T40310 -- The file path is null or empty and the file therefore can not be loaded. UI_TEXT_CONTENT["AISTUDIO::TOOLS::USERFILE::T932243993"] = "Der Dateipfad ist leer, daher kann die Datei nicht geladen werden." +-- The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3169974238"] = "Der API-Schlüssel für „{0}“ enthält ein Zeichen, das in einem API-Schlüssel nicht vorkommen kann, etwa einen Zeilenumbruch oder ein unsichtbares Zeichen. Bitte geben Sie den Schlüssel in den Einstellungen erneut ein. Wenn Ihre Organisation den Schlüssel bereitstellt, wenden Sie sich bitte an Ihre IT-Abteilung." + +-- The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3169974238::INFORMAL"] = "Der API-Schlüssel für „{0}“ enthält ein Zeichen, das in einem API-Schlüssel nicht vorkommen kann, etwa einen Zeilenumbruch oder ein unsichtbares Zeichen. Bitte gib den Schlüssel in den Einstellungen erneut ein. Wenn deine Organisation den Schlüssel bereitstellt, wende dich bitte an deine IT-Abteilung." + +-- The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3476635333"] = "Der API-Schlüssel enthält ein unsichtbares Zeichen. Solche Zeichen kommen oft mit, wenn Sie Text von einer Webseite oder aus einem Dokument kopieren. Bitte löschen Sie den Schlüssel und geben Sie ihn erneut ein." + +-- The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3476635333::INFORMAL"] = "Der API-Schlüssel enthält ein unsichtbares Zeichen. Solche Zeichen kommen oft mit, wenn du Text von einer Webseite oder aus einem Dokument kopierst. Bitte lösche den Schlüssel und gib ihn erneut ein." + +-- The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3728920309"] = "Der API-Schlüssel enthält das Zeichen „{0}“, das in einem API-Schlüssel nicht vorkommen kann. Textverarbeitungsprogramme machen zum Beispiel aus Anführungszeichen und Bindestrichen solche Zeichen. Bitte überprüfen Sie den Schlüssel." + +-- The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3728920309::INFORMAL"] = "Der API-Schlüssel enthält das Zeichen „{0}“, das in einem API-Schlüssel nicht vorkommen kann. Textverarbeitungsprogramme machen zum Beispiel aus Anführungszeichen und Bindestrichen solche Zeichen. Bitte überprüfe den Schlüssel." + +-- The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T839628124"] = "Der API-Schlüssel enthält ein Leerzeichen oder einen Zeilenumbruch. Beides kann in einem API-Schlüssel nicht vorkommen. Bitte überprüfen Sie, ob Sie mehr als nur den Schlüssel kopiert haben." + +-- The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T839628124::INFORMAL"] = "Der API-Schlüssel enthält ein Leerzeichen oder einen Zeilenumbruch. Beides kann in einem API-Schlüssel nicht vorkommen. Bitte überprüfe, ob du mehr als nur den Schlüssel kopiert hast." + -- The hostname is not a valid HTTP(S) URL. UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::DATASOURCEVALIDATION::T1013354736"] = "Der Hostname ist keine gültige HTTP(S)-URL." diff --git a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua index f6ec1d5cd..e83bf459d 100644 --- a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua +++ b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua @@ -25032,6 +25032,30 @@ UI_TEXT_CONTENT["AISTUDIO::TOOLS::TOOLCALLINGSYSTEM::TOOLSETTINGSSERVICE::T40310 -- The file path is null or empty and the file therefore can not be loaded. UI_TEXT_CONTENT["AISTUDIO::TOOLS::USERFILE::T932243993"] = "The file path is null or empty and the file therefore can not be loaded." +-- The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3169974238"] = "The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department." + +-- The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3169974238::INFORMAL"] = "The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department." + +-- The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3476635333"] = "The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again." + +-- The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3476635333::INFORMAL"] = "The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again." + +-- The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3728920309"] = "The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key." + +-- The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T3728920309::INFORMAL"] = "The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key." + +-- The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T839628124"] = "The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key." + +-- The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key. +UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::APIKEYVALIDATION::T839628124::INFORMAL"] = "The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key." + -- The hostname is not a valid HTTP(S) URL. UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::DATASOURCEVALIDATION::T1013354736"] = "The hostname is not a valid HTTP(S) URL." diff --git a/app/MindWork AI Studio/Provider/Anthropic/ProviderAnthropic.cs b/app/MindWork AI Studio/Provider/Anthropic/ProviderAnthropic.cs index 11b0a88e4..106a79130 100644 --- a/app/MindWork AI Studio/Provider/Anthropic/ProviderAnthropic.cs +++ b/app/MindWork AI Studio/Provider/Anthropic/ProviderAnthropic.cs @@ -139,7 +139,7 @@ public sealed class ProviderAnthropic() : BaseProvider(LLMProviders.ANTHROPIC, n var request = new HttpRequestMessage(HttpMethod.Post, "messages"); // Set the authorization header: - request.Headers.Add("x-api-key", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Add("x-api-key", await this.DecryptAPIKey(requestedSecret)); // Set the Anthropic version: request.Headers.Add("anthropic-version", "2023-06-01"); @@ -166,7 +166,7 @@ public sealed class ProviderAnthropic() : BaseProvider(LLMProviders.ANTHROPIC, n async Task RequestBuilder() { var request = new HttpRequestMessage(HttpMethod.Post, "messages"); - request.Headers.Add("x-api-key", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Add("x-api-key", await this.DecryptAPIKey(requestedSecret)); request.Headers.Add("anthropic-version", "2023-06-01"); request.Content = new StringContent(JsonSerializer.Serialize(requestDto, JSON_SERIALIZER_OPTIONS), Encoding.UTF8, "application/json"); return request; diff --git a/app/MindWork AI Studio/Provider/BaseProvider.cs b/app/MindWork AI Studio/Provider/BaseProvider.cs index 6ca010e64..a4c345a4d 100644 --- a/app/MindWork AI Studio/Provider/BaseProvider.cs +++ b/app/MindWork AI Studio/Provider/BaseProvider.cs @@ -15,6 +15,7 @@ using AIStudio.Tools.ToolCallingSystem.Harness; using AIStudio.Tools.MIME; using AIStudio.Tools.PluginSystem; using AIStudio.Tools.Rust; +using AIStudio.Tools.Validation; using Host = AIStudio.Provider.SelfHosted.Host; @@ -148,6 +149,11 @@ public abstract class BaseProvider : IProvider, ISecretId protected static ModelLoadResult FailedModelLoadResult(ModelLoadFailureReason failureReason, string? technicalDetails = null) => ModelLoadResult.Failure(failureReason, technicalDetails); + /// + /// The result of loading the models with a key which cannot be sent, so that nothing was requested. + /// + protected static ModelLoadResult UnusableAPIKeyModelLoadResult() => FailedModelLoadResult(ModelLoadFailureReason.INVALID_API_KEY_CHARACTERS, "The API key contains a character which an HTTP header cannot carry."); + protected bool IsTimeoutException(Exception exception, CancellationToken token = default) { if (token.IsCancellationRequested) @@ -165,15 +171,72 @@ public abstract class BaseProvider : IProvider, ISecretId ExternalHttpClientTimeout.GetTimeoutDescription(), action))); - protected async Task GetModelLoadingSecretKey(SecretStoreType storeType, string? apiKeyProvisional = null, bool isTryingSecret = false) => apiKeyProvisional switch + /// + /// Gets the API key for loading the models: the one the user is entering, or else the stored one. + /// + /// + /// Either is checked before it goes into a header. A key which the header cannot carry would + /// otherwise fail in the HTTP stack, with a message nobody understands. + /// + /// Where the stored key is kept. + /// The key the user is entering and did not store yet, or null for the stored one. + /// Whether a missing key is fine, so that the keyring logs no error for it. + /// The key without the whitespace around it, or whether it cannot be sent. + protected async Task GetModelLoadingSecretKey(SecretStoreType storeType, string? apiKeyProvisional = null, bool isTryingSecret = false) { - not null => apiKeyProvisional, - _ => await Program.RUST_SERVICE.GetAPIKey(this, storeType, isTrying: isTryingSecret) switch + var key = apiKeyProvisional; + if (key is null) { - { Success: true } result => await result.Secret.Decrypt(Program.ENCRYPTION), - _ => null, + var requestedSecret = await Program.RUST_SERVICE.GetAPIKey(this, storeType, isTrying: isTryingSecret); + if (!requestedSecret.Success) + return ModelLoadingSecretKey.NONE; + + key = await requestedSecret.Secret.Decrypt(Program.ENCRYPTION); } - }; + + var issue = APIKeyValidation.Check(key); + if (!issue.IsProblem) + return new(APIKeyValidation.Normalize(key), false); + + this.logger.LogWarning("The API key for loading the models of '{ProviderInstanceName}' (provider={ProviderType}) contains a character which an API key cannot contain ({IssueKind}). The models were not requested.", this.InstanceName, this.Provider, issue.Kind); + return ModelLoadingSecretKey.UNUSABLE; + } + + /// + /// Decrypts a stored API key for the header of a request. + /// + /// + /// + /// Every stored key which goes into a header goes through here, so that a key with a character + /// the header cannot carry never reaches the HTTP stack: its messages about such keys mean + /// nothing to the user, and some of them even quote the key. Such a key was stored before AI + /// Studio checked keys, or it reached the keyring some other way. The request then fails with a + /// ProviderRequestException, which tells the user to enter the key again. APIKeyHeaderTests + /// checks that no provider decrypts a key on its own. + /// + /// + /// A key which is empty without the whitespace around it fails as a missing key: a header with + /// an empty key would only earn a rejection from the provider. + /// + /// + /// The stored key as the keyring returned it. + /// The key without the whitespace around it. + protected async Task DecryptAPIKey(RequestedSecret requestedSecret) + { + var key = await requestedSecret.Secret.Decrypt(Program.ENCRYPTION); + var issue = APIKeyValidation.Check(key); + if (issue.IsProblem) + { + this.logger.LogWarning("The stored API key of '{ProviderInstanceName}' (provider={ProviderType}) contains a character which an API key cannot contain ({IssueKind}). The request was not sent.", this.InstanceName, this.Provider, issue.Kind); + throw new ProviderRequestException(ProviderRequestFailureReason.INVALID_API_KEY_CHARACTERS, this.GetProviderRequestFailureUserMessage(ProviderRequestFailureReason.INVALID_API_KEY_CHARACTERS)); + } + + var headerValue = APIKeyValidation.Normalize(key); + if (headerValue.Length is 0) + throw new ProviderRequestException(ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY, this.GetProviderRequestFailureUserMessage(ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY)); + + return headerValue; + } protected static ModelLoadFailureReason GetDefaultModelLoadFailureReason(HttpResponseMessage response) => response.StatusCode switch { @@ -203,14 +266,17 @@ public abstract class BaseProvider : IProvider, ISecretId CancellationToken token = default) { var secretKey = await this.GetModelLoadingSecretKey(storeType, apiKeyProvisional, isTryingSecret); - if (string.IsNullOrWhiteSpace(secretKey) && !isTryingSecret) + if (secretKey.IsUnusable) + return UnusableAPIKeyModelLoadResult(); + + if (string.IsNullOrWhiteSpace(secretKey.Key) && !isTryingSecret) return FailedModelLoadResult(ModelLoadFailureReason.INVALID_OR_MISSING_API_KEY, "No API key available for model loading."); using var request = new HttpRequestMessage(HttpMethod.Get, requestPath); if (requestConfigurator is not null) - requestConfigurator(request, secretKey ?? string.Empty); - else if (!string.IsNullOrWhiteSpace(secretKey)) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey); + requestConfigurator(request, secretKey.Key ?? string.Empty); + else if (!string.IsNullOrWhiteSpace(secretKey.Key)) + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey.Key); try { @@ -269,6 +335,7 @@ public abstract class BaseProvider : IProvider, ISecretId { ProviderRequestFailureReason.TOO_MANY_REQUESTS => TA("The provider rejected the request because too many requests were sent. Please wait a moment and try again."), ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY => string.Format(TA("The API key for the provider '{0}' is missing or was rejected. Please check the key in the settings."), this.NameForUser), + ProviderRequestFailureReason.INVALID_API_KEY_CHARACTERS => APIKeyValidation.GetUnusableKeyMessage(this.NameForUser), ProviderRequestFailureReason.AUTHENTICATION_OR_PERMISSION_ERROR => string.Format(TA("The provider '{0}' refused the request. Your account might not be allowed to use the selected model, or the provider might not serve your region."), this.NameForUser), ProviderRequestFailureReason.PROVIDER_UNAVAILABLE => string.Format(TA("The provider '{0}' could not be reached. Please check whether it is running and reachable, then try again."), this.NameForUser), ProviderRequestFailureReason.MODEL_NOT_FOUND => string.Format(TA("The provider '{0}' does not know the selected model. Please select another model."), this.NameForUser), @@ -1460,7 +1527,7 @@ public abstract class BaseProvider : IProvider, ISecretId // Set the authorization header: if (requestedSecret.Success) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await this.DecryptAPIKey(requestedSecret)); // Set provider-specific headers: requestHeadersAction?.Invoke(request.Headers); @@ -1514,7 +1581,7 @@ public abstract class BaseProvider : IProvider, ISecretId { var request = new HttpRequestMessage(HttpMethod.Post, requestPath); if (requestedSecret.Success) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await this.DecryptAPIKey(requestedSecret)); headersAction?.Invoke(request.Headers); request.Content = new StringContent(JsonSerializer.Serialize(requestDto, JSON_SERIALIZER_OPTIONS), Encoding.UTF8, "application/json"); @@ -1623,7 +1690,7 @@ public abstract class BaseProvider : IProvider, ISecretId { case LLMProviders.SELF_HOSTED: if(requestedSecret.Success) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await this.DecryptAPIKey(requestedSecret)); break; @@ -1634,7 +1701,13 @@ public abstract class BaseProvider : IProvider, ISecretId return TranscriptionResult.Failure(); } - request.Headers.Add("Authorization", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + // + // Fireworks gets the bare key, without the scheme 'Bearer'. Headers.Add would parse the key as + // an Authorization header, refuse one with a character such as '/' or '=', and quote the whole + // key in its exception. DecryptAPIKey already made sure that the key holds only printable ASCII, + // so it goes out as it is: + // + request.Headers.TryAddWithoutValidation("Authorization", await this.DecryptAPIKey(requestedSecret)); break; default: @@ -1644,7 +1717,7 @@ public abstract class BaseProvider : IProvider, ISecretId return TranscriptionResult.Failure(); } - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await this.DecryptAPIKey(requestedSecret)); break; } @@ -1677,6 +1750,11 @@ public abstract class BaseProvider : IProvider, ISecretId { throw; } + catch (ProviderRequestException e) + { + // We know what went wrong, e.g., a stored key which cannot be sent, and the user gets to read it: + return TranscriptionResult.Failure(e.UserMessage); + } catch (Exception e) { if (this.IsTimeoutException(e, token)) @@ -1713,7 +1791,7 @@ public abstract class BaseProvider : IProvider, ISecretId { case LLMProviders.SELF_HOSTED: if(requestedSecret.Success) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await this.DecryptAPIKey(requestedSecret)); break; @@ -1724,7 +1802,7 @@ public abstract class BaseProvider : IProvider, ISecretId throw new ProviderRequestException(ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY, this.GetProviderRequestFailureUserMessage(ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY)); } - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await this.DecryptAPIKey(requestedSecret)); break; } diff --git a/app/MindWork AI Studio/Provider/Google/ProviderGoogle.cs b/app/MindWork AI Studio/Provider/Google/ProviderGoogle.cs index 9475dd815..8a40937e0 100644 --- a/app/MindWork AI Studio/Provider/Google/ProviderGoogle.cs +++ b/app/MindWork AI Studio/Provider/Google/ProviderGoogle.cs @@ -96,7 +96,7 @@ public class ProviderGoogle() : BaseProvider(LLMProviders.GOOGLE, new Uri("https var embeddingRequest = JsonSerializer.Serialize(payload, JSON_SERIALIZER_OPTIONS); var embedUrl = $"https://generativelanguage.googleapis.com/v1beta/models/{modelName}:embedContent"; using var request = new HttpRequestMessage(HttpMethod.Post, embedUrl); - request.Headers.Add("x-goog-api-key", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Add("x-goog-api-key", await this.DecryptAPIKey(requestedSecret)); // Set the content: request.Content = new StringContent(embeddingRequest, Encoding.UTF8, "application/json"); diff --git a/app/MindWork AI Studio/Provider/Helmholtz/ProviderHelmholtz.cs b/app/MindWork AI Studio/Provider/Helmholtz/ProviderHelmholtz.cs index 1be75bba4..918cd3efb 100644 --- a/app/MindWork AI Studio/Provider/Helmholtz/ProviderHelmholtz.cs +++ b/app/MindWork AI Studio/Provider/Helmholtz/ProviderHelmholtz.cs @@ -126,13 +126,16 @@ public sealed class ProviderHelmholtz() : BaseProvider(LLMProviders.HELMHOLTZ, n private async Task LoadModels(SecretStoreType storeType, string? apiKeyProvisional, CancellationToken token) { var secretKey = await this.GetModelLoadingSecretKey(storeType, apiKeyProvisional); - if (string.IsNullOrWhiteSpace(secretKey)) + if (secretKey.IsUnusable) + return UnusableAPIKeyModelLoadResult(); + + if (string.IsNullOrWhiteSpace(secretKey.Key)) return FailedModelLoadResult(ModelLoadFailureReason.INVALID_OR_MISSING_API_KEY, "No API key available for model loading."); try { using var request = new HttpRequestMessage(HttpMethod.Get, "models"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey.Key); using var response = await this.HttpClient.SendAsync(request, token); var body = await response.Content.ReadAsStringAsync(token); diff --git a/app/MindWork AI Studio/Provider/ModelLoadFailureReason.cs b/app/MindWork AI Studio/Provider/ModelLoadFailureReason.cs index 786bfedd6..bb7ea404f 100644 --- a/app/MindWork AI Studio/Provider/ModelLoadFailureReason.cs +++ b/app/MindWork AI Studio/Provider/ModelLoadFailureReason.cs @@ -4,6 +4,12 @@ public enum ModelLoadFailureReason { NONE, INVALID_OR_MISSING_API_KEY, + + /// + /// The API key contains a character which an HTTP header cannot carry, so the models were never requested. + /// + INVALID_API_KEY_CHARACTERS, + AUTHENTICATION_OR_PERMISSION_ERROR, INSUFFICIENT_QUOTA, TOO_MANY_REQUESTS, diff --git a/app/MindWork AI Studio/Provider/ModelLoadFailureReasonExtensions.cs b/app/MindWork AI Studio/Provider/ModelLoadFailureReasonExtensions.cs index 43fb8332d..3a7fc2375 100644 --- a/app/MindWork AI Studio/Provider/ModelLoadFailureReasonExtensions.cs +++ b/app/MindWork AI Studio/Provider/ModelLoadFailureReasonExtensions.cs @@ -1,4 +1,5 @@ using AIStudio.Tools.PluginSystem; +using AIStudio.Tools.Validation; namespace AIStudio.Provider; @@ -13,6 +14,7 @@ public static class ModelLoadFailureReasonExtensions public string ToUserMessage(string providerName) => failureReason switch { ModelLoadFailureReason.INVALID_OR_MISSING_API_KEY => string.Format(TB("We could not load models from '{0}'. The API key is probably missing, invalid, or expired."), providerName), + ModelLoadFailureReason.INVALID_API_KEY_CHARACTERS => APIKeyValidation.GetUnusableKeyMessage(providerName), ModelLoadFailureReason.AUTHENTICATION_OR_PERMISSION_ERROR => string.Format(TB("We could not load models from '{0}'. The account or API key does not have the required permissions."), providerName), ModelLoadFailureReason.INSUFFICIENT_QUOTA => string.Format(TB("We could not load models from '{0}' because the account appears to have no API credits left."), providerName), ModelLoadFailureReason.TOO_MANY_REQUESTS => string.Format(TA("We could not load models from '{0}' because too many requests were sent. Please wait a moment and try again."), providerName), diff --git a/app/MindWork AI Studio/Provider/ModelLoadingSecretKey.cs b/app/MindWork AI Studio/Provider/ModelLoadingSecretKey.cs new file mode 100644 index 000000000..0c206a762 --- /dev/null +++ b/app/MindWork AI Studio/Provider/ModelLoadingSecretKey.cs @@ -0,0 +1,33 @@ +namespace AIStudio.Provider; + +/// +/// The API key for loading the models of a provider, ready for a header. +/// +/// +/// A plain struct instead of a record on purpose: the generated ToString of a record would print the +/// key wherever somebody logs this value by mistake. +/// +/// The key without the whitespace around it, or null when there is none or it cannot be sent. +/// Whether the key contains a character which an HTTP header cannot carry. +public readonly struct ModelLoadingSecretKey(string? key, bool isUnusable) +{ + /// + /// No key at all, e.g., because none is stored. + /// + public static readonly ModelLoadingSecretKey NONE = new(null, false); + + /// + /// A key which cannot be sent, and which therefore is not handed out. + /// + public static readonly ModelLoadingSecretKey UNUSABLE = new(null, true); + + /// + /// The key without the whitespace around it, or null when there is none or it cannot be sent. + /// + public string? Key { get; } = key; + + /// + /// Whether the key contains a character which an HTTP header cannot carry. + /// + public bool IsUnusable { get; } = isUnusable; +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Provider/OpenAI/ProviderOpenAI.cs b/app/MindWork AI Studio/Provider/OpenAI/ProviderOpenAI.cs index d6d780cf2..01cc96a23 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ProviderOpenAI.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ProviderOpenAI.cs @@ -272,7 +272,7 @@ public sealed class ProviderOpenAI() : BaseProvider(LLMProviders.OPEN_AI, new Ur var request = new HttpRequestMessage(HttpMethod.Post, requestPath); // Set the authorization header: - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await this.DecryptAPIKey(requestedSecret)); // Set the content: request.Content = new StringContent(openAIChatRequest, Encoding.UTF8, "application/json"); @@ -303,7 +303,7 @@ public sealed class ProviderOpenAI() : BaseProvider(LLMProviders.OPEN_AI, new Ur async Task RequestBuilder() { var request = new HttpRequestMessage(HttpMethod.Post, "responses"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await this.DecryptAPIKey(requestedSecret)); request.Content = new StringContent(JsonSerializer.Serialize(requestDto, JSON_SERIALIZER_OPTIONS), Encoding.UTF8, "application/json"); return request; } diff --git a/app/MindWork AI Studio/Provider/ProviderRequestFailureReason.cs b/app/MindWork AI Studio/Provider/ProviderRequestFailureReason.cs index 752cf8959..5526eb0a3 100644 --- a/app/MindWork AI Studio/Provider/ProviderRequestFailureReason.cs +++ b/app/MindWork AI Studio/Provider/ProviderRequestFailureReason.cs @@ -24,6 +24,16 @@ public enum ProviderRequestFailureReason /// INVALID_OR_MISSING_API_KEY, + /// + /// The stored API key contains a character which an HTTP header cannot carry, so the request was never sent. + /// + /// + /// Such a key was stored before AI Studio checked keys, or reached the keyring some other way. + /// The provider never saw it, so this is no rejection of its own: the user has to enter the key + /// again, or ask whoever provides it. + /// + INVALID_API_KEY_CHARACTERS, + /// /// The key was accepted, but the account is not allowed to do what we asked for. /// diff --git a/app/MindWork AI Studio/Provider/ProviderRequestFailureReasonExtensions.cs b/app/MindWork AI Studio/Provider/ProviderRequestFailureReasonExtensions.cs index 9bd30fffa..36e5bdfce 100644 --- a/app/MindWork AI Studio/Provider/ProviderRequestFailureReasonExtensions.cs +++ b/app/MindWork AI Studio/Provider/ProviderRequestFailureReasonExtensions.cs @@ -21,6 +21,7 @@ public static class ProviderRequestFailureReasonExtensions ProviderRequestFailureReason.TOO_MANY_REQUESTS => TB("Too many requests"), ProviderRequestFailureReason.MODEL_NOT_SUPPORTED_BY_PROVIDER => TB("Model not offered"), ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY => TB("API key problem"), + ProviderRequestFailureReason.INVALID_API_KEY_CHARACTERS => TB("API key problem"), ProviderRequestFailureReason.AUTHENTICATION_OR_PERMISSION_ERROR => TB("Not permitted"), ProviderRequestFailureReason.PROVIDER_UNAVAILABLE => TB("Provider unreachable"), ProviderRequestFailureReason.MODEL_NOT_FOUND => TB("Model unknown"), @@ -41,6 +42,7 @@ public static class ProviderRequestFailureReasonExtensions /// public bool IsFixedInProviderSettings => failureReason is ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY or + ProviderRequestFailureReason.INVALID_API_KEY_CHARACTERS or ProviderRequestFailureReason.AUTHENTICATION_OR_PERMISSION_ERROR or ProviderRequestFailureReason.MODEL_NOT_FOUND or ProviderRequestFailureReason.MODEL_NOT_SUPPORTED_BY_PROVIDER or diff --git a/app/MindWork AI Studio/Provider/SelfHosted/ProviderSelfHosted.cs b/app/MindWork AI Studio/Provider/SelfHosted/ProviderSelfHosted.cs index 537c21bc3..fd7aef6f4 100644 --- a/app/MindWork AI Studio/Provider/SelfHosted/ProviderSelfHosted.cs +++ b/app/MindWork AI Studio/Provider/SelfHosted/ProviderSelfHosted.cs @@ -195,6 +195,8 @@ public sealed class ProviderSelfHosted(Host host, string hostname) : BaseProvide private async Task LoadModels(SecretStoreType storeType, string? apiKeyProvisional, CancellationToken token) { var secretKey = await this.GetModelLoadingSecretKey(storeType, apiKeyProvisional, isTryingSecret: true); + if (secretKey.IsUnusable) + return UnusableAPIKeyModelLoadResult(); try { @@ -204,8 +206,8 @@ public sealed class ProviderSelfHosted(Host host, string hostname) : BaseProvide // rejects an empty bearer with 401, where it would have let a request without any // authorization header through. The dialogs hand us their key field as it stands, so // an empty string arrives here whenever the user stored no key: - if(!string.IsNullOrWhiteSpace(secretKey)) - lmStudioRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey); + if(!string.IsNullOrWhiteSpace(secretKey.Key)) + lmStudioRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey.Key); using var lmStudioResponse = await this.HttpClient.SendAsync(lmStudioRequest, token); if(!lmStudioResponse.IsSuccessStatusCode) @@ -288,12 +290,14 @@ public sealed class ProviderSelfHosted(Host host, string hostname) : BaseProvide private async Task LoadLlamaCppTextModels(string? apiKeyProvisional, CancellationToken token) { var secretKey = await this.GetModelLoadingSecretKey(SecretStoreType.LLM_PROVIDER, apiKeyProvisional, true); + if (secretKey.IsUnusable) + return UnusableAPIKeyModelLoadResult(); try { using var request = new HttpRequestMessage(HttpMethod.Get, "models"); - if (!string.IsNullOrWhiteSpace(secretKey)) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey); + if (!string.IsNullOrWhiteSpace(secretKey.Key)) + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey.Key); using var response = await this.HttpClient.SendAsync(request, token); var responseBody = await response.Content.ReadAsStringAsync(token); diff --git a/app/MindWork AI Studio/Settings/EmbeddingProvider.cs b/app/MindWork AI Studio/Settings/EmbeddingProvider.cs index 596c737aa..c2818fc9f 100644 --- a/app/MindWork AI Studio/Settings/EmbeddingProvider.cs +++ b/app/MindWork AI Studio/Settings/EmbeddingProvider.cs @@ -4,6 +4,7 @@ using AIStudio.Provider; using AIStudio.Provider.HuggingFace; using AIStudio.Tools.PluginSystem; using AIStudio.Tools.Services; +using AIStudio.Tools.Validation; using SharedTools; @@ -221,17 +222,21 @@ public sealed record EmbeddingProvider( // // Queue the API key for storage in the OS keyring. A dry run only checks the // configuration, so it queues nothing: the start which follows it would - // otherwise store the key once more for every dry run before it: + // otherwise store the key once more for every dry run before it. A key which + // cannot be sent is reported either way, so that a dry run tells about it too: // - if (!dryRun) - { - PendingEnterpriseApiKeys.Add(new( + var apiKeyIssue = dryRun + ? APIKeyValidation.Check(decryptedApiKey) + : PendingEnterpriseApiKeys.Add(new( $"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}", name, decryptedApiKey, SecretStoreType.EMBEDDING_PROVIDER)); + + if (apiKeyIssue.IsProblem) + LOGGER.LogWarning($"The API key for embedding provider {idx} contains a character which an API key cannot contain ({apiKeyIssue.Kind}). It will not be stored. (Plugin ID: {configPluginId})"); + else if (!dryRun) LOGGER.LogDebug($"Successfully decrypted API key for embedding provider {idx}. It will be stored in the OS keyring. (Plugin ID: {configPluginId})"); - } } else LOGGER.LogWarning($"Failed to decrypt API key for embedding provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})"); diff --git a/app/MindWork AI Studio/Settings/Provider.cs b/app/MindWork AI Studio/Settings/Provider.cs index 318b775b4..7b609e9aa 100644 --- a/app/MindWork AI Studio/Settings/Provider.cs +++ b/app/MindWork AI Studio/Settings/Provider.cs @@ -4,6 +4,7 @@ using AIStudio.Provider; using AIStudio.Provider.HuggingFace; using AIStudio.Tools.PluginSystem; using AIStudio.Tools.Services; +using AIStudio.Tools.Validation; using SharedTools; @@ -242,17 +243,21 @@ public sealed record Provider( // // Queue the API key for storage in the OS keyring. A dry run only checks the // configuration, so it queues nothing: the start which follows it would - // otherwise store the key once more for every dry run before it: + // otherwise store the key once more for every dry run before it. A key which + // cannot be sent is reported either way, so that a dry run tells about it too: // - if (!dryRun) - { - PendingEnterpriseApiKeys.Add(new( + var apiKeyIssue = dryRun + ? APIKeyValidation.Check(decryptedApiKey) + : PendingEnterpriseApiKeys.Add(new( $"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}", instanceName, decryptedApiKey, SecretStoreType.LLM_PROVIDER)); + + if (apiKeyIssue.IsProblem) + LOGGER.LogWarning($"The API key for provider {idx} contains a character which an API key cannot contain ({apiKeyIssue.Kind}). It will not be stored. (Plugin ID: {configPluginId})"); + else if (!dryRun) LOGGER.LogDebug($"Successfully decrypted API key for provider {idx}. It will be stored in the OS keyring. (Plugin ID: {configPluginId})"); - } } else LOGGER.LogWarning($"Failed to decrypt API key for provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})"); diff --git a/app/MindWork AI Studio/Settings/TranscriptionProvider.cs b/app/MindWork AI Studio/Settings/TranscriptionProvider.cs index 4b3eb62f6..ac4707be2 100644 --- a/app/MindWork AI Studio/Settings/TranscriptionProvider.cs +++ b/app/MindWork AI Studio/Settings/TranscriptionProvider.cs @@ -3,6 +3,7 @@ using System.Text.Json.Serialization; using AIStudio.Provider; using AIStudio.Provider.HuggingFace; using AIStudio.Tools.PluginSystem; +using AIStudio.Tools.Validation; using SharedTools; @@ -184,17 +185,21 @@ public sealed record TranscriptionProvider( // // Queue the API key for storage in the OS keyring. A dry run only checks the // configuration, so it queues nothing: the start which follows it would - // otherwise store the key once more for every dry run before it: + // otherwise store the key once more for every dry run before it. A key which + // cannot be sent is reported either way, so that a dry run tells about it too: // - if (!dryRun) - { - PendingEnterpriseApiKeys.Add(new( + var apiKeyIssue = dryRun + ? APIKeyValidation.Check(decryptedApiKey) + : PendingEnterpriseApiKeys.Add(new( $"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}", name, decryptedApiKey, SecretStoreType.TRANSCRIPTION_PROVIDER)); + + if (apiKeyIssue.IsProblem) + LOGGER.LogWarning($"The API key for transcription provider {idx} contains a character which an API key cannot contain ({apiKeyIssue.Kind}). It will not be stored. (Plugin ID: {configPluginId})"); + else if (!dryRun) LOGGER.LogDebug($"Successfully decrypted API key for transcription provider {idx}. It will be stored in the OS keyring. (Plugin ID: {configPluginId})"); - } } else LOGGER.LogWarning($"Failed to decrypt API key for transcription provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})"); diff --git a/app/MindWork AI Studio/Tools/PluginSystem/PendingEnterpriseApiKeys.cs b/app/MindWork AI Studio/Tools/PluginSystem/PendingEnterpriseApiKeys.cs index 8824424ea..f8aa11b65 100644 --- a/app/MindWork AI Studio/Tools/PluginSystem/PendingEnterpriseApiKeys.cs +++ b/app/MindWork AI Studio/Tools/PluginSystem/PendingEnterpriseApiKeys.cs @@ -1,3 +1,5 @@ +using AIStudio.Tools.Validation; + namespace AIStudio.Tools.PluginSystem; /// @@ -9,13 +11,26 @@ public static class PendingEnterpriseApiKeys private static readonly Lock LOCK = new(); /// - /// Adds a pending API key to the list. + /// Adds a pending API key to the list, unless it cannot be sent. /// + /// + /// The whitespace around the key goes, e.g., a line break which came along when somebody copied + /// the key before encrypting it. A key with any other character which an HTTP header cannot carry + /// stays out: stored, it would fail with every request, and nobody on the device could change it. + /// The caller logs that, since it knows which provider of which plugin the key belongs to. + /// /// The pending API key to add. - public static void Add(PendingEnterpriseApiKey key) + /// NONE when the key was added, otherwise why it was left out. + public static APIKeyIssue Add(PendingEnterpriseApiKey key) { + var issue = APIKeyValidation.Check(key.ApiKey); + if (issue.IsProblem) + return issue; + lock (LOCK) - PENDING_KEYS.Add(key); + PENDING_KEYS.Add(key with { ApiKey = APIKeyValidation.Normalize(key.ApiKey) }); + + return APIKeyIssue.NONE; } /// diff --git a/app/MindWork AI Studio/Tools/Services/RustService.APIKeys.cs b/app/MindWork AI Studio/Tools/Services/RustService.APIKeys.cs index d9909275a..07ef0166c 100644 --- a/app/MindWork AI Studio/Tools/Services/RustService.APIKeys.cs +++ b/app/MindWork AI Studio/Tools/Services/RustService.APIKeys.cs @@ -1,4 +1,5 @@ using AIStudio.Tools.Rust; +using AIStudio.Tools.Validation; namespace AIStudio.Tools.Services; @@ -85,13 +86,18 @@ public sealed partial class RustService /// /// Try to store the API key for the given secret ID. /// + /// + /// The whitespace around the key goes, a line break copied along with it included: an HTTP header + /// drops it anyway, and every key ends up in one. Passwords, which may well start or end with a + /// space, take SetSecret instead and stay as they are. + /// /// The secret ID to store the API key for. /// The API key to store. /// The secret store type. Defaults to LLM_PROVIDER for backward compatibility. /// The store secret response. public async Task SetAPIKey(ISecretId secretId, string key, SecretStoreType storeType) { - var encryptedKey = await this.encryptor!.Encrypt(key); + var encryptedKey = await this.encryptor!.Encrypt(APIKeyValidation.Normalize(key)); var secretKey = APIKey(storeType, secretId); var state = await this.StoreEncryptedAPIKeyByKey(secretKey, encryptedKey); if (state.Success) diff --git a/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolCallingImplementations/WebSearch/Staan/StaanSearchBackend.cs b/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolCallingImplementations/WebSearch/Staan/StaanSearchBackend.cs index 2ef73de17..47c440ecb 100644 --- a/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolCallingImplementations/WebSearch/Staan/StaanSearchBackend.cs +++ b/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolCallingImplementations/WebSearch/Staan/StaanSearchBackend.cs @@ -1,4 +1,5 @@ using AIStudio.Tools.PluginSystem; +using AIStudio.Tools.Validation; namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Staan; @@ -65,7 +66,7 @@ public sealed class StaanSearchBackend : IWebSearchBackend public void DeclareSettings(ToolSettingsSchemaBuilder builder) => builder .InGroup(SETTINGS_GROUP) - .OptionalSecret(API_KEY_SETTING) + .OptionalAPIKey(API_KEY_SETTING) .OptionalEnum(MARKET_SETTING, SUPPORTED_MARKETS) .InGroup(string.Empty); @@ -125,6 +126,13 @@ public sealed class StaanSearchBackend : IWebSearchBackend if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException(TB("A Staan API key is required.")); + // + // A key stored before AI Studio checked keys, or one the organization provides, may hold a + // character the header cannot carry. The dispatcher asks the other services all the same: + // + if (!APIKeyValidation.TryPrepareForHeader(apiKey, out var headerAPIKey)) + throw new InvalidOperationException(APIKeyValidation.GetUnusableKeyMessage("Staan")); + // // Staan refuses a longer query outright. Shortening it here would search for something // other than what was asked, so the model is told and can search again instead: @@ -141,7 +149,7 @@ public sealed class StaanSearchBackend : IWebSearchBackend var market = ResolveMarket(query.Language, settingsValues, notes); var searchRequest = new StaanSearchRequest { Query = query.Query, Market = market, Offset = ReadOffset(query.Page) }; - var response = await this.searchClient.SearchAsync(apiKey.Trim(), searchRequest, query.TimeoutSeconds, token); + var response = await this.searchClient.SearchAsync(headerAPIKey, searchRequest, query.TimeoutSeconds, token); // // Staan corrects an obvious mistake in a query and says so. Which query actually ran is diff --git a/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolCallingImplementations/WebSearch/Tavily/TavilySearchBackend.cs b/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolCallingImplementations/WebSearch/Tavily/TavilySearchBackend.cs index b634dec46..1e52b48bc 100644 --- a/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolCallingImplementations/WebSearch/Tavily/TavilySearchBackend.cs +++ b/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolCallingImplementations/WebSearch/Tavily/TavilySearchBackend.cs @@ -1,4 +1,5 @@ using AIStudio.Tools.PluginSystem; +using AIStudio.Tools.Validation; namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Tavily; @@ -58,7 +59,7 @@ public sealed class TavilySearchBackend : IWebSearchBackend public void DeclareSettings(ToolSettingsSchemaBuilder builder) => builder .InGroup(SETTINGS_GROUP) - .OptionalSecret(API_KEY_SETTING) + .OptionalAPIKey(API_KEY_SETTING) .OptionalEnum(SEARCH_DEPTH_SETTING, SUPPORTED_SEARCH_DEPTHS) .InGroup(string.Empty); @@ -118,6 +119,13 @@ public sealed class TavilySearchBackend : IWebSearchBackend if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException(TB("A Tavily API key is required.")); + // + // A key stored before AI Studio checked keys, or one the organization provides, may hold a + // character the header cannot carry. The dispatcher asks the other services all the same: + // + if (!APIKeyValidation.TryPrepareForHeader(apiKey, out var headerAPIKey)) + throw new InvalidOperationException(APIKeyValidation.GetUnusableKeyMessage("Tavily")); + var notes = new List(); var language = ResolveLanguage(query.Language, notes); var searchRequest = new TavilySearchRequest @@ -138,7 +146,7 @@ public sealed class TavilySearchBackend : IWebSearchBackend SafeSearch = query.SafeSearch?.TavilyValue, }; - var response = await this.searchClient.SearchAsync(apiKey.Trim(), searchRequest, query.TimeoutSeconds, token); + var response = await this.searchClient.SearchAsync(headerAPIKey, searchRequest, query.TimeoutSeconds, token); var hits = response.Results.Select(result => new SearchHit(result.Url, result.Title, result.Content)); var candidates = SearchCandidateCollector.Collect(WebSearchBackend.TAVILY, hits, query.Limit, out var candidateCount); return new WebSearchBackendResult(WebSearchBackend.TAVILY, candidates, candidateCount, notes); diff --git a/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolSettingsFieldDefinition.cs b/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolSettingsFieldDefinition.cs index 30db093ef..c42fff287 100644 --- a/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolSettingsFieldDefinition.cs +++ b/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolSettingsFieldDefinition.cs @@ -26,6 +26,18 @@ public sealed class ToolSettingsFieldDefinition public bool Secret { get; init; } + /// + /// Whether the field holds an API key, which is always a secret as well. + /// + /// + /// An API key goes into an HTTP header, which carries nothing but ASCII. The settings dialog + /// therefore checks what the user enters there. Settings validation leaves the key alone on + /// purpose, since it decides whether the tool is offered at all: a key which was stored before, + /// or which the organization provides, would switch off the whole tool without a word. The + /// tool checks a stored key again before sending it. + /// + public bool IsAPIKey { get; init; } + /// /// Name of the group this field belongs to, or empty when it stands on its own. /// diff --git a/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolSettingsSchemaBuilder.cs b/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolSettingsSchemaBuilder.cs index a42af6124..20a06a888 100644 --- a/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolSettingsSchemaBuilder.cs +++ b/app/MindWork AI Studio/Tools/ToolCallingSystem/ToolSettingsSchemaBuilder.cs @@ -68,19 +68,29 @@ public sealed class ToolSettingsSchemaBuilder public ToolSettingsSchemaBuilder RequiredSecret(string name) => this.Add(name, isRequired: true, isSecret: true); + /// + /// An optional API key, kept in the operating system's keyring like any secret. + /// + /// + /// Use this instead of a plain secret for every key which goes into an HTTP header, so that the + /// settings dialog tells the user about a character the header cannot carry. + /// + public ToolSettingsSchemaBuilder OptionalAPIKey(string name) => this.Add(name, isRequired: false, isSecret: true, isAPIKey: true); + public ToolSettingsSchema Build() => new() { Properties = new(this.properties, StringComparer.Ordinal), Required = [..this.requiredNames], }; - private ToolSettingsSchemaBuilder Add(string name, bool isRequired, string optionSource = "", bool isSecret = false, IReadOnlyList? enumValues = null) + private ToolSettingsSchemaBuilder Add(string name, bool isRequired, string optionSource = "", bool isSecret = false, IReadOnlyList? enumValues = null, bool isAPIKey = false) { this.properties[name] = new ToolSettingsFieldDefinition { OptionSource = optionSource, EnumValues = enumValues?.ToList() ?? [], Secret = isSecret, + IsAPIKey = isAPIKey, Group = this.currentGroup, }; diff --git a/app/MindWork AI Studio/Tools/Validation/APIKeyIssue.cs b/app/MindWork AI Studio/Tools/Validation/APIKeyIssue.cs new file mode 100644 index 000000000..dfd02693d --- /dev/null +++ b/app/MindWork AI Studio/Tools/Validation/APIKeyIssue.cs @@ -0,0 +1,20 @@ +namespace AIStudio.Tools.Validation; + +/// +/// The first character of an API key which cannot be sent. +/// +/// +/// The key itself never goes in here: this value ends up in messages, and its kind in the log. +/// Only a character the user can see is kept, so that a message can name it. +/// +/// What is wrong with the character. +/// The character as the user sees it, or empty unless it is a visible character outside of ASCII. +public readonly record struct APIKeyIssue(APIKeyIssueKind Kind, string Character) +{ + public static readonly APIKeyIssue NONE = new(APIKeyIssueKind.NONE, string.Empty); + + /// + /// Whether the key cannot be sent. + /// + public bool IsProblem => this.Kind is not APIKeyIssueKind.NONE; +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Validation/APIKeyIssueKind.cs b/app/MindWork AI Studio/Tools/Validation/APIKeyIssueKind.cs new file mode 100644 index 000000000..ab394070d --- /dev/null +++ b/app/MindWork AI Studio/Tools/Validation/APIKeyIssueKind.cs @@ -0,0 +1,32 @@ +namespace AIStudio.Tools.Validation; + +/// +/// What keeps an API key from being sent, as far as its characters tell. +/// +public enum APIKeyIssueKind +{ + NONE, + + /// + /// A space, a tab, or a line break inside the key. + /// + /// + /// No provider issues keys with whitespace, so the user most likely copied more than the key, + /// e.g., two lines of a table or the key together with its name. + /// + WHITESPACE, + + /// + /// A character nobody sees, e.g., a zero-width space, a byte order mark, or a control character. + /// + /// + /// Web pages and documents add such characters to what they show, and they come along when the + /// user copies the key from there. + /// + INVISIBLE_CHARACTER, + + /// + /// A visible character outside of ASCII, e.g., an umlaut or a typographic quotation mark. + /// + NON_ASCII_CHARACTER, +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Validation/APIKeyValidation.cs b/app/MindWork AI Studio/Tools/Validation/APIKeyValidation.cs new file mode 100644 index 000000000..fde571d46 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Validation/APIKeyValidation.cs @@ -0,0 +1,186 @@ +using System.Buffers; +using System.Globalization; +using System.Text; + +using AIStudio.Tools.PluginSystem; + +namespace AIStudio.Tools.Validation; + +/// +/// Checks whether an API key can be sent to a provider at all. +/// +/// +/// +/// API keys travel in HTTP headers, and these carry nothing but ASCII. .NET refuses every other +/// character only while sending, with a message nobody understands, such as "Request headers must +/// contain only ASCII characters." Two of its messages about line breaks even quote the value of +/// the header, i.e., the key. Hence, AI Studio checks what a key picked up on its way through the +/// clipboard before storing it, and again before sending it. +/// +/// +/// Whitespace around the key goes: nobody means it, and HTTP drops it anyway. Everything else is +/// reported instead of removed. A key with an invisible character in its middle might as well be +/// two keys glued together, and guessing which part is the key would send the wrong one. +/// +/// +/// Nothing here writes the key anywhere. Messages name at most the one character which cannot be +/// sent, and only when the user can see it; logs name the kind of the issue alone. +/// +/// +public static class APIKeyValidation +{ + private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(APIKeyValidation).Namespace, nameof(APIKeyValidation)); + + /// + /// A blank pattern of the Braille block: a letter by its category, but nothing to see. + /// + private const int BRAILLE_PATTERN_BLANK = 0x2800; + + /// + /// Removes the whitespace around a key, line breaks and no-break spaces included. + /// + /// + /// Zero-width spaces and byte order marks stay: .NET does not count them as whitespace, and + /// the check reports them. + /// + /// The key as the user entered it. + /// The key without the whitespace around it, or an empty string for no key. + public static string Normalize(string? key) => key?.Trim() ?? string.Empty; + + /// + /// Finds the first character of a key which cannot be sent. + /// + /// + /// The key is read character by character as the user sees them, i.e., by grapheme cluster: + /// an umlaut typed as a letter and a combining mark, as macOS does in file names, is one + /// character and is reported as such, not as an invisible mark. An empty key is no issue, + /// since whether a key may be missing is up to the caller. + /// + /// The key as the user entered it. + /// The first issue, or NONE when the key can be sent. + public static APIKeyIssue Check(string? key) + { + var characters = StringInfo.GetTextElementEnumerator(Normalize(key)); + while (characters.MoveNext()) + { + var issue = CheckCharacter(characters.GetTextElement()); + if (issue.IsProblem) + return issue; + } + + return APIKeyIssue.NONE; + } + + /// + /// Prepares a key for an HTTP header. + /// + /// The key as it was entered or stored. + /// The key without the whitespace around it, or an empty string when it cannot be sent. + /// True when the key can be sent, which includes an empty key. + public static bool TryPrepareForHeader(string? key, out string headerValue) + { + headerValue = Normalize(key); + if (!Check(headerValue).IsProblem) + return true; + + headerValue = string.Empty; + return false; + } + + /// + /// Checks a key the user is entering. + /// + /// The key as the user entered it. + /// What is wrong with the key, or null when it can be sent. + public static string? Validate(string? key) + { + var issue = Check(key); + return issue.IsProblem ? GetMessage(issue) : null; + } + + /// + /// Tells the user what is wrong with the key they entered. + /// + /// The issue the check found. + /// The message, or an empty string when there is no issue. + public static string GetMessage(APIKeyIssue issue) => issue.Kind switch + { + APIKeyIssueKind.WHITESPACE => TA("The API key contains a space or a line break, which an API key cannot contain. Please check whether you copied more than the key."), + APIKeyIssueKind.INVISIBLE_CHARACTER => TA("The API key contains an invisible character, which often comes along when you copy text from a web page or a document. Please delete the key and enter it again."), + APIKeyIssueKind.NON_ASCII_CHARACTER => string.Format(TA("The API key contains the character '{0}', which an API key cannot contain. Word processors, for example, turn quotation marks and dashes into such characters. Please check the key."), issue.Character), + + _ => string.Empty, + }; + + /// + /// Tells the user that a stored key cannot be sent. + /// + /// + /// Meant for a key which was stored before AI Studio checked keys, or which reached the keyring + /// some other way. The user may not be able to change it, e.g., when the organization provides + /// it, so the message names that way out as well. + /// + /// The provider or service the key belongs to. + /// The message. + public static string GetUnusableKeyMessage(string ownerName) => string.Format(TA("The API key for '{0}' contains a character which an API key cannot contain, such as a line break or an invisible character. Please enter the key again in the settings. If your organization provides the key, please contact your IT department."), ownerName); + + private static APIKeyIssue CheckCharacter(string character) + { + if (character.Length is 1 && character[0] is >= '!' and <= '~') + return APIKeyIssue.NONE; + + // + // A character as the user sees it may consist of several code points, e.g., a letter and + // its accent, or a letter and a zero-width joiner someone hid behind it. Whitespace wins, + // since it tells the user best what went wrong while copying. Anything invisible in the + // character makes the whole character one nobody can point at: + // + var isInvisible = false; + var remaining = character.AsSpan(); + while (!remaining.IsEmpty) + { + if (Rune.DecodeFromUtf16(remaining, out var codePoint, out var length) is not OperationStatus.Done) + { + // A lone surrogate is no character at all: + isInvisible = true; + remaining = remaining[Math.Max(length, 1)..]; + continue; + } + + if (Rune.IsWhiteSpace(codePoint)) + return new(APIKeyIssueKind.WHITESPACE, string.Empty); + + if (IsInvisible(codePoint)) + isInvisible = true; + + remaining = remaining[length..]; + } + + return isInvisible + ? new(APIKeyIssueKind.INVISIBLE_CHARACTER, string.Empty) + : new(APIKeyIssueKind.NON_ASCII_CHARACTER, character.Normalize(NormalizationForm.FormC)); + } + + /// + /// Whether a code point shows nothing by itself. + /// + /// + /// Besides control and format characters, these are the default-ignorable code points of + /// Unicode, which a renderer shows as nothing even where their category says otherwise, e.g., + /// the Hangul fillers, which count as letters, and the variation selectors, which count as marks. + /// + private static bool IsInvisible(Rune codePoint) => Rune.GetUnicodeCategory(codePoint) is UnicodeCategory.Control or UnicodeCategory.Format or UnicodeCategory.PrivateUse or UnicodeCategory.OtherNotAssigned or UnicodeCategory.Surrogate + || codePoint.Value is + 0x00AD or 0x034F or 0x061C or 0x3164 or 0xFEFF or 0xFFA0 or BRAILLE_PATTERN_BLANK or + (>= 0x115F and <= 0x1160) or + (>= 0x17B4 and <= 0x17B5) or + (>= 0x180B and <= 0x180F) or + (>= 0x200B and <= 0x200F) or + (>= 0x202A and <= 0x202E) or + (>= 0x2060 and <= 0x206F) or + (>= 0xFE00 and <= 0xFE0F) or + (>= 0xFFF0 and <= 0xFFF8) or + (>= 0x1BCA0 and <= 0x1BCA3) or + (>= 0x1D173 and <= 0x1D17A) or + (>= 0xE0000 and <= 0xE0FFF); +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Validation/ProviderValidation.cs b/app/MindWork AI Studio/Tools/Validation/ProviderValidation.cs index 40914018a..09cc0ca58 100644 --- a/app/MindWork AI Studio/Tools/Validation/ProviderValidation.cs +++ b/app/MindWork AI Studio/Tools/Validation/ProviderValidation.cs @@ -59,13 +59,11 @@ public sealed class ProviderValidation return apiKeyStorageIssue; // A self-hosted server may well run without any key, so an empty field is fine for it: - if(this.GetProvider() is LLMProviders.SELF_HOSTED) - return null; - if(string.IsNullOrWhiteSpace(apiKey)) - return TA("Please enter an API key."); + return this.GetProvider() is LLMProviders.SELF_HOSTED ? null : TA("Please enter an API key."); - return null; + // A key which is there has to be one we can send, also the optional key of a self-hosted server: + return APIKeyValidation.Validate(apiKey); } public string? ValidatingInstanceName(string instanceName) diff --git a/app/MindWork AI Studio/wwwroot/app.css b/app/MindWork AI Studio/wwwroot/app.css index 32633e5cf..8d98cd829 100644 --- a/app/MindWork AI Studio/wwwroot/app.css +++ b/app/MindWork AI Studio/wwwroot/app.css @@ -284,8 +284,9 @@ text-align: left; } -.configuration-help-justified .mud-input-helper-text, -.configuration-help-justified .mud-form-helpertext { +/* Every hint and every issue below a field, justified like the texts around it; app.css comes after MudBlazor's own rule */ +.mud-input-helper-text, +.mud-form-helpertext { text-align: justify; hyphens: auto; word-break: auto-phrase; diff --git a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md index 93e30d25d..fa3c2955e 100644 --- a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md +++ b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md @@ -24,6 +24,9 @@ - Improved the assistants when a request nearly fills the context window of the selected model: before sending it, AI Studio tells you, so that you can attach fewer or smaller files, or send the request anyway. - Improved the settings of the AI tasks, which AI Studio hands to a model on its own, such as the data source selection or the text content cleaner, formerly called agents: for each of them, you can now set the minimum confidence its provider needs, and the provider selection tells you which model AI Studio uses when you choose none. - Improved classic RAG: when the model you chose for selecting data sources or validating retrieval contexts may not see the data sources of your chat, AI Studio now uses the model of the chat for this step instead of skipping it. +- Improved entering API keys: AI Studio removes spaces and line breaks around a pasted key and tells you right away when a key contains a character which an API key cannot contain, such as an invisible character copied from a web page or a typographic quotation mark. +- Improved the message when a stored API key contains a character which an API key cannot contain, such as a line break: AI Studio now asks you to enter the key again instead of showing a technical error. +- Improved the API keys which organizations provide through configuration plugins: AI Studio removes spaces and line breaks around them and leaves out a key with characters which an API key cannot contain, noting this in the log. - Improved the Flatpak version of AI Studio for Linux: it now runs on the GNOME 51 runtime, ships the same up-to-date version of .NET, and is built with the same up-to-date version of Rust as all other versions of AI Studio. - Changed the icons of AI Studio to Lucide, an open-source icon set. All icons now share one style, and each feature shows the same icon wherever you meet it. - Fixed assistant plugins, which all appeared under "Installed Assistants" on the assistants page. Each one now appears under its own category, such as "Business", next to the built-in assistants of that category. diff --git a/app/Tests/Provider/APIKeyHeaderTests.cs b/app/Tests/Provider/APIKeyHeaderTests.cs new file mode 100644 index 000000000..7e01ec4d9 --- /dev/null +++ b/app/Tests/Provider/APIKeyHeaderTests.cs @@ -0,0 +1,138 @@ +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; + +using AIStudio.Provider; +using AIStudio.Provider.Anthropic; +using AIStudio.Provider.Helmholtz; +using AIStudio.Provider.OpenAI; +using AIStudio.Provider.SelfHosted; +using AIStudio.Settings; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; + +namespace AIStudio.Tests.Provider; + +/// +/// Checks that no API key reaches a header which the header cannot carry. +/// +/// +/// +/// .NET refuses such a key only while sending, with a message nobody understands, and two of its +/// messages about line breaks even quote the key. A provider therefore never decrypts a stored key +/// on its own: BaseProvider checks every key before it goes into a header, and the providers which +/// load their models on their own ways check the key they get from there. +/// +/// +/// Headers.Add parses an Authorization header and quotes the whole value in its exception when it +/// cannot, e.g., for a bare key with a '/'. A provider therefore sets this header through +/// AuthenticationHeaderValue or, for a bare key, through TryAddWithoutValidation. +/// +/// +/// The models are loaded with a key the user is entering, which needs neither the keyring nor the +/// network: a key which cannot be sent is refused before any request. Building a provider reads the +/// settings, so they are reached through Program.SERVICE_PROVIDER, as in the app. +/// +/// +[TestFixture] +[NonParallelizable] +public sealed partial class APIKeyHeaderTests +{ + private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString(); + + /// + /// A key as Fireworks issues them, which its transcription gets without the scheme 'Bearer'. + /// + private const string BARE_KEY = "fw_3ZAbC123xyz"; + + private ServiceProvider serviceProvider = null!; + private IServiceProvider previousServiceProvider = null!; + + [SetUp] + public void CreateSettings() + { + this.previousServiceProvider = Program.SERVICE_PROVIDER; + this.serviceProvider = new ServiceCollection().AddSingleton(new SettingsManager(NullLogger.Instance, null!)).BuildServiceProvider(); + Program.SERVICE_PROVIDER = this.serviceProvider; + } + + [TearDown] + public void RestoreApplicationState() + { + Program.SERVICE_PROVIDER = this.previousServiceProvider; + this.serviceProvider.Dispose(); + } + + [Test] + public void OnlyBaseProviderDecryptsAKeyForAHeader() + { + var providerDirectory = Path.Combine(AppSourceDirectory(), "Provider"); + var decryptions = Directory.EnumerateFiles(providerDirectory, "*.cs", SearchOption.AllDirectories) + .Select(path => (Path.GetRelativePath(providerDirectory, path), DecryptionRegex().Count(File.ReadAllText(path)))) + .Where(file => file.Item2 > 0) + .ToDictionary(file => file.Item1, file => file.Item2); + + Assert.That(decryptions, Is.EqualTo(new Dictionary { ["BaseProvider.cs"] = 2 }), "A stored key goes into a header through DecryptAPIKey only; GetModelLoadingSecretKey is the other place which may decrypt one."); + } + + [Test] + public void NoProviderParsesAKeyAsAnAuthorizationHeader() + { + var providerDirectory = Path.Combine(AppSourceDirectory(), "Provider"); + var files = Directory.EnumerateFiles(providerDirectory, "*.cs", SearchOption.AllDirectories) + .Where(path => ValidatedAuthorizationRegex().IsMatch(File.ReadAllText(path))) + .Select(path => Path.GetRelativePath(providerDirectory, path)); + + Assert.That(files, Is.Empty, "Headers.Add quotes an Authorization header it cannot parse, i.e., the key, in its exception; use AuthenticationHeaderValue, or TryAddWithoutValidation for a bare key."); + } + + [Test] + public void ABareKeyGoesOutAsBefore() + { + using var validated = new HttpRequestMessage(); + validated.Headers.Add("Authorization", BARE_KEY); + + using var unvalidated = new HttpRequestMessage(); + unvalidated.Headers.TryAddWithoutValidation("Authorization", BARE_KEY); + + Assert.That(unvalidated.Headers.ToString(), Is.EqualTo(validated.Headers.ToString())); + } + + private static IEnumerable ProvidersWhichLoadModels() + { + yield return new TestCaseData(() => new ProviderOpenAI()).SetArgDisplayNames("OpenAI"); + yield return new TestCaseData(() => new ProviderAnthropic()).SetArgDisplayNames("Anthropic"); + yield return new TestCaseData(() => new ProviderHelmholtz()).SetArgDisplayNames("Helmholtz"); + yield return new TestCaseData(() => new ProviderSelfHosted(Host.OLLAMA, "http://localhost:11434")).SetArgDisplayNames("Ollama"); + yield return new TestCaseData(() => new ProviderSelfHosted(Host.LLAMA_CPP, "http://localhost:8080")).SetArgDisplayNames("llama.cpp"); + } + + [TestCaseSource(nameof(ProvidersWhichLoadModels))] + public async Task AKeyWhichCannotBeSentLoadsNoModels(Func createProvider) + { + var provider = createProvider(); + var result = await provider.GetTextModels($"sk-proj{ZERO_WIDTH_SPACE}AbC123"); + + // Anthropic adds the models it knows anyway, so only the reason tells: + Assert.That(result.FailureReason, Is.EqualTo(ModelLoadFailureReason.INVALID_API_KEY_CHARACTERS)); + } + + [Test] + public void TheUserLearnsWhatToDo() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(ModelLoadFailureReason.INVALID_API_KEY_CHARACTERS.ToUserMessage("My provider"), Does.Contain("My provider")); + Assert.That(ProviderRequestFailureReason.INVALID_API_KEY_CHARACTERS.Name, Is.Not.Empty); + Assert.That(ProviderRequestFailureReason.INVALID_API_KEY_CHARACTERS.IsFixedInProviderSettings, Is.True); + } + } + + [GeneratedRegex(@"\.Decrypt\(Program\.ENCRYPTION\)")] + private static partial Regex DecryptionRegex(); + + [GeneratedRegex(@"\.Headers\.Add\(\s*""Authorization""")] + private static partial Regex ValidatedAuthorizationRegex(); + + private static string AppSourceDirectory([CallerFilePath] string sourceFilePath = "") => Path.GetFullPath(Path.Combine(Path.GetDirectoryName(sourceFilePath)!, "..", "..", "MindWork AI Studio")); +} \ No newline at end of file diff --git a/app/Tests/Tools/PluginSystem/PendingEnterpriseApiKeysTests.cs b/app/Tests/Tools/PluginSystem/PendingEnterpriseApiKeysTests.cs new file mode 100644 index 000000000..a85da96f9 --- /dev/null +++ b/app/Tests/Tools/PluginSystem/PendingEnterpriseApiKeysTests.cs @@ -0,0 +1,48 @@ +using AIStudio.Tools; +using AIStudio.Tools.PluginSystem; +using AIStudio.Tools.Validation; + +namespace AIStudio.Tests.Tools.PluginSystem; + +/// +/// Checks which API keys of configuration plugins AI Studio stores in the keyring. +/// +/// +/// Nobody on the device can change a key which the organization provides. A key which an HTTP header +/// cannot carry would therefore fail with every request, for good, and stays out of the keyring. The +/// queue is process-wide state, so these tests empty it before and after each run. +/// +[TestFixture] +[NonParallelizable] +public sealed class PendingEnterpriseApiKeysTests +{ + private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString(); + + [SetUp] + [TearDown] + public void EmptyTheQueue() => PendingEnterpriseApiKeys.GetAndClear(); + + private static PendingEnterpriseApiKey Key(string apiKey) => new("config-plugin::provider", "Provider", apiKey, SecretStoreType.LLM_PROVIDER); + + [Test] + public void TheWhitespaceAroundAKeyGoes() + { + var issue = PendingEnterpriseApiKeys.Add(Key("sk-proj-AbC123\n")); + using (Assert.EnterMultipleScope()) + { + Assert.That(issue, Is.EqualTo(APIKeyIssue.NONE)); + Assert.That(PendingEnterpriseApiKeys.GetAndClear().Select(key => key.ApiKey), Is.EqualTo(new[] { "sk-proj-AbC123" })); + } + } + + [Test] + public void AKeyWhichCannotBeSentStaysOut() + { + var issue = PendingEnterpriseApiKeys.Add(Key($"sk-proj{ZERO_WIDTH_SPACE}AbC123")); + using (Assert.EnterMultipleScope()) + { + Assert.That(issue.Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER)); + Assert.That(PendingEnterpriseApiKeys.GetAndClear(), Is.Empty); + } + } +} \ No newline at end of file diff --git a/app/Tests/Tools/ToolCalling/ToolSettingsAPIKeyTests.cs b/app/Tests/Tools/ToolCalling/ToolSettingsAPIKeyTests.cs new file mode 100644 index 000000000..3991d229c --- /dev/null +++ b/app/Tests/Tools/ToolCalling/ToolSettingsAPIKeyTests.cs @@ -0,0 +1,76 @@ +using AIStudio.Tools.ToolCallingSystem; +using AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch; +using AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Staan; +using AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Tavily; + +namespace AIStudio.Tests.Tools.ToolCalling; + +/// +/// Checks how the web search treats the API keys of its search services. +/// +/// +/// The settings dialog checks a key while the user enters it, so the fields of the keys have to say +/// that they hold one. The settings validation must not refuse such a key, though: it decides whether +/// the web search is offered at all, and one key stored before AI Studio checked keys would switch +/// off every search service, those which work included. Such a key fails when its service is asked, +/// before any request, so that the dispatcher reports it and asks the other services. +/// +[TestFixture] +public sealed class ToolSettingsAPIKeyTests +{ + private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString(); + + private static IEnumerable Backends() + { + yield return new TestCaseData(new TavilySearchBackend()).SetArgDisplayNames("Tavily"); + yield return new TestCaseData(new StaanSearchBackend()).SetArgDisplayNames("Staan"); + } + + [Test] + public void AnAPIKeyIsASecret() + { + var field = ToolSettingsSchemaBuilder.Create().OptionalAPIKey("service.apiKey").Build().Properties["service.apiKey"]; + using (Assert.EnterMultipleScope()) + { + Assert.That(field.Secret, Is.True); + Assert.That(field.IsAPIKey, Is.True); + } + } + + [TestCaseSource(nameof(Backends))] + public void EverySecretOfASearchServiceIsAnAPIKey(IWebSearchBackend backend) + { + var secrets = SecretFields(backend); + using (Assert.EnterMultipleScope()) + { + Assert.That(secrets, Is.Not.Empty); + Assert.That(secrets.Where(field => !field.Value.IsAPIKey).Select(field => field.Key), Is.Empty); + } + } + + [TestCaseSource(nameof(Backends))] + public void AKeyWhichCannotBeSentKeepsTheSearchServiceConfigured(IWebSearchBackend backend) + { + var apiKeyField = SecretFields(backend).Single().Key; + var settings = new Dictionary { [apiKeyField] = $"key{ZERO_WIDTH_SPACE}AbC123" }; + Assert.That(backend.TryValidateConfiguration(settings, out _), Is.True); + } + + [TestCaseSource(nameof(Backends))] + public async Task AStoredKeyWhichCannotBeSentFailsBeforeAnyRequest(IWebSearchBackend backend) + { + var apiKeyField = SecretFields(backend).Single().Key; + var settings = new Dictionary { [apiKeyField] = $"key{ZERO_WIDTH_SPACE}AbC123" }; + var query = new WebSearchQuery("weather", null, null, null, null, 5, 10); + + var exception = await Assert.ThrowsAsync(() => backend.SearchAsync(query, settings)); + Assert.That(exception?.Message, Does.Contain(backend.Backend.ToString()).IgnoreCase.And.Not.Contain("AbC123")); + } + + private static List> SecretFields(IWebSearchBackend backend) + { + var builder = ToolSettingsSchemaBuilder.Create(); + backend.DeclareSettings(builder); + return builder.Build().Properties.Where(field => field.Value.Secret).ToList(); + } +} \ No newline at end of file diff --git a/app/Tests/Tools/Validation/APIKeyValidationTests.cs b/app/Tests/Tools/Validation/APIKeyValidationTests.cs new file mode 100644 index 000000000..1ea8ea84f --- /dev/null +++ b/app/Tests/Tools/Validation/APIKeyValidationTests.cs @@ -0,0 +1,216 @@ +using AIStudio.Tools.Validation; + +namespace AIStudio.Tests.Tools.Validation; + +/// +/// Checks which API keys AI Studio accepts, and what it tells the user about the others. +/// +/// +/// +/// An HTTP header carries nothing but ASCII, so .NET refuses every other character in a key, and +/// only while sending. What a key picks up in the clipboard has to be found before, and named so +/// that the user knows what to do. +/// +/// +/// The invisible characters are built from their code points, so that nobody has to trust an +/// editor to keep characters it does not show. Nothing here asserts on the wording of a message: +/// I18N is process-wide state without a reset. +/// +/// +[TestFixture] +public sealed class APIKeyValidationTests +{ + private const string KEY = "sk-proj-AbC123"; + + private static readonly string NO_BREAK_SPACE = ((char)0x00A0).ToString(); + private static readonly string LINE_SEPARATOR = ((char)0x2028).ToString(); + private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString(); + private static readonly string BYTE_ORDER_MARK = ((char)0xFEFF).ToString(); + private static readonly string COMBINING_DIAERESIS = ((char)0x0308).ToString(); + private static readonly string DECOMPOSED_A_UMLAUT = $"a{COMBINING_DIAERESIS}"; + private static readonly string DECOMPOSED_CAPITAL_U_UMLAUT = $"U{COMBINING_DIAERESIS}"; + + [TestCase("sk-proj-AbC_123.xyz~")] + [TestCase("AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY")] + [TestCase("dGhpcyBpcyBhIGtleQ+/==")] + [TestCase("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")] + public void KeysOfPrintableAsciiPass(string key) => Assert.That(APIKeyValidation.Check(key), Is.EqualTo(APIKeyIssue.NONE)); + + [TestCase(null)] + [TestCase("")] + [TestCase(" \t\n")] + public void AMissingKeyIsUpToTheCaller(string? key) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(APIKeyValidation.Check(key).IsProblem, Is.False); + Assert.That(APIKeyValidation.Validate(key), Is.Null); + Assert.That(APIKeyValidation.TryPrepareForHeader(key, out var headerValue), Is.True); + Assert.That(headerValue, Is.Empty); + } + } + + [Test] + public void WhitespaceAroundTheKeyGoes() + { + string[] keys = [$" {KEY}\n", $"\t{KEY}\r\n", $"{NO_BREAK_SPACE}{KEY}{NO_BREAK_SPACE}", $"{KEY}{LINE_SEPARATOR}"]; + using (Assert.EnterMultipleScope()) + { + foreach (var key in keys) + { + Assert.That(APIKeyValidation.Normalize(key), Is.EqualTo(KEY)); + Assert.That(APIKeyValidation.Check(key), Is.EqualTo(APIKeyIssue.NONE)); + Assert.That(APIKeyValidation.TryPrepareForHeader(key, out var headerValue), Is.True); + Assert.That(headerValue, Is.EqualTo(KEY)); + } + } + } + + [TestCase(" ")] + [TestCase("\t")] + [TestCase("\n")] + [TestCase("\r\n")] + [TestCase("\u00A0")] + [TestCase("\u3000")] + public void WhitespaceInsideTheKeyIsReported(string whitespace) => Assert.That(APIKeyValidation.Check($"sk-proj{whitespace}AbC123").Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE)); + + [TestCase(0x200B)] + [TestCase(0x200D)] + [TestCase(0x2060)] + [TestCase(0x00AD)] + [TestCase(0x202E)] + [TestCase(0x0000)] + [TestCase(0x0007)] + [TestCase(0x007F)] + [TestCase(0x034F)] + [TestCase(0xFE0F)] + [TestCase(0x3164)] + [TestCase(0x2800)] + [TestCase(0xE000)] + public void AnInvisibleCharacterIsReported(int codePoint) + { + var invisible = ((char)codePoint).ToString(); + using (Assert.EnterMultipleScope()) + { + Assert.That(APIKeyValidation.Check($"sk-proj{invisible}AbC123"), Is.EqualTo(new APIKeyIssue(APIKeyIssueKind.INVISIBLE_CHARACTER, string.Empty))); + Assert.That(APIKeyValidation.Check($"{KEY}{invisible}").Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER), "Trimming must not remove a character which is no whitespace."); + } + } + + [Test] + public void ACopiedByteOrderMarkIsReported() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(APIKeyValidation.Check($"{BYTE_ORDER_MARK}{KEY}").Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER)); + Assert.That(APIKeyValidation.Check($"{ZERO_WIDTH_SPACE}{KEY}").Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER)); + } + } + + [Test] + public void ALoneSurrogateIsReportedAsInvisible() + { + var highSurrogate = ((char)0xD83D).ToString(); + var lowSurrogate = ((char)0xDD11).ToString(); + using (Assert.EnterMultipleScope()) + { + Assert.That(APIKeyValidation.Check($"sk-{highSurrogate}AbC").Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER)); + Assert.That(APIKeyValidation.Check($"sk-AbC{highSurrogate}").Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER)); + Assert.That(APIKeyValidation.Check($"sk-{lowSurrogate}AbC").Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER)); + } + } + + [TestCase("ä")] + [TestCase("ö")] + [TestCase("ü")] + [TestCase("Ä")] + [TestCase("Ö")] + [TestCase("Ü")] + [TestCase("ß")] + [TestCase("ẞ")] + [TestCase("§")] + [TestCase("°")] + [TestCase("´")] + [TestCase("µ")] + [TestCase("²")] + [TestCase("³")] + [TestCase("€")] + [TestCase("„")] + [TestCase("“")] + [TestCase("‚")] + [TestCase("‘")] + [TestCase("–")] + [TestCase("…")] + [TestCase("é")] + [TestCase("ø")] + [TestCase("ş")] + [TestCase("ł")] + [TestCase("ж")] + [TestCase("日")] + [TestCase("한")] + [TestCase("🔑")] + public void AVisibleCharacterBeyondAsciiIsNamed(string character) => Assert.That(APIKeyValidation.Check($"sk-proj{character}AbC123"), Is.EqualTo(new APIKeyIssue(APIKeyIssueKind.NON_ASCII_CHARACTER, character))); + + [Test] + public void ADecomposedUmlautIsOneVisibleCharacter() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(APIKeyValidation.Check($"sk-{DECOMPOSED_A_UMLAUT}bc"), Is.EqualTo(new APIKeyIssue(APIKeyIssueKind.NON_ASCII_CHARACTER, "ä"))); + Assert.That(APIKeyValidation.Check($"sk-{DECOMPOSED_CAPITAL_U_UMLAUT}bc"), Is.EqualTo(new APIKeyIssue(APIKeyIssueKind.NON_ASCII_CHARACTER, "Ü"))); + } + } + + [Test] + public void TheFirstIssueWins() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(APIKeyValidation.Check($"sk proj{ZERO_WIDTH_SPACE}“AbC").Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE)); + Assert.That(APIKeyValidation.Check($"sk{ZERO_WIDTH_SPACE}proj “AbC").Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER)); + Assert.That(APIKeyValidation.Check($"sk“proj {ZERO_WIDTH_SPACE}AbC"), Is.EqualTo(new APIKeyIssue(APIKeyIssueKind.NON_ASCII_CHARACTER, "“"))); + } + } + + [Test] + public void AKeyWhichCannotBeSentIsNotPrepared() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(APIKeyValidation.TryPrepareForHeader($"sk-proj{ZERO_WIDTH_SPACE}AbC123", out var headerValue), Is.False); + Assert.That(headerValue, Is.Empty); + } + } + + [Test] + public void EveryIssueHasAMessage() + { + var issues = Enum.GetValues().Where(kind => kind is not APIKeyIssueKind.NONE).Select(kind => new APIKeyIssue(kind, "„")); + using (Assert.EnterMultipleScope()) + { + foreach (var issue in issues) + Assert.That(APIKeyValidation.GetMessage(issue), Is.Not.Empty, $"The issue {issue.Kind} has no message."); + + Assert.That(APIKeyValidation.GetMessage(APIKeyIssue.NONE), Is.Empty); + Assert.That(APIKeyValidation.GetUnusableKeyMessage("Tavily"), Does.Contain("Tavily")); + } + } + + [Test] + public void AMessageNamesTheCharacterButNeverTheKey() + { + const string SECRET = "sk-secret-AbC123"; + string[] keys = [$"{SECRET} {SECRET}", $"{SECRET}{ZERO_WIDTH_SPACE}", $"{SECRET}“"]; + using (Assert.EnterMultipleScope()) + { + foreach (var key in keys) + { + var message = APIKeyValidation.Validate(key); + Assert.That(message, Is.Not.Null.And.Not.Empty); + Assert.That(message, Does.Not.Contain("secret")); + } + + Assert.That(APIKeyValidation.Validate($"{SECRET}“"), Does.Contain("“")); + } + } +} \ No newline at end of file diff --git a/app/Tests/Tools/Validation/ProviderValidationTests.cs b/app/Tests/Tools/Validation/ProviderValidationTests.cs new file mode 100644 index 000000000..ae28db52c --- /dev/null +++ b/app/Tests/Tools/Validation/ProviderValidationTests.cs @@ -0,0 +1,47 @@ +using AIStudio.Provider; +using AIStudio.Tools.Validation; + +namespace AIStudio.Tests.Tools.Validation; + +/// +/// Checks which API keys the dialogs of the LLM, embedding, and transcription providers accept. +/// +/// +/// Nothing here asserts on the wording of a message: I18N is process-wide state without a reset. +/// +[TestFixture] +public sealed class ProviderValidationTests +{ + private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString(); + + private static ProviderValidation For(LLMProviders provider, string storageIssue = "") => new() + { + GetProvider = () => provider, + GetAPIKeyStorageIssue = () => storageIssue, + }; + + [TestCase(LLMProviders.OPEN_AI, ExpectedResult = false)] + [TestCase(LLMProviders.ANTHROPIC, ExpectedResult = false)] + [TestCase(LLMProviders.SELF_HOSTED, ExpectedResult = true)] + public bool OnlyASelfHostedServerMayGoWithoutAKey(LLMProviders provider) => For(provider).ValidatingAPIKey(" ") is null; + + [TestCase(LLMProviders.OPEN_AI)] + [TestCase(LLMProviders.SELF_HOSTED)] + public void AKeyWhichCannotBeSentIsRejected(LLMProviders provider) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(For(provider).ValidatingAPIKey($"sk-proj{ZERO_WIDTH_SPACE}AbC123"), Is.Not.Null); + Assert.That(For(provider).ValidatingAPIKey("sk-proj“AbC123”"), Is.Not.Null); + Assert.That(For(provider).ValidatingAPIKey("sk-proj AbC123"), Is.Not.Null); + } + } + + [TestCase(LLMProviders.OPEN_AI)] + [TestCase(LLMProviders.SELF_HOSTED)] + public void WhitespaceAroundTheKeyIsFine(LLMProviders provider) => Assert.That(For(provider).ValidatingAPIKey(" sk-proj-AbC123\n"), Is.Null); + + [TestCase(LLMProviders.OPEN_AI)] + [TestCase(LLMProviders.SELF_HOSTED)] + public void AStorageIssueComesFirst(LLMProviders provider) => Assert.That(For(provider, "The keyring is locked.").ValidatingAPIKey("sk-proj-AbC123"), Is.EqualTo("The keyring is locked.")); +} \ No newline at end of file