From 1ab0b17a2c0c7bfe3e5cc0ac93342e390f0a6d0d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Radoslav=20Bod=C3=B3?= <bodik@cesnet.cz>
Date: Tue, 16 Apr 2024 10:16:23 +0200
Subject: [PATCH] rwm: improve config file handling (handle missing file, check
 and warn on permissions)

---
 rwm.py                | 14 +++++++++++---
 tests/test_default.py |  3 +++
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/rwm.py b/rwm.py
index e41fcdc..b356219 100755
--- a/rwm.py
+++ b/rwm.py
@@ -713,8 +713,14 @@ def load_config(path):
     """load config dict from file"""
 
     config = {}
-    if path:
-        config = yaml.safe_load(Path(path).read_text(encoding='utf-8'))
+    try:
+        config_path = Path(path)
+        config_perms = config_path.stat().st_mode & 0o777
+        if config_perms != 0o600:
+            logger.warning(f"config file permissions ({config_perms:o}) are too-open")
+        config = yaml.safe_load(config_path.read_text(encoding='utf-8'))
+    except (OSError, ValueError) as exc:
+        logger.error(f"cannot load config file, {exc}")
     logger.debug("config, %s", config)
     return config
 
@@ -725,7 +731,9 @@ def main(argv=None):  # pylint: disable=too-many-branches
     args = parse_arguments(argv)
     configure_logging(args.debug)
 
-    rwmi = RWM(load_config(args.config))
+    if not (config_dict := load_config(args.config)):
+        return 1
+    rwmi = RWM(config_dict)
     ret = -1
 
     if args.command == "version":
diff --git a/tests/test_default.py b/tests/test_default.py
index 9f19cc5..7b69848 100644
--- a/tests/test_default.py
+++ b/tests/test_default.py
@@ -70,3 +70,6 @@ def test_main():
 
     with patch.object(rwm.RWM, "storage_restore_state", mock_ok):
         assert _rwm_minconfig(["storage-restore-state", "bucket", "bucket", "state"]) == 0
+
+    # error handling
+    assert rwm_main(["--config", "notexist", "version"]) == 1
-- 
GitLab