Skip to content

Commit

Permalink
fix: add more input validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Brewer committed Aug 19, 2021
1 parent e492769 commit 1d6b49d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
18 changes: 14 additions & 4 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,13 +542,23 @@ def _resolve(self) -> ResponseBuilder:

def _remove_prefix(self, path: str) -> str:
"""Remove the configured prefix from the path"""
if self._strip_prefixes:
for prefix in self._strip_prefixes:
if path.startswith(prefix + "/"):
return path[len(prefix) :]
if not isinstance(self._strip_prefixes, list):
return path

for prefix in self._strip_prefixes:
if self._path_starts_with(path, prefix):
return path[len(prefix) :]

return path

@staticmethod
def _path_starts_with(path: str, prefix: str):
"""Returns true if the `path` starts with a prefix plus a `/`"""
if not isinstance(prefix, str) or len(prefix) == 0:
return False

return path.startswith(prefix + "/")

def _not_found(self, method: str) -> ResponseBuilder:
"""Called when no matching route was found and includes support for the cors preflight response"""
headers = {}
Expand Down
26 changes: 26 additions & 0 deletions tests/functional/event_handler/test_api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -797,3 +797,29 @@ def foo():

# THEN a route for `/foo` should be found
assert response["statusCode"] == 200


@pytest.mark.parametrize(
"prefix",
[
pytest.param("/foo", id="String are not supported"),
pytest.param({"/foo"}, id="Sets are not supported"),
pytest.param({"foo": "/foo"}, id="Dicts are not supported"),
pytest.param(tuple("/foo"), id="Tuples are not supported"),
pytest.param([None, 1, "", False], id="List of invalid values"),
],
)
def test_ignore_invalid(prefix):
# GIVEN an invalid prefix
app = ApiGatewayResolver(strip_prefixes=prefix)

@app.get("/foo/status")
def foo():
...

# WHEN calling handler
response = app({"httpMethod": "GET", "path": "/foo/status"}, None)

# THEN a route for `/foo/status` should be found
# so no prefix was stripped from the request path
assert response["statusCode"] == 200

0 comments on commit 1d6b49d

Please sign in to comment.