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));
        }
    }
Beispiel #3
0
        private void EmptyMessagesCollectionIsNotAddedToMessagesCollection()
        {
            var ex = new UnauthorizedException();

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

            ex.AddMessages(null);
            Assert.Empty(ex.Messages);
        }
Beispiel #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);
 }
Beispiel #7
0
        private void NullMessageWithValidKeyIsNotAddedToMessagesCollection()
        {
            var ex = new UnauthorizedException();

            ex.AddMessage("aKey", null);
            Assert.Equal(0, ex.Messages.Count);
        }
Beispiel #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
                },
            },
Beispiel #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());
                });
            });
        }
Beispiel #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
     });
Beispiel #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);
        }
Beispiel #13
0
        private void PropertiesAreDefaulted()
        {
            var ex = new UnauthorizedException();

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

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

            ex.AddMessages("Key1", new string[0]);
            Assert.Equal(0, ex.Messages.Count);
        }
Beispiel #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);
        }
Beispiel #17
0
        public void UnauthorizedException_WhenCreateWithContent_ShouldBeMessage(string content)
        {
            // Act
            var sut = new UnauthorizedException(content);

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

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

            // Assert
            sut.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
        }
Beispiel #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);
        }
        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);
        }
Beispiel #22
0
        private void CodeIsSet()
        {
            string code = "NOACC1";

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

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

            ex.AddMessage(null);
            ex.AddMessage(string.Empty);
            Assert.Equal(0, ex.Messages.Count);
        }
        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);
        }
        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);
        }
Beispiel #26
0
        public void AuthenticateWithThrowsUnauthenticatedExceptionWhenLoginUnsuccessful()
        {
            UserConfig userConfig = new UserConfig(null, null, null);

            SetServerResponse("unauthenticated");

            UnauthorizedException ex = Assert.ThrowsAsync <UnauthorizedException>(async() =>
                                                                                  await endPoint.AuthenticateWith(userConfig));
        }
Beispiel #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));
        }
Beispiel #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);
        }
Beispiel #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);
        }
 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);
        }