summaryrefslogtreecommitdiffstatshomepage
path: root/tests/test_canonical.py
blob: e1c825c2a6c59d639b74af367e39e181e5bb9bb9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import importlib.util
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location(
    "canonical", ROOT / "scripts/canonical.py"
)
assert SPEC and SPEC.loader
canonical = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(canonical)


class PackageTests(unittest.TestCase):
    def test_install_does_not_enable_experimental_snap_features(self):
        with patch.object(canonical.subprocess, "run") as command:
            canonical.install()
        self.assertFalse(any("set" in call.args[0] for call in command.call_args_list))

    def test_keybase_is_not_installed_or_autostarted(self):
        self.assertNotIn("keybase", canonical.packages("snap"))
        self.assertFalse(
            (ROOT / "dot_config/autostart/dotfiles-keybase.desktop").exists()
        )

    def test_extensions_install_without_shell_confirmation(self):
        with (
            patch("sys.argv", ["canonical.py", "extensions"]),
            patch.object(canonical, "require_canonical"),
            patch.object(canonical.subprocess, "run") as command,
        ):
            canonical.main()
        self.assertEqual(
            command.call_args.args[0][:3], ["gext", "--filesystem", "install"]
        )

    def test_lab_check_rejects_missing_marker(self):
        with (
            patch.object(canonical.Path, "is_file", return_value=False),
            self.assertRaises(SystemExit),
        ):
            canonical.require_lab()

    def test_normal_check_keeps_company_registration(self):
        with patch.object(canonical.subprocess, "run") as command:
            command.return_value.returncode = 0
            canonical.check()
        self.assertTrue(
            any(
                call.args[0] == ["landscape-config", "--actively-registered"]
                for call in command.call_args_list
            )
        )
        self.assertTrue(
            any(
                call.args[0] == ["nix", "store", "ping", "--store", "daemon"]
                for call in command.call_args_list
            )
        )

    def test_non_corporate_role_is_rejected_before_system_access(self):
        with (
            patch.object(
                canonical.subprocess,
                "check_output",
                return_value='{"machineRole":"host"}',
            ),
            self.assertRaises(SystemExit),
        ):
            canonical.require_canonical()

    def test_classic_permission_is_explicit(self):
        commands = canonical.snap_install_commands()
        self.assertIn(
            ["sudo", "snap", "install", "ghostty", "--channel=stable", "--classic"],
            commands,
        )
        self.assertEqual(sum("--classic" in command for command in commands), 1)

    def test_flatpaks_are_user_scoped(self):
        commands = canonical.flatpak_install_commands()
        self.assertTrue(all("--user" in command for command in commands))
        self.assertIn("im.nheko.Nheko", commands[-1])

    def test_no_destructive_package_updates(self):
        commands = canonical.update_commands()
        self.assertIn(["sudo", "apt-get", "upgrade"], commands)
        self.assertFalse(
            any(
                "autoremove" in command or "dist-upgrade" in command
                for command in commands
            )
        )
        self.assertFalse(any("--ignore-running" in command for command in commands))


class RoleTests(unittest.TestCase):
    def command(self, role: str, *args: str) -> list[str]:
        return [
            "chezmoi",
            "--config",
            "/dev/null",
            "--config-format",
            "toml",
            "--override-data",
            json.dumps(
                {
                    "machineRole": role,
                    "workName": "Work User",
                    "workEmail": "work@canonical.com",
                    "workSigningKey": "A" * 40,
                }
            ),
            "-S",
            str(ROOT),
            *args,
        ]

    def test_canonical_file_boundary(self):
        files = subprocess.check_output(
            self.command("canonical", "managed", "--include=files,scripts,symlinks"),
            text=True,
        ).splitlines()
        for required in [
            ".ssh/config",
            ".gnupg/gpg.conf",
            ".config/git/config",
            ".config/ghostty/config",
            ".local/bin/rqr",
        ]:
            self.assertIn(required, files)
        for path in files:
            self.assertFalse(
                any(
                    part in path
                    for part in [
                        "sway",
                        "waybar",
                        "nym.pub",
                        "sshcontrol",
                        "pass-secret-service",
                        ".config/git/hooks",
                        "deploy-etc",
                    ]
                )
            )
            self.assertNotIn("__pycache__", path)
            self.assertNotEqual(path, ".config/nvim/nvim-pack-lock.json")
            if path.endswith(".sh") and not path.startswith("."):
                self.assertIn(path, ["canonical-desktop.sh", "canonical-nvim-lock.sh"])

    def test_canonical_lockfile_is_seeded_without_overwriting(self):
        rendered = subprocess.check_output(
            self.command(
                "canonical",
                "execute-template",
                "--file",
                str(ROOT / "run_before_canonical-nvim-lock.sh.tmpl"),
            ),
            text=True,
        )
        with tempfile.TemporaryDirectory() as directory:
            env = {
                **os.environ,
                "HOME": directory,
                "XDG_CONFIG_HOME": directory + "/config",
            }
            target = Path(directory) / "config/nvim/nvim-pack-lock.json"
            subprocess.run(["sh", "-c", rendered], env=env, check=True)
            self.assertEqual(
                target.read_bytes(),
                (ROOT / "dot_config/nvim/nvim-pack-lock.json").read_bytes(),
            )
            target.write_text('{"local": true}\n')
            subprocess.run(["sh", "-c", rendered], env=env, check=True)
            self.assertEqual(target.read_text(), '{"local": true}\n')

    def test_work_identity_is_rendered_without_personal_identity(self):
        for source in [
            "dot_config/git/config.tmpl",
            "private_dot_ssh/config.tmpl",
            "private_dot_gnupg/gpg.conf.tmpl",
        ]:
            rendered = subprocess.check_output(
                self.command(
                    "canonical", "execute-template", "--file", str(ROOT / source)
                ),
                text=True,
            )
            self.assertNotIn("sommerfeld", rendered)
            self.assertNotIn("nym.pub", rendered)
            self.assertNotIn("proton/", rendered)

    def test_host_and_vm_do_not_receive_corporate_autostart(self):
        for role in ["host", "vm"]:
            files = subprocess.check_output(
                self.command(role, "managed", "--include=files,symlinks"), text=True
            )
            self.assertNotIn(".config/autostart/dotfiles-", files)
            self.assertNotIn("gpg-agent.service.d/canonical.conf", files)


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