Search code examples
amazon-dynamodbamazon-cognitopolicy

how to create a policy for DynamoDB where the user id is equal to DyanmoDB table name?


I am trying to create a DDB policy whereby the Cognito user id (sub) should be equal to the DynamoDB table name. The table name in DDB is the user's id (sub). So the policy should limit access to the user's table for that user only. Below is a pseudo policy I have created.

What is unclear to me is how do I specify that the user id ( sub ) should be equal to the DDB table name ?

{
 "Version": "2020-11-01",
    "Statement": [
        {
            "Sid": "xxxxxxxxxxxxxx",
            "Effect": "Allow",
            "Action": [
                "dynamodb:Scan",
                "dynamodb:Query",
            ],
             
            "Resource": [ "arn:aws:dynamodb:<REGION>:<ACCOUNT_ID>:table/<${www.amazon.com:user_id}>"]
        }  
         
      DDB TABLE NAME SHOULD MATCH USER ID HERE ${www.amazon.com:user_id}
    ]
}   

Solution

  • Unfortunately you cannot currently do it with DynamoDB. This is because the table resource for DynamoDB does no support any condition keys (see https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazondynamodb.html#amazondynamodb-resources-for-iam-policies).

    The only thing you could possibly do is to limit access per leading keys using the dynamodb:LeadingKeys condition. This again would only work for the Query action. Does not work on Scan (obviously). Your policy would then look something like this:

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "dynamodb:GetItem",
                    "dynamodb:Query"
                ],
                "Resource": ["arn:aws:dynamodb:*:*:table/MyTable"],
                "Condition": {
                    "ForAllValues:StringEquals": {
                        "dynamodb:LeadingKeys": ["${cognito-identity.amazonaws.com:sub}"]
                    }
                }
            }
        ]
    }