azureazure-cosmosdbpymongoazure-cosmosdb-mongoapissl-handshake

SSL handshake failed in cosmosdb mongo api with python


I am trying to connect a database in azure cosmos that uses the Mongo DB API in Python. When I create the client, I get the SSL handshake failed error and I don't know how to solve it. I am aware that there is some thread that talks about this issue, and I have added to my code its recommendation, however I have not been able to make it work.

I have added the tlsCAFile=certifi.where() when creating the client, but I have not been able to solve it. I have seen people recommending ssl_cert_reqs=ssl.CERT_NONE or tlsAllowInvalidCertificates=True, but I don't want to mute the problem and lose security. Furthermore, even assuming the security loss I have not been able to make it work.

I am relying on this Azure Cosmos help page to create my client. I have already configured the environment variables.

Link to azure tutorial

This is my code summarized:

import getpass
import certifi
import pymongo
import os
import sys
import pymongo
from dotenv import load_dotenv
from random import randint

#[...]

def main():
    """Connect to the API for MongoDB, create DB and collection, perform
    CRUD operations
    """
    # Variable for resource group name
    load_dotenv()
    CONNECTION_STRING = os.environ.get("COSMOS_CONNECTION_STRING")
    client = pymongo.MongoClient(CONNECTION_STRING,tls=True,tlsCAFile=certifi.where())

    for prop, value in vars(client.options).items():
        print("Property: {}: Value: {} ".format(prop, value))

    try:
        client.server_info()  # validate connection string
    except pymongo.errors.ServerSelectionTimeoutError:
        raise TimeoutError(
            "Invalid API for MongoDB connection string \
                or timed out when attempting to connect"
        )

    collection = create_database_unsharded_collection(client)
    document_id = insert_sample_document(collection)

    read_document(collection, document_id)
    update_document(collection, document_id)
    delete_document(collection, document_id)


if __name__ == "__main__":
    main()

Any help is welcome, thank you very much in advance. I have also this question in Microsoft Q&A

EDIT: I am working on a company's network, and I have read that it might cause problems. Could this be related to my issue?

I have python (3.8.5), python-dotenv (1.0.0), certifi (2020.6.20), pymongo (4.4.1), dnspython (2.4.2). MongoDB server version 4.2.


Solution

  • I have managed to solve the problem. If you work with a company network, for security reasons they have some ports closed. In my case, port 10255 was closed for security reasons and the client was well configured.

    Link that helped me