public async void PexaApiTokenOtherKeyVaultExceptionThrows()
        {
            var query = new PexaApiTokenQuery()
            {
                AuthenticatedUser = new WCAUser()
            };

            var keyVaultErrorException = new KeyVaultErrorException();

            using (var pexaTestKeyVaultClient = new PexaTestKeyVaultClient(keyVaultErrorException))
                using (var memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions())))
                {
                    var handlerUnderTest = new PexaApiTokenQueryHandler(
                        pexaTestKeyVaultClient,
                        new PexaApiTokenQuery.Validator(),
                        memoryCache,
                        Options.Create(new WCACoreSettings()
                    {
                        CredentialAzureKeyVaultUrl = "https://dummy"
                    }));

                    await Assert.ThrowsAsync <KeyVaultErrorException>(async() =>
                    {
                        var result = await handlerUnderTest.Handle(query, new CancellationToken());
                    });
                }
        }
Esempio n. 2
0
 private static void TryHandleException(KeyVaultErrorException ex)
 {
     if (IsNotFound(ex))
     {
         throw new StorageException(ErrorCode.NotFound, ex);
     }
 }
        public async void PexaApiTokenForbiddenReturnsNull()
        {
            var query = new PexaApiTokenQuery()
            {
                AuthenticatedUser = new WCAUser()
            };

            using (var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Forbidden))
            {
                var keyVaultErrorException = new KeyVaultErrorException()
                {
                    Response = new HttpResponseMessageWrapper(httpResponseMessage, null)
                };

                using (var pexaTestKeyVaultClient = new PexaTestKeyVaultClient(keyVaultErrorException))
                    using (var memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions())))
                    {
                        var handlerUnderTest = new PexaApiTokenQueryHandler(
                            pexaTestKeyVaultClient,
                            new PexaApiTokenQuery.Validator(),
                            memoryCache,
                            Options.Create(new WCACoreSettings()
                        {
                            CredentialAzureKeyVaultUrl = "https://dummy"
                        }));

                        var result = await handlerUnderTest.Handle(query, new CancellationToken());

                        Assert.Null(result);
                    }
            }
        }
        private static bool TryHandleException(KeyVaultErrorException ex)
        {
            if (IsNotFound(ex))
            {
                throw new StorageException(ErrorCode.NotFound, ex);
            }

            return(false);
        }
        private static bool TryHandleException(KeyVaultErrorException ex)
        {
            if (ex.Body.Error.Code == "SecretNotFound")
            {
                throw new StorageException(ErrorCode.NotFound, ex);
            }

            return(false);
        }
        private KeyVaultErrorException GetKeyVaultError(HttpStatusCode statusCode)
        {
            var responseMessage = new HttpResponseMessage(statusCode);

            var exception = new KeyVaultErrorException();

            exception.Response = new HttpResponseMessageWrapper(responseMessage, content: ResponseContent);

            return(exception);
        }
        // Given a KeyVaultErrorException, this will determine what status code we will
        // return to the caller. We will forward status codes related to unauhtorized
        // and return 500 for the rest.
        private HttpStatusCode GetResponseStatusCode(KeyVaultErrorException kve)
        {
            if (kve.Response == null)
            {
                return(HttpStatusCode.InternalServerError);
            }

            if (kve.Response.StatusCode == HttpStatusCode.Unauthorized || kve.Response.StatusCode == HttpStatusCode.Forbidden)
            {
                return(kve.Response.StatusCode);
            }

            // return 500 by default.
            return(HttpStatusCode.InternalServerError);
        }
        public async Task GivenKeyVaultSecretStore_WhenDeletingSecretThrowsKeyVaultErrorExceptionWithNoResponse_ThenExceptionWillBeThrownWithInternalServerErrorStatusCode()
        {
            _retryCount  = 0;
            _secretStore = GetSecretStore(_retryCount);
            KeyVaultErrorException exception = new KeyVaultErrorException();

            _kvClient.DeleteSecretWithHttpMessagesAsync(_keyVaultUri.AbsoluteUri, SecretName, customHeaders: null, _cancellationToken)
            .Returns <AzureOperationResponse <DeletedSecretBundle> >(
                _ => throw exception);

            SecretStoreException sse = await Assert.ThrowsAsync <SecretStoreException>(() => _secretStore.DeleteSecretAsync(SecretName, _cancellationToken));

            Assert.NotNull(sse);
            Assert.Equal(HttpStatusCode.InternalServerError, sse.ResponseStatusCode);
        }
        public async Task GivenKeyVaultSecretStore_WhenDeletingSecretThrowsKeyVaultErrorExceptionWithNonRetriableStatusCode_ThenItWillNotBeRetried(HttpStatusCode statusCode)
        {
            _retryCount  = 3;
            _secretStore = GetSecretStore(_retryCount);

            var successfulResult             = GetSuccessfulDeletedResult();
            KeyVaultErrorException exception = GetKeyVaultError(statusCode);

            _kvClient.DeleteSecretWithHttpMessagesAsync(_keyVaultUri.AbsoluteUri, SecretName, customHeaders: null, _cancellationToken)
            .Returns <AzureOperationResponse <DeletedSecretBundle> >(
                _ => throw exception,
                _ => successfulResult);

            await Assert.ThrowsAsync <SecretStoreException>(() => _secretStore.DeleteSecretAsync(SecretName, _cancellationToken));
        }
        public async Task GivenKeyVaultSecretStore_WhenSettingSecretThrowsKeyVaultErrorException_ThenExceptionWillBeThrownWithAppropriateStatusCode(HttpStatusCode keyVaultStatusCode, HttpStatusCode expectedStatusCode)
        {
            _retryCount  = 0;
            _secretStore = GetSecretStore(_retryCount);
            KeyVaultErrorException exception = GetKeyVaultError(keyVaultStatusCode);

            _kvClient.SetSecretWithHttpMessagesAsync(_keyVaultUri.AbsoluteUri, SecretName, SecretValue, tags: null, contentType: null, secretAttributes: null, customHeaders: null, _cancellationToken)
            .Returns <AzureOperationResponse <SecretBundle> >(
                _ => throw exception);

            SecretStoreException sse = await Assert.ThrowsAsync <SecretStoreException>(() => _secretStore.SetSecretAsync(SecretName, SecretValue, _cancellationToken));

            Assert.NotNull(sse);
            Assert.Equal(expectedStatusCode, sse.ResponseStatusCode);
        }
        public async Task GivenKeyVaultSecretStore_WhenGettingSecretThrowsKeyVaultErrorExceptionWithRetriableStatusCodeForMaxRetryCount_ThenExceptionWillBeThrown()
        {
            _retryCount  = 1;
            _secretStore = GetSecretStore(_retryCount);

            var successfulResult             = GetSuccessfulResult();
            KeyVaultErrorException exception = GetKeyVaultError(HttpStatusCode.ServiceUnavailable);

            _kvClient.GetSecretWithHttpMessagesAsync(_keyVaultUri.AbsoluteUri, SecretName, secretVersion: string.Empty, customHeaders: null, _cancellationToken)
            .Returns <AzureOperationResponse <SecretBundle> >(
                _ => throw exception,
                _ => throw exception,
                _ => successfulResult);

            await Assert.ThrowsAsync <SecretStoreException>(() => _secretStore.GetSecretAsync(SecretName, _cancellationToken));
        }
        public async Task GivenKeyVaultSecretStore_WhenGettingSecretThrowsKeyVaultErrorExceptionWithRetriableStatusCode_ThenItWillBeRetried(HttpStatusCode statusCode)
        {
            _retryCount  = 3;
            _secretStore = GetSecretStore(_retryCount);

            var successfulResult             = GetSuccessfulResult();
            KeyVaultErrorException exception = GetKeyVaultError(statusCode);

            _kvClient.GetSecretWithHttpMessagesAsync(_keyVaultUri.AbsoluteUri, SecretName, secretVersion: string.Empty, customHeaders: null, _cancellationToken)
            .Returns <AzureOperationResponse <SecretBundle> >(
                _ => throw exception,
                _ => successfulResult);

            var result = await _secretStore.GetSecretAsync(SecretName, _cancellationToken);

            Assert.Equal(SecretValue, result.SecretValue);
        }
 private static bool IsNotFound(KeyVaultErrorException ex)
 {
     return(ex.Body.Error.Code == "SecretNotFound");
 }
 public PexaTestKeyVaultClient(KeyVaultErrorException keyVaultErrorException)
 {
     _keyVaultErrorException = keyVaultErrorException;
 }
Esempio n. 15
0
        /// <summary>
        /// Gets the pending certificate signing request response.
        /// </summary>
        /// <param name='vaultBaseUrl'>
        /// The vault name, e.g. https://myvault.vault.azure.net
        /// </param>
        /// <param name='certificateName'>
        /// The name of the certificate
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <string> > GetPendingCertificateSigningRequestWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (vaultBaseUrl == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "vaultBaseUrl");
            }
            if (certificateName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
            }
            if (this.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("vaultBaseUrl", vaultBaseUrl);
                tracingParameters.Add("certificateName", certificateName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetPendingCertificateSigningRequest", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "certificates/{certificate-name}/pending";

            _url = _url.Replace("{vaultBaseUrl}", vaultBaseUrl);
            _url = _url.Replace("{certificate-name}", Uri.EscapeDataString(certificateName));
            List <string> _queryParameters = new List <string>();

            if (this.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage  _httpRequest  = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            _httpRequest.Headers.Add("Accept", "application/pkcs10");

            // Set Headers
            if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
            }
            if (this.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new KeyVaultErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    KeyVaultError _errorBody = SafeJsonConvert.DeserializeObject <KeyVaultError>(_responseContent, this.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <string>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _result.Body = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }