Skip to content

Commit

Permalink
Core: Support auth calls for AWSLambda
Browse files Browse the repository at this point in the history
  • Loading branch information
bblommers committed Sep 4, 2024
1 parent 2519843 commit 3d4d4c4
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 14 deletions.
5 changes: 4 additions & 1 deletion moto/core/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ def _authenticate_and_authorize_action(
data=self.data, # type: ignore[attr-defined]
body=self.body, # type: ignore[attr-defined]
headers=self.headers, # type: ignore[attr-defined]
action=self._get_action(), # type: ignore[attr-defined]
)
iam_request.check_signature()
iam_request.check_action_permitted(resource)
Expand Down Expand Up @@ -552,7 +553,9 @@ def _get_action_from_method_and_request_uri(
return None # type: ignore[return-value]

def _get_action(self) -> str:
action = self.querystring.get("Action", [""])[0]
action = self.querystring.get("Action")
if action and isinstance(action, list):
action = action[0]
if action:
return action
# Some services use a header for the action
Expand Down
15 changes: 2 additions & 13 deletions moto/iam/access_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ def __init__(
data: Dict[str, str],
body: bytes,
headers: Dict[str, str],
action: str,
):
log.debug(
f"Creating {self.__class__.__name__} with method={method}, path={path}, data={data}, headers={headers}"
Expand All @@ -220,15 +221,8 @@ def __init__(
credential_data = credential_scope.split("/")
self._region = credential_data[2]
self._service = credential_data[3]
action_from_request = self._action_from_request()
self._action = (
self._service
+ ":"
+ (
action_from_request[0]
if isinstance(action_from_request, list)
else action_from_request
)
f"{self._service}:{action[0] if isinstance(action, list) else action}"
)
try:
self._access_key = create_access_key(
Expand All @@ -240,11 +234,6 @@ def __init__(
except CreateAccessKeyFailure as e:
self._raise_invalid_access_key(e.reason)

def _action_from_request(self) -> str:
if "X-Amz-Target" in self._headers:
return self._headers["X-Amz-Target"].split(".")[-1]
return self._data["Action"]

def check_signature(self) -> None:
original_signature = self._get_string_between(
"Signature=", ",", self._headers["Authorization"]
Expand Down
34 changes: 34 additions & 0 deletions tests/test_awslambda/test_lambda_invoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from botocore.exceptions import ClientError

from moto import mock_aws, settings
from moto.core import set_initial_no_auth_action_count

from ..markers import requires_docker
from .test_lambda import LooseVersion, boto3_version
Expand Down Expand Up @@ -418,3 +419,36 @@ def test_invoke_lambda_with_entrypoint():
payload = result["Payload"].read().decode("utf-8")

assert json.loads(payload) == in_data


@set_initial_no_auth_action_count(4)
@mock_aws
def test_lambda_request_unauthorized_user():
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Auth decorator does not work in server mode")
iam = boto3.client("iam", region_name="us-west-2")
user_name = "test-user"
iam.create_user(UserName=user_name)
policy_document = {
"Version": "2012-10-17",
"Statement": {
"Effect": "Deny",
"Action": ["s3:*", "secretsmanager:*", "lambda:*"],
"Resource": "*",
},
}
policy_arn = iam.create_policy(
PolicyName="policy2", PolicyDocument=json.dumps(policy_document)
)["Policy"]["Arn"]
iam.attach_user_policy(UserName=user_name, PolicyArn=policy_arn)
access_key = iam.create_access_key(UserName=user_name)["AccessKey"]

_lambda = boto3.session.Session(
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
region_name="us-west-2",
).client(service_name="lambda")

with pytest.raises(ClientError) as exc:
_lambda.invoke(FunctionName="n/a", Payload="{}")
assert "not authorized to perform: lambda:Invoke" in str(exc.value)

0 comments on commit 3d4d4c4

Please sign in to comment.