Added a check for characters which an API key cannot contain (#1227)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-24 17:20:13 +01:00
1 parent c72a1948b3
commit e5a7f5423f
40 files changed
+1179 -71

No files matched your search

@@ -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. -- 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." 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. -- 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." UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::DATASOURCEVALIDATION::T1013354736"] = "The hostname is not a valid HTTP(S) URL."
@@ -56,7 +56,7 @@ public abstract partial class ConfigurationBase : MSGComponentBase
protected bool IsDisabled => this.Disabled() || this.IsLocked(); protected bool IsDisabled => this.Disabled() || this.IsLocked();
private string Classes => $"{this.GetClassForBase} {JUSTIFIED_HELP_CLASS} {this.MarginClass}"; private string Classes => $"{this.GetClassForBase} {this.MarginClass}";
/// <summary> /// <summary>
/// The bottom margin of the option. Options inside settings panels need the default /// 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 protected virtual RenderFragment? Body => null;
private const string JUSTIFIED_HELP_CLASS = "configuration-help-justified";
private const string MARGIN_CLASS = "mb-6"; private const string MARGIN_CLASS = "mb-6";
protected static readonly Dictionary<string, object?> SPELLCHECK_ATTRIBUTES = new(); protected static readonly Dictionary<string, object?> SPELLCHECK_ATTRIBUTES = new();
@@ -9,7 +9,7 @@
@foreach (var issue in this.IssuesData) @foreach (var issue in this.IssuesData)
{ {
<MudListItem Icon="@AppIcons.WARNING" IconColor="Color.Error"> <MudListItem Icon="@AppIcons.WARNING" IconColor="Color.Error">
@issue <MudJustifiedText Typo="Typo.body1">@issue</MudJustifiedText>
</MudListItem> </MudListItem>
} }
</MudList> </MudList>
@@ -7,12 +7,12 @@
} }
else else
{ {
<MudText Typo="Typo.body1" Class="mb-3"> <MudJustifiedText Typo="Typo.body1" Class="mb-3">
@TA("Your organization has set up AI providers for you. To use them, AI Studio needs your personal API key. Please enter it below.") @TA("Your organization has set up AI providers for you. To use them, AI Studio needs your personal API key. Please enter it below.")
</MudText> </MudJustifiedText>
} }
<SecretInputField Secret="@this.apiKey" SecretChanged="@(value => this.apiKey = value)" Label="@T("API key")"/> <SecretInputField Secret="@this.apiKey" SecretChanged="@(value => this.apiKey = value)" Label="@T("API key")" Validation="@ValidateAPIKey"/>
@if (!string.IsNullOrWhiteSpace(this.issue)) @if (!string.IsNullOrWhiteSpace(this.issue))
{ {
@@ -22,7 +22,7 @@
} }
<MudStack Row="@true" AlignItems="AlignItems.Center"> <MudStack Row="@true" AlignItems="AlignItems.Center">
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@AppIcons.SAVE" Disabled="@(this.isBusy || string.IsNullOrWhiteSpace(this.apiKey))" OnClick="@this.StoreAPIKeyAsync"> <MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@AppIcons.SAVE" Disabled="@(!this.CanStoreAPIKey)" OnClick="@this.StoreAPIKeyAsync">
@T("Check and save API key") @T("Check and save API key")
</MudButton> </MudButton>
@if (this.isBusy) @if (this.isBusy)
@@ -1,5 +1,6 @@
using AIStudio.Tools.Services; using AIStudio.Tools.Services;
using AIStudio.Tools.UserAPIKeys; using AIStudio.Tools.UserAPIKeys;
using AIStudio.Tools.Validation;
using Microsoft.AspNetCore.Components; 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; private string Title => string.IsNullOrWhiteSpace(this.Group.Prompt?.Title) ? TA("Your API key is missing") : this.Group.Prompt.Title;
/// <summary>
/// Whether the entered key can be checked and stored: it is there, and it can be sent.
/// </summary>
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() private async Task StoreAPIKeyAsync()
{ {
var enteredAPIKey = this.apiKey.Trim(); if (!this.CanStoreAPIKey)
if (this.isBusy || string.IsNullOrWhiteSpace(enteredAPIKey))
return; return;
var enteredAPIKey = APIKeyValidation.Normalize(this.apiKey);
this.isBusy = true; this.isBusy = true;
this.issue = string.Empty; this.issue = string.Empty;
try try
@@ -72,7 +72,7 @@
var fieldOptions = field.GetOptions(); var fieldOptions = field.GetOptions();
if (fieldOptions.Count > 0) if (fieldOptions.Count > 0)
{ {
<MudSelect T="string" Label="@GetFieldLabel(toolSection, fieldName, field)" Value="@GetValue(toolSection, fieldName)" ValueChanged="@(value => this.UpdateValue(toolSection, fieldName, value))" Variant="Variant.Outlined" Margin="Margin.Dense" HelperText="@this.GetFieldDescription(toolSection, fieldName, field)" Placeholder="@GetFieldPlaceholder(toolSection, fieldName, field)" Class="mb-3 configuration-help-justified" Disabled="@this.IsFieldDisabled(toolSection, fieldName)"> <MudSelect T="string" Label="@GetFieldLabel(toolSection, fieldName, field)" Value="@GetValue(toolSection, fieldName)" ValueChanged="@(value => this.UpdateValue(toolSection, fieldName, value))" Variant="Variant.Outlined" Margin="Margin.Dense" HelperText="@this.GetFieldDescription(toolSection, fieldName, field)" Placeholder="@GetFieldPlaceholder(toolSection, fieldName, field)" Class="mb-3" Disabled="@this.IsFieldDisabled(toolSection, fieldName)">
@if (!toolSection.Definition.SettingsSchema.Required.Contains(fieldName)) @if (!toolSection.Definition.SettingsSchema.Required.Contains(fieldName))
{ {
<MudSelectItem T="string" Value="@string.Empty">@T("Not set")</MudSelectItem> <MudSelectItem T="string" Value="@string.Empty">@T("Not set")</MudSelectItem>
@@ -85,7 +85,7 @@
} }
else else
{ {
<MudTextField T="string" Label="@GetFieldLabel(toolSection, fieldName, field)" Value="@GetValue(toolSection, fieldName)" ValueChanged="@(value => this.UpdateValue(toolSection, fieldName, value))" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3 configuration-help-justified" HelperText="@this.GetFieldDescription(toolSection, fieldName, field)" Placeholder="@GetFieldPlaceholder(toolSection, fieldName, field)" InputType="@(field.Secret ? InputType.Password : InputType.Text)" Disabled="@this.IsFieldDisabled(toolSection, fieldName)" /> <MudTextField T="string" Label="@GetFieldLabel(toolSection, fieldName, field)" Value="@GetValue(toolSection, fieldName)" ValueChanged="@(value => this.UpdateValue(toolSection, fieldName, value))" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3" HelperText="@this.GetFieldDescription(toolSection, fieldName, field)" Placeholder="@GetFieldPlaceholder(toolSection, fieldName, field)" InputType="@(field.Secret ? InputType.Password : InputType.Text)" Disabled="@this.IsFieldDisabled(toolSection, fieldName)" Validation="@GetFieldValidation(field)" DebounceInterval="@GetFieldDebounceInterval(field)" />
} }
} }
</MudPaper> </MudPaper>
@@ -1,4 +1,6 @@
using AIStudio.Components;
using AIStudio.Tools.ToolCallingSystem; using AIStudio.Tools.ToolCallingSystem;
using AIStudio.Tools.Validation;
using Microsoft.AspNetCore.Components; 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); private bool IsFieldDisabled(ToolSection section, string fieldName) => this.ToolSettingsService.IsFieldLocked(section.Definition, fieldName);
/// <summary>
/// Checks an API key while the user types it, and leaves every other field alone.
/// </summary>
private static Func<string, string?>? GetFieldValidation(ToolSettingsFieldDefinition fieldDefinition) => fieldDefinition.IsAPIKey ? APIKeyValidation.Validate : null;
/// <summary>
/// Lets an API key field pass its text on while the user types, so that its check follows the typing.
/// </summary>
/// <remarks>
/// Every other field keeps passing its text on only when the user leaves it, as it always did.
/// </remarks>
private static double GetFieldDebounceInterval(ToolSettingsFieldDefinition fieldDefinition) => fieldDefinition.IsAPIKey ? TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS : 0;
/// <summary>
/// Finds the first API key the user entered which cannot be sent.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="message">The field and what is wrong with its key, or empty when every key can be sent.</param>
/// <returns>True when a key cannot be sent.</returns>
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) => private static string GetFieldPlaceholder(ToolSection section, string fieldName, ToolSettingsFieldDefinition fieldDefinition) =>
string.IsNullOrWhiteSpace(GetValue(section, fieldName)) ? GetFieldDefaultValue(section, fieldName, fieldDefinition) : string.Empty; 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) if (this.item is null)
return; return;
if (this.TryFindAPIKeyIssue(out var apiKeyIssue))
{
this.validationMessage = apiKeyIssue;
return;
}
foreach (var section in this.sections) foreach (var section in this.sections)
{ {
var validationState = await this.ToolSettingsService.ValidateSettingsAsync(section.Definition, section.Values, section.Implementation); var validationState = await this.ToolSettingsService.ValidateSettingsAsync(section.Definition, section.Values, section.Implementation);
@@ -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. -- 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." 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. -- 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." UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::DATASOURCEVALIDATION::T1013354736"] = "Der Hostname ist keine gültige HTTP(S)-URL."
@@ -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. -- 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." 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. -- 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." UI_TEXT_CONTENT["AISTUDIO::TOOLS::VALIDATION::DATASOURCEVALIDATION::T1013354736"] = "The hostname is not a valid HTTP(S) URL."
@@ -139,7 +139,7 @@ public sealed class ProviderAnthropic() : BaseProvider(LLMProviders.ANTHROPIC, n
var request = new HttpRequestMessage(HttpMethod.Post, "messages"); var request = new HttpRequestMessage(HttpMethod.Post, "messages");
// Set the authorization header: // 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: // Set the Anthropic version:
request.Headers.Add("anthropic-version", "2023-06-01"); request.Headers.Add("anthropic-version", "2023-06-01");
@@ -166,7 +166,7 @@ public sealed class ProviderAnthropic() : BaseProvider(LLMProviders.ANTHROPIC, n
async Task<HttpRequestMessage> RequestBuilder() async Task<HttpRequestMessage> RequestBuilder()
{ {
var request = new HttpRequestMessage(HttpMethod.Post, "messages"); 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.Headers.Add("anthropic-version", "2023-06-01");
request.Content = new StringContent(JsonSerializer.Serialize(requestDto, JSON_SERIALIZER_OPTIONS), Encoding.UTF8, "application/json"); request.Content = new StringContent(JsonSerializer.Serialize(requestDto, JSON_SERIALIZER_OPTIONS), Encoding.UTF8, "application/json");
return request; return request;
+95 -17
View File
@@ -15,6 +15,7 @@ using AIStudio.Tools.ToolCallingSystem.Harness;
using AIStudio.Tools.MIME; using AIStudio.Tools.MIME;
using AIStudio.Tools.PluginSystem; using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Rust; using AIStudio.Tools.Rust;
using AIStudio.Tools.Validation;
using Host = AIStudio.Provider.SelfHosted.Host; 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); protected static ModelLoadResult FailedModelLoadResult(ModelLoadFailureReason failureReason, string? technicalDetails = null) => ModelLoadResult.Failure(failureReason, technicalDetails);
/// <summary>
/// The result of loading the models with a key which cannot be sent, so that nothing was requested.
/// </summary>
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) protected bool IsTimeoutException(Exception exception, CancellationToken token = default)
{ {
if (token.IsCancellationRequested) if (token.IsCancellationRequested)
@@ -165,15 +171,72 @@ public abstract class BaseProvider : IProvider, ISecretId
ExternalHttpClientTimeout.GetTimeoutDescription(), ExternalHttpClientTimeout.GetTimeoutDescription(),
action))); action)));
protected async Task<string?> GetModelLoadingSecretKey(SecretStoreType storeType, string? apiKeyProvisional = null, bool isTryingSecret = false) => apiKeyProvisional switch /// <summary>
/// Gets the API key for loading the models: the one the user is entering, or else the stored one.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="storeType">Where the stored key is kept.</param>
/// <param name="apiKeyProvisional">The key the user is entering and did not store yet, or null for the stored one.</param>
/// <param name="isTryingSecret">Whether a missing key is fine, so that the keyring logs no error for it.</param>
/// <returns>The key without the whitespace around it, or whether it cannot be sent.</returns>
protected async Task<ModelLoadingSecretKey> GetModelLoadingSecretKey(SecretStoreType storeType, string? apiKeyProvisional = null, bool isTryingSecret = false)
{ {
not null => apiKeyProvisional, var key = apiKeyProvisional;
_ => await Program.RUST_SERVICE.GetAPIKey(this, storeType, isTrying: isTryingSecret) switch if (key is null)
{ {
{ Success: true } result => await result.Secret.Decrypt(Program.ENCRYPTION), var requestedSecret = await Program.RUST_SERVICE.GetAPIKey(this, storeType, isTrying: isTryingSecret);
_ => null, 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;
}
/// <summary>
/// Decrypts a stored API key for the header of a request.
/// </summary>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </remarks>
/// <param name="requestedSecret">The stored key as the keyring returned it.</param>
/// <returns>The key without the whitespace around it.</returns>
protected async Task<string> 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 protected static ModelLoadFailureReason GetDefaultModelLoadFailureReason(HttpResponseMessage response) => response.StatusCode switch
{ {
@@ -203,14 +266,17 @@ public abstract class BaseProvider : IProvider, ISecretId
CancellationToken token = default) CancellationToken token = default)
{ {
var secretKey = await this.GetModelLoadingSecretKey(storeType, apiKeyProvisional, isTryingSecret); 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."); return FailedModelLoadResult(ModelLoadFailureReason.INVALID_OR_MISSING_API_KEY, "No API key available for model loading.");
using var request = new HttpRequestMessage(HttpMethod.Get, requestPath); using var request = new HttpRequestMessage(HttpMethod.Get, requestPath);
if (requestConfigurator is not null) if (requestConfigurator is not null)
requestConfigurator(request, secretKey ?? string.Empty); requestConfigurator(request, secretKey.Key ?? string.Empty);
else if (!string.IsNullOrWhiteSpace(secretKey)) else if (!string.IsNullOrWhiteSpace(secretKey.Key))
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey.Key);
try 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.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_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.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.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), 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: // Set the authorization header:
if (requestedSecret.Success) 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: // Set provider-specific headers:
requestHeadersAction?.Invoke(request.Headers); requestHeadersAction?.Invoke(request.Headers);
@@ -1514,7 +1581,7 @@ public abstract class BaseProvider : IProvider, ISecretId
{ {
var request = new HttpRequestMessage(HttpMethod.Post, requestPath); var request = new HttpRequestMessage(HttpMethod.Post, requestPath);
if (requestedSecret.Success) 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); headersAction?.Invoke(request.Headers);
request.Content = new StringContent(JsonSerializer.Serialize(requestDto, JSON_SERIALIZER_OPTIONS), Encoding.UTF8, "application/json"); 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: case LLMProviders.SELF_HOSTED:
if(requestedSecret.Success) 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; break;
@@ -1634,7 +1701,13 @@ public abstract class BaseProvider : IProvider, ISecretId
return TranscriptionResult.Failure(); 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; break;
default: default:
@@ -1644,7 +1717,7 @@ public abstract class BaseProvider : IProvider, ISecretId
return TranscriptionResult.Failure(); 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; break;
} }
@@ -1677,6 +1750,11 @@ public abstract class BaseProvider : IProvider, ISecretId
{ {
throw; 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) catch (Exception e)
{ {
if (this.IsTimeoutException(e, token)) if (this.IsTimeoutException(e, token))
@@ -1713,7 +1791,7 @@ public abstract class BaseProvider : IProvider, ISecretId
{ {
case LLMProviders.SELF_HOSTED: case LLMProviders.SELF_HOSTED:
if(requestedSecret.Success) 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; 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)); 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; break;
} }
@@ -96,7 +96,7 @@ public class ProviderGoogle() : BaseProvider(LLMProviders.GOOGLE, new Uri("https
var embeddingRequest = JsonSerializer.Serialize(payload, JSON_SERIALIZER_OPTIONS); var embeddingRequest = JsonSerializer.Serialize(payload, JSON_SERIALIZER_OPTIONS);
var embedUrl = $"https://generativelanguage.googleapis.com/v1beta/models/{modelName}:embedContent"; var embedUrl = $"https://generativelanguage.googleapis.com/v1beta/models/{modelName}:embedContent";
using var request = new HttpRequestMessage(HttpMethod.Post, embedUrl); 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: // Set the content:
request.Content = new StringContent(embeddingRequest, Encoding.UTF8, "application/json"); request.Content = new StringContent(embeddingRequest, Encoding.UTF8, "application/json");
@@ -126,13 +126,16 @@ public sealed class ProviderHelmholtz() : BaseProvider(LLMProviders.HELMHOLTZ, n
private async Task<ModelLoadResult> LoadModels(SecretStoreType storeType, string? apiKeyProvisional, CancellationToken token) private async Task<ModelLoadResult> LoadModels(SecretStoreType storeType, string? apiKeyProvisional, CancellationToken token)
{ {
var secretKey = await this.GetModelLoadingSecretKey(storeType, apiKeyProvisional); 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."); return FailedModelLoadResult(ModelLoadFailureReason.INVALID_OR_MISSING_API_KEY, "No API key available for model loading.");
try try
{ {
using var request = new HttpRequestMessage(HttpMethod.Get, "models"); 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); using var response = await this.HttpClient.SendAsync(request, token);
var body = await response.Content.ReadAsStringAsync(token); var body = await response.Content.ReadAsStringAsync(token);
@@ -4,6 +4,12 @@ public enum ModelLoadFailureReason
{ {
NONE, NONE,
INVALID_OR_MISSING_API_KEY, INVALID_OR_MISSING_API_KEY,
/// <summary>
/// The API key contains a character which an HTTP header cannot carry, so the models were never requested.
/// </summary>
INVALID_API_KEY_CHARACTERS,
AUTHENTICATION_OR_PERMISSION_ERROR, AUTHENTICATION_OR_PERMISSION_ERROR,
INSUFFICIENT_QUOTA, INSUFFICIENT_QUOTA,
TOO_MANY_REQUESTS, TOO_MANY_REQUESTS,
@@ -1,4 +1,5 @@
using AIStudio.Tools.PluginSystem; using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Validation;
namespace AIStudio.Provider; namespace AIStudio.Provider;
@@ -13,6 +14,7 @@ public static class ModelLoadFailureReasonExtensions
public string ToUserMessage(string providerName) => failureReason switch 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_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.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.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), 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),
@@ -0,0 +1,33 @@
namespace AIStudio.Provider;
/// <summary>
/// The API key for loading the models of a provider, ready for a header.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="key">The key without the whitespace around it, or null when there is none or it cannot be sent.</param>
/// <param name="isUnusable">Whether the key contains a character which an HTTP header cannot carry.</param>
public readonly struct ModelLoadingSecretKey(string? key, bool isUnusable)
{
/// <summary>
/// No key at all, e.g., because none is stored.
/// </summary>
public static readonly ModelLoadingSecretKey NONE = new(null, false);
/// <summary>
/// A key which cannot be sent, and which therefore is not handed out.
/// </summary>
public static readonly ModelLoadingSecretKey UNUSABLE = new(null, true);
/// <summary>
/// The key without the whitespace around it, or null when there is none or it cannot be sent.
/// </summary>
public string? Key { get; } = key;
/// <summary>
/// Whether the key contains a character which an HTTP header cannot carry.
/// </summary>
public bool IsUnusable { get; } = isUnusable;
}
@@ -272,7 +272,7 @@ public sealed class ProviderOpenAI() : BaseProvider(LLMProviders.OPEN_AI, new Ur
var request = new HttpRequestMessage(HttpMethod.Post, requestPath); var request = new HttpRequestMessage(HttpMethod.Post, requestPath);
// Set the authorization header: // 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: // Set the content:
request.Content = new StringContent(openAIChatRequest, Encoding.UTF8, "application/json"); 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<HttpRequestMessage> RequestBuilder() async Task<HttpRequestMessage> RequestBuilder()
{ {
var request = new HttpRequestMessage(HttpMethod.Post, "responses"); 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"); request.Content = new StringContent(JsonSerializer.Serialize(requestDto, JSON_SERIALIZER_OPTIONS), Encoding.UTF8, "application/json");
return request; return request;
} }
@@ -24,6 +24,16 @@ public enum ProviderRequestFailureReason
/// </remarks> /// </remarks>
INVALID_OR_MISSING_API_KEY, INVALID_OR_MISSING_API_KEY,
/// <summary>
/// The stored API key contains a character which an HTTP header cannot carry, so the request was never sent.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
INVALID_API_KEY_CHARACTERS,
/// <summary> /// <summary>
/// The key was accepted, but the account is not allowed to do what we asked for. /// The key was accepted, but the account is not allowed to do what we asked for.
/// </summary> /// </summary>
@@ -21,6 +21,7 @@ public static class ProviderRequestFailureReasonExtensions
ProviderRequestFailureReason.TOO_MANY_REQUESTS => TB("Too many requests"), ProviderRequestFailureReason.TOO_MANY_REQUESTS => TB("Too many requests"),
ProviderRequestFailureReason.MODEL_NOT_SUPPORTED_BY_PROVIDER => TB("Model not offered"), ProviderRequestFailureReason.MODEL_NOT_SUPPORTED_BY_PROVIDER => TB("Model not offered"),
ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY => TB("API key problem"), 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.AUTHENTICATION_OR_PERMISSION_ERROR => TB("Not permitted"),
ProviderRequestFailureReason.PROVIDER_UNAVAILABLE => TB("Provider unreachable"), ProviderRequestFailureReason.PROVIDER_UNAVAILABLE => TB("Provider unreachable"),
ProviderRequestFailureReason.MODEL_NOT_FOUND => TB("Model unknown"), ProviderRequestFailureReason.MODEL_NOT_FOUND => TB("Model unknown"),
@@ -41,6 +42,7 @@ public static class ProviderRequestFailureReasonExtensions
/// </remarks> /// </remarks>
public bool IsFixedInProviderSettings => failureReason is public bool IsFixedInProviderSettings => failureReason is
ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY or ProviderRequestFailureReason.INVALID_OR_MISSING_API_KEY or
ProviderRequestFailureReason.INVALID_API_KEY_CHARACTERS or
ProviderRequestFailureReason.AUTHENTICATION_OR_PERMISSION_ERROR or ProviderRequestFailureReason.AUTHENTICATION_OR_PERMISSION_ERROR or
ProviderRequestFailureReason.MODEL_NOT_FOUND or ProviderRequestFailureReason.MODEL_NOT_FOUND or
ProviderRequestFailureReason.MODEL_NOT_SUPPORTED_BY_PROVIDER or ProviderRequestFailureReason.MODEL_NOT_SUPPORTED_BY_PROVIDER or
@@ -195,6 +195,8 @@ public sealed class ProviderSelfHosted(Host host, string hostname) : BaseProvide
private async Task<ModelLoadResult> LoadModels(SecretStoreType storeType, string? apiKeyProvisional, CancellationToken token) private async Task<ModelLoadResult> LoadModels(SecretStoreType storeType, string? apiKeyProvisional, CancellationToken token)
{ {
var secretKey = await this.GetModelLoadingSecretKey(storeType, apiKeyProvisional, isTryingSecret: true); var secretKey = await this.GetModelLoadingSecretKey(storeType, apiKeyProvisional, isTryingSecret: true);
if (secretKey.IsUnusable)
return UnusableAPIKeyModelLoadResult();
try 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 // 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 // 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: // an empty string arrives here whenever the user stored no key:
if(!string.IsNullOrWhiteSpace(secretKey)) if(!string.IsNullOrWhiteSpace(secretKey.Key))
lmStudioRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey); lmStudioRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey.Key);
using var lmStudioResponse = await this.HttpClient.SendAsync(lmStudioRequest, token); using var lmStudioResponse = await this.HttpClient.SendAsync(lmStudioRequest, token);
if(!lmStudioResponse.IsSuccessStatusCode) if(!lmStudioResponse.IsSuccessStatusCode)
@@ -288,12 +290,14 @@ public sealed class ProviderSelfHosted(Host host, string hostname) : BaseProvide
private async Task<ModelLoadResult> LoadLlamaCppTextModels(string? apiKeyProvisional, CancellationToken token) private async Task<ModelLoadResult> LoadLlamaCppTextModels(string? apiKeyProvisional, CancellationToken token)
{ {
var secretKey = await this.GetModelLoadingSecretKey(SecretStoreType.LLM_PROVIDER, apiKeyProvisional, true); var secretKey = await this.GetModelLoadingSecretKey(SecretStoreType.LLM_PROVIDER, apiKeyProvisional, true);
if (secretKey.IsUnusable)
return UnusableAPIKeyModelLoadResult();
try try
{ {
using var request = new HttpRequestMessage(HttpMethod.Get, "models"); using var request = new HttpRequestMessage(HttpMethod.Get, "models");
if (!string.IsNullOrWhiteSpace(secretKey)) if (!string.IsNullOrWhiteSpace(secretKey.Key))
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secretKey.Key);
using var response = await this.HttpClient.SendAsync(request, token); using var response = await this.HttpClient.SendAsync(request, token);
var responseBody = await response.Content.ReadAsStringAsync(token); var responseBody = await response.Content.ReadAsStringAsync(token);
@@ -4,6 +4,7 @@ using AIStudio.Provider;
using AIStudio.Provider.HuggingFace; using AIStudio.Provider.HuggingFace;
using AIStudio.Tools.PluginSystem; using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Services; using AIStudio.Tools.Services;
using AIStudio.Tools.Validation;
using SharedTools; 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 // 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 // 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) var apiKeyIssue = dryRun
{ ? APIKeyValidation.Check(decryptedApiKey)
PendingEnterpriseApiKeys.Add(new( : PendingEnterpriseApiKeys.Add(new(
$"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}", $"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}",
name, name,
decryptedApiKey, decryptedApiKey,
SecretStoreType.EMBEDDING_PROVIDER)); 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})"); LOGGER.LogDebug($"Successfully decrypted API key for embedding provider {idx}. It will be stored in the OS keyring. (Plugin ID: {configPluginId})");
}
} }
else else
LOGGER.LogWarning($"Failed to decrypt API key for embedding provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})"); LOGGER.LogWarning($"Failed to decrypt API key for embedding provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})");
+10 -5
View File
@@ -4,6 +4,7 @@ using AIStudio.Provider;
using AIStudio.Provider.HuggingFace; using AIStudio.Provider.HuggingFace;
using AIStudio.Tools.PluginSystem; using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Services; using AIStudio.Tools.Services;
using AIStudio.Tools.Validation;
using SharedTools; 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 // 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 // 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) var apiKeyIssue = dryRun
{ ? APIKeyValidation.Check(decryptedApiKey)
PendingEnterpriseApiKeys.Add(new( : PendingEnterpriseApiKeys.Add(new(
$"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}", $"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}",
instanceName, instanceName,
decryptedApiKey, decryptedApiKey,
SecretStoreType.LLM_PROVIDER)); 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})"); LOGGER.LogDebug($"Successfully decrypted API key for provider {idx}. It will be stored in the OS keyring. (Plugin ID: {configPluginId})");
}
} }
else else
LOGGER.LogWarning($"Failed to decrypt API key for provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})"); LOGGER.LogWarning($"Failed to decrypt API key for provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})");
@@ -3,6 +3,7 @@ using System.Text.Json.Serialization;
using AIStudio.Provider; using AIStudio.Provider;
using AIStudio.Provider.HuggingFace; using AIStudio.Provider.HuggingFace;
using AIStudio.Tools.PluginSystem; using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Validation;
using SharedTools; 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 // 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 // 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) var apiKeyIssue = dryRun
{ ? APIKeyValidation.Check(decryptedApiKey)
PendingEnterpriseApiKeys.Add(new( : PendingEnterpriseApiKeys.Add(new(
$"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}", $"{ISecretId.ENTERPRISE_KEY_PREFIX}::{usedLLMProvider.SecretId}",
name, name,
decryptedApiKey, decryptedApiKey,
SecretStoreType.TRANSCRIPTION_PROVIDER)); 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})"); LOGGER.LogDebug($"Successfully decrypted API key for transcription provider {idx}. It will be stored in the OS keyring. (Plugin ID: {configPluginId})");
}
} }
else else
LOGGER.LogWarning($"Failed to decrypt API key for transcription provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})"); LOGGER.LogWarning($"Failed to decrypt API key for transcription provider {idx}. The encryption secret may be incorrect. (Plugin ID: {configPluginId})");
@@ -1,3 +1,5 @@
using AIStudio.Tools.Validation;
namespace AIStudio.Tools.PluginSystem; namespace AIStudio.Tools.PluginSystem;
/// <summary> /// <summary>
@@ -9,13 +11,26 @@ public static class PendingEnterpriseApiKeys
private static readonly Lock LOCK = new(); private static readonly Lock LOCK = new();
/// <summary> /// <summary>
/// Adds a pending API key to the list. /// Adds a pending API key to the list, unless it cannot be sent.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="key">The pending API key to add.</param> /// <param name="key">The pending API key to add.</param>
public static void Add(PendingEnterpriseApiKey key) /// <returns>NONE when the key was added, otherwise why it was left out.</returns>
public static APIKeyIssue Add(PendingEnterpriseApiKey key)
{ {
var issue = APIKeyValidation.Check(key.ApiKey);
if (issue.IsProblem)
return issue;
lock (LOCK) lock (LOCK)
PENDING_KEYS.Add(key); PENDING_KEYS.Add(key with { ApiKey = APIKeyValidation.Normalize(key.ApiKey) });
return APIKeyIssue.NONE;
} }
/// <summary> /// <summary>
@@ -1,4 +1,5 @@
using AIStudio.Tools.Rust; using AIStudio.Tools.Rust;
using AIStudio.Tools.Validation;
namespace AIStudio.Tools.Services; namespace AIStudio.Tools.Services;
@@ -85,13 +86,18 @@ public sealed partial class RustService
/// <summary> /// <summary>
/// Try to store the API key for the given secret ID. /// Try to store the API key for the given secret ID.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="secretId">The secret ID to store the API key for.</param> /// <param name="secretId">The secret ID to store the API key for.</param>
/// <param name="key">The API key to store.</param> /// <param name="key">The API key to store.</param>
/// <param name="storeType">The secret store type. Defaults to LLM_PROVIDER for backward compatibility.</param> /// <param name="storeType">The secret store type. Defaults to LLM_PROVIDER for backward compatibility.</param>
/// <returns>The store secret response.</returns> /// <returns>The store secret response.</returns>
public async Task<StoreSecretResponse> SetAPIKey(ISecretId secretId, string key, SecretStoreType storeType) public async Task<StoreSecretResponse> 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 secretKey = APIKey(storeType, secretId);
var state = await this.StoreEncryptedAPIKeyByKey(secretKey, encryptedKey); var state = await this.StoreEncryptedAPIKeyByKey(secretKey, encryptedKey);
if (state.Success) if (state.Success)
@@ -1,4 +1,5 @@
using AIStudio.Tools.PluginSystem; using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Validation;
namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Staan; namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Staan;
@@ -65,7 +66,7 @@ public sealed class StaanSearchBackend : IWebSearchBackend
public void DeclareSettings(ToolSettingsSchemaBuilder builder) => builder public void DeclareSettings(ToolSettingsSchemaBuilder builder) => builder
.InGroup(SETTINGS_GROUP) .InGroup(SETTINGS_GROUP)
.OptionalSecret(API_KEY_SETTING) .OptionalAPIKey(API_KEY_SETTING)
.OptionalEnum(MARKET_SETTING, SUPPORTED_MARKETS) .OptionalEnum(MARKET_SETTING, SUPPORTED_MARKETS)
.InGroup(string.Empty); .InGroup(string.Empty);
@@ -125,6 +126,13 @@ public sealed class StaanSearchBackend : IWebSearchBackend
if (string.IsNullOrWhiteSpace(apiKey)) if (string.IsNullOrWhiteSpace(apiKey))
throw new InvalidOperationException(TB("A Staan API key is required.")); 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 // 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: // 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 market = ResolveMarket(query.Language, settingsValues, notes);
var searchRequest = new StaanSearchRequest { Query = query.Query, Market = market, Offset = ReadOffset(query.Page) }; 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 // Staan corrects an obvious mistake in a query and says so. Which query actually ran is
@@ -1,4 +1,5 @@
using AIStudio.Tools.PluginSystem; using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Validation;
namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Tavily; namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Tavily;
@@ -58,7 +59,7 @@ public sealed class TavilySearchBackend : IWebSearchBackend
public void DeclareSettings(ToolSettingsSchemaBuilder builder) => builder public void DeclareSettings(ToolSettingsSchemaBuilder builder) => builder
.InGroup(SETTINGS_GROUP) .InGroup(SETTINGS_GROUP)
.OptionalSecret(API_KEY_SETTING) .OptionalAPIKey(API_KEY_SETTING)
.OptionalEnum(SEARCH_DEPTH_SETTING, SUPPORTED_SEARCH_DEPTHS) .OptionalEnum(SEARCH_DEPTH_SETTING, SUPPORTED_SEARCH_DEPTHS)
.InGroup(string.Empty); .InGroup(string.Empty);
@@ -118,6 +119,13 @@ public sealed class TavilySearchBackend : IWebSearchBackend
if (string.IsNullOrWhiteSpace(apiKey)) if (string.IsNullOrWhiteSpace(apiKey))
throw new InvalidOperationException(TB("A Tavily API key is required.")); 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<string>(); var notes = new List<string>();
var language = ResolveLanguage(query.Language, notes); var language = ResolveLanguage(query.Language, notes);
var searchRequest = new TavilySearchRequest var searchRequest = new TavilySearchRequest
@@ -138,7 +146,7 @@ public sealed class TavilySearchBackend : IWebSearchBackend
SafeSearch = query.SafeSearch?.TavilyValue, 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 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); var candidates = SearchCandidateCollector.Collect(WebSearchBackend.TAVILY, hits, query.Limit, out var candidateCount);
return new WebSearchBackendResult(WebSearchBackend.TAVILY, candidates, candidateCount, notes); return new WebSearchBackendResult(WebSearchBackend.TAVILY, candidates, candidateCount, notes);
@@ -26,6 +26,18 @@ public sealed class ToolSettingsFieldDefinition
public bool Secret { get; init; } public bool Secret { get; init; }
/// <summary>
/// Whether the field holds an API key, which is always a secret as well.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public bool IsAPIKey { get; init; }
/// <summary> /// <summary>
/// Name of the group this field belongs to, or empty when it stands on its own. /// Name of the group this field belongs to, or empty when it stands on its own.
/// </summary> /// </summary>
@@ -68,19 +68,29 @@ public sealed class ToolSettingsSchemaBuilder
public ToolSettingsSchemaBuilder RequiredSecret(string name) => this.Add(name, isRequired: true, isSecret: true); public ToolSettingsSchemaBuilder RequiredSecret(string name) => this.Add(name, isRequired: true, isSecret: true);
/// <summary>
/// An optional API key, kept in the operating system's keyring like any secret.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public ToolSettingsSchemaBuilder OptionalAPIKey(string name) => this.Add(name, isRequired: false, isSecret: true, isAPIKey: true);
public ToolSettingsSchema Build() => new() public ToolSettingsSchema Build() => new()
{ {
Properties = new(this.properties, StringComparer.Ordinal), Properties = new(this.properties, StringComparer.Ordinal),
Required = [..this.requiredNames], Required = [..this.requiredNames],
}; };
private ToolSettingsSchemaBuilder Add(string name, bool isRequired, string optionSource = "", bool isSecret = false, IReadOnlyList<string>? enumValues = null) private ToolSettingsSchemaBuilder Add(string name, bool isRequired, string optionSource = "", bool isSecret = false, IReadOnlyList<string>? enumValues = null, bool isAPIKey = false)
{ {
this.properties[name] = new ToolSettingsFieldDefinition this.properties[name] = new ToolSettingsFieldDefinition
{ {
OptionSource = optionSource, OptionSource = optionSource,
EnumValues = enumValues?.ToList() ?? [], EnumValues = enumValues?.ToList() ?? [],
Secret = isSecret, Secret = isSecret,
IsAPIKey = isAPIKey,
Group = this.currentGroup, Group = this.currentGroup,
}; };
@@ -0,0 +1,20 @@
namespace AIStudio.Tools.Validation;
/// <summary>
/// The first character of an API key which cannot be sent.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="Kind">What is wrong with the character.</param>
/// <param name="Character">The character as the user sees it, or empty unless it is a visible character outside of ASCII.</param>
public readonly record struct APIKeyIssue(APIKeyIssueKind Kind, string Character)
{
public static readonly APIKeyIssue NONE = new(APIKeyIssueKind.NONE, string.Empty);
/// <summary>
/// Whether the key cannot be sent.
/// </summary>
public bool IsProblem => this.Kind is not APIKeyIssueKind.NONE;
}
@@ -0,0 +1,32 @@
namespace AIStudio.Tools.Validation;
/// <summary>
/// What keeps an API key from being sent, as far as its characters tell.
/// </summary>
public enum APIKeyIssueKind
{
NONE,
/// <summary>
/// A space, a tab, or a line break inside the key.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
WHITESPACE,
/// <summary>
/// A character nobody sees, e.g., a zero-width space, a byte order mark, or a control character.
/// </summary>
/// <remarks>
/// Web pages and documents add such characters to what they show, and they come along when the
/// user copies the key from there.
/// </remarks>
INVISIBLE_CHARACTER,
/// <summary>
/// A visible character outside of ASCII, e.g., an umlaut or a typographic quotation mark.
/// </summary>
NON_ASCII_CHARACTER,
}
@@ -0,0 +1,186 @@
using System.Buffers;
using System.Globalization;
using System.Text;
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools.Validation;
/// <summary>
/// Checks whether an API key can be sent to a provider at all.
/// </summary>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </remarks>
public static class APIKeyValidation
{
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(APIKeyValidation).Namespace, nameof(APIKeyValidation));
/// <summary>
/// A blank pattern of the Braille block: a letter by its category, but nothing to see.
/// </summary>
private const int BRAILLE_PATTERN_BLANK = 0x2800;
/// <summary>
/// Removes the whitespace around a key, line breaks and no-break spaces included.
/// </summary>
/// <remarks>
/// Zero-width spaces and byte order marks stay: .NET does not count them as whitespace, and
/// the check reports them.
/// </remarks>
/// <param name="key">The key as the user entered it.</param>
/// <returns>The key without the whitespace around it, or an empty string for no key.</returns>
public static string Normalize(string? key) => key?.Trim() ?? string.Empty;
/// <summary>
/// Finds the first character of a key which cannot be sent.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="key">The key as the user entered it.</param>
/// <returns>The first issue, or NONE when the key can be sent.</returns>
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;
}
/// <summary>
/// Prepares a key for an HTTP header.
/// </summary>
/// <param name="key">The key as it was entered or stored.</param>
/// <param name="headerValue">The key without the whitespace around it, or an empty string when it cannot be sent.</param>
/// <returns>True when the key can be sent, which includes an empty key.</returns>
public static bool TryPrepareForHeader(string? key, out string headerValue)
{
headerValue = Normalize(key);
if (!Check(headerValue).IsProblem)
return true;
headerValue = string.Empty;
return false;
}
/// <summary>
/// Checks a key the user is entering.
/// </summary>
/// <param name="key">The key as the user entered it.</param>
/// <returns>What is wrong with the key, or null when it can be sent.</returns>
public static string? Validate(string? key)
{
var issue = Check(key);
return issue.IsProblem ? GetMessage(issue) : null;
}
/// <summary>
/// Tells the user what is wrong with the key they entered.
/// </summary>
/// <param name="issue">The issue the check found.</param>
/// <returns>The message, or an empty string when there is no issue.</returns>
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,
};
/// <summary>
/// Tells the user that a stored key cannot be sent.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="ownerName">The provider or service the key belongs to.</param>
/// <returns>The message.</returns>
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));
}
/// <summary>
/// Whether a code point shows nothing by itself.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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);
}
@@ -59,13 +59,11 @@ public sealed class ProviderValidation
return apiKeyStorageIssue; return apiKeyStorageIssue;
// A self-hosted server may well run without any key, so an empty field is fine for it: // 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)) 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) public string? ValidatingInstanceName(string instanceName)
+3 -2
View File
@@ -284,8 +284,9 @@
text-align: left; text-align: left;
} }
.configuration-help-justified .mud-input-helper-text, /* Every hint and every issue below a field, justified like the texts around it; app.css comes after MudBlazor's own rule */
.configuration-help-justified .mud-form-helpertext { .mud-input-helper-text,
.mud-form-helpertext {
text-align: justify; text-align: justify;
hyphens: auto; hyphens: auto;
word-break: auto-phrase; word-break: auto-phrase;
@@ -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 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 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 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. - 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. - 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. - 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.
+138
View File
@@ -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;
/// <summary>
/// Checks that no API key reaches a header which the header cannot carry.
/// </summary>
/// <remarks>
/// <para>
/// .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.
/// </para>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </remarks>
[TestFixture]
[NonParallelizable]
public sealed partial class APIKeyHeaderTests
{
private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString();
/// <summary>
/// A key as Fireworks issues them, which its transcription gets without the scheme 'Bearer'.
/// </summary>
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<SettingsManager>.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<string, int> { ["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<TestCaseData> 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<BaseProvider> 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"));
}
@@ -0,0 +1,48 @@
using AIStudio.Tools;
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Validation;
namespace AIStudio.Tests.Tools.PluginSystem;
/// <summary>
/// Checks which API keys of configuration plugins AI Studio stores in the keyring.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[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);
}
}
}
@@ -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;
/// <summary>
/// Checks how the web search treats the API keys of its search services.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[TestFixture]
public sealed class ToolSettingsAPIKeyTests
{
private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString();
private static IEnumerable<TestCaseData> 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<string, string> { [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<string, string> { [apiKeyField] = $"key{ZERO_WIDTH_SPACE}AbC123" };
var query = new WebSearchQuery("weather", null, null, null, null, 5, 10);
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => backend.SearchAsync(query, settings));
Assert.That(exception?.Message, Does.Contain(backend.Backend.ToString()).IgnoreCase.And.Not.Contain("AbC123"));
}
private static List<KeyValuePair<string, ToolSettingsFieldDefinition>> SecretFields(IWebSearchBackend backend)
{
var builder = ToolSettingsSchemaBuilder.Create();
backend.DeclareSettings(builder);
return builder.Build().Properties.Where(field => field.Value.Secret).ToList();
}
}
@@ -0,0 +1,216 @@
using AIStudio.Tools.Validation;
namespace AIStudio.Tests.Tools.Validation;
/// <summary>
/// Checks which API keys AI Studio accepts, and what it tells the user about the others.
/// </summary>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </remarks>
[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<APIKeyIssueKind>().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("“"));
}
}
}
@@ -0,0 +1,47 @@
using AIStudio.Provider;
using AIStudio.Tools.Validation;
namespace AIStudio.Tests.Tools.Validation;
/// <summary>
/// Checks which API keys the dialogs of the LLM, embedding, and transcription providers accept.
/// </summary>
/// <remarks>
/// Nothing here asserts on the wording of a message: I18N is process-wide state without a reset.
/// </remarks>
[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."));
}