From b1f3164a7e87cddb2a52f270b5d0526342c84c60 Mon Sep 17 00:00:00 2001 From: Angelo Fenoglio Date: Thu, 12 Nov 2026 14:39:52 -0300 Subject: [PATCH 1/6] Standalone account if use --- leverage/modules/credentials.py | 10 +++++++++- tests/test_modules/test_credentials.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/leverage/modules/credentials.py b/leverage/modules/credentials.py index d6ccc9d..60ec28f 100644 --- a/leverage/modules/credentials.py +++ b/leverage/modules/credentials.py @@ -517,11 +517,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"] diff --git a/tests/test_modules/test_credentials.py b/tests/test_modules/test_credentials.py index 1f637ee..59dd0ce 100644 --- a/tests/test_modules/test_credentials.py +++ b/tests/test_modules/test_credentials.py @@ -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. From e5f963042c55376975a8d4391f2cbe9a3f36613e Mon Sep 17 00:00:00 2001 From: Angelo Fenoglio Date: Thu, 12 Nov 2026 14:41:03 -0300 Subject: [PATCH 2/6] Unable to parse config.tf --- leverage/_backend_config.py | 3 +++ tests/test_backend_config.py | 31 ++++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/leverage/_backend_config.py b/leverage/_backend_config.py index fe50368..0994fd8 100644 --- a/leverage/_backend_config.py +++ b/leverage/_backend_config.py @@ -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.") diff --git a/tests/test_backend_config.py b/tests/test_backend_config.py index 9c65db8..eedbdd4 100644 --- a/tests/test_backend_config.py +++ b/tests/test_backend_config.py @@ -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" From be61debb9113fdcf604a1ea19afb904d233c68e2 Mon Sep 17 00:00:00 2001 From: Angelo Fenoglio Date: Thu, 12 Nov 2026 14:41:47 -0300 Subject: [PATCH 3/6] Region validation --- leverage/modules/credentials.py | 7 ++-- tests/test_modules/test_auth.py | 58 ++++----------------------------- 2 files changed, 9 insertions(+), 56 deletions(-) diff --git a/leverage/modules/credentials.py b/leverage/modules/credentials.py index 60ec28f..bc488e6 100644 --- a/leverage/modules/credentials.py +++ b/leverage/modules/credentials.py @@ -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)" ACCOUNT_ID = r"[0-9]{12}" MFA_SERIAL = rf"arn:aws:iam::{ACCOUNT_ID}:mfa/{USERNAME}" @@ -483,7 +480,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 diff --git a/tests/test_modules/test_auth.py b/tests/test_modules/test_auth.py index abb994b..41ee0e7 100644 --- a/tests/test_modules/test_auth.py +++ b/tests/test_modules/test_auth.py @@ -10,54 +10,9 @@ from leverage import leverage from leverage._utils import ExitError -from leverage.path import PathsHandler -from leverage.modules.auth import ( - refresh_layer_credentials, - get_layer_profile, - SkipProfile, - refresh_all_accounts_credentials, -) +from leverage.modules.auth import refresh_layer_credentials, get_layer_profile, SkipProfile from leverage.modules.aws import get_account_roles, add_sso_profile, configure_sso_profiles -# `leverage.modules.aws` resolves to the click Group of the same name, since it is re-exported -# in `leverage/modules/__init__.py`. Patching by string would target that Group instead of the -# module, so the module itself is imported and patched by object. -aws_module = import_module("leverage.modules.aws") - - -@pytest.fixture -def paths(with_click_context, propagate_logs): - """ - Mock PathsHandler used by auth.py functions. - - Backed by a MagicMock(spec=PathsHandler) so unexpected attribute access fails loudly. Path-like - attributes are real PosixPath instances so the patched `pathlib.Path.read_text` and - `configupdater.parser.open` side effects in the tests can resolve files via `data_dict`. - """ - mocked = MagicMock(spec=PathsHandler) - mocked.project = "test" - mocked.project_long = "binbash-test" - mocked.aws_config_file = PosixPath("~/.aws/test/config") - mocked.aws_credentials_file = PosixPath("~/.aws/test/credentials") - mocked.backend_tfvars = PosixPath("~/config/backend.tfvars") - mocked.cwd = PosixPath("~/some/layer") - mocked.sso_cache = PosixPath("~/.aws/test/sso/cache") - mocked.sso_token_file = PosixPath("~/.aws/test/sso/cache/token") - return mocked - - -@pytest.fixture -def mock_sso_token(): - """Mock get_sso_access_token() to return a fixed token without touching disk. - - Patches both bindings (auth.py defines it, aws.py imports it) so any caller in either - module hits the same fake. - """ - with mock.patch("leverage.modules.auth.get_sso_access_token", return_value="testing-token") as m, mock.patch.object( - aws_module, "get_sso_access_token", return_value="testing-token" - ): - yield m - ACC_ROLES = { "accName1": { @@ -111,11 +66,12 @@ def test_add_sso_profile(): @mock.patch("boto3.client") -def test_configure_sso_profiles(mocked_boto, paths, mock_sso_token): - with mock.patch.object(aws_module.ConfigUpdater, "__new__", return_value=mocked_updater): - with mock.patch.object(aws_module, "get_account_roles", return_value=ACC_ROLES): - with mock.patch.object(aws_module, "add_sso_profile") as mocked_add_profile: - configure_sso_profiles(paths) +def test_configure_sso_profiles(mocked_boto, leverage_state): + + with mock.patch("leverage.modules.aws.ConfigUpdater.__new__", return_value=mocked_updater): + with mock.patch("leverage.modules.aws.get_account_roles", return_value=ACC_ROLES): + with mock.patch("leverage.modules.aws.add_sso_profile") as mocked_add_profile: + configure_sso_profiles() # 2 profiles were added assert mocked_add_profile.call_args_list[0].args[1:] == ( From 1b24a1392c7fc1fbb6e604f9b8b14a6ebe8e6270 Mon Sep 17 00:00:00 2001 From: Angelo Fenoglio Date: Thu, 12 Nov 2026 14:47:32 -0300 Subject: [PATCH 4/6] Region validation --- tests/conftest.py | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 51596d7..b7fa7ad 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -186,17 +186,7 @@ def leverage_runner(monkeypatch): working_directory: Optional working directory (defaults to account/us-east-1/security-base) """ from contextlib import contextmanager - from leverage.modules import tf, auth - from leverage.modules.tfrunner import TFRunner - - def skip_binary_validation(tf_runner): - """Accept the binary as is, without looking it up in PATH nor checking its version. - - Tests using this fixture mock the actual execution, and the binary is not necessarily - installed where the suite runs. `TFRunner` binary discovery is covered on its own in - tests/test_modules/test_tfrunner.py. - """ - tf_runner.binary_path = str(tf_runner.binary_input) + from leverage.modules import auth @contextmanager def runner(leverage_directory): @@ -232,23 +222,33 @@ def runner(leverage_directory): @pytest.fixture -def leverage_context(leverage_project, monkeypatch): - def context(verbose=True, build_script_name="build.py"): - # Set current working directory to security-base layer - working_dir = leverage_project / "account" / "us-east-1" / "security-base" +def leverage_state(monkeypatch): + from contextlib import contextmanager + from leverage.modules import auth + + @contextmanager + def state(leverage_directory, verbose=True): + # Determine working directory + working_directory = Path(leverage_directory) / "account" / "us-east-1" / "security-base" + + # Ensure paths are Path objects + leverage_directory = Path(leverage_directory) + working_directory = Path(working_directory) - # Mock Path.cwd() to return the working directory - monkeypatch.setattr(Path, "cwd", lambda: working_dir) + # Apply patches to leverage.path module + monkeypatch.setattr(lepath, "get_root_path", lambda: leverage_directory) + monkeypatch.setattr(lepath, "get_working_path", lambda: working_directory) + monkeypatch.setattr(Path, "cwd", lambda: working_directory) - # Update get_working_path to return the security-base directory - monkeypatch.setattr(lepath, "get_working_path", lambda: working_dir) + # Also patch in conf module since it imports these functions directly + monkeypatch.setattr(conf, "get_root_path", lambda: leverage_directory) + monkeypatch.setattr(conf, "get_working_path", lambda: working_directory) state = State() state.verbosity = verbose - state.module = Module(name=build_script_name) state.config = conf.load() - state.paths = PathsHandler() + state.paths = PathsHandler(state.config) - return click.Context(command=click.Command("leverage"), obj=state) + return state - return context + return state From 87be9d98d3648058cc16cbb5e26947eb1be42ca5 Mon Sep 17 00:00:00 2001 From: Angelo Fenoglio Date: Thu, 12 Nov 2026 14:51:54 -0300 Subject: [PATCH 5/6] Region validation --- tests/test_modules/test_auth.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_modules/test_auth.py b/tests/test_modules/test_auth.py index 41ee0e7..5590493 100644 --- a/tests/test_modules/test_auth.py +++ b/tests/test_modules/test_auth.py @@ -67,7 +67,6 @@ def test_add_sso_profile(): @mock.patch("boto3.client") def test_configure_sso_profiles(mocked_boto, leverage_state): - with mock.patch("leverage.modules.aws.ConfigUpdater.__new__", return_value=mocked_updater): with mock.patch("leverage.modules.aws.get_account_roles", return_value=ACC_ROLES): with mock.patch("leverage.modules.aws.add_sso_profile") as mocked_add_profile: From 9c4b05b557e8e28dede6222160e378afb57cf625 Mon Sep 17 00:00:00 2001 From: Angelo Fenoglio Date: Thu, 12 Nov 2026 14:59:08 -0300 Subject: [PATCH 6/6] Region validation --- tests/conftest.py | 46 +++++++++++++------------- tests/test_modules/test_auth.py | 57 +++++++++++++++++++++++++++++---- 2 files changed, 74 insertions(+), 29 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index b7fa7ad..51596d7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -186,7 +186,17 @@ def leverage_runner(monkeypatch): working_directory: Optional working directory (defaults to account/us-east-1/security-base) """ from contextlib import contextmanager - from leverage.modules import auth + from leverage.modules import tf, auth + from leverage.modules.tfrunner import TFRunner + + def skip_binary_validation(tf_runner): + """Accept the binary as is, without looking it up in PATH nor checking its version. + + Tests using this fixture mock the actual execution, and the binary is not necessarily + installed where the suite runs. `TFRunner` binary discovery is covered on its own in + tests/test_modules/test_tfrunner.py. + """ + tf_runner.binary_path = str(tf_runner.binary_input) @contextmanager def runner(leverage_directory): @@ -222,33 +232,23 @@ def runner(leverage_directory): @pytest.fixture -def leverage_state(monkeypatch): - from contextlib import contextmanager - from leverage.modules import auth - - @contextmanager - def state(leverage_directory, verbose=True): - # Determine working directory - working_directory = Path(leverage_directory) / "account" / "us-east-1" / "security-base" - - # Ensure paths are Path objects - leverage_directory = Path(leverage_directory) - working_directory = Path(working_directory) +def leverage_context(leverage_project, monkeypatch): + def context(verbose=True, build_script_name="build.py"): + # Set current working directory to security-base layer + working_dir = leverage_project / "account" / "us-east-1" / "security-base" - # Apply patches to leverage.path module - monkeypatch.setattr(lepath, "get_root_path", lambda: leverage_directory) - monkeypatch.setattr(lepath, "get_working_path", lambda: working_directory) - monkeypatch.setattr(Path, "cwd", lambda: working_directory) + # Mock Path.cwd() to return the working directory + monkeypatch.setattr(Path, "cwd", lambda: working_dir) - # Also patch in conf module since it imports these functions directly - monkeypatch.setattr(conf, "get_root_path", lambda: leverage_directory) - monkeypatch.setattr(conf, "get_working_path", lambda: working_directory) + # Update get_working_path to return the security-base directory + monkeypatch.setattr(lepath, "get_working_path", lambda: working_dir) state = State() state.verbosity = verbose + state.module = Module(name=build_script_name) state.config = conf.load() - state.paths = PathsHandler(state.config) + state.paths = PathsHandler() - return state + return click.Context(command=click.Command("leverage"), obj=state) - return state + return context diff --git a/tests/test_modules/test_auth.py b/tests/test_modules/test_auth.py index 5590493..abb994b 100644 --- a/tests/test_modules/test_auth.py +++ b/tests/test_modules/test_auth.py @@ -10,9 +10,54 @@ from leverage import leverage from leverage._utils import ExitError -from leverage.modules.auth import refresh_layer_credentials, get_layer_profile, SkipProfile +from leverage.path import PathsHandler +from leverage.modules.auth import ( + refresh_layer_credentials, + get_layer_profile, + SkipProfile, + refresh_all_accounts_credentials, +) from leverage.modules.aws import get_account_roles, add_sso_profile, configure_sso_profiles +# `leverage.modules.aws` resolves to the click Group of the same name, since it is re-exported +# in `leverage/modules/__init__.py`. Patching by string would target that Group instead of the +# module, so the module itself is imported and patched by object. +aws_module = import_module("leverage.modules.aws") + + +@pytest.fixture +def paths(with_click_context, propagate_logs): + """ + Mock PathsHandler used by auth.py functions. + + Backed by a MagicMock(spec=PathsHandler) so unexpected attribute access fails loudly. Path-like + attributes are real PosixPath instances so the patched `pathlib.Path.read_text` and + `configupdater.parser.open` side effects in the tests can resolve files via `data_dict`. + """ + mocked = MagicMock(spec=PathsHandler) + mocked.project = "test" + mocked.project_long = "binbash-test" + mocked.aws_config_file = PosixPath("~/.aws/test/config") + mocked.aws_credentials_file = PosixPath("~/.aws/test/credentials") + mocked.backend_tfvars = PosixPath("~/config/backend.tfvars") + mocked.cwd = PosixPath("~/some/layer") + mocked.sso_cache = PosixPath("~/.aws/test/sso/cache") + mocked.sso_token_file = PosixPath("~/.aws/test/sso/cache/token") + return mocked + + +@pytest.fixture +def mock_sso_token(): + """Mock get_sso_access_token() to return a fixed token without touching disk. + + Patches both bindings (auth.py defines it, aws.py imports it) so any caller in either + module hits the same fake. + """ + with mock.patch("leverage.modules.auth.get_sso_access_token", return_value="testing-token") as m, mock.patch.object( + aws_module, "get_sso_access_token", return_value="testing-token" + ): + yield m + ACC_ROLES = { "accName1": { @@ -66,11 +111,11 @@ def test_add_sso_profile(): @mock.patch("boto3.client") -def test_configure_sso_profiles(mocked_boto, leverage_state): - with mock.patch("leverage.modules.aws.ConfigUpdater.__new__", return_value=mocked_updater): - with mock.patch("leverage.modules.aws.get_account_roles", return_value=ACC_ROLES): - with mock.patch("leverage.modules.aws.add_sso_profile") as mocked_add_profile: - configure_sso_profiles() +def test_configure_sso_profiles(mocked_boto, paths, mock_sso_token): + with mock.patch.object(aws_module.ConfigUpdater, "__new__", return_value=mocked_updater): + with mock.patch.object(aws_module, "get_account_roles", return_value=ACC_ROLES): + with mock.patch.object(aws_module, "add_sso_profile") as mocked_add_profile: + configure_sso_profiles(paths) # 2 profiles were added assert mocked_add_profile.call_args_list[0].args[1:] == (