"""Lambda ioc sanitize test module.""" import boto3 import pytest from unittest.mock import mock_open from unittest.mock import patch from moto import mock_aws import config from src import app @pytest.fixture def mock_boto3_client(): """Mock boto3 client fixture.""" with patch('boto3.client') as mock_client: yield mock_client @pytest.fixture def mock_open_file(): """Mock open file fixture.""" with patch( 'builtins.open', mock_open(read_data='192.168.0.1\nexample.com\nEXAMPLE.COM\ninvalid_domain\n'), ) as mock_file: yield mock_file @pytest.fixture def mock_s3(): with mock_aws(): yield boto3.client('s3', region_name='us-east-1') @pytest.fixture def mock_bucket(mock_s3): mock_s3.create_bucket(Bucket=config.GSIRT_S3_DROP_BUCKET) mock_s3.put_object( Bucket=config.GSIRT_S3_DROP_BUCKET, Key=f'{config.GSIRT_S3_DROP_FOLDER}/{config.GSIRT_S3_DROP_DOMAIN_FILE}', Body='example1.com\nexample2.com\n', ) mock_s3.put_object( Bucket=config.GSIRT_S3_DROP_BUCKET, Key=f'{config.GSIRT_S3_DROP_FOLDER}/{config.GSIRT_S3_DROP_IP_FILE}', Body='192.168.0.1\n192.168.0.2\n', ) yield mock_s3 def test_remove_ip_with_from_domains(): """Test find and remove IP with CIDR.""" lines = ['192.168.0.1', 'example.com', '10.0.0.0/8'] result = app.remove_ip_with_from_domains(lines) assert result == ['example.com'] def test_remove_duplicate_lines(): """Test remove duplicate lines.""" lines = ['example.com', 'EXAMPLE.COM', 'another.com'] result = app.remove_duplicate_lines(lines) assert sorted(result) == sorted(['example.com', 'another.com']) def test_handler_success(mock_bucket): app.handler({}, None) firewall_blocks = mock_bucket.get_object( Bucket=config.GSIRT_S3_DROP_BUCKET, Key=f'{config.GSIRT_S3_SANITIZED_FOLDER}/sanitized_ioc_dns_firewall_blocks.txt', ) assert ( firewall_blocks['Body'].read().decode('utf8') == 'example1.com\n*.example1.com\nexample2.com\n*.example2.com\n' ) palo_domain_blocks = mock_bucket.get_object( Bucket=config.GSIRT_S3_DROP_BUCKET, Key=f'{config.GSIRT_S3_SANITIZED_FOLDER}/palo_domain_blocks.txt', ) assert ( palo_domain_blocks['Body'].read().decode('utf8') == '*.example1.com\n*.example2.com\n' ) palo_url_blocks = mock_bucket.get_object( Bucket=config.GSIRT_S3_DROP_BUCKET, Key=f'{config.GSIRT_S3_SANITIZED_FOLDER}/palo_url_blocks.txt', ) assert ( palo_url_blocks['Body'].read().decode('utf8') == '*.example1.com/*\n*.example2.com/*\n' ) ipv4_blocks = mock_bucket.get_object( Bucket=config.GSIRT_S3_DROP_BUCKET, Key=f'{config.GSIRT_S3_SANITIZED_FOLDER}/ip_blocks.txt', ) assert ( ipv4_blocks['Body'].read().decode('utf8') == '192.168.0.1/32\n192.168.0.2/32\n' )