1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
|
import json
import sys
from typing import Any, Optional
from unittest import SkipTest
from uuid import uuid4
import boto3
import pytest
from botocore.exceptions import ClientError
from moto import mock_aws
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from moto.core import set_initial_no_auth_action_count
from moto.utilities.distutils_version import LooseVersion
boto3_version = sys.modules["botocore"].__version__
@mock_aws
def create_user_with_access_key(user_name: str = "test-user") -> dict[str, str]:
client = boto3.client("iam", region_name="us-east-1")
client.create_user(UserName=user_name)
return client.create_access_key(UserName=user_name)["AccessKey"]
@mock_aws
def create_user_with_access_key_and_inline_policy( # type: ignore[misc]
user_name: str,
policy_document: dict[str, Any],
policy_name: str = "policy1",
region_name: str = "us-east-1",
) -> dict[str, str]:
client = boto3.client("iam", region_name=region_name)
client.create_user(UserName=user_name)
client.put_user_policy(
UserName=user_name,
PolicyName=policy_name,
PolicyDocument=json.dumps(policy_document),
)
return client.create_access_key(UserName=user_name)["AccessKey"]
@mock_aws
def create_user_with_access_key_and_attached_policy( # type: ignore[misc]
user_name: str, policy_document: dict[str, Any], policy_name: str = "policy1"
) -> dict[str, str]:
client = boto3.client("iam", region_name="us-east-1")
client.create_user(UserName=user_name)
policy_arn = client.create_policy(
PolicyName=policy_name, PolicyDocument=json.dumps(policy_document)
)["Policy"]["Arn"]
client.attach_user_policy(UserName=user_name, PolicyArn=policy_arn)
return client.create_access_key(UserName=user_name)["AccessKey"]
@mock_aws
def create_user_with_access_key_and_multiple_policies( # type: ignore[misc]
user_name: str,
inline_policy_document: dict[str, Any],
attached_policy_document: dict[str, Any],
inline_policy_name: str = "policy1",
attached_policy_name: str = "policy1",
) -> dict[str, str]:
client = boto3.client("iam", region_name="us-east-1")
client.create_user(UserName=user_name)
policy_arn = client.create_policy(
PolicyName=attached_policy_name,
PolicyDocument=json.dumps(attached_policy_document),
)["Policy"]["Arn"]
client.attach_user_policy(UserName=user_name, PolicyArn=policy_arn)
client.put_user_policy(
UserName=user_name,
PolicyName=inline_policy_name,
PolicyDocument=json.dumps(inline_policy_document),
)
return client.create_access_key(UserName=user_name)["AccessKey"]
def create_group_with_attached_policy_and_add_user(
user_name: str,
policy_document: dict[str, Any],
group_name: str = "test-group",
policy_name: Optional[str] = None,
) -> None:
if not policy_name:
policy_name = str(uuid4())
client = boto3.client("iam", region_name="us-east-1")
client.create_group(GroupName=group_name)
policy_arn = client.create_policy(
PolicyName=policy_name, PolicyDocument=json.dumps(policy_document)
)["Policy"]["Arn"]
client.attach_group_policy(GroupName=group_name, PolicyArn=policy_arn)
client.add_user_to_group(GroupName=group_name, UserName=user_name)
def create_group_with_inline_policy_and_add_user(
user_name: str,
policy_document: dict[str, Any],
group_name: str = "test-group",
policy_name: str = "policy1",
) -> None:
client = boto3.client("iam", region_name="us-east-1")
client.create_group(GroupName=group_name)
client.put_group_policy(
GroupName=group_name,
PolicyName=policy_name,
PolicyDocument=json.dumps(policy_document),
)
client.add_user_to_group(GroupName=group_name, UserName=user_name)
def create_group_with_multiple_policies_and_add_user(
user_name: str,
inline_policy_document: dict[str, Any],
attached_policy_document: dict[str, Any],
group_name: str = "test-group",
inline_policy_name: str = "policy1",
attached_policy_name: Optional[str] = None,
) -> None:
if not attached_policy_name:
attached_policy_name = str(uuid4())
client = boto3.client("iam", region_name="us-east-1")
client.create_group(GroupName=group_name)
client.put_group_policy(
GroupName=group_name,
PolicyName=inline_policy_name,
PolicyDocument=json.dumps(inline_policy_document),
)
policy_arn = client.create_policy(
PolicyName=attached_policy_name,
PolicyDocument=json.dumps(attached_policy_document),
)["Policy"]["Arn"]
client.attach_group_policy(GroupName=group_name, PolicyArn=policy_arn)
client.add_user_to_group(GroupName=group_name, UserName=user_name)
@mock_aws
def create_role_with_attached_policy_and_assume_it( # type: ignore[misc]
role_name: str,
trust_policy_document: dict[str, Any],
policy_document: dict[str, Any],
session_name: str = "session1",
policy_name: str = "policy1",
) -> dict[str, str]:
iam_client = boto3.client("iam", region_name="us-east-1")
sts_client = boto3.client("sts", region_name="us-east-1")
role_arn = iam_client.create_role(
RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy_document)
)["Role"]["Arn"]
policy_arn = iam_client.create_policy(
PolicyName=policy_name, PolicyDocument=json.dumps(policy_document)
)["Policy"]["Arn"]
iam_client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn)
return sts_client.assume_role(RoleArn=role_arn, RoleSessionName=session_name)[
"Credentials"
]
@mock_aws
def create_role_with_inline_policy_and_assume_it( # type: ignore[misc]
role_name: str,
trust_policy_document: dict[str, Any],
policy_document: dict[str, Any],
session_name: str = "session1",
policy_name: str = "policy1",
) -> dict[str, str]:
iam_client = boto3.client("iam", region_name="us-east-1")
sts_client = boto3.client("sts", region_name="us-east-1")
role_arn = iam_client.create_role(
RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy_document)
)["Role"]["Arn"]
iam_client.put_role_policy(
RoleName=role_name,
PolicyName=policy_name,
PolicyDocument=json.dumps(policy_document),
)
return sts_client.assume_role(RoleArn=role_arn, RoleSessionName=session_name)[
"Credentials"
]
@mock_aws
def create_role( # type: ignore[misc]
role_name: str,
trust_policy_document: dict[str, Any],
) -> None:
iam_client = boto3.client("iam", region_name="us-east-1")
iam_client.create_role(
RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy_document)
)
@mock_aws
def create_role_with_attached_policy( # type: ignore[misc]
role_name: str,
trust_policy_document: dict[str, Any],
policy_document: dict[str, Any],
policy_name: str = "policy1",
) -> None:
iam_client = boto3.client("iam", region_name="us-east-1")
create_role(role_name, trust_policy_document)
iam_client.put_role_policy(
RoleName=role_name,
PolicyName=policy_name,
PolicyDocument=json.dumps(policy_document),
)
@set_initial_no_auth_action_count(0)
@mock_aws
def test_invalid_client_token_id() -> None:
client = boto3.client(
"iam",
region_name="us-east-1",
aws_access_key_id="invalid",
aws_secret_access_key="invalid",
)
with pytest.raises(ClientError) as ex:
client.get_user()
err = ex.value.response["Error"]
assert err["Code"] == "InvalidClientTokenId"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert err["Message"] == "The security token included in the request is invalid."
@set_initial_no_auth_action_count(0)
@mock_aws
def test_auth_failure() -> None:
if LooseVersion(boto3_version) < LooseVersion("1.29.0"):
raise SkipTest("Error handling is different in newer versions")
client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id="invalid",
aws_secret_access_key="invalid",
)
with pytest.raises(ClientError) as ex:
client.describe_instances()
err = ex.value.response["Error"]
assert err["Code"] == "AuthFailure"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 401
assert (
err["Message"] == "AWS was not able to validate the provided access credentials"
)
@set_initial_no_auth_action_count(2)
@mock_aws
def test_signature_does_not_match() -> None:
access_key = create_user_with_access_key()
client = boto3.client(
"iam",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key="invalid",
)
with pytest.raises(ClientError) as ex:
client.get_user()
assert ex.value.response["Error"]["Code"] == "SignatureDoesNotMatch"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."
)
@set_initial_no_auth_action_count(2)
@mock_aws
def test_auth_failure_with_valid_access_key_id() -> None:
if LooseVersion(boto3_version) < LooseVersion("1.29.0"):
raise SkipTest("Error handling is different in newer versions")
access_key = create_user_with_access_key()
client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key="invalid",
)
with pytest.raises(ClientError) as ex:
client.describe_instances()
assert ex.value.response["Error"]["Code"] == "AuthFailure"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 401
assert (
ex.value.response["Error"]["Message"]
== "AWS was not able to validate the provided access credentials"
)
@set_initial_no_auth_action_count(2)
@mock_aws
def test_access_denied_with_no_policy() -> None:
if LooseVersion(boto3_version) < LooseVersion("1.29.0"):
raise SkipTest("Error handling is different in newer versions")
user_name = "test-user"
access_key = create_user_with_access_key(user_name)
client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.describe_instances()
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:iam::{ACCOUNT_ID}:user/{user_name} is not authorized to perform: ec2:DescribeInstances"
)
@set_initial_no_auth_action_count(3)
@mock_aws
def test_access_denied_with_not_allowing_policy() -> None:
if LooseVersion(boto3_version) < LooseVersion("1.29.0"):
raise SkipTest("Error handling is different in newer versions")
user_name = "test-user"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": ["ec2:Run*"], "Resource": "*"}],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.describe_instances()
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:iam::{ACCOUNT_ID}:user/{user_name} is not authorized to perform: ec2:DescribeInstances"
)
@set_initial_no_auth_action_count(3)
@mock_aws
def test_access_denied_explicitly_on_specific_resource() -> None:
user_name = "test-user"
forbidden_role_arn = f"arn:aws:iam::{ACCOUNT_ID}:role/forbidden_explicitly"
allowed_role_arn = f"arn:aws:iam::{ACCOUNT_ID}:role/allowed_implictly"
role_session_name = "dummy"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": ["sts:AssumeRole"],
"Resource": forbidden_role_arn,
},
{"Effect": "Allow", "Action": ["sts:AssumeRole"], "Resource": "*"},
],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
client = boto3.client(
"sts",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.assume_role(
RoleArn=forbidden_role_arn, RoleSessionName=role_session_name
)
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:iam::{ACCOUNT_ID}:user/{user_name} is not authorized to perform: sts:AssumeRole"
)
# Not raising means success
client.assume_role(RoleArn=allowed_role_arn, RoleSessionName=role_session_name)
@set_initial_no_auth_action_count(3)
@mock_aws
def test_access_denied_for_run_instances() -> None:
if LooseVersion(boto3_version) < LooseVersion("1.29.0"):
raise SkipTest("Error handling is different in newer versions")
# https://github.com/getmoto/moto/issues/2774
# The run-instances method was broken between botocore versions 1.15.8 and 1.15.12
# This was due to the inclusion of '"idempotencyToken":true' in the response, somehow altering the signature and breaking the authentication
# Keeping this test in place in case botocore decides to break again
user_name = "test-user"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["ec2:Describe*"], "Resource": "*"}
],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.run_instances(MaxCount=1, MinCount=1)
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:iam::{ACCOUNT_ID}:user/{user_name} is not authorized to perform: ec2:RunInstances"
)
@set_initial_no_auth_action_count(3)
@mock_aws
def test_access_denied_with_denying_policy() -> None:
if LooseVersion(boto3_version) < LooseVersion("1.29.0"):
raise SkipTest("Error handling is different in newer versions")
user_name = "test-user"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["ec2:*"], "Resource": "*"},
{"Effect": "Deny", "Action": "ec2:CreateVpc", "Resource": "*"},
],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.create_vpc(CidrBlock="10.0.0.0/16")
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:iam::{ACCOUNT_ID}:user/{user_name} is not authorized to perform: ec2:CreateVpc"
)
@set_initial_no_auth_action_count(3)
@mock_aws
def test_get_caller_identity_allowed_with_denying_policy() -> None:
user_name = "test-user"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [
{"Effect": "Deny", "Action": "sts:GetCallerIdentity", "Resource": "*"}
],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
client = boto3.client(
"sts",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
assert (
client.get_caller_identity()["Arn"]
== f"arn:aws:iam::{ACCOUNT_ID}:user/{user_name}"
)
@set_initial_no_auth_action_count(3)
@mock_aws
def test_allowed_with_wildcard_action() -> None:
user_name = "test-user"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "ec2:Describe*", "Resource": "*"}],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
assert client.describe_tags()["Tags"] == []
@set_initial_no_auth_action_count(4)
@mock_aws
def test_allowed_with_explicit_action_in_attached_policy() -> None:
user_name = "test-user"
attached_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "iam:ListGroups", "Resource": "*"}],
}
access_key = create_user_with_access_key_and_attached_policy(
user_name, attached_policy_document
)
client = boto3.client(
"iam",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
assert client.list_groups()["Groups"] == []
@set_initial_no_auth_action_count(8)
@mock_aws
def test_s3_access_denied_with_denying_attached_group_policy() -> None:
user_name = "test-user"
attached_policy_document = {
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": "s3:ListAllMyBuckets", "Resource": "*"}
],
}
group_attached_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Deny", "Action": "s3:List*", "Resource": "*"}],
}
access_key = create_user_with_access_key_and_attached_policy(
user_name, attached_policy_document, policy_name="policy1"
)
create_group_with_attached_policy_and_add_user(
user_name, group_attached_policy_document, policy_name="policy2"
)
client = boto3.client(
"s3",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.list_buckets()
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert ex.value.response["Error"]["Message"] == "Access Denied"
@set_initial_no_auth_action_count(6)
@mock_aws
def test_s3_access_denied_with_denying_inline_group_policy() -> None:
user_name = "test-user"
bucket_name = "test-bucket"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}],
}
group_inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Deny", "Action": "s3:GetObject", "Resource": "*"}],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
create_group_with_inline_policy_and_add_user(
user_name, group_inline_policy_document
)
client = boto3.client(
"s3",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
client.create_bucket(Bucket=bucket_name)
with pytest.raises(ClientError) as ex:
client.get_object(Bucket=bucket_name, Key="sdfsdf")
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert ex.value.response["Error"]["Message"] == "Access Denied"
@set_initial_no_auth_action_count(10)
@mock_aws
def test_access_denied_with_many_irrelevant_policies() -> None:
if LooseVersion(boto3_version) < LooseVersion("1.29.0"):
raise SkipTest("Error handling is different in newer versions")
user_name = "test-user"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "ec2:Describe*", "Resource": "*"}],
}
attached_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}],
}
group_inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Deny", "Action": "iam:List*", "Resource": "*"}],
}
group_attached_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Deny", "Action": "lambda:*", "Resource": "*"}],
}
access_key = create_user_with_access_key_and_multiple_policies(
user_name,
inline_policy_document,
attached_policy_document,
attached_policy_name="policy1",
)
create_group_with_multiple_policies_and_add_user(
user_name,
group_inline_policy_document,
group_attached_policy_document,
attached_policy_name="policy2",
)
client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.create_key_pair(KeyName="TestKey")
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:iam::{ACCOUNT_ID}:user/{user_name} is not authorized to perform: ec2:CreateKeyPair"
)
@set_initial_no_auth_action_count(4)
@mock_aws
def test_allowed_with_temporary_credentials() -> None:
role_name = "test-role"
trust_policy_document = {
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": {"AWS": f"arn:aws:iam::{ACCOUNT_ID}:root"},
"Action": "sts:AssumeRole",
},
}
attached_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"elasticloadbalancing:CreateLoadBalancer",
"ec2:DescribeSubnets",
],
"Resource": "*",
}
],
}
credentials = create_role_with_attached_policy_and_assume_it(
role_name, trust_policy_document, attached_policy_document
)
elbv2_client = boto3.client(
"elbv2",
region_name="us-east-1",
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
ec2_client = boto3.client(
"ec2",
region_name="us-east-1",
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
subnets = ec2_client.describe_subnets()["Subnets"]
assert len(subnets) > 1
subnet_ids = [subnets[0]["SubnetId"], subnets[1]["SubnetId"]]
resp = elbv2_client.create_load_balancer(Name="lb", Subnets=subnet_ids)
assert len(resp["LoadBalancers"]) == 1
@set_initial_no_auth_action_count(3)
@mock_aws
def test_access_denied_with_temporary_credentials() -> None:
role_name = "test-role"
session_name = "test-session"
trust_policy_document = {
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": {"AWS": f"arn:aws:iam::{ACCOUNT_ID}:root"},
"Action": "sts:AssumeRole",
},
}
attached_policy_document = {
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["rds:Describe*"], "Resource": "*"}
],
}
credentials = create_role_with_inline_policy_and_assume_it(
role_name, trust_policy_document, attached_policy_document, session_name
)
client = boto3.client(
"rds",
region_name="us-east-1",
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
with pytest.raises(ClientError) as ex:
client.create_db_instance(
DBInstanceIdentifier="test-db-instance",
DBInstanceClass="db.t3",
Engine="aurora-postgresql",
)
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:sts::{ACCOUNT_ID}:assumed-role/{role_name}/{session_name} is not authorized to perform: rds:CreateDBInstance"
)
@set_initial_no_auth_action_count(3)
@mock_aws
def test_get_user_from_credentials() -> None:
user_name = "new-test-user"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "iam:*", "Resource": "*"}],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
client = boto3.client(
"iam",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
assert client.get_user()["User"]["UserName"] == user_name
@set_initial_no_auth_action_count(0)
@mock_aws
def test_s3_invalid_access_key_id() -> None:
client = boto3.client(
"s3",
region_name="us-east-1",
aws_access_key_id="invalid",
aws_secret_access_key="invalid",
)
with pytest.raises(ClientError) as ex:
client.list_buckets()
assert ex.value.response["Error"]["Code"] == "InvalidAccessKeyId"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== "The AWS Access Key Id you provided does not exist in our records."
)
@set_initial_no_auth_action_count(3)
@mock_aws
def test_s3_signature_does_not_match() -> None:
bucket_name = "test-bucket"
access_key = create_user_with_access_key()
client = boto3.client(
"s3",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key="invalid",
)
client.create_bucket(Bucket=bucket_name)
with pytest.raises(ClientError) as ex:
client.put_object(Bucket=bucket_name, Key="abc")
assert ex.value.response["Error"]["Code"] == "SignatureDoesNotMatch"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== "The request signature we calculated does not match the signature you provided. Check your key and signing method."
)
@set_initial_no_auth_action_count(7)
@mock_aws
def test_s3_access_denied_not_action() -> None:
user_name = "test-user"
bucket_name = "test-bucket"
inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}],
}
group_inline_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Deny", "NotAction": "iam:GetUser", "Resource": "*"}],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, inline_policy_document
)
create_group_with_inline_policy_and_add_user(
user_name, group_inline_policy_document
)
client = boto3.client(
"s3",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
client.create_bucket(Bucket=bucket_name)
with pytest.raises(ClientError) as ex:
client.delete_object(Bucket=bucket_name, Key="sdfsdf")
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert ex.value.response["Error"]["Message"] == "Access Denied"
@set_initial_no_auth_action_count(4)
@mock_aws
def test_s3_invalid_token_with_temporary_credentials() -> None:
role_name = "test-role"
session_name = "test-session"
bucket_name = "test-bucket-888"
trust_policy_document = {
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": {"AWS": f"arn:aws:iam::{ACCOUNT_ID}:root"},
"Action": "sts:AssumeRole",
},
}
attached_policy_document = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": ["*"], "Resource": "*"}],
}
credentials = create_role_with_inline_policy_and_assume_it(
role_name, trust_policy_document, attached_policy_document, session_name
)
client = boto3.client(
"s3",
region_name="us-east-1",
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token="invalid",
)
client.create_bucket(Bucket=bucket_name)
with pytest.raises(ClientError) as ex:
client.list_bucket_metrics_configurations(Bucket=bucket_name)
err = ex.value.response["Error"]
assert err["Code"] == "InvalidToken"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
assert err["Message"] == "The provided token is malformed or otherwise invalid."
@set_initial_no_auth_action_count(3)
@mock_aws
@pytest.mark.parametrize(
"region,partition", [("us-west-2", "aws"), ("cn-north-1", "aws-cn")]
)
def test_allow_bucket_access_using_resource_arn(region: str, partition: str) -> None:
user_name = "test-user"
policy_doc = {
"Version": "2012-10-17",
"Statement": [
{
"Action": ["s3:*"],
"Effect": "Allow",
"Resource": f"arn:{partition}:s3:::my_bucket",
"Sid": "BucketLevelGrants",
},
],
}
access_key = create_user_with_access_key_and_inline_policy(
user_name, policy_doc, region_name=region
)
s3_client = boto3.client(
"s3",
region_name=region,
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
s3_client.create_bucket(
Bucket="my_bucket", CreateBucketConfiguration={"LocationConstraint": region}
)
with pytest.raises(ClientError):
s3_client.create_bucket(Bucket="my_bucket2")
s3_client.head_bucket(Bucket="my_bucket")
with pytest.raises(ClientError):
s3_client.head_bucket(Bucket="my_bucket2")
@set_initial_no_auth_action_count(3)
@mock_aws
def test_allow_key_access_using_resource_arn() -> None:
user_name = "test-user"
policy_doc = {
"Version": "2012-10-17",
"Statement": [
{
"Action": ["s3:*"],
"Effect": "Allow",
"Resource": ["arn:aws:s3:::my_bucket", "arn:aws:s3:::*/keyname"],
"Sid": "KeyLevelGrants",
},
],
}
access_key = create_user_with_access_key_and_inline_policy(user_name, policy_doc)
s3_client = boto3.client(
"s3",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
s3_client.create_bucket(Bucket="my_bucket")
s3_client.put_object(Bucket="my_bucket", Key="keyname", Body=b"test")
with pytest.raises(ClientError):
s3_client.put_object(Bucket="my_bucket", Key="unknown", Body=b"test")
@set_initial_no_auth_action_count(3)
@mock_aws
def test_ssm_service() -> None:
user_name = "test-user"
policy_doc = {
"Version": "2012-10-17",
"Statement": [{"Action": ["ssm:*"], "Effect": "Allow", "Resource": ["*"]}],
}
access_key = create_user_with_access_key_and_inline_policy(user_name, policy_doc)
ssmc = boto3.client(
"ssm",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)
ssmc.put_parameter(Name="test", Value="value", Type="String")
@set_initial_no_auth_action_count(4)
@mock_aws
def test_sts_assume_role_with_external_id() -> None:
user_name = "test-user"
role_name = "test-role"
user_policy_doc = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
}
],
}
user_access_keys = create_user_with_access_key_and_inline_policy(
user_name, user_policy_doc
)
external_id = "test-external-id"
incorrect_external_id = "test-incorrect-external-id"
trust_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Principal": {
"AWS": f"arn:aws:iam::{ACCOUNT_ID}:user/{user_name}",
},
"Condition": {
"StringEquals": {
"sts:ExternalId": external_id,
},
},
},
],
}
create_role(role_name, trust_policy_document)
client = boto3.client(
"sts",
region_name="us-east-1",
aws_access_key_id=user_access_keys["AccessKeyId"],
aws_secret_access_key=user_access_keys["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.assume_role(
RoleArn=f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
RoleSessionName="test-session",
ExternalId=incorrect_external_id,
)
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:iam::{ACCOUNT_ID}:user/{user_name} is not authorized to perform: sts:AssumeRole"
)
# Not raising means success
client.assume_role(
RoleArn=f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
RoleSessionName="test-session",
ExternalId=external_id,
)
@set_initial_no_auth_action_count(7)
@mock_aws
def test_sts_assume_role_with_principal() -> None:
user_name = "test-user"
incorrect_user_name = "test-incorrect-user"
role_name = "test-role"
user_policy_doc = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
}
],
}
user_access_keys = create_user_with_access_key_and_inline_policy(
user_name, user_policy_doc, policy_name="policy-1"
)
incorrect_user_access_keys = create_user_with_access_key_and_inline_policy(
incorrect_user_name, user_policy_doc, policy_name="policy-2"
)
trust_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Principal": {
"AWS": f"arn:aws:iam::{ACCOUNT_ID}:user/{user_name}",
},
},
],
}
create_role(role_name, trust_policy_document)
client = boto3.client(
"sts",
region_name="us-east-1",
aws_access_key_id=incorrect_user_access_keys["AccessKeyId"],
aws_secret_access_key=incorrect_user_access_keys["SecretAccessKey"],
)
with pytest.raises(ClientError) as ex:
client.assume_role(
RoleArn=f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
RoleSessionName="test-session",
)
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:iam::{ACCOUNT_ID}:user/{incorrect_user_name} is not authorized to perform: sts:AssumeRole"
)
# Not raising means success
client = boto3.client(
"sts",
region_name="us-east-1",
aws_access_key_id=user_access_keys["AccessKeyId"],
aws_secret_access_key=user_access_keys["SecretAccessKey"],
)
client.assume_role(
RoleArn=f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
RoleSessionName="test-session",
)
@set_initial_no_auth_action_count(6)
@mock_aws
def test_perform_role_based_action() -> None:
user_name = "test-user"
role_name = "test-role"
incorrect_role_name = "test-incorrect-role"
user_policy_doc = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": [
f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
f"arn:aws:iam::{ACCOUNT_ID}:role/{incorrect_role_name}",
],
}
],
}
user_access_keys = create_user_with_access_key_and_inline_policy(
user_name, user_policy_doc
)
trust_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Principal": {
"AWS": f"arn:aws:iam::{ACCOUNT_ID}:user/{user_name}",
},
},
],
}
attached_policy_name = "test-attached-policy"
attached_policy_doc = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iam:ListRolePolicies",
"Resource": f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
}
],
}
create_role(incorrect_role_name, trust_policy_document)
create_role_with_attached_policy(
role_name, trust_policy_document, attached_policy_doc, attached_policy_name
)
client = boto3.client(
"sts",
region_name="us-east-1",
aws_access_key_id=user_access_keys["AccessKeyId"],
aws_secret_access_key=user_access_keys["SecretAccessKey"],
)
session_name = "test-session"
assumed_role_credentials = client.assume_role(
RoleArn=f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
RoleSessionName=session_name,
)["Credentials"]
iam_client = boto3.client(
"iam",
region_name="us-east-1",
aws_access_key_id=assumed_role_credentials["AccessKeyId"],
aws_secret_access_key=assumed_role_credentials["SecretAccessKey"],
aws_session_token=assumed_role_credentials["SessionToken"],
)
with pytest.raises(ClientError) as ex:
iam_client.list_role_policies(RoleName=incorrect_role_name)
assert ex.value.response["Error"]["Code"] == "AccessDenied"
assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
assert (
ex.value.response["Error"]["Message"]
== f"User: arn:aws:sts::{ACCOUNT_ID}:assumed-role/{role_name}/{session_name} is not authorized to perform: iam:ListRolePolicies"
)
assert (
attached_policy_name
in iam_client.list_role_policies(RoleName=role_name)["PolicyNames"]
)
@set_initial_no_auth_action_count(4)
@mock_aws
def test_sts_assume_role_with_external_id_unsupported_operation_should_supress_error() -> (
None
):
user_name = "test-user"
role_name = "test-role"
user_policy_doc = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
}
],
}
user_access_keys = create_user_with_access_key_and_inline_policy(
user_name, user_policy_doc
)
external_id = "test-external-id"
trust_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Principal": {
"AWS": f"arn:aws:iam::{ACCOUNT_ID}:user/{user_name}",
},
"Condition": {
"UnsupportedOperation": {
"sts:ExternalId": external_id,
},
},
},
],
}
create_role(role_name, trust_policy_document)
client = boto3.client(
"sts",
region_name="us-east-1",
aws_access_key_id=user_access_keys["AccessKeyId"],
aws_secret_access_key=user_access_keys["SecretAccessKey"],
)
# Not raising means success
client.assume_role(
RoleArn=f"arn:aws:iam::{ACCOUNT_ID}:role/{role_name}",
RoleSessionName="test-session",
ExternalId=external_id,
)
|