Path: redb-identity/tests/redb.Identity.Tests/Security/NonCanonicalBase64Tests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/NonCanonicalBase64Tests.cs
----
using System.Xml.Linq;
using AwesomeAssertions;
using Microsoft.AspNetCore.DataProtection;
using OpenIddict.Server;
using redb.Identity.Contracts.Common;
using redb.Identity.Core.Models;
using redb.Identity.Core.OpenIddict;
using redb.Identity.Core.OpenIddict.Handlers;
using redb.Identity.Core.Routes;
using redb.Identity.Core.Services;
using redb.Identity.Http.Processors;
using redb.Identity.Http.Security;
using redb.Identity.Soap.Processors;
using redb.Identity.Tests.Infrastructure;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Soap;
using Xunit;
using static OpenIddict.Server.OpenIddictServerEvents;
namespace redb.Identity.Tests.Security;
///
/// Every place that decodes base64 a client sends refuses a value whose last character carries
/// non-zero unused bits. .NET 10 decodes such a value to the same bytes as the canonical one and
/// .NET 11 refuses it; the answer must not depend on the runtime, so both refuse. Each test hands
/// in the respelling of a value the site accepts in its canonical form.
///
public sealed class NonCanonicalBase64Tests
{
private static readonly XNamespace Wst = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
private static readonly XNamespace Wsse =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
private const string Credentials = "basic-client:basic-secret";
// ── the helper ───────────────────────────────────────────
[Theory]
[InlineData("AQ==", true)]
[InlineData("AR==", false)]
[InlineData("AQI=", true)]
[InlineData("AQJ=", false)]
[InlineData("AQID", true)]
[InlineData("", true)]
[InlineData("AQ", false)]
[InlineData("AQ== ", false)]
[InlineData("A Q==", false)]
[InlineData("!!!!", false)]
public void TryDecode_AcceptsOnlyTheCanonicalSpelling(string value, bool accepted)
{
Base64Canonical.TryDecode(value, out var bytes).Should().Be(accepted);
if (accepted)
Convert.ToBase64String(bytes!).Should().Be(value);
else
bytes.Should().BeNull();
}
[Fact]
public void Decode_ThrowsFormatException_ForANonCanonicalValue()
{
var act = () => Base64Canonical.Decode(Respell(Basic(Credentials)));
act.Should().Throw();
}
// ── HTTP Basic client credentials ────────────────────────
[Fact]
public async Task ExtractClientCredentialsHandler_RejectsANonCanonicalBasicValue()
{
var canonical = await Extract(Basic(Credentials));
var respelled = await Extract(Respell(Basic(Credentials)));
canonical.IsRejected.Should().BeFalse();
canonical.Request!.ClientId.Should().Be("basic-client");
respelled.IsRejected.Should().BeTrue();
respelled.Error.Should().Be(OpenIddict.Abstractions.OpenIddictConstants.Errors.InvalidClient);
respelled.Request!.ClientId.Should().BeNull();
static async Task Extract(string basic)
{
var exchange = new TestExchange();
exchange.In.Headers["Authorization"] = $"Basic {basic}";
var transaction = new OpenIddictServerTransaction();
transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange;
var context = new ExtractTokenRequestContext(transaction)
{
Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange),
};
await new ExtractClientCredentialsHandler().HandleAsync(context);
return context;
}
}
[Fact]
public void ThrottleClientId_DoesNotReadANonCanonicalBasicValue()
{
static string ClientId(string basic)
{
var exchange = new TestExchange();
exchange.In.Headers["Authorization"] = $"Basic {basic}";
return IdentityCoreRouteBuilder.ExtractClientIdForThrottle(exchange);
}
ClientId(Basic(Credentials)).Should().Be("basic-client");
ClientId(Respell(Basic(Credentials))).Should().Be("anonymous");
}
[Fact]
public async Task HttpFacade_MapsNoCredentials_FromANonCanonicalBasicValue()
{
var canonical = await MapHeaders(Basic(Credentials));
var respelled = await MapHeaders(Respell(Basic(Credentials)));
canonical.In.GetHeader("client_id").Should().Be("basic-client");
respelled.In.Headers.Should().NotContainKey("client_id");
respelled.In.Headers.Should().NotContainKey("client_secret");
}
[Fact]
public async Task HttpFacade_MapsNoCredentials_FromAMalformedBasicValue_InsteadOfThrowing()
{
var exchange = await MapHeaders("!!!not-base64!!!");
exchange.In.Headers.Should().NotContainKey("client_id");
exchange.In.Headers.Should().NotContainKey("client_secret");
}
private static async Task MapHeaders(string basic)
{
var exchange = new Exchange(new Message());
exchange.In.Headers[HttpHeaders.Authorization] = $"Basic {basic}";
await HttpIdentityProcessors.MapHttpToIdentityHeaders(exchange, CancellationToken.None);
return exchange;
}
// ── server-issued values a client sends back ─────────────
[Fact]
public void SessionTicket_RefusesARespelledTicket()
{
var sut = new SessionTicketService(new EphemeralDataProtectionProvider());
var ticket = Padded(filler => sut.Protect(42, 100, "user" + filler));
sut.Unprotect(ticket, TimeSpan.FromHours(1)).Should().NotBeNull();
sut.Unprotect(Respell(ticket), TimeSpan.FromHours(1)).Should().BeNull();
}
[Fact]
public void ReauthMarker_RefusesARespelledMarker()
{
var sut = new SessionTicketService(new EphemeralDataProtectionProvider());
var marker = Padded(filler => sut.ProtectReauth(100 + filler.Length));
sut.UnprotectReauth(marker, TimeSpan.FromHours(1)).Should().NotBeNull();
sut.UnprotectReauth(Respell(marker), TimeSpan.FromHours(1)).Should().BeNull();
}
[Fact]
public void ConsentTicket_RefusesARespelledTicket()
{
var sut = new SessionTicketService(new EphemeralDataProtectionProvider());
var ticket = Padded(filler =>
sut.ProtectConsent(new ConsentTicket(42, "client" + filler, "App", "openid", "/back")));
sut.UnprotectConsent(ticket, TimeSpan.FromHours(1)).Should().NotBeNull();
sut.UnprotectConsent(Respell(ticket), TimeSpan.FromHours(1)).Should().BeNull();
}
[Fact]
public void LogoutConfirmation_RefusesARespelledState()
{
var sut = new LogoutConfirmationProtector(DataProtectionProvider.Create("redb-identity-tests"));
long userId = 0;
var state = Padded(filler =>
{
userId = long.Parse("1" + new string('0', filler.Length));
return sut.Issue(userId, 7);
});
sut.Accepts(state, userId, 7).Should().BeTrue();
sut.Accepts(Respell(state), userId, 7).Should().BeFalse();
}
[Fact]
public void MfaSetupToken_RefusesARespelledToken()
{
var sut = new MfaSetupTokenProtector(DataProtectionProvider.Create("redb-identity-tests"));
var token = Padded(filler => sut.Protect(new MfaSetupTokenPayload { UserId = 42, MethodId = "totp" + filler }));
sut.Unprotect(token).Should().NotBeNull();
sut.Unprotect(Respell(token)).Should().BeNull();
}
[Fact]
public void MfaState_RefusesARespelledState()
{
var sut = new MfaStateProtector(DataProtectionProvider.Create("redb-identity-tests"));
var state = Padded(filler => sut.Protect(new MfaState { UserId = 42, Username = "alice" + filler, Methods = ["totp"] }));
sut.Unprotect(state).Should().NotBeNull();
sut.Unprotect(Respell(state)).Should().BeNull();
}
[Fact]
public void FederationState_RefusesARespelledState()
{
var sut = new FederationStateProtector(DataProtectionProvider.Create("redb-identity-tests"));
var state = Padded(filler => sut.Protect(new FederationState { ProviderId = "google" + filler, ReturnUrl = "/" }));
sut.Unprotect(state).Should().NotBeNull();
sut.Unprotect(Respell(state)).Should().BeNull();
}
// ── WS-Trust BinarySecurityToken ─────────────────────────
[Fact]
public async Task WsTrust_DecodesAWrappedBinarySecurityToken()
{
var token = Basic("token-xyz");
var wrapped = token[..4] + "\r\n " + token[4..];
var exchange = await MapValidate(wrapped);
exchange.Exception.Should().BeNull();
((Dictionary)exchange.In.Body!)["token"].Should().Be("token-xyz");
}
[Fact]
public async Task WsTrust_FaultsOnANonCanonicalBinarySecurityToken()
{
var exchange = await MapValidate(Respell(Basic("token-1234")));
exchange.Exception.Should().BeNull("a refusal is an answer, not a failure of the exchange");
var reply = exchange.HasOut ? exchange.Out! : exchange.In;
reply.GetHeader(SoapHeaders.FaultCode).Should().Be("wst:InvalidRequest");
}
[Fact]
public async Task WsTrust_FaultsOnAMalformedBinarySecurityToken_InsteadOfPassingItsText()
{
var exchange = await MapValidate("!!!not-base64!!!");
var reply = exchange.HasOut ? exchange.Out! : exchange.In;
reply.GetHeader(SoapHeaders.FaultCode).Should().Be("wst:InvalidRequest");
}
private static async Task MapValidate(string binaryContent)
{
var rst = new XElement(Wst + "RequestSecurityToken",
new XElement(Wst + "ValidateTarget",
new XElement(Wsse + "BinarySecurityToken",
new XAttribute("EncodingType", redb.Identity.Soap.WsTrust.Base64Encoding),
binaryContent)));
var message = new Message(rst.ToString());
message.Headers[SoapHeaders.Action] = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Validate";
var exchange = new Exchange(message);
await SoapIdentityProcessors.MapRequest(exchange, default);
return exchange;
}
// ── helpers ──────────────────────────────────────────────
private static string Basic(string text) => Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
///
/// The same bytes spelled with a non-zero unused bit in the last character. Needs a padded value:
/// without padding the last character has no unused bits.
///
private static string Respell(string canonical)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var data = canonical.TrimEnd('=');
data.Length.Should().BeLessThan(canonical.Length, "only a padded value has unused bits to set");
var last = alphabet.IndexOf(data[^1]);
return data[..^1] + alphabet[last | 1] + canonical[data.Length..];
}
///
/// Mints values with a growing filler until one comes out padded. DataProtection output grows in
/// cipher blocks, so a few lengths are enough to reach one that is not a multiple of three bytes.
///
private static string Padded(Func mint)
{
for (var length = 0; length < 64; length++)
{
var value = mint(new string('x', length));
if (value.EndsWith('='))
return value;
}
throw new InvalidOperationException("No padded value within 64 filler lengths.");
}
}