elsa-core/test/unit/Elsa.Persistence.VNext.UnitTests/VNextSecretRepositoryTests.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

136 lines
5.4 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Elsa.Secrets.Persistence.VNext.Extensions;
using Elsa.Secrets.Contracts;
using Elsa.Persistence.VNext.Document;
using Elsa.Persistence.VNext.Sqlite;
using Elsa.Secrets.Models;
using Elsa.Secrets.Persistence.VNext;
using Elsa.Secrets.Persistence.VNext.Repositories;
using Microsoft.Data.Sqlite;
namespace Elsa.Persistence.VNext.UnitTests;
public class VNextSecretRepositoryTests : IAsyncDisposable
{
private readonly SqliteConnection _connection = new("Data Source=:memory:");
private readonly SqliteDocumentStore _store;
private readonly VNextSecretRepository _repository;
public VNextSecretRepositoryTests()
{
_store = new SqliteDocumentStore(_connection, new SecretPersistenceSchemaProvider().DescribeSchema());
_repository = new VNextSecretRepository(_store, new StubTenantAccessor(string.Empty));
}
[Fact]
public async Task Repository_PersistsAndListsSecretsThroughDocumentStore()
{
await ActivateAsync();
await _repository.AddAsync(CreateSecret("smtp:password", "SMTP password"));
var reloaded = await _repository.GetAsync("SMTP:PASSWORD");
Assert.NotNull(reloaded);
Assert.Equal("SMTP password", reloaded.DisplayName);
Assert.Contains("api-key", reloaded.Tags);
reloaded.DisplayName = "Updated password";
await _repository.SaveAsync(reloaded);
var listed = await _repository.ListAsync();
Assert.Single(listed);
Assert.Equal("Updated password", listed.Single().DisplayName);
}
[Fact]
public async Task TryAddOrReplaceDeletedAsync_ReplacesOnlyDeletedSecret()
{
await ActivateAsync();
await _repository.AddAsync(CreateSecret("smtp:password", "SMTP password"));
var activeReplacementResult = await _repository.TryAddOrReplaceDeletedAsync(CreateSecret("SMTP:PASSWORD", "Active replacement"));
var deleted = CreateSecret("smtp:password", "Deleted password");
deleted.Status = SecretStatus.Deleted;
await _repository.SaveAsync(deleted);
var deletedReplacementResult = await _repository.TryAddOrReplaceDeletedAsync(CreateSecret("SMTP:PASSWORD", "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);
}
public async ValueTask DisposeAsync()
{
await _connection.DisposeAsync();
}
private async Task ActivateAsync()
{
await _connection.OpenAsync();
await _store.MaterializeAsync();
}
private static Secret CreateSecret(string name, string displayName)
{
return new Secret
{
Name = name.Trim().ToLowerInvariant(),
DisplayName = displayName,
TypeName = SecretTypeNames.Text,
StoreName = SecretStoreNames.Encrypted,
Tags = ["API-Key"],
Versions =
{
new SecretVersion
{
Version = 1,
Payload = new SecretPayload { Value = "stored", Metadata = { ["protectedValue"] = "ciphertext" } }
}
}
};
}
[Theory]
// The provider keys documents by name alone, so serving a tenant would hand back another tenant's secret.
// The default-tenant path needs no case of its own: every other test in this class runs through the same
// guard with an empty tenant id, which is what a single-tenant deployment does.
[InlineData("tenant-a")]
[InlineData("*")]
public async Task RefusesToServeANonDefaultTenant(string tenantId)
{
var repository = new VNextSecretRepository(_store, new StubTenantAccessor(tenantId));
await Assert.ThrowsAsync<NotSupportedException>(() => repository.ListAsync());
await Assert.ThrowsAsync<NotSupportedException>(() => repository.GetAsync("anything"));
await Assert.ThrowsAsync<NotSupportedException>(() => repository.AddAsync(new Secret { Name = "a", DisplayName = "a" }));
}
[Fact]
public void ResolvesFromAContainerThatNeverAddedMultitenancy()
{
// The tenancy guard needs an ITenantAccessor, which the tenants module registers -- so a host that
// never added multitenancy has none. Taking it as a required dependency made resolving the repository
// throw for exactly the deployments the guard is meant to leave alone. Every other test here
// constructs the repository directly and so could not see that; this one goes through the container,
// which is the only place the failure existed.
var services = new ServiceCollection();
services.AddSingleton<IDocumentStore>(_store);
services.AddSecretsPersistenceVNext();
using var provider = services.BuildServiceProvider();
Assert.NotNull(provider.GetRequiredService<ISecretRepository>());
}
private sealed class StubTenantAccessor(string tenantId) : Elsa.Common.Multitenancy.ITenantAccessor
{
public string TenantId { get; } = tenantId;
public Elsa.Common.Multitenancy.Tenant? Tenant => null;
public IDisposable PushContext(Elsa.Common.Multitenancy.Tenant? tenant) => throw new NotSupportedException();
}
}