Skip to content

fix(lambda): enforce lambda alias alphanumeric logical id #3738

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Apr 18, 2025
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions samtranslator/model/sam_resources.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
""" SAM macro definitions """

import copy
import re
from contextlib import suppress
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union, cast

Expand Down Expand Up @@ -238,7 +239,6 @@ class SamFunction(SamResourceMacro):

# DeadLetterQueue
dead_letter_queue_policy_actions = {"SQS": "sqs:SendMessage", "SNS": "sns:Publish"}
#

# Conditions
conditions: Dict[str, Any] = {} # TODO: Replace `Any` with something more specific
Expand Down Expand Up @@ -325,7 +325,7 @@ def to_cloudformation(self, **kwargs): # type: ignore[no-untyped-def] # noqa: P
resources.append(url_permission)

self._validate_deployment_preference_and_add_update_policy(
kwargs.get("deployment_preference_collection", None),
kwargs.get("deployment_preference_collection"),
lambda_alias,
intrinsics_resolver,
cast(IntrinsicsResolver, mappings_resolver), # TODO: better handle mappings_resolver's Optional
Expand Down Expand Up @@ -1002,7 +1002,22 @@ def _construct_alias(self, name: str, function: LambdaFunction, version: LambdaV
if not name:
raise InvalidResourceException(self.logical_id, "Alias name is required to create an alias")

logical_id = f"{function.logical_id}Alias{name}"
# Validate alias name against the required pattern: (?!^[0-9]+$)([a-zA-Z0-9-_]+)
# This ensures the alias name:
# 1. Contains only alphanumeric characters, hyphens, and underscores
# 2. Is not purely numeric
ALIAS_REGEX = r"(?!^[0-9]+$)([a-zA-Z0-9\-_]+)$"
if not re.match(ALIAS_REGEX, name):
raise InvalidResourceException(
self.logical_id,
f"AutoPublishAlias name ('{name}') must contain only alphanumeric characters, hyphens, or underscores matching (?!^[0-9]+$)([a-zA-Z0-9-_]+) pattern.",
)

# Strip hyphens and underscores from the alias name for the logical ID
# This ensures the logical ID contains only alphanumeric characters
alias_alphanumeric_name = name.replace("-", "D").replace("_", "U")

logical_id = f"{function.logical_id}Alias{alias_alphanumeric_name}"
alias = LambdaAlias(logical_id=logical_id, attributes=self.get_passthrough_resource_attributes())
alias.Name = name
alias.FunctionName = function.get_runtime_attr("name")
Expand All @@ -1014,7 +1029,7 @@ def _construct_alias(self, name: str, function: LambdaFunction, version: LambdaV

def _validate_deployment_preference_and_add_update_policy( # noqa: PLR0913
self,
deployment_preference_collection: DeploymentPreferenceCollection,
deployment_preference_collection: Optional[DeploymentPreferenceCollection],
lambda_alias: Optional[LambdaAlias],
intrinsics_resolver: IntrinsicsResolver,
mappings_resolver: IntrinsicsResolver,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: s3://sam-demo-bucket/hello.zip
Handler: hello.handler
Runtime: python3.9
# Using an invalid alias name with special characters that can't be properly transformed
AutoPublishAlias: invalid*alias@name
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"_autoGeneratedBreakdownErrorMessage": [
"Invalid Serverless Application Specification document. ",
"Number of errors found: 1. ",
"Resource with id [MyFunction] is invalid. ",
"AutoPublishAlias name ('invalid*alias@name') must contain only alphanumeric characters, hyphens, or underscores matching (?!^[0-9]+$)([a-zA-Z0-9-_]+) pattern."
],
"errorMessage": "Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [MyFunction] is invalid. AutoPublishAlias name ('invalid*alias@name') must contain only alphanumeric characters, hyphens, or underscores matching (?!^[0-9]+$)([a-zA-Z0-9-_]+) pattern."
}
66 changes: 57 additions & 9 deletions tests/translator/test_function_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -765,20 +765,68 @@ def test_version_logical_id_changes_with_snapstart(self):
self.assertNotEqual(version1.logical_id, version_snapstart.logical_id)
self.assertEqual(version1.logical_id, version_snapstart_none.logical_id)

def test_alias_creation(self):
name = "aliasname"

alias = self.sam_func._construct_alias(name, self.lambda_func, self.lambda_version)
@parameterized.expand(
[
# Valid cases
# Expect logical id should be {fn name}{'Alias'}{alphanumerica alias name without `-` or `_`}
("aliasname", "fooAliasaliasname"),
("alias-name", "fooAliasaliasDname"),
("alias_name", "fooAliasaliasUname"),
("alias123", "fooAliasalias123"),
("123alias", "fooAlias123alias"),
("UPPERCASE", "fooAliasUPPERCASE"),
("mixed-Case_123", "fooAliasmixedDCaseU123"),
("a", "fooAliasa"), # Single character
("1a", "fooAlias1a"), # Starts with number
# Check the placement of dash and underscore
("1-1_1", "fooAlias1D1U1"),
("1_1-1", "fooAlias1U1D1"),
("11-1", "fooAlias11D1"),
("1-11", "fooAlias1D11"),
("11_1", "fooAlias11U1"),
("1_11", "fooAlias1U11"),
("1-1-1", "fooAlias1D1D1"),
("-1-1-1-", "fooAliasD1D1D1D"),
("_1_1-1-", "fooAliasU1U1D1D"),
]
)
def test_alias_creation(self, alias_name, expected_logical_id):
alias = self.sam_func._construct_alias(alias_name, self.lambda_func, self.lambda_version)

expected_logical_id = f"{self.lambda_func.logical_id}Alias{name}"
self.assertEqual(alias.logical_id, expected_logical_id)
self.assertEqual(alias.Name, name)
self.assertEqual(alias.Name, alias_name)
self.assertEqual(alias.FunctionName, {"Ref": self.lambda_func.logical_id})
self.assertEqual(alias.FunctionVersion, {"Fn::GetAtt": [self.lambda_version.logical_id, "Version"]})

def test_alias_creation_error(self):
with self.assertRaises(InvalidResourceException):
self.sam_func._construct_alias(None, self.lambda_func, self.lambda_version)
@parameterized.expand(
[
# Invalid cases
("", "Resource with id [foo] is invalid. Alias name is required to create an alias"),
(None, "Resource with id [foo] is invalid. Alias name is required to create an alias"),
(
"123",
"Resource with id [foo] is invalid. AutoPublishAlias name ('123') must contain only alphanumeric characters, hyphens, or underscores matching (?!^[0-9]+$)([a-zA-Z0-9-_]+) pattern.",
),
(
"name with space",
"Resource with id [foo] is invalid. AutoPublishAlias name ('name with space') must contain only alphanumeric characters, hyphens, or underscores matching (?!^[0-9]+$)([a-zA-Z0-9-_]+) pattern.",
),
(
"alias@name",
"Resource with id [foo] is invalid. AutoPublishAlias name ('alias@name') must contain only alphanumeric characters, hyphens, or underscores matching (?!^[0-9]+$)([a-zA-Z0-9-_]+) pattern.",
),
(
"alias/name",
"Resource with id [foo] is invalid. AutoPublishAlias name ('alias/name') must contain only alphanumeric characters, hyphens, or underscores matching (?!^[0-9]+$)([a-zA-Z0-9-_]+) pattern.",
),
]
)
def test_alias_creation_error(self, alias_name, expected_error_massage):
with self.assertRaises(InvalidResourceException) as context:
self.sam_func._construct_alias(alias_name, self.lambda_func, self.lambda_version)

error = context.exception
self.assertEqual(str(error.message), expected_error_massage)

def test_get_resolved_alias_name_must_work(self):
property_name = "something"
Expand Down