import unittest from pathlib import PurePosixPath from jinja2 import Environment, StrictUndefined, select_autoescape from utils import PROJECT_ROOT from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE from utils.security.deploy import HOST_PATH_ENV ROLE = PROJECT_ROOT / "roles" / "svc-runner" INSTANCE_ENV = ROLE / "templates" / "runner_instance_env.j2" INSTANCE_TASKS = ROLE / "tasks" / "02_instance.yml" INSTANCE = 2 PATHS = {"RUNNER_INSTALL_DIR": "/srv/runner", "RUNNER_DOCKER_BASE": "/srv/docker"} def _render(text: str) -> str: environment = Environment( undefined=StrictUndefined, autoescape=select_autoescape(default_for_string=False), ) return environment.from_string(text).render( runner_instance=INSTANCE, i=INSTANCE, **PATHS ) def _database_path() -> PurePosixPath | None: line = next( ( line for line in read_text(str(INSTANCE_ENV)).splitlines() if line.startswith(f"{HOST_PATH_ENV}=") ), None, ) if line is None: return None return PurePosixPath(_render(line.partition("=")[2])) def _same_path_mounts() -> list[PurePosixPath]: mounts = [] in_volumes = False for line in read_text(str(ROLE / ROLE_FILE_TEMPL_COMPOSE)).splitlines(): entry = line.strip() if entry == "volumes:": in_volumes = True continue if in_volumes and not entry.startswith("- "): in_volumes = False if in_volumes: source, _, target = _render(entry[2:]).strip('"').partition(":") if source == target: mounts.append(PurePosixPath(source)) return mounts def _runner_owned_dirs() -> list[PurePosixPath]: return [ PurePosixPath(_render(task["file"]["path"])) for task in load_yaml_any(str(INSTANCE_TASKS)) if task.get("file", {}).get("state") == "directory" and task["file"].get("owner") == "{{ RUNNER_USER }}" ] class TestRunnerVulnerabilityDatabasePath(unittest.TestCase): def setUp(self): self.database = _database_path() self.assertIsNotNone(self.database, f"{INSTANCE_ENV} sets no {HOST_PATH_ENV}") def test_the_docker_daemon_sees_the_databases_at_the_runner_path(self): mounts = _same_path_mounts() self.assertTrue(mounts) self.assertTrue( any( self.database.is_relative_to(mount) and self.database != mount for mount in mounts ), (self.database, mounts), ) def test_the_runner_user_can_create_the_databases(self): owned = _runner_owned_dirs() self.assertTrue(owned) self.assertTrue( any(self.database.is_relative_to(directory) for directory in owned), (self.database, owned), ) if __name__ == "__main__": unittest.main()