"""Test token model.""" from typing import Any from unittest.mock import MagicMock import pytest from botocore.exceptions import ClientError from assets import config from assets.models import token @pytest.fixture def fixture_set_iam_role() -> None: """Fixture to set IAM role.""" config.IAM_ROLE = "arn:aws:iam::11111111111:role/ows-assets-service-role" @pytest.fixture def fixture_filename() -> str: """Fixture to generate a filename.""" return "a_filename" @pytest.fixture def fixture_duration() -> int: """Fixture to duration.""" return 1000 @pytest.fixture def fixture_assume_role_error() -> MagicMock: """Fixture for an STS ClientError.""" sts_error = { "Error": {"Code": "AccessDeniedException", "Message": "Error assuming role"}, "ResponseMetadata": {"HTTPStatusCode": 403}, } return MagicMock( side_effect=ClientError(error_response=sts_error, operation_name="AssumeRole") # type: ignore[arg-type] ) @pytest.fixture def fixture_token_dict() -> dict[str, str]: """Fixture for a token.""" return { "token": "a token", "aws_access_key_id": "access key", "aws_secret_access_key": "secret key", "expiration": "today", } def fixture_policy(bucket: str, filename: str) -> dict[str, Any]: """Fixture for iam policy for s3. Args: bucket (string): name of bucket. filename (string): name of filename. Returns: dict: Expected structure of iam policy for s3. """ return { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:PutObject"], "Resource": "arn:aws:s3:::{bucket}/{filename}.*".format( bucket=bucket, filename=filename ), } ], } def test__to_dict() -> None: """Test converting an aws credential object.""" session_token = "a session token" access_key = "access" secret_key = "shhhhh" expiration = "in 900 seconds" sts_response = { "Credentials": { "SessionToken": session_token, "AccessKeyId": access_key, "SecretAccessKey": secret_key, "Expiration": expiration, } } result = token._to_dict(sts_response) # type: ignore[arg-type] assert result.get("token") == session_token assert result.get("aws_access_key_id") == access_key assert result.get("aws_secret_access_key") == secret_key assert result.get("expiration") == expiration def test__prepare_iam_policy_s3(monkeypatch: pytest.MonkeyPatch) -> None: """Test iam policy for s3 uses bucket name and filename.""" expected = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:PutObject"], "Resource": "arn:aws:s3:::bucket/filename.*", } ], } result = token._prepare_iam_policy_s3("bucket", "filename") assert result == expected def test_prepare_iam_policy_s3_entity( fixture_filename: str, fixture_is_valid_path: dict[str, str] ) -> None: """Test iam policy for s3 uses bucket name and folder.""" result = token._prepare_iam_policy_s3_entity( "bucket", fixture_is_valid_path, fixture_filename ) assert "Resource" in result["Statement"][0]