Exemplo n.º 1
0
        public void Authentication_succeeds_with_MONGODB_X509_mechanism(
            [Values(false, true)] bool async)
        {
            RequireEnvironment.Check().EnvironmentVariable("MONGO_X509_CLIENT_CERTIFICATE_PATH", isDefined: true);
            RequireEnvironment.Check().EnvironmentVariable("MONGO_X509_CLIENT_CERTIFICATE_PASSWORD", isDefined: true);
            RequireServer.Check().Tls(required: true);

            var pathToClientCertificate = Environment.GetEnvironmentVariable("MONGO_X509_CLIENT_CERTIFICATE_PATH");
            var password          = Environment.GetEnvironmentVariable("MONGO_X509_CLIENT_CERTIFICATE_PASSWORD");
            var clientCertificate = new X509Certificate2(pathToClientCertificate, password);

            var userName = GetRfc2253FormattedUsernameFromX509ClientCertificate(clientCertificate);

            DropDatabaseUser(DriverTestConfiguration.Client, database: "$external", userName);
            CreateX509DatabaseUser(DriverTestConfiguration.Client, userName);

            var settings      = DriverTestConfiguration.GetClientSettings().Clone();
            var serverVersion = CoreTestConfiguration.ServerVersion;

            if (Feature.ServerExtractsUsernameFromX509Certificate.IsSupported(serverVersion))
            {
                settings.Credential = MongoCredential.CreateMongoX509Credential();
            }
            else
            {
                settings.Credential = MongoCredential.CreateMongoX509Credential(userName);
            }
            settings.SslSettings = settings.SslSettings.Clone();
            settings.SslSettings.ClientCertificates = new[] { clientCertificate };

            AssertAuthenticationSucceeds(settings, async, speculativeAuthenticatationShouldSucceedIfPossible: true);
        }
        public void Run(JsonDrivenTestCase testCase)
        {
#if DEBUG
            RequirePlatform
            .Check()
            .SkipWhen(SupportedOperatingSystem.Linux)
            .SkipWhen(SupportedOperatingSystem.MacOS);
            // Make sure that LB is started. "nginx" is a LB we use for windows testing
            RequireEnvironment.Check().ProcessStarted("nginx");
            Environment.SetEnvironmentVariable("MONGODB_URI", "mongodb://localhost:17017?loadBalanced=true");
            Environment.SetEnvironmentVariable("MONGODB_URI_WITH_MULTIPLE_MONGOSES", "mongodb://localhost:17018?loadBalanced=true");
            RequireServer
            .Check()
            .LoadBalancing(enabled: true, ignorePreviousSetup: true)
            .Authentication(authentication: false); // auth server requires credentials in connection string
#else
            RequireEnvironment                      // these env variables are used only on the scripting side
            .Check()
            .EnvironmentVariable("SINGLE_MONGOS_LB_URI")
            .EnvironmentVariable("MULTI_MONGOS_LB_URI");
            // EG currently supports LB only for Ubuntu
            RequirePlatform
            .Check()
            .SkipWhen(SupportedOperatingSystem.Windows)
            .SkipWhen(SupportedOperatingSystem.MacOS);
#endif

            using (var runner = new UnifiedTestRunner())
            {
                runner.Run(testCase);
            }
        }
        public void BsonBinaryReader_should_support_reading_more_than_2GB()
        {
            RequireEnvironment.Check().EnvironmentVariable("EXPLICIT");

            var binaryData = new BsonBinaryData(new byte[1024 * 1024]);

            var tempFileName = Path.GetTempFileName();

            try
            {
                using (var stream = new FileStream(tempFileName, FileMode.Open))
                {
                    using (var binaryWriter = new BsonBinaryWriter(stream))
                    {
                        while (stream.Position < (long)int.MaxValue * 4)
                        {
                            binaryWriter.WriteStartDocument();
                            binaryWriter.WriteName("x");
                            binaryWriter.WriteBinaryData(binaryData);
                            binaryWriter.WriteEndDocument();
                        }
                    }

                    var endOfFilePosition = stream.Position;
                    stream.Position = 0;

                    using (var binaryReader = new BsonBinaryReader(stream))
                    {
                        while (!binaryReader.IsAtEndOfFile())
                        {
                            binaryReader.ReadStartDocument();
                            var bookmark = binaryReader.GetBookmark();

                            binaryReader.ReadName("x");
                            binaryReader.ReturnToBookmark(bookmark);

                            binaryReader.ReadName("x");
                            var readBinaryData = binaryReader.ReadBinaryData();
                            Assert.Equal(binaryData.Bytes.Length, readBinaryData.Bytes.Length);

                            binaryReader.ReadEndDocument();
                        }
                    }

                    Assert.Equal(endOfFilePosition, stream.Position);
                }
            }
            finally
            {
                try
                {
                    File.Delete(tempFileName);
                }
                catch
                {
                    // ignore exceptions
                }
            }
        }
        public void Should_acquire_gssapi_security_credential_with_username_only()
        {
            RequireEnvironment.Check().EnvironmentVariable("GSSAPI_TESTS_ENABLED");

            var credential = GssapiSecurityCredential.Acquire(_username);

            credential.Should().NotBeNull();
        }
        public void Driver_should_connect_to_AtlasDataLake_without_authentication()
        {
            RequireEnvironment.Check().EnvironmentVariable("ATLAS_DATA_LAKE_TESTS_ENABLED");

            using (var client = DriverTestConfiguration.CreateDisposableClient())
            {
                client.GetDatabase("admin").RunCommand <BsonDocument>(new BsonDocument("ping", 1));
            }
        }
        public void Should_acquire_gssapi_security_credential_with_username_and_password()
        {
            RequireEnvironment.Check().EnvironmentVariable("GSSAPI_TESTS_ENABLED");

            var securePassword = SecureStringHelper.ToSecureString(_password);
            var credential     = GssapiSecurityCredential.Acquire(_username, securePassword);

            credential.Should().NotBeNull();
        }
        public void Should_fail_to_acquire_gssapi_security_credential_with_username_and_bad_password()
        {
            RequireEnvironment.Check().EnvironmentVariable("GSSAPI_TESTS_ENABLED");

            var securePassword = SecureStringHelper.ToSecureString("BADPASSWORD");

            var exception = Record.Exception(() => GssapiSecurityCredential.Acquire(_username, securePassword));

            exception.Should().BeOfType <LibgssapiException>();
        }
Exemplo n.º 8
0
        public void TestSuccessfulAuthentication()
        {
            RequireEnvironment.Check().EnvironmentVariable("EXPLICIT");
            var client = new MongoClient(_settings);

            var result = client
                         .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                         .GetCollection <BsonDocument>(__collectionName)
                         .FindSync(new BsonDocument())
                         .ToList();

            Assert.NotNull(result);
        }
Exemplo n.º 9
0
        public void TestNoCredentials()
        {
            RequireEnvironment.Check().EnvironmentVariable("EXPLICIT");
            _settings.Credential = null;
            var client = new MongoClient(_settings);

            Assert.Throws <MongoCommandException>(() =>
            {
                client
                .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                .GetCollection <BsonDocument>(__collectionName)
                .Count(new BsonDocument());
            });
        }
        public void TestSuccessfulAuthentication()
        {
            RequireEnvironment.Check().EnvironmentVariable("GSSAPI_TESTS_ENABLED");

            var mongoUrl = CreateMongoUrl();
            var client   = new MongoClient(mongoUrl);

            var collection = GetTestCollection(client, mongoUrl.DatabaseName);
            var result     = collection
                             .FindSync(new BsonDocument())
                             .ToList();

            result.Should().NotBeNull();
        }
Exemplo n.º 11
0
        public void TestNoCredentials()
        {
            RequireEnvironment.Check().EnvironmentVariable("PLAIN_AUTH_TESTS_ENABLED");
            _settings.Credential = null;
            var client = new MongoClient(_settings);

            Assert.Throws <MongoCommandException>(() =>
            {
#pragma warning disable 618
                client
                .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                .GetCollection <BsonDocument>(__collectionName)
                .Count(new BsonDocument());
#pragma warning restore
            });
        }
        public void TestNoCredentials()
        {
            RequireEnvironment.Check().EnvironmentVariable("GSSAPI_TESTS_ENABLED");

            var mongoUrl       = CreateMongoUrl();
            var clientSettings = MongoClientSettings.FromUrl(mongoUrl);

            clientSettings.Credential = null;
            var client     = new MongoClient(clientSettings);
            var collection = GetTestCollection(client, mongoUrl.DatabaseName);

            var exception = Record.Exception(() => { collection.CountDocuments(new BsonDocument()); });
            var e         = exception.Should().BeOfType <MongoCommandException>().Subject;

            e.CodeName.Should().Be("Unauthorized");
        }
        public void TestBadPassword()
        {
            RequireEnvironment.Check().EnvironmentVariable("GSSAPI_TESTS_ENABLED");

            var mongoUrl = CreateMongoUrl();
            var currentCredentialUsername = mongoUrl.Username;
            var clientSettings            = MongoClientSettings.FromUrl(mongoUrl);

            clientSettings.Credential = MongoCredential.CreateGssapiCredential(currentCredentialUsername, "wrongPassword");

            var client     = new MongoClient(clientSettings);
            var collection = GetTestCollection(client, mongoUrl.DatabaseName);

            var exception = Record.Exception(() => { collection.FindSync(new BsonDocument()).ToList(); });

            exception.Should().BeOfType <MongoAuthenticationException>();
        }
Exemplo n.º 14
0
        public void Aws_authentication_should_should_have_expected_result()
        {
            RequireEnvironment.Check().EnvironmentVariable("AWS_TESTS_ENABLED");

            using (var client = DriverTestConfiguration.CreateDisposableClient())
            {
                // test that a command that doesn't require auth completes normally
                var adminDatabase   = client.GetDatabase("admin");
                var isMasterCommand = new BsonDocument("ismaster", 1);
                var isMasterResult  = adminDatabase.RunCommand <BsonDocument>(isMasterCommand);

                // test that a command that does require auth completes normally
                var database   = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName);
                var collection = database.GetCollection <BsonDocument>(DriverTestConfiguration.CollectionNamespace.CollectionName);
                var count      = collection.CountDocuments(FilterDefinition <BsonDocument> .Empty);
            }
        }
Exemplo n.º 15
0
        public void TestBadPassword()
        {
            RequireEnvironment.Check().EnvironmentVariable("EXPLICIT");
            var currentCredential = _settings.Credential;

            _settings.Credential = MongoCredential.CreatePlainCredential(currentCredential.Source, currentCredential.Username, "wrongPassword");

            var client = new MongoClient(_settings);

            Assert.Throws <TimeoutException>(() =>
            {
                client
                .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                .GetCollection <BsonDocument>(__collectionName)
                .FindSync(new BsonDocument())
                .ToList();
            });
        }
        public void Run(JsonDrivenTestCase testCase)
        {
            if (testCase.Name.Contains("awsTemporary"))
            {
                // This test requires setting of some temporary environment variables that can be set by mongo orchestration or manually.
                // Add this environment variable on your local machine only together with FLE_AWS_TEMP_* variables (note: they will be expired in 12 hours)
                RequireEnvironment.Check().EnvironmentVariable("FLE_AWS_TEMPORARY_CREDS_ENABLED");
            }

            RequirePlatform
            .Check()
            .SkipWhen(SupportedOperatingSystem.Linux, SupportedTargetFramework.NetStandard15)
            .SkipWhen(() => testCase.Name.Contains("gcpKMS.json"), SupportedOperatingSystem.Linux, SupportedTargetFramework.NetStandard20)     // gcp is supported starting from netstandard2.1
            .SkipWhen(SupportedOperatingSystem.MacOS, SupportedTargetFramework.NetStandard15)
            .SkipWhen(() => testCase.Name.Contains("gcpKMS.json"), SupportedOperatingSystem.MacOS, SupportedTargetFramework.NetStandard20);    // gcp is supported starting from netstandard2.1

            SetupAndRunTest(testCase);
        }
        public void Driver_should_connect_to_AtlasDataLake_with_SCRAM_SHA_256()
        {
            RequireEnvironment.Check().EnvironmentVariable("ATLAS_DATA_LAKE_TESTS_ENABLED");
            RequireServer.Check().Supports(Feature.ScramSha256Authentication);

            var connectionString = CoreTestConfiguration.ConnectionString;
            var username         = connectionString.Username;
            var password         = connectionString.Password;
            var source           = connectionString.AuthSource;

            var settings = DriverTestConfiguration.Client.Settings.Clone();

            settings.Credential = MongoCredential.FromComponents(mechanism: "SCRAM-SHA-256", source, username, password);

            using (var client = DriverTestConfiguration.CreateDisposableClient(settings))
            {
                client.GetDatabase("admin").RunCommand <BsonDocument>(new BsonDocument("ping", 1));
            }
        }
        public void MongoClientShouldRespectCertificateStatusAndTlsInsecure()
        {
            /* We cannot call RequireServer.Check() because this would result in a connection being made to the mongod
             * and that connection will not succeed if we're testing the revoked certificate case. */

            RequireEnvironment.Check().EnvironmentVariable(_shouldSucceedEnvironmentVariableName);

            var shouldSucceed = GetShouldSucceed();

            /* To prevent OCSP caching from polluting the test results, we MUST run the "secure" version before
             * the tlsInsecure version.  */
            var secureClientException      = Record.Exception(() => Ping(tlsInsecure: false));
            var tlsInsecureClientException = Record.Exception(() => Ping(tlsInsecure: true));

            tlsInsecureClientException.Should().BeNull();
            if (shouldSucceed)
            {
                secureClientException.Should().BeNull();
            }
            else
            {
                secureClientException.Should().BeOfType <TimeoutException>();
                var message = secureClientException.Message;
                // The exception will lack this message if the heartbeat doesn't fire
                message.Should().Contain("The remote certificate is invalid according to the validation procedure.");
            }

            void Ping(bool tlsInsecure)
            {
                using (var client = CreateDisposableMongoClient(tlsInsecure))
                {
                    client.GetDatabase("admin").RunCommand <BsonDocument>(new BsonDocument("ping", 1));
                    if (client.Settings.SdamLogFilename != null)
                    { // Log file needs a bit of time to be written before we dispose the client
                        System.Threading.Thread.Sleep(2000);
                    }
                }
            }
        }
        public void KillCursors_should_return_expected_result()
        {
            RequireEnvironment.Check().EnvironmentVariable("ATLAS_DATA_LAKE_TESTS_ENABLED");
            RequireServer.Check();

            var databaseName   = "test";
            var collectionName = "driverdata";

            var eventCapturer = new EventCapturer()
                                .Capture <CommandStartedEvent>(x => "killCursors" == x.CommandName)
                                .Capture <CommandSucceededEvent>(x => new[] { "killCursors", "find" }.Contains(x.CommandName));

            using (var client = DriverTestConfiguration.CreateDisposableClient(eventCapturer))
            {
                var cursor = client
                             .GetDatabase(databaseName)
                             .GetCollection <BsonDocument>(collectionName)
                             .Find(new BsonDocument(), new FindOptions {
                    BatchSize = 2
                })
                             .ToCursor();

                var findCommandSucceededEvent = eventCapturer.Events.OfType <CommandSucceededEvent>().First(x => x.CommandName == "find");
                var findCommandResult         = findCommandSucceededEvent.Reply;
                var cursorId        = findCommandResult["cursor"]["id"].AsInt64;
                var cursorNamespace = CollectionNamespace.FromFullName(findCommandResult["cursor"]["ns"].AsString);

                cursor.Dispose();

                var killCursorsCommandStartedEvent   = eventCapturer.Events.OfType <CommandStartedEvent>().First(x => x.CommandName == "killCursors");
                var killCursorsCommandSucceededEvent = eventCapturer.Events.OfType <CommandSucceededEvent>().First(x => x.CommandName == "killCursors");
                var killCursorsStartedCommand        = killCursorsCommandStartedEvent.Command;

                cursorNamespace.DatabaseNamespace.DatabaseName.Should().Be(killCursorsCommandStartedEvent.DatabaseNamespace.DatabaseName);
                cursorNamespace.CollectionName.Should().Be(killCursorsStartedCommand["killCursors"].AsString);
                cursorId.Should().Be(killCursorsStartedCommand["cursors"][0].AsInt64);
                cursorId.Should().Be(killCursorsCommandSucceededEvent.Reply["cursorsKilled"][0].AsInt64);
            }
        }
Exemplo n.º 20
0
        private void SkipIfNotLoadBalancingMode()
        {
#if DEBUG
            RequirePlatform.Check().SkipWhen(SupportedOperatingSystem.Linux);
            RequirePlatform.Check().SkipWhen(SupportedOperatingSystem.MacOS);
            // Make sure that LB is started. "nginx" is a LB we use for windows testing
            RequireEnvironment.Check().ProcessStarted("nginx");
            Environment.SetEnvironmentVariable("MONGODB_URI", "mongodb://localhost:17017?loadBalanced=true");
            Environment.SetEnvironmentVariable("MONGODB_URI_WITH_MULTIPLE_MONGOSES", "mongodb://localhost:17018?loadBalanced=true");
            RequireServer
            .Check()
            .LoadBalancing(enabled: true, ignorePreviousSetup: true)
            .Authentication(authentication: false);                                 // auth server requires credentials in connection string
#else
            RequireEnvironment.Check().EnvironmentVariable("SINGLE_MONGOS_LB_URI"); // these env variables are used only on the scripting side
            RequireEnvironment.Check().EnvironmentVariable("MULTI_MONGOS_LB_URI");
            // EG currently supports LB only for Ubuntu
            RequirePlatform.Check().SkipWhen(SupportedOperatingSystem.Windows);
            RequirePlatform.Check().SkipWhen(SupportedOperatingSystem.MacOS);
            RequireServer.Check().ClusterType(ClusterType.LoadBalanced);
#endif
        }
Exemplo n.º 21
0
        public void TestWhereEEqualsA()
        {
            RequireEnvironment.Check().EnvironmentVariable("MONO"); // Does not pass on Mono 3.2.5. Excluding for now.
            var query = from c in __collection.AsQueryable <C>()
                        where c.E == E.A
                        select c;

            var translatedQuery = MongoQueryTranslator.Translate(query);

            Assert.IsType <SelectQuery>(translatedQuery);
            Assert.Same(__collection, translatedQuery.Collection);
            Assert.Same(typeof(C), translatedQuery.DocumentType);

            var selectQuery = (SelectQuery)translatedQuery;

            Assert.Equal("(C c) => ((Nullable<Int32>)c.E == (Nullable<Int32>)1)", ExpressionFormatter.ToString(selectQuery.Where));
            Assert.Null(selectQuery.OrderBy);
            Assert.Null(selectQuery.Projection);
            Assert.Null(selectQuery.Skip);
            Assert.Null(selectQuery.Take);

            Assert.Equal("{ \"e\" : \"A\" }", selectQuery.BuildQuery().ToJson());
            Assert.Equal(1, Consume(query));
        }
        public void Run(JsonDrivenTestCase testCase)
        {
            RequireEnvironment.Check().EnvironmentVariable("ATLAS_DATA_LAKE_TESTS_ENABLED");

            SetupAndRunTest(testCase);
        }
Exemplo n.º 23
0
 public void TestReconnect()
 {
     RequireEnvironment.Check().EnvironmentVariable("EXPLICIT");
     __server.Reconnect();
     Assert.True(__server.State == MongoServerState.Connected || __server.State == MongoServerState.ConnectedToSubset);
 }