Exemplo n.º 1
0
class TestTaggingService(unittest.TestCase):
    svc = TaggingService()

    def test_list_empty(self):
        result = self.svc.list_tags_for_resource("test")
        self.assertEqual({"Tags": []}, result)

    def test_create_tag(self):
        tags = [{"Key": "key_key", "Value": "value_value"}]
        self.svc.tag_resource("arn", tags)
        actual = self.svc.list_tags_for_resource("arn")
        expected = {"Tags": [{"Key": "key_key", "Value": "value_value"}]}
        self.assertDictEqual(expected, actual)

    def test_delete_tag(self):
        tags = [{"Key": "key_key", "Value": "value_value"}]
        self.svc.tag_resource("arn", tags)
        self.svc.untag_resource("arn", ["key_key"])
        result = self.svc.list_tags_for_resource("arn")
        self.assertEqual({"Tags": []}, result)

    def test_list_empty_delete(self):
        self.svc.untag_resource("arn", ["key_key"])
        result = self.svc.list_tags_for_resource("arn")
        self.assertEqual({"Tags": []}, result)
Exemplo n.º 2
0
class TestTaggingService(unittest.TestCase):
    svc = TaggingService()

    def test_list_empty(self):
        result = self.svc.list_tags_for_resource('test')
        self.assertEqual({'Tags': []}, result)

    def test_create_tag(self):
        tags = [{'Key': 'key_key', 'Value': 'value_value'}]
        self.svc.tag_resource('arn', tags)
        actual = self.svc.list_tags_for_resource('arn')
        expected = {'Tags': [{'Key': 'key_key', 'Value': 'value_value'}]}
        self.assertDictEqual(expected, actual)

    def test_delete_tag(self):
        tags = [{'Key': 'key_key', 'Value': 'value_value'}]
        self.svc.tag_resource('arn', tags)
        self.svc.untag_resource('arn', ['key_key'])
        result = self.svc.list_tags_for_resource('arn')
        self.assertEqual({'Tags': []}, result)

    def test_list_empty_delete(self):
        self.svc.untag_resource('arn', ['key_key'])
        result = self.svc.list_tags_for_resource('arn')
        self.assertEqual({'Tags': []}, result)
Exemplo n.º 3
0
class OpenSearchServiceBackend(RegionBackend):
    # storage for domain resources (access should be protected with the _domain_mutex)
    opensearch_domains: Dict[str, DomainStatus]
    # static tagging service instance
    TAGS = TaggingService()

    def __init__(self):
        self.opensearch_domains = {}
Exemplo n.º 4
0
class FirehoseBackend(RegionBackend):
    # maps delivery stream names to DeliveryStreamDescription
    delivery_streams: Dict[str, DeliveryStreamDescription]
    # static tagging service instance
    TAGS = TaggingService()

    def __init__(self):
        self.delivery_streams = {}
Exemplo n.º 5
0
class ElasticsearchServiceBackend(RegionBackend):
    # maps cluster names to cluster details
    es_clusters: Dict[str, ProxiedElasticsearchCluster]
    # storage for domain resources (access should be protected with the _domain_mutex)
    es_domains: Dict[str, Dict]
    # static tagging service instance
    TAGS = TaggingService()

    def __init__(self):
        self.es_clusters = {}
        self.es_domains = {}
Exemplo n.º 6
0
class ProxyListenerEvents(ProxyListener):
    svc = TaggingService()

    def forward_request(self, method, path, data, headers):
        if method == 'OPTIONS':
            return 200

        action = headers.get('X-Amz-Target')
        if method == 'POST' and path == '/':
            parsed_data = json.loads(to_str(data))

            if action == 'AWSEvents.PutRule':
                return handle_put_rule(parsed_data)

            elif action == 'AWSEvents.DeleteRule':
                handle_delete_rule(rule_name=parsed_data.get('Name', None))

            elif action == 'AWSEvents.ListTagsForResource':
                return self.svc.list_tags_for_resource(
                    parsed_data['ResourceARN']) or {}

            elif action == 'AWSEvents.TagResource':
                self.svc.tag_resource(parsed_data['ResourceARN'],
                                      parsed_data['Tags'])
                return {}

            elif action == 'AWSEvents.UntagResource':
                self.svc.untag_resource(parsed_data['ResourceARN'],
                                        parsed_data['TagKeys'])
                return {}

            elif action == 'AWSEvents.DisableRule':
                handle_disable_rule(rule_name=parsed_data.get('Name', None))

        return True

    def return_response(self,
                        method,
                        path,
                        data,
                        headers,
                        response,
                        request_handler=None):
        if response.content:
            # fix hardcoded account ID in ARNs returned from this API
            fix_account_id(response)

            # fix dates returned from this API (fixes an issue with Terraform)
            fix_date_format(response)

            # fix Content-Length header
            response.headers['Content-Length'] = len(response._content)
Exemplo n.º 7
0
class ProxyListenerEvents(ProxyListener):
    svc = TaggingService()

    def forward_request(self, method, path, data, headers):
        if method == "OPTIONS":
            return 200

        if method == "POST" and path == "/":
            action = headers.get("X-Amz-Target", "").split(".")[-1]
            parsed_data = json.loads(to_str(data))

            if action == "PutRule":
                return handle_put_rule(parsed_data)

            elif action == "DeleteRule":
                handle_delete_rule(rule_name=parsed_data.get("Name", None))

            elif action == "DisableRule":
                handle_disable_rule(rule_name=parsed_data.get("Name", None))

            elif action == "PutEvents":
                # keep track of events for local integration testing
                if os.environ.get(ENV_INTERNAL_TEST_RUN):
                    TEST_EVENTS_CACHE.extend(parsed_data.get("Entries", []))

        return True

    def return_response(self,
                        method,
                        path,
                        data,
                        headers,
                        response,
                        request_handler=None):
        if response.content:
            # fix hardcoded account ID in ARNs returned from this API
            fix_account_id(response)

            # fix dates returned from this API (fixes an issue with Terraform)
            fix_date_format(response)

            # fix Content-Length header
            response.headers["Content-Length"] = len(response._content)
Exemplo n.º 8
0
class ProxyListenerEvents(ProxyListener):
    svc = TaggingService()

    def forward_request(self, method, path, data, headers):
        if method == "OPTIONS":
            return 200

        action = headers.get("X-Amz-Target")
        if method == "POST" and path == "/":
            parsed_data = json.loads(to_str(data))

            if action == "AWSEvents.PutRule":
                return handle_put_rule(parsed_data)

            elif action == "AWSEvents.DeleteRule":
                handle_delete_rule(rule_name=parsed_data.get("Name", None))

            elif action == "AWSEvents.DisableRule":
                handle_disable_rule(rule_name=parsed_data.get("Name", None))

        return True

    def return_response(self,
                        method,
                        path,
                        data,
                        headers,
                        response,
                        request_handler=None):
        if response.content:
            # fix hardcoded account ID in ARNs returned from this API
            fix_account_id(response)

            # fix dates returned from this API (fixes an issue with Terraform)
            fix_date_format(response)

            # fix Content-Length header
            response.headers["Content-Length"] = len(response._content)
Exemplo n.º 9
0
API_PREFIX = '/2015-01-01'

DEFAULT_ES_VERSION = '7.7'

ES_DOMAINS = {}

DEFAULT_ES_CLUSTER_CONFIG = {
    'InstanceType': 'm3.medium.elasticsearch',
    'InstanceCount': 1,
    'DedicatedMasterEnabled': True,
    'ZoneAwarenessEnabled': False,
    'DedicatedMasterType': 'm3.medium.elasticsearch',
    'DedicatedMasterCount': 1
}

TAGS = TaggingService()

app = Flask(APP_NAME)
app.url_map.strict_slashes = False


def error_response(error_type, code=400, message='Unknown error.'):
    if not message:
        if error_type == 'ResourceNotFoundException':
            message = 'Resource not found.'
        elif error_type == 'ResourceAlreadyExistsException':
            message = 'Resource already exists.'
    response = make_response(jsonify({'error': message}))
    response.headers['x-amzn-errortype'] = error_type
    return response, code
Exemplo n.º 10
0
class ProxyListenerEvents(ProxyListener):
    svc = TaggingService()

    def forward_request(self, method, path, data, headers):
        action = headers.get('X-Amz-Target')
        if method == 'POST' and path == '/':
            parsed_data = json.loads(to_str(data))
            if action == 'AWSEvents.PutEvents':
                events_with_added_uuid = list(
                    map(
                        lambda event: {
                            'event': event,
                            'uuid': str(uuid.uuid4())
                        }, parsed_data['Entries']))
                content = {
                    'Entries':
                    list(
                        map(lambda event: {'EventId': event['uuid']},
                            events_with_added_uuid))
                }
                self._create_and_register_temp_dir()
                self._dump_events_to_files(events_with_added_uuid)
                return make_response(content)
            elif action == 'AWSEvents.ListTagsForResource':
                return make_response(
                    self.svc.list_tags_for_resource(
                        parsed_data['ResourceARN']))
            elif action == 'AWSEvents.TagResource':
                self.svc.tag_resource(parsed_data['ResourceARN'],
                                      parsed_data['Tags'])
                return make_response()
            elif action == 'AWSEvents.UntagResource':
                self.svc.untag_resource(parsed_data['ResourceARN'],
                                        parsed_data['TagKeys'])
                return make_response()

        if method == 'OPTIONS':
            return 200
        return True

    def return_response(self,
                        method,
                        path,
                        data,
                        headers,
                        response,
                        request_handler=None):
        if response.content:
            # fix hardcoded account ID in ARNs returned from this API
            self._fix_account_id(response)
            # fix dates returned from this API (fixes an issue with Terraform)
            self._fix_date_format(response)
            # fix content-length header
            response.headers['content-length'] = len(response._content)

    def _create_and_register_temp_dir(self):
        if EVENTS_TMP_DIR not in TMP_FILES:
            mkdir(EVENTS_TMP_DIR)
            TMP_FILES.append(EVENTS_TMP_DIR)

    def _dump_events_to_files(self, events_with_added_uuid):
        current_time_millis = int(round(time.time() * 1000))
        for event in events_with_added_uuid:
            save_file(
                os.path.join(EVENTS_TMP_DIR,
                             '%s_%s' % (current_time_millis, event['uuid'])),
                json.dumps(event['event']))

    def _fix_date_format(self, response):
        """ Normalize date to format '2019-06-13T18:10:09.1234Z' """
        pattern = r'<CreateDate>([^<]+) ([^<+]+)(\+[^<]*)?</CreateDate>'
        replacement = r'<CreateDate>\1T\2Z</CreateDate>'
        self._replace(response, pattern, replacement)

    def _fix_account_id(self, response):
        return aws_stack.fix_account_id_in_arns(response,
                                                existing=MOTO_ACCOUNT_ID,
                                                replace=TEST_AWS_ACCOUNT_ID)

    def _replace(self, response, pattern, replacement):
        content = to_str(response.content)
        response._content = re.sub(pattern, replacement, content)
Exemplo n.º 11
0
 def __init__(self):
     self.tags = TaggingService()
Exemplo n.º 12
0
class LambdaServiceBackend(RegionBackend):
    # name => Function; Account/region are implicit through the Backend
    functions: Dict[str, Function] = {}
    # static tagging service instance
    TAGS = TaggingService()
Exemplo n.º 13
0
 def __init__(self):
     self.tags = TaggingService()
     self.alarm_scheduler = None