Skip to content
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

Fix KeyError Action #8063

Closed
wants to merge 1 commit into from
Closed

Fix KeyError Action #8063

wants to merge 1 commit into from

Conversation

manycoding
Copy link

Fixes such case

@set_initial_no_auth_action_count(0)
def test_lambda_request_unauthorized_user(mocker, aws_lambda):
    mocker.patch(
        "moto.awslambda.responses.LambdaResponse.invoke",
        return_value=(403, {}, '{"message": "No access"}'),
    )
    with pytest.raises(exceptions.ClientError):
        lambda_with_unauthorized_user().request(
            function_name=LAMBDA_FUNCTION,
            payload={"parameter": "value"},
        )

@pytest.fixture(scope="function")
def aws_lambda(iam_user, aws_lambda_role, aws_lambda_bucket):
    with mock_aws(config={"lambda": {"use_docker": True}}):
        lmb = boto3.client(service_name="lambda", region_name=REGION)
        lmb.create_function(
            FunctionName=LAMBDA_FUNCTION,
            Runtime=LAMBDA_PYTHON_RUNTIME,
            Role=aws_lambda_role["Role"]["Arn"],
            Handler="aws_lambda_function.aws_lambda_handler",
            Code={"S3Bucket": LAMBDA_BUCKET, "S3Key": "test.zip"},
            Description="test aws-lambda-function",
            Timeout=1,
            MemorySize=128,
            PackageType="ZIP",
            Publish=True,
            VpcConfig={"SecurityGroupIds": ["sg-123abc"], "SubnetIds": ["subnet-123abc"]},
        )

        yield lmb

@bblommers
Copy link
Collaborator

Hi @manycoding, I'm struggling to see the relation between the test case that you've added and the fix.

Can you add an MRE (Minimum Reproducible Example) to show the problem?

@manycoding
Copy link
Author

It's not that easy, but I solve this one:

    action_from_request = self._action_from_request()
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "tox/py311/lib/python3.11/site-packages/moto/iam/access_control.py", line 246, in _action_from_request
    return self._data["Action"]
           ~~~~~~~~~~^^^^^^^^^^
KeyError: 'Action'

For some reason Action doesn't exist.

@manycoding
Copy link
Author

manycoding commented Sep 2, 2024


import boto3


@pytest.fixture(scope="function")
def iam_user_no_access_v2():
    with moto.mock_aws():
        iam_v2 = boto3.client("iam", region_name="us-west-2")
        user_name = "test-user-2"
        policy_name = "policy2"
        iam_v2.create_user(UserName=user_name)
        policy_document = {
            "Version": "2012-10-17",
            "Statement": {
                "Effect": "Deny",
                "Action": ["s3:*", "secretsmanager:*", "lambda:*"],
                "Resource": "*",
            },
        }
        policy_arn = iam_v2.create_policy(
            PolicyName=policy_name, PolicyDocument=json.dumps(policy_document)
        )["Policy"]["Arn"]
        iam_v2.attach_user_policy(UserName=user_name, PolicyArn=policy_arn)
        access_key = iam_v2.create_access_key(UserName=user_name)["AccessKey"]

        yield access_key


@set_initial_no_auth_action_count(0)
def test_lambda_request_unauthorized_user_v2(iam_user_no_access_v2):
    with moto.mock_aws():
        session = boto3.session.Session(
            aws_access_key_id=iam_user_no_access_v2["AccessKeyId"],
            aws_secret_access_key=iam_user_no_access_v2["SecretAccessKey"],
            region_name="us-west-2",
        )
        _lambda_client = session.client(service_name="lambda")

        with pytest.raises(exceptions.ClientError):
            _lambda_client.invoke(
                FunctionName="aws-lambda-function",
                Payload=json.dumps({}),
            )

@bblommers
Copy link
Collaborator

Ah, I understand what's going wrong - thank you for posting the MRE @manycoding.

The Action is required here though. It works in your case, because the policy denies access to lambda:* - but if someone only wants to deny access to lambda:Invoke, we need to know exactly which action was invoked before we decide whether we should deny or approve access.

I've opened PR #8084 to implement this properly for AWSLambda, so this should now be fixed as of moto >= 5.0.14.dev61.

Please let us know if you run into any other issues.

@bblommers bblommers closed this Sep 4, 2024
@manycoding manycoding deleted the patch-1 branch September 9, 2024 16:13
@manycoding
Copy link
Author

yep that fixes it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants