Skip to content

Commit e450bfe

Browse files
author
Michael Brewer
committed
refactor: method to route
1 parent 0386b68 commit e450bfe

File tree

2 files changed

+34
-32
lines changed

2 files changed

+34
-32
lines changed

aws_lambda_powertools/utilities/data_classes/api_gateway_authorizer_event.py

+20-18
Original file line numberDiff line numberDiff line change
@@ -379,11 +379,11 @@ def __init__(
379379
self.api_id = api_id
380380
self.stage = stage
381381
self.context = context
382-
self._allow_methods: List[Dict] = []
383-
self._deny_methods: List[Dict] = []
382+
self._allow_routes: List[Dict] = []
383+
self._deny_routes: List[Dict] = []
384384

385-
def _add_method(self, effect: str, verb: str, resource: str, conditions: List[Dict]):
386-
"""Adds a method to the internal lists of allowed or denied methods. Each object in
385+
def _add_route(self, effect: str, verb: str, resource: str, conditions: List[Dict]):
386+
"""Adds a route to the internal lists of allowed or denied routes. Each object in
387387
the internal list contains a resource ARN and a condition statement. The condition
388388
statement can be null."""
389389
if verb != "*" and not hasattr(HttpVerb, verb):
@@ -392,16 +392,18 @@ def _add_method(self, effect: str, verb: str, resource: str, conditions: List[Di
392392
resource_pattern = re.compile(self.path_regex)
393393
if not resource_pattern.match(resource):
394394
raise ValueError(f"Invalid resource path: {resource}. Path should match {self.path_regex}")
395+
395396
if resource[:1] == "/":
396397
resource = resource[1:]
397398

398399
resource_arn = APIGatewayRouteArn(self.region, self.aws_account_id, self.api_id, self.stage, verb, resource).arn
399400

400-
method = {"resourceArn": resource_arn, "conditions": conditions}
401+
route = {"resourceArn": resource_arn, "conditions": conditions}
402+
401403
if effect.lower() == "allow":
402-
self._allow_methods.append(method)
404+
self._allow_routes.append(route)
403405
else: # deny
404-
self._deny_methods.append(method)
406+
self._deny_routes.append(route)
405407

406408
@staticmethod
407409
def _get_empty_statement(effect: str) -> Dict[str, Any]:
@@ -431,45 +433,45 @@ def _get_statement_for_effect(self, effect: str, methods: List) -> List:
431433

432434
return statements
433435

434-
def allow_all_methods(self):
436+
def allow_all_routes(self):
435437
"""Adds a '*' allow to the policy to authorize access to all methods of an API"""
436-
self._add_method("Allow", HttpVerb.ALL, "*", [])
438+
self._add_route("Allow", HttpVerb.ALL, "*", [])
437439

438-
def deny_all_methods(self):
440+
def deny_all_route(self):
439441
"""Adds a '*' allow to the policy to deny access to all methods of an API"""
440-
self._add_method("Deny", HttpVerb.ALL, "*", [])
442+
self._add_route("Deny", HttpVerb.ALL, "*", [])
441443

442-
def allow_method(self, http_method: str, resource: str, conditions: Optional[List[Dict]] = None):
444+
def allow_route(self, http_method: str, resource: str, conditions: Optional[List[Dict]] = None):
443445
"""Adds an API Gateway method (Http verb + Resource path) to the list of allowed
444446
methods for the policy.
445447
446448
Optionally includes a condition for the policy statement. More on AWS policy
447449
conditions here: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"""
448-
self._add_method("Allow", http_method, resource, conditions or [])
450+
self._add_route("Allow", http_method, resource, conditions or [])
449451

450-
def deny_method(self, http_method: str, resource: str, conditions: Optional[List[Dict]] = None):
452+
def deny_route(self, http_method: str, resource: str, conditions: Optional[List[Dict]] = None):
451453
"""Adds an API Gateway method (Http verb + Resource path) to the list of denied
452454
methods for the policy.
453455
454456
Optionally includes a condition for the policy statement. More on AWS policy
455457
conditions here: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"""
456-
self._add_method("Deny", http_method, resource, conditions or [])
458+
self._add_route("Deny", http_method, resource, conditions or [])
457459

458460
def asdict(self) -> Dict[str, Any]:
459461
"""Generates the policy document based on the internal lists of allowed and denied
460462
conditions. This will generate a policy with two main statements for the effect:
461463
one statement for Allow and one statement for Deny.
462464
Methods that includes conditions will have their own statement in the policy."""
463-
if len(self._allow_methods) == 0 and len(self._deny_methods) == 0:
465+
if len(self._allow_routes) == 0 and len(self._deny_routes) == 0:
464466
raise ValueError("No statements defined for the policy")
465467

466468
response: Dict[str, Any] = {
467469
"principalId": self.principal_id,
468470
"policyDocument": {"Version": self.version, "Statement": []},
469471
}
470472

471-
response["policyDocument"]["Statement"].extend(self._get_statement_for_effect("Allow", self._allow_methods))
472-
response["policyDocument"]["Statement"].extend(self._get_statement_for_effect("Deny", self._deny_methods))
473+
response["policyDocument"]["Statement"].extend(self._get_statement_for_effect("Allow", self._allow_routes))
474+
response["policyDocument"]["Statement"].extend(self._get_statement_for_effect("Deny", self._deny_routes))
473475

474476
if self.context:
475477
response["context"] = self.context

tests/functional/data_classes/test_api_gateway_authorizer.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def test_authorizer_response_invalid_verb(builder: APIGatewayAuthorizerResponse)
2525
with pytest.raises(ValueError) as ex:
2626
# GIVEN a invalid http_method
2727
# WHEN calling deny_method
28-
builder.deny_method("INVALID", "foo")
28+
builder.deny_route("INVALID", "foo")
2929

3030
# THEN raise a name error for invalid http verb
3131
assert str(ex.value) == "Invalid HTTP verb INVALID. Allowed verbs in HttpVerb class"
@@ -35,15 +35,15 @@ def test_authorizer_response_invalid_resource(builder: APIGatewayAuthorizerRespo
3535
with pytest.raises(ValueError) as ex:
3636
# GIVEN a invalid resource path "$"
3737
# WHEN calling deny_method
38-
builder.deny_method(HttpVerb.GET, "$")
38+
builder.deny_route(HttpVerb.GET, "$")
3939

4040
# THEN raise a name error for invalid resource
4141
assert "Invalid resource path: $" in str(ex.value)
4242

4343

44-
def test_authorizer_response_allow_all_methods_with_context():
44+
def test_authorizer_response_allow_all_routes_with_context():
4545
builder = APIGatewayAuthorizerResponse("foo", "us-west-1", "123456789", "fantom", "dev", {"name": "Foo"})
46-
builder.allow_all_methods()
46+
builder.allow_all_routes()
4747
assert builder.asdict() == {
4848
"principalId": "foo",
4949
"policyDocument": {
@@ -60,8 +60,8 @@ def test_authorizer_response_allow_all_methods_with_context():
6060
}
6161

6262

63-
def test_authorizer_response_deny_all_methods(builder: APIGatewayAuthorizerResponse):
64-
builder.deny_all_methods()
63+
def test_authorizer_response_deny_all_routes(builder: APIGatewayAuthorizerResponse):
64+
builder.deny_all_route()
6565
assert builder.asdict() == {
6666
"principalId": "foo",
6767
"policyDocument": {
@@ -77,8 +77,8 @@ def test_authorizer_response_deny_all_methods(builder: APIGatewayAuthorizerRespo
7777
}
7878

7979

80-
def test_authorizer_response_allow_method(builder: APIGatewayAuthorizerResponse):
81-
builder.allow_method(HttpVerb.GET, "/foo")
80+
def test_authorizer_response_allow_route(builder: APIGatewayAuthorizerResponse):
81+
builder.allow_route(HttpVerb.GET, "/foo")
8282
assert builder.asdict() == {
8383
"policyDocument": {
8484
"Version": "2012-10-17",
@@ -94,8 +94,8 @@ def test_authorizer_response_allow_method(builder: APIGatewayAuthorizerResponse)
9494
}
9595

9696

97-
def test_authorizer_response_deny_method(builder: APIGatewayAuthorizerResponse):
98-
builder.deny_method(HttpVerb.PUT, "foo")
97+
def test_authorizer_response_deny_route(builder: APIGatewayAuthorizerResponse):
98+
builder.deny_route(HttpVerb.PUT, "foo")
9999
assert builder.asdict() == {
100100
"principalId": "foo",
101101
"policyDocument": {
@@ -111,8 +111,8 @@ def test_authorizer_response_deny_method(builder: APIGatewayAuthorizerResponse):
111111
}
112112

113113

114-
def test_authorizer_response_allow_method_with_conditions(builder: APIGatewayAuthorizerResponse):
115-
builder.allow_method(
114+
def test_authorizer_response_allow_route_with_conditions(builder: APIGatewayAuthorizerResponse):
115+
builder.allow_route(
116116
HttpVerb.POST,
117117
"/foo",
118118
[
@@ -135,8 +135,8 @@ def test_authorizer_response_allow_method_with_conditions(builder: APIGatewayAut
135135
}
136136

137137

138-
def test_authorizer_response_deny_method_with_conditions(builder: APIGatewayAuthorizerResponse):
139-
builder.deny_method(
138+
def test_authorizer_response_deny_route_with_conditions(builder: APIGatewayAuthorizerResponse):
139+
builder.deny_route(
140140
HttpVerb.POST,
141141
"/foo",
142142
[

0 commit comments

Comments
 (0)