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

+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."));
}