public void Test_Offline_License_Failure()
        {
            var clock = new OffsetClock("2017-04-25", "2017-04-25");
            var mgr   = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock)
            {
                Cache = new StringCacheMem()
            };
            var conf = new Config();

            conf.Plugins.LicenseScope = LicenseAccess.Local;
            conf.Plugins.Install(new LicensedPlugin(mgr, clock, "R4Creative"));

            Assert.Empty(mgr.GetIssues());
            Assert.Null(mgr.GetAllLicenses().FirstOrDefault());

            var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);

            Assert.False(result.LicensedForRequestUrl(new Uri("http://acme.com")));
            conf.Plugins.AddLicense(LicenseStrings.Offlinev4DomainAcmeComCreative);

            Assert.NotNull(mgr.GetAllLicenses().First());

            result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);
            Assert.True(result.LicensedForRequestUrl(new Uri("http://acme.com")));

            Assert.Empty(mgr.GetIssues());
            Assert.NotNull(conf.GetDiagnosticsPage());
            Assert.NotNull(conf.GetLicensesPage());
        }
Beispiel #2
0
        public void Test_License_Enforcer_Watermark()
        {
            var clock   = new RealClock();
            var mgr     = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
            var request = new RequestUrlProvider();

            var conf = new Config();

            conf.Plugins.LicenseScope = LicenseAccess.Local;
            conf.Plugins.AddLicense(LicenseStrings.Offlinev4DomainAcmeComCreative);
            conf.Plugins.LicenseError = LicenseErrorAction.Watermark;
            conf.Plugins.AddLicensedDomainMapping("localhost", "acme.com");
            conf.Plugins.Install(new Gradient());
            conf.Plugins.Install(new EmptyLicenseEnforcedPlugin(new LicenseEnforcer <EmptyLicenseEnforcedPlugin>(mgr, mgr, request.Get).EnableEnforcement(), "R4Creative"));

            request.Url = null;
            Assert.False(IsWatermarking(conf, mgr));

            request.Url = new Uri("http://acme.com");
            Assert.False(IsWatermarking(conf, mgr));

            request.Url = new Uri("http://subdomain.acme.com");
            Assert.False(IsWatermarking(conf, mgr));

            request.Url = new Uri("http://localhost");
            Assert.False(IsWatermarking(conf, mgr));

            // We should watermark unlicensed domains
            request.Url = new Uri("http://other.co");
            Assert.True(IsWatermarking(conf, mgr));
            Assert.True(IsWatermarking(conf, mgr));

            Assert.Empty(mgr.GetIssues());
        }
        public void Test_Offline_License_Success()
        {
            var clock = new OffsetClock("2017-04-25", "2017-04-25");
            var mgr   = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());

            var conf = new MockConfig(mgr, clock, new [] { "R4Creative" }, new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("localhost", "acme.com")
            });

            conf.AddLicense(LicenseStrings.OfflineV4DomainAcmeComCreative);

            Assert.Equal(0, mgr.WaitForTasks());
            Assert.Empty(mgr.GetIssues());

            Assert.Single(mgr.GetAllLicenses());


            Assert.NotNull(mgr.GetAllLicenses().First());

            var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);

            Assert.True(result.LicensedForRequestUrl(new Uri("http://acme.com")));
            Assert.True(result.LicensedForRequestUrl(new Uri("http://subdomain.acme.com")));
            Assert.True(result.LicensedForRequestUrl(new Uri("http://localhost")));
            Assert.False(result.LicensedForRequestUrl(new Uri("http://other.com")));
            Assert.Equal(0, mgr.WaitForTasks());
            Assert.Empty(mgr.GetIssues());
            Assert.NotNull(conf.GetLicensesPage());
        }
        public async void TestAGPL()
        {
            using (var contentRoot = new TempContentRoot()
                                     .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg"))
            {
                var clock     = new RealClock();
                var mgr       = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
                var licensing = new Licensing(mgr);


                using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions ()
                {
                    Licensing = licensing,
                    MyOpenSourceProjectUrl = "https://github.com/username/project",
                    EnforcementMethod      = EnforceLicenseWith.RedDotWatermark
                }.MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")));

                // Create an HttpClient to send requests to the TestServer
                using var client = host.GetTestClient();

                using var licensedResponse = await client.GetAsync("/fire.jpg?w=1");

                licensedResponse.EnsureSuccessStatusCode();

                var page = licensing.Result.ProvidePublicLicensesPage();
                Assert.Contains("License Validation OFF", page);
                Assert.Contains("No license keys found.", page);
                Assert.DoesNotContain("You must purchase a license key or comply with the AGPLv3.", page);
                Assert.DoesNotContain("To get a license key", page);
                Assert.Contains("You are using EnforceLicenseWith.RedDotWatermark", page);

                await host.StopAsync(CancellationToken.None);
            }
        }
Beispiel #5
0
        public void Test_License_Enforcer_Exception_Web_Config()
        {
            var clock   = new RealClock();
            var mgr     = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
            var request = new RequestUrlProvider();

            var conf = new Config(new ResizerSection(
                                      @"<resizer><licenses licenseError='exception' licenseScope='local'>
      <maphost from='localhost' to='acme.com' />
      <license>" + LicenseStrings.Offlinev4DomainAcmeComCreative + "</license></licenses>" +
                                      "<plugins><add name='Gradient'/></plugins></resizer>"));

            conf.Plugins.Install(new EmptyLicenseEnforcedPlugin(new LicenseEnforcer <EmptyLicenseEnforcedPlugin>(mgr, mgr, request.Get).EnableEnforcement(), "R4Creative"));

            request.Url = null;
            Assert.False(IsWatermarking(conf, mgr));
            request.Url = new Uri("http://acme.com");
            Assert.False(IsWatermarking(conf, mgr));
            request.Url = new Uri("http://subdomain.acme.com");
            Assert.False(IsWatermarking(conf, mgr));
            request.Url = new Uri("http://localhost");
            Assert.False(IsWatermarking(conf, mgr));

            request.Url = new Uri("http://other.co");
            var e = Record.Exception(() => IsWatermarking(conf, mgr));

            Assert.NotNull(e);
            Assert.IsType <LicenseException>(e);

            Assert.Empty(mgr.GetIssues());
        }
        public void Test_Offline_License_Success()
        {
            var clock = new OffsetClock("2017-04-25", "2017-04-25");
            var mgr   = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock)
            {
                Cache = new StringCacheMem()
            };
            var conf = new Config(new ResizerSection(
                                      @"<resizer><licenses>
      <maphost from='localhost' to='acme.com' />
      <license>" + LicenseStrings.Offlinev4DomainAcmeComCreative + "</license></licenses></resizer>"));

            conf.Plugins.LicenseScope = LicenseAccess.Local;
            conf.Plugins.Install(new LicensedPlugin(mgr, clock, "R4Creative"));

            Assert.Equal(0, mgr.WaitForTasks());
            Assert.Empty(mgr.GetIssues());

            Assert.NotNull(mgr.GetAllLicenses().First());

            var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);

            Assert.True(result.LicensedForRequestUrl(new Uri("http://acme.com")));
            Assert.True(result.LicensedForRequestUrl(new Uri("http://subdomain.acme.com")));
            Assert.True(result.LicensedForRequestUrl(new Uri("http://localhost")));
            Assert.False(result.LicensedForRequestUrl(new Uri("http://other.com")));
            Assert.Equal(0, mgr.WaitForTasks());
            Assert.Empty(mgr.GetIssues());
            Assert.NotNull(conf.GetDiagnosticsPage());
            Assert.NotNull(conf.GetLicensesPage());
        }
        public void Test_Caching_With_Timeout()
        {
            if (Environment.GetEnvironmentVariable("APPVEYOR") == "True")
            {
                return;
            }

            var clock = new OffsetClock("2017-04-25", "2017-04-25");
            var cache = new StringCacheMem();

            // Populate cache
            {
                var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, cache);
                MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, LicenseStrings.EliteSubscriptionRemote,
                                                  null);

                var conf = new MockConfig(mgr, clock, new [] { "R_Elite", "R4Elite" }, new List <KeyValuePair <string, string> >());

                conf.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder);

                mgr.WaitForTasks();

                var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);
                Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain")));

                Assert.Empty(mgr.GetIssues());
                Assert.NotNull(conf.GetLicensesPage());
            }

            // Use cache
            {
                var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, cache)
                {
                    SkipHeartbeatsIfDiskCacheIsFresh = 0
                };
                MockHttpHelpers.MockRemoteLicenseException(mgr, WebExceptionStatus.NameResolutionFailure);

                var conf = new MockConfig(mgr, clock, new [] { "R_Elite", "R4Elite" }, new List <KeyValuePair <string, string> >());
                try {
                    conf.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder);

                    conf.FireHeartbeat();
                    mgr.WaitForTasks();

                    var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);
                    Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain")));


                    Assert.NotNull(conf.GetLicensesPage());

                    Assert.Single(mgr.GetIssues());
                } catch {
                    output.WriteLine(conf.GetLicensesPage());
                    throw;
                }
            }
        }
        public async void TestSiteLicense()
        {
            using (var contentRoot = new TempContentRoot()
                                     .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg"))
            {
                var clock = new FakeClock("2017-04-25", "2017-04-25");
                var set   = LicenseStrings.GetSets("SiteWideImageflow").First();
                var mgr   = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
                MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, set.Remote, null);
                var url       = new RequestUrlProvider();
                var licensing = new Licensing(mgr, url.Get);

                using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions ()
                {
                    Licensing = licensing,
                    MyOpenSourceProjectUrl = null
                }
                                                             .SetLicenseKey (EnforceLicenseWith.Http402Error,
                                                                             set.Placeholder)
                                                             .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")));

                // Create an HttpClient to send requests to the TestServer
                using var client = host.GetTestClient();

                mgr.WaitForTasks();

                Assert.Empty(mgr.GetIssues());


                url.Url = new Uri("https://acme.com");
                using var licensedResponse1 = await client.GetAsync("/fire.jpg?w=1");

                licensedResponse1.EnsureSuccessStatusCode();

                url.Url = new Uri("https://acmestaging.com");
                using var licensedResponse2 = await client.GetAsync("/fire.jpg?w=1");

                licensedResponse2.EnsureSuccessStatusCode();

                url.Url = new Uri("https://subdomain.acme.com");
                using var licensedResponse3 = await client.GetAsync("/fire.jpg?w=1");

                licensedResponse3.EnsureSuccessStatusCode();

                Assert.Empty(mgr.GetIssues());

                var page = licensing.Result.ProvidePublicLicensesPage();
                Assert.Contains("License Validation ON", page);
                Assert.Contains("License key valid for all domains.", page);
                Assert.Contains("No resale of usage. Only for organizations with less than 500 employees.", page);
                Assert.Contains("You are using EnforceLicenseWith.Http402Error", page);
                Assert.Contains("Manage your subscription at https://account.imazen.io", page);


                await host.StopAsync(CancellationToken.None);
            }
        }
        public static Mock <HttpMessageHandler> MockRemoteLicenseException(LicenseManagerSingleton mgr, WebExceptionStatus status)
        {
            var ex      = new HttpRequestException("Mock failure", new WebException("Mock failure", status));
            var handler = new Mock <HttpMessageHandler>();
            var method  = handler.Protected()
                          .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(),
                                                               ItExpr.IsAny <CancellationToken>())
                          .ThrowsAsync(ex);

            method.Verifiable("SendAsync must be called");

            mgr.SetHttpMessageHandler(handler.Object, true);
            return(handler);
        }
        public async void TestNoLicense()
        {
            using (var contentRoot = new TempContentRoot()
                                     .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg"))
            {
                var clock     = new RealClock();
                var mgr       = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
                var licensing = new Licensing(mgr);


                using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions ()
                {
                    Licensing = licensing,
                    MyOpenSourceProjectUrl = null,
                    EnforcementMethod      = EnforceLicenseWith.Http402Error
                }
                                                             .SetDiagnosticsPageAccess (AccessDiagnosticsFrom.None)
                                                             .SetDiagnosticsPagePassword ("pass")
                                                             .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")));

                // Create an HttpClient to send requests to the TestServer
                using var client = host.GetTestClient();

                using var notLicensedResponse = await client.GetAsync("/fire.jpg?w=1");

                Assert.Equal(HttpStatusCode.PaymentRequired, notLicensedResponse.StatusCode);

                using var licensePageResponse = await client.GetAsync("/imageflow.license");

                licensePageResponse.EnsureSuccessStatusCode();

                using var notAuthorizedResponse = await client.GetAsync("/imageflow.debug");

                Assert.Equal(HttpStatusCode.Unauthorized, notAuthorizedResponse.StatusCode);

                using var debugPageResponse = await client.GetAsync("/imageflow.debug?password=pass");

                debugPageResponse.EnsureSuccessStatusCode();


                var page = licensing.Result.ProvidePublicLicensesPage();
                Assert.Contains("License Validation ON", page);
                Assert.Contains("No license keys found.", page);
                Assert.Contains("You must purchase a license key or comply with the AGPLv3.", page);
                Assert.Contains("To get a license key, visit", page);
                Assert.Contains("You are using EnforceLicenseWith.Http402Error", page);

                await host.StopAsync(CancellationToken.None);
            }
        }
Beispiel #11
0
        public void Test_Remote_License_Success()
        {
            if (Environment.GetEnvironmentVariable("APPVEYOR") == "True")
            {
                return;
            }
            var clock = new OffsetClock("2017-04-25", "2017-04-25");
            var mgr   = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock)
            {
                Cache = new StringCacheMem()
            };
            Uri invokedUri  = null;
            var httpHandler = MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, LicenseStrings.EliteSubscriptionRemote,
                                                                (r, c) => { invokedUri = r.RequestUri; });
            var conf = new Config();

            try {
                conf.Plugins.LicenseScope = LicenseAccess.Local;
                conf.Plugins.Install(new LicensedPlugin(mgr, clock, "R_Elite"));
                conf.Plugins.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder);

                Assert.Equal(1, mgr.GetAllLicenses().Count());
                Assert.True(mgr.GetAllLicenses().First().IsRemote);
                mgr.Heartbeat();

                mgr.WaitForTasks();
                Assert.Empty(mgr.GetIssues());

                Mock.Verify(httpHandler);
                Assert.StartsWith(
                    "https://s3-us-west-2.amazonaws.com/licenses.imazen.net/v1/licenses/latest/",
                    invokedUri.ToString());


                Assert.NotNull(mgr.GetAllLicenses().First().FetchedLicense());

                var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);

                Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain")));
                Assert.Equal(0, mgr.WaitForTasks());
                Assert.Empty(mgr.GetIssues());
                Assert.NotNull(conf.GetDiagnosticsPage());
                Assert.NotNull(conf.GetLicensesPage());
            } catch {
                output.WriteLine(conf.GetDiagnosticsPage());
                throw;
            }
        }
Beispiel #12
0
        public void Test_DomainPerCore()
        {
            // set clock to present
            var clock = new FakeClock("2017-04-25", "2017-04-25");

            foreach (var set in LicenseStrings.GetSets("PerCore2Domains"))
            {
                var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
                MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, set.Remote, null);

                var request = new RequestUrlProvider();

                var conf = new Config();
                conf.Plugins.LicenseScope = LicenseAccess.Local;
                conf.Plugins.AddLicense(set.Placeholder);
                conf.Plugins.LicenseError = LicenseErrorAction.Exception;
                conf.Plugins.Install(new Gradient());
                conf.Plugins.Install(new EmptyLicenseEnforcedPlugin(new LicenseEnforcer <EmptyLicenseEnforcedPlugin>(mgr, mgr, request.Get).EnableEnforcement(), "R_Performance"));

                Assert.Equal(1, mgr.WaitForTasks());
                // We don't raise exceptions without a request url, unless there are absolutely no valid licenses
                request.Url = null;
                Assert.False(IsWatermarking(conf, mgr));

                // We never watermark outside of http requests
                conf.Plugins.LicenseError = LicenseErrorAction.Watermark;
                Assert.False(IsWatermarking(conf, mgr));

                conf.Plugins.LicenseError = LicenseErrorAction.Exception;

                //We should not raise an exception on our domains
                request.Url = new Uri("http://acme.com");
                Assert.False(IsWatermarking(conf, mgr));
                request.Url = new Uri("http://acmestaging.com");
                Assert.False(IsWatermarking(conf, mgr));

                // We should raise an exception on other domains
                request.Url = new Uri("http://other.co");
                Assert.Throws <LicenseException>(() => IsWatermarking(conf, mgr));


                Assert.Empty(mgr.GetIssues());
            }
        }
        string GetInfo(ILicenseConfig c, LicenseManagerSingleton mgr)
        {
            var result = new Computation(c, mgr.TrustedKeys, mgr, mgr,
                                         mgr.Clock, true);
            var sb = new StringBuilder();

            sb.AppendLine($"Plugins.LicenseError = {c.LicenseEnforcement}");
            sb.AppendLine($"Plugins.LicenseScope = {c.LicenseScope}");
            sb.AppendLine($"Computation.");
            sb.AppendLine($"LicensedForAll() => {result.LicensedForAll()}");
            sb.AppendLine($"LicensedForSomething() => {result.LicensedForSomething()}");
            sb.AppendLine($"LicensedForRequestUrl(null) => {result.LicensedForRequestUrl(null)}");
            sb.AppendLine($"LicensedForRequestUrl(new Uri(\"http://other.com\")) => {result.LicensedForRequestUrl(new Uri("http://other.com"))}");
            sb.AppendLine($"LicensedForRequestUrl(new Uri(\"http://acme.com\")) => {result.LicensedForRequestUrl(new Uri("http://acme.com"))}");
            sb.AppendLine($"GetBuildDate() => {result.GetBuildDate()}");
            sb.AppendLine($"ProvideDiagnostics() => {result.ProvideDiagnostics()}");

            return(sb.ToString());
        }
        public void Test_Remote_License_Success()
        {
            if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CI")))
            {
                return;
            }
            var clock       = new OffsetClock("2017-04-25", "2017-04-25");
            var mgr         = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
            Uri invokedUri  = null;
            var httpHandler = MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, LicenseStrings.EliteSubscriptionRemote,
                                                                (r, c) => { invokedUri = r.RequestUri; });
            var conf = new MockConfig(mgr, clock, new [] { "R_Elite" }, new List <KeyValuePair <string, string> >());

            try {
                conf.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder);

                Assert.Single(mgr.GetAllLicenses());
                Assert.True(mgr.GetAllLicenses().First().IsRemote);
                conf.FireHeartbeat();

                mgr.WaitForTasks();
                Assert.Empty(mgr.GetIssues());

                Mock.Verify(httpHandler);
                Assert.StartsWith(
                    "https://s3-us-west-2.amazonaws.com/licenses.imazen.net/v1/licenses/latest/",
                    invokedUri.ToString());


                Assert.NotNull(mgr.GetAllLicenses().First().FetchedLicense());

                var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);

                Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain")));
                //TODO: Explore why WaitForTasks() can sometimes return 1
                mgr.WaitForTasks();
                Assert.Empty(mgr.GetIssues());
                Assert.NotNull(conf.GetLicensesPage());
            } catch {
                output.WriteLine(conf.GetLicensesPage());
                throw;
            }
        }
Beispiel #15
0
        bool IsWatermarking(Config c, LicenseManagerSingleton mgr)
        {
            var newInfo = GetInfo(c, mgr);

            if (lastInfo != newInfo)
            {
                lastInfo = newInfo;
                output.WriteLine(newInfo);
            }
            var j = new ImageJob("~/gradient.png", typeof(Bitmap), new Instructions("format=png&width=10"));

            c.Build(j);
            using (var b = j.Result as Bitmap) {
                var cornerPixel = b.GetPixel(b.Width - 1, b.Height - 1);
                var watermarked = cornerPixel.ToArgb() == Color.Red.ToArgb();
                output.WriteLine($"Watermarked={watermarked}, color={cornerPixel}");
                return(watermarked);
            }
        }
        public MockConfig(LicenseManagerSingleton mgr, ILicenseClock clock, string[] codes, IEnumerable <KeyValuePair <string, string> > domainMappings)
        {
            this.codes = codes;
            this.mgr   = mgr;
            Clock      = clock ?? Clock;

            mgr.MonitorLicenses(this);
            mgr.MonitorHeartbeat(this);

            // Ensure our cache is appropriately invalidated
            cache = null;
            mgr.AddLicenseChangeHandler(this, (me, manager) => me.cache = null);

            // And repopulated, so that errors show up.
            if (Result == null)
            {
                throw new ApplicationException("Failed to populate license result");
            }
            this.domainMappings = domainMappings;
        }
        public static Mock <HttpMessageHandler> MockRemoteLicense(LicenseManagerSingleton mgr, HttpStatusCode code, string value,
                                                                  Action <HttpRequestMessage, CancellationToken> callback)
        {
            var handler = new Mock <HttpMessageHandler>();
            var method  = handler.Protected()
                          .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(),
                                                               ItExpr.IsAny <CancellationToken>())
                          .Returns(Task.Run(() => new HttpResponseMessage(code)
            {
                Content = new StringContent(value, System.Text.Encoding.UTF8)
            }));

            if (callback != null)
            {
                method.Callback(callback);
            }

            method.Verifiable("SendAsync must be called");

            mgr.SetHttpMessageHandler(handler.Object, true);
            return(handler);
        }
Beispiel #18
0
        public void Test_NoLicense()
        {
            var clock   = new RealClock();
            var mgr     = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
            var request = new RequestUrlProvider();

            var conf = new Config();

            conf.Plugins.LicenseScope = LicenseAccess.Local;
            conf.Plugins.Install(new Gradient());
            conf.Plugins.Install(new EmptyLicenseEnforcedPlugin(new LicenseEnforcer <EmptyLicenseEnforcedPlugin>(mgr, mgr, request.Get).EnableEnforcement(), "R4Creative"));

            // We don't watermark outside of http requests (even if there are no valid licenses)
            request.Url = null;
            Assert.False(IsWatermarking(conf, mgr));

            // But we certainly should be, here
            request.Url = new Uri("http://other.co");
            Assert.True(IsWatermarking(conf, mgr));

            Assert.Empty(mgr.GetIssues());
        }
Beispiel #19
0
        public void Test_Revocations()
        {
            // set clock to present, and build date to far future
            var clock = new FakeClock("2017-04-25", "2022-01-01");

            foreach (var set in LicenseStrings.GetSets("Cancelled", "SoftRevocation", "HardRevocation"))
            {
                output.WriteLine($"Testing revocation for {set.Name}");
                var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
                MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, set.Remote, null);

                var request = new RequestUrlProvider();

                var conf = new Config();
                conf.Plugins.LicenseScope = LicenseAccess.Local;
                conf.Plugins.AddLicense(set.Placeholder);
                conf.Plugins.LicenseError = LicenseErrorAction.Watermark;
                conf.Plugins.Install(new Gradient());
                conf.Plugins.Install(new EmptyLicenseEnforcedPlugin(new LicenseEnforcer <EmptyLicenseEnforcedPlugin>(mgr, mgr, request.Get).EnableEnforcement(), "R4Creative"));
                Assert.Equal(1, mgr.WaitForTasks());

                request.Url = null;
                Assert.False(IsWatermarking(conf, mgr));


                // We don't raise exceptions outside of http requests, unless there are absolutely no valid licenses
                conf.Plugins.LicenseError = LicenseErrorAction.Exception;
                // There are no valid licences
                request.Url = null;
                Assert.Throws <LicenseException>(() => IsWatermarking(conf, mgr));

                // But we certainly should be, here
                request.Url = new Uri("http://other.co");
                Assert.Throws <LicenseException>(() => IsWatermarking(conf, mgr));

                Assert.NotEmpty(mgr.GetIssues());
            }
        }
Beispiel #20
0
 internal Licensing(LicenseManagerSingleton mgr, Func <Uri> getCurrentRequestUrl = null)
 {
     this.mgr = mgr;
     this.getCurrentRequestUrl = getCurrentRequestUrl;
 }
        public async void TestRevocations()
        {
            using (var contentRoot = new TempContentRoot()
                                     .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg"))
            {
                // set clock to present, and build date to far future
                var clock = new FakeClock("2017-04-25", "2022-01-01");

                foreach (var set in LicenseStrings.GetSets("CancelledImageflow", "SoftRevocationImageflow",
                                                           "HardRevocationImageflow"))
                {
                    output.WriteLine($"Testing revocation for {set.Name}");
                    var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
                    MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, set.Remote, null);

                    var url       = new RequestUrlProvider();
                    var licensing = new Licensing(mgr, url.Get);

                    using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions ()
                    {
                        Licensing = licensing,
                        MyOpenSourceProjectUrl = null
                    }
                                                                 .SetLicenseKey (EnforceLicenseWith.Http402Error,
                                                                                 set.Placeholder)
                                                                 .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")));

                    // Create an HttpClient to send requests to the TestServer
                    using var client = host.GetTestClient();

                    mgr.WaitForTasks();


                    url.Url = new Uri("https://domain.com");
                    using var notLicensedResponse = await client.GetAsync("/fire.jpg?w=1");

                    Assert.Equal(HttpStatusCode.PaymentRequired, notLicensedResponse.StatusCode);

                    url.Url = null;
                    using var notLicensedResponse2 = await client.GetAsync("/fire.jpg?w=1");

                    Assert.Equal(HttpStatusCode.PaymentRequired, notLicensedResponse2.StatusCode);


                    Assert.NotEmpty(mgr.GetIssues());

                    var page = licensing.Result.ProvidePublicLicensesPage();
                    Assert.Contains("License Validation ON", page);
                    Assert.Contains("You are using EnforceLicenseWith.Http402Error", page);
                    Assert.Contains("No valid license keys found.", page);

                    Assert.Contains(
                        "Your license is invalid. Please renew your license via the management portal or purchase a new one at",
                        page);
                    Assert.DoesNotContain("Your license needs to be upgraded.", page);

                    if (set.Name == "CancelledImageflow")
                    {
                        Assert.Contains("Your subscription has lapsed; please renew to continue using product.", page);
                    }

                    if (set.Name == "SoftRevocationImageflow")
                    {
                        Assert.Contains(
                            "This license has been compromised; please contact Vendor Gamma for an updated license",
                            page);
                    }
                    if (set.Name == "HardRevocationImageflow")
                    {
                        Assert.Contains(
                            "Please contact support; the license was shared with an unauthorized party and has been revoked.",
                            page);
                    }



                    await host.StopAsync(CancellationToken.None);
                }
            }
        }
        public async void TestDomainsLicense()
        {
            using (var contentRoot = new TempContentRoot()
                                     .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg"))
            {
                var clock = new FakeClock("2017-04-25", "2017-04-25");
                var set   = LicenseStrings.GetSets("PerCore2DomainsImageflow").First();
                var mgr   = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem());
                MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, set.Remote, null);
                var url       = new RequestUrlProvider();
                var licensing = new Licensing(mgr, url.Get);

                using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions ()
                {
                    Licensing = licensing,
                    MyOpenSourceProjectUrl = null
                }
                                                             .SetLicenseKey (EnforceLicenseWith.Http402Error,
                                                                             set.Placeholder)
                                                             .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")));

                // Create an HttpClient to send requests to the TestServer
                using var client = host.GetTestClient();

                mgr.WaitForTasks();

                Assert.Empty(mgr.GetIssues());

                url.Url = new Uri("https://unlicenseddomain.com");
                using var notLicensedResponse = await client.GetAsync("/fire.jpg?w=1");

                Assert.Equal(HttpStatusCode.PaymentRequired, notLicensedResponse.StatusCode);



                url.Url = new Uri("https://acme.com");
                using var licensedResponse1 = await client.GetAsync("/fire.jpg?w=1");

                licensedResponse1.EnsureSuccessStatusCode();

                url.Url = new Uri("https://acmestaging.com");
                using var licensedResponse2 = await client.GetAsync("/fire.jpg?w=1");

                licensedResponse2.EnsureSuccessStatusCode();

                url.Url = new Uri("https://subdomain.acme.com");
                using var licensedResponse3 = await client.GetAsync("/fire.jpg?w=1");

                licensedResponse3.EnsureSuccessStatusCode();

                Assert.Empty(mgr.GetIssues());

                var page = licensing.Result.ProvidePublicLicensesPage();
                Assert.Contains("License Validation ON", page);
                Assert.DoesNotContain("No license keys found.", page);
                Assert.Contains("License valid for 2 domains, missing for 1 domains", page);
                Assert.Contains("Your license needs to be upgraded", page);
                Assert.Contains("You are using EnforceLicenseWith.Http402Error", page);


                await host.StopAsync(CancellationToken.None);
            }
        }
Beispiel #23
0
        public ImageflowMiddleware(
            RequestDelegate next,
            IWebHostEnvironment env,
            IEnumerable <ILogger <ImageflowMiddleware> > logger,
            IEnumerable <IClassicDiskCache> diskCaches,
            IEnumerable <IStreamCache> streamCaches,
            IEnumerable <IBlobProvider> blobProviders,
            ImageflowMiddlewareOptions options)
        {
            this.next = next;
            options.Licensing ??= new Licensing(LicenseManagerSingleton.GetOrCreateSingleton(
                                                    "imageflow_", new[] { env.ContentRootPath, Path.GetTempPath() }));
            this.options = options;
            this.env     = env;
            this.logger  = logger.FirstOrDefault();
            diskCache    = diskCaches.FirstOrDefault();

            var streamCacheArray = streamCaches.ToArray();

            if (streamCacheArray.Count() > 1)
            {
                throw new InvalidOperationException("Only 1 IStreamCache instance can be registered at a time");
            }

            streamCache = streamCacheArray.FirstOrDefault();


            var providers   = blobProviders.ToList();
            var mappedPaths = options.MappedPaths.ToList();

            if (options.MapWebRoot)
            {
                if (this.env?.WebRootPath == null)
                {
                    throw new InvalidOperationException("Cannot call MapWebRoot if env.WebRootPath is null");
                }
                mappedPaths.Add(new PathMapping("/", this.env.WebRootPath));
            }

            //Determine the active cache backend
            var streamCacheEnabled = streamCache != null && options.AllowCaching;
            var diskCacheEnabled   = this.diskCache != null && options.AllowDiskCaching;

            if (streamCacheEnabled)
            {
                options.ActiveCacheBackend = CacheBackend.StreamCache;
            }
            else if (diskCacheEnabled)
            {
                options.ActiveCacheBackend = CacheBackend.ClassicDiskCache;
            }
            else
            {
                options.ActiveCacheBackend = CacheBackend.NoCache;
            }


            options.Licensing.Initialize(this.options);

            blobProvider       = new BlobProvider(providers, mappedPaths);
            diagnosticsPage    = new DiagnosticsPage(options, env, this.logger, streamCache, this.diskCache, providers);
            licensePage        = new LicensePage(options);
            globalInfoProvider = new GlobalInfoProvider(options, env, this.logger, streamCache, this.diskCache, providers);

            options.Licensing.FireHeartbeat();
            GlobalPerf.Singleton.SetInfoProviders(new List <IInfoProvider>()
            {
                globalInfoProvider
            });
        }
Beispiel #24
0
        public void Test_Caching_With_Write_Delay()
        {
            if (Environment.GetEnvironmentVariable("APPVEYOR") == "True")
            {
                return;
            }

            var clock = new OffsetClock("2017-04-25", "2017-04-25");
            var cache = new StringCacheMem();

            // Populate cache
            {
                var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock)
                {
                    Cache = cache
                };
                MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, LicenseStrings.EliteSubscriptionRemote,
                                                  null);

                var conf = new Config();
                conf.Plugins.LicenseScope = LicenseAccess.Local;
                conf.Plugins.Install(new LicensedPlugin(mgr, clock, "R_Elite", "R4Elite"));
                conf.Plugins.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder);

                Assert.Equal(1, mgr.WaitForTasks());

                var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);
                Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain")));

                Assert.Empty(mgr.GetIssues());
                Assert.NotNull(conf.GetLicensesPage());
            }

            // Use cache
            {
                var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock)
                {
                    Cache = cache
                };

                var conf = new Config();

                conf.Plugins.LicenseScope = LicenseAccess.Local;
                conf.Plugins.Install(new LicensedPlugin(mgr, clock, "R_Elite", "R4Elite"));
                conf.Plugins.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder);

                mgr.Heartbeat();
                Assert.Equal(0, mgr.WaitForTasks());

                var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);
                Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain")));


                Assert.NotNull(conf.GetDiagnosticsPage());
                Assert.NotNull(conf.GetLicensesPage());

                Assert.Equal(0, mgr.GetIssues().Count());

                MockHttpHelpers.MockRemoteLicenseException(mgr, WebExceptionStatus.NameResolutionFailure);

                while (!mgr.AllowFetching())
                {
                    mgr.Heartbeat();
                }

                mgr.WaitForTasks();

                result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true);
                Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain")));
                Assert.Equal(1, mgr.GetIssues().Count());
            }
        }