From eb79d064e88af4b6cc294b14313df569e2642e07 Mon Sep 17 00:00:00 2001 From: Bert Blommers Date: Sat, 18 Feb 2023 09:48:02 -0100 Subject: [PATCH] IAM: get_user() should return PasswordLastUsed-field if set (#5942) --- moto/iam/models.py | 7 ++++ moto/iam/responses.py | 3 ++ tests/test_iam/test_iam_password_last_used.py | 37 +++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 tests/test_iam/test_iam_password_last_used.py diff --git a/moto/iam/models.py b/moto/iam/models.py index 602d5ae8b..31554d683 100644 --- a/moto/iam/models.py +++ b/moto/iam/models.py @@ -1181,6 +1181,13 @@ class User(CloudFormationModel): def created_iso_8601(self): return iso_8601_datetime_with_milliseconds(self.create_date) + @property + def password_last_used_iso_8601(self): + if self.password_last_used is not None: + return iso_8601_datetime_with_milliseconds(self.password_last_used) + else: + return None + def get_policy(self, policy_name): policy_json = None try: diff --git a/moto/iam/responses.py b/moto/iam/responses.py index 06f2fa1e7..3a75e0367 100644 --- a/moto/iam/responses.py +++ b/moto/iam/responses.py @@ -1805,6 +1805,9 @@ USER_TEMPLATE = """<{{ action }}UserResponse> {{ user.id }} {{ user.created_iso_8601 }} {{ user.arn }} + {% if user.password_last_used_iso_8601 %} + {{ user.password_last_used_iso_8601 }} + {% endif %} {% if tags %} {% for tag in tags %} diff --git a/tests/test_iam/test_iam_password_last_used.py b/tests/test_iam/test_iam_password_last_used.py new file mode 100644 index 000000000..045cc7f27 --- /dev/null +++ b/tests/test_iam/test_iam_password_last_used.py @@ -0,0 +1,37 @@ +import boto3 +from datetime import datetime +from moto import mock_iam, settings +from moto.backends import get_backend +from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID +from unittest import SkipTest + + +@mock_iam +def test_password_last_used(): + if settings.TEST_SERVER_MODE: + raise SkipTest("Can't set password_last_used in ServerMode") + client = boto3.client("iam", "us-east-1") + username = "test.user" + client.create_user(Path="/staff/", UserName=username)["User"] + client.create_login_profile( + UserName=username, Password="Password1", PasswordResetRequired=False + ) + + access_key = client.create_access_key(UserName=username)["AccessKey"] + + as_new_user = boto3.resource( + "iam", + region_name="us-east-1", + aws_access_key_id=access_key["AccessKeyId"], + aws_secret_access_key=access_key["SecretAccessKey"], + ) + + # Username is set, but password not yet + assert as_new_user.CurrentUser().user_name == username + assert not as_new_user.CurrentUser().password_last_used + + iam_backend = get_backend("iam")[ACCOUNT_ID]["global"] + iam_backend.users[username].password_last_used = datetime.utcnow() + + # Password is returned now + assert as_new_user.CurrentUser().password_last_used