def test_must_return_function_value(self):
        provider = SamFunctionProvider({})
        provider.functions = {
            "func1": "value"
        }  # Cheat a bit here by setting the value of this property directly

        self.assertEqual("value", provider.get("func1"))
Пример #2
0
def auth_per_resource(stacks: List[Stack]):
    """
    Check if authentication has been set for the function resources defined in the template that have `Api` Event type.

    Parameters
    ----------
    stacks: List[Stack]
        The list of stacks where resources are looked for

    Returns
    -------

    List of tuples per function resource that have the `Api` or `HttpApi` event types, that describes the resource name
    and if authorization is required per resource.

    """

    _auth_per_resource: List[Tuple[str, bool]] = []

    sam_function_provider = SamFunctionProvider(
        stacks, ignore_code_extraction_warnings=True)
    for sam_function in sam_function_provider.get_all():
        # Only check for auth if there are function events defined.
        if sam_function.events:
            _auth_resource_event(sam_function_provider, sam_function,
                                 _auth_per_resource)

    return _auth_per_resource
Пример #3
0
def auth_per_resource(parameter_overrides, template_dict):
    """
    Check if authentication has been set for the function resources defined in the template that have `Api` Event type.

    Parameters
    ----------
    parameter_overrides: dict
        list of parameter overrides for the parameters defined in the template
    template_dict: dict
        Raw dictionary of the defined SAM template

    Returns
    -------

    List of tuples per function resource that have the `Api` or `HttpApi` event types, that describes the resource name
    and if authorization is required per resource.

    """

    _auth_per_resource = []

    sam_functions = SamFunctionProvider(
        template_dict=template_dict,
        parameter_overrides=parameter_overrides,
        ignore_code_extraction_warnings=True)
    for sam_function in sam_functions.get_all():
        # Only check for auth if there are function events defined.
        if sam_function.events:
            _auth_resource_event(sam_functions, sam_function,
                                 _auth_per_resource)

    return _auth_per_resource
Пример #4
0
    def test_must_return_function_value(self):
        provider = SamFunctionProvider([])
        # Cheat a bit here by setting the value of this property directly
        function = Function(
            name="not-value",
            functionname="value",
            runtime=None,
            handler=None,
            codeuri=None,
            memory=None,
            timeout=None,
            environment=None,
            rolearn=None,
            layers=[],
            events=None,
            metadata=None,
            inlinecode=None,
            imageuri=None,
            imageconfig=None,
            packagetype=None,
            codesign_config_arn=None,
            stack_path=STACK_PATH,
        )
        provider.functions = {"func1": function}

        self.assertEqual(function, provider.get("value"))
Пример #5
0
    def __enter__(self):
        """
        Performs some basic checks and returns itself when everything is ready to invoke a Lambda function.

        :returns InvokeContext: Returns this object
        """

        # Grab template from file and create a provider
        self._template_dict = self._get_template_data(self._template_file)
        self._function_provider = SamFunctionProvider(self._template_dict,
                                                      self.parameter_overrides)

        self._env_vars_value = self._get_env_vars_value(self._env_vars_file)
        self._log_file_handle = self._setup_log_file(self._log_file)

        self._debug_context = self._get_debug_context(self._debug_ports,
                                                      self._debug_args,
                                                      self._debugger_path)

        self._container_manager = self._get_container_manager(
            self._docker_network, self._skip_pull_image)

        if not self._container_manager.is_docker_reachable:
            raise InvokeContextException(
                "Running AWS SAM projects locally requires Docker. Have you got it installed?"
            )

        return self
Пример #6
0
    def __enter__(self):
        self._template_dict = get_template_data(self._template_file)

        self._function_provider = SamFunctionProvider(
            self._template_dict, self._parameter_overrides)
        self._layer_provider = SamLayerProvider(self._template_dict,
                                                self._parameter_overrides)

        if not self._base_dir:
            # Base directory, if not provided, is the directory containing the template
            self._base_dir = str(
                pathlib.Path(self._template_file).resolve().parent)

        self._build_dir = self._setup_build_dir(self._build_dir, self._clean)

        if self._cached:
            cache_path = pathlib.Path(self._cache_dir)
            cache_path.mkdir(mode=self._BUILD_DIR_PERMISSIONS,
                             parents=True,
                             exist_ok=True)
            self._cache_dir = str(cache_path.resolve())

        if self._use_container:
            self._container_manager = ContainerManager(
                docker_network_id=self._docker_network,
                skip_pull_image=self._skip_pull_image)

        return self
 def setUp(self):
     self.parameter_overrides = {}
     root_stack = Stack("", "", "template.yaml", self.parameter_overrides, self.TEMPLATE)
     child_stack = Stack("", "ChildStack", "./child/template.yaml", None, self.CHILD_TEMPLATE)
     with patch("samcli.lib.providers.sam_stack_provider.get_template_data") as get_template_data_mock:
         get_template_data_mock.side_effect = lambda t: {
             "template.yaml": self.TEMPLATE,
             "./child/template.yaml": self.CHILD_TEMPLATE,
         }
         self.provider = SamFunctionProvider([root_stack, child_stack])
Пример #8
0
    def __enter__(self):
        """
        Performs some basic checks and returns itself when everything is ready to invoke a Lambda function.

        :returns InvokeContext: Returns this object
        """

        # Grab template from file and create a provider
        self._template_dict = self._get_template_data(self._template_file)
        self._function_provider = SamFunctionProvider(self._template_dict,
                                                      self.parameter_overrides)

        self._env_vars_value = self._get_env_vars_value(self._env_vars_file)
        self._container_env_vars_value = self._get_env_vars_value(
            self._container_env_vars_file)
        self._log_file_handle = self._setup_log_file(self._log_file)

        # in case of warm containers && debugging is enabled && if debug-function property is not provided, so
        # if the provided template only contains one lambda function, so debug-function will be set to this function
        # if the template contains multiple functions, a warning message "that the debugging option will be ignored"
        # will be printed
        if self._containers_mode == ContainersMode.WARM and self._debug_ports and not self._debug_function:
            if len(self._function_provider.functions) == 1:
                self._debug_function = list(
                    self._function_provider.functions.keys())[0]
            else:
                LOG.info(
                    "Warning: you supplied debugging options but you did not specify the --debug-function option."
                    " To specify which function you want to debug, please use the --debug-function <function-name>"
                )
                # skipp the debugging
                self._debug_ports = None

        self._debug_context = self._get_debug_context(
            self._debug_ports,
            self._debug_args,
            self._debugger_path,
            self._container_env_vars_value,
            self._debug_function,
        )

        self._container_manager = self._get_container_manager(
            self._docker_network, self._skip_pull_image, self._shutdown)

        if not self._container_manager.is_docker_reachable:
            raise InvokeContextException(
                "Running AWS SAM projects locally requires Docker. Have you got it installed and running?"
            )

        # initialize all lambda function containers upfront
        if self._containers_initializing_mode == ContainersInitializationMode.EAGER:
            self._initialize_all_functions_containers()

        return self
Пример #9
0
    def test_must_extract_functions(self, extract_mock, get_template_mock):
        extract_result = {"foo": "bar"}
        extract_mock.return_value = extract_result

        template = {"Resources": {"a": "b"}}
        get_template_mock.return_value = template
        provider = SamFunctionProvider(template, parameter_overrides=self.parameter_overrides)

        extract_mock.assert_called_with({"a": "b"}, False)
        get_template_mock.assert_called_with(template, self.parameter_overrides)
        self.assertEqual(provider.functions, extract_result)
Пример #10
0
    def test_must_default_to_empty_resources(self, extract_mock, get_template_mock):
        extract_result = {"foo": "bar"}
        extract_mock.return_value = extract_result

        template = {"a": "b"}  # Template does *not* have 'Resources' key
        get_template_mock.return_value = template
        provider = SamFunctionProvider(template, parameter_overrides=self.parameter_overrides)

        extract_mock.assert_called_with({}, False)  # Empty Resources value must be passed
        self.assertEqual(provider.functions, extract_result)
        self.assertEqual(provider.resources, {})
Пример #11
0
    def prompt_image_repository(self, stacks: List[Stack]):
        """
        Prompt for the image repository to push the images.
        For each image function found in build artifacts, it will prompt for an image repository.

        Parameters
        ----------
        stacks : List[Stack]
            List of stacks to look for image functions.

        Returns
        -------
        Dict
            A dictionary contains image function logical ID as key, image repository as value.
        """
        image_repositories = {}
        artifacts_format = get_template_artifacts_format(
            template_file=self.template_file)
        if IMAGE in artifacts_format:
            self.function_provider = SamFunctionProvider(
                stacks, ignore_code_extraction_warnings=True)
            function_resources = get_template_function_resource_ids(
                template_file=self.template_file, artifact=IMAGE)
            for resource_id in function_resources:
                image_repositories[resource_id] = prompt(
                    f"\t{self.start_bold}Image Repository for {resource_id}{self.end_bold}",
                    default=self.image_repositories.get(resource_id, "")
                    if isinstance(self.image_repositories, dict) else ""
                    or self.image_repository,
                )
                if not is_ecr_url(image_repositories.get(resource_id)):
                    raise GuidedDeployFailedError(
                        f"Invalid Image Repository ECR URI: {image_repositories.get(resource_id)}"
                    )
            for resource_id, function_prop in self.function_provider.functions.items(
            ):
                if function_prop.packagetype == IMAGE:
                    image = function_prop.imageuri
                    try:
                        tag = tag_translation(image)
                    except NonLocalImageException:
                        pass
                    except NoImageFoundException as ex:
                        raise GuidedDeployFailedError(
                            "No images found to deploy, try running sam build"
                        ) from ex
                    else:
                        click.secho(
                            f"\t  {image} to be pushed to {image_repositories.get(resource_id)}:{tag}"
                        )
            click.secho(nl=True)

        return image_repositories
Пример #12
0
def transform_template(parameter_overrides, template_dict):
    """

    :param parameter_overrides: Dictionary of parameter overrides for the SAM template.
    :param template_dict: Dictionary representation of the SAM template.
    :return:
    """
    sam_functions = SamFunctionProvider(
        template_dict=template_dict, parameter_overrides=parameter_overrides, ignore_code_extraction_warnings=True
    )

    return sam_functions
Пример #13
0
    def test_must_return_function_value(self):
        provider = SamFunctionProvider({})
        # Cheat a bit here by setting the value of this property directly
        function = Function(
            name="not-value",
            functionname="value",
            runtime=None,
            handler=None,
            codeuri=None,
            memory=None,
            timeout=None,
            environment=None,
            rolearn=None,
            layers=[],
        )
        provider.functions = {"func1": function}

        self.assertEqual(function, provider.get("value"))
Пример #14
0
    def __enter__(self):
        self._template_dict = get_template_data(self._template_file)

        self._function_provider = SamFunctionProvider(
            self._template_dict, self._parameter_overrides)

        if not self._base_dir:
            # Base directory, if not provided, is the directory containing the template
            self._base_dir = str(
                pathlib.Path(self._template_file).resolve().parent)

        self._build_dir = self._setup_build_dir(self._build_dir, self._clean)

        if self._use_container:
            self._container_manager = ContainerManager(
                docker_network_id=self._docker_network,
                skip_pull_image=self._skip_pull_image)

        return self
Пример #15
0
    def __enter__(self) -> "BuildContext":

        self._stacks, remote_stack_full_paths = SamLocalStackProvider.get_stacks(
            self._template_file, parameter_overrides=self._parameter_overrides)

        if remote_stack_full_paths:
            LOG.warning(
                "Below nested stacks(s) specify non-local URL(s), which are unsupported:\n%s\n"
                "Skipping building resources inside these nested stacks.",
                "\n".join([
                    f"- {full_path}" for full_path in remote_stack_full_paths
                ]),
            )

        # Note(xinhol): self._use_raw_codeuri is added temporarily to fix issue #2717
        # when base_dir is provided, codeuri should not be resolved based on template file path.
        # we will refactor to make all path resolution inside providers intead of in multiple places
        self._function_provider = SamFunctionProvider(self.stacks,
                                                      self._use_raw_codeuri)
        self._layer_provider = SamLayerProvider(self.stacks,
                                                self._use_raw_codeuri)

        if not self._base_dir:
            # Base directory, if not provided, is the directory containing the template
            self._base_dir = str(
                pathlib.Path(self._template_file).resolve().parent)

        self._build_dir = self._setup_build_dir(self._build_dir, self._clean)

        if self._cached:
            cache_path = pathlib.Path(self._cache_dir)
            cache_path.mkdir(mode=self._BUILD_DIR_PERMISSIONS,
                             parents=True,
                             exist_ok=True)
            self._cache_dir = str(cache_path.resolve())

        if self._use_container:
            self._container_manager = ContainerManager(
                docker_network_id=self._docker_network,
                skip_pull_image=self._skip_pull_image)

        return self
Пример #16
0
def signer_config_per_function(parameter_overrides, template_dict):
    functions_with_code_sign = set()
    layers_with_code_sign = {}

    sam_functions = SamFunctionProvider(template_dict=template_dict, parameter_overrides=parameter_overrides)

    for sam_function in sam_functions.get_all():
        if sam_function.codesign_config_arn:
            function_name = sam_function.name
            LOG.debug("Found the following function with a code signing config %s", function_name)
            functions_with_code_sign.add(function_name)

            if sam_function.layers:
                for layer in sam_function.layers:
                    layer_name = layer.name
                    LOG.debug("Found following layers inside the function %s", layer_name)
                    if layer_name in layers_with_code_sign:
                        layers_with_code_sign[layer_name].add(function_name)
                    else:
                        functions_that_is_referring_to_function = set()
                        functions_that_is_referring_to_function.add(function_name)
                        layers_with_code_sign[layer_name] = functions_that_is_referring_to_function

    return functions_with_code_sign, layers_with_code_sign
Пример #17
0
def signer_config_per_function(stacks: List[Stack]):
    functions_with_code_sign = set()
    layers_with_code_sign: Dict[str, Set[str]] = {}

    sam_functions = SamFunctionProvider(stacks)

    for sam_function in sam_functions.get_all():
        if sam_function.codesign_config_arn:
            function_name = sam_function.name
            LOG.debug("Found the following function with a code signing config %s", function_name)
            functions_with_code_sign.add(function_name)

            if sam_function.layers:
                for layer in sam_function.layers:
                    layer_name = layer.name
                    LOG.debug("Found following layers inside the function %s", layer_name)
                    if layer_name in layers_with_code_sign:
                        layers_with_code_sign[layer_name].add(function_name)
                    else:
                        functions_that_is_referring_to_function = set()
                        functions_that_is_referring_to_function.add(function_name)
                        layers_with_code_sign[layer_name] = functions_that_is_referring_to_function

    return functions_with_code_sign, layers_with_code_sign
Пример #18
0
    def test_must_work_with_no_functions(self):
        provider = SamFunctionProvider({})

        result = [f for f in provider.get_all()]
        self.assertEqual(result, [])
Пример #19
0
    def test_return_none_if_function_not_found(self):
        provider = SamFunctionProvider({})

        self.assertIsNone(provider.get("somefunc"),
                          "Must return None when Function is not found")
Пример #20
0
    def test_raise_on_invalid_name(self):
        provider = SamFunctionProvider({})

        with self.assertRaises(ValueError):
            provider.get(None)
Пример #21
0
 def setUp(self):
     self.parameter_overrides = {}
     self.provider = SamFunctionProvider(
         self.TEMPLATE, parameter_overrides=self.parameter_overrides)