-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Add self-hosted premium license signing to the seeder #8178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nthompson-bitwarden
wants to merge
4
commits into
main
Choose a base branch
from
seeder/premium-selfhost-license-signing
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
f68322e
Add self-hosted premium license signing to the seeder
nthompson-bitwarden 5d70e72
resolve review comments
nthompson-bitwarden 255324b
Merge branch 'main' into seeder/premium-selfhost-license-signing
nthompson-bitwarden ed199d8
add guard against null license directory on DeleteSeededUserLicenseFiles
nthompson-bitwarden File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
156 changes: 156 additions & 0 deletions
156
test/SeederApi.IntegrationTest/Commands/DestroySceneCommandTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| ο»Ώusing AutoMapper; | ||
| using Bit.Core.Entities; | ||
| using Bit.Core.Settings; | ||
| using Bit.Core.Utilities; | ||
| using Bit.Infrastructure.EntityFramework.AdminConsole.Repositories; | ||
| using Bit.Infrastructure.EntityFramework.Repositories; | ||
| using Bit.SeederApi.Commands; | ||
| using Microsoft.Data.Sqlite; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Xunit; | ||
|
|
||
| namespace Bit.SeederApi.IntegrationTest.Commands; | ||
|
|
||
| /// <summary>Exercises <see cref="DestroySceneCommand"/> premium license-file cleanup against in-memory SQLite.</summary> | ||
| public sealed class DestroySceneCommandTests : IDisposable | ||
| { | ||
| private readonly SqliteConnection _connection; | ||
| private readonly ServiceProvider _provider; | ||
| private readonly string _licenseDirectory; | ||
|
|
||
| public DestroySceneCommandTests() | ||
| { | ||
| _connection = new SqliteConnection("DataSource=:memory:"); | ||
| _connection.Open(); | ||
|
|
||
| var services = new ServiceCollection(); | ||
| services.AddLogging(); | ||
| // DatabaseContext.OnModelCreating resolves IDataProtectionProvider for the | ||
| // User.Key / User.MasterPassword field converters, so DI must include it. | ||
| services.AddDataProtection(); | ||
| services.AddDbContext<DatabaseContext>(opts => opts.UseSqlite(_connection)); | ||
| services.AddAutoMapper(typeof(UserRepository)); | ||
|
|
||
| _provider = services.BuildServiceProvider(); | ||
| _provider.GetRequiredService<DatabaseContext>().Database.EnsureCreated(); | ||
|
|
||
| _licenseDirectory = Path.Combine(Path.GetTempPath(), $"seeder-license-tests-{Guid.NewGuid():N}"); | ||
| Directory.CreateDirectory(Path.Combine(_licenseDirectory, "user")); | ||
|
nthompson-bitwarden marked this conversation as resolved.
Dismissed
|
||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| _provider.Dispose(); | ||
| _connection.Dispose(); | ||
| if (Directory.Exists(_licenseDirectory)) | ||
| { | ||
| Directory.Delete(_licenseDirectory, recursive: true); | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DestroyAsync_SelfHosted_DeletesSeededUserLicenseFile() | ||
| { | ||
| var playId = Guid.NewGuid().ToString(); | ||
| var user = await SeedUserWithPlayItemAsync(playId); | ||
| var licenseFile = WriteLicenseFile(user.Id); | ||
|
|
||
| await BuildCommand(selfHosted: true).DestroyAsync(playId); | ||
|
|
||
| Assert.False(File.Exists(licenseFile)); | ||
| Assert.False(UserExists(user.Id)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DestroyAsync_NotSelfHosted_LeavesLicenseFileUntouched() | ||
| { | ||
| var playId = Guid.NewGuid().ToString(); | ||
| var user = await SeedUserWithPlayItemAsync(playId); | ||
| var licenseFile = WriteLicenseFile(user.Id); | ||
|
|
||
| await BuildCommand(selfHosted: false).DestroyAsync(playId); | ||
|
|
||
| Assert.True(File.Exists(licenseFile)); | ||
| Assert.False(UserExists(user.Id)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DestroyAsync_SelfHosted_MissingLicenseFile_StillSucceeds() | ||
| { | ||
| var playId = Guid.NewGuid().ToString(); | ||
| var user = await SeedUserWithPlayItemAsync(playId); | ||
|
|
||
| await BuildCommand(selfHosted: true).DestroyAsync(playId); | ||
|
|
||
| Assert.False(UserExists(user.Id)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DestroyAsync_SelfHosted_UndeletableLicenseFile_DoesNotAbortDestroy() | ||
| { | ||
| var playId = Guid.NewGuid().ToString(); | ||
| var user = await SeedUserWithPlayItemAsync(playId); | ||
|
|
||
| // A directory at the license file path forces File.Delete to throw; the best-effort cleanup must | ||
| // swallow it so the database teardown still succeeds. | ||
| var blockingPath = Path.Combine(_licenseDirectory, "user", $"{user.Id}.json"); | ||
|
nthompson-bitwarden marked this conversation as resolved.
Dismissed
|
||
| Directory.CreateDirectory(blockingPath); | ||
|
|
||
| await BuildCommand(selfHosted: true).DestroyAsync(playId); | ||
|
|
||
| Assert.False(UserExists(user.Id)); | ||
| Assert.True(Directory.Exists(blockingPath)); | ||
| } | ||
|
|
||
| private DestroySceneCommand BuildCommand(bool selfHosted) | ||
| { | ||
| var scopeFactory = _provider.GetRequiredService<IServiceScopeFactory>(); | ||
| var mapper = _provider.GetRequiredService<IMapper>(); | ||
| var globalSettings = new GlobalSettings | ||
| { | ||
| SelfHosted = selfHosted, | ||
| LicenseDirectory = _licenseDirectory, | ||
| }; | ||
|
|
||
| return new DestroySceneCommand( | ||
| _provider.GetRequiredService<DatabaseContext>(), | ||
| _provider.GetRequiredService<ILogger<DestroySceneCommand>>(), | ||
| new UserRepository(scopeFactory, mapper), | ||
| new PlayItemRepository(scopeFactory, mapper), | ||
| new ProviderRepository(scopeFactory, mapper), | ||
| new OrganizationRepository(scopeFactory, mapper, | ||
| _provider.GetRequiredService<ILogger<OrganizationRepository>>()), | ||
| globalSettings); | ||
| } | ||
|
|
||
| private async Task<User> SeedUserWithPlayItemAsync(string playId) | ||
| { | ||
| var scopeFactory = _provider.GetRequiredService<IServiceScopeFactory>(); | ||
| var mapper = _provider.GetRequiredService<IMapper>(); | ||
|
|
||
| var user = new User | ||
| { | ||
| Id = CombGuid.Generate(), | ||
| Email = $"destroy-{Guid.NewGuid():N}@bw.example", | ||
| SecurityStamp = Guid.NewGuid().ToString(), | ||
| ApiKey = "test-api-key", | ||
| }; | ||
| await new UserRepository(scopeFactory, mapper).CreateAsync(user); | ||
|
|
||
| var playItem = PlayItem.Create(user, playId); | ||
| playItem.SetNewId(); | ||
| await new PlayItemRepository(scopeFactory, mapper).CreateAsync(playItem); | ||
|
|
||
| return user; | ||
| } | ||
|
|
||
| private string WriteLicenseFile(Guid userId) | ||
| { | ||
| var path = Path.Combine(_licenseDirectory, "user", $"{userId}.json"); | ||
|
nthompson-bitwarden marked this conversation as resolved.
Dismissed
|
||
| File.WriteAllText(path, "{}"); | ||
| return path; | ||
| } | ||
|
|
||
| private bool UserExists(Guid userId) => | ||
| _provider.GetRequiredService<DatabaseContext>().Users.Any(u => u.Id == userId); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| ο»Ώusing System.Security.Claims; | ||
| using Bit.Core.AdminConsole.Entities; | ||
| using Bit.Core.Billing.Models.Business; | ||
| using Bit.Core.Billing.Organizations.Models; | ||
| using Bit.Core.Billing.Services; | ||
| using Bit.Core.Entities; | ||
| using Bit.Core.Models.Business; | ||
| using Bit.Seeder.Services; | ||
|
|
||
| namespace Bit.SeederApi.IntegrationTest; | ||
|
|
||
| /// <summary> | ||
| /// Shared harness for the self-hosted premium license tests: a premium-owner factory plus hand-written | ||
| /// licensing stubs. | ||
| /// </summary> | ||
| internal static class LicenseTestHelpers | ||
| { | ||
| internal static User NewPremiumOwner() => new() | ||
| { | ||
| Id = Guid.NewGuid(), | ||
| Email = "premium.user@example.com", | ||
| Premium = true, | ||
| }; | ||
|
|
||
| internal sealed class StubSeederLicenseSigner(Func<User, Task<LicenseSigningResult>> behavior) : ISeederLicenseSigner | ||
| { | ||
| public Task<LicenseSigningResult> CreateUserTokenAsync(User user) => behavior(user); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Captures the licenses passed to <see cref="ILicensingService.WriteUserLicenseAsync"/> and runs | ||
| /// <paramref name="onWrite"/> to drive the success or failure path. | ||
| /// </summary> | ||
| internal sealed class StubLicensingService(Func<User, UserLicense, Task> onWrite) : ILicensingService | ||
| { | ||
| public List<UserLicense> WrittenLicenses { get; } = []; | ||
|
|
||
| public Task WriteUserLicenseAsync(User user, UserLicense license) | ||
| { | ||
| WrittenLicenses.Add(license); | ||
| return onWrite(user, license); | ||
| } | ||
|
|
||
| public Task ValidateOrganizationsAsync() => throw new NotImplementedException(); | ||
| public Task ValidateUsersAsync() => throw new NotImplementedException(); | ||
| public Task<bool> ValidateUserPremiumAsync(User user) => throw new NotImplementedException(); | ||
| public bool VerifyLicense(ILicense license) => throw new NotImplementedException(); | ||
| public byte[] SignLicense(ILicense license) => throw new NotImplementedException(); | ||
| public Task<OrganizationLicense?> ReadOrganizationLicenseAsync(Organization organization) => throw new NotImplementedException(); | ||
| public Task<OrganizationLicense?> ReadOrganizationLicenseAsync(Guid organizationId) => throw new NotImplementedException(); | ||
| public ClaimsPrincipal? GetClaimsPrincipalFromLicense(ILicense license) => throw new NotImplementedException(); | ||
| public Task<string?> CreateOrganizationTokenAsync(Organization organization, Guid installationId, SubscriptionInfo subscriptionInfo) => throw new NotImplementedException(); | ||
| public Task<string?> CreateUserTokenAsync(User user, SubscriptionInfo subscriptionInfo) => throw new NotImplementedException(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.