diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx index 1c30eb29..6fe5016e 100644 --- a/src/OpenIddict.Abstractions/OpenIddictResources.resx +++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx @@ -2296,6 +2296,9 @@ Make sure the authorization server supports 'private_key_jwt', 'tls_client_auth' No sender-constraining mechanism allowed by the FAPI 2.0 security profile (DPoP or mTLS) could be negotiated with the authorization server. + + The token entry cannot be created as another token entry with the same reference identifier already exists. + The security token is missing. diff --git a/src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs b/src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs index 6d5bcb20..bfc5a9f6 100644 --- a/src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs +++ b/src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs @@ -112,7 +112,48 @@ public class OpenIddictEntityFrameworkTokenStore< context.Set().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().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; + } + } } /// diff --git a/test/OpenIddict.EntityFramework.Tests/OpenIddict.EntityFramework.Tests.csproj b/test/OpenIddict.EntityFramework.Tests/OpenIddict.EntityFramework.Tests.csproj index 6c13834a..9444158c 100644 --- a/test/OpenIddict.EntityFramework.Tests/OpenIddict.EntityFramework.Tests.csproj +++ b/test/OpenIddict.EntityFramework.Tests/OpenIddict.EntityFramework.Tests.csproj @@ -4,6 +4,17 @@ $(NetFrameworkTargetFrameworks);$(NetCoreTargetFrameworks) + + + + win-x64 + x64 + false + + @@ -13,6 +24,12 @@ + + + + + + diff --git a/test/OpenIddict.EntityFramework.Tests/OpenIddictEntityFrameworkTokenStoreTests.cs b/test/OpenIddict.EntityFramework.Tests/OpenIddictEntityFrameworkTokenStoreTests.cs new file mode 100644 index 00000000..09a92950 --- /dev/null +++ b/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().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(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().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().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().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(context), + Mock.Of>(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(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