public void Can_validate_floating_license()
        {
            string fileName = WriteFloatingLicenseFile();

            GenerateLicenseFileInLicensesDirectory();

            LicensingService.SoftwarePublicKey = public_only;
            LicensingService.LicenseServerPrivateKey = floating_private;

            var host = new ServiceHost(typeof(LicensingService));
            const string address = "http://localhost:19292/license";
            host.AddServiceEndpoint(typeof(ILicensingService), new WSHttpBinding(), address);

            host.Open();
            try
            {

                var validator = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                validator.AssertValidLicense();
            }
            finally
            {
                host.Abort();
            }
        }
        public void Gen_and_validate_with_attributes()
        {
            var guid = Guid.NewGuid();
            var generator = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(30);
            var key = generator.Generate("Oren Eini", guid, expiration,
                                         new Dictionary<string, string>
                                         {
                                            {"prof", "llb"},
                                            {"reporting", "on"}
                                         }, LicenseType.Trial);

            var path = Path.GetTempFileName();
            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);
            validator.AssertValidLicense();

            Assert.Equal("llb", validator.LicenseAttributes["prof"]);
            Assert.Equal("on", validator.LicenseAttributes["reporting"]);
            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("Oren Eini", validator.Name);
            Assert.Equal(LicenseType.Trial, validator.LicenseType);
        }
        public void Can_only_get_license_per_allocated_licenses()
        {
            string fileName = WriteFloatingLicenseFile();

            GenerateLicenseFileInLicensesDirectory();

            LicensingService.SoftwarePublicKey = public_only;
            LicensingService.LicenseServerPrivateKey = floating_private;

            var host = new ServiceHost(typeof(LicensingService));
            var address = "http://localhost:29292/license";
            host.AddServiceEndpoint(typeof(ILicensingService), new WSHttpBinding(), address);

            host.Open();

            try
            {
                var validator = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                validator.AssertValidLicense();

                var validator2 = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                Assert.Throws<FloatingLicenseNotAvialableException>(() => validator2.AssertValidLicense());
            }
            finally
            {
                host.Abort();
            }
        }
        public void Cannot_validate_hacked_license()
        {
            const string hackedLicense =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
            <license id=""2bc65446-0c78-453f-9da3-badb9f191163"" expiration=""2009-04-04T12:16:45.4328736"" type=""Trial"">
              <name>Oren Eini</name>
              <Signature xmlns=""http://www.w3.org/2000/09/xmldsig#"">
            <SignedInfo>
              <CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" />
              <SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" />
              <Reference URI="""">
            <Transforms>
              <Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" />
            </Transforms>
            <DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" />
            <DigestValue>KxG48zaXJ0gEOpuCc4NPYTh7U7c=</DigestValue>
              </Reference>
            </SignedInfo>
            <SignatureValue>KfNKJRDwPeJ2Olw+sbe1RLLrzQzMAf/Kwcs34LkRMR/bRYTvm+RX1KMr0/+bNxtg0NCqMjMgPqrZfx3V416GMhlwMIFzFSRzF8Z/khKHXM2Hbur3ibeyMoj5GGTx5sUKJy0v5eVaLvE9pDc5pafVaUynk/5NDgCQR6wBbKtzLJamaX+zigS8uXGvDxcMAGSeY97wtATdXBawrWbfQgeJ72h0FHshaepqS5roNXgr/5oV4ma/KWTrwTZVBo76ThkgB4HzsZGqjAo9vZa5eUHQwrJfNEEwoHnu4Ld8PfKErwTbr6Q8GK8CSxldP5HJ0BALuj1bETlDum6/vcZZXGEtsQ==</SignatureValue>
              </Signature>
            </license>";

            var path = Path.GetTempFileName();
            File.WriteAllText(path, hackedLicense);

            var validator = new LicenseValidator(public_only, path);
            Assert.Throws<LicenseNotFoundException>(validator.AssertValidLicense);
        }
		public void Will_detect_duplicate_license()
		{
			var guid = Guid.NewGuid();
			var generator = new LicenseGenerator(public_and_private);
			var expiration = DateTime.Now.AddDays(30);
			var key = generator.Generate("Oren Eini", guid, expiration, LicenseType.Trial);

			var path = Path.GetTempFileName();
			File.WriteAllText(path, key);

			var wait = new ManualResetEvent(false);

			var validator = new LicenseValidator(public_only, path)
			{
				LeaseTimeout = TimeSpan.FromSeconds(1)
			};
			InvalidationType? invalidation = null;
			validator.LicenseInvalidated += type => invalidation = type;
			validator.MultipleLicensesWereDiscovered += (sender, args) => wait.Set();
			validator.AssertValidLicense();

			var validator2 = new LicenseValidator(public_only, path);
			validator2.AssertValidLicense();

      //todo: marked this out  for now
		  //	Assert.True(wait.WaitOne(TimeSpan.FromSeconds(100)));
			//Assert.Equal(invalidation.Value, InvalidationType.TimeExpired);
		}
Ejemplo n.º 6
0
 private static void Reset()
 {
     initialized            = false;
     startupType            = null;
     startupMethods         = null;
     serviceProvider        = null;
     routingServiceProvider = null;
     router             = null;
     AdditionalServices = null;
     AdditionalApplicationConfiguration = null;
     AdditionalRouting           = null;
     TestServiceProvider.Current = null;
     TestServiceProvider.ClearServiceLifetimes();
     LicenseValidator.ClearLicenseDetails();
     PluginsContainer.Reset();
 }
        public void ValidateShouldThrowExceptionWithInvalidNumberOfLicenseParts()
        {
            Test.AssertException <InvalidLicenseException>(
                () =>
            {
                LicenseValidator.ClearLicenseDetails();
                LicenseValidator.Validate(
                    new[] { "1-aIqZBgCHicW6QK8wpk+T6a1WDfgvk1+uUEYkwxnFw+Ucla5Pxmyxyn9JJJcczy3iXet0exCvBMrkFE2PqAkwNd1TnZLt+pxmZaEPlUYwzfVCIpdB2rZAaFmrRToQvqrUv4jHHUyWw9/4C1yntfOUUkcYmFYLuNC4rmqocrv1o7AxOjIwMTYtMDEtMDE6OjpJbnRlcm5hbDpNeVRlc3RlZC5NdmMu" },
                    new DateTime(2016, 10, 10),
                    new DateTime(2016, 10, 10),
                    string.Empty);
            },
                "License details are invalid");

            Assert.False(LicenseValidator.HasValidLicense);
        }
        public void ValidateShouldThrowExceptionWithInvalidLicenseIdMatch()
        {
            Test.AssertException <InvalidLicenseException>(
                () =>
            {
                var license = "1-Lh95BZUyA92DgQ9B8o10CtFX0/Nhykf6upFj8rOIyodNLLc6iMRD3loJVZv00jtkUkdYPHDHAKW4YGqd8ROc3ZXUyrzNmQl67eUQ1BIELx8QfHo2gwPnQgMgdh5tfm+gtNNBvim0dqki2AN6ABwK0Garnd0lU3BAxM2YJ2k/C4oxOjIwMTctMTAtMTU6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLk12YyBUZXN0czpJbnRlcm5hbDpNeVRlc3RlZC5NdmMu";

                var licenseArray = license.ToArray();
                licenseArray[0]  = '2';

                LicenseValidator.ClearLicenseDetails();
                LicenseValidator.Validate(new[] { new string(licenseArray) }, new DateTime(2016, 10, 10), string.Empty);
            },
                "License ID does not match signature license ID");

            Assert.False(LicenseValidator.HasValidLicense);
        }
        private void Verify()
        {
            var lv = new LicenseValidator();

            if (!lv.HasLicense)
            {
                LicenseLabel.Content = "Лицензия не найдена.";
                return;
            }
            if (!lv.IsValid)
            {
                LicenseLabel.Content = "Лицензия просрочена.";
                return;
            }
            new MainWindow().Show();
            Close();
        }
        public void Gen_and_validate()
        {
            var guid = Guid.NewGuid();
            var generator = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(30);
            var key = generator.Generate("Oren Eini", guid, expiration, LicenseType.Trial);

            var path = Path.GetTempFileName();
            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);
            validator.AssertValidLicense();

            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("Oren Eini", validator.Name);
            Assert.Equal(LicenseType.Trial, validator.LicenseType);
        }
        public void Throws_date_exception_when_license_is_expired()
        {
            var guid = Guid.NewGuid();
            var generator = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(-1);
            var key = generator.Generate("Oren Eini", guid, expiration,
                                         new Dictionary<string, string>
                                         {
                                            {"prof", "llb"},
                                            {"reporting", "on"}
                                         }, LicenseType.Trial);

            var path = Path.GetTempFileName();
            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);
            Assert.Throws<LicenseExpiredException>(() => validator.AssertValidLicense());
        }
Ejemplo n.º 12
0
        public void Bug_for_year_over_8000_was_marked_as_expired()
        {
            var guid = Guid.NewGuid();
            var generator = new LicenseGenerator(public_and_private);
            var expiration = new DateTime(9999, 10, 10, 10, 10, 10);
            var key = generator.Generate("User name", guid, expiration, LicenseType.Standard);

            var path = Path.GetTempFileName();
            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);
            validator.AssertValidLicense();

            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("User name", validator.Name);
            Assert.Equal(LicenseType.Standard, validator.LicenseType);
        }
        public void TestLicenseValidator()
        {
            const string licenseNumber = "AP-FAAA-N1J7-RMCF-B4JX-1QS7-RK";
            var          validator     = new LicenseValidator();

            try
            {
                var response = validator.GetValidatorResponse(licenseNumber);
                var isValid  = validator.Valid(licenseNumber);
                var date     = new DateTime(2020, 10, 8);

                Assert.IsTrue(response?.ExpirationDate.Date == date);
                Assert.IsTrue(isValid);
            }
            catch (Exception)
            {
                Assert.Fail();
            }
        }
Ejemplo n.º 14
0
        public void Bug_for_year_over_8000_was_marked_as_expired()
        {
            var guid       = Guid.NewGuid();
            var generator  = new LicenseGenerator(public_and_private);
            var expiration = new DateTime(9999, 10, 10, 10, 10, 10);
            var key        = generator.Generate("User name", guid, expiration, LicenseType.Standard);

            var path = Path.GetTempFileName();

            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);

            validator.AssertValidLicense();

            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("User name", validator.Name);
            Assert.Equal(LicenseType.Standard, validator.LicenseType);
        }
        public void Throws_date_exception_when_license_is_expired()
        {
            var guid       = Guid.NewGuid();
            var generator  = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(-1);
            var key        = generator.Generate("Oren Eini", guid, expiration,
                                                new Dictionary <string, string>
            {
                { "prof", "llb" },
                { "reporting", "on" }
            }, LicenseType.Trial);

            var path = Path.GetTempFileName();

            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);

            Assert.Throws <LicenseExpiredException>(() => validator.AssertValidLicense());
        }
        public void Gen_and_validate()
        {
            var guid       = Guid.NewGuid();
            var generator  = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(30);
            var key        = generator.Generate("Oren Eini", guid, expiration, LicenseType.Trial);

            var path = Path.GetTempFileName();

            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);

            validator.AssertValidLicense();

            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("Oren Eini", validator.Name);
            Assert.Equal(LicenseType.Trial, validator.LicenseType);
        }
Ejemplo n.º 17
0
        private static void ValidateLicense()
        {
            if (!File.Exists("publicKey.xml"))
            {
                MessageBox.Show("Please create a license key first");
                return;
            }

            var publicKey = File.ReadAllText(@"publicKey.xml");

            var validator = new LicenseValidator(publicKey, @"license.lic");

            try
            {
                validator.AssertValidLicense();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 18
0
        public void CanValidateLicense()
        {
            var domain = "lol1.lo2.foobar.com";

            var scenario = new LicenseValidationScenario();

            var identity       = new Mock <IIdentity>(MockBehavior.Loose);
            var loggingService = new Mock <ILoggingService>(MockBehavior.Loose);
            var applicationIssuesUnitOfWork = new Mock <IApplicationIssueUnitOfWork>(MockBehavior.Loose);

            using (var dataContextFactory = new CheckedDataContextFactory(identity.Object))
            {
                var validator = new LicenseValidator(dataContextFactory, loggingService.Object,
                                                     applicationIssuesUnitOfWork.Object);

                var result = validator.Validate(scenario.AppKey, new[] { new DomainValidation(domain, scenario.FeatureCode) }).Single();

                Assert.Equal(result.DomainLicense.Domain, domain);
                Assert.Contains(scenario.FeatureCode, result.DomainLicense.Features);
            }
        }
Ejemplo n.º 19
0
        public void WithLicenseNoExceptionShouldBeThrown()
        {
            MyApplication
            .StartsFrom <DefaultStartup>()
            .WithTestConfiguration(config =>
            {
                config.AddInMemoryCollection(new[]
                {
                    new KeyValuePair <string, string>("License", "1-3i7E5P3qX5IUWHIAfcXG6DSbOwUBidygp8bnYY/2Rd9zA15SwRWP6QDDp+m/dDTZNBFX2eIHcU/gdcdm83SL695kf3VyvMPw+iyPN6QBh/WnfQwGLqBecrQw+WNPJMz6UgXi2q4e4s/D8/iSjMlwCnzJvC2Yv3zSuADdWObQsygxOjk5OTktMTItMzE6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLk12YyBUZXN0czpGdWxsOk15VGVzdGVkLkFzcE5ldENvcmUuTXZjLg=="),
                });
            })
            .WithTestAssembly(this);

            LicenseValidator.ClearLicenseDetails();
            TestCounter.SetLicenseData(null, DateTime.MinValue, "MyTested.AspNetCore.Mvc.Tests");

            Task.Run(async() =>
            {
                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        MyController <MvcController>
                        .Instance()
                        .Calling(c => c.OkResultAction())
                        .ShouldReturn()
                        .Ok();
                    }));
                }

                await Task.WhenAll(tasks);
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            MyApplication.StartsFrom <DefaultStartup>();
        }
        public void Can_validate_floating_license()
        {
            string fileName = WriteFloatingLicenseFile();

            GenerateLicenseFileInLicensesDirectory();

            LicensingService.SoftwarePublicKey       = public_only;
            LicensingService.LicenseServerPrivateKey = floating_private;

            var          host    = new ServiceHost(typeof(LicensingService));
            const string address = "http://localhost:9292/license";

            host.AddServiceEndpoint(typeof(ILicensingService), new WSHttpBinding(), address);

            host.Open();

            var validator = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());

            validator.AssertValidLicense();

            host.Abort();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 验证并且返回验证信息
        /// </summary>
        /// <returns>不成功返回空</returns>
        internal static LicenseValidator ValidationGetInfo()
        {
            if (!File.Exists(_path_license) || !File.Exists(_path_pub))
            {
                return(null); // 如果文件不全,则不验证
            }

            string publicKey = File.ReadAllText(_path_pub);

            try
            {
                var licenseValidator = new LicenseValidator(publicKey, _path_license);
                licenseValidator.AssertValidLicense();

                return(licenseValidator);
            }
            catch
            {
            }

            return(null);
        }
 private static void Reset()
 {
     initialiazed           = false;
     configurationBuilder   = null;
     configuration          = null;
     environment            = null;
     startupType            = null;
     serviceProvider        = null;
     routingServiceProvider = null;
     router             = null;
     AdditionalServices = null;
     AdditionalApplicationConfiguration = null;
     AdditionalRouting           = null;
     TestAssembly                = null;
     TestServiceProvider.Current = null;
     TestServiceProvider.ClearServiceLifetimes();
     DefaultRegistrationPlugins.Clear();
     ServiceRegistrationPlugins.Clear();
     RoutingServiceRegistrationPlugins.Clear();
     InitializationPlugins.Clear();
     LicenseValidator.ClearLicenseDetails();
 }
Ejemplo n.º 23
0
        public static bool IsValid(out DateTime expiration, string licFile, string publicKey)
        {
            expiration = DateTime.MinValue;

            var licVal = new LicenseValidator(publicKey, licFile);

            try
            {
                licVal.AssertValidLicense();
            }
            catch (Exception)
            {
                return(false);
            }

            expiration = licVal.ExpirationDate;

            var cpuInfo = string.Empty;
            var mc      = new ManagementClass("win32_processor");
            var moc     = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                cpuInfo = mo.Properties["processorID"].Value.ToString();
                break;
            }
            if (licVal.ExpirationDate <= DateTime.Now)
            {
                return(false);
            }

            if (licVal.Name != cpuInfo)
            {
                return(false);
            }


            return(true);
        }
    internal static void Validate(this IApplicationBuilder app)
    {
        var loggerFactory = app.ApplicationServices.GetService(typeof(ILoggerFactory)) as ILoggerFactory;

        if (loggerFactory == null)
        {
            throw new ArgumentNullException(nameof(loggerFactory));
        }

        var logger = loggerFactory.CreateLogger("Duende.IdentityServer.Startup");

        logger.LogInformation("Starting Duende IdentityServer version {version} ({netversion})", typeof(Duende.IdentityServer.Hosting.IdentityServerMiddleware).Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion, RuntimeInformation.FrameworkDescription);

        var scopeFactory = app.ApplicationServices.GetService <IServiceScopeFactory>();

        using (var scope = scopeFactory.CreateScope())
        {
            var serviceProvider = scope.ServiceProvider;

            var options = serviceProvider.GetRequiredService <IdentityServerOptions>();
            var env     = serviceProvider.GetRequiredService <IHostEnvironment>();
            LicenseValidator.Initalize(loggerFactory, options, env.IsDevelopment());
            LicenseValidator.ValidateLicense();

            TestService(serviceProvider, typeof(IPersistedGrantStore), logger, "No storage mechanism for grants specified. Use the 'AddInMemoryPersistedGrants' extension method to register a development version.");
            TestService(serviceProvider, typeof(IClientStore), logger, "No storage mechanism for clients specified. Use the 'AddInMemoryClients' extension method to register a development version.");
            TestService(serviceProvider, typeof(IResourceStore), logger, "No storage mechanism for resources specified. Use the 'AddInMemoryIdentityResources' or 'AddInMemoryApiResources' extension method to register a development version.");

            var persistedGrants = serviceProvider.GetService(typeof(IPersistedGrantStore));
            if (persistedGrants.GetType().FullName == typeof(InMemoryPersistedGrantStore).FullName)
            {
                logger.LogInformation("You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation.");
            }

            ValidateOptions(options, logger);

            ValidateAsync(serviceProvider, logger).GetAwaiter().GetResult();
        }
    }
        public void ValidateShouldThrowExceptionWithIncorrectNumberOfParts()
        {
            Test.AssertException <InvalidLicenseException>(
                () =>
            {
                LicenseValidator.ClearLicenseDetails();
                LicenseValidator.Validate(new[] { "1-2-3" }, new DateTime(2016, 10, 10), string.Empty);
            },
                "License text is invalid");

            Assert.False(LicenseValidator.HasValidLicense);

            Test.AssertException <InvalidLicenseException>(
                () =>
            {
                LicenseValidator.ClearLicenseDetails();
                LicenseValidator.Validate(new[] { "1" }, new DateTime(2016, 10, 10), string.Empty);
            },
                "License text is invalid");

            Assert.False(LicenseValidator.HasValidLicense);
        }
        public void IncrementAndValidateShouldThrowExceptionWithInvalidPerpetualLicense()
        {
            Exception caughtException = null;

            Task.Run(async() =>
            {
                var license = "1-IRaNRwlovf7moJnDcQCJW8JDq++p8/1hTNsRnBRLDGkd6HidiJ3OEzpFdwmlDacikCv5oRBisRkJ8edjqx1R21VA+SxCgpGHJE2ftOBpV1OBysguNUSIKJyte2heP3xD4tY1BQNh0vcVhXJDcE3qImhodZmi1aXJ19SK5f4JRA8xOjIwMTctMTAtMTU6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLkFzcE5ldENvcmUuTXZjIFRlc3RzOkRldmVsb3BlcjpNeVRlc3RlZC5Bc3BOZXRDb3JlLk12Yy46UGVycGV0dWFs";

                LicenseValidator.ClearLicenseDetails();
                TestCounter.SetLicenseData(new[] { license }, new DateTime(2016, 10, 10), new DateTime(2018, 10, 10), "MyTested.AspNetCore.Mvc.Tests");

                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        TestCounter.IncrementAndValidate();
                    }));
                }

                try
                {
                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            Assert.NotNull(caughtException);
            Assert.IsAssignableFrom <InvalidLicenseException>(caughtException);
            Assert.Equal("You have invalid license: 'License is not valid for this version of My Tested ASP.NET Core MVC. License expired on 2017-10-15. This version of My Tested ASP.NET Core MVC was released on 2018-10-10'. The free-quota limit of 100 assertions per test project has been reached. Please visit https://mytestedasp.net/core/mvc#pricing to request a free license or upgrade to a commercial one.", caughtException.Message);
        }
Ejemplo n.º 27
0
        public void WithNoLicenseExceptionShouldBeThrown()
        {
            MyApplication
            .StartsFrom <DefaultStartup>()
            .WithTestConfiguration(config =>
            {
                config.AddInMemoryCollection(new[]
                {
                    new KeyValuePair <string, string>("License", null),
                });
            })
            .WithTestAssembly(this);

            LicenseValidator.ClearLicenseDetails();
            TestCounter.SetLicenseData(null, DateTime.MinValue, "MyTested.AspNetCore.Mvc.Tests");

            Task.Run(async() =>
            {
                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        MyController <MvcController>
                        .Instance()
                        .Calling(c => c.OkResultAction())
                        .ShouldReturn()
                        .Ok();
                    }));
                }

                await Assert.ThrowsAsync <InvalidLicenseException>(async() => await Task.WhenAll(tasks));
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();
        }
        public void IncrementAndValidateShouldThrowExceptionWithInvalidLegacyLicense()
        {
            Exception caughtException = null;

            Task.Run(async() =>
            {
                var license = "1-0WUoGNBmCpgJ+ktp3BObsUjsaX5XKc4Ed4LoeJBUPgTacqG2wUw9iKAMG4jdDIaiU+AnoTvrXwwLuvfvn57oukhw6HwTqp8hJ2I0vmNZFisQGyD4sjTDlKCBaOXJwXzifCIty2UuGUeo3KNqKoM+5MF1D0i/kEg/LKztnAN312gxOjIwMTctMTAtMTU6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLk12YyBUZXN0czpGdWxsOk15VGVzdGVkLk12Yy4=";

                LicenseValidator.ClearLicenseDetails();
                TestCounter.SetLicenseData(new[] { license }, new DateTime(2018, 10, 10), new DateTime(2018, 10, 10), "MyTested.AspNetCore.Mvc.Tests");

                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        TestCounter.IncrementAndValidate();
                    }));
                }

                try
                {
                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            Assert.NotNull(caughtException);
            Assert.IsAssignableFrom <InvalidLicenseException>(caughtException);
            Assert.Equal("You have invalid license: 'License is not valid for this version of My Tested ASP.NET Core MVC. License expired on 2017-10-15. This version of My Tested ASP.NET Core MVC was released on 2018-10-10'. The free-quota limit of 100 assertions per test project has been reached. Please visit https://mytestedasp.net/core/mvc#pricing to request a free license or upgrade to a commercial one.", caughtException.Message);
        }
        public void IncrementAndValidateShouldThrowExceptionWithInvalidSubscriptionLicense()
        {
            Exception caughtException = null;

            Task.Run(async() =>
            {
                var license = "1-TE6MO5GnjYwR3DcbT8rIXfjk9e0+ZPOb+c27A7pA83aNY4IQNBhgnIf4eUfy0MBvyXYrh9rkLa1hpGnrGu2TMZSoYxeZS07rM7WCqxzd2xXqfzuTAxsO1yNiEo/UwvVZUqz6s3nunKXn1m0b5dbKrsu7hxmWf8P8L2DhCDD09/sxOjIwMTctMTAtMTU6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLkFzcE5ldENvcmUuTXZjIFRlc3RzOkRldmVsb3BlcjpNeVRlc3RlZC5Bc3BOZXRDb3JlLk12Yy46U3Vic2NyaXB0aW9u";

                LicenseValidator.ClearLicenseDetails();
                TestCounter.SetLicenseData(new[] { license }, new DateTime(2018, 10, 10), new DateTime(2016, 10, 10), "MyTested.AspNetCore.Mvc.Tests");

                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        TestCounter.IncrementAndValidate();
                    }));
                }

                try
                {
                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            Assert.NotNull(caughtException);
            Assert.IsAssignableFrom <InvalidLicenseException>(caughtException);
            Assert.Equal("You have invalid license: 'License subscription expired on 2017-10-15'. The free-quota limit of 100 assertions per test project has been reached. Please visit https://mytestedasp.net/core/mvc#pricing to request a free license or upgrade to a commercial one.", caughtException.Message);
        }
    private async Task <TokenRequestValidationResult> RunValidationAsync(Func <NameValueCollection, Task <TokenRequestValidationResult> > validationFunc, NameValueCollection parameters)
    {
        // run standard validation
        var result = await validationFunc(parameters);

        if (result.IsError)
        {
            return(result);
        }

        // run custom validation
        _logger.LogTrace("Calling into custom request validator: {type}", _customRequestValidator.GetType().FullName);

        var customValidationContext = new CustomTokenRequestValidationContext {
            Result = result
        };
        await _customRequestValidator.ValidateAsync(customValidationContext);

        if (customValidationContext.Result.IsError)
        {
            if (customValidationContext.Result.Error.IsPresent())
            {
                LogError("Custom token request validator", new { error = customValidationContext.Result.Error });
            }
            else
            {
                LogError("Custom token request validator error");
            }

            return(customValidationContext.Result);
        }

        LogSuccess();

        LicenseValidator.ValidateClient(customValidationContext.Result.ValidatedRequest.ClientId);

        return(customValidationContext.Result);
    }
Ejemplo n.º 31
0
        public void WithMultipleLicensesNoExceptionShouldBeThrown()
        {
            MyApplication
            .StartsFrom <DefaultStartup>()
            .WithTestConfiguration(config =>
            {
                config.AddJsonFile("multilicenseconfig.json");
            })
            .WithTestAssembly(this);

            LicenseValidator.ClearLicenseDetails();
            TestCounter.SetLicenseData(null, DateTime.MinValue, "MyTested.AspNetCore.Mvc.Tests");

            Task.Run(async() =>
            {
                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        MyController <MvcController>
                        .Instance()
                        .Calling(c => c.OkResultAction())
                        .ShouldReturn()
                        .Ok();
                    }));
                }

                await Task.WhenAll(tasks);
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            MyApplication.StartsFrom <DefaultStartup>();
        }
        public void IncrementAndValidateShouldNotThrowExceptionWithValidSubscriptionLicense()
        {
            Exception caughtException = null;

            Task.Run(async() =>
            {
                var license = "1-TE6MO5GnjYwR3DcbT8rIXfjk9e0+ZPOb+c27A7pA83aNY4IQNBhgnIf4eUfy0MBvyXYrh9rkLa1hpGnrGu2TMZSoYxeZS07rM7WCqxzd2xXqfzuTAxsO1yNiEo/UwvVZUqz6s3nunKXn1m0b5dbKrsu7hxmWf8P8L2DhCDD09/sxOjIwMTctMTAtMTU6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLkFzcE5ldENvcmUuTXZjIFRlc3RzOkRldmVsb3BlcjpNeVRlc3RlZC5Bc3BOZXRDb3JlLk12Yy46U3Vic2NyaXB0aW9u";

                LicenseValidator.ClearLicenseDetails();
                TestCounter.SetLicenseData(new[] { license }, new DateTime(2016, 10, 10), new DateTime(2018, 10, 10), "MyTested.AspNetCore.Mvc.Tests");

                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        TestCounter.IncrementAndValidate();
                    }));
                }

                try
                {
                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            Assert.Null(caughtException);
        }
        public void IncrementAndValidateShouldNotThrowExceptionWithValidLegacyLicense()
        {
            Exception caughtException = null;

            Task.Run(async() =>
            {
                var license = "1-rXDHzH/rR8IN83Qmtpyf8vsAd4cPfSd/roXjngSxf12fuEY5+nk/evBTOD3xcOQSrEQLte3BcpH/RxIxDaSmZU11zV4jafnJ4N0u+yfNmTvRhVAtGuVCPj1UgYva64QK5fsPbOXBXq1c9+ccfWoWuB7nuRPaJvUlv/dcHQAy3cUxOjIwMTctMTAtMTU6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLkFzcE5ldENvcmUuTXZjIFRlc3RzOkRldmVsb3BlcjpNeVRlc3RlZC5Bc3BOZXRDb3JlLk12Yy4=";

                LicenseValidator.ClearLicenseDetails();
                TestCounter.SetLicenseData(new[] { license }, new DateTime(2016, 10, 10), new DateTime(2016, 10, 10), "MyTested.AspNetCore.Mvc.Tests");

                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        TestCounter.IncrementAndValidate();
                    }));
                }

                try
                {
                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            Assert.Null(caughtException);
        }
        public void IncrementAndValidateShouldThrowExceptionWithNoLicense()
        {
            Exception caughtException = null;

            Task.Run(async() =>
            {
                LicenseValidator.ClearLicenseDetails();
                TestCounter.SetLicenseData(new string[0], new DateTime(2018, 10, 10), new DateTime(2018, 10, 10), "MyTested.AspNetCore.Mvc.Tests");

                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        TestCounter.IncrementAndValidate();
                    }));
                }

                try
                {
                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            Assert.NotNull(caughtException);
            Assert.IsAssignableFrom <InvalidLicenseException>(caughtException);
            Assert.Equal("The free-quota limit of 100 assertions per test project has been reached. Please visit https://mytestedasp.net/core/mvc#pricing to request a free license or upgrade to a commercial one.", caughtException.Message);
        }
        public void IncrementAndValidateShouldNotThrowExceptionWithValidPerpetualLicense()
        {
            Exception caughtException = null;

            Task.Run(async() =>
            {
                var license = "1-IRaNRwlovf7moJnDcQCJW8JDq++p8/1hTNsRnBRLDGkd6HidiJ3OEzpFdwmlDacikCv5oRBisRkJ8edjqx1R21VA+SxCgpGHJE2ftOBpV1OBysguNUSIKJyte2heP3xD4tY1BQNh0vcVhXJDcE3qImhodZmi1aXJ19SK5f4JRA8xOjIwMTctMTAtMTU6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLkFzcE5ldENvcmUuTXZjIFRlc3RzOkRldmVsb3BlcjpNeVRlc3RlZC5Bc3BOZXRDb3JlLk12Yy46UGVycGV0dWFs";

                LicenseValidator.ClearLicenseDetails();
                TestCounter.SetLicenseData(new[] { license }, new DateTime(2018, 10, 10), new DateTime(2016, 10, 10), "MyTested.AspNetCore.Mvc.Tests");

                var tasks = new List <Task>();

                for (int i = 0; i < 200; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        TestCounter.IncrementAndValidate();
                    }));
                }

                try
                {
                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            Assert.Null(caughtException);
        }
Ejemplo n.º 36
0
        public void IncrementAndValidateShouldThrowExceptionWithInvalidLicense()
        {
            Exception caughtException = null;

            Task.Run(async() =>
            {
                var license = "1-0WUoGNBmCpgJ+ktp3BObsUjsaX5XKc4Ed4LoeJBUPgTacqG2wUw9iKAMG4jdDIaiU+AnoTvrXwwLuvfvn57oukhw6HwTqp8hJ2I0vmNZFisQGyD4sjTDlKCBaOXJwXzifCIty2UuGUeo3KNqKoM+5MF1D0i/kEg/LKztnAN312gxOjIwMTctMTAtMTU6YWRtaW5AbXl0ZXN0ZWRhc3AubmV0Ok15VGVzdGVkLk12YyBUZXN0czpGdWxsOk15VGVzdGVkLk12Yy4=";

                LicenseValidator.ClearLicenseDetails();
                TestCounter.SetLicenseData(new [] { license }, new DateTime(2018, 10, 10), "MyTested.AspNetCore.Mvc.Tests");

                var tasks = new List <Task>();

                for (int i = 0; i < 1000; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        TestCounter.IncrementAndValidate();
                    }));
                }

                try
                {
                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            })
            .GetAwaiter()
            .GetResult();

            Assert.NotNull(caughtException);
            Assert.IsAssignableFrom <InvalidLicenseException>(caughtException);
        }
 public void Will_fail_if_file_is_not_there()
 {
     var validator = new LicenseValidator(public_only, "not_there");
     Assert.Throws<LicenseFileNotFoundException>(validator.AssertValidLicense);
 }
 public void Will_tell_that_we_are_in_invalid_state()
 {
     var validator = new LicenseValidator(public_only, Path.GetTempFileName());
     Assert.Throws<LicenseNotFoundException>(validator.AssertValidLicense);
 }
Ejemplo n.º 39
0
    /// <summary>
    /// Invokes the middleware.
    /// </summary>
    /// <param name="context">The context.</param>
    /// <param name="router">The router.</param>
    /// <param name="userSession">The user session.</param>
    /// <param name="events">The event service.</param>
    /// <param name="issuerNameService">The issuer name service</param>
    /// <param name="sessionCoordinationService"></param>
    /// <returns></returns>
    public async Task Invoke(
        HttpContext context,
        IEndpointRouter router,
        IUserSession userSession,
        IEventService events,
        IIssuerNameService issuerNameService,
        ISessionCoordinationService sessionCoordinationService)
    {
        // this will check the authentication session and from it emit the check session
        // cookie needed from JS-based signout clients.
        await userSession.EnsureSessionIdCookieAsync();

        context.Response.OnStarting(async() =>
        {
            if (context.GetSignOutCalled())
            {
                _logger.LogDebug("SignOutCalled set; processing post-signout session cleanup.");

                // this clears our session id cookie so JS clients can detect the user has signed out
                await userSession.RemoveSessionIdCookieAsync();

                var user = await userSession.GetUserAsync();
                if (user != null)
                {
                    var session = new UserSession
                    {
                        SubjectId   = user.GetSubjectId(),
                        SessionId   = await userSession.GetSessionIdAsync(),
                        DisplayName = user.GetDisplayName(),
                        ClientIds   = (await userSession.GetClientListAsync()).ToList(),
                        Issuer      = await issuerNameService.GetCurrentAsync()
                    };
                    await sessionCoordinationService.ProcessLogoutAsync(session);
                }
            }
        });

        try
        {
            var endpoint = router.Find(context);
            if (endpoint != null)
            {
                var endpointType = endpoint.GetType().FullName;

                using var activity = Tracing.BasicActivitySource.StartActivity("IdentityServerProtocolRequest");
                activity?.SetTag(Tracing.Properties.EndpointType, endpointType);

                LicenseValidator.ValidateIssuer(await issuerNameService.GetCurrentAsync());

                _logger.LogInformation("Invoking IdentityServer endpoint: {endpointType} for {url}", endpointType, context.Request.Path.ToString());

                var result = await endpoint.ProcessAsync(context);

                if (result != null)
                {
                    _logger.LogTrace("Invoking result: {type}", result.GetType().FullName);
                    await result.ExecuteAsync(context);
                }

                return;
            }
        }
        catch (Exception ex)
        {
            await events.RaiseAsync(new UnhandledExceptionEvent(ex));

            _logger.LogCritical(ex, "Unhandled exception: {exception}", ex.Message);
            throw;
        }

        await _next(context);
    }
		//internal License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        internal static License GetLicense(Type type, string key)
		{
			//if (System.Security.SecurityManager.SecurityEnabled == false)
			//	return null;
				
			KrystalwareRuntimeLicense l = null;

			string assembly = type.Assembly.GetName().Name;
			string licenseFile = assembly + ".xml.lic";

			// First, check if someone has set the license manually
			PropertyInfo[] licenseProperties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Static);

			foreach (PropertyInfo pi in licenseProperties)
			{
				if (pi.PropertyType == typeof(KrystalwareRuntimeLicense))
				{
					l = pi.GetValue(null, null) as KrystalwareRuntimeLicense;

					break;
				}
			}
            
            // First, check to see if there's a license file with the app
            if (l == null)
                l = LoadLicenseFromFile(type, HostingEnvironment.MapPath("~/"));

            // Next, check to see if there's a license file in the bin folder
            if (l == null)
                l = LoadLicenseFromFile(type, HostingEnvironment.MapPath("~/bin/"));

            // Next, check to see if there's a license file in the App_Data folder
            if (l == null)
                l = LoadLicenseFromFile(type, HostingEnvironment.MapPath("~/App_Data/"));

            // Next, check to see if there's a license resource somewhere
			if (l == null)
				l = LoadLicenseFromResource(type);

			// Next, check to see if there's a license file with the assembly
			if (l == null)
				l = LoadLicenseFromFile(type);
			
            if (l != null)
			{
				//string key = ((LicensePublicKeyAttribute)Attribute.GetCustomAttribute(type.Assembly, typeof(LicensePublicKeyAttribute))).XmlString;

				if (key != null)
				{
					KeyInfo keyInfo = LicenseValidator.GetKeyInfoFromXml(key);

					LicenseValidator validator = new LicenseValidator(l);

					if (!validator.IsValid(keyInfo))
						l = null;
				}
				else
				{
					l = null;
				}
			}

			// If not, create a new evaluation license
			if (l == null)
			{
				string version = type.Assembly.GetName().Version.Major.ToString();

				l = new KrystalwareRuntimeLicense(assembly, version);
			}

			return l;
		}
Ejemplo n.º 41
0
        public static ChocolateyLicense validate()
        {
            var chocolateyLicense = new ChocolateyLicense
            {
                LicenseType  = ChocolateyLicenseType.Unknown,
                IsCompatible = true
            };

            var regularLogOutput = determine_if_regular_output_for_logging();

            string licenseFile     = ApplicationParameters.LicenseFileLocation;
            var    userLicenseFile = ApplicationParameters.UserLicenseFileLocation;

            if (File.Exists(userLicenseFile))
            {
                licenseFile = userLicenseFile;
            }

            // no IFileSystem at this point
            if (!File.Exists(licenseFile))
            {
                var licenseFileName  = Path.GetFileName(ApplicationParameters.LicenseFileLocation);
                var licenseDirectory = Path.GetDirectoryName(ApplicationParameters.LicenseFileLocation);

                // look for misnamed files and locations
                // - look in the license directory for misnamed files
                if (Directory.Exists(licenseDirectory))
                {
                    if (Directory.GetFiles(licenseDirectory).Length != 0)
                    {
                        "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, @"Files found in directory '{0}' but not a
 valid license file. License should be named '{1}'.".format_with(licenseDirectory, licenseFileName));
                        "chocolatey".Log().Warn(ChocolateyLoggers.Important, @" Rename license file to '{0}' to allow commercial features.".format_with(licenseFileName));
                    }
                }


                // - user put the license file in the top level location and/or forgot to rename it
                if (File.Exists(Path.Combine(ApplicationParameters.InstallLocation, licenseFileName)) || File.Exists(Path.Combine(ApplicationParameters.InstallLocation, licenseFileName + ".txt")))
                {
                    "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, @"Chocolatey license found in the wrong location. File must be located at
 '{0}'.".format_with(ApplicationParameters.LicenseFileLocation));
                    "chocolatey".Log().Warn(regularLogOutput ? ChocolateyLoggers.Important : ChocolateyLoggers.LogFileOnly, @" Move license file to '{0}' to allow commercial features.".format_with(ApplicationParameters.LicenseFileLocation));
                }
            }

            // no IFileSystem at this point
            if (File.Exists(licenseFile))
            {
                "chocolatey".Log().Debug("Evaluating license file found at '{0}'".format_with(licenseFile));
                var license = new LicenseValidator(PUBLIC_KEY, licenseFile);

                try
                {
                    license.AssertValidLicense();

                    // There is a lease expiration timer within Rhino.Licensing, which by
                    // default re-asserts the license every 5 minutes.  Since we assert a
                    // valid license on each attempt to execute an action with Chocolatey,
                    // re-checking of the license for the current session is not required.
                    license.DisableFutureChecks();

                    chocolateyLicense.IsValid = true;
                }
                catch (LicenseFileNotFoundException e)
                {
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, "A license was not found for a licensed version of Chocolatey:{0} {1}{0} {2}".format_with(Environment.NewLine, e.Message,
                                                                                                                                                                                                                    "A license was also not found in the user profile: '{0}'.".format_with(ApplicationParameters.UserLicenseFileLocation)));
                }
                catch (Exception e)
                {
                    //license may be invalid
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, "A license was found for a licensed version of Chocolatey, but is invalid:{0} {1}".format_with(Environment.NewLine, e.Message));
                }

                var chocolateyLicenseType = ChocolateyLicenseType.Unknown;
                try
                {
                    Enum.TryParse(license.LicenseType.to_string(), true, out chocolateyLicenseType);
                }
                catch (Exception)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.Unknown;
                }

                if (license.LicenseType == LicenseType.Trial)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.BusinessTrial;
                }
                else if (license.LicenseType == LicenseType.Education)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.Educational;
                }

                chocolateyLicense.LicenseType    = chocolateyLicenseType;
                chocolateyLicense.ExpirationDate = license.ExpirationDate;
                chocolateyLicense.Name           = license.Name;
                chocolateyLicense.Id             = license.UserId.to_string();

                //todo: #2584 if it is expired, provide a warning.
                // one month after it should stop working
            }
            else
            {
                //free version
                chocolateyLicense.LicenseType = ChocolateyLicenseType.Foss;
            }

            return(chocolateyLicense);
        }