protected override void Act()
                {
                    var oauthAccessTokenClient = new OAuthTokenClient();
                    var input = new[] { oauthAccessTokenClient };

                    Result = ApiClientDetails.Create(input);
                }
 protected override void Arrange()
 {
     TokenClient = new OAuthTokenClient
     {
         ClaimSetName            = "Disintegration",
         EducationOrganizationId = 12,
         Key             = "is the",
         NamespacePrefix = "best",
         ProfileName     = "album",
         StudentIdentificationSystemDescriptor = "ever!",
         UseSandbox = true
     };
 }
示例#3
0
        public void GetTokenTest()
        {
            const int tokenExpiredLifetime = 1;

            const string expectedValue1 = "1111111111";
            var          tokenResponse1 = "{'access_token':'" + expectedValue1 +
                                          "' , 'expires_in':'" + tokenExpiredLifetime +
                                          "' , 'token_type':'bearer', 'scope':'" + EnvId + "'}";

            const string expectedValue2 = "2222222222";
            const string tokenResponse2 = "{'access_token':'" + expectedValue2 +
                                          "' , 'expires_in':'300' , 'token_type':'bearer', 'scope':'" + EnvId + "'}";

            const string expectedValue3 = "3333333333";
            const string tokenResponse3 = "{'access_token':'" + expectedValue3 +
                                          "' , 'expires_in':'300' , 'token_type':'bearer', 'scope':'" + EnvId + "'}";


            var server = new FakeHttpServer(Port,
                                            new[]
            {
                new FakeHttpServerResponse(200, tokenResponse1),
                new FakeHttpServerResponse(200, tokenResponse2),
                new FakeHttpServerResponse(200, tokenResponse3)
            });

            server.Start();

            using var httpClient = new HttpClient();
            var tokenClient =
                new OAuthTokenClient(s_defaultAuthEndpoint, null, EnvId, ClientId, ClientSecret, httpClient);
            //get the first token
            var token = tokenClient.RefreshTokenAsync(false, Audience, Apac).Result;

            Assert.AreEqual(expectedValue1, token);
            Thread.Sleep(tokenExpiredLifetime * 2 * 1_000);
            //get new token after expiration
            token = tokenClient.RefreshTokenAsync(false, Audience, Apac).Result;
            Assert.AreEqual(expectedValue2, token);
            //get cashed token
            token = tokenClient.RefreshTokenAsync(false, Audience, Apac).Result;
            Assert.AreEqual(expectedValue2, token);
            //force update token
            token = tokenClient.RefreshTokenAsync(true, Audience, Apac).Result;
            Assert.AreEqual(expectedValue3, token);

            server.Stop();
        }
示例#4
0
        public void TokenBadEndpointTest()
        {
            using var httpClient = new HttpClient { Timeout = new TimeSpan(0, 0, 1) };
            var tokenClient =
                new OAuthTokenClient(s_defaultAuthEndpoint, null, EnvId, ClientId, ClientSecret, httpClient);
            var exception = Assert.ThrowsAsync <StorageServerException>(async() =>
            {
                var unused = await tokenClient.RefreshTokenAsync(false, Audience, Emea).ConfigureAwait(false);
            });

            Assert.AreEqual(
                "Unexpected exception during authorization, params [OAuth URL=http://localhost:8765, audience=http://audience.localhost, region=emea]",
                exception.Message);
            Assert.IsNotNull(exception.InnerException);
            Assert.AreEqual("Connection refused", exception.InnerException.Message);
        }
示例#5
0
        public void TokenResponseWrongStatusTest()
        {
            var server = new FakeHttpServer(Port, new[] { new FakeHttpServerResponse(401, "") });

            server.Start();
            using var httpClient = new HttpClient();
            var tokenClient =
                new OAuthTokenClient(s_defaultAuthEndpoint, null, EnvId, ClientId, ClientSecret, httpClient);
            var exception = Assert.ThrowsAsync <StorageServerException>(async() =>
            {
                var unused = await tokenClient.RefreshTokenAsync(false, Audience, Emea).ConfigureAwait(false);
            });

            Assert.AreEqual("Unexpected authorization response status='Unauthorized', content=''", exception.Message);
            server.Stop();
        }
示例#6
0
        public LowLevelHttpTest()
        {
            _client = new HttpClient();
            _client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(VersionInfo.ProductName,
                                                                                   VersionInfo.ProductVersion));
            var config = CredentialsHelper.GetConfigWithOauth();

            var tokenClient = new OAuthTokenClient(config.DefaultAuthEndpoint, null, config.EnvironmentId,
                                                   config.ClientId, config.ClientSecret, _client);

            var endpoint = "https://" + CredentialsHelper.GetMidPopCountry() + config.EndpointMask;
            var token    = tokenClient.RefreshTokenAsync(true, endpoint, "emea").Result;

            _client.DefaultRequestHeaders.TryAddWithoutValidation("x-env-id", config.EnvironmentId);
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            _endpoint         = endpoint + "/v2/storage/records/" + CredentialsHelper.GetMidPopCountry();
            _countiesEndpoint = config.CountriesEndPoint;
        }
示例#7
0
        public void CreateTokenClientTest()
        {
            using var httpClient = new HttpClient();
            var tokenClient = new OAuthTokenClient(null, null, EnvId, ClientId, ClientSecret, httpClient);

            Assert.IsNotNull(tokenClient);

            tokenClient = new OAuthTokenClient(s_defaultAuthEndpoint, null, EnvId, ClientId, ClientSecret, httpClient);
            Assert.IsNotNull(tokenClient);

            var endPointDict = new Dictionary <string, string>();

            tokenClient = new OAuthTokenClient(s_defaultAuthEndpoint, endPointDict, EnvId, ClientId, ClientSecret,
                                               httpClient);
            Assert.IsNotNull(tokenClient);

            endPointDict[Apac] = s_apacEndpoint;
            endPointDict[Emea] = s_emeaEndpoint;
            tokenClient        = new OAuthTokenClient(s_defaultAuthEndpoint, endPointDict, EnvId, ClientId, ClientSecret,
                                                      httpClient);
            Assert.IsNotNull(tokenClient);
        }
示例#8
0
        public void GetEndPointTest()
        {
            var server = new FakeHttpServer(Port,
                                            new[]
            {
                new FakeHttpServerResponse(200, CountryLoadResponse),
                //for getting token to midpop
                new FakeHttpServerResponse(200, TokenResponse),
                //for getting token to minipop
                new FakeHttpServerResponse(200, TokenResponse)
            });

            using var httpClient = new HttpClient { Timeout = new TimeSpan(0, 0, 30) };
            server.Start();
            var tokenClient = new OAuthTokenClient(s_endpoint, null, EnvId, "clientId", "clientSecret", httpClient);

            using var dao = HttpDao.NewDao(EnvId, tokenClient, httpClient, null, "-localhost:123", s_endpoint);

            const string midPopCountry = "us";
            var          exception     = Assert.ThrowsAsync <StorageServerException>(async() =>
                                                                                     await dao.CreateRecordAsync(midPopCountry, new TransferRecord("recordKey")).ConfigureAwait(false));

            Assert.AreEqual("Unexpected error [https://us-localhost:123/v2/storage/records/us]", exception.Message);
            Assert.IsNotNull(exception.InnerException);
            Assert.IsInstanceOf <HttpRequestException>(exception.InnerException);

            const string miniPopCountry = "miniPopCountryCode";

            exception = Assert.ThrowsAsync <StorageServerException>(async() =>
                                                                    await dao.CreateRecordAsync(miniPopCountry, new TransferRecord("recordKey")).ConfigureAwait(false));
            Assert.AreEqual("Unexpected error [https://us-localhost:123/v2/storage/records/miniPopCountryCode]",
                            exception.Message);
            Assert.IsNotNull(exception.InnerException);
            Assert.IsInstanceOf <HttpRequestException>(exception.InnerException);

            server.Stop();
        }
示例#9
0
        public void CreateTokenClientTestNegative()
        {
            var endPointDict = new Dictionary <string, string> {
                [Apac] = s_apacEndpoint, [Emea] = s_emeaEndpoint
            };

            using var httpClient = new HttpClient();
            var exception = Assert.Throws <StorageClientException>(() =>
            {
                var unused = new OAuthTokenClient(null, endPointDict, EnvId, ClientId, ClientSecret,
                                                  httpClient);
            });

            Assert.AreEqual("Can't use param 'authEndpoints' without setting 'defaultAuthEndpoint'", exception.Message);

            endPointDict = new Dictionary <string, string> {
                [""] = s_apacEndpoint, [Emea] = s_emeaEndpoint
            };
            exception = Assert.Throws <StorageClientException>(() =>
            {
                var unused = new OAuthTokenClient(s_defaultAuthEndpoint, endPointDict, EnvId, ClientId,
                                                  ClientSecret,
                                                  httpClient);
            });
            Assert.AreEqual("Parameter 'authEndpoints' contains null keys/values", exception.Message);

            endPointDict = new Dictionary <string, string> {
                [Apac] = null, [Emea] = null
            };
            exception = Assert.Throws <StorageClientException>(() =>
            {
                var unused = new OAuthTokenClient(s_defaultAuthEndpoint, endPointDict, EnvId, ClientId,
                                                  ClientSecret,
                                                  httpClient);
            });
            Assert.AreEqual("Parameter 'authEndpoints' contains null keys/values", exception.Message);
        }
示例#10
0
        private Storage(StorageConfig config)
        {
            s_helper.Check <StorageClientException>(config == null, Messages.Storage.s_errNullConfig);
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(VersionInfo.ProductName,
                                                                                       VersionInfo.ProductVersion));
#pragma warning disable CA1062
            _httpClient.Timeout = new TimeSpan(0, 0, config.HttpTimeout);
#pragma warning restore CA1062
            ITokenClient tokenClient = null;
            if (!string.IsNullOrEmpty(config.ApiKey))
            {
                tokenClient = new ApiKeyTokenClient(config.ApiKey);
            }

            if (!(string.IsNullOrEmpty(config.ClientId) || string.IsNullOrEmpty(config.ClientSecret)))
            {
                tokenClient = new OAuthTokenClient(config.DefaultAuthEndpoint, config.AuthEndpoints,
                                                   config.EnvironmentId, config.ClientId, config.ClientSecret, _httpClient);
            }


            s_helper.Check <StorageClientException>(tokenClient == null, Messages.Storage.s_errNullCredentials);
            _cryptoProvider = config.CryptoProvider;
            if (config.CryptoProvider == null)
            {
                _cryptoProvider = new CryptoProvider();
            }

            _cryptoProvider.ValidateCustomCiphers(config.SecretKeyAccessor?.Invoke());
            _hashUtils   = new HashUtils(config.EnvironmentId, config.NormalizeKeys, Encoding.UTF8);
            _transformer = new DtoTransformer(_cryptoProvider, _hashUtils, config.HashSearchKeys,
                                              config.SecretKeyAccessor);
            _dao = HttpDao.NewDao(config.EnvironmentId, tokenClient, _httpClient, config.EndPoint, config.EndpointMask,
                                  config.CountriesEndPoint);
        }
示例#11
0
        public async Task AuthorisationRetryTest()
        {
            const string tokenValue1    = "12345";
            const string tokenResponse1 =
                "{'access_token':'" + tokenValue1 + "' , 'expires_in':'300' , 'token_type':'bearer', 'scope':'" +
                EnvId +
                "'}";
            const string tokenValue2    = "67890";
            const string tokenResponse2 =
                "{'access_token':'" + tokenValue2 + "' , 'expires_in':'300' , 'token_type':'bearer', 'scope':'" +
                EnvId +
                "'}";
            var server = new FakeHttpServer(Port,
                                            new[]
            {
                new FakeHttpServerResponse(200, tokenResponse1),
                new FakeHttpServerResponse(401, "Unauthorized"),
                new FakeHttpServerResponse(200, tokenResponse2), new FakeHttpServerResponse(201, "OK")
            });

            using var httpClient = new HttpClient();
            server.Start();
            var tokenClient = new OAuthTokenClient(s_endpoint, null, EnvId, "clientId", "clientSecret", httpClient);

            using var dao = HttpDao.NewDao(EnvId, tokenClient, httpClient, s_endpoint, ".localhost:" + Port,
                                           s_endpoint);
            const string country = "us";
            await dao.CreateRecordAsync(country, new TransferRecord("recordKey")).ConfigureAwait(false);

            var finalToken = await tokenClient
                             .RefreshTokenAsync(false, s_endpoint + " https://" + country + ".localhost:" + Port, "emea")
                             .ConfigureAwait(false);

            Assert.AreEqual(tokenValue2, finalToken);
            server.Stop();
        }
            protected override void Act()
            {
                var input = new OAuthTokenClient[0];

                Result = ApiClientDetails.Create(input);
            }
示例#13
0
        public void TokenWrongResponseTest()
        {
            const string tokenResponse1 = "{'access_token':'" +
                                          "' , 'expires_in':'300' , 'token_type':'bearer', 'scope':'" + EnvId + "'}";

            const string tokenResponse2 = "{'access_token':'2222222222'" +
                                          ", 'expires_in':'-1' , 'token_type':'bearer', 'scope':'" + EnvId + "'}";

            const string tokenResponse3 = "{'access_token':'3333333333'" +
                                          ", 'expires_in':'300' , 'token_type':'NotBearer', 'scope':'" + EnvId + "'}";

            const string tokenResponse4 = "{'access_token':'3333333333'" +
                                          ", 'expires_in':'300' , 'token_type':'bearer', 'scope':'" + EnvId + EnvId +
                                          "'}";

            const string tokenResponse5 = "{StringNotJson:";

            var server = new FakeHttpServer(Port,
                                            new[]
            {
                new FakeHttpServerResponse(200, tokenResponse1),
                new FakeHttpServerResponse(200, tokenResponse2),
                new FakeHttpServerResponse(200, tokenResponse3),
                new FakeHttpServerResponse(200, tokenResponse4),
                new FakeHttpServerResponse(200, tokenResponse5)
            });

            server.Start();
            using var httpClient = new HttpClient();
            var tokenClient =
                new OAuthTokenClient(s_defaultAuthEndpoint, null, EnvId, ClientId, ClientSecret, httpClient);
            var exception = Assert.ThrowsAsync <StorageServerException>(async() =>
            {
                var unused = await tokenClient.RefreshTokenAsync(false, Audience, Emea).ConfigureAwait(false);
            });

            Assert.AreEqual("Token is null", exception.Message);

            exception = Assert.ThrowsAsync <StorageServerException>(async() =>
            {
                var unused = await tokenClient.RefreshTokenAsync(false, Audience, Emea).ConfigureAwait(false);
            });
            Assert.AreEqual("Token TTL is invalid", exception.Message);

            exception = Assert.ThrowsAsync <StorageServerException>(async() =>
            {
                var unused = await tokenClient.RefreshTokenAsync(false, Audience, Emea).ConfigureAwait(false);
            });
            Assert.AreEqual("Token type is invalid", exception.Message);

            exception = Assert.ThrowsAsync <StorageServerException>(async() =>
            {
                var unused = await tokenClient.RefreshTokenAsync(false, Audience, Emea).ConfigureAwait(false);
            });
            Assert.AreEqual("Token scope is invalid", exception.Message);

            exception = Assert.ThrowsAsync <StorageServerException>(async() =>
            {
                var unused = await tokenClient.RefreshTokenAsync(false, Audience, Emea).ConfigureAwait(false);
            });
            Assert.AreEqual("Error in parsing authorization response: '{StringNotJson:'", exception.Message);
            server.Stop();
        }