elsa-core/test/unit/Elsa.Secrets.UnitTests/EFCoreSecretRepositoryTests.cs
Sipke Schoorstra ee40689ef9
feat(secrets)!: scope secrets to tenants (#7991)
* feat(secrets)!: scope secrets to tenants

Secret was the one user-facing entity with no notion of tenancy. It did not
derive from Entity, so it carried no TenantId and no query filter applied to
it: in a multi-tenant deployment every tenant could see and resolve every
other tenant's secrets. Permissions did not help, because secrets:view is
evaluated against the caller rather than against which tenant owns the
secret, so any caller holding it reached the whole set.

Secret now derives from Entity and is filtered like everything else. The
infrastructure was already in place -- SecretsElsaDbContext derives from
ElsaDbContextBase and the feature from PersistenceFeatureBase, which
registers SetTenantIdFilter -- and the handler was skipping secrets for one
reason: it only applies to Entity.

No backfill, deliberately. The column is added nullable and existing rows
keep a null tenant, because SetTenantIdFilter already treats null as the
default tenant through a clause written for exactly this case. Single-tenant
deployments see no change at all, since the filter is only installed when
multitenancy is enabled. Multi-tenant deployments find pre-existing secrets
invisible until assigned, which is a visible failure rather than continued
cross-tenant exposure.

Two things this needed that were not obvious:

Secret self-initialized its Id and nothing else ever assigned one -- there is
no identity generator on the create path -- while Entity.Id is null!. Simply
deriving would have produced a null id on every insert, which any test that
builds a Secret by hand would have missed. A constructor preserves it.

The unique index moves from NormalizedName to (TenantId, NormalizedName),
matching User, Role and Application in the same release. Leaving it global
would have made secret names a shared resource: the second tenant to want
"smtp-password" could not create one.

Elsa.Secrets.Persistence.VNext cannot support this. It keys documents by name
alone and Elsa.Persistence.VNext has no tenant concept to filter on, so it now
throws outside the default tenant rather than serving one tenant's secret to
another. Making it tenant-aware means changing the document id scheme, which
relocates existing documents and is a storage change to make deliberately.

Refs #7972

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(secrets): let the VNext repository resolve without multitenancy

The tenancy guard took ITenantAccessor as a required dependency. That
interface is registered by the tenants module, so a host that never added
multitenancy has none, and resolving ISecretRepository threw for exactly the
deployments the guard is meant to leave alone.

The accessor is now optional, and its absence means no tenancy, which is the
default tenant.

Found by review, and it is worth naming why the tests missed it: every case
in VNextSecretRepositoryTests constructs the repository directly with a stub
accessor, so none of them ever went through the container where the failure
lived. The new case resolves through a service collection that adds only the
document store and the module's own registration, which is what a
single-tenant host looks like. Reverting the fix makes it fail with the same
missing-service exception review reported.

Refs #7972

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 01:56:55 +02:00

164 lines
7.8 KiB
C#

using Elsa.Persistence.EFCore;
using Elsa.Persistence.EFCore.Extensions;
using Elsa.Secrets.Contracts;
using Elsa.Secrets.Models;
using Elsa.Secrets.Persistence.EFCore;
using Elsa.Secrets.Persistence.EFCore.Repositories;
using Elsa.Secrets.Persistence.EFCore.Sqlite.Extensions;
using Elsa.Secrets.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Elsa.Secrets.UnitTests;
public class EFCoreSecretRepositoryTests : IAsyncLifetime
{
private readonly string _databasePath = Path.Join(Path.GetTempPath(), $"elsa-secrets-{Guid.NewGuid():N}.db");
private readonly ServiceProvider _serviceProvider;
public EFCoreSecretRepositoryTests()
{
var services = new ServiceCollection();
var connectionString = $"Data Source={_databasePath}";
services.AddSqliteEntityModelCreatingHandlers();
services.AddDbContextFactory<SecretsElsaDbContext>(builder => builder.UseElsaSqlite(typeof(SqliteSecretsPersistenceFeatureExtensions).Assembly, connectionString));
services.AddSingleton<ISecretNameValidator, DefaultSecretNameValidator>();
services.AddScoped<Store<SecretsElsaDbContext, Secret>>();
services.AddScoped<EFCoreSecretRepository>();
_serviceProvider = services.BuildServiceProvider();
}
public async Task InitializeAsync()
{
await using var scope = _serviceProvider.CreateAsyncScope();
var factory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<SecretsElsaDbContext>>();
await using var dbContext = await factory.CreateDbContextAsync();
await dbContext.Database.MigrateAsync();
}
public async Task DisposeAsync()
{
await _serviceProvider.DisposeAsync();
if (File.Exists(_databasePath))
File.Delete(_databasePath);
}
[Fact]
public async Task SecretNamesAreUniquePerTenantRatherThanGlobally()
{
// Asserted against the schema rather than through the repository. The repository's own duplicate-name
// check queries dbContext.Secrets, which the global query filter already scopes to the ambient tenant
// when multitenancy is on -- so exercising it here would test SetTenantIdFilter, not this change. What
// this change owns is the index, and a global unique index would make the name a shared resource: the
// second tenant to want "smtp:password" could not create one.
await using var scope = _serviceProvider.CreateAsyncScope();
var factory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<SecretsElsaDbContext>>();
await using var dbContext = await factory.CreateDbContextAsync();
var index = dbContext.Model
.FindEntityType(typeof(Secret))!
.GetIndexes()
.Single(x => x.IsUnique);
Assert.Equal(["TenantId", SecretShadowPropertyNames.NormalizedName], index.Properties.Select(x => x.Name));
}
[Fact]
public async Task ExistingSecretsCarryNoTenantUntilOneIsAssigned()
{
// The upgrade adds the column nullable with no backfill, so rows written before it stay null. That is
// what SetTenantIdFilter's "null counts as the default tenant" clause is for, and it is why the
// migration needs no data step.
await using var scope = _serviceProvider.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<EFCoreSecretRepository>();
await repository.AddAsync(new Secret { Name = "legacy:secret", DisplayName = "Legacy" });
var stored = await repository.GetAsync("legacy:secret");
Assert.NotNull(stored);
Assert.Null(stored!.TenantId);
}
[Fact]
public async Task PersistsSecretAggregate()
{
await using var scope = _serviceProvider.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<EFCoreSecretRepository>();
var secret = new Secret
{
Name = "smtp:password",
DisplayName = "SMTP password",
Tags = ["API-Key"],
Versions = { new SecretVersion { Version = 1, Payload = new SecretPayload { Metadata = { ["ProtectedValue"] = "ciphertext" } } } }
};
await repository.AddAsync(secret);
var reloaded = await repository.GetAsync("smtp:password");
Assert.NotNull(reloaded);
Assert.Equal("SMTP password", reloaded.DisplayName);
Assert.Contains("api-key", reloaded.Tags);
Assert.True(reloaded.Versions.Single().Payload.Metadata.ContainsKey("protectedvalue"));
Assert.Equal(1, reloaded.Versions.Single().Version);
}
[Fact]
public async Task TryAddOrReplaceDeletedAsync_ReplacesOnlyDeletedSecret()
{
await using var scope = _serviceProvider.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<EFCoreSecretRepository>();
await repository.AddAsync(new Secret { Name = "smtp:password", DisplayName = "SMTP password" });
var activeReplacementResult = await repository.TryAddOrReplaceDeletedAsync(new Secret { Name = "smtp:password", DisplayName = "Active replacement" });
await repository.SaveAsync(new Secret { Name = "smtp:password", DisplayName = "Deleted password", Status = SecretStatus.Deleted });
var deletedReplacementResult = await repository.TryAddOrReplaceDeletedAsync(new Secret { Name = "smtp:password", DisplayName = "Replacement password" });
var reloaded = await repository.GetAsync("smtp:password");
Assert.False(activeReplacementResult);
Assert.True(deletedReplacementResult);
Assert.NotNull(reloaded);
Assert.Equal("Replacement password", reloaded.DisplayName);
Assert.Equal(SecretStatus.Active, reloaded.Status);
}
[Fact]
public async Task NameLookups_AreCaseInsensitive()
{
await using var scope = _serviceProvider.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<EFCoreSecretRepository>();
await repository.AddAsync(new Secret { Name = "SMTP:PASSWORD", DisplayName = "SMTP password" });
var reloaded = await repository.GetAsync("smtp:password");
var whitespaceReloaded = await repository.GetAsync(" SMTP:PASSWORD ");
var activeReplacementResult = await repository.TryAddOrReplaceDeletedAsync(new Secret { Name = "smtp:password", DisplayName = "Replacement password" });
var duplicateException = await Assert.ThrowsAsync<InvalidOperationException>(() => repository.AddAsync(new Secret { Name = "smtp:password", DisplayName = "Duplicate password" }));
Assert.NotNull(reloaded);
Assert.NotNull(whitespaceReloaded);
Assert.Equal("SMTP:PASSWORD", reloaded.Name);
Assert.Equal(reloaded.Id, whitespaceReloaded.Id);
Assert.False(activeReplacementResult);
Assert.Equal("A secret named 'smtp:password' already exists.", duplicateException.Message);
}
[Fact]
public async Task TryAddOrReplaceDeletedAsync_WhenReplacingDeletedSecret_PersistsReplacementId()
{
await using var scope = _serviceProvider.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<EFCoreSecretRepository>();
await repository.SaveAsync(new Secret { Id = "old", Name = "smtp:password", DisplayName = "Deleted password", Status = SecretStatus.Deleted });
var replacement = new Secret { Id = "new", Name = "SMTP:PASSWORD", DisplayName = "Replacement password" };
var result = await repository.TryAddOrReplaceDeletedAsync(replacement);
var reloaded = await repository.GetAsync("smtp:password");
Assert.True(result);
Assert.NotNull(reloaded);
Assert.Equal("new", reloaded.Id);
Assert.Equal("Replacement password", reloaded.DisplayName);
Assert.Equal(SecretStatus.Active, reloaded.Status);
}
}