Exemplo n.º 1
0
        protected void ThrowIfNotAllowedInApp(List <Grants> requiredGrants, IAppIdentity alternateApp = null)
        {
            var permCheck = ServiceProvider.Build <MultiPermissionsApp>().Init(ContextOfBlock, alternateApp ?? ContextOfBlock.AppState, Log);

            if (!permCheck.EnsureAll(requiredGrants, out var error))
            {
                throw HttpException.PermissionDenied(error);
            }
        }
Exemplo n.º 2
0
 public override IUiContextBuilder SetZoneAndApp(int zoneId, IAppIdentity app)
 {
     // check if we're providing context for missing app
     // in this case we must find the zone based on the portals.
     if (zoneId == 0 && app == null)
     {
         zoneId = _zoneMapper.Value.Init(null).GetZoneId(_portal.PortalId);
     }
     return(base.SetZoneAndApp(zoneId, app));
 }
        public void GetStatementsSafelyUnavailableRecognizedDataProviderRequestWorks()
        {
            IAutonomousApp      client       = this.GetAutonomousClient();
            IUserIdentity       userIdentity = RecognizedUserIdentity.Master;
            string              docType      = userIdentity.DocType;
            string              docNumber    = userIdentity.DocNumber;
            IList <AccountInfo> accounts     = client.Inquiries.GetAccounts(docType, docNumber);

            CollectionAssert.IsNotEmpty(accounts);
            AccountInfo accountInfo = accounts.FirstOrDefault(account => account.Source == Subsystem.Tup);

            Assert.IsNotNull(accountInfo);
            string accountId = accountInfo.SourceAccountId;

            Assert.IsNotEmpty(accountId);
            IList <BalanceInfo> balances = client.Inquiries.GetBalances(docType, docNumber, accountId);

            CollectionAssert.IsNotEmpty(balances);

            void AssertStatementsSafeResults(IList <MiniStatementResultInfo> statementInquiryResults)
            {
                CollectionAssert.IsNotEmpty(statementInquiryResults);
                Assert.That(statementInquiryResults.Count, Is.EqualTo(1));
                foreach (MiniStatementResultInfo inquiryResult in statementInquiryResults)
                {
                    CollectionAssert.IsEmpty(inquiryResult.Data);
                    Assert.IsNotEmpty(inquiryResult.Reason);
                    Assert.That(inquiryResult.Subsystem, Is.EqualTo(Subsystem.Tup));
                    Assert.That(inquiryResult.Status, Is.EqualTo(SubsystemStatus.Unavailable));
                }
            }

            // Se configura una conexión inválida para el proveedor de datos de TUP para esperar que falle la consulta de saldos...
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Bifrost:ConnectionStringName", "RabbitMQ:Broken:Tests");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "TUP:ConnectionStringName", "Aspen");

            // Los movimientos más recientes realizados por la cuenta...
            IList <MiniStatementResultInfo> inquiryResults = client.InquiriesV11.GetStatements(docType, docNumber, accountId);

            AssertStatementsSafeResults(inquiryResults);

            // Los movimientos más recientes realizados por la cuenta y el bolsillo específico...
            string accountTypeId = balances.First().TypeId;

            Assert.IsNotEmpty(accountTypeId);
            inquiryResults = client.InquiriesV11.GetStatements(docType, docNumber, accountId, accountTypeId);
            AssertStatementsSafeResults(inquiryResults);

            // Se reestablece las conexión valida al proveedor de datos de TUP...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Bifrost:ConnectionStringName", "RabbitMQ:Bifrost:Tests");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "TUP:ConnectionStringName", "Sql:TupCompensar");
        }
 public HelloWorldCronService(
     IScheduleConfig <HelloWorldCronService> config,
     ILogger <HelloWorldCronService> logger,
     IQueueService <HelloWorldModel> queueService,
     IAppIdentity appIdentity
     ) : base(config.CronExpression, config.TimeZoneInfo)
 {
     this.logger       = logger;
     this.queueService = queueService;
     this.appIdentity  = appIdentity;
 }
Exemplo n.º 5
0
        public void NotFoundValidTokenWhenAppSignedRequestThrows()
        {
            IAutonomousApp client      = this.GetAutonomousClient();
            IAppIdentity   appIdentity = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().RemoveAppAuthToken(appIdentity.ApiKey);
            AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15847"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("No hay un token de autenticación vigente", exception.Message);
        }
Exemplo n.º 6
0
        public void MismatchTokenSignatureWhenAppSignedRequestThrows()
        {
            IAutonomousApp client            = this.GetAutonomousClient();
            IAppIdentity   appIdentityMaster = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().EnsureMismatchAppAuthToken(appIdentityMaster.ApiKey);
            AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15846"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("No coinciden los datos recibidos del token vs los valores esperados. ¿Se modificaron los valores en tránsito o está utilizando el ApiKey en otra aplicación?", exception.Message);
        }
        public void ApiKeyDisabledWhenAppSigninRequestThrows()
        {
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().UpdateEnabled(appIdentity.ApiKey, false);
            AspenException exception = Assert.Throws <AspenException>(() => this.GetAutonomousClient());

            Assert.That(exception.EventId, Is.EqualTo("20006"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
            StringAssert.IsMatch("ApiKey está desactivado. Póngase en contacto con el administrador", exception.Message);
            TestContext.CurrentContext.DatabaseHelper().UpdateEnabled(appIdentity.ApiKey, true);
        }
        public void AppRequiresChangeSecretWhenSigninRequestThrows()
        {
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().UpdateChangeSecret(appIdentity.ApiKey, true);
            AspenException exception = Assert.Throws <AspenException>(() => this.GetAutonomousClient());

            Assert.That(exception.EventId, Is.EqualTo("20009"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.UpgradeRequired));
            StringAssert.IsMatch("Necesita actualizar el secreto de la aplicación.", exception.Message);
            TestContext.CurrentContext.DatabaseHelper().UpdateChangeSecret(appIdentity.ApiKey, false);
        }
        public void GetAccountsRecognizedDataProvidersRequestWorks()
        {
            // Se habilitan los proveedores actuales en la aplicación...
            IAppIdentity appIdentity = DelegatedAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP|Bancor");

            IDelegatedApp client = this.GetDelegatedClient();
            IList <AccountExtendedInfo> accounts = client.Inquiries.GetAccounts();

            CollectionAssert.IsNotEmpty(accounts);
            Assert.That(accounts.Count, Is.EqualTo(2));

            const string AccountIdPattern       = @"^[\d]*$";
            const string AccountNumberPattern   = @".*\d{4}";
            const string BackgroundColorPattern = @"^#(?:[0-9a-fA-F]{3}){1,2}$";

            foreach (AccountExtendedInfo account in accounts)
            {
                Assert.That(account.Balance, Is.AssignableTo(typeof(decimal)));
                Assert.That(account.Id, Is.Not.Null.And.Match(AccountIdPattern));
                Assert.That(account.SourceAccountId, Is.Not.Null.And.Match(AccountIdPattern));
                Assert.That(account.MaskedPan, Is.Not.Null.And.Match(AccountNumberPattern));
                Assert.That(account.Name, Is.Not.Empty);
                Assert.That(account.ShortName, Is.Not.Empty);
                Assert.That(account.BackgroundColor, Is.Not.Null.And.Match(BackgroundColorPattern));
                CollectionAssert.IsNotEmpty(account.Properties);

                IList <AccountProperty> accountProperties = account.Properties;
                switch (account.Source)
                {
                case Subsystem.Tup:
                    Assert.That(accountProperties.Count, Is.EqualTo(4));
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "LastTranName"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "LastTranDate"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "LastTranCardAcceptor"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "CardStatusName"), Is.Not.Null);
                    break;

                case Subsystem.Bancor:
                    Assert.That(accountProperties.Count, Is.EqualTo(4));
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "LastTran"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "NextPayment"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "FullPayment"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "PartialPayment"), Is.Not.Null);
                    break;
                }
            }

            // Se reestablece la aplicación para usar el proveedor predeterminando para pruebas...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP");
        }
Exemplo n.º 10
0
        public void MismatchTokenWhenUserSignedRequestThrows()
        {
            IDelegatedApp client             = this.GetDelegatedClient();
            IAppIdentity  appIdentityMaster  = DelegatedAppIdentity.Master;
            IUserIdentity userIdentityMaster = RecognizedUserIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().EnsureMismatchUserAuthToken(appIdentityMaster.ApiKey, userIdentityMaster.DocType, userIdentityMaster.DocNumber, userIdentityMaster.Device.DeviceId);
            AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15846"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("No coinciden los datos recibidos del token vs los valores esperados. ¿Se modificaron los valores en tránsito o está utilizando el ApiKey en otra aplicación?", exception.Message);
        }
        public void GetAccountsRecognizedDataProvidersRequestWorks()
        {
            // Se habilitan los proveedores conocidos para la aplicación...
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP|Bancor");

            IAutonomousApp      client       = this.GetAutonomousClient();
            IUserIdentity       userIdentity = RecognizedUserIdentity.Master;
            string              docType      = userIdentity.DocType;
            string              docNumber    = userIdentity.DocNumber;
            IList <AccountInfo> accounts     = client.Inquiries.GetAccounts(docType, docNumber);

            CollectionAssert.IsNotEmpty(accounts);
            Assert.That(accounts.Count, Is.EqualTo(2));

            const string AccountIdPattern     = @"^[\d]*$";
            const string AccountNumberPattern = @".*\d{4}";

            foreach (AccountInfo account in accounts)
            {
                Assert.That(account.Balance, Is.AssignableTo(typeof(decimal)));
                Assert.That(account.Id, Is.Not.Null.And.Match(AccountIdPattern));
                Assert.That(account.SourceAccountId, Is.Not.Null.And.Match(AccountIdPattern));
                Assert.That(account.MaskedPan, Is.Not.Null.And.Match(AccountNumberPattern));
                Assert.That(account.Name, Is.Not.Empty);
                CollectionAssert.IsNotEmpty(account.Properties);

                IList <AccountProperty> accountProperties = account.Properties;
                switch (account.Source)
                {
                case Subsystem.Tup:
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "LastTranName"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "LastTranDate"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "LastTranCardAcceptor"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "CardStatusName"), Is.Not.Null);
                    break;

                case Subsystem.Bancor:
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "LastTran"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "NextPayment"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "FullPayment"), Is.Not.Null);
                    Assert.That(accountProperties.SingleOrDefault(p => p.Key == "PartialPayment"), Is.Not.Null);
                    break;
                }
            }

            // Se reestablece la aplicación para usar el proveedor de datos predeterminando para pruebas...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP");
        }
        public void RunBeforeTestFixture()
        {
            IAppIdentity appIdentity = DelegatedAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Bifrost:ConnectionStringName", "RabbitMQ:Bifrost:Tests");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Bancor:ConnectionStringName", "RabbitMQ:Bancor:Tests");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Kraken:ConnectionStringName", "RabbitMQ:Kraken:Tests");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "TUP:InquiryProvider", "Database");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "IOC:AuthProviderKey", "DbAuthProvider");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "IOC:TokenProviderKey", "LocalTokenProvider");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "RemoteTokenProvider:SupportsChannels", "False");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "RemoteTokenProvider:NullifyErrorBehavior", "SilentlyContinue");
        }
        public void GetBalancesSafelyUnavailableRecognizedDataProviderRequestWorks()
        {
            // Se habilitan los proveedores conocidos para la aplicación...
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP|Bancor");

            IAutonomousApp      client       = this.GetAutonomousClient();
            IUserIdentity       userIdentity = RecognizedUserIdentity.Master;
            string              docType      = userIdentity.DocType;
            string              docNumber    = userIdentity.DocNumber;
            IList <AccountInfo> accounts     = client.Inquiries.GetAccounts(docType, docNumber);

            CollectionAssert.IsNotEmpty(accounts);
            AccountInfo accountInfo = accounts.FirstOrDefault(account => account.Source == Subsystem.Tup);

            Assert.IsNotNull(accountInfo);
            string accountId = accountInfo.SourceAccountId;

            // Se configura una conexión inválida para el proveedor de datos de TUP para esperar que falle la consulta de saldos...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Bifrost:ConnectionStringName", "RabbitMQ:Broken:Tests");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "TUP:ConnectionStringName", "Aspen");

            IList <BalanceResultInfo> inquiryResults = client.InquiriesV11.GetBalances(docType, docNumber, accountId);

            CollectionAssert.IsNotEmpty(inquiryResults);
            Assert.That(inquiryResults.Count, Is.EqualTo(2));

            // El proveedor de datos de TUP debe indicar que no está disponible para procesar la consulta requerida...
            BalanceResultInfo tupInquiryResult = inquiryResults.First(info => info.Subsystem == Subsystem.Tup);

            CollectionAssert.IsEmpty(tupInquiryResult.Data);
            Assert.IsNotEmpty(tupInquiryResult.Reason);
            Assert.That(tupInquiryResult.Status, Is.EqualTo(SubsystemStatus.Unavailable));

            // El proveedor de datos de BANCOR debe indicar que no implementa la característica de saldos...
            BalanceResultInfo bancorInquiryResult = inquiryResults.First(info => info.Subsystem == Subsystem.Bancor);

            CollectionAssert.IsEmpty(bancorInquiryResult.Data);
            Assert.IsNotEmpty(bancorInquiryResult.Reason);
            Assert.That(bancorInquiryResult.Status, Is.EqualTo(SubsystemStatus.MissingFeature));

            // Se reestablece la aplicación para usar el proveedor de datos predeterminando para pruebas...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP");

            // Se reestablece las conexión valida al proveedor de datos de TUP...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Bifrost:ConnectionStringName", "RabbitMQ:Bifrost:Tests");
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "TUP:ConnectionStringName", "Sql:TupCompensar");
        }
        public void UpdateApiSecretRequestWorks()
        {
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;
            string apiKey = appIdentity.ApiKey;
            string currentApiSecret = appIdentity.ApiSecret;
            string newApiSecret = this.GetRandomSecret();

            Assert.That(newApiSecret.Length, Is.GreaterThanOrEqualTo(128));
            Assert.DoesNotThrow(() => AutonomousApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(apiKey, currentApiSecret)
                .UpdateApiSecret(newApiSecret));

            TestContext.CurrentContext.DatabaseHelper().UpdateApiSecret(apiKey, currentApiSecret);
        }
        /// <summary>
        /// Inicializa una nueva instancia de la clase <see cref="ServiceLocator" />
        /// </summary>
        /// <param name="nonceGenerator">Instancia de <see cref="INonceGenerator" /> que se utiliza para inicializar el proveedor de valores nonce o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="epochGenerator">Instancia de <see cref="IEpochGenerator" /> que se utiliza para inicializar el proveedor de valores epoch o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="headersManager">Instancia de <see cref="IHeadersManager" /> que se utiliza para inicializar el proveedor de cabeceras para las solicitudes al servicio o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="requestHeaderNames">Instancia de <see cref="IHeaderElement" /> que se utiliza para inicializar el proveedor de los nombres de cabeceras personalizadas o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="payloadClaimNames">Instancia de <see cref="IPayloadClaimElement" /> que se utiliza para inicializar el proveedor de los nombres para las reclamaciones usadas en la carga útil del servicio o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="payloadClaimsManager">Instancia de <see cref="IPayloadClaimsManager" /> que se utiliza para inicializar el proveedor de reclamaciones de la carga útil o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="jwtJsonSerializer">Instancia de <see cref="IJsonSerializer" /> que se utiliza para inicializar el proveedor de serialización y deserialización de JWT o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="webProxy">Instancia de <see cref="IWebProxy" /> que se utiliza para inicializar el proveedor del servidor proxy o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="loggingProvider">Instancia de <see cref="ILoggingProvider" /> que se utiliza para inicializar el proveedor de escritura de trazas de seguimiento o <c>null</c> para utilizar la instancia predeterminada.</param>
        /// <param name="endpointProvider">Instancia que implementa <see cref="IEndpointProvider"/> para la obtención de valores de configuración.</param>
        /// <param name="appIdentity">Instancia que implementa <see cref="IAppIdentity"/> para la obtención de valores de configuración.</param>
        private void RegisterInstance(
            INonceGenerator nonceGenerator             = null,
            IEpochGenerator epochGenerator             = null,
            IHeadersManager headersManager             = null,
            IHeaderElement requestHeaderNames          = null,
            IPayloadClaimElement payloadClaimNames     = null,
            IPayloadClaimsManager payloadClaimsManager = null,
            IJsonSerializer jwtJsonSerializer          = null,
            IWebProxy webProxy = null,
            ILoggingProvider loggingProvider   = null,
            IEndpointProvider endpointProvider = null,
            IAppIdentity appIdentity           = null)
        {
            lock (padlock)
            {
                INonceGenerator       instanceOfNonceGenerator       = nonceGenerator ?? this.NonceGenerator ?? new GuidNonceGenerator();
                IEpochGenerator       instanceOfEpochGenerator       = epochGenerator ?? this.EpochGenerator ?? new UnixEpochGenerator();
                IHeaderElement        instanceOfRequestHeaderNames   = requestHeaderNames ?? this.RequestHeaderNames ?? new DefaultHeaderElement();
                IPayloadClaimElement  instanceOfPayloadClaimNames    = payloadClaimNames ?? this.PayloadClaimNames ?? new DefaultPayloadClaimElement();
                IPayloadClaimsManager instanceOfPayloadClaimsManager = payloadClaimsManager ?? this.PayloadClaimsManager ?? new DefaultPayloadClaimsManager();
                IHeadersManager       instanceOfHeadersManager       = headersManager ?? this.HeadersManager ?? new DefaultHeadersManager();
                IJsonSerializer       instanceOfJwtJsonSerializer    = jwtJsonSerializer ?? this.JwtJsonSerializer ?? new JsonNetSerializer();
                IWebProxy             instanceOfWebProxy             = webProxy ?? this.WebProxy ?? new NullWebProxy();
                ILoggingProvider      instanceOfLoggingProvider      = loggingProvider ?? this.LoggingProvider ?? new NullLoggingProvider();
                IEndpointProvider     instanceOfEndpointProvider     = endpointProvider ?? new EnvironmentEndpoint();
                IAppIdentity          instanceOfAppIdentity          = appIdentity ?? new EnvironmentIdentity();

                if (this.container != null)
                {
                    this.container.Dispose();
                    this.container = null;
                }

                this.container = new Container();
                this.container.RegisterInstance <IEnvironmentRuntime>(new EnvironmentRuntime());
                this.container.RegisterInstance(instanceOfNonceGenerator);
                this.container.RegisterInstance(instanceOfEpochGenerator);
                this.container.RegisterInstance(instanceOfRequestHeaderNames);
                this.container.RegisterInstance(instanceOfHeadersManager);
                this.container.RegisterInstance(instanceOfPayloadClaimNames);
                this.container.RegisterInstance(instanceOfPayloadClaimsManager);
                this.container.RegisterInstance(instanceOfJwtJsonSerializer);
                this.container.RegisterInstance(instanceOfWebProxy);
                this.container.RegisterInstance(instanceOfLoggingProvider);
                this.container.RegisterInstance(instanceOfEndpointProvider);
                this.container.RegisterInstance(instanceOfAppIdentity);
            }
        }
        public void ApiKeyScopeMismatchThrows()
        {
            IAppIdentity   delegatedAppIdentity = DelegatedAppIdentity.Master;
            AspenException exception            = Assert.Throws <AspenException>(() =>
            {
                AutonomousApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(delegatedAppIdentity)
                .Authenticate()
                .GetClient();
            });

            Assert.That(exception.EventId, Is.EqualTo("1000478"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
            StringAssert.IsMatch("ApiKey no tiene permisos para realizar la operación. Alcance requerido: 'Autonomous'", exception.Message);
        }
Exemplo n.º 17
0
        public void NotFoundValidTokenWhenUserSignedRequestThrows()
        {
            IDelegatedApp client    = this.GetDelegatedClient();
            UserAuthToken authToken = client.AuthToken as UserAuthToken;

            Assert.That(authToken, Is.Not.Null);
            IAppIdentity  appIdentity  = DelegatedAppIdentity.Master;
            IUserIdentity userIdentity = RecognizedUserIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().RemoveUserAuthToken(appIdentity.ApiKey, userIdentity.DocType, userIdentity.DocNumber, authToken.DeviceId);
            AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15847"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("No hay un token de autenticación vigente", exception.Message);
        }
Exemplo n.º 18
0
        public void TokenProvidedExpiredWhenAppSignedRequestThrows()
        {
            IAutonomousApp client    = this.GetAutonomousClient();
            AuthToken      authToken = client.AuthToken as AuthToken;

            Assert.That(authToken, Is.Not.Null);
            Assert.That(authToken.Expired, Is.False);
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().EnsureExpireAppAuthToken(appIdentity.ApiKey);
            AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15848"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("El token de autenticación proporcionado ya venció", exception.Message);
        }
        public void SecretFormatMustBeEncryptedTypeAfterUpdate()
        {
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;
            string apiKey = appIdentity.ApiKey;
            string currentApiSecret = appIdentity.ApiSecret;
            string newApiSecret = this.GetRandomSecret();

            Assert.DoesNotThrow(() => AutonomousApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(apiKey, currentApiSecret)
                .UpdateApiSecret(newApiSecret));

            // El tipo de formato del secreto debe ser 'SecretFormat.Encrypted' (1)
            Assert.IsTrue(TestContext.CurrentContext.DatabaseHelper().AppSecretFormatIsEncrypted(apiKey));

            TestContext.CurrentContext.DatabaseHelper().UpdateApiSecret(apiKey, currentApiSecret);
        }
Exemplo n.º 20
0
        public void TokenProvidedExpiredWhenUserSignedRequestThrows()
        {
            IDelegatedApp client    = this.GetDelegatedClient();
            UserAuthToken authToken = client.AuthToken as UserAuthToken;

            Assert.That(authToken, Is.Not.Null);
            Assert.That(authToken.DeviceId, Is.Not.Empty);
            Assert.That(authToken.Expired, Is.False);
            IAppIdentity  appIdentity  = DelegatedAppIdentity.Master;
            IUserIdentity userIdentity = RecognizedUserIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().EnsureExpireUserAuthToken(appIdentity.ApiKey, userIdentity.DocType, userIdentity.DocNumber, authToken.DeviceId);

            AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15848"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("El token de autenticación proporcionado ya venció", exception.Message);
        }
Exemplo n.º 21
0
        public DnnPermissionCheck(
            Log parentLog,
            IContentType targetType = null,
            IEntity targetItem      = null,
            IInstanceInfo instance  = null,
            IApp app = null,
            IEnumerable <IEntity> permissions1 = null,
            PortalSettings portal    = null,
            IAppIdentity appIdentity = null
            )
            : base(parentLog, targetType, targetItem, app?.Metadata.Permissions, permissions1)
        {
            var logWrap = Log.New("DnnPermissionCheck", $"..., {targetItem?.EntityId}, app: {app?.AppId}, ");

            AppIdentity = appIdentity ?? app;
            App         = app;
            Instance    = instance;
            Portal      = portal;
            logWrap(null);
        }
Exemplo n.º 22
0
        public void MismatchBetweenAppsWhenUserSignedRequestThrows()
        {
            IUserIdentity commonUserIdentity = RecognizedUserIdentity.Master;

            IAppIdentity appIdentityMaster = DelegatedAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().EnsureUserAndProfileInfo(appIdentityMaster.ApiKey, commonUserIdentity.DocType, commonUserIdentity.DocNumber);

            IDelegatedApp clientAppMaster = DelegatedApp.Initialize(CachePolicy.BypassCache)
                                            .RoutingTo(TestingEndpointProvider.Default)
                                            .WithIdentity(appIdentityMaster)
                                            .Authenticate(commonUserIdentity)
                                            .GetClient();

            Assert.That(clientAppMaster, Is.Not.Null);
            Assert.That(clientAppMaster.AuthToken, Is.Not.Null);
            Assert.That(clientAppMaster.AuthToken.Token, Is.Not.Null);

            IAppIdentity appIdentityHelper = DelegatedAppIdentity.Helper;

            TestContext.CurrentContext.DatabaseHelper().EnsureUserAndProfileInfo(appIdentityHelper.ApiKey, commonUserIdentity.DocType, commonUserIdentity.DocNumber);

            IDelegatedApp clientAppHelper = DelegatedApp.Initialize(CachePolicy.BypassCache)
                                            .RoutingTo(TestingEndpointProvider.Default)
                                            .WithIdentity(appIdentityHelper)
                                            .Authenticate(commonUserIdentity)
                                            .GetClient();

            Assert.That(clientAppHelper, Is.Not.Null);
            Assert.That(clientAppHelper.AuthToken, Is.Not.Null);
            Assert.That(clientAppHelper.AuthToken.Token, Is.Not.Null);

            IPayloadClaimsManager mismatchTokenClaimBehavior = InvalidTokenPayloadClaim.WithClaimBehavior(() => clientAppHelper.AuthToken.Token);

            ServiceLocator.Instance.RegisterPayloadClaimsManager(mismatchTokenClaimBehavior);
            AspenException exception = Assert.Throws <AspenException>(() => clientAppMaster.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15846"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("No coinciden los datos recibidos del token vs los valores esperados. ¿Se modificaron los valores en tránsito o está utilizando el ApiKey en otra aplicación?", exception.Message);
        }
        public void GetAccountsSafelyUnavailableRecognizedDataProviderRequestWorks()
        {
            // Se habilitan los proveedores conocidos para la aplicación...
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP|Bancor");

            // Se configura una conexión inválida a un proveedor de datos conocido para esperar que falle la consulta...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Bancor:ConnectionStringName", "RabbitMQ:Broken:Tests");

            IAutonomousApp            client         = this.GetAutonomousClient();
            IUserIdentity             userIdentity   = RecognizedUserIdentity.Master;
            string                    docType        = userIdentity.DocType;
            string                    docNumber      = userIdentity.DocNumber;
            IList <AccountResultInfo> inquiryResults = client.InquiriesV11.GetAccounts(docType, docNumber);

            CollectionAssert.IsNotEmpty(inquiryResults);
            Assert.That(inquiryResults.Count, Is.EqualTo(2));

            // El proveedor de datos de TUP debe retornar un resultado por la consulta de cuentas...
            AccountResultInfo tupInquiryResult = inquiryResults.First(info => info.Subsystem == Subsystem.Tup);

            CollectionAssert.IsNotEmpty(tupInquiryResult.Data);
            Assert.IsNotEmpty(tupInquiryResult.Reason);
            Assert.That(tupInquiryResult.Status, Is.EqualTo(SubsystemStatus.Available));

            // El proveedor de datos de BANCOR debe indicar que no está disponible para procesar la consulta requerida...
            AccountResultInfo bancorInquiryResult = inquiryResults.First(info => info.Subsystem == Subsystem.Bancor);

            CollectionAssert.IsEmpty(bancorInquiryResult.Data);
            Assert.IsNotEmpty(bancorInquiryResult.Reason);
            Assert.That(bancorInquiryResult.Status, Is.EqualTo(SubsystemStatus.Unavailable));

            // Se reestablece la aplicación para usar el proveedor de datos predeterminando para pruebas...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "DataProvider:SubsystemEnabled", "TUP");

            // Se reestablece las conexión valida al proveedor de datos conocido...
            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "Bancor:ConnectionStringName", "RabbitMQ:Bancor:Tests");
        }
        private static void SetChannelForRemoteTokenProvider(ChannelTarget target)
        {
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;
            string       value       = string.Empty;

            switch (target)
            {
            case ChannelTarget.ToInternalServerError:
                value = "DEMOINTSERERR0000000";
                break;

            case ChannelTarget.ToUnrecognizedStatusCode:
                value = "DEMOINVRESCOD0000000";
                break;

            case ChannelTarget.ToCustomStatusCode:
                value = "DEMOCUSTOMCOD0000000";
                break;
            }

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "RemoteTokenProvider:Channel", value);
        }
        public void UseNewSecretWhenAppSigninRequestWorks()
        {
            IAppIdentity appIdentity = AutonomousAppIdentity.Master;
            string apiKey = appIdentity.ApiKey;
            string currentApiSecret = appIdentity.ApiSecret;
            string newApiSecret = this.GetRandomSecret();

            Assert.DoesNotThrow(() => AutonomousApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(apiKey, currentApiSecret)
                .UpdateApiSecret(newApiSecret));

            IAutonomousApp client = AutonomousApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(apiKey, newApiSecret)
                .Authenticate()
                .GetClient();

            Assert.That(client, Is.Not.Null);
            Assert.That(client.AuthToken, Is.Not.Null);
            Assert.That(client.AuthToken.Token, Is.Not.Null);

            TestContext.CurrentContext.DatabaseHelper().UpdateApiSecret(apiKey, currentApiSecret);
        }
Exemplo n.º 26
0
 public new App Init(IAppIdentity appId, Func <EavApp, IAppDataConfiguration> buildConfig, ILog parentLog)
 {
     base.Init(appId, buildConfig, parentLog);
     return(this);
 }
        private static void UseUnrecognizedTokenProvider()
        {
            IAppIdentity appIdentity = DelegatedAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "IOC:TokenProviderKey", "UnrecognizedTokenProviderName");
        }
        private static void UseBrokenConnection()
        {
            IAppIdentity appIdentity = DelegatedAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "RemoteTokenProvider:ConnectionStringName", "RabbitMQ:Broken:Tests");
        }
        private static void SupportsChannels()
        {
            IAppIdentity appIdentity = DelegatedAppIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().SetAppSettingsKey(appIdentity.ApiKey, "RemoteTokenProvider:SupportsChannels", "True");
        }
Exemplo n.º 30
0
        public static IApp Init(this App app, IAppIdentity appIdentity, ILog log, bool showDrafts = false)
        {
            var buildConfig = ConfigurationProvider.Build(showDrafts, false, new LookUpEngine(log));

            return(app.Init(appIdentity, buildConfig, false, log));
        }