Added a check for the characters of ERI usernames, tokens, and passwords (#1228)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-24 18:47:44 +01:00
1 parent e5a7f5423f
commit 9b4d07552d
16 files changed
+988 -21

No files matched your search

@@ -0,0 +1,212 @@
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.ERIClient;
using AIStudio.Tools.ERIClient.DataModel;
using AIStudio.Tools.Services;
using AIStudio.Tools.Validation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Tools;
/// <summary>
/// Checks that the ERI client sends no username, password, or access token which an HTTP header
/// cannot carry, and what it says instead.
/// </summary>
/// <remarks>
/// <para>
/// The data source points to port 1 of the own machine, where nothing listens: a request which the
/// client sends fails right away, with a message of its own. A message about the credentials thus
/// shows that the client stopped before sending. Nothing here asserts on the wording of a message:
/// I18N is process-wide state without a reset.
/// </para>
/// <para>
/// The messages of the client end up in the log. .NET quotes a header value in its exception only
/// when it parses the header and fails, as it does for an Authorization header with a line break
/// in the token. The other headers of ERI, i.e., user, password, and the session token, go unparsed,
/// and .NET names no value when it refuses them.
/// </para>
/// </remarks>
[TestFixture]
[NonParallelizable]
public sealed partial class ERIClientV1AuthenticationTests
{
private const string NAME = "Intranet";
// A part of each secret which no message could contain by chance, whatever its language:
private const string SECRET_PART = "Xq7";
private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString();
private static readonly DataSourceERI_V1 UNREACHABLE = new()
{
Id = "44444444-4444-4444-4444-444444444444",
Name = NAME,
Type = DataSourceType.ERI_V1,
Hostname = "http://127.0.0.1",
Port = 1,
AuthMethod = AuthMethod.TOKEN,
SecurityPolicy = DataSourceSecurity.ALLOW_ANY,
MaxMatches = 10,
};
private RustService rustService = null!;
private ServiceProvider serviceProvider = null!;
private IServiceProvider previousServiceProvider = null!;
[SetUp]
public void PrepareServices()
{
this.rustService = new RustService("1", "unused");
var settingsManager = new SettingsManager(NullLogger<SettingsManager>.Instance, this.rustService);
this.previousServiceProvider = Program.SERVICE_PROVIDER;
this.serviceProvider = new ServiceCollection()
.AddSingleton(this.rustService)
.AddSingleton(settingsManager)
.AddLogging()
.BuildServiceProvider();
Program.SERVICE_PROVIDER = this.serviceProvider;
}
[TearDown]
public void RestoreApplicationState()
{
Program.SERVICE_PROVIDER = this.previousServiceProvider;
this.serviceProvider.Dispose();
this.rustService.Dispose();
}
private async Task<APIResponse<AuthResponse>> AuthenticateAsync(DataSourceERI_V1 dataSource, string secret)
{
using var client = new ERIClientV1(dataSource);
return await client.AuthenticateAsync(this.rustService, secret);
}
[Test]
public async Task ATokenWithAnInvisibleCharacterIsNotSent()
{
var response = await this.AuthenticateAsync(UNREACHABLE, $"tok{ZERO_WIDTH_SPACE}en-{SECRET_PART}");
using (Assert.EnterMultipleScope())
{
Assert.That(response.Successful, Is.False);
Assert.That(response.Message, Is.EqualTo(ERICredentialValidation.GetUnusableSecretMessage(AuthMethod.TOKEN, NAME)));
Assert.That(response.Message, Does.Not.Contain(SECRET_PART));
}
}
[Test]
public async Task APasswordWithAnUmlautIsNotSent()
{
var dataSource = UNREACHABLE with { AuthMethod = AuthMethod.USERNAME_PASSWORD, Username = "max" };
var response = await this.AuthenticateAsync(dataSource, $"Grüße 2024 {SECRET_PART}");
using (Assert.EnterMultipleScope())
{
Assert.That(response.Successful, Is.False);
Assert.That(response.Message, Is.EqualTo(ERICredentialValidation.GetUnusableSecretMessage(AuthMethod.USERNAME_PASSWORD, NAME)));
Assert.That(response.Message, Does.Not.Contain(SECRET_PART));
}
}
[Test]
public async Task AUsernameWithAnUmlautIsNotSent()
{
var dataSource = UNREACHABLE with { AuthMethod = AuthMethod.USERNAME_PASSWORD, Username = "jürgen" };
var response = await this.AuthenticateAsync(dataSource, "Mein Passwort");
using (Assert.EnterMultipleScope())
{
Assert.That(response.Successful, Is.False);
Assert.That(response.Message, Is.EqualTo(ERICredentialValidation.GetUnusableUsernameMessage(NAME)));
}
}
[Test]
public async Task APasswordWithSpacesIsSent()
{
var dataSource = UNREACHABLE with { AuthMethod = AuthMethod.USERNAME_PASSWORD, Username = "Max Mustermann" };
var response = await this.AuthenticateAsync(dataSource, " Mein Passwort\n");
string[] messagesAboutCredentials =
[
ERICredentialValidation.GetUnusableSecretMessage(AuthMethod.USERNAME_PASSWORD, NAME),
ERICredentialValidation.GetUnusableUsernameMessage(NAME),
];
using (Assert.EnterMultipleScope())
{
Assert.That(response.Successful, Is.False, "Nothing listens on port 1.");
Assert.That(messagesAboutCredentials, Has.No.Member(response.Message), "The client has to send the request.");
}
}
[Test]
public async Task APasswordWithALineBreakIsNotQuoted()
{
var dataSource = UNREACHABLE with { AuthMethod = AuthMethod.USERNAME_PASSWORD, Username = "max" };
var response = await this.AuthenticateAsync(dataSource, $"Pass\n{SECRET_PART} 2024");
using (Assert.EnterMultipleScope())
{
Assert.That(response.Message, Is.EqualTo(ERICredentialValidation.GetUnusableSecretMessage(AuthMethod.USERNAME_PASSWORD, NAME)));
Assert.That(response.Message, Does.Not.Contain(SECRET_PART));
}
}
[Test]
public async Task ATokenOfPrintableAsciiIsSent()
{
var response = await this.AuthenticateAsync(UNREACHABLE, "eyJhbGciOiJIUzI1NiJ9.e30.abc-_~+/=\n");
using (Assert.EnterMultipleScope())
{
Assert.That(response.Successful, Is.False, "Nothing listens on port 1.");
Assert.That(response.Message, Is.Not.EqualTo(ERICredentialValidation.GetUnusableSecretMessage(AuthMethod.TOKEN, NAME)), "The client has to send the request.");
}
}
[Test]
public async Task ATokenWithALineBreakIsNotQuoted()
{
// Parsed as an Authorization header, this token made .NET quote it in its exception:
var response = await this.AuthenticateAsync(UNREACHABLE, $"tok\n{SECRET_PART}");
using (Assert.EnterMultipleScope())
{
Assert.That(response.Message, Is.EqualTo(ERICredentialValidation.GetUnusableSecretMessage(AuthMethod.TOKEN, NAME)));
Assert.That(response.Message, Does.Not.Contain(SECRET_PART));
}
}
[Test]
public async Task ASessionTokenWithALineBreakIsNotQuoted()
{
using var server = new LoopbackERIServer($"Sitzung\n{SECRET_PART}");
using var client = new ERIClientV1(UNREACHABLE with { AuthMethod = AuthMethod.NONE, Port = server.Port });
var authentication = await client.AuthenticateAsync(this.rustService);
var securityRequirements = await client.GetSecurityRequirementsAsync();
using (Assert.EnterMultipleScope())
{
Assert.That(authentication.Successful, Is.True, "The server has to hand out its session token.");
Assert.That(securityRequirements.Successful, Is.False);
Assert.That(securityRequirements.Message, Is.Not.Empty);
Assert.That(securityRequirements.Message, Does.Not.Contain(SECRET_PART));
}
}
[Test]
public void NoERIClientParsesAnAuthorizationHeader()
{
var clientDirectory = Path.Combine(AppSourceDirectory(), "Tools", "ERIClient");
var files = Directory.EnumerateFiles(clientDirectory, "*.cs", SearchOption.AllDirectories)
.Where(path => ValidatedAuthorizationRegex().IsMatch(File.ReadAllText(path)))
.Select(path => Path.GetRelativePath(clientDirectory, path));
Assert.That(files, Is.Empty, "Headers.Add quotes an Authorization header it cannot parse, i.e., the token, in its exception; use AuthenticationHeaderValue.");
}
[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"));
}
+78
View File
@@ -0,0 +1,78 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
namespace AIStudio.Tests.Tools;
/// <summary>
/// A minimal ERI server on the loopback address, which signs every client in with the session token
/// the test names.
/// </summary>
/// <remarks>
/// POST /auth answers with that token, and every other request with an error, so that a test sees what
/// the client does with the token before it would need anything else of the server.
/// </remarks>
internal sealed class LoopbackERIServer : IDisposable
{
private readonly TcpListener listener = new(IPAddress.Loopback, 0);
private readonly CancellationTokenSource stop = new();
private readonly string sessionToken;
/// <param name="sessionToken">The session token the server hands out.</param>
public LoopbackERIServer(string sessionToken)
{
this.sessionToken = sessionToken;
this.listener.Start();
_ = this.ServeAsync();
}
public int Port => ((IPEndPoint)this.listener.LocalEndpoint).Port;
private async Task ServeAsync()
{
try
{
while (!this.stop.IsCancellationRequested)
{
using var client = await this.listener.AcceptTcpClientAsync(this.stop.Token);
await using var stream = client.GetStream();
var request = await ReadRequestHeadAsync(stream, this.stop.Token);
var response = request.StartsWith("POST /auth", StringComparison.Ordinal)
? Json($$"""{"success":true,"token":"{{JsonEncodedText.Encode(this.sessionToken)}}","message":null}""")
: "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
await stream.WriteAsync(Encoding.UTF8.GetBytes(response), this.stop.Token);
}
}
catch (Exception exception) when (exception is OperationCanceledException or ObjectDisposedException or SocketException)
{
// The test is over.
}
}
private static string Json(string json) => $"HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {Encoding.UTF8.GetByteCount(json)}\r\nConnection: close\r\n\r\n{json}";
private static async Task<string> ReadRequestHeadAsync(NetworkStream stream, CancellationToken token)
{
var head = new StringBuilder();
var buffer = new byte[1024];
while (!head.ToString().Contains("\r\n\r\n", StringComparison.Ordinal))
{
var read = await stream.ReadAsync(buffer, token);
if (read == 0)
break;
head.Append(Encoding.ASCII.GetString(buffer, 0, read));
}
return head.ToString();
}
public void Dispose()
{
this.stop.Cancel();
this.listener.Stop();
this.stop.Dispose();
}
}
@@ -74,6 +74,25 @@ public sealed class APIKeyValidationTests
[TestCase("\u3000")]
public void WhitespaceInsideTheKeyIsReported(string whitespace) => Assert.That(APIKeyValidation.Check($"sk-proj{whitespace}AbC123").Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE));
[Test]
public void AValueWhichAllowsSpacesKeepsThem()
{
using (Assert.EnterMultipleScope())
{
Assert.That(APIKeyValidation.Check("my secret phrase", allowsSpaces: true), Is.EqualTo(APIKeyIssue.NONE));
Assert.That(APIKeyValidation.Check(" my secret phrase\n", allowsSpaces: true), Is.EqualTo(APIKeyIssue.NONE), "The whitespace around the value goes, as for a key.");
Assert.That(APIKeyValidation.Check("my secret phrase", allowsSpaces: false).Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE));
Assert.That(APIKeyValidation.Check("my secret phrase").Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE), "A key allows no spaces.");
}
}
[TestCase("\t")]
[TestCase("\n")]
[TestCase("\r\n")]
[TestCase("\u00A0")]
[TestCase("\u3000")]
public void AValueWhichAllowsSpacesStillReportsOtherWhitespace(string whitespace) => Assert.That(APIKeyValidation.Check($"my{whitespace}secret", allowsSpaces: true).Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE));
[TestCase(0x200B)]
[TestCase(0x200D)]
[TestCase(0x2060)]
@@ -0,0 +1,87 @@
using AIStudio.Tools.ERIClient.DataModel;
using AIStudio.Tools.Validation;
namespace AIStudio.Tests.Tools.Validation;
/// <summary>
/// Checks what the dialog of an ERI data source says about the username and the secret entered there.
/// </summary>
/// <remarks>
/// Nothing here asserts on the wording of a message: I18N is process-wide state without a reset.
/// The messages about characters are compared with those of ERICredentialValidation instead.
/// </remarks>
[TestFixture]
public sealed class DataSourceCredentialValidationTests
{
private const string STORAGE_ISSUE = "The keyring is locked.";
private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString();
private static DataSourceValidation For(AuthMethod authMethod, string secretStorageIssue = "") => new()
{
GetAuthMethod = () => authMethod,
GetSecretStorageIssue = () => secretStorageIssue,
};
[TestCase(AuthMethod.NONE)]
[TestCase(AuthMethod.KERBEROS)]
public void AnAuthMethodWithoutASecretNeedsNone(AuthMethod authMethod)
{
using (Assert.EnterMultipleScope())
{
Assert.That(For(authMethod).ValidatingSecret(string.Empty), Is.Null);
Assert.That(For(authMethod).ValidatingSecret($"a{ZERO_WIDTH_SPACE}b"), Is.Null);
}
}
[TestCase(AuthMethod.TOKEN)]
[TestCase(AuthMethod.USERNAME_PASSWORD)]
public void AStorageIssueComesFirst(AuthMethod authMethod)
{
using (Assert.EnterMultipleScope())
{
Assert.That(For(authMethod, STORAGE_ISSUE).ValidatingSecret($"a{ZERO_WIDTH_SPACE}b"), Is.EqualTo(STORAGE_ISSUE));
Assert.That(For(authMethod, STORAGE_ISSUE).ValidatingSecret(string.Empty), Is.EqualTo(STORAGE_ISSUE));
}
}
[TestCase(AuthMethod.TOKEN)]
[TestCase(AuthMethod.USERNAME_PASSWORD)]
public void AMissingSecretIsReported(AuthMethod authMethod)
{
var message = For(authMethod).ValidatingSecret(" ");
using (Assert.EnterMultipleScope())
{
Assert.That(message, Is.Not.Null.And.Not.Empty);
Assert.That(message, Is.Not.EqualTo(ERICredentialValidation.ValidateSecret(authMethod, $"a{ZERO_WIDTH_SPACE}b")), "An empty field is no issue of its characters.");
}
}
[Test]
public void ATokenWithAnInvisibleCharacterIsReported()
{
var token = $"eyJhbGciOiJIUzI1NiJ9{ZERO_WIDTH_SPACE}.e30";
Assert.That(For(AuthMethod.TOKEN).ValidatingSecret(token), Is.Not.Null.And.EqualTo(ERICredentialValidation.ValidateSecret(AuthMethod.TOKEN, token)));
}
[Test]
public void APasswordWithAnUmlautIsReported() => Assert.That(For(AuthMethod.USERNAME_PASSWORD).ValidatingSecret("Grüße 2024"), Is.Not.Null.And.EqualTo(ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, "Grüße 2024")));
[Test]
public void APasswordWithSpacesIsAccepted() => Assert.That(For(AuthMethod.USERNAME_PASSWORD).ValidatingSecret("Mein Passwort"), Is.Null);
[Test]
public void AUsernameWithAnUmlautIsReported()
{
var validation = For(AuthMethod.USERNAME_PASSWORD);
using (Assert.EnterMultipleScope())
{
Assert.That(validation.ValidateUsername("jürgen"), Is.Not.Null.And.EqualTo(ERICredentialValidation.ValidateUsername("jürgen")));
Assert.That(validation.ValidateUsername("Max Mustermann"), Is.Null);
Assert.That(validation.ValidateUsername(" "), Is.Not.Null, "An empty username is still reported.");
}
}
[Test]
public void TheUsernameMattersOnlyForUsernameAndPassword() => Assert.That(For(AuthMethod.TOKEN).ValidateUsername("jürgen"), Is.Null);
}
@@ -0,0 +1,209 @@
using AIStudio.Tools.ERIClient.DataModel;
using AIStudio.Tools.Validation;
namespace AIStudio.Tests.Tools.Validation;
/// <summary>
/// Checks which usernames, passwords, and access tokens of ERI data sources AI Studio accepts, and
/// what it tells the user about the others.
/// </summary>
/// <remarks>
/// <para>
/// ERI v1 sends all three in HTTP headers, which carry nothing but ASCII. An access token is checked
/// like an API key; a password and a username may contain spaces, since people choose them.
/// </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. Whether a message names a character shows instead
/// in whether two values with different characters get different messages.
/// </para>
/// </remarks>
[TestFixture]
public sealed class ERICredentialValidationTests
{
private const string DATA_SOURCE_NAME = "Project archive";
// A part of each secret which no message could contain by chance, whatever its language:
private const string SECRET_PART = "Xq7";
private static readonly string ZERO_WIDTH_SPACE = ((char)0x200B).ToString();
private static readonly string COMBINING_DIAERESIS = ((char)0x0308).ToString();
private static IEnumerable<string> CharactersBeyondAscii() =>
[
"ä", "ö", "ü", "Ä", "Ö", "Ü", "ß", "ẞ", "§", "°", "´", "µ", "²", "³", "€", "„", "“", "‚", "‘", "–", "…",
"é", "ø", "ş", "ł", "ж", "日本", "한",
$"a{COMBINING_DIAERESIS}", $"U{COMBINING_DIAERESIS}",
];
[TestCase("eyJhbGciOiJIUzI1NiJ9.e30.Xq7-_~+/=")]
[TestCase("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")]
public void ATokenOfPrintableAsciiPasses(string token) => Assert.That(ERICredentialValidation.CheckSecret(AuthMethod.TOKEN, token), Is.EqualTo(APIKeyIssue.NONE));
[Test]
public void ATokenIsCheckedLikeAnAPIKey()
{
string[] tokens = [$"{SECRET_PART} token", $"{SECRET_PART}{ZERO_WIDTH_SPACE}", $"{SECRET_PART}„", $"{SECRET_PART}a{COMBINING_DIAERESIS}", $" {SECRET_PART}\n"];
using (Assert.EnterMultipleScope())
{
foreach (var token in tokens)
Assert.That(ERICredentialValidation.CheckSecret(AuthMethod.TOKEN, token), Is.EqualTo(APIKeyValidation.Check(token)));
Assert.That(ERICredentialValidation.CheckSecret(AuthMethod.TOKEN, $"{SECRET_PART} token").Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE), "A token allows no spaces.");
}
}
[Test]
public void APasswordMayContainSpaces()
{
using (Assert.EnterMultipleScope())
{
Assert.That(ERICredentialValidation.CheckSecret(AuthMethod.USERNAME_PASSWORD, "Mein geheimes Passwort 2024!"), Is.EqualTo(APIKeyIssue.NONE));
Assert.That(ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, "Mein geheimes Passwort 2024!"), Is.Null);
}
}
[Test]
public void TheWhitespaceAroundAPasswordGoes()
{
using (Assert.EnterMultipleScope())
{
Assert.That(ERICredentialValidation.CheckSecret(AuthMethod.USERNAME_PASSWORD, " Passwort\n"), Is.EqualTo(APIKeyIssue.NONE));
Assert.That(ERICredentialValidation.Normalize(" Passwort\n"), Is.EqualTo("Passwort"));
}
}
[TestCaseSource(nameof(CharactersBeyondAscii))]
public void ACharacterBeyondAsciiInAPasswordIsReported(string character) => Assert.That(ERICredentialValidation.CheckSecret(AuthMethod.USERNAME_PASSWORD, $"Pass{character}wort 2024").Kind, Is.EqualTo(APIKeyIssueKind.NON_ASCII_CHARACTER));
[TestCase(0x0009)]
[TestCase(0x000A)]
[TestCase(0x000D)]
[TestCase(0x00A0)]
[TestCase(0x3000)]
public void OtherWhitespaceInAPasswordIsReported(int codePoint) => Assert.That(ERICredentialValidation.CheckSecret(AuthMethod.USERNAME_PASSWORD, $"Pass{(char)codePoint}wort").Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE));
[TestCase(0x200B)]
[TestCase(0xFEFF)]
[TestCase(0x00AD)]
public void AnInvisibleCharacterInAPasswordIsReported(int codePoint) => Assert.That(ERICredentialValidation.CheckSecret(AuthMethod.USERNAME_PASSWORD, $"Pass{(char)codePoint}wort").Kind, Is.EqualTo(APIKeyIssueKind.INVISIBLE_CHARACTER));
[Test]
public void AMessageAboutAPasswordNamesNeitherTheCharacterNorThePassword()
{
var umlaut = ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, $"Grüße-{SECRET_PART}");
var decomposedUmlaut = ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, $"Gru{COMBINING_DIAERESIS}ße-{SECRET_PART}");
var euro = ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, $"Preis€-{SECRET_PART}");
var tab = ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, $"Pass\t{SECRET_PART}");
var invisible = ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, $"Pass{ZERO_WIDTH_SPACE}{SECRET_PART}");
using (Assert.EnterMultipleScope())
{
Assert.That(umlaut, Is.Not.Null.And.Not.Empty);
Assert.That(decomposedUmlaut, Is.EqualTo(umlaut), "The message must not depend on the character.");
Assert.That(euro, Is.EqualTo(umlaut), "The message must not depend on the character.");
Assert.That(tab, Is.Not.Null.And.Not.Empty);
Assert.That(invisible, Is.EqualTo(tab), "Whitespace and invisible characters share one message.");
foreach (var message in new[] { umlaut, tab })
Assert.That(message, Does.Not.Contain(SECRET_PART));
}
}
[Test]
public void AMessageAboutATokenNamesTheCharacterButNeverTheToken()
{
var lowQuotationMark = ERICredentialValidation.ValidateSecret(AuthMethod.TOKEN, $"{SECRET_PART}„token");
var highQuotationMark = ERICredentialValidation.ValidateSecret(AuthMethod.TOKEN, $"{SECRET_PART}“token");
using (Assert.EnterMultipleScope())
{
Assert.That(lowQuotationMark, Does.Contain("„"));
Assert.That(highQuotationMark, Is.Not.EqualTo(lowQuotationMark));
foreach (var token in new[] { $"{SECRET_PART} token", $"{SECRET_PART}{ZERO_WIDTH_SPACE}token", $"{SECRET_PART}„token" })
{
var message = ERICredentialValidation.ValidateSecret(AuthMethod.TOKEN, token);
Assert.That(message, Is.Not.Null.And.Not.Empty);
Assert.That(message, Does.Not.Contain(SECRET_PART));
}
}
}
[Test]
public void AUsernameMayContainSpaces()
{
using (Assert.EnterMultipleScope())
{
Assert.That(ERICredentialValidation.CheckUsername("Max Mustermann"), Is.EqualTo(APIKeyIssue.NONE));
Assert.That(ERICredentialValidation.ValidateUsername("Max Mustermann"), Is.Null);
Assert.That(ERICredentialValidation.CheckUsername("Max\tMustermann").Kind, Is.EqualTo(APIKeyIssueKind.WHITESPACE));
}
}
[Test]
public void AMessageAboutAUsernameNamesTheCharacter()
{
var composed = ERICredentialValidation.ValidateUsername("jürgen");
var decomposed = ERICredentialValidation.ValidateUsername($"ju{COMBINING_DIAERESIS}rgen");
var otherUmlaut = ERICredentialValidation.ValidateUsername("jörgen");
using (Assert.EnterMultipleScope())
{
Assert.That(ERICredentialValidation.CheckUsername($"ju{COMBINING_DIAERESIS}rgen"), Is.EqualTo(new APIKeyIssue(APIKeyIssueKind.NON_ASCII_CHARACTER, "ü")));
Assert.That(composed, Is.Not.Null.And.Not.Empty);
Assert.That(decomposed, Is.EqualTo(composed), "A decomposed umlaut is named as the one character the user sees.");
Assert.That(otherUmlaut, Is.Not.EqualTo(composed));
}
}
[Test]
public void EveryIssueHasAMessage()
{
string[] values = [$"a b{ZERO_WIDTH_SPACE}", $"a{ZERO_WIDTH_SPACE}", "a„", "a\tb"];
using (Assert.EnterMultipleScope())
{
foreach (var value in values)
{
Assert.That(ERICredentialValidation.ValidateSecret(AuthMethod.TOKEN, value), Is.Not.Null.And.Not.Empty, $"The token '{value}' has no message.");
Assert.That(ERICredentialValidation.ValidateUsername(value), Is.Not.Null.And.Not.Empty, $"The username '{value}' has no message.");
Assert.That(ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, value), Is.Not.Null.And.Not.Empty, $"The password '{value}' has no message.");
}
}
}
[Test]
public void AStoredValueIsNamedByItsDataSourceOnly()
{
var token = ERICredentialValidation.GetUnusableSecretMessage(AuthMethod.TOKEN, DATA_SOURCE_NAME);
var password = ERICredentialValidation.GetUnusableSecretMessage(AuthMethod.USERNAME_PASSWORD, DATA_SOURCE_NAME);
var username = ERICredentialValidation.GetUnusableUsernameMessage(DATA_SOURCE_NAME);
using (Assert.EnterMultipleScope())
{
foreach (var message in new[] { token, password, username })
Assert.That(message, Does.Contain(DATA_SOURCE_NAME));
Assert.That(new[] { token, password, username }, Is.Unique, "Each value needs its own message.");
}
}
[TestCase(AuthMethod.NONE)]
[TestCase(AuthMethod.KERBEROS)]
public void WithoutASecretNothingIsChecked(AuthMethod authMethod)
{
using (Assert.EnterMultipleScope())
{
Assert.That(ERICredentialValidation.CheckSecret(authMethod, $"a{ZERO_WIDTH_SPACE}„"), Is.EqualTo(APIKeyIssue.NONE));
Assert.That(ERICredentialValidation.ValidateSecret(authMethod, $"a{ZERO_WIDTH_SPACE}„"), Is.Null);
}
}
[TestCase(null)]
[TestCase("")]
[TestCase(" \n")]
public void AMissingValueIsUpToTheCaller(string? value)
{
using (Assert.EnterMultipleScope())
{
Assert.That(ERICredentialValidation.ValidateSecret(AuthMethod.TOKEN, value), Is.Null);
Assert.That(ERICredentialValidation.ValidateSecret(AuthMethod.USERNAME_PASSWORD, value), Is.Null);
Assert.That(ERICredentialValidation.ValidateUsername(value), Is.Null);
}
}
}