Cosa sono i Secret di Snowflake?
In Snowflake un Secret è un oggetto a livello di schema che permette di custodire informazioni sensibili come API key o password.
A cosa serve questa funzionalità?
Negli ultimi tempi Snowflake ha introdotto numerose funzionalità che consentono di sviluppare applicazioni e data pipeline direttamente al suo interno:
- Snowpark Container Services consente di eseguire applicazioni personalizzate in qualsiasi linguaggio di programmazione.
- Snowpark for Python si sta affermando come scelta privilegiata per il data engineering, incluse intere pipeline ELT/ETL.
- Oggi è possibile inviare notifiche via email, Slack o Microsoft Teams (tramite webhook).
- Snowflake permette ora di effettuare chiamate API verso la rete pubblica: molti utenti non vedono l'ora di sfruttare le API di OpenAI dal proprio account Snowflake.
Tutti questi scenari richiedono di archiviare secret e di accedervi per autenticarsi verso applicazioni e servizi diversi.
I vantaggi di gestire i Secret in Snowflake
- I secret creati in Snowflake si appoggiano allo stesso modello RBAC di Snowflake che già conosciamo (es.
grant usage on secret to role <role>). - Il secret vive accanto al codice dell'applicazione o della pipeline: nessun sistema aggiuntivo da gestire.
- Adottare un secrets manager esterno (come AWS Secrets Manager) sarebbe complesso senza disporre prima di un metodo lineare per autenticarsi a quel servizio.
Come creare un Secret in Snowflake
In Snowflake si possono creare 4 tipi di secret e la DDL cambia leggermente a seconda del tipo.
OAuth:
Sintassi
CREATE [ OR REPLACE ] SECRET [ IF NOT EXISTS ] <name>
TYPE = OAUTH2
API_AUTHENTICATION = <security_integration_name>
OAUTH_SCOPES = ( '<scope_1>' [ , '<scope_2>' ... ] )
[ COMMENT = '<string_literal>' ]
Esempio
-- Assume an integration exists:
CREATE OR REPLACE SECURITY INTEGRATION my_oauth2_integration
TYPE = API_AUTHENTICATION
AUTH_TYPE = OAUTH2
ENABLED = TRUE
OAUTH_CLIENT_ID = 'your_client_id'
OAUTH_CLIENT_SECRET = 'your_client_secret'
OAUTH_TOKEN_ENDPOINT = 'https://oauth2.example.com/token'
OAUTH_ALLOWED_SCOPES = ('scope1', 'scope2');
-- create the secret
CREATE OR REPLACE SECRET my_oauth2_secret
TYPE = OAUTH2
API_AUTHENTICATION = my_oauth2_integration
OAUTH_SCOPES = ('scope1', 'scope2')
Espandi codice
Cloud Provider:
Sintassi:
CREATE [ OR REPLACE ] SECRET [ IF NOT EXISTS ] <name>
TYPE = CLOUD_PROVIDER_TOKEN
API_AUTHENTICATION = '<cloud_provider_security_integration>'
[ COMMENT = '<string_literal>' ]
Esempio:
-- assume this integration exists called test_integration:
CREATE OR REPLACE SECRET test_secret
TYPE = CLOUD_PROVIDER_TOKEN
API_AUTHENTICATION = 'TEST_INTEGRATION';
Basic Auth:
Sintassi:
CREATE [ OR REPLACE ] SECRET [ IF NOT EXISTS ] <name>
TYPE = PASSWORD
USERNAME = '<username>'
PASSWORD = '<password>'
[ COMMENT = '<string_literal>' ]
Esempio:
CREATE OR REPLACE SECRET my_password_secret
TYPE = PASSWORD
USERNAME = 'db_user'
PASSWORD = 'MySecurePass123!'
COMMENT = 'Database credentials for application access';
Generic String:
Sintassi:
CREATE [ OR REPLACE ] SECRET [ IF NOT EXISTS ] <name>
TYPE = GENERIC_STRING
SECRET_STRING = '<string_literal>'
[ COMMENT = '<string_literal>' ]
Esempio:
CREATE OR REPLACE SECRET my_string_secret
TYPE = GENERIC_STRING
SECRET_STRING = 'my-secret-api-key-123'
COMMENT = 'API key for service authentication';
Come usare un Secret di Snowflake nel codice
I secret possono essere recuperati solo tramite Java o Python. Se l'applicazione è ospitata in Snowpark Container Services con un altro linguaggio, servirà un piccolo modulo dedicato in Java o Python che recuperi il secret e ne restituisca poi il valore all'applicazione.
Ecco un esempio di recupero di un secret in Python.
Passo 1: creare una funzione per recuperare i secret per nome
CREATE OR REPLACE FUNCTION get_secret_by_name(secret_name STRING)
RETURNS STRING
LANGUAGE PYTHON
RUNTIME_VERSION = 3.9
HANDLER = 'get_secret_by_name'
EXTERNAL_ACCESS_INTEGRATIONS = (external_access_integration)
AS
$$
import _snowflake
def get_secret_by_name(secret_name):
username_password_object = _snowflake.get_username_password(secret_name)
username_password_dictionary = {}
username_password_dictionary["Username"] = username_password_object.username
Espandi codice
Passo 2: richiamare la funzione
1SELECT get_secret_by_name('jeffs_credentials');
Usare i Secret nelle Notification Integration / Webhook
Snowflake mette a disposizione un metodo intuitivo per passare un secret alle Notification Integration e inviare notifiche ai webhook (Slack, Microsoft Teams, ecc.).
È sufficiente passare il nome completamente qualificato database.schema.<secret_name> all'argomento WEBHOOK_SECRET dell'istruzione create notification integration. Ad esempio:
CREATE OR REPLACE NOTIFICATION INTEGRATION my_slack_webhook_int
TYPE=WEBHOOK
ENABLED=TRUE
WEBHOOK_URL='https://hooks.slack.com/services/SNOWFLAKE_WEBHOOK_SECRET'
WEBHOOK_SECRET=my_secrets_db.my_secrets_schema.my_slack_webhook_secret
WEBHOOK_BODY_TEMPLATE='{"text": "SNOWFLAKE_WEBHOOK_MESSAGE"}'
WEBHOOK_HEADERS=('Content-Type'='application/json');
Gestire i Secret in Snowflake
Visualizzare tutti i Secret
Per vedere tutti i secret basta usare il comando show secrets.
show secrets; -- shows all secrets in account
show secrets in account; -- verbose way of `show secrets`
show secrets in database analytics; -- shows secrets for a database named analytics
Eliminare un Secret
Per eliminare un secret si usa il comando drop:
drop secret my_oauth2_secret; -- this works if your worksheet or connection has a database and schema context set.
drop secret <fully qualified secret name> -- this will always work
Modificare un Secret
Il comando alter secret serve a ruotare chiavi o password, oppure a modificare qualsiasi altro attributo del secret.
1alter secret <fully qualitfied secret name> set <parameter> = <value>;
Descrivere un Secret
L'uso di describe secret <fully qualified secret name> restituisce i seguenti campi:
- created on
- name
- schema_name
- database_name
- owner
- comment
- secret_type
- username
- oauth_access_token_expiry_time
- oauth_refresh_token_expiry_time
- oauth_scopes
- integration_name
Gestire i secret direttamente in Snowflake è un modo efficace per semplificare l'uso di informazioni sensibili nello sviluppo di applicazioni, pipeline o avvisi all'interno della piattaforma.
Nel prossimo articolo metteremo in pratica quanto visto creando un avviso Slack in Snowflake.
Jeff è un Data and Analytics Consultant con oltre 15 anni di esperienza nell'automazione degli insight e nell'uso dei dati per governare i processi aziendali. Sul fronte tecnologico è specializzato in Snowflake + dbt + Tableau. Sul fronte dei settori, ha lavorato in Public Utility, Clinical Trials, Publishing, CPG e Manufacturing. Per qualsiasi richiesta, scrivetegli a [email protected].