Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions leverage/_backend_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,5 +168,8 @@ def get_backend_key(config_file: Union[str, Path]) -> Optional[str]:
f"Possible invalid expression in [bold]config.tf[/bold] near line {error.line}, column {error.column}\n"
f"{error.get_context(config_content)}",
)
except ExitError:
# Let our own, more specific errors (e.g. missing backend block) through untouched
raise
except Exception:
raise ExitError(1, f"Malformed [bold]config.tf[/bold] file. Unable to parse.")
17 changes: 11 additions & 6 deletions leverage/modules/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,7 @@
# https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html#API_CreateUser_RequestParameters
KEY_ID = r"[A-Z0-9]{20}"
SECRET_KEY = r"[a-zA-Z0-9/\+]{40}"
REGION = (
r"[a-z]{2}-[gov-]?"
r"(?:central|north|south|east|west|northeast|northwest|southeast|southwest|secret|topsecret)-[1-3]"
)
REGION = r"(([a-z]{2}(-gov)?)-(central|(north|south)?(east|west)?)-\d)"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Direction token is fully optional, so the region check accepts invalid names

Both optional groups in (north|south)?(east|west)? can match empty, so re.fullmatch(REGION, ...) accepts strings like us--1 or us-1 as valid regions. Making the outer direction group required while keeping the compass prefix optional preserves the intended loosening (ap-southeast-4, us-gov-west-1, mx-central-1) without accepting directionless names.

Suggested change
REGION = r"(([a-z]{2}(-gov)?)-(central|(north|south)?(east|west)?)-\d)"
REGION = r"(([a-z]{2}(-gov)?)-(central|(north|south)?(east|west))-\d)"

ACCOUNT_ID = r"[0-9]{12}"
MFA_SERIAL = rf"arn:aws:iam::{ACCOUNT_ID}:mfa/{USERNAME}"

Expand Down Expand Up @@ -484,7 +481,7 @@ def _credentials_are_valid(awscli: Runner, profile: str):
"""
error_code, output, _ = awscli.exec("sts", "get-caller-identity", "--profile", profile, raises=False)

return error_code != 255 and "InvalidClientTokenId" not in output
return error_code == 0


@pass_runner
Expand Down Expand Up @@ -518,11 +515,19 @@ def _get_organization_accounts(awscli: Runner, profile: str, project_name: str):
Returns:
dict: Mapping of organization accounts names to ids.
"""
exit_code, organization_accounts, _ = awscli.exec(
exit_code, organization_accounts, error = awscli.exec(
"organizations", "list-accounts", "--output", "json", "--profile", profile, raises=False
)

if exit_code:
if "AWSOrganizationsNotInUseException" in error:
logger.warning(
"The account is not a member of an AWS Organization (standalone account). "
"Accounts ids will not be fetched from the organization; only the ones already set in the "
"project configuration will be used."
)
else:
logger.warning(f"Unable to fetch organization accounts: {error or organization_accounts}")
return {}

organization_accounts = json.loads(organization_accounts)["Accounts"]
Expand Down
31 changes: 30 additions & 1 deletion tests/test_backend_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,39 @@ def test_set_backend_key_raises_for_missing_backend(config_without_backend):

def test_get_backend_key_raises_for_missing_backend(config_without_backend):
"""Test that get_backend_key raises ExitError when backend block is missing."""
with pytest.raises(ExitError, match="Malformed"):
with pytest.raises(ExitError, match="Missing backend block"):
get_backend_key(config_without_backend)


def test_get_backend_key_reports_missing_backend_when_backend_is_commented_out(tmp_path):
"""A valid config.tf whose backend block is commented out (as in the tf-backend layer template before its first
apply) must report the missing backend, not a generic parsing error."""
config_file = tmp_path / "config.tf"
config_file.write_text(
'provider "aws" {\n'
" region = var.region\n"
"}\n"
"\n"
'provider "aws" {\n'
' alias = "secondary_region"\n'
" region = var.region_secondary\n"
"}\n"
"\n"
"terraform {\n"
' required_version = "~> 1.2"\n'
"\n"
" required_providers {\n"
' aws = "~> 5.0"\n'
" }\n"
' # backend "s3" {\n'
' # key = "management/tf-backend/terraform.tfstate"\n'
" # }\n"
"}\n"
)
with pytest.raises(ExitError, match="Missing backend block"):
get_backend_key(config_file)


def test_set_backend_key_with_complex_formatting(tmp_path):
"""Test with various formatting styles."""
config_file = tmp_path / "config.tf"
Expand Down
16 changes: 16 additions & 0 deletions tests/test_modules/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,22 @@ def test_get_organization_accounts_error():
assert _get_organization_accounts("foo", "bar") == {}


def test_get_organization_accounts_standalone_account(propagate_logs, caplog):
"""
Test that a standalone account (not member of an AWS Organization) is reported clearly and an empty dict returned.
"""
awscli = awscli_returning(
254,
"",
"An error occurred (AWSOrganizationsNotInUseException) when calling the ListAccounts operation: "
"Your account is not a member of an organization.",
)
with cli_context(runner=awscli):
assert _get_organization_accounts("foo", "bar") == {}

assert "not a member of an AWS Organization" in caplog.text


def test_get_mfa_serial():
"""
Test that we fetch the mfa devices from the profile and return the serial number of the first one that is valid.
Expand Down
Loading