Skip to content

Commit

Permalink
Separate licence monitoring mechanism into its own class
Browse files Browse the repository at this point in the history
Going forward Plugins aren't the only thing that might need licensing, built in features may also.
  • Loading branch information
timothycoleman committed Sep 10, 2024
1 parent c9e60bd commit b7dfb96
Show file tree
Hide file tree
Showing 8 changed files with 196 additions and 54 deletions.
15 changes: 15 additions & 0 deletions src/EventStore.Plugins/LicenseException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace EventStore.Plugins;

public class LicenseException(string featureName, Exception? inner = null) : Exception(
$"A license is required to use the {featureName} feature, but was not found. " +
"Please obtain a license or disable the feature.",
inner
) {
public string FeatureName { get; } = featureName;
}

public class LicenseEntitlementException(string featureName, string entitlement) : Exception(
$"{featureName} feature requires the {entitlement} entitlement. Please contact EventStore support.") {
public string FeatureName { get; } = featureName;
public string MissingEntitlement { get; } = entitlement;
}
8 changes: 8 additions & 0 deletions src/EventStore.Plugins/Licensing/License.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ public async Task<bool> ValidateAsync(string publicKey) {
return result.IsValid;
}

public async Task<bool> TryValidateAsync(string publicKey) {
try {
return await ValidateAsync(publicKey);
} catch {
return false;
}
}

public bool HasEntitlements(string[] entitlements, [MaybeNullWhen(true)] out string missing) {
foreach (var entitlement in entitlements) {
if (!HasEntitlement(entitlement)) {
Expand Down
5 changes: 5 additions & 0 deletions src/EventStore.Plugins/Licensing/LicenseConstants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
namespace EventStore.Plugins.Licensing;

public static class LicenseConstants {
public const string LicensePublicKey = "MEgCQQDGtRXIWmeJqkdpQryJdKBFVvLaMNHFkDcVXSoaDzg1ahrtCrAgwYpARAvGyFs0bcwYJZaZSt9aNwpgkAPOPQM5AgMBAAE=";
}
51 changes: 51 additions & 0 deletions src/EventStore.Plugins/Licensing/LicenseMonitor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.Extensions.Logging;

namespace EventStore.Plugins.Licensing;

public static class LicenseMonitor {

// the EULA prevents tampering with the license mechanism. we make the license mechanism
// robust enough that circumventing it requires intentional tampering.
public static async Task<IDisposable> MonitorAsync(
string featureName,
string[] requiredEntitlements,
ILicenseService licenseService,
ILogger logger,
string licensePublicKey = LicenseConstants.LicensePublicKey,
Action<int>? onCriticalError = null) {

onCriticalError ??= Environment.Exit;

// authenticate the license service itself so that we can trust it to
// 1. send us any licences at all
// 2. respect our decision to reject licences
var authentic = await licenseService.SelfLicense.TryValidateAsync(licensePublicKey);
if (!authentic) {
// this should never happen, but could if we end up with some unknown LicenseService.
logger.LogCritical("LicenseService could not be authenticated");
onCriticalError(11);
}

// authenticate the licenses that the license service sends us
return licenseService.Licenses.Subscribe(
onNext: async license => {

Check warning on line 31 in src/EventStore.Plugins/Licensing/LicenseMonitor.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Avoid using 'async' lambda when delegate type returns 'void'

Avoid using 'async' lambda when delegate type returns 'void'
if (await license.TryValidateAsync(licensePublicKey)) {
// got an authentic license. check required entitlements
if (license.HasEntitlement("ALL"))
return;

if (!license.HasEntitlements(requiredEntitlements, out var missing)) {
licenseService.RejectLicense(new LicenseEntitlementException(featureName, missing));
}
} else {
// this should never happen
logger.LogCritical("ESDB License was not valid");
licenseService.RejectLicense(new LicenseException(featureName, new Exception("ESDB License was not valid")));
onCriticalError(12);
}
},
onError: ex => {
licenseService.RejectLicense(new LicenseException(featureName, ex));
});
}
}
41 changes: 6 additions & 35 deletions src/EventStore.Plugins/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,43 +136,14 @@ void IPlugableComponent.ConfigureApplication(IApplicationBuilder app, IConfigura

if (Enabled && LicensePublicKey is not null) {
// the plugin is enabled and requires a license
// the EULA prevents tampering with the license mechanism. we make the license mechanism
// robust enough that circumventing it requires intentional tampering.
var licenseService = app.ApplicationServices.GetRequiredService<ILicenseService>();

// authenticate the license service itself so that we can trust it to
// 1. send us any licences at all
// 2. respect our decision to reject licences
Task.Run(async () => {
var authentic = await licenseService.SelfLicense.ValidateAsync(LicensePublicKey);
if (!authentic) {
// this should never happen, but could if we end up with some unknown LicenseService.
logger.LogCritical("LicenseService could not be authenticated");
Environment.Exit(11);
}
});

// authenticate the licenses that the license service sends us
licenseService.Licenses.Subscribe(
onNext: async license => {
if (await license.ValidateAsync(LicensePublicKey)) {
// got an authentic license. check required entitlements
if (license.HasEntitlement("ALL"))
return;

if (!license.HasEntitlements(RequiredEntitlements ?? [], out var missing)) {
licenseService.RejectLicense(new PluginLicenseEntitlementException(Name, missing));
}
} else {
// this should never happen
logger.LogCritical("ESDB License was not valid");
licenseService.RejectLicense(new PluginLicenseException(Name, new Exception("ESDB License was not valid")));
Environment.Exit(12);
}
},
onError: ex => {
licenseService.RejectLicense(new PluginLicenseException(Name, ex));
});
_ = LicenseMonitor.MonitorAsync(
Name,
RequiredEntitlements ?? [],
licenseService,
logger,
LicensePublicKey);
}

// there is still a chance to disable the plugin when configuring the application
Expand Down
14 changes: 0 additions & 14 deletions src/EventStore.Plugins/PluginLicenseException.cs

This file was deleted.

106 changes: 106 additions & 0 deletions test/EventStore.Plugins.Tests/Licensing/LicenseMonitorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using EventStore.Plugins.Licensing;
using Microsoft.Extensions.Logging.Testing;

namespace EventStore.Plugins.Tests.Licensing;

public class LicenseMonitorTests {
[Fact]
public async Task valid_license_with_correct_entitlements() {
var licenseService = new PluginBaseTests.FakeLicenseService(
createLicense: true,
entitlements: ["MY_ENTITLEMENT"]);

var criticalError = false;

using var subscription = await LicenseMonitor.MonitorAsync(
featureName: "TestFeature",
requiredEntitlements: ["MY_ENTITLEMENT"],
licenseService: licenseService,
logger: new FakeLogger(),
licensePublicKey: licenseService.PublicKey,
onCriticalError: _ => criticalError = true);

licenseService.RejectionException.Should().BeNull();
criticalError.Should().BeFalse();
}

[Fact]
public async Task valid_license_with_all_entitlement() {
var licenseService = new PluginBaseTests.FakeLicenseService(
createLicense: true,
entitlements: ["ALL"]);

var criticalError = false;

using var subscription = await LicenseMonitor.MonitorAsync(
featureName: "TestFeature",
requiredEntitlements: ["MY_ENTITLEMENT"],
licenseService: licenseService,
logger: new FakeLogger(),
licensePublicKey: licenseService.PublicKey,
onCriticalError: _ => criticalError = true);

licenseService.RejectionException.Should().BeNull();
criticalError.Should().BeFalse();
}

[Fact]
public async Task valid_license_with_missing_entitlement() {
var licenseService = new PluginBaseTests.FakeLicenseService(
createLicense: true,
entitlements: []);

var criticalError = false;

using var subscription = await LicenseMonitor.MonitorAsync(
featureName: "TestFeature",
requiredEntitlements: ["MY_ENTITLEMENT"],
licenseService: licenseService,
logger: new FakeLogger(),
licensePublicKey: licenseService.PublicKey,
onCriticalError: _ => criticalError = true);

licenseService.RejectionException.Should().BeOfType<LicenseEntitlementException>()
.Which.MissingEntitlement.Should().Be("MY_ENTITLEMENT");
criticalError.Should().BeFalse();
}

[Fact]
public async Task no_license() {
var licenseService = new PluginBaseTests.FakeLicenseService(
createLicense: false);

var criticalError = false;

using var subscription = await LicenseMonitor.MonitorAsync(
featureName: "TestFeature",
requiredEntitlements: [],
licenseService: licenseService,
logger: new FakeLogger(),
licensePublicKey: licenseService.PublicKey,
onCriticalError: _ => criticalError = true);

licenseService.RejectionException.Should().BeOfType<LicenseException>();
criticalError.Should().BeFalse();
}

[Fact]
public async Task license_is_not_valid() {
var licenseService = new PluginBaseTests.FakeLicenseService(
createLicense: true,
entitlements: []);

var criticalError = false;

using var subscription = await LicenseMonitor.MonitorAsync(
featureName: "TestFeature",
requiredEntitlements: [],
licenseService: licenseService,
logger: new FakeLogger(),
licensePublicKey: "a_different_public_key",
onCriticalError: _ => criticalError = true);

licenseService.RejectionException.Should().BeOfType<LicenseException>();
criticalError.Should().BeTrue();
}
}
10 changes: 5 additions & 5 deletions test/EventStore.Plugins.Tests/PluginBaseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ public void commercial_plugin_is_disabled_when_licence_is_missing() {
plugin.ConfigureApplication(app, app.Configuration);

// Assert
licenseService.RejectionException.Should().BeOfType<PluginLicenseException>().Which
.PluginName.Should().Be(plugin.Name);
licenseService.RejectionException.Should().BeOfType<LicenseException>().Which
.FeatureName.Should().Be(plugin.Name);
}

[Fact]
Expand All @@ -119,8 +119,8 @@ public void commercial_plugin_is_disabled_when_licence_is_missing_entitlement()
plugin.ConfigureApplication(app, app.Configuration);

// Assert
licenseService.RejectionException.Should().BeOfType<PluginLicenseEntitlementException>().Which
.PluginName.Should().Be(plugin.Name);
licenseService.RejectionException.Should().BeOfType<LicenseEntitlementException>().Which
.FeatureName.Should().Be(plugin.Name);
}

[Fact]
Expand Down Expand Up @@ -197,7 +197,7 @@ public void plugin_can_be_disabled_on_ConfigureApplication() {
.WhoseValue.Should().BeEquivalentTo(false);
}

class FakeLicenseService : ILicenseService {
public class FakeLicenseService : ILicenseService {
public FakeLicenseService(
bool createLicense,
params string[] entitlements) {
Expand Down

0 comments on commit b7dfb96

Please sign in to comment.