Debian Codegraph @

tests/test_config.py

raw
1 # This file is part of Paramiko and subject to the license in /LICENSE in this
2 # repository
3
4 from os.path import expanduser
5 from socket import gaierror
6
7 try:
8 from invoke import Result
9 except ImportError:
10 Result = None
11
12 from unittest.mock import patch
13 from pytest import raises, mark, fixture
14
15 from paramiko import (
16 SSHConfig,
17 SSHConfigDict,
18 CouldNotCanonicalize,
19 ConfigParseError,
20 )
21
22 from ._util import _config
23
24
25 @fixture
26 def socket():
27 """
28 Patch all of socket.* in our config module to prevent eg real DNS lookups.
29
30 Also forces getaddrinfo (used in our addressfamily lookup stuff) to always
31 fail by default to mimic usual lack of AddressFamily related crap.
32
33 Callers who want to mock DNS lookups can then safely assume gethostbyname()
34 will be in use.
35 """
36 with patch("paramiko.config.socket") as mocket:
37 # Reinstate gaierror as an actual exception and not a sub-mock.
38 # (Presumably this would work with any exception, but why not use the
39 # real one?)
40 mocket.gaierror = gaierror
41 # Patch out getaddrinfo, used to detect family-specific IP lookup -
42 # only useful for a few specific tests.
43 mocket.getaddrinfo.side_effect = mocket.gaierror
44 # Patch out getfqdn to return some real string for when it gets called;
45 # some code (eg tokenization) gets mad w/ MagicMocks
46 mocket.getfqdn.return_value = "some.fake.fqdn"
47 mocket.gethostname.return_value = "local.fake.fqdn"
48 yield mocket
49
50
51 def load_config(name):
52 return SSHConfig.from_path(_config(name))
53
54
55 class TestSSHConfig:
56 def setup_method(self):
57 self.config = load_config("robey")
58
59 def test_init(self):
60 # No args!
61 with raises(TypeError):
62 SSHConfig("uh oh!")
63 # No args.
64 assert not SSHConfig()._config
65
66 def test_from_text(self):
67 config = SSHConfig.from_text("User foo")
68 assert config.lookup("foo.example.com")["user"] == "foo"
69
70 def test_from_file(self):
71 with open(_config("robey")) as flo:
72 config = SSHConfig.from_file(flo)
73 assert config.lookup("whatever")["user"] == "robey"
74
75 def test_from_path(self):
76 # NOTE: DO NOT replace with use of load_config() :D
77 config = SSHConfig.from_path(_config("robey"))
78 assert config.lookup("meh.example.com")["port"] == "3333"
79
80 def test_parse_config(self):
81 expected = [
82 {"host": ["*"], "config": {}},
83 {
84 "host": ["*"],
85 "config": {"identityfile": ["~/.ssh/id_rsa"], "user": "robey"},
86 },
87 {
88 "host": ["*.example.com"],
89 "config": {"user": "bjork", "port": "3333"},
90 },
91 {"host": ["*"], "config": {"crazy": "something dumb"}},
92 {
93 "host": ["spoo.example.com"],
94 "config": {"crazy": "something else"},
95 },
96 ]
97 assert self.config._config == expected
98
99 @mark.parametrize(
100 "host,values",
101 (
102 (
103 "irc.danger.com",
104 {
105 "crazy": "something dumb",
106 "hostname": "irc.danger.com",
107 "user": "robey",
108 },
109 ),
110 (
111 "irc.example.com",
112 {
113 "crazy": "something dumb",
114 "hostname": "irc.example.com",
115 "user": "robey",
116 "port": "3333",
117 },
118 ),
119 (
120 "spoo.example.com",
121 {
122 "crazy": "something dumb",
123 "hostname": "spoo.example.com",
124 "user": "robey",
125 "port": "3333",
126 },
127 ),
128 ),
129 )
130 def test_host_config(self, host, values):
131 expected = dict(
132 values, hostname=host, identityfile=[expanduser("~/.ssh/id_rsa")]
133 )
134 assert self.config.lookup(host) == expected
135
136 def test_fabric_issue_33(self):
137 config = SSHConfig.from_text(
138 """
139 Host www13.*
140 Port 22
141
142 Host *.example.com
143 Port 2222
144
145 Host *
146 Port 3333
147 """
148 )
149 host = "www13.example.com"
150 expected = {"hostname": host, "port": "22"}
151 assert config.lookup(host) == expected
152
153 def test_proxycommand_config_equals_parsing(self):
154 """
155 ProxyCommand should not split on equals signs within the value.
156 """
157 config = SSHConfig.from_text(
158 """
159 Host space-delimited
160 ProxyCommand foo bar=biz baz
161
162 Host equals-delimited
163 ProxyCommand=foo bar=biz baz
164 """
165 )
166 for host in ("space-delimited", "equals-delimited"):
167 value = config.lookup(host)["proxycommand"]
168 assert value == "foo bar=biz baz"
169
170 def test_proxycommand_interpolation(self):
171 """
172 ProxyCommand should perform interpolation on the value
173 """
174 config = SSHConfig.from_text(
175 """
176 Host specific
177 Port 37
178 ProxyCommand host %h port %p lol
179
180 Host portonly
181 Port 155
182
183 Host *
184 Port 25
185 ProxyCommand host %h port %p
186 """
187 )
188 for host, val in (
189 ("foo.com", "host foo.com port 25"),
190 ("specific", "host specific port 37 lol"),
191 ("portonly", "host portonly port 155"),
192 ):
193 assert config.lookup(host)["proxycommand"] == val
194
195 def test_proxycommand_tilde_expansion(self):
196 """
197 Tilde (~) should be expanded inside ProxyCommand
198 """
199 config = SSHConfig.from_text(
200 """
201 Host test
202 ProxyCommand ssh -F ~/.ssh/test_config bastion nc %h %p
203 """
204 )
205 expected = "ssh -F {}/.ssh/test_config bastion nc test 22".format(
206 expanduser("~")
207 )
208 got = config.lookup("test")["proxycommand"]
209 assert got == expected
210
211 @patch("paramiko.config.getpass")
212 def test_proxyjump_token_expansion(self, getpass):
213 getpass.getuser.return_value = "gandalf"
214 config = SSHConfig.from_text(
215 """
216 Host justhost
217 ProxyJump jumpuser@%h
218 Host userhost
219 ProxyJump %r@%h:222
220 Host allcustom
221 ProxyJump %r@%h:%p
222 """
223 )
224 assert config.lookup("justhost")["proxyjump"] == "jumpuser@justhost"
225 assert config.lookup("userhost")["proxyjump"] == "gandalf@userhost:222"
226 assert (
227 config.lookup("allcustom")["proxyjump"] == "gandalf@allcustom:22"
228 )
229
230 @patch("paramiko.config.getpass")
231 def test_controlpath_token_expansion(self, getpass, socket):
232 getpass.getuser.return_value = "gandalf"
233 config = SSHConfig.from_text(
234 """
235 Host explicit_user
236 User root
237 ControlPath user %u remoteuser %r
238
239 Host explicit_host
240 HostName ohai
241 ControlPath remoteuser %r host %h orighost %n
242
243 Host hashbrowns
244 ControlPath %C
245 """
246 )
247 result = config.lookup("explicit_user")["controlpath"]
248 # Remote user is User val, local user is User val
249 assert result == "user gandalf remoteuser root"
250 result = config.lookup("explicit_host")["controlpath"]
251 # Remote user falls back to local user; host and orighost may differ
252 assert result == "remoteuser gandalf host ohai orighost explicit_host"
253 # Supports %C
254 result = config.lookup("hashbrowns")["controlpath"]
255 assert result == "a438e7dbf5308b923aba9db8fe2ca63447ac8688"
256
257 def test_negation(self):
258 config = SSHConfig.from_text(
259 """
260 Host www13.* !*.example.com
261 Port 22
262
263 Host *.example.com !www13.*
264 Port 2222
265
266 Host www13.*
267 Port 8080
268
269 Host *
270 Port 3333
271 """
272 )
273 host = "www13.example.com"
274 expected = {"hostname": host, "port": "8080"}
275 assert config.lookup(host) == expected
276
277 def test_proxycommand(self):
278 config = SSHConfig.from_text(
279 """
280 Host proxy-with-equal-divisor-and-space
281 ProxyCommand = foo=bar
282
283 Host proxy-with-equal-divisor-and-no-space
284 ProxyCommand=foo=bar
285
286 Host proxy-without-equal-divisor
287 ProxyCommand foo=bar:%h-%p
288 """
289 )
290 for host, values in {
291 "proxy-with-equal-divisor-and-space": {
292 "hostname": "proxy-with-equal-divisor-and-space",
293 "proxycommand": "foo=bar",
294 },
295 "proxy-with-equal-divisor-and-no-space": {
296 "hostname": "proxy-with-equal-divisor-and-no-space",
297 "proxycommand": "foo=bar",
298 },
299 "proxy-without-equal-divisor": {
300 "hostname": "proxy-without-equal-divisor",
301 "proxycommand": "foo=bar:proxy-without-equal-divisor-22",
302 },
303 }.items():
304
305 assert config.lookup(host) == values
306
307 @patch("paramiko.config.getpass")
308 def test_identityfile(self, getpass, socket):
309 getpass.getuser.return_value = "gandalf"
310 config = SSHConfig.from_text(
311 """
312 IdentityFile id_rsa0
313
314 Host *
315 IdentityFile id_rsa1
316
317 Host rsa2
318 IdentityFile id_rsa2
319
320 Host rsa2*
321 IdentityFile id_rsa22
322
323 Host hashbrowns
324 IdentityFile %C
325 """
326 )
327 for host, values in {
328 "foo": {"hostname": "foo", "identityfile": ["id_rsa0", "id_rsa1"]},
329 "rsa2": {
330 "hostname": "rsa2",
331 "identityfile": ["id_rsa0", "id_rsa1", "id_rsa2", "id_rsa22"],
332 },
333 "rsa22": {
334 "hostname": "rsa22",
335 "identityfile": ["id_rsa0", "id_rsa1", "id_rsa22"],
336 },
337 "hashbrowns": {
338 "hostname": "hashbrowns",
339 "identityfile": [
340 "id_rsa0",
341 "id_rsa1",
342 "a438e7dbf5308b923aba9db8fe2ca63447ac8688",
343 ],
344 },
345 }.items():
346 assert config.lookup(host) == values
347
348 def test_config_addressfamily_and_lazy_fqdn(self):
349 """
350 Ensure the code path honoring non-'all' AddressFamily doesn't asplode
351 """
352 config = SSHConfig.from_text(
353 """
354 AddressFamily inet
355 IdentityFile something_%l_using_fqdn
356 """
357 )
358 assert config.lookup(
359 "meh"
360 ) # will die during lookup() if bug regresses
361
362 def test_config_dos_crlf_succeeds(self):
363 config = SSHConfig.from_text(
364 """
365 Host abcqwerty\r\nHostName 127.0.0.1\r\n
366 """
367 )
368 assert config.lookup("abcqwerty")["hostname"] == "127.0.0.1"
369
370 def test_get_hostnames(self):
371 expected = {"*", "*.example.com", "spoo.example.com"}
372 assert self.config.get_hostnames() == expected
373
374 def test_quoted_host_names(self):
375 config = SSHConfig.from_text(
376 """
377 Host "param pam" param "pam"
378 Port 1111
379
380 Host "param2"
381 Port 2222
382
383 Host param3 parara
384 Port 3333
385
386 Host param4 "p a r" "p" "par" para
387 Port 4444
388 """
389 )
390 res = {
391 "param pam": {"hostname": "param pam", "port": "1111"},
392 "param": {"hostname": "param", "port": "1111"},
393 "pam": {"hostname": "pam", "port": "1111"},
394 "param2": {"hostname": "param2", "port": "2222"},
395 "param3": {"hostname": "param3", "port": "3333"},
396 "parara": {"hostname": "parara", "port": "3333"},
397 "param4": {"hostname": "param4", "port": "4444"},
398 "p a r": {"hostname": "p a r", "port": "4444"},
399 "p": {"hostname": "p", "port": "4444"},
400 "par": {"hostname": "par", "port": "4444"},
401 "para": {"hostname": "para", "port": "4444"},
402 }
403 for host, values in res.items():
404 assert config.lookup(host) == values
405
406 def test_quoted_params_in_config(self):
407 config = SSHConfig.from_text(
408 """
409 Host "param pam" param "pam"
410 IdentityFile id_rsa
411
412 Host "param2"
413 IdentityFile "test rsa key"
414
415 Host param3 parara
416 IdentityFile id_rsa
417 IdentityFile "test rsa key"
418 """
419 )
420 res = {
421 "param pam": {"hostname": "param pam", "identityfile": ["id_rsa"]},
422 "param": {"hostname": "param", "identityfile": ["id_rsa"]},
423 "pam": {"hostname": "pam", "identityfile": ["id_rsa"]},
424 "param2": {"hostname": "param2", "identityfile": ["test rsa key"]},
425 "param3": {
426 "hostname": "param3",
427 "identityfile": ["id_rsa", "test rsa key"],
428 },
429 "parara": {
430 "hostname": "parara",
431 "identityfile": ["id_rsa", "test rsa key"],
432 },
433 }
434 for host, values in res.items():
435 assert config.lookup(host) == values
436
437 def test_quoted_host_in_config(self):
438 conf = SSHConfig()
439 correct_data = {
440 "param": ["param"],
441 '"param"': ["param"],
442 "param pam": ["param", "pam"],
443 '"param" "pam"': ["param", "pam"],
444 '"param" pam': ["param", "pam"],
445 'param "pam"': ["param", "pam"],
446 'param "pam" p': ["param", "pam", "p"],
447 '"param" pam "p"': ["param", "pam", "p"],
448 '"pa ram"': ["pa ram"],
449 '"pa ram" pam': ["pa ram", "pam"],
450 'param "p a m"': ["param", "p a m"],
451 }
452 incorrect_data = ['param"', '"param', 'param "pam', 'param "pam" "p a']
453 for host, values in correct_data.items():
454 assert conf._get_hosts(host) == values
455 for host in incorrect_data:
456 with raises(ConfigParseError):
457 conf._get_hosts(host)
458
459 def test_invalid_line_format_excepts(self):
460 with raises(ConfigParseError):
461 load_config("invalid")
462
463 def test_proxycommand_none_issue_415(self):
464 config = SSHConfig.from_text(
465 """
466 Host proxycommand-standard-none
467 ProxyCommand None
468
469 Host proxycommand-with-equals-none
470 ProxyCommand=None
471 """
472 )
473 for host, values in {
474 "proxycommand-standard-none": {
475 "hostname": "proxycommand-standard-none",
476 "proxycommand": None,
477 },
478 "proxycommand-with-equals-none": {
479 "hostname": "proxycommand-with-equals-none",
480 "proxycommand": None,
481 },
482 }.items():
483
484 assert config.lookup(host) == values
485
486 def test_proxycommand_none_masking(self):
487 # Re: https://github.com/paramiko/paramiko/issues/670
488 config = SSHConfig.from_text(
489 """
490 Host specific-host
491 ProxyCommand none
492
493 Host other-host
494 ProxyCommand other-proxy
495
496 Host *
497 ProxyCommand default-proxy
498 """
499 )
500 # In versions <3.0, 'None' ProxyCommands got deleted, and this itself
501 # caused bugs. In 3.0, we more cleanly map "none" to None. This test
502 # has been altered accordingly but left around to ensure no
503 # regressions.
504 assert config.lookup("specific-host")["proxycommand"] is None
505 assert config.lookup("other-host")["proxycommand"] == "other-proxy"
506 cmd = config.lookup("some-random-host")["proxycommand"]
507 assert cmd == "default-proxy"
508
509 def test_hostname_tokenization(self):
510 result = load_config("hostname-tokenized").lookup("whatever")
511 assert result["hostname"] == "prefix.whatever"
512
513
514 class TestSSHConfigDict:
515 def test_SSHConfigDict_construct_empty(self):
516 assert not SSHConfigDict()
517
518 def test_SSHConfigDict_construct_from_list(self):
519 assert SSHConfigDict([(1, 2)])[1] == 2
520
521 def test_SSHConfigDict_construct_from_dict(self):
522 assert SSHConfigDict({1: 2})[1] == 2
523
524 @mark.parametrize("true_ish", ("yes", "YES", "Yes", True))
525 def test_SSHConfigDict_as_bool_true_ish(self, true_ish):
526 assert SSHConfigDict({"key": true_ish}).as_bool("key") is True
527
528 @mark.parametrize("false_ish", ("no", "NO", "No", False))
529 def test_SSHConfigDict_as_bool(self, false_ish):
530 assert SSHConfigDict({"key": false_ish}).as_bool("key") is False
531
532 @mark.parametrize("int_val", ("42", 42))
533 def test_SSHConfigDict_as_int(self, int_val):
534 assert SSHConfigDict({"key": int_val}).as_int("key") == 42
535
536 @mark.parametrize("non_int", ("not an int", None, object()))
537 def test_SSHConfigDict_as_int_failures(self, non_int):
538 conf = SSHConfigDict({"key": non_int})
539
540 try:
541 int(non_int)
542 except Exception as e:
543 exception_type = type(e)
544
545 with raises(exception_type):
546 conf.as_int("key")
547
548 def test_SSHConfig_host_dicts_are_SSHConfigDict_instances(self):
549 config = SSHConfig.from_text(
550 """
551 Host *.example.com
552 Port 2222
553
554 Host *
555 Port 3333
556 """
557 )
558 assert config.lookup("foo.example.com").as_int("port") == 2222
559
560 def test_SSHConfig_wildcard_host_dicts_are_SSHConfigDict_instances(self):
561 config = SSHConfig.from_text(
562 """
563 Host *.example.com
564 Port 2222
565
566 Host *
567 Port 3333
568 """
569 )
570 assert config.lookup("anything-else").as_int("port") == 3333
571
572
573 class TestHostnameCanonicalization:
574 # NOTE: this class uses on-disk configs, and ones with real (at time of
575 # writing) DNS names, so that one can easily test OpenSSH's behavior using
576 # "ssh -F path/to/file.config -G <target>".
577
578 def test_off_by_default(self, socket):
579 result = load_config("basic").lookup("www")
580 assert result["hostname"] == "www"
581 assert "user" not in result
582 assert not socket.gethostbyname.called
583
584 def test_explicit_no_same_as_default(self, socket):
585 result = load_config("no-canon").lookup("www")
586 assert result["hostname"] == "www"
587 assert "user" not in result
588 assert not socket.gethostbyname.called
589
590 @mark.parametrize(
591 "config_name",
592 ("canon", "canon-always", "canon-local", "canon-local-always"),
593 )
594 def test_canonicalization_base_cases(self, socket, config_name):
595 result = load_config(config_name).lookup("www")
596 assert result["hostname"] == "www.paramiko.org"
597 assert result["user"] == "rando"
598 socket.gethostbyname.assert_called_once_with("www.paramiko.org")
599
600 def test_uses_getaddrinfo_when_AddressFamily_given(self, socket):
601 # Undo default 'always fails' mock
602 socket.getaddrinfo.side_effect = None
603 socket.getaddrinfo.return_value = [True] # just need 1st value truthy
604 result = load_config("canon-ipv4").lookup("www")
605 assert result["hostname"] == "www.paramiko.org"
606 assert result["user"] == "rando"
607 assert not socket.gethostbyname.called
608 gai_args = socket.getaddrinfo.call_args[0]
609 assert gai_args[0] == "www.paramiko.org"
610 assert gai_args[2] is socket.AF_INET # Mocked, but, still useful
611
612 @mark.skip
613 def test_empty_CanonicalDomains_canonicalizes_despite_noop(self, socket):
614 # Confirmed this is how OpenSSH behaves as well. Bit silly, but.
615 # TODO: this requires modifying SETTINGS_REGEX, which is a mite scary
616 # (honestly I'd prefer to move to a real parser lib anyhow) and since
617 # this is a very dumb corner case, it's marked skip for now.
618 result = load_config("empty-canon").lookup("www")
619 assert result["hostname"] == "www" # no paramiko.org
620 assert "user" not in result # did not discover canonicalized block
621
622 def test_CanonicalDomains_may_be_set_to_space_separated_list(self, socket):
623 # Test config has a bogus domain, followed by paramiko.org
624 socket.gethostbyname.side_effect = [socket.gaierror, True]
625 result = load_config("multi-canon-domains").lookup("www")
626 assert result["hostname"] == "www.paramiko.org"
627 assert result["user"] == "rando"
628 assert [x[0][0] for x in socket.gethostbyname.call_args_list] == [
629 "www.not-a-real-tld",
630 "www.paramiko.org",
631 ]
632
633 def test_canonicalization_applies_to_single_dot_by_default(self, socket):
634 result = load_config("deep-canon").lookup("sub.www")
635 assert result["hostname"] == "sub.www.paramiko.org"
636 assert result["user"] == "deep"
637
638 def test_canonicalization_not_applied_to_two_dots_by_default(self, socket):
639 result = load_config("deep-canon").lookup("subber.sub.www")
640 assert result["hostname"] == "subber.sub.www"
641 assert "user" not in result
642
643 def test_hostname_depth_controllable_with_max_dots_directive(self, socket):
644 # This config sets MaxDots of 2, so now canonicalization occurs
645 result = load_config("deep-canon-maxdots").lookup("subber.sub.www")
646 assert result["hostname"] == "subber.sub.www.paramiko.org"
647 assert result["user"] == "deeper"
648
649 def test_max_dots_may_be_zero(self, socket):
650 result = load_config("zero-maxdots").lookup("sub.www")
651 assert result["hostname"] == "sub.www"
652 assert "user" not in result
653
654 def test_fallback_yes_does_not_canonicalize_or_error(self, socket):
655 socket.gethostbyname.side_effect = socket.gaierror
656 result = load_config("fallback-yes").lookup("www")
657 assert result["hostname"] == "www"
658 assert "user" not in result
659
660 def test_fallback_no_causes_errors_for_unresolvable_names(self, socket):
661 socket.gethostbyname.side_effect = socket.gaierror
662 with raises(CouldNotCanonicalize) as info:
663 load_config("fallback-no").lookup("doesnotexist")
664 assert str(info.value) == "doesnotexist"
665
666 def test_identityfile_continues_being_appended_to(self, socket):
667 result = load_config("canon").lookup("www")
668 assert result["identityfile"] == ["base.key", "canonicalized.key"]
669
670
671 @mark.skip
672 class TestCanonicalizationOfCNAMEs:
673 def test_permitted_cnames_may_be_one_to_one_mapping(self):
674 # CanonicalizePermittedCNAMEs *.foo.com:*.bar.com
675 pass
676
677 def test_permitted_cnames_may_be_one_to_many_mapping(self):
678 # CanonicalizePermittedCNAMEs *.foo.com:*.bar.com,*.biz.com
679 pass
680
681 def test_permitted_cnames_may_be_many_to_one_mapping(self):
682 # CanonicalizePermittedCNAMEs *.foo.com,*.bar.com:*.biz.com
683 pass
684
685 def test_permitted_cnames_may_be_many_to_many_mapping(self):
686 # CanonicalizePermittedCNAMEs *.foo.com,*.bar.com:*.biz.com,*.baz.com
687 pass
688
689 def test_permitted_cnames_may_be_multiple_mappings(self):
690 # CanonicalizePermittedCNAMEs *.foo.com,*.bar.com *.biz.com:*.baz.com
691 pass
692
693 def test_permitted_cnames_may_be_multiple_complex_mappings(self):
694 # Same as prev but with multiple patterns on both ends in both args
695 pass
696
697
698 class TestMatchAll:
699 def test_always_matches(self):
700 result = load_config("match-all").lookup("general")
701 assert result["user"] == "awesome"
702
703 def test_may_not_mix_with_non_canonical_keywords(self):
704 for config in ("match-all-and-more", "match-all-and-more-before"):
705 with raises(ConfigParseError):
706 load_config(config).lookup("whatever")
707
708 def test_may_come_after_canonical(self, socket):
709 result = load_config("match-all-after-canonical").lookup("www")
710 assert result["user"] == "awesome"
711
712 def test_may_not_come_before_canonical(self, socket):
713 with raises(ConfigParseError):
714 load_config("match-all-before-canonical")
715
716 def test_after_canonical_not_loaded_when_non_canonicalized(self, socket):
717 result = load_config("match-canonical-no").lookup("a-host")
718 assert "user" not in result
719
720
721 def _expect(success_on):
722 """
723 Returns a side_effect-friendly Invoke success result for given command(s).
724
725 Ensures that any other commands fail; this is useful for testing 'Match
726 exec' because it means all other such clauses under test act like no-ops.
727
728 :param success_on:
729 Single string or list of strings, noting commands that should appear to
730 succeed.
731 """
732 if isinstance(success_on, str):
733 success_on = [success_on]
734
735 def inner(command, *args, **kwargs):
736 # Sanity checking - we always expect that invoke.run is called with
737 # these.
738 assert kwargs.get("hide", None) == "stdout"
739 assert kwargs.get("warn", None) is True
740 # Fake exit
741 exit = 0 if command in success_on else 1
742 return Result(exited=exit)
743
744 return inner
745
746
747 @mark.skipif(Result is None, reason="requires invoke package")
748 class TestMatchExec:
749 @patch("paramiko.config.invoke", new=None)
750 @patch("paramiko.config.invoke_import_error", new=ImportError("meh"))
751 def test_raises_invoke_ImportErrors_at_runtime(self):
752 # Not an ideal test, but I don't know of a non-bad way to fake out
753 # module-time ImportErrors. So we mock the symptoms. Meh!
754 with raises(ImportError) as info:
755 load_config("match-exec").lookup("oh-noes")
756 assert str(info.value) == "meh"
757
758 @patch("paramiko.config.invoke.run")
759 @mark.parametrize(
760 "cmd,user",
761 [
762 ("unquoted", "rando"),
763 ("quoted", "benjamin"),
764 ("quoted spaced", "neil"),
765 ],
766 )
767 def test_accepts_single_possibly_quoted_argument(self, run, cmd, user):
768 run.side_effect = _expect(cmd)
769 result = load_config("match-exec").lookup("whatever")
770 assert result["user"] == user
771
772 @patch("paramiko.config.invoke.run")
773 def test_does_not_match_nonzero_exit_codes(self, run):
774 # Nothing will succeed -> no User ever gets loaded
775 run.return_value = Result(exited=1)
776 result = load_config("match-exec").lookup("whatever")
777 assert "user" not in result
778
779 @patch("paramiko.config.getpass")
780 @patch("paramiko.config.invoke.run")
781 def test_tokenizes_argument(self, run, getpass, socket):
782 getpass.getuser.return_value = "gandalf"
783 # Actual exec value is "%C %d %h %L %l %n %p %r %u"
784 parts = (
785 "bf5ba06778434a9384ee4217e462f64888bd0cd2",
786 expanduser("~"),
787 "configured",
788 "local",
789 "some.fake.fqdn",
790 "target",
791 "22",
792 "intermediate",
793 "gandalf",
794 )
795 run.side_effect = _expect(" ".join(parts))
796 result = load_config("match-exec").lookup("target")
797 assert result["port"] == "1337"
798
799 @patch("paramiko.config.invoke.run")
800 def test_works_with_canonical(self, run, socket):
801 # Ensure both stanzas' exec components appear to match
802 run.side_effect = _expect(["uncanonicalized", "canonicalized"])
803 result = load_config("match-exec-canonical").lookup("who-cares")
804 # Prove both config values got loaded up, across the two passes
805 assert result["user"] == "defenseless"
806 assert result["port"] == "8007"
807
808 @patch("paramiko.config.invoke.run")
809 def test_may_be_negated(self, run):
810 run.side_effect = _expect("this succeeds")
811 result = load_config("match-exec-negation").lookup("so-confusing")
812 # If negation did not work, the first of the two Match exec directives
813 # would have set User to 'nope' (and/or the second would have NOT set
814 # User to 'yup')
815 assert result["user"] == "yup"
816
817 def test_requires_an_argument(self):
818 with raises(ConfigParseError):
819 load_config("match-exec-no-arg")
820
821 @patch("paramiko.config.invoke.run")
822 def test_works_with_tokenized_hostname(self, run):
823 run.side_effect = _expect("ping target")
824 result = load_config("hostname-exec-tokenized").lookup("target")
825 assert result["hostname"] == "pingable.target"
826
827
828 class TestMatchHost:
829 def test_matches_target_name_when_no_hostname(self):
830 result = load_config("match-host").lookup("target")
831 assert result["user"] == "rand"
832
833 def test_matches_hostname_from_global_setting(self):
834 # Also works for ones set in regular Host stanzas
835 result = load_config("match-host-name").lookup("anything")
836 assert result["user"] == "silly"
837
838 def test_matches_hostname_from_earlier_match(self):
839 # Corner case: one Match matches original host, sets HostName,
840 # subsequent Match matches the latter.
841 result = load_config("match-host-from-match").lookup("original-host")
842 assert result["user"] == "inner"
843
844 def test_may_be_globbed(self):
845 result = load_config("match-host-glob-list").lookup("whatever")
846 assert result["user"] == "matrim"
847
848 def test_may_be_comma_separated_list(self):
849 for target in ("somehost", "someotherhost"):
850 result = load_config("match-host-glob-list").lookup(target)
851 assert result["user"] == "thom"
852
853 def test_comma_separated_list_may_have_internal_negation(self):
854 conf = load_config("match-host-glob-list")
855 assert conf.lookup("good")["user"] == "perrin"
856 assert "user" not in conf.lookup("goof")
857
858 def test_matches_canonicalized_name(self, socket):
859 # Without 'canonical' explicitly declared, mind.
860 result = load_config("match-host-canonicalized").lookup("www")
861 assert result["user"] == "rand"
862
863 def test_works_with_canonical_keyword(self, socket):
864 # NOTE: distinct from 'happens to be canonicalized' above
865 result = load_config("match-host-canonicalized").lookup("docs")
866 assert result["user"] == "eric"
867
868 def test_may_be_negated(self):
869 conf = load_config("match-host-negated")
870 assert conf.lookup("docs")["user"] == "jeff"
871 assert "user" not in conf.lookup("www")
872
873 def test_requires_an_argument(self):
874 with raises(ConfigParseError):
875 load_config("match-host-no-arg")
876
877
878 class TestMatchOriginalHost:
879 def test_matches_target_host_not_hostname(self):
880 result = load_config("match-orighost").lookup("target")
881 assert result["hostname"] == "bogus"
882 assert result["user"] == "tuon"
883
884 def test_matches_target_host_not_canonicalized_name(self, socket):
885 result = load_config("match-orighost-canonical").lookup("www")
886 assert result["hostname"] == "www.paramiko.org"
887 assert result["user"] == "tuon"
888
889 def test_may_be_globbed(self):
890 result = load_config("match-orighost").lookup("whatever")
891 assert result["user"] == "matrim"
892
893 def test_may_be_comma_separated_list(self):
894 for target in ("comma", "separated"):
895 result = load_config("match-orighost").lookup(target)
896 assert result["user"] == "chameleon"
897
898 def test_comma_separated_list_may_have_internal_negation(self):
899 result = load_config("match-orighost").lookup("nope")
900 assert "user" not in result
901
902 def test_may_be_negated(self):
903 result = load_config("match-orighost").lookup("docs")
904 assert result["user"] == "thom"
905
906 def test_requires_an_argument(self):
907 with raises(ConfigParseError):
908 load_config("match-orighost-no-arg")
909
910
911 class TestMatchUser:
912 def test_matches_configured_username(self):
913 result = load_config("match-user-explicit").lookup("anything")
914 assert result["hostname"] == "dumb"
915
916 @patch("paramiko.config.getpass.getuser")
917 def test_matches_local_username_by_default(self, getuser):
918 getuser.return_value = "gandalf"
919 result = load_config("match-user").lookup("anything")
920 assert result["hostname"] == "gondor"
921
922 @patch("paramiko.config.getpass.getuser")
923 def test_may_be_globbed(self, getuser):
924 for user in ("bilbo", "bombadil"):
925 getuser.return_value = user
926 result = load_config("match-user").lookup("anything")
927 assert result["hostname"] == "shire"
928
929 @patch("paramiko.config.getpass.getuser")
930 def test_may_be_comma_separated_list(self, getuser):
931 for user in ("aragorn", "frodo"):
932 getuser.return_value = user
933 result = load_config("match-user").lookup("anything")
934 assert result["hostname"] == "moria"
935
936 @patch("paramiko.config.getpass.getuser")
937 def test_comma_separated_list_may_have_internal_negation(self, getuser):
938 getuser.return_value = "legolas"
939 result = load_config("match-user").lookup("anything")
940 assert "port" not in result
941 getuser.return_value = "gimli"
942 result = load_config("match-user").lookup("anything")
943 assert result["port"] == "7373"
944
945 @patch("paramiko.config.getpass.getuser")
946 def test_may_be_negated(self, getuser):
947 getuser.return_value = "saruman"
948 result = load_config("match-user").lookup("anything")
949 assert result["hostname"] == "mordor"
950
951 def test_requires_an_argument(self):
952 with raises(ConfigParseError):
953 load_config("match-user-no-arg")
954
955
956 # NOTE: highly derivative of previous suite due to the former's use of
957 # localuser fallback. Doesn't seem worth conflating/refactoring right now.
958 class TestMatchLocalUser:
959 @patch("paramiko.config.getpass.getuser")
960 def test_matches_local_username(self, getuser):
961 getuser.return_value = "gandalf"
962 result = load_config("match-localuser").lookup("anything")
963 assert result["hostname"] == "gondor"
964
965 @patch("paramiko.config.getpass.getuser")
966 def test_may_be_globbed(self, getuser):
967 for user in ("bilbo", "bombadil"):
968 getuser.return_value = user
969 result = load_config("match-localuser").lookup("anything")
970 assert result["hostname"] == "shire"
971
972 @patch("paramiko.config.getpass.getuser")
973 def test_may_be_comma_separated_list(self, getuser):
974 for user in ("aragorn", "frodo"):
975 getuser.return_value = user
976 result = load_config("match-localuser").lookup("anything")
977 assert result["hostname"] == "moria"
978
979 @patch("paramiko.config.getpass.getuser")
980 def test_comma_separated_list_may_have_internal_negation(self, getuser):
981 getuser.return_value = "legolas"
982 result = load_config("match-localuser").lookup("anything")
983 assert "port" not in result
984 getuser.return_value = "gimli"
985 result = load_config("match-localuser").lookup("anything")
986 assert result["port"] == "7373"
987
988 @patch("paramiko.config.getpass.getuser")
989 def test_may_be_negated(self, getuser):
990 getuser.return_value = "saruman"
991 result = load_config("match-localuser").lookup("anything")
992 assert result["hostname"] == "mordor"
993
994 def test_requires_an_argument(self):
995 with raises(ConfigParseError):
996 load_config("match-localuser-no-arg")
997
998
999 class TestComplexMatching:
1000 # NOTE: this is still a cherry-pick of a few levels of complexity, there's
1001 # no point testing literally all possible combinations.
1002
1003 def test_originalhost_host(self):
1004 result = load_config("match-complex").lookup("target")
1005 assert result["hostname"] == "bogus"
1006 assert result["user"] == "rand"
1007
1008 @patch("paramiko.config.getpass.getuser")
1009 def test_originalhost_localuser(self, getuser):
1010 getuser.return_value = "rando"
1011 result = load_config("match-complex").lookup("remote")
1012 assert result["user"] == "calrissian"
1013
1014 @patch("paramiko.config.getpass.getuser")
1015 def test_everything_but_all(self, getuser):
1016 getuser.return_value = "rando"
1017 result = load_config("match-complex").lookup("www")
1018 assert result["port"] == "7777"
1019
1020 @patch("paramiko.config.getpass.getuser")
1021 def test_everything_but_all_with_some_negated(self, getuser):
1022 getuser.return_value = "rando"
1023 result = load_config("match-complex").lookup("docs")
1024 assert result["port"] == "1234"
1025
1026 def test_negated_canonical(self, socket):
1027 # !canonical in a config that is not canonicalized - does match
1028 result = load_config("match-canonical-no").lookup("specific")
1029 assert result["user"] == "overload"
1030 # !canonical in a config that is canonicalized - does NOT match
1031 result = load_config("match-canonical-yes").lookup("www")
1032 assert result["user"] == "hidden"
1033
1034
1035 class TestFinalMatching(object):
1036 def test_finally(self):
1037 result = load_config("match-final").lookup("finally")
1038 assert result["proxyjump"] == "jump"
1039 assert result["port"] == "1001"
1040
1041 def test_default_port(self):
1042 result = load_config("match-final").lookup("default-port")
1043 assert result["proxyjump"] == "jump"
1044 assert result["port"] == "1002"
1045
1046 def test_negated(self):
1047 result = load_config("match-final").lookup("jump")
1048 assert result["port"] == "1003"