Created
January 20, 2021 13:59
-
-
Save rdsedmundo/65c6ef2e75dfb01cebed806891623fa9 to your computer and use it in GitHub Desktop.
Get IAM permissions from CloudTrail logs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const _ = require('lodash'); | |
const devHistory = require('../event_history_dev.json'); | |
const prodHistory = require('../event_history_prod.json'); | |
(async () => { | |
const events = [...devHistory.Records, ...prodHistory.Records]; | |
const policiesByService = {}; | |
for (const event of events) { | |
const serviceName = event.eventSource.split('.amazonaws.')[0]; | |
policiesByService[serviceName] = policiesByService[serviceName] || []; | |
const resources = event.resources?.map((resource) => resource.ARN) || '*'; | |
const iamAction = `${serviceName}:${event.eventName}`; | |
const policy = policiesByService[serviceName]; | |
const indexOfAction = policy.findIndex((p) => p.Action === iamAction); | |
if (indexOfAction === -1) { | |
policy.push({ | |
Effect: 'Allow', | |
Action: iamAction, | |
Resource: resources, | |
}); | |
} else if (policy[indexOfAction].Resource !== '*') { | |
policy[indexOfAction].Resource = Array.from( | |
new Set([...policy[indexOfAction].Resource, ...resources]), | |
); | |
} | |
} | |
console.log( | |
JSON.stringify( | |
Object.values( | |
Object.fromEntries( | |
Object.entries(policiesByService).map(([key, statements]) => { | |
return [ | |
key, | |
Object.entries(_.groupBy(statements, 'Resource')).map( | |
([resource, groupedStatements]) => ({ | |
Effect: 'Allow', | |
Action: groupedStatements.map((s) => s.Action), | |
Resource: resource === '*' ? '*' : resource.split(','), | |
}), | |
), | |
]; | |
}), | |
), | |
).flat(), | |
undefined, | |
2, | |
), | |
); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment