8000 Fix error with non-existent policy for AttachRolePolicy operation by dfangl · Pull Request #8615 · localstack/localstack · GitHub
[go: up one dir, main page]

Skip to content

Fix error with non-existent policy for AttachRolePolicy operation #8615

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions localstack/services/iam/provider.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import re
from datetime import datetime
from typing import Dict, List, Optional
from urllib.parse import quote
Expand Down Expand Up @@ -26,6 +27,7 @@
GetServiceLinkedRoleDeletionStatusResponse,
GetUserResponse,
IamApi,
InvalidInputException,
ListInstanceProfileTagsResponse,
ListRolesResponse,
MalformedPolicyDocumentException,
Expand Down Expand Up @@ -89,6 +91,8 @@
}
}

POLICY_ARN_REGEX = re.compile(r"arn:[^:]+:iam::(?:\d{12}|aws):policy/.*")


def get_iam_backend(context: RequestContext) -> IAMBackend:
return iam_backends[context.account_id]["global"]
Expand Down Expand Up @@ -416,6 +420,20 @@ def get_user(

return response

def attach_role_policy(
self, context: RequestContext, role_name: roleNameType, policy_arn: arnType
) -> None:
if not POLICY_ARN_REGEX.match(policy_arn):
raise InvalidInputException(f"ARN {policy_arn} is not valid.")
return call_moto(context=context)

def attach_user_policy(
self, context: RequestContext, user_name: userNameType, policy_arn: arnType
) -> None:
if not POLICY_ARN_REGEX.match(policy_arn):
raise InvalidInputException(f"ARN {policy_arn} is not valid.")
return call_moto(context=context)

# def get_user(
# self, context: RequestContext, user_name: existingUserNameType = None
# ) -> GetUserResponse:
Expand Down
2 changes: 2 additions & 0 deletions localstack/testing/snapshots/transformer_utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,8 @@ def iam_api():
TransformerUtility.key_value("UserId"),
TransformerUtility.key_value("RoleId"),
TransformerUtility.key_value("RoleName"),
TransformerUtility.key_value("PolicyName"),
TransformerUtility.key_value("PolicyId"),
]

@staticmethod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,25 @@
}
},
"tests/integration/cloudformation/resources/test_iam.py::test_managed_policy_with_empty_resource": {
"recorded-date": "05-09-2022, 10:01:53",
"recorded-date": "11-07-2023, 18:10:41",
"recorded-content": {
"outputs": {
"PolicyArn": "arn:aws:iam::111111111111:policy/<resource:1>",
"StreamARN": "arn:aws:dynamodb:<region>:111111111111:table/<resource:3>/stream/<resource:2>",
"TableARN": "arn:aws:dynamodb:<region>:111111111111:table/<resource:3>",
"TableName": "<resource:3>"
"PolicyArn": "arn:aws:iam::111111111111:policy/<policy-name:1>",
"StreamARN": "arn:aws:dynamodb:<region>:111111111111:table/<resource:2>/stream/<resource:1>",
"TableARN": "arn:aws:dynamodb:<region>:111111111111:table/<resource:2>",
"TableName": "<resource:2>"
},
"managed_policy": {
"Policy": {
"Arn": "arn:aws:iam::111111111111:policy/<resource:1>",
"Arn": "arn:aws:iam::111111111111:policy/<policy-name:1>",
"AttachmentCount": 0,
"CreateDate": "datetime",
"DefaultVersionId": "v1",
"IsAttachable": true,
"Path": "/",
"PermissionsBoundaryUsageCount": 0,
"PolicyId": "<policy-id:1>",
"PolicyName": "<resource:1>",
"PolicyName": "<policy-name:1>",
"Tags": [],
"UpdateDate": "datetime"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
{
"tests/integration/cloudformation/resources/test_sam.py::test_sam_policies": {
"recorded-date": "02-06-2022, 13:13:20",
"recorded-date": "11-07-2023, 18:08:53",
"recorded-content": {
"list_attached_role_policies": {
"AttachedPolicies": [
{
"PolicyName": "AWSLambdaBasicExecutionRole",
"PolicyArn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
"PolicyArn": "arn:aws:iam::aws:policy/service-role/<policy-name:1>",
"PolicyName": "<policy-name:1>"
},
{
"PolicyName": "AmazonSNSFullAccess",
"PolicyArn": "arn:aws:iam::aws:policy/AmazonSNSFullAccess"
"PolicyArn": "arn:aws:iam::aws:policy/<policy-name:2>",
"PolicyName": "<policy-name:2>"
}
],
"IsTruncated": false,
"ResponseMetadata": {
"HTTPStatusCode": 200,
"HTTPHeaders": {}
"HTTPHeaders": {},
"HTTPStatusCode": 200
}
}
}
Expand Down
102 changes: 102 additions & 0 deletions tests/integration/test_iam.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,3 +585,105 @@ def test_list_roles_with_permission_boundary(

list_roles_result = aws_client.iam.list_roles(PathPrefix=path_prefix)
snapshot.match("list_roles_result", list_roles_result)

@pytest.mark.aws_validated
@pytest.mark.skip_snapshot_verify(
paths=[
"$..Policy.IsAttachable",
"$..Policy.PermissionsBoundaryUsageCount",
"$..Policy.Tags",
]
)
def test_role_attach_policy(self, snapshot, aws_client, create_role, create_policy):
snapshot.add_transformer(snapshot.transform.iam_api())

trust_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole",
}
],
}
policy_document = {
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["lambda:ListFunctions"], "Resource": ["*"]}
],
}

role_name = f"test-role-{short_uid()}"
policy_name = f"test-policy-{short_uid()}"
create_role(RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy))
create_policy_response = create_policy(
PolicyName=policy_name, PolicyDocument=json.dumps(policy_document)
)
snapshot.match("create_policy_response", create_policy_response)
policy_arn = create_policy_response["Policy"]["Arn"]

with pytest.raises(ClientError) as e:
aws_client.iam.attach_role_policy(
RoleName=role_name, PolicyArn="longpolicynamebutnoarn"
)
snapshot.match("non_existent_malformed_policy_arn", e.value.response)

with pytest.raises(ClientError) as e:
aws_client.iam.attach_role_policy(RoleName=role_name, PolicyArn=policy_name)
snapshot.match("existing_policy_name_provided", e.value.response)

with pytest.raises(ClientError) as e:
aws_client.iam.attach_role_policy(RoleName=role_name, PolicyArn=f"{policy_arn}123")
snapshot.match("valid_arn_not_existent", e.value.response)

attach_policy_response = aws_client.iam.attach_role_policy(
RoleName=role_name, PolicyArn=policy_arn
)
snapshot.match("valid_policy_arn", attach_policy_response)

@pytest.mark.aws_validated
@pytest.mark.skip_snapshot_verify(
paths=[
"$..Policy.IsAttachable",
"$..Policy.PermissionsBoundaryUsageCount",
"$..Policy.Tags",
]
)
def test_user_attach_policy(self, snapshot, aws_client, create_user, create_policy):
snapshot.add_transformer(snapshot.transform.iam_api())

policy_document = {
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["lambda:ListFunctions"], "Resource": ["*"]}
],
}

user_name = f"test-role-{short_uid()}"
policy_name = f"test-policy-{short_uid()}"
create_user(UserName=user_name)
create_policy_response = create_policy(
PolicyName=policy_name, PolicyDocument=json.dumps(policy_document)
)
snapshot.match("create_policy_response", create_policy_response)
policy_arn = create_policy_response["Policy"]["Arn"]

with pytest.raises(ClientError) as e:
aws_client.iam.attach_user_policy(
Us 9E88 erName=user_name, PolicyArn="longpolicynamebutnoarn"
)
snapshot.match("non_existent_malformed_policy_arn", e.value.response)

with pytest.raises(ClientError) as e:
aws_client.iam.attach_user_policy(UserName=user_name, PolicyArn=policy_name)
snapshot.match("existing_policy_name_provided", e.value.response)

with pytest.raises(ClientError) as e:
aws_client.iam.attach_user_policy(UserName=user_name, PolicyArn=f"{policy_arn}123")
snapshot.match("valid_arn_not_existent", e.value.response)

attach_policy_response = aws_client.iam.attach_user_policy(
UserName=user_name, PolicyArn=policy_arn
)
snapshot.match("valid_policy_arn", attach_policy_response)
124 changes: 124 additions & 0 deletions tests/integration/test_iam.snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -199,5 +199,129 @@
}
}
}
},
"tests/integration/test_iam.py::TestIAMIntegrations::test_role_attach_policy": {
"recorded-date": "04-07-2023, 17:04:08",
"recorded-content": {
"create_policy_response": {
"Policy": {
"Arn": "arn:aws:iam::111111111111:policy/<policy-name:1>",
"AttachmentCount": 0,
"CreateDate": "datetime",
"DefaultVersionId": "v1",
"IsAttachable": true,
"Path": "/",
"PermissionsBoundaryUsageCount": 0,
"PolicyId": "<policy-id:1>",
"PolicyName": "<policy-name:1>",
"UpdateDate": "datetime"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 200
}
},
"non_existent_malformed_policy_arn": {
"Error": {
"Code": "InvalidInput",
"Message": "ARN longpolicynamebutnoarn is not valid.",
"Type": "Sender"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 400
}
},
"existing_policy_name_provided": {
"Error": {
"Code": "InvalidInput",
"Message": "ARN <policy-name:1> is not valid.",
"Type": "Sender"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 400
}
},
"valid_arn_not_existent": {
"Error": {
"Code": "NoSuchEntity",
"Message": "Policy arn:aws:iam::111111111111:policy/<policy-name:1>123 does not exist or is not attachable.",
"Type": "Sender"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 404
}
},
"valid_policy_arn": {
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 200
}
}
}
},
"tests/integration/test_iam.py::TestIAMIntegrations::test_user_attach_policy": {
"recorded-date": "04-07-2023, 17:16:43",
"recorded-content": {
"create_policy_response": {
"Policy": {
"Arn": "arn:aws:iam::111111111111:policy/<policy-name:1>",
"AttachmentCount": 0,
"CreateDate": "datetime",
"DefaultVersionId": "v1",
"IsAttachable": true,
"Path": "/",
"PermissionsBoundaryUsageCount": 0,
"PolicyId": "<policy-id:1>",
"PolicyName": "<policy-name:1>",
"UpdateDate": "datetime"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 200
}
},
"non_existent_malformed_policy_arn": {
"Error": {
"Code": "InvalidInput",
"Message": "ARN longpolicynamebutnoarn is not valid.",
"Type": "Sender"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 400
}
},
"existing_policy_name_provided": {
"Error": {
"Code": "InvalidInput",
"Message": "ARN <policy-name:1> is not valid.",
"Type": "Sender"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 400
}
},
"valid_arn_not_existent": {
"Error": {
"Code": "NoSuchEntity",
"Message": "Policy arn:aws:iam::111111111111:policy/<policy-name:1>123 does not exist or is not attachable.",
"Type": "Sender"
},
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 404
}
},
"valid_policy_arn": {
"ResponseMetadata": {
"HTTPHeaders": {},
"HTTPStatusCode": 200
}
}
}
}
}
0