Debian Codegraph @

ansible_collections/community/proxmox/tests/unit/plugins/connection/test_proxmox_pct_remote.py

raw
1 # Copyright (c) 2024 Nils Stein (@mietzen) <[email protected]>
2 # Copyright (c) 2024 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 import os
9 import stat
10 from contextlib import ExitStack
11 from io import StringIO
12 from pathlib import Path
13 from unittest.mock import MagicMock, mock_open, patch
14
15 import pytest
16 from ansible.errors import AnsibleAuthenticationFailure, AnsibleConnectionFailure, AnsibleError
17 from ansible.module_utils.common.text.converters import to_bytes
18 from ansible.playbook.play_context import PlayContext
19 from ansible.plugins.loader import connection_loader
20
21 from ansible_collections.community.proxmox.plugins.connection.proxmox_pct_remote import MyAddPolicy, authenticity_msg
22 from ansible_collections.community.proxmox.plugins.module_utils._filelock import FileLock, LockTimeout
23
24 paramiko = pytest.importorskip("paramiko")
25
26
27 @pytest.fixture
28 def connection():
29 play_context = PlayContext()
30 in_stream = StringIO()
31 conn = connection_loader.get("community.proxmox.proxmox_pct_remote", play_context, in_stream)
32 conn.set_option("remote_addr", "192.168.1.100")
33 conn.set_option("remote_user", "root")
34 conn.set_option("password", "password")
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
44
45 def test_authenticity_msg():
46 """Test authenticity message formatting"""
47 msg = authenticity_msg("test.host", "ssh-rsa", "AA:BB:CC:DD")
48 assert "test.host" in msg
49 assert "ssh-rsa" in msg
50 assert "AA:BB:CC:DD" in msg
51
52
53 def test_missing_host_key(connection):
54 """Test MyAddPolicy missing_host_key method"""
55
56 client = MagicMock()
57 key = MagicMock()
58 key.get_fingerprint.return_value = b"fingerprint"
59 key.get_name.return_value = "ssh-rsa"
60
61 policy = MyAddPolicy(connection)
62
63 connection.set_option("host_key_auto_add", True)
64 policy.missing_host_key(client, "test.host", key)
65 assert hasattr(key, "_added_by_ansible_this_time")
66
67 connection.set_option("host_key_auto_add", False)
68 connection.set_option("host_key_checking", False)
69 policy.missing_host_key(client, "test.host", key)
70
71 connection.set_option("host_key_checking", True)
72 connection.set_option("host_key_auto_add", False)
73 connection.set_option("use_persistent_connections", False)
74
75 with patch("ansible.utils.display.Display.prompt_until", return_value="yes"):
76 policy.missing_host_key(client, "test.host", key)
77
78 with patch("ansible.utils.display.Display.prompt_until", return_value="no"), pytest.raises(
79 AnsibleError, match="host connection rejected by user"
80 ):
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_pct_command(connection):
201 """Test PCT command building with different users"""
202 connection.set_option("vmid", "100")
203
204 cmd = connection._build_pct_command('/bin/sh -c "ls -la"')
205 assert cmd == '/usr/sbin/pct exec 100 -- /bin/sh -c "ls -la"'
206
207 connection.set_option("remote_user", "user")
208 connection.set_option("proxmox_become_method", "sudo")
209 cmd = connection._build_pct_command('/bin/sh -c "ls -la"')
210 assert cmd == 'sudo /usr/sbin/pct exec 100 -- /bin/sh -c "ls -la"'
211
212
213 @patch("paramiko.SSHClient")
214 def test_exec_command_success(mock_ssh, connection):
215 """Test successful command execution"""
216 mock_client = MagicMock()
217 mock_ssh.return_value = mock_client
218 mock_channel = MagicMock()
219 mock_transport = MagicMock()
220
221 mock_client.get_transport.return_value = mock_transport
222 mock_transport.open_session.return_value = mock_channel
223 mock_channel.recv_exit_status.return_value = 0
224 mock_channel.makefile.return_value = [to_bytes("stdout")]
225 mock_channel.makefile_stderr.return_value = [to_bytes("")]
226
227 connection._connected = True
228 connection.ssh = mock_client
229
230 returncode, stdout, stderr = connection.exec_command("ls -la")
231
232 mock_transport.open_session.assert_called_once()
233 mock_channel.get_pty.assert_called_once()
234 mock_transport.set_keepalive.assert_called_once_with(5)
235
236
237 @patch("paramiko.SSHClient")
238 def test_exec_command_pct_not_found(mock_ssh, connection):
239 """Test command execution when PCT is not found"""
240 mock_client = MagicMock()
241 mock_ssh.return_value = mock_client
242 mock_channel = MagicMock()
243 mock_transport = MagicMock()
244
245 mock_client.get_transport.return_value = mock_transport
246 mock_transport.open_session.return_value = mock_channel
247 mock_channel.recv_exit_status.return_value = 1
248 mock_channel.makefile.return_value = [to_bytes("")]
249 mock_channel.makefile_stderr.return_value = [to_bytes("pct: not found")]
250
251 connection._connected = True
252 connection.ssh = mock_client
253
254 with pytest.raises(AnsibleError, match="pct not found in path of host"):
255 connection.exec_command("ls -la")
256
257
258 @patch("paramiko.SSHClient")
259 def test_exec_command_session_open_failure(mock_ssh, connection):
260 """Test exec_command when session opening fails"""
261 mock_client = MagicMock()
262 mock_transport = MagicMock()
263 mock_transport.open_session.side_effect = Exception("Failed to open session")
264 mock_client.get_transport.return_value = mock_transport
265
266 connection._connected = True
267 connection.ssh = mock_client
268
269 with pytest.raises(AnsibleConnectionFailure, match="Failed to open session"):
270 connection.exec_command("test command")
271
272
273 @patch("paramiko.SSHClient")
274 def test_exec_command_with_privilege_escalation(mock_ssh, connection):
275 """Test exec_command with privilege escalation"""
276 mock_client = MagicMock()
277 mock_channel = MagicMock()
278 mock_transport = MagicMock()
279
280 mock_client.get_transport.return_value = mock_transport
281 mock_transport.open_session.return_value = mock_channel
282 connection._connected = True
283 connection.ssh = mock_client
284
285 connection.become = MagicMock()
286 connection.become.expect_prompt.return_value = True
287 connection.become.check_success.return_value = False
288 connection.become.check_password_prompt.return_value = True
289 connection.become.get_option.return_value = "sudo_password"
290
291 mock_channel.recv.return_value = b"[sudo] password:"
292 mock_channel.recv_exit_status.return_value = 0
293 mock_channel.makefile.return_value = [b""]
294 mock_channel.makefile_stderr.return_value = [b""]
295
296 returncode, stdout, stderr = connection.exec_command("sudo test command")
297
298 mock_channel.sendall.assert_called_once_with(b"sudo_password\n")
299
300
301 @patch("paramiko.SSHClient")
302 def test_exec_command_with_forward_agent(mock_ssh, connection):
303 """Test exec_command with forward agent"""
304 mock_client = MagicMock()
305 mock_channel = MagicMock()
306 mock_transport = MagicMock()
307
308 mock_client.get_transport.return_value = mock_transport
309 mock_transport.open_session.return_value = mock_channel
310 connection._connected = True
311 connection.ssh = mock_client
312
313 connection.set_option("forward_agent", True)
314
315 with patch("paramiko.agent.AgentRequestHandler") as mock_agent_handler:
316 connection.exec_command("test command")
317 mock_agent_handler.assert_called_once_with(mock_channel)
318
319
320 def test_put_file(connection):
321 """Test putting a file to the remote system"""
322 connection.exec_command = MagicMock()
323 connection.exec_command.return_value = (0, b"", b"")
324
325 with patch("builtins.open", create=True) as mock_open:
326 mock_open.return_value.__enter__.return_value.read.return_value = b"test content"
327 connection.put_file("/local/path", "/remote/path")
328
329 connection.exec_command.assert_called_once_with(
330 "/bin/sh -c 'cat > /remote/path'", in_data=b"test content", sudoable=False
331 )
332
333
334 @patch("paramiko.SSHClient")
335 def test_put_file_general_error(mock_ssh, connection):
336 """Test put_file with general error"""
337 mock_client = MagicMock()
338 mock_ssh.return_value = mock_client
339 mock_channel = MagicMock()
340 mock_transport = MagicMock()
341
342 mock_client.get_transport.return_value = mock_transport
343 mock_transport.open_session.return_value = mock_channel
344 mock_channel.recv_exit_status.return_value = 1
345 mock_channel.makefile.return_value = [to_bytes("")]
346 mock_channel.makefile_stderr.return_value = [to_bytes("Some error")]
347
348 connection._connected = True
349 connection.ssh = mock_client
350
351 with pytest.raises(AnsibleError, match="error occurred while putting file from /remote/path to /local/path"):
352 connection.put_file("/remote/path", "/local/path")
353
354
355 @patch("paramiko.SSHClient")
356 def test_put_file_cat_not_found(mock_ssh, connection):
357 """Test command execution when cat is not found"""
358 mock_client = MagicMock()
359 mock_ssh.return_value = mock_client
360 mock_channel = MagicMock()
361 mock_transport = MagicMock()
362
363 mock_client.get_transport.return_value = mock_transport
364 mock_transport.open_session.return_value = mock_channel
365 mock_channel.recv_exit_status.return_value = 1
366 mock_channel.makefile.return_value = [to_bytes("")]
367 mock_channel.makefile_stderr.return_value = [to_bytes("cat: not found")]
368
369 connection._connected = True
370 connection.ssh = mock_client
371
372 with pytest.raises(AnsibleError, match="cat not found in path of container:"):
373 connection.fetch_file("/remote/path", "/local/path")
374
375
376 def test_fetch_file(connection):
377 """Test fetching a file from the remote system"""
378 connection.exec_command = MagicMock()
379 connection.exec_command.return_value = (0, b"test content", b"")
380
381 with patch("builtins.open", create=True) as mock_open:
382 connection.fetch_file("/remote/path", "/local/path")
383
384 connection.exec_command.assert_called_once_with("/bin/sh -c 'cat /remote/path'", sudoable=False)
385 mock_open.assert_called_with("/local/path", "wb")
386
387
388 @patch("paramiko.SSHClient")
389 def test_fetch_file_general_error(mock_ssh, connection):
390 """Test fetch_file with general error"""
391 mock_client = MagicMock()
392 mock_ssh.return_value = mock_client
393 mock_channel = MagicMock()
394 mock_transport = MagicMock()
395
396 mock_client.get_transport.return_value = mock_transport
397 mock_transport.open_session.return_value = mock_channel
398 mock_channel.recv_exit_status.return_value = 1
399 mock_channel.makefile.return_value = [to_bytes("")]
400 mock_channel.makefile_stderr.return_value = [to_bytes("Some error")]
401
402 connection._connected = True
403 connection.ssh = mock_client
404
405 with pytest.raises(AnsibleError, match="error occurred while fetching file from /remote/path to /local/path"):
406 connection.fetch_file("/remote/path", "/local/path")
407
408
409 @patch("paramiko.SSHClient")
410 def test_fetch_file_cat_not_found(mock_ssh, connection):
411 """Test command execution when cat is not found"""
412 mock_client = MagicMock()
413 mock_ssh.return_value = mock_client
414 mock_channel = MagicMock()
415 mock_transport = MagicMock()
416
417 mock_client.get_transport.return_value = mock_transport
418 mock_transport.open_session.return_value = mock_channel
419 mock_channel.recv_exit_status.return_value = 1
420 mock_channel.makefile.return_value = [to_bytes("")]
421 mock_channel.makefile_stderr.return_value = [to_bytes("cat: not found")]
422
423 connection._connected = True
424 connection.ssh = mock_client
425
426 with pytest.raises(AnsibleError, match="cat not found in path of container:"):
427 connection.fetch_file("/remote/path", "/local/path")
428
429
430 def test_close(connection):
431 """Test connection close"""
432 mock_ssh = MagicMock()
433 connection.ssh = mock_ssh
434 connection._connected = True
435
436 connection.close()
437
438 assert mock_ssh.close.called, "ssh.close was not called"
439 assert not connection._connected, "self._connected is still True"
440
441
442 def test_close_with_lock_file(connection):
443 """Test close method with lock file creation"""
444 connection._any_keys_added = MagicMock(return_value=True)
445 connection._connected = True
446 connection.keyfile = "/tmp/pct-remote-known_hosts-test"
447 connection.set_option("host_key_checking", True)
448 connection.set_option("lock_file_timeout", 5)
449 connection.set_option("record_host_keys", True)
450 connection.ssh = MagicMock()
451
452 lock_file_path = os.path.join(
453 os.path.dirname(connection.keyfile), f"ansible-{os.path.basename(connection.keyfile)}.lock"
454 )
455
456 try:
457 connection.close()
458 assert os.path.exists(lock_file_path), "Lock file was not created"
459
460 lock_stat = os.stat(lock_file_path)
461 assert stat.S_IMODE(lock_stat.st_mode) == (stat.S_IWRITE | stat.S_IREAD), "Incorrect lock file permissions"
462 finally:
463 Path(lock_file_path).unlink(missing_ok=True)
464
465
466 @patch("pathlib.Path.unlink")
467 @patch("os.path.exists")
468 def test_close_lock_file_time_out_error_handling(mock_exists, mock_unlink, connection):
469 """Test close method with lock file timeout error"""
470 connection._any_keys_added = MagicMock(return_value=True)
471 connection._connected = True
472 connection._save_ssh_host_keys = MagicMock()
473 connection.keyfile = "/tmp/pct-remote-known_hosts-test"
474 connection.set_option("host_key_checking", True)
475 connection.set_option("lock_file_timeout", 5)
476 connection.set_option("record_host_keys", True)
477 connection.ssh = MagicMock()
478
479 mock_exists.return_value = False
480 matcher = f"writing lock file for {connection.keyfile} ran in to the timeout of {connection.get_option('lock_file_timeout')}s"
481
482 with pytest.raises(AnsibleError, match=matcher), ExitStack() as stack:
483 stack.enter_context(patch("os.getuid", return_value=1000))
484 stack.enter_context(patch("os.getgid", return_value=1000))
485 stack.enter_context(patch("os.chmod"))
486 stack.enter_context(patch("os.chown"))
487 stack.enter_context(patch("os.rename"))
488 stack.enter_context(patch.object(FileLock, "lock_file", side_effect=LockTimeout()))
489 connection.close()
490
491
492 @patch("ansible_collections.community.proxmox.plugins.module_utils._filelock.FileLock.lock_file")
493 @patch("tempfile.NamedTemporaryFile")
494 @patch("os.chmod")
495 @patch("os.chown")
496 @patch("os.rename")
497 @patch("os.path.exists")
498 def test_tempfile_creation_and_move( # noqa: PLR0913
499 mock_exists, mock_rename, mock_chown, mock_chmod, mock_tempfile, mock_lock_file, connection
500 ):
501 """Test tempfile creation and move during close"""
502 connection._any_keys_added = MagicMock(return_value=True)
503 connection._connected = True
504 connection._save_ssh_host_keys = MagicMock()
505 connection.keyfile = "/tmp/pct-remote-known_hosts-test"
506 connection.set_option("host_key_checking", True)
507 connection.set_option("lock_file_timeout", 5)
508 connection.set_option("record_host_keys", True)
509 connection.ssh = MagicMock()
510
511 mock_exists.return_value = False
512
513 mock_lock_file_instance = MagicMock()
514 mock_lock_file.return_value = mock_lock_file_instance
515 mock_lock_file_instance.__enter__.return_value = None
516
517 mock_tempfile_instance = MagicMock()
518 mock_tempfile_instance.name = "/tmp/mock_tempfile"
519 mock_tempfile.return_value.__enter__.return_value = mock_tempfile_instance
520
521 mode = 0o644
522 uid = 1000
523 gid = 1000
524 key_dir = os.path.dirname(connection.keyfile)
525
526 with patch("os.getuid", return_value=uid), patch("os.getgid", return_value=gid):
527 connection.close()
528
529 connection._save_ssh_host_keys.assert_called_once_with("/tmp/mock_tempfile")
530 mock_chmod.assert_called_once_with("/tmp/mock_tempfile", mode)
531 mock_chown.assert_called_once_with("/tmp/mock_tempfile", uid, gid)
532 mock_rename.assert_called_once_with("/tmp/mock_tempfile", connection.keyfile)
533 mock_tempfile.assert_called_once_with(dir=key_dir, delete=False)
534
535
536 @patch("pathlib.Path.unlink")
537 @patch("tempfile.NamedTemporaryFile")
538 @patch("ansible_collections.community.proxmox.plugins.module_utils._filelock.FileLock.lock_file")
539 @patch("os.path.exists")
540 def test_close_tempfile_error_handling(mock_exists, mock_lock_file, mock_tempfile, mock_unlink, connection):
541 """Test tempfile creation error"""
542 connection._any_keys_added = MagicMock(return_value=True)
543 connection._connected = True
544 connection._save_ssh_host_keys = MagicMock()
545 connection.keyfile = "/tmp/pct-remote-known_hosts-test"
546 connection.set_option("host_key_checking", True)
547 connection.set_option("lock_file_timeout", 5)
548 connection.set_option("record_host_keys", True)
549 connection.ssh = MagicMock()
550
551 mock_exists.return_value = False
552
553 mock_lock_file_instance = MagicMock()
554 mock_lock_file.return_value = mock_lock_file_instance
555 mock_lock_file_instance.__enter__.return_value = None
556
557 mock_tempfile_instance = MagicMock()
558 mock_tempfile_instance.name = "/tmp/mock_tempfile"
559 mock_tempfile.return_value.__enter__.return_value = mock_tempfile_instance
560
561 with pytest.raises(AnsibleError, match="error occurred while writing SSH host keys!"), patch.object(
562 os, "chmod", side_effect=Exception()
563 ):
564 connection.close()
565 mock_unlink.assert_called_with(missing_ok=True)
566
567
568 @patch("ansible_collections.community.proxmox.plugins.module_utils._filelock.FileLock.lock_file")
569 @patch("os.path.exists")
570 def test_close_with_invalid_host_key(mock_exists, mock_lock_file, connection):
571 """Test load_system_host_keys on close with InvalidHostKey error"""
572 connection._any_keys_added = MagicMock(return_value=True)
573 connection._connected = True
574 connection._save_ssh_host_keys = MagicMock()
575 connection.keyfile = "/tmp/pct-remote-known_hosts-test"
576 connection.set_option("host_key_checking", True)
577 connection.set_option("lock_file_timeout", 5)
578 connection.set_option("record_host_keys", True)
579 connection.ssh = MagicMock()
580 connection.ssh.load_system_host_keys.side_effect = paramiko.hostkeys.InvalidHostKey(
581 "Bad Line!", Exception("Something crashed!")
582 )
583
584 mock_exists.return_value = False
585
586 mock_lock_file_instance = MagicMock()
587 mock_lock_file.return_value = mock_lock_file_instance
588 mock_lock_file_instance.__enter__.return_value = None
589
590 with pytest.raises(AnsibleConnectionFailure, match="Invalid host key: Bad Line!"):
591 connection.close()
592
593
594 def test_reset(connection):
595 """Test connection reset"""
596 connection._connected = True
597 connection.close = MagicMock()
598 connection._connect = MagicMock()
599
600 connection.reset()
601
602 connection.close.assert_called_once()
603 connection._connect.assert_called_once()
604
605 connection._connected = False
606 connection.reset()
607 assert connection.close.call_count == 1