Browse Source

Enforce unique token reference identifiers in the Entity Framework 6.x token store

pull/2549/head
pieroviano 2 months ago
parent
commit
c85637893c
  1. 3
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  2. 43
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs
  3. 17
      test/OpenIddict.EntityFramework.Tests/OpenIddict.EntityFramework.Tests.csproj
  4. 153
      test/OpenIddict.EntityFramework.Tests/OpenIddictEntityFrameworkTokenStoreTests.cs

3
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -2296,6 +2296,9 @@ Make sure the authorization server supports 'private_key_jwt', 'tls_client_auth'
<data name="ID0985" xml:space="preserve">
<value>No sender-constraining mechanism allowed by the FAPI 2.0 security profile (DPoP or mTLS) could be negotiated with the authorization server.</value>
</data>
<data name="ID0986" xml:space="preserve">
<value>The token entry cannot be created as another token entry with the same reference identifier already exists.</value>
</data>
<data name="ID2000" xml:space="preserve">
<value>The security token is missing.</value>
</data>

43
src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs

@ -112,7 +112,48 @@ public class OpenIddictEntityFrameworkTokenStore<
context.Set<TToken>().Add(token);
await context.SaveChangesAsync(cancellationToken);
if (string.IsNullOrEmpty(token.ReferenceId))
{
await context.SaveChangesAsync(cancellationToken);
return;
}
// Reference identifiers are expected to be unique (they are used to resolve reference tokens and
// to detect replayed values like DPoP proofs). Unlike Entity Framework Core, Entity Framework 6.x
// doesn't support declaring filtered unique indexes, so the ReferenceId index cannot be unique.
// To prevent concurrent requests from creating two entries with the same reference identifier,
// the existence check and the insertion are executed in a serializable transaction, which
// puts a range lock on the looked up value and blocks concurrent insertions of the same value
// until the transaction completes (one of the concurrent transactions is aborted by the database).
var identifier = token.ReferenceId;
for (var attempt = 1; ; attempt++)
{
using var transaction = CreateTransaction(context, IsolationLevel.Serializable);
try
{
if (await context.Set<TToken>().AnyAsync(entity => entity.ReferenceId == identifier, cancellationToken))
{
throw new ConcurrencyException(SR.GetResourceString(SR.ID0986));
}
await context.SaveChangesAsync(cancellationToken);
transaction?.Commit();
return;
}
// Note: range locks can occasionally cause deadlocks between transactions inserting different
// values. In this case, the aborted transaction is retried: if the entry was concurrently
// created by another transaction, the existence check will detect it during the next attempt.
catch (Exception exception) when (transaction is not null && attempt < 3 &&
exception is not ConcurrencyException && !OpenIddictHelpers.IsFatal(exception))
{
continue;
}
}
}
/// <inheritdoc/>

17
test/OpenIddict.EntityFramework.Tests/OpenIddict.EntityFramework.Tests.csproj

@ -4,6 +4,17 @@
<TargetFrameworks>$(NetFrameworkTargetFrameworks);$(NetCoreTargetFrameworks)</TargetFrameworks>
</PropertyGroup>
<!--
Note: the SourceGear.sqlite3 package (used by the SQLite-based store tests) doesn't support
AnyCPU builds, so the .NET Framework test assembly is always built as a x64 assembly.
-->
<PropertyGroup Condition=" $(TargetFramework.StartsWith('net4')) ">
<RuntimeIdentifier Condition=" '$(RuntimeIdentifier)' == '' ">win-x64</RuntimeIdentifier>
<PlatformTarget Condition=" '$(PlatformTarget)' == '' ">x64</PlatformTarget>
<Prefer32Bit Condition=" '$(Prefer32Bit)' == '' ">false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\OpenIddict.EntityFramework\OpenIddict.EntityFramework.csproj" />
</ItemGroup>
@ -13,6 +24,12 @@
<PackageReference Include="Moq" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
<PackageReference Include="SourceGear.sqlite3" />
<PackageReference Include="SQLite.CodeFirst" />
<PackageReference Include="System.Data.SQLite.EF6" />
</ItemGroup>
<ItemGroup>
<Using Include="OpenIddict.Abstractions" />
<Using Include="OpenIddict.Abstractions.OpenIddictConstants" Static="true" />

153
test/OpenIddict.EntityFramework.Tests/OpenIddictEntityFrameworkTokenStoreTests.cs

@ -0,0 +1,153 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
#if NETFRAMEWORK
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Common;
using System.Data.SQLite;
using System.Data.SQLite.EF6;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Moq;
using OpenIddict.EntityFramework.Models;
using SQLite.CodeFirst;
using Xunit;
using static OpenIddict.Abstractions.OpenIddictExceptions;
namespace OpenIddict.EntityFramework.Tests;
public sealed class OpenIddictEntityFrameworkTokenStoreTests : IDisposable
{
private readonly string _path = Path.Combine(Path.GetTempPath(), $"openiddict-ef6-{Guid.NewGuid():N}.sqlite3");
[Fact]
public async Task CreateAsync_EntriesWithoutReferenceIdentifierCanBeCreated()
{
// Arrange
using (var context = CreateContext())
{
var store = CreateStore(context);
// Act
await store.CreateAsync(new OpenIddictEntityFrameworkToken { Type = "type" }, CancellationToken.None);
await store.CreateAsync(new OpenIddictEntityFrameworkToken { Type = "type" }, CancellationToken.None);
}
// Assert
using (var context = CreateContext())
{
Assert.Equal(2, await context.Set<OpenIddictEntityFrameworkToken>().CountAsync());
}
}
[Fact]
public async Task CreateAsync_ThrowsAnExceptionForDuplicateReferenceIdentifier()
{
// Arrange
using (var context = CreateContext())
{
await CreateStore(context).CreateAsync(new OpenIddictEntityFrameworkToken { ReferenceId = "reference" }, CancellationToken.None);
}
using (var context = CreateContext())
{
var store = CreateStore(context);
// Act and assert
var exception = await Assert.ThrowsAsync<ConcurrencyException>(async () =>
await store.CreateAsync(new OpenIddictEntityFrameworkToken { ReferenceId = "reference" }, CancellationToken.None));
Assert.Equal(SR.GetResourceString(SR.ID0986), exception.Message);
}
using (var context = CreateContext())
{
Assert.Equal(1, await context.Set<OpenIddictEntityFrameworkToken>().CountAsync());
}
}
[Fact]
public async Task CreateAsync_AtMostOneConcurrentEntryWithSameReferenceIdentifierIsCreated()
{
// Arrange
using (var context = CreateContext())
{
// Ensure the database is created before starting the concurrent operations.
Assert.Equal(0, await context.Set<OpenIddictEntityFrameworkToken>().CountAsync());
}
var tasks = Enumerable.Range(0, 8).Select(_ => Task.Run(async () =>
{
using var context = CreateContext();
try
{
await CreateStore(context).CreateAsync(new OpenIddictEntityFrameworkToken { ReferenceId = "proof" }, CancellationToken.None);
return true;
}
catch (Exception)
{
return false;
}
})).ToArray();
// Act
await Task.WhenAll(tasks);
// Assert
using var verification = CreateContext();
Assert.Equal(1, await verification.Set<OpenIddictEntityFrameworkToken>().CountAsync(static token => token.ReferenceId == "proof"));
Assert.InRange(tasks.Count(static task => task.Result), 0, 1);
}
public void Dispose()
{
SQLiteConnection.ClearAllPools();
try
{
File.Delete(_path);
}
catch (IOException)
{
}
}
private TestContext CreateContext() => new(new SQLiteConnection($"Data Source={_path};Version=3;BusyTimeout=10000"));
private static OpenIddictEntityFrameworkTokenStore CreateStore(TestContext context) => new(
new MemoryCache(new MemoryCacheOptions()),
new OpenIddictEntityFrameworkContext<TestContext>(context),
Mock.Of<IOptionsMonitor<OpenIddictEntityFrameworkOptions>>(monitor =>
monitor.CurrentValue == new OpenIddictEntityFrameworkOptions()));
[DbConfigurationType(typeof(TestConfiguration))]
public sealed class TestContext(DbConnection connection) : DbContext(connection, contextOwnsConnection: true)
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.UseOpenIddict();
Database.SetInitializer(new SqliteCreateDatabaseIfNotExists<TestContext>(modelBuilder));
}
}
public sealed class TestConfiguration : DbConfiguration
{
public TestConfiguration()
{
SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
SetProviderServices("System.Data.SQLite", (DbProviderServices) SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
}
}
}
#endif
Loading…
Cancel
Save