From 3b1e4e7436558789a17ff8d176d017da71b9e4d5 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Tue, 1 Dec 2026 15:18:20 +0100 Subject: [PATCH] Skip a vault-encrypted secure.yml in the CLI The osism CLI reads the OpenStack admin password from os_password_ in environments/openstack/secrets.yml. If that secret is missing, it falls back to a legacy /etc/openstack/secure.yml (or secure.yaml) and copies it to /tmp for openstacksdk. That fallback did not check the file's format. A secure.yml committed vault-encrypted, like every other secret in the configuration repository, was handed to openstacksdk, which cannot read Ansible Vault. The command then failed with "Configuration file ... is empty or not a valid mapping", which points neither at the encryption nor at os_password_. A new helper, find_secure_file(), returns the first secure file that is not vault-encrypted, detected by the $ANSIBLE_VAULT header, and logs a warning for each encrypted one it skips. Both places that consulted the fallback use it: - setup_cloud_environment() treats an encrypted file as absent. Without os_password_, the command now ends with the existing "No credentials found for cloud ... Set 'os_password_' in .../secrets.yml" error. - get_openstack_connection() no longer retries without the password override after Unauthorized when the only secure file is encrypted. It reports "Authentication failed ... Check 'os_password_'" instead. A plain-text secure.yml keeps working as a fallback, as before. The osism-ansible run scripts treat an encrypted secure.yml the same way for plays in the openstack environment. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/tasks/openstack.py | 51 +++++++++++---- tests/unit/tasks/test_openstack_env.py | 87 ++++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 13 deletions(-) diff --git a/osism/tasks/openstack.py b/osism/tasks/openstack.py index cf79dc8c3..e25ebecb9 100644 --- a/osism/tasks/openstack.py +++ b/osism/tasks/openstack.py @@ -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_ 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_ 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 @@ -546,14 +580,8 @@ 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}'. " @@ -561,6 +589,7 @@ def setup_cloud_environment(cloud): "/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}'" @@ -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}) @@ -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" diff --git a/tests/unit/tasks/test_openstack_env.py b/tests/unit/tasks/test_openstack_env.py index 80098f376..eb44781be 100644 --- a/tests/unit/tasks/test_openstack_env.py +++ b/tests/unit/tasks/test_openstack_env.py @@ -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 # --------------------------------------------------------------------------- @@ -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_`` 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 @@ -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_`` 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") @@ -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