Search code examples
amazon-web-servicesaws-lambdaassume-role

Find accounts calling my lambda with assumed role


We have an account A with a lambda and a role to invoke it. We have accounts B, C, D which are allowed to assume that A-role and invoke that lambda.

Now the problem: we have too many invocations of the lambda, and we would like to figure out, what exact accounts are the most actively using it. So in lambda code I would like to know who is calling it and write some log or put some metric record. But It looks like I can't find that with the code (at least in java).

Also I've enabled cloudtrail data events, and now in the trail I could see some additional info about my lambda invocation. The field "userIdentity" was looking promising, but it also doesn't contain any info about original account who assumed the role. The only potentially useful info there is role-session-name provided during assume-role operation. But B, C, D services don't provide anything reasonable as session-name, just some random things.

For now I see only two options, and both require changes in dependent services: provide account-id or service name as a role-session-name, or create independent assumable roles for each B, C and D service.

Are there any other possibilities to trace this down without changing the code of these services?


Solution

  • @jellycsc's comment does provide the answer, although that document is a rather long-winded description of how to set up an automated auditing system. The short answer is: it's all in CloudTrail.

    As you've already identified, you can find the InvokeFunction or InvokeAsync event in CloudTrail. In the userIdentity object of the CloudTrail event, look at the accessKeyId field. We want to use this field instead of the arn field (which contains the ARN of the assumed role) because it's unique for each time a role is assumed (meaning it allows you to link a specific InvokeFunction action to a specific AssumeRole action).

    Now, you want to find a CloudTrail management event (not data event) with the event type AssumeRole, where the responseElements.credentials.accessKeyId field matches the accessKeyId that you found in the previous step. This is the event where the role that was used to invoke the Lambda was first assumed. Within the userIdentity object of this event you will find the credentials of the user who assumed the role, i.e. the original user who actually invoked the Lambda via the assumed role.