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
51 changes: 38 additions & 13 deletions osism/tasks/openstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,40 @@ def get_cloud_password(cloud):
return None


SECURE_FILES = {
"/etc/openstack/secure.yml": "/tmp/secure.yml",
"/etc/openstack/secure.yaml": "/tmp/secure.yaml",
}


def _is_vault_encrypted(path):
try:
with open(path, "rb") as f:
return f.read(len(b"$ANSIBLE_VAULT")) == b"$ANSIBLE_VAULT"
except OSError:
return False


def find_secure_file():
"""Return the first plain-text secure.yml/secure.yaml, or None.

openstacksdk cannot read Ansible Vault, so an encrypted file is skipped
with a warning; os_password_<cloud> in secrets.yml replaces it.
"""
for path in SECURE_FILES:
if not os.path.exists(path):
continue
if _is_vault_encrypted(path):
logger.warning(
f"Ignoring {path}: it is vault-encrypted and cannot be read. "
"Use os_password_<cloud> in "
"/opt/configuration/environments/openstack/secrets.yml instead"
)
continue
return path
return None


def get_cloud_helpers():
return setup_cloud_environment, get_openstack_connection, cleanup_cloud_environment

Expand Down Expand Up @@ -546,21 +580,16 @@ def setup_cloud_environment(cloud):

# Fallback: check if /etc/openstack/secure.yml exists (backward compatibility)
if not password:
# Check for secure.yml
if os.path.exists("/etc/openstack/secure.yml"):
src_secure = "/etc/openstack/secure.yml"
dst_secure = "/tmp/secure.yml"
elif os.path.exists("/etc/openstack/secure.yaml"):
src_secure = "/etc/openstack/secure.yaml"
dst_secure = "/tmp/secure.yaml"
else:
src_secure = find_secure_file()
if src_secure is None:
cloud_normalized = cloud.replace("-", "_")
logger.error(
f"No credentials found for cloud '{cloud}'. "
f"Set 'os_password_{cloud_normalized}' in "
"/opt/configuration/environments/openstack/secrets.yml"
)
return None, temp_files_to_cleanup, original_cwd, False
dst_secure = SECURE_FILES[src_secure]

logger.debug(
f"Using /opt/configuration/environments/openstack/secure.yml for cloud '{cloud}'"
Expand Down Expand Up @@ -682,10 +711,6 @@ def get_openstack_connection(cloud, password=None):
import openstack
import keystoneauth1.exceptions

secure_yml_exists = os.path.exists("/etc/openstack/secure.yml") or os.path.exists(
"/etc/openstack/secure.yaml"
)

def try_connect(use_password):
if use_password:
return openstack.connect(cloud=cloud, auth={"password": use_password})
Expand All @@ -703,7 +728,7 @@ def test_connection(conn):
conn = try_connect(password)
return test_connection(conn)
except keystoneauth1.exceptions.http.Unauthorized:
if secure_yml_exists:
if find_secure_file() is not None:
logger.debug(
f"Password from secrets.yml failed for cloud '{cloud}', "
"trying secure.yml fallback"
Expand Down
87 changes: 87 additions & 0 deletions tests/unit/tasks/test_openstack_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ def _exists_only(fake_os, *paths):
fake_os.path.exists.side_effect = lambda path: path in existing


VAULT_HEADER = b"$ANSIBLE_VAULT;1.1;AES256\n6162636465\n"


def _files_with_content(mocker, contents):
"""Patch ``open`` so each path in ``contents`` reads the given bytes."""

def fake_open(path, mode="r"):
return mocker.mock_open(read_data=contents.get(path, b""))(path, mode)

return mocker.patch("builtins.open", side_effect=fake_open)


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -348,6 +360,40 @@ def test_setup_cloud_environment_no_credentials(cloud_env, loguru_logs):
assert _has_log(loguru_logs, "ERROR", "os_password_admin_system")


def test_setup_cloud_environment_ignores_vault_encrypted_secure_yml(
mocker, cloud_env, loguru_logs
):
"""An encrypted secure.yml is not copied: the error points at
``os_password_<cloud>`` instead of an unreadable file reaching the SDK."""
cloud_env.get_cloud_password.return_value = None
_exists_only(cloud_env.os, "/etc/openstack/secure.yml")
_files_with_content(mocker, {"/etc/openstack/secure.yml": VAULT_HEADER})

result = openstack_tasks.setup_cloud_environment("admin")

assert result == (None, [], "/orig", False)
cloud_env.shutil.copy2.assert_not_called()
cloud_env.os.chdir.assert_not_called()
assert _has_log(loguru_logs, "WARNING", "vault-encrypted")
assert _has_log(loguru_logs, "ERROR", "Set 'os_password_admin'")


def test_setup_cloud_environment_encrypted_yml_plain_yaml(mocker, cloud_env):
"""An encrypted secure.yml is skipped in favour of a plain secure.yaml."""
cloud_env.get_cloud_password.return_value = None
_exists_only(
cloud_env.os, "/etc/openstack/secure.yml", "/etc/openstack/secure.yaml"
)
_files_with_content(mocker, {"/etc/openstack/secure.yml": VAULT_HEADER})

result = openstack_tasks.setup_cloud_environment("admin")

cloud_env.shutil.copy2.assert_called_once_with(
"/etc/openstack/secure.yaml", "/tmp/secure.yaml"
)
assert result == (None, ["/tmp/secure.yaml"], "/orig", True)


def test_setup_cloud_environment_copy_error(cloud_env, loguru_logs):
"""A failing copy in the fallback branch fails the setup."""
cloud_env.get_cloud_password.return_value = None
Expand Down Expand Up @@ -454,6 +500,22 @@ def test_connection_password_unauthorized_without_secure_yml(mock_connect, logur
assert _has_log(loguru_logs, "ERROR", "os_password_admin_system")


def test_connection_password_unauthorized_with_encrypted_secure_yml(
mocker, mock_connect, mock_os, loguru_logs
):
"""An encrypted secure.yml is no fallback: ``Unauthorized`` exits with
the ``os_password_<cloud>`` hint instead of retrying."""
_exists_only(mock_os, "/etc/openstack/secure.yml")
_files_with_content(mocker, {"/etc/openstack/secure.yml": VAULT_HEADER})
mock_connect.side_effect = Unauthorized()

with pytest.raises(SystemExit):
openstack_tasks.get_openstack_connection("admin", password="wrong")

mock_connect.assert_called_once_with(cloud="admin", auth={"password": "wrong"})
assert _has_log(loguru_logs, "ERROR", "Check 'os_password_admin'")


def test_connection_password_missing_options(mock_connect, loguru_logs):
mock_connect.side_effect = _missing_options("auth_url")

Expand Down Expand Up @@ -593,3 +655,28 @@ def test_run_openstack_command_with_cloud_aborts_on_setup_failure(
command_env.run.assert_not_called()
command_env.cleanup.assert_called_once_with([], "/orig")
assert _has_log(loguru_logs, "ERROR", "cloud environment setup failed")


# ---------------------------------------------------------------------------
# _is_vault_encrypted (real files)
# ---------------------------------------------------------------------------


@pytest.mark.parametrize(
"content, expected",
[
(VAULT_HEADER, True),
(b"clouds:\n admin:\n auth:\n password: x\n", False),
(b"", False),
],
ids=["encrypted", "plain", "empty"],
)
def test_is_vault_encrypted(tmp_path, content, expected):
path = tmp_path / "secure.yml"
path.write_bytes(content)

assert openstack_tasks._is_vault_encrypted(str(path)) is expected


def test_is_vault_encrypted_unreadable(tmp_path):
assert openstack_tasks._is_vault_encrypted(str(tmp_path / "missing")) is False