Skip to content

Instantly share code, notes, and snippets.

@Alex-Wauters
Created April 14, 2019 16:11
Show Gist options
  • Save Alex-Wauters/aa2a3452cab1e6c80c58e32b424a4079 to your computer and use it in GitHub Desktop.
Save Alex-Wauters/aa2a3452cab1e6c80c58e32b424a4079 to your computer and use it in GitHub Desktop.
Firebase-Azure AD: Update function for IdP keys
/**
* Retrieve IDP signature keys.
*/
async function updateIdpKeys(): Promise<Array<MSOpenIdKey>> {
const data = await rp({ uri: 'https://login.microsoftonline.com/common/discovery/v2.0/keys', json: true });
if (data && data.keys && isArray(data.keys) && data.keys.length > 0) {
data.keys.forEach(async (k: MSOpenIdKey) => {
await db.collection('IdpKeys').doc(k.kid).set(k);
});
keys = data.keys; // Store in container. Will be re-used when container is re-used
return keys;
} else {
console.error(`Received from MS openID endpoint: ${data}`);
throw new Error("Could not read the keys from MS' openID discovery endpoint");
}
}
/**
* Periodically retrieve the IDP Signature keys.
* Triggered by a Cloud Composer call to the daily pubsub.
*/
exports.updatePublicKey = functions.pubsub.topic('daily').onPublish(async event => {
console.log("Refreshing IdP Public keys");
const updatedKeys = await updateIdpKeys();
// Remove old signing keys
const toDelete = await getOldKeys(updatedKeys);
console.log(`${toDelete.length} keys to remove`);
toDelete.forEach(async k => {
try {
await db.collection("IdpKeys").doc(k).delete();
console.log(`Document ${k} deleted`);
} catch (err) {
console.error("Error removing document: ", err);
}
})
});
async function getOldKeys(updatedKeys: Array<MSOpenIdKey>) {
const querySnapshot = await db.collection("IdpKeys").get();
const oldKeys: string[] = [];
querySnapshot.forEach(doc => {
if (!updatedKeys.some(k => k.kid === doc.id)) {
oldKeys.push(doc.id);
}
});
return oldKeys;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment