PlotDirector/PlotLine.Tests/SubscriptionEntitlementTests.cs

194 lines
11 KiB
C#

using System.Reflection;
using Microsoft.AspNetCore.Authorization;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
internal static class SubscriptionEntitlementTests
{
public static void EffectiveStateAndLimits()
{
var now = DateTime.UtcNow;
var subscription = Trial(now.AddDays(-10), now.AddSeconds(1));
SubscriptionOverride? activeOverride = null;
var ownedBooks = 1;
var levels = new Dictionary<int, SubscriptionLevel>
{
[1] = Level(1, "DraftDesk", "Draft Desk", 2, false),
[2] = Level(2, "WritingRoom", "Writing Room", 10, true),
[3] = Level(3, "StoryForge", "Story Forge", 30, true),
[4] = Level(4, "AuthorStudio", "Author Studio", 999999, true)
};
var repository = Proxy<ISubscriptionRepository>((method, args) => method switch
{
nameof(ISubscriptionRepository.GetCurrentSubscriptionAsync) => Task.FromResult<UserSubscriptionDetail?>(subscription),
nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult<UserSubscriptionDetail?>(subscription),
nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(activeOverride),
nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult<SubscriptionLevel?>(levels[(int)args![0]!]),
nameof(ISubscriptionRepository.GetOwnedBookCountAsync) => Task.FromResult(ownedBooks),
_ => DefaultTask(method)
});
var service = new SubscriptionService(repository, Proxy<IUserFileRepository>((method, _) => DefaultTask(method)));
var active = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(active.State == EntitlementState.ActiveTrial, "A trial immediately before expiry must remain active.");
Check(service.CanUseFeatureAsync(7, SubscriptionFeature.StoryIntelligence, now).GetAwaiter().GetResult().Allowed,
"An active trial must be able to use entitled features.");
var boundary = service.GetEffectiveEntitlementAsync(7, subscription.TrialExpiryDateUTC).GetAwaiter().GetResult();
Check(boundary.State == EntitlementState.ExpiredTrial && boundary.IsReadOnly,
"The exact trial expiry boundary must be read-only.");
Check(!service.CanUseFeatureAsync(7, SubscriptionFeature.Import, subscription.TrialExpiryDateUTC).GetAwaiter().GetResult().Allowed,
"An expired trial must not be able to import.");
subscription.TrialExpiryDateUTC = now.AddDays(30);
var extended = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(extended.State == EntitlementState.ActiveTrial, "An administrator-extended trial must become active.");
subscription.TrialExpiryDateUTC = null;
subscription.StartDateUTC = now.AddDays(-31);
Check(service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult().State == EntitlementState.ExpiredTrial,
"A malformed historical trial with no expiry must safely fall back to start plus 30 days.");
subscription.StartDateUTC = now.AddDays(-10);
subscription.TrialExpiryDateUTC = now.AddDays(20);
ownedBooks = 1;
Check(service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, "Below the real Draft Desk book limit should be allowed.");
ownedBooks = 2;
Check(!service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, "Exactly at the book limit must block another book.");
ownedBooks = 1;
var oversizedImport = service.CanUseResourcesAsync(7, new SubscriptionResourceRequest
{
AdditionalBooks = 1,
FinalChapterCounts = [76],
FinalSceneCounts = [301],
FinalCharacterCount = 76
}, now).GetAwaiter().GetResult();
Check(!oversizedImport.Allowed && oversizedImport.Code == "chapter_limit",
"Bulk creation must enforce configured per-book limits before persistence.");
activeOverride = new SubscriptionOverride
{
SubscriptionOverrideID = 9,
UserID = 7,
SubscriptionLevelID = 3,
StartDateUTC = now.AddDays(-1),
ExpiryDateUTC = now.AddMonths(3),
Reason = "Complimentary review",
LevelDisplayName = "Story Forge"
};
var overridden = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(overridden.State == EntitlementState.ActiveOverride && overridden.EffectiveLevel?.Name == "StoryForge",
"An active temporary override must take precedence over the underlying trial.");
ownedBooks = 8;
Check(service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, "A higher-plan override must use that plan's resource limit.");
activeOverride = null;
var fallback = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(fallback.State == EntitlementState.ActiveTrial && fallback.EffectiveLevel?.Name == "DraftDesk",
"Removing or expiring an override must fall back to underlying access.");
subscription = Paid(now, "active");
var paid = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(paid.State == EntitlementState.ActivePaid, "An active paid subscription must be active.");
foreach (var (levelId, maximum) in new[] { (2, 10), (3, 30) })
{
var level = levels[levelId];
subscription = Paid(now, "active");
subscription.SubscriptionLevelID = levelId;
subscription.Name = level.Name;
subscription.DisplayName = level.DisplayName;
subscription.MaxBooks = maximum;
ownedBooks = maximum - 1;
Check(service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, $"{level.DisplayName} must allow its final configured book slot.");
ownedBooks = maximum;
Check(!service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, $"{level.DisplayName} must enforce its configured {maximum}-book limit.");
}
subscription = Paid(now, "active");
subscription.SubscriptionLevelID = 4;
subscription.Name = "AuthorStudio";
subscription.DisplayName = "Author Studio";
subscription.MaxBooks = 999999;
ownedBooks = 999999;
Check(service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, "Author Studio's configured practical-unlimited value must remain unlimited.");
subscription.StripeStatus = "canceled";
subscription.CurrentPeriodEndUTC = now;
Check(service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult().State == EntitlementState.InactiveSubscription,
"A cancelled paid subscription at its period boundary must be read-only.");
}
public static void EnforcementAndAdminSecurity()
{
var sql = File.ReadAllText(Path.Combine(FindRepositoryRoot(), "PlotLine", "Sql", "201_SubscriptionEntitlementEnforcement.sql"));
Check(sql.Contains("sp_getapplock", StringComparison.Ordinal) && sql.Contains("SubscriptionBookSlotReservation", StringComparison.Ordinal),
"Book creation concurrency must be protected by a database lock and reservation.");
Check(sql.Contains("SubscriptionAdministrationAudit", StringComparison.Ordinal), "Administrative subscription changes must be audited.");
var authorize = typeof(AdminController).GetCustomAttribute<AuthorizeAttribute>();
Check(authorize?.Policy == "AdminOnly", "Subscription administration must remain under the existing AdminOnly policy.");
Check(typeof(SubscriptionEnforcementFilter).GetInterfaces().Any(x => x.Name == "IAsyncActionFilter"),
"Unsafe requests must have a server-side entitlement filter.");
}
private static UserSubscriptionDetail Trial(DateTime start, DateTime expiry) => new()
{
UserID = 7, SubscriptionLevelID = 1, StartDateUTC = start, TrialExpiryDateUTC = expiry,
IsActive = true, IsTrial = true, SubscriptionLevelIsActive = true, Name = "DraftDesk", DisplayName = "Draft Desk",
MaxBooks = 2, MaxChaptersPerBook = 75, MaxScenesPerBook = 300, MaxCharactersPerProject = 75,
MaxStorageMB = 100, MaxCollaborators = 0, RequiresStripeSubscription = false
};
private static UserSubscriptionDetail Paid(DateTime now, string status) => new()
{
UserID = 7, SubscriptionLevelID = 3, StartDateUTC = now.AddMonths(-1), IsActive = true,
SubscriptionLevelIsActive = true, Name = "StoryForge", DisplayName = "Story Forge", RequiresStripeSubscription = true,
StripeSubscriptionId = "sub_test", StripeStatus = status, CurrentPeriodEndUTC = now.AddMonths(1),
MaxBooks = 30, MaxChaptersPerBook = 200, MaxScenesPerBook = 2000, MaxCharactersPerProject = 500,
MaxStorageMB = 5120, MaxCollaborators = 3
};
private static SubscriptionLevel Level(int id, string name, string display, int maxBooks, bool stripe) => new()
{
SubscriptionLevelID = id, Name = name, DisplayName = display, MaxBooks = maxBooks,
MaxChaptersPerBook = id == 1 ? 75 : 200, MaxScenesPerBook = id == 1 ? 300 : 2000,
MaxCharactersPerProject = id == 1 ? 75 : 500, MaxStorageMB = id == 1 ? 100 : 5120,
MaxCollaborators = id == 1 ? 0 : 3, RequiresStripeSubscription = stripe, IsActive = true
};
private static object DefaultTask(string method) => method switch
{
nameof(IUserFileRepository.GetStorageUsageForOwnerAsync) => Task.FromResult(0L),
_ => Task.CompletedTask
};
private static T Proxy<T>(Func<string, object?[]?, object> handler) where T : class
{
var proxy = DispatchProxy.Create<T, EntitlementProxy>();
((EntitlementProxy)(object)proxy).Handler = handler;
return proxy;
}
private static string FindRepositoryRoot()
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "PlotLine.slnx"))) directory = directory.Parent;
return directory?.FullName ?? throw new InvalidOperationException("Repository root not found.");
}
private static void Check(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
public class EntitlementProxy : DispatchProxy
{
public Func<string, object?[]?, object> Handler { get; set; } = null!;
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) => Handler(targetMethod!.Name, args);
}
}