async Task ProcessConnectAckAsync(IChannelHandlerContext context, ConnAckPacket packet)
        {
            if (packet.ReturnCode != ConnectReturnCode.Accepted)
            {
                string reason          = "CONNECT failed: " + packet.ReturnCode;
                var    iotHubException = new UnauthorizedException(reason);
                ShutdownOnError(context, iotHubException);
                return;
            }

            if (!this.IsInState(StateFlags.Connecting))
            {
                string reason          = "CONNECT has been received, however a session has already been established. Only one CONNECT/CONNACK pair is expected per session.";
                var    iotHubException = new IotHubException(reason);
                ShutdownOnError(context, iotHubException);
                return;
            }

            this.stateFlags = StateFlags.Connected;

            this.mqttIotHubEventHandler.OnConnected();

            this.ResumeReadingIfNecessary(context);

            if (packet.SessionPresent)
            {
                await this.SubscribeAsync(context, null);
            }
        }
        private Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            _logger.LogError(
                $"Error while processing request {context.Request.Method} {context.Request.Path}: {ex.Message}");
            if (ex is AutoMapperMappingException mappingException && mappingException.InnerException != null)
            {
                ex = mappingException.InnerException;
            }
            var code = ex switch
            {
                ArgumentException _ => HttpStatusCode.BadRequest,
                BadDataException _ => HttpStatusCode.BadRequest,
                DataChangedException _ => HttpStatusCode.BadRequest,
                ForbiddenException _ => HttpStatusCode.Forbidden,
                InfrastructureException _ => HttpStatusCode.InternalServerError,
                InvalidDataException _ => HttpStatusCode.BadRequest,
                NotFoundException _ => HttpStatusCode.NotFound,
                UnauthorizedException _ => HttpStatusCode.Unauthorized,
                _ => HttpStatusCode.InternalServerError
            };

            var result = JsonSerializer.Serialize(new { error = ex.Message });

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            return(context.Response.WriteAsync(result));
        }
    }
Exemplo n.º 3
0
        private void EmptyMessagesCollectionIsNotAddedToMessagesCollection()
        {
            var ex = new UnauthorizedException();

            ex.AddMessages(new string[0]);
            Assert.Empty(ex.Messages);
        }
Exemplo n.º 4
0
        private void NullMessagesCollectionIsNotAddedToMessagesCollection()
        {
            var ex = new UnauthorizedException();

            ex.AddMessages(null);
            Assert.Empty(ex.Messages);
        }
Exemplo n.º 5
0
 public UnauthorizedProblemDetails(UnauthorizedException exception)
 {
     this.Title  = exception.Message;
     this.Status = StatusCodes.Status403Forbidden;
     this.Detail = exception.Details;
     this.Type   = "https://httpstatuses.com/" + this.Status;
 }
 protected virtual void CreateUnauthorizedMap(Error error, UnauthorizedException exception)
 {
     error.Title           = Defaults.UnauthorizedException.Title;
     error.Code            = exception.Code;
     error.Status          = (int)HttpStatusCode.Unauthorized;
     error.ExtraParameters = exception.Messages.ToDictionary(ms => ms.Key, ms => ms.Value);
 }
Exemplo n.º 7
0
        private void NullMessageWithValidKeyIsNotAddedToMessagesCollection()
        {
            var ex = new UnauthorizedException();

            ex.AddMessage("aKey", null);
            Assert.Equal(0, ex.Messages.Count);
        }
Exemplo n.º 8
0
        internal static IActionResult ErrorResult <TModel>(BaseException exception)
        {
            switch (exception)
            {
            case ForbiddenException _:
            case NotFoundException _:
            case UnauthorizedException _:
                LogWarning <TModel>("A warning has occurred.", exception);
                break;

            default:
                LogError <TModel>("An error has occurred.", exception);
                break;
            }

            var @try = HandleException <TModel>(exception);

            return(@try.Match(
                       failure => failure switch
            {
                InvalidRequestException _ => new BadRequestObjectResult(@try),
                ForbiddenException _ => new ObjectResult(@try)
                {
                    StatusCode = 403
                },
                NotFoundException _ => new NotFoundObjectResult(@try),
                AlreadyExistsException _ => new ConflictObjectResult(@try),
                UnauthorizedException _ => new UnauthorizedObjectResult(@try),
                InvalidObjectException _ => new UnprocessableEntityObjectResult(@try),
                _ => new ObjectResult(@try)
                {
                    StatusCode = 500
                },
            },
Exemplo n.º 9
0
        public static void ConfigureExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(error =>
            {
                error.Run(async context =>
                {
                    var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>();
                    var exception = exceptionHandlerFeature.Error;

                    var statusCode = exception switch
                    {
                        ResourceNotFoundException _ => (int)HttpStatusCode.NotFound,
                        ModelFormatException _ => (int)HttpStatusCode.PreconditionFailed,
                        ResourceAlreadyExistsException _ => (int)HttpStatusCode.Conflict,
                        InvalidLoginException _ => (int)HttpStatusCode.Unauthorized,
                        UnauthorizedException _ => (int)HttpStatusCode.Unauthorized,
                        InvalidProductIdentifierException _ => (int)HttpStatusCode.PreconditionFailed,
                        _ => (int)HttpStatusCode.InternalServerError
                    };

                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode  = statusCode;

                    await context.Response.WriteAsync(new ExceptionModel
                    {
                        StatusCode = statusCode,
                        Message    = exception.Message
                    }.ToString());
                });
            });
        }
Exemplo n.º 10
0
        private void MessageIsSet()
        {
            var ex = new UnauthorizedException("access denied");

            Assert.Equal("access denied", ex.Message);
            Assert.NotNull(ex.Messages);
        }
 static bool IsExceptionTransient(Exception exception)
 {
     return(exception switch
     {
         UnauthorizedException _ => false,
         _ => true
     });
Exemplo n.º 12
0
        private Exception CreateUnauthorizedException(List <string> targetSubscriptions)
        {
            UnauthorizedException unauthorizedException;

            switch (_azureAuthenticationInfo.Mode)
            {
            case AuthenticationMode.ServicePrincipal:
                unauthorizedException = new UnauthorizedException(QueryIdentityId, targetSubscriptions);
                _logger.LogCritical(unauthorizedException, "Unable to query Azure Resource Graph using the Service Principal");

                break;

            case AuthenticationMode.UserAssignedManagedIdentity:
                unauthorizedException = new UnauthorizedException(QueryIdentityId, targetSubscriptions);
                _logger.LogCritical(unauthorizedException, "Unable to query Azure Resource Graph using the User Managed Identity");

                break;

            case AuthenticationMode.SystemAssignedManagedIdentity:
                unauthorizedException = new UnauthorizedException("System Assigned Identity", targetSubscriptions);
                _logger.LogCritical(unauthorizedException, "Unable to query Azure Resource Graph using the System Assigned Identity");

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(_azureAuthenticationInfo.Mode), _azureAuthenticationInfo.Mode, "Authentication was forbidden");
            }

            return(unauthorizedException);
        }
Exemplo n.º 13
0
        private void PropertiesAreDefaulted()
        {
            var ex = new UnauthorizedException();

            Assert.Equal(Defaults.UnauthorizedException.Title, ex.Message);
            Assert.NotNull(ex.Messages);
        }
Exemplo n.º 14
0
        private void NullKeyThrowsArgumentNullException()
        {
            var ex     = new UnauthorizedException();
            var result = Assert.Throws <ArgumentNullException>(() => ex.AddMessage(null, "aMessage"));

            Assert.Equal("key", result.ParamName);
        }
Exemplo n.º 15
0
        private void EmptyMessagesCollectionWithKeyIsNotAddedToMessagesCollection()
        {
            var ex = new UnauthorizedException();

            ex.AddMessages("Key1", new string[0]);
            Assert.Equal(0, ex.Messages.Count);
        }
Exemplo n.º 16
0
        private void MessageAndInnerExceptionAreSetInProperties()
        {
            var innerEx = new Exception("innerMessage");
            var ex      = new UnauthorizedException("access denied", "NOACC1", innerEx);

            Assert.Equal("access denied", ex.Message);
            Assert.Same(innerEx, ex.InnerException);
        }
Exemplo n.º 17
0
        public void UnauthorizedException_WhenCreateWithContent_ShouldBeMessage(string content)
        {
            // Act
            var sut = new UnauthorizedException(content);

            // Assert
            sut.Message.Should().Be(content);
        }
Exemplo n.º 18
0
        public void UnauthorizedException_WhenCreateWithoutParams_ShouldReturnApiError()
        {
            // Act
            var sut = new UnauthorizedException();

            // Assert
            sut.ApiError.Should().NotBeNull();
        }
Exemplo n.º 19
0
        public void UnauthorizedException_WhenCreate_ShouldReturnStatusCode()
        {
            // Act
            var sut = new UnauthorizedException();

            // Assert
            sut.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
        }
Exemplo n.º 20
0
        protected override void CreateUnauthorizedMap(Error error, UnauthorizedException exception)
        {
            base.CreateUnauthorizedMap(error, exception);
            error.Identifier = GetIdentifier();
            SetErrorTypeReferenceUri(error);

            _logger.LogWarning($"Access denied: {exception.Message}", exception);
        }
Exemplo n.º 21
0
        private void ErrorIsSet()
        {
            var error = new Error("id");
            var ex    = new UnauthorizedException(error);

            Assert.Equal(Defaults.UnauthorizedException.Message, ex.Message);
            Assert.Same(error, ex.Error);
        }
Exemplo n.º 22
0
        private void CodeIsSet()
        {
            string code = "NOACC1";

            var ex = new UnauthorizedException("access denied", code);

            Assert.Equal(code, ex.Code);
        }
Exemplo n.º 23
0
        private void NullMessagesOnlyIsNotAddedToMessagesCollection()
        {
            var ex = new UnauthorizedException();

            ex.AddMessage(null);
            ex.AddMessage(string.Empty);
            Assert.Equal(0, ex.Messages.Count);
        }
Exemplo n.º 24
0
        private void PropertiesAreDefaulted()
        {
            var ex = new UnauthorizedException();

            Assert.Equal(Defaults.UnauthorizedException.Message, ex.Message);
            Assert.NotNull(ex.Error);
            Assert.Equal(1, ex.Error.Messages.Count());
            Assert.Equal(Defaults.UnauthorizedException.Message, ex.Error.Messages.First().Message);
        }
Exemplo n.º 25
0
        private void MessageIsSet()
        {
            var ex = new UnauthorizedException("access denied");

            Assert.Equal("access denied", ex.Message);
            Assert.NotNull(ex.Error);
            Assert.Equal(1, ex.Error.Messages.Count());
            Assert.Equal("access denied", ex.Error.Messages.First().Message);
        }
Exemplo n.º 26
0
        public void AuthenticateWithThrowsUnauthenticatedExceptionWhenLoginUnsuccessful()
        {
            UserConfig userConfig = new UserConfig(null, null, null);

            SetServerResponse("unauthenticated");

            UnauthorizedException ex = Assert.ThrowsAsync <UnauthorizedException>(async() =>
                                                                                  await endPoint.AuthenticateWith(userConfig));
        }
Exemplo n.º 27
0
        private void DefaultEmptyKeyAddsToCollection()
        {
            var ex = new UnauthorizedException();

            ex.AddMessage(Defaults.ErrorMessage.Key, "aMessage");

            Assert.Equal(1, ex.Messages.Count);
            Assert.Contains("aMessage", ex.Messages.First().Value);
        }
        public void SetsTheUnauthorizedAccessFlag()
        {
            var exception = new UnauthorizedException(request, response);

            errorHandlingService.TryHandleUnauthorizedError(Arg.Any <UnauthorizedException>()).Returns(true);

            errorsSubject.OnNext(exception);

            errorHandlingService.Received().TryHandleUnauthorizedError(Arg.Is(exception));
        }
Exemplo n.º 29
0
        private void MessageIsAddedToMessagesCollectionWithDefaultKey()
        {
            var ex = new UnauthorizedException();

            ex.AddMessage("aMessage");

            Assert.Equal(1, ex.Messages.Count);
            Assert.Contains("aMessage", ex.Messages.First().Value);
            Assert.Equal(Defaults.ErrorMessage.Key, ex.Messages.First().Key);
        }
Exemplo n.º 30
0
        private void KeyAndMessageAreAddedToMessagesCollection()
        {
            var ex = new UnauthorizedException();

            ex.AddMessage("aKey", "aMessage");

            Assert.Equal(1, ex.Messages.Count);
            Assert.Equal("aKey", ex.Messages.First().Key);
            Assert.Contains("aMessage", ex.Messages.First().Value);
        }
Exemplo n.º 31
0
 protected void CheckFileUploadStatus(string response)
 {
     UploadInfo info = DeserializeUploadResponse(response);
     if (info != null)
     {
         string errorMessage = HttpUtility.HtmlDecode(info.ErrorMessage);
         HttpUploadCode code = (HttpUploadCode) info.StatusCode;
         switch (code)
         {
             case HttpUploadCode.Ok:
                 {
                     break;
                 }
             case HttpUploadCode.Unauthorized:
                 {
                     Exception = new UnauthorizedException(errorMessage);
                     break;
                 }
             case HttpUploadCode.NotFound:
                 {
                     Exception = new FileNotFoundException(errorMessage);
                     break;
                 }
             case HttpUploadCode.FileExists:
                 {
                     Exception = new FileExistsException(errorMessage);
                     break;
                 }
             case HttpUploadCode.BlockedFile:
                 {
                     Exception = new FileBlockedException(errorMessage);
                     break;
                 }
             case HttpUploadCode.FileLocked:
                 {
                     Exception = new FileLockedException(errorMessage);
                     break;
                 }
             case HttpUploadCode.DeleteFailed:
                 {
                     Exception = new DeleteFailedException(errorMessage);
                     break;
                 }
             default:
                 {
                     Exception = new UploadException(string.Format(CultureInfo.InvariantCulture, "Invalid status code : {0}", code));
                     break;
                 }
         }
     }
 }
        public async Task ExpireAlreadyExpiredAdvertisement()
        {
            var advertisementId = new Guid("c294088d-ff50-4374-bc38-7fa805790e3e");
            OAuth2Token oAuth2Token = new OAuth2TokenBuilder().Build();
            var link = $"{AdvertisementLink}/{advertisementId}";

            this.Fixture.AdPostingApiService
                .Given("There is an expired advertisement")
                .UponReceiving("a PATCH advertisement request to expire an advertisement")
                .With(
                    new ProviderServiceRequest
                    {
                        Method = HttpVerb.Patch,
                        Path = link,
                        Headers = new Dictionary<string, string>
                        {
                            { "Authorization", "Bearer " + oAuth2Token.AccessToken },
                            { "Content-Type", RequestContentTypes.AdvertisementPatchVersion1 },
                            { "Accept", this._acceptHeader },
                            { "User-Agent", AdPostingApiFixture.UserAgentHeaderValue }
                        },
                        Body = new[]
                        {
                            new
                            {
                                op = "replace",
                                path = "state",
                                value = AdvertisementState.Expired.ToString()
                            }
                        }
                    }
                )
                .WillRespondWith(
                    new ProviderServiceResponse
                    {
                        Status = 403,
                        Headers = new Dictionary<string, string>
                        {
                            { "Content-Type", ResponseContentTypes.AdvertisementErrorVersion1 },
                            { "X-Request-Id", RequestId }
                        },
                        Body = new
                        {
                            message = "Forbidden",
                            errors = new[] { new { code = "Expired" } }
                        }
                    });

            UnauthorizedException actualException;

            using (AdPostingApiClient client = this.Fixture.GetClient(oAuth2Token))
            {
                actualException = await Assert.ThrowsAsync<UnauthorizedException>(
                    async () => await client.ExpireAdvertisementAsync(new Uri(this.Fixture.AdPostingApiServiceBaseUri, link)));
            }

            var expectedException =
                new UnauthorizedException(
                    RequestId,
                    403,
                    new AdvertisementErrorResponse
                    {
                        Message = "Forbidden",
                        Errors = new[] { new AdvertisementError { Code = "Expired" } }
                    });

            actualException.ShouldBeEquivalentToException(expectedException);
        }