Search code examples
amazon-web-servicesamazon-iamamazon-ecr

AWS IAM Policy condition statement logical OR operator


I have a simple IAM policy with two conditions:


{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowPush",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com",
        "AWS": "arn:aws:iam::123456789:root"
      },
      "Action": [
        "ecr:*"
      ],
      "Condition": {
        "StringEquals": {
          "aws:username": [
            "user01",
            "marketing"
          ]
        },
        "StringLike": {
          "aws:sourceArn": [
            "arn:aws:lambda:eu-west-1:987654321:function:*",
            "arn:aws:lambda:eu-west-1:481275139:function:*",
            "arn:aws:lambda:eu-west-1:428385139:function:*"
          ]
        }
      }
    }
  ]
}

I would like to grant an entity permissions ecr:* if ONE of the two conditions are met, either their are user01 / marketing or a lambda function from another account is requesting the grant.

I have tried the policy before but it seems like the two conditions must be met at the same time in order to work.

Note: This policy is attached to an ECR repository.


Solution

  • Your policy statement has multiple condition operators, so the condition operators are evaluated using a logical AND.

    Your aws:username context key has multiple values, so those values are evaluated using a logical OR. Ditto for the aws:sourceArn context key.

    Here is a visualization of IAM policy evaluation of conditions.

    enter image description here

    If you want either condition (OR) rather than both conditions (AND) use two statements, like so:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "AllowPushUser",
          "Effect": "Allow",
          "Principal": {
            "Service": "lambda.amazonaws.com",
            "AWS": "arn:aws:iam::123456789:root"
          },
          "Action": [
            "ecr:*"
          ],
          "Condition": {
            "StringEquals": {
              "aws:username": [
                "user01",
                "marketing"
              ]
            }
          }
        },
        {
          "Sid": "AllowPushLambda",
          "Effect": "Allow",
          "Principal": {
            "Service": "lambda.amazonaws.com",
            "AWS": "arn:aws:iam::123456789:root"
          },
          "Action": [
            "ecr:*"
          ],
          "Condition": {
            "StringLike": {
              "aws:sourceArn": [
                "arn:aws:lambda:eu-west-1:987654321:function:*",
                "arn:aws:lambda:eu-west-1:481275139:function:*",
                "arn:aws:lambda:eu-west-1:428385139:function:*"
              ]
            }
          }
        }
      ]
    }