Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/connection/test_wsl.py

raw
1 # Derived from test_proxmox_pct_remote.py (c) 2024 Nils Stein (@mietzen) <[email protected]>
2 # Copyright (c) 2025 Rui Lopes (@rgl) <ruilopes.com>
3 # Copyright (c) 2025 Ansible Project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 import os
10 from io import StringIO
11 from pathlib import Path
12 from unittest.mock import MagicMock, mock_open, patch
13
14 import pytest
15 from ansible.errors import AnsibleAuthenticationFailure, AnsibleConnectionFailure, AnsibleError
16 from ansible.module_utils.common.text.converters import to_bytes
17 from ansible.playbook.play_context import PlayContext
18 from ansible.plugins.loader import connection_loader
19
20 from ansible_collections.community.general.plugins.connection.wsl import MyAddPolicy, authenticity_msg
21 from ansible_collections.community.general.plugins.module_utils._filelock import FileLock, LockTimeout
22
23 paramiko = pytest.importorskip("paramiko")
24
25
26 @pytest.fixture
27 def connection():
28 play_context = PlayContext()
29 in_stream = StringIO()
30 conn = connection_loader.get("community.general.wsl", play_context, in_stream)
31 conn.set_option("remote_addr", "192.168.1.100")
32 conn.set_option("remote_user", "root")
33 conn.set_option("password", "password")
34 conn.set_option("wsl_distribution", "test")
35 return conn
36
37
38 def test_connection_options(connection):
39 """Test that connection options are properly set"""
40 assert connection.get_option("remote_addr") == "192.168.1.100"
41 assert connection.get_option("remote_user") == "root"
42 assert connection.get_option("password") == "password"
43 assert connection.get_option("wsl_distribution") == "test"
44
45
46 def test_authenticity_msg():
47 """Test authenticity message formatting"""
48 msg = authenticity_msg("test.host", "ssh-rsa", "AA:BB:CC:DD")
49 assert "test.host" in msg
50 assert "ssh-rsa" in msg
51 assert "AA:BB:CC:DD" in msg
52
53
54 def test_missing_host_key(connection):
55 """Test MyAddPolicy missing_host_key method"""
56
57 client = MagicMock()
58 key = MagicMock()
59 key.get_fingerprint.return_value = b"fingerprint"
60 key.get_name.return_value = "ssh-rsa"
61
62 policy = MyAddPolicy(connection)
63
64 connection.set_option("host_key_auto_add", True)
65 policy.missing_host_key(client, "test.host", key)
66 assert hasattr(key, "_added_by_ansible_this_time")
67
68 connection.set_option("host_key_auto_add", False)
69 connection.set_option("host_key_checking", False)
70 policy.missing_host_key(client, "test.host", key)
71
72 connection.set_option("host_key_checking", True)
73 connection.set_option("host_key_auto_add", False)
74 connection.set_option("use_persistent_connections", False)
75
76 with patch("ansible.utils.display.Display.prompt_until", return_value="yes"):
77 policy.missing_host_key(client, "test.host", key)
78
79 with patch("ansible.utils.display.Display.prompt_until", return_value="no"):
80 with pytest.raises(AnsibleError, match="host connection rejected by user"):
81 policy.missing_host_key(client, "test.host", key)
82
83
84 def test_set_log_channel(connection):
85 """Test setting log channel"""
86 connection._set_log_channel("test_channel")
87 assert connection._log_channel == "test_channel"
88
89
90 def test_parse_proxy_command(connection):
91 """Test proxy command parsing"""
92 connection.set_option("proxy_command", "ssh -W %h:%p proxy.example.com")
93 connection.set_option("remote_addr", "target.example.com")
94 connection.set_option("remote_user", "testuser")
95
96 result = connection._parse_proxy_command(port=2222)
97 assert "sock" in result
98 assert isinstance(result["sock"], paramiko.ProxyCommand)
99
100
101 @patch("paramiko.SSHClient")
102 def test_connect_with_rsa_sha2_disabled(mock_ssh, connection):
103 """Test connection with RSA SHA2 algorithms disabled"""
104 connection.set_option("use_rsa_sha2_algorithms", False)
105 mock_client = MagicMock()
106 mock_ssh.return_value = mock_client
107
108 connection._connect()
109
110 call_kwargs = mock_client.connect.call_args[1]
111 assert "disabled_algorithms" in call_kwargs
112 assert "pubkeys" in call_kwargs["disabled_algorithms"]
113
114
115 @patch("paramiko.SSHClient")
116 def test_connect_with_bad_host_key(mock_ssh, connection):
117 """Test connection with bad host key"""
118 mock_client = MagicMock()
119 mock_ssh.return_value = mock_client
120 mock_client.connect.side_effect = paramiko.ssh_exception.BadHostKeyException("hostname", MagicMock(), MagicMock())
121
122 with pytest.raises(AnsibleConnectionFailure, match="host key mismatch"):
123 connection._connect()
124
125
126 @patch("paramiko.SSHClient")
127 def test_connect_with_invalid_host_key(mock_ssh, connection):
128 """Test connection with bad host key"""
129 connection.set_option("host_key_checking", True)
130 mock_client = MagicMock()
131 mock_ssh.return_value = mock_client
132 mock_client.load_system_host_keys.side_effect = paramiko.hostkeys.InvalidHostKey(
133 "Bad Line!", Exception("Something crashed!")
134 )
135
136 with pytest.raises(AnsibleConnectionFailure, match="Invalid host key: Bad Line!"):
137 connection._connect()
138
139
140 @patch("paramiko.SSHClient")
141 def test_connect_success(mock_ssh, connection):
142 """Test successful SSH connection establishment"""
143 mock_client = MagicMock()
144 mock_ssh.return_value = mock_client
145
146 connection._connect()
147
148 assert mock_client.connect.called
149 assert connection._connected
150
151
152 @patch("paramiko.SSHClient")
153 def test_connect_authentication_failure(mock_ssh, connection):
154 """Test SSH connection with authentication failure"""
155 mock_client = MagicMock()
156 mock_ssh.return_value = mock_client
157 mock_client.connect.side_effect = paramiko.ssh_exception.AuthenticationException("Auth failed")
158
159 with pytest.raises(AnsibleAuthenticationFailure):
160 connection._connect()
161
162
163 def test_any_keys_added(connection):
164 """Test checking for added host keys"""
165 connection.ssh = MagicMock()
166 connection.ssh._host_keys = {
167 "host1": {
168 "ssh-rsa": MagicMock(_added_by_ansible_this_time=True),
169 "ssh-ed25519": MagicMock(_added_by_ansible_this_time=False),
170 }
171 }
172
173 assert connection._any_keys_added() is True
174
175 connection.ssh._host_keys = {"host1": {"ssh-rsa": MagicMock(_added_by_ansible_this_time=False)}}
176 assert connection._any_keys_added() is False
177
178
179 @patch("os.path.exists")
180 @patch("os.stat")
181 @patch("tempfile.NamedTemporaryFile")
182 def test_save_ssh_host_keys(mock_tempfile, mock_stat, mock_exists, connection):
183 """Test saving SSH host keys"""
184 mock_exists.return_value = True
185 mock_stat.return_value = MagicMock(st_mode=0o644, st_uid=1000, st_gid=1000)
186 mock_tempfile.return_value.__enter__.return_value.name = "/tmp/test_keys"
187
188 connection.ssh = MagicMock()
189 connection.ssh._host_keys = {
190 "host1": {"ssh-rsa": MagicMock(get_base64=lambda: "KEY1", _added_by_ansible_this_time=True)}
191 }
192
193 mock_open_obj = mock_open()
194 with patch("builtins.open", mock_open_obj):
195 connection._save_ssh_host_keys("/tmp/test_keys")
196
197 mock_open_obj().write.assert_called_with("host1 ssh-rsa KEY1\n")
198
199
200 def test_build_wsl_command(connection):
201 """Test wsl command building with different users"""
202 cmd = connection._build_wsl_command('/bin/sh -c "ls -la"')
203 assert cmd == 'wsl.exe --distribution test -- /bin/sh -c "ls -la"'
204
205 connection.set_option("wsl_user", "test-user")
206 cmd = connection._build_wsl_command('/bin/sh -c "ls -la"')
207 assert cmd == 'wsl.exe --distribution test --user test-user -- /bin/sh -c "ls -la"'
208
209 connection.set_option("become", True)
210 connection.set_option("become_user", "test-become-user")
211 cmd = connection._build_wsl_command('/bin/sh -c "ls -la"')
212 assert cmd == 'wsl.exe --distribution test --user test-become-user -- /bin/sh -c "ls -la"'
213
214
215 def test_build_wsl_command_powershell(connection):
216 """Test wsl command building for powershell and cmd remote ssh shell"""
217 cmd = connection._build_wsl_command('/bin/sh -c "ls -la %PATH%"')
218 assert cmd == 'wsl.exe --distribution test -- /bin/sh -c "ls -la ^%PATH^%"'
219
220 connection.set_option("wsl_remote_ssh_shell_type", "powershell")
221 cmd = connection._build_wsl_command('/bin/sh -c "ls -la"')
222 assert cmd == 'wsl.exe --% --distribution test -- /bin/sh -c "ls -la"'
223
224 with pytest.raises(AnsibleError, match="The command contains '%', cannot safely escape it for Powershell"):
225 connection._build_wsl_command('/bin/sh -c "ls -la %PATH%"')
226
227
228 @patch("paramiko.SSHClient")
229 def test_exec_command_success(mock_ssh, connection):
230 """Test successful command execution"""
231 mock_client = MagicMock()
232 mock_ssh.return_value = mock_client
233 mock_channel = MagicMock()
234 mock_transport = MagicMock()
235
236 mock_client.get_transport.return_value = mock_transport
237 mock_transport.open_session.return_value = mock_channel
238 mock_channel.recv_exit_status.return_value = 0
239 mock_channel.makefile.return_value = [to_bytes("stdout")]
240 mock_channel.makefile_stderr.return_value = [to_bytes("")]
241
242 connection._connected = True
243 connection.ssh = mock_client
244
245 returncode, stdout, stderr = connection.exec_command("ls -la")
246
247 mock_transport.open_session.assert_called_once()
248 mock_transport.set_keepalive.assert_called_once_with(5)
249
250
251 @patch("paramiko.SSHClient")
252 def test_exec_command_wsl_not_found(mock_ssh, connection):
253 """Test command execution when wsl.exe is not found"""
254 mock_client = MagicMock()
255 mock_ssh.return_value = mock_client
256 mock_channel = MagicMock()
257 mock_transport = MagicMock()
258
259 mock_client.get_transport.return_value = mock_transport
260 mock_transport.open_session.return_value = mock_channel
261 mock_channel.recv_exit_status.return_value = 1
262 mock_channel.makefile.return_value = [to_bytes("")]
263 mock_channel.makefile_stderr.return_value = [to_bytes("'wsl.exe' is not recognized")]
264
265 connection._connected = True
266 connection.ssh = mock_client
267
268 with pytest.raises(AnsibleError, match="wsl.exe not found in path of host"):
269 connection.exec_command("ls -la")
270
271
272 @patch("paramiko.SSHClient")
273 def test_exec_command_session_open_failure(mock_ssh, connection):
274 """Test exec_command when session opening fails"""
275 mock_client = MagicMock()
276 mock_transport = MagicMock()
277 mock_transport.open_session.side_effect = Exception("Failed to open session")
278 mock_client.get_transport.return_value = mock_transport
279
280 connection._connected = True
281 connection.ssh = mock_client
282
283 with pytest.raises(AnsibleConnectionFailure, match="Failed to open session"):
284 connection.exec_command("test command")
285
286
287 @patch("paramiko.SSHClient")
288 def test_exec_command_with_privilege_escalation(mock_ssh, connection):
289 """Test exec_command with privilege escalation"""
290 mock_client = MagicMock()
291 mock_channel = MagicMock()
292 mock_transport = MagicMock()
293
294 mock_client.get_transport.return_value = mock_transport
295 mock_transport.open_session.return_value = mock_channel
296 connection._connected = True
297 connection.ssh = mock_client
298
299 connection.become = MagicMock()
300 connection.become.expect_prompt.return_value = True
301 connection.become.check_success.return_value = False
302 connection.become.check_password_prompt.return_value = True
303 connection.become.get_option.return_value = "sudo_password"
304
305 mock_channel.recv.return_value = b"[sudo] password:"
306 mock_channel.recv_exit_status.return_value = 0
307 mock_channel.makefile.return_value = [b""]
308 mock_channel.makefile_stderr.return_value = [b""]
309
310 returncode, stdout, stderr = connection.exec_command("sudo test command")
311
312 mock_channel.sendall.assert_called_once_with(b"sudo_password\n")
313
314
315 def test_put_file(connection):
316 """Test putting a file to the remote system"""
317 connection.exec_command = MagicMock()
318 connection.exec_command.return_value = (0, b"", b"")
319
320 with patch("builtins.open", create=True) as mock_open:
321 mock_open.return_value.__enter__.return_value.read.return_value = b"test content"
322 connection.put_file("/local/path", "/remote/path")
323
324 connection.exec_command.assert_called_once_with(
325 "/bin/sh -c 'cat > /remote/path'", in_data=b"test content", sudoable=False
326 )
327
328
329 @patch("paramiko.SSHClient")
330 def test_put_file_general_error(mock_ssh, connection):
331 """Test put_file with general error"""
332 mock_client = MagicMock()
333 mock_ssh.return_value = mock_client
334 mock_channel = MagicMock()
335 mock_transport = MagicMock()
336
337 mock_client.get_transport.return_value = mock_transport
338 mock_transport.open_session.return_value = mock_channel
339 mock_channel.recv_exit_status.return_value = 1
340 mock_channel.makefile.return_value = [to_bytes("")]
341 mock_channel.makefile_stderr.return_value = [to_bytes("Some error")]
342
343 connection._connected = True
344 connection.ssh = mock_client
345
346 with pytest.raises(AnsibleError, match="error occurred while putting file from /remote/path to /local/path"):
347 connection.put_file("/remote/path", "/local/path")
348
349
350 @patch("paramiko.SSHClient")
351 def test_put_file_cat_not_found(mock_ssh, connection):
352 """Test command execution when cat is not found"""
353 mock_client = MagicMock()
354 mock_ssh.return_value = mock_client
355 mock_channel = MagicMock()
356 mock_transport = MagicMock()
357
358 mock_client.get_transport.return_value = mock_transport
359 mock_transport.open_session.return_value = mock_channel
360 mock_channel.recv_exit_status.return_value = 1
361 mock_channel.makefile.return_value = [to_bytes("")]
362 mock_channel.makefile_stderr.return_value = [to_bytes("cat: not found")]
363
364 connection._connected = True
365 connection.ssh = mock_client
366
367 with pytest.raises(AnsibleError, match="cat not found in path of WSL distribution"):
368 connection.fetch_file("/remote/path", "/local/path")
369
370
371 def test_fetch_file(connection):
372 """Test fetching a file from the remote system"""
373 connection.exec_command = MagicMock()
374 connection.exec_command.return_value = (0, b"test content", b"")
375
376 with patch("builtins.open", create=True) as mock_open:
377 connection.fetch_file("/remote/path", "/local/path")
378
379 connection.exec_command.assert_called_once_with("/bin/sh -c 'cat /remote/path'", sudoable=False)
380 mock_open.assert_called_with("/local/path", "wb")
381
382
383 @patch("paramiko.SSHClient")
384 def test_fetch_file_general_error(mock_ssh, connection):
385 """Test fetch_file with general error"""
386 mock_client = MagicMock()
387 mock_ssh.return_value = mock_client
388 mock_channel = MagicMock()
389 mock_transport = MagicMock()
390
391 mock_client.get_transport.return_value = mock_transport
392 mock_transport.open_session.return_value = mock_channel
393 mock_channel.recv_exit_status.return_value = 1
394 mock_channel.makefile.return_value = [to_bytes("")]
395 mock_channel.makefile_stderr.return_value = [to_bytes("Some error")]
396
397 connection._connected = True
398 connection.ssh = mock_client
399
400 with pytest.raises(AnsibleError, match="error occurred while fetching file from /remote/path to /local/path"):
401 connection.fetch_file("/remote/path", "/local/path")
402
403
404 @patch("paramiko.SSHClient")
405 def test_fetch_file_cat_not_found(mock_ssh, connection):
406 """Test command execution when cat is not found"""
407 mock_client = MagicMock()
408 mock_ssh.return_value = mock_client
409 mock_channel = MagicMock()
410 mock_transport = MagicMock()
411
412 mock_client.get_transport.return_value = mock_transport
413 mock_transport.open_session.return_value = mock_channel
414 mock_channel.recv_exit_status.return_value = 1
415 mock_channel.makefile.return_value = [to_bytes("")]
416 mock_channel.makefile_stderr.return_value = [to_bytes("cat: not found")]
417
418 connection._connected = True
419 connection.ssh = mock_client
420
421 with pytest.raises(AnsibleError, match="cat not found in path of WSL distribution"):
422 connection.fetch_file("/remote/path", "/local/path")
423
424
425 def test_close(connection):
426 """Test connection close"""
427 mock_ssh = MagicMock()
428 connection.ssh = mock_ssh
429 connection._connected = True
430
431 connection.close()
432
433 assert mock_ssh.close.called, "ssh.close was not called"
434 assert not connection._connected, "self._connected is still True"
435
436
437 def test_close_with_lock_file(connection):
438 """Test close method with lock file creation"""
439 connection._any_keys_added = MagicMock(return_value=True)
440 connection._connected = True
441 connection.keyfile = "/tmp/wsl-known_hosts-test"
442 connection.set_option("host_key_checking", True)
443 connection.set_option("lock_file_timeout", 5)
444 connection.set_option("record_host_keys", True)
445 connection.ssh = MagicMock()
446
447 lock_file_path = os.path.join(
448 os.path.dirname(connection.keyfile), f"ansible-{os.path.basename(connection.keyfile)}.lock"
449 )
450
451 try:
452 connection.close()
453 assert os.path.exists(lock_file_path), "Lock file was not created"
454
455 lock_stat = os.stat(lock_file_path)
456 assert lock_stat.st_mode & 0o777 == 0o600, "Incorrect lock file permissions"
457 finally:
458 Path(lock_file_path).unlink(missing_ok=True)
459
460
461 @patch("pathlib.Path.unlink")
462 @patch("os.path.exists")
463 def test_close_lock_file_time_out_error_handling(mock_exists, mock_unlink, connection):
464 """Test close method with lock file timeout error"""
465 connection._any_keys_added = MagicMock(return_value=True)
466 connection._connected = True
467 connection._save_ssh_host_keys = MagicMock()
468 connection.keyfile = "/tmp/wsl-known_hosts-test"
469 connection.set_option("host_key_checking", True)
470 connection.set_option("lock_file_timeout", 5)
471 connection.set_option("record_host_keys", True)
472 connection.ssh = MagicMock()
473
474 mock_exists.return_value = False
475 matcher = f"writing lock file for {connection.keyfile} ran in to the timeout of {connection.get_option('lock_file_timeout')}s"
476 with pytest.raises(AnsibleError, match=matcher):
477 with (
478 patch("os.getuid", return_value=1000),
479 patch("os.getgid", return_value=1000),
480 patch("os.chmod"),
481 patch("os.chown"),
482 patch("os.rename"),
483 patch.object(FileLock, "lock_file", side_effect=LockTimeout()),
484 ):
485 connection.close()
486
487
488 @patch("ansible_collections.community.general.plugins.module_utils._filelock.FileLock.lock_file")
489 @patch("tempfile.NamedTemporaryFile")
490 @patch("os.chmod")
491 @patch("os.chown")
492 @patch("os.rename")
493 @patch("os.path.exists")
494 def test_tempfile_creation_and_move(
495 mock_exists, mock_rename, mock_chown, mock_chmod, mock_tempfile, mock_lock_file, connection
496 ):
497 """Test tempfile creation and move during close"""
498 connection._any_keys_added = MagicMock(return_value=True)
499 connection._connected = True
500 connection._save_ssh_host_keys = MagicMock()
501 connection.keyfile = "/tmp/wsl-known_hosts-test"
502 connection.set_option("host_key_checking", True)
503 connection.set_option("lock_file_timeout", 5)
504 connection.set_option("record_host_keys", True)
505 connection.ssh = MagicMock()
506
507 mock_exists.return_value = False
508
509 mock_lock_file_instance = MagicMock()
510 mock_lock_file.return_value = mock_lock_file_instance
511 mock_lock_file_instance.__enter__.return_value = None
512
513 mock_tempfile_instance = MagicMock()
514 mock_tempfile_instance.name = "/tmp/mock_tempfile"
515 mock_tempfile.return_value.__enter__.return_value = mock_tempfile_instance
516
517 mode = 0o644
518 uid = 1000
519 gid = 1000
520 key_dir = os.path.dirname(connection.keyfile)
521
522 with patch("os.getuid", return_value=uid), patch("os.getgid", return_value=gid):
523 connection.close()
524
525 connection._save_ssh_host_keys.assert_called_once_with("/tmp/mock_tempfile")
526 mock_chmod.assert_called_once_with("/tmp/mock_tempfile", mode)
527 mock_chown.assert_called_once_with("/tmp/mock_tempfile", uid, gid)
528 mock_rename.assert_called_once_with("/tmp/mock_tempfile", connection.keyfile)
529 mock_tempfile.assert_called_once_with(dir=key_dir, delete=False)
530
531
532 @patch("pathlib.Path.unlink")
533 @patch("tempfile.NamedTemporaryFile")
534 @patch("ansible_collections.community.general.plugins.module_utils._filelock.FileLock.lock_file")
535 @patch("os.path.exists")
536 def test_close_tempfile_error_handling(mock_exists, mock_lock_file, mock_tempfile, mock_unlink, connection):
537 """Test tempfile creation error"""
538 connection._any_keys_added = MagicMock(return_value=True)
539 connection._connected = True
540 connection._save_ssh_host_keys = MagicMock()
541 connection.keyfile = "/tmp/wsl-known_hosts-test"
542 connection.set_option("host_key_checking", True)
543 connection.set_option("lock_file_timeout", 5)
544 connection.set_option("record_host_keys", True)
545 connection.ssh = MagicMock()
546
547 mock_exists.return_value = False
548
549 mock_lock_file_instance = MagicMock()
550 mock_lock_file.return_value = mock_lock_file_instance
551 mock_lock_file_instance.__enter__.return_value = None
552
553 mock_tempfile_instance = MagicMock()
554 mock_tempfile_instance.name = "/tmp/mock_tempfile"
555 mock_tempfile.return_value.__enter__.return_value = mock_tempfile_instance
556
557 with pytest.raises(AnsibleError, match="error occurred while writing SSH host keys!"):
558 with patch.object(os, "chmod", side_effect=Exception()):
559 connection.close()
560 mock_unlink.assert_called_with(missing_ok=True)
561
562
563 @patch("ansible_collections.community.general.plugins.module_utils._filelock.FileLock.lock_file")
564 @patch("os.path.exists")
565 def test_close_with_invalid_host_key(mock_exists, mock_lock_file, connection):
566 """Test load_system_host_keys on close with InvalidHostKey error"""
567 connection._any_keys_added = MagicMock(return_value=True)
568 connection._connected = True
569 connection._save_ssh_host_keys = MagicMock()
570 connection.keyfile = "/tmp/wsl-known_hosts-test"
571 connection.set_option("host_key_checking", True)
572 connection.set_option("lock_file_timeout", 5)
573 connection.set_option("record_host_keys", True)
574 connection.ssh = MagicMock()
575 connection.ssh.load_system_host_keys.side_effect = paramiko.hostkeys.InvalidHostKey(
576 "Bad Line!", Exception("Something crashed!")
577 )
578
579 mock_exists.return_value = False
580
581 mock_lock_file_instance = MagicMock()
582 mock_lock_file.return_value = mock_lock_file_instance
583 mock_lock_file_instance.__enter__.return_value = None
584
585 with pytest.raises(AnsibleConnectionFailure, match="Invalid host key: Bad Line!"):
586 connection.close()
587
588
589 def test_reset(connection):
590 """Test connection reset"""
591 connection._connected = True
592 connection.close = MagicMock()
593 connection._connect = MagicMock()
594
595 connection.reset()
596
597 connection.close.assert_called_once()
598 connection._connect.assert_called_once()
599
600 connection._connected = False
601 connection.reset()
602 assert connection.close.call_count == 1