8000 Remove last uses of get_aws_account_id() and aws_stack.get_region() (… · localstack/localstack@82fd17a · GitHub
[go: up one dir, main page]

Skip to content

Commit 82fd17a

Browse files
Remove last uses of get_aws_account_id() and aws_stack.get_region() (#9641)
1 parent 731873d commit 82fd17a

File tree

11 files changed

+31
-30
lines changed

11 files changed

+31
-30
lines changed

localstack/services/apigateway/helpers.py

Lines changed: 6 additions & 5 deletions
< 8000 td data-grid-cell-id="diff-056962eb9804524e85fe705957e5d78d5e1206e7461cd12db42234f79e51ae54-34-35-1" data-selected="false" role="gridcell" style="background-color:var(--diffBlob-additionNum-bgColor, var(--diffBlob-addition-bgColor-num));text-align:center" tabindex="-1" valign="top" class="focusable-grid-cell diff-line-number position-relative left-side">35
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
from requests.models import Response
1919

2020
from localstack import config
21-
from localstack.aws.accounts import get_aws_account_id
2221
from localstack.aws.api import RequestContext
2322
from localstack.aws.api.apigateway import (
2423
Authorizer,
@@ -32,6 +31,8 @@
3231
from localstack.aws.connect import connect_to
3332
from localstack.constants import (
3433
APPLICATION_JSON,
34+
AWS_REGION_US_EAST_1,
+
DEFAULT_AWS_ACCOUNT_ID,
3536
HEADER_LOCALSTACK_EDGE_URL,
3637
PATH_USER_REQUEST,
3738
)
@@ -42,7 +43,7 @@
4243
apigateway_stores,
4344
)
4445
from localstack.utils import common
45-
from localstack.utils.aws import aws_stack, queries
46+
from localstack.utils.aws import queries
4647
from localstack.utils.aws import resources as resource_utils
4748
from localstack.utils.aws.arns import parse_arn
4849
from localstack.utils.aws.aws_responses import requests_error_response_json, requests_response
@@ -134,8 +135,8 @@ def get_apigateway_store(context: RequestContext) -> ApiGatewayStore:
134135

135136

136137
def get_apigateway_store_for_invocation(context: ApiInvocationContext) -> ApiGatewayStore:
137-
account_id = context.account_id or get_aws_account_id()
138-
region_name = context.region_name or aws_stack.get_region()
138+
account_id = context.account_id or DEFAULT_AWS_ACCOUNT_ID
139+
region_name = context.region_name or AWS_REGION_US_EAST_1
139140
return apigateway_stores[account_id][region_name]
140141

141142

@@ -1387,7 +1388,7 @@ def get_event_request_context(invocation_context: ApiInvocationContext):
13871388
source_ip = headers.get("X-Forwarded-For", ",").split(",")[-2].strip()
13881389
integration_uri = integration_uri or ""
13891390
account_id = integration_uri.split(":lambda:path")[-1].split(":function:")[0].split(":")[-1]
1390-
account_id = account_id or get_aws_account_id()
1391+
account_id = account_id or DEFAULT_AWS_ACCOUNT_ID
13911392
request_context = {
13921393
"accountId": account_id,
13931394
"apiId": api_id,

localstack/services/apigateway/integration.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from requests import Response
1515

1616
from localstack import config
17-
from localstack.aws.accounts import get_aws_account_id
1817
from localstack.aws.connect import (
1918
INTERNAL_REQUEST_PARAMS_HEADER,
2019
InternalRequestParameters,
@@ -689,10 +688,10 @@ def invoke(self, invocation_context: ApiInvocationContext):
689688
new_request = f"{payload}&QueueName={queue}"
690689
else:
691690
payload = self.request_templates.render(invocation_context)
692-
queue_url = f"{config.internal_service_url()}/{account_id}/{queue}"
691+
queue_url = f"{config.internal_service_url()}/queue/{region_name}/{account_id}/{queue}"
693692
new_request = f"{payload}&QueueUrl={queue_url}"
694693

695-
url = urljoin(config.internal_service_url(), f"{get_aws_account_id()}/{queue}")
694+
url = urljoin(config.internal_service_url(), f"/queue/{region_name}/{account_id}/{queue}")
696695
response = common.make_http_request(url, method="POST", headers=headers, data=new_request)
697696

698697
# apply response template

localstack/services/cloudformation/deployment_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,14 +213,14 @@ def fix_boto_parameters_based_on_report(original_params: dict, report: str) -> d
213213
return params
214214

215215

216-
def fix_account_id_in_arns(params: dict) -> dict:
216+
def fix_account_id_in_arns(params: dict, replacement_account_id: str) -> dict:
217217
def fix_ids(o, **kwargs):
218218
if isinstance(o, dict):
219219
for k, v in o.items():
220220
if is_string(v, exclude_binary=True):
221-
o[k] = aws_stack.fix_account_id_in_arns(v)
221+
o[k] = aws_stack.fix_account_id_in_arns(v, replacement=replacement_account_id)
222222
elif is_string(o, exclude_binary=True):
223-
o = aws_stack.fix_account_id_in_arns(o)
223+
o = aws_stack.fix_account_id_in_arns(o, replacement=replacement_account_id)
224224
return o
225225

226226
result = recurse_object(params, fix_ids)

localstack/services/cloudformation/resource_provider.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ def resolve_resource_parameters(
438438

439439
# FIXME: move this to a single place after template processing is finished
440440
# convert any moto account IDs (123456789012) in ARNs to our format (000000000000)
441-
params = fix_account_id_in_arns(params)
441+
params = fix_account_id_in_arns(params, account_id_)
442442
# convert data types (e.g., boolean strings to bool)
443443
# TODO: this might not be needed anymore
444444
params = convert_data_types(func_details.get("types", {}), params)

localstack/services/cloudwatch/provider.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from moto.cloudwatch import cloudwatch_backends
66
from moto.cloudwatch.models import CloudWatchBackend, FakeAlarm, MetricDatum
77

8-
from localstack.aws.accounts import get_account_id_from_access_key_id, get_aws_account_id
8+
from localstack.aws.accounts import get_account_id_from_access_key_id
99
from localstack.aws.api import CommonServiceException, RequestContext, handler
1010
from localstack.aws.api.cloudwatch import (
1111
AlarmNames,
@@ -34,6 +34,7 @@
3434
from localstack.services.edge import ROUTER
3535
from localstack.services.plugins import SERVICE_PLUGINS, ServiceLifecycleHook
3636
from localstack.utils.aws import arns, aws_stack
37+
from localstack.utils.aws.arns import extract_account_id_from_arn
3738
from localstack.utils.aws.aws_stack import extract_access_key_id_from_auth_header
3839
from localstack.utils.patch import patch
3940
from localstack.utils.sync import poll_condition
@@ -143,7 +144,7 @@ def put_metric_alarm(
143144

144145
def create_message_response_update_state(alarm, old_state):
145146
response = {
146-
"AWSAccountId": get_aws_account_id(),
147+
"AWSAccountId": extract_account_id_from_arn(alarm.alarm_arn),
147148
"OldStateValue": old_state,
148149
"AlarmName": alarm.name,
149150
"AlarmDescription": alarm.description or "",

localstack/services/infra.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from moto.core.base_backend import InstanceTrackerMeta
1111

1212
from localstack import config, constants
13-
from localstack.aws.accounts import get_aws_account_id
1413
from localstack.constants import (
1514
AWS_REGION_US_EAST_1,
1615
ENV_DEV,
@@ -186,7 +185,7 @@ def log_startup_message(service):
186185

187186
def check_aws_credentials():
188187
# Setup AWS environment vars, these are used by Boto when LocalStack makes internal cross-service calls
189-
os.environ["AWS_ACCESS_KEY_ID"] = get_aws_account_id()
188+
os.environ["AWS_ACCESS_KEY_ID"] = constants.DEFAULT_AWS_ACCOUNT_ID
190189
os.environ["AWS_SECRET_ACCESS_KEY"] = constants.INTERNAL_AWS_SECRET_ACCESS_KEY
191190
session = boto3.Session()
192191
credentials = session.get_credentials()

localstack/services/kms/models.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa, utils
2020
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
2121

22-
from localstack.aws.accounts import get_aws_account_id
2322
from localstack.aws.api.kms import (
2423
CreateAliasRequest,
2524
CreateGrantRequest,
@@ -402,7 +401,7 @@ def _populate_metadata(
402401
)
403402

404403
# Metadata fields AWS introduces automatically
405-
self.metadata["AWSAccountId"] = account_id or get_aws_account_id()
404+
self.metadata["AWSAccountId"] = account_id
406405
self.metadata["CreationDate"] = datetime.datetime.now()
407406
self.metadata["Enabled"] = create_key_request.get("Origin") != OriginType.EXTERNAL
408407
self.metadata["KeyManager"] = "CUSTOMER"

localstack/services/lambda_/event_source_listeners/dynamodb_event_source_listener.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from localstack.services.lambda_.event_source_listeners.stream_event_source_listener import (
55
StreamEventSourceListener,
66
)
7-
from localstack.utils.aws import aws_stack
7+
from localstack.utils.aws.arns import extract_region_from_arn
88
from localstack.utils.threads import FuncThread
99

1010

@@ -48,7 +48,7 @@ def _create_lambda_event_payload(self, stream_arn, records, shard_id=None):
4848
{
4949
"eventID": record["eventID"],
5050
"eventVersion": "1.0",
51-
"awsRegion": aws_stack.get_region(),
51+
"awsRegion": extract_region_from_arn(stream_arn),
5252
"eventName": record["eventName"],
5353
"eventSourceARN": stream_arn,
5454
"eventSource": "aws:dynamodb",

localstack/services/lambda_/provider.py

Lines changed: 1 addition & 2 del F438 etions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from typing import IO, Optional, Tuple
1010

1111
from localstack import config
12-
from localstack.aws.accounts import get_aws_account_id
1312
from localstack.aws.api import RequestContext, ServiceException, handler
1413
from localstack.aws.api.lambda_ import (
1514
AccountLimit,
@@ -643,7 +642,7 @@ def _validate_layers(self, new_layers: list[str], region: str, account_id: int):
643642
layer_version = None
644643
if layer is not None:
645644
layer_version = layer.layer_versions.get(layer_version_str)
646-
if layer_account_id == get_aws_account_id():
645+
if layer_account_id == account_id:
647646
if region and layer_region != region:
648647
raise InvalidParameterValueException(
649648
f"Layers are not in the same region as the function. "

localstack/utils/aws/aws_stack.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
from typing import Dict, Optional, Union
66

77
import boto3
8+
from moto.core import DEFAULT_ACCOUNT_ID
89

910
from localstack import config
10-
from localstack.aws.accounts import get_aws_account_id
1111
from localstack.config import S3_VIRTUAL_HOSTNAME
1212
from localstack.constants import (
1313
AWS_REGION_US_EAST_1,
@@ -98,20 +98,23 @@ def get_s3_hostname():
9898
return LOCALHOST
9999

100100

101-
def fix_account_id_in_arns(response, colon_delimiter=":", existing=None, replace=None):
101+
def fix_account_id_in_arns(
102+
response, replacement: str, colon_delimiter: str = ":", existing: str | list[str] = None
103+
):
102104
"""Fix the account ID in the ARNs returned in the given Flask response or string"""
103-
existing = existing or ["123456789", "1234567890", "123456789012", get_aws_account_id()]
105+
existing = existing or ["123456789", "1234567890", DEFAULT_ACCOUNT_ID]
104106
existing = existing if isinstance(existing, list) else [existing]
105-
replace = replace or get_aws_account_id()
106107
is_str_obj = is_string_or_bytes(response)
107108
content = to_str(response if is_str_obj else response._content)
108109

109-
replace = r"arn{col}aws{col}\1{col}\2{col}{acc}{col}".format(col=colon_delimiter, acc=replace)
110+
replacement = r"arn{col}aws{col}\1{col}\2{col}{acc}{col}".format(
111+
col=colon_delimiter, acc=replacement
112+
)
110113
for acc_id in existing:
111114
regex = r"arn{col}aws{col}([^:%]+){col}([^:%]*){col}{acc}{col}".format(
112115
col=colon_delimiter, acc=acc_id
113116
)
114-
content = re.sub(regex, replace, content)
117+
content = re.sub(regex, replacement, content)
115118

116119
if not is_str_obj:
117120
response._content = content

localstack/utils/testutil.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@
2727
import requests
2828

2929
from localstack import config
30-
from localstack.aws.accounts import get_aws_account_id
3130
from localstack.constants import (
3231
LOCALSTACK_ROOT_FOLDER,
3332
LOCALSTACK_VENV_FOLDER,
3433
TEST_AWS_ACCESS_KEY_ID,
34+
TEST_AWS_ACCOUNT_ID,
3535
TEST_AWS_REGION_NAME,
3636
)
3737
from localstack.services.lambda_.lambda_utils import (
@@ -253,7 +253,7 @@ def create_lambda_function(
253253
"FunctionName": func_name,
254254
"Runtime": runtime,
255255
"Handler": handler,
256-
"Role": role or LAMBDA_TEST_ROLE.format(account_id=get_aws_account_id()),
256+
"Role": role or LAMBDA_TEST_ROLE.format(account_id=TEST_AWS_ACCOUNT_ID),
257257
"Code": lambda_code,
258258
"Timeout": timeout or LAMBDA_TIMEOUT_SEC,
259259
"Environment": dict(Variables=envvars),

0 commit comments

Comments
 (0)
0