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

@@ -1,3 +1,5 @@
using AIStudio.Tools.Validation;
namespace AIStudio.Tools.PluginSystem;
/// <summary>
@@ -9,13 +11,26 @@ public static class PendingEnterpriseApiKeys
private static readonly Lock LOCK = new();
/// <summary>
/// Adds a pending API key to the list.
/// Adds a pending API key to the list, unless it cannot be sent.
/// </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>
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)
PENDING_KEYS.Add(key);
PENDING_KEYS.Add(key with { ApiKey = APIKeyValidation.Normalize(key.ApiKey) });
return APIKeyIssue.NONE;
}
/// <summary>
@@ -1,4 +1,5 @@
using AIStudio.Tools.Rust;
using AIStudio.Tools.Validation;
namespace AIStudio.Tools.Services;
@@ -85,13 +86,18 @@ public sealed partial class RustService
/// <summary>
/// Try to store the API key for the given secret ID.
/// </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="key">The API key to store.</param>
/// <param name="storeType">The secret store type. Defaults to LLM_PROVIDER for backward compatibility.</param>
/// <returns>The store secret response.</returns>
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 state = await this.StoreEncryptedAPIKeyByKey(secretKey, encryptedKey);
if (state.Success)
@@ -1,4 +1,5 @@
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Validation;
namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Staan;
@@ -65,7 +66,7 @@ public sealed class StaanSearchBackend : IWebSearchBackend
public void DeclareSettings(ToolSettingsSchemaBuilder builder) => builder
.InGroup(SETTINGS_GROUP)
.OptionalSecret(API_KEY_SETTING)
.OptionalAPIKey(API_KEY_SETTING)
.OptionalEnum(MARKET_SETTING, SUPPORTED_MARKETS)
.InGroup(string.Empty);
@@ -125,6 +126,13 @@ public sealed class StaanSearchBackend : IWebSearchBackend
if (string.IsNullOrWhiteSpace(apiKey))
throw new InvalidOperationException(TB("A Staan API key is required."));
//
// A key stored before AI Studio checked keys, or one the organization provides, may hold a
// character the header cannot carry. The dispatcher asks the other services all the same:
//
if (!APIKeyValidation.TryPrepareForHeader(apiKey, out var headerAPIKey))
throw new InvalidOperationException(APIKeyValidation.GetUnusableKeyMessage("Staan"));
//
// Staan refuses a longer query outright. Shortening it here would search for something
// other than what was asked, so the model is told and can search again instead:
@@ -141,7 +149,7 @@ public sealed class StaanSearchBackend : IWebSearchBackend
var market = ResolveMarket(query.Language, settingsValues, notes);
var searchRequest = new StaanSearchRequest { Query = query.Query, Market = market, Offset = ReadOffset(query.Page) };
var response = await this.searchClient.SearchAsync(apiKey.Trim(), searchRequest, query.TimeoutSeconds, token);
var response = await this.searchClient.SearchAsync(headerAPIKey, searchRequest, query.TimeoutSeconds, token);
//
// Staan corrects an obvious mistake in a query and says so. Which query actually ran is
@@ -1,4 +1,5 @@
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Validation;
namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.WebSearch.Tavily;
@@ -58,7 +59,7 @@ public sealed class TavilySearchBackend : IWebSearchBackend
public void DeclareSettings(ToolSettingsSchemaBuilder builder) => builder
.InGroup(SETTINGS_GROUP)
.OptionalSecret(API_KEY_SETTING)
.OptionalAPIKey(API_KEY_SETTING)
.OptionalEnum(SEARCH_DEPTH_SETTING, SUPPORTED_SEARCH_DEPTHS)
.InGroup(string.Empty);
@@ -118,6 +119,13 @@ public sealed class TavilySearchBackend : IWebSearchBackend
if (string.IsNullOrWhiteSpace(apiKey))
throw new InvalidOperationException(TB("A Tavily API key is required."));
//
// A key stored before AI Studio checked keys, or one the organization provides, may hold a
// character the header cannot carry. The dispatcher asks the other services all the same:
//
if (!APIKeyValidation.TryPrepareForHeader(apiKey, out var headerAPIKey))
throw new InvalidOperationException(APIKeyValidation.GetUnusableKeyMessage("Tavily"));
var notes = new List<string>();
var language = ResolveLanguage(query.Language, notes);
var searchRequest = new TavilySearchRequest
@@ -138,7 +146,7 @@ public sealed class TavilySearchBackend : IWebSearchBackend
SafeSearch = query.SafeSearch?.TavilyValue,
};
var response = await this.searchClient.SearchAsync(apiKey.Trim(), searchRequest, query.TimeoutSeconds, token);
var response = await this.searchClient.SearchAsync(headerAPIKey, searchRequest, query.TimeoutSeconds, token);
var hits = response.Results.Select(result => new SearchHit(result.Url, result.Title, result.Content));
var candidates = SearchCandidateCollector.Collect(WebSearchBackend.TAVILY, hits, query.Limit, out var candidateCount);
return new WebSearchBackendResult(WebSearchBackend.TAVILY, candidates, candidateCount, notes);
@@ -26,6 +26,18 @@ public sealed class ToolSettingsFieldDefinition
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>
/// Name of the group this field belongs to, or empty when it stands on its own.
/// </summary>
@@ -68,19 +68,29 @@ public sealed class ToolSettingsSchemaBuilder
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()
{
Properties = new(this.properties, StringComparer.Ordinal),
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
{
OptionSource = optionSource,
EnumValues = enumValues?.ToList() ?? [],
Secret = isSecret,
IsAPIKey = isAPIKey,
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;
// A self-hosted server may well run without any key, so an empty field is fine for it:
if(this.GetProvider() is LLMProviders.SELF_HOSTED)
return null;
if(string.IsNullOrWhiteSpace(apiKey))
return TA("Please enter an API key.");
return this.GetProvider() is LLMProviders.SELF_HOSTED ? null : TA("Please enter an API key.");
return null;
// A key which is there has to be one we can send, also the optional key of a self-hosted server:
return APIKeyValidation.Validate(apiKey);
}
public string? ValidatingInstanceName(string instanceName)