summaryrefslogtreecommitdiff
path: root/tests/unittests/config/test_cc_set_passwords.py
blob: f6885b2b0f7e9fb501a1c07b1a11750d67e2ebd3 (plain)
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
# This file is part of cloud-init. See LICENSE file for license information.

import logging
from unittest import mock

import pytest

from cloudinit import features, subp, util
from cloudinit.config import cc_set_passwords as setpass
from cloudinit.config.schema import (
    SchemaValidationError,
    get_schema,
    validate_cloudconfig_schema,
)
from tests.unittests.helpers import does_not_raise, skipUnlessJsonSchema
from tests.unittests.util import get_cloud

MODPATH = "cloudinit.config.cc_set_passwords."
LOG = logging.getLogger(__name__)
SYSTEMD_CHECK_CALL = mock.call(
    ["systemctl", "show", "--property", "ActiveState", "--value", "ssh"]
)
SYSTEMD_RESTART_CALL = mock.call(["systemctl", "restart", "ssh"], capture=True)
SERVICE_RESTART_CALL = mock.call(["service", "ssh", "restart"], capture=True)


@pytest.fixture(autouse=True)
def common_fixtures(mocker):
    mocker.patch("cloudinit.distros.uses_systemd", return_value=True)
    mocker.patch("cloudinit.util.write_to_console")


class TestHandleSSHPwauth:
    @mock.patch("cloudinit.distros.subp.subp")
    def test_unknown_value_logs_warning(self, m_subp, caplog):
        cloud = get_cloud("ubuntu")
        setpass.handle_ssh_pwauth("floo", cloud.distro)
        assert "Unrecognized value: ssh_pwauth=floo" in caplog.text
        assert SYSTEMD_CHECK_CALL not in m_subp.call_args_list
        assert SYSTEMD_RESTART_CALL not in m_subp.call_args_list
        assert SERVICE_RESTART_CALL not in m_subp.call_args_list

    @pytest.mark.parametrize(
        "uses_systemd,ssh_updated,systemd_state",
        (
            (True, True, "activating"),
            (True, True, "inactive"),
            (True, False, None),
            (False, True, None),
            (False, False, None),
        ),
    )
    @mock.patch(f"{MODPATH}update_ssh_config")
    @mock.patch("cloudinit.distros.subp.subp")
    def test_restart_ssh_only_when_changes_made_and_ssh_installed(
        self,
        m_subp,
        update_ssh_config,
        uses_systemd,
        ssh_updated,
        systemd_state,
        caplog,
    ):
        update_ssh_config.return_value = ssh_updated
        m_subp.return_value = subp.SubpResult(systemd_state, "")
        cloud = get_cloud("ubuntu")
        with mock.patch.object(
            cloud.distro, "uses_systemd", return_value=uses_systemd
        ):
            setpass.handle_ssh_pwauth(True, cloud.distro)

        if not ssh_updated:
            assert "No need to restart SSH" in caplog.text
            assert m_subp.call_args_list == []
        elif uses_systemd:
            assert SYSTEMD_CHECK_CALL in m_subp.call_args_list
            assert SERVICE_RESTART_CALL not in m_subp.call_args_list
            if systemd_state == "activating":
                assert SYSTEMD_RESTART_CALL in m_subp.call_args_list
            else:
                assert SYSTEMD_RESTART_CALL not in m_subp.call_args_list
        else:
            assert SERVICE_RESTART_CALL in m_subp.call_args_list
            assert SYSTEMD_CHECK_CALL not in m_subp.call_args_list
            assert SYSTEMD_RESTART_CALL not in m_subp.call_args_list

    @mock.patch(f"{MODPATH}update_ssh_config", return_value=True)
    @mock.patch("cloudinit.distros.subp.subp")
    def test_unchanged_value_does_nothing(self, m_subp, update_ssh_config):
        """If 'unchanged', then no updates to config and no restart."""
        update_ssh_config.assert_not_called()
        cloud = get_cloud("ubuntu")
        setpass.handle_ssh_pwauth("unchanged", cloud.distro)
        assert SYSTEMD_CHECK_CALL not in m_subp.call_args_list
        assert SYSTEMD_RESTART_CALL not in m_subp.call_args_list
        assert SERVICE_RESTART_CALL not in m_subp.call_args_list

    @pytest.mark.allow_subp_for("systemctl")
    @mock.patch("cloudinit.distros.subp.subp")
    def test_valid_value_changes_updates_ssh(self, m_subp):
        """If value is a valid changed value, then update will be called."""
        cloud = get_cloud("ubuntu")
        upname = f"{MODPATH}update_ssh_config"
        optname = "PasswordAuthentication"
        for _, value in enumerate(util.FALSE_STRINGS + util.TRUE_STRINGS, 1):
            optval = "yes" if value in util.TRUE_STRINGS else "no"
            with mock.patch(upname, return_value=False) as m_update:
                setpass.handle_ssh_pwauth(value, cloud.distro)
                assert (
                    mock.call({optname: optval}) == m_update.call_args_list[-1]
                )


def get_chpasswd_calls(cfg, cloud, log):
    with mock.patch(f"{MODPATH}subp.subp") as subp:
        with mock.patch.object(setpass.Distro, "chpasswd") as chpasswd:
            setpass.handle(
                "IGNORED",
                cfg=cfg,
                cloud=cloud,
                args=[],
            )
    assert chpasswd.call_count > 0
    return chpasswd.call_args[0], subp.call_args


class TestSetPasswordsHandle:
    """Test cc_set_passwords.handle"""

    @mock.patch(f"{MODPATH}subp.subp")
    def test_handle_on_empty_config(self, m_subp, caplog):
        """handle logs that no password has changed when config is empty."""
        cloud = get_cloud()
        setpass.handle("IGNORED", cfg={}, cloud=cloud, args=[])
        assert (
            "Leaving SSH config 'PasswordAuthentication' unchanged. "
            "ssh_pwauth=None"
        ) in caplog.text
        assert SYSTEMD_CHECK_CALL not in m_subp.call_args_list
        assert SYSTEMD_RESTART_CALL not in m_subp.call_args_list
        assert SERVICE_RESTART_CALL not in m_subp.call_args_list

    @mock.patch(f"{MODPATH}subp.subp")
    def test_handle_on_chpasswd_list_parses_common_hashes(
        self, _m_subp, caplog
    ):
        """handle parses command password hashes."""
        cloud = get_cloud()
        valid_hashed_pwds = [
            "root:$2y$10$8BQjxjVByHA/Ee.O1bCXtO8S7Y5WojbXWqnqYpUW.BrPx/"
            "Dlew1Va",
            "ubuntu:$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoakMMC7dR52q"
            "SDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXazGGx3oo1",
        ]
        cfg = {"chpasswd": {"list": valid_hashed_pwds}}
        with mock.patch.object(setpass.Distro, "chpasswd") as chpasswd:
            setpass.handle("IGNORED", cfg=cfg, cloud=cloud, args=[])
        assert "Handling input for chpasswd as list." in caplog.text
        assert "Setting hashed password for ['root', 'ubuntu']" in caplog.text

        first_arg = chpasswd.call_args[0]
        for i, val in enumerate(*first_arg):
            assert valid_hashed_pwds[i] == ":".join(val)

    @mock.patch(f"{MODPATH}subp.subp")
    def test_handle_on_chpasswd_users_parses_common_hashes(
        self, _m_subp, caplog
    ):
        """handle parses command password hashes."""
        cloud = get_cloud()
        valid_hashed_pwds = [
            {
                "name": "root",
                "password": "$2y$10$8BQjxjVByHA/Ee.O1bCXtO8S7Y5WojbXWqnqYpUW.BrPx/Dlew1Va",  # noqa: E501
            },
            {
                "name": "ubuntu",
                "password": "$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoakMMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXazGGx3oo1",  # noqa: E501
            },
        ]
        cfg = {"chpasswd": {"users": valid_hashed_pwds}}
        with mock.patch.object(setpass.Distro, "chpasswd") as chpasswd:
            setpass.handle("IGNORED", cfg=cfg, cloud=cloud, args=[])
        assert "Handling input for chpasswd as list." not in caplog.text
        assert "Setting hashed password for ['root', 'ubuntu']" in caplog.text
        first_arg = chpasswd.call_args[0]
        for i, (name, password) in enumerate(*first_arg):
            assert valid_hashed_pwds[i]["name"] == name
            assert valid_hashed_pwds[i]["password"] == password

    @pytest.mark.parametrize(
        "user_cfg",
        [
            {
                "list": [
                    "ubuntu:passw0rd",
                    "sadegh:$6$cTpht$Z2pSYxleRWK8IrsynFzHcrnPlpUhA7N9AM/",
                ]
            },
            {
                "users": [
                    {
                        "name": "ubuntu",
                        "password": "passw0rd",
                        "type": "text",
                    },
                    {
                        "name": "sadegh",
                        "password": "$6$cTpht$Z2pSYxleRWK8IrsynFzHcrnPlpUhA7N9AM/",  # noqa: E501
                    },
                ]
            },
        ],
    )
    def test_bsd_calls_custom_pw_cmds_to_set_and_expire_passwords(
        self, user_cfg, mocker
    ):
        """BSD don't use chpasswd"""
        mocker.patch(f"{MODPATH}util.is_BSD", return_value=True)
        m_subp = mocker.patch(f"{MODPATH}subp.subp")
        # patch for ifconfig -a
        with mock.patch(
            "cloudinit.distros.networking.subp.subp", return_values=("", None)
        ):
            cloud = get_cloud(distro="freebsd")
        cfg = {"chpasswd": user_cfg}
        with mock.patch.object(
            cloud.distro, "uses_systemd", return_value=False
        ):
            setpass.handle("IGNORED", cfg=cfg, cloud=cloud, args=[])
        assert [
            mock.call(
                ["pw", "usermod", "ubuntu", "-h", "0"],
                data="passw0rd",
                logstring="chpasswd for ubuntu",
            ),
            mock.call(
                ["pw", "usermod", "sadegh", "-H", "0"],
                data="$6$cTpht$Z2pSYxleRWK8IrsynFzHcrnPlpUhA7N9AM/",
                logstring="chpasswd for sadegh",
            ),
            mock.call(["pw", "usermod", "ubuntu", "-p", "01-Jan-1970"]),
            mock.call(["pw", "usermod", "sadegh", "-p", "01-Jan-1970"]),
        ] == m_subp.call_args_list

    @pytest.mark.parametrize(
        "user_cfg",
        [
            {"expire": "false", "list": ["root:R", "ubuntu:RANDOM"]},
            {
                "expire": "false",
                "users": [
                    {
                        "name": "root",
                        "type": "RANDOM",
                    },
                    {
                        "name": "ubuntu",
                        "type": "RANDOM",
                    },
                ],
            },
        ],
    )
    def test_random_passwords(self, user_cfg, mocker, caplog):
        """handle parses command set random passwords."""
        m_multi_log = mocker.patch(f"{MODPATH}util.multi_log")
        mocker.patch(f"{MODPATH}subp.subp")

        cloud = get_cloud()
        cfg = {"chpasswd": user_cfg}

        with mock.patch.object(setpass.Distro, "chpasswd") as chpasswd:
            setpass.handle("IGNORED", cfg=cfg, cloud=cloud, args=[])
        dbg_text = "Handling input for chpasswd as list."
        if "list" in cfg["chpasswd"]:
            assert dbg_text in caplog.text
        else:
            assert dbg_text not in caplog.text
        assert 1 == chpasswd.call_count
        user_pass = dict(*chpasswd.call_args[0])

        assert 1 == m_multi_log.call_count
        assert (
            mock.call(mock.ANY, stderr=False, fallback_to_stdout=False)
            == m_multi_log.call_args
        )

        assert {"root", "ubuntu"} == set(user_pass.keys())
        written_lines = m_multi_log.call_args[0][0].splitlines()
        for password in user_pass.values():
            for line in written_lines:
                if password in line:
                    break
            else:
                pytest.fail("Password not emitted to console")

    @pytest.mark.parametrize(
        "list_def, users_def",
        [
            # demonstrate that new addition matches current behavior
            (
                {
                    "chpasswd": {
                        "list": [
                            "root:$2y$10$8BQjxjVByHA/Ee.O1bCXtO8S7Y5WojbXWqnqY"
                            "pUW.BrPx/Dlew1Va",
                            "ubuntu:$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoak"
                            "MMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXaz"
                            "GGx3oo1",
                            "dog:$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoakMMC"
                            "7dR52qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXazGGx"
                            "3oo1",
                            "Till:RANDOM",
                        ]
                    }
                },
                {
                    "chpasswd": {
                        "users": [
                            {
                                "name": "root",
                                "password": "$2y$10$8BQjxjVByHA/Ee.O1bCXtO8S7Y"
                                "5WojbXWqnqYpUW.BrPx/Dlew1Va",
                            },
                            {
                                "name": "ubuntu",
                                "password": "$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9"
                                "acWCVEoakMMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSw"
                                "OlbOQSW/HpXazGGx3oo1",
                            },
                            {
                                "name": "dog",
                                "type": "hash",
                                "password": "$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9"
                                "acWCVEoakMMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSw"
                                "OlbOQSW/HpXazGGx3oo1",
                            },
                            {
                                "name": "Till",
                                "type": "RANDOM",
                            },
                        ]
                    }
                },
            ),
            # Duplicate user: demonstrate no change in current duplicate
            # behavior
            (
                {
                    "chpasswd": {
                        "list": [
                            "root:$2y$10$8BQjxjVByHA/Ee.O1bCXtO8S7Y5WojbXWqnqY"
                            "pUW.BrPx/Dlew1Va",
                            "ubuntu:$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoak"
                            "MMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXaz"
                            "GGx3oo1",
                            "ubuntu:$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoak"
                            "MMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXaz"
                            "GGx3oo1",
                        ]
                    }
                },
                {
                    "chpasswd": {
                        "users": [
                            {
                                "name": "root",
                                "password": "$2y$10$8BQjxjVByHA/Ee.O1bCXtO8S7Y"
                                "5WojbXWqnqYpUW.BrPx/Dlew1Va",
                            },
                            {
                                "name": "ubuntu",
                                "password": "$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9"
                                "acWCVEoakMMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSw"
                                "OlbOQSW/HpXazGGx3oo1",
                            },
                            {
                                "name": "ubuntu",
                                "password": "$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9"
                                "acWCVEoakMMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSw"
                                "OlbOQSW/HpXazGGx3oo1",
                            },
                        ]
                    }
                },
            ),
            # Duplicate user: demonstrate duplicate across users/list doesn't
            # change
            (
                {
                    "chpasswd": {
                        "list": [
                            "root:$2y$10$8BQjxjVByHA/Ee.O1bCXtO8S7Y5WojbXWqnqY"
                            "pUW.BrPx/Dlew1Va",
                            "ubuntu:$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoak"
                            "MMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXaz"
                            "GGx3oo1",
                            "ubuntu:$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoak"
                            "MMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXaz"
                            "GGx3oo1",
                        ]
                    }
                },
                {
                    "chpasswd": {
                        "users": [
                            {
                                "name": "root",
                                "password": "$2y$10$8BQjxjVByHA/Ee.O1bCXtO8S7Y"
                                "5WojbXWqnqYpUW.BrPx/Dlew1Va",
                            },
                            {
                                "name": "ubuntu",
                                "password": "$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9"
                                "acWCVEoakMMC7dR5"
                                "2qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXazGGx"
                                "3oo1",
                            },
                        ],
                        "list": [
                            "ubuntu:$6$5hOurLPO$naywm3Ce0UlmZg9gG2Fl9acWCVEoak"
                            "MMC7dR52qSDexZbrN9z8yHxhUM2b.sxpguSwOlbOQSW/HpXaz"
                            "GGx3oo1",
                        ],
                    }
                },
            ),
        ],
    )
    def test_chpasswd_parity(self, list_def, users_def):
        """Assert that two different configs cause identical calls"""

        cloud = get_cloud()

        def_1 = get_chpasswd_calls(list_def, cloud, LOG)
        def_2 = get_chpasswd_calls(users_def, cloud, LOG)
        assert def_1 == def_2


expire_cases = [
    {
        "chpasswd": {
            "expire": True,
            "list": [
                "user1:password",
                "user2:R",
                "user3:$6$cTpht$Z2pSYxleRWK8IrsynFzHcrnPlpUhA7N9AM/",
            ],
        }
    },
    {
        "chpasswd": {
            "expire": True,
            "users": [
                {
                    "name": "user1",
                    "password": "password",
                    "type": "text",
                },
                {
                    "name": "user2",
                    "type": "RANDOM",
                },
                {
                    "name": "user3",
                    "password": "$6$cTpht$Z2pSYxleRWK8IrsynFzHcrnPlpUhA7N9AM/",  # noqa: E501
                },
            ],
        }
    },
    {
        "chpasswd": {
            "expire": False,
            "list": [
                "user1:password",
                "user2:R",
                "user3:$6$cTpht$Z2pSYxleRWK8IrsynFzHcrnPlpUhA7N9AM/",
            ],
        }
    },
    {
        "chpasswd": {
            "expire": False,
            "users": [
                {
                    "name": "user1",
                    "password": "password",
                    "type": "text",
                },
                {
                    "name": "user2",
                    "type": "RANDOM",
                },
                {
                    "name": "user3",
                    "password": "$6$cTpht$Z2pSYxleRWK8IrsynFzHcrnPlpUhA7N9AM/",  # noqa: E501
                },
            ],
        }
    },
]


class TestExpire:
    @pytest.mark.parametrize("cfg", expire_cases)
    def test_expire(self, cfg, mocker, caplog):
        cloud = get_cloud()
        mocker.patch(f"{MODPATH}subp.subp")
        mocker.patch.object(cloud.distro, "chpasswd")
        m_expire = mocker.patch.object(cloud.distro, "expire_passwd")

        setpass.handle("IGNORED", cfg=cfg, cloud=cloud, args=[])

        if bool(cfg["chpasswd"]["expire"]):
            assert m_expire.call_args_list == [
                mock.call("user1"),
                mock.call("user2"),
                mock.call("user3"),
            ]
            assert (
                "Expired passwords for: ['user1', 'user2', 'user3'] users"
                in caplog.text
            )
        else:
            assert m_expire.call_args_list == []
            assert "Expired passwords" not in caplog.text

    @pytest.mark.parametrize("cfg", expire_cases)
    def test_expire_old_behavior(self, cfg, mocker, caplog):
        # Previously expire didn't apply to hashed passwords.
        # Ensure we can preserve that case on older releases
        features.EXPIRE_APPLIES_TO_HASHED_USERS = False
        cloud = get_cloud()
        mocker.patch(f"{MODPATH}subp.subp")
        mocker.patch.object(cloud.distro, "chpasswd")
        m_expire = mocker.patch.object(cloud.distro, "expire_passwd")

        setpass.handle("IGNORED", cfg=cfg, cloud=cloud, args=[])

        if bool(cfg["chpasswd"]["expire"]):
            assert m_expire.call_args_list == [
                mock.call("user1"),
                mock.call("user2"),
            ]
            assert (
                "Expired passwords for: ['user1', 'user2'] users"
                in caplog.text
            )
        else:
            assert m_expire.call_args_list == []
            assert "Expired passwords" not in caplog.text


class TestSetPasswordsSchema:
    @pytest.mark.parametrize(
        "config, expectation",
        [
            # Test both formats still work
            ({"ssh_pwauth": True}, does_not_raise()),
            ({"ssh_pwauth": False}, does_not_raise()),
            (
                {"ssh_pwauth": "yes"},
                pytest.raises(
                    SchemaValidationError,
                    match=(
                        "Cloud config schema deprecations: ssh_pwauth:"
                        "  Changed in version 22.3. Use of non-boolean"
                        " values for this field is deprecated."
                    ),
                ),
            ),
            (
                {"ssh_pwauth": "unchanged"},
                pytest.raises(
                    SchemaValidationError,
                    match=(
                        "Cloud config schema deprecations: ssh_pwauth:"
                        "  Changed in version 22.3. Use of non-boolean"
                        " values for this field is deprecated."
                    ),
                ),
            ),
            (
                {"chpasswd": {"list": "blah"}},
                pytest.raises(
                    SchemaValidationError, match="Deprecated in version"
                ),
            ),
            # Valid combinations
            (
                {
                    "chpasswd": {
                        "users": [
                            {
                                "name": "what-if-1",
                                "type": "text",
                                "password": "correct-horse-battery-staple",
                            },
                            {
                                "name": "what-if-2",
                                "type": "hash",
                                "password": "no-magic-parsing-done-here",
                            },
                            {
                                "name": "what-if-3",
                                "password": "type-is-optional-default-"
                                "value-is-hash",
                            },
                            {
                                "name": "what-if-4",
                                "type": "RANDOM",
                            },
                        ]
                    }
                },
                does_not_raise(),
            ),
            (
                {
                    "chpasswd": {
                        "users": [
                            {
                                "name": "what-if-1",
                                "type": "plaintext",
                                "password": "type-has-two-legal-values: "
                                "{'hash', 'text'}",
                            }
                        ]
                    }
                },
                pytest.raises(
                    SchemaValidationError,
                    match="is not valid under any of the given schemas",
                ),
            ),
            (
                {
                    "chpasswd": {
                        "users": [
                            {
                                "name": "what-if-1",
                                "type": "RANDOM",
                                "password": "but you want random?",
                            }
                        ]
                    }
                },
                pytest.raises(
                    SchemaValidationError,
                    match="is not valid under any of the given schemas",
                ),
            ),
            (
                {"chpasswd": {"users": [{"password": "."}]}},
                pytest.raises(
                    SchemaValidationError,
                    match="is not valid under any of the given schemas",
                ),
            ),
            # when type != RANDOM, password is a required key
            (
                {
                    "chpasswd": {
                        "users": [{"name": "what-if-1", "type": "hash"}]
                    }
                },
                pytest.raises(
                    SchemaValidationError,
                    match="is not valid under any of the given schemas",
                ),
            ),
            pytest.param(
                {
                    "chpasswd": {
                        "users": [
                            {
                                "name": "sonata",
                                "password": "dit",
                                "dat": "dot",
                            }
                        ]
                    }
                },
                pytest.raises(
                    SchemaValidationError,
                    match="is not valid under any of the given schemas",
                ),
                id="dat_is_an_additional_property",
            ),
            (
                {"chpasswd": {"users": [{"name": "."}]}},
                pytest.raises(
                    SchemaValidationError,
                    match="is not valid under any of the given schemas",
                ),
            ),
            # Test regex
            (
                {"chpasswd": {"list": ["user:pass"]}},
                pytest.raises(
                    SchemaValidationError, match="Deprecated in version"
                ),
            ),
            # Test valid
            ({"password": "pass"}, does_not_raise()),
            # Test invalid values
            (
                {"chpasswd": {"expire": "yes"}},
                pytest.raises(
                    SchemaValidationError,
                    match="'yes' is not of type 'boolean'",
                ),
            ),
            (
                {"chpasswd": {"list": ["user"]}},
                pytest.raises(SchemaValidationError),
            ),
            (
                {"chpasswd": {"list": []}},
                pytest.raises(
                    SchemaValidationError, match=r"\[\] is too short"
                ),
            ),
        ],
    )
    @skipUnlessJsonSchema()
    def test_schema_validation(self, config, expectation):
        with expectation:
            validate_cloudconfig_schema(config, get_schema(), strict=True)


# vi: ts=4 expandtab