Search code examples
amazon-web-servicessdkcredentials

AWS PHP SDK - Assuming role from different account gives "Error in retrieving assume role credentials."


I have AWS Account 1 with the following role ARN:

arn:aws:iam::534953367916:role/role3

and the following trust policy for the role (in which I have entered Account 2 user ARN as principal):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::201255186948:user/testuser"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "StringEquals": {
                    "sts:ExternalId": "1234"
                }
            }
        }
    ]
}

In Account 2 I have created access key and secret for "testuser" and I use them in PHP SDK code:

  $provider = CredentialProvider::assumeRole([
                'client' => new StsClient([
                    'region' => "us-east-1",
                    'version' => "2011-06-15",
                    'credentials' => [
                        "key" => "AKIAS5W56OICHSKXFKYP", // testuser access key and secret
                        "secret" => "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",
                    ]
                ]),
                'assume_role_params' => [
                    'RoleArn' => "arn:aws:iam::534953367916:role/role3",
                    'RoleSessionName' => 'my-custom-app',
                    'ExternalId' => "1234"
                ],
            ]);

            $s3Client = new S3Client([
                'region' => "us-east-1",
                'version' => "2006-03-01",
                'credentials' => $provider
            ]);
            $adapter = new \League\Flysystem\AwsS3V3\AwsS3V3Adapter($s3Client, $bucket);
            $contents = $adapter->listContents("", true);

            foreach ($contents as $content) {
                
            }

I receive error on the "foreach":

Error in retrieving assume role credentials.

After more debugging I get the internal error:

Sender AccessDenied User: arn:aws:iam::201255186948:user/testuser is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::534953367916:role/role3

The role has AmazonS3FullAccess permission.


Solution

  • For cross account assume-roles (and any action in general) you need the permission for the AssumeRole call both on the target role (or resource in general) in its trust relationship (resource policy in general) and on the source principal performing the action.

    See e.g. https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic-cross-account.html