repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
test_nixmod.pyPython170 lines8.9 KiBraw download
"""Nixmod regressions: evaluate generated Nix; no network or system activation."""
import contextlib
import copy
import importlib.util
import io
import json
from pathlib import Path
import shutil
import subprocess
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch

SPEC = importlib.util.spec_from_file_location(
    "nixmod", Path(__file__).resolve().parents[1] / "modules/home/_nixmod/nixmod.py")
nixmod = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(nixmod)


def gallery_info():
    prefix = "<name>.programs.gallery-dl"
    return {
        "path": "programs.gallery-dl", "prefix": prefix, "scope": "home", "pkg": None,
        "options": [
            {"name": prefix + ".enable", "type": "boolean"},
            {"name": prefix + ".package", "type": "null or package"},
            {"name": prefix + ".settings", "type": "JSON value",
             "default": {"_type": "literalExpression", "text": "{ }"},
             "example": {"_type": "literalExpression", "text": '{ extractor.base-directory = "~/Downloads"; }'},
             "exampleValue": {"extractor": {"base-directory": "~/Downloads"}}},
        ],
    }


class NixmodTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.repo = Path(self.temp.name)
        (self.repo / "modules/home").mkdir(parents=True)
        (self.repo / "modules/home/default.nix").write_text(
            "{ self, ... }: { flake.homeModules.user = { imports = with self.homeModules; [\n"
            "      existing\n    ]; }; }\n")

    def evaluate(self, text):
        if not shutil.which("nix-instantiate"):
            self.skipTest("Nix is needed to evaluate generated modules")
        path = self.repo / "modules/home/gallery-dl.nix"
        path.write_text(text)
        expr = f'(import {path} {{}}).flake.homeModules.gallery-dl {{ config = {{}}; lib = {{}}; pkgs = {{}}; }}'
        result = subprocess.run(["nix-instantiate", "--eval", "--strict", "--json", "--expr", expr],
                                capture_output=True, text=True)
        self.assertEqual(result.returncode, 0, result.stderr)
        return json.loads(result.stdout)["programs"]["gallery-dl"]

    def test_live_wrapper_preserves_default_and_example_is_easy_to_enable(self):
        text = nixmod.render("gallery-dl", "home", "program", gallery_info())
        self.assertEqual(self.evaluate(text), {"enable": True, "settings": {}})
        text = text.replace('# extractor.base-directory =', 'extractor.base-directory =')
        self.assertEqual(self.evaluate(text)["settings"], {"extractor": {"base-directory": "~/Downloads"}})

    def test_settings_and_typed_values_round_trip_through_nix(self):
        info = gallery_info()
        info["assignments"] = nixmod.assignments(info, [
            "settings.extractor.base-directory=~/Downloads/gallery-dl/",
            'settings.extractor.retries=3', 'settings.extractor.skip=true',
            'settings.extractor.types=["jpg","png"]', 'enable=false',
        ])
        actual = self.evaluate(nixmod.render("gallery-dl", "home", "program", info))
        self.assertFalse(actual["enable"])
        self.assertEqual(actual["settings"]["extractor"], {
            "base-directory": "~/Downloads/gallery-dl/", "retries": 3,
            "skip": True, "types": ["jpg", "png"],
        })

    def test_json_data_cannot_become_nix_code(self):
        expected = {"${throw \"bad key\"}": '${throw "bad string"}',
                    "text": '  first\n  ${throw "bad multiline"}\n  最後\n',
                    "controls": '\b\f',
                    "_type": "literalExpression", "text2": "builtins.abort"}
        info = gallery_info()
        info["assignments"] = nixmod.assignments(info, ["settings=" + json.dumps(expected)])
        actual = self.evaluate(nixmod.render("gallery-dl", "home", "program", info))
        self.assertEqual(actual["settings"], expected)

    def test_quoted_data_keys_and_full_option_paths(self):
        info = gallery_info()
        info["assignments"] = nixmod.assignments(info, ['programs.gallery-dl.settings."a.b"=value'])
        actual = self.evaluate(nixmod.render("gallery-dl", "home", "program", info))
        self.assertEqual(actual["settings"], {"a.b": "value"})

    def test_null_bytes_are_rejected_before_generating_invalid_nix(self):
        info = gallery_info()
        info["assignments"] = nixmod.assignments(info, ['settings.value="\\u0000"'])
        with contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit):
            nixmod.render("gallery-dl", "home", "program", info)
        self.assertIn("Nix strings cannot contain null bytes", err.getvalue())

    def test_configured_values_do_not_offer_conflicting_examples(self):
        info = gallery_info()
        info["assignments"] = nixmod.assignments(info, ["settings.extractor.base-directory=~/Pictures"])
        text = nixmod.render("gallery-dl", "home", "program", info)
        self.assertNotIn('# extractor.base-directory =', text)
        self.assertEqual(self.evaluate(text)["settings"]["extractor"]["base-directory"], "~/Pictures")

    def test_misplaced_option_explains_settings_wrapper(self):
        with contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit):
            nixmod.assignments(gallery_info(), ["extractor.base-directory=~/Downloads"])
        self.assertIn("Put application settings under settings", err.getvalue())

    def test_bad_paths_values_and_overlaps_fail_before_writing(self):
        for specs in (["settings..extractor=x"], ["enable.foo=true"], ["settings={broken"],
                      ["settings={} ", "settings.extractor=x"], ["enable=true", "enable=false"],
                      ["settings.value=NaN"], ["settings.value=Infinity"]):
            with self.subTest(specs=specs), contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
                nixmod.assignments(gallery_info(), specs)
        self.assertFalse((self.repo / "modules/home/gallery-dl.nix").exists())

    def test_host_selection_never_silently_falls_back_to_generic(self):
        result = SimpleNamespace(returncode=0, stdout='["nixdaemon", "nixos"]')
        with patch.object(nixmod, "run", return_value=result), patch.object(nixmod.socket, "gethostname", return_value="unknown"):
            with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
                nixmod.pick_host(self.repo, None)
            self.assertEqual(nixmod.pick_host(self.repo, "nixos"), "nixos")
        with patch.object(nixmod, "run", return_value=result), patch.object(nixmod.socket, "gethostname", return_value="nixos"):
            self.assertEqual(nixmod.pick_host(self.repo, None), "nixos")

    def args(self, **changes):
        return SimpleNamespace(**({"name": "gallery-dl", "template": "program", "host": None,
            "scope": None, "option": None, "set": [], "dry_run": False, "force": False,
            "no_wire": False, "check": False, "no_check": False, "edit": False} | changes))

    def create(self, args, valid=True):
        with patch.object(nixmod, "pick_host", return_value="nixos"), \
             patch.object(nixmod, "nix_eval", return_value=copy.deepcopy(gallery_info())), \
             patch.object(nixmod, "git_add"), \
             patch.object(nixmod, "check_hosts", return_value=valid) as checking:
            nixmod.cmd_new(args, self.repo)
            return checking

    def test_new_program_checks_selected_host_by_default(self):
        with contextlib.redirect_stdout(io.StringIO()):
            checking = self.create(self.args())
        checking.assert_called_once_with(self.repo, ["nixos"])
        self.assertIn("gallery-dl # programs.gallery-dl", (self.repo / "modules/home/default.nix").read_text())

    def test_invalid_configuration_returns_failure_and_keeps_editable_file(self):
        with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
            self.create(self.args(), valid=False)
        self.assertNotIn("build   nh os build", out.getvalue())
        self.assertTrue((self.repo / "modules/home/gallery-dl.nix").is_file())

    def test_dry_run_never_writes_or_checks_hosts(self):
        before = (self.repo / "modules/home/default.nix").read_text()
        with contextlib.redirect_stdout(io.StringIO()):
            checking = self.create(self.args(dry_run=True))
        checking.assert_not_called()
        self.assertFalse((self.repo / "modules/home/gallery-dl.nix").exists())
        self.assertEqual((self.repo / "modules/home/default.nix").read_text(), before)

    def test_unwired_module_reports_syntax_only(self):
        with contextlib.redirect_stdout(io.StringIO()) as out:
            checking = self.create(self.args(no_wire=True))
        checking.assert_not_called()
        self.assertIn("syntax only", out.getvalue())


if __name__ == "__main__":
    unittest.main()