Snowflake-Labs / django-snowflake

MIT License
59 stars 15 forks source link

Document how to authenticate with a private key #72

Closed fhoffa closed 1 year ago

fhoffa commented 1 year ago

I see @sfc-gh-hachouraria is adding some examples to OPTIONS for authentication:

https://github.com/Snowflake-Labs/django-snowflake/pull/66

As we find the best way to include this code, I wanted to document a hack to authenticate with a private key in the meantime.

In settings.py I just add an ugly block to decrypt the key:

#### --Fh
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives import serialization

with open("./rsa_key.p8", "rb") as key:
    p_key= serialization.load_pem_private_key(
        key.read(),
        password=None,
        backend=default_backend()
    )

pkb = p_key.private_bytes(
    encoding=serialization.Encoding.DER,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption())
### --Fh

So then in DATABASES in settings.py I can use that pkb value:

DATABASES = {
    'default': {
        'ENGINE': 'django_snowflake',
        'NAME': 'DJANGO',
        'SCHEMA': 'PUBLIC',
        'WAREHOUSE': 'S',
        'USER': 'DJANGO',
        'PASSWORD': '#',
        'ACCOUNT': 'my_account',
        # Include 'OPTIONS' if you need to specify any other
        # snowflake.connector.connect() parameters.
        # https://docs.snowflake.com/en/user-guide/python-connector-api.html#connect
        'OPTIONS': {
            'private_key': pkb,
        }
    }
}
sfc-gh-hachouraria commented 1 year ago

There's not a simpler way (other than reading the private key bytes (pkb) yourself) because the python connector does not accept a file path as an input yet. See also a related issue discussion on: https://github.com/Snowflake-Labs/django-snowflake/issues/67

Feature request raised at: https://github.com/snowflakedb/snowflake-connector-python/issues/1565