├── .errcheck-excludes ├── .evergreen ├── config.yml ├── krb5.config ├── ocsp-requirements.txt ├── run-mongodb-aws-ecs-test.sh ├── run-task.sh └── setup-system.sh ├── .github ├── CODEOWNERS ├── dependabot.yml ├── labeler.yml ├── release.yml ├── reviewers.txt └── workflows │ ├── codeql.yml │ ├── create-release-branch.yml │ ├── merge-up.yml │ ├── release.yml │ └── test.yml ├── .gitignore ├── .gitmodules ├── .golangci.yml ├── .pre-commit-config.yaml ├── Dockerfile ├── LICENSE ├── README.md ├── THIRD-PARTY-NOTICES ├── Taskfile.yml ├── bson ├── array_codec.go ├── benchmark_test.go ├── bson_binary_vector_spec_test.go ├── bson_corpus_spec_test.go ├── bson_test.go ├── bsoncodec.go ├── bsoncodec_test.go ├── bsonrw_test.go ├── byte_slice_codec.go ├── codec_cache.go ├── codec_cache_test.go ├── cond_addr_codec.go ├── cond_addr_codec_test.go ├── copier.go ├── copier_test.go ├── decimal.go ├── decimal_test.go ├── decode_value_fuzz_test.go ├── decoder.go ├── decoder_example_test.go ├── decoder_test.go ├── default_value_decoders.go ├── default_value_decoders_test.go ├── default_value_encoders.go ├── default_value_encoders_test.go ├── doc.go ├── empty_interface_codec.go ├── encoder.go ├── encoder_example_test.go ├── encoder_test.go ├── example_test.go ├── extjson_parser.go ├── extjson_parser_test.go ├── extjson_prose_test.go ├── extjson_reader.go ├── extjson_reader_test.go ├── extjson_tables.go ├── extjson_wrappers.go ├── extjson_writer.go ├── extjson_writer_test.go ├── fuzz_test.go ├── json_scanner.go ├── json_scanner_test.go ├── map_codec.go ├── marshal.go ├── marshal_test.go ├── marshal_value_cases_test.go ├── marshal_value_test.go ├── marshaling_cases_test.go ├── mgocompat │ ├── doc.go │ └── registry.go ├── mgoregistry.go ├── mgoregistry_test.go ├── mode.go ├── objectid.go ├── objectid_test.go ├── pointer_codec.go ├── primitive.go ├── primitive_codecs.go ├── primitive_codecs_test.go ├── raw.go ├── raw_array.go ├── raw_array_test.go ├── raw_element.go ├── raw_test.go ├── raw_value.go ├── raw_value_test.go ├── reader.go ├── registry.go ├── registry_examples_test.go ├── registry_test.go ├── slice_codec.go ├── string_codec.go ├── struct_codec.go ├── struct_codec_test.go ├── struct_tag_parser.go ├── struct_tag_parser_test.go ├── testdata │ ├── code.json.gz │ ├── fuzz │ │ └── FuzzDecode │ │ │ ├── 002ae7d43f636100116fede772a03d07726ed75c3c3b83da865fe9b718adf8ae │ │ │ ├── 0de854041b0055ca1e5e6e54a7fb667ed38461db171af267665c21776f9a9ef4 │ │ │ ├── 718592474a0a3626039f3471449b9aa374c746754d4925fcfe4ba747e7101504 │ │ │ ├── 93c43e3c1cf35c19b7618a618d128cea0ce05cef0711fdd91e403fe3b2f45628 │ │ │ └── c3ffbb42eb85b743ede396f00b7706e6ad0529c32689c63ca663dae37d072627 │ └── lorem.txt ├── time_codec.go ├── time_codec_test.go ├── truncation_test.go ├── type_test.go ├── types.go ├── uint_codec.go ├── unmarshal.go ├── unmarshal_test.go ├── unmarshal_value_test.go ├── unmarshaling_cases_test.go ├── value_reader.go ├── value_reader_test.go ├── value_reader_writer_test.go ├── value_writer.go ├── value_writer_test.go ├── vector.go └── writer.go ├── docs ├── CONTRIBUTING.md ├── common-issues.md ├── migration-2.0.md └── pull_request_template.md ├── etc ├── api_report.sh ├── assets │ ├── docs-mongodb-green.svg │ ├── godev-bson-blue.svg │ ├── godev-mongo-blue.svg │ └── mongo-gopher.png ├── check_fmt.sh ├── check_license.sh ├── check_modules.sh ├── cherry-picker.sh ├── compile_check.sh ├── docker_entry.sh ├── gen-ec-certs │ ├── client.ext │ ├── empty.cnf │ ├── gen-ec-certs.sh │ └── server.ext ├── generate_notices.pl ├── golangci-lint.sh ├── install-libmongocrypt.sh ├── pr-task.sh ├── run-awskms-test.sh ├── run-azurekms-test.sh ├── run-compile-check-test.sh ├── run-fuzz.sh ├── run-gcpkms-test.sh ├── run-goleak-test.sh ├── run-mongodb-aws-ecs-test.sh ├── run-mongodb-aws-test.sh ├── run-oidc-remote-test.sh ├── run-oidc-test.sh ├── run_docker.sh ├── setup-encryption.sh ├── setup-test.sh └── update_spec_tests.sh ├── event ├── description.go ├── doc.go ├── examples_test.go └── monitoring.go ├── examples ├── _example_customdns_test.go └── _logger │ ├── logrus │ ├── go.mod │ ├── go.sum │ └── main.go │ ├── zap │ ├── go.mod │ ├── go.sum │ └── main.go │ └── zerolog │ ├── go.mod │ ├── go.sum │ └── main.go ├── go.mod ├── go.sum ├── go.work ├── internal ├── assert │ ├── assertion_compare.go │ ├── assertion_compare_can_convert.go │ ├── assertion_compare_go1.17_test.go │ ├── assertion_compare_legacy.go │ ├── assertion_compare_test.go │ ├── assertion_format.go │ ├── assertion_mongo.go │ ├── assertion_mongo_test.go │ ├── assertions.go │ ├── assertions_test.go │ ├── difflib.go │ └── difflib_test.go ├── aws │ ├── awserr │ │ ├── error.go │ │ └── types.go │ ├── credentials │ │ ├── chain_provider.go │ │ ├── chain_provider_test.go │ │ ├── credentials.go │ │ └── credentials_test.go │ ├── signer │ │ └── v4 │ │ │ ├── header_rules.go │ │ │ ├── request.go │ │ │ ├── uri_path.go │ │ │ ├── v4.go │ │ │ └── v4_test.go │ └── types.go ├── bsoncoreutil │ ├── bsoncoreutil.go │ └── bsoncoreutil_test.go ├── bsonutil │ └── bsonutil.go ├── cmd │ ├── benchmark │ │ ├── benchmark_test.go │ │ ├── go.mod │ │ └── go.sum │ ├── build-oss-fuzz-corpus │ │ └── main.go │ ├── compilecheck │ │ ├── go.mod │ │ ├── go.sum │ │ └── main.go │ ├── faas │ │ └── awslambda │ │ │ ├── Makefile │ │ │ ├── mongodb │ │ │ ├── bootstrap.go │ │ │ ├── go.mod │ │ │ └── go.sum │ │ │ └── template.yaml │ ├── parse-api-report │ │ └── main.go │ ├── testatlas │ │ └── atlas_test.go │ ├── testaws │ │ └── main.go │ ├── testentauth │ │ └── main.go │ ├── testkms │ │ └── main.go │ └── testoidcauth │ │ └── main.go ├── codecutil │ ├── encoding.go │ └── encoding_test.go ├── credproviders │ ├── assume_role_provider.go │ ├── ec2_provider.go │ ├── ecs_provider.go │ ├── env_provider.go │ ├── imds_provider.go │ └── static_provider.go ├── csfle │ └── csfle.go ├── csot │ ├── csot.go │ └── csot_test.go ├── decimal128 │ └── decinal128.go ├── docexamples │ ├── README │ ├── examples.go │ └── examples_test.go ├── driverutil │ ├── description.go │ ├── hello.go │ ├── operation.go │ └── operation_test.go ├── errutil │ ├── join.go │ ├── join_go1.19.go │ ├── join_go1.20.go │ └── join_test.go ├── eventtest │ └── eventtest.go ├── failpoint │ └── failpoint.go ├── handshake │ └── handshake.go ├── httputil │ └── httputil.go ├── integration │ ├── causal_consistency_test.go │ ├── change_stream_test.go │ ├── clam_prose_test.go │ ├── client_options_test.go │ ├── client_side_encryption_prose_test.go │ ├── client_side_encryption_spec_test.go │ ├── client_side_encryption_test.go │ ├── client_test.go │ ├── cmd_monitoring_helpers_test.go │ ├── collection_test.go │ ├── crud_helpers_test.go │ ├── crud_prose_test.go │ ├── csot_cse_prose_test.go │ ├── csot_prose_test.go │ ├── csot_test.go │ ├── cursor_test.go │ ├── data_lake_test.go │ ├── database_test.go │ ├── errors_test.go │ ├── gridfs_test.go │ ├── handshake_test.go │ ├── index_view_test.go │ ├── initial_dns_seedlist_discovery_test.go │ ├── json_helpers_test.go │ ├── load_balancer_prose_test.go │ ├── log_helpers_test.go │ ├── main.go │ ├── main_test.go │ ├── mock_find_test.go │ ├── mongos_pinning_test.go │ ├── mtest │ │ ├── csfle_enabled.go │ │ ├── csfle_not_enabled.go │ │ ├── deployment_helpers.go │ │ ├── doc.go │ │ ├── global_state.go │ │ ├── mongotest.go │ │ ├── options.go │ │ ├── proxy_dialer.go │ │ ├── received_message.go │ │ ├── sent_message.go │ │ ├── setup.go │ │ ├── setup_options.go │ │ └── wiremessage_helpers.go │ ├── primary_stepdown_test.go │ ├── retryable_reads_prose_test.go │ ├── retryable_writes_prose_test.go │ ├── sdam_error_handling_test.go │ ├── sdam_prose_test.go │ ├── search_index_prose_test.go │ ├── server_selection_prose_test.go │ ├── sessions_mongocryptd_prose_test.go │ ├── sessions_test.go │ ├── unified │ │ ├── admin_helpers.go │ │ ├── bsonutil.go │ │ ├── bucket_options.go │ │ ├── bulkwrite_helpers.go │ │ ├── client_encryption_operation_execution.go │ │ ├── client_entity.go │ │ ├── client_operation_execution.go │ │ ├── collection_data.go │ │ ├── collection_operation_execution.go │ │ ├── common_options.go │ │ ├── context.go │ │ ├── crud_helpers.go │ │ ├── cursor_entity.go │ │ ├── cursor_operation_execution.go │ │ ├── database_operation_execution.go │ │ ├── db_collection_options.go │ │ ├── entity.go │ │ ├── entity_test.go │ │ ├── error.go │ │ ├── event.go │ │ ├── event_verification.go │ │ ├── gridfs_bucket_operation_execution.go │ │ ├── logger.go │ │ ├── logger_verification.go │ │ ├── main_test.go │ │ ├── matches.go │ │ ├── matches_test.go │ │ ├── operation.go │ │ ├── options.go │ │ ├── result.go │ │ ├── schema_version.go │ │ ├── server_api_options.go │ │ ├── session_operation_execution.go │ │ ├── session_options.go │ │ ├── testrunner_operation.go │ │ ├── unified_spec_runner.go │ │ └── unified_spec_test.go │ ├── unified_runner_events_helper_test.go │ ├── unified_runner_thread_helpers_test.go │ └── unified_spec_test.go ├── integtest │ └── integtest.go ├── israce │ ├── norace.go │ └── race.go ├── logger │ ├── component.go │ ├── component_test.go │ ├── context.go │ ├── context_test.go │ ├── io_sink.go │ ├── level.go │ ├── logger.go │ └── logger_test.go ├── mongoutil │ ├── mongoutil.go │ └── mongoutil_test.go ├── optionsutil │ └── options.go ├── ptrutil │ ├── int64.go │ ├── int64_test.go │ └── ptr.go ├── rand │ ├── arith128_test.go │ ├── bits.go │ ├── example_test.go │ ├── exp.go │ ├── modulo_test.go │ ├── normal.go │ ├── race_test.go │ ├── rand.go │ ├── rand_test.go │ ├── regress_test.go │ └── rng.go ├── randutil │ ├── randutil.go │ └── randutil_test.go ├── require │ └── require.go ├── serverselector │ ├── server_selector.go │ └── server_selector_test.go ├── spectest │ ├── skip.go │ └── spectest.go ├── test │ ├── compilecheck │ │ ├── compile_check_test.go │ │ ├── go.mod │ │ └── go.sum │ └── goleak │ │ ├── go.mod │ │ ├── go.sum │ │ └── goleak_test.go └── uuid │ ├── uuid.go │ └── uuid_test.go ├── mongo ├── address │ ├── addr.go │ └── addr_test.go ├── background_context.go ├── background_context_test.go ├── batch_cursor.go ├── bson_helpers_test.go ├── bulk_write.go ├── bulk_write_models.go ├── change_stream.go ├── change_stream_deployment.go ├── change_stream_test.go ├── client.go ├── client_bulk_write.go ├── client_bulk_write_models.go ├── client_bulk_write_test.go ├── client_encryption.go ├── client_encryption_test.go ├── client_examples_test.go ├── client_side_encryption_examples_test.go ├── client_test.go ├── collection.go ├── collection_test.go ├── crud_examples_test.go ├── crypt_retrievers.go ├── cursor.go ├── cursor_test.go ├── database.go ├── database_test.go ├── doc.go ├── errors.go ├── errors_test.go ├── gridfs_bucket.go ├── gridfs_bucket_test.go ├── gridfs_download_stream.go ├── gridfs_examples_test.go ├── gridfs_test.go ├── gridfs_upload_stream.go ├── index_view.go ├── mongo.go ├── mongo_test.go ├── mongocryptd.go ├── ocsp_test.go ├── options │ ├── aggregateoptions.go │ ├── autoencryptionoptions.go │ ├── bulkwriteoptions.go │ ├── changestreamoptions.go │ ├── clientbulkwriteoptions.go │ ├── clientencryptionoptions.go │ ├── clientoptions.go │ ├── clientoptions_test.go │ ├── collectionoptions.go │ ├── countoptions.go │ ├── createcollectionoptions.go │ ├── datakeyoptions.go │ ├── dboptions.go │ ├── deleteoptions.go │ ├── distinctoptions.go │ ├── doc.go │ ├── dropcollectionoptions.go │ ├── encryptoptions.go │ ├── estimatedcountoptions.go │ ├── example_test.go │ ├── findoptions.go │ ├── gridfsoptions.go │ ├── indexoptions.go │ ├── insertoptions.go │ ├── listcollectionsoptions.go │ ├── listdatabasesoptions.go │ ├── lister.go │ ├── loggeroptions.go │ ├── mongooptions.go │ ├── replaceoptions.go │ ├── rewrapdatakeyoptions.go │ ├── runcmdoptions.go │ ├── searchindexoptions.go │ ├── serverapioptions.go │ ├── sessionoptions.go │ ├── testdata │ │ ├── ca-key.pem │ │ ├── ca-with-intermediates-first.pem │ │ ├── ca-with-intermediates-second.pem │ │ ├── ca-with-intermediates-third.pem │ │ ├── ca-with-intermediates.pem │ │ ├── ca.pem │ │ ├── cert.pem │ │ ├── certificate.pem │ │ ├── csr.json │ │ ├── empty-ca.pem │ │ ├── key.pem │ │ ├── malformed-ca.pem │ │ ├── nopass │ │ │ ├── cert.pem │ │ │ ├── certificate.pem │ │ │ └── key.pem │ │ └── one-pk-multiple-certs.pem │ ├── transactionoptions.go │ └── updateoptions.go ├── read_write_concern_spec_test.go ├── readconcern │ └── readconcern.go ├── readpref │ ├── mode.go │ ├── mode_test.go │ ├── options.go │ ├── options_example_test.go │ ├── readpref.go │ └── readpref_test.go ├── results.go ├── search_index_view.go ├── session.go ├── single_result.go ├── single_result_test.go ├── with_transactions_test.go └── writeconcern │ ├── writeconcern.go │ ├── writeconcern_example_test.go │ └── writeconcern_test.go ├── sbom.json ├── tag ├── tag.go └── tag_test.go ├── testdata ├── client-side-encryption-prose │ ├── change-streams-test.json │ ├── corpus-encrypted.json │ ├── corpus-key-aws.json │ ├── corpus-key-azure.json │ ├── corpus-key-gcp.json │ ├── corpus-key-kmip.json │ ├── corpus-key-local.json │ ├── corpus-schema.json │ ├── corpus.json │ ├── encrypted-fields.json │ ├── external-key.json │ ├── external-schema.json │ ├── key1-document.json │ ├── limits-doc.json │ ├── limits-key.json │ ├── limits-schema.json │ ├── range-encryptedFields-Date.json │ ├── range-encryptedFields-DecimalNoPrecision.json │ ├── range-encryptedFields-DecimalPrecision.json │ ├── range-encryptedFields-DoubleNoPrecision.json │ ├── range-encryptedFields-DoublePrecision.json │ ├── range-encryptedFields-Int.json │ └── range-encryptedFields-Long.json ├── extended_bson │ ├── deep_bson.json.gz │ ├── flat_bson.json.gz │ └── full_bson.json.gz ├── kmip-certs │ ├── ca-ec.pem │ ├── client-ec.pem │ └── server-ec.pem └── mongocrypt │ ├── collection-info.json │ ├── command-reply.json │ ├── command.json │ ├── encrypted-command-reply.json │ ├── encrypted-command.json │ ├── encrypted-value.json │ ├── json-schema.json │ ├── key-document.json │ ├── key-filter-keyAltName.json │ ├── key-filter.json │ ├── kms-reply.txt │ ├── list-collections-filter.json │ ├── local-key-document.json │ ├── mongocryptd-command-local.json │ ├── mongocryptd-command-remote.json │ └── mongocryptd-reply.json ├── version └── version.go └── x ├── README.md ├── bsonx └── bsoncore │ ├── array.go │ ├── array_test.go │ ├── bson_arraybuilder.go │ ├── bson_arraybuilder_test.go │ ├── bson_documentbuilder.go │ ├── bson_documentbuilder_test.go │ ├── bsoncore.go │ ├── bsoncore_test.go │ ├── doc.go │ ├── document.go │ ├── document_test.go │ ├── element.go │ ├── element_test.go │ ├── iterator.go │ ├── iterator_test.go │ ├── tables.go │ ├── type.go │ ├── value.go │ └── value_test.go └── mongo └── driver ├── auth ├── auth.go ├── auth_spec_test.go ├── auth_test.go ├── aws_conv.go ├── conversation.go ├── cred.go ├── creds │ ├── awscreds.go │ ├── azurecreds.go │ ├── credscaching_test.go │ ├── doc.go │ └── gcpcreds.go ├── default.go ├── doc.go ├── gssapi.go ├── gssapi_not_enabled.go ├── gssapi_not_supported.go ├── gssapi_test.go ├── internal │ └── gssapi │ │ ├── gss.go │ │ ├── gss_wrapper.c │ │ ├── gss_wrapper.h │ │ ├── sspi.go │ │ ├── sspi_wrapper.c │ │ └── sspi_wrapper.h ├── mongodbaws.go ├── mongodbaws_test.go ├── mongodbcr.go ├── mongodbcr_test.go ├── oidc.go ├── oidc_test.go ├── plain.go ├── plain_test.go ├── sasl.go ├── scram.go ├── scram_test.go ├── speculative_scram_test.go ├── speculative_x509_test.go ├── util.go └── x509.go ├── batch_cursor.go ├── batch_cursor_test.go ├── batches.go ├── batches_test.go ├── command_monitoring_test.go ├── compression.go ├── compression_test.go ├── connstring ├── connstring.go ├── connstring_spec_test.go ├── connstring_test.go └── initial_dns_seedlist_discovery_prose_test.go ├── crypt.go ├── description ├── server.go └── topology.go ├── dns └── dns.go ├── driver.go ├── drivertest ├── channel_conn.go ├── channel_netconn.go ├── doc.go ├── opmsg_deployment.go └── opmsg_deployment_test.go ├── errors.go ├── integration ├── aggregate_test.go ├── compressor_test.go ├── doc.go ├── insert_test.go ├── integration.go ├── main_test.go └── scram_test.go ├── legacy.go ├── mnet └── connection.go ├── mongocrypt ├── binary.go ├── binary_test.go ├── errors.go ├── errors_not_enabled.go ├── mongocrypt.go ├── mongocrypt_context.go ├── mongocrypt_context_not_enabled.go ├── mongocrypt_kms_context.go ├── mongocrypt_kms_context_not_enabled.go ├── mongocrypt_not_enabled.go ├── mongocrypt_test.go ├── options │ ├── doc.go │ ├── mongocrypt_context_options.go │ └── mongocrypt_options.go └── state.go ├── ocsp ├── cache.go ├── cache_test.go ├── config.go ├── ocsp.go ├── ocsp_test.go └── options.go ├── operation.go ├── operation ├── abort_transaction.go ├── aggregate.go ├── command.go ├── commit_transaction.go ├── count.go ├── create.go ├── create_indexes.go ├── create_search_indexes.go ├── delete.go ├── distinct.go ├── doc.go ├── drop_collection.go ├── drop_database.go ├── drop_indexes.go ├── drop_search_index.go ├── end_sessions.go ├── errors.go ├── find.go ├── find_and_modify.go ├── hello.go ├── hello_test.go ├── insert.go ├── list_collections.go ├── list_databases.go ├── list_indexes.go ├── update.go └── update_search_index.go ├── operation_exhaust.go ├── operation_test.go ├── serverapioptions.go ├── session ├── client_session.go ├── client_session_test.go ├── cluster_clock.go ├── cluster_clock_test.go ├── doc.go ├── options.go ├── server_session.go ├── server_session_test.go ├── session_pool.go └── session_pool_test.go ├── testdata └── compression.go ├── topology ├── CMAP_spec_test.go ├── DESIGN.md ├── cmap_prose_test.go ├── connection.go ├── connection_errors_test.go ├── connection_legacy.go ├── connection_options.go ├── connection_test.go ├── context_listener.go ├── diff.go ├── diff_test.go ├── errors.go ├── example_test.go ├── fsm.go ├── fsm_test.go ├── polling_srv_records_test.go ├── pool.go ├── pool_generation_counter.go ├── pool_test.go ├── rtt_monitor.go ├── rtt_monitor_test.go ├── sdam_spec_test.go ├── server.go ├── server_options.go ├── server_rtt_test.go ├── server_test.go ├── stats.go ├── stats_test.go ├── tls_connection_source_1_16.go ├── tls_connection_source_1_17.go ├── topology.go ├── topology_errors_test.go ├── topology_options.go ├── topology_options_test.go └── topology_test.go ├── wiremessage ├── wiremessage.go └── wiremessage_test.go └── xoptions ├── options.go └── options_test.go /.errcheck-excludes: -------------------------------------------------------------------------------- 1 | (go.mongodb.org/mongo-driver/x/mongo/driver.Connection).Close 2 | (*go.mongodb.org/mongo-driver/x/network/connection.connection).Close 3 | (go.mongodb.org/mongo-driver/x/network/connection.Connection).Close 4 | (*go.mongodb.org/mongo-driver/x/mongo/driver/topology.connection).close 5 | (*go.mongodb.org/mongo-driver/x/mongo/driver/topology.Topology).Unsubscribe 6 | (*go.mongodb.org/mongo-driver/x/mongo/driver/topology.Server).Close 7 | (*go.mongodb.org/mongo-driver/x/network/connection.pool).closeConnection 8 | (*go.mongodb.org/mongo-driver/x/mongo/driver/topology.pool).close 9 | (go.mongodb.org/mongo-driver/x/network/wiremessage.ReadWriteCloser).Close 10 | (*go.mongodb.org/mongo-driver/mongo.Cursor).Close 11 | (*go.mongodb.org/mongo-driver/mongo.ChangeStream).Close 12 | (*go.mongodb.org/mongo-driver/mongo.Client).Disconnect 13 | (net.Conn).Close 14 | encoding/pem.Encode 15 | fmt.Fprintf 16 | fmt.Fprint 17 | -------------------------------------------------------------------------------- /.evergreen/krb5.config: -------------------------------------------------------------------------------- 1 | [realms] 2 | LDAPTEST.10GEN.CC = { 3 | kdc = ldaptest.10gen.cc 4 | admin_server = ldaptest.10gen.cc 5 | } 6 | 7 | [libdefaults] 8 | rdns = false 9 | -------------------------------------------------------------------------------- /.evergreen/ocsp-requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==1.3.0 2 | bottle==0.12.20 3 | oscrypto==1.2.0 4 | -------------------------------------------------------------------------------- /.evergreen/run-mongodb-aws-ecs-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -o errexit # Exit the script with error if any of the commands fail 4 | 5 | ############################################ 6 | # Main Program # 7 | ############################################ 8 | 9 | if [[ -z "$1" ]]; then 10 | echo "usage: $0 " 11 | exit 1 12 | fi 13 | export MONGODB_URI="$1" 14 | 15 | echo "Running MONGODB-AWS ECS authentication tests" 16 | 17 | if echo "$MONGODB_URI" | grep -q "@"; then 18 | echo "MONGODB_URI unexpectedly contains user credentials in ECS test!"; 19 | exit 1 20 | fi 21 | 22 | ./src/main 23 | -------------------------------------------------------------------------------- /.evergreen/run-task.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Source the env.sh file and run the given task 4 | set -eu 5 | 6 | SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) 7 | PROJECT_DIRECTORY=$(dirname $SCRIPT_DIR) 8 | pushd ${PROJECT_DIRECTORY} > /dev/null 9 | 10 | source env.sh 11 | task "$@" 12 | 13 | popd > /dev/null 14 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @mongodb/dbx-go 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | groups: 8 | actions: 9 | patterns: 10 | - "*" 11 | - package-ecosystem: gomod 12 | directory: / 13 | schedule: 14 | interval: "weekly" 15 | - package-ecosystem: "gitsubmodule" 16 | directory: "/" 17 | schedule: 18 | interval: "weekly" 19 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | 2 | priority-3-low: 3 | - changed-files: 4 | - any-glob-to-any-file: '*' 5 | 6 | documentation: 7 | - changed-files: 8 | - any-glob-to-any-file: 9 | - docs/** 10 | - examples/** 11 | 12 | dependencies: 13 | - changed-files: 14 | - any-glob-to-any-file: 15 | - go.mod 16 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | exclude: 3 | labels: 4 | - ignore-for-release 5 | - submodules 6 | authors: 7 | - mongodb-drivers-pr-bot 8 | categories: 9 | - title: Breaking Changes 🛠 10 | labels: 11 | - breaking-change 12 | - title: New Features 13 | labels: 14 | - enhancement 15 | - title: Fixed 16 | labels: 17 | - bug 18 | - fixed 19 | - title: Other Changes 20 | labels: 21 | - "*" 22 | -------------------------------------------------------------------------------- /.github/reviewers.txt: -------------------------------------------------------------------------------- 1 | qingyang-hu 2 | matthewdale 3 | prestonvasquez 4 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [ "v1", "cloud-*", "master", "release/*" ] 6 | pull_request: 7 | branches: [ "v1", "cloud-*", "master", "release/*" ] 8 | schedule: 9 | - cron: '36 17 * * 0' 10 | workflow_call: 11 | inputs: 12 | ref: 13 | required: true 14 | type: string 15 | 16 | jobs: 17 | analyze: 18 | name: Analyze (go) 19 | runs-on: 'ubuntu-latest' 20 | timeout-minutes: 360 21 | permissions: 22 | # required for all workflows 23 | security-events: write 24 | 25 | steps: 26 | - name: Checkout repository 27 | uses: actions/checkout@v4 28 | 29 | # Initializes the CodeQL tools for scanning. 30 | - name: Initialize CodeQL 31 | uses: github/codeql-action/init@v3 32 | with: 33 | languages: go 34 | build-mode: manual 35 | 36 | - name: Install Taskfile support 37 | uses: arduino/setup-task@v2 38 | 39 | - shell: bash 40 | run: task build 41 | 42 | - name: Perform CodeQL Analysis 43 | uses: github/codeql-action/analyze@v3 44 | with: 45 | category: "/language:go" 46 | -------------------------------------------------------------------------------- /.github/workflows/merge-up.yml: -------------------------------------------------------------------------------- 1 | name: Merge up 2 | 3 | on: 4 | push: 5 | branches: 6 | - release/*.* 7 | - v* 8 | 9 | permissions: 10 | id-token: write 11 | contents: write 12 | pull-requests: write 13 | 14 | jobs: 15 | merge-up: 16 | name: Create merge up pull request 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - uses: mongodb-labs/drivers-github-tools/secure-checkout@v2 21 | with: 22 | app_id: ${{ vars.PR_APP_ID }} 23 | private_key: ${{ secrets.PR_APP_PRIVATE_KEY }} 24 | # Make sure to include fetch-depth 0 so all branches are fetched, not 25 | # just the current one 26 | fetch-depth: 0 27 | 28 | - name: Create pull request 29 | id: create-pull-request 30 | uses: alcaeus/automatic-merge-up-action@1.0.0 31 | with: 32 | ref: ${{ github.ref_name }} 33 | branchNamePattern: 'release/.' 34 | devBranchNamePattern: 'v' 35 | fallbackBranch: 'master' 36 | ignoredBranches: ${{ vars.IGNORED_MERGE_UP_BRANCHES }} 37 | enableAutoMerge: true 38 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: GoDriver Tests 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | concurrency: 8 | group: test-${{ github.ref }} 9 | cancel-in-progress: true 10 | 11 | defaults: 12 | run: 13 | shell: bash -eux {0} 14 | 15 | jobs: 16 | pre_commit: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v4 20 | - uses: actions/setup-python@v5 21 | - uses: actions/setup-go@v5 22 | with: 23 | go-version: 'stable' 24 | - uses: pre-commit/action@v3.0.1 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | debug 3 | .idea 4 | *.iml 5 | *.ipr 6 | *.iws 7 | .idea 8 | *.sublime-project 9 | *.sublime-workspace 10 | driver-test-data.tar.gz 11 | perf 12 | perf.json 13 | perf.suite 14 | **mongocryptd.pid 15 | *.test 16 | .DS_Store 17 | install 18 | main.so 19 | .cache 20 | install 21 | libmongocrypt 22 | venv 23 | test.suite 24 | go.work.sum 25 | .task 26 | env.sh 27 | expansion.yml 28 | 29 | # AWS SAM-generated files 30 | internal/cmd/faas/awslambda/.aws-sam 31 | internal/cmd/faas/awslambda/events/event.json 32 | 33 | # Ignore compiled binaries from the compilecheck 34 | internal/cmd/compilecheck/compilecheck 35 | internal/cmd/compilecheck/compilecheck.so 36 | 37 | # Ignore api report files 38 | api-report.md 39 | api-report.txt 40 | 41 | # Ignore secrets files 42 | secrets-expansion.yml 43 | secrets-export.sh 44 | .test.env 45 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "specifications"] 2 | path = testdata/specifications 3 | url = https://github.com/mongodb/specifications 4 | -------------------------------------------------------------------------------- /bson/array_codec.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package bson 8 | 9 | import ( 10 | "reflect" 11 | 12 | "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" 13 | ) 14 | 15 | // arrayCodec is the Codec used for bsoncore.Array values. 16 | type arrayCodec struct{} 17 | 18 | // EncodeValue is the ValueEncoder for bsoncore.Array values. 19 | func (ac *arrayCodec) EncodeValue(_ EncodeContext, vw ValueWriter, val reflect.Value) error { 20 | if !val.IsValid() || val.Type() != tCoreArray { 21 | return ValueEncoderError{Name: "CoreArrayEncodeValue", Types: []reflect.Type{tCoreArray}, Received: val} 22 | } 23 | 24 | arr := val.Interface().(bsoncore.Array) 25 | return copyArrayFromBytes(vw, arr) 26 | } 27 | 28 | // DecodeValue is the ValueDecoder for bsoncore.Array values. 29 | func (ac *arrayCodec) DecodeValue(_ DecodeContext, vr ValueReader, val reflect.Value) error { 30 | if !val.CanSet() || val.Type() != tCoreArray { 31 | return ValueDecoderError{Name: "CoreArrayDecodeValue", Types: []reflect.Type{tCoreArray}, Received: val} 32 | } 33 | 34 | if val.IsNil() { 35 | val.Set(reflect.MakeSlice(val.Type(), 0, 0)) 36 | } 37 | 38 | val.SetLen(0) 39 | arr, err := appendArrayBytes(val.Interface().(bsoncore.Array), vr) 40 | val.Set(reflect.ValueOf(arr)) 41 | return err 42 | } 43 | -------------------------------------------------------------------------------- /bson/extjson_prose_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package bson 8 | 9 | import ( 10 | "fmt" 11 | "testing" 12 | 13 | "go.mongodb.org/mongo-driver/v2/internal/assert" 14 | ) 15 | 16 | func TestExtJSON(t *testing.T) { 17 | timestampNegativeInt32Err := fmt.Errorf("$timestamp i number should be uint32: -1") 18 | timestampNegativeInt64Err := fmt.Errorf("$timestamp i number should be uint32: -2147483649") 19 | timestampLargeValueErr := fmt.Errorf("$timestamp i number should be uint32: 4294967296") 20 | 21 | testCases := []struct { 22 | name string 23 | input string 24 | canonical bool 25 | err error 26 | }{ 27 | {"timestamp - negative int32 value", `{"":{"$timestamp":{"t":0,"i":-1}}}`, false, timestampNegativeInt32Err}, 28 | {"timestamp - negative int64 value", `{"":{"$timestamp":{"t":0,"i":-2147483649}}}`, false, timestampNegativeInt64Err}, 29 | {"timestamp - value overflows uint32", `{"":{"$timestamp":{"t":0,"i":4294967296}}}`, false, timestampLargeValueErr}, 30 | {"top level key is not treated as special", `{"$code": "foo"}`, false, nil}, 31 | {"escaped single quote errors", `{"f\'oo": "bar"}`, false, ErrInvalidJSON}, 32 | } 33 | for _, tc := range testCases { 34 | t.Run(tc.name, func(t *testing.T) { 35 | var res Raw 36 | err := UnmarshalExtJSON([]byte(tc.input), tc.canonical, &res) 37 | if tc.err == nil { 38 | assert.Nil(t, err, "UnmarshalExtJSON error: %v", err) 39 | return 40 | } 41 | 42 | assert.NotNil(t, err, "expected error %v, got nil", tc.err) 43 | assert.Equal(t, tc.err.Error(), err.Error(), "expected error %v, got %v", tc.err, err) 44 | }) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /bson/fuzz_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // fuzz_test.go is used by the "oss-fuzz" integration. Use caution when 8 | // modifying this file because it may break that integration. 9 | // 10 | // See https://github.com/google/oss-fuzz/tree/master/projects/mongo-go-driver 11 | 12 | package bson 13 | 14 | import ( 15 | "testing" 16 | ) 17 | 18 | func FuzzDecode(f *testing.F) { 19 | seedBSONCorpus(f) 20 | 21 | f.Fuzz(func(t *testing.T, data []byte) { 22 | for _, typ := range []func() interface{}{ 23 | func() interface{} { return new(D) }, 24 | func() interface{} { return new([]E) }, 25 | func() interface{} { return new(M) }, 26 | func() interface{} { return new(interface{}) }, 27 | func() interface{} { return make(map[string]interface{}) }, 28 | func() interface{} { return new([]interface{}) }, 29 | } { 30 | i := typ() 31 | if err := Unmarshal(data, i); err != nil { 32 | return 33 | } 34 | 35 | encoded, err := Marshal(i) 36 | if err != nil { 37 | t.Fatalf("failed to marshal: %v", err) 38 | } 39 | 40 | if err := Unmarshal(encoded, i); err != nil { 41 | t.Fatalf("failed to unmarshal: %v", err) 42 | } 43 | } 44 | }) 45 | } 46 | -------------------------------------------------------------------------------- /bson/marshaling_cases_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package bson 8 | 9 | type marshalingTestCase struct { 10 | name string 11 | reg *Registry 12 | val interface{} 13 | want []byte 14 | } 15 | 16 | var marshalingTestCases = []marshalingTestCase{ 17 | { 18 | "small struct", 19 | nil, 20 | struct { 21 | Foo bool 22 | }{Foo: true}, 23 | docToBytes(D{{"foo", true}}), 24 | }, 25 | } 26 | -------------------------------------------------------------------------------- /bson/mgocompat/registry.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package mgocompat 8 | 9 | import ( 10 | "go.mongodb.org/mongo-driver/v2/bson" 11 | ) 12 | 13 | // Registry is the mgo compatible bson.Registry. It contains the default and 14 | // primitive codecs with mgo compatible options. 15 | var Registry = bson.NewMgoRegistry() 16 | 17 | // RespectNilValuesRegistry is the bson.Registry compatible with mgo withSetRespectNilValues set to true. 18 | var RespectNilValuesRegistry = bson.NewRespectNilValuesMgoRegistry() 19 | -------------------------------------------------------------------------------- /bson/reader.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package bson 8 | 9 | // ArrayReader is implemented by types that allow reading values from a BSON 10 | // array. 11 | type ArrayReader interface { 12 | ReadValue() (ValueReader, error) 13 | } 14 | 15 | // DocumentReader is implemented by types that allow reading elements from a 16 | // BSON document. 17 | type DocumentReader interface { 18 | ReadElement() (string, ValueReader, error) 19 | } 20 | 21 | // ValueReader is a generic interface used to read values from BSON. This type 22 | // is implemented by several types with different underlying representations of 23 | // BSON, such as a bson.Document, raw BSON bytes, or extended JSON. 24 | type ValueReader interface { 25 | Type() Type 26 | Skip() error 27 | 28 | ReadArray() (ArrayReader, error) 29 | ReadBinary() (b []byte, btype byte, err error) 30 | ReadBoolean() (bool, error) 31 | ReadDocument() (DocumentReader, error) 32 | ReadCodeWithScope() (code string, dr DocumentReader, err error) 33 | ReadDBPointer() (ns string, oid ObjectID, err error) 34 | ReadDateTime() (int64, error) 35 | ReadDecimal128() (Decimal128, error) 36 | ReadDouble() (float64, error) 37 | ReadInt32() (int32, error) 38 | ReadInt64() (int64, error) 39 | ReadJavascript() (code string, err error) 40 | ReadMaxKey() error 41 | ReadMinKey() error 42 | ReadNull() error 43 | ReadObjectID() (ObjectID, error) 44 | ReadRegex() (pattern, options string, err error) 45 | ReadString() (string, error) 46 | ReadSymbol() (symbol string, err error) 47 | ReadTimestamp() (t, i uint32, err error) 48 | ReadUndefined() error 49 | } 50 | -------------------------------------------------------------------------------- /bson/testdata/code.json.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb/mongo-go-driver/579a2659ff88b1c612182a97b69efe3b0523a76c/bson/testdata/code.json.gz -------------------------------------------------------------------------------- /bson/testdata/fuzz/FuzzDecode/002ae7d43f636100116fede772a03d07726ed75c3c3b83da865fe9b718adf8ae: -------------------------------------------------------------------------------- 1 | go test fuzz v1 2 | []byte("\x10\x00\x00\x00\v\x00\x00\x00\b\x00\x00\v\x00\x00\x00\x00") 3 | -------------------------------------------------------------------------------- /bson/testdata/fuzz/FuzzDecode/0de854041b0055ca1e5e6e54a7fb667ed38461db171af267665c21776f9a9ef4: -------------------------------------------------------------------------------- 1 | go test fuzz v1 2 | []byte("0\\x00\\x00\\x00\\x0f\\x00000\\x8a00000000000000000000000000000000000000\n") 3 | -------------------------------------------------------------------------------- /bson/testdata/fuzz/FuzzDecode/718592474a0a3626039f3471449b9aa374c746754d4925fcfe4ba747e7101504: -------------------------------------------------------------------------------- 1 | go test fuzz v1 2 | []byte("\\x80\\x00\\x00\\x00\\x03000000\\x00s\\x00\\x00\\x00\\x0300000\\x00g\\x00\\x00\\x00\\x100z\\x000000\\x11\\x00000\\x150000\\x020\\x00\\x02\\x00\\x00\\x000\\x12\\x00\\x050\\x00\\x01\\x00\\x00\\x0000\\x050\\x00\\x01\\x00\\x00\\x0000\\x040\\x00200000\\x00\\x000\\x02\\x00\\x10\\x0000000\\x110\\x0000000000\\x020\\x00\\x02\\x00\\x00\\x000\\x00\\x050\\x00\\x01\\x00\\x00\\x0000\\x050\\x00\\x01\\x00\\x00\\x0000\\x00\\x00\\x00\\x00\n") 3 | -------------------------------------------------------------------------------- /bson/testdata/fuzz/FuzzDecode/93c43e3c1cf35c19b7618a618d128cea0ce05cef0711fdd91e403fe3b2f45628: -------------------------------------------------------------------------------- 1 | go test fuzz v1 2 | []byte("\\x59\\x01\\x00\\x00\\x01\\x64\\x6f\\x75\\x62\\x6c\\x65\\x00\\x9a\\x99\\x99\\x99\\x99\\x99\\xf1\\x3f\\x02\\x73\\x74\\x72\\x69\\x6e\\x67\\x00\\x06\\x00\\x00\\x00\\x68\\x65\\x6c\\x6c\\x6f\\x00\\x03\\x65\\x6d\\x62\\x65\\x64\\x64\\x65\\x64\\x00\\x4b\\x00\\x00\\x00\\x04\\x61\\x72\\x72\\x61\\x79\\x00\\x3f\\x00\\x00\\x00\\x10\\x30\\x00\\x01\\x00\\x00\\x00\\x01\\x31\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x02\\x32\\x00\\x02\\x00\\x00\\x00\\x33\\x00\\x04\\x33\\x00\\x0c\\x00\\x00\\x00\\x10\\x30\\x00\\x04\\x00\\x00\\x00\\x00\\x03\\x34\\x00\\x0d\\x00\\x00\\x00\\x03\\x35\\x00\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x62\\x69\\x6e\\x61\\x72\\x79\\x00\\x03\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x07\\x6f\\x62\\x6a\\x65\\x63\\x74\\x69\\x64\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x62\\x6f\\x6f\\x6c\\x65\\x61\\x6e\\x00\\x01\\x09\\x64\\x61\\x74\\x65\\x74\\x69\\x6d\\x65\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0a\\x6e\\x75\\x6c\\x6c\\x00\\x0b\\x72\\x65\\x67\\x65\\x78\\x00\\x68\\x65\\x6c\\x6c\\x6f\\x00\\x69\\x00\\x0d\\x6a\\x73\\x00\\x0e\\x00\\x00\\x00\\x66\\x75\\x6e\\x63\\x74\\x69\\x6f\\x6e\\x28\\x29\\x20\\x7b\\x7d\\x00\\x0f\\x73\\x63\\x6f\\x70\\x65\\x00\\x2c\\x00\\x00\\x00\\x0e\\x00\\x00\\x00\\x66\\x75\\x6e\\x63\\x74\\x69\\x6f\\x6e\\x28\\x29\\x20\\x7b\\x7d\\x00\\x16\\x00\\x00\\x00\\x02\\x68\\x65\\x6c\\x6c\\x6f\\x00\\x06\\x00\\x00\\x00\\x77\\x6f\\x72\\x6c\\x64\\x00\\x00\\x10\\x69\\x6e\\x74\\x33\\x32\\x00\\x20\\x00\\x00\\x00\\x11\\x74\\x69\\x6d\\x65\\x73\\x74\\x61\\x6d\\x70\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x12\\x69\\x6e\\x74\\x36\\x34\\x00\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\x6d\\x69\\x6e\\x6b\\x65\\x79\\x00\\x7f\\x6d\\x61\\x78\\x6b\\x65\\x79\\x00\\x00\"\n") 3 | -------------------------------------------------------------------------------- /bson/testdata/fuzz/FuzzDecode/c3ffbb42eb85b743ede396f00b7706e6ad0529c32689c63ca663dae37d072627: -------------------------------------------------------------------------------- 1 | go test fuzz v1 2 | []byte("\\x05\\xf0\\xff\\x00\\x7f\n") 3 | -------------------------------------------------------------------------------- /bson/type_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package bson 8 | 9 | import ( 10 | "testing" 11 | ) 12 | 13 | func TestType(t *testing.T) { 14 | testCases := []struct { 15 | name string 16 | t Type 17 | want string 18 | }{ 19 | {"double", TypeDouble, "double"}, 20 | {"string", TypeString, "string"}, 21 | {"embedded document", TypeEmbeddedDocument, "embedded document"}, 22 | {"array", TypeArray, "array"}, 23 | {"binary", TypeBinary, "binary"}, 24 | {"undefined", TypeUndefined, "undefined"}, 25 | {"objectID", TypeObjectID, "objectID"}, 26 | {"boolean", TypeBoolean, "boolean"}, 27 | {"UTC datetime", TypeDateTime, "UTC datetime"}, 28 | {"null", TypeNull, "null"}, 29 | {"regex", TypeRegex, "regex"}, 30 | {"dbPointer", TypeDBPointer, "dbPointer"}, 31 | {"javascript", TypeJavaScript, "javascript"}, 32 | {"symbol", TypeSymbol, "symbol"}, 33 | {"code with scope", TypeCodeWithScope, "code with scope"}, 34 | {"32-bit integer", TypeInt32, "32-bit integer"}, 35 | {"timestamp", TypeTimestamp, "timestamp"}, 36 | {"64-bit integer", TypeInt64, "64-bit integer"}, 37 | {"128-bit decimal", TypeDecimal128, "128-bit decimal"}, 38 | {"max key", TypeMaxKey, "max key"}, 39 | {"min key", TypeMinKey, "min key"}, 40 | {"invalid", (0), "invalid"}, 41 | } 42 | 43 | for _, tc := range testCases { 44 | t.Run(tc.name, func(t *testing.T) { 45 | got := tc.t.String() 46 | if got != tc.want { 47 | t.Errorf("String outputs do not match. got %s; want %s", got, tc.want) 48 | } 49 | }) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /docs/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Summary 4 | 5 | 6 | 7 | ## Background & Motivation 8 | 9 | 10 | -------------------------------------------------------------------------------- /etc/api_report.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # api-report 3 | # Generates a report of Go Driver API changes for the current branch. 4 | set -eux 5 | 6 | # Skip the report of it isn't a PR run. 7 | if [ "$BASE_SHA" == "$HEAD_SHA" ]; then 8 | echo "Skipping API Report" 9 | exit 0 10 | fi 11 | 12 | # Ensure a clean checkout. 13 | git checkout -b test-api-report 14 | git add . 15 | git commit -m "local changes" 16 | 17 | # Ensure gorelease is installed. 18 | cmd=$(command -v gorelease || true) 19 | if [ -z $cmd ]; then 20 | go install golang.org/x/exp/cmd/gorelease@latest 21 | fi 22 | 23 | # Generate and parse the report. 24 | gorelease -base=$BASE_SHA > api-report.txt || true 25 | cat api-report.txt 26 | go run ./internal/cmd/parse-api-report/main.go 27 | rm api-report.txt 28 | 29 | # Make the PR comment. 30 | target=$DRIVERS_TOOLS/.evergreen/github_app/create_or_modify_comment.sh 31 | bash $target -m "## API Change Report" -c "$(pwd)/api-report.md" -h $HEAD_SHA -o "mongodb" -n "mongo-go-driver" 32 | -------------------------------------------------------------------------------- /etc/assets/docs-mongodb-green.svg: -------------------------------------------------------------------------------- 1 | docsdocsmongodbmongodb 2 | -------------------------------------------------------------------------------- /etc/assets/godev-bson-blue.svg: -------------------------------------------------------------------------------- 1 | go.devgo.devbsonbson 2 | -------------------------------------------------------------------------------- /etc/assets/godev-mongo-blue.svg: -------------------------------------------------------------------------------- 1 | go.devgo.devmongomongo 2 | -------------------------------------------------------------------------------- /etc/assets/mongo-gopher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb/mongo-go-driver/579a2659ff88b1c612182a97b69efe3b0523a76c/etc/assets/mongo-gopher.png -------------------------------------------------------------------------------- /etc/check_fmt.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # check_fmt 3 | # Runs go fmt on all packages in the repo and checks that *_example_test.go files have wrapped lines. 4 | 5 | gofmt_out="$(go fmt ./...)" 6 | 7 | if [[ $gofmt_out ]]; then 8 | echo "go fmt check failed for:"; 9 | sed -e 's/^/ - /' <<< "$gofmt_out"; 10 | exit 1; 11 | fi 12 | 13 | # Use the "github.com/walle/lll" tool to check that all lines in *_example_test.go files are 14 | # wrapped at 80 characters to keep them readable when rendered on https://pkg.go.dev. 15 | # Ignore long lines that are comments containing URI-like strings and testable example output 16 | # comments like "// Output: ...". 17 | # E.g ignored lines: 18 | # // "mongodb://ldap-user:ldap-pwd@localhost:27017/?authMechanism=PLAIN" 19 | # // (https://www.mongodb.com/docs/manual/core/authentication-mechanisms-enterprise/#security-auth-ldap). 20 | # // Output: {"myint": {"$numberLong":"1"},"int32": {"$numberLong":"1"},"int64": {"$numberLong":"1"}} 21 | lll_out="$(find . -type f -name "*_examples_test.go" | lll -w 4 -l 80 -e '^\s*\/\/(.+:\/\/| Output:)' --files)" 22 | 23 | if [[ $lll_out ]]; then 24 | echo "lll check failed for:"; 25 | sed -e 's/^/ - /' <<< "$lll_out"; 26 | exit 1; 27 | fi 28 | -------------------------------------------------------------------------------- /etc/check_license.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | year=$(date +"%Y") 4 | copyright=$"// Copyright (C) MongoDB, Inc. $year-present. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the \"License\"); you may 7 | // not use this file except in compliance with the License. You may obtain 8 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | " 10 | 11 | add_copyright() { 12 | file=$1 13 | 14 | # Check if first 24 bytes match first 24 bytes of copyright notice. 15 | local line 16 | line=$(head -c 24 $file) 17 | if [ "$line" == "// Copyright (C) MongoDB" ]; then 18 | if [ ! -z "$verbose" ]; then 19 | echo "$file already has copyright notice" >&2 20 | fi 21 | return 22 | fi 23 | 24 | # Check if first 14 bytes matches the prefix "// Copied from" 25 | line=$(head -c 14 $file) 26 | if [ "$line" == "// Copied from" ]; then 27 | if [ ! -z "$verbose" ]; then 28 | echo "$file has a third-party copyright notice" >&2 29 | fi 30 | return 31 | fi 32 | 33 | if [ ! -z "$add" ]; then 34 | echo "$copyright" | cat - $file > temp && mv temp $file 35 | return 36 | fi 37 | 38 | echo "Missing copyright notice in \"$file\". Run \"task add-license\" to add missing licenses." 39 | exit 1 40 | } 41 | 42 | # Options are: 43 | # -a : Add licenses that are missing. 44 | # -v : Verbose. Print all files as they're checked. 45 | while getopts at:vt: flag 46 | do 47 | case "${flag}" in 48 | a) add=1;; 49 | v) verbose=1;; 50 | *) 51 | echo "flag not recognized" 52 | exit 1 53 | ;; 54 | esac 55 | done 56 | 57 | # Find all .go files and try to write a license notice. 58 | GO_FILES=$(find . -type f -name "*.go" -print) 59 | 60 | for file in $GO_FILES 61 | do 62 | add_copyright "$file" 63 | done 64 | -------------------------------------------------------------------------------- /etc/check_modules.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # check-modules runs "go mod tidy" on each module and exits with a non-zero exit code if there 3 | # are any module changes. The intent is to confirm that exactly the required 4 | # modules are declared as dependencies. We should always be able to run "go mod 5 | # tidy" and expect that no unrelated changes are made to the "go.mod" file. 6 | set -eu 7 | 8 | mods=$(find . -name go.mod) 9 | exit_code=0 10 | for mod in $mods; do 11 | pushd "$(dirname $mod)" > /dev/null 12 | echo "Checking $mod..." 13 | go mod tidy -v 14 | git diff --exit-code go.mod go.sum || { 15 | exit_code=$? 16 | } 17 | echo "Checking $mod... done" 18 | popd > /dev/null 19 | done 20 | exit $exit_code 21 | -------------------------------------------------------------------------------- /etc/compile_check.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e # exit when any command fails 3 | set -x # show all commands being run 4 | 5 | : ${GC:=go${GO_VERSION="1.19"}} 6 | 7 | COMPILE_CHECK_DIR="internal/cmd/compilecheck" 8 | ARCHITECTURES=("386" "arm" "arm64" "ppc64le" "s390x") 9 | BUILD_CMD="${GC} build -buildvcs=false" 10 | 11 | # compile_check will attempt to build the internal/test/compilecheck project 12 | # using the provided Go version. This is to simulate an end-to-end use case. 13 | function compile_check { 14 | # Change the directory to the compilecheck test directory. 15 | pushd "${COMPILE_CHECK_DIR}" >/dev/null 16 | 17 | # If a custom Go version is set using the GO_VERSION env var (e.g. "1.18"), 18 | # add the GOPATH bin directory to PATH and then install that Go version. 19 | if [ ! -z "$GO_VERSION" ]; then 20 | PATH=$(go env GOPATH)/bin:$PATH 21 | export PATH 22 | 23 | go install golang.org/dl/go$GO_VERSION@latest 24 | ${GC} download 25 | fi 26 | 27 | ${GC} version 28 | ${GC} mod tidy 29 | 30 | # Standard build 31 | $BUILD_CMD ./... 32 | 33 | # Dynamic linking 34 | $BUILD_CMD -buildmode=plugin 35 | 36 | # Check build with tags. 37 | [[ -n "$BUILD_TAGS" ]] && $BUILD_CMD $BUILD_TAGS ./... 38 | 39 | # Check build with various architectures. 40 | for ARCH in "${ARCHITECTURES[@]}"; do 41 | GOOS=linux GOARCH=$ARCH $BUILD_CMD ./... 42 | done 43 | 44 | # Change the directory back to the working directory. 45 | popd >/dev/null 46 | } 47 | 48 | compile_check 49 | -------------------------------------------------------------------------------- /etc/docker_entry.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Entry point for Dockerfile for running a go test. 4 | # 5 | set -eux 6 | 7 | # Prep files. 8 | cd /src 9 | rm -f test.suite 10 | cp -r $HOME/install ./install 11 | 12 | export PATH="$MONGODB_BINARIES:$HOME/go/bin:$PATH" 13 | 14 | task setup-test 15 | 16 | # Run the test. 17 | task $TASKFILE_TARGET 18 | -------------------------------------------------------------------------------- /etc/gen-ec-certs/client.ext: -------------------------------------------------------------------------------- 1 | basicConstraints = CA: FALSE 2 | subjectAltName = DNS: localhost, IP: 127.0.0.1 3 | extendedKeyUsage = clientAuth 4 | -------------------------------------------------------------------------------- /etc/gen-ec-certs/empty.cnf: -------------------------------------------------------------------------------- 1 | # A nearly empty OpenSSL CA configuration file. 2 | # `openssl req` complains without a configuration file. 3 | [ req ] 4 | distinguished_name = distinguished_name 5 | 6 | [ distinguished_name ] 7 | -------------------------------------------------------------------------------- /etc/gen-ec-certs/server.ext: -------------------------------------------------------------------------------- 1 | basicConstraints = CA: FALSE 2 | subjectAltName = DNS: localhost, IP: 127.0.0.1 3 | extendedKeyUsage = serverAuth 4 | -------------------------------------------------------------------------------- /etc/golangci-lint.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -ex 3 | 4 | # Keep this in sync with go version used in static-analysis Evergreen build variant. 5 | GO_VERSION=1.22.8 6 | GOLANGCI_LINT_VERSION=1.60.1 7 | 8 | # Unset the cross-compiler overrides while downloading binaries. 9 | GOOS_ORIG=${GOOS:-} 10 | export GOOS= 11 | GOARCH_ORIG=${GOARCH:-} 12 | export GOARCH= 13 | 14 | go install golang.org/dl/go$GO_VERSION@latest 15 | go${GO_VERSION} download 16 | GOROOT="$(go${GO_VERSION} env GOROOT)" 17 | PATH="$GOROOT/bin:$PATH" 18 | export PATH 19 | export GOROOT 20 | go install github.com/golangci/golangci-lint/cmd/golangci-lint@v${GOLANGCI_LINT_VERSION} 21 | 22 | export GOOS=$GOOS_ORIG 23 | export GOARCH=$GOARCH_ORIG 24 | golangci-lint run --config .golangci.yml ./... 25 | -------------------------------------------------------------------------------- /etc/install-libmongocrypt.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # install libmongocrypt 3 | # This script installs libmongocrypt into an "install" directory. 4 | set -eux 5 | 6 | LIBMONGOCRYPT_TAG="1.12.0" 7 | 8 | # Install libmongocrypt based on OS. 9 | if [ "Windows_NT" = "${OS:-}" ]; then 10 | mkdir -p c:/libmongocrypt/include 11 | mkdir -p c:/libmongocrypt/bin 12 | echo "fetching build for Windows ... begin" 13 | mkdir libmongocrypt-all 14 | cd libmongocrypt-all 15 | # The following URL is published from the upload-all task in the libmongocrypt Evergreen project. 16 | curl -L https://github.com/mongodb/libmongocrypt/releases/download/$LIBMONGOCRYPT_TAG/libmongocrypt-windows-x86_64-$LIBMONGOCRYPT_TAG.tar.gz -o libmongocrypt-all.tar.gz 17 | tar -xf libmongocrypt-all.tar.gz 18 | cd .. 19 | cp libmongocrypt-all/bin/mongocrypt.dll c:/libmongocrypt/bin 20 | cp libmongocrypt-all/include/mongocrypt/*.h c:/libmongocrypt/include 21 | 22 | rm -rf libmongocrypt-all 23 | echo "fetching build for Windows ... end" 24 | else 25 | rm -rf libmongocrypt 26 | git clone https://github.com/mongodb/libmongocrypt --depth=1 --branch $LIBMONGOCRYPT_TAG 2> /dev/null 27 | if ! ( ./libmongocrypt/.evergreen/compile.sh >| output.txt 2>&1 ); then 28 | cat output.txt 1>&2 29 | exit 1 30 | fi 31 | mv output.txt install 32 | rm -rf libmongocrypt 33 | fi 34 | -------------------------------------------------------------------------------- /etc/pr-task.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -eu 3 | 4 | VARLIST=( 5 | PR_TASK 6 | COMMIT 7 | DRIVERS_TOOLS 8 | ) 9 | 10 | # Ensure that all variables required to run the test are set, otherwise throw 11 | # an error. 12 | for VARNAME in "${VARLIST[@]}"; do 13 | [[ -z "${!VARNAME:-}" ]] && echo "ERROR: $VARNAME not set" && exit 1; 14 | done 15 | 16 | case $PR_TASK in 17 | apply-labels) 18 | CONFIG=$(pwd)/.github/labeler.yml 19 | SCRIPT="${DRIVERS_TOOLS}/.evergreen/github_app/apply-labels.sh" 20 | bash $SCRIPT -l $CONFIG -h $COMMIT -o "mongodb" -n "mongo-go-driver" 21 | ;; 22 | assign-reviewer) 23 | CONFIG=$(pwd)/.github/reviewers.txt 24 | SCRIPT="${DRIVERS_TOOLS}/.evergreen/github_app/assign-reviewer.sh" 25 | bash $SCRIPT -p $CONFIG -h $COMMIT -o "mongodb" -n "mongo-go-driver" 26 | ;; 27 | backport-pr) 28 | bash ${DRIVERS_TOOLS}/.evergreen/github_app/backport-pr.sh mongodb mongo-go-driver $COMMIT 29 | ;; 30 | esac 31 | -------------------------------------------------------------------------------- /etc/run-awskms-test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # run-awskms-test 3 | # Runs the awskms test. 4 | set -eu 5 | 6 | GO_BUILD_TAGS="cse" task setup-test 7 | task build-kms-test 8 | 9 | . ${DRIVERS_TOOLS}/.evergreen/secrets_handling/setup-secrets.sh drivers/atlas_connect 10 | export MONGODB_URI="$ATLAS_FREE" 11 | 12 | if [ -z "${EXPECT_ERROR:-}" ]; then 13 | . ${DRIVERS_TOOLS}/.evergreen/csfle/setup-secrets.sh 14 | export AWS_SECRET_ACCESS_KEY=$FLE_AWS_SECRET_ACCESS_KEY 15 | export AWS_ACCESS_KEY_ID=$FLE_AWS_ACCESS_KEY_ID 16 | fi 17 | 18 | LD_LIBRARY_PATH=./install/libmongocrypt/lib64 PROVIDER='aws' ./testkms 19 | -------------------------------------------------------------------------------- /etc/run-azurekms-test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # run-gcpkms-test 3 | # Runs gcpkms tests. 4 | set -eu 5 | 6 | GO_BUILD_TAGS="cse" task setup-test 7 | task build-kms-test 8 | 9 | if [ -n "${EXPECT_ERROR:-}" ]; then 10 | . ${DRIVERS_TOOLS}/.evergreen/csfle/azurekms/setup-secrets.sh 11 | LD_LIBRARY_PATH=./install/libmongocrypt/lib64 \ 12 | MONGODB_URI='mongodb://localhost:27017' \ 13 | EXPECT_ERROR='unable to retrieve azure credentials' \ 14 | PROVIDER='azure' AZUREKMS_KEY_NAME=$AZUREKMS_KEYNAME AZUREKMS_KEY_VAULT_ENDPOINT=$AZUREKMS_KEYVAULTENDPOINT \ 15 | ./testkms 16 | exit 0 17 | fi 18 | 19 | echo "Copying files ... begin" 20 | source ${DRIVERS_TOOLS}/.evergreen/csfle/azurekms/secrets-export.sh 21 | tar czf testazurekms.tgz ./testkms ./install/libmongocrypt/lib64/libmongocrypt.* 22 | AZUREKMS_SRC=testazurekms.tgz AZUREKMS_DST=/tmp ${DRIVERS_TOOLS}/.evergreen/csfle/azurekms/copy-file.sh 23 | echo "Copying files ... end" 24 | echo "Untarring file ... begin" 25 | AZUREKMS_CMD="tar xf /tmp/testazurekms.tgz" ${DRIVERS_TOOLS}/.evergreen/csfle/azurekms/run-command.sh 26 | echo "Untarring file ... end" 27 | 28 | AZUREKMS_CMD="LD_LIBRARY_PATH=./install/libmongocrypt/lib64 MONGODB_URI='mongodb://localhost:27017' PROVIDER='azure' AZUREKMS_KEY_NAME=$AZUREKMS_KEYNAME AZUREKMS_KEY_VAULT_ENDPOINT=$AZUREKMS_KEYVAULTENDPOINT ./testkms" ${DRIVERS_TOOLS}/.evergreen/csfle/azurekms/run-command.sh 29 | -------------------------------------------------------------------------------- /etc/run-compile-check-test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # run-compile-check-test 3 | # Run compile check tests. 4 | set -eu 5 | set +x 6 | 7 | echo "Running internal/test/compilecheck" 8 | pushd internal/test/compilecheck 9 | GOWORK=off go test -timeout 30m -v ./... >>../../../test.suite 10 | popd 11 | -------------------------------------------------------------------------------- /etc/run-gcpkms-test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # run-gcpkms-test 3 | # Runs gcpkms tests. 4 | set -eu 5 | 6 | GO_BUILD_TAGS="cse" task setup-test 7 | task build-kms-test 8 | 9 | if [ -n "${EXPECT_ERROR:-}" ]; then 10 | LD_LIBRARY_PATH=./install/libmongocrypt/lib64 \ 11 | MONGODB_URI='mongodb://localhost:27017/' \ 12 | EXPECT_ERROR='unable to retrieve GCP credentials' \ 13 | PROVIDER='gcp' \ 14 | ./testkms 15 | exit 0 16 | fi 17 | 18 | source ${DRIVERS_TOOLS}/.evergreen/csfle/gcpkms/secrets-export.sh 19 | echo "Copying files ... begin" 20 | tar czf testgcpkms.tgz ./testkms ./install/libmongocrypt/lib64/libmongocrypt.* 21 | GCPKMS_SRC=testgcpkms.tgz GCPKMS_DST=$GCPKMS_INSTANCENAME: ${DRIVERS_TOOLS}/.evergreen/csfle/gcpkms/copy-file.sh 22 | echo "Copying files ... end" 23 | 24 | echo "Untarring file ... begin" 25 | GCPKMS_CMD="tar xf testgcpkms.tgz" ${DRIVERS_TOOLS}/.evergreen/csfle/gcpkms/run-command.sh 26 | echo "Untarring file ... end" 27 | 28 | GCPKMS_CMD="LD_LIBRARY_PATH=./install/libmongocrypt/lib64 MONGODB_URI='mongodb://localhost:27017' PROVIDER='gcp' ./testkms" ${DRIVERS_TOOLS}/.evergreen/csfle/gcpkms/run-command.sh 29 | -------------------------------------------------------------------------------- /etc/run-goleak-test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # run-goleak-test 3 | # Run goroutine leak tests. 4 | set -eu 5 | set +x 6 | 7 | echo "Running internal/test/goleak" 8 | pushd internal/test/goleak 9 | go test -v ./... >> ../../../test.suite 10 | popd 11 | -------------------------------------------------------------------------------- /etc/run-mongodb-aws-ecs-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -eu 3 | 4 | if [ "${SKIP_ECS_AUTH_TEST:-}" = "true" ]; then 5 | echo "This platform does not support the ECS auth test, skipping..." 6 | exit 0 7 | fi 8 | 9 | task build-aws-ecs-test 10 | 11 | AUTH_AWS_DIR=${DRIVERS_TOOLS}/.evergreen/auth_aws 12 | ECS_SRC_DIR=$AUTH_AWS_DIR/src 13 | 14 | # pack up project directory to ssh it to the container 15 | mkdir -p $ECS_SRC_DIR/.evergreen 16 | cp ${PROJECT_DIRECTORY}/main $ECS_SRC_DIR 17 | cp ${PROJECT_DIRECTORY}/.evergreen/run-mongodb-aws-ecs-test.sh $ECS_SRC_DIR/.evergreen 18 | tar -czf $ECS_SRC_DIR/src.tgz -C ${PROJECT_DIRECTORY} . 19 | 20 | export PROJECT_DIRECTORY="$ECS_SRC_DIR" 21 | $AUTH_AWS_DIR/aws_setup.sh ecs 22 | -------------------------------------------------------------------------------- /etc/run-mongodb-aws-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -eu 4 | 5 | ############################################ 6 | # Main Program # 7 | ############################################ 8 | 9 | # Supported/used environment variables: 10 | # MONGODB_URI Set the URI, including an optional username/password to use 11 | # to connect to the server via MONGODB-AWS authentication 12 | # mechanism. 13 | 14 | echo "Running MONGODB-AWS authentication tests" 15 | 16 | if [ "$AWS_TEST" == "ec2" ] && [ "${SKIP_EC2_AUTH_TEST:-}" == "true" ]; then 17 | echo "This platform does not support the EC2 auth test, skipping..." 18 | exit 0 19 | fi 20 | 21 | if [ "$AWS_TEST" == "web-identity" ] && [ "${SKIP_WEB_IDENTITY_AUTH_TEST:-}" == "true" ]; then 22 | echo "This platform does not support the web identity auth test, skipping..." 23 | exit 0 24 | fi 25 | 26 | # Handle credentials and environment setup. 27 | . $DRIVERS_TOOLS/.evergreen/auth_aws/aws_setup.sh $AWS_TEST 28 | 29 | # show test output 30 | set -x 31 | 32 | # For Go 1.16+, Go builds requires a go.mod file in the current working directory or a parent 33 | # directory. Spawn a new subshell, "cd" to the project directory, then run "go run". 34 | (cd ${PROJECT_DIRECTORY} && go run "./internal/cmd/testaws/main.go" | tee test.suite) 35 | -------------------------------------------------------------------------------- /etc/run-oidc-test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # run-oidc-test 3 | # Runs oidc auth tests. 4 | set -eu 5 | 6 | echo "Running MONGODB-OIDC authentication tests" 7 | 8 | OIDC_ENV="${OIDC_ENV:-"test"}" 9 | 10 | if [ $OIDC_ENV == "test" ]; then 11 | # Make sure DRIVERS_TOOLS is set. 12 | if [ -z "$DRIVERS_TOOLS" ]; then 13 | echo "Must specify DRIVERS_TOOLS" 14 | exit 1 15 | fi 16 | source ${DRIVERS_TOOLS}/.evergreen/auth_oidc/secrets-export.sh 17 | 18 | elif [ $OIDC_ENV == "azure" ]; then 19 | source ./env.sh 20 | 21 | elif [ $OIDC_ENV == "gcp" ]; then 22 | source ./secrets-export.sh 23 | 24 | elif [ $OIDC_ENV == "k8s" ]; then 25 | # "run-driver-test.sh" in drivers-evergreen-tools takes care of sourcing 26 | # "secrets-export.sh". Nothing to do in this block, but we still need a 27 | # command to be syntactically valid, so use no-op command ":". 28 | : 29 | 30 | else 31 | echo "Unrecognized OIDC_ENV $OIDC_ENV" 32 | exit 1 33 | fi 34 | 35 | export TEST_AUTH_OIDC=1 36 | export COVERAGE=1 37 | export AUTH="auth" 38 | 39 | $1 40 | -------------------------------------------------------------------------------- /etc/run_docker.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Script to run a test suite in docker locally 4 | set -eux 5 | 6 | if [ -z "$DRIVERS_TOOLS" ]; then 7 | echo "Please set DRIVERS_TOOLS env variable." 8 | exit 1 9 | fi 10 | PLATFORM=${DOCKER_PLATFORM:-} 11 | docker build $PLATFORM -t go-test . 12 | 13 | # Handle environment variables and optional positional arg for the taskfile target. 14 | TASKFILE_TARGET=${TASKFILE_TARGET:-$1} 15 | TASKFILE_TARGET=${TASKFILE_TARGET:-evg-test-versioned-api} 16 | GO_BUILD_TAGS=${GO_BUILD_TAGS:-""} 17 | 18 | ARGS=" -e TASKFILE_TARGET=$TASKFILE_TARGET" 19 | ARGS="$ARGS -e GO_BUILD_TAGS=$GO_BUILD_TAGS" 20 | ARGS="$ARGS go-test" 21 | 22 | $DRIVERS_TOOLS/.evergreen/docker/run-client.sh $ARGS 23 | if [ -f "test.suite" ]; then 24 | tail test.suite 25 | fi 26 | -------------------------------------------------------------------------------- /etc/setup-encryption.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Script to set up encryption assets and servers. 4 | set -eux 5 | 6 | if [ -z "$DRIVERS_TOOLS" ]; then 7 | echo "Please define DRIVERS_TOOLS variable" 8 | exit 1 9 | fi 10 | 11 | SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) 12 | PARENT_DIR=$(dirname $SCRIPT_DIR) 13 | 14 | # Handle the secrets 15 | export CSFLE_TLS_CA_FILE="${PARENT_DIR}/testdata/kmip-certs/ca-ec.pem" 16 | export CSFLE_TLS_CERT_FILE="${PARENT_DIR}/testdata/kmip-certs/server-ec.pem" 17 | export CSFLE_TLS_CLIENT_CERT_FILE="${PARENT_DIR}/testdata/kmip-certs/client-ec.pem" 18 | 19 | bash $DRIVERS_TOOLS/.evergreen/csfle/setup-secrets.sh 20 | bash $DRIVERS_TOOLS/.evergreen/csfle/start-servers.sh 21 | -------------------------------------------------------------------------------- /etc/update_spec_tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # update_spec_tests spec 3 | # This script is used to fetch the latest tests for the given spec. It puts the tests in the 4 | # directory data/[specname]. It should be run from the root of the repository. 5 | 6 | set -o errexit 7 | set -o nounset 8 | 9 | if [ ! -d ".git" ]; then 10 | echo "$0: This script must be run from the root of the repository" >&2 11 | exit 1 12 | fi 13 | 14 | if [ $# -ne 1 ]; then 15 | echo "$0: This script must be passed exactly one argument for which tests to sync" >&2 16 | exit 1 17 | fi 18 | 19 | tmpdir=`perl -MFile::Temp=tempdir -wle 'print tempdir(TMPDIR => 1, CLEANUP => 0)'` 20 | curl -sL https://github.com/mongodb/specifications/archive/master.zip -o "$tmpdir/specs.zip" 21 | unzip -d "$tmpdir" "$tmpdir/specs.zip" > /dev/null 22 | mkdir -p "data/$1" 23 | rsync -ah "$tmpdir/specifications-master/source/$1/tests/" "data/$1" 24 | rm -rf "$tmpdir" 25 | -------------------------------------------------------------------------------- /examples/_logger/logrus/go.mod: -------------------------------------------------------------------------------- 1 | module go.mongodb.go/mongo-driver/v2/examples/logger/logrus 2 | 3 | go 1.23 4 | 5 | replace go.mongodb.org/mongo-driver/v2 => ../../../ 6 | 7 | require ( 8 | github.com/bombsimon/logrusr/v4 v4.0.0 9 | github.com/sirupsen/logrus v1.9.0 10 | go.mongodb.org/mongo-driver/v2 v2.0.0-alpha2 11 | ) 12 | 13 | require ( 14 | github.com/go-logr/logr v1.2.3 // indirect 15 | github.com/golang/snappy v1.0.0 // indirect 16 | github.com/klauspost/compress v1.16.7 // indirect 17 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 18 | github.com/xdg-go/scram v1.1.2 // indirect 19 | github.com/xdg-go/stringprep v1.0.4 // indirect 20 | github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect 21 | golang.org/x/crypto v0.33.0 // indirect 22 | golang.org/x/sync v0.11.0 // indirect 23 | golang.org/x/sys v0.30.0 // indirect 24 | golang.org/x/text v0.22.0 // indirect 25 | ) 26 | -------------------------------------------------------------------------------- /examples/_logger/logrus/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build logrus 8 | 9 | package main 10 | 11 | import ( 12 | "context" 13 | "log" 14 | 15 | "github.com/bombsimon/logrusr/v4" 16 | "github.com/sirupsen/logrus" 17 | "go.mongodb.org/mongo-driver/v2/bson" 18 | "go.mongodb.org/mongo-driver/v2/mongo" 19 | "go.mongodb.org/mongo-driver/v2/mongo/options" 20 | ) 21 | 22 | func main() { 23 | // Create a new logrus logger instance. 24 | logger := logrus.StandardLogger() 25 | logger.SetLevel(logrus.DebugLevel) 26 | 27 | // Create a new sink for logrus using "logrusr". 28 | sink := logrusr.New(logger).GetSink() 29 | 30 | // Create a client with our logger options. 31 | loggerOptions := options. 32 | Logger(). 33 | SetSink(sink). 34 | SetMaxDocumentLength(25). 35 | SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) 36 | 37 | clientOptions := options. 38 | Client(). 39 | ApplyURI("mongodb://localhost:27017"). 40 | SetLoggerOptions(loggerOptions) 41 | 42 | client, err := mongo.Connect(clientOptions) 43 | if err != nil { 44 | log.Fatalf("error connecting to MongoDB: %v", err) 45 | } 46 | 47 | defer client.Disconnect(context.TODO()) 48 | 49 | // Make a database request to test our logging solution. 50 | coll := client.Database("test").Collection("test") 51 | 52 | _, err = coll.InsertOne(context.TODO(), bson.D{{"Alice", "123"}}) 53 | if err != nil { 54 | log.Fatalf("InsertOne failed: %v", err) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /examples/_logger/zap/go.mod: -------------------------------------------------------------------------------- 1 | module go.mongodb.go/mongo-driver/v2/examples/logger/zap 2 | 3 | go 1.23 4 | 5 | replace go.mongodb.org/mongo-driver/v2 => ../../../ 6 | 7 | require ( 8 | github.com/go-logr/zapr v1.2.3 9 | go.mongodb.org/mongo-driver/v2 v2.0.0-alpha2 10 | go.uber.org/zap v1.24.0 11 | ) 12 | 13 | require ( 14 | github.com/go-logr/logr v1.2.2 // indirect 15 | github.com/golang/snappy v1.0.0 // indirect 16 | github.com/klauspost/compress v1.16.7 // indirect 17 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 18 | github.com/xdg-go/scram v1.1.2 // indirect 19 | github.com/xdg-go/stringprep v1.0.4 // indirect 20 | github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect 21 | go.uber.org/atomic v1.7.0 // indirect 22 | go.uber.org/multierr v1.6.0 // indirect 23 | golang.org/x/crypto v0.33.0 // indirect 24 | golang.org/x/sync v0.11.0 // indirect 25 | golang.org/x/text v0.22.0 // indirect 26 | ) 27 | -------------------------------------------------------------------------------- /examples/_logger/zap/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build zap 8 | 9 | package main 10 | 11 | import ( 12 | "context" 13 | "log" 14 | 15 | "github.com/go-logr/zapr" 16 | "go.mongodb.org/mongo-driver/v2/bson" 17 | "go.mongodb.org/mongo-driver/v2/mongo" 18 | "go.mongodb.org/mongo-driver/v2/mongo/options" 19 | "go.uber.org/zap" 20 | ) 21 | 22 | func main() { 23 | logger, err := zap.NewDevelopment() 24 | if err != nil { 25 | log.Fatalf("error creating zap logger: %w", err) 26 | } 27 | 28 | sink := zapr.NewLogger(logger).GetSink() 29 | 30 | // Create a client with our logger options. 31 | loggerOptions := options. 32 | Logger(). 33 | SetSink(sink). 34 | SetMaxDocumentLength(25). 35 | SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) 36 | 37 | clientOptions := options. 38 | Client(). 39 | ApplyURI("mongodb://localhost:27017"). 40 | SetLoggerOptions(loggerOptions) 41 | 42 | client, err := mongo.Connect(clientOptions) 43 | if err != nil { 44 | log.Fatalf("error connecting to MongoDB: %v", err) 45 | } 46 | 47 | defer client.Disconnect(context.TODO()) 48 | 49 | // Make a database request to test our logging solution. 50 | coll := client.Database("test").Collection("test") 51 | 52 | _, err = coll.InsertOne(context.TODO(), bson.D{{"Alice", "123"}}) 53 | if err != nil { 54 | log.Fatalf("InsertOne failed: %v", err) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /examples/_logger/zerolog/go.mod: -------------------------------------------------------------------------------- 1 | module go.mongodb.go/mongo-driver/v2/examples/logger/zerolog 2 | 3 | go 1.23 4 | 5 | replace go.mongodb.org/mongo-driver/v2 => ../../../ 6 | 7 | require ( 8 | github.com/go-logr/zerologr v1.2.2 9 | github.com/rs/zerolog v1.28.0 10 | go.mongodb.org/mongo-driver/v2 v2.0.0-alpha2 11 | ) 12 | 13 | require ( 14 | github.com/go-logr/logr v1.2.3 // indirect 15 | github.com/golang/snappy v1.0.0 // indirect 16 | github.com/klauspost/compress v1.16.7 // indirect 17 | github.com/mattn/go-colorable v0.1.12 // indirect 18 | github.com/mattn/go-isatty v0.0.14 // indirect 19 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 20 | github.com/xdg-go/scram v1.1.2 // indirect 21 | github.com/xdg-go/stringprep v1.0.4 // indirect 22 | github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect 23 | golang.org/x/crypto v0.33.0 // indirect 24 | golang.org/x/sync v0.11.0 // indirect 25 | golang.org/x/sys v0.30.0 // indirect 26 | golang.org/x/text v0.22.0 // indirect 27 | ) 28 | -------------------------------------------------------------------------------- /examples/_logger/zerolog/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build zerolog 8 | 9 | package main 10 | 11 | import ( 12 | "context" 13 | "log" 14 | "os" 15 | 16 | "github.com/go-logr/zerologr" 17 | "github.com/rs/zerolog" 18 | "go.mongodb.org/mongo-driver/v2/bson" 19 | "go.mongodb.org/mongo-driver/v2/mongo" 20 | "go.mongodb.org/mongo-driver/v2/mongo/options" 21 | ) 22 | 23 | func main() { 24 | logger := zerolog.New(os.Stderr).With().Caller().Timestamp().Logger() 25 | sink := zerologr.New(&logger).GetSink() 26 | 27 | // Create a client with our logger options. 28 | loggerOptions := options. 29 | Logger(). 30 | SetSink(sink). 31 | SetMaxDocumentLength(25). 32 | SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) 33 | 34 | clientOptions := options. 35 | Client(). 36 | ApplyURI("mongodb://localhost:27017"). 37 | SetLoggerOptions(loggerOptions) 38 | 39 | client, err := mongo.Connect(clientOptions) 40 | if err != nil { 41 | log.Fatalf("error connecting to MongoDB: %v", err) 42 | } 43 | 44 | defer client.Disconnect(context.TODO()) 45 | 46 | // Make a database request to test our logging solution 47 | coll := client.Database("test").Collection("test") 48 | 49 | _, err = coll.InsertOne(context.TODO(), bson.D{{"Alice", "123"}}) 50 | if err != nil { 51 | log.Fatalf("InsertOne failed: %v", err) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module go.mongodb.org/mongo-driver/v2 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/davecgh/go-spew v1.1.1 7 | github.com/golang/snappy v1.0.0 8 | github.com/google/go-cmp v0.6.0 9 | github.com/klauspost/compress v1.16.7 10 | github.com/xdg-go/scram v1.1.2 11 | github.com/xdg-go/stringprep v1.0.4 12 | github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 13 | golang.org/x/crypto v0.33.0 14 | golang.org/x/sync v0.11.0 15 | ) 16 | 17 | require ( 18 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 19 | golang.org/x/text v0.22.0 // indirect 20 | ) 21 | 22 | replace golang.org/x/net/http2 => golang.org/x/net/http2 v0.23.0 // GODRIVER-3225 23 | -------------------------------------------------------------------------------- /go.work: -------------------------------------------------------------------------------- 1 | go 1.23 2 | 3 | use ( 4 | . 5 | ./examples/_logger/logrus 6 | ./examples/_logger/zap 7 | ./examples/_logger/zerolog 8 | ./internal/cmd/benchmark 9 | ./internal/cmd/compilecheck 10 | ./internal/cmd/faas/awslambda/mongodb 11 | ./internal/test/goleak 12 | ) 13 | -------------------------------------------------------------------------------- /internal/assert/assertion_compare_can_convert.go: -------------------------------------------------------------------------------- 1 | // Copied from https://github.com/stretchr/testify/blob/1333b5d3bda8cf5aedcf3e1aaa95cac28aaab892/assert/assertion_compare_can_convert.go 2 | 3 | // Copyright 2020 Mat Ryer, Tyler Bunnell and all contributors. All rights reserved. 4 | // Use of this source code is governed by an MIT-style license that can be found in 5 | // the THIRD-PARTY-NOTICES file. 6 | 7 | //go:build go1.17 8 | // +build go1.17 9 | 10 | package assert 11 | 12 | import "reflect" 13 | 14 | // Wrapper around reflect.Value.CanConvert, for compatibility 15 | // reasons. 16 | func canConvert(value reflect.Value, to reflect.Type) bool { 17 | return value.CanConvert(to) 18 | } 19 | -------------------------------------------------------------------------------- /internal/assert/assertion_compare_legacy.go: -------------------------------------------------------------------------------- 1 | // Copied from https://github.com/stretchr/testify/blob/1333b5d3bda8cf5aedcf3e1aaa95cac28aaab892/assert/assertion_compare_legacy.go 2 | 3 | // Copyright 2020 Mat Ryer, Tyler Bunnell and all contributors. All rights reserved. 4 | // Use of this source code is governed by an MIT-style license that can be found in 5 | // the THIRD-PARTY-NOTICES file. 6 | 7 | //go:build !go1.17 8 | // +build !go1.17 9 | 10 | package assert 11 | 12 | import "reflect" 13 | 14 | // Older versions of Go does not have the reflect.Value.CanConvert 15 | // method. 16 | func canConvert(value reflect.Value, to reflect.Type) bool { 17 | return false 18 | } 19 | -------------------------------------------------------------------------------- /internal/aws/signer/v4/header_rules.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Based on github.com/aws/aws-sdk-go by Amazon.com, Inc. with code from: 8 | // - github.com/aws/aws-sdk-go/blob/v1.44.225/aws/signer/v4/header_rules.go 9 | // See THIRD-PARTY-NOTICES for original license terms 10 | 11 | package v4 12 | 13 | // validator houses a set of rule needed for validation of a 14 | // string value 15 | type rules []rule 16 | 17 | // rule interface allows for more flexible rules and just simply 18 | // checks whether or not a value adheres to that rule 19 | type rule interface { 20 | IsValid(value string) bool 21 | } 22 | 23 | // IsValid will iterate through all rules and see if any rules 24 | // apply to the value and supports nested rules 25 | func (r rules) IsValid(value string) bool { 26 | for _, rule := range r { 27 | if rule.IsValid(value) { 28 | return true 29 | } 30 | } 31 | return false 32 | } 33 | 34 | // mapRule generic rule for maps 35 | type mapRule map[string]struct{} 36 | 37 | // IsValid for the map rule satisfies whether it exists in the map 38 | func (m mapRule) IsValid(value string) bool { 39 | _, ok := m[value] 40 | return ok 41 | } 42 | 43 | // excludeList is a generic rule for exclude listing 44 | type excludeList struct { 45 | rule 46 | } 47 | 48 | // IsValid for exclude list checks if the value is within the exclude list 49 | func (b excludeList) IsValid(value string) bool { 50 | return !b.rule.IsValid(value) 51 | } 52 | -------------------------------------------------------------------------------- /internal/aws/signer/v4/uri_path.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Based on github.com/aws/aws-sdk-go by Amazon.com, Inc. with code from: 8 | // - github.com/aws/aws-sdk-go/blob/v1.44.225/aws/signer/v4/uri_path.go 9 | // - github.com/aws/aws-sdk-go/blob/v1.44.225/private/protocol/rest/build.go 10 | // See THIRD-PARTY-NOTICES for original license terms 11 | 12 | package v4 13 | 14 | import ( 15 | "bytes" 16 | "fmt" 17 | "net/url" 18 | "strings" 19 | ) 20 | 21 | // Whether the byte value can be sent without escaping in AWS URLs 22 | var noEscape [256]bool 23 | 24 | func init() { 25 | for i := 0; i < len(noEscape); i++ { 26 | // AWS expects every character except these to be escaped 27 | noEscape[i] = (i >= 'A' && i <= 'Z') || 28 | (i >= 'a' && i <= 'z') || 29 | (i >= '0' && i <= '9') || 30 | i == '-' || 31 | i == '.' || 32 | i == '_' || 33 | i == '~' 34 | } 35 | } 36 | 37 | func getURIPath(u *url.URL) string { 38 | var uri string 39 | 40 | if len(u.Opaque) > 0 { 41 | uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/") 42 | } else { 43 | uri = u.EscapedPath() 44 | } 45 | 46 | if len(uri) == 0 { 47 | uri = "/" 48 | } 49 | 50 | return uri 51 | } 52 | 53 | // EscapePath escapes part of a URL path in Amazon style 54 | func EscapePath(path string, encodeSep bool) string { 55 | var buf bytes.Buffer 56 | for i := 0; i < len(path); i++ { 57 | c := path[i] 58 | if noEscape[c] || (c == '/' && !encodeSep) { 59 | buf.WriteByte(c) 60 | } else { 61 | fmt.Fprintf(&buf, "%%%02X", c) 62 | } 63 | } 64 | return buf.String() 65 | } 66 | -------------------------------------------------------------------------------- /internal/bsoncoreutil/bsoncoreutil.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package bsoncoreutil 8 | 9 | // Truncate truncates a given string for a certain width 10 | func Truncate(str string, width int) string { 11 | if width == 0 { 12 | return "" 13 | } 14 | 15 | if len(str) <= width { 16 | return str 17 | } 18 | 19 | // Truncate the byte slice of the string to the given width. 20 | newStr := str[:width] 21 | 22 | // Check if the last byte is at the beginning of a multi-byte character. 23 | // If it is, then remove the last byte. 24 | if newStr[len(newStr)-1]&0xC0 == 0xC0 { 25 | return newStr[:len(newStr)-1] 26 | } 27 | 28 | // Check if the last byte is a multi-byte character 29 | if newStr[len(newStr)-1]&0xC0 == 0x80 { 30 | // If it is, step back until you we are at the start of a character 31 | for i := len(newStr) - 1; i >= 0; i-- { 32 | if newStr[i]&0xC0 == 0xC0 { 33 | // Truncate at the end of the character before the character we stepped back to 34 | return newStr[:i] 35 | } 36 | } 37 | } 38 | 39 | return newStr 40 | } 41 | -------------------------------------------------------------------------------- /internal/bsoncoreutil/bsoncoreutil_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package bsoncoreutil 8 | 9 | import ( 10 | "testing" 11 | 12 | "go.mongodb.org/mongo-driver/v2/internal/assert" 13 | ) 14 | 15 | func TestTruncate(t *testing.T) { 16 | t.Parallel() 17 | 18 | for _, tcase := range []struct { 19 | name string 20 | arg string 21 | width int 22 | expected string 23 | }{ 24 | { 25 | name: "empty", 26 | arg: "", 27 | width: 0, 28 | expected: "", 29 | }, 30 | { 31 | name: "short", 32 | arg: "foo", 33 | width: 1000, 34 | expected: "foo", 35 | }, 36 | { 37 | name: "long", 38 | arg: "foo bar baz", 39 | width: 9, 40 | expected: "foo bar b", 41 | }, 42 | { 43 | name: "multi-byte", 44 | arg: "你好", 45 | width: 4, 46 | expected: "你", 47 | }, 48 | } { 49 | tcase := tcase 50 | 51 | t.Run(tcase.name, func(t *testing.T) { 52 | t.Parallel() 53 | 54 | actual := Truncate(tcase.arg, tcase.width) 55 | assert.Equal(t, tcase.expected, actual) 56 | }) 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /internal/cmd/benchmark/go.mod: -------------------------------------------------------------------------------- 1 | module go.mongodb.go/mongo-driver/v2/internal/cmd/benchmark 2 | 3 | go 1.19 4 | 5 | replace go.mongodb.org/mongo-driver/v2 => ../../../ 6 | 7 | require ( 8 | github.com/stretchr/testify v1.8.1 9 | go.mongodb.org/mongo-driver/v2 v2.0.0-00010101000000-000000000000 10 | ) 11 | 12 | require ( 13 | github.com/davecgh/go-spew v1.1.1 // indirect 14 | github.com/golang/snappy v1.0.0 // indirect 15 | github.com/klauspost/compress v1.16.7 // indirect 16 | github.com/pmezard/go-difflib v1.0.0 // indirect 17 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 18 | github.com/xdg-go/scram v1.1.2 // indirect 19 | github.com/xdg-go/stringprep v1.0.4 // indirect 20 | github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect 21 | golang.org/x/crypto v0.33.0 // indirect 22 | golang.org/x/sync v0.11.0 // indirect 23 | golang.org/x/text v0.22.0 // indirect 24 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 25 | gopkg.in/yaml.v3 v3.0.1 // indirect 26 | ) 27 | -------------------------------------------------------------------------------- /internal/cmd/compilecheck/go.mod: -------------------------------------------------------------------------------- 1 | module go.mongodb.go/mongo-driver/v2/internal/cmd/compilecheck 2 | 3 | go 1.19 4 | 5 | replace go.mongodb.org/mongo-driver/v2 => ../../../ 6 | 7 | // Note that the Go driver version is replaced with the local Go driver code by 8 | // the replace directive above. 9 | require go.mongodb.org/mongo-driver/v2 v2.0.0-alpha2 10 | 11 | require ( 12 | github.com/golang/snappy v1.0.0 // indirect 13 | github.com/klauspost/compress v1.16.7 // indirect 14 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 15 | github.com/xdg-go/scram v1.1.2 // indirect 16 | github.com/xdg-go/stringprep v1.0.4 // indirect 17 | github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect 18 | golang.org/x/crypto v0.33.0 // indirect 19 | golang.org/x/sync v0.11.0 // indirect 20 | golang.org/x/text v0.22.0 // indirect 21 | ) 22 | -------------------------------------------------------------------------------- /internal/cmd/compilecheck/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package main 8 | 9 | import ( 10 | "fmt" 11 | 12 | "go.mongodb.org/mongo-driver/v2/bson" 13 | "go.mongodb.org/mongo-driver/v2/mongo" 14 | "go.mongodb.org/mongo-driver/v2/mongo/options" 15 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver/xoptions" 16 | ) 17 | 18 | func main() { 19 | opts := options.Client() 20 | xoptions.SetInternalClientOptions(opts, "foo", "bar") 21 | 22 | _, _ = mongo.Connect(options.Client()) 23 | fmt.Println(bson.D{{Key: "key", Value: "value"}}) 24 | } 25 | -------------------------------------------------------------------------------- /internal/cmd/faas/awslambda/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: default 2 | default: 3 | sam build --debug 4 | # Cannot connect to a local mongo server on non x86_64 architectures. 5 | # These cases require either building a mongodb docker container or 6 | # using a serverless service such as Atlas. 7 | sam local invoke --parameter-overrides "MongoDbUri=${MONGODB_URI}" 8 | -------------------------------------------------------------------------------- /internal/cmd/faas/awslambda/mongodb/go.mod: -------------------------------------------------------------------------------- 1 | module go.mongodb.go/mongo-driver/v2/internal/cmd/faas/awslambda/mongodb 2 | 3 | go 1.23 4 | 5 | replace go.mongodb.org/mongo-driver/v2 => ../../../../../ 6 | 7 | require github.com/aws/aws-lambda-go v1.41.0 8 | 9 | require go.mongodb.org/mongo-driver/v2 v2.0.0-00010101000000-000000000000 10 | 11 | require ( 12 | github.com/golang/snappy v1.0.0 // indirect 13 | github.com/klauspost/compress v1.16.7 // indirect 14 | github.com/stretchr/testify v1.8.1 // indirect 15 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 16 | github.com/xdg-go/scram v1.1.2 // indirect 17 | github.com/xdg-go/stringprep v1.0.4 // indirect 18 | github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect 19 | golang.org/x/crypto v0.33.0 // indirect 20 | golang.org/x/sync v0.11.0 // indirect 21 | golang.org/x/text v0.22.0 // indirect 22 | ) 23 | 24 | replace gopkg.in/yaml.v2 => gopkg.in/yaml.v2 v2.2.8 25 | -------------------------------------------------------------------------------- /internal/cmd/faas/awslambda/template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: > 4 | Go Driver lambda function test 5 | 6 | Parameters: 7 | MongoDbUri: 8 | Type: String 9 | Description: The MongoDB connection string. 10 | 11 | Globals: 12 | Function: 13 | Timeout: 30 14 | 15 | Resources: 16 | MongoDBFunction: 17 | Type: AWS::Serverless::Function 18 | Metadata: 19 | BuildMethod: go1.x 20 | Properties: 21 | CodeUri: mongodb/ 22 | Handler: bootstrap 23 | Runtime: provided.al2 24 | Architectures: [arm64] 25 | Events: 26 | MongoDB: 27 | Type: Api 28 | Properties: 29 | Path: /mongodb 30 | Method: GET 31 | Environment: 32 | Variables: 33 | MONGODB_URI: !Ref MongoDbUri 34 | 35 | ApplicationResourceGroup: 36 | Type: AWS::ResourceGroups::Group 37 | Properties: 38 | Name: 39 | Fn::Sub: ApplicationInsights-SAM-${AWS::StackName} 40 | ResourceQuery: 41 | Type: CLOUDFORMATION_STACK_1_0 42 | ApplicationInsightsMonitoring: 43 | Type: AWS::ApplicationInsights::Application 44 | Properties: 45 | ResourceGroupName: 46 | Ref: ApplicationResourceGroup 47 | AutoConfigurationEnabled: 'true' 48 | 49 | Outputs: 50 | MongoDBApi: 51 | Description: "API Gateway endpoint URL for Prod stage for MongoDB function" 52 | Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/mongodb/" 53 | MongoDBFunction: 54 | Description: "MongoDB Lambda Function ARN" 55 | Value: !GetAtt MongoDBFunction.Arn 56 | MongoDBFunctionIamRole: 57 | Description: "Implicit IAM Role created for MongoDB function" 58 | Value: !GetAtt MongoDBFunctionRole.Arn -------------------------------------------------------------------------------- /internal/cmd/testaws/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package main 8 | 9 | import ( 10 | "context" 11 | "errors" 12 | "fmt" 13 | "os" 14 | 15 | "go.mongodb.org/mongo-driver/v2/bson" 16 | "go.mongodb.org/mongo-driver/v2/mongo" 17 | "go.mongodb.org/mongo-driver/v2/mongo/options" 18 | ) 19 | 20 | func main() { 21 | uri := os.Getenv("MONGODB_URI") 22 | ctx := context.Background() 23 | 24 | client, err := mongo.Connect(options.Client().ApplyURI(uri)) 25 | if err != nil { 26 | panic(fmt.Sprintf("Connect error: %v", err)) 27 | } 28 | 29 | defer func() { 30 | if err = client.Disconnect(ctx); err != nil { 31 | panic(fmt.Sprintf("Disconnect error: %v", err)) 32 | } 33 | }() 34 | 35 | db := client.Database("aws") 36 | coll := db.Collection("test") 37 | if err = coll.FindOne(ctx, bson.D{{"x", 1}}).Err(); err != nil && !errors.Is(err, mongo.ErrNoDocuments) { 38 | panic(fmt.Sprintf("FindOne error: %v", err)) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /internal/cmd/testentauth/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package main 8 | 9 | import ( 10 | "context" 11 | "log" 12 | "os" 13 | "time" 14 | 15 | "go.mongodb.org/mongo-driver/v2/mongo" 16 | "go.mongodb.org/mongo-driver/v2/mongo/options" 17 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring" 18 | ) 19 | 20 | func main() { 21 | uri := os.Getenv("MONGODB_URI") 22 | compressor := os.Getenv("MONGO_GO_DRIVER_COMPRESSOR") 23 | 24 | client, err := mongo.Connect( 25 | options.Client().ApplyURI(uri).SetCompressors([]string{compressor})) 26 | if err != nil { 27 | log.Panicf("Error connecting client: %v", err) 28 | } 29 | 30 | // Use the defaultauthdb (i.e. the database name after the "/") specified in the connection 31 | // string to run the count operation. 32 | cs, err := connstring.Parse(uri) 33 | if err != nil { 34 | log.Panicf("Error parsing connection string: %v", err) 35 | } 36 | if cs.Database == "" { 37 | log.Panic("Connection string must contain a defaultauthdb.") 38 | } 39 | 40 | coll := client.Database(cs.Database).Collection("test") 41 | 42 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 43 | defer cancel() 44 | 45 | count, err := coll.EstimatedDocumentCount(ctx) 46 | if err != nil { 47 | log.Panicf("failed executing count command: %v", err) 48 | } 49 | log.Println("Count of test collection:", count) 50 | } 51 | -------------------------------------------------------------------------------- /internal/csfle/csfle.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package csfle 8 | 9 | import ( 10 | "errors" 11 | "fmt" 12 | 13 | "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" 14 | ) 15 | 16 | const ( 17 | EncryptedCacheCollection = "ecc" 18 | EncryptedStateCollection = "esc" 19 | EncryptedCompactionCollection = "ecoc" 20 | ) 21 | 22 | // GetEncryptedStateCollectionName returns the encrypted state collection name associated with dataCollectionName. 23 | func GetEncryptedStateCollectionName(efBSON bsoncore.Document, dataCollectionName string, stateCollection string) (string, error) { 24 | fieldName := stateCollection + "Collection" 25 | val, err := efBSON.LookupErr(fieldName) 26 | if err != nil { 27 | if !errors.Is(err, bsoncore.ErrElementNotFound) { 28 | return "", err 29 | } 30 | // Return default name. 31 | defaultName := "enxcol_." + dataCollectionName + "." + stateCollection 32 | return defaultName, nil 33 | } 34 | 35 | stateCollectionName, ok := val.StringValueOK() 36 | if !ok { 37 | return "", fmt.Errorf("expected string for '%v', got: %v", fieldName, val.Type) 38 | } 39 | return stateCollectionName, nil 40 | } 41 | -------------------------------------------------------------------------------- /internal/docexamples/README: -------------------------------------------------------------------------------- 1 | Go Driver Documentation Examples 2 | ================================ 3 | 4 | examples.go contains numerous documentation examples that are rendered in various locations on www.mongodb.com/docs. 5 | Each example is delineated with starting and ending comments (// Start/End Example #). All examples in examples.go 6 | are valid Go driver code. Each example is run as part of our CI with examples_test.go, so all code is up-to-date and 7 | accurate. We recommend using www.mongodb.com/docs to interact with these examples rather than viewing these files 8 | directly. 9 | -------------------------------------------------------------------------------- /internal/errutil/join_go1.19.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build !go1.20 8 | // +build !go1.20 9 | 10 | package errutil 11 | 12 | // Join returns an error that wraps the given errors. Any nil error values are 13 | // discarded. Join returns nil if every value in errs is nil. The error formats 14 | // as the concatenation of the strings obtained by calling the Error method of 15 | // each element of errs, with a newline between each string. 16 | // 17 | // A non-nil error returned by Join implements the "Unwrap() error" method. 18 | func Join(errs ...error) error { 19 | return join(errs...) 20 | } 21 | -------------------------------------------------------------------------------- /internal/errutil/join_go1.20.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build go1.20 8 | // +build go1.20 9 | 10 | package errutil 11 | 12 | import "errors" 13 | 14 | // Join calls [errors.Join]. 15 | func Join(errs ...error) error { 16 | return errors.Join(errs...) 17 | } 18 | -------------------------------------------------------------------------------- /internal/handshake/handshake.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package handshake 8 | 9 | // LegacyHello is the legacy version of the hello command. 10 | var LegacyHello = "isMaster" 11 | 12 | // LegacyHelloLowercase is the lowercase, legacy version of the hello command. 13 | var LegacyHelloLowercase = "ismaster" 14 | -------------------------------------------------------------------------------- /internal/httputil/httputil.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package httputil 8 | 9 | import ( 10 | "net/http" 11 | ) 12 | 13 | // DefaultHTTPClient is the default HTTP client used across the driver. 14 | var DefaultHTTPClient = &http.Client{ 15 | Transport: http.DefaultTransport.(*http.Transport).Clone(), 16 | } 17 | 18 | // CloseIdleHTTPConnections closes any connections which were previously 19 | // connected from previous requests but are now sitting idle in a "keep-alive" 20 | // state. It does not interrupt any connections currently in use. 21 | // 22 | // Borrowed from the Go standard library. 23 | func CloseIdleHTTPConnections(client *http.Client) { 24 | type closeIdler interface { 25 | CloseIdleConnections() 26 | } 27 | if tr, ok := client.Transport.(closeIdler); ok { 28 | tr.CloseIdleConnections() 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /internal/integration/client_options_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package integration 8 | 9 | import ( 10 | "context" 11 | "net" 12 | "sync/atomic" 13 | "testing" 14 | 15 | "go.mongodb.org/mongo-driver/v2/bson" 16 | "go.mongodb.org/mongo-driver/v2/internal/integtest" 17 | "go.mongodb.org/mongo-driver/v2/internal/require" 18 | "go.mongodb.org/mongo-driver/v2/mongo" 19 | "go.mongodb.org/mongo-driver/v2/mongo/options" 20 | ) 21 | 22 | func TestClientOptions_CustomDialer(t *testing.T) { 23 | td := &testDialer{d: &net.Dialer{}} 24 | cs := integtest.ConnString(t) 25 | opts := options.Client().ApplyURI(cs.String()).SetDialer(td) 26 | integtest.AddTestServerAPIVersion(opts) 27 | client, err := mongo.Connect(opts) 28 | require.NoError(t, err) 29 | _, err = client.ListDatabases(context.Background(), bson.D{}) 30 | require.NoError(t, err) 31 | got := atomic.LoadInt32(&td.called) 32 | if got < 1 { 33 | t.Errorf("Custom dialer was not used when dialing new connections") 34 | } 35 | } 36 | 37 | type testDialer struct { 38 | called int32 39 | d mongo.Dialer 40 | } 41 | 42 | func (td *testDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { 43 | atomic.AddInt32(&td.called, 1) 44 | return td.d.DialContext(ctx, network, address) 45 | } 46 | -------------------------------------------------------------------------------- /internal/integration/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package integration 8 | 9 | // This file exists to allow the build scripts (and standard Go builds for some early Go versions) 10 | // to succeed. Without it, the build may encounter an error like: 11 | // 12 | // go build go.mongodb.org/mongo-driver/mongo/integration: build constraints exclude all Go files in ./go.mongodb.org/mongo-driver/mongo/integration 13 | // 14 | -------------------------------------------------------------------------------- /internal/integration/main_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package integration 8 | 9 | import ( 10 | "flag" 11 | "log" 12 | "os" 13 | "testing" 14 | 15 | "go.mongodb.org/mongo-driver/v2/internal/integration/mtest" 16 | ) 17 | 18 | func TestMain(m *testing.M) { 19 | // All tests that use mtest.Setup() are expected to be integration tests, so skip them when the 20 | // -short flag is included in the "go test" command. Also, we have to parse flags here to use 21 | // testing.Short() because flags aren't parsed before TestMain() is called. 22 | flag.Parse() 23 | if testing.Short() { 24 | log.Print("skipping mtest integration test in short mode") 25 | return 26 | } 27 | 28 | if err := mtest.Setup(); err != nil { 29 | log.Panic(err) 30 | } 31 | defer os.Exit(m.Run()) 32 | if err := mtest.Teardown(); err != nil { 33 | log.Panic(err) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /internal/integration/mtest/csfle_enabled.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build cse 8 | // +build cse 9 | 10 | package mtest 11 | 12 | // IsCSFLEEnabled returns true if driver is built with Client Side Field Level Encryption support. 13 | // Client Side Field Level Encryption support is enabled with the cse build tag. 14 | func IsCSFLEEnabled() bool { 15 | return true 16 | } 17 | -------------------------------------------------------------------------------- /internal/integration/mtest/csfle_not_enabled.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build !cse 8 | // +build !cse 9 | 10 | package mtest 11 | 12 | // IsCSFLEEnabled returns true if driver is built with Client Side Field Level Encryption support. 13 | // Client Side Field Level Encryption support is enabled with the cse build tag. 14 | func IsCSFLEEnabled() bool { 15 | return false 16 | } 17 | -------------------------------------------------------------------------------- /internal/integration/mtest/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package mtest is unstable and there is no backward compatibility guarantee. 8 | // It is experimental and subject to change. 9 | package mtest 10 | -------------------------------------------------------------------------------- /internal/integration/mtest/setup_options.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package mtest 8 | 9 | // SetupOptions is the type used to configure mtest setup 10 | type SetupOptions struct { 11 | // Specifies the URI to connect to. Defaults to URI based on the environment variables MONGODB_URI, 12 | // MONGO_GO_DRIVER_CA_FILE, and MONGO_GO_DRIVER_COMPRESSOR 13 | URI *string 14 | } 15 | 16 | // NewSetupOptions creates an empty SetupOptions struct 17 | func NewSetupOptions() *SetupOptions { 18 | return &SetupOptions{} 19 | } 20 | 21 | // SetURI sets the uri to connect to 22 | func (so *SetupOptions) SetURI(uri string) *SetupOptions { 23 | so.URI = &uri 24 | return so 25 | } 26 | -------------------------------------------------------------------------------- /internal/integration/unified/cursor_entity.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package unified 8 | 9 | import ( 10 | "context" 11 | ) 12 | 13 | // The cursor interface defines the methods that must be implemented by iterable types that can be stored in an 14 | // EntityMap. This type exists so that we can store multiple concrete types returned by functions from the mongo package 15 | // under a single interface (e.g. mongo.Cursor and mongo.ChangeStream). 16 | type cursor interface { 17 | Close(context.Context) error 18 | Decode(interface{}) error 19 | Err() error 20 | Next(context.Context) bool 21 | TryNext(context.Context) bool 22 | } 23 | -------------------------------------------------------------------------------- /internal/integration/unified/cursor_operation_execution.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package unified 8 | 9 | import ( 10 | "context" 11 | "fmt" 12 | 13 | "go.mongodb.org/mongo-driver/v2/bson" 14 | ) 15 | 16 | func executeIterateOnce(ctx context.Context, operation *operation) (*operationResult, error) { 17 | cursor, err := entities(ctx).cursor(operation.Object) 18 | if err != nil { 19 | return nil, err 20 | } 21 | 22 | // TryNext will attempt to get the next document, potentially issuing a single 'getMore'. 23 | if cursor.TryNext(ctx) { 24 | // We don't expect the server to return malformed documents, so any errors from Decode here are treated 25 | // as fatal. 26 | var res bson.Raw 27 | if err := cursor.Decode(&res); err != nil { 28 | return nil, fmt.Errorf("error decoding cursor result: %w", err) 29 | } 30 | 31 | return newDocumentResult(res, nil), nil 32 | } 33 | return newErrorResult(cursor.Err()), nil 34 | } 35 | 36 | func executeIterateUntilDocumentOrError(ctx context.Context, operation *operation) (*operationResult, error) { 37 | cursor, err := entities(ctx).cursor(operation.Object) 38 | if err != nil { 39 | return nil, err 40 | } 41 | 42 | // Next will loop until there is either a result or an error. 43 | if cursor.Next(ctx) { 44 | // We don't expect the server to return malformed documents, so any errors from Decode are treated as fatal. 45 | var res bson.Raw 46 | if err := cursor.Decode(&res); err != nil { 47 | return nil, fmt.Errorf("error decoding cursor result: %w", err) 48 | } 49 | 50 | return newDocumentResult(res, nil), nil 51 | } 52 | return newErrorResult(cursor.Err()), nil 53 | } 54 | -------------------------------------------------------------------------------- /internal/integration/unified/main_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package unified 8 | 9 | import ( 10 | "flag" 11 | "log" 12 | "os" 13 | "testing" 14 | 15 | "go.mongodb.org/mongo-driver/v2/internal/integration/mtest" 16 | ) 17 | 18 | func TestMain(m *testing.M) { 19 | // All tests that use mtest.Setup() are expected to be integration tests, so skip them when the 20 | // -short flag is included in the "go test" command. Also, we have to parse flags here to use 21 | // testing.Short() because flags aren't parsed before TestMain() is called. 22 | flag.Parse() 23 | if testing.Short() { 24 | log.Print("skipping mtest integration test in short mode") 25 | return 26 | } 27 | 28 | if err := mtest.Setup(); err != nil { 29 | log.Panic(err) 30 | } 31 | defer os.Exit(m.Run()) 32 | if err := mtest.Teardown(); err != nil { 33 | log.Panic(err) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /internal/integration/unified/options.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package unified 8 | 9 | var defaultRunKillAllSessionsValue = true 10 | 11 | // Options is the type used to configure tests 12 | type Options struct { 13 | // Specifies if killAllSessions should be run after the test completes. 14 | // Defaults to true 15 | RunKillAllSessions *bool 16 | } 17 | 18 | // NewOptions creates an empty options interface 19 | func NewOptions() *Options { 20 | return &Options{&defaultRunKillAllSessionsValue} 21 | } 22 | 23 | // SetRunKillAllSessions sets the value for RunKillAllSessions 24 | func (op *Options) SetRunKillAllSessions(killAllSessions bool) *Options { 25 | op.RunKillAllSessions = &killAllSessions 26 | return op 27 | } 28 | -------------------------------------------------------------------------------- /internal/integration/unified/schema_version.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package unified 8 | 9 | import ( 10 | "fmt" 11 | "strconv" 12 | "strings" 13 | 14 | "go.mongodb.org/mongo-driver/v2/internal/integration/mtest" 15 | ) 16 | 17 | var ( 18 | supportedSchemaVersions = map[int]string{ 19 | 1: "1.22", 20 | } 21 | ) 22 | 23 | // checkSchemaVersion determines if the provided schema version is supported and returns an error if it is not. 24 | func checkSchemaVersion(version string) error { 25 | // First get the major version number from the schema. The schema version string should be in the format 26 | // "major.minor.patch", "major.minor", or "major". 27 | 28 | parts := strings.Split(version, ".") 29 | if len(parts) == 0 { 30 | return fmt.Errorf("error splitting schema version %q into parts", version) 31 | } 32 | 33 | majorVersion, err := strconv.Atoi(parts[0]) 34 | if err != nil { 35 | return fmt.Errorf("error converting major version component %q to an integer: %v", parts[0], err) 36 | } 37 | 38 | // Find the latest supported version for the major version and use that to determine if the provided version is 39 | // supported. 40 | supportedVersion, ok := supportedSchemaVersions[majorVersion] 41 | if !ok { 42 | return fmt.Errorf("major version %d not supported", majorVersion) 43 | } 44 | if mtest.CompareServerVersions(supportedVersion, version) < 0 { 45 | return fmt.Errorf( 46 | "latest version supported for major version %d is %q, which is incompatible with specified version %q", 47 | majorVersion, supportedVersion, version, 48 | ) 49 | } 50 | return nil 51 | } 52 | -------------------------------------------------------------------------------- /internal/integration/unified/server_api_options.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package unified 8 | 9 | import ( 10 | "fmt" 11 | 12 | "go.mongodb.org/mongo-driver/v2/bson" 13 | "go.mongodb.org/mongo-driver/v2/mongo/options" 14 | ) 15 | 16 | // serverAPIOptions is a wrapper for *options.ServerAPIOptions. This type implements the bson.Unmarshaler interface 17 | // to convert BSON documents to a serverAPIOptions instance. 18 | type serverAPIOptions struct { 19 | *options.ServerAPIOptions 20 | } 21 | 22 | type serverAPIVersion = options.ServerAPIVersion 23 | 24 | var _ bson.Unmarshaler = (*serverAPIOptions)(nil) 25 | 26 | func (s *serverAPIOptions) UnmarshalBSON(data []byte) error { 27 | var temp struct { 28 | ServerAPIVersion serverAPIVersion `bson:"version"` 29 | DeprecationErrors *bool `bson:"deprecationErrors"` 30 | Strict *bool `bson:"strict"` 31 | Extra map[string]interface{} `bson:",inline"` 32 | } 33 | if err := bson.Unmarshal(data, &temp); err != nil { 34 | return fmt.Errorf("error unmarshalling to temporary serverAPIOptions object: %v", err) 35 | } 36 | if len(temp.Extra) > 0 { 37 | return fmt.Errorf("unrecognized fields for serverAPIOptions: %v", mapKeys(temp.Extra)) 38 | } 39 | 40 | s.ServerAPIOptions = options.ServerAPI(temp.ServerAPIVersion) 41 | if temp.DeprecationErrors != nil { 42 | s.SetDeprecationErrors(*temp.DeprecationErrors) 43 | } 44 | if temp.Strict != nil { 45 | s.SetStrict(*temp.Strict) 46 | } 47 | 48 | return nil 49 | } 50 | -------------------------------------------------------------------------------- /internal/israce/norace.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build !race 8 | // +build !race 9 | 10 | // Package israce reports if the Go race detector is enabled. 11 | package israce 12 | 13 | // Enabled reports if the race detector is enabled. 14 | const Enabled = false 15 | -------------------------------------------------------------------------------- /internal/israce/race.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build race 8 | // +build race 9 | 10 | // Package israce reports if the Go race detector is enabled. 11 | package israce 12 | 13 | // Enabled reports if the race detector is enabled. 14 | const Enabled = true 15 | -------------------------------------------------------------------------------- /internal/logger/context.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package logger 8 | 9 | import "context" 10 | 11 | // contextKey is a custom type used to prevent key collisions when using the 12 | // context package. 13 | type contextKey string 14 | 15 | const ( 16 | contextKeyOperation contextKey = "operation" 17 | contextKeyOperationID contextKey = "operationID" 18 | ) 19 | 20 | // WithOperationName adds the operation name to the context. 21 | func WithOperationName(ctx context.Context, operation string) context.Context { 22 | return context.WithValue(ctx, contextKeyOperation, operation) 23 | } 24 | 25 | // WithOperationID adds the operation ID to the context. 26 | func WithOperationID(ctx context.Context, operationID int32) context.Context { 27 | return context.WithValue(ctx, contextKeyOperationID, operationID) 28 | } 29 | 30 | // OperationName returns the operation name from the context. 31 | func OperationName(ctx context.Context) (string, bool) { 32 | operationName := ctx.Value(contextKeyOperation) 33 | if operationName == nil { 34 | return "", false 35 | } 36 | 37 | return operationName.(string), true 38 | } 39 | 40 | // OperationID returns the operation ID from the context. 41 | func OperationID(ctx context.Context) (int32, bool) { 42 | operationID := ctx.Value(contextKeyOperationID) 43 | if operationID == nil { 44 | return 0, false 45 | } 46 | 47 | return operationID.(int32), true 48 | } 49 | -------------------------------------------------------------------------------- /internal/mongoutil/mongoutil_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package mongoutil 8 | 9 | import ( 10 | "strings" 11 | "testing" 12 | 13 | "go.mongodb.org/mongo-driver/v2/mongo/options" 14 | ) 15 | 16 | func BenchmarkNewOptions(b *testing.B) { 17 | b.Run("reflect.ValueOf is always called", func(b *testing.B) { 18 | opts := make([]options.Lister[options.FindOptions], b.N) 19 | 20 | // Create a huge string to see if we can force reflect.ValueOf to use heap 21 | // over stack. 22 | size := 16 * 1024 * 1024 23 | str := strings.Repeat("a", size) 24 | 25 | for i := 0; i < b.N; i++ { 26 | opts[i] = options.Find().SetComment(str).SetHint("y").SetMin(1).SetMax(2) 27 | } 28 | 29 | b.ReportAllocs() 30 | for i := 0; i < b.N; i++ { 31 | _, _ = NewOptions[options.FindOptions](opts...) 32 | } 33 | }) 34 | } 35 | -------------------------------------------------------------------------------- /internal/optionsutil/options.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2025-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package optionsutil 8 | 9 | // Options stores internal options. 10 | type Options struct { 11 | values map[string]any 12 | } 13 | 14 | // WithValue sets an option value with the associated key. 15 | func WithValue(opts Options, key string, option any) Options { 16 | if opts.values == nil { 17 | opts.values = make(map[string]any) 18 | } 19 | opts.values[key] = option 20 | return opts 21 | } 22 | 23 | // Value returns the value associated with the options for key. 24 | func Value(opts Options, key string) any { 25 | if opts.values == nil { 26 | return nil 27 | } 28 | if val, ok := opts.values[key]; ok { 29 | return val 30 | } 31 | return nil 32 | } 33 | 34 | // Equal compares two Options instances for equality. 35 | func Equal(opts1, opts2 Options) bool { 36 | if len(opts1.values) != len(opts2.values) { 37 | return false 38 | } 39 | for key, val1 := range opts1.values { 40 | if val2, ok := opts2.values[key]; !ok || val1 != val2 { 41 | return false 42 | } 43 | } 44 | return true 45 | } 46 | -------------------------------------------------------------------------------- /internal/ptrutil/int64.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package ptrutil 8 | 9 | // CompareInt64 is a piecewise function with the following return conditions: 10 | // 11 | // (1) 2, ptr1 != nil AND ptr2 == nil 12 | // (2) 1, *ptr1 > *ptr2 13 | // (3) 0, ptr1 == ptr2 or *ptr1 == *ptr2 14 | // (4) -1, *ptr1 < *ptr2 15 | // (5) -2, ptr1 == nil AND ptr2 != nil 16 | func CompareInt64(ptr1, ptr2 *int64) int { 17 | if ptr1 == ptr2 { 18 | // This will catch the double nil or same-pointer cases. 19 | return 0 20 | } 21 | 22 | if ptr1 == nil && ptr2 != nil { 23 | return -2 24 | } 25 | 26 | if ptr1 != nil && ptr2 == nil { 27 | return 2 28 | } 29 | 30 | if *ptr1 > *ptr2 { 31 | return 1 32 | } 33 | 34 | if *ptr1 < *ptr2 { 35 | return -1 36 | } 37 | 38 | return 0 39 | } 40 | -------------------------------------------------------------------------------- /internal/ptrutil/int64_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package ptrutil 8 | 9 | import ( 10 | "testing" 11 | 12 | "go.mongodb.org/mongo-driver/v2/internal/assert" 13 | ) 14 | 15 | func TestCompareInt64(t *testing.T) { 16 | t.Parallel() 17 | 18 | int64ToPtr := func(i64 int64) *int64 { return &i64 } 19 | int64Ptr := int64ToPtr(1) 20 | 21 | tests := []struct { 22 | name string 23 | ptr1, ptr2 *int64 24 | want int 25 | }{ 26 | { 27 | name: "empty", 28 | want: 0, 29 | }, 30 | { 31 | name: "ptr1 nil", 32 | ptr2: int64ToPtr(1), 33 | want: -2, 34 | }, 35 | { 36 | name: "ptr2 nil", 37 | ptr1: int64ToPtr(1), 38 | want: 2, 39 | }, 40 | { 41 | name: "ptr1 and ptr2 have same value, different address", 42 | ptr1: int64ToPtr(1), 43 | ptr2: int64ToPtr(1), 44 | want: 0, 45 | }, 46 | { 47 | name: "ptr1 and ptr2 have the same address", 48 | ptr1: int64Ptr, 49 | ptr2: int64Ptr, 50 | want: 0, 51 | }, 52 | { 53 | name: "ptr1 GT ptr2", 54 | ptr1: int64ToPtr(1), 55 | ptr2: int64ToPtr(0), 56 | want: 1, 57 | }, 58 | { 59 | name: "ptr1 LT ptr2", 60 | ptr1: int64ToPtr(0), 61 | ptr2: int64ToPtr(1), 62 | want: -1, 63 | }, 64 | } 65 | 66 | for _, test := range tests { 67 | test := test // capture the range variable 68 | 69 | t.Run(test.name, func(t *testing.T) { 70 | t.Parallel() 71 | 72 | got := CompareInt64(test.ptr1, test.ptr2) 73 | assert.Equal(t, test.want, got, "compareInt64() = %v, wanted %v", got, test.want) 74 | }) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /internal/ptrutil/ptr.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package ptrutil 8 | 9 | // Ptr will return the memory location of the given value. 10 | func Ptr[T any](val T) *T { 11 | return &val 12 | } 13 | -------------------------------------------------------------------------------- /internal/rand/bits.go: -------------------------------------------------------------------------------- 1 | // Copied from https://cs.opensource.google/go/go/+/946b4baaf6521d521928500b2b57429c149854e7:src/math/bits.go 2 | 3 | // Copyright 2017 The Go Authors. All rights reserved. 4 | // Use of this source code is governed by a BSD-style 5 | // license that can be found in the LICENSE file. 6 | 7 | package rand 8 | 9 | // Add64 returns the sum with carry of x, y and carry: sum = x + y + carry. 10 | // The carry input must be 0 or 1; otherwise the behavior is undefined. 11 | // The carryOut output is guaranteed to be 0 or 1. 12 | func Add64(x, y, carry uint64) (sum, carryOut uint64) { 13 | yc := y + carry 14 | sum = x + yc 15 | if sum < x || yc < y { 16 | carryOut = 1 17 | } 18 | return 19 | } 20 | 21 | // Mul64 returns the 128-bit product of x and y: (hi, lo) = x * y 22 | // with the product bits' upper half returned in hi and the lower 23 | // half returned in lo. 24 | func Mul64(x, y uint64) (hi, lo uint64) { 25 | const mask32 = 1<<32 - 1 26 | x0 := x & mask32 27 | x1 := x >> 32 28 | y0 := y & mask32 29 | y1 := y >> 32 30 | w0 := x0 * y0 31 | t := x1*y0 + w0>>32 32 | w1 := t & mask32 33 | w2 := t >> 32 34 | w1 += x0 * y1 35 | hi = x1*y1 + w2 + w1>>32 36 | lo = x * y 37 | return 38 | } 39 | -------------------------------------------------------------------------------- /internal/rand/modulo_test.go: -------------------------------------------------------------------------------- 1 | // Copied from https://cs.opensource.google/go/x/exp/+/24438e51023af3bfc1db8aed43c1342817e8cfcd:rand/modulo_test.go 2 | 3 | // Copyright 2017 The Go Authors. All rights reserved. 4 | // Use of this source code is governed by a BSD-style 5 | // license that can be found in the LICENSE file. 6 | 7 | // This file validates that the calculation in Uint64n corrects for 8 | // possible bias. 9 | 10 | package rand 11 | 12 | import ( 13 | "testing" 14 | ) 15 | 16 | // modSource is used to probe the upper region of uint64 space. It 17 | // generates values sequentially in [maxUint64-15,maxUint64]. With 18 | // modEdge == 15 and maxUint64 == 1<<64-1 == 18446744073709551615, 19 | // this means that Uint64n(10) will repeatedly probe the top range. 20 | // We thus expect a bias to result unless the calculation in Uint64n 21 | // gets the edge condition right. We test this by calling Uint64n 100 22 | // times; the results should be perfectly evenly distributed across 23 | // [0,10). 24 | type modSource uint64 25 | 26 | const modEdge = 15 27 | 28 | func (m *modSource) Seed(uint64) {} 29 | 30 | // Uint64 returns a non-pseudo-random 64-bit unsigned integer as a uint64. 31 | func (m *modSource) Uint64() uint64 { 32 | if *m > modEdge { 33 | *m = 0 34 | } 35 | r := maxUint64 - *m 36 | *m++ 37 | return uint64(r) 38 | } 39 | 40 | func TestUint64Modulo(t *testing.T) { 41 | var src modSource 42 | rng := New(&src) 43 | var result [10]uint64 44 | for i := 0; i < 100; i++ { 45 | result[rng.Uint64n(10)]++ 46 | } 47 | for _, r := range result { 48 | if r != 10 { 49 | t.Fatal(result) 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /internal/rand/race_test.go: -------------------------------------------------------------------------------- 1 | // Copied from https://cs.opensource.google/go/x/exp/+/24438e51023af3bfc1db8aed43c1342817e8cfcd:rand/race_test.go 2 | 3 | // Copyright 2016 The Go Authors. All rights reserved. 4 | // Use of this source code is governed by a BSD-style 5 | // license that can be found in the LICENSE file. 6 | 7 | package rand 8 | 9 | import ( 10 | "sync" 11 | "testing" 12 | ) 13 | 14 | // TestConcurrent exercises the rand API concurrently, triggering situations 15 | // where the race detector is likely to detect issues. 16 | func TestConcurrent(t *testing.T) { 17 | const ( 18 | numRoutines = 10 19 | numCycles = 10 20 | ) 21 | var wg sync.WaitGroup 22 | defer wg.Wait() 23 | wg.Add(numRoutines) 24 | for i := 0; i < numRoutines; i++ { 25 | go func(i int) { 26 | defer wg.Done() 27 | buf := make([]byte, 997) 28 | for j := 0; j < numCycles; j++ { 29 | var seed uint64 30 | seed += uint64(ExpFloat64()) 31 | seed += uint64(Float32()) 32 | seed += uint64(Float64()) 33 | seed += uint64(Intn(Int())) 34 | seed += uint64(Int31n(Int31())) 35 | seed += uint64(Int63n(Int63())) 36 | seed += uint64(NormFloat64()) 37 | seed += uint64(Uint32()) 38 | seed += uint64(Uint64()) 39 | for _, p := range Perm(10) { 40 | seed += uint64(p) 41 | } 42 | Read(buf) 43 | for _, b := range buf { 44 | seed += uint64(b) 45 | } 46 | Seed(uint64(i*j) * seed) 47 | } 48 | }(i) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /internal/randutil/randutil.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package randutil provides common random number utilities. 8 | package randutil 9 | 10 | import ( 11 | crand "crypto/rand" 12 | "fmt" 13 | "io" 14 | 15 | xrand "go.mongodb.org/mongo-driver/v2/internal/rand" 16 | ) 17 | 18 | // NewLockedRand returns a new "x/exp/rand" pseudo-random number generator seeded with a 19 | // cryptographically-secure random number. 20 | // It is safe to use from multiple goroutines. 21 | func NewLockedRand() *xrand.Rand { 22 | var randSrc = new(xrand.LockedSource) 23 | randSrc.Seed(cryptoSeed()) 24 | return xrand.New(randSrc) 25 | } 26 | 27 | // cryptoSeed returns a random uint64 read from the "crypto/rand" random number generator. It is 28 | // intended to be used to seed pseudorandom number generators at package initialization. It panics 29 | // if it encounters any errors. 30 | func cryptoSeed() uint64 { 31 | var b [8]byte 32 | _, err := io.ReadFull(crand.Reader, b[:]) 33 | if err != nil { 34 | panic(fmt.Errorf("failed to read 8 bytes from a \"crypto/rand\".Reader: %v", err)) 35 | } 36 | 37 | return (uint64(b[0]) << 0) | (uint64(b[1]) << 8) | (uint64(b[2]) << 16) | (uint64(b[3]) << 24) | 38 | (uint64(b[4]) << 32) | (uint64(b[5]) << 40) | (uint64(b[6]) << 48) | (uint64(b[7]) << 56) 39 | } 40 | -------------------------------------------------------------------------------- /internal/randutil/randutil_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package randutil 8 | 9 | import ( 10 | "testing" 11 | 12 | "go.mongodb.org/mongo-driver/v2/internal/require" 13 | ) 14 | 15 | func TestCryptoSeed(t *testing.T) { 16 | seeds := make(map[uint64]bool) 17 | for i := 1; i < 1000000; i++ { 18 | s := cryptoSeed() 19 | require.False(t, seeds[s], "cryptoSeed returned a duplicate value %d", s) 20 | seeds[s] = true 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /internal/spectest/spectest.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package spectest 8 | 9 | import ( 10 | "os" 11 | "path" 12 | "path/filepath" 13 | "runtime" 14 | "testing" 15 | 16 | "go.mongodb.org/mongo-driver/v2/internal/require" 17 | ) 18 | 19 | // FindJSONFilesInDir finds the JSON files in a directory. 20 | func FindJSONFilesInDir(t *testing.T, dir string) []string { 21 | t.Helper() 22 | 23 | files := make([]string, 0) 24 | 25 | entries, err := os.ReadDir(dir) 26 | require.NoError(t, err) 27 | 28 | for _, entry := range entries { 29 | if entry.IsDir() || path.Ext(entry.Name()) != ".json" { 30 | continue 31 | } 32 | 33 | files = append(files, entry.Name()) 34 | } 35 | 36 | if len(files) == 0 { 37 | t.Fatalf("no JSON files found in %q", dir) 38 | } 39 | 40 | return files 41 | } 42 | 43 | // Path returns the absolute path to the given specifications repo file or 44 | // subdirectory. 45 | // 46 | // If the PROJECT_DIRECTORY environment variable is set, Path uses that to find 47 | // the repo root path. Otherwise, it falls back to using the call stack to find 48 | // the repo root path. Path panics if it can't find the repo root path. 49 | func Path(subdir string) string { 50 | root := os.Getenv("PROJECT_DIRECTORY") 51 | if root == "" { 52 | _, file, _, ok := runtime.Caller(0) 53 | if !ok { 54 | panic("unable to get current file path from call stack") 55 | } 56 | 57 | // Get the repository root path from the current Go file path. 58 | root = filepath.Dir(filepath.Dir(filepath.Dir(file))) 59 | } 60 | 61 | return filepath.Join(root, "testdata", "specifications", "source", subdir) 62 | } 63 | -------------------------------------------------------------------------------- /internal/test/goleak/go.mod: -------------------------------------------------------------------------------- 1 | module go.mongodb.go/mongo-driver/v2/internal/test/goleak 2 | 3 | go 1.22 4 | 5 | replace go.mongodb.org/mongo-driver => ../../../ 6 | 7 | require ( 8 | github.com/stretchr/testify v1.9.0 9 | go.mongodb.org/mongo-driver/v2 v2.0.0-beta2 10 | go.uber.org/goleak v1.3.0 11 | ) 12 | 13 | require ( 14 | github.com/davecgh/go-spew v1.1.1 // indirect 15 | github.com/golang/snappy v1.0.0 // indirect 16 | github.com/klauspost/compress v1.16.7 // indirect 17 | github.com/kr/pretty v0.3.0 // indirect 18 | github.com/pmezard/go-difflib v1.0.0 // indirect 19 | github.com/rogpeppe/go-internal v1.8.1 // indirect 20 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 21 | github.com/xdg-go/scram v1.1.2 // indirect 22 | github.com/xdg-go/stringprep v1.0.4 // indirect 23 | github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect 24 | golang.org/x/crypto v0.28.0 // indirect 25 | golang.org/x/sync v0.8.0 // indirect 26 | golang.org/x/text v0.19.0 // indirect 27 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 28 | gopkg.in/yaml.v3 v3.0.1 // indirect 29 | ) 30 | -------------------------------------------------------------------------------- /mongo/address/addr.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package address provides structured representations of network addresses. 8 | package address 9 | 10 | import ( 11 | "net" 12 | "strings" 13 | ) 14 | 15 | const defaultPort = "27017" 16 | 17 | // Address is a network address. It can either be an IP address or a DNS name. 18 | type Address string 19 | 20 | // Network is the network protocol for this address. In most cases this will be 21 | // "tcp" or "unix". 22 | func (a Address) Network() string { 23 | if strings.HasSuffix(string(a), "sock") { 24 | return "unix" 25 | } 26 | return "tcp" 27 | } 28 | 29 | // String is the canonical version of this address, e.g. localhost:27017, 30 | // 1.2.3.4:27017, example.com:27017. 31 | func (a Address) String() string { 32 | s := string(a) 33 | if a.Network() != "unix" { 34 | // TODO: unicode case folding? 35 | s = strings.ToLower(string(a)) 36 | } 37 | if len(s) == 0 { 38 | return "" 39 | } 40 | if a.Network() != "unix" { 41 | _, _, err := net.SplitHostPort(s) 42 | if err != nil && strings.Contains(err.Error(), "missing port in address") { 43 | s += ":" + defaultPort 44 | } 45 | } 46 | 47 | return s 48 | } 49 | 50 | // Canonicalize creates a canonicalized address. 51 | func (a Address) Canonicalize() Address { 52 | return Address(a.String()) 53 | } 54 | -------------------------------------------------------------------------------- /mongo/address/addr_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package address 8 | 9 | import ( 10 | "testing" 11 | 12 | "go.mongodb.org/mongo-driver/v2/internal/require" 13 | ) 14 | 15 | func TestAddress_String(t *testing.T) { 16 | tests := []struct { 17 | in string 18 | expected string 19 | }{ 20 | {"a", "a:27017"}, 21 | {"A", "a:27017"}, 22 | {"A:27017", "a:27017"}, 23 | {"a:27017", "a:27017"}, 24 | {"a.sock", "a.sock"}, 25 | {"A.sock", "A.sock"}, 26 | } 27 | 28 | for _, test := range tests { 29 | t.Run(test.in, func(t *testing.T) { 30 | require.Equal(t, Address(test.in).String(), test.expected) 31 | }) 32 | } 33 | } 34 | 35 | func TestAddress_Canonicalize(t *testing.T) { 36 | tests := []struct { 37 | in string 38 | expected string 39 | }{ 40 | {"a", "a:27017"}, 41 | {"A", "a:27017"}, 42 | {"A:27017", "a:27017"}, 43 | {"a:27017", "a:27017"}, 44 | {"a.sock", "a.sock"}, 45 | } 46 | 47 | for _, test := range tests { 48 | t.Run(test.in, func(t *testing.T) { 49 | require.Equal(t, Address(test.in).Canonicalize(), Address(test.expected)) 50 | }) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /mongo/background_context.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package mongo 8 | 9 | import "context" 10 | 11 | // backgroundContext is an implementation of the context.Context interface that wraps a child Context. Value requests 12 | // are forwarded to the child Context but the Done and Err functions are overridden to ensure the new context does not 13 | // time out or get cancelled. 14 | type backgroundContext struct { 15 | context.Context 16 | childValuesCtx context.Context 17 | } 18 | 19 | // newBackgroundContext creates a new Context whose behavior matches that of context.Background(), but Value calls are 20 | // forwarded to the provided ctx parameter. If ctx is nil, context.Background() is returned. 21 | func newBackgroundContext(ctx context.Context) context.Context { 22 | if ctx == nil { 23 | return context.Background() 24 | } 25 | 26 | return &backgroundContext{ 27 | Context: context.Background(), 28 | childValuesCtx: ctx, 29 | } 30 | } 31 | 32 | func (b *backgroundContext) Value(key interface{}) interface{} { 33 | return b.childValuesCtx.Value(key) 34 | } 35 | -------------------------------------------------------------------------------- /mongo/gridfs_bucket_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package mongo 8 | 9 | import ( 10 | "context" 11 | "testing" 12 | 13 | "go.mongodb.org/mongo-driver/v2/bson" 14 | "go.mongodb.org/mongo-driver/v2/internal/assert" 15 | "go.mongodb.org/mongo-driver/v2/internal/integtest" 16 | "go.mongodb.org/mongo-driver/v2/mongo/options" 17 | ) 18 | 19 | func TestBucket_openDownloadStream(t *testing.T) { 20 | tests := []struct { 21 | name string 22 | filter interface{} 23 | err error 24 | }{ 25 | { 26 | name: "nil filter", 27 | filter: nil, 28 | err: ErrNilDocument, 29 | }, 30 | { 31 | name: "nonmatching filter", 32 | filter: bson.D{{"x", 1}}, 33 | err: ErrFileNotFound, 34 | }, 35 | } 36 | 37 | cs := integtest.ConnString(t) 38 | clientOpts := options.Client().ApplyURI(cs.Original) 39 | 40 | integtest.AddTestServerAPIVersion(clientOpts) 41 | 42 | client, err := Connect(clientOpts) 43 | assert.Nil(t, err, "Connect error: %v", err) 44 | 45 | db := client.Database("bucket") 46 | 47 | for _, test := range tests { 48 | t.Run(test.name, func(t *testing.T) { 49 | bucket := db.GridFSBucket() 50 | _, err = bucket.openDownloadStream(context.Background(), test.filter) 51 | assert.ErrorIs(t, err, test.err) 52 | }) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /mongo/options/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package options defines the optional configurations for the MongoDB Go Driver. 8 | package options 9 | -------------------------------------------------------------------------------- /mongo/options/dropcollectionoptions.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package options 8 | 9 | // DropCollectionOptions represents arguments that can be used to configure a 10 | // Drop operation. 11 | // 12 | // See corresponding setter methods for documentation. 13 | type DropCollectionOptions struct { 14 | EncryptedFields interface{} 15 | } 16 | 17 | // DropCollectionOptionsBuilder contains options to configure collection drop 18 | // operations. Each option can be set through setter functions. See 19 | // documentation for each setter function for an explanation of the option. 20 | type DropCollectionOptionsBuilder struct { 21 | Opts []func(*DropCollectionOptions) error 22 | } 23 | 24 | // DropCollection creates a new DropCollectionOptions instance. 25 | func DropCollection() *DropCollectionOptionsBuilder { 26 | return &DropCollectionOptionsBuilder{} 27 | } 28 | 29 | // List returns a list of DropCollectionOptions setter functions. 30 | func (d *DropCollectionOptionsBuilder) List() []func(*DropCollectionOptions) error { 31 | return d.Opts 32 | } 33 | 34 | // SetEncryptedFields sets the encrypted fields for encrypted collections. 35 | // 36 | // This option is only valid for MongoDB versions >= 6.0 37 | func (d *DropCollectionOptionsBuilder) SetEncryptedFields(encryptedFields interface{}) *DropCollectionOptionsBuilder { 38 | d.Opts = append(d.Opts, func(opts *DropCollectionOptions) error { 39 | opts.EncryptedFields = encryptedFields 40 | 41 | return nil 42 | }) 43 | 44 | return d 45 | } 46 | -------------------------------------------------------------------------------- /mongo/options/lister.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package options 8 | 9 | // Lister is an interface that wraps a List method to return a 10 | // slice of option setters. 11 | type Lister[T any] interface { 12 | List() []func(*T) error 13 | } 14 | -------------------------------------------------------------------------------- /mongo/options/runcmdoptions.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package options 8 | 9 | import ( 10 | "go.mongodb.org/mongo-driver/v2/mongo/readpref" 11 | ) 12 | 13 | // RunCmdOptions represents arguments that can be used to configure a RunCommand 14 | // operation. 15 | // 16 | // See corresponding setter methods for documentation. 17 | type RunCmdOptions struct { 18 | ReadPreference *readpref.ReadPref 19 | } 20 | 21 | // RunCmdOptionsBuilder contains options to configure runCommand operations. 22 | // Each option can be set through setter functions. See documentation for each 23 | // setter function for an explanation of the option. 24 | type RunCmdOptionsBuilder struct { 25 | Opts []func(*RunCmdOptions) error 26 | } 27 | 28 | // RunCmd creates a new RunCmdOptions instance. 29 | func RunCmd() *RunCmdOptionsBuilder { 30 | return &RunCmdOptionsBuilder{} 31 | } 32 | 33 | // List returns a list of CountOptions setter functions. 34 | func (rc *RunCmdOptionsBuilder) List() []func(*RunCmdOptions) error { 35 | return rc.Opts 36 | } 37 | 38 | // SetReadPreference sets value for the ReadPreference field. Specifies the read preference 39 | // to use for the operation. The default value is nil, which means that the primary read 40 | // preference will be used. 41 | func (rc *RunCmdOptionsBuilder) SetReadPreference(rp *readpref.ReadPref) *RunCmdOptionsBuilder { 42 | rc.Opts = append(rc.Opts, func(opts *RunCmdOptions) error { 43 | opts.ReadPreference = rp 44 | 45 | return nil 46 | }) 47 | 48 | return rc 49 | } 50 | -------------------------------------------------------------------------------- /mongo/options/testdata/ca-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEAo+gfY2cD5r55HwqLDauU7Fj7jv7iYUzjNG3/iTPrsHkSrmmW 3 | /DnmQ9Px/D78sOwkIzLNqdt4j94pOxEzY4XzVpYqoiTUkJH+vj7yoEhlCulgvewY 4 | Jp6s5dSo0k5DksVLbCjKOfXzL5hAwn//Q1P9m58sBwb1FW7ElHK6CNIhLoijeJPi 5 | v7SUPb6mitPzn4k+WAbPLgsOGoFJMVns0czzhcc45nlVZIsW1UsETjXAcof1MSh4 6 | bpGgjNo/0Tnkn2mrPeS4n1KsWTPWGjVQBCXhKBXLGDIrLksF5H4OF26SOSq0lg2O 7 | 6zjDDfIiEiAmTDHojJHBAAVVk9h8jmOG/J1qVwIDAQABAoIBACO1gJEhcmIlATJY 8 | E69owEs1n6ipsxxLqfxUMqXrn9+UoRNKgdB1tMr2M/QmrNrGt6DLgq8M15lQZ18t 9 | AiselcM5eBRXPdA5XmyIPkfZPdpAugjmlORlEXoI+LbIwkQJo8LuqBA0m0S1QPae 10 | +Dfs5oWvCeKGC4Md3MoSrKEbVotSdC1P3MCM+tCzYIL+QivjOJFMGrdYhk9qQRER 11 | U7G03j5JZmknMo82JknxsAgunrWEZlwfA+KrvXOwAgTQJxtqh1lKv+NK6EhIjqVm 12 | 25Zgi89SFqFNS5ShrzdNqvBZyrEktzr4oi4fWR5MoQR/5wIjF92nc9+qjhqvj5U8 13 | 9kl9LYECgYEAxkblYtVi7YXUjT2JZ93n+3tUiXvf966pQjtux01Qg3t1X2lJ8OrL 14 | PI/A4anT6s5PNnHENuRJj/k9Uu9AItv4IonklmMGwOKvxUBgl9aHEYFjJ2+ej6wp 15 | 2OXawdSIinuCBTQ/qX5IrgmQFPrj80585pVhB0zDuqtl1af3TauVWWECgYEA05+y 16 | jPXxM2+ws73XBaPFHMUpHCUTSHtljjLM+aSbIlklHtTCvmdOFG8Qrhn9O6ivJ6ms 17 | C91ETB0JJ3ZSnimvYK/yV7N6lJcY1GSLOdLScf0oFGAbLQbk5h5t5iIuhOi8lJCa 18 | atg8zIQMADudrHtbQGtQrz6903jJrYUOB6SqRrcCgYEAmb4lZeJyKB0KuE4L+ob9 19 | t2llHon4G3TKd7nf5xhTIvCbDVV16SIWXypUdGacFMjOcTf73lhblhC79U/g2mbY 20 | W+eyYM3+UZg0lO2bOIE3EGLUgKKzP1JOzIlGe9+R1Fd6dRCTgJiUQKbXmv0DvgiR 21 | Hrabmu5yIo9+khIA17ABSWECgYBVfIt6GdfHuXSeBzAXHSMBDjwfHHL/sqlBmg/n 22 | QLFSXMR8AeJxW/XUl1Ebo3ACa4/l68qOOGHghVIvWMLjFV+9JRY2i1AXOjpTghIj 23 | 16AfX+6S3Ifd1o0c0GoArwovsnyLXyahxpw42ZaneW2mQWaJTVCYmjXAeWiu6bLT 24 | L5eBXQKBgD/TvxZ+VEAJPMUDAoTahZ//RwokBX8zOkRAnCl8VCLU0kLv9/Phht7F 25 | Ntg/pnJ0Ksrhr4X5WRl/ziAIXwc2j+qVGjwXnU0o9tu/KJ7OkfCAFjSM6Tk6ILE2 26 | MN7yw4baP/7JNQcf90VsIcTUvBOOu+agO2FuE5P86C8DaRkTE1Co 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /mongo/options/testdata/ca-with-intermediates-first.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDdDCCAlwCBBmRIxIwDQYJKoZIhvcNAQELBQAwdDELMAkGA1UEBhMCVVMxETAP 3 | BgNVBAgMCE5ldyBZb3JrMRYwFAYDVQQHDA1OZXcgWW9yayBDaXR5MRAwDgYDVQQK 4 | DAdNb25nb0RCMQ8wDQYDVQQLDAZLZXJuZWwxFzAVBgNVBAMMDktlcm5lbCBUZXN0 5 | IENBMB4XDTE5MDkyNTIzMjczOVoXDTM5MDkyNzIzMjczOVowdDELMAkGA1UEBhMC 6 | VVMxETAPBgNVBAgMCE5ldyBZb3JrMRYwFAYDVQQHDA1OZXcgWW9yayBDaXR5MRAw 7 | DgYDVQQKDAdNb25nb0RCMQ8wDQYDVQQLDAZLZXJuZWwxFzAVBgNVBAMMDktlcm5l 8 | bCBUZXN0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAupVkx8+n 9 | AqzsANKwNPeCYlf2q0WgF4kSUMNJdpmMelrr7hh7EOnAU0hTAQx9BKTEbExeCzH6 10 | OArFNGjewjWVXwaOpCjK8FMvK6/lGVEpmoHNF9XuiQVmaQ4bJD6rC73YjpgNIPeL 11 | 5PyoFLEZv+X2cRBPpTcSRcf87tk8HL7v0eyk1JBhkeKK68SYdWwZlHaa1jqwmliW 12 | WvVMkHVH3lx0VOgQwWtOgs0K1zpcZ0sH5MGpYRQOiidIRZj3PkKeTPQe2D6VQQtv 13 | 2yDs9dWfCxJJP9QiWclL2rF/xqlFSNEIfNZpZhk6I1DHQpA2uyJfzRH62pFasJuB 14 | CVh5Tr0EDoVreQIDAQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEB 15 | CwUAA4IBAQARdNCYYWxi2fyhJwzGHwIT261d/pTlOSYLlm84c72aEneFUnfp8/H5 16 | JjuFbnhiX+5+h3M7eDQhra9s+H3vKr7o38EIVf5OKXvpNLwv1UUmomBvKqccioYh 17 | bxrfwCzfBRuUmW05kcAVn8iKovqyxL7npEZbckwtT+BqZ4kOL4Uzre+S1HMx0zOu 18 | xulSYA/sBoJ2BB93ZIAqB+f/+InS9yggzyhhaQqS7QEl1L4nZE4Oy0jKcxdCzysm 19 | TqiyH+OI5SVRTfXh4XvHmdWBBaQyaTmQzXYUxUi7jg1jEAiebCGrEJv9plwq4KfC 20 | cze9NLBjaXR3GzonT8kICyVT/0UvhuJg 21 | -----END CERTIFICATE----- 22 | -------------------------------------------------------------------------------- /mongo/options/testdata/ca-with-intermediates-second.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDcjCCAloCBFNvXv0wDQYJKoZIhvcNAQELBQAwdDELMAkGA1UEBhMCVVMxETAP 3 | BgNVBAgMCE5ldyBZb3JrMRYwFAYDVQQHDA1OZXcgWW9yayBDaXR5MRAwDgYDVQQK 4 | DAdNb25nb0RCMQ8wDQYDVQQLDAZLZXJuZWwxFzAVBgNVBAMMDktlcm5lbCBUZXN0 5 | IENBMB4XDTE5MTAxNjE3NTc0OVoXDTM5MTAxODE3NTc0OVowdTELMAkGA1UEBhMC 6 | VVMxETAPBgNVBAgMCE5ldyBZb3JrMRYwFAYDVQQHDA1OZXcgWW9yayBDaXR5MRAw 7 | DgYDVQQKDAdNb25nb0RCMQ8wDQYDVQQLDAZLZXJuZWwxGDAWBgNVBAMMD0ludGVy 8 | bWVkaWF0ZSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOcrt0K/ 9 | K8ueq9lQ9wVtA+rka82FPaHXpZkH7ii/ZJlNcDXLaJPdRb7XgAabAS3gru+Hpm/g 10 | kAofoL7cDmGZRAbiW0I6X5Nlmjh4/0E6RxSs0urhU34m8sM3OPmAgbq7oLlFINZ6 11 | GbVR2RzMWhK5HPld8WApDkIVpBFbRGV7dt/LVKY34Nab9hu15WRSH3wzSHJvt8e1 12 | alYxaRUoE27Fk3zdHPw9Z91/XvfIThTsNXEQVOeaieyQLwoKx8tpMa/ck/mFmSkD 13 | nH4h37ev0ZABB04iTBfLGCpUCKd5LerYIqEu4UPp9r9czbco7twp+k8875pJ3bpV 14 | wMH0/jF68GTC8HsCAwEAAaMQMA4wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsF 15 | AAOCAQEAaL61HT6JD19Ok2LY6b5KkZ4oRhiV73l2/82X88GcV63Bl0rN6AF+W0ut 16 | GuHzSqcHV4qZkt9ezNoDYq41BsV4I8Cxvyaz8is956uyrzQAsVCzidZSGeq2GIfV 17 | 9y+IRISBRdzXQHrB0ni93b16MJO1KoJxZbXcb8W9ll2URp+YEnHIrhWpDcMcHN3O 18 | mjoy1+WpHDXpNK2D3Xk5tT5pwxJZWRPB9wvPfTux5Vp07+Rkef9YjXL2ZZxt4vKu 19 | WU0HJWfK905HpbHjwFNRlbT39WWaF8VeJ2nT6OrXTpE8tDdPoeZt5u76eaWEmsf5 20 | gX2ClrsSmegOKT52V+2NAlKDjQkaDg== 21 | -----END CERTIFICATE----- 22 | -------------------------------------------------------------------------------- /mongo/options/testdata/ca-with-intermediates-third.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDaTCCAlECBCLMKCQwDQYJKoZIhvcNAQELBQAwdTELMAkGA1UEBhMCVVMxETAP 3 | BgNVBAgMCE5ldyBZb3JrMRYwFAYDVQQHDA1OZXcgWW9yayBDaXR5MRAwDgYDVQQK 4 | DAdNb25nb0RCMQ8wDQYDVQQLDAZLZXJuZWwxGDAWBgNVBAMMD0ludGVybWVkaWF0 5 | ZSBDQTAeFw0xOTEwMTYxNzU3NDlaFw0zOTEwMTgxNzU3NDlaMH0xCzAJBgNVBAYT 6 | AlVTMREwDwYDVQQIDAhOZXcgWW9yazEWMBQGA1UEBwwNTmV3IFlvcmsgQ2l0eTEQ 7 | MA4GA1UECgwHTW9uZ29EQjEPMA0GA1UECwwGS2VybmVsMSAwHgYDVQQDDBdTZXJ2 8 | ZXIgVmlhIEludGVybWVkaWF0ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC 9 | ggEBAKCj95jJi63dCJDKyTWQAJwgLtvqwPmIvBMbYMcmrolP3tYolwkkh6c0RJdP 10 | UTy4gJaLZ9b9B8GuiGFatG+ZzEqCUh6AlG1lGJwdyqyP2eotpzkZJhwLGFc81DUt 11 | 7WKhZjHikgXcAd3VMCXsjv7/axvBnc459SpsCW5heOiJ3Ap8OJIrTuD4GAWW5cfW 12 | GYa1v07hqXZ7SEloRE5Hm5bItnZA9+A5QNCj2a2PqK3TlrtCnDP125iYHc4W/+NO 13 | 1V9LPKpDffdJ7slhrX69k9oV8HTQBgu7lRHKQlprW64pg6EMsw/5hpGjpZkyG9J9 14 | L1FYrXqsagA1E5j87JQH+SJDOEUCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAPRu7 15 | YtgaGPx4O2IfvYoK+BsiD/55WylDp/0zxf/xipvuoPRcMgX1ORoNuQTPfeIMxlZS 16 | UAIRHQSjOZQkH0WL2dglqaoBhTXO6c0PUuWOUsDDwnZE8lj26Jkka6PC8d8t7gjt 17 | w/k2IRnhcklKOu6pNlcYi+/WGcWphmkjMRWeka0vqXab/bxF1sdeHD9bMY59QOwI 18 | FT0JCG8Wn0LSi6V/Ip35JV3CryBP1Jual2aCXIXEKm3m+P4NboRQTZ7zqIcJoA8S 19 | i2GkuHCPOhhQP2isiRRBILujcJxnRYrR7qNIqvMrmPx3va8fMrHKtWAx+bfo/EIJ 20 | hlU1Eyls7Xv83x3vaA== 21 | -----END CERTIFICATE----- 22 | -------------------------------------------------------------------------------- /mongo/options/testdata/ca.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDmzCCAoOgAwIBAgIUDcX5ZdXD55buEoQtl45OcMrCtSUwDQYJKoZIhvcNAQEL 3 | BQAwXTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRYwFAYDVQQHEw1O 4 | ZXcgWW9yayBDaXR5MRUwEwYDVQQKEwxNb25nb0RCLCBJbmMxDDAKBgNVBAsTA1dX 5 | VzAeFw0xOTAyMDgxODM2MDBaFw0yNDAyMDcxODM2MDBaMF0xCzAJBgNVBAYTAlVT 6 | MREwDwYDVQQIEwhOZXcgWW9yazEWMBQGA1UEBxMNTmV3IFlvcmsgQ2l0eTEVMBMG 7 | A1UEChMMTW9uZ29EQiwgSW5jMQwwCgYDVQQLEwNXV1cwggEiMA0GCSqGSIb3DQEB 8 | AQUAA4IBDwAwggEKAoIBAQCj6B9jZwPmvnkfCosNq5TsWPuO/uJhTOM0bf+JM+uw 9 | eRKuaZb8OeZD0/H8Pvyw7CQjMs2p23iP3ik7ETNjhfNWliqiJNSQkf6+PvKgSGUK 10 | 6WC97Bgmnqzl1KjSTkOSxUtsKMo59fMvmEDCf/9DU/2bnywHBvUVbsSUcroI0iEu 11 | iKN4k+K/tJQ9vqaK0/OfiT5YBs8uCw4agUkxWezRzPOFxzjmeVVkixbVSwRONcBy 12 | h/UxKHhukaCM2j/ROeSfaas95LifUqxZM9YaNVAEJeEoFcsYMisuSwXkfg4XbpI5 13 | KrSWDY7rOMMN8iISICZMMeiMkcEABVWT2HyOY4b8nWpXAgMBAAGjUzBRMA4GA1Ud 14 | DwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBT6a2dHAAcv+ueV 15 | zUQcteAnZXAHIzAPBgNVHREECDAGhwR/AAABMA0GCSqGSIb3DQEBCwUAA4IBAQBa 16 | KQn/gWmyFE8LaL6lCEmSveT2jKk1OfJ6QFFAv8sJZhhx9X4HaYzFhhafvX7pp9TZ 17 | JLBDRznb4aro6u81jLk6lIP8eQsDnDk68VZtLOUcIgkO8bUqQP93RsNJKyv2o6h4 18 | eEyNb3cHqrhD05PlGx5D6uKuLAgfxd2pzx8OHGSV1yfr7asgL0fW+077/OQk/9Gk 19 | C+oi9uLjpKKXKwZz/hhyaKBHovlaw/xmDCjnrn+pnB3K+PFBCdU1yHqiKHcqsnEE 20 | qGrUL+MPP7lK/g2tyybrZVyXMVsvhESgk3RFao0cR0jj6xQDaSRNTSAX9Rl3ZysJ 21 | 9P1ekH8zhXV924mUePXW 22 | -----END CERTIFICATE----- 23 | -------------------------------------------------------------------------------- /mongo/options/testdata/cert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIEejCCA2KgAwIBAgIJAM+1x3rLrnhEMA0GCSqGSIb3DQEBBQUAMIGEMQswCQYD 3 | VQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxFjAUBgNVBAcTDU5ldyBZb3JrIENp 4 | dHkxEDAOBgNVBAoTB01vbmdvREIxEDAOBgNVBAsTB0RyaXZlcnMxJjAkBgNVBAMT 5 | HUV4YW1wbGUgR28gRHJpdmVyIENlcnRpZmljYXRlMB4XDTE5MDIwODE4MzUxNloX 6 | DTI5MDIwNTE4MzUxNlowgYQxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhOZXcgWW9y 7 | azEWMBQGA1UEBxMNTmV3IFlvcmsgQ2l0eTEQMA4GA1UEChMHTW9uZ29EQjEQMA4G 8 | A1UECxMHRHJpdmVyczEmMCQGA1UEAxMdRXhhbXBsZSBHbyBEcml2ZXIgQ2VydGlm 9 | aWNhdGUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvUnMj0/0tnvmi 10 | c5qR9HFIHyuow8DKsJggyy9DMWP7NlOV309rMj9bghithSrjP7LGc5wRMHpOd2Iu 11 | BtL21Mxlb09Vo8lEYnS0vZQg7fu+JPcRL3cwtRm5BOQFy8PghrAOUcq8UNxBfOb4 12 | 0f8OjEtAE4yCVTDvzUg6YOohwJi3Qm98qVwYy2RAo5BM2EK8ZyFbF+Eouz6hHHf+ 13 | q0anWX5qI4gpCpQgrrtD4x+IRDjWfUwX3AJ1RsMgrPkv/aaVjw2u0Qx4m5m8q64s 14 | dJCjDHHesCLMm7Eygt92mjYrAmJfeUeLovGntwPi1ZWz3Mbd9BRUGQb2mKSEJEao 15 | hTssMOAfAgMBAAGjgewwgekwHQYDVR0OBBYEFPGN3fwZlmrOpQzO6ZYydSM4xF5m 16 | MIG5BgNVHSMEgbEwga6AFPGN3fwZlmrOpQzO6ZYydSM4xF5moYGKpIGHMIGEMQsw 17 | CQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxFjAUBgNVBAcTDU5ldyBZb3Jr 18 | IENpdHkxEDAOBgNVBAoTB01vbmdvREIxEDAOBgNVBAsTB0RyaXZlcnMxJjAkBgNV 19 | BAMTHUV4YW1wbGUgR28gRHJpdmVyIENlcnRpZmljYXRlggkAz7XHesuueEQwDAYD 20 | VR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEARyAiYkXwGRyLOkjcZ9+5ZYD8 21 | fyLSYda4LpPUWL46nJGYJvDZrfEYsX9nCrOEty0WwBa6WVZupV/beLSgosLf3DmS 22 | pApExPw7tOZAxD+MtX5IM3jA3+EDHZpSZElK4VeZ0MGE3ZLj8MzcKF1qDjOIVjxk 23 | bCnDBaO/SG4oEIzUwwiTUgwjMwTOta3uM9CUuoYw9KEPtYzh696jzGqPwkqDMMID 24 | NCl1VDgp1TzTHSDOsmjUWMghnozmv4hGPhA67kOWxpnwRd+LadcofvmXmqp13c3Z 25 | WBQQqkcBd92Ud00tBkaYYAZjjhnHEJyCE+TR2DKnk7u/uyBqD2DqbEKXInHcow== 26 | -----END CERTIFICATE----- 27 | -------------------------------------------------------------------------------- /mongo/options/testdata/csr.json: -------------------------------------------------------------------------------- 1 | { 2 | "hosts": [ 3 | "example.com", 4 | "www.example.com", 5 | "127.0.0.1" 6 | ], 7 | "key": { 8 | "algo": "rsa", 9 | "size": 2048 10 | }, 11 | "names": [ 12 | { 13 | "C": "US", 14 | "L": "New York City", 15 | "O": "MongoDB, Inc", 16 | "OU": "WWW", 17 | "ST": "New York" 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /mongo/options/testdata/empty-ca.pem: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb/mongo-go-driver/579a2659ff88b1c612182a97b69efe3b0523a76c/mongo/options/testdata/empty-ca.pem -------------------------------------------------------------------------------- /mongo/options/testdata/key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | Proc-Type: 4,ENCRYPTED 3 | DEK-Info: DES-EDE3-CBC,29C1684ECF3DEADF 4 | 5 | WX/uHcI/ORmzz4N9Pd7FQNRYJo5fye+jsPgmaVBvaVE6y92sbEGoaT8Wzvrm1JYd 6 | yD8emPLHWZuchA7CBx51rc736FWE5oyqf5CLAdp/ZOr4W0VDnhjOjp5wYB/k5c4y 7 | 1lyqFZPejEU0c9UlRiXmZQKKXm7TafM5VSedhDALPuD3aa8lUPAfzVQkkMj3kEoD 8 | YYcMXNA3GiPRiQipbVEcISuhzxQFbqCK1TQBP2xXx12Dl6vGrINElWXGJP4FAqzv 9 | 9m8/Pwu/1RZtEWW7+W4powVM/vCGaRPC0p/YD55BzceC/OLzVDspHajYPvDE0s/e 10 | lmFFPcZaoThFFbIGhqYESFqJ2xcAaQLGsp4viet7JbTfhvZjoYq5ZNcTSlVkDsWz 11 | Cw/kFbFiJoc9yf2AYdvbEazS4SUAzEILliE8ETXTyIqiwhqRq5ZDLbQzVptI2Qhy 12 | DazRdQsUon/7avSYHTcI8e2aUGeyPzujRHfzXgPVR4f6TAy/DJ6mWT+5lP93AdXM 13 | Icfpp2Y5K8VY6N21jPPK9iPixTO2kndRXgGxLsaG8D2bcEAdM3H5BMZCBIBNPTUl 14 | RE79Kdp4YpCNuIHKk80zfGZM5TPJgpTJvd2nDEMM4522nDVF116PByd62S7gj5D6 15 | o0rjpV/Vm26ech2O4d3dwKC+4K7ZHicUIo3HJ16oyxKPniYOlbYRrYUY3kNLmfPG 16 | HF8ZuXauz27x0FGI3zwrEt8j9q1g6l9TIY2NrOEEWoQuK7CrtK4J95/Ypm5bKCdC 17 | yy/saiST9SpjCoz96JhHFY1/zDXqenV9Xz6V1if/42kMJx/nbixpJkHktNCgoZ9i 18 | 5ouT+GZMW0VxtlpG/SgGYSICHlbdSRdrKsJQ752GiqQ7Ijm3gyzlZNyWUY8M/L6U 19 | vKf18YKHOBHBVhleiLi78INVNABtJWoLvJAizjBGD0Nqpo8i1GyPcQv8OTWjbEH6 20 | +gWf6tAaSH+cvJwP0CO+PoyoQ7pf4Gdmo+UFPfEhjXjSpSzY3n7hlmqmTvJ15XD2 21 | ULS4K2w4WBq/wbaRkuWOrqDcI4EoJitCQGtG+XmwErMslbuHPcRPHZvq5F6D34O5 22 | +6z8c75/bpGHCcSOb4aBwU5LrxTPvbiBML42Es7pdy8D4M8PH+W7enjC+jeBS3ey 23 | vkq6Bc4FTS67SWxAx2rXPIIqjgXO/W3iGECycwnJNGtTA3Xg4CDiJGDqEsKZcCpn 24 | SX4CLwGytJhHW8KeSW2i3MjjR7BBzebej8HSzRrdxDO9J8J/usmWPo6T3sgozZuX 25 | HvMI9ApYsm0cYkouqgTmNrMwhyb2hvQbIlJY6Q0l3UekQAuV2RdVQekKgSOY0k6j 26 | KnfMvxVFWpgDfaF/tVQ19kbSLkIlXUc8T4O9Vu61BYRhLY3jxSq8WN5I5sBAJJJ/ 27 | WL46ihd4ttkAKjSH6WUnDgXDMWp/mjUwYB+JZKzRr1C97kWAKdsFI+J83aBcCKtZ 28 | M5l8Sq9QsosNuAV7UjKJMwUz6mT4U/txTzEvShQTBbHTHAveS5cUYlW40dTtaNPJ 29 | XxEt/4jpjugODg94nWxDV55vfn8RkmpVxPKMOGKDDUQunuLXAdP97Gu2RoFqFVaQ 30 | -----END RSA PRIVATE KEY----- 31 | -------------------------------------------------------------------------------- /mongo/options/testdata/malformed-ca.pem: -------------------------------------------------------------------------------- 1 | totally valid CA certificate 2 | -------------------------------------------------------------------------------- /mongo/options/testdata/nopass/cert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDxjCCAq6gAwIBAgIUdT7iyEmPsG2bPvhF080w1UpbXEowDQYJKoZIhvcNAQEL 3 | BQAwXTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRYwFAYDVQQHEw1O 4 | ZXcgWW9yayBDaXR5MRUwEwYDVQQKEwxNb25nb0RCLCBJbmMxDDAKBgNVBAsTA1dX 5 | VzAeFw0xOTAyMDgxODUzMDBaFw0yMDAyMDgxODUzMDBaMF0xCzAJBgNVBAYTAlVT 6 | MREwDwYDVQQIEwhOZXcgWW9yazEWMBQGA1UEBxMNTmV3IFlvcmsgQ2l0eTEVMBMG 7 | A1UEChMMTW9uZ29EQiwgSW5jMQwwCgYDVQQLEwNXV1cwggEiMA0GCSqGSIb3DQEB 8 | AQUAA4IBDwAwggEKAoIBAQCS1V3pEo4El+dii490Nz3qi1iLWx+bzUXpM96NDcFF 9 | v/u9VHBtyOlCSK9/kgzbnq01PqMJr3Rq3x6K1Lwd+wlqpp+bfNCRn7unhfiRQ3aL 10 | BpZbNSYrtaWMWK2RqqdBv5lIM0xoGsFpZT4QhbAdc/i7HajlGgrkizPvcsvQadsA 11 | Itj7sbPZswqEqQS+nFLpPmA0vF5klVESZsuzXiEtO1crHNYSXAbSaYZfl3A7xUhw 12 | idtroXm28HifF1DcPX8QiEREjgPDyZdJpbOmDt6xx52pRpX78GgWfHSusgESezwi 13 | lMUVJ0tyXFMvhqdKnW//RV/OUe8UFES/IVZ5l+r1t1EfAgMBAAGjfjB8MA4GA1Ud 14 | DwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0T 15 | AQH/BAIwADAdBgNVHQ4EFgQUrs6cayQcO4BLP8ccND0O/hvBTK0wHgYDVR0RBBcw 16 | FYITZXhhbXBsZS5tb25nb2RiLmNvbTANBgkqhkiG9w0BAQsFAAOCAQEAmXvIbyK+ 17 | GyPN9KQpN/gS4XB6ajVAmTqNqvxMs6Ql/y6crjBn2wP0FIYNuDThP0byeOLBUmOL 18 | /0Qz3QpeCOCIal03fZdUte0Nypj/N6LFbo6V53Ir+AFz7rzKHPMj52KoPGTLDhgN 19 | LqanKkO630+pOoYeNfFLKJpEX+5JqiVMqCxwIdjmz94MG2RAKS4kGjtTLL0Ac52N 20 | gWb/YJKhQazoRuFqLpowcQwOIgpis4goZnJ3qm4wakY50/fOLTLZutkJu4zkGenG 21 | +x8NZ7ht6uVHVNhC8IIC/b60VOr3rylBZm+NTcP2AaWKZ5TVEyIm8CkGnF7D/4aa 22 | XYPCLNQsuA93sg== 23 | -----END CERTIFICATE----- 24 | -------------------------------------------------------------------------------- /mongo/options/testdata/nopass/key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEAktVd6RKOBJfnYouPdDc96otYi1sfm81F6TPejQ3BRb/7vVRw 3 | bcjpQkivf5IM256tNT6jCa90at8eitS8HfsJaqafm3zQkZ+7p4X4kUN2iwaWWzUm 4 | K7WljFitkaqnQb+ZSDNMaBrBaWU+EIWwHXP4ux2o5RoK5Isz73LL0GnbACLY+7Gz 5 | 2bMKhKkEvpxS6T5gNLxeZJVREmbLs14hLTtXKxzWElwG0mmGX5dwO8VIcInba6F5 6 | tvB4nxdQ3D1/EIhERI4Dw8mXSaWzpg7escedqUaV+/BoFnx0rrIBEns8IpTFFSdL 7 | clxTL4anSp1v/0VfzlHvFBREvyFWeZfq9bdRHwIDAQABAoIBAGHqRPii9e+cOKGf 8 | fWc7W1+n0sEDYB2ukntDqpoXXRYdQ0trHponS113SQjiJQ7jTo/eGCziQtjtttlP 9 | qa64c/wZ5v9yCUfC5Al/rlV4TnnBR8zEsZKeTCo+DGjCC00t7pKWGtKlXOrip7Ou 10 | 4tWRO4HT8ofsiO0E4vo/bCisHm2EzOSwjwT1RBV6wuOxVNa5ITY6nq/4zu+KbcQP 11 | x4T1jAk3mte9E9+C2k5UXB+uBSg+jxnw+7MgP0Lr5ZtkKHf3rdcpWcHXTkR3Jjsp 12 | eBGx8A+aiqEdXIxFYIMomJrUsSPYM2pZ2foFr0EuJA2c2Ht6dh6PKpM3WYEmxGJg 13 | ltuwriECgYEAw43/MNYS4hSEU9XRnsry71T16ZpIf1DEGNdm8hUpR5l5xGWxBCNN 14 | t/UShGklpRrXjSrZZmvCJRfJ4EfSGMUk22xy1gtkHq/3/mcfuLUTL2qi+EmGyLI/ 15 | lLni94msCZWJKfXQphVt0BdlMK6SrN3dQTZhOYXBEe4AMaoWHFJXYBECgYEAwDge 16 | tKHDzUycfbLPxfRsg5TinuFe6JZ2RZwf+sY+X9+v96cIiYH7eobO4MxcX/CriDlX 17 | fHfqrFYhwXGkw9vwPfRx2BRMPELh2u6+ZKnt5vUahsEWE29nLjlZa+OPsa8NoxXv 18 | bNS03VhPu2pwf6LMWnQVXzR9zagwMetX1dFvzi8CgYEAiBR24WAGseY/Eyu2e/6U 19 | QPFpUo63JklovDSggZMyL43gS0fMf6mlen6CzTtyI8ti9ew8bmZMKo28QGMaE3yU 20 | olB8NPCmUih3tUPDsj/nQta843Qe4+gOEIuuIj1eRykU0usor3o3+VdeZhsFHGAj 21 | iC60R1gJO1XYMrc+PaUbAlECgYBpIgjBWTzj3AQ3yAZWSjLT4Sn2JmQnqKv1tMfU 22 | /Hr/KzRuqsBDnYFzaapbT8syeksHjf1oyZnkOpPp3wN0UKZc7Icb3TY5O4eWnEAs 23 | hLjnOqYQkClH5gW0RY/AL83XLFy0F3pFty1ZZ0Tsx/HSDbPhwV4zHV21j0kU9Jit 24 | DQku5wKBgEjABXtkNyAH2PObn10sPphaAFFJop6QRNpwwF/dx+jrd+nPd+wZzK9U 25 | AbE6K+VjjZ39vQ0mfawfHwjyQ3QR3Pb/fGzmQ8pQjpGT227A8IdcGOy6Acffg+uF 26 | V8K9VbdLIIC7A3h3Bwf7E3aGddIB+rJeApAg/8UlFgvMiJDb8a+2 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /mongo/readpref/mode_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2020-present. 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package readpref 8 | 9 | import ( 10 | "testing" 11 | 12 | "go.mongodb.org/mongo-driver/v2/internal/assert" 13 | ) 14 | 15 | func TestMode_String(t *testing.T) { 16 | t.Parallel() 17 | 18 | testCases := []struct { 19 | name string 20 | mode Mode 21 | }{ 22 | {"primary", PrimaryMode}, 23 | {"primaryPreferred", PrimaryPreferredMode}, 24 | {"secondary", SecondaryMode}, 25 | {"secondaryPreferred", SecondaryPreferredMode}, 26 | {"nearest", NearestMode}, 27 | {"unknown", Mode(42)}, 28 | } 29 | 30 | for _, tc := range testCases { 31 | t.Run(tc.name, func(t *testing.T) { 32 | assert.Equal(t, tc.name, tc.mode.String(), "expected %q, got %q", tc.name, tc.mode.String()) 33 | }) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /mongo/writeconcern/writeconcern_example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package writeconcern_test 8 | 9 | import ( 10 | "go.mongodb.org/mongo-driver/v2/mongo" 11 | "go.mongodb.org/mongo-driver/v2/mongo/options" 12 | "go.mongodb.org/mongo-driver/v2/mongo/writeconcern" 13 | ) 14 | 15 | // Configure a Client with write concern "majority" that requests 16 | // acknowledgement that a majority of the nodes have committed write operations. 17 | func Example_majority() { 18 | wc := writeconcern.Majority() 19 | 20 | opts := options.Client(). 21 | ApplyURI("mongodb://localhost:27017"). 22 | SetWriteConcern(wc) 23 | 24 | _, err := mongo.Connect(opts) 25 | if err != nil { 26 | panic(err) 27 | } 28 | } 29 | 30 | // Configure a Client with a write concern that requests acknowledgement that 31 | // exactly 2 nodes have committed and journaled write operations. 32 | func Example_w2Journaled() { 33 | wc := &writeconcern.WriteConcern{ 34 | W: 2, 35 | Journal: boolPtr(true), 36 | } 37 | 38 | opts := options.Client(). 39 | ApplyURI("mongodb://localhost:27017"). 40 | SetWriteConcern(wc) 41 | 42 | _, err := mongo.Connect(opts) 43 | if err != nil { 44 | panic(err) 45 | } 46 | } 47 | 48 | // boolPtr is a helper function to convert a bool constant into a bool pointer. 49 | // 50 | // If you're using a version of Go that supports generics, you can define a 51 | // generic version of this function that works with any type. For example: 52 | // 53 | // func ptr[T any](v T) *T { 54 | // return &v 55 | // } 56 | func boolPtr(b bool) *bool { 57 | return &b 58 | } 59 | -------------------------------------------------------------------------------- /sbom.json: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "timestamp": "2024-05-02T17:36:29.429171+00:00" 4 | }, 5 | "components": [], 6 | "serialNumber": "urn:uuid:06a59521-ad52-420b-aee6-7d9ed15e1fd9", 7 | "version": 1, 8 | "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", 9 | "bomFormat": "CycloneDX", 10 | "specVersion": "1.5" 11 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/corpus-key-aws.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": { 3 | "$numberInt": "1" 4 | }, 5 | "_id": { 6 | "$binary": { 7 | "base64": "AWSAAAAAAAAAAAAAAAAAAA==", 8 | "subType": "04" 9 | } 10 | }, 11 | "masterKey": { 12 | "region": "us-east-1", 13 | "key": "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0", 14 | "provider": "aws" 15 | }, 16 | "updateDate": { 17 | "$date": { 18 | "$numberLong": "1557827033449" 19 | } 20 | }, 21 | "keyMaterial": { 22 | "$binary": { 23 | "base64": "AQICAHhQNmWG2CzOm1dq3kWLM+iDUZhEqnhJwH9wZVpuZ94A8gEqnsxXlR51T5EbEVezUqqKAAAAwjCBvwYJKoZIhvcNAQcGoIGxMIGuAgEAMIGoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDHa4jo6yp0Z18KgbUgIBEIB74sKxWtV8/YHje5lv5THTl0HIbhSwM6EqRlmBiFFatmEWaeMk4tO4xBX65eq670I5TWPSLMzpp8ncGHMmvHqRajNBnmFtbYxN3E3/WjxmdbOOe+OXpnGJPcGsftc7cB2shRfA4lICPnE26+oVNXT6p0Lo20nY5XC7jyCO", 24 | "subType": "00" 25 | } 26 | }, 27 | "creationDate": { 28 | "$date": { 29 | "$numberLong": "1557827033449" 30 | } 31 | }, 32 | "keyAltNames": ["aws"] 33 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/corpus-key-azure.json: -------------------------------------------------------------------------------- 1 | { 2 | "_id": { 3 | "$binary": { 4 | "base64": "AZUREAAAAAAAAAAAAAAAAA==", 5 | "subType": "04" 6 | } 7 | }, 8 | "keyMaterial": { 9 | "$binary": { 10 | "base64": "n+HWZ0ZSVOYA3cvQgP7inN4JSXfOH85IngmeQxRpQHjCCcqT3IFqEWNlrsVHiz3AELimHhX4HKqOLWMUeSIT6emUDDoQX9BAv8DR1+E1w4nGs/NyEneac78EYFkK3JysrFDOgl2ypCCTKAypkn9CkAx1if4cfgQE93LW4kczcyHdGiH36CIxrCDGv1UzAvERN5Qa47DVwsM6a+hWsF2AAAJVnF0wYLLJU07TuRHdMrrphPWXZsFgyV+lRqJ7DDpReKNO8nMPLV/mHqHBHGPGQiRdb9NoJo8CvokGz4+KE8oLwzKf6V24dtwZmRkrsDV4iOhvROAzz+Euo1ypSkL3mw==", 11 | "subType": "00" 12 | } 13 | }, 14 | "creationDate": { 15 | "$date": { 16 | "$numberLong": "1601573901680" 17 | } 18 | }, 19 | "updateDate": { 20 | "$date": { 21 | "$numberLong": "1601573901680" 22 | } 23 | }, 24 | "status": { 25 | "$numberInt": "0" 26 | }, 27 | "masterKey": { 28 | "provider": "azure", 29 | "keyVaultEndpoint": "key-vault-csfle.vault.azure.net", 30 | "keyName": "key-name-csfle" 31 | }, 32 | "keyAltNames": ["azure"] 33 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/corpus-key-gcp.json: -------------------------------------------------------------------------------- 1 | { 2 | "_id": { 3 | "$binary": { 4 | "base64": "GCPAAAAAAAAAAAAAAAAAAA==", 5 | "subType": "04" 6 | } 7 | }, 8 | "keyMaterial": { 9 | "$binary": { 10 | "base64": "CiQAIgLj0WyktnB4dfYHo5SLZ41K4ASQrjJUaSzl5vvVH0G12G0SiQEAjlV8XPlbnHDEDFbdTO4QIe8ER2/172U1ouLazG0ysDtFFIlSvWX5ZnZUrRMmp/R2aJkzLXEt/zf8Mn4Lfm+itnjgo5R9K4pmPNvvPKNZX5C16lrPT+aA+rd+zXFSmlMg3i5jnxvTdLHhg3G7Q/Uv1ZIJskKt95bzLoe0tUVzRWMYXLIEcohnQg==", 11 | "subType": "00" 12 | } 13 | }, 14 | "creationDate": { 15 | "$date": { 16 | "$numberLong": "1601574333107" 17 | } 18 | }, 19 | "updateDate": { 20 | "$date": { 21 | "$numberLong": "1601574333107" 22 | } 23 | }, 24 | "status": { 25 | "$numberInt": "0" 26 | }, 27 | "masterKey": { 28 | "provider": "gcp", 29 | "projectId": "devprod-drivers", 30 | "location": "global", 31 | "keyRing": "key-ring-csfle", 32 | "keyName": "key-name-csfle" 33 | }, 34 | "keyAltNames": ["gcp"] 35 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/corpus-key-kmip.json: -------------------------------------------------------------------------------- 1 | { 2 | "_id": { 3 | "$binary": { 4 | "base64": "KMIPAAAAAAAAAAAAAAAAAA==", 5 | "subType": "04" 6 | } 7 | }, 8 | "keyMaterial": { 9 | "$binary": { 10 | "base64": "eUYDyB0HuWb+lQgUwO+6qJQyTTDTY2gp9FbemL7ZFo0pvr0x6rm6Ff9OVUTGH6HyMKipaeHdiIJU1dzsLwvqKvi7Beh+U4iaIWX/K0oEg1GOsJc0+Z/in8gNHbGUYLmycHViM3LES3kdt7FdFSUl5rEBHrM71yoNEXImz17QJWMGOuT4x6yoi2pvnaRJwfrI4DjpmnnTrDMac92jgZehbg==", 11 | "subType": "00" 12 | } 13 | }, 14 | "creationDate": { 15 | "$date": { 16 | "$numberLong": "1634220190041" 17 | } 18 | }, 19 | "updateDate": { 20 | "$date": { 21 | "$numberLong": "1634220190041" 22 | } 23 | }, 24 | "status": { 25 | "$numberInt": "0" 26 | }, 27 | "masterKey": { 28 | "provider": "kmip", 29 | "keyId": "1" 30 | }, 31 | "keyAltNames": ["kmip"] 32 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/corpus-key-local.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": { 3 | "$numberInt": "1" 4 | }, 5 | "_id": { 6 | "$binary": { 7 | "base64": "LOCALAAAAAAAAAAAAAAAAA==", 8 | "subType": "04" 9 | } 10 | }, 11 | "masterKey": { 12 | "provider": "local" 13 | }, 14 | "updateDate": { 15 | "$date": { 16 | "$numberLong": "1557827033449" 17 | } 18 | }, 19 | "keyMaterial": { 20 | "$binary": { 21 | "base64": "Ce9HSz/HKKGkIt4uyy+jDuKGA+rLC2cycykMo6vc8jXxqa1UVDYHWq1r+vZKbnnSRBfB981akzRKZCFpC05CTyFqDhXv6OnMjpG97OZEREGIsHEYiJkBW0jJJvfLLgeLsEpBzsro9FztGGXASxyxFRZFhXvHxyiLOKrdWfs7X1O/iK3pEoHMx6uSNSfUOgbebLfIqW7TO++iQS5g1xovXA==", 22 | "subType": "00" 23 | } 24 | }, 25 | "creationDate": { 26 | "$date": { 27 | "$numberLong": "1557827033449" 28 | } 29 | }, 30 | "keyAltNames": [ "local" ] 31 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/encrypted-fields.json: -------------------------------------------------------------------------------- 1 | { 2 | "fields": [ 3 | { 4 | "keyId": { 5 | "$binary": { 6 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 7 | "subType": "04" 8 | } 9 | }, 10 | "path": "encryptedIndexed", 11 | "bsonType": "string", 12 | "queries": { 13 | "queryType": "equality", 14 | "contention": { 15 | "$numberLong": "0" 16 | } 17 | } 18 | }, 19 | { 20 | "keyId": { 21 | "$binary": { 22 | "base64": "q83vqxI0mHYSNBI0VniQEg==", 23 | "subType": "04" 24 | } 25 | }, 26 | "path": "encryptedUnindexed", 27 | "bsonType": "string" 28 | } 29 | ] 30 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/external-key.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": { 3 | "$numberInt": "1" 4 | }, 5 | "_id": { 6 | "$binary": { 7 | "base64": "LOCALAAAAAAAAAAAAAAAAA==", 8 | "subType": "04" 9 | } 10 | }, 11 | "masterKey": { 12 | "provider": "local" 13 | }, 14 | "updateDate": { 15 | "$date": { 16 | "$numberLong": "1557827033449" 17 | } 18 | }, 19 | "keyMaterial": { 20 | "$binary": { 21 | "base64": "Ce9HSz/HKKGkIt4uyy+jDuKGA+rLC2cycykMo6vc8jXxqa1UVDYHWq1r+vZKbnnSRBfB981akzRKZCFpC05CTyFqDhXv6OnMjpG97OZEREGIsHEYiJkBW0jJJvfLLgeLsEpBzsro9FztGGXASxyxFRZFhXvHxyiLOKrdWfs7X1O/iK3pEoHMx6uSNSfUOgbebLfIqW7TO++iQS5g1xovXA==", 22 | "subType": "00" 23 | } 24 | }, 25 | "creationDate": { 26 | "$date": { 27 | "$numberLong": "1557827033449" 28 | } 29 | }, 30 | "keyAltNames": [ "local" ] 31 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/external-schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "bsonType": "object", 3 | "properties": { 4 | "encrypted": { 5 | "encrypt": { 6 | "keyId": [ 7 | { 8 | "$binary": { 9 | "base64": "LOCALAAAAAAAAAAAAAAAAA==", 10 | "subType": "04" 11 | } 12 | } 13 | ], 14 | "bsonType": "string", 15 | "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" 16 | } 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/key1-document.json: -------------------------------------------------------------------------------- 1 | { 2 | "_id": { 3 | "$binary": { 4 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 5 | "subType": "04" 6 | } 7 | }, 8 | "keyMaterial": { 9 | "$binary": { 10 | "base64": "sHe0kz57YW7v8g9VP9sf/+K1ex4JqKc5rf/URX3n3p8XdZ6+15uXPaSayC6adWbNxkFskuMCOifDoTT+rkqMtFkDclOy884RuGGtUysq3X7zkAWYTKi8QAfKkajvVbZl2y23UqgVasdQu3OVBQCrH/xY00nNAs/52e958nVjBuzQkSb1T8pKJAyjZsHJ60+FtnfafDZSTAIBJYn7UWBCwQ==", 11 | "subType": "00" 12 | } 13 | }, 14 | "creationDate": { 15 | "$date": { 16 | "$numberLong": "1648914851981" 17 | } 18 | }, 19 | "updateDate": { 20 | "$date": { 21 | "$numberLong": "1648914851981" 22 | } 23 | }, 24 | "status": { 25 | "$numberInt": "0" 26 | }, 27 | "masterKey": { 28 | "provider": "local" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/limits-key.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": { 3 | "$numberInt": "1" 4 | }, 5 | "_id": { 6 | "$binary": { 7 | "base64": "LOCALAAAAAAAAAAAAAAAAA==", 8 | "subType": "04" 9 | } 10 | }, 11 | "masterKey": { 12 | "provider": "local" 13 | }, 14 | "updateDate": { 15 | "$date": { 16 | "$numberLong": "1557827033449" 17 | } 18 | }, 19 | "keyMaterial": { 20 | "$binary": { 21 | "base64": "Ce9HSz/HKKGkIt4uyy+jDuKGA+rLC2cycykMo6vc8jXxqa1UVDYHWq1r+vZKbnnSRBfB981akzRKZCFpC05CTyFqDhXv6OnMjpG97OZEREGIsHEYiJkBW0jJJvfLLgeLsEpBzsro9FztGGXASxyxFRZFhXvHxyiLOKrdWfs7X1O/iK3pEoHMx6uSNSfUOgbebLfIqW7TO++iQS5g1xovXA==", 22 | "subType": "00" 23 | } 24 | }, 25 | "creationDate": { 26 | "$date": { 27 | "$numberLong": "1557827033449" 28 | } 29 | }, 30 | "keyAltNames": [ "local" ] 31 | } -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/range-encryptedFields-Date.json: -------------------------------------------------------------------------------- 1 | { 2 | "fields": [ 3 | { 4 | "keyId": { 5 | "$binary": { 6 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 7 | "subType": "04" 8 | } 9 | }, 10 | "path": "encryptedDate", 11 | "bsonType": "date", 12 | "queries": { 13 | "queryType": "range", 14 | "contention": { 15 | "$numberLong": "0" 16 | }, 17 | "trimFactor": { 18 | "$numberInt": "1" 19 | }, 20 | "sparsity": { 21 | "$numberLong": "1" 22 | }, 23 | "min": { 24 | "$date": { 25 | "$numberLong": "0" 26 | } 27 | }, 28 | "max": { 29 | "$date": { 30 | "$numberLong": "200" 31 | } 32 | } 33 | } 34 | } 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/range-encryptedFields-DecimalNoPrecision.json: -------------------------------------------------------------------------------- 1 | { 2 | "fields": [ 3 | { 4 | "keyId": { 5 | "$binary": { 6 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 7 | "subType": "04" 8 | } 9 | }, 10 | "path": "encryptedDecimalNoPrecision", 11 | "bsonType": "decimal", 12 | "queries": { 13 | "queryType": "range", 14 | "contention": { 15 | "$numberLong": "0" 16 | }, 17 | "trimFactor": { 18 | "$numberInt": "1" 19 | }, 20 | "sparsity": { 21 | "$numberLong": "1" 22 | } 23 | } 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/range-encryptedFields-DecimalPrecision.json: -------------------------------------------------------------------------------- 1 | { 2 | "fields": [ 3 | { 4 | "keyId": { 5 | "$binary": { 6 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 7 | "subType": "04" 8 | } 9 | }, 10 | "path": "encryptedDecimalPrecision", 11 | "bsonType": "decimal", 12 | "queries": { 13 | "queryType": "range", 14 | "contention": { 15 | "$numberLong": "0" 16 | }, 17 | "trimFactor": { 18 | "$numberInt": "1" 19 | }, 20 | "sparsity": { 21 | "$numberLong": "1" 22 | }, 23 | "min": { 24 | "$numberDecimal": "0.0" 25 | }, 26 | "max": { 27 | "$numberDecimal": "200.0" 28 | }, 29 | "precision": { 30 | "$numberInt": "2" 31 | } 32 | } 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/range-encryptedFields-DoubleNoPrecision.json: -------------------------------------------------------------------------------- 1 | { 2 | "fields": [ 3 | { 4 | "keyId": { 5 | "$binary": { 6 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 7 | "subType": "04" 8 | } 9 | }, 10 | "path": "encryptedDoubleNoPrecision", 11 | "bsonType": "double", 12 | "queries": { 13 | "queryType": "range", 14 | "contention": { 15 | "$numberLong": "0" 16 | }, 17 | "trimFactor": { 18 | "$numberInt": "1" 19 | }, 20 | "sparsity": { 21 | "$numberLong": "1" 22 | } 23 | } 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/range-encryptedFields-DoublePrecision.json: -------------------------------------------------------------------------------- 1 | { 2 | "fields": [ 3 | { 4 | "keyId": { 5 | "$binary": { 6 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 7 | "subType": "04" 8 | } 9 | }, 10 | "path": "encryptedDoublePrecision", 11 | "bsonType": "double", 12 | "queries": { 13 | "queryType": "range", 14 | "contention": { 15 | "$numberLong": "0" 16 | }, 17 | "trimFactor": { 18 | "$numberInt": "1" 19 | }, 20 | "sparsity": { 21 | "$numberLong": "1" 22 | }, 23 | "min": { 24 | "$numberDouble": "0.0" 25 | }, 26 | "max": { 27 | "$numberDouble": "200.0" 28 | }, 29 | "precision": { 30 | "$numberInt": "2" 31 | } 32 | } 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/range-encryptedFields-Int.json: -------------------------------------------------------------------------------- 1 | { 2 | "fields": [ 3 | { 4 | "keyId": { 5 | "$binary": { 6 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 7 | "subType": "04" 8 | } 9 | }, 10 | "path": "encryptedInt", 11 | "bsonType": "int", 12 | "queries": { 13 | "queryType": "range", 14 | "contention": { 15 | "$numberLong": "0" 16 | }, 17 | "trimFactor": { 18 | "$numberInt": "1" 19 | }, 20 | "sparsity": { 21 | "$numberLong": "1" 22 | }, 23 | "min": { 24 | "$numberInt": "0" 25 | }, 26 | "max": { 27 | "$numberInt": "200" 28 | } 29 | } 30 | } 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /testdata/client-side-encryption-prose/range-encryptedFields-Long.json: -------------------------------------------------------------------------------- 1 | { 2 | "fields": [ 3 | { 4 | "keyId": { 5 | "$binary": { 6 | "base64": "EjRWeBI0mHYSNBI0VniQEg==", 7 | "subType": "04" 8 | } 9 | }, 10 | "path": "encryptedLong", 11 | "bsonType": "long", 12 | "queries": { 13 | "queryType": "range", 14 | "contention": { 15 | "$numberLong": "0" 16 | }, 17 | "trimFactor": { 18 | "$numberInt": "1" 19 | }, 20 | "sparsity": { 21 | "$numberLong": "1" 22 | }, 23 | "min": { 24 | "$numberLong": "0" 25 | }, 26 | "max": { 27 | "$numberLong": "200" 28 | } 29 | } 30 | } 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /testdata/extended_bson/deep_bson.json.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb/mongo-go-driver/579a2659ff88b1c612182a97b69efe3b0523a76c/testdata/extended_bson/deep_bson.json.gz -------------------------------------------------------------------------------- /testdata/extended_bson/flat_bson.json.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb/mongo-go-driver/579a2659ff88b1c612182a97b69efe3b0523a76c/testdata/extended_bson/flat_bson.json.gz -------------------------------------------------------------------------------- /testdata/extended_bson/full_bson.json.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb/mongo-go-driver/579a2659ff88b1c612182a97b69efe3b0523a76c/testdata/extended_bson/full_bson.json.gz -------------------------------------------------------------------------------- /testdata/kmip-certs/ca-ec.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIBtjCCAVsCAj+0MAoGCCqGSM49BAMCMGUxCzAJBgNVBAYTAlVTMREwDwYDVQQI 3 | DAhOZXcgWW9yazEWMBQGA1UEBwwNTmV3IFlvcmsgQ2l0eTEQMA4GA1UECgwHTW9u 4 | Z29EQjEMMAoGA1UECwwDREJYMQswCQYDVQQDDAJjYTAgFw0yMjA4MTgwMDM5NTZa 5 | GA8yMDYyMDgwODAwMzk1NlowZTELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE5ldyBZ 6 | b3JrMRYwFAYDVQQHDA1OZXcgWW9yayBDaXR5MRAwDgYDVQQKDAdNb25nb0RCMQww 7 | CgYDVQQLDANEQlgxCzAJBgNVBAMMAmNhMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD 8 | QgAE0YOWpm6I2mES1h6CKMw5j29lWDfk36/S7i2+Rw5e9JvGmDGSepDH03MJlm4l 9 | J9pou6NJrtAfIhMsxvh4oECodTAKBggqhkjOPQQDAgNJADBGAiEAyr7ByfWjA1aG 10 | hJD1zFtU2C/+i59vGY3oYQ3gX6Y7HrICIQDkO5JF9tXeDOL5IPkpjBAp6OjACE6Y 11 | Ns42/ywMFmyWhA== 12 | -----END CERTIFICATE----- 13 | -------------------------------------------------------------------------------- /testdata/kmip-certs/client-ec.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIB/jCCAaSgAwIBAgICYz4wCgYIKoZIzj0EAwIwZTELMAkGA1UEBhMCVVMxETAP 3 | BgNVBAgMCE5ldyBZb3JrMRYwFAYDVQQHDA1OZXcgWW9yayBDaXR5MRAwDgYDVQQK 4 | DAdNb25nb0RCMQwwCgYDVQQLDANEQlgxCzAJBgNVBAMMAmNhMCAXDTIyMDgxODAw 5 | Mzk1NloYDzIwNjIwODA4MDAzOTU2WjBpMQswCQYDVQQGEwJVUzERMA8GA1UECAwI 6 | TmV3IFlvcmsxFjAUBgNVBAcMDU5ldyBZb3JrIENpdHkxEDAOBgNVBAoMB01vbmdv 7 | REIxDDAKBgNVBAsMA0RCWDEPMA0GA1UEAwwGY2xpZW50MFkwEwYHKoZIzj0CAQYI 8 | KoZIzj0DAQcDQgAE3lcl3A0IqcmuNeNhk9u8KZKe/Du5/e2xd3B8MRqROb/MDTFY 9 | JkBatcCNhcSCIjgtFMjZ8Rv2WrrN0fvmEqYpm6M+MDwwCQYDVR0TBAIwADAaBgNV 10 | HREEEzARgglsb2NhbGhvc3SHBH8AAAEwEwYDVR0lBAwwCgYIKwYBBQUHAwIwCgYI 11 | KoZIzj0EAwIDSAAwRQIgbkV6V3MK2nZdjr7LV0PKqfxKCWRyxRACEOH61a6dctsC 12 | IQD6k65C8AXAPOL+cqaZjoEMBpRea4F8gL0jIwzHh+tkAA== 13 | -----END CERTIFICATE----- 14 | -----BEGIN EC PRIVATE KEY----- 15 | MHcCAQEEIOw4V3MEjv/5go8JQGr9Au1sa9yzLzPXVsiZ2OihwN7joAoGCCqGSM49 16 | AwEHoUQDQgAE3lcl3A0IqcmuNeNhk9u8KZKe/Du5/e2xd3B8MRqROb/MDTFYJkBa 17 | tcCNhcSCIjgtFMjZ8Rv2WrrN0fvmEqYpmw== 18 | -----END EC PRIVATE KEY----- 19 | -------------------------------------------------------------------------------- /testdata/kmip-certs/server-ec.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIB/TCCAaSgAwIBAgICNNIwCgYIKoZIzj0EAwIwZTELMAkGA1UEBhMCVVMxETAP 3 | BgNVBAgMCE5ldyBZb3JrMRYwFAYDVQQHDA1OZXcgWW9yayBDaXR5MRAwDgYDVQQK 4 | DAdNb25nb0RCMQwwCgYDVQQLDANEQlgxCzAJBgNVBAMMAmNhMCAXDTIyMDgxODAw 5 | Mzk1NloYDzIwNjIwODA4MDAzOTU2WjBpMQswCQYDVQQGEwJVUzERMA8GA1UECAwI 6 | TmV3IFlvcmsxFjAUBgNVBAcMDU5ldyBZb3JrIENpdHkxEDAOBgNVBAoMB01vbmdv 7 | REIxDDAKBgNVBAsMA0RCWDEPMA0GA1UEAwwGc2VydmVyMFkwEwYHKoZIzj0CAQYI 8 | KoZIzj0DAQcDQgAEgWFZeI/XzPl42qAMa8UZBLoW2IdkIowhz+iu9F5LkAXI388L 9 | qbRE4327RvquPO7Ca5eB9GNs77DEtnfMnVuXQ6M+MDwwCQYDVR0TBAIwADAaBgNV 10 | HREEEzARgglsb2NhbGhvc3SHBH8AAAEwEwYDVR0lBAwwCgYIKwYBBQUHAwEwCgYI 11 | KoZIzj0EAwIDRwAwRAIgHz7k59ubmnFHM+4GQpz0aeQ+FQGadRYe/h31iRye2wMC 12 | IAvirZCoxYBLlZ0NoXH8ncmEQzgkCx9hhv7mWpjNRk/h 13 | -----END CERTIFICATE----- 14 | -----BEGIN EC PRIVATE KEY----- 15 | MHcCAQEEIIRjzdANl/ghc/LgEdyGRc3xo07YHu1qku3GQNGY2OnboAoGCCqGSM49 16 | AwEHoUQDQgAEgWFZeI/XzPl42qAMa8UZBLoW2IdkIowhz+iu9F5LkAXI388LqbRE 17 | 4327RvquPO7Ca5eB9GNs77DEtnfMnVuXQw== 18 | -----END EC PRIVATE KEY----- 19 | -------------------------------------------------------------------------------- /testdata/mongocrypt/collection-info.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "collection", 3 | "name": "test", 4 | "idIndex": { 5 | "ns": "test.test", 6 | "name": "_id_", 7 | "key": { 8 | "_id": { 9 | "$numberInt": "1" 10 | } 11 | }, 12 | "v": { 13 | "$numberInt": "2" 14 | } 15 | }, 16 | "options": { 17 | "validator": { 18 | "$jsonSchema": { 19 | "properties": { 20 | "ssn": { 21 | "encrypt": { 22 | "keyId": { 23 | "$binary": { 24 | "base64": "YWFhYWFhYWFhYWFhYWFhYQ==", 25 | "subType": "04" 26 | } 27 | }, 28 | "type": "string", 29 | "algorithm": "AEAD_AES_CBC_HMAC_SHA512-Deterministic" 30 | } 31 | } 32 | }, 33 | "bsonType": "object" 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /testdata/mongocrypt/command-reply.json: -------------------------------------------------------------------------------- 1 | { 2 | "cursor": { 3 | "firstBatch": [ 4 | { 5 | "_id": 1, 6 | "ssn": "457-55-5462" 7 | } 8 | ], 9 | "id": 0, 10 | "ns": "test.test" 11 | }, 12 | "ok": 1 13 | } 14 | -------------------------------------------------------------------------------- /testdata/mongocrypt/command.json: -------------------------------------------------------------------------------- 1 | { 2 | "find": "test", 3 | "filter": { 4 | "ssn": "457-55-5462" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /testdata/mongocrypt/encrypted-command-reply.json: -------------------------------------------------------------------------------- 1 | { 2 | "cursor" : { 3 | "firstBatch" : [ 4 | { 5 | "_id": 1, 6 | "ssn": { 7 | "$binary": "AWFhYWFhYWFhYWFhYWFhYWECRTOW9yZzNDn5dGwuqsrJQNLtgMEKaujhs9aRWRp+7Yo3JK8N8jC8P0Xjll6C1CwLsE/iP5wjOMhVv1KMMyOCSCrHorXRsb2IKPtzl2lKTqQ=", 8 | "$type": "06" 9 | } 10 | } 11 | ], 12 | "id" : 0, 13 | "ns" : "test.test" 14 | }, 15 | "ok" : 1 16 | } -------------------------------------------------------------------------------- /testdata/mongocrypt/encrypted-command.json: -------------------------------------------------------------------------------- 1 | { 2 | "filter": { 3 | "ssn": { 4 | "$binary": { 5 | "base64": "AWFhYWFhYWFhYWFhYWFhYWECRTOW9yZzNDn5dGwuqsrJQNLtgMEKaujhs9aRWRp+7Yo3JK8N8jC8P0Xjll6C1CwLsE/iP5wjOMhVv1KMMyOCSCrHorXRsb2IKPtzl2lKTqQ=", 6 | "subType": "06" 7 | } 8 | } 9 | }, 10 | "find": "test" 11 | } 12 | -------------------------------------------------------------------------------- /testdata/mongocrypt/encrypted-value.json: -------------------------------------------------------------------------------- 1 | { 2 | "v": { 3 | "$binary": "AWFhYWFhYWFhYWFhYWFhYWECW+zDjR/69eS6VtuMD5+O2lZw6JyiWOw3avI7mnUkdpKzPfvy8F/nlZrgZa2cGmQsb0TmLZuk5trldosnGKD91w==", 4 | "$type": "06" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /testdata/mongocrypt/json-schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": { 3 | "ssn": { 4 | "encrypt": { 5 | "keyId": { 6 | "$binary": "YWFhYWFhYWFhYWFhYWFhYQ==", 7 | "$type": "04" 8 | }, 9 | "type": "string", 10 | "algorithm": "AEAD_AES_CBC_HMAC_SHA512-Deterministic" 11 | } 12 | } 13 | }, 14 | "bsonType": "object" 15 | } -------------------------------------------------------------------------------- /testdata/mongocrypt/key-document.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": { 3 | "$numberInt": "1" 4 | }, 5 | "_id": { 6 | "$binary": { 7 | "base64": "YWFhYWFhYWFhYWFhYWFhYQ==", 8 | "subType": "04" 9 | } 10 | }, 11 | "masterKey": { 12 | "region": "us-east-1", 13 | "key": "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0", 14 | "provider": "aws" 15 | }, 16 | "updateDate": { 17 | "$date": { 18 | "$numberLong": "1557827033449" 19 | } 20 | }, 21 | "keyMaterial": { 22 | "$binary": { 23 | "base64": "AQICAHhQNmWG2CzOm1dq3kWLM+iDUZhEqnhJwH9wZVpuZ94A8gEqnsxXlR51T5EbEVezUqqKAAAAwjCBvwYJKoZIhvcNAQcGoIGxMIGuAgEAMIGoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDHa4jo6yp0Z18KgbUgIBEIB74sKxWtV8/YHje5lv5THTl0HIbhSwM6EqRlmBiFFatmEWaeMk4tO4xBX65eq670I5TWPSLMzpp8ncGHMmvHqRajNBnmFtbYxN3E3/WjxmdbOOe+OXpnGJPcGsftc7cB2shRfA4lICPnE26+oVNXT6p0Lo20nY5XC7jyCO", 24 | "subType": "00" 25 | } 26 | }, 27 | "creationDate": { 28 | "$date": { 29 | "$numberLong": "1557827033449" 30 | } 31 | }, 32 | "keyAltNames": [ 33 | "altKeyName", 34 | "another_altname" 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /testdata/mongocrypt/key-filter-keyAltName.json: -------------------------------------------------------------------------------- 1 | { 2 | "$or": [ 3 | { 4 | "_id": { 5 | "$in": [] 6 | } 7 | }, 8 | { 9 | "keyAltNames": { 10 | "$in": ["altKeyName"] 11 | } 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /testdata/mongocrypt/key-filter.json: -------------------------------------------------------------------------------- 1 | { 2 | "$or": [ 3 | { 4 | "_id": { 5 | "$in": [ 6 | { 7 | "$binary": "YWFhYWFhYWFhYWFhYWFhYQ==", 8 | "$type": "04" 9 | } 10 | ] 11 | } 12 | }, 13 | { 14 | "keyAltNames": { 15 | "$in": [] 16 | } 17 | } 18 | ] 19 | } -------------------------------------------------------------------------------- /testdata/mongocrypt/kms-reply.txt: -------------------------------------------------------------------------------- 1 | HTTP/1.1 200 OK 2 | x-amzn-RequestId: deeb35e5-4ecb-4bf1-9af5-84a54ff0af0e 3 | Content-Type: application/x-amz-json-1.1 4 | Content-Length: 233 5 | 6 | {"KeyId": "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0", "Plaintext": "TqhXy3tKckECjy4/ZNykMWG8amBF46isVPzeOgeusKrwheBmYaU8TMG5AHR/NeUDKukqo8hBGgogiQOVpLPkqBQHD8YkLsNbDmHoGOill5QAHnniF/Lz405bGucB5TfR"} 7 | -------------------------------------------------------------------------------- /testdata/mongocrypt/list-collections-filter.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test" 3 | } -------------------------------------------------------------------------------- /testdata/mongocrypt/local-key-document.json: -------------------------------------------------------------------------------- 1 | { 2 | "_id": { 3 | "$binary": { 4 | "base64": "YWFhYWFhYWFhYWFhYWFhYQ==", 5 | "subType": "04" 6 | } 7 | }, 8 | "keyMaterial": { 9 | "$binary": { 10 | "base64": "ACR7Hm33dDOAAD7l2ubZhSpSUWK8BkALUY+qW3UgBAEcTV8sBwZnaAWnzDsmrX55dgmYHWfynDlJogC/e33u6pbhyXvFTs5ow9OLCuCWBJ39T/Ivm3kMaZJybkejY0V+uc4UEdHvVVz/SbitVnzs2WXdMGmo1/HmDRrxGYZjewFslquv8wtUHF5pyB+QDlQBd/al9M444/8bJZFbMSmtIg==", 11 | "subType": "00" 12 | } 13 | }, 14 | "creationDate": { 15 | "$date": "2023-08-21T14:28:20.875Z" 16 | }, 17 | "updateDate": { 18 | "$date": "2023-08-21T14:28:20.875Z" 19 | }, 20 | "status": 0, 21 | "masterKey": { 22 | "provider": "local" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /testdata/mongocrypt/mongocryptd-command-local.json: -------------------------------------------------------------------------------- 1 | { 2 | "find": "test", 3 | "filter": { 4 | "ssn": "457-55-5462" 5 | }, 6 | "jsonSchema": { 7 | "properties": { 8 | "ssn": { 9 | "encrypt": { 10 | "keyId": { 11 | "$binary": "YWFhYWFhYWFhYWFhYWFhYQ==", 12 | "$type": "04" 13 | }, 14 | "type": "string", 15 | "algorithm": "AEAD_AES_CBC_HMAC_SHA512-Deterministic" 16 | } 17 | } 18 | }, 19 | "bsonType": "object" 20 | }, 21 | "isRemoteSchema": false 22 | } -------------------------------------------------------------------------------- /testdata/mongocrypt/mongocryptd-command-remote.json: -------------------------------------------------------------------------------- 1 | { 2 | "find": "test", 3 | "filter": { 4 | "ssn": "457-55-5462" 5 | }, 6 | "jsonSchema": { 7 | "properties": { 8 | "ssn": { 9 | "encrypt": { 10 | "keyId": { 11 | "$binary": "YWFhYWFhYWFhYWFhYWFhYQ==", 12 | "$type": "04" 13 | }, 14 | "type": "string", 15 | "algorithm": "AEAD_AES_CBC_HMAC_SHA512-Deterministic" 16 | } 17 | } 18 | }, 19 | "bsonType": "object" 20 | }, 21 | "isRemoteSchema": true 22 | } -------------------------------------------------------------------------------- /testdata/mongocrypt/mongocryptd-reply.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaRequiresEncryption": true, 3 | "ok": { 4 | "$numberInt": "1" 5 | }, 6 | "result": { 7 | "filter": { 8 | "ssn": { 9 | "$binary": { 10 | "base64": "ADgAAAAQYQABAAAABWtpABAAAAAEYWFhYWFhYWFhYWFhYWFhYQJ2AAwAAAA0NTctNTUtNTQ2MgAA", 11 | "subType": "06" 12 | } 13 | } 14 | }, 15 | "find": "test" 16 | }, 17 | "hasEncryptedPlaceholders": true 18 | } -------------------------------------------------------------------------------- /version/version.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // DO NOT EDIT. Code generated by Github action 8 | // "mongodb-labs/drivers-github-tools/golang/pre-publish". 9 | 10 | // Package version defines the Go Driver version. 11 | package version 12 | 13 | // Driver is the current version of the driver. 14 | var Driver = "2.2.0" 15 | -------------------------------------------------------------------------------- /x/README.md: -------------------------------------------------------------------------------- 1 | # MongoDB Go Driver Experimental Packages 2 | 3 | **WARNING: THESE PACKAGES ARE EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED 4 | WITHOUT NOTICE.** 5 | 6 | This directory contains packages intended only for internal use. They are made 7 | available to facilitate use cases that require access to internal MongoDB driver 8 | functionality and state. The APIs of these packages are not stable and there is 9 | no backward compatibility guarantee. Use with extreme caution! 10 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/conversation.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package auth 8 | 9 | import ( 10 | "context" 11 | 12 | "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" 13 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver" 14 | ) 15 | 16 | // SpeculativeConversation represents an authentication conversation that can be merged with the initial connection 17 | // handshake. 18 | // 19 | // FirstMessage method returns the first message to be sent to the server. This message will be included in the initial 20 | // hello command. 21 | // 22 | // Finish takes the server response to the initial message and conducts the remainder of the conversation to 23 | // authenticate the provided connection. 24 | type SpeculativeConversation interface { 25 | FirstMessage() (bsoncore.Document, error) 26 | Finish(ctx context.Context, cfg *driver.AuthConfig, firstResponse bsoncore.Document) error 27 | } 28 | 29 | // SpeculativeAuthenticator represents an authenticator that supports speculative authentication. 30 | type SpeculativeAuthenticator interface { 31 | CreateSpeculativeConversation() (SpeculativeConversation, error) 32 | } 33 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/cred.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package auth 8 | 9 | import ( 10 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver" 11 | ) 12 | 13 | // Cred is the type of user credential 14 | type Cred = driver.Cred 15 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/creds/azurecreds.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2023-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package creds 8 | 9 | import ( 10 | "context" 11 | "net/http" 12 | "time" 13 | 14 | "go.mongodb.org/mongo-driver/v2/internal/aws/credentials" 15 | "go.mongodb.org/mongo-driver/v2/internal/credproviders" 16 | "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" 17 | ) 18 | 19 | // AzureCredentialProvider provides Azure credentials. 20 | type AzureCredentialProvider struct { 21 | cred *credentials.Credentials 22 | } 23 | 24 | // NewAzureCredentialProvider generates new AzureCredentialProvider 25 | func NewAzureCredentialProvider(httpClient *http.Client) AzureCredentialProvider { 26 | return AzureCredentialProvider{ 27 | credentials.NewCredentials(credproviders.NewAzureProvider(httpClient, 1*time.Minute)), 28 | } 29 | } 30 | 31 | // GetCredentialsDoc generates Azure credentials. 32 | func (p AzureCredentialProvider) GetCredentialsDoc(ctx context.Context) (bsoncore.Document, error) { 33 | creds, err := p.cred.GetWithContext(ctx) 34 | if err != nil { 35 | return nil, err 36 | } 37 | builder := bsoncore.NewDocumentBuilder(). 38 | AppendString("accessToken", creds.SessionToken) 39 | return builder.Build(), nil 40 | } 41 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/creds/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package creds is intended for internal use only. It is made available to 8 | // facilitate use cases that require access to internal MongoDB driver 9 | // functionality and state. The API of this package is not stable and there is 10 | // no backward compatibility guarantee. 11 | // 12 | // WARNING: THIS PACKAGE IS EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED WITHOUT 13 | // NOTICE! USE WITH EXTREME CAUTION! 14 | package creds 15 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package auth is intended for internal use only. It is made available to 8 | // facilitate use cases that require access to internal MongoDB driver 9 | // functionality and state. The API of this package is not stable and there is 10 | // no backward compatibility guarantee. 11 | // 12 | // WARNING: THIS PACKAGE IS EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED WITHOUT 13 | // NOTICE! USE WITH EXTREME CAUTION! 14 | package auth 15 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/gssapi_not_enabled.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build !gssapi 8 | // +build !gssapi 9 | 10 | package auth 11 | 12 | import "net/http" 13 | 14 | // GSSAPI is the mechanism name for GSSAPI. 15 | const GSSAPI = "GSSAPI" 16 | 17 | func newGSSAPIAuthenticator(*Cred, *http.Client) (Authenticator, error) { 18 | return nil, newAuthError("GSSAPI support not enabled during build (-tags gssapi)", nil) 19 | } 20 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/gssapi_not_supported.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build gssapi && !windows && !linux && !darwin 8 | // +build gssapi,!windows,!linux,!darwin 9 | 10 | package auth 11 | 12 | import ( 13 | "fmt" 14 | "net/http" 15 | "runtime" 16 | ) 17 | 18 | // GSSAPI is the mechanism name for GSSAPI. 19 | const GSSAPI = "GSSAPI" 20 | 21 | func newGSSAPIAuthenticator(*Cred, *http.Client) (Authenticator, error) { 22 | return nil, newAuthError(fmt.Sprintf("GSSAPI is not supported on %s", runtime.GOOS), nil) 23 | } 24 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/gssapi_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build gssapi 8 | // +build gssapi 9 | 10 | package auth 11 | 12 | import ( 13 | "context" 14 | "testing" 15 | 16 | "go.mongodb.org/mongo-driver/v2/mongo/address" 17 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver" 18 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver/description" 19 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver/drivertest" 20 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver/mnet" 21 | ) 22 | 23 | func TestGSSAPIAuthenticator(t *testing.T) { 24 | t.Run("PropsError", func(t *testing.T) { 25 | // Cannot specify both CANONICALIZE_HOST_NAME and SERVICE_HOST 26 | 27 | authenticator := &GSSAPIAuthenticator{ 28 | Username: "foo", 29 | Password: "bar", 30 | PasswordSet: true, 31 | Props: map[string]string{ 32 | "CANONICALIZE_HOST_NAME": "true", 33 | "SERVICE_HOST": "localhost", 34 | }, 35 | } 36 | desc := description.Server{ 37 | WireVersion: &description.VersionRange{ 38 | Max: 6, 39 | }, 40 | Addr: address.Address("foo:27017"), 41 | } 42 | chanconn := &drivertest.ChannelConn{ 43 | Desc: desc, 44 | } 45 | 46 | mnetconn := mnet.NewConnection(chanconn) 47 | 48 | err := authenticator.Auth(context.Background(), &driver.AuthConfig{Connection: mnetconn}) 49 | if err == nil { 50 | t.Fatalf("expected err, got nil") 51 | } 52 | }) 53 | 54 | } 55 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/internal/gssapi/gss_wrapper.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //+build gssapi 8 | //+build linux darwin 9 | #ifndef GSS_WRAPPER_H 10 | #define GSS_WRAPPER_H 11 | 12 | #include 13 | #ifdef GOOS_linux 14 | #include 15 | #include 16 | #endif 17 | #ifdef GOOS_darwin 18 | #include 19 | #endif 20 | 21 | #define GSSAPI_OK 0 22 | #define GSSAPI_CONTINUE 1 23 | #define GSSAPI_ERROR 2 24 | 25 | typedef struct { 26 | gss_name_t spn; 27 | gss_cred_id_t cred; 28 | gss_ctx_id_t ctx; 29 | 30 | OM_uint32 maj_stat; 31 | OM_uint32 min_stat; 32 | } gssapi_client_state; 33 | 34 | int gssapi_error_desc( 35 | OM_uint32 maj_stat, 36 | OM_uint32 min_stat, 37 | char **desc 38 | ); 39 | 40 | int gssapi_client_init( 41 | gssapi_client_state *client, 42 | char* spn, 43 | char* username, 44 | char* password 45 | ); 46 | 47 | int gssapi_client_username( 48 | gssapi_client_state *client, 49 | char** username 50 | ); 51 | 52 | int gssapi_client_negotiate( 53 | gssapi_client_state *client, 54 | void* input, 55 | size_t input_length, 56 | void** output, 57 | size_t* output_length 58 | ); 59 | 60 | int gssapi_client_wrap_msg( 61 | gssapi_client_state *client, 62 | void* input, 63 | size_t input_length, 64 | void** output, 65 | size_t* output_length 66 | ); 67 | 68 | int gssapi_client_destroy( 69 | gssapi_client_state *client 70 | ); 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/internal/gssapi/sspi_wrapper.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //+build gssapi,windows 8 | 9 | #ifndef SSPI_WRAPPER_H 10 | #define SSPI_WRAPPER_H 11 | 12 | #define SECURITY_WIN32 1 /* Required for SSPI */ 13 | 14 | #include 15 | #include 16 | 17 | #define SSPI_OK 0 18 | #define SSPI_CONTINUE 1 19 | #define SSPI_ERROR 2 20 | 21 | typedef struct { 22 | CredHandle cred; 23 | CtxtHandle ctx; 24 | 25 | int has_ctx; 26 | 27 | SECURITY_STATUS status; 28 | } sspi_client_state; 29 | 30 | int sspi_init(); 31 | 32 | int sspi_client_init( 33 | sspi_client_state *client, 34 | char* username, 35 | char* password 36 | ); 37 | 38 | int sspi_client_username( 39 | sspi_client_state *client, 40 | char** username 41 | ); 42 | 43 | int sspi_client_negotiate( 44 | sspi_client_state *client, 45 | char* spn, 46 | PVOID input, 47 | ULONG input_length, 48 | PVOID* output, 49 | ULONG* output_length 50 | ); 51 | 52 | int sspi_client_wrap_msg( 53 | sspi_client_state *client, 54 | PVOID input, 55 | ULONG input_length, 56 | PVOID* output, 57 | ULONG* output_length 58 | ); 59 | 60 | int sspi_client_destroy( 61 | sspi_client_state *client 62 | ); 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/mongodbaws_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package auth 8 | 9 | import ( 10 | "errors" 11 | "testing" 12 | 13 | "go.mongodb.org/mongo-driver/v2/internal/assert" 14 | ) 15 | 16 | func TestGetRegion(t *testing.T) { 17 | longHost := make([]rune, 256) 18 | emptyErr := errors.New("invalid STS host: empty") 19 | tooLongErr := errors.New("invalid STS host: too large") 20 | emptyPartErr := errors.New("invalid STS host: empty part") 21 | testCases := []struct { 22 | name string 23 | host string 24 | err error 25 | region string 26 | }{ 27 | {"success default", "sts.amazonaws.com", nil, "us-east-1"}, 28 | {"success parse", "first.second", nil, "second"}, 29 | {"success no region", "first", nil, "us-east-1"}, 30 | {"error host too long", string(longHost), tooLongErr, ""}, 31 | {"error host empty", "", emptyErr, ""}, 32 | {"error empty middle part", "abc..def", emptyPartErr, ""}, 33 | {"error empty part", "first.", emptyPartErr, ""}, 34 | } 35 | for _, tc := range testCases { 36 | t.Run(tc.name, func(t *testing.T) { 37 | reg, err := getRegion(tc.host) 38 | if tc.err == nil { 39 | assert.Nil(t, err, "error getting region: %v", err) 40 | assert.Equal(t, tc.region, reg, "expected %v, got %v", tc.region, reg) 41 | return 42 | } 43 | assert.NotNil(t, err, "expected error, got nil") 44 | assert.Equal(t, err, tc.err, "expected error: %v, got: %v", tc.err, err) 45 | }) 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/oidc_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package auth 8 | 9 | import ( 10 | "regexp" 11 | "testing" 12 | 13 | "go.mongodb.org/mongo-driver/v2/internal/assert" 14 | ) 15 | 16 | func TestCreatePatternsForGlobs(t *testing.T) { 17 | t.Run("transform allowedHosts patterns", func(t *testing.T) { 18 | 19 | hosts := []string{ 20 | "*.mongodb.net", 21 | "*.mongodb-qa.net", 22 | "*.mongodb-dev.net", 23 | "*.mongodbgov.net", 24 | "localhost", 25 | "127.0.0.1", 26 | "::1", 27 | } 28 | 29 | check, err := createPatternsForGlobs(hosts) 30 | assert.NoError(t, err) 31 | assert.Equal(t, 32 | []*regexp.Regexp{ 33 | regexp.MustCompile(`^.*[.]mongodb[.]net(:\d+)?$`), 34 | regexp.MustCompile(`^.*[.]mongodb-qa[.]net(:\d+)?$`), 35 | regexp.MustCompile(`^.*[.]mongodb-dev[.]net(:\d+)?$`), 36 | regexp.MustCompile(`^.*[.]mongodbgov[.]net(:\d+)?$`), 37 | regexp.MustCompile(`^localhost(:\d+)?$`), 38 | regexp.MustCompile(`^127[.]0[.]0[.]1(:\d+)?$`), 39 | regexp.MustCompile(`^::1(:\d+)?$`), 40 | }, 41 | check, 42 | ) 43 | }) 44 | } 45 | -------------------------------------------------------------------------------- /x/mongo/driver/auth/util.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package auth 8 | 9 | import ( 10 | "fmt" 11 | "io" 12 | 13 | // Ignore gosec warning "Blocklisted import crypto/md5: weak cryptographic primitive". We need 14 | // to use MD5 here to implement the SCRAM specification. 15 | /* #nosec G501 */ 16 | "crypto/md5" 17 | ) 18 | 19 | const defaultAuthDB = "admin" 20 | 21 | func mongoPasswordDigest(username, password string) string { 22 | // Ignore gosec warning "Use of weak cryptographic primitive". We need to use MD5 here to 23 | // implement the SCRAM specification. 24 | /* #nosec G401 */ 25 | h := md5.New() 26 | _, _ = io.WriteString(h, username) 27 | _, _ = io.WriteString(h, ":mongo:") 28 | _, _ = io.WriteString(h, password) 29 | return fmt.Sprintf("%x", h.Sum(nil)) 30 | } 31 | -------------------------------------------------------------------------------- /x/mongo/driver/drivertest/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package drivertest is intended for internal use only. It is made available to 8 | // facilitate use cases that require access to internal MongoDB driver 9 | // functionality and state. The API of this package is not stable and there is 10 | // no backward compatibility guarantee. 11 | // 12 | // WARNING: THIS PACKAGE IS EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED WITHOUT 13 | // NOTICE! USE WITH EXTREME CAUTION! 14 | package drivertest 15 | -------------------------------------------------------------------------------- /x/mongo/driver/integration/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package integration is intended for internal use only. It is made available 8 | // to facilitate use cases that require access to internal MongoDB driver 9 | // functionality and state. The API of this package is not stable and there is 10 | // no backward compatibility guarantee. 11 | // 12 | // WARNING: THIS PACKAGE IS EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED WITHOUT 13 | // NOTICE! USE WITH EXTREME CAUTION! 14 | package integration 15 | -------------------------------------------------------------------------------- /x/mongo/driver/integration/integration.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package integration 8 | -------------------------------------------------------------------------------- /x/mongo/driver/legacy.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package driver 8 | 9 | // LegacyOperationKind indicates if an operation is a legacy find, getMore, or killCursors. This is used 10 | // in Operation.Execute, which will create legacy OP_QUERY, OP_GET_MORE, or OP_KILL_CURSORS instead 11 | // of sending them as a command. 12 | type LegacyOperationKind uint 13 | 14 | // These constants represent the three different kinds of legacy operations. 15 | const ( 16 | LegacyNone LegacyOperationKind = iota 17 | LegacyFind 18 | LegacyGetMore 19 | LegacyKillCursors 20 | LegacyListCollections 21 | LegacyListIndexes 22 | LegacyHandshake 23 | ) 24 | -------------------------------------------------------------------------------- /x/mongo/driver/mongocrypt/binary.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build cse 8 | // +build cse 9 | 10 | package mongocrypt 11 | 12 | /* 13 | #include 14 | #include 15 | */ 16 | import "C" 17 | import ( 18 | "unsafe" 19 | ) 20 | 21 | // binary is a wrapper type around a mongocrypt_binary_t* 22 | type binary struct { 23 | p *C.uint8_t 24 | wrapped *C.mongocrypt_binary_t 25 | } 26 | 27 | // newBinary creates an empty binary instance. 28 | func newBinary() *binary { 29 | return &binary{ 30 | wrapped: C.mongocrypt_binary_new(), 31 | } 32 | } 33 | 34 | // newBinaryFromBytes creates a binary instance from a byte buffer. 35 | func newBinaryFromBytes(data []byte) *binary { 36 | if len(data) == 0 { 37 | return newBinary() 38 | } 39 | 40 | // TODO: Consider using runtime.Pinner to replace the C.CBytes after using go1.21.0. 41 | addr := (*C.uint8_t)(C.CBytes(data)) // uint8_t* 42 | dataLen := C.uint32_t(len(data)) // uint32_t 43 | return &binary{ 44 | p: addr, 45 | wrapped: C.mongocrypt_binary_new_from_data(addr, dataLen), 46 | } 47 | } 48 | 49 | // toBytes converts the given binary instance to []byte. 50 | func (b *binary) toBytes() []byte { 51 | dataPtr := C.mongocrypt_binary_data(b.wrapped) // C.uint8_t* 52 | dataLen := C.mongocrypt_binary_len(b.wrapped) // C.uint32_t 53 | 54 | return C.GoBytes(unsafe.Pointer(dataPtr), C.int(dataLen)) 55 | } 56 | 57 | // close cleans up any resources associated with the given binary instance. 58 | func (b *binary) close() { 59 | if b.p != nil { 60 | C.free(unsafe.Pointer(b.p)) 61 | } 62 | C.mongocrypt_binary_destroy(b.wrapped) 63 | } 64 | -------------------------------------------------------------------------------- /x/mongo/driver/mongocrypt/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build cse 8 | // +build cse 9 | 10 | package mongocrypt 11 | 12 | // #include 13 | import "C" 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | // Error represents an error from an operation on a MongoCrypt instance. 19 | type Error struct { 20 | Code int32 21 | Message string 22 | } 23 | 24 | // Error implements the error interface. 25 | func (e Error) Error() string { 26 | return fmt.Sprintf("mongocrypt error %d: %v", e.Code, e.Message) 27 | } 28 | 29 | // errorFromStatus builds a Error from a mongocrypt_status_t object. 30 | func errorFromStatus(status *C.mongocrypt_status_t) error { 31 | cCode := C.mongocrypt_status_code(status) // uint32_t 32 | // mongocrypt_status_message takes uint32_t* as its second param to store the length of the returned string. 33 | // pass nil because the length is handled by C.GoString 34 | cMsg := C.mongocrypt_status_message(status, nil) // const char* 35 | var msg string 36 | if cMsg != nil { 37 | msg = C.GoString(cMsg) 38 | } 39 | 40 | return Error{ 41 | Code: int32(cCode), 42 | Message: msg, 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /x/mongo/driver/mongocrypt/errors_not_enabled.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build !cse 8 | // +build !cse 9 | 10 | package mongocrypt 11 | 12 | // Error represents an error from an operation on a MongoCrypt instance. 13 | type Error struct { 14 | Code int32 15 | Message string 16 | } 17 | 18 | // Error implements the error interface 19 | func (Error) Error() string { 20 | panic(cseNotSupportedMsg) 21 | } 22 | -------------------------------------------------------------------------------- /x/mongo/driver/mongocrypt/mongocrypt_kms_context_not_enabled.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build !cse 8 | // +build !cse 9 | 10 | package mongocrypt 11 | 12 | // KmsContext represents a mongocrypt_kms_ctx_t handle. 13 | type KmsContext struct{} 14 | 15 | // HostName gets the host name of the KMS. 16 | func (kc *KmsContext) HostName() (string, error) { 17 | panic(cseNotSupportedMsg) 18 | } 19 | 20 | // Message returns the message to send to the KMS. 21 | func (kc *KmsContext) Message() ([]byte, error) { 22 | panic(cseNotSupportedMsg) 23 | } 24 | 25 | // KMSProvider gets the KMS provider of the KMS context. 26 | func (kc *KmsContext) KMSProvider() string { 27 | panic(cseNotSupportedMsg) 28 | } 29 | 30 | // BytesNeeded returns the number of bytes that should be received from the KMS. 31 | // After sending the message to the KMS, this message should be called in a loop until the number returned is 0. 32 | func (kc *KmsContext) BytesNeeded() int32 { 33 | panic(cseNotSupportedMsg) 34 | } 35 | 36 | // FeedResponse feeds the bytes received from the KMS to mongocrypt. 37 | func (kc *KmsContext) FeedResponse([]byte) error { 38 | panic(cseNotSupportedMsg) 39 | } 40 | 41 | // RequestError returns the source of the network error for KMS requests. 42 | func (kc *KmsContext) RequestError() error { 43 | panic(cseNotSupportedMsg) 44 | } 45 | -------------------------------------------------------------------------------- /x/mongo/driver/mongocrypt/options/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package options is intended for internal use only. It is made available to 8 | // facilitate use cases that require access to internal MongoDB driver 9 | // functionality and state. The API of this package is not stable and there is 10 | // no backward compatibility guarantee. 11 | // 12 | // WARNING: THIS PACKAGE IS EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED WITHOUT 13 | // NOTICE! USE WITH EXTREME CAUTION! 14 | package options 15 | -------------------------------------------------------------------------------- /x/mongo/driver/mongocrypt/state.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package mongocrypt 8 | 9 | // State represents a state that a MongocryptContext can be in. 10 | type State int 11 | 12 | // These constants are valid values for the State type. 13 | // The values must match the values defined in the mongocrypt_ctx_state_t enum in libmongocrypt. 14 | const ( 15 | StateError State = 0 16 | NeedMongoCollInfo State = 1 17 | NeedMongoMarkings State = 2 18 | NeedMongoKeys State = 3 19 | NeedKms State = 4 20 | Ready State = 5 21 | Done State = 6 22 | NeedKmsCredentials State = 7 23 | ) 24 | 25 | // String implements the Stringer interface. 26 | func (s State) String() string { 27 | switch s { 28 | case StateError: 29 | return "Error" 30 | case NeedMongoCollInfo: 31 | return "NeedMongoCollInfo" 32 | case NeedMongoMarkings: 33 | return "NeedMongoMarkings" 34 | case NeedMongoKeys: 35 | return "NeedMongoKeys" 36 | case NeedKms: 37 | return "NeedKms" 38 | case Ready: 39 | return "Ready" 40 | case Done: 41 | return "Done" 42 | case NeedKmsCredentials: 43 | return "NeedKmsCredentials" 44 | default: 45 | return "Unknown State" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /x/mongo/driver/ocsp/options.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package ocsp 8 | 9 | import "net/http" 10 | 11 | // VerifyOptions specifies options to configure OCSP verification. 12 | type VerifyOptions struct { 13 | Cache Cache 14 | DisableEndpointChecking bool 15 | HTTPClient *http.Client 16 | } 17 | -------------------------------------------------------------------------------- /x/mongo/driver/operation/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package operation is intended for internal use only. It is made available to 8 | // facilitate use cases that require access to internal MongoDB driver 9 | // functionality and state. The API of this package is not stable and there is 10 | // no backward compatibility guarantee. 11 | // 12 | // WARNING: THIS PACKAGE IS EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED WITHOUT 13 | // NOTICE! USE WITH EXTREME CAUTION! 14 | package operation 15 | -------------------------------------------------------------------------------- /x/mongo/driver/operation/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package operation 8 | 9 | import "errors" 10 | 11 | var ( 12 | errUnacknowledgedHint = errors.New("the 'hint' command parameter cannot be used with unacknowledged writes") 13 | ) 14 | -------------------------------------------------------------------------------- /x/mongo/driver/operation_exhaust.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package driver 8 | 9 | import ( 10 | "context" 11 | "errors" 12 | 13 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver/mnet" 14 | ) 15 | 16 | // ExecuteExhaust reads a response from the provided StreamerConnection. This will error if the connection's 17 | // CurrentlyStreaming function returns false. 18 | func (op Operation) ExecuteExhaust(ctx context.Context, conn *mnet.Connection) error { 19 | if !conn.CurrentlyStreaming() { 20 | return errors.New("exhaust read must be done with a connection that is currently streaming") 21 | } 22 | 23 | res, err := op.readWireMessage(ctx, conn) 24 | if err != nil { 25 | return err 26 | } 27 | if op.ProcessResponseFn != nil { 28 | // Server, ConnectionDescription, and CurrentIndex are unused in this mode. 29 | info := ResponseInfo{ 30 | Connection: conn, 31 | } 32 | if err = op.ProcessResponseFn(ctx, res, info); err != nil { 33 | return err 34 | } 35 | } 36 | 37 | return nil 38 | } 39 | -------------------------------------------------------------------------------- /x/mongo/driver/serverapioptions.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package driver 8 | 9 | // TestServerAPIVersion is the most recent, stable variant of options.ServerAPIVersion. 10 | // Only to be used in testing. 11 | const TestServerAPIVersion = "1" 12 | 13 | // ServerAPIOptions represents arguments used to configure the API version sent 14 | // to the server when running commands. 15 | type ServerAPIOptions struct { 16 | ServerAPIVersion string 17 | Strict *bool 18 | DeprecationErrors *bool 19 | } 20 | 21 | // NewServerAPIOptions creates a new ServerAPIOptions configured with the provided serverAPIVersion. 22 | func NewServerAPIOptions(serverAPIVersion string) *ServerAPIOptions { 23 | return &ServerAPIOptions{ServerAPIVersion: serverAPIVersion} 24 | } 25 | 26 | // SetStrict specifies whether the server should return errors for features that are not part of the API version. 27 | func (s *ServerAPIOptions) SetStrict(strict bool) *ServerAPIOptions { 28 | s.Strict = &strict 29 | return s 30 | } 31 | 32 | // SetDeprecationErrors specifies whether the server should return errors for deprecated features. 33 | func (s *ServerAPIOptions) SetDeprecationErrors(deprecationErrors bool) *ServerAPIOptions { 34 | s.DeprecationErrors = &deprecationErrors 35 | return s 36 | } 37 | -------------------------------------------------------------------------------- /x/mongo/driver/session/cluster_clock.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package session 8 | 9 | import ( 10 | "sync" 11 | 12 | "go.mongodb.org/mongo-driver/v2/bson" 13 | ) 14 | 15 | // ClusterClock represents a logical clock for keeping track of cluster time. 16 | type ClusterClock struct { 17 | clusterTime bson.Raw 18 | lock sync.Mutex 19 | } 20 | 21 | // GetClusterTime returns the cluster's current time. 22 | func (cc *ClusterClock) GetClusterTime() bson.Raw { 23 | var ct bson.Raw 24 | cc.lock.Lock() 25 | ct = cc.clusterTime 26 | cc.lock.Unlock() 27 | 28 | return ct 29 | } 30 | 31 | // AdvanceClusterTime updates the cluster's current time. 32 | func (cc *ClusterClock) AdvanceClusterTime(clusterTime bson.Raw) { 33 | cc.lock.Lock() 34 | cc.clusterTime = MaxClusterTime(cc.clusterTime, clusterTime) 35 | cc.lock.Unlock() 36 | } 37 | -------------------------------------------------------------------------------- /x/mongo/driver/session/cluster_clock_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package session 8 | 9 | import ( 10 | "bytes" 11 | "testing" 12 | 13 | "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" 14 | ) 15 | 16 | func TestClusterClock(t *testing.T) { 17 | var clusterTime1 = bsoncore.BuildDocument(nil, bsoncore.AppendDocumentElement(nil, "$clusterTime", bsoncore.BuildDocument(nil, bsoncore.AppendTimestampElement(nil, "clusterTime", 10, 5)))) 18 | var clusterTime2 = bsoncore.BuildDocument(nil, bsoncore.AppendDocumentElement(nil, "$clusterTime", bsoncore.BuildDocument(nil, bsoncore.AppendTimestampElement(nil, "clusterTime", 5, 5)))) 19 | var clusterTime3 = bsoncore.BuildDocument(nil, bsoncore.AppendDocumentElement(nil, "$clusterTime", bsoncore.BuildDocument(nil, bsoncore.AppendTimestampElement(nil, "clusterTime", 5, 0)))) 20 | 21 | t.Run("ClusterTime", func(t *testing.T) { 22 | clock := ClusterClock{} 23 | clock.AdvanceClusterTime(clusterTime3) 24 | done := make(chan struct{}) 25 | go func() { 26 | clock.AdvanceClusterTime(clusterTime1) 27 | done <- struct{}{} 28 | }() 29 | clock.AdvanceClusterTime(clusterTime2) 30 | 31 | <-done 32 | if !bytes.Equal(clock.GetClusterTime(), clusterTime1) { 33 | t.Errorf("Expected cluster time %v, received %v", clusterTime1, clock.GetClusterTime()) 34 | } 35 | }) 36 | } 37 | -------------------------------------------------------------------------------- /x/mongo/driver/session/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | // Package session is intended for internal use only. It is made available to 8 | // facilitate use cases that require access to internal MongoDB driver 9 | // functionality and state. The API of this package is not stable and there is 10 | // no backward compatibility guarantee. 11 | // 12 | // WARNING: THIS PACKAGE IS EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED WITHOUT 13 | // NOTICE! USE WITH EXTREME CAUTION! 14 | package session 15 | -------------------------------------------------------------------------------- /x/mongo/driver/session/options.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package session 8 | 9 | import ( 10 | "go.mongodb.org/mongo-driver/v2/mongo/readconcern" 11 | "go.mongodb.org/mongo-driver/v2/mongo/readpref" 12 | "go.mongodb.org/mongo-driver/v2/mongo/writeconcern" 13 | ) 14 | 15 | // ClientOptions represents all possible options for creating a client session. 16 | type ClientOptions struct { 17 | CausalConsistency *bool 18 | DefaultReadConcern *readconcern.ReadConcern 19 | DefaultWriteConcern *writeconcern.WriteConcern 20 | DefaultReadPreference *readpref.ReadPref 21 | Snapshot *bool 22 | } 23 | 24 | // TransactionOptions represents all possible options for starting a transaction in a session. 25 | type TransactionOptions struct { 26 | ReadConcern *readconcern.ReadConcern 27 | WriteConcern *writeconcern.WriteConcern 28 | ReadPreference *readpref.ReadPref 29 | } 30 | 31 | func mergeClientOptions(opts ...*ClientOptions) *ClientOptions { 32 | c := &ClientOptions{} 33 | for _, opt := range opts { 34 | if opt == nil { 35 | continue 36 | } 37 | if opt.CausalConsistency != nil { 38 | c.CausalConsistency = opt.CausalConsistency 39 | } 40 | if opt.DefaultReadConcern != nil { 41 | c.DefaultReadConcern = opt.DefaultReadConcern 42 | } 43 | if opt.DefaultReadPreference != nil { 44 | c.DefaultReadPreference = opt.DefaultReadPreference 45 | } 46 | if opt.DefaultWriteConcern != nil { 47 | c.DefaultWriteConcern = opt.DefaultWriteConcern 48 | } 49 | if opt.Snapshot != nil { 50 | c.Snapshot = opt.Snapshot 51 | } 52 | } 53 | 54 | return c 55 | } 56 | -------------------------------------------------------------------------------- /x/mongo/driver/topology/connection_legacy.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package topology 8 | -------------------------------------------------------------------------------- /x/mongo/driver/topology/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package topology_test 8 | 9 | import ( 10 | "log" 11 | 12 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology" 13 | ) 14 | 15 | func Example_clusterMonitoring() { 16 | topo, err := topology.New(nil) 17 | if err != nil { 18 | log.Fatalf("could not create topology: %v", err) 19 | } 20 | err = topo.Connect() 21 | if err != nil { 22 | log.Fatalf("could not create topology: %v", err) 23 | } 24 | 25 | sub, err := topo.Subscribe() 26 | if err != nil { 27 | log.Fatalf("could not subscribe to topology: %v", err) 28 | } 29 | 30 | for desc := range sub.Updates { 31 | log.Printf("%#v", desc) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /x/mongo/driver/topology/stats.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2024-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package topology 8 | 9 | import ( 10 | "container/list" 11 | "math" 12 | "time" 13 | ) 14 | 15 | func standardDeviationList(l *list.List) float64 { 16 | if l.Len() == 0 { 17 | return 0 18 | } 19 | 20 | var mean, variance float64 21 | count := 0.0 22 | 23 | for el := l.Front(); el != nil; el = el.Next() { 24 | count++ 25 | sample := float64(el.Value.(time.Duration)) 26 | 27 | delta := sample - mean 28 | mean += delta / count 29 | variance += delta * (sample - mean) 30 | } 31 | 32 | return math.Sqrt(variance / count) 33 | } 34 | -------------------------------------------------------------------------------- /x/mongo/driver/topology/stats_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package topology 8 | 9 | import ( 10 | "container/list" 11 | "testing" 12 | "time" 13 | 14 | "go.mongodb.org/mongo-driver/v2/internal/assert" 15 | ) 16 | 17 | func TestStandardDeviationList_Duration(t *testing.T) { 18 | tests := []struct { 19 | name string 20 | data []time.Duration 21 | want float64 22 | }{ 23 | { 24 | name: "empty", 25 | data: []time.Duration{}, 26 | want: 0, 27 | }, 28 | { 29 | name: "multiple", 30 | data: []time.Duration{ 31 | time.Millisecond, 32 | 2 * time.Millisecond, 33 | time.Microsecond, 34 | }, 35 | want: 816088.36667497, 36 | }, 37 | } 38 | 39 | for _, test := range tests { 40 | t.Run(test.name, func(t *testing.T) { 41 | l := list.New() 42 | for _, d := range test.data { 43 | l.PushBack(d) 44 | } 45 | 46 | got := standardDeviationList(l) 47 | 48 | assert.InDelta(t, test.want, got, 1e-6) 49 | }) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /x/mongo/driver/topology/tls_connection_source_1_16.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2017-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build !go1.17 8 | // +build !go1.17 9 | 10 | package topology 11 | 12 | import ( 13 | "context" 14 | "crypto/tls" 15 | "net" 16 | ) 17 | 18 | type tlsConn interface { 19 | net.Conn 20 | 21 | // Only require Handshake on the interface for Go 1.16 and less. 22 | Handshake() error 23 | ConnectionState() tls.ConnectionState 24 | } 25 | 26 | var _ tlsConn = (*tls.Conn)(nil) 27 | 28 | type tlsConnectionSource interface { 29 | Client(net.Conn, *tls.Config) tlsConn 30 | } 31 | 32 | type tlsConnectionSourceFn func(net.Conn, *tls.Config) tlsConn 33 | 34 | var _ tlsConnectionSource = (tlsConnectionSourceFn)(nil) 35 | 36 | func (t tlsConnectionSourceFn) Client(nc net.Conn, cfg *tls.Config) tlsConn { 37 | return t(nc, cfg) 38 | } 39 | 40 | var defaultTLSConnectionSource tlsConnectionSourceFn = func(nc net.Conn, cfg *tls.Config) tlsConn { 41 | return tls.Client(nc, cfg) 42 | } 43 | 44 | // clientHandshake will perform a handshake with a goroutine and wait for its completion on Go 1.16 and less 45 | // when HandshakeContext is not available. 46 | func clientHandshake(ctx context.Context, client tlsConn) error { 47 | errChan := make(chan error, 1) 48 | go func() { 49 | errChan <- client.Handshake() 50 | }() 51 | 52 | select { 53 | case err := <-errChan: 54 | return err 55 | case <-ctx.Done(): 56 | return ctx.Err() 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /x/mongo/driver/topology/tls_connection_source_1_17.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2022-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | //go:build go1.17 8 | // +build go1.17 9 | 10 | package topology 11 | 12 | import ( 13 | "context" 14 | "crypto/tls" 15 | "net" 16 | ) 17 | 18 | type tlsConn interface { 19 | net.Conn 20 | 21 | // Require HandshakeContext on the interface for Go 1.17 and higher. 22 | HandshakeContext(ctx context.Context) error 23 | ConnectionState() tls.ConnectionState 24 | } 25 | 26 | var _ tlsConn = (*tls.Conn)(nil) 27 | 28 | type tlsConnectionSource interface { 29 | Client(net.Conn, *tls.Config) tlsConn 30 | } 31 | 32 | type tlsConnectionSourceFn func(net.Conn, *tls.Config) tlsConn 33 | 34 | var _ tlsConnectionSource = (tlsConnectionSourceFn)(nil) 35 | 36 | func (t tlsConnectionSourceFn) Client(nc net.Conn, cfg *tls.Config) tlsConn { 37 | return t(nc, cfg) 38 | } 39 | 40 | var defaultTLSConnectionSource tlsConnectionSourceFn = func(nc net.Conn, cfg *tls.Config) tlsConn { 41 | return tls.Client(nc, cfg) 42 | } 43 | 44 | // clientHandshake will perform a handshake on Go 1.17 and higher with HandshakeContext. 45 | func clientHandshake(ctx context.Context, client tlsConn) error { 46 | return client.HandshakeContext(ctx) 47 | } 48 | -------------------------------------------------------------------------------- /x/mongo/driver/xoptions/options.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) MongoDB, Inc. 2025-present. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | package xoptions 8 | 9 | import ( 10 | "fmt" 11 | 12 | "go.mongodb.org/mongo-driver/v2/internal/optionsutil" 13 | "go.mongodb.org/mongo-driver/v2/mongo/options" 14 | "go.mongodb.org/mongo-driver/v2/x/mongo/driver" 15 | ) 16 | 17 | // SetInternalClientOptions sets internal options for ClientOptions. 18 | // 19 | // Deprecated: This function is for internal use only. It may be changed or removed in any release. 20 | func SetInternalClientOptions(opts *options.ClientOptions, key string, option any) error { 21 | typeErrFunc := func(t string) error { 22 | return fmt.Errorf("unexpected type for %s: %T is not %s", key, option, t) 23 | } 24 | switch key { 25 | case "crypt": 26 | c, ok := option.(driver.Crypt) 27 | if !ok { 28 | return typeErrFunc("driver.Crypt") 29 | } 30 | opts.Crypt = c 31 | case "deployment": 32 | d, ok := option.(driver.Deployment) 33 | if !ok { 34 | return typeErrFunc("driver.Deployment") 35 | } 36 | opts.Deployment = d 37 | case "authenticateToAnything": 38 | b, ok := option.(bool) 39 | if !ok { 40 | return typeErrFunc("bool") 41 | } 42 | opts.Custom = optionsutil.WithValue(opts.Custom, key, b) 43 | default: 44 | return fmt.Errorf("unsupported option: %s", key) 45 | } 46 | return nil 47 | } 48 | --------------------------------------------------------------------------------