Skip to content

Commit

Permalink
use WorkloadIdentityCredential for MySQL Sequelize connection (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
IanR01 authored Feb 19, 2024
1 parent 3f6a081 commit 1939f26
Show file tree
Hide file tree
Showing 4 changed files with 546 additions and 6 deletions.
13 changes: 13 additions & 0 deletions azure-auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { WorkloadIdentityCredential } = require("@azure/identity");

const scope = 'https://ossrdbms-aad.database.windows.net/.default'

// This relies on environment variables that get injected.
// AZURE_AUTHORITY_HOST: (Injected by the webhook)
// AZURE_CLIENT_ID: (Injected by the webhook)
// AZURE_TENANT_ID: (Injected by the webhook)
// AZURE_FEDERATED_TOKEN_FILE: (Injected by the webhook)
const credential = new WorkloadIdentityCredential()
const getAzureAuthToken = async () => (await credential.getToken(scope)).token

module.exports = getAzureAuthToken
19 changes: 18 additions & 1 deletion db.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,36 @@

const { Sequelize } = require('sequelize');

var getAzureAuthToken = require('./azure-auth')

let ssl;
if (process.env.MYSQL_CA_CERT) {
ssl = {
ca: process.env.MYSQL_CA_CERT
}
}

if (process.env.AZURE_CLIENT_ID) {
ssl = {
require: true
}
}

let sequelize = new Sequelize({
hooks: {
beforeConnect: async (config) => {
if (process.env.AZURE_CLIENT_ID) {
const azureAuthToken = await getAzureAuthToken()
config.password = azureAuthToken
} else {
config.password = process.env.DB_PASSWORD
}
}
},

host: process.env.DB_HOST,
database: process.env.DB_NAME,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT || '3306',

ssl,
Expand Down
Loading

0 comments on commit 1939f26

Please sign in to comment.