コード例 #1
0
        public void Authenticate_should_throw_an_AuthenticationException_when_authentication_fails(
            [Values(false, true)] bool async)
        {
            var credential = new UsernamePasswordCredential("$external", "permanentuser", "FAKEFAKEFAKEFAKEFAKEfakefakefakefakefake");
            var subject    = new MongoAWSAuthenticator(credential, properties: null, serverApi: null);

            var commandResponse = MessageHelper.BuildCommandResponse(RawBsonDocumentHelper.FromJson("{ }")); // return no documents
            var connection      = new MockConnection(__serverId);

            connection.EnqueueCommandResponseMessage(commandResponse);
            connection.Description = __descriptionCommandWireProtocol;

            Exception exception;

            if (async)
            {
                exception = Record.Exception(() => subject.AuthenticateAsync(connection, __descriptionCommandWireProtocol, CancellationToken.None).GetAwaiter().GetResult());
            }
            else
            {
                exception = Record.Exception(() => subject.Authenticate(connection, __descriptionCommandWireProtocol, CancellationToken.None));
            }

            exception.Should().BeOfType <MongoAuthenticationException>();
        }
コード例 #2
0
        public void Authenticate_should_throw_when_server_provides_unexpected_field(
            [Values(false, true)] bool async)
        {
            var clientNonce = __randomByteGenerator.Generate(ClientNonceLength);
            var serverNonce = Combine(clientNonce, __randomByteGenerator.Generate(ClientNonceLength));
            var host        = "sts.amazonaws.com";
            var credential  = new UsernamePasswordCredential("$external", "permanentuser", "FAKEFAKEFAKEFAKEFAKEfakefakefakefakefake");

            var mockRandomByteGenerator = new Mock <IRandomByteGenerator>();

            mockRandomByteGenerator.Setup(x => x.Generate(It.IsAny <int>())).Returns(clientNonce);

            var serverFirstMessage = new BsonDocument
            {
                { "s", serverNonce },
                { "h", host },
                { "u", "unexpected" }
            };

            var saslStartCommandResponse = MessageHelper.BuildCommandResponse(RawBsonDocumentHelper.FromJson(
                                                                                  $"{{ conversationId : 1, done : false, payload : BinData(0,\"{ToBase64(serverFirstMessage.ToBson())}\"), ok : 1 }}"));
            var saslContinueCommandResponse = MessageHelper.BuildCommandResponse(RawBsonDocumentHelper.FromJson(
                                                                                     "{ conversationId : 1, done : true, payload : BinData(0,\"\"), ok : 1}"));

            var subject = new MongoAWSAuthenticator(credential, null, mockRandomByteGenerator.Object, SystemClock.Instance, serverApi: null);

            var connection = new MockConnection(__serverId);

            connection.EnqueueCommandResponseMessage(saslStartCommandResponse);
            connection.EnqueueCommandResponseMessage(saslContinueCommandResponse);
            connection.Description = __descriptionCommandWireProtocol;

            Exception exception;

            if (async)
            {
                exception = Record.Exception(() => subject.AuthenticateAsync(connection, __descriptionCommandWireProtocol, CancellationToken.None).GetAwaiter().GetResult());
            }
            else
            {
                exception = Record.Exception(() => subject.Authenticate(connection, __descriptionCommandWireProtocol, CancellationToken.None));
            }

            exception.Should().BeOfType <MongoAuthenticationException>();
            exception.Message.Should().Be("Server returned unexpected fields: u.");
        }
コード例 #3
0
        public void Authenticate_should_throw_when_server_provides_invalid_host(
            [Values("", "abc..def")] string host,
            [Values(false, true)] bool async)
        {
            var clientNonce = __randomByteGenerator.Generate(ClientNonceLength);
            var serverNonce = Combine(clientNonce, __randomByteGenerator.Generate(ClientNonceLength));
            var credential  = new UsernamePasswordCredential("$external", "permanentuser", "FAKEFAKEFAKEFAKEFAKEfakefakefakefakefake");

            var mockRandomByteGenerator = new Mock <IRandomByteGenerator>();

            mockRandomByteGenerator.Setup(x => x.Generate(It.IsAny <int>())).Returns(clientNonce);

            var serverFirstMessage = new BsonDocument
            {
                { "s", serverNonce },
                { "h", host },
            };

            var saslStartReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                $"{{ conversationId : 1, done : false, payload : BinData(0,\"{ToBase64(serverFirstMessage.ToBson())}\"), ok : 1 }}"));
            var saslContinueReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                   "{ conversationId : 1, done : true, payload : BinData(0,\"\"), ok : 1}"));

            var subject = new MongoAWSAuthenticator(credential, null, mockRandomByteGenerator.Object, SystemClock.Instance);

            var connection = new MockConnection(__serverId);

            connection.EnqueueReplyMessage(saslStartReply);
            connection.EnqueueReplyMessage(saslContinueReply);

            Exception exception;

            if (async)
            {
                exception = Record.Exception(() => subject.AuthenticateAsync(connection, __connectionDescription, CancellationToken.None).GetAwaiter().GetResult());
            }
            else
            {
                exception = Record.Exception(() => subject.Authenticate(connection, __connectionDescription, CancellationToken.None));
            }

            exception.Should().BeOfType <MongoAuthenticationException>();
            exception.Message.Should().Be("Server returned an invalid sts host.");
        }
コード例 #4
0
        public void Authenticate_should_throw_an_AuthenticationException_when_authentication_fails(
            [Values(false, true)] bool async)
        {
            var credential = new UsernamePasswordCredential("$external", "permanentuser", "FAKEFAKEFAKEFAKEFAKEfakefakefakefakefake");
            var subject    = new MongoAWSAuthenticator(credential, null);

            var reply      = MessageHelper.BuildNoDocumentsReturnedReply <RawBsonDocument>();
            var connection = new MockConnection(__serverId);

            connection.EnqueueReplyMessage(reply);

            Exception exception;

            if (async)
            {
                exception = Record.Exception(() => subject.AuthenticateAsync(connection, __connectionDescription, CancellationToken.None).GetAwaiter().GetResult());
            }
            else
            {
                exception = Record.Exception(() => subject.Authenticate(connection, __connectionDescription, CancellationToken.None));
            }

            exception.Should().BeOfType <MongoAuthenticationException>();
        }
コード例 #5
0
        public void Authenticate_should_have_expected_result(
            [Values(false, true)] bool async)
        {
            var dateTime    = DateTime.UtcNow;
            var clientNonce = __randomByteGenerator.Generate(ClientNonceLength);
            var serverNonce = Combine(clientNonce, __randomByteGenerator.Generate(ClientNonceLength));
            var host        = "sts.amazonaws.com";
            var credential  = new UsernamePasswordCredential("$external", "permanentuser", "FAKEFAKEFAKEFAKEFAKEfakefakefakefakefake");

            AwsSignatureVersion4.CreateAuthorizationRequest(
                dateTime,
                credential.Username,
                credential.Password,
                null,
                serverNonce,
                host,
                out var authHeader,
                out var timestamp);

            var mockClock = new Mock <IClock>();

            mockClock.Setup(x => x.UtcNow).Returns(dateTime);

            var mockRandomByteGenerator = new Mock <IRandomByteGenerator>();

            mockRandomByteGenerator.Setup(x => x.Generate(It.IsAny <int>())).Returns(clientNonce);

            var expectedClientFirstMessage = new BsonDocument
            {
                { "r", clientNonce },
                { "p", (int)'n' }
            };
            var expectedClientSecondMessage = new BsonDocument
            {
                { "a", authHeader },
                { "d", timestamp }
            };
            var serverFirstMessage = new BsonDocument
            {
                { "s", serverNonce },
                { "h", host }
            };

            var saslStartCommandResponse = MessageHelper.BuildCommandResponse(RawBsonDocumentHelper.FromJson(
                                                                                  $"{{ conversationId : 1, done : false, payload : BinData(0,\"{ToBase64(serverFirstMessage.ToBson())}\"), ok : 1 }}"));
            var saslContinueCommandResponse = MessageHelper.BuildCommandResponse(RawBsonDocumentHelper.FromJson(
                                                                                     "{ conversationId : 1, done : true, payload : BinData(0,\"\"), ok : 1}"));

            var subject = new MongoAWSAuthenticator(credential, null, mockRandomByteGenerator.Object, mockClock.Object, serverApi: null);

            var connection = new MockConnection(__serverId);

            connection.EnqueueCommandResponseMessage(saslStartCommandResponse);
            connection.EnqueueCommandResponseMessage(saslContinueCommandResponse);
            connection.Description = __descriptionCommandWireProtocol;

            if (async)
            {
                subject.AuthenticateAsync(connection, __descriptionCommandWireProtocol, CancellationToken.None).GetAwaiter().GetResult();
            }
            else
            {
                subject.Authenticate(connection, __descriptionCommandWireProtocol, CancellationToken.None);
            }

            SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue();

            var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages());

            sentMessages.Count.Should().Be(2);

            var actualRequestId0 = sentMessages[0]["requestId"].AsInt32;
            var actualRequestId1 = sentMessages[1]["requestId"].AsInt32;

            var expectedFirstMessage  = GetExpectedSaslStartCommandMessage(actualRequestId0, expectedClientFirstMessage);
            var expectedSecondMessage = GetExpectedSaslContinueCommandMessage(actualRequestId1, expectedClientSecondMessage);

            sentMessages[0].Should().Be(expectedFirstMessage);
            sentMessages[1].Should().Be(expectedSecondMessage);
        }
コード例 #6
0
        public void Authenticate_with_session_token_should_have_expected_result(
            [Values(false, true)] bool async)
        {
            var dateTime     = DateTime.UtcNow;
            var clientNonce  = __randomByteGenerator.Generate(ClientNonceLength);
            var serverNonce  = Combine(clientNonce, __randomByteGenerator.Generate(ClientNonceLength));
            var host         = "sts.amazonaws.com";
            var credential   = new UsernamePasswordCredential("$external", "permanentuser", "FAKEFAKEFAKEFAKEFAKEfakefakefakefakefake");
            var sessionToken = "MXUpbuzwzPo67WKCNYtdBq47taFtIpt+SVx58hNx1/jSz37h9d67dtUOg0ejKrv83u8ai+VFZxMx=";

            AwsSignatureVersion4.CreateAuthorizationRequest(
                dateTime,
                credential.Username,
                credential.Password,
                sessionToken,
                serverNonce,
                host,
                out var authorizationHeader,
                out var timestamp);

            var mockClock = new Mock <IClock>();

            mockClock.Setup(x => x.UtcNow).Returns(dateTime);

            var mockRandomByteGenerator = new Mock <IRandomByteGenerator>();

            mockRandomByteGenerator.Setup(x => x.Generate(It.IsAny <int>())).Returns(clientNonce);

            var expectedClientFirstMessage = new BsonDocument
            {
                { "r", clientNonce },
                { "p", (int)'n' }
            };
            var expectedClientSecondMessage = new BsonDocument
            {
                { "a", authorizationHeader },
                { "d", timestamp },
                { "t", sessionToken }
            };
            var serverFirstMessage = new BsonDocument
            {
                { "s", serverNonce },
                { "h", host }
            };

            var saslStartReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                $"{{ conversationId : 1, done : false, payload : BinData(0,\"{ToBase64(serverFirstMessage.ToBson())}\"), ok : 1}}"));
            var saslContinueReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                   "{ conversationId : 1, done : true, payload : BinData(0,\"\"), ok : 1}"));

            var properties = new[] { new KeyValuePair <string, string>("AWS_SESSION_TOKEN", sessionToken) };
            var subject    = new MongoAWSAuthenticator(credential, properties, mockRandomByteGenerator.Object, mockClock.Object, serverApi: null);

            var connection = new MockConnection(__serverId);

            connection.EnqueueReplyMessage(saslStartReply);
            connection.EnqueueReplyMessage(saslContinueReply);

            if (async)
            {
                subject.AuthenticateAsync(connection, __descriptionQueryWireProtocol, CancellationToken.None).GetAwaiter().GetResult();
            }
            else
            {
                subject.Authenticate(connection, __descriptionQueryWireProtocol, CancellationToken.None);
            }

            SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue();

            var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages());

            sentMessages.Count.Should().Be(2);

            var actualRequestId0 = sentMessages[0]["requestId"].AsInt32;
            var actualRequestId1 = sentMessages[1]["requestId"].AsInt32;

            var expectedFirstMessage  = GetExpectedSaslStartQueryMessage(actualRequestId0, expectedClientFirstMessage);
            var expectedSecondMessage = GetExpectedSaslContinueQueryMessage(actualRequestId1, expectedClientSecondMessage);

            sentMessages[0].Should().Be(expectedFirstMessage);
            sentMessages[1].Should().Be(expectedSecondMessage);
        }