diff --git a/leverage/modules/project.py b/leverage/modules/project.py index f5b1430..084ed9c 100644 --- a/leverage/modules/project.py +++ b/leverage/modules/project.py @@ -2,6 +2,7 @@ Module for managing Leverage projects. """ +import ipaddress import re from pathlib import Path from shutil import copy2 @@ -35,6 +36,19 @@ CONFIG_DIRECTORY = "config" +# project.yaml validation +EMAIL = r"^[^@\s<>]+@[^@\s<>]+\.[^@\s<>]+$" +HCL_IDENTIFIER = r"^[a-zA-Z_][a-zA-Z0-9_-]*$" +SCP_POLICY = r"^aws_organizations_policy\.[a-zA-Z_][a-zA-Z0-9_-]*$" +NETWORK_FIELDS = ( + "cidr_block", + "availability_zones", + "private_subnets_cidr", + "private_subnets", + "public_subnets_cidr", + "public_subnets", +) + # TODO: Keep this structure in the project's directory PROJECT_STRUCTURE = { "management": { @@ -185,7 +199,7 @@ def value(dictionary, key): JINJA_ENV.filters["value"] = value -def _render_templates(template_files, config, source=TEMPLATE_DIR, destination=PROJECT_ROOT): +def _render_templates(template_files, config, source=TEMPLATE_DIR, destination=None): """Render the given templates using the given configuration values. Args: @@ -193,15 +207,19 @@ def _render_templates(template_files, config, source=TEMPLATE_DIR, destination=P templates to render. config (dict): Values to replace in the templates. source (Path, optional): Source directory of the templates. Defaults to TEMPLATE_DIR. - destination (Path, optional): Destination where to render the templates. Defaults to PROJECT_ROOT. + destination (Path, optional): Destination where to render the templates. Defaults to PROJECT_ROOT, + resolved at call time so it always matches the project root the rest of the module is using. """ + if destination is None: + destination = PROJECT_ROOT + + # Optional, an empty value makes the CLI look for `tofu`/`terraform` in PATH + config.setdefault("tf_binary", "") + for template_file in template_files: template_location = template_file.relative_to(TEMPLATES_REPO_DIR) template = JINJA_ENV.get_template(template_location.as_posix()) - if "terraform_image_tag" not in config: - config["terraform_image_tag"] = "" - rendered_template = template.render(config) rendered_location = template_file.relative_to(source) @@ -222,14 +240,13 @@ def _render_templates(template_files, config, source=TEMPLATE_DIR, destination=P rendered_location.write_text(rendered_template) -def _render_account_templates(account, config, source=TEMPLATE_DIR): - account_name = account["name"] +def _render_account_templates(account_name, config, source=TEMPLATE_DIR): logger.info(f"Account: Setting up [bold]{account_name}[/bold].") account_dir = source / account_name layers = [CONFIG_DIRECTORY] - for account_name, account_layers in PROJECT_STRUCTURE[account_name].items(): - layers = layers + [f"{account_name}/{layer}" for layer in account_layers] + for location, location_layers in PROJECT_STRUCTURE[account_name].items(): + layers = layers + [f"{location}/{layer}" for layer in location_layers] for layer in layers: logger.info(f"\tLayer: Setting up [bold]{layer.split('/')[-1]}[/bold].") @@ -249,8 +266,8 @@ def _render_project_template(config, source=TEMPLATE_DIR): _render_templates(template_files=template_files, config=config, source=source) # Render each account's templates - for account in config["organization"]["accounts"]: - _render_account_templates(account=account, config=config, source=source) + for account_name in PROJECT_STRUCTURE: + _render_account_templates(account_name=account_name, config=config, source=source) logger.info("Project configuration finished.") @@ -293,9 +310,150 @@ def validate_config(config: dict): "Project short name is not valid. Only lowercase alphabetic characters are allowed. It must be between 2 and 4 characters long.", ) + tf_binary = config.get("tf_binary") + if tf_binary is not None and not isinstance(tf_binary, str): + raise ExitError(1, "[bold]tf_binary[/bold] must be the path to the OpenTofu/Terraform binary.") + + _validate_organization_accounts(config) + _validate_organizational_units(config) + _validate_shared_network(config) + return True +def _validate_organization_accounts(config: dict): + """ + The accounts of the organization must be exactly the ones the project structure is able to create. + """ + accounts = (config.get("organization") or {}).get("accounts") or [] + if not isinstance(accounts, list) or not all(isinstance(account, dict) for account in accounts): + raise ExitError(1, "[bold]organization.accounts[/bold] must be a list of accounts with a name and an email.") + + names = [account.get("name") for account in accounts] + unknown = [str(name) for name in names if name not in PROJECT_STRUCTURE] + missing = [name for name in PROJECT_STRUCTURE if name not in names] + duplicated = sorted({str(name) for name in names if names.count(name) > 1}) + + if unknown or missing or duplicated: + raise ExitError( + 1, + f"The [bold]organization.accounts[/bold] must be exactly: {', '.join(PROJECT_STRUCTURE)}.\n" + + (f" Unknown: {', '.join(unknown)}\n" if unknown else "") + + (f" Missing: {', '.join(missing)}\n" if missing else "") + + (f" Duplicated: {', '.join(duplicated)}\n" if duplicated else "") + + "Additional accounts can be added once the project has been created.", + ) + + for account in accounts: + if not re.match(EMAIL, str(account.get("email") or "")): + raise ExitError(1, f"Invalid or missing email for account [bold]{account['name']}[/bold].") + + +def _validate_organizational_units(config: dict): + """ + Every member account (all but management) must belong to exactly one organizational unit, since the + organizations layer creates each of them under its parent unit. + """ + organizational_units = (config.get("organization") or {}).get("organizational_units") or [] + if not isinstance(organizational_units, list) or not all(isinstance(unit, dict) for unit in organizational_units): + raise ExitError( + 1, + "[bold]organization.organizational_units[/bold] must be a list of units with a name, policy and accounts.", + ) + + parents = {account: [] for account in PROJECT_STRUCTURE if account != "management"} + unit_names = [] + for unit in organizational_units: + name = unit.get("name") + if not isinstance(name, str) or not re.match(HCL_IDENTIFIER, name): + raise ExitError(1, f"Invalid organizational unit name [bold]{name}[/bold].") + unit_names.append(name) + + # The organizations layer attaches a single policy per unit + policies = unit.get("policy") + if ( + not isinstance(policies, list) + or len(policies) != 1 + or not isinstance(policies[0], str) + or not re.match(SCP_POLICY, policies[0]) + ): + raise ExitError( + 1, + f"Organizational unit [bold]{name}[/bold] must have a [bold]policy[/bold] list with exactly one " + "organization policy, e.g. [aws_organizations_policy.default].", + ) + + unit_accounts = unit.get("accounts") or [] + if not isinstance(unit_accounts, list): + raise ExitError(1, f"The accounts of organizational unit [bold]{name}[/bold] must be a list.") + + for account in unit_accounts: + if account == "management": + raise ExitError(1, "The management account can not be part of an organizational unit.") + if account not in parents: + raise ExitError( + 1, + f"Organizational unit [bold]{name}[/bold] references unknown account [bold]{account}[/bold]. " + f"Valid accounts are: {', '.join(parents)}.", + ) + parents[account].append(name) + + duplicated = sorted({name for name in unit_names if unit_names.count(name) > 1}) + if duplicated: + raise ExitError(1, f"Duplicated organizational units: {', '.join(duplicated)}.") + + orphans = [account for account, units in parents.items() if not units] + multiple = [account for account, units in parents.items() if len(units) > 1] + if orphans or multiple: + raise ExitError( + 1, + "Each account other than management must belong to exactly one organizational unit.\n" + + (f" Without unit: {', '.join(orphans)}\n" if orphans else "") + + (f" In more than one unit: {', '.join(multiple)}\n" if multiple else ""), + ) + + +def _validate_shared_network(config: dict): + """ + Only the network of the shared account can be configured, and it is required by its base-network layer. + """ + accounts = config.get("accounts") or {} + if not isinstance(accounts, dict): + raise ExitError(1, "[bold]accounts[/bold] must be a mapping containing the [bold]shared[/bold] account.") + + unknown = [str(account) for account in accounts if account != "shared"] + if unknown: + raise ExitError( + 1, + f"Only the [bold]shared[/bold] account can be configured under [bold]accounts[/bold]. Found: {', '.join(unknown)}.", + ) + + networks = (accounts.get("shared") or {}).get("networks") + if not isinstance(networks, list) or not networks or not isinstance(networks[0], dict): + raise ExitError(1, "[bold]accounts.shared.networks[/bold] must define at least one network.") + + network = networks[0] + missing = [field for field in NETWORK_FIELDS if not network.get(field)] + if missing: + raise ExitError(1, f"The shared account network is missing: {', '.join(missing)}.") + + zones = network["availability_zones"] + if not isinstance(zones, list) or not all(isinstance(zone, str) and re.match(r"^[a-z]$", zone) for zone in zones): + raise ExitError(1, "[bold]availability_zones[/bold] must be a list of zone letters, e.g. [a, b].") + + cidrs = [network["cidr_block"], network["private_subnets_cidr"], network["public_subnets_cidr"]] + for subnets_field in ("private_subnets", "public_subnets"): + if not isinstance(network[subnets_field], list): + raise ExitError(1, f"[bold]{subnets_field}[/bold] must be a list of CIDR blocks.") + cidrs.extend(network[subnets_field]) + + for cidr in cidrs: + try: + ipaddress.ip_network(str(cidr)) + except ValueError: + raise ExitError(1, f"Invalid CIDR block [bold]{cidr}[/bold] in the shared account network.") + + @project.command() def create(): """Create the directory structure required by the project configuration and set up each account accordingly.""" @@ -314,6 +472,12 @@ def create(): validate_config(config) + # Keep the rendered accounts in the same order as the project structure + account_order = list(PROJECT_STRUCTURE) + config["organization"]["accounts"] = sorted( + config["organization"]["accounts"], key=lambda account: account_order.index(account["name"]) + ) + # Make project structure _copy_project_template(config=config) diff --git a/tests/test_modules/test_project.py b/tests/test_modules/test_project.py index 6fdf465..4d0b354 100644 --- a/tests/test_modules/test_project.py +++ b/tests/test_modules/test_project.py @@ -1,13 +1,56 @@ +import copy import subprocess +from importlib import import_module from pathlib import Path +from unittest import mock import pytest from click.testing import CliRunner +from jinja2 import FileSystemLoader from leverage import conf, leverage from leverage import path as lepath from leverage._utils import ExitError -from leverage.modules.project import validate_config + +from leverage.modules.project import PROJECT_STRUCTURE, create, validate_config + +project_module = import_module("leverage.modules.project") + +VALID_CONFIG = { + "project_name": "test", + "short_name": "ok", + "primary_region": "us-east-1", + "secondary_region": "us-west-2", + "organization": { + "accounts": [ + {"name": "management", "email": "aws+management@example.com"}, + {"name": "security", "email": "aws+security@example.com"}, + {"name": "shared", "email": "aws+shared@example.com"}, + ], + "organizational_units": [ + {"name": "security", "policy": ["aws_organizations_policy.default"], "accounts": ["security"]}, + {"name": "shared", "policy": ["aws_organizations_policy.standard"], "accounts": ["shared"]}, + ], + }, + "accounts": { + "shared": { + "networks": [ + { + "cidr_block": "172.20.0.0/20", + "availability_zones": ["a", "b"], + "private_subnets_cidr": "172.20.0.0/21", + "private_subnets": ["172.20.0.0/23", "172.20.2.0/23"], + "public_subnets_cidr": "172.20.8.0/21", + "public_subnets": ["172.20.8.0/23", "172.20.10.0/23"], + } + ] + } + }, +} + + +def valid_config(**overrides): + return {**copy.deepcopy(VALID_CONFIG), **overrides} def test_project_commands_run_before_the_project_configuration_exists(tmp_path, monkeypatch): @@ -50,7 +93,7 @@ def test_project_commands_run_before_the_project_configuration_exists(tmp_path, ], ) def test_validate_config_happy_path(project_name, short_name): - assert validate_config({"project_name": project_name, "short_name": short_name}) + assert validate_config(valid_config(project_name=project_name, short_name=short_name)) @pytest.mark.parametrize( @@ -80,3 +123,176 @@ def test_validate_config_project_name_errors(muted_click_context, invalid_name): def test_validate_config_short_project_name_errors(muted_click_context, invalid_name): with pytest.raises(ExitError, match="Project short name is not valid"): validate_config({"project_name": "test", "short_name": invalid_name}) + + +def _set(path, value): + """Return a mutator that sets `value` at the given path (keys and list indexes) of a config.""" + + def mutate(config): + target = config + for step in path[:-1]: + target = target[step] + target[path[-1]] = value + + return mutate + + +def _delete(path): + def mutate(config): + target = config + for step in path[:-1]: + target = target[step] + del target[path[-1]] + + return mutate + + +def _append_account(account): + return lambda config: config["organization"]["accounts"].append(account) + + +@pytest.mark.parametrize( + "mutate,error", + [ + # organization accounts + (_append_account({"name": "apps-devstg", "email": "a@example.com"}), "Unknown: apps-devstg"), + (_delete(["organization", "accounts", 1]), "Missing: security"), + (_append_account({"name": "shared", "email": "a@example.com"}), "Duplicated: shared"), + (_delete(["organization", "accounts"]), "Missing: management, security, shared"), + (_set(["tf_binary"], 123), "tf_binary"), + (_set(["organization", "accounts"], "management"), "must be a list of accounts"), + (_set(["organization", "accounts", 0, "email"], ""), "email for account"), + (_delete(["organization", "accounts", 2, "email"]), "email for account"), + # organizational units + (_delete(["organization", "organizational_units"]), "Without unit: security, shared"), + (_delete(["organization", "organizational_units", 1]), "Without unit: shared"), + ( + _set(["organization", "organizational_units", 0, "accounts"], ["security", "shared"]), + "In more than one unit: shared", + ), + (_set(["organization", "organizational_units", 0, "accounts"], ["apps-devstg"]), "unknown account"), + (_set(["organization", "organizational_units", 0, "accounts"], ["management"]), "management account"), + (_set(["organization", "organizational_units", 0, "name"], "has spaces"), "organizational unit name"), + (_set(["organization", "organizational_units", 1, "name"], "security"), "Duplicated organizational units"), + (_set(["organization", "organizational_units", 0, "policy"], []), "policy"), + (_set(["organization", "organizational_units", 0, "policy"], ["default"]), "policy"), + (_set(["organization", "organizational_units", 0, "policy"], "aws_organizations_policy.default"), "policy"), + ( + _set( + ["organization", "organizational_units", 0, "policy"], + ["aws_organizations_policy.default", "aws_organizations_policy.standard"], + ), + "exactly one", + ), + # shared network + (_set(["accounts", "management"], {"networks": []}), "Only the .*shared.* account"), + (_delete(["accounts"]), "must define at least one network"), + (_set(["accounts", "shared", "networks"], []), "must define at least one network"), + (_delete(["accounts", "shared", "networks", 0, "public_subnets"]), "missing: public_subnets"), + (_set(["accounts", "shared", "networks", 0, "availability_zones"], ["us-east-1a"]), "availability_zones"), + (_set(["accounts", "shared", "networks", 0, "cidr_block"], "172.20.0.0/40"), "Invalid CIDR block"), + (_set(["accounts", "shared", "networks", 0, "private_subnets"], ["nope"]), "Invalid CIDR block"), + ], +) +def test_validate_config_structure_errors(muted_click_context, mutate, error): + config = valid_config() + mutate(config) + + with pytest.raises(ExitError, match=error): + validate_config(config) + + +def test_render_project_template_renders_every_account_in_the_project_structure(tmp_path): + """Accounts are rendered from PROJECT_STRUCTURE, not from the order or content of project.yaml.""" + config = valid_config() + config["organization"]["accounts"].reverse() + + with mock.patch.object(project_module, "_render_templates"), mock.patch.object( + project_module, "_render_account_templates" + ) as mocked_render_account: + project_module._render_project_template(config=config, source=tmp_path) + + rendered = [call.kwargs["account_name"] for call in mocked_render_account.call_args_list] + assert rendered == list(PROJECT_STRUCTURE) + + +def test_create_with_extra_account_fails_before_touching_the_project(muted_click_context, tmp_path, monkeypatch): + config = valid_config() + config["organization"]["accounts"].append({"name": "apps-devstg", "email": "a@example.com"}) + monkeypatch.setattr(project_module, "PROJECT_ROOT", tmp_path) + monkeypatch.setattr(project_module, "load_project_config", lambda: config) + + with mock.patch.object(project_module, "_copy_project_template") as mocked_copy, mock.patch.object( + project_module, "_render_project_template" + ) as mocked_render: + with pytest.raises(ExitError, match="Unknown: apps-devstg"): + create.callback() + + mocked_copy.assert_not_called() + mocked_render.assert_not_called() + assert not (tmp_path / "config").exists() + + +def test_create_orders_accounts_like_the_project_structure(tmp_path, monkeypatch): + config = valid_config() + config["organization"]["accounts"].reverse() + monkeypatch.setattr(project_module, "PROJECT_ROOT", tmp_path) + monkeypatch.setattr(project_module, "load_project_config", lambda: config) + + with mock.patch.object(project_module, "_copy_project_template"), mock.patch.object( + project_module, "_render_project_template" + ) as mocked_render, mock.patch.object(project_module, "TFRunner"): + create.callback() + + rendered_config = mocked_render.call_args.kwargs["config"] + assert [account["name"] for account in rendered_config["organization"]["accounts"]] == list(PROJECT_STRUCTURE) + + +def test_render_templates_writes_to_the_current_project_root(tmp_path, monkeypatch): + """The default destination must be resolved when rendering, not frozen at import time, so it always + follows PROJECT_ROOT (and never writes into whatever directory the module was imported from).""" + templates_repo = tmp_path / "templates" + source = templates_repo / "template" + source.mkdir(parents=True) + template_file = source / "build.env.template" + template_file.write_text("PROJECT={{ short_name }}") + + project_root = tmp_path / "project" + project_root.mkdir() + monkeypatch.setattr(project_module, "PROJECT_ROOT", project_root) + monkeypatch.setattr(project_module, "TEMPLATES_REPO_DIR", templates_repo) + monkeypatch.setattr( + project_module, "JINJA_ENV", project_module.Environment(loader=FileSystemLoader(templates_repo.as_posix())) + ) + + project_module._render_templates([template_file], config={"short_name": "ok"}, source=source) + + assert (project_root / "build.env").read_text() == "PROJECT=ok" + + +@pytest.mark.parametrize( + "config,expected", + [ + ({"short_name": "ok"}, "TF_BINARY="), + ({"short_name": "ok", "tf_binary": "~/bin/tofu"}, "TF_BINARY=~/bin/tofu"), + ], +) +def test_render_templates_tf_binary(tmp_path, monkeypatch, config, expected): + """`tf_binary` from project.yaml ends up as TF_BINARY in build.env, empty (look up in PATH) when not set.""" + templates_repo = tmp_path / "templates" + source = templates_repo / "template" + source.mkdir(parents=True) + template_file = source / "build.env.template" + template_file.write_text("TF_BINARY={{ tf_binary }}") + + project_root = tmp_path / "project" + project_root.mkdir() + monkeypatch.setattr(project_module, "PROJECT_ROOT", project_root) + monkeypatch.setattr(project_module, "TEMPLATES_REPO_DIR", templates_repo) + monkeypatch.setattr( + project_module, "JINJA_ENV", project_module.Environment(loader=FileSystemLoader(templates_repo.as_posix())) + ) + + project_module._render_templates([template_file], config=config, source=source) + + assert (project_root / "build.env").read_text() == expected